LLVM 23.0.0git
OMPIRBuilder.h
Go to the documentation of this file.
1//===- IR/OpenMPIRBuilder.h - OpenMP encoding builder for LLVM IR - C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the OpenMPIRBuilder class and helpers used as a convenient
10// way to create LLVM instructions for OpenMP directives.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_FRONTEND_OPENMP_OMPIRBUILDER_H
15#define LLVM_FRONTEND_OPENMP_OMPIRBUILDER_H
16
17#include "llvm/ADT/APSInt.h"
18#include "llvm/ADT/SetVector.h"
22#include "llvm/IR/CallingConv.h"
23#include "llvm/IR/DebugLoc.h"
24#include "llvm/IR/IRBuilder.h"
25#include "llvm/IR/Module.h"
26#include "llvm/IR/ValueMap.h"
29#include "llvm/Support/Error.h"
31#include <forward_list>
32#include <map>
33#include <optional>
34
35namespace llvm {
37class ScanInfo;
40class OpenMPIRBuilder;
41class Loop;
42class LoopAnalysis;
43class LoopInfo;
44
45namespace vfs {
46class FileSystem;
47} // namespace vfs
48
49/// Move the instruction after an InsertPoint to the beginning of another
50/// BasicBlock.
51///
52/// The instructions after \p IP are moved to the beginning of \p New which must
53/// not have any PHINodes. If \p CreateBranch is true, a branch instruction to
54/// \p New will be added such that there is no semantic change. Otherwise, the
55/// \p IP insert block remains degenerate and it is up to the caller to insert a
56/// terminator. \p DL is used as the debug location for the branch instruction
57/// if one is created.
59 bool CreateBranch, DebugLoc DL);
60
61/// Splice a BasicBlock at an IRBuilder's current insertion point. Its new
62/// insert location will stick to after the instruction before the insertion
63/// point (instead of moving with the instruction the InsertPoint stores
64/// internally).
65LLVM_ABI void spliceBB(IRBuilder<> &Builder, BasicBlock *New,
66 bool CreateBranch);
67
68/// Split a BasicBlock at an InsertPoint, even if the block is degenerate
69/// (missing the terminator).
70///
71/// llvm::SplitBasicBlock and BasicBlock::splitBasicBlock require a well-formed
72/// BasicBlock. \p Name is used for the new successor block. If \p CreateBranch
73/// is true, a branch to the new successor will new created such that
74/// semantically there is no change; otherwise the block of the insertion point
75/// remains degenerate and it is the caller's responsibility to insert a
76/// terminator. \p DL is used as the debug location for the branch instruction
77/// if one is created. Returns the new successor block.
79 DebugLoc DL, llvm::Twine Name = {});
80
81/// Split a BasicBlock at \p Builder's insertion point, even if the block is
82/// degenerate (missing the terminator). Its new insert location will stick to
83/// after the instruction before the insertion point (instead of moving with the
84/// instruction the InsertPoint stores internally).
85LLVM_ABI BasicBlock *splitBB(IRBuilderBase &Builder, bool CreateBranch,
86 llvm::Twine Name = {});
87
88/// Split a BasicBlock at \p Builder's insertion point, even if the block is
89/// degenerate (missing the terminator). Its new insert location will stick to
90/// after the instruction before the insertion point (instead of moving with the
91/// instruction the InsertPoint stores internally).
92LLVM_ABI BasicBlock *splitBB(IRBuilder<> &Builder, bool CreateBranch,
93 llvm::Twine Name);
94
95/// Like splitBB, but reuses the current block's name for the new name.
97 bool CreateBranch,
98 llvm::Twine Suffix = ".split");
99
100/// Captures attributes that affect generating LLVM-IR using the
101/// OpenMPIRBuilder and related classes. Note that not all attributes are
102/// required for all classes or functions. In some use cases the configuration
103/// is not necessary at all, because because the only functions that are called
104/// are ones that are not dependent on the configuration.
106public:
107 /// Flag to define whether to generate code for the role of the OpenMP host
108 /// (if set to false) or device (if set to true) in an offloading context. It
109 /// is set when the -fopenmp-is-target-device compiler frontend option is
110 /// specified.
111 std::optional<bool> IsTargetDevice;
112
113 /// Flag for specifying if the compilation is done for an accelerator. It is
114 /// set according to the architecture of the target triple and currently only
115 /// true when targeting AMDGPU or NVPTX. Today, these targets can only perform
116 /// the role of an OpenMP target device, so `IsTargetDevice` must also be true
117 /// if `IsGPU` is true. This restriction might be lifted if an accelerator-
118 /// like target with the ability to work as the OpenMP host is added, or if
119 /// the capabilities of the currently supported GPU architectures are
120 /// expanded.
121 std::optional<bool> IsGPU;
122
123 /// Flag for specifying if LLVMUsed information should be emitted.
124 std::optional<bool> EmitLLVMUsedMetaInfo;
125
126 /// Flag for specifying if offloading is mandatory.
127 std::optional<bool> OpenMPOffloadMandatory;
128
129 /// First separator used between the initial two parts of a name.
130 std::optional<StringRef> FirstSeparator;
131 /// Separator used between all of the rest consecutive parts of s name.
132 std::optional<StringRef> Separator;
133
134 // Grid Value for the GPU target.
135 std::optional<omp::GV> GridValue;
136
137 /// When compilation is being done for the OpenMP host (i.e. `IsTargetDevice =
138 /// false`), this contains the list of offloading triples associated, if any.
140
141 // Default address space for the target.
142 unsigned DefaultTargetAS = 0;
143
145
149 bool HasRequiresReverseOffload,
150 bool HasRequiresUnifiedAddress,
151 bool HasRequiresUnifiedSharedMemory,
152 bool HasRequiresDynamicAllocators);
153
154 // Getters functions that assert if the required values are not present.
155 bool isTargetDevice() const {
156 assert(IsTargetDevice.has_value() && "IsTargetDevice is not set");
157 return *IsTargetDevice;
158 }
159
160 bool isGPU() const {
161 assert(IsGPU.has_value() && "IsGPU is not set");
162 return *IsGPU;
163 }
164
166 assert(OpenMPOffloadMandatory.has_value() &&
167 "OpenMPOffloadMandatory is not set");
169 }
170
172 assert(GridValue.has_value() && "GridValue is not set");
173 return *GridValue;
174 }
175
176 unsigned getDefaultTargetAS() const { return DefaultTargetAS; }
177
179
180 bool hasRequiresFlags() const { return RequiresFlags; }
185
186 /// Returns requires directive clauses as flags compatible with those expected
187 /// by libomptarget.
188 LLVM_ABI int64_t getRequiresFlags() const;
189
190 // Returns the FirstSeparator if set, otherwise use the default separator
191 // depending on isGPU
193 if (FirstSeparator.has_value())
194 return *FirstSeparator;
195 if (isGPU())
196 return "_";
197 return ".";
198 }
199
200 // Returns the Separator if set, otherwise use the default separator depending
201 // on isGPU
203 if (Separator.has_value())
204 return *Separator;
205 if (isGPU())
206 return "$";
207 return ".";
208 }
209
211 void setIsGPU(bool Value) { IsGPU = Value; }
217 void setDefaultTargetAS(unsigned AS) { DefaultTargetAS = AS; }
219
224
225private:
226 /// Flags for specifying which requires directive clauses are present.
227 int64_t RequiresFlags;
228};
229
230/// Data structure to contain the information needed to uniquely identify
231/// a target entry.
233 /// The prefix used for kernel names.
234 static constexpr const char *KernelNamePrefix = "__omp_offloading_";
235
236 std::string ParentName;
237 unsigned DeviceID;
238 unsigned FileID;
239 unsigned Line;
240 unsigned Count;
241
244 unsigned FileID, unsigned Line, unsigned Count = 0)
246 Count(Count) {}
247
248 LLVM_ABI static void
250 unsigned DeviceID, unsigned FileID, unsigned Line,
251 unsigned Count);
252
254 return std::make_tuple(ParentName, DeviceID, FileID, Line, Count) <
255 std::make_tuple(RHS.ParentName, RHS.DeviceID, RHS.FileID, RHS.Line,
256 RHS.Count);
257 }
258};
259
260/// Class that manages information about offload code regions and data
262 /// Number of entries registered so far.
263 OpenMPIRBuilder *OMPBuilder;
264 unsigned OffloadingEntriesNum = 0;
265
266public:
267 /// Base class of the entries info.
269 public:
270 /// Kind of a given entry.
271 enum OffloadingEntryInfoKinds : unsigned {
272 /// Entry is a target region.
274 /// Entry is a declare target variable.
276 /// Invalid entry info.
278 };
279
280 protected:
282 explicit OffloadEntryInfo(OffloadingEntryInfoKinds Kind) : Kind(Kind) {}
283 explicit OffloadEntryInfo(OffloadingEntryInfoKinds Kind, unsigned Order,
284 uint32_t Flags)
285 : Flags(Flags), Order(Order), Kind(Kind) {}
286 ~OffloadEntryInfo() = default;
287
288 public:
289 bool isValid() const { return Order != ~0u; }
290 unsigned getOrder() const { return Order; }
291 OffloadingEntryInfoKinds getKind() const { return Kind; }
292 uint32_t getFlags() const { return Flags; }
293 void setFlags(uint32_t NewFlags) { Flags = NewFlags; }
294 Constant *getAddress() const { return cast_or_null<Constant>(Addr); }
296 assert(!Addr.pointsToAliveValue() && "Address has been set before!");
297 Addr = V;
298 }
299 static bool classof(const OffloadEntryInfo *Info) { return true; }
300
301 private:
302 /// Address of the entity that has to be mapped for offloading.
303 WeakTrackingVH Addr;
304
305 /// Flags associated with the device global.
306 uint32_t Flags = 0u;
307
308 /// Order this entry was emitted.
309 unsigned Order = ~0u;
310
311 OffloadingEntryInfoKinds Kind = OffloadingEntryInfoInvalid;
312 };
313
314 /// Return true if a there are no entries defined.
315 LLVM_ABI bool empty() const;
316 /// Return number of entries defined so far.
317 unsigned size() const { return OffloadingEntriesNum; }
318
319 OffloadEntriesInfoManager(OpenMPIRBuilder *builder) : OMPBuilder(builder) {}
320
321 //
322 // Target region entries related.
323 //
324
325 /// Kind of the target registry entry.
327 /// Mark the entry as target region.
329 };
330
331 /// Target region entries info.
333 /// Address that can be used as the ID of the entry.
334 Constant *ID = nullptr;
335
336 public:
339 explicit OffloadEntryInfoTargetRegion(unsigned Order, Constant *Addr,
340 Constant *ID,
343 ID(ID) {
344 setAddress(Addr);
345 }
346
347 Constant *getID() const { return ID; }
348 void setID(Constant *V) {
349 assert(!ID && "ID has been set before!");
350 ID = V;
351 }
352 static bool classof(const OffloadEntryInfo *Info) {
353 return Info->getKind() == OffloadingEntryInfoTargetRegion;
354 }
355 };
356
357 /// Initialize target region entry.
358 /// This is ONLY needed for DEVICE compilation.
359 LLVM_ABI void
361 unsigned Order);
362 /// Register target region entry.
364 Constant *Addr, Constant *ID,
366 /// Return true if a target region entry with the provided information
367 /// exists.
369 bool IgnoreAddressId = false) const;
370
371 // Return the Name based on \a EntryInfo using the next available Count.
372 LLVM_ABI void
374 const TargetRegionEntryInfo &EntryInfo);
375
376 /// brief Applies action \a Action on all registered entries.
377 typedef function_ref<void(const TargetRegionEntryInfo &EntryInfo,
378 const OffloadEntryInfoTargetRegion &)>
380 LLVM_ABI void
382
383 //
384 // Device global variable entries related.
385 //
386
387 /// Kind of the global variable entry..
389 /// Mark the entry as a to declare target.
391 /// Mark the entry as a to declare target link.
393 /// Mark the entry as a declare target enter.
395 /// Mark the entry as having no declare target entry kind.
397 /// Mark the entry as a declare target indirect global.
399 /// Mark the entry as a register requires global.
401 /// Mark the entry as a declare target indirect vtable.
403 };
404
405 /// Kind of device clause for declare target variables
406 /// and functions
407 /// NOTE: Currently not used as a part of a variable entry
408 /// used for Flang and Clang to interface with the variable
409 /// related registration functions
411 /// The target is marked for all devices
413 /// The target is marked for non-host devices
415 /// The target is marked for host devices
417 /// The target is marked as having no clause
419 };
420
421 /// Device global variable entries info.
423 /// Type of the global variable.
424 int64_t VarSize;
426 const std::string VarName;
427
428 public:
434 explicit OffloadEntryInfoDeviceGlobalVar(unsigned Order, Constant *Addr,
435 int64_t VarSize,
438 const std::string &VarName)
440 VarSize(VarSize), Linkage(Linkage), VarName(VarName) {
441 setAddress(Addr);
442 }
443
444 int64_t getVarSize() const { return VarSize; }
445 StringRef getVarName() const { return VarName; }
446 void setVarSize(int64_t Size) { VarSize = Size; }
447 GlobalValue::LinkageTypes getLinkage() const { return Linkage; }
448 void setLinkage(GlobalValue::LinkageTypes LT) { Linkage = LT; }
449 static bool classof(const OffloadEntryInfo *Info) {
450 return Info->getKind() == OffloadingEntryInfoDeviceGlobalVar;
451 }
452 };
453
454 /// Initialize device global variable entry.
455 /// This is ONLY used for DEVICE compilation.
457 StringRef Name, OMPTargetGlobalVarEntryKind Flags, unsigned Order);
458
459 /// Register device global variable entry.
461 StringRef VarName, Constant *Addr, int64_t VarSize,
463 /// Checks if the variable with the given name has been registered already.
465 return OffloadEntriesDeviceGlobalVar.count(VarName) > 0;
466 }
467 /// Applies action \a Action on all registered entries.
468 typedef function_ref<void(StringRef, const OffloadEntryInfoDeviceGlobalVar &)>
472
473private:
474 /// Return the count of entries at a particular source location.
475 unsigned
476 getTargetRegionEntryInfoCount(const TargetRegionEntryInfo &EntryInfo) const;
477
478 /// Update the count of entries at a particular source location.
479 void
480 incrementTargetRegionEntryInfoCount(const TargetRegionEntryInfo &EntryInfo);
481
483 getTargetRegionEntryCountKey(const TargetRegionEntryInfo &EntryInfo) {
484 return TargetRegionEntryInfo(EntryInfo.ParentName, EntryInfo.DeviceID,
485 EntryInfo.FileID, EntryInfo.Line, 0);
486 }
487
488 // Count of entries at a location.
489 std::map<TargetRegionEntryInfo, unsigned> OffloadEntriesTargetRegionCount;
490
491 // Storage for target region entries kind.
492 typedef std::map<TargetRegionEntryInfo, OffloadEntryInfoTargetRegion>
493 OffloadEntriesTargetRegionTy;
494 OffloadEntriesTargetRegionTy OffloadEntriesTargetRegion;
495 /// Storage for device global variable entries kind. The storage is to be
496 /// indexed by mangled name.
498 OffloadEntriesDeviceGlobalVarTy;
499 OffloadEntriesDeviceGlobalVarTy OffloadEntriesDeviceGlobalVar;
500};
501
502/// An interface to create LLVM-IR for OpenMP directives.
503///
504/// Each OpenMP directive has a corresponding public generator method.
506public:
507 /// Create a new OpenMPIRBuilder operating on the given module \p M. This will
508 /// not have an effect on \p M (see initialize)
510 : M(M), Builder(M.getContext()), OffloadInfoManager(this),
511 T(M.getTargetTriple()), IsFinalized(false) {}
513
515 llvm::Value *AtomicVar;
516
517 public:
525
526 llvm::Value *getAtomicPointer() const override { return AtomicVar; }
529 const llvm::Twine &Name) const override {
530 llvm::AllocaInst *allocaInst = Builder->CreateAlloca(Ty);
531 allocaInst->setName(Name);
532 return allocaInst;
533 }
534 };
535 /// Initialize the internal state, this will put structures types and
536 /// potentially other helpers into the underlying module. Must be called
537 /// before any other method and only once! This internal state includes types
538 /// used in the OpenMPIRBuilder generated from OMPKinds.def.
539 LLVM_ABI void initialize();
540
542
543 /// Finalize the underlying module, e.g., by outlining regions.
544 /// \param Fn The function to be finalized. If not used,
545 /// all functions are finalized.
546 LLVM_ABI void finalize(Function *Fn = nullptr);
547
548 /// Check whether the finalize function has already run
549 /// \return true if the finalize function has already run
550 LLVM_ABI bool isFinalized();
551
552 /// Add attributes known for \p FnID to \p Fn.
554
555 /// Type used throughout for insertion points.
557
558 /// Type used to represent an insertion point or an error value.
560
561 /// Get the create a name using the platform specific separators.
562 /// \param Parts parts of the final name that needs separation
563 /// The created name has a first separator between the first and second part
564 /// and a second separator between all other parts.
565 /// E.g. with FirstSeparator "$" and Separator "." and
566 /// parts: "p1", "p2", "p3", "p4"
567 /// The resulting name is "p1$p2.p3.p4"
568 /// The separators are retrieved from the OpenMPIRBuilderConfig.
569 LLVM_ABI std::string
571
572 /// Callback type for variable finalization (think destructors).
573 ///
574 /// \param CodeGenIP is the insertion point at which the finalization code
575 /// should be placed.
576 ///
577 /// A finalize callback knows about all objects that need finalization, e.g.
578 /// destruction, when the scope of the currently generated construct is left
579 /// at the time, and location, the callback is invoked.
580 using FinalizeCallbackTy = std::function<Error(InsertPointTy CodeGenIP)>;
581
583 FinalizationInfo(FinalizeCallbackTy FiniCB, omp::Directive DK,
584 bool IsCancellable)
585 : DK(DK), IsCancellable(IsCancellable), FiniCB(std::move(FiniCB)) {}
586 /// The directive kind of the innermost directive that has an associated
587 /// region which might require finalization when it is left.
588 const omp::Directive DK;
589
590 /// Flag to indicate if the directive is cancellable.
591 const bool IsCancellable;
592
593 /// The basic block to which control should be transferred to
594 /// implement the FiniCB. Memoized to avoid generating finalization
595 /// multiple times.
597
598 /// For cases where there is an unavoidable existing finalization block
599 /// (e.g. loop finialization after omp sections). The existing finalization
600 /// block must not contain any non-finalization code.
602
603 private:
604 /// Access via getFiniBB.
605 BasicBlock *FiniBB = nullptr;
606
607 /// The finalization callback provided by the last in-flight invocation of
608 /// createXXXX for the directive of kind DK.
609 FinalizeCallbackTy FiniCB;
610 };
611
612 /// Push a finalization callback on the finalization stack.
613 ///
614 /// NOTE: Temporary solution until Clang CG is gone.
616 FinalizationStack.push_back(FI);
617 }
618
619 /// Pop the last finalization callback from the finalization stack.
620 ///
621 /// NOTE: Temporary solution until Clang CG is gone.
623
624 /// Callback type for body (=inner region) code generation
625 ///
626 /// The callback takes code locations as arguments, each describing a
627 /// location where additional instructions can be inserted.
628 ///
629 /// The CodeGenIP may be in the middle of a basic block or point to the end of
630 /// it. The basic block may have a terminator or be degenerate. The callback
631 /// function may just insert instructions at that position, but also split the
632 /// block (without the Before argument of BasicBlock::splitBasicBlock such
633 /// that the identify of the split predecessor block is preserved) and insert
634 /// additional control flow, including branches that do not lead back to what
635 /// follows the CodeGenIP. Note that since the callback is allowed to split
636 /// the block, callers must assume that InsertPoints to positions in the
637 /// BasicBlock after CodeGenIP including CodeGenIP itself are invalidated. If
638 /// such InsertPoints need to be preserved, it can split the block itself
639 /// before calling the callback.
640 ///
641 /// AllocaIP and CodeGenIP must not point to the same position.
642 ///
643 /// \param AllocaIP is the insertion point at which new alloca instructions
644 /// should be placed. The BasicBlock it is pointing to must
645 /// not be split.
646 /// \param CodeGenIP is the insertion point at which the body code should be
647 /// placed.
648 ///
649 /// \return an error, if any were triggered during execution.
651 function_ref<Error(InsertPointTy AllocaIP, InsertPointTy CodeGenIP)>;
652
653 /// Callback type for task duplication function code generation. This is the
654 /// task duplication function passed to __kmpc_taskloop. It is expected that
655 /// this function will set up (first)private variables in the duplicated task
656 /// which have non-trivial (copy-)constructors. Insertion points are handled
657 /// the same way as for BodyGenCallbackTy.
658 ///
659 /// \ref createTaskloop lays out the task's auxiliary data structure as:
660 /// `{ lower bound, upper bound, step, data... }`. DestPtr and SrcPtr point
661 /// to this data.
662 ///
663 /// It is acceptable for the callback to be set to nullptr. In that case no
664 /// function will be generated and nullptr will be passed as the task
665 /// duplication function to __kmpc_taskloop.
666 ///
667 /// \param AllocaIP is the insertion point at which new alloca instructions
668 /// should be placed. The BasicBlock it is pointing to must
669 /// not be split.
670 /// \param CodeGenIP is the insertion point at which the body code should be
671 /// placed.
672 /// \param DestPtr This is a pointer to data inside the newly duplicated
673 /// task's auxiliary data structure (allocated after the task
674 /// descriptor.)
675 /// \param SrcPtr This is a pointer to data inside the original task's
676 /// auxiliary data structure (allocated after the task
677 /// descriptor.)
678 ///
679 /// \return The insertion point immediately after the generated code, or an
680 /// error if any occured.
682 InsertPointTy AllocaIP, InsertPointTy CodeGenIP, Value *DestPtr,
683 Value *SrcPtr)>;
684
685 // This is created primarily for sections construct as llvm::function_ref
686 // (BodyGenCallbackTy) is not storable (as described in the comments of
687 // function_ref class - function_ref contains non-ownable reference
688 // to the callable.
689 ///
690 /// \return an error, if any were triggered during execution.
692 std::function<Error(InsertPointTy AllocaIP, InsertPointTy CodeGenIP)>;
693
694 /// Callback type for loop body code generation.
695 ///
696 /// \param CodeGenIP is the insertion point where the loop's body code must be
697 /// placed. This will be a dedicated BasicBlock with a
698 /// conditional branch from the loop condition check and
699 /// terminated with an unconditional branch to the loop
700 /// latch.
701 /// \param IndVar is the induction variable usable at the insertion point.
702 ///
703 /// \return an error, if any were triggered during execution.
705 function_ref<Error(InsertPointTy CodeGenIP, Value *IndVar)>;
706
707 /// Callback type for variable privatization (think copy & default
708 /// constructor).
709 ///
710 /// \param AllocaIP is the insertion point at which new alloca instructions
711 /// should be placed.
712 /// \param CodeGenIP is the insertion point at which the privatization code
713 /// should be placed.
714 /// \param Original The value being copied/created, should not be used in the
715 /// generated IR.
716 /// \param Inner The equivalent of \p Original that should be used in the
717 /// generated IR; this is equal to \p Original if the value is
718 /// a pointer and can thus be passed directly, otherwise it is
719 /// an equivalent but different value.
720 /// \param ReplVal The replacement value, thus a copy or new created version
721 /// of \p Inner.
722 ///
723 /// \returns The new insertion point where code generation continues and
724 /// \p ReplVal the replacement value.
726 InsertPointTy AllocaIP, InsertPointTy CodeGenIP, Value &Original,
727 Value &Inner, Value *&ReplVal)>;
728
729 /// Description of a LLVM-IR insertion point (IP) and a debug/source location
730 /// (filename, line, column, ...).
733 : IP(IRB.saveIP()), DL(IRB.getCurrentDebugLocation()) {}
736 : IP(IP), DL(DL) {}
739 };
740
741 /// Emitter methods for OpenMP directives.
742 ///
743 ///{
744
745 /// Generator for '#omp barrier'
746 ///
747 /// \param Loc The location where the barrier directive was encountered.
748 /// \param Kind The kind of directive that caused the barrier.
749 /// \param ForceSimpleCall Flag to force a simple (=non-cancellation) barrier.
750 /// \param CheckCancelFlag Flag to indicate a cancel barrier return value
751 /// should be checked and acted upon.
752 /// \param ThreadID Optional parameter to pass in any existing ThreadID value.
753 ///
754 /// \returns The insertion point after the barrier.
756 omp::Directive Kind,
757 bool ForceSimpleCall = false,
758 bool CheckCancelFlag = true);
759
760 /// Generator for '#omp cancel'
761 ///
762 /// \param Loc The location where the directive was encountered.
763 /// \param IfCondition The evaluated 'if' clause expression, if any.
764 /// \param CanceledDirective The kind of directive that is cancled.
765 ///
766 /// \returns The insertion point after the barrier.
768 Value *IfCondition,
769 omp::Directive CanceledDirective);
770
771 /// Generator for '#omp cancellation point'
772 ///
773 /// \param Loc The location where the directive was encountered.
774 /// \param CanceledDirective The kind of directive that is cancled.
775 ///
776 /// \returns The insertion point after the barrier.
778 const LocationDescription &Loc, omp::Directive CanceledDirective);
779
780 /// Creates a ScanInfo object, allocates and returns the pointer.
782
783 /// Generator for '#omp parallel'
784 ///
785 /// \param Loc The insert and source location description.
786 /// \param AllocaIP The insertion points to be used for alloca instructions.
787 /// \param BodyGenCB Callback that will generate the region code.
788 /// \param PrivCB Callback to copy a given variable (think copy constructor).
789 /// \param FiniCB Callback to finalize variable copies.
790 /// \param IfCondition The evaluated 'if' clause expression, if any.
791 /// \param NumThreads The evaluated 'num_threads' clause expression, if any.
792 /// \param ProcBind The value of the 'proc_bind' clause (see ProcBindKind).
793 /// \param IsCancellable Flag to indicate a cancellable parallel region.
794 ///
795 /// \returns The insertion position *after* the parallel.
797 const LocationDescription &Loc, InsertPointTy AllocaIP,
798 BodyGenCallbackTy BodyGenCB, PrivatizeCallbackTy PrivCB,
799 FinalizeCallbackTy FiniCB, Value *IfCondition, Value *NumThreads,
800 omp::ProcBindKind ProcBind, bool IsCancellable);
801
802 /// Generator for the control flow structure of an OpenMP canonical loop.
803 ///
804 /// This generator operates on the logical iteration space of the loop, i.e.
805 /// the caller only has to provide a loop trip count of the loop as defined by
806 /// base language semantics. The trip count is interpreted as an unsigned
807 /// integer. The induction variable passed to \p BodyGenCB will be of the same
808 /// type and run from 0 to \p TripCount - 1. It is up to the callback to
809 /// convert the logical iteration variable to the loop counter variable in the
810 /// loop body.
811 ///
812 /// \param Loc The insert and source location description. The insert
813 /// location can be between two instructions or the end of a
814 /// degenerate block (e.g. a BB under construction).
815 /// \param BodyGenCB Callback that will generate the loop body code.
816 /// \param TripCount Number of iterations the loop body is executed.
817 /// \param Name Base name used to derive BB and instruction names.
818 ///
819 /// \returns An object representing the created control flow structure which
820 /// can be used for loop-associated directives.
823 LoopBodyGenCallbackTy BodyGenCB, Value *TripCount,
824 const Twine &Name = "loop");
825
826 /// Generator for the control flow structure of an OpenMP canonical loops if
827 /// the parent directive has an `inscan` modifier specified.
828 /// If the `inscan` modifier is specified, the region of the parent is
829 /// expected to have a `scan` directive. Based on the clauses in
830 /// scan directive, the body of the loop is split into two loops: Input loop
831 /// and Scan Loop. Input loop contains the code generated for input phase of
832 /// scan and Scan loop contains the code generated for scan phase of scan.
833 /// From the bodyGen callback of these loops, `createScan` would be called
834 /// when a scan directive is encountered from the loop body. `createScan`
835 /// based on whether 1. inclusive or exclusive scan is specified and, 2. input
836 /// loop or scan loop is generated, lowers the body of the for loop
837 /// accordingly.
838 ///
839 /// \param Loc The insert and source location description.
840 /// \param BodyGenCB Callback that will generate the loop body code.
841 /// \param Start Value of the loop counter for the first iterations.
842 /// \param Stop Loop counter values past this will stop the loop.
843 /// \param Step Loop counter increment after each iteration; negative
844 /// means counting down.
845 /// \param IsSigned Whether Start, Stop and Step are signed integers.
846 /// \param InclusiveStop Whether \p Stop itself is a valid value for the loop
847 /// counter.
848 /// \param ComputeIP Insertion point for instructions computing the trip
849 /// count. Can be used to ensure the trip count is available
850 /// at the outermost loop of a loop nest. If not set,
851 /// defaults to the preheader of the generated loop.
852 /// \param Name Base name used to derive BB and instruction names.
853 /// \param ScanRedInfo Pointer to the ScanInfo objected created using
854 /// `ScanInfoInitialize`.
855 ///
856 /// \returns A vector containing Loop Info of Input Loop and Scan Loop.
859 LoopBodyGenCallbackTy BodyGenCB, Value *Start,
860 Value *Stop, Value *Step, bool IsSigned,
861 bool InclusiveStop, InsertPointTy ComputeIP,
862 const Twine &Name, ScanInfo *ScanRedInfo);
863
864 /// Calculate the trip count of a canonical loop.
865 ///
866 /// This allows specifying user-defined loop counter values using increment,
867 /// upper- and lower bounds. To disambiguate the terminology when counting
868 /// downwards, instead of lower bounds we use \p Start for the loop counter
869 /// value in the first body iteration.
870 ///
871 /// Consider the following limitations:
872 ///
873 /// * A loop counter space over all integer values of its bit-width cannot be
874 /// represented. E.g using uint8_t, its loop trip count of 256 cannot be
875 /// stored into an 8 bit integer):
876 ///
877 /// DO I = 0, 255, 1
878 ///
879 /// * Unsigned wrapping is only supported when wrapping only "once"; E.g.
880 /// effectively counting downwards:
881 ///
882 /// for (uint8_t i = 100u; i > 0; i += 127u)
883 ///
884 ///
885 /// TODO: May need to add additional parameters to represent:
886 ///
887 /// * Allow representing downcounting with unsigned integers.
888 ///
889 /// * Sign of the step and the comparison operator might disagree:
890 ///
891 /// for (int i = 0; i < 42; i -= 1u)
892 ///
893 /// \param Loc The insert and source location description.
894 /// \param Start Value of the loop counter for the first iterations.
895 /// \param Stop Loop counter values past this will stop the loop.
896 /// \param Step Loop counter increment after each iteration; negative
897 /// means counting down.
898 /// \param IsSigned Whether Start, Stop and Step are signed integers.
899 /// \param InclusiveStop Whether \p Stop itself is a valid value for the loop
900 /// counter.
901 /// \param Name Base name used to derive instruction names.
902 ///
903 /// \returns The value holding the calculated trip count.
905 const LocationDescription &Loc, Value *Start, Value *Stop, Value *Step,
906 bool IsSigned, bool InclusiveStop, const Twine &Name = "loop");
907
908 /// Generator for the control flow structure of an OpenMP canonical loop.
909 ///
910 /// Instead of a logical iteration space, this allows specifying user-defined
911 /// loop counter values using increment, upper- and lower bounds. To
912 /// disambiguate the terminology when counting downwards, instead of lower
913 /// bounds we use \p Start for the loop counter value in the first body
914 ///
915 /// It calls \see calculateCanonicalLoopTripCount for trip count calculations,
916 /// so limitations of that method apply here as well.
917 ///
918 /// \param Loc The insert and source location description.
919 /// \param BodyGenCB Callback that will generate the loop body code.
920 /// \param Start Value of the loop counter for the first iterations.
921 /// \param Stop Loop counter values past this will stop the loop.
922 /// \param Step Loop counter increment after each iteration; negative
923 /// means counting down.
924 /// \param IsSigned Whether Start, Stop and Step are signed integers.
925 /// \param InclusiveStop Whether \p Stop itself is a valid value for the loop
926 /// counter.
927 /// \param ComputeIP Insertion point for instructions computing the trip
928 /// count. Can be used to ensure the trip count is available
929 /// at the outermost loop of a loop nest. If not set,
930 /// defaults to the preheader of the generated loop.
931 /// \param Name Base name used to derive BB and instruction names.
932 /// \param InScan Whether loop has a scan reduction specified.
933 /// \param ScanRedInfo Pointer to the ScanInfo objected created using
934 /// `ScanInfoInitialize`.
935 ///
936 /// \returns An object representing the created control flow structure which
937 /// can be used for loop-associated directives.
940 Value *Start, Value *Stop, Value *Step, bool IsSigned, bool InclusiveStop,
941 InsertPointTy ComputeIP = {}, const Twine &Name = "loop",
942 bool InScan = false, ScanInfo *ScanRedInfo = nullptr);
943
944 /// Collapse a loop nest into a single loop.
945 ///
946 /// Merges loops of a loop nest into a single CanonicalLoopNest representation
947 /// that has the same number of innermost loop iterations as the origin loop
948 /// nest. The induction variables of the input loops are derived from the
949 /// collapsed loop's induction variable. This is intended to be used to
950 /// implement OpenMP's collapse clause. Before applying a directive,
951 /// collapseLoops normalizes a loop nest to contain only a single loop and the
952 /// directive's implementation does not need to handle multiple loops itself.
953 /// This does not remove the need to handle all loop nest handling by
954 /// directives, such as the ordered(<n>) clause or the simd schedule-clause
955 /// modifier of the worksharing-loop directive.
956 ///
957 /// Example:
958 /// \code
959 /// for (int i = 0; i < 7; ++i) // Canonical loop "i"
960 /// for (int j = 0; j < 9; ++j) // Canonical loop "j"
961 /// body(i, j);
962 /// \endcode
963 ///
964 /// After collapsing with Loops={i,j}, the loop is changed to
965 /// \code
966 /// for (int ij = 0; ij < 63; ++ij) {
967 /// int i = ij / 9;
968 /// int j = ij % 9;
969 /// body(i, j);
970 /// }
971 /// \endcode
972 ///
973 /// In the current implementation, the following limitations apply:
974 ///
975 /// * All input loops have an induction variable of the same type.
976 ///
977 /// * The collapsed loop will have the same trip count integer type as the
978 /// input loops. Therefore it is possible that the collapsed loop cannot
979 /// represent all iterations of the input loops. For instance, assuming a
980 /// 32 bit integer type, and two input loops both iterating 2^16 times, the
981 /// theoretical trip count of the collapsed loop would be 2^32 iteration,
982 /// which cannot be represented in an 32-bit integer. Behavior is undefined
983 /// in this case.
984 ///
985 /// * The trip counts of every input loop must be available at \p ComputeIP.
986 /// Non-rectangular loops are not yet supported.
987 ///
988 /// * At each nest level, code between a surrounding loop and its nested loop
989 /// is hoisted into the loop body, and such code will be executed more
990 /// often than before collapsing (or not at all if any inner loop iteration
991 /// has a trip count of 0). This is permitted by the OpenMP specification.
992 ///
993 /// \param DL Debug location for instructions added for collapsing,
994 /// such as instructions to compute/derive the input loop's
995 /// induction variables.
996 /// \param Loops Loops in the loop nest to collapse. Loops are specified
997 /// from outermost-to-innermost and every control flow of a
998 /// loop's body must pass through its directly nested loop.
999 /// \param ComputeIP Where additional instruction that compute the collapsed
1000 /// trip count. If not set, defaults to before the generated
1001 /// loop.
1002 ///
1003 /// \returns The CanonicalLoopInfo object representing the collapsed loop.
1006 InsertPointTy ComputeIP);
1007
1008 /// Get the default alignment value for given target
1009 ///
1010 /// \param TargetTriple Target triple
1011 /// \param Features StringMap which describes extra CPU features
1012 LLVM_ABI static unsigned
1013 getOpenMPDefaultSimdAlign(const Triple &TargetTriple,
1014 const StringMap<bool> &Features);
1015
1016 /// Retrieve (or create if non-existent) the address of a declare
1017 /// target variable, used in conjunction with registerTargetGlobalVariable
1018 /// to create declare target global variables.
1019 ///
1020 /// \param CaptureClause - enumerator corresponding to the OpenMP capture
1021 /// clause used in conjunction with the variable being registered (link,
1022 /// to, enter).
1023 /// \param DeviceClause - enumerator corresponding to the OpenMP capture
1024 /// clause used in conjunction with the variable being registered (nohost,
1025 /// host, any)
1026 /// \param IsDeclaration - boolean stating if the variable being registered
1027 /// is a declaration-only and not a definition
1028 /// \param IsExternallyVisible - boolean stating if the variable is externally
1029 /// visible
1030 /// \param EntryInfo - Unique entry information for the value generated
1031 /// using getTargetEntryUniqueInfo, used to name generated pointer references
1032 /// to the declare target variable
1033 /// \param MangledName - the mangled name of the variable being registered
1034 /// \param GeneratedRefs - references generated by invocations of
1035 /// registerTargetGlobalVariable invoked from getAddrOfDeclareTargetVar,
1036 /// these are required by Clang for book keeping.
1037 /// \param OpenMPSIMD - if OpenMP SIMD mode is currently enabled
1038 /// \param TargetTriple - The OpenMP device target triple we are compiling
1039 /// for
1040 /// \param LlvmPtrTy - The type of the variable we are generating or
1041 /// retrieving an address for
1042 /// \param GlobalInitializer - a lambda function which creates a constant
1043 /// used for initializing a pointer reference to the variable in certain
1044 /// cases. If a nullptr is passed, it will default to utilising the original
1045 /// variable to initialize the pointer reference.
1046 /// \param VariableLinkage - a lambda function which returns the variables
1047 /// linkage type, if unspecified and a nullptr is given, it will instead
1048 /// utilise the linkage stored on the existing global variable in the
1049 /// LLVMModule.
1053 bool IsDeclaration, bool IsExternallyVisible,
1054 TargetRegionEntryInfo EntryInfo, StringRef MangledName,
1055 std::vector<GlobalVariable *> &GeneratedRefs, bool OpenMPSIMD,
1056 std::vector<Triple> TargetTriple, Type *LlvmPtrTy,
1057 std::function<Constant *()> GlobalInitializer,
1058 std::function<GlobalValue::LinkageTypes()> VariableLinkage);
1059
1060 /// Registers a target variable for device or host.
1061 ///
1062 /// \param CaptureClause - enumerator corresponding to the OpenMP capture
1063 /// clause used in conjunction with the variable being registered (link,
1064 /// to, enter).
1065 /// \param DeviceClause - enumerator corresponding to the OpenMP capture
1066 /// clause used in conjunction with the variable being registered (nohost,
1067 /// host, any)
1068 /// \param IsDeclaration - boolean stating if the variable being registered
1069 /// is a declaration-only and not a definition
1070 /// \param IsExternallyVisible - boolean stating if the variable is externally
1071 /// visible
1072 /// \param EntryInfo - Unique entry information for the value generated
1073 /// using getTargetEntryUniqueInfo, used to name generated pointer references
1074 /// to the declare target variable
1075 /// \param MangledName - the mangled name of the variable being registered
1076 /// \param GeneratedRefs - references generated by invocations of
1077 /// registerTargetGlobalVariable these are required by Clang for book
1078 /// keeping.
1079 /// \param OpenMPSIMD - if OpenMP SIMD mode is currently enabled
1080 /// \param TargetTriple - The OpenMP device target triple we are compiling
1081 /// for
1082 /// \param GlobalInitializer - a lambda function which creates a constant
1083 /// used for initializing a pointer reference to the variable in certain
1084 /// cases. If a nullptr is passed, it will default to utilising the original
1085 /// variable to initialize the pointer reference.
1086 /// \param VariableLinkage - a lambda function which returns the variables
1087 /// linkage type, if unspecified and a nullptr is given, it will instead
1088 /// utilise the linkage stored on the existing global variable in the
1089 /// LLVMModule.
1090 /// \param LlvmPtrTy - The type of the variable we are generating or
1091 /// retrieving an address for
1092 /// \param Addr - the original llvm value (addr) of the variable to be
1093 /// registered
1097 bool IsDeclaration, bool IsExternallyVisible,
1098 TargetRegionEntryInfo EntryInfo, StringRef MangledName,
1099 std::vector<GlobalVariable *> &GeneratedRefs, bool OpenMPSIMD,
1100 std::vector<Triple> TargetTriple,
1101 std::function<Constant *()> GlobalInitializer,
1102 std::function<GlobalValue::LinkageTypes()> VariableLinkage,
1103 Type *LlvmPtrTy, Constant *Addr);
1104
1105 /// Get the offset of the OMP_MAP_MEMBER_OF field.
1106 LLVM_ABI unsigned getFlagMemberOffset();
1107
1108 /// Get OMP_MAP_MEMBER_OF flag with extra bits reserved based on
1109 /// the position given.
1110 /// \param Position - A value indicating the position of the parent
1111 /// of the member in the kernel argument structure, often retrieved
1112 /// by the parents position in the combined information vectors used
1113 /// to generate the structure itself. Multiple children (member's of)
1114 /// with the same parent will use the same returned member flag.
1116
1117 /// Given an initial flag set, this function modifies it to contain
1118 /// the passed in MemberOfFlag generated from the getMemberOfFlag
1119 /// function. The results are dependent on the existing flag bits
1120 /// set in the original flag set.
1121 /// \param Flags - The original set of flags to be modified with the
1122 /// passed in MemberOfFlag.
1123 /// \param MemberOfFlag - A modified OMP_MAP_MEMBER_OF flag, adjusted
1124 /// slightly based on the getMemberOfFlag which adjusts the flag bits
1125 /// based on the members position in its parent.
1126 LLVM_ABI void
1128 omp::OpenMPOffloadMappingFlags MemberOfFlag);
1129
1130private:
1131 /// Modifies the canonical loop to be a statically-scheduled workshare loop
1132 /// which is executed on the device
1133 ///
1134 /// This takes a \p CLI representing a canonical loop, such as the one
1135 /// created by \see createCanonicalLoop and emits additional instructions to
1136 /// turn it into a workshare loop. In particular, it calls to an OpenMP
1137 /// runtime function in the preheader to call OpenMP device rtl function
1138 /// which handles worksharing of loop body interations.
1139 ///
1140 /// \param DL Debug location for instructions added for the
1141 /// workshare-loop construct itself.
1142 /// \param CLI A descriptor of the canonical loop to workshare.
1143 /// \param AllocaIP An insertion point for Alloca instructions usable in the
1144 /// preheader of the loop.
1145 /// \param LoopType Information about type of loop worksharing.
1146 /// It corresponds to type of loop workshare OpenMP pragma.
1147 /// \param NoLoop If true, no-loop code is generated.
1148 ///
1149 /// \returns Point where to insert code after the workshare construct.
1150 InsertPointTy applyWorkshareLoopTarget(DebugLoc DL, CanonicalLoopInfo *CLI,
1151 InsertPointTy AllocaIP,
1152 omp::WorksharingLoopType LoopType,
1153 bool NoLoop);
1154
1155 /// Modifies the canonical loop to be a statically-scheduled workshare loop.
1156 ///
1157 /// This takes a \p LoopInfo representing a canonical loop, such as the one
1158 /// created by \p createCanonicalLoop and emits additional instructions to
1159 /// turn it into a workshare loop. In particular, it calls to an OpenMP
1160 /// runtime function in the preheader to obtain the loop bounds to be used in
1161 /// the current thread, updates the relevant instructions in the canonical
1162 /// loop and calls to an OpenMP runtime finalization function after the loop.
1163 ///
1164 /// \param DL Debug location for instructions added for the
1165 /// workshare-loop construct itself.
1166 /// \param CLI A descriptor of the canonical loop to workshare.
1167 /// \param AllocaIP An insertion point for Alloca instructions usable in the
1168 /// preheader of the loop.
1169 /// \param NeedsBarrier Indicates whether a barrier must be inserted after
1170 /// the loop.
1171 /// \param LoopType Type of workshare loop.
1172 /// \param HasDistSchedule Defines if the clause being lowered is
1173 /// dist_schedule as this is handled slightly differently
1174 /// \param DistScheduleSchedType Defines the Schedule Type for the Distribute
1175 /// loop. Defaults to None if no Distribute loop is present.
1176 ///
1177 /// \returns Point where to insert code after the workshare construct.
1178 InsertPointOrErrorTy applyStaticWorkshareLoop(
1180 omp::WorksharingLoopType LoopType, bool NeedsBarrier,
1181 bool HasDistSchedule = false,
1182 omp::OMPScheduleType DistScheduleSchedType = omp::OMPScheduleType::None);
1183
1184 /// Modifies the canonical loop a statically-scheduled workshare loop with a
1185 /// user-specified chunk size.
1186 ///
1187 /// \param DL Debug location for instructions added for the
1188 /// workshare-loop construct itself.
1189 /// \param CLI A descriptor of the canonical loop to workshare.
1190 /// \param AllocaIP An insertion point for Alloca instructions usable in
1191 /// the preheader of the loop.
1192 /// \param NeedsBarrier Indicates whether a barrier must be inserted after the
1193 /// loop.
1194 /// \param ChunkSize The user-specified chunk size.
1195 /// \param SchedType Optional type of scheduling to be passed to the init
1196 /// function.
1197 /// \param DistScheduleChunkSize The size of dist_shcedule chunk considered
1198 /// as a unit when
1199 /// scheduling. If \p nullptr, defaults to 1.
1200 /// \param DistScheduleSchedType Defines the Schedule Type for the Distribute
1201 /// loop. Defaults to None if no Distribute loop is present.
1202 ///
1203 /// \returns Point where to insert code after the workshare construct.
1204 InsertPointOrErrorTy applyStaticChunkedWorkshareLoop(
1206 bool NeedsBarrier, Value *ChunkSize,
1207 omp::OMPScheduleType SchedType =
1209 Value *DistScheduleChunkSize = nullptr,
1210 omp::OMPScheduleType DistScheduleSchedType = omp::OMPScheduleType::None);
1211
1212 /// Modifies the canonical loop to be a dynamically-scheduled workshare loop.
1213 ///
1214 /// This takes a \p LoopInfo representing a canonical loop, such as the one
1215 /// created by \p createCanonicalLoop and emits additional instructions to
1216 /// turn it into a workshare loop. In particular, it calls to an OpenMP
1217 /// runtime function in the preheader to obtain, and then in each iteration
1218 /// to update the loop counter.
1219 ///
1220 /// \param DL Debug location for instructions added for the
1221 /// workshare-loop construct itself.
1222 /// \param CLI A descriptor of the canonical loop to workshare.
1223 /// \param AllocaIP An insertion point for Alloca instructions usable in the
1224 /// preheader of the loop.
1225 /// \param SchedType Type of scheduling to be passed to the init function.
1226 /// \param NeedsBarrier Indicates whether a barrier must be insterted after
1227 /// the loop.
1228 /// \param Chunk The size of loop chunk considered as a unit when
1229 /// scheduling. If \p nullptr, defaults to 1.
1230 ///
1231 /// \returns Point where to insert code after the workshare construct.
1232 InsertPointOrErrorTy applyDynamicWorkshareLoop(DebugLoc DL,
1233 CanonicalLoopInfo *CLI,
1234 InsertPointTy AllocaIP,
1235 omp::OMPScheduleType SchedType,
1236 bool NeedsBarrier,
1237 Value *Chunk = nullptr);
1238
1239 /// Create alternative version of the loop to support if clause
1240 ///
1241 /// OpenMP if clause can require to generate second loop. This loop
1242 /// will be executed when if clause condition is not met. createIfVersion
1243 /// adds branch instruction to the copied loop if \p ifCond is not met.
1244 ///
1245 /// \param Loop Original loop which should be versioned.
1246 /// \param IfCond Value which corresponds to if clause condition
1247 /// \param VMap Value to value map to define relation between
1248 /// original and copied loop values and loop blocks.
1249 /// \param NamePrefix Optional name prefix for if.then if.else blocks.
1250 void createIfVersion(CanonicalLoopInfo *Loop, Value *IfCond,
1252 LoopAnalysis &LIA, LoopInfo &LI, llvm::Loop *L,
1253 const Twine &NamePrefix = "");
1254
1255 /// Creates a task duplication function to be passed to kmpc_taskloop.
1256 ///
1257 /// The OpenMP runtime defines this function as taking the destination
1258 /// kmp_task_t, source kmp_task_t, and a lastprivate flag. This function is
1259 /// called on the source and destination tasks after the source task has been
1260 /// duplicated to create the destination task. At this point the destination
1261 /// task has been otherwise set up from the runtime's perspective, but this
1262 /// function is needed to fix up any data for the duplicated task e.g. private
1263 /// variables with non-trivial constructors.
1264 ///
1265 /// \param PrivatesTy The type of the privates structure for the task.
1266 /// \param PrivatesIndex The index inside the privates structure containing
1267 /// the data for the callback.
1268 /// \param DupCB The callback to generate the duplication code. See
1269 /// documentation for \ref TaskDupCallbackTy. This can be
1270 /// nullptr.
1271 Expected<Value *> createTaskDuplicationFunction(Type *PrivatesTy,
1272 int32_t PrivatesIndex,
1273 TaskDupCallbackTy DupCB);
1274
1275public:
1276 /// Modifies the canonical loop to be a workshare loop.
1277 ///
1278 /// This takes a \p LoopInfo representing a canonical loop, such as the one
1279 /// created by \p createCanonicalLoop and emits additional instructions to
1280 /// turn it into a workshare loop. In particular, it calls to an OpenMP
1281 /// runtime function in the preheader to obtain the loop bounds to be used in
1282 /// the current thread, updates the relevant instructions in the canonical
1283 /// loop and calls to an OpenMP runtime finalization function after the loop.
1284 ///
1285 /// The concrete transformation is done by applyStaticWorkshareLoop,
1286 /// applyStaticChunkedWorkshareLoop, or applyDynamicWorkshareLoop, depending
1287 /// on the value of \p SchedKind and \p ChunkSize.
1288 ///
1289 /// \param DL Debug location for instructions added for the
1290 /// workshare-loop construct itself.
1291 /// \param CLI A descriptor of the canonical loop to workshare.
1292 /// \param AllocaIP An insertion point for Alloca instructions usable in the
1293 /// preheader of the loop.
1294 /// \param NeedsBarrier Indicates whether a barrier must be insterted after
1295 /// the loop.
1296 /// \param SchedKind Scheduling algorithm to use.
1297 /// \param ChunkSize The chunk size for the inner loop.
1298 /// \param HasSimdModifier Whether the simd modifier is present in the
1299 /// schedule clause.
1300 /// \param HasMonotonicModifier Whether the monotonic modifier is present in
1301 /// the schedule clause.
1302 /// \param HasNonmonotonicModifier Whether the nonmonotonic modifier is
1303 /// present in the schedule clause.
1304 /// \param HasOrderedClause Whether the (parameterless) ordered clause is
1305 /// present.
1306 /// \param LoopType Information about type of loop worksharing.
1307 /// It corresponds to type of loop workshare OpenMP pragma.
1308 /// \param NoLoop If true, no-loop code is generated.
1309 /// \param HasDistSchedule Defines if the clause being lowered is
1310 /// dist_schedule as this is handled slightly differently
1311 ///
1312 /// \param DistScheduleChunkSize The chunk size for dist_schedule loop
1313 ///
1314 /// \returns Point where to insert code after the workshare construct.
1317 bool NeedsBarrier,
1318 llvm::omp::ScheduleKind SchedKind = llvm::omp::OMP_SCHEDULE_Default,
1319 Value *ChunkSize = nullptr, bool HasSimdModifier = false,
1320 bool HasMonotonicModifier = false, bool HasNonmonotonicModifier = false,
1321 bool HasOrderedClause = false,
1322 omp::WorksharingLoopType LoopType =
1324 bool NoLoop = false, bool HasDistSchedule = false,
1325 Value *DistScheduleChunkSize = nullptr);
1326
1327 /// Tile a loop nest.
1328 ///
1329 /// Tiles the loops of \p Loops by the tile sizes in \p TileSizes. Loops in
1330 /// \p/ Loops must be perfectly nested, from outermost to innermost loop
1331 /// (i.e. Loops.front() is the outermost loop). The trip count llvm::Value
1332 /// of every loop and every tile sizes must be usable in the outermost
1333 /// loop's preheader. This implies that the loop nest is rectangular.
1334 ///
1335 /// Example:
1336 /// \code
1337 /// for (int i = 0; i < 15; ++i) // Canonical loop "i"
1338 /// for (int j = 0; j < 14; ++j) // Canonical loop "j"
1339 /// body(i, j);
1340 /// \endcode
1341 ///
1342 /// After tiling with Loops={i,j} and TileSizes={5,7}, the loop is changed to
1343 /// \code
1344 /// for (int i1 = 0; i1 < 3; ++i1)
1345 /// for (int j1 = 0; j1 < 2; ++j1)
1346 /// for (int i2 = 0; i2 < 5; ++i2)
1347 /// for (int j2 = 0; j2 < 7; ++j2)
1348 /// body(i1*3+i2, j1*3+j2);
1349 /// \endcode
1350 ///
1351 /// The returned vector are the loops {i1,j1,i2,j2}. The loops i1 and j1 are
1352 /// referred to the floor, and the loops i2 and j2 are the tiles. Tiling also
1353 /// handles non-constant trip counts, non-constant tile sizes and trip counts
1354 /// that are not multiples of the tile size. In the latter case the tile loop
1355 /// of the last floor-loop iteration will have fewer iterations than specified
1356 /// as its tile size.
1357 ///
1358 ///
1359 /// @param DL Debug location for instructions added by tiling, for
1360 /// instance the floor- and tile trip count computation.
1361 /// @param Loops Loops to tile. The CanonicalLoopInfo objects are
1362 /// invalidated by this method, i.e. should not used after
1363 /// tiling.
1364 /// @param TileSizes For each loop in \p Loops, the tile size for that
1365 /// dimensions.
1366 ///
1367 /// \returns A list of generated loops. Contains twice as many loops as the
1368 /// input loop nest; the first half are the floor loops and the
1369 /// second half are the tile loops.
1370 LLVM_ABI std::vector<CanonicalLoopInfo *>
1372 ArrayRef<Value *> TileSizes);
1373
1374 /// Fuse a sequence of loops.
1375 ///
1376 /// Fuses the loops of \p Loops.
1377 /// The merging of the loops is done in the following structure:
1378 ///
1379 /// Example:
1380 /// \code
1381 /// for (int i = lb0; i < ub0; i += st0) // trip count is calculated as:
1382 /// body(i) // tc0 = (ub0 - lb0 + st0) / st0
1383 /// for (int j = lb1; j < ub1; j += st1)
1384 /// body(j);
1385 ///
1386 /// ...
1387 ///
1388 /// for (int k = lbk; j < ubk; j += stk)
1389 /// body(k);
1390 /// \endcode
1391 ///
1392 /// After fusing the loops a single loop is left:
1393 /// \code
1394 /// for (fuse.index = 0; fuse.index < max(tc0, tc1, ... tck); ++fuse.index) {
1395 /// if (fuse.index < tc0){
1396 /// iv0 = lb0 + st0 * fuse.index;
1397 /// original.index0 = iv0
1398 /// body(0);
1399 /// }
1400 /// if (fuse.index < tc1){
1401 /// iv1 = lb1 + st1 * fuse.index;
1402 /// original.index1 = iv1
1403 /// body(1);
1404 /// }
1405 ///
1406 /// ...
1407 ///
1408 /// if (fuse.index < tck){
1409 /// ivk = lbk + stk * fuse.index;
1410 /// original.indexk = ivk
1411 /// body(k);
1412 /// }
1413 /// }
1414 /// \endcode
1415 ///
1416 ///
1417 /// @param DL Debug location for instructions added by fusion.
1418 ///
1419 /// @param Loops Loops to fuse. The CanonicalLoopInfo objects are
1420 /// invalidated by this method, i.e. should not used after
1421 /// fusion.
1422 ///
1423 /// \returns A single loop generated by the loop fusion
1426
1427 /// Fully unroll a loop.
1428 ///
1429 /// Instead of unrolling the loop immediately (and duplicating its body
1430 /// instructions), it is deferred to LLVM's LoopUnrollPass by adding loop
1431 /// metadata.
1432 ///
1433 /// \param DL Debug location for instructions added by unrolling.
1434 /// \param Loop The loop to unroll. The loop will be invalidated.
1436
1437 /// Fully or partially unroll a loop. How the loop is unrolled is determined
1438 /// using LLVM's LoopUnrollPass.
1439 ///
1440 /// \param DL Debug location for instructions added by unrolling.
1441 /// \param Loop The loop to unroll. The loop will be invalidated.
1443
1444 /// Partially unroll a loop.
1445 ///
1446 /// The CanonicalLoopInfo of the unrolled loop for use with chained
1447 /// loop-associated directive can be requested using \p UnrolledCLI. Not
1448 /// needing the CanonicalLoopInfo allows more efficient code generation by
1449 /// deferring the actual unrolling to the LoopUnrollPass using loop metadata.
1450 /// A loop-associated directive applied to the unrolled loop needs to know the
1451 /// new trip count which means that if using a heuristically determined unroll
1452 /// factor (\p Factor == 0), that factor must be computed immediately. We are
1453 /// using the same logic as the LoopUnrollPass to derived the unroll factor,
1454 /// but which assumes that some canonicalization has taken place (e.g.
1455 /// Mem2Reg, LICM, GVN, Inlining, etc.). That is, the heuristic will perform
1456 /// better when the unrolled loop's CanonicalLoopInfo is not needed.
1457 ///
1458 /// \param DL Debug location for instructions added by unrolling.
1459 /// \param Loop The loop to unroll. The loop will be invalidated.
1460 /// \param Factor The factor to unroll the loop by. A factor of 0
1461 /// indicates that a heuristic should be used to determine
1462 /// the unroll-factor.
1463 /// \param UnrolledCLI If non-null, receives the CanonicalLoopInfo of the
1464 /// partially unrolled loop. Otherwise, uses loop metadata
1465 /// to defer unrolling to the LoopUnrollPass.
1467 int32_t Factor,
1468 CanonicalLoopInfo **UnrolledCLI);
1469
1470 /// Add metadata to simd-ize a loop. If IfCond is not nullptr, the loop
1471 /// is cloned. The metadata which prevents vectorization is added to
1472 /// to the cloned loop. The cloned loop is executed when ifCond is evaluated
1473 /// to false.
1474 ///
1475 /// \param Loop The loop to simd-ize.
1476 /// \param AlignedVars The map which containts pairs of the pointer
1477 /// and its corresponding alignment.
1478 /// \param IfCond The value which corresponds to the if clause
1479 /// condition.
1480 /// \param Order The enum to map order clause.
1481 /// \param Simdlen The Simdlen length to apply to the simd loop.
1482 /// \param Safelen The Safelen length to apply to the simd loop.
1484 MapVector<Value *, Value *> AlignedVars,
1485 Value *IfCond, omp::OrderKind Order,
1486 ConstantInt *Simdlen, ConstantInt *Safelen);
1487
1488 /// Generator for '#omp flush'
1489 ///
1490 /// \param Loc The location where the flush directive was encountered
1491 LLVM_ABI void createFlush(const LocationDescription &Loc);
1492
1493 /// Generator for '#omp taskwait'
1494 ///
1495 /// \param Loc The location where the taskwait directive was encountered.
1496 LLVM_ABI void createTaskwait(const LocationDescription &Loc);
1497
1498 /// Generator for '#omp taskyield'
1499 ///
1500 /// \param Loc The location where the taskyield directive was encountered.
1501 LLVM_ABI void createTaskyield(const LocationDescription &Loc);
1502
1503 /// A struct to pack the relevant information for an OpenMP depend clause.
1513
1514 /// A struct to pack static and dynamic dependency information for a task.
1515 ///
1516 /// For fixed-count (non-iterator) dependencies, callers populate \p Deps
1517 /// and the builder allocates and fills the kmp_depend_info array internally.
1518 /// For iterator-based dependencies, the caller pre-builds the array and
1519 /// sets \p NumDeps and \p DepArray directly.
1521 SmallVector<DependData> Deps; // vector of dependencies
1522 Value *NumDeps; // number of kmp_depend_info entries (used by iterator path)
1523 Value *DepArray; // kmp_depend_info array (used by iterator path)
1524
1525 DependenciesInfo() : Deps(), NumDeps(nullptr), DepArray(nullptr) {}
1528
1529 bool empty() const { return Deps.empty() && DepArray == nullptr; }
1530 };
1531
1532 /// Store one kmp_depend_info entry at the given \p Entry pointer.
1533 LLVM_ABI void emitTaskDependency(IRBuilderBase &Builder, Value *Entry,
1534 const DependData &Dep);
1535
1536 /// Return the LLVM struct type matching runtime `kmp_task_affinity_info_t`.
1537 /// `{ kmp_intptr_t base_addr; size_t len; flags (bitfield storage as i32) }`
1539
1540 /// A struct to pack the relevant information for an OpenMP affinity clause.
1542 Value *Count; // number of kmp_task_affinity_info_t entries
1543 Value *Info; // kmp_task_affinity_info_t
1544 };
1545
1546 /// Generator for `#omp taskloop`
1547 ///
1548 /// \param Loc The location where the taskloop construct was encountered.
1549 /// \param AllocaIP The insertion point to be used for alloca instructions.
1550 /// \param BodyGenCB Callback that will generate the region code.
1551 /// \param LoopInfo Callback that return the CLI
1552 /// \param LBVal Lowerbound value of loop
1553 /// \param UBVal Upperbound value of loop
1554 /// \param StepVal Step value of loop
1555 /// \param Untied True if the task is untied, false if the task is tied.
1556 /// \param IfCond i1 value. If it evaluates to `false`, an undeferred
1557 /// task is generated, and the encountering thread must
1558 /// suspend the current task region, for which execution
1559 /// cannot be resumed until execution of the structured
1560 /// block that is associated with the generated task is
1561 /// completed.
1562 /// \param GrainSize Value of the GrainSize/Num of Tasks if present
1563 /// \param NoGroup False if NoGroup is defined, true if not
1564 /// \param Sched If Grainsize is defined, Sched is 1. Num Tasks, Shed is 2.
1565 /// Otherwise Sched is 0
1566 /// \param Final i1 value which is `true` if the task is final, `false` if the
1567 /// task is not final.
1568 /// \param Mergeable If the given task is `mergeable`
1569 /// \param Priority `priority-value' specifies the execution order of the
1570 /// tasks that is generated by the construct
1571 /// \param NumOfCollapseLoops Defines the number of loops that are being
1572 /// collapsed. The default value is 1, as thats the value when collapse is not
1573 /// used.
1574 /// \param DupCB The callback to generate the duplication code. See
1575 /// documentation for \ref TaskDupCallbackTy. This can be nullptr.
1576 /// \param TaskContextStructPtrVal If non-null, a pointer to to be placed
1577 /// immediately after the {lower bound, upper
1578 /// bound, step} values in the task data.
1579 LLVM_ABI InsertPointOrErrorTy createTaskloop(
1580 const LocationDescription &Loc, InsertPointTy AllocaIP,
1581 BodyGenCallbackTy BodyGenCB,
1583 Value *LBVal, Value *UBVal, Value *StepVal, bool Untied = false,
1584 Value *IfCond = nullptr, Value *GrainSize = nullptr, bool NoGroup = false,
1585 int Sched = 0, Value *Final = nullptr, bool Mergeable = false,
1586 Value *Priority = nullptr, uint64_t NumOfCollapseLoops = 1,
1587 TaskDupCallbackTy DupCB = nullptr,
1588 Value *TaskContextStructPtrVal = nullptr);
1589
1590 /// Generator for `#omp task`
1591 ///
1592 /// \param Loc The location where the task construct was encountered.
1593 /// \param AllocaIP The insertion point to be used for alloca instructions.
1594 /// \param BodyGenCB Callback that will generate the region code.
1595 /// \param Tied True if the task is tied, false if the task is untied.
1596 /// \param Final i1 value which is `true` if the task is final, `false` if the
1597 /// task is not final.
1598 /// \param IfCondition i1 value. If it evaluates to `false`, an undeferred
1599 /// task is generated, and the encountering thread must
1600 /// suspend the current task region, for which execution
1601 /// cannot be resumed until execution of the structured
1602 /// block that is associated with the generated task is
1603 /// completed.
1604 /// \param Dependencies Dependencies info holding either a vector of
1605 /// DependData objects or a pre-built dependency array.
1606 /// \param Affinities AffinityData object holding information of accumulated
1607 /// affinities as specified by the 'affinity' clause.
1608 /// \param EventHandle If present, signifies the event handle as part of
1609 /// the detach clause
1610 /// \param Mergeable If the given task is `mergeable`
1611 /// \param priority `priority-value' specifies the execution order of the
1612 /// tasks that is generated by the construct
1614 const LocationDescription &Loc, InsertPointTy AllocaIP,
1615 BodyGenCallbackTy BodyGenCB, bool Tied = true, Value *Final = nullptr,
1616 Value *IfCondition = nullptr, const DependenciesInfo &Dependencies = {},
1617 AffinityData Affinities = {}, bool Mergeable = false,
1618 Value *EventHandle = nullptr, Value *Priority = nullptr);
1619
1620 /// Generator for the taskgroup construct
1621 ///
1622 /// \param Loc The location where the taskgroup construct was encountered.
1623 /// \param AllocaIP The insertion point to be used for alloca instructions.
1624 /// \param BodyGenCB Callback that will generate the region code.
1625 LLVM_ABI InsertPointOrErrorTy createTaskgroup(const LocationDescription &Loc,
1626 InsertPointTy AllocaIP,
1627 BodyGenCallbackTy BodyGenCB);
1628
1630 std::function<std::tuple<std::string, uint64_t>()>;
1631
1632 /// Creates a unique info for a target entry when provided a filename and
1633 /// line number from.
1634 ///
1635 /// \param CallBack A callback function which should return filename the entry
1636 /// resides in as well as the line number for the target entry
1637 /// \param ParentName The name of the parent the target entry resides in, if
1638 /// any.
1641 vfs::FileSystem &VFS, StringRef ParentName = "");
1642
1643 /// Enum class for the RedctionGen CallBack type to be used.
1645
1646 /// ReductionGen CallBack for Clang
1647 ///
1648 /// \param CodeGenIP InsertPoint for CodeGen.
1649 /// \param Index Index of the ReductionInfo to generate code for.
1650 /// \param LHSPtr Optionally used by Clang to return the LHSPtr it used for
1651 /// codegen, used for fixup later.
1652 /// \param RHSPtr Optionally used by Clang to
1653 /// return the RHSPtr it used for codegen, used for fixup later.
1654 /// \param CurFn Optionally used by Clang to pass in the Current Function as
1655 /// Clang context may be old.
1657 std::function<InsertPointTy(InsertPointTy CodeGenIP, unsigned Index,
1658 Value **LHS, Value **RHS, Function *CurFn)>;
1659
1660 /// ReductionGen CallBack for MLIR
1661 ///
1662 /// \param CodeGenIP InsertPoint for CodeGen.
1663 /// \param LHS Pass in the LHS Value to be used for CodeGen.
1664 /// \param RHS Pass in the RHS Value to be used for CodeGen.
1666 InsertPointTy CodeGenIP, Value *LHS, Value *RHS, Value *&Res)>;
1667
1668 /// Functions used to generate atomic reductions. Such functions take two
1669 /// Values representing pointers to LHS and RHS of the reduction, as well as
1670 /// the element type of these pointers. They are expected to atomically
1671 /// update the LHS to the reduced value.
1673 InsertPointTy, Type *, Value *, Value *)>;
1674
1676 InsertPointTy, Value *ByRefVal, Value *&Res)>;
1677
1678 /// Enum class for reduction evaluation types scalar, complex and aggregate.
1680
1681 /// Information about an OpenMP reduction.
1696
1702
1703 /// Reduction element type, must match pointee type of variable. For by-ref
1704 /// reductions, this would be just an opaque `ptr`.
1706
1707 /// Reduction variable of pointer type.
1709
1710 /// Thread-private partial reduction variable.
1712
1713 /// Reduction evaluation kind - scalar, complex or aggregate.
1715
1716 /// Callback for generating the reduction body. The IR produced by this will
1717 /// be used to combine two values in a thread-safe context, e.g., under
1718 /// lock or within the same thread, and therefore need not be atomic.
1720
1721 /// Clang callback for generating the reduction body. The IR produced by
1722 /// this will be used to combine two values in a thread-safe context, e.g.,
1723 /// under lock or within the same thread, and therefore need not be atomic.
1725
1726 /// Callback for generating the atomic reduction body, may be null. The IR
1727 /// produced by this will be used to atomically combine two values during
1728 /// reduction. If null, the implementation will use the non-atomic version
1729 /// along with the appropriate synchronization mechanisms.
1731
1733
1734 /// For by-ref reductions, we need to keep track of 2 extra types that are
1735 /// potentially different:
1736 /// * The allocated type is the type of the storage allocated by the
1737 /// reduction op's `alloc` region. For example, for allocatables and arrays,
1738 /// this type would be the descriptor/box struct.
1740
1741 /// * The by-ref element type is the type of the actual storage needed for
1742 /// the data of the allocatable or array. For example, an float allocatable
1743 /// of would need some float storage to store intermediate reduction
1744 /// results.
1746 };
1747
1748 enum class CopyAction : unsigned {
1749 // RemoteLaneToThread: Copy over a Reduce list from a remote lane in
1750 // the warp using shuffle instructions.
1752 // ThreadCopy: Make a copy of a Reduce list on the thread's stack.
1754 };
1755
1761
1762 /// Supporting functions for Reductions CodeGen.
1763private:
1764 /// Get the id of the current thread on the GPU.
1765 Value *getGPUThreadID();
1766
1767 /// Get the GPU warp size.
1768 Value *getGPUWarpSize();
1769
1770 /// Get the id of the warp in the block.
1771 /// We assume that the warp size is 32, which is always the case
1772 /// on the NVPTX device, to generate more efficient code.
1773 Value *getNVPTXWarpID();
1774
1775 /// Get the id of the current lane in the Warp.
1776 /// We assume that the warp size is 32, which is always the case
1777 /// on the NVPTX device, to generate more efficient code.
1778 Value *getNVPTXLaneID();
1779
1780 /// Cast value to the specified type.
1781 Value *castValueToType(InsertPointTy AllocaIP, Value *From, Type *ToType);
1782
1783 /// This function creates calls to one of two shuffle functions to copy
1784 /// variables between lanes in a warp.
1785 Value *createRuntimeShuffleFunction(InsertPointTy AllocaIP, Value *Element,
1786 Type *ElementType, Value *Offset);
1787
1788 /// Function to shuffle over the value from the remote lane.
1789 void shuffleAndStore(InsertPointTy AllocaIP, Value *SrcAddr, Value *DstAddr,
1790 Type *ElementType, Value *Offset, Type *ReductionArrayTy,
1791 bool IsByRefElem);
1792
1793 /// Emit instructions to copy a Reduce list, which contains partially
1794 /// aggregated values, in the specified direction.
1795 Error emitReductionListCopy(
1796 InsertPointTy AllocaIP, CopyAction Action, Type *ReductionArrayTy,
1797 ArrayRef<ReductionInfo> ReductionInfos, Value *SrcBase, Value *DestBase,
1798 ArrayRef<bool> IsByRef,
1799 CopyOptionsTy CopyOptions = {nullptr, nullptr, nullptr});
1800
1801 /// Emit a helper that reduces data across two OpenMP threads (lanes)
1802 /// in the same warp. It uses shuffle instructions to copy over data from
1803 /// a remote lane's stack. The reduction algorithm performed is specified
1804 /// by the fourth parameter.
1805 ///
1806 /// Algorithm Versions.
1807 /// Full Warp Reduce (argument value 0):
1808 /// This algorithm assumes that all 32 lanes are active and gathers
1809 /// data from these 32 lanes, producing a single resultant value.
1810 /// Contiguous Partial Warp Reduce (argument value 1):
1811 /// This algorithm assumes that only a *contiguous* subset of lanes
1812 /// are active. This happens for the last warp in a parallel region
1813 /// when the user specified num_threads is not an integer multiple of
1814 /// 32. This contiguous subset always starts with the zeroth lane.
1815 /// Partial Warp Reduce (argument value 2):
1816 /// This algorithm gathers data from any number of lanes at any position.
1817 /// All reduced values are stored in the lowest possible lane. The set
1818 /// of problems every algorithm addresses is a super set of those
1819 /// addressable by algorithms with a lower version number. Overhead
1820 /// increases as algorithm version increases.
1821 ///
1822 /// Terminology
1823 /// Reduce element:
1824 /// Reduce element refers to the individual data field with primitive
1825 /// data types to be combined and reduced across threads.
1826 /// Reduce list:
1827 /// Reduce list refers to a collection of local, thread-private
1828 /// reduce elements.
1829 /// Remote Reduce list:
1830 /// Remote Reduce list refers to a collection of remote (relative to
1831 /// the current thread) reduce elements.
1832 ///
1833 /// We distinguish between three states of threads that are important to
1834 /// the implementation of this function.
1835 /// Alive threads:
1836 /// Threads in a warp executing the SIMT instruction, as distinguished from
1837 /// threads that are inactive due to divergent control flow.
1838 /// Active threads:
1839 /// The minimal set of threads that has to be alive upon entry to this
1840 /// function. The computation is correct iff active threads are alive.
1841 /// Some threads are alive but they are not active because they do not
1842 /// contribute to the computation in any useful manner. Turning them off
1843 /// may introduce control flow overheads without any tangible benefits.
1844 /// Effective threads:
1845 /// In order to comply with the argument requirements of the shuffle
1846 /// function, we must keep all lanes holding data alive. But at most
1847 /// half of them perform value aggregation; we refer to this half of
1848 /// threads as effective. The other half is simply handing off their
1849 /// data.
1850 ///
1851 /// Procedure
1852 /// Value shuffle:
1853 /// In this step active threads transfer data from higher lane positions
1854 /// in the warp to lower lane positions, creating Remote Reduce list.
1855 /// Value aggregation:
1856 /// In this step, effective threads combine their thread local Reduce list
1857 /// with Remote Reduce list and store the result in the thread local
1858 /// Reduce list.
1859 /// Value copy:
1860 /// In this step, we deal with the assumption made by algorithm 2
1861 /// (i.e. contiguity assumption). When we have an odd number of lanes
1862 /// active, say 2k+1, only k threads will be effective and therefore k
1863 /// new values will be produced. However, the Reduce list owned by the
1864 /// (2k+1)th thread is ignored in the value aggregation. Therefore
1865 /// we copy the Reduce list from the (2k+1)th lane to (k+1)th lane so
1866 /// that the contiguity assumption still holds.
1867 ///
1868 /// \param ReductionInfos Array type containing the ReductionOps.
1869 /// \param ReduceFn The reduction function.
1870 /// \param FuncAttrs Optional param to specify any function attributes that
1871 /// need to be copied to the new function.
1872 /// \param IsByRef For each reduction clause, whether the reduction is by-ref
1873 /// or not.
1874 ///
1875 /// \return The ShuffleAndReduce function.
1876 Expected<Function *> emitShuffleAndReduceFunction(
1878 Function *ReduceFn, AttributeList FuncAttrs, ArrayRef<bool> IsByRef);
1879
1880 /// Helper function for CreateCanonicalScanLoops to create InputLoop
1881 /// in the firstGen and Scan Loop in the SecondGen
1882 /// \param InputLoopGen Callback for generating the loop for input phase
1883 /// \param ScanLoopGen Callback for generating the loop for scan phase
1884 /// \param ScanRedInfo Pointer to the ScanInfo objected created using
1885 /// `ScanInfoInitialize`.
1886 ///
1887 /// \return error if any produced, else return success.
1888 Error emitScanBasedDirectiveIR(
1889 llvm::function_ref<Error()> InputLoopGen,
1890 llvm::function_ref<Error(LocationDescription Loc)> ScanLoopGen,
1891 ScanInfo *ScanRedInfo);
1892
1893 /// Creates the basic blocks required for scan reduction.
1894 /// \param ScanRedInfo Pointer to the ScanInfo objected created using
1895 /// `ScanInfoInitialize`.
1896 void createScanBBs(ScanInfo *ScanRedInfo);
1897
1898 /// Dynamically allocates the buffer needed for scan reduction.
1899 /// \param AllocaIP The IP where possibly-shared pointer of buffer needs to
1900 /// be declared.
1901 /// \param ScanVars Scan Variables.
1902 /// \param ScanRedInfo Pointer to the ScanInfo objected created using
1903 /// `ScanInfoInitialize`.
1904 ///
1905 /// \return error if any produced, else return success.
1906 Error emitScanBasedDirectiveDeclsIR(InsertPointTy AllocaIP,
1907 ArrayRef<llvm::Value *> ScanVars,
1908 ArrayRef<llvm::Type *> ScanVarsType,
1909 ScanInfo *ScanRedInfo);
1910
1911 /// Copies the result back to the reduction variable.
1912 /// \param ReductionInfos Array type containing the ReductionOps.
1913 /// \param ScanRedInfo Pointer to the ScanInfo objected created using
1914 /// `ScanInfoInitialize`.
1915 ///
1916 /// \return error if any produced, else return success.
1917 Error emitScanBasedDirectiveFinalsIR(
1920
1921 /// This function emits a helper that gathers Reduce lists from the first
1922 /// lane of every active warp to lanes in the first warp.
1923 ///
1924 /// void inter_warp_copy_func(void* reduce_data, num_warps)
1925 /// shared smem[warp_size];
1926 /// For all data entries D in reduce_data:
1927 /// sync
1928 /// If (I am the first lane in each warp)
1929 /// Copy my local D to smem[warp_id]
1930 /// sync
1931 /// if (I am the first warp)
1932 /// Copy smem[thread_id] to my local D
1933 ///
1934 /// \param Loc The insert and source location description.
1935 /// \param ReductionInfos Array type containing the ReductionOps.
1936 /// \param FuncAttrs Optional param to specify any function attributes that
1937 /// need to be copied to the new function.
1938 /// \param IsByRef For each reduction clause, whether the reduction is by-ref
1939 /// or not.
1940 ///
1941 /// \return The InterWarpCopy function.
1943 emitInterWarpCopyFunction(const LocationDescription &Loc,
1944 ArrayRef<ReductionInfo> ReductionInfos,
1945 AttributeList FuncAttrs, ArrayRef<bool> IsByRef);
1946
1947 /// This function emits a helper that copies all the reduction variables from
1948 /// the team into the provided global buffer for the reduction variables.
1949 ///
1950 /// void list_to_global_copy_func(void *buffer, int Idx, void *reduce_data)
1951 /// For all data entries D in reduce_data:
1952 /// Copy local D to buffer.D[Idx]
1953 ///
1954 /// \param ReductionInfos Array type containing the ReductionOps.
1955 /// \param ReductionsBufferTy The StructTy for the reductions buffer.
1956 /// \param FuncAttrs Optional param to specify any function attributes that
1957 /// need to be copied to the new function.
1958 ///
1959 /// \return The ListToGlobalCopy function.
1961 emitListToGlobalCopyFunction(ArrayRef<ReductionInfo> ReductionInfos,
1962 Type *ReductionsBufferTy,
1963 AttributeList FuncAttrs, ArrayRef<bool> IsByRef);
1964
1965 /// This function emits a helper that copies all the reduction variables from
1966 /// the team into the provided global buffer for the reduction variables.
1967 ///
1968 /// void list_to_global_copy_func(void *buffer, int Idx, void *reduce_data)
1969 /// For all data entries D in reduce_data:
1970 /// Copy buffer.D[Idx] to local D;
1971 ///
1972 /// \param ReductionInfos Array type containing the ReductionOps.
1973 /// \param ReductionsBufferTy The StructTy for the reductions buffer.
1974 /// \param FuncAttrs Optional param to specify any function attributes that
1975 /// need to be copied to the new function.
1976 ///
1977 /// \return The GlobalToList function.
1979 emitGlobalToListCopyFunction(ArrayRef<ReductionInfo> ReductionInfos,
1980 Type *ReductionsBufferTy,
1981 AttributeList FuncAttrs, ArrayRef<bool> IsByRef);
1982
1983 /// This function emits a helper that reduces all the reduction variables from
1984 /// the team into the provided global buffer for the reduction variables.
1985 ///
1986 /// void list_to_global_reduce_func(void *buffer, int Idx, void *reduce_data)
1987 /// void *GlobPtrs[];
1988 /// GlobPtrs[0] = (void*)&buffer.D0[Idx];
1989 /// ...
1990 /// GlobPtrs[N] = (void*)&buffer.DN[Idx];
1991 /// reduce_function(GlobPtrs, reduce_data);
1992 ///
1993 /// \param ReductionInfos Array type containing the ReductionOps.
1994 /// \param ReduceFn The reduction function.
1995 /// \param ReductionsBufferTy The StructTy for the reductions buffer.
1996 /// \param FuncAttrs Optional param to specify any function attributes that
1997 /// need to be copied to the new function.
1998 ///
1999 /// \return The ListToGlobalReduce function.
2001 emitListToGlobalReduceFunction(ArrayRef<ReductionInfo> ReductionInfos,
2002 Function *ReduceFn, Type *ReductionsBufferTy,
2003 AttributeList FuncAttrs,
2004 ArrayRef<bool> IsByRef);
2005
2006 /// This function emits a helper that reduces all the reduction variables from
2007 /// the team into the provided global buffer for the reduction variables.
2008 ///
2009 /// void global_to_list_reduce_func(void *buffer, int Idx, void *reduce_data)
2010 /// void *GlobPtrs[];
2011 /// GlobPtrs[0] = (void*)&buffer.D0[Idx];
2012 /// ...
2013 /// GlobPtrs[N] = (void*)&buffer.DN[Idx];
2014 /// reduce_function(reduce_data, GlobPtrs);
2015 ///
2016 /// \param ReductionInfos Array type containing the ReductionOps.
2017 /// \param ReduceFn The reduction function.
2018 /// \param ReductionsBufferTy The StructTy for the reductions buffer.
2019 /// \param FuncAttrs Optional param to specify any function attributes that
2020 /// need to be copied to the new function.
2021 ///
2022 /// \return The GlobalToListReduce function.
2024 emitGlobalToListReduceFunction(ArrayRef<ReductionInfo> ReductionInfos,
2025 Function *ReduceFn, Type *ReductionsBufferTy,
2026 AttributeList FuncAttrs,
2027 ArrayRef<bool> IsByRef);
2028
2029 /// Get the function name of a reduction function.
2030 std::string getReductionFuncName(StringRef Name) const;
2031
2032 /// Generate a Fortran descriptor for array reductions
2033 ///
2034 /// \param DescriptorAddr Address of the descriptor to initialize
2035 /// \param DataPtr Pointer to the actual data the descriptor should reference
2036 /// \param ElemType Type of elements in the array (may be array type)
2037 /// \param DescriptorType Type of the descriptor structure
2038 /// \param DataPtrPtrGen Callback to get the base_ptr field in the descriptor
2039 ///
2040 /// \return Error if DataPtrPtrGen fails, otherwise success.
2041 InsertPointOrErrorTy generateReductionDescriptor(
2042 Value *DescriptorAddr, Value *DataPtr, Value *SrcDescriptorAddr,
2043 Type *DescriptorType,
2045 DataPtrPtrGen);
2046
2047 /// Emits reduction function.
2048 /// \param ReducerName Name of the function calling the reduction.
2049 /// \param ReductionInfos Array type containing the ReductionOps.
2050 /// \param ReductionGenCBKind Optional param to specify Clang or MLIR
2051 /// CodeGenCB kind.
2052 /// \param FuncAttrs Optional param to specify any function attributes that
2053 /// need to be copied to the new function.
2054 ///
2055 /// \return The reduction function.
2056 Expected<Function *> createReductionFunction(
2057 StringRef ReducerName, ArrayRef<ReductionInfo> ReductionInfos,
2058 ArrayRef<bool> IsByRef,
2060 AttributeList FuncAttrs = {});
2061
2062public:
2063 ///
2064 /// Design of OpenMP reductions on the GPU
2065 ///
2066 /// Consider a typical OpenMP program with one or more reduction
2067 /// clauses:
2068 ///
2069 /// float foo;
2070 /// double bar;
2071 /// #pragma omp target teams distribute parallel for \
2072 /// reduction(+:foo) reduction(*:bar)
2073 /// for (int i = 0; i < N; i++) {
2074 /// foo += A[i]; bar *= B[i];
2075 /// }
2076 ///
2077 /// where 'foo' and 'bar' are reduced across all OpenMP threads in
2078 /// all teams. In our OpenMP implementation on the NVPTX device an
2079 /// OpenMP team is mapped to a CUDA threadblock and OpenMP threads
2080 /// within a team are mapped to CUDA threads within a threadblock.
2081 /// Our goal is to efficiently aggregate values across all OpenMP
2082 /// threads such that:
2083 ///
2084 /// - the compiler and runtime are logically concise, and
2085 /// - the reduction is performed efficiently in a hierarchical
2086 /// manner as follows: within OpenMP threads in the same warp,
2087 /// across warps in a threadblock, and finally across teams on
2088 /// the NVPTX device.
2089 ///
2090 /// Introduction to Decoupling
2091 ///
2092 /// We would like to decouple the compiler and the runtime so that the
2093 /// latter is ignorant of the reduction variables (number, data types)
2094 /// and the reduction operators. This allows a simpler interface
2095 /// and implementation while still attaining good performance.
2096 ///
2097 /// Pseudocode for the aforementioned OpenMP program generated by the
2098 /// compiler is as follows:
2099 ///
2100 /// 1. Create private copies of reduction variables on each OpenMP
2101 /// thread: 'foo_private', 'bar_private'
2102 /// 2. Each OpenMP thread reduces the chunk of 'A' and 'B' assigned
2103 /// to it and writes the result in 'foo_private' and 'bar_private'
2104 /// respectively.
2105 /// 3. Call the OpenMP runtime on the GPU to reduce within a team
2106 /// and store the result on the team master:
2107 ///
2108 /// __kmpc_nvptx_parallel_reduce_nowait_v2(...,
2109 /// reduceData, shuffleReduceFn, interWarpCpyFn)
2110 ///
2111 /// where:
2112 /// struct ReduceData {
2113 /// double *foo;
2114 /// double *bar;
2115 /// } reduceData
2116 /// reduceData.foo = &foo_private
2117 /// reduceData.bar = &bar_private
2118 ///
2119 /// 'shuffleReduceFn' and 'interWarpCpyFn' are pointers to two
2120 /// auxiliary functions generated by the compiler that operate on
2121 /// variables of type 'ReduceData'. They aid the runtime perform
2122 /// algorithmic steps in a data agnostic manner.
2123 ///
2124 /// 'shuffleReduceFn' is a pointer to a function that reduces data
2125 /// of type 'ReduceData' across two OpenMP threads (lanes) in the
2126 /// same warp. It takes the following arguments as input:
2127 ///
2128 /// a. variable of type 'ReduceData' on the calling lane,
2129 /// b. its lane_id,
2130 /// c. an offset relative to the current lane_id to generate a
2131 /// remote_lane_id. The remote lane contains the second
2132 /// variable of type 'ReduceData' that is to be reduced.
2133 /// d. an algorithm version parameter determining which reduction
2134 /// algorithm to use.
2135 ///
2136 /// 'shuffleReduceFn' retrieves data from the remote lane using
2137 /// efficient GPU shuffle intrinsics and reduces, using the
2138 /// algorithm specified by the 4th parameter, the two operands
2139 /// element-wise. The result is written to the first operand.
2140 ///
2141 /// Different reduction algorithms are implemented in different
2142 /// runtime functions, all calling 'shuffleReduceFn' to perform
2143 /// the essential reduction step. Therefore, based on the 4th
2144 /// parameter, this function behaves slightly differently to
2145 /// cooperate with the runtime to ensure correctness under
2146 /// different circumstances.
2147 ///
2148 /// 'InterWarpCpyFn' is a pointer to a function that transfers
2149 /// reduced variables across warps. It tunnels, through CUDA
2150 /// shared memory, the thread-private data of type 'ReduceData'
2151 /// from lane 0 of each warp to a lane in the first warp.
2152 /// 4. Call the OpenMP runtime on the GPU to reduce across teams.
2153 /// The last team writes the global reduced value to memory.
2154 ///
2155 /// ret = __kmpc_nvptx_teams_reduce_nowait(...,
2156 /// reduceData, shuffleReduceFn, interWarpCpyFn,
2157 /// scratchpadCopyFn, loadAndReduceFn)
2158 ///
2159 /// 'scratchpadCopyFn' is a helper that stores reduced
2160 /// data from the team master to a scratchpad array in
2161 /// global memory.
2162 ///
2163 /// 'loadAndReduceFn' is a helper that loads data from
2164 /// the scratchpad array and reduces it with the input
2165 /// operand.
2166 ///
2167 /// These compiler generated functions hide address
2168 /// calculation and alignment information from the runtime.
2169 /// 5. if ret == 1:
2170 /// The team master of the last team stores the reduced
2171 /// result to the globals in memory.
2172 /// foo += reduceData.foo; bar *= reduceData.bar
2173 ///
2174 ///
2175 /// Warp Reduction Algorithms
2176 ///
2177 /// On the warp level, we have three algorithms implemented in the
2178 /// OpenMP runtime depending on the number of active lanes:
2179 ///
2180 /// Full Warp Reduction
2181 ///
2182 /// The reduce algorithm within a warp where all lanes are active
2183 /// is implemented in the runtime as follows:
2184 ///
2185 /// full_warp_reduce(void *reduce_data,
2186 /// kmp_ShuffleReductFctPtr ShuffleReduceFn) {
2187 /// for (int offset = WARPSIZE/2; offset > 0; offset /= 2)
2188 /// ShuffleReduceFn(reduce_data, 0, offset, 0);
2189 /// }
2190 ///
2191 /// The algorithm completes in log(2, WARPSIZE) steps.
2192 ///
2193 /// 'ShuffleReduceFn' is used here with lane_id set to 0 because it is
2194 /// not used therefore we save instructions by not retrieving lane_id
2195 /// from the corresponding special registers. The 4th parameter, which
2196 /// represents the version of the algorithm being used, is set to 0 to
2197 /// signify full warp reduction.
2198 ///
2199 /// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
2200 ///
2201 /// #reduce_elem refers to an element in the local lane's data structure
2202 /// #remote_elem is retrieved from a remote lane
2203 /// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
2204 /// reduce_elem = reduce_elem REDUCE_OP remote_elem;
2205 ///
2206 /// Contiguous Partial Warp Reduction
2207 ///
2208 /// This reduce algorithm is used within a warp where only the first
2209 /// 'n' (n <= WARPSIZE) lanes are active. It is typically used when the
2210 /// number of OpenMP threads in a parallel region is not a multiple of
2211 /// WARPSIZE. The algorithm is implemented in the runtime as follows:
2212 ///
2213 /// void
2214 /// contiguous_partial_reduce(void *reduce_data,
2215 /// kmp_ShuffleReductFctPtr ShuffleReduceFn,
2216 /// int size, int lane_id) {
2217 /// int curr_size;
2218 /// int offset;
2219 /// curr_size = size;
2220 /// mask = curr_size/2;
2221 /// while (offset>0) {
2222 /// ShuffleReduceFn(reduce_data, lane_id, offset, 1);
2223 /// curr_size = (curr_size+1)/2;
2224 /// offset = curr_size/2;
2225 /// }
2226 /// }
2227 ///
2228 /// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
2229 ///
2230 /// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
2231 /// if (lane_id < offset)
2232 /// reduce_elem = reduce_elem REDUCE_OP remote_elem
2233 /// else
2234 /// reduce_elem = remote_elem
2235 ///
2236 /// This algorithm assumes that the data to be reduced are located in a
2237 /// contiguous subset of lanes starting from the first. When there is
2238 /// an odd number of active lanes, the data in the last lane is not
2239 /// aggregated with any other lane's dat but is instead copied over.
2240 ///
2241 /// Dispersed Partial Warp Reduction
2242 ///
2243 /// This algorithm is used within a warp when any discontiguous subset of
2244 /// lanes are active. It is used to implement the reduction operation
2245 /// across lanes in an OpenMP simd region or in a nested parallel region.
2246 ///
2247 /// void
2248 /// dispersed_partial_reduce(void *reduce_data,
2249 /// kmp_ShuffleReductFctPtr ShuffleReduceFn) {
2250 /// int size, remote_id;
2251 /// int logical_lane_id = number_of_active_lanes_before_me() * 2;
2252 /// do {
2253 /// remote_id = next_active_lane_id_right_after_me();
2254 /// # the above function returns 0 of no active lane
2255 /// # is present right after the current lane.
2256 /// size = number_of_active_lanes_in_this_warp();
2257 /// logical_lane_id /= 2;
2258 /// ShuffleReduceFn(reduce_data, logical_lane_id,
2259 /// remote_id-1-threadIdx.x, 2);
2260 /// } while (logical_lane_id % 2 == 0 && size > 1);
2261 /// }
2262 ///
2263 /// There is no assumption made about the initial state of the reduction.
2264 /// Any number of lanes (>=1) could be active at any position. The reduction
2265 /// result is returned in the first active lane.
2266 ///
2267 /// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
2268 ///
2269 /// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
2270 /// if (lane_id % 2 == 0 && offset > 0)
2271 /// reduce_elem = reduce_elem REDUCE_OP remote_elem
2272 /// else
2273 /// reduce_elem = remote_elem
2274 ///
2275 ///
2276 /// Intra-Team Reduction
2277 ///
2278 /// This function, as implemented in the runtime call
2279 /// '__kmpc_nvptx_parallel_reduce_nowait_v2', aggregates data across OpenMP
2280 /// threads in a team. It first reduces within a warp using the
2281 /// aforementioned algorithms. We then proceed to gather all such
2282 /// reduced values at the first warp.
2283 ///
2284 /// The runtime makes use of the function 'InterWarpCpyFn', which copies
2285 /// data from each of the "warp master" (zeroth lane of each warp, where
2286 /// warp-reduced data is held) to the zeroth warp. This step reduces (in
2287 /// a mathematical sense) the problem of reduction across warp masters in
2288 /// a block to the problem of warp reduction.
2289 ///
2290 ///
2291 /// Inter-Team Reduction
2292 ///
2293 /// Once a team has reduced its data to a single value, it is stored in
2294 /// a global scratchpad array. Since each team has a distinct slot, this
2295 /// can be done without locking.
2296 ///
2297 /// The last team to write to the scratchpad array proceeds to reduce the
2298 /// scratchpad array. One or more workers in the last team use the helper
2299 /// 'loadAndReduceDataFn' to load and reduce values from the array, i.e.,
2300 /// the k'th worker reduces every k'th element.
2301 ///
2302 /// Finally, a call is made to '__kmpc_nvptx_parallel_reduce_nowait_v2' to
2303 /// reduce across workers and compute a globally reduced value.
2304 ///
2305 /// \param Loc The location where the reduction was
2306 /// encountered. Must be within the associate
2307 /// directive and after the last local access to the
2308 /// reduction variables.
2309 /// \param AllocaIP An insertion point suitable for allocas usable
2310 /// in reductions.
2311 /// \param CodeGenIP An insertion point suitable for code
2312 /// generation.
2313 /// \param ReductionInfos A list of info on each reduction
2314 /// variable.
2315 /// \param IsNoWait Optional flag set if the reduction is
2316 /// marked as nowait.
2317 /// \param IsByRef For each reduction clause, whether the reduction is by-ref.
2318 /// \param IsTeamsReduction Optional flag set if it is a teams
2319 /// reduction.
2320 /// \param GridValue Optional GPU grid value.
2321 /// \param ReductionBufNum Optional OpenMPCUDAReductionBufNumValue to be
2322 /// used for teams reduction.
2323 /// \param SrcLocInfo Source location information global.
2325 const LocationDescription &Loc, InsertPointTy AllocaIP,
2326 InsertPointTy CodeGenIP, ArrayRef<ReductionInfo> ReductionInfos,
2327 ArrayRef<bool> IsByRef, bool IsNoWait = false,
2328 bool IsTeamsReduction = false,
2330 std::optional<omp::GV> GridValue = {}, unsigned ReductionBufNum = 1024,
2331 Value *SrcLocInfo = nullptr);
2332
2333 // TODO: provide atomic and non-atomic reduction generators for reduction
2334 // operators defined by the OpenMP specification.
2335
2336 /// Generator for '#omp reduction'.
2337 ///
2338 /// Emits the IR instructing the runtime to perform the specific kind of
2339 /// reductions. Expects reduction variables to have been privatized and
2340 /// initialized to reduction-neutral values separately. Emits the calls to
2341 /// runtime functions as well as the reduction function and the basic blocks
2342 /// performing the reduction atomically and non-atomically.
2343 ///
2344 /// The code emitted for the following:
2345 ///
2346 /// \code
2347 /// type var_1;
2348 /// type var_2;
2349 /// #pragma omp <directive> reduction(reduction-op:var_1,var_2)
2350 /// /* body */;
2351 /// \endcode
2352 ///
2353 /// corresponds to the following sketch.
2354 ///
2355 /// \code
2356 /// void _outlined_par() {
2357 /// // N is the number of different reductions.
2358 /// void *red_array[] = {privatized_var_1, privatized_var_2, ...};
2359 /// switch(__kmpc_reduce(..., N, /*size of data in red array*/, red_array,
2360 /// _omp_reduction_func,
2361 /// _gomp_critical_user.reduction.var)) {
2362 /// case 1: {
2363 /// var_1 = var_1 <reduction-op> privatized_var_1;
2364 /// var_2 = var_2 <reduction-op> privatized_var_2;
2365 /// // ...
2366 /// __kmpc_end_reduce(...);
2367 /// break;
2368 /// }
2369 /// case 2: {
2370 /// _Atomic<ReductionOp>(var_1, privatized_var_1);
2371 /// _Atomic<ReductionOp>(var_2, privatized_var_2);
2372 /// // ...
2373 /// break;
2374 /// }
2375 /// default: break;
2376 /// }
2377 /// }
2378 ///
2379 /// void _omp_reduction_func(void **lhs, void **rhs) {
2380 /// *(type *)lhs[0] = *(type *)lhs[0] <reduction-op> *(type *)rhs[0];
2381 /// *(type *)lhs[1] = *(type *)lhs[1] <reduction-op> *(type *)rhs[1];
2382 /// // ...
2383 /// }
2384 /// \endcode
2385 ///
2386 /// \param Loc The location where the reduction was
2387 /// encountered. Must be within the associate
2388 /// directive and after the last local access to the
2389 /// reduction variables.
2390 /// \param AllocaIP An insertion point suitable for allocas usable
2391 /// in reductions.
2392 /// \param ReductionInfos A list of info on each reduction variable.
2393 /// \param IsNoWait A flag set if the reduction is marked as nowait.
2394 /// \param IsByRef A flag set if the reduction is using reference
2395 /// or direct value.
2396 /// \param IsTeamsReduction Optional flag set if it is a teams
2397 /// reduction.
2399 const LocationDescription &Loc, InsertPointTy AllocaIP,
2400 ArrayRef<ReductionInfo> ReductionInfos, ArrayRef<bool> IsByRef,
2401 bool IsNoWait = false, bool IsTeamsReduction = false);
2402
2403 ///}
2404
2405 /// Return the insertion point used by the underlying IRBuilder.
2407
2408 /// Update the internal location to \p Loc.
2410 Builder.restoreIP(Loc.IP);
2411 Builder.SetCurrentDebugLocation(Loc.DL);
2412 return Loc.IP.getBlock() != nullptr;
2413 }
2414
2415 /// Return the function declaration for the runtime function with \p FnID.
2418
2420
2422 ArrayRef<Value *> Args,
2423 StringRef Name = "");
2424
2425 /// Return the (LLVM-IR) string describing the source location \p LocStr.
2427 uint32_t &SrcLocStrSize);
2428
2429 /// Return the (LLVM-IR) string describing the default source location.
2431
2432 /// Return the (LLVM-IR) string describing the source location identified by
2433 /// the arguments.
2435 StringRef FileName, unsigned Line,
2436 unsigned Column,
2437 uint32_t &SrcLocStrSize);
2438
2439 /// Return the (LLVM-IR) string describing the DebugLoc \p DL. Use \p F as
2440 /// fallback if \p DL does not specify the function name.
2442 Function *F = nullptr);
2443
2444 /// Return the (LLVM-IR) string describing the source location \p Loc.
2445 LLVM_ABI Constant *getOrCreateSrcLocStr(const LocationDescription &Loc,
2446 uint32_t &SrcLocStrSize);
2447
2448 /// Return an ident_t* encoding the source location \p SrcLocStr and \p Flags.
2449 /// TODO: Create a enum class for the Reserve2Flags
2451 uint32_t SrcLocStrSize,
2452 omp::IdentFlag Flags = omp::IdentFlag(0),
2453 unsigned Reserve2Flags = 0);
2454
2455 /// Create a hidden global flag \p Name in the module with initial value \p
2456 /// Value.
2458
2459 /// Emit the llvm.used metadata.
2461
2462 /// Emit the kernel execution mode.
2465
2466 /// Generate control flow and cleanup for cancellation.
2467 ///
2468 /// \param CancelFlag Flag indicating if the cancellation is performed.
2469 /// \param CanceledDirective The kind of directive that is cancled.
2470 /// \param ExitCB Extra code to be generated in the exit block.
2471 ///
2472 /// \return an error, if any were triggered during execution.
2474 omp::Directive CanceledDirective);
2475
2476 /// Generate a target region entry call.
2477 ///
2478 /// \param Loc The location at which the request originated and is fulfilled.
2479 /// \param AllocaIP The insertion point to be used for alloca instructions.
2480 /// \param Return Return value of the created function returned by reference.
2481 /// \param DeviceID Identifier for the device via the 'device' clause.
2482 /// \param NumTeams Numer of teams for the region via the 'num_teams' clause
2483 /// or 0 if unspecified and -1 if there is no 'teams' clause.
2484 /// \param NumThreads Number of threads via the 'thread_limit' clause.
2485 /// \param HostPtr Pointer to the host-side pointer of the target kernel.
2486 /// \param KernelArgs Array of arguments to the kernel.
2487 LLVM_ABI InsertPointTy emitTargetKernel(const LocationDescription &Loc,
2488 InsertPointTy AllocaIP,
2489 Value *&Return, Value *Ident,
2490 Value *DeviceID, Value *NumTeams,
2491 Value *NumThreads, Value *HostPtr,
2492 ArrayRef<Value *> KernelArgs);
2493
2494 /// Generate a flush runtime call.
2495 ///
2496 /// \param Loc The location at which the request originated and is fulfilled.
2497 LLVM_ABI void emitFlush(const LocationDescription &Loc);
2498
2499 /// The finalization stack made up of finalize callbacks currently in-flight,
2500 /// wrapped into FinalizationInfo objects that reference also the finalization
2501 /// target block and the kind of cancellable directive.
2503
2504 /// Return true if the last entry in the finalization stack is of kind \p DK
2505 /// and cancellable.
2506 bool isLastFinalizationInfoCancellable(omp::Directive DK) {
2507 return !FinalizationStack.empty() &&
2508 FinalizationStack.back().IsCancellable &&
2509 FinalizationStack.back().DK == DK;
2510 }
2511
2512 /// Generate a taskwait runtime call.
2513 ///
2514 /// \param Loc The location at which the request originated and is fulfilled.
2515 LLVM_ABI void emitTaskwaitImpl(const LocationDescription &Loc);
2516
2517 /// Generate a taskyield runtime call.
2518 ///
2519 /// \param Loc The location at which the request originated and is fulfilled.
2520 LLVM_ABI void emitTaskyieldImpl(const LocationDescription &Loc);
2521
2522 /// Return the current thread ID.
2523 ///
2524 /// \param Ident The ident (ident_t*) describing the query origin.
2526
2527 /// The OpenMPIRBuilder Configuration
2529
2530 /// The underlying LLVM-IR module
2532
2533 /// The LLVM-IR Builder used to create IR.
2535
2536 /// Map to remember source location strings
2538
2539 /// Map to remember existing ident_t*.
2541
2542 /// Info manager to keep track of target regions.
2544
2545 /// The target triple of the underlying module.
2546 const Triple T;
2547
2548 /// Helper that contains information about regions we need to outline
2549 /// during finalization.
2551 using PostOutlineCBTy = std::function<void(Function &)>;
2556 // TODO: this should be safe to enable by default
2558
2559 /// Collect all blocks in between EntryBB and ExitBB in both the given
2560 /// vector and set.
2562 SmallVectorImpl<BasicBlock *> &BlockVector);
2563
2564 /// Return the function that contains the region to be outlined.
2565 Function *getFunction() const { return EntryBB->getParent(); }
2566 };
2567
2568 /// Collection of regions that need to be outlined during finalization.
2570
2571 /// A collection of candidate target functions that's constant allocas will
2572 /// attempt to be raised on a call of finalize after all currently enqueued
2573 /// outline info's have been processed.
2575
2576 /// Collection of owned canonical loop objects that eventually need to be
2577 /// free'd.
2578 std::forward_list<CanonicalLoopInfo> LoopInfos;
2579
2580 /// Collection of owned ScanInfo objects that eventually need to be free'd.
2581 std::forward_list<ScanInfo> ScanInfos;
2582
2583 /// Add a new region that will be outlined later.
2584 void addOutlineInfo(OutlineInfo &&OI) { OutlineInfos.emplace_back(OI); }
2585
2586 /// An ordered map of auto-generated variables to their unique names.
2587 /// It stores variables with the following names: 1) ".gomp_critical_user_" +
2588 /// <critical_section_name> + ".var" for "omp critical" directives; 2)
2589 /// <mangled_name_for_global_var> + ".cache." for cache for threadprivate
2590 /// variables.
2592
2593 /// Computes the size of type in bytes.
2595
2596 // Emit a branch from the current block to the Target block only if
2597 // the current block has a terminator.
2599
2600 // If BB has no use then delete it and return. Else place BB after the current
2601 // block, if possible, or else at the end of the function. Also add a branch
2602 // from current block to BB if current block does not have a terminator.
2603 LLVM_ABI void emitBlock(BasicBlock *BB, Function *CurFn,
2604 bool IsFinished = false);
2605
2606 /// Emits code for OpenMP 'if' clause using specified \a BodyGenCallbackTy
2607 /// Here is the logic:
2608 /// if (Cond) {
2609 /// ThenGen();
2610 /// } else {
2611 /// ElseGen();
2612 /// }
2613 ///
2614 /// \return an error, if any were triggered during execution.
2616 BodyGenCallbackTy ElseGen,
2617 InsertPointTy AllocaIP = {});
2618
2619 /// Create the global variable holding the offload mappings information.
2622 std::string VarName);
2623
2624 /// Create the global variable holding the offload names information.
2627 std::string VarName);
2628
2631 AllocaInst *Args = nullptr;
2633 };
2634
2635 /// Create the allocas instruction used in call to mapper functions.
2637 InsertPointTy AllocaIP,
2638 unsigned NumOperands,
2640
2641 /// Create the call for the target mapper function.
2642 /// \param Loc The source location description.
2643 /// \param MapperFunc Function to be called.
2644 /// \param SrcLocInfo Source location information global.
2645 /// \param MaptypesArg The argument types.
2646 /// \param MapnamesArg The argument names.
2647 /// \param MapperAllocas The AllocaInst used for the call.
2648 /// \param DeviceID Device ID for the call.
2649 /// \param NumOperands Number of operands in the call.
2651 Function *MapperFunc, Value *SrcLocInfo,
2652 Value *MaptypesArg, Value *MapnamesArg,
2654 int64_t DeviceID, unsigned NumOperands);
2655
2656 /// Container for the arguments used to pass data to the runtime library.
2658 /// The array of base pointer passed to the runtime library.
2660 /// The array of section pointers passed to the runtime library.
2662 /// The array of sizes passed to the runtime library.
2663 Value *SizesArray = nullptr;
2664 /// The array of map types passed to the runtime library for the beginning
2665 /// of the region or for the entire region if there are no separate map
2666 /// types for the region end.
2668 /// The array of map types passed to the runtime library for the end of the
2669 /// region, or nullptr if there are no separate map types for the region
2670 /// end.
2672 /// The array of user-defined mappers passed to the runtime library.
2674 /// The array of original declaration names of mapped pointers sent to the
2675 /// runtime library for debugging
2677
2678 explicit TargetDataRTArgs() = default;
2687 };
2688
2689 /// Container to pass the default attributes with which a kernel must be
2690 /// launched, used to set kernel attributes and populate associated static
2691 /// structures.
2692 ///
2693 /// For max values, < 0 means unset, == 0 means set but unknown at compile
2694 /// time. The number of max values will be 1 except for the case where
2695 /// ompx_bare is set.
2706
2707 /// Container to pass LLVM IR runtime values or constants related to the
2708 /// number of teams and threads with which the kernel must be launched, as
2709 /// well as the trip count of the loop, if it is an SPMD or Generic-SPMD
2710 /// kernel. These must be defined in the host prior to the call to the kernel
2711 /// launch OpenMP RTL function.
2714 Value *MinTeams = nullptr;
2717
2718 /// 'parallel' construct 'num_threads' clause value, if present and it is an
2719 /// SPMD kernel.
2720 Value *MaxThreads = nullptr;
2721
2722 /// Total number of iterations of the SPMD or Generic-SPMD kernel or null if
2723 /// it is a generic kernel.
2725
2726 /// Device ID value used in the kernel launch.
2727 Value *DeviceID = nullptr;
2728 };
2729
2730 /// Data structure that contains the needed information to construct the
2731 /// kernel args vector.
2733 /// Number of arguments passed to the runtime library.
2734 unsigned NumTargetItems = 0;
2735 /// Arguments passed to the runtime library
2737 /// The number of iterations
2739 /// The number of teams.
2741 /// The number of threads.
2743 /// The size of the dynamic shared memory.
2745 /// True if the kernel has 'no wait' clause.
2746 bool HasNoWait = false;
2747 /// The fallback mechanism for the shared memory.
2750
2751 // Constructors for TargetKernelArgs.
2752 TargetKernelArgs() = default;
2762 };
2763
2764 /// Create the kernel args vector used by emitTargetKernel. This function
2765 /// creates various constant values that are used in the resulting args
2766 /// vector.
2767 LLVM_ABI static void getKernelArgsVector(TargetKernelArgs &KernelArgs,
2768 IRBuilderBase &Builder,
2769 SmallVector<Value *> &ArgsVector);
2770
2771 /// Struct that keeps the information that should be kept throughout
2772 /// a 'target data' region.
2774 /// Set to true if device pointer information have to be obtained.
2775 bool RequiresDevicePointerInfo = false;
2776 /// Set to true if Clang emits separate runtime calls for the beginning and
2777 /// end of the region. These calls might have separate map type arrays.
2778 bool SeparateBeginEndCalls = false;
2779
2780 public:
2782
2785
2786 /// Indicate whether any user-defined mapper exists.
2787 bool HasMapper = false;
2788 /// The total number of pointers passed to the runtime library.
2789 unsigned NumberOfPtrs = 0u;
2790
2791 bool EmitDebug = false;
2792
2793 /// Whether the `target ... data` directive has a `nowait` clause.
2794 bool HasNoWait = false;
2795
2796 explicit TargetDataInfo() = default;
2797 explicit TargetDataInfo(bool RequiresDevicePointerInfo,
2798 bool SeparateBeginEndCalls)
2799 : RequiresDevicePointerInfo(RequiresDevicePointerInfo),
2800 SeparateBeginEndCalls(SeparateBeginEndCalls) {}
2801 /// Clear information about the data arrays.
2804 HasMapper = false;
2805 NumberOfPtrs = 0u;
2806 }
2807 /// Return true if the current target data information has valid arrays.
2808 bool isValid() {
2809 return RTArgs.BasePointersArray && RTArgs.PointersArray &&
2810 RTArgs.SizesArray && RTArgs.MapTypesArray &&
2811 (!HasMapper || RTArgs.MappersArray) && NumberOfPtrs;
2812 }
2813 bool requiresDevicePointerInfo() { return RequiresDevicePointerInfo; }
2814 bool separateBeginEndCalls() { return SeparateBeginEndCalls; }
2815 };
2816
2824
2825 /// This structure contains combined information generated for mappable
2826 /// clauses, including base pointers, pointers, sizes, map types, user-defined
2827 /// mappers, and non-contiguous information.
2828 struct MapInfosTy {
2843
2844 /// Append arrays in \a CurInfo.
2845 void append(MapInfosTy &CurInfo) {
2846 BasePointers.append(CurInfo.BasePointers.begin(),
2847 CurInfo.BasePointers.end());
2848 Pointers.append(CurInfo.Pointers.begin(), CurInfo.Pointers.end());
2849 DevicePointers.append(CurInfo.DevicePointers.begin(),
2850 CurInfo.DevicePointers.end());
2851 Sizes.append(CurInfo.Sizes.begin(), CurInfo.Sizes.end());
2852 Types.append(CurInfo.Types.begin(), CurInfo.Types.end());
2853 Names.append(CurInfo.Names.begin(), CurInfo.Names.end());
2854 NonContigInfo.Dims.append(CurInfo.NonContigInfo.Dims.begin(),
2855 CurInfo.NonContigInfo.Dims.end());
2856 NonContigInfo.Offsets.append(CurInfo.NonContigInfo.Offsets.begin(),
2857 CurInfo.NonContigInfo.Offsets.end());
2858 NonContigInfo.Counts.append(CurInfo.NonContigInfo.Counts.begin(),
2859 CurInfo.NonContigInfo.Counts.end());
2860 NonContigInfo.Strides.append(CurInfo.NonContigInfo.Strides.begin(),
2861 CurInfo.NonContigInfo.Strides.end());
2862 }
2863 };
2865
2866 /// Callback function type for functions emitting the host fallback code that
2867 /// is executed when the kernel launch fails. It takes an insertion point as
2868 /// parameter where the code should be emitted. It returns an insertion point
2869 /// that points right after after the emitted code.
2872
2873 // Callback function type for emitting and fetching user defined custom
2874 // mappers.
2876 function_ref<Expected<Function *>(unsigned int)>;
2877
2878 /// Generate a target region entry call and host fallback call.
2879 ///
2880 /// \param Loc The location at which the request originated and is fulfilled.
2881 /// \param OutlinedFnID The ooulined function ID.
2882 /// \param EmitTargetCallFallbackCB Call back function to generate host
2883 /// fallback code.
2884 /// \param Args Data structure holding information about the kernel arguments.
2885 /// \param DeviceID Identifier for the device via the 'device' clause.
2886 /// \param RTLoc Source location identifier
2887 /// \param AllocaIP The insertion point to be used for alloca instructions.
2889 const LocationDescription &Loc, Value *OutlinedFnID,
2890 EmitFallbackCallbackTy EmitTargetCallFallbackCB, TargetKernelArgs &Args,
2891 Value *DeviceID, Value *RTLoc, InsertPointTy AllocaIP);
2892
2893 /// Callback type for generating the bodies of device directives that require
2894 /// outer target tasks (e.g. in case of having `nowait` or `depend` clauses).
2895 ///
2896 /// \param DeviceID The ID of the device on which the target region will
2897 /// execute.
2898 /// \param RTLoc Source location identifier
2899 /// \Param TargetTaskAllocaIP Insertion point for the alloca block of the
2900 /// generated task.
2901 ///
2902 /// \return an error, if any were triggered during execution.
2904 function_ref<Error(Value *DeviceID, Value *RTLoc,
2905 IRBuilderBase::InsertPoint TargetTaskAllocaIP)>;
2906
2907 /// Generate a target-task for the target construct
2908 ///
2909 /// \param TaskBodyCB Callback to generate the actual body of the target task.
2910 /// \param DeviceID Identifier for the device via the 'device' clause.
2911 /// \param RTLoc Source location identifier
2912 /// \param AllocaIP The insertion point to be used for alloca instructions.
2913 /// \param Dependencies Dependencies info as specified by the 'depend' clause.
2914 /// \param HasNoWait True if the target construct had 'nowait' on it, false
2915 /// otherwise
2917 emitTargetTask(TargetTaskBodyCallbackTy TaskBodyCB, Value *DeviceID,
2918 Value *RTLoc, OpenMPIRBuilder::InsertPointTy AllocaIP,
2919 const DependenciesInfo &Dependencies,
2920 const TargetDataRTArgs &RTArgs, bool HasNoWait);
2921
2922 /// Emit the arguments to be passed to the runtime library based on the
2923 /// arrays of base pointers, pointers, sizes, map types, and mappers. If
2924 /// ForEndCall, emit map types to be passed for the end of the region instead
2925 /// of the beginning.
2928 OpenMPIRBuilder::TargetDataInfo &Info, bool ForEndCall = false);
2929
2930 /// Emit an array of struct descriptors to be assigned to the offload args.
2932 InsertPointTy CodeGenIP,
2933 MapInfosTy &CombinedInfo,
2934 TargetDataInfo &Info);
2935
2936 /// Emit the arrays used to pass the captures and map information to the
2937 /// offloading runtime library. If there is no map or capture information,
2938 /// return nullptr by reference. Accepts a reference to a MapInfosTy object
2939 /// that contains information generated for mappable clauses,
2940 /// including base pointers, pointers, sizes, map types, user-defined mappers.
2942 InsertPointTy AllocaIP, InsertPointTy CodeGenIP, MapInfosTy &CombinedInfo,
2943 TargetDataInfo &Info, CustomMapperCallbackTy CustomMapperCB,
2944 bool IsNonContiguous = false,
2945 function_ref<void(unsigned int, Value *)> DeviceAddrCB = nullptr);
2946
2947 /// Allocates memory for and populates the arrays required for offloading
2948 /// (offload_{baseptrs|ptrs|mappers|sizes|maptypes|mapnames}). Then, it
2949 /// emits their base addresses as arguments to be passed to the runtime
2950 /// library. In essence, this function is a combination of
2951 /// emitOffloadingArrays and emitOffloadingArraysArgument and should arguably
2952 /// be preferred by clients of OpenMPIRBuilder.
2954 InsertPointTy AllocaIP, InsertPointTy CodeGenIP, TargetDataInfo &Info,
2955 TargetDataRTArgs &RTArgs, MapInfosTy &CombinedInfo,
2956 CustomMapperCallbackTy CustomMapperCB, bool IsNonContiguous = false,
2957 bool ForEndCall = false,
2958 function_ref<void(unsigned int, Value *)> DeviceAddrCB = nullptr);
2959
2960 /// Creates offloading entry for the provided entry ID \a ID, address \a
2961 /// Addr, size \a Size, and flags \a Flags.
2963 int32_t Flags, GlobalValue::LinkageTypes,
2964 StringRef Name = "");
2965
2966 /// The kind of errors that can occur when emitting the offload entries and
2967 /// metadata.
2974
2975 /// Callback function type
2977 std::function<void(EmitMetadataErrorKind, TargetRegionEntryInfo)>;
2978
2979 // Emit the offloading entries and metadata so that the device codegen side
2980 // can easily figure out what to emit. The produced metadata looks like
2981 // this:
2982 //
2983 // !omp_offload.info = !{!1, ...}
2984 //
2985 // We only generate metadata for function that contain target regions.
2987 EmitMetadataErrorReportFunctionTy &ErrorReportFunction);
2988
2989public:
2990 /// Generator for __kmpc_copyprivate
2991 ///
2992 /// \param Loc The source location description.
2993 /// \param BufSize Number of elements in the buffer.
2994 /// \param CpyBuf List of pointers to data to be copied.
2995 /// \param CpyFn function to call for copying data.
2996 /// \param DidIt flag variable; 1 for 'single' thread, 0 otherwise.
2997 ///
2998 /// \return The insertion position *after* the CopyPrivate call.
2999
3001 llvm::Value *BufSize,
3002 llvm::Value *CpyBuf,
3003 llvm::Value *CpyFn,
3004 llvm::Value *DidIt);
3005
3006 /// Generator for '#omp single'
3007 ///
3008 /// \param Loc The source location description.
3009 /// \param BodyGenCB Callback that will generate the region code.
3010 /// \param FiniCB Callback to finalize variable copies.
3011 /// \param IsNowait If false, a barrier is emitted.
3012 /// \param CPVars copyprivate variables.
3013 /// \param CPFuncs copy functions to use for each copyprivate variable.
3014 ///
3015 /// \returns The insertion position *after* the single call.
3018 FinalizeCallbackTy FiniCB, bool IsNowait,
3019 ArrayRef<llvm::Value *> CPVars = {},
3020 ArrayRef<llvm::Function *> CPFuncs = {});
3021
3022 /// Generator for '#omp master'
3023 ///
3024 /// \param Loc The insert and source location description.
3025 /// \param BodyGenCB Callback that will generate the region code.
3026 /// \param FiniCB Callback to finalize variable copies.
3027 ///
3028 /// \returns The insertion position *after* the master.
3029 LLVM_ABI InsertPointOrErrorTy createMaster(const LocationDescription &Loc,
3030 BodyGenCallbackTy BodyGenCB,
3031 FinalizeCallbackTy FiniCB);
3032
3033 /// Generator for '#omp masked'
3034 ///
3035 /// \param Loc The insert and source location description.
3036 /// \param BodyGenCB Callback that will generate the region code.
3037 /// \param FiniCB Callback to finialize variable copies.
3038 ///
3039 /// \returns The insertion position *after* the masked.
3040 LLVM_ABI InsertPointOrErrorTy createMasked(const LocationDescription &Loc,
3041 BodyGenCallbackTy BodyGenCB,
3042 FinalizeCallbackTy FiniCB,
3043 Value *Filter);
3044
3045 /// This function performs the scan reduction of the values updated in
3046 /// the input phase. The reduction logic needs to be emitted between input
3047 /// and scan loop returned by `CreateCanonicalScanLoops`. The following
3048 /// is the code that is generated, `buffer` and `span` are expected to be
3049 /// populated before executing the generated code.
3050 /// \code{c}
3051 /// for (int k = 0; k != ceil(log2(span)); ++k) {
3052 /// i=pow(2,k)
3053 /// for (size cnt = last_iter; cnt >= i; --cnt)
3054 /// buffer[cnt] op= buffer[cnt-i];
3055 /// }
3056 /// \endcode
3057 /// \param Loc The insert and source location description.
3058 /// \param ReductionInfos Array type containing the ReductionOps.
3059 /// \param ScanRedInfo Pointer to the ScanInfo objected created using
3060 /// `ScanInfoInitialize`.
3061 ///
3062 /// \returns The insertion position *after* the masked.
3064 const LocationDescription &Loc,
3066 ScanInfo *ScanRedInfo);
3067
3068 /// This directive split and directs the control flow to input phase
3069 /// blocks or scan phase blocks based on 1. whether input loop or scan loop
3070 /// is executed, 2. whether exclusive or inclusive scan is used.
3071 ///
3072 /// \param Loc The insert and source location description.
3073 /// \param AllocaIP The IP where the temporary buffer for scan reduction
3074 // needs to be allocated.
3075 /// \param ScanVars Scan Variables.
3076 /// \param IsInclusive Whether it is an inclusive or exclusive scan.
3077 /// \param ScanRedInfo Pointer to the ScanInfo objected created using
3078 /// `ScanInfoInitialize`.
3079 ///
3080 /// \returns The insertion position *after* the scan.
3081 LLVM_ABI InsertPointOrErrorTy createScan(const LocationDescription &Loc,
3082 InsertPointTy AllocaIP,
3083 ArrayRef<llvm::Value *> ScanVars,
3084 ArrayRef<llvm::Type *> ScanVarsType,
3085 bool IsInclusive,
3086 ScanInfo *ScanRedInfo);
3087
3088 /// Generator for '#omp critical'
3089 ///
3090 /// \param Loc The insert and source location description.
3091 /// \param BodyGenCB Callback that will generate the region body code.
3092 /// \param FiniCB Callback to finalize variable copies.
3093 /// \param CriticalName name of the lock used by the critical directive
3094 /// \param HintInst Hint Instruction for hint clause associated with critical
3095 ///
3096 /// \returns The insertion position *after* the critical.
3097 LLVM_ABI InsertPointOrErrorTy createCritical(const LocationDescription &Loc,
3098 BodyGenCallbackTy BodyGenCB,
3099 FinalizeCallbackTy FiniCB,
3100 StringRef CriticalName,
3101 Value *HintInst);
3102
3103 /// Generator for '#omp ordered depend (source | sink)'
3104 ///
3105 /// \param Loc The insert and source location description.
3106 /// \param AllocaIP The insertion point to be used for alloca instructions.
3107 /// \param NumLoops The number of loops in depend clause.
3108 /// \param StoreValues The value will be stored in vector address.
3109 /// \param Name The name of alloca instruction.
3110 /// \param IsDependSource If true, depend source; otherwise, depend sink.
3111 ///
3112 /// \return The insertion position *after* the ordered.
3114 createOrderedDepend(const LocationDescription &Loc, InsertPointTy AllocaIP,
3115 unsigned NumLoops, ArrayRef<llvm::Value *> StoreValues,
3116 const Twine &Name, bool IsDependSource);
3117
3118 /// Generator for '#omp ordered [threads | simd]'
3119 ///
3120 /// \param Loc The insert and source location description.
3121 /// \param BodyGenCB Callback that will generate the region code.
3122 /// \param FiniCB Callback to finalize variable copies.
3123 /// \param IsThreads If true, with threads clause or without clause;
3124 /// otherwise, with simd clause;
3125 ///
3126 /// \returns The insertion position *after* the ordered.
3128 const LocationDescription &Loc, BodyGenCallbackTy BodyGenCB,
3129 FinalizeCallbackTy FiniCB, bool IsThreads);
3130
3131 /// Generator for '#omp sections'
3132 ///
3133 /// \param Loc The insert and source location description.
3134 /// \param AllocaIP The insertion points to be used for alloca instructions.
3135 /// \param SectionCBs Callbacks that will generate body of each section.
3136 /// \param PrivCB Callback to copy a given variable (think copy constructor).
3137 /// \param FiniCB Callback to finalize variable copies.
3138 /// \param IsCancellable Flag to indicate a cancellable parallel region.
3139 /// \param IsNowait If true, barrier - to ensure all sections are executed
3140 /// before moving forward will not be generated.
3141 /// \returns The insertion position *after* the sections.
3143 createSections(const LocationDescription &Loc, InsertPointTy AllocaIP,
3146 bool IsCancellable, bool IsNowait);
3147
3148 /// Generator for '#omp section'
3149 ///
3150 /// \param Loc The insert and source location description.
3151 /// \param BodyGenCB Callback that will generate the region body code.
3152 /// \param FiniCB Callback to finalize variable copies.
3153 /// \returns The insertion position *after* the section.
3154 LLVM_ABI InsertPointOrErrorTy createSection(const LocationDescription &Loc,
3155 BodyGenCallbackTy BodyGenCB,
3156 FinalizeCallbackTy FiniCB);
3157
3158 /// Generator for `#omp teams`
3159 ///
3160 /// \param Loc The location where the teams construct was encountered.
3161 /// \param BodyGenCB Callback that will generate the region code.
3162 /// \param NumTeamsLower Lower bound on number of teams. If this is nullptr,
3163 /// it is as if lower bound is specified as equal to upperbound. If
3164 /// this is non-null, then upperbound must also be non-null.
3165 /// \param NumTeamsUpper Upper bound on the number of teams.
3166 /// \param ThreadLimit on the number of threads that may participate in a
3167 /// contention group created by each team.
3168 /// \param IfExpr is the integer argument value of the if condition on the
3169 /// teams clause.
3170 LLVM_ABI InsertPointOrErrorTy createTeams(const LocationDescription &Loc,
3171 BodyGenCallbackTy BodyGenCB,
3172 Value *NumTeamsLower = nullptr,
3173 Value *NumTeamsUpper = nullptr,
3174 Value *ThreadLimit = nullptr,
3175 Value *IfExpr = nullptr);
3176
3177 /// Generator for `#omp distribute`
3178 ///
3179 /// \param Loc The location where the distribute construct was encountered.
3180 /// \param AllocaIP The insertion points to be used for alloca instructions.
3181 /// \param BodyGenCB Callback that will generate the region code.
3182 LLVM_ABI InsertPointOrErrorTy createDistribute(const LocationDescription &Loc,
3183 InsertPointTy AllocaIP,
3184 BodyGenCallbackTy BodyGenCB);
3185
3186 /// Generate conditional branch and relevant BasicBlocks through which private
3187 /// threads copy the 'copyin' variables from Master copy to threadprivate
3188 /// copies.
3189 ///
3190 /// \param IP insertion block for copyin conditional
3191 /// \param MasterVarPtr a pointer to the master variable
3192 /// \param PrivateVarPtr a pointer to the threadprivate variable
3193 /// \param IntPtrTy Pointer size type
3194 /// \param BranchtoEnd Create a branch between the copyin.not.master blocks
3195 // and copy.in.end block
3196 ///
3197 /// \returns The insertion point where copying operation to be emitted.
3199 Value *MasterAddr,
3200 Value *PrivateAddr,
3201 llvm::IntegerType *IntPtrTy,
3202 bool BranchtoEnd = true);
3203
3204 /// Create a runtime call for kmpc_Alloc
3205 ///
3206 /// \param Loc The insert and source location description.
3207 /// \param Size Size of allocated memory space
3208 /// \param Allocator Allocator information instruction
3209 /// \param Name Name of call Instruction for OMP_alloc
3210 ///
3211 /// \returns CallInst to the OMP_Alloc call
3212 LLVM_ABI CallInst *createOMPAlloc(const LocationDescription &Loc, Value *Size,
3213 Value *Allocator, std::string Name = "");
3214
3215 /// Create a runtime call for kmpc_free
3216 ///
3217 /// \param Loc The insert and source location description.
3218 /// \param Addr Address of memory space to be freed
3219 /// \param Allocator Allocator information instruction
3220 /// \param Name Name of call Instruction for OMP_Free
3221 ///
3222 /// \returns CallInst to the OMP_Free call
3223 LLVM_ABI CallInst *createOMPFree(const LocationDescription &Loc, Value *Addr,
3224 Value *Allocator, std::string Name = "");
3225
3226 /// Create a runtime call for kmpc_threadprivate_cached
3227 ///
3228 /// \param Loc The insert and source location description.
3229 /// \param Pointer pointer to data to be cached
3230 /// \param Size size of data to be cached
3231 /// \param Name Name of call Instruction for callinst
3232 ///
3233 /// \returns CallInst to the thread private cache call.
3234 LLVM_ABI CallInst *
3235 createCachedThreadPrivate(const LocationDescription &Loc,
3237 const llvm::Twine &Name = Twine(""));
3238
3239 /// Create a runtime call for __tgt_interop_init
3240 ///
3241 /// \param Loc The insert and source location description.
3242 /// \param InteropVar variable to be allocated
3243 /// \param InteropType type of interop operation
3244 /// \param Device devide to which offloading will occur
3245 /// \param NumDependences number of dependence variables
3246 /// \param DependenceAddress pointer to dependence variables
3247 /// \param HaveNowaitClause does nowait clause exist
3248 ///
3249 /// \returns CallInst to the __tgt_interop_init call
3250 LLVM_ABI CallInst *createOMPInteropInit(const LocationDescription &Loc,
3251 Value *InteropVar,
3252 omp::OMPInteropType InteropType,
3253 Value *Device, Value *NumDependences,
3254 Value *DependenceAddress,
3255 bool HaveNowaitClause);
3256
3257 /// Create a runtime call for __tgt_interop_destroy
3258 ///
3259 /// \param Loc The insert and source location description.
3260 /// \param InteropVar variable to be allocated
3261 /// \param Device devide to which offloading will occur
3262 /// \param NumDependences number of dependence variables
3263 /// \param DependenceAddress pointer to dependence variables
3264 /// \param HaveNowaitClause does nowait clause exist
3265 ///
3266 /// \returns CallInst to the __tgt_interop_destroy call
3267 LLVM_ABI CallInst *createOMPInteropDestroy(const LocationDescription &Loc,
3268 Value *InteropVar, Value *Device,
3269 Value *NumDependences,
3270 Value *DependenceAddress,
3271 bool HaveNowaitClause);
3272
3273 /// Create a runtime call for __tgt_interop_use
3274 ///
3275 /// \param Loc The insert and source location description.
3276 /// \param InteropVar variable to be allocated
3277 /// \param Device devide to which offloading will occur
3278 /// \param NumDependences number of dependence variables
3279 /// \param DependenceAddress pointer to dependence variables
3280 /// \param HaveNowaitClause does nowait clause exist
3281 ///
3282 /// \returns CallInst to the __tgt_interop_use call
3283 LLVM_ABI CallInst *createOMPInteropUse(const LocationDescription &Loc,
3284 Value *InteropVar, Value *Device,
3285 Value *NumDependences,
3286 Value *DependenceAddress,
3287 bool HaveNowaitClause);
3288
3289 /// The `omp target` interface
3290 ///
3291 /// For more information about the usage of this interface,
3292 /// \see openmp/device/include/Interface.h
3293 ///
3294 ///{
3295
3296 /// Create a runtime call for kmpc_target_init
3297 ///
3298 /// \param Loc The insert and source location description.
3299 /// \param Attrs Structure containing the default attributes, including
3300 /// numbers of threads and teams to launch the kernel with.
3302 const LocationDescription &Loc,
3304
3305 /// Create a runtime call for kmpc_target_deinit
3306 ///
3307 /// \param Loc The insert and source location description.
3308 /// \param TeamsReductionDataSize The maximal size of all the reduction data
3309 /// for teams reduction.
3310 /// \param TeamsReductionBufferLength The number of elements (each of up to
3311 /// \p TeamsReductionDataSize size), in the teams reduction buffer.
3312 LLVM_ABI void createTargetDeinit(const LocationDescription &Loc,
3313 int32_t TeamsReductionDataSize = 0,
3314 int32_t TeamsReductionBufferLength = 1024);
3315
3316 ///}
3317
3318 /// Helpers to read/write kernel annotations from the IR.
3319 ///
3320 ///{
3321
3322 /// Read/write a bounds on threads for \p Kernel. Read will return 0 if none
3323 /// is set.
3324 LLVM_ABI static std::pair<int32_t, int32_t>
3325 readThreadBoundsForKernel(const Triple &T, Function &Kernel);
3326 LLVM_ABI static void writeThreadBoundsForKernel(const Triple &T,
3327 Function &Kernel, int32_t LB,
3328 int32_t UB);
3329
3330 /// Read/write a bounds on teams for \p Kernel. Read will return 0 if none
3331 /// is set.
3332 LLVM_ABI static std::pair<int32_t, int32_t>
3333 readTeamBoundsForKernel(const Triple &T, Function &Kernel);
3334 LLVM_ABI static void writeTeamsForKernel(const Triple &T, Function &Kernel,
3335 int32_t LB, int32_t UB);
3336 ///}
3337
3338private:
3339 // Sets the function attributes expected for the outlined function
3340 void setOutlinedTargetRegionFunctionAttributes(Function *OutlinedFn);
3341
3342 // Creates the function ID/Address for the given outlined function.
3343 // In the case of an embedded device function the address of the function is
3344 // used, in the case of a non-offload function a constant is created.
3345 Constant *createOutlinedFunctionID(Function *OutlinedFn,
3346 StringRef EntryFnIDName);
3347
3348 // Creates the region entry address for the outlined function
3349 Constant *createTargetRegionEntryAddr(Function *OutlinedFunction,
3350 StringRef EntryFnName);
3351
3352public:
3353 /// Functions used to generate a function with the given name.
3355 std::function<Expected<Function *>(StringRef FunctionName)>;
3356
3357 /// Create a unique name for the entry function using the source location
3358 /// information of the current target region. The name will be something like:
3359 ///
3360 /// __omp_offloading_DD_FFFF_PP_lBB[_CC]
3361 ///
3362 /// where DD_FFFF is an ID unique to the file (device and file IDs), PP is the
3363 /// mangled name of the function that encloses the target region and BB is the
3364 /// line number of the target region. CC is a count added when more than one
3365 /// region is located at the same location.
3366 ///
3367 /// If this target outline function is not an offload entry, we don't need to
3368 /// register it. This may happen if it is guarded by an if clause that is
3369 /// false at compile time, or no target archs have been specified.
3370 ///
3371 /// The created target region ID is used by the runtime library to identify
3372 /// the current target region, so it only has to be unique and not
3373 /// necessarily point to anything. It could be the pointer to the outlined
3374 /// function that implements the target region, but we aren't using that so
3375 /// that the compiler doesn't need to keep that, and could therefore inline
3376 /// the host function if proven worthwhile during optimization. In the other
3377 /// hand, if emitting code for the device, the ID has to be the function
3378 /// address so that it can retrieved from the offloading entry and launched
3379 /// by the runtime library. We also mark the outlined function to have
3380 /// external linkage in case we are emitting code for the device, because
3381 /// these functions will be entry points to the device.
3382 ///
3383 /// \param InfoManager The info manager keeping track of the offload entries
3384 /// \param EntryInfo The entry information about the function
3385 /// \param GenerateFunctionCallback The callback function to generate the code
3386 /// \param OutlinedFunction Pointer to the outlined function
3387 /// \param EntryFnIDName Name of the ID o be created
3389 TargetRegionEntryInfo &EntryInfo,
3390 FunctionGenCallback &GenerateFunctionCallback, bool IsOffloadEntry,
3391 Function *&OutlinedFn, Constant *&OutlinedFnID);
3392
3393 /// Registers the given function and sets up the attribtues of the function
3394 /// Returns the FunctionID.
3395 ///
3396 /// \param InfoManager The info manager keeping track of the offload entries
3397 /// \param EntryInfo The entry information about the function
3398 /// \param OutlinedFunction Pointer to the outlined function
3399 /// \param EntryFnName Name of the outlined function
3400 /// \param EntryFnIDName Name of the ID o be created
3403 Function *OutlinedFunction,
3404 StringRef EntryFnName, StringRef EntryFnIDName);
3405
3406 /// Type of BodyGen to use for region codegen
3407 ///
3408 /// Priv: If device pointer privatization is required, emit the body of the
3409 /// region here. It will have to be duplicated: with and without
3410 /// privatization.
3411 /// DupNoPriv: If we need device pointer privatization, we need
3412 /// to emit the body of the region with no privatization in the 'else' branch
3413 /// of the conditional.
3414 /// NoPriv: If we don't require privatization of device
3415 /// pointers, we emit the body in between the runtime calls. This avoids
3416 /// duplicating the body code.
3418
3419 /// Callback type for creating the map infos for the kernel parameters.
3420 /// \param CodeGenIP is the insertion point where code should be generated,
3421 /// if any.
3424
3425private:
3426 /// Emit the array initialization or deletion portion for user-defined mapper
3427 /// code generation. First, it evaluates whether an array section is mapped
3428 /// and whether the \a MapType instructs to delete this section. If \a IsInit
3429 /// is true, and \a MapType indicates to not delete this array, array
3430 /// initialization code is generated. If \a IsInit is false, and \a MapType
3431 /// indicates to delete this array, array deletion code is generated.
3432 void emitUDMapperArrayInitOrDel(Function *MapperFn, llvm::Value *MapperHandle,
3433 llvm::Value *Base, llvm::Value *Begin,
3434 llvm::Value *Size, llvm::Value *MapType,
3435 llvm::Value *MapName, TypeSize ElementSize,
3436 llvm::BasicBlock *ExitBB, bool IsInit);
3437
3438public:
3439 /// Emit the user-defined mapper function. The code generation follows the
3440 /// pattern in the example below.
3441 /// \code
3442 /// void .omp_mapper.<type_name>.<mapper_id>.(void *rt_mapper_handle,
3443 /// void *base, void *begin,
3444 /// int64_t size, int64_t type,
3445 /// void *name = nullptr) {
3446 /// // Allocate space for an array section first or add a base/begin for
3447 /// // pointer dereference.
3448 /// if ((size > 1 || (base != begin && maptype.IsPtrAndObj)) &&
3449 /// !maptype.IsDelete)
3450 /// __tgt_push_mapper_component(rt_mapper_handle, base, begin,
3451 /// size*sizeof(Ty), clearToFromMember(type));
3452 /// // Map members.
3453 /// for (unsigned i = 0; i < size; i++) {
3454 /// // For each component specified by this mapper:
3455 /// for (auto c : begin[i]->all_components) {
3456 /// if (c.hasMapper())
3457 /// (*c.Mapper())(rt_mapper_handle, c.arg_base, c.arg_begin,
3458 /// c.arg_size,
3459 /// c.arg_type, c.arg_name);
3460 /// else
3461 /// __tgt_push_mapper_component(rt_mapper_handle, c.arg_base,
3462 /// c.arg_begin, c.arg_size, c.arg_type,
3463 /// c.arg_name);
3464 /// }
3465 /// }
3466 /// // Delete the array section.
3467 /// if (size > 1 && maptype.IsDelete)
3468 /// __tgt_push_mapper_component(rt_mapper_handle, base, begin,
3469 /// size*sizeof(Ty), clearToFromMember(type));
3470 /// }
3471 /// \endcode
3472 ///
3473 /// \param PrivAndGenMapInfoCB Callback that privatizes code and populates the
3474 /// MapInfos and returns.
3475 /// \param ElemTy DeclareMapper element type.
3476 /// \param FuncName Optional param to specify mapper function name.
3477 /// \param CustomMapperCB Optional callback to generate code related to
3478 /// custom mappers.
3481 InsertPointTy CodeGenIP, llvm::Value *PtrPHI, llvm::Value *BeginArg)>
3482 PrivAndGenMapInfoCB,
3483 llvm::Type *ElemTy, StringRef FuncName,
3484 CustomMapperCallbackTy CustomMapperCB);
3485
3486 /// Generator for '#omp target data'
3487 ///
3488 /// \param Loc The location where the target data construct was encountered.
3489 /// \param AllocaIP The insertion points to be used for alloca instructions.
3490 /// \param CodeGenIP The insertion point at which the target directive code
3491 /// should be placed.
3492 /// \param IsBegin If true then emits begin mapper call otherwise emits
3493 /// end mapper call.
3494 /// \param DeviceID Stores the DeviceID from the device clause.
3495 /// \param IfCond Value which corresponds to the if clause condition.
3496 /// \param Info Stores all information realted to the Target Data directive.
3497 /// \param GenMapInfoCB Callback that populates the MapInfos and returns.
3498 /// \param CustomMapperCB Callback to generate code related to
3499 /// custom mappers.
3500 /// \param BodyGenCB Optional Callback to generate the region code.
3501 /// \param DeviceAddrCB Optional callback to generate code related to
3502 /// use_device_ptr and use_device_addr.
3504 const LocationDescription &Loc, InsertPointTy AllocaIP,
3505 InsertPointTy CodeGenIP, Value *DeviceID, Value *IfCond,
3506 TargetDataInfo &Info, GenMapInfoCallbackTy GenMapInfoCB,
3507 CustomMapperCallbackTy CustomMapperCB,
3508 omp::RuntimeFunction *MapperFunc = nullptr,
3510 BodyGenTy BodyGenType)>
3511 BodyGenCB = nullptr,
3512 function_ref<void(unsigned int, Value *)> DeviceAddrCB = nullptr,
3513 Value *SrcLocInfo = nullptr);
3514
3516 InsertPointTy AllocaIP, InsertPointTy CodeGenIP)>;
3517
3519 Argument &Arg, Value *Input, Value *&RetVal, InsertPointTy AllocaIP,
3520 InsertPointTy CodeGenIP)>;
3521
3522 /// Generator for '#omp target'
3523 ///
3524 /// \param Loc where the target data construct was encountered.
3525 /// \param IsOffloadEntry whether it is an offload entry.
3526 /// \param CodeGenIP The insertion point where the call to the outlined
3527 /// function should be emitted.
3528 /// \param Info Stores all information realted to the Target directive.
3529 /// \param EntryInfo The entry information about the function.
3530 /// \param DefaultAttrs Structure containing the default attributes, including
3531 /// numbers of threads and teams to launch the kernel with.
3532 /// \param RuntimeAttrs Structure containing the runtime numbers of threads
3533 /// and teams to launch the kernel with.
3534 /// \param IfCond value of the `if` clause.
3535 /// \param Inputs The input values to the region that will be passed.
3536 /// as arguments to the outlined function.
3537 /// \param BodyGenCB Callback that will generate the region code.
3538 /// \param ArgAccessorFuncCB Callback that will generate accessors
3539 /// instructions for passed in target arguments where neccessary
3540 /// \param CustomMapperCB Callback to generate code related to
3541 /// custom mappers.
3542 /// \param Dependencies A vector of DependData objects that carry
3543 /// dependency information as passed in the depend clause
3544 /// \param HasNowait Whether the target construct has a `nowait` clause or
3545 /// not.
3546 /// \param DynCGroupMem The size of the dynamic groupprivate memory for each
3547 /// cgroup.
3548 /// \param DynCGroupMem The fallback mechanism to execute if the requested
3549 /// cgroup memory cannot be provided.
3551 const LocationDescription &Loc, bool IsOffloadEntry,
3554 TargetRegionEntryInfo &EntryInfo,
3555 const TargetKernelDefaultAttrs &DefaultAttrs,
3556 const TargetKernelRuntimeAttrs &RuntimeAttrs, Value *IfCond,
3557 SmallVectorImpl<Value *> &Inputs, GenMapInfoCallbackTy GenMapInfoCB,
3558 TargetBodyGenCallbackTy BodyGenCB,
3559 TargetGenArgAccessorsCallbackTy ArgAccessorFuncCB,
3560 CustomMapperCallbackTy CustomMapperCB,
3561 const DependenciesInfo &Dependencies = {}, bool HasNowait = false,
3562 Value *DynCGroupMem = nullptr,
3563 omp::OMPDynGroupprivateFallbackType DynCGroupMemFallback =
3565
3566 /// Returns __kmpc_for_static_init_* runtime function for the specified
3567 /// size \a IVSize and sign \a IVSigned. Will create a distribute call
3568 /// __kmpc_distribute_static_init* if \a IsGPUDistribute is set.
3570 bool IVSigned,
3571 bool IsGPUDistribute);
3572
3573 /// Returns __kmpc_dispatch_init_* runtime function for the specified
3574 /// size \a IVSize and sign \a IVSigned.
3576 bool IVSigned);
3577
3578 /// Returns __kmpc_dispatch_next_* runtime function for the specified
3579 /// size \a IVSize and sign \a IVSigned.
3581 bool IVSigned);
3582
3583 /// Returns __kmpc_dispatch_fini_* runtime function for the specified
3584 /// size \a IVSize and sign \a IVSigned.
3586 bool IVSigned);
3587
3588 /// Returns __kmpc_dispatch_deinit runtime function.
3590
3591 /// Declarations for LLVM-IR types (simple, array, function and structure) are
3592 /// generated below. Their names are defined and used in OpenMPKinds.def. Here
3593 /// we provide the declarations, the initializeTypes function will provide the
3594 /// values.
3595 ///
3596 ///{
3597#define OMP_TYPE(VarName, InitValue) Type *VarName = nullptr;
3598#define OMP_ARRAY_TYPE(VarName, ElemTy, ArraySize) \
3599 ArrayType *VarName##Ty = nullptr; \
3600 PointerType *VarName##PtrTy = nullptr;
3601#define OMP_FUNCTION_TYPE(VarName, IsVarArg, ReturnType, ...) \
3602 FunctionType *VarName = nullptr; \
3603 PointerType *VarName##Ptr = nullptr;
3604#define OMP_STRUCT_TYPE(VarName, StrName, ...) \
3605 StructType *VarName = nullptr; \
3606 PointerType *VarName##Ptr = nullptr;
3607#include "llvm/Frontend/OpenMP/OMPKinds.def"
3608
3609 ///}
3610
3611private:
3612 /// Create all simple and struct types exposed by the runtime and remember
3613 /// the llvm::PointerTypes of them for easy access later.
3614 void initializeTypes(Module &M);
3615
3616 /// Common interface for generating entry calls for OMP Directives.
3617 /// if the directive has a region/body, It will set the insertion
3618 /// point to the body
3619 ///
3620 /// \param OMPD Directive to generate entry blocks for
3621 /// \param EntryCall Call to the entry OMP Runtime Function
3622 /// \param ExitBB block where the region ends.
3623 /// \param Conditional indicate if the entry call result will be used
3624 /// to evaluate a conditional of whether a thread will execute
3625 /// body code or not.
3626 ///
3627 /// \return The insertion position in exit block
3628 InsertPointTy emitCommonDirectiveEntry(omp::Directive OMPD, Value *EntryCall,
3629 BasicBlock *ExitBB,
3630 bool Conditional = false);
3631
3632 /// Common interface to finalize the region
3633 ///
3634 /// \param OMPD Directive to generate exiting code for
3635 /// \param FinIP Insertion point for emitting Finalization code and exit call.
3636 /// This block must not contain any non-finalization code.
3637 /// \param ExitCall Call to the ending OMP Runtime Function
3638 /// \param HasFinalize indicate if the directive will require finalization
3639 /// and has a finalization callback in the stack that
3640 /// should be called.
3641 ///
3642 /// \return The insertion position in exit block
3643 InsertPointOrErrorTy emitCommonDirectiveExit(omp::Directive OMPD,
3644 InsertPointTy FinIP,
3645 Instruction *ExitCall,
3646 bool HasFinalize = true);
3647
3648 /// Common Interface to generate OMP inlined regions
3649 ///
3650 /// \param OMPD Directive to generate inlined region for
3651 /// \param EntryCall Call to the entry OMP Runtime Function
3652 /// \param ExitCall Call to the ending OMP Runtime Function
3653 /// \param BodyGenCB Body code generation callback.
3654 /// \param FiniCB Finalization Callback. Will be called when finalizing region
3655 /// \param Conditional indicate if the entry call result will be used
3656 /// to evaluate a conditional of whether a thread will execute
3657 /// body code or not.
3658 /// \param HasFinalize indicate if the directive will require finalization
3659 /// and has a finalization callback in the stack that
3660 /// should be called.
3661 /// \param IsCancellable if HasFinalize is set to true, indicate if the
3662 /// the directive should be cancellable.
3663 /// \return The insertion point after the region
3665 EmitOMPInlinedRegion(omp::Directive OMPD, Instruction *EntryCall,
3666 Instruction *ExitCall, BodyGenCallbackTy BodyGenCB,
3667 FinalizeCallbackTy FiniCB, bool Conditional = false,
3668 bool HasFinalize = true, bool IsCancellable = false);
3669
3670 /// Get the platform-specific name separator.
3671 /// \param Parts different parts of the final name that needs separation
3672 /// \param FirstSeparator First separator used between the initial two
3673 /// parts of the name.
3674 /// \param Separator separator used between all of the rest consecutive
3675 /// parts of the name
3676 static std::string getNameWithSeparators(ArrayRef<StringRef> Parts,
3677 StringRef FirstSeparator,
3678 StringRef Separator);
3679
3680 /// Returns corresponding lock object for the specified critical region
3681 /// name. If the lock object does not exist it is created, otherwise the
3682 /// reference to the existing copy is returned.
3683 /// \param CriticalName Name of the critical region.
3684 ///
3685 Value *getOMPCriticalRegionLock(StringRef CriticalName);
3686
3687 /// Callback type for Atomic Expression update
3688 /// ex:
3689 /// \code{.cpp}
3690 /// unsigned x = 0;
3691 /// #pragma omp atomic update
3692 /// x = Expr(x_old); //Expr() is any legal operation
3693 /// \endcode
3694 ///
3695 /// \param XOld the value of the atomic memory address to use for update
3696 /// \param IRB reference to the IRBuilder to use
3697 ///
3698 /// \returns Value to update X to.
3699 using AtomicUpdateCallbackTy =
3700 const function_ref<Expected<Value *>(Value *XOld, IRBuilder<> &IRB)>;
3701
3702private:
3703 enum AtomicKind { Read, Write, Update, Capture, Compare };
3704
3705 /// Determine whether to emit flush or not
3706 ///
3707 /// \param Loc The insert and source location description.
3708 /// \param AO The required atomic ordering
3709 /// \param AK The OpenMP atomic operation kind used.
3710 ///
3711 /// \returns wether a flush was emitted or not
3712 bool checkAndEmitFlushAfterAtomic(const LocationDescription &Loc,
3713 AtomicOrdering AO, AtomicKind AK);
3714
3715 /// Emit atomic update for constructs: X = X BinOp Expr ,or X = Expr BinOp X
3716 /// For complex Operations: X = UpdateOp(X) => CmpExch X, old_X, UpdateOp(X)
3717 /// Only Scalar data types.
3718 ///
3719 /// \param AllocaIP The insertion point to be used for alloca
3720 /// instructions.
3721 /// \param X The target atomic pointer to be updated
3722 /// \param XElemTy The element type of the atomic pointer.
3723 /// \param Expr The value to update X with.
3724 /// \param AO Atomic ordering of the generated atomic
3725 /// instructions.
3726 /// \param RMWOp The binary operation used for update. If
3727 /// operation is not supported by atomicRMW,
3728 /// or belong to {FADD, FSUB, BAD_BINOP}.
3729 /// Then a `cmpExch` based atomic will be generated.
3730 /// \param UpdateOp Code generator for complex expressions that cannot be
3731 /// expressed through atomicrmw instruction.
3732 /// \param VolatileX true if \a X volatile?
3733 /// \param IsXBinopExpr true if \a X is Left H.S. in Right H.S. part of the
3734 /// update expression, false otherwise.
3735 /// (e.g. true for X = X BinOp Expr)
3736 ///
3737 /// \returns A pair of the old value of X before the update, and the value
3738 /// used for the update.
3739 Expected<std::pair<Value *, Value *>>
3740 emitAtomicUpdate(InsertPointTy AllocaIP, Value *X, Type *XElemTy, Value *Expr,
3742 AtomicUpdateCallbackTy &UpdateOp, bool VolatileX,
3743 bool IsXBinopExpr, bool IsIgnoreDenormalMode,
3744 bool IsFineGrainedMemory, bool IsRemoteMemory);
3745
3746 /// Emit the binary op. described by \p RMWOp, using \p Src1 and \p Src2 .
3747 ///
3748 /// \Return The instruction
3749 Value *emitRMWOpAsInstruction(Value *Src1, Value *Src2,
3750 AtomicRMWInst::BinOp RMWOp);
3751
3752 bool IsFinalized;
3753
3754public:
3755 /// a struct to pack relevant information while generating atomic Ops
3757 Value *Var = nullptr;
3758 Type *ElemTy = nullptr;
3759 bool IsSigned = false;
3760 bool IsVolatile = false;
3761 };
3762
3763 /// Emit atomic Read for : V = X --- Only Scalar data types.
3764 ///
3765 /// \param Loc The insert and source location description.
3766 /// \param X The target pointer to be atomically read
3767 /// \param V Memory address where to store atomically read
3768 /// value
3769 /// \param AO Atomic ordering of the generated atomic
3770 /// instructions.
3771 /// \param AllocaIP Insert point for allocas
3772 //
3773 /// \return Insertion point after generated atomic read IR.
3776 AtomicOrdering AO,
3777 InsertPointTy AllocaIP);
3778
3779 /// Emit atomic write for : X = Expr --- Only Scalar data types.
3780 ///
3781 /// \param Loc The insert and source location description.
3782 /// \param X The target pointer to be atomically written to
3783 /// \param Expr The value to store.
3784 /// \param AO Atomic ordering of the generated atomic
3785 /// instructions.
3786 /// \param AllocaIP Insert point for allocas
3787 ///
3788 /// \return Insertion point after generated atomic Write IR.
3790 AtomicOpValue &X, Value *Expr,
3791 AtomicOrdering AO,
3792 InsertPointTy AllocaIP);
3793
3794 /// Emit atomic update for constructs: X = X BinOp Expr ,or X = Expr BinOp X
3795 /// For complex Operations: X = UpdateOp(X) => CmpExch X, old_X, UpdateOp(X)
3796 /// Only Scalar data types.
3797 ///
3798 /// \param Loc The insert and source location description.
3799 /// \param AllocaIP The insertion point to be used for alloca instructions.
3800 /// \param X The target atomic pointer to be updated
3801 /// \param Expr The value to update X with.
3802 /// \param AO Atomic ordering of the generated atomic instructions.
3803 /// \param RMWOp The binary operation used for update. If operation
3804 /// is not supported by atomicRMW, or belong to
3805 /// {FADD, FSUB, BAD_BINOP}. Then a `cmpExch` based
3806 /// atomic will be generated.
3807 /// \param UpdateOp Code generator for complex expressions that cannot be
3808 /// expressed through atomicrmw instruction.
3809 /// \param IsXBinopExpr true if \a X is Left H.S. in Right H.S. part of the
3810 /// update expression, false otherwise.
3811 /// (e.g. true for X = X BinOp Expr)
3812 ///
3813 /// \return Insertion point after generated atomic update IR.
3816 Value *Expr, AtomicOrdering AO, AtomicRMWInst::BinOp RMWOp,
3817 AtomicUpdateCallbackTy &UpdateOp, bool IsXBinopExpr,
3818 bool IsIgnoreDenormalMode = false, bool IsFineGrainedMemory = false,
3819 bool IsRemoteMemory = false);
3820
3821 /// Emit atomic update for constructs: --- Only Scalar data types
3822 /// V = X; X = X BinOp Expr ,
3823 /// X = X BinOp Expr; V = X,
3824 /// V = X; X = Expr BinOp X,
3825 /// X = Expr BinOp X; V = X,
3826 /// V = X; X = UpdateOp(X),
3827 /// X = UpdateOp(X); V = X,
3828 ///
3829 /// \param Loc The insert and source location description.
3830 /// \param AllocaIP The insertion point to be used for alloca instructions.
3831 /// \param X The target atomic pointer to be updated
3832 /// \param V Memory address where to store captured value
3833 /// \param Expr The value to update X with.
3834 /// \param AO Atomic ordering of the generated atomic instructions
3835 /// \param RMWOp The binary operation used for update. If
3836 /// operation is not supported by atomicRMW, or belong to
3837 /// {FADD, FSUB, BAD_BINOP}. Then a cmpExch based
3838 /// atomic will be generated.
3839 /// \param UpdateOp Code generator for complex expressions that cannot be
3840 /// expressed through atomicrmw instruction.
3841 /// \param UpdateExpr true if X is an in place update of the form
3842 /// X = X BinOp Expr or X = Expr BinOp X
3843 /// \param IsXBinopExpr true if X is Left H.S. in Right H.S. part of the
3844 /// update expression, false otherwise.
3845 /// (e.g. true for X = X BinOp Expr)
3846 /// \param IsPostfixUpdate true if original value of 'x' must be stored in
3847 /// 'v', not an updated one.
3848 ///
3849 /// \return Insertion point after generated atomic capture IR.
3852 AtomicOpValue &V, Value *Expr, AtomicOrdering AO,
3853 AtomicRMWInst::BinOp RMWOp, AtomicUpdateCallbackTy &UpdateOp,
3854 bool UpdateExpr, bool IsPostfixUpdate, bool IsXBinopExpr,
3855 bool IsIgnoreDenormalMode = false, bool IsFineGrainedMemory = false,
3856 bool IsRemoteMemory = false);
3857
3858 /// Emit atomic compare for constructs: --- Only scalar data types
3859 /// cond-expr-stmt:
3860 /// x = x ordop expr ? expr : x;
3861 /// x = expr ordop x ? expr : x;
3862 /// x = x == e ? d : x;
3863 /// x = e == x ? d : x; (this one is not in the spec)
3864 /// cond-update-stmt:
3865 /// if (x ordop expr) { x = expr; }
3866 /// if (expr ordop x) { x = expr; }
3867 /// if (x == e) { x = d; }
3868 /// if (e == x) { x = d; } (this one is not in the spec)
3869 /// conditional-update-capture-atomic:
3870 /// v = x; cond-update-stmt; (IsPostfixUpdate=true, IsFailOnly=false)
3871 /// cond-update-stmt; v = x; (IsPostfixUpdate=false, IsFailOnly=false)
3872 /// if (x == e) { x = d; } else { v = x; } (IsPostfixUpdate=false,
3873 /// IsFailOnly=true)
3874 /// r = x == e; if (r) { x = d; } (IsPostfixUpdate=false, IsFailOnly=false)
3875 /// r = x == e; if (r) { x = d; } else { v = x; } (IsPostfixUpdate=false,
3876 /// IsFailOnly=true)
3877 ///
3878 /// \param Loc The insert and source location description.
3879 /// \param X The target atomic pointer to be updated.
3880 /// \param V Memory address where to store captured value (for
3881 /// compare capture only).
3882 /// \param R Memory address where to store comparison result
3883 /// (for compare capture with '==' only).
3884 /// \param E The expected value ('e') for forms that use an
3885 /// equality comparison or an expression ('expr') for
3886 /// forms that use 'ordop' (logically an atomic maximum or
3887 /// minimum).
3888 /// \param D The desired value for forms that use an equality
3889 /// comparison. If forms that use 'ordop', it should be
3890 /// \p nullptr.
3891 /// \param AO Atomic ordering of the generated atomic instructions.
3892 /// \param Op Atomic compare operation. It can only be ==, <, or >.
3893 /// \param IsXBinopExpr True if the conditional statement is in the form where
3894 /// x is on LHS. It only matters for < or >.
3895 /// \param IsPostfixUpdate True if original value of 'x' must be stored in
3896 /// 'v', not an updated one (for compare capture
3897 /// only).
3898 /// \param IsFailOnly True if the original value of 'x' is stored to 'v'
3899 /// only when the comparison fails. This is only valid for
3900 /// the case the comparison is '=='.
3901 ///
3902 /// \return Insertion point after generated atomic capture IR.
3907 bool IsXBinopExpr, bool IsPostfixUpdate, bool IsFailOnly);
3911 omp::OMPAtomicCompareOp Op, bool IsXBinopExpr, bool IsPostfixUpdate,
3912 bool IsFailOnly, AtomicOrdering Failure);
3913
3914 /// Create the control flow structure of a canonical OpenMP loop.
3915 ///
3916 /// The emitted loop will be disconnected, i.e. no edge to the loop's
3917 /// preheader and no terminator in the AfterBB. The OpenMPIRBuilder's
3918 /// IRBuilder location is not preserved.
3919 ///
3920 /// \param DL DebugLoc used for the instructions in the skeleton.
3921 /// \param TripCount Value to be used for the trip count.
3922 /// \param F Function in which to insert the BasicBlocks.
3923 /// \param PreInsertBefore Where to insert BBs that execute before the body,
3924 /// typically the body itself.
3925 /// \param PostInsertBefore Where to insert BBs that execute after the body.
3926 /// \param Name Base name used to derive BB
3927 /// and instruction names.
3928 ///
3929 /// \returns The CanonicalLoopInfo that represents the emitted loop.
3931 Function *F,
3932 BasicBlock *PreInsertBefore,
3933 BasicBlock *PostInsertBefore,
3934 const Twine &Name = {});
3935 /// OMP Offload Info Metadata name string
3936 const std::string ompOffloadInfoName = "omp_offload.info";
3937
3938 /// Loads all the offload entries information from the host IR
3939 /// metadata. This function is only meant to be used with device code
3940 /// generation.
3941 ///
3942 /// \param M Module to load Metadata info from. Module passed maybe
3943 /// loaded from bitcode file, i.e, different from OpenMPIRBuilder::M module.
3945
3946 /// Loads all the offload entries information from the host IR
3947 /// metadata read from the file passed in as the HostFilePath argument. This
3948 /// function is only meant to be used with device code generation.
3949 ///
3950 /// \param HostFilePath The path to the host IR file,
3951 /// used to load in offload metadata for the device, allowing host and device
3952 /// to maintain the same metadata mapping.
3954 StringRef HostFilePath);
3955
3956 /// Gets (if variable with the given name already exist) or creates
3957 /// internal global variable with the specified Name. The created variable has
3958 /// linkage CommonLinkage by default and is initialized by null value.
3959 /// \param Ty Type of the global variable. If it is exist already the type
3960 /// must be the same.
3961 /// \param Name Name of the variable.
3964 std::optional<unsigned> AddressSpace = {});
3965
3967 InsertPointTy BodyIP, llvm::Value *LinearIV)>;
3968
3969 /// Create a canonical iterator loop at the current insertion point.
3970 ///
3971 /// This helper splits the current block and builds a canonical loop
3972 /// using createLoopSkeleton(). The resulting control flow looks like:
3973 ///
3974 /// CurBB -> Preheader -> Header -> Body -> Latch -> After -> ContBB
3975 ///
3976 /// The body of the loop is produced by calling \p BodyGen with the insertion
3977 /// point for the loop body and the induction variable.
3978 /// Unlike createCanonicalLoop(), this function is intended for \p BodyGen
3979 /// that may perform region lowering (e.g., translating MLIR regions) and are
3980 /// not guaranteed to preserve the canonical skeleton's body terminator. In
3981 /// particular:
3982 ///
3983 /// - The skeleton’s unconditional branch from the loop body is removed
3984 /// before invoking \p BodyGen.
3985 /// - \p BodyGen may freely emit instructions and temporarily introduce
3986 /// control flow.
3987 /// - If the loop body does not end with a terminator after \p BodyGen
3988 /// returns, a branch to the latch is inserted to restore canonical form.
3989 ///
3990 /// \param Loc The location where the iterator modifier was encountered.
3991 /// \param TripCount Number of loop iterations.
3992 /// \param BodyGen Callback to generate the loop body.
3993 /// \param Name Base name used for creating the loop
3994 /// \returns The insertion position *after* the iterator loop
3997 IteratorBodyGenTy BodyGen, llvm::StringRef Name = "iterator");
3998
3999 /// Kind of parameter in a function with 'declare simd' directive.
4008
4009 /// Attribute set of the `declare simd` parameter.
4016
4022
4023 /// Emit x86 vector-function ABI attributes for a `declare simd` function.
4024 ///
4025 /// Generates and attaches `_ZGV*` vector function ABI attributes to \p Fn
4026 /// following the x86 vector ABI used by OpenMP `declare simd`. For each
4027 /// supported ISA (SSE, AVX, AVX2, AVX512) and masking variant, this
4028 /// constructs the appropriate mangled vector-function name and adds it as a
4029 /// function attribute.
4030 ///
4031 /// \param Fn The scalar function to which vector-function attributes
4032 /// are attached.
4033 /// \param NumElements Number of elements used to derive the vector length
4034 /// when
4035 /// \p VLENVal is not specified.
4036 /// \param VLENVal User provided vector length.
4037 /// \param ParamAttrs Array of attribute set of the `declare simd` parameter.
4038 /// \param Branch `undefined`, `inbranch` or `notinbranch` clause.
4040 llvm::Function *Fn, unsigned NumElements, const llvm::APSInt &VLENVal,
4042
4043 /// Emit AArch64 vector-function ABI attributes for a `declare simd` function.
4044 ///
4045 /// Generates and attaches `_ZGV*` vector function ABI attributes to \p Fn
4046 /// following the AArch64 vector-function ABI. The emitted names depend on the
4047 /// selected ISA, user-specified vector length, parameter attribute mangling,
4048 /// and the declare simd branch clause.
4049 ///
4050 /// \param Fn The scalar function to which vector-function
4051 /// attributes are attached.
4052 /// \param VLENVal User provided vector length.
4053 /// \param ParamAttrs Array of attribute set of the `declare simd`
4054 /// parameter.
4055 /// \param Branch `undefined`, `inbranch` or `notinbranch`
4056 /// clause.
4057 /// \param ISA `'n'` for Advanced SIMD or `'s'` for SVE.
4058 /// \param NarrowestDataSize Narrowest data size in bits used to infer the
4059 /// default vector length when \p VLENVal is
4060 /// absent.
4061 /// \param OutputBecomesInput Whether result values are represented as input
4062 /// parameters in the emitted vector-function ABI
4063 /// name.
4065 llvm::Function *Fn, unsigned VLENVal,
4067 char ISA, unsigned NarrowestDataSize, bool OutputBecomesInput);
4068};
4069
4070/// Class to represented the control flow structure of an OpenMP canonical loop.
4071///
4072/// The control-flow structure is standardized for easy consumption by
4073/// directives associated with loops. For instance, the worksharing-loop
4074/// construct may change this control flow such that each loop iteration is
4075/// executed on only one thread. The constraints of a canonical loop in brief
4076/// are:
4077///
4078/// * The number of loop iterations must have been computed before entering the
4079/// loop.
4080///
4081/// * Has an (unsigned) logical induction variable that starts at zero and
4082/// increments by one.
4083///
4084/// * The loop's CFG itself has no side-effects. The OpenMP specification
4085/// itself allows side-effects, but the order in which they happen, including
4086/// how often or whether at all, is unspecified. We expect that the frontend
4087/// will emit those side-effect instructions somewhere (e.g. before the loop)
4088/// such that the CanonicalLoopInfo itself can be side-effect free.
4089///
4090/// Keep in mind that CanonicalLoopInfo is meant to only describe a repeated
4091/// execution of a loop body that satifies these constraints. It does NOT
4092/// represent arbitrary SESE regions that happen to contain a loop. Do not use
4093/// CanonicalLoopInfo for such purposes.
4094///
4095/// The control flow can be described as follows:
4096///
4097/// Preheader
4098/// |
4099/// /-> Header
4100/// | |
4101/// | Cond---\
4102/// | | |
4103/// | Body |
4104/// | | | |
4105/// | <...> |
4106/// | | | |
4107/// \--Latch |
4108/// |
4109/// Exit
4110/// |
4111/// After
4112///
4113/// The loop is thought to start at PreheaderIP (at the Preheader's terminator,
4114/// including) and end at AfterIP (at the After's first instruction, excluding).
4115/// That is, instructions in the Preheader and After blocks (except the
4116/// Preheader's terminator) are out of CanonicalLoopInfo's control and may have
4117/// side-effects. Typically, the Preheader is used to compute the loop's trip
4118/// count. The instructions from BodyIP (at the Body block's first instruction,
4119/// excluding) until the Latch are also considered outside CanonicalLoopInfo's
4120/// control and thus can have side-effects. The body block is the single entry
4121/// point into the loop body, which may contain arbitrary control flow as long
4122/// as all control paths eventually branch to the Latch block.
4123///
4124/// TODO: Consider adding another standardized BasicBlock between Body CFG and
4125/// Latch to guarantee that there is only a single edge to the latch. It would
4126/// make loop transformations easier to not needing to consider multiple
4127/// predecessors of the latch (See redirectAllPredecessorsTo) and would give us
4128/// an equivalant to PreheaderIP, AfterIP and BodyIP for inserting code that
4129/// executes after each body iteration.
4130///
4131/// There must be no loop-carried dependencies through llvm::Values. This is
4132/// equivalant to that the Latch has no PHINode and the Header's only PHINode is
4133/// for the induction variable.
4134///
4135/// All code in Header, Cond, Latch and Exit (plus the terminator of the
4136/// Preheader) are CanonicalLoopInfo's responsibility and their build-up checked
4137/// by assertOK(). They are expected to not be modified unless explicitly
4138/// modifying the CanonicalLoopInfo through a methods that applies a OpenMP
4139/// loop-associated construct such as applyWorkshareLoop, tileLoops, unrollLoop,
4140/// etc. These methods usually invalidate the CanonicalLoopInfo and re-use its
4141/// basic blocks. After invalidation, the CanonicalLoopInfo must not be used
4142/// anymore as its underlying control flow may not exist anymore.
4143/// Loop-transformation methods such as tileLoops, collapseLoops and unrollLoop
4144/// may also return a new CanonicalLoopInfo that can be passed to other
4145/// loop-associated construct implementing methods. These loop-transforming
4146/// methods may either create a new CanonicalLoopInfo usually using
4147/// createLoopSkeleton and invalidate the input CanonicalLoopInfo, or reuse and
4148/// modify one of the input CanonicalLoopInfo and return it as representing the
4149/// modified loop. What is done is an implementation detail of
4150/// transformation-implementing method and callers should always assume that the
4151/// CanonicalLoopInfo passed to it is invalidated and a new object is returned.
4152/// Returned CanonicalLoopInfo have the same structure and guarantees as the one
4153/// created by createCanonicalLoop, such that transforming methods do not have
4154/// to special case where the CanonicalLoopInfo originated from.
4155///
4156/// Generally, methods consuming CanonicalLoopInfo do not need an
4157/// OpenMPIRBuilder::InsertPointTy as argument, but use the locations of the
4158/// CanonicalLoopInfo to insert new or modify existing instructions. Unless
4159/// documented otherwise, methods consuming CanonicalLoopInfo do not invalidate
4160/// any InsertPoint that is outside CanonicalLoopInfo's control. Specifically,
4161/// any InsertPoint in the Preheader, After or Block can still be used after
4162/// calling such a method.
4163///
4164/// TODO: Provide mechanisms for exception handling and cancellation points.
4165///
4166/// Defined outside OpenMPIRBuilder because nested classes cannot be
4167/// forward-declared, e.g. to avoid having to include the entire OMPIRBuilder.h.
4169 friend class OpenMPIRBuilder;
4170
4171private:
4172 BasicBlock *Header = nullptr;
4173 BasicBlock *Cond = nullptr;
4174 BasicBlock *Latch = nullptr;
4175 BasicBlock *Exit = nullptr;
4176
4177 // Hold the MLIR value for the `lastiter` of the canonical loop.
4178 Value *LastIter = nullptr;
4179
4180 /// Add the control blocks of this loop to \p BBs.
4181 ///
4182 /// This does not include any block from the body, including the one returned
4183 /// by getBody().
4184 ///
4185 /// FIXME: This currently includes the Preheader and After blocks even though
4186 /// their content is (mostly) not under CanonicalLoopInfo's control.
4187 /// Re-evaluated whether this makes sense.
4188 void collectControlBlocks(SmallVectorImpl<BasicBlock *> &BBs);
4189
4190 /// Sets the number of loop iterations to the given value. This value must be
4191 /// valid in the condition block (i.e., defined in the preheader) and is
4192 /// interpreted as an unsigned integer.
4193 void setTripCount(Value *TripCount);
4194
4195 /// Replace all uses of the canonical induction variable in the loop body with
4196 /// a new one.
4197 ///
4198 /// The intended use case is to update the induction variable for an updated
4199 /// iteration space such that it can stay normalized in the 0...tripcount-1
4200 /// range.
4201 ///
4202 /// The \p Updater is called with the (presumable updated) current normalized
4203 /// induction variable and is expected to return the value that uses of the
4204 /// pre-updated induction values should use instead, typically dependent on
4205 /// the new induction variable. This is a lambda (instead of e.g. just passing
4206 /// the new value) to be able to distinguish the uses of the pre-updated
4207 /// induction variable and uses of the induction varible to compute the
4208 /// updated induction variable value.
4209 void mapIndVar(llvm::function_ref<Value *(Instruction *)> Updater);
4210
4211public:
4212 /// Sets the last iteration variable for this loop.
4213 void setLastIter(Value *IterVar) { LastIter = std::move(IterVar); }
4214
4215 /// Returns the last iteration variable for this loop.
4216 /// Certain use-cases (like translation of linear clause) may access
4217 /// this variable even after a loop transformation. Hence, do not guard
4218 /// this getter function by `isValid`. It is the responsibility of the
4219 /// callee to ensure this functionality is not invoked by a non-outlined
4220 /// CanonicalLoopInfo object (in which case, `setLastIter` will never be
4221 /// invoked and `LastIter` will be by default `nullptr`).
4222 Value *getLastIter() { return LastIter; }
4223
4224 /// Returns whether this object currently represents the IR of a loop. If
4225 /// returning false, it may have been consumed by a loop transformation or not
4226 /// been initialized. Do not use in this case;
4227 bool isValid() const { return Header; }
4228
4229 /// The preheader ensures that there is only a single edge entering the loop.
4230 /// Code that must be execute before any loop iteration can be emitted here,
4231 /// such as computing the loop trip count and begin lifetime markers. Code in
4232 /// the preheader is not considered part of the canonical loop.
4234
4235 /// The header is the entry for each iteration. In the canonical control flow,
4236 /// it only contains the PHINode for the induction variable.
4238 assert(isValid() && "Requires a valid canonical loop");
4239 return Header;
4240 }
4241
4242 /// The condition block computes whether there is another loop iteration. If
4243 /// yes, branches to the body; otherwise to the exit block.
4245 assert(isValid() && "Requires a valid canonical loop");
4246 return Cond;
4247 }
4248
4249 /// The body block is the single entry for a loop iteration and not controlled
4250 /// by CanonicalLoopInfo. It can contain arbitrary control flow but must
4251 /// eventually branch to the \p Latch block.
4253 assert(isValid() && "Requires a valid canonical loop");
4254 return cast<CondBrInst>(Cond->getTerminator())->getSuccessor(0);
4255 }
4256
4257 /// Reaching the latch indicates the end of the loop body code. In the
4258 /// canonical control flow, it only contains the increment of the induction
4259 /// variable.
4261 assert(isValid() && "Requires a valid canonical loop");
4262 return Latch;
4263 }
4264
4265 /// Reaching the exit indicates no more iterations are being executed.
4267 assert(isValid() && "Requires a valid canonical loop");
4268 return Exit;
4269 }
4270
4271 /// The after block is intended for clean-up code such as lifetime end
4272 /// markers. It is separate from the exit block to ensure, analogous to the
4273 /// preheader, it having just a single entry edge and being free from PHI
4274 /// nodes should there be multiple loop exits (such as from break
4275 /// statements/cancellations).
4277 assert(isValid() && "Requires a valid canonical loop");
4278 return Exit->getSingleSuccessor();
4279 }
4280
4281 /// Returns the llvm::Value containing the number of loop iterations. It must
4282 /// be valid in the preheader and always interpreted as an unsigned integer of
4283 /// any bit-width.
4285 assert(isValid() && "Requires a valid canonical loop");
4286 Instruction *CmpI = &Cond->front();
4287 assert(isa<CmpInst>(CmpI) && "First inst must compare IV with TripCount");
4288 return CmpI->getOperand(1);
4289 }
4290
4291 /// Returns the instruction representing the current logical induction
4292 /// variable. Always unsigned, always starting at 0 with an increment of one.
4294 assert(isValid() && "Requires a valid canonical loop");
4295 Instruction *IndVarPHI = &Header->front();
4296 assert(isa<PHINode>(IndVarPHI) && "First inst must be the IV PHI");
4297 return IndVarPHI;
4298 }
4299
4300 /// Return the type of the induction variable (and the trip count).
4302 assert(isValid() && "Requires a valid canonical loop");
4303 return getIndVar()->getType();
4304 }
4305
4306 /// Return the insertion point for user code before the loop.
4308 assert(isValid() && "Requires a valid canonical loop");
4309 BasicBlock *Preheader = getPreheader();
4310 return {Preheader, std::prev(Preheader->end())};
4311 };
4312
4313 /// Return the insertion point for user code in the body.
4315 assert(isValid() && "Requires a valid canonical loop");
4316 BasicBlock *Body = getBody();
4317 return {Body, Body->begin()};
4318 };
4319
4320 /// Return the insertion point for user code after the loop.
4322 assert(isValid() && "Requires a valid canonical loop");
4323 BasicBlock *After = getAfter();
4324 return {After, After->begin()};
4325 };
4326
4328 assert(isValid() && "Requires a valid canonical loop");
4329 return Header->getParent();
4330 }
4331
4332 /// Consistency self-check.
4333 LLVM_ABI void assertOK() const;
4334
4335 /// Invalidate this loop. That is, the underlying IR does not fulfill the
4336 /// requirements of an OpenMP canonical loop anymore.
4337 LLVM_ABI void invalidate();
4338};
4339
4340/// ScanInfo holds the information to assist in lowering of Scan reduction.
4341/// Before lowering, the body of the for loop specifying scan reduction is
4342/// expected to have the following structure
4343///
4344/// Loop Body Entry
4345/// |
4346/// Code before the scan directive
4347/// |
4348/// Scan Directive
4349/// |
4350/// Code after the scan directive
4351/// |
4352/// Loop Body Exit
4353/// When `createCanonicalScanLoops` is executed, the bodyGen callback of it
4354/// transforms the body to:
4355///
4356/// Loop Body Entry
4357/// |
4358/// OMPScanDispatch
4359///
4360/// OMPBeforeScanBlock
4361/// |
4362/// OMPScanLoopExit
4363/// |
4364/// Loop Body Exit
4365///
4366/// The insert point is updated to the first insert point of OMPBeforeScanBlock.
4367/// It dominates the control flow of code generated until
4368/// scan directive is encountered and OMPAfterScanBlock dominates the
4369/// control flow of code generated after scan is encountered. The successor
4370/// of OMPScanDispatch can be OMPBeforeScanBlock or OMPAfterScanBlock based
4371/// on 1.whether it is in Input phase or Scan Phase , 2. whether it is an
4372/// exclusive or inclusive scan. This jump is added when `createScan` is
4373/// executed. If input loop is being generated, if it is inclusive scan,
4374/// `OMPAfterScanBlock` succeeds `OMPScanDispatch` , if exclusive,
4375/// `OMPBeforeScanBlock` succeeds `OMPDispatch` and vice versa for scan loop. At
4376/// the end of the input loop, temporary buffer is populated and at the
4377/// beginning of the scan loop, temporary buffer is read. After scan directive
4378/// is encountered, insertion point is updated to `OMPAfterScanBlock` as it is
4379/// expected to dominate the code after the scan directive. Both Before and
4380/// After scan blocks are succeeded by `OMPScanLoopExit`.
4381/// Temporary buffer allocations are done in `ScanLoopInit` block before the
4382/// lowering of for-loop. The results are copied back to reduction variable in
4383/// `ScanLoopFinish` block.
4385public:
4386 /// Dominates the body of the loop before scan directive
4388
4389 /// Dominates the body of the loop before scan directive
4391
4392 /// Controls the flow to before or after scan blocks
4394
4395 /// Exit block of loop body
4397
4398 /// Block before loop body where scan initializations are done
4400
4401 /// Block after loop body where scan finalizations are done
4403
4404 /// If true, it indicates Input phase is lowered; else it indicates
4405 /// ScanPhase is lowered
4406 bool OMPFirstScanLoop = false;
4407
4408 /// Maps the private reduction variable to the pointer of the temporary
4409 /// buffer
4411
4412 /// Keeps track of value of iteration variable for input/scan loop to be
4413 /// used for Scan directive lowering
4414 llvm::Value *IV = nullptr;
4415
4416 /// Stores the span of canonical loop being lowered to be used for temporary
4417 /// buffer allocation or Finalization.
4418 llvm::Value *Span = nullptr;
4419
4423 ScanInfo(ScanInfo &) = delete;
4424 ScanInfo &operator=(const ScanInfo &) = delete;
4425
4426 ~ScanInfo() { delete (ScanBuffPtrs); }
4427};
4428
4429} // end namespace llvm
4430
4431#endif // LLVM_FRONTEND_OPENMP_OMPIRBUILDER_H
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file implements the APSInt class, which is a simple class that represents an arbitrary sized int...
arc branch finalize
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
This file defines the BumpPtrAllocator interface.
#define X(NUM, ENUM, NAME)
Definition ELF.h:851
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define LLVM_ABI
Definition Compiler.h:213
DXIL Finalize Linkage
Hexagon Hardware Loops
Module.h This file contains the declarations for the Module class.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define G(x, y, z)
Definition MD5.cpp:55
Machine Check Debug Module
#define T
This file defines constans and helpers used when dealing with OpenMP.
Provides definitions for Target specific Grid Values.
const SmallVectorImpl< MachineOperand > & Cond
Basic Register Allocator
static cl::opt< RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode > Mode("regalloc-enable-advisor", cl::Hidden, cl::init(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default), cl::desc("Enable regalloc advisor mode"), cl::values(clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default, "default", "Default"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Release, "release", "precompiled"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Development, "development", "for training")))
std::unordered_set< BasicBlock * > BlockSet
This file implements a set that has insertion order iteration characteristics.
Value * RHS
Value * LHS
The Input class is used to parse a yaml document into in-memory structs and vectors.
An arbitrary precision integer that knows its signedness.
Definition APSInt.h:24
an instruction to allocate memory on the stack
This class represents an incoming formal argument to a Function.
Definition Argument.h:32
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
Align AtomicAlign
Definition Atomic.h:23
bool UseLibcall
Definition Atomic.h:25
IRBuilderBase * Builder
Definition Atomic.h:19
uint64_t AtomicSizeInBits
Definition Atomic.h:21
uint64_t ValueSizeInBits
Definition Atomic.h:22
IRBuilderBase::InsertPoint AllocaIP
Definition Atomic.h:26
Align ValueAlign
Definition Atomic.h:24
BinOp
This enumeration lists the possible modifications atomicrmw can make.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator end()
Definition BasicBlock.h:474
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:461
This class represents a function call, abstracting a target machine's calling convention.
Class to represented the control flow structure of an OpenMP canonical loop.
Value * getTripCount() const
Returns the llvm::Value containing the number of loop iterations.
BasicBlock * getHeader() const
The header is the entry for each iteration.
LLVM_ABI void assertOK() const
Consistency self-check.
Type * getIndVarType() const
Return the type of the induction variable (and the trip count).
BasicBlock * getBody() const
The body block is the single entry for a loop iteration and not controlled by CanonicalLoopInfo.
bool isValid() const
Returns whether this object currently represents the IR of a loop.
void setLastIter(Value *IterVar)
Sets the last iteration variable for this loop.
OpenMPIRBuilder::InsertPointTy getAfterIP() const
Return the insertion point for user code after the loop.
Value * getLastIter()
Returns the last iteration variable for this loop.
OpenMPIRBuilder::InsertPointTy getBodyIP() const
Return the insertion point for user code in the body.
BasicBlock * getAfter() const
The after block is intended for clean-up code such as lifetime end markers.
Function * getFunction() const
LLVM_ABI void invalidate()
Invalidate this loop.
BasicBlock * getLatch() const
Reaching the latch indicates the end of the loop body code.
OpenMPIRBuilder::InsertPointTy getPreheaderIP() const
Return the insertion point for user code before the loop.
BasicBlock * getCond() const
The condition block computes whether there is another loop iteration.
BasicBlock * getExit() const
Reaching the exit indicates no more iterations are being executed.
LLVM_ABI BasicBlock * getPreheader() const
The preheader ensures that there is only a single edge entering the loop.
Instruction * getIndVar() const
Returns the instruction representing the current logical induction variable.
This is the shared class of boolean and integer constants.
Definition Constants.h:87
This is an important base class in LLVM.
Definition Constant.h:43
A debug info location.
Definition DebugLoc.h:123
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
Tagged union holding either a T or a Error.
Definition Error.h:485
A handy container for a FunctionType+Callee-pointer pair, which can be passed around as a single enti...
LinkageTypes
An enumeration for the kinds of linkage for global values.
Definition GlobalValue.h:52
InsertPoint - A saved insertion point.
Definition IRBuilder.h:291
Common base class shared among various IRBuilders.
Definition IRBuilder.h:114
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2812
Class to represent integer types.
Analysis pass that exposes the LoopInfo for a function.
Definition LoopInfo.h:569
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
This class implements a map that also provides access to all stored values in a deterministic order.
Definition MapVector.h:36
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
OffloadEntryInfoDeviceGlobalVar(unsigned Order, OMPTargetGlobalVarEntryKind Flags)
OffloadEntryInfoDeviceGlobalVar(unsigned Order, Constant *Addr, int64_t VarSize, OMPTargetGlobalVarEntryKind Flags, GlobalValue::LinkageTypes Linkage, const std::string &VarName)
static bool classof(const OffloadEntryInfo *Info)
OffloadEntryInfoTargetRegion(unsigned Order, Constant *Addr, Constant *ID, OMPTargetRegionEntryKind Flags)
@ OffloadingEntryInfoTargetRegion
Entry is a target region.
@ OffloadingEntryInfoDeviceGlobalVar
Entry is a declare target variable.
OffloadingEntryInfoKinds getKind() const
OffloadEntryInfo(OffloadingEntryInfoKinds Kind)
static bool classof(const OffloadEntryInfo *Info)
OffloadEntryInfo(OffloadingEntryInfoKinds Kind, unsigned Order, uint32_t Flags)
Class that manages information about offload code regions and data.
function_ref< void(StringRef, const OffloadEntryInfoDeviceGlobalVar &)> OffloadDeviceGlobalVarEntryInfoActTy
Applies action Action on all registered entries.
OMPTargetDeviceClauseKind
Kind of device clause for declare target variables and functions NOTE: Currently not used as a part o...
@ OMPTargetDeviceClauseNoHost
The target is marked for non-host devices.
@ OMPTargetDeviceClauseAny
The target is marked for all devices.
@ OMPTargetDeviceClauseNone
The target is marked as having no clause.
@ OMPTargetDeviceClauseHost
The target is marked for host devices.
LLVM_ABI void registerDeviceGlobalVarEntryInfo(StringRef VarName, Constant *Addr, int64_t VarSize, OMPTargetGlobalVarEntryKind Flags, GlobalValue::LinkageTypes Linkage)
Register device global variable entry.
LLVM_ABI void initializeDeviceGlobalVarEntryInfo(StringRef Name, OMPTargetGlobalVarEntryKind Flags, unsigned Order)
Initialize device global variable entry.
LLVM_ABI void actOnDeviceGlobalVarEntriesInfo(const OffloadDeviceGlobalVarEntryInfoActTy &Action)
OMPTargetRegionEntryKind
Kind of the target registry entry.
@ OMPTargetRegionEntryTargetRegion
Mark the entry as target region.
OffloadEntriesInfoManager(OpenMPIRBuilder *builder)
LLVM_ABI void getTargetRegionEntryFnName(SmallVectorImpl< char > &Name, const TargetRegionEntryInfo &EntryInfo)
LLVM_ABI bool hasTargetRegionEntryInfo(TargetRegionEntryInfo EntryInfo, bool IgnoreAddressId=false) const
Return true if a target region entry with the provided information exists.
LLVM_ABI void registerTargetRegionEntryInfo(TargetRegionEntryInfo EntryInfo, Constant *Addr, Constant *ID, OMPTargetRegionEntryKind Flags)
Register target region entry.
LLVM_ABI void actOnTargetRegionEntriesInfo(const OffloadTargetRegionEntryInfoActTy &Action)
unsigned size() const
Return number of entries defined so far.
LLVM_ABI void initializeTargetRegionEntryInfo(const TargetRegionEntryInfo &EntryInfo, unsigned Order)
Initialize target region entry.
OMPTargetGlobalVarEntryKind
Kind of the global variable entry..
@ OMPTargetGlobalVarEntryEnter
Mark the entry as a declare target enter.
@ OMPTargetGlobalVarEntryNone
Mark the entry as having no declare target entry kind.
@ OMPTargetGlobalRegisterRequires
Mark the entry as a register requires global.
@ OMPTargetGlobalVarEntryIndirect
Mark the entry as a declare target indirect global.
@ OMPTargetGlobalVarEntryLink
Mark the entry as a to declare target link.
@ OMPTargetGlobalVarEntryTo
Mark the entry as a to declare target.
@ OMPTargetGlobalVarEntryIndirectVTable
Mark the entry as a declare target indirect vtable.
function_ref< void(const TargetRegionEntryInfo &EntryInfo, const OffloadEntryInfoTargetRegion &)> OffloadTargetRegionEntryInfoActTy
brief Applies action Action on all registered entries.
bool hasDeviceGlobalVarEntryInfo(StringRef VarName) const
Checks if the variable with the given name has been registered already.
LLVM_ABI bool empty() const
Return true if a there are no entries defined.
Captures attributes that affect generating LLVM-IR using the OpenMPIRBuilder and related classes.
std::optional< bool > IsTargetDevice
Flag to define whether to generate code for the role of the OpenMP host (if set to false) or device (...
std::optional< bool > IsGPU
Flag for specifying if the compilation is done for an accelerator.
std::optional< StringRef > FirstSeparator
First separator used between the initial two parts of a name.
StringRef separator() const
LLVM_ABI int64_t getRequiresFlags() const
Returns requires directive clauses as flags compatible with those expected by libomptarget.
void setFirstSeparator(StringRef FS)
void setDefaultTargetAS(unsigned AS)
StringRef firstSeparator() const
std::optional< bool > OpenMPOffloadMandatory
Flag for specifying if offloading is mandatory.
std::optional< bool > EmitLLVMUsedMetaInfo
Flag for specifying if LLVMUsed information should be emitted.
SmallVector< Triple > TargetTriples
When compilation is being done for the OpenMP host (i.e.
LLVM_ABI void setHasRequiresReverseOffload(bool Value)
LLVM_ABI bool hasRequiresUnifiedSharedMemory() const
LLVM_ABI void setHasRequiresUnifiedSharedMemory(bool Value)
unsigned getDefaultTargetAS() const
std::optional< StringRef > Separator
Separator used between all of the rest consecutive parts of s name.
LLVM_ABI bool hasRequiresDynamicAllocators() const
bool openMPOffloadMandatory() const
CallingConv::ID getRuntimeCC() const
LLVM_ABI void setHasRequiresUnifiedAddress(bool Value)
void setOpenMPOffloadMandatory(bool Value)
void setIsTargetDevice(bool Value)
void setSeparator(StringRef S)
void setRuntimeCC(CallingConv::ID CC)
LLVM_ABI void setHasRequiresDynamicAllocators(bool Value)
void setEmitLLVMUsed(bool Value=true)
std::optional< omp::GV > GridValue
LLVM_ABI bool hasRequiresReverseOffload() const
LLVM_ABI bool hasRequiresUnifiedAddress() const
llvm::AllocaInst * CreateAlloca(llvm::Type *Ty, const llvm::Twine &Name) const override
void decorateWithTBAA(llvm::Instruction *I) override
AtomicInfo(IRBuilder<> *Builder, llvm::Type *Ty, uint64_t AtomicSizeInBits, uint64_t ValueSizeInBits, llvm::Align AtomicAlign, llvm::Align ValueAlign, bool UseLibcall, IRBuilderBase::InsertPoint AllocaIP, llvm::Value *AtomicVar)
llvm::Value * getAtomicPointer() const override
Struct that keeps the information that should be kept throughout a 'target data' region.
TargetDataInfo(bool RequiresDevicePointerInfo, bool SeparateBeginEndCalls)
SmallMapVector< const Value *, std::pair< Value *, Value * >, 4 > DevicePtrInfoMap
void clearArrayInfo()
Clear information about the data arrays.
unsigned NumberOfPtrs
The total number of pointers passed to the runtime library.
bool HasNoWait
Whether the target ... data directive has a nowait clause.
bool isValid()
Return true if the current target data information has valid arrays.
bool HasMapper
Indicate whether any user-defined mapper exists.
An interface to create LLVM-IR for OpenMP directives.
LLVM_ABI InsertPointOrErrorTy createOrderedThreadsSimd(const LocationDescription &Loc, BodyGenCallbackTy BodyGenCB, FinalizeCallbackTy FiniCB, bool IsThreads)
Generator for 'omp ordered [threads | simd]'.
LLVM_ABI void emitAArch64DeclareSimdFunction(llvm::Function *Fn, unsigned VLENVal, llvm::ArrayRef< DeclareSimdAttrTy > ParamAttrs, DeclareSimdBranch Branch, char ISA, unsigned NarrowestDataSize, bool OutputBecomesInput)
Emit AArch64 vector-function ABI attributes for a declare simd function.
LLVM_ABI Constant * getOrCreateIdent(Constant *SrcLocStr, uint32_t SrcLocStrSize, omp::IdentFlag Flags=omp::IdentFlag(0), unsigned Reserve2Flags=0)
Return an ident_t* encoding the source location SrcLocStr and Flags.
LLVM_ABI FunctionCallee getOrCreateRuntimeFunction(Module &M, omp::RuntimeFunction FnID)
Return the function declaration for the runtime function with FnID.
LLVM_ABI InsertPointOrErrorTy createCancel(const LocationDescription &Loc, Value *IfCondition, omp::Directive CanceledDirective)
Generator for 'omp cancel'.
std::function< Expected< Function * >(StringRef FunctionName)> FunctionGenCallback
Functions used to generate a function with the given name.
ReductionGenCBKind
Enum class for the RedctionGen CallBack type to be used.
LLVM_ABI CanonicalLoopInfo * collapseLoops(DebugLoc DL, ArrayRef< CanonicalLoopInfo * > Loops, InsertPointTy ComputeIP)
Collapse a loop nest into a single loop.
LLVM_ABI void createTaskyield(const LocationDescription &Loc)
Generator for 'omp taskyield'.
std::function< Error(InsertPointTy CodeGenIP)> FinalizeCallbackTy
Callback type for variable finalization (think destructors).
LLVM_ABI void emitBranch(BasicBlock *Target)
LLVM_ABI Error emitCancelationCheckImpl(Value *CancelFlag, omp::Directive CanceledDirective)
Generate control flow and cleanup for cancellation.
static LLVM_ABI void writeThreadBoundsForKernel(const Triple &T, Function &Kernel, int32_t LB, int32_t UB)
EvalKind
Enum class for reduction evaluation types scalar, complex and aggregate.
LLVM_ABI void emitTaskwaitImpl(const LocationDescription &Loc)
Generate a taskwait runtime call.
LLVM_ABI Constant * registerTargetRegionFunction(TargetRegionEntryInfo &EntryInfo, Function *OutlinedFunction, StringRef EntryFnName, StringRef EntryFnIDName)
Registers the given function and sets up the attribtues of the function Returns the FunctionID.
LLVM_ABI GlobalVariable * emitKernelExecutionMode(StringRef KernelName, omp::OMPTgtExecModeFlags Mode)
Emit the kernel execution mode.
LLVM_ABI InsertPointOrErrorTy createDistribute(const LocationDescription &Loc, InsertPointTy AllocaIP, BodyGenCallbackTy BodyGenCB)
Generator for #omp distribute
LLVM_ABI void initialize()
Initialize the internal state, this will put structures types and potentially other helpers into the ...
LLVM_ABI void createTargetDeinit(const LocationDescription &Loc, int32_t TeamsReductionDataSize=0, int32_t TeamsReductionBufferLength=1024)
Create a runtime call for kmpc_target_deinit.
LLVM_ABI InsertPointOrErrorTy createTaskgroup(const LocationDescription &Loc, InsertPointTy AllocaIP, BodyGenCallbackTy BodyGenCB)
Generator for the taskgroup construct.
std::function< InsertPointTy(InsertPointTy CodeGenIP, unsigned Index, Value **LHS, Value **RHS, Function *CurFn)> ReductionGenClangCBTy
ReductionGen CallBack for Clang.
LLVM_ABI InsertPointTy createAtomicWrite(const LocationDescription &Loc, AtomicOpValue &X, Value *Expr, AtomicOrdering AO, InsertPointTy AllocaIP)
Emit atomic write for : X = Expr — Only Scalar data types.
LLVM_ABI void loadOffloadInfoMetadata(Module &M)
Loads all the offload entries information from the host IR metadata.
function_ref< MapInfosTy &(InsertPointTy CodeGenIP)> GenMapInfoCallbackTy
Callback type for creating the map infos for the kernel parameters.
LLVM_ABI Error emitOffloadingArrays(InsertPointTy AllocaIP, InsertPointTy CodeGenIP, MapInfosTy &CombinedInfo, TargetDataInfo &Info, CustomMapperCallbackTy CustomMapperCB, bool IsNonContiguous=false, function_ref< void(unsigned int, Value *)> DeviceAddrCB=nullptr)
Emit the arrays used to pass the captures and map information to the offloading runtime library.
LLVM_ABI void unrollLoopFull(DebugLoc DL, CanonicalLoopInfo *Loop)
Fully unroll a loop.
function_ref< Error(InsertPointTy CodeGenIP, Value *IndVar)> LoopBodyGenCallbackTy
Callback type for loop body code generation.
LLVM_ABI InsertPointOrErrorTy emitScanReduction(const LocationDescription &Loc, ArrayRef< llvm::OpenMPIRBuilder::ReductionInfo > ReductionInfos, ScanInfo *ScanRedInfo)
This function performs the scan reduction of the values updated in the input phase.
LLVM_ABI void emitFlush(const LocationDescription &Loc)
Generate a flush runtime call.
static LLVM_ABI std::pair< int32_t, int32_t > readThreadBoundsForKernel(const Triple &T, Function &Kernel)
}
OpenMPIRBuilderConfig Config
The OpenMPIRBuilder Configuration.
LLVM_ABI CallInst * createOMPInteropDestroy(const LocationDescription &Loc, Value *InteropVar, Value *Device, Value *NumDependences, Value *DependenceAddress, bool HaveNowaitClause)
Create a runtime call for __tgt_interop_destroy.
LLVM_ABI Error emitIfClause(Value *Cond, BodyGenCallbackTy ThenGen, BodyGenCallbackTy ElseGen, InsertPointTy AllocaIP={})
Emits code for OpenMP 'if' clause using specified BodyGenCallbackTy Here is the logic: if (Cond) { Th...
std::function< InsertPointOrErrorTy( InsertPointTy CodeGenIP, Value *LHS, Value *RHS, Value *&Res)> ReductionGenCBTy
ReductionGen CallBack for MLIR.
function_ref< InsertPointOrErrorTy( Argument &Arg, Value *Input, Value *&RetVal, InsertPointTy AllocaIP, InsertPointTy CodeGenIP)> TargetGenArgAccessorsCallbackTy
LLVM_ABI void emitUsed(StringRef Name, ArrayRef< llvm::WeakTrackingVH > List)
Emit the llvm.used metadata.
void setConfig(OpenMPIRBuilderConfig C)
LLVM_ABI InsertPointOrErrorTy createSingle(const LocationDescription &Loc, BodyGenCallbackTy BodyGenCB, FinalizeCallbackTy FiniCB, bool IsNowait, ArrayRef< llvm::Value * > CPVars={}, ArrayRef< llvm::Function * > CPFuncs={})
Generator for 'omp single'.
LLVM_ABI InsertPointOrErrorTy createTeams(const LocationDescription &Loc, BodyGenCallbackTy BodyGenCB, Value *NumTeamsLower=nullptr, Value *NumTeamsUpper=nullptr, Value *ThreadLimit=nullptr, Value *IfExpr=nullptr)
Generator for #omp teams
std::forward_list< CanonicalLoopInfo > LoopInfos
Collection of owned canonical loop objects that eventually need to be free'd.
LLVM_ABI void createTaskwait(const LocationDescription &Loc)
Generator for 'omp taskwait'.
LLVM_ABI llvm::StructType * getKmpTaskAffinityInfoTy()
Return the LLVM struct type matching runtime kmp_task_affinity_info_t.
LLVM_ABI CanonicalLoopInfo * createLoopSkeleton(DebugLoc DL, Value *TripCount, Function *F, BasicBlock *PreInsertBefore, BasicBlock *PostInsertBefore, const Twine &Name={})
Create the control flow structure of a canonical OpenMP loop.
SmallVector< uint64_t, 4 > MapDimArrayTy
LLVM_ABI std::string createPlatformSpecificName(ArrayRef< StringRef > Parts) const
Get the create a name using the platform specific separators.
LLVM_ABI FunctionCallee createDispatchNextFunction(unsigned IVSize, bool IVSigned)
Returns __kmpc_dispatch_next_* runtime function for the specified size IVSize and sign IVSigned.
static LLVM_ABI void getKernelArgsVector(TargetKernelArgs &KernelArgs, IRBuilderBase &Builder, SmallVector< Value * > &ArgsVector)
Create the kernel args vector used by emitTargetKernel.
function_ref< Error(InsertPointTy AllocaIP, InsertPointTy CodeGenIP)> BodyGenCallbackTy
Callback type for body (=inner region) code generation.
SmallVector< Constant *, 4 > MapNamesArrayTy
LLVM_ABI void unrollLoopHeuristic(DebugLoc DL, CanonicalLoopInfo *Loop)
Fully or partially unroll a loop.
LLVM_ABI InsertPointOrErrorTy createParallel(const LocationDescription &Loc, InsertPointTy AllocaIP, BodyGenCallbackTy BodyGenCB, PrivatizeCallbackTy PrivCB, FinalizeCallbackTy FiniCB, Value *IfCondition, Value *NumThreads, omp::ProcBindKind ProcBind, bool IsCancellable)
Generator for 'omp parallel'.
LLVM_ABI omp::OpenMPOffloadMappingFlags getMemberOfFlag(unsigned Position)
Get OMP_MAP_MEMBER_OF flag with extra bits reserved based on the position given.
LLVM_ABI void addAttributes(omp::RuntimeFunction FnID, Function &Fn)
Add attributes known for FnID to Fn.
LLVM_ABI InsertPointOrErrorTy createTask(const LocationDescription &Loc, InsertPointTy AllocaIP, BodyGenCallbackTy BodyGenCB, bool Tied=true, Value *Final=nullptr, Value *IfCondition=nullptr, const DependenciesInfo &Dependencies={}, AffinityData Affinities={}, bool Mergeable=false, Value *EventHandle=nullptr, Value *Priority=nullptr)
Generator for #omp taskloop
Module & M
The underlying LLVM-IR module.
StringMap< Constant * > SrcLocStrMap
Map to remember source location strings.
LLVM_ABI void createMapperAllocas(const LocationDescription &Loc, InsertPointTy AllocaIP, unsigned NumOperands, struct MapperAllocas &MapperAllocas)
Create the allocas instruction used in call to mapper functions.
LLVM_ABI Constant * getOrCreateSrcLocStr(StringRef LocStr, uint32_t &SrcLocStrSize)
Return the (LLVM-IR) string describing the source location LocStr.
void addOutlineInfo(OutlineInfo &&OI)
Add a new region that will be outlined later.
LLVM_ABI Error emitTargetRegionFunction(TargetRegionEntryInfo &EntryInfo, FunctionGenCallback &GenerateFunctionCallback, bool IsOffloadEntry, Function *&OutlinedFn, Constant *&OutlinedFnID)
Create a unique name for the entry function using the source location information of the current targ...
LLVM_ABI InsertPointOrErrorTy createIteratorLoop(LocationDescription Loc, llvm::Value *TripCount, IteratorBodyGenTy BodyGen, llvm::StringRef Name="iterator")
Create a canonical iterator loop at the current insertion point.
LLVM_ABI Expected< SmallVector< llvm::CanonicalLoopInfo * > > createCanonicalScanLoops(const LocationDescription &Loc, LoopBodyGenCallbackTy BodyGenCB, Value *Start, Value *Stop, Value *Step, bool IsSigned, bool InclusiveStop, InsertPointTy ComputeIP, const Twine &Name, ScanInfo *ScanRedInfo)
Generator for the control flow structure of an OpenMP canonical loops if the parent directive has an ...
LLVM_ABI FunctionCallee createDispatchFiniFunction(unsigned IVSize, bool IVSigned)
Returns __kmpc_dispatch_fini_* runtime function for the specified size IVSize and sign IVSigned.
LLVM_ABI void unrollLoopPartial(DebugLoc DL, CanonicalLoopInfo *Loop, int32_t Factor, CanonicalLoopInfo **UnrolledCLI)
Partially unroll a loop.
function_ref< Error(Value *DeviceID, Value *RTLoc, IRBuilderBase::InsertPoint TargetTaskAllocaIP)> TargetTaskBodyCallbackTy
Callback type for generating the bodies of device directives that require outer target tasks (e....
Expected< MapInfosTy & > MapInfosOrErrorTy
SmallVector< omp::OpenMPOffloadMappingFlags, 4 > MapFlagsArrayTy
LLVM_ABI void emitTaskyieldImpl(const LocationDescription &Loc)
Generate a taskyield runtime call.
LLVM_ABI void emitMapperCall(const LocationDescription &Loc, Function *MapperFunc, Value *SrcLocInfo, Value *MaptypesArg, Value *MapnamesArg, struct MapperAllocas &MapperAllocas, int64_t DeviceID, unsigned NumOperands)
Create the call for the target mapper function.
function_ref< Expected< Function * >(unsigned int)> CustomMapperCallbackTy
LLVM_ABI InsertPointTy createAtomicCompare(const LocationDescription &Loc, AtomicOpValue &X, AtomicOpValue &V, AtomicOpValue &R, Value *E, Value *D, AtomicOrdering AO, omp::OMPAtomicCompareOp Op, bool IsXBinopExpr, bool IsPostfixUpdate, bool IsFailOnly)
Emit atomic compare for constructs: — Only scalar data types cond-expr-stmt: x = x ordop expr ?
LLVM_ABI InsertPointTy createOrderedDepend(const LocationDescription &Loc, InsertPointTy AllocaIP, unsigned NumLoops, ArrayRef< llvm::Value * > StoreValues, const Twine &Name, bool IsDependSource)
Generator for 'omp ordered depend (source | sink)'.
LLVM_ABI InsertPointTy createCopyinClauseBlocks(InsertPointTy IP, Value *MasterAddr, Value *PrivateAddr, llvm::IntegerType *IntPtrTy, bool BranchtoEnd=true)
Generate conditional branch and relevant BasicBlocks through which private threads copy the 'copyin' ...
SmallVector< MapValuesArrayTy, 4 > MapNonContiguousArrayTy
function_ref< InsertPointOrErrorTy( InsertPointTy AllocaIP, InsertPointTy CodeGenIP, Value &Original, Value &Inner, Value *&ReplVal)> PrivatizeCallbackTy
Callback type for variable privatization (think copy & default constructor).
LLVM_ABI bool isFinalized()
Check whether the finalize function has already run.
function_ref< InsertPointOrErrorTy( InsertPointTy AllocaIP, InsertPointTy CodeGenIP)> TargetBodyGenCallbackTy
SmallVector< DeviceInfoTy, 4 > MapDeviceInfoArrayTy
SmallVector< FinalizationInfo, 8 > FinalizationStack
The finalization stack made up of finalize callbacks currently in-flight, wrapped into FinalizationIn...
std::function< Error(InsertPointTy AllocaIP, InsertPointTy CodeGenIP)> StorableBodyGenCallbackTy
LLVM_ABI std::vector< CanonicalLoopInfo * > tileLoops(DebugLoc DL, ArrayRef< CanonicalLoopInfo * > Loops, ArrayRef< Value * > TileSizes)
Tile a loop nest.
LLVM_ABI CallInst * createOMPInteropInit(const LocationDescription &Loc, Value *InteropVar, omp::OMPInteropType InteropType, Value *Device, Value *NumDependences, Value *DependenceAddress, bool HaveNowaitClause)
Create a runtime call for __tgt_interop_init.
SmallVector< OutlineInfo, 16 > OutlineInfos
Collection of regions that need to be outlined during finalization.
LLVM_ABI Function * getOrCreateRuntimeFunctionPtr(omp::RuntimeFunction FnID)
std::function< InsertPointOrErrorTy( InsertPointTy, Value *ByRefVal, Value *&Res)> ReductionGenDataPtrPtrCBTy
LLVM_ABI InsertPointTy createTargetInit(const LocationDescription &Loc, const llvm::OpenMPIRBuilder::TargetKernelDefaultAttrs &Attrs)
The omp target interface.
LLVM_ABI InsertPointOrErrorTy createReductions(const LocationDescription &Loc, InsertPointTy AllocaIP, ArrayRef< ReductionInfo > ReductionInfos, ArrayRef< bool > IsByRef, bool IsNoWait=false, bool IsTeamsReduction=false)
Generator for 'omp reduction'.
const Triple T
The target triple of the underlying module.
DenseMap< std::pair< Constant *, uint64_t >, Constant * > IdentMap
Map to remember existing ident_t*.
LLVM_ABI CallInst * createOMPFree(const LocationDescription &Loc, Value *Addr, Value *Allocator, std::string Name="")
Create a runtime call for kmpc_free.
LLVM_ABI FunctionCallee createForStaticInitFunction(unsigned IVSize, bool IVSigned, bool IsGPUDistribute)
Returns __kmpc_for_static_init_* runtime function for the specified size IVSize and sign IVSigned.
LLVM_ABI CallInst * createOMPAlloc(const LocationDescription &Loc, Value *Size, Value *Allocator, std::string Name="")
Create a runtime call for kmpc_Alloc.
LLVM_ABI void emitNonContiguousDescriptor(InsertPointTy AllocaIP, InsertPointTy CodeGenIP, MapInfosTy &CombinedInfo, TargetDataInfo &Info)
Emit an array of struct descriptors to be assigned to the offload args.
SmallVector< Value *, 4 > MapValuesArrayTy
LLVM_ABI InsertPointOrErrorTy createSection(const LocationDescription &Loc, BodyGenCallbackTy BodyGenCB, FinalizeCallbackTy FiniCB)
Generator for 'omp section'.
LLVM_ABI InsertPointOrErrorTy createTarget(const LocationDescription &Loc, bool IsOffloadEntry, OpenMPIRBuilder::InsertPointTy AllocaIP, OpenMPIRBuilder::InsertPointTy CodeGenIP, TargetDataInfo &Info, TargetRegionEntryInfo &EntryInfo, const TargetKernelDefaultAttrs &DefaultAttrs, const TargetKernelRuntimeAttrs &RuntimeAttrs, Value *IfCond, SmallVectorImpl< Value * > &Inputs, GenMapInfoCallbackTy GenMapInfoCB, TargetBodyGenCallbackTy BodyGenCB, TargetGenArgAccessorsCallbackTy ArgAccessorFuncCB, CustomMapperCallbackTy CustomMapperCB, const DependenciesInfo &Dependencies={}, bool HasNowait=false, Value *DynCGroupMem=nullptr, omp::OMPDynGroupprivateFallbackType DynCGroupMemFallback=omp::OMPDynGroupprivateFallbackType::Abort)
Generator for 'omp target'.
function_ref< InsertPointOrErrorTy(InsertPointTy)> EmitFallbackCallbackTy
Callback function type for functions emitting the host fallback code that is executed when the kernel...
static LLVM_ABI TargetRegionEntryInfo getTargetEntryUniqueInfo(FileIdentifierInfoCallbackTy CallBack, vfs::FileSystem &VFS, StringRef ParentName="")
Creates a unique info for a target entry when provided a filename and line number from.
LLVM_ABI void emitTaskDependency(IRBuilderBase &Builder, Value *Entry, const DependData &Dep)
Store one kmp_depend_info entry at the given Entry pointer.
LLVM_ABI void emitBlock(BasicBlock *BB, Function *CurFn, bool IsFinished=false)
LLVM_ABI Value * getOrCreateThreadID(Value *Ident)
Return the current thread ID.
LLVM_ABI InsertPointOrErrorTy createMaster(const LocationDescription &Loc, BodyGenCallbackTy BodyGenCB, FinalizeCallbackTy FiniCB)
Generator for 'omp master'.
void pushFinalizationCB(const FinalizationInfo &FI)
Push a finalization callback on the finalization stack.
LLVM_ABI InsertPointOrErrorTy createTargetData(const LocationDescription &Loc, InsertPointTy AllocaIP, InsertPointTy CodeGenIP, Value *DeviceID, Value *IfCond, TargetDataInfo &Info, GenMapInfoCallbackTy GenMapInfoCB, CustomMapperCallbackTy CustomMapperCB, omp::RuntimeFunction *MapperFunc=nullptr, function_ref< InsertPointOrErrorTy(InsertPointTy CodeGenIP, BodyGenTy BodyGenType)> BodyGenCB=nullptr, function_ref< void(unsigned int, Value *)> DeviceAddrCB=nullptr, Value *SrcLocInfo=nullptr)
Generator for 'omp target data'.
CallInst * createRuntimeFunctionCall(FunctionCallee Callee, ArrayRef< Value * > Args, StringRef Name="")
LLVM_ABI InsertPointOrErrorTy emitKernelLaunch(const LocationDescription &Loc, Value *OutlinedFnID, EmitFallbackCallbackTy EmitTargetCallFallbackCB, TargetKernelArgs &Args, Value *DeviceID, Value *RTLoc, InsertPointTy AllocaIP)
Generate a target region entry call and host fallback call.
InsertPointTy getInsertionPoint()
}
StringMap< GlobalVariable *, BumpPtrAllocator > InternalVars
An ordered map of auto-generated variables to their unique names.
LLVM_ABI InsertPointOrErrorTy createCancellationPoint(const LocationDescription &Loc, omp::Directive CanceledDirective)
Generator for 'omp cancellation point'.
LLVM_ABI FunctionCallee createDispatchInitFunction(unsigned IVSize, bool IVSigned)
Returns __kmpc_dispatch_init_* runtime function for the specified size IVSize and sign IVSigned.
LLVM_ABI InsertPointOrErrorTy createScan(const LocationDescription &Loc, InsertPointTy AllocaIP, ArrayRef< llvm::Value * > ScanVars, ArrayRef< llvm::Type * > ScanVarsType, bool IsInclusive, ScanInfo *ScanRedInfo)
This directive split and directs the control flow to input phase blocks or scan phase blocks based on...
LLVM_ABI CallInst * createOMPInteropUse(const LocationDescription &Loc, Value *InteropVar, Value *Device, Value *NumDependences, Value *DependenceAddress, bool HaveNowaitClause)
Create a runtime call for __tgt_interop_use.
IRBuilder<>::InsertPoint InsertPointTy
Type used throughout for insertion points.
LLVM_ABI GlobalVariable * getOrCreateInternalVariable(Type *Ty, const StringRef &Name, std::optional< unsigned > AddressSpace={})
Gets (if variable with the given name already exist) or creates internal global variable with the spe...
LLVM_ABI GlobalVariable * createOffloadMapnames(SmallVectorImpl< llvm::Constant * > &Names, std::string VarName)
Create the global variable holding the offload names information.
std::forward_list< ScanInfo > ScanInfos
Collection of owned ScanInfo objects that eventually need to be free'd.
static LLVM_ABI void writeTeamsForKernel(const Triple &T, Function &Kernel, int32_t LB, int32_t UB)
std::function< InsertPointOrErrorTy( InsertPointTy, Type *, Value *, Value *)> ReductionGenAtomicCBTy
Functions used to generate atomic reductions.
LLVM_ABI Value * calculateCanonicalLoopTripCount(const LocationDescription &Loc, Value *Start, Value *Stop, Value *Step, bool IsSigned, bool InclusiveStop, const Twine &Name="loop")
Calculate the trip count of a canonical loop.
DeclareSimdKindTy
Kind of parameter in a function with 'declare simd' directive.
LLVM_ABI InsertPointOrErrorTy createBarrier(const LocationDescription &Loc, omp::Directive Kind, bool ForceSimpleCall=false, bool CheckCancelFlag=true)
Emitter methods for OpenMP directives.
LLVM_ABI void setCorrectMemberOfFlag(omp::OpenMPOffloadMappingFlags &Flags, omp::OpenMPOffloadMappingFlags MemberOfFlag)
Given an initial flag set, this function modifies it to contain the passed in MemberOfFlag generated ...
LLVM_ABI Error emitOffloadingArraysAndArgs(InsertPointTy AllocaIP, InsertPointTy CodeGenIP, TargetDataInfo &Info, TargetDataRTArgs &RTArgs, MapInfosTy &CombinedInfo, CustomMapperCallbackTy CustomMapperCB, bool IsNonContiguous=false, bool ForEndCall=false, function_ref< void(unsigned int, Value *)> DeviceAddrCB=nullptr)
Allocates memory for and populates the arrays required for offloading (offload_{baseptrs|ptrs|mappers...
LLVM_ABI Constant * getOrCreateDefaultSrcLocStr(uint32_t &SrcLocStrSize)
Return the (LLVM-IR) string describing the default source location.
LLVM_ABI InsertPointOrErrorTy createCritical(const LocationDescription &Loc, BodyGenCallbackTy BodyGenCB, FinalizeCallbackTy FiniCB, StringRef CriticalName, Value *HintInst)
Generator for 'omp critical'.
LLVM_ABI void createOffloadEntry(Constant *ID, Constant *Addr, uint64_t Size, int32_t Flags, GlobalValue::LinkageTypes, StringRef Name="")
Creates offloading entry for the provided entry ID ID, address Addr, size Size, and flags Flags.
static LLVM_ABI unsigned getOpenMPDefaultSimdAlign(const Triple &TargetTriple, const StringMap< bool > &Features)
Get the default alignment value for given target.
LLVM_ABI unsigned getFlagMemberOffset()
Get the offset of the OMP_MAP_MEMBER_OF field.
LLVM_ABI InsertPointOrErrorTy applyWorkshareLoop(DebugLoc DL, CanonicalLoopInfo *CLI, InsertPointTy AllocaIP, bool NeedsBarrier, llvm::omp::ScheduleKind SchedKind=llvm::omp::OMP_SCHEDULE_Default, Value *ChunkSize=nullptr, bool HasSimdModifier=false, bool HasMonotonicModifier=false, bool HasNonmonotonicModifier=false, bool HasOrderedClause=false, omp::WorksharingLoopType LoopType=omp::WorksharingLoopType::ForStaticLoop, bool NoLoop=false, bool HasDistSchedule=false, Value *DistScheduleChunkSize=nullptr)
Modifies the canonical loop to be a workshare loop.
LLVM_ABI InsertPointOrErrorTy createAtomicCapture(const LocationDescription &Loc, InsertPointTy AllocaIP, AtomicOpValue &X, AtomicOpValue &V, Value *Expr, AtomicOrdering AO, AtomicRMWInst::BinOp RMWOp, AtomicUpdateCallbackTy &UpdateOp, bool UpdateExpr, bool IsPostfixUpdate, bool IsXBinopExpr, bool IsIgnoreDenormalMode=false, bool IsFineGrainedMemory=false, bool IsRemoteMemory=false)
Emit atomic update for constructs: — Only Scalar data types V = X; X = X BinOp Expr ,...
LLVM_ABI void createOffloadEntriesAndInfoMetadata(EmitMetadataErrorReportFunctionTy &ErrorReportFunction)
LLVM_ABI void applySimd(CanonicalLoopInfo *Loop, MapVector< Value *, Value * > AlignedVars, Value *IfCond, omp::OrderKind Order, ConstantInt *Simdlen, ConstantInt *Safelen)
Add metadata to simd-ize a loop.
LLVM_ABI InsertPointOrErrorTy createAtomicUpdate(const LocationDescription &Loc, InsertPointTy AllocaIP, AtomicOpValue &X, Value *Expr, AtomicOrdering AO, AtomicRMWInst::BinOp RMWOp, AtomicUpdateCallbackTy &UpdateOp, bool IsXBinopExpr, bool IsIgnoreDenormalMode=false, bool IsFineGrainedMemory=false, bool IsRemoteMemory=false)
Emit atomic update for constructs: X = X BinOp Expr ,or X = Expr BinOp X For complex Operations: X = ...
std::function< std::tuple< std::string, uint64_t >()> FileIdentifierInfoCallbackTy
bool isLastFinalizationInfoCancellable(omp::Directive DK)
Return true if the last entry in the finalization stack is of kind DK and cancellable.
LLVM_ABI InsertPointTy emitTargetKernel(const LocationDescription &Loc, InsertPointTy AllocaIP, Value *&Return, Value *Ident, Value *DeviceID, Value *NumTeams, Value *NumThreads, Value *HostPtr, ArrayRef< Value * > KernelArgs)
Generate a target region entry call.
LLVM_ABI GlobalVariable * createOffloadMaptypes(SmallVectorImpl< uint64_t > &Mappings, std::string VarName)
Create the global variable holding the offload mappings information.
LLVM_ABI CallInst * createCachedThreadPrivate(const LocationDescription &Loc, llvm::Value *Pointer, llvm::ConstantInt *Size, const llvm::Twine &Name=Twine(""))
Create a runtime call for kmpc_threadprivate_cached.
IRBuilder Builder
The LLVM-IR Builder used to create IR.
LLVM_ABI GlobalValue * createGlobalFlag(unsigned Value, StringRef Name)
Create a hidden global flag Name in the module with initial value Value.
LLVM_ABI void emitOffloadingArraysArgument(IRBuilderBase &Builder, OpenMPIRBuilder::TargetDataRTArgs &RTArgs, OpenMPIRBuilder::TargetDataInfo &Info, bool ForEndCall=false)
Emit the arguments to be passed to the runtime library based on the arrays of base pointers,...
LLVM_ABI InsertPointOrErrorTy createMasked(const LocationDescription &Loc, BodyGenCallbackTy BodyGenCB, FinalizeCallbackTy FiniCB, Value *Filter)
Generator for 'omp masked'.
LLVM_ABI Expected< CanonicalLoopInfo * > createCanonicalLoop(const LocationDescription &Loc, LoopBodyGenCallbackTy BodyGenCB, Value *TripCount, const Twine &Name="loop")
Generator for the control flow structure of an OpenMP canonical loop.
function_ref< Expected< InsertPointTy >( InsertPointTy AllocaIP, InsertPointTy CodeGenIP, Value *DestPtr, Value *SrcPtr)> TaskDupCallbackTy
Callback type for task duplication function code generation.
LLVM_ABI Value * getSizeInBytes(Value *BasePtr)
Computes the size of type in bytes.
llvm::function_ref< llvm::Error( InsertPointTy BodyIP, llvm::Value *LinearIV)> IteratorBodyGenTy
OpenMPIRBuilder(Module &M)
Create a new OpenMPIRBuilder operating on the given module M.
LLVM_ABI InsertPointOrErrorTy createReductionsGPU(const LocationDescription &Loc, InsertPointTy AllocaIP, InsertPointTy CodeGenIP, ArrayRef< ReductionInfo > ReductionInfos, ArrayRef< bool > IsByRef, bool IsNoWait=false, bool IsTeamsReduction=false, ReductionGenCBKind ReductionGenCBKind=ReductionGenCBKind::MLIR, std::optional< omp::GV > GridValue={}, unsigned ReductionBufNum=1024, Value *SrcLocInfo=nullptr)
Design of OpenMP reductions on the GPU.
LLVM_ABI Expected< Function * > emitUserDefinedMapper(function_ref< MapInfosOrErrorTy(InsertPointTy CodeGenIP, llvm::Value *PtrPHI, llvm::Value *BeginArg)> PrivAndGenMapInfoCB, llvm::Type *ElemTy, StringRef FuncName, CustomMapperCallbackTy CustomMapperCB)
Emit the user-defined mapper function.
LLVM_ABI FunctionCallee createDispatchDeinitFunction()
Returns __kmpc_dispatch_deinit runtime function.
LLVM_ABI void registerTargetGlobalVariable(OffloadEntriesInfoManager::OMPTargetGlobalVarEntryKind CaptureClause, OffloadEntriesInfoManager::OMPTargetDeviceClauseKind DeviceClause, bool IsDeclaration, bool IsExternallyVisible, TargetRegionEntryInfo EntryInfo, StringRef MangledName, std::vector< GlobalVariable * > &GeneratedRefs, bool OpenMPSIMD, std::vector< Triple > TargetTriple, std::function< Constant *()> GlobalInitializer, std::function< GlobalValue::LinkageTypes()> VariableLinkage, Type *LlvmPtrTy, Constant *Addr)
Registers a target variable for device or host.
BodyGenTy
Type of BodyGen to use for region codegen.
LLVM_ABI CanonicalLoopInfo * fuseLoops(DebugLoc DL, ArrayRef< CanonicalLoopInfo * > Loops)
Fuse a sequence of loops.
LLVM_ABI void emitX86DeclareSimdFunction(llvm::Function *Fn, unsigned NumElements, const llvm::APSInt &VLENVal, llvm::ArrayRef< DeclareSimdAttrTy > ParamAttrs, DeclareSimdBranch Branch)
Emit x86 vector-function ABI attributes for a declare simd function.
SmallVector< llvm::Function *, 16 > ConstantAllocaRaiseCandidates
A collection of candidate target functions that's constant allocas will attempt to be raised on a cal...
OffloadEntriesInfoManager OffloadInfoManager
Info manager to keep track of target regions.
static LLVM_ABI std::pair< int32_t, int32_t > readTeamBoundsForKernel(const Triple &T, Function &Kernel)
Read/write a bounds on teams for Kernel.
const std::string ompOffloadInfoName
OMP Offload Info Metadata name string.
Expected< InsertPointTy > InsertPointOrErrorTy
Type used to represent an insertion point or an error value.
LLVM_ABI InsertPointTy createCopyPrivate(const LocationDescription &Loc, llvm::Value *BufSize, llvm::Value *CpyBuf, llvm::Value *CpyFn, llvm::Value *DidIt)
Generator for __kmpc_copyprivate.
void popFinalizationCB()
Pop the last finalization callback from the finalization stack.
LLVM_ABI InsertPointOrErrorTy createSections(const LocationDescription &Loc, InsertPointTy AllocaIP, ArrayRef< StorableBodyGenCallbackTy > SectionCBs, PrivatizeCallbackTy PrivCB, FinalizeCallbackTy FiniCB, bool IsCancellable, bool IsNowait)
Generator for 'omp sections'.
std::function< void(EmitMetadataErrorKind, TargetRegionEntryInfo)> EmitMetadataErrorReportFunctionTy
Callback function type.
LLVM_ABI Expected< ScanInfo * > scanInfoInitialize()
Creates a ScanInfo object, allocates and returns the pointer.
LLVM_ABI InsertPointOrErrorTy emitTargetTask(TargetTaskBodyCallbackTy TaskBodyCB, Value *DeviceID, Value *RTLoc, OpenMPIRBuilder::InsertPointTy AllocaIP, const DependenciesInfo &Dependencies, const TargetDataRTArgs &RTArgs, bool HasNoWait)
Generate a target-task for the target construct.
LLVM_ABI InsertPointTy createAtomicRead(const LocationDescription &Loc, AtomicOpValue &X, AtomicOpValue &V, AtomicOrdering AO, InsertPointTy AllocaIP)
Emit atomic Read for : V = X — Only Scalar data types.
bool updateToLocation(const LocationDescription &Loc)
Update the internal location to Loc.
LLVM_ABI void createFlush(const LocationDescription &Loc)
Generator for 'omp flush'.
LLVM_ABI Constant * getAddrOfDeclareTargetVar(OffloadEntriesInfoManager::OMPTargetGlobalVarEntryKind CaptureClause, OffloadEntriesInfoManager::OMPTargetDeviceClauseKind DeviceClause, bool IsDeclaration, bool IsExternallyVisible, TargetRegionEntryInfo EntryInfo, StringRef MangledName, std::vector< GlobalVariable * > &GeneratedRefs, bool OpenMPSIMD, std::vector< Triple > TargetTriple, Type *LlvmPtrTy, std::function< Constant *()> GlobalInitializer, std::function< GlobalValue::LinkageTypes()> VariableLinkage)
Retrieve (or create if non-existent) the address of a declare target variable, used in conjunction wi...
EmitMetadataErrorKind
The kind of errors that can occur when emitting the offload entries and metadata.
ScanInfo holds the information to assist in lowering of Scan reduction.
llvm::SmallDenseMap< llvm::Value *, llvm::Value * > * ScanBuffPtrs
Maps the private reduction variable to the pointer of the temporary buffer.
llvm::BasicBlock * OMPScanLoopExit
Exit block of loop body.
llvm::Value * IV
Keeps track of value of iteration variable for input/scan loop to be used for Scan directive lowering...
llvm::BasicBlock * OMPAfterScanBlock
Dominates the body of the loop before scan directive.
llvm::BasicBlock * OMPScanInit
Block before loop body where scan initializations are done.
llvm::BasicBlock * OMPBeforeScanBlock
Dominates the body of the loop before scan directive.
llvm::BasicBlock * OMPScanFinish
Block after loop body where scan finalizations are done.
ScanInfo & operator=(const ScanInfo &)=delete
llvm::Value * Span
Stores the span of canonical loop being lowered to be used for temporary buffer allocation or Finaliz...
bool OMPFirstScanLoop
If true, it indicates Input phase is lowered; else it indicates ScanPhase is lowered.
ScanInfo(ScanInfo &)=delete
llvm::BasicBlock * OMPScanDispatch
Controls the flow to before or after scan blocks.
A vector that has set insertion semantics.
Definition SetVector.h:57
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringMap - This is an unconventional map that is specialized for handling keys that are "strings",...
Definition StringMap.h:133
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
Class to represent struct types.
Target - Wrapper for Target specific information.
Triple - Helper class for working with autoconf configuration names.
Definition Triple.h:47
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
Value * getOperand(unsigned i) const
Definition User.h:207
See the file comment.
Definition ValueMap.h:84
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:255
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
Definition Value.cpp:393
Value handle that is nullable, but tries to track the Value.
An efficient, type-erasing, non-owning reference to a callable.
The virtual file system interface.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
OpenMPOffloadMappingFlags
Values for bit flags used to specify the mapping type for offloading.
IdentFlag
IDs for all omp runtime library ident_t flag encodings (see their defintion in openmp/runtime/src/kmp...
RTLDependenceKindTy
Dependence kind for RTL.
RuntimeFunction
IDs for all omp runtime library (RTL) functions.
OMPDynGroupprivateFallbackType
The fallback types for the dyn_groupprivate clause.
WorksharingLoopType
A type of worksharing loop construct.
OMPAtomicCompareOp
Atomic compare operations. Currently OpenMP only supports ==, >, and <.
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI BasicBlock * splitBBWithSuffix(IRBuilderBase &Builder, bool CreateBranch, llvm::Twine Suffix=".split")
Like splitBB, but reuses the current block's name for the new name.
@ Offset
Definition DWP.cpp:532
FunctionAddr VTableAddr Value
Definition InstrProf.h:137
LLVM_ABI BasicBlock * splitBB(IRBuilderBase::InsertPoint IP, bool CreateBranch, DebugLoc DL, llvm::Twine Name={})
Split a BasicBlock at an InsertPoint, even if the block is degenerate (missing the terminator).
auto cast_or_null(const Y &Val)
Definition Casting.h:714
FunctionAddr VTableAddr Count
Definition InstrProf.h:139
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
AtomicOrdering
Atomic ordering for LLVM's memory model.
IRBuilder(LLVMContext &, FolderTy, InserterTy, MDNode *, ArrayRef< OperandBundleDef >) -> IRBuilder< FolderTy, InserterTy >
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1917
LLVM_ABI void spliceBB(IRBuilderBase::InsertPoint IP, BasicBlock *New, bool CreateBranch, DebugLoc DL)
Move the instruction after an InsertPoint to the beginning of another BasicBlock.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:870
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
A struct to pack the relevant information for an OpenMP affinity clause.
a struct to pack relevant information while generating atomic Ops
Attribute set of the declare simd parameter.
DependData(omp::RTLDependenceKindTy DepKind, Type *DepValueType, Value *DepVal)
omp::RTLDependenceKindTy DepKind
A struct to pack static and dynamic dependency information for a task.
DependenciesInfo(SmallVector< DependData > D)
const omp::Directive DK
The directive kind of the innermost directive that has an associated region which might require final...
const bool IsCancellable
Flag to indicate if the directive is cancellable.
Error mergeFiniBB(IRBuilderBase &Builder, BasicBlock *ExistingFiniBB)
For cases where there is an unavoidable existing finalization block (e.g.
FinalizationInfo(FinalizeCallbackTy FiniCB, omp::Directive DK, bool IsCancellable)
Expected< BasicBlock * > getFiniBB(IRBuilderBase &Builder)
The basic block to which control should be transferred to implement the FiniCB.
Description of a LLVM-IR insertion point (IP) and a debug/source location (filename,...
LocationDescription(const InsertPointTy &IP)
LocationDescription(const InsertPointTy &IP, const DebugLoc &DL)
LocationDescription(const IRBuilderBase &IRB)
This structure contains combined information generated for mappable clauses, including base pointers,...
void append(MapInfosTy &CurInfo)
Append arrays in CurInfo.
MapDeviceInfoArrayTy DevicePointers
StructNonContiguousInfo NonContigInfo
Helper that contains information about regions we need to outline during finalization.
LLVM_ABI void collectBlocks(SmallPtrSetImpl< BasicBlock * > &BlockSet, SmallVectorImpl< BasicBlock * > &BlockVector)
Collect all blocks in between EntryBB and ExitBB in both the given vector and set.
Function * getFunction() const
Return the function that contains the region to be outlined.
SmallVector< Value *, 2 > ExcludeArgsFromAggregate
std::function< void(Function &)> PostOutlineCBTy
EvalKind EvaluationKind
Reduction evaluation kind - scalar, complex or aggregate.
ReductionInfo(Type *ElementType, Value *Variable, Value *PrivateVariable, EvalKind EvaluationKind, ReductionGenCBTy ReductionGen, ReductionGenClangCBTy ReductionGenClang, ReductionGenAtomicCBTy AtomicReductionGen, ReductionGenDataPtrPtrCBTy DataPtrPtrGen, Type *ByRefAllocatedType=nullptr, Type *ByRefElementType=nullptr)
ReductionGenAtomicCBTy AtomicReductionGen
Callback for generating the atomic reduction body, may be null.
ReductionGenCBTy ReductionGen
Callback for generating the reduction body.
ReductionInfo(Value *PrivateVariable)
Type * ByRefAllocatedType
For by-ref reductions, we need to keep track of 2 extra types that are potentially different:
Value * Variable
Reduction variable of pointer type.
Value * PrivateVariable
Thread-private partial reduction variable.
ReductionGenClangCBTy ReductionGenClang
Clang callback for generating the reduction body.
Type * ElementType
Reduction element type, must match pointee type of variable.
ReductionGenDataPtrPtrCBTy DataPtrPtrGen
Container for the arguments used to pass data to the runtime library.
Value * SizesArray
The array of sizes passed to the runtime library.
TargetDataRTArgs(Value *BasePointersArray, Value *PointersArray, Value *SizesArray, Value *MapTypesArray, Value *MapTypesArrayEnd, Value *MappersArray, Value *MapNamesArray)
Value * PointersArray
The array of section pointers passed to the runtime library.
Value * MappersArray
The array of user-defined mappers passed to the runtime library.
Value * MapTypesArrayEnd
The array of map types passed to the runtime library for the end of the region, or nullptr if there a...
Value * BasePointersArray
The array of base pointer passed to the runtime library.
Value * MapTypesArray
The array of map types passed to the runtime library for the beginning of the region or for the entir...
Value * MapNamesArray
The array of original declaration names of mapped pointers sent to the runtime library for debugging.
Data structure that contains the needed information to construct the kernel args vector.
ArrayRef< Value * > NumThreads
The number of threads.
TargetDataRTArgs RTArgs
Arguments passed to the runtime library.
Value * NumIterations
The number of iterations.
Value * DynCGroupMem
The size of the dynamic shared memory.
TargetKernelArgs(unsigned NumTargetItems, TargetDataRTArgs RTArgs, Value *NumIterations, ArrayRef< Value * > NumTeams, ArrayRef< Value * > NumThreads, Value *DynCGroupMem, bool HasNoWait, omp::OMPDynGroupprivateFallbackType DynCGroupMemFallback)
unsigned NumTargetItems
Number of arguments passed to the runtime library.
bool HasNoWait
True if the kernel has 'no wait' clause.
ArrayRef< Value * > NumTeams
The number of teams.
omp::OMPDynGroupprivateFallbackType DynCGroupMemFallback
The fallback mechanism for the shared memory.
Container to pass the default attributes with which a kernel must be launched, used to set kernel att...
Container to pass LLVM IR runtime values or constants related to the number of teams and threads with...
Value * DeviceID
Device ID value used in the kernel launch.
Value * MaxThreads
'parallel' construct 'num_threads' clause value, if present and it is an SPMD kernel.
Value * LoopTripCount
Total number of iterations of the SPMD or Generic-SPMD kernel or null if it is a generic kernel.
A MapVector that performs no allocations if smaller than a certain size.
Definition MapVector.h:276
Data structure to contain the information needed to uniquely identify a target entry.
static LLVM_ABI void getTargetRegionEntryFnName(SmallVectorImpl< char > &Name, StringRef ParentName, unsigned DeviceID, unsigned FileID, unsigned Line, unsigned Count)
static constexpr const char * KernelNamePrefix
The prefix used for kernel names.
bool operator<(const TargetRegionEntryInfo &RHS) const
TargetRegionEntryInfo(StringRef ParentName, unsigned DeviceID, unsigned FileID, unsigned Line, unsigned Count=0)
Defines various target-specific GPU grid values that must be consistent between host RTL (plugin),...