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