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