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 Function *emitListToGlobalCopyFunction(ArrayRef<ReductionInfo> ReductionInfos,
1772 Type *ReductionsBufferTy,
1773 AttributeList FuncAttrs);
1774
1775 /// This function emits a helper that copies all the reduction variables from
1776 /// the team into the provided global buffer for the reduction variables.
1777 ///
1778 /// void list_to_global_copy_func(void *buffer, int Idx, void *reduce_data)
1779 /// For all data entries D in reduce_data:
1780 /// Copy buffer.D[Idx] to local D;
1781 ///
1782 /// \param ReductionInfos Array type containing the ReductionOps.
1783 /// \param ReductionsBufferTy The StructTy for the reductions buffer.
1784 /// \param FuncAttrs Optional param to specify any function attributes that
1785 /// need to be copied to the new function.
1786 ///
1787 /// \return The GlobalToList function.
1788 Function *emitGlobalToListCopyFunction(ArrayRef<ReductionInfo> ReductionInfos,
1789 Type *ReductionsBufferTy,
1790 AttributeList FuncAttrs);
1791
1792 /// This function emits a helper that reduces all the reduction variables from
1793 /// the team into the provided global buffer for the reduction variables.
1794 ///
1795 /// void list_to_global_reduce_func(void *buffer, int Idx, void *reduce_data)
1796 /// void *GlobPtrs[];
1797 /// GlobPtrs[0] = (void*)&buffer.D0[Idx];
1798 /// ...
1799 /// GlobPtrs[N] = (void*)&buffer.DN[Idx];
1800 /// reduce_function(GlobPtrs, reduce_data);
1801 ///
1802 /// \param ReductionInfos Array type containing the ReductionOps.
1803 /// \param ReduceFn The reduction function.
1804 /// \param ReductionsBufferTy The StructTy for the reductions buffer.
1805 /// \param FuncAttrs Optional param to specify any function attributes that
1806 /// need to be copied to the new function.
1807 ///
1808 /// \return The ListToGlobalReduce function.
1809 Function *
1810 emitListToGlobalReduceFunction(ArrayRef<ReductionInfo> ReductionInfos,
1811 Function *ReduceFn, Type *ReductionsBufferTy,
1812 AttributeList FuncAttrs);
1813
1814 /// This function emits a helper that reduces all the reduction variables from
1815 /// the team into the provided global buffer for the reduction variables.
1816 ///
1817 /// void global_to_list_reduce_func(void *buffer, int Idx, void *reduce_data)
1818 /// void *GlobPtrs[];
1819 /// GlobPtrs[0] = (void*)&buffer.D0[Idx];
1820 /// ...
1821 /// GlobPtrs[N] = (void*)&buffer.DN[Idx];
1822 /// reduce_function(reduce_data, GlobPtrs);
1823 ///
1824 /// \param ReductionInfos Array type containing the ReductionOps.
1825 /// \param ReduceFn The reduction function.
1826 /// \param ReductionsBufferTy The StructTy for the reductions buffer.
1827 /// \param FuncAttrs Optional param to specify any function attributes that
1828 /// need to be copied to the new function.
1829 ///
1830 /// \return The GlobalToListReduce function.
1831 Function *
1832 emitGlobalToListReduceFunction(ArrayRef<ReductionInfo> ReductionInfos,
1833 Function *ReduceFn, Type *ReductionsBufferTy,
1834 AttributeList FuncAttrs);
1835
1836 /// Get the function name of a reduction function.
1837 std::string getReductionFuncName(StringRef Name) const;
1838
1839 /// Emits reduction function.
1840 /// \param ReducerName Name of the function calling the reduction.
1841 /// \param ReductionInfos Array type containing the ReductionOps.
1842 /// \param ReductionGenCBKind Optional param to specify Clang or MLIR
1843 /// CodeGenCB kind.
1844 /// \param FuncAttrs Optional param to specify any function attributes that
1845 /// need to be copied to the new function.
1846 ///
1847 /// \return The reduction function.
1848 Expected<Function *> createReductionFunction(
1849 StringRef ReducerName, ArrayRef<ReductionInfo> ReductionInfos,
1850 ArrayRef<bool> IsByRef,
1851 ReductionGenCBKind ReductionGenCBKind = ReductionGenCBKind::MLIR,
1852 AttributeList FuncAttrs = {});
1853
1854public:
1855 ///
1856 /// Design of OpenMP reductions on the GPU
1857 ///
1858 /// Consider a typical OpenMP program with one or more reduction
1859 /// clauses:
1860 ///
1861 /// float foo;
1862 /// double bar;
1863 /// #pragma omp target teams distribute parallel for \
1864 /// reduction(+:foo) reduction(*:bar)
1865 /// for (int i = 0; i < N; i++) {
1866 /// foo += A[i]; bar *= B[i];
1867 /// }
1868 ///
1869 /// where 'foo' and 'bar' are reduced across all OpenMP threads in
1870 /// all teams. In our OpenMP implementation on the NVPTX device an
1871 /// OpenMP team is mapped to a CUDA threadblock and OpenMP threads
1872 /// within a team are mapped to CUDA threads within a threadblock.
1873 /// Our goal is to efficiently aggregate values across all OpenMP
1874 /// threads such that:
1875 ///
1876 /// - the compiler and runtime are logically concise, and
1877 /// - the reduction is performed efficiently in a hierarchical
1878 /// manner as follows: within OpenMP threads in the same warp,
1879 /// across warps in a threadblock, and finally across teams on
1880 /// the NVPTX device.
1881 ///
1882 /// Introduction to Decoupling
1883 ///
1884 /// We would like to decouple the compiler and the runtime so that the
1885 /// latter is ignorant of the reduction variables (number, data types)
1886 /// and the reduction operators. This allows a simpler interface
1887 /// and implementation while still attaining good performance.
1888 ///
1889 /// Pseudocode for the aforementioned OpenMP program generated by the
1890 /// compiler is as follows:
1891 ///
1892 /// 1. Create private copies of reduction variables on each OpenMP
1893 /// thread: 'foo_private', 'bar_private'
1894 /// 2. Each OpenMP thread reduces the chunk of 'A' and 'B' assigned
1895 /// to it and writes the result in 'foo_private' and 'bar_private'
1896 /// respectively.
1897 /// 3. Call the OpenMP runtime on the GPU to reduce within a team
1898 /// and store the result on the team master:
1899 ///
1900 /// __kmpc_nvptx_parallel_reduce_nowait_v2(...,
1901 /// reduceData, shuffleReduceFn, interWarpCpyFn)
1902 ///
1903 /// where:
1904 /// struct ReduceData {
1905 /// double *foo;
1906 /// double *bar;
1907 /// } reduceData
1908 /// reduceData.foo = &foo_private
1909 /// reduceData.bar = &bar_private
1910 ///
1911 /// 'shuffleReduceFn' and 'interWarpCpyFn' are pointers to two
1912 /// auxiliary functions generated by the compiler that operate on
1913 /// variables of type 'ReduceData'. They aid the runtime perform
1914 /// algorithmic steps in a data agnostic manner.
1915 ///
1916 /// 'shuffleReduceFn' is a pointer to a function that reduces data
1917 /// of type 'ReduceData' across two OpenMP threads (lanes) in the
1918 /// same warp. It takes the following arguments as input:
1919 ///
1920 /// a. variable of type 'ReduceData' on the calling lane,
1921 /// b. its lane_id,
1922 /// c. an offset relative to the current lane_id to generate a
1923 /// remote_lane_id. The remote lane contains the second
1924 /// variable of type 'ReduceData' that is to be reduced.
1925 /// d. an algorithm version parameter determining which reduction
1926 /// algorithm to use.
1927 ///
1928 /// 'shuffleReduceFn' retrieves data from the remote lane using
1929 /// efficient GPU shuffle intrinsics and reduces, using the
1930 /// algorithm specified by the 4th parameter, the two operands
1931 /// element-wise. The result is written to the first operand.
1932 ///
1933 /// Different reduction algorithms are implemented in different
1934 /// runtime functions, all calling 'shuffleReduceFn' to perform
1935 /// the essential reduction step. Therefore, based on the 4th
1936 /// parameter, this function behaves slightly differently to
1937 /// cooperate with the runtime to ensure correctness under
1938 /// different circumstances.
1939 ///
1940 /// 'InterWarpCpyFn' is a pointer to a function that transfers
1941 /// reduced variables across warps. It tunnels, through CUDA
1942 /// shared memory, the thread-private data of type 'ReduceData'
1943 /// from lane 0 of each warp to a lane in the first warp.
1944 /// 4. Call the OpenMP runtime on the GPU to reduce across teams.
1945 /// The last team writes the global reduced value to memory.
1946 ///
1947 /// ret = __kmpc_nvptx_teams_reduce_nowait(...,
1948 /// reduceData, shuffleReduceFn, interWarpCpyFn,
1949 /// scratchpadCopyFn, loadAndReduceFn)
1950 ///
1951 /// 'scratchpadCopyFn' is a helper that stores reduced
1952 /// data from the team master to a scratchpad array in
1953 /// global memory.
1954 ///
1955 /// 'loadAndReduceFn' is a helper that loads data from
1956 /// the scratchpad array and reduces it with the input
1957 /// operand.
1958 ///
1959 /// These compiler generated functions hide address
1960 /// calculation and alignment information from the runtime.
1961 /// 5. if ret == 1:
1962 /// The team master of the last team stores the reduced
1963 /// result to the globals in memory.
1964 /// foo += reduceData.foo; bar *= reduceData.bar
1965 ///
1966 ///
1967 /// Warp Reduction Algorithms
1968 ///
1969 /// On the warp level, we have three algorithms implemented in the
1970 /// OpenMP runtime depending on the number of active lanes:
1971 ///
1972 /// Full Warp Reduction
1973 ///
1974 /// The reduce algorithm within a warp where all lanes are active
1975 /// is implemented in the runtime as follows:
1976 ///
1977 /// full_warp_reduce(void *reduce_data,
1978 /// kmp_ShuffleReductFctPtr ShuffleReduceFn) {
1979 /// for (int offset = WARPSIZE/2; offset > 0; offset /= 2)
1980 /// ShuffleReduceFn(reduce_data, 0, offset, 0);
1981 /// }
1982 ///
1983 /// The algorithm completes in log(2, WARPSIZE) steps.
1984 ///
1985 /// 'ShuffleReduceFn' is used here with lane_id set to 0 because it is
1986 /// not used therefore we save instructions by not retrieving lane_id
1987 /// from the corresponding special registers. The 4th parameter, which
1988 /// represents the version of the algorithm being used, is set to 0 to
1989 /// signify full warp reduction.
1990 ///
1991 /// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
1992 ///
1993 /// #reduce_elem refers to an element in the local lane's data structure
1994 /// #remote_elem is retrieved from a remote lane
1995 /// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
1996 /// reduce_elem = reduce_elem REDUCE_OP remote_elem;
1997 ///
1998 /// Contiguous Partial Warp Reduction
1999 ///
2000 /// This reduce algorithm is used within a warp where only the first
2001 /// 'n' (n <= WARPSIZE) lanes are active. It is typically used when the
2002 /// number of OpenMP threads in a parallel region is not a multiple of
2003 /// WARPSIZE. The algorithm is implemented in the runtime as follows:
2004 ///
2005 /// void
2006 /// contiguous_partial_reduce(void *reduce_data,
2007 /// kmp_ShuffleReductFctPtr ShuffleReduceFn,
2008 /// int size, int lane_id) {
2009 /// int curr_size;
2010 /// int offset;
2011 /// curr_size = size;
2012 /// mask = curr_size/2;
2013 /// while (offset>0) {
2014 /// ShuffleReduceFn(reduce_data, lane_id, offset, 1);
2015 /// curr_size = (curr_size+1)/2;
2016 /// offset = curr_size/2;
2017 /// }
2018 /// }
2019 ///
2020 /// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
2021 ///
2022 /// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
2023 /// if (lane_id < offset)
2024 /// reduce_elem = reduce_elem REDUCE_OP remote_elem
2025 /// else
2026 /// reduce_elem = remote_elem
2027 ///
2028 /// This algorithm assumes that the data to be reduced are located in a
2029 /// contiguous subset of lanes starting from the first. When there is
2030 /// an odd number of active lanes, the data in the last lane is not
2031 /// aggregated with any other lane's dat but is instead copied over.
2032 ///
2033 /// Dispersed Partial Warp Reduction
2034 ///
2035 /// This algorithm is used within a warp when any discontiguous subset of
2036 /// lanes are active. It is used to implement the reduction operation
2037 /// across lanes in an OpenMP simd region or in a nested parallel region.
2038 ///
2039 /// void
2040 /// dispersed_partial_reduce(void *reduce_data,
2041 /// kmp_ShuffleReductFctPtr ShuffleReduceFn) {
2042 /// int size, remote_id;
2043 /// int logical_lane_id = number_of_active_lanes_before_me() * 2;
2044 /// do {
2045 /// remote_id = next_active_lane_id_right_after_me();
2046 /// # the above function returns 0 of no active lane
2047 /// # is present right after the current lane.
2048 /// size = number_of_active_lanes_in_this_warp();
2049 /// logical_lane_id /= 2;
2050 /// ShuffleReduceFn(reduce_data, logical_lane_id,
2051 /// remote_id-1-threadIdx.x, 2);
2052 /// } while (logical_lane_id % 2 == 0 && size > 1);
2053 /// }
2054 ///
2055 /// There is no assumption made about the initial state of the reduction.
2056 /// Any number of lanes (>=1) could be active at any position. The reduction
2057 /// result is returned in the first active lane.
2058 ///
2059 /// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
2060 ///
2061 /// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
2062 /// if (lane_id % 2 == 0 && offset > 0)
2063 /// reduce_elem = reduce_elem REDUCE_OP remote_elem
2064 /// else
2065 /// reduce_elem = remote_elem
2066 ///
2067 ///
2068 /// Intra-Team Reduction
2069 ///
2070 /// This function, as implemented in the runtime call
2071 /// '__kmpc_nvptx_parallel_reduce_nowait_v2', aggregates data across OpenMP
2072 /// threads in a team. It first reduces within a warp using the
2073 /// aforementioned algorithms. We then proceed to gather all such
2074 /// reduced values at the first warp.
2075 ///
2076 /// The runtime makes use of the function 'InterWarpCpyFn', which copies
2077 /// data from each of the "warp master" (zeroth lane of each warp, where
2078 /// warp-reduced data is held) to the zeroth warp. This step reduces (in
2079 /// a mathematical sense) the problem of reduction across warp masters in
2080 /// a block to the problem of warp reduction.
2081 ///
2082 ///
2083 /// Inter-Team Reduction
2084 ///
2085 /// Once a team has reduced its data to a single value, it is stored in
2086 /// a global scratchpad array. Since each team has a distinct slot, this
2087 /// can be done without locking.
2088 ///
2089 /// The last team to write to the scratchpad array proceeds to reduce the
2090 /// scratchpad array. One or more workers in the last team use the helper
2091 /// 'loadAndReduceDataFn' to load and reduce values from the array, i.e.,
2092 /// the k'th worker reduces every k'th element.
2093 ///
2094 /// Finally, a call is made to '__kmpc_nvptx_parallel_reduce_nowait_v2' to
2095 /// reduce across workers and compute a globally reduced value.
2096 ///
2097 /// \param Loc The location where the reduction was
2098 /// encountered. Must be within the associate
2099 /// directive and after the last local access to the
2100 /// reduction variables.
2101 /// \param AllocaIP An insertion point suitable for allocas usable
2102 /// in reductions.
2103 /// \param CodeGenIP An insertion point suitable for code
2104 /// generation.
2105 /// \param ReductionInfos A list of info on each reduction
2106 /// variable.
2107 /// \param IsNoWait Optional flag set if the reduction is
2108 /// marked as nowait.
2109 /// \param IsByRef For each reduction clause, whether the reduction is by-ref.
2110 /// \param IsTeamsReduction Optional flag set if it is a teams
2111 /// reduction.
2112 /// \param GridValue Optional GPU grid value.
2113 /// \param ReductionBufNum Optional OpenMPCUDAReductionBufNumValue to be
2114 /// used for teams reduction.
2115 /// \param SrcLocInfo Source location information global.
2116 LLVM_ABI InsertPointOrErrorTy createReductionsGPU(
2117 const LocationDescription &Loc, InsertPointTy AllocaIP,
2118 InsertPointTy CodeGenIP, ArrayRef<ReductionInfo> ReductionInfos,
2119 ArrayRef<bool> IsByRef, bool IsNoWait = false,
2120 bool IsTeamsReduction = false,
2121 ReductionGenCBKind ReductionGenCBKind = ReductionGenCBKind::MLIR,
2122 std::optional<omp::GV> GridValue = {}, unsigned ReductionBufNum = 1024,
2123 Value *SrcLocInfo = nullptr);
2124
2125 // TODO: provide atomic and non-atomic reduction generators for reduction
2126 // operators defined by the OpenMP specification.
2127
2128 /// Generator for '#omp reduction'.
2129 ///
2130 /// Emits the IR instructing the runtime to perform the specific kind of
2131 /// reductions. Expects reduction variables to have been privatized and
2132 /// initialized to reduction-neutral values separately. Emits the calls to
2133 /// runtime functions as well as the reduction function and the basic blocks
2134 /// performing the reduction atomically and non-atomically.
2135 ///
2136 /// The code emitted for the following:
2137 ///
2138 /// \code
2139 /// type var_1;
2140 /// type var_2;
2141 /// #pragma omp <directive> reduction(reduction-op:var_1,var_2)
2142 /// /* body */;
2143 /// \endcode
2144 ///
2145 /// corresponds to the following sketch.
2146 ///
2147 /// \code
2148 /// void _outlined_par() {
2149 /// // N is the number of different reductions.
2150 /// void *red_array[] = {privatized_var_1, privatized_var_2, ...};
2151 /// switch(__kmpc_reduce(..., N, /*size of data in red array*/, red_array,
2152 /// _omp_reduction_func,
2153 /// _gomp_critical_user.reduction.var)) {
2154 /// case 1: {
2155 /// var_1 = var_1 <reduction-op> privatized_var_1;
2156 /// var_2 = var_2 <reduction-op> privatized_var_2;
2157 /// // ...
2158 /// __kmpc_end_reduce(...);
2159 /// break;
2160 /// }
2161 /// case 2: {
2162 /// _Atomic<ReductionOp>(var_1, privatized_var_1);
2163 /// _Atomic<ReductionOp>(var_2, privatized_var_2);
2164 /// // ...
2165 /// break;
2166 /// }
2167 /// default: break;
2168 /// }
2169 /// }
2170 ///
2171 /// void _omp_reduction_func(void **lhs, void **rhs) {
2172 /// *(type *)lhs[0] = *(type *)lhs[0] <reduction-op> *(type *)rhs[0];
2173 /// *(type *)lhs[1] = *(type *)lhs[1] <reduction-op> *(type *)rhs[1];
2174 /// // ...
2175 /// }
2176 /// \endcode
2177 ///
2178 /// \param Loc The location where the reduction was
2179 /// encountered. Must be within the associate
2180 /// directive and after the last local access to the
2181 /// reduction variables.
2182 /// \param AllocaIP An insertion point suitable for allocas usable
2183 /// in reductions.
2184 /// \param ReductionInfos A list of info on each reduction variable.
2185 /// \param IsNoWait A flag set if the reduction is marked as nowait.
2186 /// \param IsByRef A flag set if the reduction is using reference
2187 /// or direct value.
2188 /// \param IsTeamsReduction Optional flag set if it is a teams
2189 /// reduction.
2190 LLVM_ABI InsertPointOrErrorTy createReductions(
2191 const LocationDescription &Loc, InsertPointTy AllocaIP,
2192 ArrayRef<ReductionInfo> ReductionInfos, ArrayRef<bool> IsByRef,
2193 bool IsNoWait = false, bool IsTeamsReduction = false);
2194
2195 ///}
2196
2197 /// Return the insertion point used by the underlying IRBuilder.
2198 InsertPointTy getInsertionPoint() { return Builder.saveIP(); }
2199
2200 /// Update the internal location to \p Loc.
2201 bool updateToLocation(const LocationDescription &Loc) {
2202 Builder.restoreIP(Loc.IP);
2203 Builder.SetCurrentDebugLocation(Loc.DL);
2204 return Loc.IP.getBlock() != nullptr;
2205 }
2206
2207 /// Return the function declaration for the runtime function with \p FnID.
2208 LLVM_ABI FunctionCallee getOrCreateRuntimeFunction(Module &M,
2209 omp::RuntimeFunction FnID);
2210
2211 LLVM_ABI Function *getOrCreateRuntimeFunctionPtr(omp::RuntimeFunction FnID);
2212
2213 CallInst *createRuntimeFunctionCall(FunctionCallee Callee,
2214 ArrayRef<Value *> Args,
2215 StringRef Name = "");
2216
2217 /// Return the (LLVM-IR) string describing the source location \p LocStr.
2218 LLVM_ABI Constant *getOrCreateSrcLocStr(StringRef LocStr,
2219 uint32_t &SrcLocStrSize);
2220
2221 /// Return the (LLVM-IR) string describing the default source location.
2222 LLVM_ABI Constant *getOrCreateDefaultSrcLocStr(uint32_t &SrcLocStrSize);
2223
2224 /// Return the (LLVM-IR) string describing the source location identified by
2225 /// the arguments.
2226 LLVM_ABI Constant *getOrCreateSrcLocStr(StringRef FunctionName,
2227 StringRef FileName, unsigned Line,
2228 unsigned Column,
2229 uint32_t &SrcLocStrSize);
2230
2231 /// Return the (LLVM-IR) string describing the DebugLoc \p DL. Use \p F as
2232 /// fallback if \p DL does not specify the function name.
2233 LLVM_ABI Constant *getOrCreateSrcLocStr(DebugLoc DL, uint32_t &SrcLocStrSize,
2234 Function *F = nullptr);
2235
2236 /// Return the (LLVM-IR) string describing the source location \p Loc.
2237 LLVM_ABI Constant *getOrCreateSrcLocStr(const LocationDescription &Loc,
2238 uint32_t &SrcLocStrSize);
2239
2240 /// Return an ident_t* encoding the source location \p SrcLocStr and \p Flags.
2241 /// TODO: Create a enum class for the Reserve2Flags
2242 LLVM_ABI Constant *getOrCreateIdent(Constant *SrcLocStr,
2243 uint32_t SrcLocStrSize,
2244 omp::IdentFlag Flags = omp::IdentFlag(0),
2245 unsigned Reserve2Flags = 0);
2246
2247 /// Create a hidden global flag \p Name in the module with initial value \p
2248 /// Value.
2249 LLVM_ABI GlobalValue *createGlobalFlag(unsigned Value, StringRef Name);
2250
2251 /// Emit the llvm.used metadata.
2252 LLVM_ABI void emitUsed(StringRef Name, ArrayRef<llvm::WeakTrackingVH> List);
2253
2254 /// Emit the kernel execution mode.
2255 LLVM_ABI GlobalVariable *
2256 emitKernelExecutionMode(StringRef KernelName, omp::OMPTgtExecModeFlags Mode);
2257
2258 /// Generate control flow and cleanup for cancellation.
2259 ///
2260 /// \param CancelFlag Flag indicating if the cancellation is performed.
2261 /// \param CanceledDirective The kind of directive that is cancled.
2262 /// \param ExitCB Extra code to be generated in the exit block.
2263 ///
2264 /// \return an error, if any were triggered during execution.
2265 LLVM_ABI Error emitCancelationCheckImpl(Value *CancelFlag,
2266 omp::Directive CanceledDirective);
2267
2268 /// Generate a target region entry call.
2269 ///
2270 /// \param Loc The location at which the request originated and is fulfilled.
2271 /// \param AllocaIP The insertion point to be used for alloca instructions.
2272 /// \param Return Return value of the created function returned by reference.
2273 /// \param DeviceID Identifier for the device via the 'device' clause.
2274 /// \param NumTeams Numer of teams for the region via the 'num_teams' clause
2275 /// or 0 if unspecified and -1 if there is no 'teams' clause.
2276 /// \param NumThreads Number of threads via the 'thread_limit' clause.
2277 /// \param HostPtr Pointer to the host-side pointer of the target kernel.
2278 /// \param KernelArgs Array of arguments to the kernel.
2279 LLVM_ABI InsertPointTy emitTargetKernel(const LocationDescription &Loc,
2280 InsertPointTy AllocaIP,
2281 Value *&Return, Value *Ident,
2282 Value *DeviceID, Value *NumTeams,
2283 Value *NumThreads, Value *HostPtr,
2284 ArrayRef<Value *> KernelArgs);
2285
2286 /// Generate a flush runtime call.
2287 ///
2288 /// \param Loc The location at which the request originated and is fulfilled.
2289 LLVM_ABI void emitFlush(const LocationDescription &Loc);
2290
2291 /// The finalization stack made up of finalize callbacks currently in-flight,
2292 /// wrapped into FinalizationInfo objects that reference also the finalization
2293 /// target block and the kind of cancellable directive.
2294 SmallVector<FinalizationInfo, 8> FinalizationStack;
2295
2296 /// Return true if the last entry in the finalization stack is of kind \p DK
2297 /// and cancellable.
2298 bool isLastFinalizationInfoCancellable(omp::Directive DK) {
2299 return !FinalizationStack.empty() &&
2300 FinalizationStack.back().IsCancellable &&
2301 FinalizationStack.back().DK == DK;
2302 }
2303
2304 /// Generate a taskwait runtime call.
2305 ///
2306 /// \param Loc The location at which the request originated and is fulfilled.
2307 LLVM_ABI void emitTaskwaitImpl(const LocationDescription &Loc);
2308
2309 /// Generate a taskyield runtime call.
2310 ///
2311 /// \param Loc The location at which the request originated and is fulfilled.
2312 LLVM_ABI void emitTaskyieldImpl(const LocationDescription &Loc);
2313
2314 /// Return the current thread ID.
2315 ///
2316 /// \param Ident The ident (ident_t*) describing the query origin.
2317 LLVM_ABI Value *getOrCreateThreadID(Value *Ident);
2318
2319 /// The OpenMPIRBuilder Configuration
2320 OpenMPIRBuilderConfig Config;
2321
2322 /// The underlying LLVM-IR module
2323 Module &M;
2324
2325 /// The LLVM-IR Builder used to create IR.
2326 IRBuilder<> Builder;
2327
2328 /// Map to remember source location strings
2329 StringMap<Constant *> SrcLocStrMap;
2330
2331 /// Map to remember existing ident_t*.
2332 DenseMap<std::pair<Constant *, uint64_t>, Constant *> IdentMap;
2333
2334 /// Info manager to keep track of target regions.
2335 OffloadEntriesInfoManager OffloadInfoManager;
2336
2337 /// The target triple of the underlying module.
2338 const Triple T;
2339
2340 /// Helper that contains information about regions we need to outline
2341 /// during finalization.
2342 struct OutlineInfo {
2343 using PostOutlineCBTy = std::function<void(Function &)>;
2344 PostOutlineCBTy PostOutlineCB;
2345 BasicBlock *EntryBB, *ExitBB, *OuterAllocaBB;
2346 SmallVector<Value *, 2> ExcludeArgsFromAggregate;
2347
2348 /// Collect all blocks in between EntryBB and ExitBB in both the given
2349 /// vector and set.
2350 LLVM_ABI void collectBlocks(SmallPtrSetImpl<BasicBlock *> &BlockSet,
2351 SmallVectorImpl<BasicBlock *> &BlockVector);
2352
2353 /// Return the function that contains the region to be outlined.
2354 Function *getFunction() const { return EntryBB->getParent(); }
2355 };
2356
2357 /// Collection of regions that need to be outlined during finalization.
2358 SmallVector<OutlineInfo, 16> OutlineInfos;
2359
2360 /// A collection of candidate target functions that's constant allocas will
2361 /// attempt to be raised on a call of finalize after all currently enqueued
2362 /// outline info's have been processed.
2363 SmallVector<llvm::Function *, 16> ConstantAllocaRaiseCandidates;
2364
2365 /// Collection of owned canonical loop objects that eventually need to be
2366 /// free'd.
2367 std::forward_list<CanonicalLoopInfo> LoopInfos;
2368
2369 /// Collection of owned ScanInfo objects that eventually need to be free'd.
2370 std::forward_list<ScanInfo> ScanInfos;
2371
2372 /// Add a new region that will be outlined later.
2373 void addOutlineInfo(OutlineInfo &&OI) { OutlineInfos.emplace_back(OI); }
2374
2375 /// An ordered map of auto-generated variables to their unique names.
2376 /// It stores variables with the following names: 1) ".gomp_critical_user_" +
2377 /// <critical_section_name> + ".var" for "omp critical" directives; 2)
2378 /// <mangled_name_for_global_var> + ".cache." for cache for threadprivate
2379 /// variables.
2380 StringMap<GlobalVariable *, BumpPtrAllocator> InternalVars;
2381
2382 /// Computes the size of type in bytes.
2384
2385 // Emit a branch from the current block to the Target block only if
2386 // the current block has a terminator.
2387 LLVM_ABI void emitBranch(BasicBlock *Target);
2388
2389 // If BB has no use then delete it and return. Else place BB after the current
2390 // block, if possible, or else at the end of the function. Also add a branch
2391 // from current block to BB if current block does not have a terminator.
2392 LLVM_ABI void emitBlock(BasicBlock *BB, Function *CurFn,
2393 bool IsFinished = false);
2394
2395 /// Emits code for OpenMP 'if' clause using specified \a BodyGenCallbackTy
2396 /// Here is the logic:
2397 /// if (Cond) {
2398 /// ThenGen();
2399 /// } else {
2400 /// ElseGen();
2401 /// }
2402 ///
2403 /// \return an error, if any were triggered during execution.
2404 LLVM_ABI Error emitIfClause(Value *Cond, BodyGenCallbackTy ThenGen,
2405 BodyGenCallbackTy ElseGen,
2406 InsertPointTy AllocaIP = {});
2407
2408 /// Create the global variable holding the offload mappings information.
2409 LLVM_ABI GlobalVariable *
2410 createOffloadMaptypes(SmallVectorImpl<uint64_t> &Mappings,
2411 std::string VarName);
2412
2413 /// Create the global variable holding the offload names information.
2414 LLVM_ABI GlobalVariable *
2415 createOffloadMapnames(SmallVectorImpl<llvm::Constant *> &Names,
2416 std::string VarName);
2417
2418 struct MapperAllocas {
2419 AllocaInst *ArgsBase = nullptr;
2420 AllocaInst *Args = nullptr;
2421 AllocaInst *ArgSizes = nullptr;
2422 };
2423
2424 /// Create the allocas instruction used in call to mapper functions.
2425 LLVM_ABI void createMapperAllocas(const LocationDescription &Loc,
2426 InsertPointTy AllocaIP,
2427 unsigned NumOperands,
2428 struct MapperAllocas &MapperAllocas);
2429
2430 /// Create the call for the target mapper function.
2431 /// \param Loc The source location description.
2432 /// \param MapperFunc Function to be called.
2433 /// \param SrcLocInfo Source location information global.
2434 /// \param MaptypesArg The argument types.
2435 /// \param MapnamesArg The argument names.
2436 /// \param MapperAllocas The AllocaInst used for the call.
2437 /// \param DeviceID Device ID for the call.
2438 /// \param NumOperands Number of operands in the call.
2439 LLVM_ABI void emitMapperCall(const LocationDescription &Loc,
2440 Function *MapperFunc, Value *SrcLocInfo,
2441 Value *MaptypesArg, Value *MapnamesArg,
2442 struct MapperAllocas &MapperAllocas,
2443 int64_t DeviceID, unsigned NumOperands);
2444
2445 /// Container for the arguments used to pass data to the runtime library.
2446 struct TargetDataRTArgs {
2447 /// The array of base pointer passed to the runtime library.
2448 Value *BasePointersArray = nullptr;
2449 /// The array of section pointers passed to the runtime library.
2450 Value *PointersArray = nullptr;
2451 /// The array of sizes passed to the runtime library.
2452 Value *SizesArray = nullptr;
2453 /// The array of map types passed to the runtime library for the beginning
2454 /// of the region or for the entire region if there are no separate map
2455 /// types for the region end.
2456 Value *MapTypesArray = nullptr;
2457 /// The array of map types passed to the runtime library for the end of the
2458 /// region, or nullptr if there are no separate map types for the region
2459 /// end.
2460 Value *MapTypesArrayEnd = nullptr;
2461 /// The array of user-defined mappers passed to the runtime library.
2462 Value *MappersArray = nullptr;
2463 /// The array of original declaration names of mapped pointers sent to the
2464 /// runtime library for debugging
2465 Value *MapNamesArray = nullptr;
2466
2467 explicit TargetDataRTArgs() = default;
2468 explicit TargetDataRTArgs(Value *BasePointersArray, Value *PointersArray,
2469 Value *SizesArray, Value *MapTypesArray,
2470 Value *MapTypesArrayEnd, Value *MappersArray,
2471 Value *MapNamesArray)
2472 : BasePointersArray(BasePointersArray), PointersArray(PointersArray),
2473 SizesArray(SizesArray), MapTypesArray(MapTypesArray),
2474 MapTypesArrayEnd(MapTypesArrayEnd), MappersArray(MappersArray),
2475 MapNamesArray(MapNamesArray) {}
2476 };
2477
2478 /// Container to pass the default attributes with which a kernel must be
2479 /// launched, used to set kernel attributes and populate associated static
2480 /// structures.
2481 ///
2482 /// For max values, < 0 means unset, == 0 means set but unknown at compile
2483 /// time. The number of max values will be 1 except for the case where
2484 /// ompx_bare is set.
2485 struct TargetKernelDefaultAttrs {
2486 omp::OMPTgtExecModeFlags ExecFlags =
2487 omp::OMPTgtExecModeFlags::OMP_TGT_EXEC_MODE_GENERIC;
2488 SmallVector<int32_t, 3> MaxTeams = {-1};
2489 int32_t MinTeams = 1;
2490 SmallVector<int32_t, 3> MaxThreads = {-1};
2491 int32_t MinThreads = 1;
2492 int32_t ReductionDataSize = 0;
2493 int32_t ReductionBufferLength = 0;
2494 };
2495
2496 /// Container to pass LLVM IR runtime values or constants related to the
2497 /// number of teams and threads with which the kernel must be launched, as
2498 /// well as the trip count of the loop, if it is an SPMD or Generic-SPMD
2499 /// kernel. These must be defined in the host prior to the call to the kernel
2500 /// launch OpenMP RTL function.
2501 struct TargetKernelRuntimeAttrs {
2502 SmallVector<Value *, 3> MaxTeams = {nullptr};
2503 Value *MinTeams = nullptr;
2504 SmallVector<Value *, 3> TargetThreadLimit = {nullptr};
2505 SmallVector<Value *, 3> TeamsThreadLimit = {nullptr};
2506
2507 /// 'parallel' construct 'num_threads' clause value, if present and it is an
2508 /// SPMD kernel.
2509 Value *MaxThreads = nullptr;
2510
2511 /// Total number of iterations of the SPMD or Generic-SPMD kernel or null if
2512 /// it is a generic kernel.
2513 Value *LoopTripCount = nullptr;
2514 };
2515
2516 /// Data structure that contains the needed information to construct the
2517 /// kernel args vector.
2518 struct TargetKernelArgs {
2519 /// Number of arguments passed to the runtime library.
2520 unsigned NumTargetItems = 0;
2521 /// Arguments passed to the runtime library
2522 TargetDataRTArgs RTArgs;
2523 /// The number of iterations
2524 Value *NumIterations = nullptr;
2525 /// The number of teams.
2526 ArrayRef<Value *> NumTeams;
2527 /// The number of threads.
2528 ArrayRef<Value *> NumThreads;
2529 /// The size of the dynamic shared memory.
2530 Value *DynCGroupMem = nullptr;
2531 /// True if the kernel has 'no wait' clause.
2532 bool HasNoWait = false;
2533 /// The fallback mechanism for the shared memory.
2534 omp::OMPDynGroupprivateFallbackType DynCGroupMemFallback =
2535 omp::OMPDynGroupprivateFallbackType::Abort;
2536
2537 // Constructors for TargetKernelArgs.
2538 TargetKernelArgs() = default;
2539 TargetKernelArgs(unsigned NumTargetItems, TargetDataRTArgs RTArgs,
2540 Value *NumIterations, ArrayRef<Value *> NumTeams,
2541 ArrayRef<Value *> NumThreads, Value *DynCGroupMem,
2542 bool HasNoWait,
2543 omp::OMPDynGroupprivateFallbackType DynCGroupMemFallback)
2544 : NumTargetItems(NumTargetItems), RTArgs(RTArgs),
2545 NumIterations(NumIterations), NumTeams(NumTeams),
2546 NumThreads(NumThreads), DynCGroupMem(DynCGroupMem),
2547 HasNoWait(HasNoWait), DynCGroupMemFallback(DynCGroupMemFallback) {}
2548 };
2549
2550 /// Create the kernel args vector used by emitTargetKernel. This function
2551 /// creates various constant values that are used in the resulting args
2552 /// vector.
2553 LLVM_ABI static void getKernelArgsVector(TargetKernelArgs &KernelArgs,
2554 IRBuilderBase &Builder,
2555 SmallVector<Value *> &ArgsVector);
2556
2557 /// Struct that keeps the information that should be kept throughout
2558 /// a 'target data' region.
2559 class TargetDataInfo {
2560 /// Set to true if device pointer information have to be obtained.
2561 bool RequiresDevicePointerInfo = false;
2562 /// Set to true if Clang emits separate runtime calls for the beginning and
2563 /// end of the region. These calls might have separate map type arrays.
2564 bool SeparateBeginEndCalls = false;
2565
2566 public:
2567 TargetDataRTArgs RTArgs;
2568
2569 SmallMapVector<const Value *, std::pair<Value *, Value *>, 4>
2570 DevicePtrInfoMap;
2571
2572 /// Indicate whether any user-defined mapper exists.
2573 bool HasMapper = false;
2574 /// The total number of pointers passed to the runtime library.
2575 unsigned NumberOfPtrs = 0u;
2576
2577 bool EmitDebug = false;
2578
2579 /// Whether the `target ... data` directive has a `nowait` clause.
2580 bool HasNoWait = false;
2581
2582 explicit TargetDataInfo() = default;
2583 explicit TargetDataInfo(bool RequiresDevicePointerInfo,
2584 bool SeparateBeginEndCalls)
2585 : RequiresDevicePointerInfo(RequiresDevicePointerInfo),
2586 SeparateBeginEndCalls(SeparateBeginEndCalls) {}
2587 /// Clear information about the data arrays.
2588 void clearArrayInfo() {
2589 RTArgs = TargetDataRTArgs();
2590 HasMapper = false;
2591 NumberOfPtrs = 0u;
2592 }
2593 /// Return true if the current target data information has valid arrays.
2594 bool isValid() {
2595 return RTArgs.BasePointersArray && RTArgs.PointersArray &&
2596 RTArgs.SizesArray && RTArgs.MapTypesArray &&
2597 (!HasMapper || RTArgs.MappersArray) && NumberOfPtrs;
2598 }
2599 bool requiresDevicePointerInfo() { return RequiresDevicePointerInfo; }
2600 bool separateBeginEndCalls() { return SeparateBeginEndCalls; }
2601 };
2602
2603 enum class DeviceInfoTy { None, Pointer, Address };
2604 using MapValuesArrayTy = SmallVector<Value *, 4>;
2605 using MapDeviceInfoArrayTy = SmallVector<DeviceInfoTy, 4>;
2606 using MapFlagsArrayTy = SmallVector<omp::OpenMPOffloadMappingFlags, 4>;
2607 using MapNamesArrayTy = SmallVector<Constant *, 4>;
2608 using MapDimArrayTy = SmallVector<uint64_t, 4>;
2609 using MapNonContiguousArrayTy = SmallVector<MapValuesArrayTy, 4>;
2610
2611 /// This structure contains combined information generated for mappable
2612 /// clauses, including base pointers, pointers, sizes, map types, user-defined
2613 /// mappers, and non-contiguous information.
2614 struct MapInfosTy {
2615 struct StructNonContiguousInfo {
2616 bool IsNonContiguous = false;
2617 MapDimArrayTy Dims;
2618 MapNonContiguousArrayTy Offsets;
2619 MapNonContiguousArrayTy Counts;
2620 MapNonContiguousArrayTy Strides;
2621 };
2622 MapValuesArrayTy BasePointers;
2623 MapValuesArrayTy Pointers;
2624 MapDeviceInfoArrayTy DevicePointers;
2625 MapValuesArrayTy Sizes;
2626 MapFlagsArrayTy Types;
2627 MapNamesArrayTy Names;
2628 StructNonContiguousInfo NonContigInfo;
2629
2630 /// Append arrays in \a CurInfo.
2631 void append(MapInfosTy &CurInfo) {
2632 BasePointers.append(CurInfo.BasePointers.begin(),
2633 CurInfo.BasePointers.end());
2634 Pointers.append(CurInfo.Pointers.begin(), CurInfo.Pointers.end());
2635 DevicePointers.append(CurInfo.DevicePointers.begin(),
2636 CurInfo.DevicePointers.end());
2637 Sizes.append(CurInfo.Sizes.begin(), CurInfo.Sizes.end());
2638 Types.append(CurInfo.Types.begin(), CurInfo.Types.end());
2639 Names.append(CurInfo.Names.begin(), CurInfo.Names.end());
2640 NonContigInfo.Dims.append(CurInfo.NonContigInfo.Dims.begin(),
2641 CurInfo.NonContigInfo.Dims.end());
2642 NonContigInfo.Offsets.append(CurInfo.NonContigInfo.Offsets.begin(),
2643 CurInfo.NonContigInfo.Offsets.end());
2644 NonContigInfo.Counts.append(CurInfo.NonContigInfo.Counts.begin(),
2645 CurInfo.NonContigInfo.Counts.end());
2646 NonContigInfo.Strides.append(CurInfo.NonContigInfo.Strides.begin(),
2647 CurInfo.NonContigInfo.Strides.end());
2648 }
2649 };
2650 using MapInfosOrErrorTy = Expected<MapInfosTy &>;
2651
2652 /// Callback function type for functions emitting the host fallback code that
2653 /// is executed when the kernel launch fails. It takes an insertion point as
2654 /// parameter where the code should be emitted. It returns an insertion point
2655 /// that points right after after the emitted code.
2656 using EmitFallbackCallbackTy =
2657 function_ref<InsertPointOrErrorTy(InsertPointTy)>;
2658
2659 // Callback function type for emitting and fetching user defined custom
2660 // mappers.
2661 using CustomMapperCallbackTy =
2662 function_ref<Expected<Function *>(unsigned int)>;
2663
2664 /// Generate a target region entry call and host fallback call.
2665 ///
2666 /// \param Loc The location at which the request originated and is fulfilled.
2667 /// \param OutlinedFnID The ooulined function ID.
2668 /// \param EmitTargetCallFallbackCB Call back function to generate host
2669 /// fallback code.
2670 /// \param Args Data structure holding information about the kernel arguments.
2671 /// \param DeviceID Identifier for the device via the 'device' clause.
2672 /// \param RTLoc Source location identifier
2673 /// \param AllocaIP The insertion point to be used for alloca instructions.
2674 LLVM_ABI InsertPointOrErrorTy emitKernelLaunch(
2675 const LocationDescription &Loc, Value *OutlinedFnID,
2676 EmitFallbackCallbackTy EmitTargetCallFallbackCB, TargetKernelArgs &Args,
2677 Value *DeviceID, Value *RTLoc, InsertPointTy AllocaIP);
2678
2679 /// Callback type for generating the bodies of device directives that require
2680 /// outer target tasks (e.g. in case of having `nowait` or `depend` clauses).
2681 ///
2682 /// \param DeviceID The ID of the device on which the target region will
2683 /// execute.
2684 /// \param RTLoc Source location identifier
2685 /// \Param TargetTaskAllocaIP Insertion point for the alloca block of the
2686 /// generated task.
2687 ///
2688 /// \return an error, if any were triggered during execution.
2689 using TargetTaskBodyCallbackTy =
2690 function_ref<Error(Value *DeviceID, Value *RTLoc,
2691 IRBuilderBase::InsertPoint TargetTaskAllocaIP)>;
2692
2693 /// Generate a target-task for the target construct
2694 ///
2695 /// \param TaskBodyCB Callback to generate the actual body of the target task.
2696 /// \param DeviceID Identifier for the device via the 'device' clause.
2697 /// \param RTLoc Source location identifier
2698 /// \param AllocaIP The insertion point to be used for alloca instructions.
2699 /// \param Dependencies Vector of DependData objects holding information of
2700 /// dependencies as specified by the 'depend' clause.
2701 /// \param HasNoWait True if the target construct had 'nowait' on it, false
2702 /// otherwise
2703 LLVM_ABI InsertPointOrErrorTy emitTargetTask(
2704 TargetTaskBodyCallbackTy TaskBodyCB, Value *DeviceID, Value *RTLoc,
2705 OpenMPIRBuilder::InsertPointTy AllocaIP,
2706 const SmallVector<llvm::OpenMPIRBuilder::DependData> &Dependencies,
2707 const TargetDataRTArgs &RTArgs, bool HasNoWait);
2708
2709 /// Emit the arguments to be passed to the runtime library based on the
2710 /// arrays of base pointers, pointers, sizes, map types, and mappers. If
2711 /// ForEndCall, emit map types to be passed for the end of the region instead
2712 /// of the beginning.
2713 LLVM_ABI void emitOffloadingArraysArgument(
2714 IRBuilderBase &Builder, OpenMPIRBuilder::TargetDataRTArgs &RTArgs,
2715 OpenMPIRBuilder::TargetDataInfo &Info, bool ForEndCall = false);
2716
2717 /// Emit an array of struct descriptors to be assigned to the offload args.
2718 LLVM_ABI void emitNonContiguousDescriptor(InsertPointTy AllocaIP,
2719 InsertPointTy CodeGenIP,
2720 MapInfosTy &CombinedInfo,
2721 TargetDataInfo &Info);
2722
2723 /// Emit the arrays used to pass the captures and map information to the
2724 /// offloading runtime library. If there is no map or capture information,
2725 /// return nullptr by reference. Accepts a reference to a MapInfosTy object
2726 /// that contains information generated for mappable clauses,
2727 /// including base pointers, pointers, sizes, map types, user-defined mappers.
2728 LLVM_ABI Error emitOffloadingArrays(
2729 InsertPointTy AllocaIP, InsertPointTy CodeGenIP, MapInfosTy &CombinedInfo,
2730 TargetDataInfo &Info, CustomMapperCallbackTy CustomMapperCB,
2731 bool IsNonContiguous = false,
2732 function_ref<void(unsigned int, Value *)> DeviceAddrCB = nullptr);
2733
2734 /// Allocates memory for and populates the arrays required for offloading
2735 /// (offload_{baseptrs|ptrs|mappers|sizes|maptypes|mapnames}). Then, it
2736 /// emits their base addresses as arguments to be passed to the runtime
2737 /// library. In essence, this function is a combination of
2738 /// emitOffloadingArrays and emitOffloadingArraysArgument and should arguably
2739 /// be preferred by clients of OpenMPIRBuilder.
2740 LLVM_ABI Error emitOffloadingArraysAndArgs(
2741 InsertPointTy AllocaIP, InsertPointTy CodeGenIP, TargetDataInfo &Info,
2742 TargetDataRTArgs &RTArgs, MapInfosTy &CombinedInfo,
2743 CustomMapperCallbackTy CustomMapperCB, bool IsNonContiguous = false,
2744 bool ForEndCall = false,
2745 function_ref<void(unsigned int, Value *)> DeviceAddrCB = nullptr);
2746
2747 /// Creates offloading entry for the provided entry ID \a ID, address \a
2748 /// Addr, size \a Size, and flags \a Flags.
2749 LLVM_ABI void createOffloadEntry(Constant *ID, Constant *Addr, uint64_t Size,
2750 int32_t Flags, GlobalValue::LinkageTypes,
2751 StringRef Name = "");
2752
2753 /// The kind of errors that can occur when emitting the offload entries and
2754 /// metadata.
2755 enum EmitMetadataErrorKind {
2756 EMIT_MD_TARGET_REGION_ERROR,
2757 EMIT_MD_DECLARE_TARGET_ERROR,
2758 EMIT_MD_GLOBAL_VAR_LINK_ERROR
2759 };
2760
2761 /// Callback function type
2762 using EmitMetadataErrorReportFunctionTy =
2763 std::function<void(EmitMetadataErrorKind, TargetRegionEntryInfo)>;
2764
2765 // Emit the offloading entries and metadata so that the device codegen side
2766 // can easily figure out what to emit. The produced metadata looks like
2767 // this:
2768 //
2769 // !omp_offload.info = !{!1, ...}
2770 //
2771 // We only generate metadata for function that contain target regions.
2772 LLVM_ABI void createOffloadEntriesAndInfoMetadata(
2773 EmitMetadataErrorReportFunctionTy &ErrorReportFunction);
2774
2775public:
2776 /// Generator for __kmpc_copyprivate
2777 ///
2778 /// \param Loc The source location description.
2779 /// \param BufSize Number of elements in the buffer.
2780 /// \param CpyBuf List of pointers to data to be copied.
2781 /// \param CpyFn function to call for copying data.
2782 /// \param DidIt flag variable; 1 for 'single' thread, 0 otherwise.
2783 ///
2784 /// \return The insertion position *after* the CopyPrivate call.
2785
2786 LLVM_ABI InsertPointTy createCopyPrivate(const LocationDescription &Loc,
2787 llvm::Value *BufSize,
2788 llvm::Value *CpyBuf,
2789 llvm::Value *CpyFn,
2790 llvm::Value *DidIt);
2791
2792 /// Generator for '#omp single'
2793 ///
2794 /// \param Loc The source location description.
2795 /// \param BodyGenCB Callback that will generate the region code.
2796 /// \param FiniCB Callback to finalize variable copies.
2797 /// \param IsNowait If false, a barrier is emitted.
2798 /// \param CPVars copyprivate variables.
2799 /// \param CPFuncs copy functions to use for each copyprivate variable.
2800 ///
2801 /// \returns The insertion position *after* the single call.
2802 LLVM_ABI InsertPointOrErrorTy
2803 createSingle(const LocationDescription &Loc, BodyGenCallbackTy BodyGenCB,
2804 FinalizeCallbackTy FiniCB, bool IsNowait,
2805 ArrayRef<llvm::Value *> CPVars = {},
2806 ArrayRef<llvm::Function *> CPFuncs = {});
2807
2808 /// Generator for '#omp master'
2809 ///
2810 /// \param Loc The insert and source location description.
2811 /// \param BodyGenCB Callback that will generate the region code.
2812 /// \param FiniCB Callback to finalize variable copies.
2813 ///
2814 /// \returns The insertion position *after* the master.
2815 LLVM_ABI InsertPointOrErrorTy createMaster(const LocationDescription &Loc,
2816 BodyGenCallbackTy BodyGenCB,
2817 FinalizeCallbackTy FiniCB);
2818
2819 /// Generator for '#omp masked'
2820 ///
2821 /// \param Loc The insert and source location description.
2822 /// \param BodyGenCB Callback that will generate the region code.
2823 /// \param FiniCB Callback to finialize variable copies.
2824 ///
2825 /// \returns The insertion position *after* the masked.
2826 LLVM_ABI InsertPointOrErrorTy createMasked(const LocationDescription &Loc,
2827 BodyGenCallbackTy BodyGenCB,
2828 FinalizeCallbackTy FiniCB,
2829 Value *Filter);
2830
2831 /// This function performs the scan reduction of the values updated in
2832 /// the input phase. The reduction logic needs to be emitted between input
2833 /// and scan loop returned by `CreateCanonicalScanLoops`. The following
2834 /// is the code that is generated, `buffer` and `span` are expected to be
2835 /// populated before executing the generated code.
2836 /// \code{c}
2837 /// for (int k = 0; k != ceil(log2(span)); ++k) {
2838 /// i=pow(2,k)
2839 /// for (size cnt = last_iter; cnt >= i; --cnt)
2840 /// buffer[cnt] op= buffer[cnt-i];
2841 /// }
2842 /// \endcode
2843 /// \param Loc The insert and source location description.
2844 /// \param ReductionInfos Array type containing the ReductionOps.
2845 /// \param ScanRedInfo Pointer to the ScanInfo objected created using
2846 /// `ScanInfoInitialize`.
2847 ///
2848 /// \returns The insertion position *after* the masked.
2849 LLVM_ABI InsertPointOrErrorTy emitScanReduction(
2850 const LocationDescription &Loc,
2851 ArrayRef<llvm::OpenMPIRBuilder::ReductionInfo> ReductionInfos,
2852 ScanInfo *ScanRedInfo);
2853
2854 /// This directive split and directs the control flow to input phase
2855 /// blocks or scan phase blocks based on 1. whether input loop or scan loop
2856 /// is executed, 2. whether exclusive or inclusive scan is used.
2857 ///
2858 /// \param Loc The insert and source location description.
2859 /// \param AllocaIP The IP where the temporary buffer for scan reduction
2860 // needs to be allocated.
2861 /// \param ScanVars Scan Variables.
2862 /// \param IsInclusive Whether it is an inclusive or exclusive scan.
2863 /// \param ScanRedInfo Pointer to the ScanInfo objected created using
2864 /// `ScanInfoInitialize`.
2865 ///
2866 /// \returns The insertion position *after* the scan.
2867 LLVM_ABI InsertPointOrErrorTy createScan(const LocationDescription &Loc,
2868 InsertPointTy AllocaIP,
2869 ArrayRef<llvm::Value *> ScanVars,
2870 ArrayRef<llvm::Type *> ScanVarsType,
2871 bool IsInclusive,
2872 ScanInfo *ScanRedInfo);
2873
2874 /// Generator for '#omp critical'
2875 ///
2876 /// \param Loc The insert and source location description.
2877 /// \param BodyGenCB Callback that will generate the region body code.
2878 /// \param FiniCB Callback to finalize variable copies.
2879 /// \param CriticalName name of the lock used by the critical directive
2880 /// \param HintInst Hint Instruction for hint clause associated with critical
2881 ///
2882 /// \returns The insertion position *after* the critical.
2883 LLVM_ABI InsertPointOrErrorTy createCritical(const LocationDescription &Loc,
2884 BodyGenCallbackTy BodyGenCB,
2885 FinalizeCallbackTy FiniCB,
2886 StringRef CriticalName,
2887 Value *HintInst);
2888
2889 /// Generator for '#omp ordered depend (source | sink)'
2890 ///
2891 /// \param Loc The insert and source location description.
2892 /// \param AllocaIP The insertion point to be used for alloca instructions.
2893 /// \param NumLoops The number of loops in depend clause.
2894 /// \param StoreValues The value will be stored in vector address.
2895 /// \param Name The name of alloca instruction.
2896 /// \param IsDependSource If true, depend source; otherwise, depend sink.
2897 ///
2898 /// \return The insertion position *after* the ordered.
2899 LLVM_ABI InsertPointTy
2900 createOrderedDepend(const LocationDescription &Loc, InsertPointTy AllocaIP,
2901 unsigned NumLoops, ArrayRef<llvm::Value *> StoreValues,
2902 const Twine &Name, bool IsDependSource);
2903
2904 /// Generator for '#omp ordered [threads | simd]'
2905 ///
2906 /// \param Loc The insert and source location description.
2907 /// \param BodyGenCB Callback that will generate the region code.
2908 /// \param FiniCB Callback to finalize variable copies.
2909 /// \param IsThreads If true, with threads clause or without clause;
2910 /// otherwise, with simd clause;
2911 ///
2912 /// \returns The insertion position *after* the ordered.
2913 LLVM_ABI InsertPointOrErrorTy createOrderedThreadsSimd(
2914 const LocationDescription &Loc, BodyGenCallbackTy BodyGenCB,
2915 FinalizeCallbackTy FiniCB, bool IsThreads);
2916
2917 /// Generator for '#omp sections'
2918 ///
2919 /// \param Loc The insert and source location description.
2920 /// \param AllocaIP The insertion points to be used for alloca instructions.
2921 /// \param SectionCBs Callbacks that will generate body of each section.
2922 /// \param PrivCB Callback to copy a given variable (think copy constructor).
2923 /// \param FiniCB Callback to finalize variable copies.
2924 /// \param IsCancellable Flag to indicate a cancellable parallel region.
2925 /// \param IsNowait If true, barrier - to ensure all sections are executed
2926 /// before moving forward will not be generated.
2927 /// \returns The insertion position *after* the sections.
2928 LLVM_ABI InsertPointOrErrorTy
2929 createSections(const LocationDescription &Loc, InsertPointTy AllocaIP,
2930 ArrayRef<StorableBodyGenCallbackTy> SectionCBs,
2931 PrivatizeCallbackTy PrivCB, FinalizeCallbackTy FiniCB,
2932 bool IsCancellable, bool IsNowait);
2933
2934 /// Generator for '#omp section'
2935 ///
2936 /// \param Loc The insert and source location description.
2937 /// \param BodyGenCB Callback that will generate the region body code.
2938 /// \param FiniCB Callback to finalize variable copies.
2939 /// \returns The insertion position *after* the section.
2940 LLVM_ABI InsertPointOrErrorTy createSection(const LocationDescription &Loc,
2941 BodyGenCallbackTy BodyGenCB,
2942 FinalizeCallbackTy FiniCB);
2943
2944 /// Generator for `#omp teams`
2945 ///
2946 /// \param Loc The location where the teams construct was encountered.
2947 /// \param BodyGenCB Callback that will generate the region code.
2948 /// \param NumTeamsLower Lower bound on number of teams. If this is nullptr,
2949 /// it is as if lower bound is specified as equal to upperbound. If
2950 /// this is non-null, then upperbound must also be non-null.
2951 /// \param NumTeamsUpper Upper bound on the number of teams.
2952 /// \param ThreadLimit on the number of threads that may participate in a
2953 /// contention group created by each team.
2954 /// \param IfExpr is the integer argument value of the if condition on the
2955 /// teams clause.
2956 LLVM_ABI InsertPointOrErrorTy createTeams(const LocationDescription &Loc,
2957 BodyGenCallbackTy BodyGenCB,
2958 Value *NumTeamsLower = nullptr,
2959 Value *NumTeamsUpper = nullptr,
2960 Value *ThreadLimit = nullptr,
2961 Value *IfExpr = nullptr);
2962
2963 /// Generator for `#omp distribute`
2964 ///
2965 /// \param Loc The location where the distribute construct was encountered.
2966 /// \param AllocaIP The insertion points to be used for alloca instructions.
2967 /// \param BodyGenCB Callback that will generate the region code.
2968 LLVM_ABI InsertPointOrErrorTy createDistribute(const LocationDescription &Loc,
2969 InsertPointTy AllocaIP,
2970 BodyGenCallbackTy BodyGenCB);
2971
2972 /// Generate conditional branch and relevant BasicBlocks through which private
2973 /// threads copy the 'copyin' variables from Master copy to threadprivate
2974 /// copies.
2975 ///
2976 /// \param IP insertion block for copyin conditional
2977 /// \param MasterVarPtr a pointer to the master variable
2978 /// \param PrivateVarPtr a pointer to the threadprivate variable
2979 /// \param IntPtrTy Pointer size type
2980 /// \param BranchtoEnd Create a branch between the copyin.not.master blocks
2981 // and copy.in.end block
2982 ///
2983 /// \returns The insertion point where copying operation to be emitted.
2984 LLVM_ABI InsertPointTy createCopyinClauseBlocks(InsertPointTy IP,
2985 Value *MasterAddr,
2986 Value *PrivateAddr,
2987 llvm::IntegerType *IntPtrTy,
2988 bool BranchtoEnd = true);
2989
2990 /// Create a runtime call for kmpc_Alloc
2991 ///
2992 /// \param Loc The insert and source location description.
2993 /// \param Size Size of allocated memory space
2994 /// \param Allocator Allocator information instruction
2995 /// \param Name Name of call Instruction for OMP_alloc
2996 ///
2997 /// \returns CallInst to the OMP_Alloc call
2998 LLVM_ABI CallInst *createOMPAlloc(const LocationDescription &Loc, Value *Size,
2999 Value *Allocator, std::string Name = "");
3000
3001 /// Create a runtime call for kmpc_free
3002 ///
3003 /// \param Loc The insert and source location description.
3004 /// \param Addr Address of memory space to be freed
3005 /// \param Allocator Allocator information instruction
3006 /// \param Name Name of call Instruction for OMP_Free
3007 ///
3008 /// \returns CallInst to the OMP_Free call
3009 LLVM_ABI CallInst *createOMPFree(const LocationDescription &Loc, Value *Addr,
3010 Value *Allocator, std::string Name = "");
3011
3012 /// Create a runtime call for kmpc_threadprivate_cached
3013 ///
3014 /// \param Loc The insert and source location description.
3015 /// \param Pointer pointer to data to be cached
3016 /// \param Size size of data to be cached
3017 /// \param Name Name of call Instruction for callinst
3018 ///
3019 /// \returns CallInst to the thread private cache call.
3020 LLVM_ABI CallInst *
3021 createCachedThreadPrivate(const LocationDescription &Loc,
3022 llvm::Value *Pointer, llvm::ConstantInt *Size,
3023 const llvm::Twine &Name = Twine(""));
3024
3025 /// Create a runtime call for __tgt_interop_init
3026 ///
3027 /// \param Loc The insert and source location description.
3028 /// \param InteropVar variable to be allocated
3029 /// \param InteropType type of interop operation
3030 /// \param Device devide to which offloading will occur
3031 /// \param NumDependences number of dependence variables
3032 /// \param DependenceAddress pointer to dependence variables
3033 /// \param HaveNowaitClause does nowait clause exist
3034 ///
3035 /// \returns CallInst to the __tgt_interop_init call
3036 LLVM_ABI CallInst *createOMPInteropInit(const LocationDescription &Loc,
3037 Value *InteropVar,
3038 omp::OMPInteropType InteropType,
3039 Value *Device, Value *NumDependences,
3040 Value *DependenceAddress,
3041 bool HaveNowaitClause);
3042
3043 /// Create a runtime call for __tgt_interop_destroy
3044 ///
3045 /// \param Loc The insert and source location description.
3046 /// \param InteropVar variable to be allocated
3047 /// \param Device devide to which offloading will occur
3048 /// \param NumDependences number of dependence variables
3049 /// \param DependenceAddress pointer to dependence variables
3050 /// \param HaveNowaitClause does nowait clause exist
3051 ///
3052 /// \returns CallInst to the __tgt_interop_destroy call
3053 LLVM_ABI CallInst *createOMPInteropDestroy(const LocationDescription &Loc,
3054 Value *InteropVar, Value *Device,
3055 Value *NumDependences,
3056 Value *DependenceAddress,
3057 bool HaveNowaitClause);
3058
3059 /// Create a runtime call for __tgt_interop_use
3060 ///
3061 /// \param Loc The insert and source location description.
3062 /// \param InteropVar variable to be allocated
3063 /// \param Device devide to which offloading will occur
3064 /// \param NumDependences number of dependence variables
3065 /// \param DependenceAddress pointer to dependence variables
3066 /// \param HaveNowaitClause does nowait clause exist
3067 ///
3068 /// \returns CallInst to the __tgt_interop_use call
3069 LLVM_ABI CallInst *createOMPInteropUse(const LocationDescription &Loc,
3070 Value *InteropVar, Value *Device,
3071 Value *NumDependences,
3072 Value *DependenceAddress,
3073 bool HaveNowaitClause);
3074
3075 /// The `omp target` interface
3076 ///
3077 /// For more information about the usage of this interface,
3078 /// \see openmp/libomptarget/deviceRTLs/common/include/target.h
3079 ///
3080 ///{
3081
3082 /// Create a runtime call for kmpc_target_init
3083 ///
3084 /// \param Loc The insert and source location description.
3085 /// \param Attrs Structure containing the default attributes, including
3086 /// numbers of threads and teams to launch the kernel with.
3087 LLVM_ABI InsertPointTy createTargetInit(
3088 const LocationDescription &Loc,
3089 const llvm::OpenMPIRBuilder::TargetKernelDefaultAttrs &Attrs);
3090
3091 /// Create a runtime call for kmpc_target_deinit
3092 ///
3093 /// \param Loc The insert and source location description.
3094 /// \param TeamsReductionDataSize The maximal size of all the reduction data
3095 /// for teams reduction.
3096 /// \param TeamsReductionBufferLength The number of elements (each of up to
3097 /// \p TeamsReductionDataSize size), in the teams reduction buffer.
3098 LLVM_ABI void createTargetDeinit(const LocationDescription &Loc,
3099 int32_t TeamsReductionDataSize = 0,
3100 int32_t TeamsReductionBufferLength = 1024);
3101
3102 ///}
3103
3104 /// Helpers to read/write kernel annotations from the IR.
3105 ///
3106 ///{
3107
3108 /// Read/write a bounds on threads for \p Kernel. Read will return 0 if none
3109 /// is set.
3110 LLVM_ABI static std::pair<int32_t, int32_t>
3111 readThreadBoundsForKernel(const Triple &T, Function &Kernel);
3112 LLVM_ABI static void writeThreadBoundsForKernel(const Triple &T,
3113 Function &Kernel, int32_t LB,
3114 int32_t UB);
3115
3116 /// Read/write a bounds on teams for \p Kernel. Read will return 0 if none
3117 /// is set.
3118 LLVM_ABI static std::pair<int32_t, int32_t>
3119 readTeamBoundsForKernel(const Triple &T, Function &Kernel);
3120 LLVM_ABI static void writeTeamsForKernel(const Triple &T, Function &Kernel,
3121 int32_t LB, int32_t UB);
3122 ///}
3123
3124private:
3125 // Sets the function attributes expected for the outlined function
3126 void setOutlinedTargetRegionFunctionAttributes(Function *OutlinedFn);
3127
3128 // Creates the function ID/Address for the given outlined function.
3129 // In the case of an embedded device function the address of the function is
3130 // used, in the case of a non-offload function a constant is created.
3131 Constant *createOutlinedFunctionID(Function *OutlinedFn,
3132 StringRef EntryFnIDName);
3133
3134 // Creates the region entry address for the outlined function
3135 Constant *createTargetRegionEntryAddr(Function *OutlinedFunction,
3136 StringRef EntryFnName);
3137
3138public:
3139 /// Functions used to generate a function with the given name.
3140 using FunctionGenCallback =
3141 std::function<Expected<Function *>(StringRef FunctionName)>;
3142
3143 /// Create a unique name for the entry function using the source location
3144 /// information of the current target region. The name will be something like:
3145 ///
3146 /// __omp_offloading_DD_FFFF_PP_lBB[_CC]
3147 ///
3148 /// where DD_FFFF is an ID unique to the file (device and file IDs), PP is the
3149 /// mangled name of the function that encloses the target region and BB is the
3150 /// line number of the target region. CC is a count added when more than one
3151 /// region is located at the same location.
3152 ///
3153 /// If this target outline function is not an offload entry, we don't need to
3154 /// register it. This may happen if it is guarded by an if clause that is
3155 /// false at compile time, or no target archs have been specified.
3156 ///
3157 /// The created target region ID is used by the runtime library to identify
3158 /// the current target region, so it only has to be unique and not
3159 /// necessarily point to anything. It could be the pointer to the outlined
3160 /// function that implements the target region, but we aren't using that so
3161 /// that the compiler doesn't need to keep that, and could therefore inline
3162 /// the host function if proven worthwhile during optimization. In the other
3163 /// hand, if emitting code for the device, the ID has to be the function
3164 /// address so that it can retrieved from the offloading entry and launched
3165 /// by the runtime library. We also mark the outlined function to have
3166 /// external linkage in case we are emitting code for the device, because
3167 /// these functions will be entry points to the device.
3168 ///
3169 /// \param InfoManager The info manager keeping track of the offload entries
3170 /// \param EntryInfo The entry information about the function
3171 /// \param GenerateFunctionCallback The callback function to generate the code
3172 /// \param OutlinedFunction Pointer to the outlined function
3173 /// \param EntryFnIDName Name of the ID o be created
3174 LLVM_ABI Error emitTargetRegionFunction(
3175 TargetRegionEntryInfo &EntryInfo,
3176 FunctionGenCallback &GenerateFunctionCallback, bool IsOffloadEntry,
3177 Function *&OutlinedFn, Constant *&OutlinedFnID);
3178
3179 /// Registers the given function and sets up the attribtues of the function
3180 /// Returns the FunctionID.
3181 ///
3182 /// \param InfoManager The info manager keeping track of the offload entries
3183 /// \param EntryInfo The entry information about the function
3184 /// \param OutlinedFunction Pointer to the outlined function
3185 /// \param EntryFnName Name of the outlined function
3186 /// \param EntryFnIDName Name of the ID o be created
3188 registerTargetRegionFunction(TargetRegionEntryInfo &EntryInfo,
3189 Function *OutlinedFunction,
3190 StringRef EntryFnName, StringRef EntryFnIDName);
3191
3192 /// Type of BodyGen to use for region codegen
3193 ///
3194 /// Priv: If device pointer privatization is required, emit the body of the
3195 /// region here. It will have to be duplicated: with and without
3196 /// privatization.
3197 /// DupNoPriv: If we need device pointer privatization, we need
3198 /// to emit the body of the region with no privatization in the 'else' branch
3199 /// of the conditional.
3200 /// NoPriv: If we don't require privatization of device
3201 /// pointers, we emit the body in between the runtime calls. This avoids
3202 /// duplicating the body code.
3203 enum BodyGenTy { Priv, DupNoPriv, NoPriv };
3204
3205 /// Callback type for creating the map infos for the kernel parameters.
3206 /// \param CodeGenIP is the insertion point where code should be generated,
3207 /// if any.
3208 using GenMapInfoCallbackTy =
3209 function_ref<MapInfosTy &(InsertPointTy CodeGenIP)>;
3210
3211private:
3212 /// Emit the array initialization or deletion portion for user-defined mapper
3213 /// code generation. First, it evaluates whether an array section is mapped
3214 /// and whether the \a MapType instructs to delete this section. If \a IsInit
3215 /// is true, and \a MapType indicates to not delete this array, array
3216 /// initialization code is generated. If \a IsInit is false, and \a MapType
3217 /// indicates to delete this array, array deletion code is generated.
3218 void emitUDMapperArrayInitOrDel(Function *MapperFn, llvm::Value *MapperHandle,
3219 llvm::Value *Base, llvm::Value *Begin,
3220 llvm::Value *Size, llvm::Value *MapType,
3221 llvm::Value *MapName, TypeSize ElementSize,
3222 llvm::BasicBlock *ExitBB, bool IsInit);
3223
3224public:
3225 /// Emit the user-defined mapper function. The code generation follows the
3226 /// pattern in the example below.
3227 /// \code
3228 /// void .omp_mapper.<type_name>.<mapper_id>.(void *rt_mapper_handle,
3229 /// void *base, void *begin,
3230 /// int64_t size, int64_t type,
3231 /// void *name = nullptr) {
3232 /// // Allocate space for an array section first or add a base/begin for
3233 /// // pointer dereference.
3234 /// if ((size > 1 || (base != begin && maptype.IsPtrAndObj)) &&
3235 /// !maptype.IsDelete)
3236 /// __tgt_push_mapper_component(rt_mapper_handle, base, begin,
3237 /// size*sizeof(Ty), clearToFromMember(type));
3238 /// // Map members.
3239 /// for (unsigned i = 0; i < size; i++) {
3240 /// // For each component specified by this mapper:
3241 /// for (auto c : begin[i]->all_components) {
3242 /// if (c.hasMapper())
3243 /// (*c.Mapper())(rt_mapper_handle, c.arg_base, c.arg_begin,
3244 /// c.arg_size,
3245 /// c.arg_type, c.arg_name);
3246 /// else
3247 /// __tgt_push_mapper_component(rt_mapper_handle, c.arg_base,
3248 /// c.arg_begin, c.arg_size, c.arg_type,
3249 /// c.arg_name);
3250 /// }
3251 /// }
3252 /// // Delete the array section.
3253 /// if (size > 1 && maptype.IsDelete)
3254 /// __tgt_push_mapper_component(rt_mapper_handle, base, begin,
3255 /// size*sizeof(Ty), clearToFromMember(type));
3256 /// }
3257 /// \endcode
3258 ///
3259 /// \param PrivAndGenMapInfoCB Callback that privatizes code and populates the
3260 /// MapInfos and returns.
3261 /// \param ElemTy DeclareMapper element type.
3262 /// \param FuncName Optional param to specify mapper function name.
3263 /// \param CustomMapperCB Optional callback to generate code related to
3264 /// custom mappers.
3265 LLVM_ABI Expected<Function *> emitUserDefinedMapper(
3266 function_ref<MapInfosOrErrorTy(
3267 InsertPointTy CodeGenIP, llvm::Value *PtrPHI, llvm::Value *BeginArg)>
3268 PrivAndGenMapInfoCB,
3269 llvm::Type *ElemTy, StringRef FuncName,
3270 CustomMapperCallbackTy CustomMapperCB);
3271
3272 /// Generator for '#omp target data'
3273 ///
3274 /// \param Loc The location where the target data construct was encountered.
3275 /// \param AllocaIP The insertion points to be used for alloca instructions.
3276 /// \param CodeGenIP The insertion point at which the target directive code
3277 /// should be placed.
3278 /// \param IsBegin If true then emits begin mapper call otherwise emits
3279 /// end mapper call.
3280 /// \param DeviceID Stores the DeviceID from the device clause.
3281 /// \param IfCond Value which corresponds to the if clause condition.
3282 /// \param Info Stores all information realted to the Target Data directive.
3283 /// \param GenMapInfoCB Callback that populates the MapInfos and returns.
3284 /// \param CustomMapperCB Callback to generate code related to
3285 /// custom mappers.
3286 /// \param BodyGenCB Optional Callback to generate the region code.
3287 /// \param DeviceAddrCB Optional callback to generate code related to
3288 /// use_device_ptr and use_device_addr.
3289 LLVM_ABI InsertPointOrErrorTy createTargetData(
3290 const LocationDescription &Loc, InsertPointTy AllocaIP,
3291 InsertPointTy CodeGenIP, Value *DeviceID, Value *IfCond,
3292 TargetDataInfo &Info, GenMapInfoCallbackTy GenMapInfoCB,
3293 CustomMapperCallbackTy CustomMapperCB,
3294 omp::RuntimeFunction *MapperFunc = nullptr,
3295 function_ref<InsertPointOrErrorTy(InsertPointTy CodeGenIP,
3296 BodyGenTy BodyGenType)>
3297 BodyGenCB = nullptr,
3298 function_ref<void(unsigned int, Value *)> DeviceAddrCB = nullptr,
3299 Value *SrcLocInfo = nullptr);
3300
3301 using TargetBodyGenCallbackTy = function_ref<InsertPointOrErrorTy(
3302 InsertPointTy AllocaIP, InsertPointTy CodeGenIP)>;
3303
3304 using TargetGenArgAccessorsCallbackTy = function_ref<InsertPointOrErrorTy(
3305 Argument &Arg, Value *Input, Value *&RetVal, InsertPointTy AllocaIP,
3306 InsertPointTy CodeGenIP)>;
3307
3308 /// Generator for '#omp target'
3309 ///
3310 /// \param Loc where the target data construct was encountered.
3311 /// \param IsOffloadEntry whether it is an offload entry.
3312 /// \param CodeGenIP The insertion point where the call to the outlined
3313 /// function should be emitted.
3314 /// \param Info Stores all information realted to the Target directive.
3315 /// \param EntryInfo The entry information about the function.
3316 /// \param DefaultAttrs Structure containing the default attributes, including
3317 /// numbers of threads and teams to launch the kernel with.
3318 /// \param RuntimeAttrs Structure containing the runtime numbers of threads
3319 /// and teams to launch the kernel with.
3320 /// \param IfCond value of the `if` clause.
3321 /// \param Inputs The input values to the region that will be passed.
3322 /// as arguments to the outlined function.
3323 /// \param BodyGenCB Callback that will generate the region code.
3324 /// \param ArgAccessorFuncCB Callback that will generate accessors
3325 /// instructions for passed in target arguments where neccessary
3326 /// \param CustomMapperCB Callback to generate code related to
3327 /// custom mappers.
3328 /// \param Dependencies A vector of DependData objects that carry
3329 /// dependency information as passed in the depend clause
3330 /// \param HasNowait Whether the target construct has a `nowait` clause or
3331 /// not.
3332 /// \param DynCGroupMem The size of the dynamic groupprivate memory for each
3333 /// cgroup.
3334 /// \param DynCGroupMem The fallback mechanism to execute if the requested
3335 /// cgroup memory cannot be provided.
3336 LLVM_ABI InsertPointOrErrorTy createTarget(
3337 const LocationDescription &Loc, bool IsOffloadEntry,
3338 OpenMPIRBuilder::InsertPointTy AllocaIP,
3339 OpenMPIRBuilder::InsertPointTy CodeGenIP, TargetDataInfo &Info,
3340 TargetRegionEntryInfo &EntryInfo,
3341 const TargetKernelDefaultAttrs &DefaultAttrs,
3342 const TargetKernelRuntimeAttrs &RuntimeAttrs, Value *IfCond,
3343 SmallVectorImpl<Value *> &Inputs, GenMapInfoCallbackTy GenMapInfoCB,
3344 TargetBodyGenCallbackTy BodyGenCB,
3345 TargetGenArgAccessorsCallbackTy ArgAccessorFuncCB,
3346 CustomMapperCallbackTy CustomMapperCB,
3347 const SmallVector<DependData> &Dependencies, bool HasNowait = false,
3348 Value *DynCGroupMem = nullptr,
3349 omp::OMPDynGroupprivateFallbackType DynCGroupMemFallback =
3350 omp::OMPDynGroupprivateFallbackType::Abort);
3351
3352 /// Returns __kmpc_for_static_init_* runtime function for the specified
3353 /// size \a IVSize and sign \a IVSigned. Will create a distribute call
3354 /// __kmpc_distribute_static_init* if \a IsGPUDistribute is set.
3355 LLVM_ABI FunctionCallee createForStaticInitFunction(unsigned IVSize,
3356 bool IVSigned,
3357 bool IsGPUDistribute);
3358
3359 /// Returns __kmpc_dispatch_init_* runtime function for the specified
3360 /// size \a IVSize and sign \a IVSigned.
3361 LLVM_ABI FunctionCallee createDispatchInitFunction(unsigned IVSize,
3362 bool IVSigned);
3363
3364 /// Returns __kmpc_dispatch_next_* runtime function for the specified
3365 /// size \a IVSize and sign \a IVSigned.
3366 LLVM_ABI FunctionCallee createDispatchNextFunction(unsigned IVSize,
3367 bool IVSigned);
3368
3369 /// Returns __kmpc_dispatch_fini_* runtime function for the specified
3370 /// size \a IVSize and sign \a IVSigned.
3371 LLVM_ABI FunctionCallee createDispatchFiniFunction(unsigned IVSize,
3372 bool IVSigned);
3373
3374 /// Returns __kmpc_dispatch_deinit runtime function.
3375 LLVM_ABI FunctionCallee createDispatchDeinitFunction();
3376
3377 /// Declarations for LLVM-IR types (simple, array, function and structure) are
3378 /// generated below. Their names are defined and used in OpenMPKinds.def. Here
3379 /// we provide the declarations, the initializeTypes function will provide the
3380 /// values.
3381 ///
3382 ///{
3383#define OMP_TYPE(VarName, InitValue) Type *VarName = nullptr;
3384#define OMP_ARRAY_TYPE(VarName, ElemTy, ArraySize) \
3385 ArrayType *VarName##Ty = nullptr; \
3386 PointerType *VarName##PtrTy = nullptr;
3387#define OMP_FUNCTION_TYPE(VarName, IsVarArg, ReturnType, ...) \
3388 FunctionType *VarName = nullptr; \
3389 PointerType *VarName##Ptr = nullptr;
3390#define OMP_STRUCT_TYPE(VarName, StrName, ...) \
3391 StructType *VarName = nullptr; \
3392 PointerType *VarName##Ptr = nullptr;
3393#include "llvm/Frontend/OpenMP/OMPKinds.def"
3394
3395 ///}
3396
3397private:
3398 /// Create all simple and struct types exposed by the runtime and remember
3399 /// the llvm::PointerTypes of them for easy access later.
3400 void initializeTypes(Module &M);
3401
3402 /// Common interface for generating entry calls for OMP Directives.
3403 /// if the directive has a region/body, It will set the insertion
3404 /// point to the body
3405 ///
3406 /// \param OMPD Directive to generate entry blocks for
3407 /// \param EntryCall Call to the entry OMP Runtime Function
3408 /// \param ExitBB block where the region ends.
3409 /// \param Conditional indicate if the entry call result will be used
3410 /// to evaluate a conditional of whether a thread will execute
3411 /// body code or not.
3412 ///
3413 /// \return The insertion position in exit block
3414 InsertPointTy emitCommonDirectiveEntry(omp::Directive OMPD, Value *EntryCall,
3415 BasicBlock *ExitBB,
3416 bool Conditional = false);
3417
3418 /// Common interface to finalize the region
3419 ///
3420 /// \param OMPD Directive to generate exiting code for
3421 /// \param FinIP Insertion point for emitting Finalization code and exit call.
3422 /// This block must not contain any non-finalization code.
3423 /// \param ExitCall Call to the ending OMP Runtime Function
3424 /// \param HasFinalize indicate if the directive will require finalization
3425 /// and has a finalization callback in the stack that
3426 /// should be called.
3427 ///
3428 /// \return The insertion position in exit block
3429 InsertPointOrErrorTy emitCommonDirectiveExit(omp::Directive OMPD,
3430 InsertPointTy FinIP,
3431 Instruction *ExitCall,
3432 bool HasFinalize = true);
3433
3434 /// Common Interface to generate OMP inlined regions
3435 ///
3436 /// \param OMPD Directive to generate inlined region for
3437 /// \param EntryCall Call to the entry OMP Runtime Function
3438 /// \param ExitCall Call to the ending OMP Runtime Function
3439 /// \param BodyGenCB Body code generation callback.
3440 /// \param FiniCB Finalization Callback. Will be called when finalizing region
3441 /// \param Conditional indicate if the entry call result will be used
3442 /// to evaluate a conditional of whether a thread will execute
3443 /// body code or not.
3444 /// \param HasFinalize indicate if the directive will require finalization
3445 /// and has a finalization callback in the stack that
3446 /// should be called.
3447 /// \param IsCancellable if HasFinalize is set to true, indicate if the
3448 /// the directive should be cancellable.
3449 /// \return The insertion point after the region
3450 InsertPointOrErrorTy
3451 EmitOMPInlinedRegion(omp::Directive OMPD, Instruction *EntryCall,
3452 Instruction *ExitCall, BodyGenCallbackTy BodyGenCB,
3453 FinalizeCallbackTy FiniCB, bool Conditional = false,
3454 bool HasFinalize = true, bool IsCancellable = false);
3455
3456 /// Get the platform-specific name separator.
3457 /// \param Parts different parts of the final name that needs separation
3458 /// \param FirstSeparator First separator used between the initial two
3459 /// parts of the name.
3460 /// \param Separator separator used between all of the rest consecutive
3461 /// parts of the name
3462 static std::string getNameWithSeparators(ArrayRef<StringRef> Parts,
3463 StringRef FirstSeparator,
3464 StringRef Separator);
3465
3466 /// Returns corresponding lock object for the specified critical region
3467 /// name. If the lock object does not exist it is created, otherwise the
3468 /// reference to the existing copy is returned.
3469 /// \param CriticalName Name of the critical region.
3470 ///
3471 Value *getOMPCriticalRegionLock(StringRef CriticalName);
3472
3473 /// Callback type for Atomic Expression update
3474 /// ex:
3475 /// \code{.cpp}
3476 /// unsigned x = 0;
3477 /// #pragma omp atomic update
3478 /// x = Expr(x_old); //Expr() is any legal operation
3479 /// \endcode
3480 ///
3481 /// \param XOld the value of the atomic memory address to use for update
3482 /// \param IRB reference to the IRBuilder to use
3483 ///
3484 /// \returns Value to update X to.
3485 using AtomicUpdateCallbackTy =
3486 const function_ref<Expected<Value *>(Value *XOld, IRBuilder<> &IRB)>;
3487
3488private:
3489 enum AtomicKind { Read, Write, Update, Capture, Compare };
3490
3491 /// Determine whether to emit flush or not
3492 ///
3493 /// \param Loc The insert and source location description.
3494 /// \param AO The required atomic ordering
3495 /// \param AK The OpenMP atomic operation kind used.
3496 ///
3497 /// \returns wether a flush was emitted or not
3498 bool checkAndEmitFlushAfterAtomic(const LocationDescription &Loc,
3499 AtomicOrdering AO, AtomicKind AK);
3500
3501 /// Emit atomic update for constructs: X = X BinOp Expr ,or X = Expr BinOp X
3502 /// For complex Operations: X = UpdateOp(X) => CmpExch X, old_X, UpdateOp(X)
3503 /// Only Scalar data types.
3504 ///
3505 /// \param AllocaIP The insertion point to be used for alloca
3506 /// instructions.
3507 /// \param X The target atomic pointer to be updated
3508 /// \param XElemTy The element type of the atomic pointer.
3509 /// \param Expr The value to update X with.
3510 /// \param AO Atomic ordering of the generated atomic
3511 /// instructions.
3512 /// \param RMWOp The binary operation used for update. If
3513 /// operation is not supported by atomicRMW,
3514 /// or belong to {FADD, FSUB, BAD_BINOP}.
3515 /// Then a `cmpExch` based atomic will be generated.
3516 /// \param UpdateOp Code generator for complex expressions that cannot be
3517 /// expressed through atomicrmw instruction.
3518 /// \param VolatileX true if \a X volatile?
3519 /// \param IsXBinopExpr true if \a X is Left H.S. in Right H.S. part of the
3520 /// update expression, false otherwise.
3521 /// (e.g. true for X = X BinOp Expr)
3522 ///
3523 /// \returns A pair of the old value of X before the update, and the value
3524 /// used for the update.
3525 Expected<std::pair<Value *, Value *>>
3526 emitAtomicUpdate(InsertPointTy AllocaIP, Value *X, Type *XElemTy, Value *Expr,
3527 AtomicOrdering AO, AtomicRMWInst::BinOp RMWOp,
3528 AtomicUpdateCallbackTy &UpdateOp, bool VolatileX,
3529 bool IsXBinopExpr, bool IsIgnoreDenormalMode,
3530 bool IsFineGrainedMemory, bool IsRemoteMemory);
3531
3532 /// Emit the binary op. described by \p RMWOp, using \p Src1 and \p Src2 .
3533 ///
3534 /// \Return The instruction
3535 Value *emitRMWOpAsInstruction(Value *Src1, Value *Src2,
3536 AtomicRMWInst::BinOp RMWOp);
3537
3538 bool IsFinalized;
3539
3540public:
3541 /// a struct to pack relevant information while generating atomic Ops
3542 struct AtomicOpValue {
3543 Value *Var = nullptr;
3544 Type *ElemTy = nullptr;
3545 bool IsSigned = false;
3546 bool IsVolatile = false;
3547 };
3548
3549 /// Emit atomic Read for : V = X --- Only Scalar data types.
3550 ///
3551 /// \param Loc The insert and source location description.
3552 /// \param X The target pointer to be atomically read
3553 /// \param V Memory address where to store atomically read
3554 /// value
3555 /// \param AO Atomic ordering of the generated atomic
3556 /// instructions.
3557 /// \param AllocaIP Insert point for allocas
3558 //
3559 /// \return Insertion point after generated atomic read IR.
3560 LLVM_ABI InsertPointTy createAtomicRead(const LocationDescription &Loc,
3561 AtomicOpValue &X, AtomicOpValue &V,
3562 AtomicOrdering AO,
3563 InsertPointTy AllocaIP);
3564
3565 /// Emit atomic write for : X = Expr --- Only Scalar data types.
3566 ///
3567 /// \param Loc The insert and source location description.
3568 /// \param X The target pointer to be atomically written to
3569 /// \param Expr The value to store.
3570 /// \param AO Atomic ordering of the generated atomic
3571 /// instructions.
3572 /// \param AllocaIP Insert point for allocas
3573 ///
3574 /// \return Insertion point after generated atomic Write IR.
3575 LLVM_ABI InsertPointTy createAtomicWrite(const LocationDescription &Loc,
3576 AtomicOpValue &X, Value *Expr,
3577 AtomicOrdering AO,
3578 InsertPointTy AllocaIP);
3579
3580 /// Emit atomic update for constructs: X = X BinOp Expr ,or X = Expr BinOp X
3581 /// For complex Operations: X = UpdateOp(X) => CmpExch X, old_X, UpdateOp(X)
3582 /// Only Scalar data types.
3583 ///
3584 /// \param Loc The insert and source location description.
3585 /// \param AllocaIP The insertion point to be used for alloca instructions.
3586 /// \param X The target atomic pointer to be updated
3587 /// \param Expr The value to update X with.
3588 /// \param AO Atomic ordering of the generated atomic instructions.
3589 /// \param RMWOp The binary operation used for update. If operation
3590 /// is not supported by atomicRMW, or belong to
3591 /// {FADD, FSUB, BAD_BINOP}. Then a `cmpExch` based
3592 /// atomic will be generated.
3593 /// \param UpdateOp Code generator for complex expressions that cannot be
3594 /// expressed through atomicrmw instruction.
3595 /// \param IsXBinopExpr true if \a X is Left H.S. in Right H.S. part of the
3596 /// update expression, false otherwise.
3597 /// (e.g. true for X = X BinOp Expr)
3598 ///
3599 /// \return Insertion point after generated atomic update IR.
3600 LLVM_ABI InsertPointOrErrorTy createAtomicUpdate(
3601 const LocationDescription &Loc, InsertPointTy AllocaIP, AtomicOpValue &X,
3602 Value *Expr, AtomicOrdering AO, AtomicRMWInst::BinOp RMWOp,
3603 AtomicUpdateCallbackTy &UpdateOp, bool IsXBinopExpr,
3604 bool IsIgnoreDenormalMode = false, bool IsFineGrainedMemory = false,
3605 bool IsRemoteMemory = false);
3606
3607 /// Emit atomic update for constructs: --- Only Scalar data types
3608 /// V = X; X = X BinOp Expr ,
3609 /// X = X BinOp Expr; V = X,
3610 /// V = X; X = Expr BinOp X,
3611 /// X = Expr BinOp X; V = X,
3612 /// V = X; X = UpdateOp(X),
3613 /// X = UpdateOp(X); V = X,
3614 ///
3615 /// \param Loc The insert and source location description.
3616 /// \param AllocaIP The insertion point to be used for alloca instructions.
3617 /// \param X The target atomic pointer to be updated
3618 /// \param V Memory address where to store captured value
3619 /// \param Expr The value to update X with.
3620 /// \param AO Atomic ordering of the generated atomic instructions
3621 /// \param RMWOp The binary operation used for update. If
3622 /// operation is not supported by atomicRMW, or belong to
3623 /// {FADD, FSUB, BAD_BINOP}. Then a cmpExch based
3624 /// atomic will be generated.
3625 /// \param UpdateOp Code generator for complex expressions that cannot be
3626 /// expressed through atomicrmw instruction.
3627 /// \param UpdateExpr true if X is an in place update of the form
3628 /// X = X BinOp Expr or X = Expr BinOp X
3629 /// \param IsXBinopExpr true if X is Left H.S. in Right H.S. part of the
3630 /// update expression, false otherwise.
3631 /// (e.g. true for X = X BinOp Expr)
3632 /// \param IsPostfixUpdate true if original value of 'x' must be stored in
3633 /// 'v', not an updated one.
3634 ///
3635 /// \return Insertion point after generated atomic capture IR.
3636 LLVM_ABI InsertPointOrErrorTy createAtomicCapture(
3637 const LocationDescription &Loc, InsertPointTy AllocaIP, AtomicOpValue &X,
3638 AtomicOpValue &V, Value *Expr, AtomicOrdering AO,
3639 AtomicRMWInst::BinOp RMWOp, AtomicUpdateCallbackTy &UpdateOp,
3640 bool UpdateExpr, bool IsPostfixUpdate, bool IsXBinopExpr,
3641 bool IsIgnoreDenormalMode = false, bool IsFineGrainedMemory = false,
3642 bool IsRemoteMemory = false);
3643
3644 /// Emit atomic compare for constructs: --- Only scalar data types
3645 /// cond-expr-stmt:
3646 /// x = x ordop expr ? expr : x;
3647 /// x = expr ordop x ? expr : x;
3648 /// x = x == e ? d : x;
3649 /// x = e == x ? d : x; (this one is not in the spec)
3650 /// cond-update-stmt:
3651 /// if (x ordop expr) { x = expr; }
3652 /// if (expr ordop x) { x = expr; }
3653 /// if (x == e) { x = d; }
3654 /// if (e == x) { x = d; } (this one is not in the spec)
3655 /// conditional-update-capture-atomic:
3656 /// v = x; cond-update-stmt; (IsPostfixUpdate=true, IsFailOnly=false)
3657 /// cond-update-stmt; v = x; (IsPostfixUpdate=false, IsFailOnly=false)
3658 /// if (x == e) { x = d; } else { v = x; } (IsPostfixUpdate=false,
3659 /// IsFailOnly=true)
3660 /// r = x == e; if (r) { x = d; } (IsPostfixUpdate=false, IsFailOnly=false)
3661 /// r = x == e; if (r) { x = d; } else { v = x; } (IsPostfixUpdate=false,
3662 /// IsFailOnly=true)
3663 ///
3664 /// \param Loc The insert and source location description.
3665 /// \param X The target atomic pointer to be updated.
3666 /// \param V Memory address where to store captured value (for
3667 /// compare capture only).
3668 /// \param R Memory address where to store comparison result
3669 /// (for compare capture with '==' only).
3670 /// \param E The expected value ('e') for forms that use an
3671 /// equality comparison or an expression ('expr') for
3672 /// forms that use 'ordop' (logically an atomic maximum or
3673 /// minimum).
3674 /// \param D The desired value for forms that use an equality
3675 /// comparison. If forms that use 'ordop', it should be
3676 /// \p nullptr.
3677 /// \param AO Atomic ordering of the generated atomic instructions.
3678 /// \param Op Atomic compare operation. It can only be ==, <, or >.
3679 /// \param IsXBinopExpr True if the conditional statement is in the form where
3680 /// x is on LHS. It only matters for < or >.
3681 /// \param IsPostfixUpdate True if original value of 'x' must be stored in
3682 /// 'v', not an updated one (for compare capture
3683 /// only).
3684 /// \param IsFailOnly True if the original value of 'x' is stored to 'v'
3685 /// only when the comparison fails. This is only valid for
3686 /// the case the comparison is '=='.
3687 ///
3688 /// \return Insertion point after generated atomic capture IR.
3689 LLVM_ABI InsertPointTy
3690 createAtomicCompare(const LocationDescription &Loc, AtomicOpValue &X,
3691 AtomicOpValue &V, AtomicOpValue &R, Value *E, Value *D,
3692 AtomicOrdering AO, omp::OMPAtomicCompareOp Op,
3693 bool IsXBinopExpr, bool IsPostfixUpdate, bool IsFailOnly);
3694 LLVM_ABI InsertPointTy createAtomicCompare(
3695 const LocationDescription &Loc, AtomicOpValue &X, AtomicOpValue &V,
3696 AtomicOpValue &R, Value *E, Value *D, AtomicOrdering AO,
3697 omp::OMPAtomicCompareOp Op, bool IsXBinopExpr, bool IsPostfixUpdate,
3698 bool IsFailOnly, AtomicOrdering Failure);
3699
3700 /// Create the control flow structure of a canonical OpenMP loop.
3701 ///
3702 /// The emitted loop will be disconnected, i.e. no edge to the loop's
3703 /// preheader and no terminator in the AfterBB. The OpenMPIRBuilder's
3704 /// IRBuilder location is not preserved.
3705 ///
3706 /// \param DL DebugLoc used for the instructions in the skeleton.
3707 /// \param TripCount Value to be used for the trip count.
3708 /// \param F Function in which to insert the BasicBlocks.
3709 /// \param PreInsertBefore Where to insert BBs that execute before the body,
3710 /// typically the body itself.
3711 /// \param PostInsertBefore Where to insert BBs that execute after the body.
3712 /// \param Name Base name used to derive BB
3713 /// and instruction names.
3714 ///
3715 /// \returns The CanonicalLoopInfo that represents the emitted loop.
3716 LLVM_ABI CanonicalLoopInfo *createLoopSkeleton(DebugLoc DL, Value *TripCount,
3717 Function *F,
3718 BasicBlock *PreInsertBefore,
3719 BasicBlock *PostInsertBefore,
3720 const Twine &Name = {});
3721 /// OMP Offload Info Metadata name string
3722 const std::string ompOffloadInfoName = "omp_offload.info";
3723
3724 /// Loads all the offload entries information from the host IR
3725 /// metadata. This function is only meant to be used with device code
3726 /// generation.
3727 ///
3728 /// \param M Module to load Metadata info from. Module passed maybe
3729 /// loaded from bitcode file, i.e, different from OpenMPIRBuilder::M module.
3730 LLVM_ABI void loadOffloadInfoMetadata(Module &M);
3731
3732 /// Loads all the offload entries information from the host IR
3733 /// metadata read from the file passed in as the HostFilePath argument. This
3734 /// function is only meant to be used with device code generation.
3735 ///
3736 /// \param HostFilePath The path to the host IR file,
3737 /// used to load in offload metadata for the device, allowing host and device
3738 /// to maintain the same metadata mapping.
3739 LLVM_ABI void loadOffloadInfoMetadata(vfs::FileSystem &VFS,
3740 StringRef HostFilePath);
3741
3742 /// Gets (if variable with the given name already exist) or creates
3743 /// internal global variable with the specified Name. The created variable has
3744 /// linkage CommonLinkage by default and is initialized by null value.
3745 /// \param Ty Type of the global variable. If it is exist already the type
3746 /// must be the same.
3747 /// \param Name Name of the variable.
3748 LLVM_ABI GlobalVariable *
3749 getOrCreateInternalVariable(Type *Ty, const StringRef &Name,
3750 std::optional<unsigned> AddressSpace = {});
3751};
3752
3753/// Class to represented the control flow structure of an OpenMP canonical loop.
3754///
3755/// The control-flow structure is standardized for easy consumption by
3756/// directives associated with loops. For instance, the worksharing-loop
3757/// construct may change this control flow such that each loop iteration is
3758/// executed on only one thread. The constraints of a canonical loop in brief
3759/// are:
3760///
3761/// * The number of loop iterations must have been computed before entering the
3762/// loop.
3763///
3764/// * Has an (unsigned) logical induction variable that starts at zero and
3765/// increments by one.
3766///
3767/// * The loop's CFG itself has no side-effects. The OpenMP specification
3768/// itself allows side-effects, but the order in which they happen, including
3769/// how often or whether at all, is unspecified. We expect that the frontend
3770/// will emit those side-effect instructions somewhere (e.g. before the loop)
3771/// such that the CanonicalLoopInfo itself can be side-effect free.
3772///
3773/// Keep in mind that CanonicalLoopInfo is meant to only describe a repeated
3774/// execution of a loop body that satifies these constraints. It does NOT
3775/// represent arbitrary SESE regions that happen to contain a loop. Do not use
3776/// CanonicalLoopInfo for such purposes.
3777///
3778/// The control flow can be described as follows:
3779///
3780/// Preheader
3781/// |
3782/// /-> Header
3783/// | |
3784/// | Cond---\
3785/// | | |
3786/// | Body |
3787/// | | | |
3788/// | <...> |
3789/// | | | |
3790/// \--Latch |
3791/// |
3792/// Exit
3793/// |
3794/// After
3795///
3796/// The loop is thought to start at PreheaderIP (at the Preheader's terminator,
3797/// including) and end at AfterIP (at the After's first instruction, excluding).
3798/// That is, instructions in the Preheader and After blocks (except the
3799/// Preheader's terminator) are out of CanonicalLoopInfo's control and may have
3800/// side-effects. Typically, the Preheader is used to compute the loop's trip
3801/// count. The instructions from BodyIP (at the Body block's first instruction,
3802/// excluding) until the Latch are also considered outside CanonicalLoopInfo's
3803/// control and thus can have side-effects. The body block is the single entry
3804/// point into the loop body, which may contain arbitrary control flow as long
3805/// as all control paths eventually branch to the Latch block.
3806///
3807/// TODO: Consider adding another standardized BasicBlock between Body CFG and
3808/// Latch to guarantee that there is only a single edge to the latch. It would
3809/// make loop transformations easier to not needing to consider multiple
3810/// predecessors of the latch (See redirectAllPredecessorsTo) and would give us
3811/// an equivalant to PreheaderIP, AfterIP and BodyIP for inserting code that
3812/// executes after each body iteration.
3813///
3814/// There must be no loop-carried dependencies through llvm::Values. This is
3815/// equivalant to that the Latch has no PHINode and the Header's only PHINode is
3816/// for the induction variable.
3817///
3818/// All code in Header, Cond, Latch and Exit (plus the terminator of the
3819/// Preheader) are CanonicalLoopInfo's responsibility and their build-up checked
3820/// by assertOK(). They are expected to not be modified unless explicitly
3821/// modifying the CanonicalLoopInfo through a methods that applies a OpenMP
3822/// loop-associated construct such as applyWorkshareLoop, tileLoops, unrollLoop,
3823/// etc. These methods usually invalidate the CanonicalLoopInfo and re-use its
3824/// basic blocks. After invalidation, the CanonicalLoopInfo must not be used
3825/// anymore as its underlying control flow may not exist anymore.
3826/// Loop-transformation methods such as tileLoops, collapseLoops and unrollLoop
3827/// may also return a new CanonicalLoopInfo that can be passed to other
3828/// loop-associated construct implementing methods. These loop-transforming
3829/// methods may either create a new CanonicalLoopInfo usually using
3830/// createLoopSkeleton and invalidate the input CanonicalLoopInfo, or reuse and
3831/// modify one of the input CanonicalLoopInfo and return it as representing the
3832/// modified loop. What is done is an implementation detail of
3833/// transformation-implementing method and callers should always assume that the
3834/// CanonicalLoopInfo passed to it is invalidated and a new object is returned.
3835/// Returned CanonicalLoopInfo have the same structure and guarantees as the one
3836/// created by createCanonicalLoop, such that transforming methods do not have
3837/// to special case where the CanonicalLoopInfo originated from.
3838///
3839/// Generally, methods consuming CanonicalLoopInfo do not need an
3840/// OpenMPIRBuilder::InsertPointTy as argument, but use the locations of the
3841/// CanonicalLoopInfo to insert new or modify existing instructions. Unless
3842/// documented otherwise, methods consuming CanonicalLoopInfo do not invalidate
3843/// any InsertPoint that is outside CanonicalLoopInfo's control. Specifically,
3844/// any InsertPoint in the Preheader, After or Block can still be used after
3845/// calling such a method.
3846///
3847/// TODO: Provide mechanisms for exception handling and cancellation points.
3848///
3849/// Defined outside OpenMPIRBuilder because nested classes cannot be
3850/// forward-declared, e.g. to avoid having to include the entire OMPIRBuilder.h.
3851class CanonicalLoopInfo {
3852 friend class OpenMPIRBuilder;
3853
3854private:
3855 BasicBlock *Header = nullptr;
3856 BasicBlock *Cond = nullptr;
3857 BasicBlock *Latch = nullptr;
3858 BasicBlock *Exit = nullptr;
3859
3860 // Hold the MLIR value for the `lastiter` of the canonical loop.
3861 Value *LastIter = nullptr;
3862
3863 /// Add the control blocks of this loop to \p BBs.
3864 ///
3865 /// This does not include any block from the body, including the one returned
3866 /// by getBody().
3867 ///
3868 /// FIXME: This currently includes the Preheader and After blocks even though
3869 /// their content is (mostly) not under CanonicalLoopInfo's control.
3870 /// Re-evaluated whether this makes sense.
3871 void collectControlBlocks(SmallVectorImpl<BasicBlock *> &BBs);
3872
3873 /// Sets the number of loop iterations to the given value. This value must be
3874 /// valid in the condition block (i.e., defined in the preheader) and is
3875 /// interpreted as an unsigned integer.
3876 void setTripCount(Value *TripCount);
3877
3878 /// Replace all uses of the canonical induction variable in the loop body with
3879 /// a new one.
3880 ///
3881 /// The intended use case is to update the induction variable for an updated
3882 /// iteration space such that it can stay normalized in the 0...tripcount-1
3883 /// range.
3884 ///
3885 /// The \p Updater is called with the (presumable updated) current normalized
3886 /// induction variable and is expected to return the value that uses of the
3887 /// pre-updated induction values should use instead, typically dependent on
3888 /// the new induction variable. This is a lambda (instead of e.g. just passing
3889 /// the new value) to be able to distinguish the uses of the pre-updated
3890 /// induction variable and uses of the induction varible to compute the
3891 /// updated induction variable value.
3892 void mapIndVar(llvm::function_ref<Value *(Instruction *)> Updater);
3893
3894public:
3895 /// Sets the last iteration variable for this loop.
3896 void setLastIter(Value *IterVar) { LastIter = std::move(IterVar); }
3897
3898 /// Returns the last iteration variable for this loop.
3899 /// Certain use-cases (like translation of linear clause) may access
3900 /// this variable even after a loop transformation. Hence, do not guard
3901 /// this getter function by `isValid`. It is the responsibility of the
3902 /// callee to ensure this functionality is not invoked by a non-outlined
3903 /// CanonicalLoopInfo object (in which case, `setLastIter` will never be
3904 /// invoked and `LastIter` will be by default `nullptr`).
3905 Value *getLastIter() { return LastIter; }
3906
3907 /// Returns whether this object currently represents the IR of a loop. If
3908 /// returning false, it may have been consumed by a loop transformation or not
3909 /// been intialized. Do not use in this case;
3910 bool isValid() const { return Header; }
3911
3912 /// The preheader ensures that there is only a single edge entering the loop.
3913 /// Code that must be execute before any loop iteration can be emitted here,
3914 /// such as computing the loop trip count and begin lifetime markers. Code in
3915 /// the preheader is not considered part of the canonical loop.
3916 LLVM_ABI BasicBlock *getPreheader() const;
3917
3918 /// The header is the entry for each iteration. In the canonical control flow,
3919 /// it only contains the PHINode for the induction variable.
3920 BasicBlock *getHeader() const {
3921 assert(isValid() && "Requires a valid canonical loop");
3922 return Header;
3923 }
3924
3925 /// The condition block computes whether there is another loop iteration. If
3926 /// yes, branches to the body; otherwise to the exit block.
3927 BasicBlock *getCond() const {
3928 assert(isValid() && "Requires a valid canonical loop");
3929 return Cond;
3930 }
3931
3932 /// The body block is the single entry for a loop iteration and not controlled
3933 /// by CanonicalLoopInfo. It can contain arbitrary control flow but must
3934 /// eventually branch to the \p Latch block.
3935 BasicBlock *getBody() const {
3936 assert(isValid() && "Requires a valid canonical loop");
3937 return cast<BranchInst>(Cond->getTerminator())->getSuccessor(0);
3938 }
3939
3940 /// Reaching the latch indicates the end of the loop body code. In the
3941 /// canonical control flow, it only contains the increment of the induction
3942 /// variable.
3943 BasicBlock *getLatch() const {
3944 assert(isValid() && "Requires a valid canonical loop");
3945 return Latch;
3946 }
3947
3948 /// Reaching the exit indicates no more iterations are being executed.
3949 BasicBlock *getExit() const {
3950 assert(isValid() && "Requires a valid canonical loop");
3951 return Exit;
3952 }
3953
3954 /// The after block is intended for clean-up code such as lifetime end
3955 /// markers. It is separate from the exit block to ensure, analogous to the
3956 /// preheader, it having just a single entry edge and being free from PHI
3957 /// nodes should there be multiple loop exits (such as from break
3958 /// statements/cancellations).
3959 BasicBlock *getAfter() const {
3960 assert(isValid() && "Requires a valid canonical loop");
3961 return Exit->getSingleSuccessor();
3962 }
3963
3964 /// Returns the llvm::Value containing the number of loop iterations. It must
3965 /// be valid in the preheader and always interpreted as an unsigned integer of
3966 /// any bit-width.
3967 Value *getTripCount() const {
3968 assert(isValid() && "Requires a valid canonical loop");
3969 Instruction *CmpI = &Cond->front();
3970 assert(isa<CmpInst>(CmpI) && "First inst must compare IV with TripCount");
3971 return CmpI->getOperand(1);
3972 }
3973
3974 /// Returns the instruction representing the current logical induction
3975 /// variable. Always unsigned, always starting at 0 with an increment of one.
3976 Instruction *getIndVar() const {
3977 assert(isValid() && "Requires a valid canonical loop");
3978 Instruction *IndVarPHI = &Header->front();
3979 assert(isa<PHINode>(IndVarPHI) && "First inst must be the IV PHI");
3980 return IndVarPHI;
3981 }
3982
3983 /// Return the type of the induction variable (and the trip count).
3984 Type *getIndVarType() const {
3985 assert(isValid() && "Requires a valid canonical loop");
3986 return getIndVar()->getType();
3987 }
3988
3989 /// Return the insertion point for user code before the loop.
3990 OpenMPIRBuilder::InsertPointTy getPreheaderIP() const {
3991 assert(isValid() && "Requires a valid canonical loop");
3992 BasicBlock *Preheader = getPreheader();
3993 return {Preheader, std::prev(Preheader->end())};
3994 };
3995
3996 /// Return the insertion point for user code in the body.
3997 OpenMPIRBuilder::InsertPointTy getBodyIP() const {
3998 assert(isValid() && "Requires a valid canonical loop");
3999 BasicBlock *Body = getBody();
4000 return {Body, Body->begin()};
4001 };
4002
4003 /// Return the insertion point for user code after the loop.
4004 OpenMPIRBuilder::InsertPointTy getAfterIP() const {
4005 assert(isValid() && "Requires a valid canonical loop");
4006 BasicBlock *After = getAfter();
4007 return {After, After->begin()};
4008 };
4009
4010 Function *getFunction() const {
4011 assert(isValid() && "Requires a valid canonical loop");
4012 return Header->getParent();
4013 }
4014
4015 /// Consistency self-check.
4016 LLVM_ABI void assertOK() const;
4017
4018 /// Invalidate this loop. That is, the underlying IR does not fulfill the
4019 /// requirements of an OpenMP canonical loop anymore.
4020 LLVM_ABI void invalidate();
4021};
4022
4023/// ScanInfo holds the information to assist in lowering of Scan reduction.
4024/// Before lowering, the body of the for loop specifying scan reduction is
4025/// expected to have the following structure
4026///
4027/// Loop Body Entry
4028/// |
4029/// Code before the scan directive
4030/// |
4031/// Scan Directive
4032/// |
4033/// Code after the scan directive
4034/// |
4035/// Loop Body Exit
4036/// When `createCanonicalScanLoops` is executed, the bodyGen callback of it
4037/// transforms the body to:
4038///
4039/// Loop Body Entry
4040/// |
4041/// OMPScanDispatch
4042///
4043/// OMPBeforeScanBlock
4044/// |
4045/// OMPScanLoopExit
4046/// |
4047/// Loop Body Exit
4048///
4049/// The insert point is updated to the first insert point of OMPBeforeScanBlock.
4050/// It dominates the control flow of code generated until
4051/// scan directive is encountered and OMPAfterScanBlock dominates the
4052/// control flow of code generated after scan is encountered. The successor
4053/// of OMPScanDispatch can be OMPBeforeScanBlock or OMPAfterScanBlock based
4054/// on 1.whether it is in Input phase or Scan Phase , 2. whether it is an
4055/// exclusive or inclusive scan. This jump is added when `createScan` is
4056/// executed. If input loop is being generated, if it is inclusive scan,
4057/// `OMPAfterScanBlock` succeeds `OMPScanDispatch` , if exclusive,
4058/// `OMPBeforeScanBlock` succeeds `OMPDispatch` and vice versa for scan loop. At
4059/// the end of the input loop, temporary buffer is populated and at the
4060/// beginning of the scan loop, temporary buffer is read. After scan directive
4061/// is encountered, insertion point is updated to `OMPAfterScanBlock` as it is
4062/// expected to dominate the code after the scan directive. Both Before and
4063/// After scan blocks are succeeded by `OMPScanLoopExit`.
4064/// Temporary buffer allocations are done in `ScanLoopInit` block before the
4065/// lowering of for-loop. The results are copied back to reduction variable in
4066/// `ScanLoopFinish` block.
4067class ScanInfo {
4068public:
4069 /// Dominates the body of the loop before scan directive
4070 llvm::BasicBlock *OMPBeforeScanBlock = nullptr;
4071
4072 /// Dominates the body of the loop before scan directive
4073 llvm::BasicBlock *OMPAfterScanBlock = nullptr;
4074
4075 /// Controls the flow to before or after scan blocks
4076 llvm::BasicBlock *OMPScanDispatch = nullptr;
4077
4078 /// Exit block of loop body
4079 llvm::BasicBlock *OMPScanLoopExit = nullptr;
4080
4081 /// Block before loop body where scan initializations are done
4082 llvm::BasicBlock *OMPScanInit = nullptr;
4083
4084 /// Block after loop body where scan finalizations are done
4085 llvm::BasicBlock *OMPScanFinish = nullptr;
4086
4087 /// If true, it indicates Input phase is lowered; else it indicates
4088 /// ScanPhase is lowered
4089 bool OMPFirstScanLoop = false;
4090
4091 /// Maps the private reduction variable to the pointer of the temporary
4092 /// buffer
4093 llvm::SmallDenseMap<llvm::Value *, llvm::Value *> *ScanBuffPtrs;
4094
4095 /// Keeps track of value of iteration variable for input/scan loop to be
4096 /// used for Scan directive lowering
4097 llvm::Value *IV = nullptr;
4098
4099 /// Stores the span of canonical loop being lowered to be used for temporary
4100 /// buffer allocation or Finalization.
4101 llvm::Value *Span = nullptr;
4102
4103 ScanInfo() {
4104 ScanBuffPtrs = new llvm::SmallDenseMap<llvm::Value *, llvm::Value *>();
4105 }
4106 ScanInfo(ScanInfo &) = delete;
4107 ScanInfo &operator=(const ScanInfo &) = delete;
4108
4109 ~ScanInfo() { delete (ScanBuffPtrs); }
4110};
4111
4112} // end namespace llvm
4113
4114#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