LLVM 24.0.0git
OMPIRBuilder.cpp
Go to the documentation of this file.
1//===- OpenMPIRBuilder.cpp - Builder for LLVM-IR for OpenMP directives ----===//
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/// \file
9///
10/// This file implements the OpenMPIRBuilder class, which is used as a
11/// convenient way to create LLVM instructions for OpenMP directives.
12///
13//===----------------------------------------------------------------------===//
14
17#include "llvm/ADT/SmallSet.h"
20#include "llvm/ADT/StringRef.h"
21#include "llvm/ADT/StringSet.h"
29#include "llvm/IR/Attributes.h"
30#include "llvm/IR/BasicBlock.h"
31#include "llvm/IR/CFG.h"
32#include "llvm/IR/CallingConv.h"
33#include "llvm/IR/Constant.h"
34#include "llvm/IR/Constants.h"
35#include "llvm/IR/DIBuilder.h"
38#include "llvm/IR/Function.h"
40#include "llvm/IR/IRBuilder.h"
42#include "llvm/IR/LLVMContext.h"
43#include "llvm/IR/MDBuilder.h"
44#include "llvm/IR/Metadata.h"
46#include "llvm/IR/PassManager.h"
48#include "llvm/IR/Value.h"
50#include "llvm/Support/Error.h"
57
58#include <cstdint>
59#include <optional>
60
61#define DEBUG_TYPE "openmp-ir-builder"
62
63using namespace llvm;
64using namespace omp;
65
66static cl::opt<bool>
67 OptimisticAttributes("openmp-ir-builder-optimistic-attributes", cl::Hidden,
68 cl::desc("Use optimistic attributes describing "
69 "'as-if' properties of runtime calls."),
70 cl::init(false));
71
73 "openmp-ir-builder-use-default-max-threads", cl::Hidden,
74 cl::desc("Use a default max threads if none is provided."), cl::init(true));
75
76#ifndef NDEBUG
77/// Return whether IP1 and IP2 are ambiguous, i.e. that inserting instructions
78/// at position IP1 may change the meaning of IP2 or vice-versa. This is because
79/// an InsertPoint stores the instruction before something is inserted. For
80/// instance, if both point to the same instruction, two IRBuilders alternating
81/// creating instruction will cause the instructions to be interleaved.
84 if (!IP1.isValid() || !IP2.isValid())
85 return false;
86 return IP1 == IP2;
87}
88
90 // Valid ordered/unordered and base algorithm combinations.
91 switch (SchedType & ~OMPScheduleType::MonotonicityMask) {
92 case OMPScheduleType::UnorderedStaticChunked:
93 case OMPScheduleType::UnorderedStatic:
94 case OMPScheduleType::UnorderedDynamicChunked:
95 case OMPScheduleType::UnorderedGuidedChunked:
96 case OMPScheduleType::UnorderedRuntime:
97 case OMPScheduleType::UnorderedAuto:
98 case OMPScheduleType::UnorderedTrapezoidal:
99 case OMPScheduleType::UnorderedGreedy:
100 case OMPScheduleType::UnorderedBalanced:
101 case OMPScheduleType::UnorderedGuidedIterativeChunked:
102 case OMPScheduleType::UnorderedGuidedAnalyticalChunked:
103 case OMPScheduleType::UnorderedSteal:
104 case OMPScheduleType::UnorderedStaticBalancedChunked:
105 case OMPScheduleType::UnorderedGuidedSimd:
106 case OMPScheduleType::UnorderedRuntimeSimd:
107 case OMPScheduleType::OrderedStaticChunked:
108 case OMPScheduleType::OrderedStatic:
109 case OMPScheduleType::OrderedDynamicChunked:
110 case OMPScheduleType::OrderedGuidedChunked:
111 case OMPScheduleType::OrderedRuntime:
112 case OMPScheduleType::OrderedAuto:
113 case OMPScheduleType::OrderdTrapezoidal:
114 case OMPScheduleType::NomergeUnorderedStaticChunked:
115 case OMPScheduleType::NomergeUnorderedStatic:
116 case OMPScheduleType::NomergeUnorderedDynamicChunked:
117 case OMPScheduleType::NomergeUnorderedGuidedChunked:
118 case OMPScheduleType::NomergeUnorderedRuntime:
119 case OMPScheduleType::NomergeUnorderedAuto:
120 case OMPScheduleType::NomergeUnorderedTrapezoidal:
121 case OMPScheduleType::NomergeUnorderedGreedy:
122 case OMPScheduleType::NomergeUnorderedBalanced:
123 case OMPScheduleType::NomergeUnorderedGuidedIterativeChunked:
124 case OMPScheduleType::NomergeUnorderedGuidedAnalyticalChunked:
125 case OMPScheduleType::NomergeUnorderedSteal:
126 case OMPScheduleType::NomergeOrderedStaticChunked:
127 case OMPScheduleType::NomergeOrderedStatic:
128 case OMPScheduleType::NomergeOrderedDynamicChunked:
129 case OMPScheduleType::NomergeOrderedGuidedChunked:
130 case OMPScheduleType::NomergeOrderedRuntime:
131 case OMPScheduleType::NomergeOrderedAuto:
132 case OMPScheduleType::NomergeOrderedTrapezoidal:
133 case OMPScheduleType::OrderedDistributeChunked:
134 case OMPScheduleType::OrderedDistribute:
135 break;
136 default:
137 return false;
138 }
139
140 // Must not set both monotonicity modifiers at the same time.
141 OMPScheduleType MonotonicityFlags =
142 SchedType & OMPScheduleType::MonotonicityMask;
143 if (MonotonicityFlags == OMPScheduleType::MonotonicityMask)
144 return false;
145
146 return true;
147}
148#endif
149
150/// This is a wrapper over IRBuilderBase::restoreIP that also restores a current
151/// debug location when the insert point is at the end of a block. It picks a
152/// location scoped to the current function: the block's last instruction
153/// location if the block is non-empty, otherwise a location synthesized from
154/// the function's subprogram (when the function has debug info).
157 Builder.restoreIP(IP);
158 // When IP points at a real instruction, restoreIP (SetInsertPoint) already
159 // set the debug location from that instruction, so leave it alone.
160 llvm::BasicBlock *BB = Builder.GetInsertBlock();
161 if (Builder.GetInsertPoint() != BB->end())
162 return;
163
164 // At the end of a block, pick a location guaranteed to belong to the current
165 // insertion function's subprogram. Prefer the block's own last instruction;
166 // otherwise synthesize a location from the function's subprogram.
167 if (!BB->empty())
168 Builder.SetCurrentDebugLocation(BB->back().getDebugLoc());
169 else if (llvm::DISubprogram *FSP =
170 BB->getParent() ? BB->getParent()->getSubprogram() : nullptr) {
171 unsigned Line = FSP->getScopeLine() ? FSP->getScopeLine() : FSP->getLine();
172 Builder.SetCurrentDebugLocation(
173 llvm::DILocation::get(FSP->getContext(), Line, /*Column=*/0, FSP));
174 }
175}
176
177static bool hasGridValue(const Triple &T) {
178 return T.isAMDGPU() || T.isNVPTX() || T.isSPIRV();
179}
180
181static const omp::GV &getGridValue(const Triple &T, Function *Kernel) {
182 if (T.isAMDGPU()) {
183 StringRef Features =
184 Kernel->getFnAttribute("target-features").getValueAsString();
185 if (Features.count("+wavefrontsize64"))
188 }
189 if (T.isNVPTX())
191 if (T.isSPIRV())
193 llvm_unreachable("No grid value available for this architecture!");
194}
195
196/// Determine which scheduling algorithm to use, determined from schedule clause
197/// arguments.
198static OMPScheduleType
199getOpenMPBaseScheduleType(llvm::omp::ScheduleKind ClauseKind, bool HasChunks,
200 bool HasSimdModifier, bool HasDistScheduleChunks) {
201 // Currently, the default schedule it static.
202 switch (ClauseKind) {
203 case OMP_SCHEDULE_Default:
204 case OMP_SCHEDULE_Static:
205 return HasChunks ? OMPScheduleType::BaseStaticChunked
206 : OMPScheduleType::BaseStatic;
207 case OMP_SCHEDULE_Dynamic:
208 return OMPScheduleType::BaseDynamicChunked;
209 case OMP_SCHEDULE_Guided:
210 return HasSimdModifier ? OMPScheduleType::BaseGuidedSimd
211 : OMPScheduleType::BaseGuidedChunked;
212 case OMP_SCHEDULE_Auto:
214 case OMP_SCHEDULE_Runtime:
215 return HasSimdModifier ? OMPScheduleType::BaseRuntimeSimd
216 : OMPScheduleType::BaseRuntime;
217 case OMP_SCHEDULE_Distribute:
218 return HasDistScheduleChunks ? OMPScheduleType::BaseDistributeChunked
219 : OMPScheduleType::BaseDistribute;
220 }
221 llvm_unreachable("unhandled schedule clause argument");
222}
223
224/// Adds ordering modifier flags to schedule type.
225static OMPScheduleType
227 bool HasOrderedClause) {
228 assert((BaseScheduleType & OMPScheduleType::ModifierMask) ==
229 OMPScheduleType::None &&
230 "Must not have ordering nor monotonicity flags already set");
231
232 OMPScheduleType OrderingModifier = HasOrderedClause
233 ? OMPScheduleType::ModifierOrdered
234 : OMPScheduleType::ModifierUnordered;
235 OMPScheduleType OrderingScheduleType = BaseScheduleType | OrderingModifier;
236
237 // Unsupported combinations
238 if (OrderingScheduleType ==
239 (OMPScheduleType::BaseGuidedSimd | OMPScheduleType::ModifierOrdered))
240 return OMPScheduleType::OrderedGuidedChunked;
241 else if (OrderingScheduleType == (OMPScheduleType::BaseRuntimeSimd |
242 OMPScheduleType::ModifierOrdered))
243 return OMPScheduleType::OrderedRuntime;
244
245 return OrderingScheduleType;
246}
247
248/// Adds monotonicity modifier flags to schedule type.
249static OMPScheduleType
251 bool HasSimdModifier, bool HasMonotonic,
252 bool HasNonmonotonic, bool HasOrderedClause) {
253 assert((ScheduleType & OMPScheduleType::MonotonicityMask) ==
254 OMPScheduleType::None &&
255 "Must not have monotonicity flags already set");
256 assert((!HasMonotonic || !HasNonmonotonic) &&
257 "Monotonic and Nonmonotonic are contradicting each other");
258
259 if (HasMonotonic) {
260 return ScheduleType | OMPScheduleType::ModifierMonotonic;
261 } else if (HasNonmonotonic) {
262 return ScheduleType | OMPScheduleType::ModifierNonmonotonic;
263 } else {
264 // OpenMP 5.1, 2.11.4 Worksharing-Loop Construct, Description.
265 // If the static schedule kind is specified or if the ordered clause is
266 // specified, and if the nonmonotonic modifier is not specified, the
267 // effect is as if the monotonic modifier is specified. Otherwise, unless
268 // the monotonic modifier is specified, the effect is as if the
269 // nonmonotonic modifier is specified.
270 OMPScheduleType BaseScheduleType =
271 ScheduleType & ~OMPScheduleType::ModifierMask;
272 if ((BaseScheduleType == OMPScheduleType::BaseStatic) ||
273 (BaseScheduleType == OMPScheduleType::BaseStaticChunked) ||
274 HasOrderedClause) {
275 // The monotonic is used by default in openmp runtime library, so no need
276 // to set it.
277 return ScheduleType;
278 } else {
279 return ScheduleType | OMPScheduleType::ModifierNonmonotonic;
280 }
281 }
282}
283
284/// Determine the schedule type using schedule and ordering clause arguments.
285static OMPScheduleType
286computeOpenMPScheduleType(ScheduleKind ClauseKind, bool HasChunks,
287 bool HasSimdModifier, bool HasMonotonicModifier,
288 bool HasNonmonotonicModifier, bool HasOrderedClause,
289 bool HasDistScheduleChunks) {
291 ClauseKind, HasChunks, HasSimdModifier, HasDistScheduleChunks);
292 OMPScheduleType OrderedSchedule =
293 getOpenMPOrderingScheduleType(BaseSchedule, HasOrderedClause);
295 OrderedSchedule, HasSimdModifier, HasMonotonicModifier,
296 HasNonmonotonicModifier, HasOrderedClause);
297
299 return Result;
300}
301
302/// Given a function, if it represents the entry point of a target kernel, this
303/// returns the execution mode flags associated with that kernel.
304static std::optional<omp::OMPTgtExecModeFlags>
306 CallInst *TargetInitCall = nullptr;
307 for (Instruction &Inst : Kernel.getEntryBlock()) {
308 if (auto *Call = dyn_cast<CallInst>(&Inst)) {
309 if (Call->getCalledFunction()->getName() == "__kmpc_target_init") {
310 TargetInitCall = Call;
311 break;
312 }
313 }
314 }
315
316 if (!TargetInitCall)
317 return std::nullopt;
318
319 // Get the kernel mode information from the global variable associated to the
320 // first argument to the call to __kmpc_target_init. Refer to
321 // createTargetInit() to see how this is initialized.
322 Value *InitOperand = TargetInitCall->getArgOperand(0);
323 GlobalVariable *KernelEnv = nullptr;
324 if (auto *Cast = dyn_cast<ConstantExpr>(InitOperand))
325 KernelEnv = cast<GlobalVariable>(Cast->getOperand(0));
326 else
327 KernelEnv = cast<GlobalVariable>(InitOperand);
328 auto *KernelEnvInit = cast<ConstantStruct>(KernelEnv->getInitializer());
329 auto *ConfigEnv = cast<ConstantStruct>(KernelEnvInit->getOperand(0));
330 auto *KernelMode = cast<ConstantInt>(ConfigEnv->getOperand(2));
331 return static_cast<OMPTgtExecModeFlags>(KernelMode->getZExtValue());
332}
333
334static bool isGenericKernel(Function &Fn) {
335 std::optional<omp::OMPTgtExecModeFlags> ExecMode =
337 return !ExecMode || (*ExecMode & OMP_TGT_EXEC_MODE_GENERIC);
338}
339
340/// Make \p Source branch to \p Target.
341///
342/// Handles two situations:
343/// * \p Source already has an unconditional branch.
344/// * \p Source is a degenerate block (no terminator because the BB is
345/// the current head of the IR construction).
347 if (Instruction *Term = Source->getTerminatorOrNull()) {
348 auto *Br = cast<UncondBrInst>(Term);
349 BasicBlock *Succ = Br->getSuccessor();
350 Succ->removePredecessor(Source, /*KeepOneInputPHIs=*/true);
351 Br->setSuccessor(Target);
352 return;
353 }
354
355 auto *NewBr = UncondBrInst::Create(Target, Source);
356 NewBr->setDebugLoc(DL);
357}
358
360 bool CreateBranch, DebugLoc DL) {
361 assert(New->getFirstInsertionPt() == New->begin() &&
362 "Target BB must not have PHI nodes");
363
364 // Move instructions to new block.
365 BasicBlock *Old = IP.getNodeParent();
366 // If the `Old` block is empty then there are no instructions to move. But in
367 // the new debug scheme, it could have trailing debug records which will be
368 // moved to `New` in `spliceDebugInfoEmptyBlock`. We dont want that for 2
369 // reasons:
370 // 1. If `New` is also empty, `BasicBlock::splice` crashes.
371 // 2. Even if `New` is not empty, the rationale to move those records to `New`
372 // (in `spliceDebugInfoEmptyBlock`) does not apply here. That function
373 // assumes that `Old` is optimized out and is going away. This is not the case
374 // here. The `Old` block is still being used e.g. a branch instruction is
375 // added to it later in this function.
376 // So we call `BasicBlock::splice` only when `Old` is not empty.
377 if (!Old->empty())
378 New->splice(New->begin(), Old, IP, Old->end());
379
380 if (CreateBranch) {
381 auto *NewBr = UncondBrInst::Create(New, Old);
382 NewBr->setDebugLoc(DL);
383 }
384}
385
386void llvm::spliceBB(IRBuilder<> &Builder, BasicBlock *New, bool CreateBranch) {
387 DebugLoc DebugLoc = Builder.getCurrentDebugLocation();
388 BasicBlock *Old = Builder.GetInsertBlock();
389
390 spliceBB(Builder.saveIP(), New, CreateBranch, DebugLoc);
391 if (CreateBranch)
392 Builder.SetInsertPoint(Old->getTerminator());
393 else
394 Builder.SetInsertPoint(Old);
395
396 // SetInsertPoint also updates the Builder's debug location, but we want to
397 // keep the one the Builder was configured to use.
398 Builder.SetCurrentDebugLocation(DebugLoc);
399}
400
402 DebugLoc DL, llvm::Twine Name) {
403 BasicBlock *Old = IP.getNodeParent();
405 Old->getContext(), Name.isTriviallyEmpty() ? Old->getName() : Name,
406 Old->getParent(), Old->getNextNode());
407 spliceBB(IP, New, CreateBranch, DL);
408 New->replaceSuccessorsPhiUsesWith(Old, New);
409 return New;
410}
411
412BasicBlock *llvm::splitBB(IRBuilderBase &Builder, bool CreateBranch,
413 llvm::Twine Name) {
414 DebugLoc DebugLoc = Builder.getCurrentDebugLocation();
415 BasicBlock *Old = Builder.GetInsertBlock();
416 BasicBlock *New = splitBB(Builder.saveIP(), CreateBranch, DebugLoc, Name);
417 if (CreateBranch)
418 Builder.SetInsertPoint(Old->getTerminator());
419 else
420 Builder.SetInsertPoint(Old);
421 // SetInsertPoint also updates the Builder's debug location, but we want to
422 // keep the one the Builder was configured to use.
423 Builder.SetCurrentDebugLocation(DebugLoc);
424 return New;
425}
426
427BasicBlock *llvm::splitBB(IRBuilder<> &Builder, bool CreateBranch,
428 llvm::Twine Name) {
429 DebugLoc DebugLoc = Builder.getCurrentDebugLocation();
430 BasicBlock *Old = Builder.GetInsertBlock();
431 BasicBlock *New = splitBB(Builder.saveIP(), CreateBranch, DebugLoc, Name);
432 if (CreateBranch)
433 Builder.SetInsertPoint(Old->getTerminator());
434 else
435 Builder.SetInsertPoint(Old);
436 // SetInsertPoint also updates the Builder's debug location, but we want to
437 // keep the one the Builder was configured to use.
438 Builder.SetCurrentDebugLocation(DebugLoc);
439 return New;
440}
441
443 llvm::Twine Suffix) {
444 BasicBlock *Old = Builder.GetInsertBlock();
445 return splitBB(Builder, CreateBranch, Old->getName() + Suffix);
446}
447
448// This function creates a fake integer value and a fake use for the integer
449// value. It returns the fake value created. This is useful in modeling the
450// extra arguments to the outlined functions.
452 OpenMPIRBuilder::InsertPointTy OuterAllocaIP,
454 OpenMPIRBuilder::InsertPointTy InnerAllocaIP,
455 const Twine &Name = "", bool AsPtr = true,
456 bool Is64Bit = false) {
457 Builder.restoreIP(OuterAllocaIP);
458 IntegerType *IntTy = Is64Bit ? Builder.getInt64Ty() : Builder.getInt32Ty();
459 Instruction *FakeVal;
460 AllocaInst *FakeValAddr =
461 Builder.CreateAlloca(IntTy, nullptr, Name + ".addr");
462 ToBeDeleted.push_back(FakeValAddr);
463
464 if (AsPtr) {
465 FakeVal = FakeValAddr;
466 // The runtime passes these extra arguments to the outlined function as
467 // generic pointers, so cast away a non-zero alloca address space.
468 if (FakeValAddr->getAddressSpace() != 0) {
469 FakeVal = cast<Instruction>(Builder.CreateAddrSpaceCast(
470 FakeValAddr, Builder.getPtrTy(), Name + ".ascast"));
471 ToBeDeleted.push_back(FakeVal);
472 }
473 } else {
474 FakeVal = Builder.CreateLoad(IntTy, FakeValAddr, Name + ".val");
475 ToBeDeleted.push_back(FakeVal);
476 }
477
478 // Generate a fake use of this value
479 Builder.restoreIP(InnerAllocaIP);
480 Instruction *UseFakeVal;
481 if (AsPtr) {
482 UseFakeVal = Builder.CreateLoad(IntTy, FakeVal, Name + ".use");
483 } else {
484 UseFakeVal = cast<BinaryOperator>(Builder.CreateAdd(
485 FakeVal, Is64Bit ? Builder.getInt64(10) : Builder.getInt32(10)));
486 }
487 ToBeDeleted.push_back(UseFakeVal);
488 return FakeVal;
489}
490
491//===----------------------------------------------------------------------===//
492// OpenMPIRBuilderConfig
493//===----------------------------------------------------------------------===//
494
495namespace {
497/// Values for bit flags for marking which requires clauses have been used.
498enum OpenMPOffloadingRequiresDirFlags {
499 /// flag undefined.
500 OMP_REQ_UNDEFINED = 0x000,
501 /// no requires directive present.
502 OMP_REQ_NONE = 0x001,
503 /// reverse_offload clause.
504 OMP_REQ_REVERSE_OFFLOAD = 0x002,
505 /// unified_address clause.
506 OMP_REQ_UNIFIED_ADDRESS = 0x004,
507 /// unified_shared_memory clause.
508 OMP_REQ_UNIFIED_SHARED_MEMORY = 0x008,
509 /// dynamic_allocators clause.
510 OMP_REQ_DYNAMIC_ALLOCATORS = 0x010,
511 LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/OMP_REQ_DYNAMIC_ALLOCATORS)
512};
513
514class OMPCodeExtractor : public CodeExtractor {
515public:
516 OMPCodeExtractor(OpenMPIRBuilder &OMPBuilder, ArrayRef<BasicBlock *> BBs,
517 DominatorTree *DT = nullptr, bool AggregateArgs = false,
518 BlockFrequencyInfo *BFI = nullptr,
519 BranchProbabilityInfo *BPI = nullptr,
520 AssumptionCache *AC = nullptr, bool AllowVarArgs = false,
521 bool AllowAlloca = false,
522 BasicBlock *AllocationBlock = nullptr,
523 ArrayRef<BasicBlock *> DeallocationBlocks = {},
524 std::string Suffix = "", bool ArgsInZeroAddressSpace = false)
525 : CodeExtractor(BBs, DT, AggregateArgs, BFI, BPI, AC, AllowVarArgs,
526 AllowAlloca, AllocationBlock, DeallocationBlocks, Suffix,
527 ArgsInZeroAddressSpace),
528 OMPBuilder(OMPBuilder) {}
529
530 virtual ~OMPCodeExtractor() = default;
531
532protected:
533 OpenMPIRBuilder &OMPBuilder;
534};
535
536class DeviceSharedMemCodeExtractor : public OMPCodeExtractor {
537public:
538 using OMPCodeExtractor::OMPCodeExtractor;
539 virtual ~DeviceSharedMemCodeExtractor() = default;
540
541protected:
542 virtual Instruction *
543 allocateVar(IRBuilder<>::InsertPoint AllocaIP, DebugLoc DL, Type *VarType,
544 const Twine &Name = Twine(""),
545 AddrSpaceCastInst **CastedAlloc = nullptr) override {
546 return OMPBuilder.createOMPAllocShared({AllocaIP, DL}, VarType, Name);
547 }
548
549 virtual Instruction *deallocateVar(IRBuilder<>::InsertPoint DeallocIP,
550 DebugLoc DL, Value *Var,
551 Type *VarType) override {
552 return OMPBuilder.createOMPFreeShared({DeallocIP, DL}, Var, VarType);
553 }
554};
555
556/// Helper storing information about regions to outline using device shared
557/// memory for intermediate allocations.
558struct DeviceSharedMemOutlineInfo : public OpenMPIRBuilder::OutlineInfo {
559 OpenMPIRBuilder &OMPBuilder;
560
561 DeviceSharedMemOutlineInfo(OpenMPIRBuilder &OMPBuilder)
562 : OMPBuilder(OMPBuilder) {}
563 virtual ~DeviceSharedMemOutlineInfo() = default;
564
565 virtual std::unique_ptr<CodeExtractor>
566 createCodeExtractor(ArrayRef<BasicBlock *> Blocks,
567 bool ArgsInZeroAddressSpace,
568 Twine Suffix = Twine("")) override;
569};
570
571} // anonymous namespace
572
574 : RequiresFlags(OMP_REQ_UNDEFINED) {}
575
578 bool HasRequiresReverseOffload, bool HasRequiresUnifiedAddress,
579 bool HasRequiresUnifiedSharedMemory, bool HasRequiresDynamicAllocators)
582 RequiresFlags(OMP_REQ_UNDEFINED) {
583 if (HasRequiresReverseOffload)
584 RequiresFlags |= OMP_REQ_REVERSE_OFFLOAD;
585 if (HasRequiresUnifiedAddress)
586 RequiresFlags |= OMP_REQ_UNIFIED_ADDRESS;
587 if (HasRequiresUnifiedSharedMemory)
588 RequiresFlags |= OMP_REQ_UNIFIED_SHARED_MEMORY;
589 if (HasRequiresDynamicAllocators)
590 RequiresFlags |= OMP_REQ_DYNAMIC_ALLOCATORS;
591}
592
594 return RequiresFlags & OMP_REQ_REVERSE_OFFLOAD;
595}
596
598 return RequiresFlags & OMP_REQ_UNIFIED_ADDRESS;
599}
600
602 return RequiresFlags & OMP_REQ_UNIFIED_SHARED_MEMORY;
603}
604
606 return RequiresFlags & OMP_REQ_DYNAMIC_ALLOCATORS;
607}
608
610 return hasRequiresFlags() ? RequiresFlags
611 : static_cast<int64_t>(OMP_REQ_NONE);
612}
613
615 if (Value)
616 RequiresFlags |= OMP_REQ_REVERSE_OFFLOAD;
617 else
618 RequiresFlags &= ~OMP_REQ_REVERSE_OFFLOAD;
619}
620
622 if (Value)
623 RequiresFlags |= OMP_REQ_UNIFIED_ADDRESS;
624 else
625 RequiresFlags &= ~OMP_REQ_UNIFIED_ADDRESS;
626}
627
629 if (Value)
630 RequiresFlags |= OMP_REQ_UNIFIED_SHARED_MEMORY;
631 else
632 RequiresFlags &= ~OMP_REQ_UNIFIED_SHARED_MEMORY;
633}
634
636 if (Value)
637 RequiresFlags |= OMP_REQ_DYNAMIC_ALLOCATORS;
638 else
639 RequiresFlags &= ~OMP_REQ_DYNAMIC_ALLOCATORS;
640}
641
642//===----------------------------------------------------------------------===//
643// OpenMPIRBuilder
644//===----------------------------------------------------------------------===//
645
648 SmallVector<Value *> &ArgsVector) {
650 Value *PointerNum = Builder.getInt32(KernelArgs.NumTargetItems);
651 auto Int32Ty = Type::getInt32Ty(Builder.getContext());
652 constexpr size_t MaxDim = 3;
653 Value *ZeroArray = Constant::getNullValue(ArrayType::get(Int32Ty, MaxDim));
654
655 Value *HasNoWaitFlag = Builder.getInt64(KernelArgs.HasNoWait);
656
657 Value *DynCGroupMemFallbackFlag =
658 Builder.getInt64(static_cast<uint64_t>(KernelArgs.DynCGroupMemFallback));
659 DynCGroupMemFallbackFlag = Builder.CreateShl(DynCGroupMemFallbackFlag, 2);
660
661 Value *StrictBlocksFlag = Builder.getInt64(KernelArgs.StrictBlocks);
662 Value *StrictThreadsFlag = Builder.getInt64(KernelArgs.StrictThreads);
663
664 StrictBlocksFlag = Builder.CreateShl(StrictBlocksFlag, 6);
665 StrictThreadsFlag = Builder.CreateShl(StrictThreadsFlag, 7);
666
667 Value *Flags = Builder.CreateOr(HasNoWaitFlag, DynCGroupMemFallbackFlag);
668 Flags = Builder.CreateOr(Flags, StrictBlocksFlag);
669 Flags = Builder.CreateOr(Flags, StrictThreadsFlag);
670
671 assert(!KernelArgs.NumTeams.empty() && !KernelArgs.NumThreads.empty());
672
673 Value *NumTeams3D =
674 Builder.CreateInsertValue(ZeroArray, KernelArgs.NumTeams[0], {0});
675 Value *NumThreads3D =
676 Builder.CreateInsertValue(ZeroArray, KernelArgs.NumThreads[0], {0});
677 for (unsigned I :
678 seq<unsigned>(1, std::min(KernelArgs.NumTeams.size(), MaxDim)))
679 NumTeams3D =
680 Builder.CreateInsertValue(NumTeams3D, KernelArgs.NumTeams[I], {I});
681 for (unsigned I :
682 seq<unsigned>(1, std::min(KernelArgs.NumThreads.size(), MaxDim)))
683 NumThreads3D =
684 Builder.CreateInsertValue(NumThreads3D, KernelArgs.NumThreads[I], {I});
685
686 ArgsVector = {Version,
687 PointerNum,
688 KernelArgs.RTArgs.BasePointersArray,
689 KernelArgs.RTArgs.PointersArray,
690 KernelArgs.RTArgs.SizesArray,
691 KernelArgs.RTArgs.MapTypesArray,
692 KernelArgs.RTArgs.MapNamesArray,
693 KernelArgs.RTArgs.MappersArray,
694 KernelArgs.NumIterations,
695 Flags,
696 NumTeams3D,
697 NumThreads3D,
698 KernelArgs.DynCGroupMem};
699}
700
702 LLVMContext &Ctx = Fn.getContext();
703
704 // Get the function's current attributes.
705 auto Attrs = Fn.getAttributes();
706 auto FnAttrs = Attrs.getFnAttrs();
707 auto RetAttrs = Attrs.getRetAttrs();
709 for (size_t ArgNo = 0; ArgNo < Fn.arg_size(); ++ArgNo)
710 ArgAttrs.emplace_back(Attrs.getParamAttrs(ArgNo));
711
712 // Add AS to FnAS while taking special care with integer extensions.
713 auto addAttrSet = [&](AttributeSet &FnAS, const AttributeSet &AS,
714 bool Param = true) -> void {
715 bool HasSignExt = AS.hasAttribute(Attribute::SExt);
716 bool HasZeroExt = AS.hasAttribute(Attribute::ZExt);
717 if (HasSignExt || HasZeroExt) {
718 assert(AS.getNumAttributes() == 1 &&
719 "Currently not handling extension attr combined with others.");
720 if (Param) {
721 if (auto AK = TargetLibraryInfo::getExtAttrForI32Param(T, HasSignExt))
722 FnAS = FnAS.addAttribute(Ctx, AK);
723 } else if (auto AK =
724 TargetLibraryInfo::getExtAttrForI32Return(T, HasSignExt))
725 FnAS = FnAS.addAttribute(Ctx, AK);
726 } else {
727 FnAS = FnAS.addAttributes(Ctx, AS);
728 }
729 };
730
731#define OMP_ATTRS_SET(VarName, AttrSet) AttributeSet VarName = AttrSet;
732#include "llvm/Frontend/OpenMP/OMPKinds.def"
733
734 // Add attributes to the function declaration.
735 switch (FnID) {
736#define OMP_RTL_ATTRS(Enum, FnAttrSet, RetAttrSet, ArgAttrSets) \
737 case Enum: \
738 FnAttrs = FnAttrs.addAttributes(Ctx, FnAttrSet); \
739 addAttrSet(RetAttrs, RetAttrSet, /*Param*/ false); \
740 for (size_t ArgNo = 0; ArgNo < ArgAttrSets.size(); ++ArgNo) \
741 addAttrSet(ArgAttrs[ArgNo], ArgAttrSets[ArgNo]); \
742 Fn.setAttributes(AttributeList::get(Ctx, FnAttrs, RetAttrs, ArgAttrs)); \
743 break;
744#include "llvm/Frontend/OpenMP/OMPKinds.def"
745 default:
746 // Attributes are optional.
747 break;
748 }
749}
750
753 FunctionType *FnTy = nullptr;
754 StringRef Name;
755
756 switch (FnID) {
757#define OMP_RTL(Enum, Str, IsVarArg, ReturnType, ...) \
758 case Enum: \
759 FnTy = FunctionType::get(ReturnType, ArrayRef<Type *>{__VA_ARGS__}, \
760 IsVarArg); \
761 Name = Str; \
762 break;
763#include "llvm/Frontend/OpenMP/OMPKinds.def"
764 }
765
766 return M.getOrInsertFunction(Name, FnTy, [&](Function &Fn) {
767 Fn.setCallingConv(Config.getRuntimeCC());
768 // Add information if the runtime function takes a callback function
769 if (FnID == OMPRTL___kmpc_fork_call || FnID == OMPRTL___kmpc_fork_teams) {
770 LLVMContext &Ctx = Fn.getContext();
771 MDBuilder MDB(Ctx);
772 // Annotate the callback behavior of the runtime function:
773 // - The callback callee is argument number 2 (microtask).
774 // - The first two arguments of the callback callee are unknown (-1).
775 // - All variadic arguments to the runtime function are passed to the
776 // callback callee.
777 Fn.addMetadata(
778 LLVMContext::MD_callback,
780 2, {-1, -1}, /* VarArgsArePassed */ true)}));
781 }
782
783 LLVM_DEBUG(dbgs() << "Created OpenMP runtime function " << Fn.getName()
784 << " with type " << *Fn.getFunctionType() << "\n");
785 addAttributes(FnID, Fn);
786 });
787}
788
791 if (!FiniBB) {
792 Function *ParentFunc = Builder.GetInsertBlock()->getParent();
794 FiniBB = BasicBlock::Create(Builder.getContext(), ".fini", ParentFunc);
795 Builder.SetInsertPoint(FiniBB);
796 // FiniCB adds the branch to the exit stub.
797 if (Error Err = FiniCB(Builder.saveIP()))
798 return Err;
799 }
800 return FiniBB;
801}
802
804 BasicBlock *OtherFiniBB) {
805 // Simple case: FiniBB does not exist yet: re-use OtherFiniBB.
806 if (!FiniBB) {
807 FiniBB = OtherFiniBB;
808
809 Builder.SetInsertPoint(FiniBB->getFirstNonPHIIt());
810 if (Error Err = FiniCB(Builder.saveIP()))
811 return Err;
812
813 return Error::success();
814 }
815
816 // Move instructions from FiniBB to the start of OtherFiniBB.
817 auto EndIt = FiniBB->end();
818 if (FiniBB->size() >= 1)
819 if (auto Prev = std::prev(EndIt); Prev->isTerminator())
820 EndIt = Prev;
821 OtherFiniBB->splice(OtherFiniBB->getFirstNonPHIIt(), FiniBB, FiniBB->begin(),
822 EndIt);
823
824 FiniBB->replaceAllUsesWith(OtherFiniBB);
825 FiniBB->eraseFromParent();
826 FiniBB = OtherFiniBB;
827 return Error::success();
828}
829
832 auto *Fn = dyn_cast<llvm::Function>(RTLFn.getCallee());
833 assert(Fn && "Failed to create OpenMP runtime function pointer");
834 return Fn;
835}
836
839 StringRef Name) {
840 CallInst *Call = Builder.CreateCall(Callee, Args, Name);
841 Call->setCallingConv(Config.getRuntimeCC());
842 return Call;
843}
844
845void OpenMPIRBuilder::initialize() { initializeTypes(M); }
846
849 BasicBlock &EntryBlock = Function->getEntryBlock();
850 BasicBlock::iterator MoveLocInst = EntryBlock.getFirstNonPHIIt();
851
852 // Loop over blocks looking for constant allocas, skipping the entry block
853 // as any allocas there are already in the desired location.
854 for (auto Block = std::next(Function->begin(), 1); Block != Function->end();
855 Block++) {
856 for (auto Inst = Block->getReverseIterator()->begin();
857 Inst != Block->getReverseIterator()->end();) {
859 Inst++;
861 continue;
862 AllocaInst->moveBeforePreserving(MoveLocInst);
863 } else {
864 Inst++;
865 }
866 }
867 }
868}
869
872
873 auto ShouldHoistAlloca = [](const llvm::AllocaInst &AllocaInst) {
874 // TODO: For now, we support simple static allocations, we might need to
875 // move non-static ones as well. However, this will need further analysis to
876 // move the lenght arguments as well.
878 };
879
880 for (llvm::Instruction &Inst : Block)
882 if (ShouldHoistAlloca(*AllocaInst))
883 AllocasToMove.push_back(AllocaInst);
884
885 auto InsertPoint =
886 Block.getParent()->getEntryBlock().getTerminator()->getIterator();
887
888 for (llvm::Instruction *AllocaInst : AllocasToMove)
890}
891
893 PostDominatorTree PostDomTree(*Func);
894 for (llvm::BasicBlock &BB : *Func)
895 if (PostDomTree.properlyDominates(&BB, &Func->getEntryBlock()))
897}
898
899#ifndef NDEBUG
900/// Return true if \p Name names an OpenMP runtime function.
902 static const StringSet<> Names = {
903#define OMP_RTL(Enum, Str, ...) Str,
904#include "llvm/Frontend/OpenMP/OMPKinds.def"
905 };
906 return Names.contains(Name);
907}
908
909/// Assert that every direct call to an OpenMP runtime function in \p M has a
910/// debug location if its function has a subprogram.
912 for (Function &F : M) {
913 if (!F.getSubprogram())
914 continue;
915 for (Instruction &I : instructions(F)) {
916 auto *CB = dyn_cast<CallBase>(&I);
917 if (!CB || CB->getDebugLoc())
918 continue;
919 Function *Callee = CB->getCalledFunction();
920 if (Callee && isRuntimeFunctionName(Callee->getName())) {
921 errs() << "OpenMP runtime call to '" << Callee->getName()
922 << "' in function '" << F.getName()
923 << "' has no debug location\n";
924 llvm_unreachable("OpenMP runtime call has no debug location");
925 }
926 }
927 }
928}
929#endif
930
932 SmallPtrSet<BasicBlock *, 32> ParallelRegionBlockSet;
934 SmallVector<std::unique_ptr<OutlineInfo>, 16> DeferredOutlines;
935 for (std::unique_ptr<OutlineInfo> &OI : OutlineInfos) {
936 // Skip functions that have not finalized yet; may happen with nested
937 // function generation.
938 if (Fn && OI->getFunction() != Fn) {
939 DeferredOutlines.push_back(std::move(OI));
940 continue;
941 }
942
943 ParallelRegionBlockSet.clear();
944 Blocks.clear();
945 OI->collectBlocks(ParallelRegionBlockSet, Blocks);
946
947 Function *OuterFn = OI->getFunction();
948 CodeExtractorAnalysisCache CEAC(*OuterFn);
949 // If we generate code for the target device, we need to allocate
950 // struct for aggregate params in the device default alloca address space.
951 // OpenMP runtime requires that the params of the extracted functions are
952 // passed as zero address space pointers. This flag ensures that
953 // CodeExtractor generates correct code for extracted functions
954 // which are used by OpenMP runtime.
955 bool ArgsInZeroAddressSpace = Config.isTargetDevice();
956 std::unique_ptr<CodeExtractor> Extractor =
957 OI->createCodeExtractor(Blocks, ArgsInZeroAddressSpace, ".omp_par");
958
959 LLVM_DEBUG(dbgs() << "Before outlining: " << *OuterFn << "\n");
960 LLVM_DEBUG(dbgs() << "Entry " << OI->EntryBB->getName()
961 << " Exit: " << OI->ExitBB->getName() << "\n");
962 assert(Extractor->isEligible() &&
963 "Expected OpenMP outlining to be possible!");
964
965 for (auto *V : OI->ExcludeArgsFromAggregate)
966 Extractor->excludeArgFromAggregate(V);
967
968 Function *OutlinedFn =
969 Extractor->extractCodeRegion(CEAC, OI->Inputs, OI->Outputs);
970
971 // Forward target-cpu, target-features attributes to the outlined function.
972 auto TargetCpuAttr = OuterFn->getFnAttribute("target-cpu");
973 if (TargetCpuAttr.isStringAttribute())
974 OutlinedFn->addFnAttr(TargetCpuAttr);
975
976 auto TargetFeaturesAttr = OuterFn->getFnAttribute("target-features");
977 if (TargetFeaturesAttr.isStringAttribute())
978 OutlinedFn->addFnAttr(TargetFeaturesAttr);
979
980 LLVM_DEBUG(dbgs() << "After outlining: " << *OuterFn << "\n");
981 LLVM_DEBUG(dbgs() << " Outlined function: " << *OutlinedFn << "\n");
982 assert(OutlinedFn->getReturnType()->isVoidTy() &&
983 "OpenMP outlined functions should not return a value!");
984
985 // For compability with the clang CG we move the outlined function after the
986 // one with the parallel region.
987 OutlinedFn->removeFromParent();
988 M.getFunctionList().insertAfter(OuterFn->getIterator(), OutlinedFn);
989
990 // Remove the artificial entry introduced by the extractor right away, we
991 // made our own entry block after all.
992 {
993 BasicBlock &ArtificialEntry = OutlinedFn->getEntryBlock();
994 assert(ArtificialEntry.getUniqueSuccessor() == OI->EntryBB);
995 assert(OI->EntryBB->getUniquePredecessor() == &ArtificialEntry);
996 // Move instructions from the to-be-deleted ArtificialEntry to the entry
997 // basic block of the parallel region. CodeExtractor generates
998 // instructions to unwrap the aggregate argument and may sink
999 // allocas/bitcasts for values that are solely used in the outlined region
1000 // and do not escape.
1001 assert(!ArtificialEntry.empty() &&
1002 "Expected instructions to add in the outlined region entry");
1003 for (BasicBlock::reverse_iterator It = ArtificialEntry.rbegin(),
1004 End = ArtificialEntry.rend();
1005 It != End;) {
1006 Instruction &I = *It;
1007 It++;
1008
1009 if (I.isTerminator()) {
1010 // Absorb any debug value that terminator may have
1011 if (Instruction *TI = OI->EntryBB->getTerminatorOrNull())
1012 TI->adoptDbgRecords(&ArtificialEntry, I.getIterator(), false);
1013 continue;
1014 }
1015
1016 I.moveBeforePreserving(*OI->EntryBB,
1017 OI->EntryBB->getFirstInsertionPt());
1018 }
1019
1020 OI->EntryBB->moveBefore(&ArtificialEntry);
1021 ArtificialEntry.eraseFromParent();
1022 }
1023 assert(&OutlinedFn->getEntryBlock() == OI->EntryBB);
1024 assert(OutlinedFn && OutlinedFn->hasNUses(1));
1025
1026 // Run a user callback, e.g. to add attributes.
1027 if (OI->PostOutlineCB)
1028 OI->PostOutlineCB(*OutlinedFn);
1029
1030 if (OI->FixUpNonEntryAllocas)
1032 }
1033
1034 // Remove work items that have been completed.
1035 OutlineInfos = std::move(DeferredOutlines);
1036
1037 // The createTarget functions embeds user written code into
1038 // the target region which may inject allocas which need to
1039 // be moved to the entry block of our target or risk malformed
1040 // optimisations by later passes (however, we do not block on
1041 // that here, it's up to the inserter to the list to do so).
1042 // This notbaly has to occur after the OutlinedInfo candidates
1043 // have been extracted so we have an end product that will not
1044 // be implicitly adversely affected by any raises unless
1045 // intentionally appended to the list.
1046 // NOTE: This only does so for ConstantData, it could be extended
1047 // to ConstantExpr's with further effort, however, they should
1048 // largely be folded when they get here. Extending it to runtime
1049 // defined/read+writeable allocation sizes would be non-trivial
1050 // (need to factor in movement of any stores to variables the
1051 // allocation size depends on, as well as the usual loads,
1052 // otherwise it'll yield the wrong result after movement) and
1053 // likely be more suitable as an LLVM optimisation pass.
1056
1057 EmitMetadataErrorReportFunctionTy &&ErrorReportFn =
1058 [](EmitMetadataErrorKind Kind,
1059 const TargetRegionEntryInfo &EntryInfo) -> void {
1060 errs() << "Error of kind: " << Kind
1061 << " when emitting offload entries and metadata during "
1062 "OMPIRBuilder finalization \n";
1063 };
1064
1065 if (!OffloadInfoManager.empty())
1067
1068 // Rewrite uses of globals to their replacement declare target globals if
1069 // we are processing a device module.
1070 if (Config.isTargetDevice())
1071 applyDeclareTargetGlobalReplacements();
1072
1073 if (Config.EmitLLVMUsedMetaInfo.value_or(false)) {
1074 std::vector<WeakTrackingVH> LLVMCompilerUsed = {
1075 M.getGlobalVariable("__openmp_nvptx_data_transfer_temporary_storage")};
1076 emitUsed("llvm.compiler.used", LLVMCompilerUsed);
1077 }
1078
1079 IsFinalized = true;
1080
1081#ifndef NDEBUG
1082 // A caller finalizing one function at a time would have the module walked
1083 // once per function, so only check when the whole module is finalized.
1084 if (!Fn)
1086#endif
1087}
1088
1089bool OpenMPIRBuilder::isFinalized() { return IsFinalized; }
1090
1092 GlobalValue *Original, GlobalValue *Replacement) {
1093 assert(Original && Replacement &&
1094 "Null values provided to registerDeclareTargetGlobalReplacement");
1095 DeclareTargetGlobalReplacements.push_back({Original, Replacement});
1096}
1097
1098void OpenMPIRBuilder::applyDeclareTargetGlobalReplacements() {
1099 for (DeclareTargetGlobalReplacement &R : DeclareTargetGlobalReplacements) {
1100 GlobalValue *OldGV = R.Original;
1101 GlobalValue *NewGV = R.Replacement;
1102
1103 assert(OldGV && NewGV &&
1104 "A null value was inserted into DeclareTargetGlobalReplacements");
1105
1106 // The assert above should catch this case, but this is kept to attempt
1107 // to proceed without issue when asserts are off.
1108 if (!OldGV || !NewGV)
1109 continue;
1110
1111 // The replacement global is a reference pointer that holds the
1112 // address of the device-resident storage. Every use must load the
1113 // reference pointer first and use the loaded address.
1114 //
1115 // Constant expression users (e.g. a constant GEP embedded in another
1116 // global's initializer or in an instruction) cannot have a load inserted
1117 // in place, so first expand any constant-expression users that live inside
1118 // functions into instructions. Any remaining constant users are handled
1119 // via a direct constant rewrite below as we cannot materialize a load
1120 // there.
1121 //
1122 // NOTE: We extend the constant rewrite to module scope, as we replace all
1123 // usages.
1124 if (auto *OldConst = dyn_cast<Constant>(OldGV))
1126 /*RestrictToFunc=*/nullptr,
1127 /*RemoveDeadConstants=*/false);
1128
1129 IRBuilderBase::InsertPointGuard Guard(Builder);
1131 for (User *U : Users) {
1132 auto *Insn = dyn_cast<Instruction>(U);
1133 if (!Insn)
1134 continue;
1135
1136 // A PHI node cannot have a load inserted immediately before it, as PHIs
1137 // must remain grouped at the top of their basic block. So we need to
1138 // make sure any loads we emit are generated in the preceding edge, a
1139 // PHI may reference the global on more than one edge, so every matching
1140 // slot must be handled.
1141 if (auto *PHI = dyn_cast<PHINode>(Insn)) {
1142 for (unsigned I = 0, E = PHI->getNumIncomingValues(); I < E; ++I) {
1143 if (PHI->getIncomingValue(I) != OldGV)
1144 continue;
1145
1146 BasicBlock *IncomingBB = PHI->getIncomingBlock(I);
1147 Builder.SetInsertPoint(IncomingBB->getTerminator());
1148 Builder.SetCurrentDebugLocation(PHI->getDebugLoc());
1149 LoadInst *EdgeLoad = Builder.CreateLoad(NewGV->getType(), NewGV);
1150 PHI->setIncomingValue(I, EdgeLoad);
1151 }
1152 continue;
1153 }
1154
1155 Builder.SetInsertPoint(Insn);
1156 Builder.SetCurrentDebugLocation(Insn->getDebugLoc());
1157 LoadInst *Load = Builder.CreateLoad(NewGV->getType(), NewGV);
1158
1159 // The replacement declare target global lives in the default address
1160 // space, whereas the original global may reside in a non-default
1161 // address space. In that case the initial lowering may have
1162 // emitted an addrspacecast that is no longer valid. Replace the
1163 // whole addrspacecast with the load and erase it rather than
1164 // feeding the load back into the (now pointless) cast.
1165 // NOTE: If we end up with replacement declare target globals in
1166 // non-zero AS's the below will need some minor extensions to have the
1167 // option to alter the address space cast to the new address space where
1168 // required rather than just replacing it.
1169 if (auto *ASC = dyn_cast<AddrSpaceCastInst>(Insn)) {
1170 unsigned NewGVAS = NewGV->getType()->getPointerAddressSpace();
1171 assert(NewGVAS == 0 &&
1172 "Non-default address space declare target global");
1173 unsigned OldGVAS = OldGV->getType()->getPointerAddressSpace();
1174 unsigned DestAS = ASC->getType()->getPointerAddressSpace();
1175 if (DestAS == 0 && NewGVAS != OldGVAS) {
1176 ASC->replaceAllUsesWith(Load);
1177 ASC->eraseFromParent();
1178 continue;
1179 }
1180 }
1181
1182 Insn->replaceUsesOfWith(OldGV, Load);
1183 }
1184 }
1185
1187}
1188
1190 assert(OutlineInfos.empty() && "There must be no outstanding outlinings");
1191}
1192
1194 IntegerType *I32Ty = Type::getInt32Ty(M.getContext());
1195 auto *GV =
1196 new GlobalVariable(M, I32Ty,
1197 /* isConstant = */ true, GlobalValue::WeakODRLinkage,
1198 ConstantInt::get(I32Ty, Value), Name);
1199 GV->setVisibility(GlobalValue::HiddenVisibility);
1200
1201 return GV;
1202}
1203
1205 if (List.empty())
1206 return;
1207
1208 // Convert List to what ConstantArray needs.
1210 UsedArray.resize(List.size());
1211 for (unsigned I = 0, E = List.size(); I != E; ++I)
1213 cast<Constant>(&*List[I]), Builder.getPtrTy());
1214
1215 if (UsedArray.empty())
1216 return;
1217 ArrayType *ATy = ArrayType::get(Builder.getPtrTy(), UsedArray.size());
1218
1219 auto *GV = new GlobalVariable(M, ATy, false, GlobalValue::AppendingLinkage,
1220 ConstantArray::get(ATy, UsedArray), Name);
1221
1222 GV->setSection("llvm.metadata");
1223}
1224
1227 OMPTgtExecModeFlags Mode) {
1228 auto *Int8Ty = Builder.getInt8Ty();
1229 auto *GVMode = new GlobalVariable(
1230 M, Int8Ty, /*isConstant=*/true, GlobalValue::WeakAnyLinkage,
1231 ConstantInt::get(Int8Ty, Mode), Twine(KernelName, "_exec_mode"));
1232 GVMode->setVisibility(GlobalVariable::ProtectedVisibility);
1233 return GVMode;
1234}
1235
1237 uint32_t SrcLocStrSize,
1238 IdentFlag LocFlags,
1239 unsigned Reserve2Flags) {
1240 // Enable "C-mode".
1241 LocFlags |= OMP_IDENT_FLAG_KMPC;
1242
1243 Constant *&Ident =
1244 IdentMap[{SrcLocStr, uint64_t(LocFlags) << 31 | Reserve2Flags}];
1245 if (!Ident) {
1246 Constant *I32Null = ConstantInt::getNullValue(Int32);
1247 Constant *IdentData[] = {I32Null,
1248 ConstantInt::get(Int32, uint32_t(LocFlags)),
1249 ConstantInt::get(Int32, Reserve2Flags),
1250 ConstantInt::get(Int32, SrcLocStrSize), SrcLocStr};
1251
1252 size_t SrcLocStrArgIdx = 4;
1253 if (OpenMPIRBuilder::Ident->getElementType(SrcLocStrArgIdx)
1255 IdentData[SrcLocStrArgIdx]->getType()->getPointerAddressSpace())
1256 IdentData[SrcLocStrArgIdx] = ConstantExpr::getAddrSpaceCast(
1257 SrcLocStr, OpenMPIRBuilder::Ident->getElementType(SrcLocStrArgIdx));
1258 Constant *Initializer =
1259 ConstantStruct::get(OpenMPIRBuilder::Ident, IdentData);
1260
1261 // Look for existing encoding of the location + flags, not needed but
1262 // minimizes the difference to the existing solution while we transition.
1263 for (GlobalVariable &GV : M.globals())
1264 if (GV.getValueType() == OpenMPIRBuilder::Ident && GV.hasInitializer())
1265 if (GV.getInitializer() == Initializer)
1266 Ident = &GV;
1267
1268 if (!Ident) {
1269 auto *GV = new GlobalVariable(
1270 M, OpenMPIRBuilder::Ident,
1271 /* isConstant = */ true, GlobalValue::PrivateLinkage, Initializer, "",
1273 M.getDataLayout().getDefaultGlobalsAddressSpace());
1274 GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
1275 GV->setAlignment(Align(8));
1276 Ident = GV;
1277 }
1278 }
1279
1280 return ConstantExpr::getPointerBitCastOrAddrSpaceCast(Ident, IdentPtr);
1281}
1282
1284 uint32_t &SrcLocStrSize) {
1285 SrcLocStrSize = LocStr.size();
1286 Constant *&SrcLocStr = SrcLocStrMap[LocStr];
1287 if (!SrcLocStr) {
1288 Constant *Initializer =
1289 ConstantDataArray::getString(M.getContext(), LocStr);
1290
1291 // Look for existing encoding of the location, not needed but minimizes the
1292 // difference to the existing solution while we transition.
1293 for (GlobalVariable &GV : M.globals())
1294 if (GV.isConstant() && GV.hasInitializer() &&
1295 GV.getInitializer() == Initializer)
1296 return SrcLocStr = ConstantExpr::getPointerCast(&GV, Int8Ptr);
1297
1298 SrcLocStr = Builder.CreateGlobalString(
1299 LocStr, /*Name=*/"", M.getDataLayout().getDefaultGlobalsAddressSpace(),
1300 &M);
1301 }
1302 return SrcLocStr;
1303}
1304
1306 StringRef FileName,
1307 unsigned Line, unsigned Column,
1308 uint32_t &SrcLocStrSize) {
1309 SmallString<128> Buffer;
1310 Buffer.push_back(';');
1311 Buffer.append(FileName);
1312 Buffer.push_back(';');
1313 Buffer.append(FunctionName);
1314 Buffer.push_back(';');
1315 Buffer.append(std::to_string(Line));
1316 Buffer.push_back(';');
1317 Buffer.append(std::to_string(Column));
1318 Buffer.push_back(';');
1319 Buffer.push_back(';');
1320 return getOrCreateSrcLocStr(Buffer.str(), SrcLocStrSize);
1321}
1322
1323Constant *
1325 StringRef UnknownLoc = ";unknown;unknown;0;0;;";
1326 return getOrCreateSrcLocStr(UnknownLoc, SrcLocStrSize);
1327}
1328
1330 uint32_t &SrcLocStrSize,
1331 const Function *F) {
1332 DILocation *DIL = DL.get();
1333 if (!DIL)
1334 return getOrCreateDefaultSrcLocStr(SrcLocStrSize);
1335 StringRef FileName =
1336 !DIL->getFilename().empty() ? DIL->getFilename() : M.getName();
1337 StringRef Function = DIL->getScope()->getSubprogram()->getName();
1338 if (Function.empty() && F)
1339 Function = F->getName();
1340 return getOrCreateSrcLocStr(Function, FileName, DIL->getLine(),
1341 DIL->getColumn(), SrcLocStrSize);
1342}
1343
1345 uint32_t &SrcLocStrSize) {
1346 return getOrCreateSrcLocStr(Loc.DL, SrcLocStrSize,
1347 Loc.IP.getNodeParent()->getParent());
1348}
1349
1352 getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_global_thread_num), Ident,
1353 "omp_global_thread_num");
1354}
1355
1356OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::createTargetInReduction(
1357 const LocationDescription &Loc, ArrayRef<Value *> OrigPtrs,
1358 ArrayRef<Type *> ResultPtrTys,
1359 function_ref<void(unsigned, Value *)> MapPrivateCB) {
1360 assert(OrigPtrs.size() == ResultPtrTys.size() &&
1361 "expected one result pointer type per in_reduction item");
1362 if (!updateToLocation(Loc))
1363 return Loc.IP;
1364 if (OrigPtrs.empty())
1365 return Builder.saveIP();
1366
1367 // Compute the executing thread's gtid once for the whole target body and
1368 // reuse it for every in_reduction lookup, so a target with several
1369 // in_reduction items does not emit a redundant __kmpc_global_thread_num per
1370 // item.
1371 uint32_t SrcLocStrSize;
1372 Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
1373 Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
1374 Value *Gtid = getOrCreateThreadID(Ident);
1375
1376 // The runtime entry point takes (and returns) a generic, default-address-
1377 // space `ptr`. A NULL descriptor makes the runtime walk the enclosing
1378 // taskgroups to find the matching task_reduction registration for the item.
1379 Type *PtrTy = PointerType::getUnqual(M.getContext());
1380 Value *NullDesc = ConstantPointerNull::get(PtrTy);
1381 FunctionCallee GetThData =
1382 getOrCreateRuntimeFunction(M, OMPRTL___kmpc_task_reduction_get_th_data);
1383
1384 for (unsigned Idx = 0; Idx < OrigPtrs.size(); ++Idx) {
1385 // Normalize a non-default-address-space original pointer to the generic
1386 // address space before the call.
1387 Value *OrigPtr = OrigPtrs[Idx];
1388 if (auto *OrigPtrTy = dyn_cast<PointerType>(OrigPtr->getType());
1389 OrigPtrTy && OrigPtrTy->getAddressSpace() != 0)
1390 OrigPtr = Builder.CreateAddrSpaceCast(OrigPtr, PtrTy);
1391
1392 Value *Priv = Builder.CreateCall(GetThData, {Gtid, NullDesc, OrigPtr},
1393 "omp.inred.priv");
1394
1395 // Cast the returned private pointer back to the requested address space
1396 // when it differs.
1397 if (auto *ResPtrTy = dyn_cast<PointerType>(ResultPtrTys[Idx]);
1398 ResPtrTy && ResPtrTy->getAddressSpace() != 0)
1399 Priv = Builder.CreateAddrSpaceCast(Priv, ResultPtrTys[Idx]);
1400
1401 MapPrivateCB(Idx, Priv);
1402 }
1403 return Builder.saveIP();
1404}
1405
1408 bool ForceSimpleCall, bool CheckCancelFlag) {
1409 if (!updateToLocation(Loc))
1410 return Loc.IP;
1411
1412 // Build call __kmpc_cancel_barrier(loc, thread_id) or
1413 // __kmpc_barrier(loc, thread_id);
1414
1415 IdentFlag BarrierLocFlags;
1416 switch (Kind) {
1417 case OMPD_for:
1418 BarrierLocFlags = OMP_IDENT_FLAG_BARRIER_IMPL_FOR;
1419 break;
1420 case OMPD_sections:
1421 BarrierLocFlags = OMP_IDENT_FLAG_BARRIER_IMPL_SECTIONS;
1422 break;
1423 case OMPD_single:
1424 BarrierLocFlags = OMP_IDENT_FLAG_BARRIER_IMPL_SINGLE;
1425 break;
1426 case OMPD_barrier:
1427 BarrierLocFlags = OMP_IDENT_FLAG_BARRIER_EXPL;
1428 break;
1429 default:
1430 BarrierLocFlags = OMP_IDENT_FLAG_BARRIER_IMPL;
1431 break;
1432 }
1433
1434 uint32_t SrcLocStrSize;
1435 Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
1436 Value *Args[] = {
1437 getOrCreateIdent(SrcLocStr, SrcLocStrSize, BarrierLocFlags),
1438 getOrCreateThreadID(getOrCreateIdent(SrcLocStr, SrcLocStrSize))};
1439
1440 // If we are in a cancellable parallel region, barriers are cancellation
1441 // points.
1442 // TODO: Check why we would force simple calls or to ignore the cancel flag.
1443 bool UseCancelBarrier =
1444 !ForceSimpleCall && isLastFinalizationInfoCancellable(OMPD_parallel);
1445
1447 getOrCreateRuntimeFunctionPtr(UseCancelBarrier
1448 ? OMPRTL___kmpc_cancel_barrier
1449 : OMPRTL___kmpc_barrier),
1450 Args);
1451
1452 if (UseCancelBarrier && CheckCancelFlag)
1453 if (Error Err = emitCancelationCheckImpl(Result, OMPD_parallel))
1454 return Err;
1455
1456 return Builder.saveIP();
1457}
1458
1461 Value *IfCondition,
1462 omp::Directive CanceledDirective) {
1463 if (!updateToLocation(Loc))
1464 return Loc.IP;
1465
1466 // LLVM utilities like blocks with terminators.
1467 auto *UI = Builder.CreateUnreachable();
1468
1469 Instruction *ThenTI = UI, *ElseTI = nullptr;
1470 if (IfCondition) {
1471 SplitBlockAndInsertIfThenElse(IfCondition, UI, &ThenTI, &ElseTI);
1472
1473 // Even if the if condition evaluates to false, this should count as a
1474 // cancellation point
1475 Builder.SetInsertPoint(ElseTI);
1476 auto ElseIP = Builder.saveIP();
1477
1479 LocationDescription{ElseIP, Loc.DL}, CanceledDirective);
1480 if (!IPOrErr)
1481 return IPOrErr;
1482 }
1483
1484 Builder.SetInsertPoint(ThenTI);
1485
1486 Value *CancelKind = nullptr;
1487 switch (CanceledDirective) {
1488#define OMP_CANCEL_KIND(Enum, Str, DirectiveEnum, Value) \
1489 case DirectiveEnum: \
1490 CancelKind = Builder.getInt32(Value); \
1491 break;
1492#include "llvm/Frontend/OpenMP/OMPKinds.def"
1493 default:
1494 llvm_unreachable("Unknown cancel kind!");
1495 }
1496
1497 uint32_t SrcLocStrSize;
1498 Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
1499 Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
1500 Value *Args[] = {Ident, getOrCreateThreadID(Ident), CancelKind};
1502 getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_cancel), Args);
1503
1504 // The actual cancel logic is shared with others, e.g., cancel_barriers.
1505 if (Error Err = emitCancelationCheckImpl(Result, CanceledDirective))
1506 return Err;
1507
1508 // Update the insertion point and remove the terminator we introduced.
1509 Builder.SetInsertPoint(UI->getParent());
1510 UI->eraseFromParent();
1511
1512 return Builder.saveIP();
1513}
1514
1517 omp::Directive CanceledDirective) {
1518 if (!updateToLocation(Loc))
1519 return Loc.IP;
1520
1521 // LLVM utilities like blocks with terminators.
1522 auto *UI = Builder.CreateUnreachable();
1523 Builder.SetInsertPoint(UI);
1524
1525 Value *CancelKind = nullptr;
1526 switch (CanceledDirective) {
1527#define OMP_CANCEL_KIND(Enum, Str, DirectiveEnum, Value) \
1528 case DirectiveEnum: \
1529 CancelKind = Builder.getInt32(Value); \
1530 break;
1531#include "llvm/Frontend/OpenMP/OMPKinds.def"
1532 default:
1533 llvm_unreachable("Unknown cancel kind!");
1534 }
1535
1536 uint32_t SrcLocStrSize;
1537 Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
1538 Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
1539 Value *Args[] = {Ident, getOrCreateThreadID(Ident), CancelKind};
1541 getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_cancellationpoint), Args);
1542
1543 // The actual cancel logic is shared with others, e.g., cancel_barriers.
1544 if (Error Err = emitCancelationCheckImpl(Result, CanceledDirective))
1545 return Err;
1546
1547 // Update the insertion point and remove the terminator we introduced.
1548 Builder.SetInsertPoint(UI->getParent());
1549 UI->eraseFromParent();
1550
1551 return Builder.saveIP();
1552}
1553
1555 const LocationDescription &Loc, InsertPointTy AllocaIP, Value *&Return,
1556 Value *Ident, Value *DeviceID, Value *NumTeams, Value *NumThreads,
1557 Value *HostPtr, ArrayRef<Value *> KernelArgs) {
1558 if (!updateToLocation(Loc))
1559 return Loc.IP;
1560
1561 Builder.restoreIP(AllocaIP);
1562 auto *KernelArgsPtr =
1563 Builder.CreateAlloca(OpenMPIRBuilder::KernelArgs, nullptr, "kernel_args");
1565
1566 for (unsigned I = 0, Size = KernelArgs.size(); I != Size; ++I) {
1567 llvm::Value *Arg =
1568 Builder.CreateStructGEP(OpenMPIRBuilder::KernelArgs, KernelArgsPtr, I);
1569 Builder.CreateAlignedStore(
1570 KernelArgs[I], Arg,
1571 M.getDataLayout().getPrefTypeAlign(KernelArgs[I]->getType()));
1572 }
1573
1574 SmallVector<Value *> OffloadingArgs{Ident, DeviceID, NumTeams,
1575 NumThreads, HostPtr, KernelArgsPtr};
1576
1578 getOrCreateRuntimeFunction(M, OMPRTL___tgt_target_kernel),
1579 OffloadingArgs);
1580
1581 return Builder.saveIP();
1582}
1583
1585 const LocationDescription &Loc, Value *OutlinedFnID,
1586 EmitFallbackCallbackTy EmitTargetCallFallbackCB, TargetKernelArgs &Args,
1587 Value *DeviceID, Value *RTLoc, InsertPointTy AllocaIP) {
1588
1589 if (!updateToLocation(Loc))
1590 return Loc.IP;
1591
1592 // On top of the arrays that were filled up, the target offloading call
1593 // takes as arguments the device id as well as the host pointer. The host
1594 // pointer is used by the runtime library to identify the current target
1595 // region, so it only has to be unique and not necessarily point to
1596 // anything. It could be the pointer to the outlined function that
1597 // implements the target region, but we aren't using that so that the
1598 // compiler doesn't need to keep that, and could therefore inline the host
1599 // function if proven worthwhile during optimization.
1600
1601 // From this point on, we need to have an ID of the target region defined.
1602 assert(OutlinedFnID && "Invalid outlined function ID!");
1603 (void)OutlinedFnID;
1604
1605 // Return value of the runtime offloading call.
1606 Value *Return = nullptr;
1607
1608 // Arguments for the target kernel.
1609 SmallVector<Value *> ArgsVector;
1610 getKernelArgsVector(Args, Builder, ArgsVector);
1611
1612 // The target region is an outlined function launched by the runtime
1613 // via calls to __tgt_target_kernel().
1614 //
1615 // Note that on the host and CPU targets, the runtime implementation of
1616 // these calls simply call the outlined function without forking threads.
1617 // The outlined functions themselves have runtime calls to
1618 // __kmpc_fork_teams() and __kmpc_fork() for this purpose, codegen'd by
1619 // the compiler in emitTeamsCall() and emitParallelCall().
1620 //
1621 // In contrast, on the NVPTX target, the implementation of
1622 // __tgt_target_teams() launches a GPU kernel with the requested number
1623 // of teams and threads so no additional calls to the runtime are required.
1624 // Check the error code and execute the host version if required.
1625 Builder.restoreIP(emitTargetKernel(
1626 Builder, AllocaIP, Return, RTLoc, DeviceID, Args.NumTeams.front(),
1627 Args.NumThreads.front(), OutlinedFnID, ArgsVector));
1628
1629 BasicBlock *OffloadFailedBlock =
1630 BasicBlock::Create(Builder.getContext(), "omp_offload.failed");
1631 BasicBlock *OffloadContBlock =
1632 BasicBlock::Create(Builder.getContext(), "omp_offload.cont");
1633 Value *Failed = Builder.CreateIsNotNull(Return);
1634 Builder.CreateCondBr(Failed, OffloadFailedBlock, OffloadContBlock);
1635
1636 auto CurFn = Builder.GetInsertBlock()->getParent();
1637 emitBlock(OffloadFailedBlock, CurFn);
1638 InsertPointOrErrorTy AfterIP = EmitTargetCallFallbackCB(Builder.saveIP());
1639 if (!AfterIP)
1640 return AfterIP.takeError();
1641 Builder.restoreIP(*AfterIP);
1642 emitBranch(OffloadContBlock);
1643 emitBlock(OffloadContBlock, CurFn, /*IsFinished=*/true);
1644 return Builder.saveIP();
1645}
1646
1648 Value *CancelFlag, omp::Directive CanceledDirective) {
1649 assert(isLastFinalizationInfoCancellable(CanceledDirective) &&
1650 "Unexpected cancellation!");
1651
1652 // For a cancel barrier we create two new blocks.
1653 BasicBlock *BB = Builder.GetInsertBlock();
1654 BasicBlock *NonCancellationBlock;
1655 if (Builder.GetInsertPoint() == BB->end()) {
1656 // TODO: This branch will not be needed once we moved to the
1657 // OpenMPIRBuilder codegen completely.
1658 NonCancellationBlock = BasicBlock::Create(
1659 BB->getContext(), BB->getName() + ".cont", BB->getParent());
1660 } else {
1661 NonCancellationBlock = SplitBlock(BB, &*Builder.GetInsertPoint());
1663 Builder.SetInsertPoint(BB);
1664 }
1665 BasicBlock *CancellationBlock = BasicBlock::Create(
1666 BB->getContext(), BB->getName() + ".cncl", BB->getParent());
1667
1668 // Jump to them based on the return value.
1669 Value *Cmp = Builder.CreateIsNull(CancelFlag);
1670 Builder.CreateCondBr(Cmp, NonCancellationBlock, CancellationBlock,
1671 /* TODO weight */ nullptr, nullptr);
1672
1673 // From the cancellation block we finalize all variables and go to the
1674 // post finalization block that is known to the FiniCB callback.
1675 auto &FI = FinalizationStack.back();
1676 Expected<BasicBlock *> FiniBBOrErr = FI.getFiniBB(Builder);
1677 if (!FiniBBOrErr)
1678 return FiniBBOrErr.takeError();
1679 Builder.SetInsertPoint(CancellationBlock);
1680 Builder.CreateBr(*FiniBBOrErr);
1681
1682 // The continuation block is where code generation continues.
1683 Builder.SetInsertPoint(NonCancellationBlock->begin());
1684 return Error::success();
1685}
1686
1687/// Create wrapper function used to gather the outlined function's argument
1688/// structure from a shared buffer and to forward them to it when running in
1689/// Generic mode.
1690///
1691/// The outlined function is expected to receive 2 integer arguments followed by
1692/// an optional pointer argument to an argument structure holding the rest.
1694 Function &OutlinedFn) {
1695 size_t NumArgs = OutlinedFn.arg_size();
1696 assert((NumArgs == 2 || NumArgs == 3) &&
1697 "expected a 2-3 argument parallel outlined function");
1698 bool UseArgStruct = NumArgs == 3;
1699
1700 IRBuilder<> &Builder = OMPIRBuilder->Builder;
1701 IRBuilder<>::InsertPointGuard IPG(Builder);
1702 auto *FnTy = FunctionType::get(Builder.getVoidTy(),
1703 {Builder.getInt16Ty(), Builder.getInt32Ty()},
1704 /*isVarArg=*/false);
1705 auto *WrapperFn =
1707 OutlinedFn.getName() + ".wrapper", OMPIRBuilder->M);
1708
1709 WrapperFn->addParamAttr(0, Attribute::NoUndef);
1710 WrapperFn->addParamAttr(0, Attribute::ZExt);
1711 WrapperFn->addParamAttr(1, Attribute::NoUndef);
1712
1713 BasicBlock *EntryBB =
1714 BasicBlock::Create(OMPIRBuilder->M.getContext(), "entry", WrapperFn);
1715 Builder.SetInsertPoint(EntryBB);
1716
1717 // Allocation.
1718 Value *AddrAlloca = Builder.CreateAlloca(Builder.getInt32Ty(),
1719 /*ArraySize=*/nullptr, "addr");
1720 AddrAlloca = Builder.CreatePointerBitCastOrAddrSpaceCast(
1721 AddrAlloca, Builder.getPtrTy(/*AddrSpace=*/0),
1722 AddrAlloca->getName() + ".ascast");
1723
1724 Value *ZeroAlloca = Builder.CreateAlloca(Builder.getInt32Ty(),
1725 /*ArraySize=*/nullptr, "zero");
1726 ZeroAlloca = Builder.CreatePointerBitCastOrAddrSpaceCast(
1727 ZeroAlloca, Builder.getPtrTy(/*AddrSpace=*/0),
1728 ZeroAlloca->getName() + ".ascast");
1729
1730 Value *ArgsAlloca = nullptr;
1731 if (UseArgStruct) {
1732 ArgsAlloca = Builder.CreateAlloca(Builder.getPtrTy(),
1733 /*ArraySize=*/nullptr, "global_args");
1734 ArgsAlloca = Builder.CreatePointerBitCastOrAddrSpaceCast(
1735 ArgsAlloca, Builder.getPtrTy(/*AddrSpace=*/0),
1736 ArgsAlloca->getName() + ".ascast");
1737 }
1738
1739 // Initialization.
1740 Builder.CreateStore(WrapperFn->getArg(1), AddrAlloca);
1741 Builder.CreateStore(Builder.getInt32(0), ZeroAlloca);
1742 if (UseArgStruct) {
1743 Builder.CreateCall(
1744 OMPIRBuilder->getOrCreateRuntimeFunctionPtr(
1745 llvm::omp::RuntimeFunction::OMPRTL___kmpc_get_shared_variables),
1746 {ArgsAlloca});
1747 }
1748
1749 SmallVector<Value *, 3> Args{AddrAlloca, ZeroAlloca};
1750
1751 // Load structArg from global_args.
1752 if (UseArgStruct) {
1753 Value *StructArg = Builder.CreateLoad(Builder.getPtrTy(), ArgsAlloca);
1754 StructArg = Builder.CreateInBoundsGEP(Builder.getPtrTy(), StructArg,
1755 {Builder.getInt64(0)});
1756 StructArg = Builder.CreateLoad(Builder.getPtrTy(), StructArg, "structArg");
1757 Args.push_back(StructArg);
1758 }
1759
1760 // Call the outlined function holding the parallel body.
1761 Builder.CreateCall(&OutlinedFn, Args);
1762 Builder.CreateRetVoid();
1763
1764 return WrapperFn;
1765}
1766
1767// Callback used to create OpenMP runtime calls to support
1768// omp parallel clause for the device.
1769// We need to use this callback to replace call to the OutlinedFn in OuterFn
1770// by the call to the OpenMP DeviceRTL runtime function (kmpc_parallel_60)
1772 OpenMPIRBuilder *OMPIRBuilder, Function &OutlinedFn, Function *OuterFn,
1773 BasicBlock *OuterAllocaBB, Value *Ident, Value *IfCondition,
1774 Value *NumThreads, Instruction *PrivTID, AllocaInst *PrivTIDAddr,
1775 Value *ThreadID, const SmallVector<Instruction *, 4> &ToBeDeleted) {
1776 assert(OutlinedFn.arg_size() >= 2 &&
1777 "Expected at least tid and bounded tid as arguments");
1778 unsigned NumCapturedVars = OutlinedFn.arg_size() - /* tid & bounded tid */ 2;
1779
1780 // Add some known attributes.
1781 IRBuilder<> &Builder = OMPIRBuilder->Builder;
1782 OutlinedFn.addParamAttr(0, Attribute::NoAlias);
1783 OutlinedFn.addParamAttr(1, Attribute::NoAlias);
1784 OutlinedFn.addParamAttr(0, Attribute::NoUndef);
1785 OutlinedFn.addParamAttr(1, Attribute::NoUndef);
1786 OutlinedFn.addFnAttr(Attribute::NoUnwind);
1787
1788 CallInst *CI = cast<CallInst>(OutlinedFn.user_back());
1789 assert(CI && "Expected call instruction to outlined function");
1790 CI->getParent()->setName("omp_parallel");
1791
1792 Builder.SetInsertPoint(CI);
1793 Type *PtrTy = OMPIRBuilder->VoidPtr;
1794
1795 // Add alloca for kernel args
1796 OpenMPIRBuilder ::InsertPointTy CurrentIP = Builder.saveIP();
1797 Builder.SetInsertPoint(OuterAllocaBB->getFirstInsertionPt());
1798 AllocaInst *ArgsAlloca =
1799 Builder.CreateAlloca(ArrayType::get(PtrTy, NumCapturedVars));
1800 Value *Args = ArgsAlloca;
1801 // Add address space cast if array for storing arguments is not allocated
1802 // in address space 0
1803 if (ArgsAlloca->getAddressSpace())
1804 Args = Builder.CreatePointerCast(ArgsAlloca, PtrTy);
1805 Builder.restoreIP(CurrentIP);
1806
1807 // Store captured vars which are used by kmpc_parallel_60
1808 for (unsigned Idx = 0; Idx < NumCapturedVars; Idx++) {
1809 Value *V = *(CI->arg_begin() + 2 + Idx);
1810 Value *StoreAddress = Builder.CreateConstInBoundsGEP2_64(
1811 ArrayType::get(PtrTy, NumCapturedVars), Args, 0, Idx);
1812 Builder.CreateStore(V, StoreAddress);
1813 }
1814
1815 Value *Cond =
1816 IfCondition ? Builder.CreateSExtOrTrunc(IfCondition, OMPIRBuilder->Int32)
1817 : Builder.getInt32(1);
1818 Value *NumThreadsArg =
1819 NumThreads ? Builder.CreateZExtOrTrunc(NumThreads, OMPIRBuilder->Int32)
1820 : Builder.getInt32(-1);
1821
1822 // If this is not a Generic kernel, we can skip generating the wrapper.
1823 Value *WrapperFn;
1824 if (isGenericKernel(*OuterFn))
1825 WrapperFn = createTargetParallelWrapper(OMPIRBuilder, OutlinedFn);
1826 else
1827 WrapperFn = Constant::getNullValue(PtrTy);
1828
1829 // Build kmpc_parallel_60 call
1830 Value *Parallel60CallArgs[] = {
1831 /* identifier*/ Ident,
1832 /* global thread num*/ ThreadID,
1833 /* if expression */ Cond,
1834 /* number of threads */ NumThreadsArg,
1835 /* Proc bind */ Builder.getInt32(-1),
1836 /* outlined function */ &OutlinedFn,
1837 /* wrapper function */ WrapperFn,
1838 /* arguments of the outlined funciton*/ Args,
1839 /* number of arguments */ Builder.getInt64(NumCapturedVars),
1840 /* strict for number of threads */ Builder.getInt32(0)};
1841
1842 FunctionCallee RTLFn =
1843 OMPIRBuilder->getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_parallel_60);
1844
1845 OMPIRBuilder->createRuntimeFunctionCall(RTLFn, Parallel60CallArgs);
1846
1847 LLVM_DEBUG(dbgs() << "With kmpc_parallel_60 placed: "
1848 << *Builder.GetInsertBlock()->getParent() << "\n");
1849
1850 // Initialize the local TID stack location with the argument value.
1851 Builder.SetInsertPoint(PrivTID);
1852 Function::arg_iterator OutlinedAI = OutlinedFn.arg_begin();
1853 Builder.CreateStore(Builder.CreateLoad(OMPIRBuilder->Int32, OutlinedAI),
1854 PrivTIDAddr);
1855
1856 // Remove redundant call to the outlined function.
1857 CI->eraseFromParent();
1858
1859 for (Instruction *I : ToBeDeleted) {
1860 I->eraseFromParent();
1861 }
1862}
1863
1864// Callback used to create OpenMP runtime calls to support
1865// omp parallel clause for the host.
1866// We need to use this callback to replace call to the OutlinedFn in OuterFn
1867// by the call to the OpenMP host runtime function ( __kmpc_fork_call[_if])
1868static void
1870 Function *OuterFn, Value *Ident, Value *IfCondition,
1871 Instruction *PrivTID, AllocaInst *PrivTIDAddr,
1872 const SmallVector<Instruction *, 4> &ToBeDeleted) {
1873 IRBuilder<> &Builder = OMPIRBuilder->Builder;
1874 FunctionCallee RTLFn;
1875 if (IfCondition) {
1876 RTLFn =
1877 OMPIRBuilder->getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_fork_call_if);
1878 } else {
1879 RTLFn =
1880 OMPIRBuilder->getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_fork_call);
1881 }
1882 if (auto *F = dyn_cast<Function>(RTLFn.getCallee())) {
1883 if (!F->hasMetadata(LLVMContext::MD_callback)) {
1884 LLVMContext &Ctx = F->getContext();
1885 MDBuilder MDB(Ctx);
1886 // Annotate the callback behavior of the __kmpc_fork_call:
1887 // - The callback callee is argument number 2 (microtask).
1888 // - The first two arguments of the callback callee are unknown (-1).
1889 // - All variadic arguments to the __kmpc_fork_call are passed to the
1890 // callback callee.
1891 F->addMetadata(LLVMContext::MD_callback,
1893 2, {-1, -1},
1894 /* VarArgsArePassed */ true)}));
1895 }
1896 }
1897 // Add some known attributes.
1898 OutlinedFn.addParamAttr(0, Attribute::NoAlias);
1899 OutlinedFn.addParamAttr(1, Attribute::NoAlias);
1900 OutlinedFn.addFnAttr(Attribute::NoUnwind);
1901
1902 assert(OutlinedFn.arg_size() >= 2 &&
1903 "Expected at least tid and bounded tid as arguments");
1904 unsigned NumCapturedVars = OutlinedFn.arg_size() - /* tid & bounded tid */ 2;
1905
1906 CallInst *CI = cast<CallInst>(OutlinedFn.user_back());
1907
1908 // CodeExtractor creates an alloca aggregate struct containing pointers to all
1909 // the captured values. The address of this struct is then passed as a
1910 // parameter to the outlined function. This parameter of the outlined function
1911 // can be marked noalias because CodeExractor + this host OpenMP lowering
1912 // maintains the following invariants:
1913 // - The caller initializes the fields before starting any callbacks.
1914 // - Neither the caller, OpenMP runtime, nor callbacks modify the structure
1915 // while callbacks are executing.
1916 // - The callbacks only load captured values from the structure; they do not
1917 // use it to write results back to the caller. This is generated code; the
1918 // user has no way to modify the structure directly.
1919 //
1920 // Multiple callbacks may read the same structure. This is allowed by noalias,
1921 // which permits aliasing accesses to memory that is not modified during the
1922 // call.
1923 //
1924 // The synchronous fork keeps the structure alive until all callbacks return,
1925 // which justifies nofreeobj. Neither attribute extends to the objects pointed
1926 // to by the captured fields.
1927 if (NumCapturedVars) {
1928 assert(NumCapturedVars == 1 && "Expected an aggregate capture argument");
1931 ->getAllocatedType()
1932 ->isStructTy() &&
1933 "Expected a stack-allocated capture structure");
1934
1935 OutlinedFn.addParamAttr(2, Attribute::NoAlias);
1936 OutlinedFn.addParamAttr(2, Attribute::NoFreeObj);
1937 }
1938
1939 CI->getParent()->setName("omp_parallel");
1940 Builder.SetInsertPoint(CI);
1941
1942 // Build call __kmpc_fork_call[_if](Ident, n, microtask, var1, .., varn);
1943 Value *ForkCallArgs[] = {Ident, Builder.getInt32(NumCapturedVars),
1944 &OutlinedFn};
1945
1946 SmallVector<Value *, 16> RealArgs;
1947 RealArgs.append(std::begin(ForkCallArgs), std::end(ForkCallArgs));
1948 if (IfCondition) {
1949 Value *Cond = Builder.CreateSExtOrTrunc(IfCondition, OMPIRBuilder->Int32);
1950 RealArgs.push_back(Cond);
1951 }
1952 RealArgs.append(CI->arg_begin() + /* tid & bound tid */ 2, CI->arg_end());
1953
1954 // __kmpc_fork_call_if always expects a void ptr as the last argument
1955 // If there are no arguments, pass a null pointer.
1956 auto PtrTy = OMPIRBuilder->VoidPtr;
1957 if (IfCondition && NumCapturedVars == 0) {
1958 Value *NullPtrValue = Constant::getNullValue(PtrTy);
1959 RealArgs.push_back(NullPtrValue);
1960 }
1961
1962 OMPIRBuilder->createRuntimeFunctionCall(RTLFn, RealArgs);
1963
1964 LLVM_DEBUG(dbgs() << "With fork_call placed: "
1965 << *Builder.GetInsertBlock()->getParent() << "\n");
1966
1967 // Initialize the local TID stack location with the argument value.
1968 Builder.SetInsertPoint(PrivTID);
1969 Function::arg_iterator OutlinedAI = OutlinedFn.arg_begin();
1970 Builder.CreateStore(Builder.CreateLoad(OMPIRBuilder->Int32, OutlinedAI),
1971 PrivTIDAddr);
1972
1973 // Remove redundant call to the outlined function.
1974 CI->eraseFromParent();
1975
1976 for (Instruction *I : ToBeDeleted) {
1977 I->eraseFromParent();
1978 }
1979}
1980
1982 const LocationDescription &Loc, InsertPointTy OuterAllocIP,
1983 ArrayRef<BasicBlock *> OuterDeallocBlocks, BodyGenCallbackTy BodyGenCB,
1984 PrivatizeCallbackTy PrivCB, FinalizeCallbackTy FiniCB, Value *IfCondition,
1985 Value *NumThreads, omp::ProcBindKind ProcBind, bool IsCancellable) {
1986 assert(!isConflictIP(Loc.IP, OuterAllocIP) && "IPs must not be ambiguous");
1987
1988 if (!updateToLocation(Loc))
1989 return Loc.IP;
1990
1991 uint32_t SrcLocStrSize;
1992 Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
1993 Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
1994 const bool NeedThreadID = NumThreads || Config.isTargetDevice() ||
1995 (ProcBind != OMP_PROC_BIND_default);
1996 Value *ThreadID = NeedThreadID ? getOrCreateThreadID(Ident) : nullptr;
1997 // If we generate code for the target device, we need to allocate
1998 // struct for aggregate params in the device default alloca address space.
1999 // OpenMP runtime requires that the params of the extracted functions are
2000 // passed as zero address space pointers. This flag ensures that extracted
2001 // function arguments are declared in zero address space
2002 bool ArgsInZeroAddressSpace = Config.isTargetDevice();
2003
2004 // Build call __kmpc_push_num_threads(&Ident, global_tid, num_threads)
2005 // only if we compile for host side.
2006 if (NumThreads && !Config.isTargetDevice()) {
2007 Value *Args[] = {
2008 Ident, ThreadID,
2009 Builder.CreateIntCast(NumThreads, Int32, /*isSigned*/ false)};
2011 getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_push_num_threads), Args);
2012 }
2013
2014 if (ProcBind != OMP_PROC_BIND_default) {
2015 // Build call __kmpc_push_proc_bind(&Ident, global_tid, proc_bind)
2016 Value *Args[] = {
2017 Ident, ThreadID,
2018 ConstantInt::get(Int32, unsigned(ProcBind), /*isSigned=*/true)};
2020 getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_push_proc_bind), Args);
2021 }
2022
2023 BasicBlock *InsertBB = Builder.GetInsertBlock();
2024 Function *OuterFn = InsertBB->getParent();
2025
2026 // Save the outer alloca block because the insertion iterator may get
2027 // invalidated and we still need this later.
2028 BasicBlock *OuterAllocaBlock = OuterAllocIP.getNodeParent();
2029
2030 // Vector to remember instructions we used only during the modeling but which
2031 // we want to delete at the end.
2033
2034 // Change the location to the outer alloca insertion point to create and
2035 // initialize the allocas we pass into the parallel region.
2036 InsertPointTy NewOuter(OuterAllocaBlock->begin());
2037 Builder.restoreIP(NewOuter);
2038 AllocaInst *TIDAddrAlloca = Builder.CreateAlloca(Int32, nullptr, "tid.addr");
2039 AllocaInst *ZeroAddrAlloca =
2040 Builder.CreateAlloca(Int32, nullptr, "zero.addr");
2041 Instruction *TIDAddr = TIDAddrAlloca;
2042 Instruction *ZeroAddr = ZeroAddrAlloca;
2043 if (ArgsInZeroAddressSpace && M.getDataLayout().getAllocaAddrSpace() != 0) {
2044 // Add additional casts to enforce pointers in zero address space
2045 TIDAddr = new AddrSpaceCastInst(
2046 TIDAddrAlloca, PointerType ::get(M.getContext(), 0), "tid.addr.ascast");
2047 TIDAddr->insertAfter(TIDAddrAlloca->getIterator());
2048 ToBeDeleted.push_back(TIDAddr);
2049 ZeroAddr = new AddrSpaceCastInst(ZeroAddrAlloca,
2050 PointerType ::get(M.getContext(), 0),
2051 "zero.addr.ascast");
2052 ZeroAddr->insertAfter(ZeroAddrAlloca->getIterator());
2053 ToBeDeleted.push_back(ZeroAddr);
2054 }
2055
2056 // We only need TIDAddr and ZeroAddr for modeling purposes to get the
2057 // associated arguments in the outlined function, so we delete them later.
2058 ToBeDeleted.push_back(TIDAddrAlloca);
2059 ToBeDeleted.push_back(ZeroAddrAlloca);
2060
2061 // Create an artificial insertion point that will also ensure the blocks we
2062 // are about to split are not degenerated.
2063 auto *UI = new UnreachableInst(Builder.getContext(), InsertBB);
2064 UI->setDebugLoc(Loc.DL);
2065
2066 BasicBlock *EntryBB = UI->getParent();
2067 BasicBlock *PRegEntryBB = EntryBB->splitBasicBlock(UI, "omp.par.entry");
2068 BasicBlock *PRegBodyBB = PRegEntryBB->splitBasicBlock(UI, "omp.par.region");
2069 BasicBlock *PRegPreFiniBB =
2070 PRegBodyBB->splitBasicBlock(UI, "omp.par.pre_finalize");
2071 BasicBlock *PRegExitBB = PRegPreFiniBB->splitBasicBlock(UI, "omp.par.exit");
2072
2073 auto FiniCBWrapper = [&](InsertPointTy IP) {
2074 // Hide "open-ended" blocks from the given FiniCB by setting the right jump
2075 // target to the region exit block.
2076 if (IP == IP.getNodeParent()->end()) {
2078 Builder.restoreIP(IP);
2079 Instruction *I = Builder.CreateBr(PRegExitBB);
2080 IP = I->getIterator();
2081 }
2082 assert(IP.getNodeParent()->getTerminator()->getNumSuccessors() == 1 &&
2083 IP.getNodeParent()->getTerminator()->getSuccessor(0) == PRegExitBB &&
2084 "Unexpected insertion point for finalization call!");
2085 return FiniCB(IP);
2086 };
2087
2088 FinalizationStack.push_back({FiniCBWrapper, OMPD_parallel, IsCancellable});
2089
2090 // Generate the privatization allocas in the block that will become the entry
2091 // of the outlined function.
2092 Builder.SetInsertPoint(PRegEntryBB->getTerminator());
2093 InsertPointTy InnerAllocaIP = Builder.saveIP();
2094
2095 AllocaInst *PrivTIDAddr =
2096 Builder.CreateAlloca(Int32, nullptr, "tid.addr.local");
2097 Instruction *PrivTID = Builder.CreateLoad(Int32, PrivTIDAddr, "tid");
2098
2099 // Add some fake uses for OpenMP provided arguments.
2100 ToBeDeleted.push_back(Builder.CreateLoad(Int32, TIDAddr, "tid.addr.use"));
2101 Instruction *ZeroAddrUse =
2102 Builder.CreateLoad(Int32, ZeroAddr, "zero.addr.use");
2103 ToBeDeleted.push_back(ZeroAddrUse);
2104
2105 // EntryBB
2106 // |
2107 // V
2108 // PRegionEntryBB <- Privatization allocas are placed here.
2109 // |
2110 // V
2111 // PRegionBodyBB <- BodeGen is invoked here.
2112 // |
2113 // V
2114 // PRegPreFiniBB <- The block we will start finalization from.
2115 // |
2116 // V
2117 // PRegionExitBB <- A common exit to simplify block collection.
2118 //
2119
2120 LLVM_DEBUG(dbgs() << "Before body codegen: " << *OuterFn << "\n");
2121
2122 // Let the caller create the body.
2123 assert(BodyGenCB && "Expected body generation callback!");
2124 InsertPointTy CodeGenIP(PRegBodyBB->begin());
2125 if (Error Err = BodyGenCB(InnerAllocaIP, CodeGenIP, PRegExitBB))
2126 return Err;
2127
2128 LLVM_DEBUG(dbgs() << "After body codegen: " << *OuterFn << "\n");
2129
2130 // If OuterFn is a Generic kernel, we need to use device shared memory to
2131 // allocate argument structures. Otherwise, we use stack allocations as usual.
2132 bool UsesDeviceSharedMemory =
2133 Config.isTargetDevice() && isGenericKernel(*OuterFn);
2134 std::unique_ptr<OutlineInfo> OI =
2135 UsesDeviceSharedMemory
2136 ? std::make_unique<DeviceSharedMemOutlineInfo>(*this)
2137 : std::make_unique<OutlineInfo>();
2138
2139 if (Config.isTargetDevice()) {
2140 // Generate OpenMP target specific runtime call
2141 OI->PostOutlineCB = [=, ToBeDeletedVec =
2142 std::move(ToBeDeleted)](Function &OutlinedFn) {
2143 targetParallelCallback(this, OutlinedFn, OuterFn, OuterAllocaBlock, Ident,
2144 IfCondition, NumThreads, PrivTID, PrivTIDAddr,
2145 ThreadID, ToBeDeletedVec);
2146 };
2147 } else {
2148 // Generate OpenMP host runtime call
2149 OI->PostOutlineCB = [=, ToBeDeletedVec =
2150 std::move(ToBeDeleted)](Function &OutlinedFn) {
2151 hostParallelCallback(this, OutlinedFn, OuterFn, Ident, IfCondition,
2152 PrivTID, PrivTIDAddr, ToBeDeletedVec);
2153 };
2154 }
2155
2156 OI->FixUpNonEntryAllocas = true;
2157 OI->OuterAllocBB = OuterAllocaBlock;
2158 OI->EntryBB = PRegEntryBB;
2159 OI->ExitBB = PRegExitBB;
2160 OI->OuterDeallocBBs.reserve(OuterDeallocBlocks.size());
2161 copy(OuterDeallocBlocks, OI->OuterDeallocBBs.end());
2162
2163 SmallPtrSet<BasicBlock *, 32> ParallelRegionBlockSet;
2165 OI->collectBlocks(ParallelRegionBlockSet, Blocks);
2166
2167 CodeExtractorAnalysisCache CEAC(*OuterFn);
2168 CodeExtractor Extractor(Blocks, /* DominatorTree */ nullptr,
2169 /* AggregateArgs */ false,
2170 /* BlockFrequencyInfo */ nullptr,
2171 /* BranchProbabilityInfo */ nullptr,
2172 /* AssumptionCache */ nullptr,
2173 /* AllowVarArgs */ true,
2174 /* AllowAlloca */ true,
2175 /* AllocationBlock */ OuterAllocaBlock,
2176 /* DeallocationBlocks */ {},
2177 /* Suffix */ ".omp_par", ArgsInZeroAddressSpace);
2178
2179 // Find inputs to, outputs from the code region.
2180 BasicBlock *CommonExit = nullptr;
2181 SetVector<Value *> Inputs, Outputs, SinkingCands, HoistingCands;
2182 Extractor.findAllocas(CEAC, SinkingCands, HoistingCands, CommonExit);
2183
2184 Extractor.findInputsOutputs(Inputs, Outputs, SinkingCands,
2185 /*CollectGlobalInputs=*/true);
2186
2187 Inputs.remove_if([&](Value *I) {
2189 return GV->getValueType() == OpenMPIRBuilder::Ident;
2190
2191 return false;
2192 });
2193
2194 LLVM_DEBUG(dbgs() << "Before privatization: " << *OuterFn << "\n");
2195
2196 FunctionCallee TIDRTLFn =
2197 getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_global_thread_num);
2198
2199 auto PrivHelper = [&](Value &V) -> Error {
2200 if (&V == TIDAddr || &V == ZeroAddr) {
2201 OI->ExcludeArgsFromAggregate.push_back(&V);
2202 return Error::success();
2203 }
2204
2206 for (Use &U : V.uses())
2207 if (auto *UserI = dyn_cast<Instruction>(U.getUser()))
2208 if (ParallelRegionBlockSet.count(UserI->getParent()))
2209 Uses.insert(&U);
2210
2211 // __kmpc_fork_call expects extra arguments as pointers. If the input
2212 // already has a pointer type, everything is fine. Otherwise, store the
2213 // value onto stack and load it back inside the to-be-outlined region. This
2214 // will ensure only the pointer will be passed to the function.
2215 // FIXME: if there are more than 15 trailing arguments, they must be
2216 // additionally packed in a struct.
2217 Value *Inner = &V;
2218 if (!V.getType()->isPointerTy()) {
2220 LLVM_DEBUG(llvm::dbgs() << "Forwarding input as pointer: " << V << "\n");
2221
2222 Builder.restoreIP(OuterAllocIP);
2223 Value *Ptr;
2224 if (UsesDeviceSharedMemory) {
2225 // Use device shared memory instead, if needed.
2226 Ptr = createOMPAllocShared(Builder, V.getType(),
2227 V.getName() + ".reloaded");
2228 for (BasicBlock *DeallocBlock : OuterDeallocBlocks) {
2229 assert(DeallocBlock->getParent() ==
2230 OuterAllocIP.getNodeParent()->getParent() &&
2231 "Dealloc block must be in the allocation's function to reuse "
2232 "its debug location");
2233 createOMPFreeShared({DeallocBlock->getFirstInsertionPt(),
2234 Builder.getCurrentDebugLocation()},
2235 Ptr, V.getType());
2236 }
2237 } else {
2238 Ptr = Builder.CreateAlloca(V.getType(), nullptr,
2239 V.getName() + ".reloaded");
2240 }
2241
2242 // Store to stack at end of the block that currently branches to the entry
2243 // block of the to-be-outlined region.
2244 Builder.SetInsertPoint(InsertBB->getTerminator()->getIterator());
2245 Builder.CreateStore(&V, Ptr);
2246
2247 // Load back next to allocations in the to-be-outlined region.
2248 Builder.restoreIP(InnerAllocaIP);
2249 Inner = Builder.CreateLoad(V.getType(), Ptr);
2250 }
2251
2252 Value *ReplacementValue = nullptr;
2253 CallInst *CI = dyn_cast<CallInst>(&V);
2254 if (CI && CI->getCalledFunction() == TIDRTLFn.getCallee()) {
2255 ReplacementValue = PrivTID;
2256 } else {
2257 InsertPointOrErrorTy AfterIP =
2258 PrivCB(InnerAllocaIP, Builder.saveIP(), V, *Inner, ReplacementValue);
2259 if (!AfterIP)
2260 return AfterIP.takeError();
2261 Builder.restoreIP(*AfterIP);
2262 InnerAllocaIP =
2263 InnerAllocaIP.getNodeParent()->getTerminator()->getIterator();
2264
2265 assert(ReplacementValue &&
2266 "Expected copy/create callback to set replacement value!");
2267 if (ReplacementValue == &V)
2268 return Error::success();
2269 }
2270
2271 for (Use *UPtr : Uses)
2272 UPtr->set(ReplacementValue);
2273
2274 return Error::success();
2275 };
2276
2277 // Reset the inner alloca insertion as it will be used for loading the values
2278 // wrapped into pointers before passing them into the to-be-outlined region.
2279 // Configure it to insert immediately after the fake use of zero address so
2280 // that they are available in the generated body and so that the
2281 // OpenMP-related values (thread ID and zero address pointers) remain leading
2282 // in the argument list.
2283 InnerAllocaIP = ZeroAddrUse->getNextNode()->getIterator();
2284
2285 // Reset the outer alloca insertion point to the entry of the relevant block
2286 // in case it was invalidated.
2287 OuterAllocIP = OuterAllocaBlock->getFirstInsertionPt();
2288
2289 for (Value *Input : Inputs) {
2290 LLVM_DEBUG(dbgs() << "Captured input: " << *Input << "\n");
2291 if (Error Err = PrivHelper(*Input))
2292 return Err;
2293 }
2294 LLVM_DEBUG({
2295 for (Value *Output : Outputs)
2296 LLVM_DEBUG(dbgs() << "Captured output: " << *Output << "\n");
2297 });
2298 assert(Outputs.empty() &&
2299 "OpenMP outlining should not produce live-out values!");
2300
2301 LLVM_DEBUG(dbgs() << "After privatization: " << *OuterFn << "\n");
2302 LLVM_DEBUG({
2303 for (auto *BB : Blocks)
2304 dbgs() << " PBR: " << BB->getName() << "\n";
2305 });
2306
2307 // Adjust the finalization stack, verify the adjustment, and call the
2308 // finalize function a last time to finalize values between the pre-fini
2309 // block and the exit block if we left the parallel "the normal way".
2310 auto FiniInfo = FinalizationStack.pop_back_val();
2311 (void)FiniInfo;
2312 assert(FiniInfo.DK == OMPD_parallel &&
2313 "Unexpected finalization stack state!");
2314
2315 Instruction *PRegPreFiniTI = PRegPreFiniBB->getTerminator();
2316
2317 InsertPointTy PreFiniIP(PRegPreFiniTI->getIterator());
2318 Expected<BasicBlock *> FiniBBOrErr = FiniInfo.getFiniBB(Builder);
2319 if (!FiniBBOrErr)
2320 return FiniBBOrErr.takeError();
2321 {
2323 Builder.restoreIP(PreFiniIP);
2324 Builder.CreateBr(*FiniBBOrErr);
2325 // There's currently a branch to omp.par.exit. Delete it. We will get there
2326 // via the fini block
2327 Builder.GetInsertBlock()->getTerminator()->eraseFromParent();
2328 }
2329
2330 // Register the outlined info.
2331 addOutlineInfo(std::move(OI));
2332
2333 InsertPointTy AfterIP(UI->getParent()->end());
2334 UI->eraseFromParent();
2335
2336 return AfterIP;
2337}
2338
2340 AtomicOrdering AO, AtomicScope Scope) {
2341 // A flush with a list is a strong flush, which is treated as seq_cst.
2342 if (AO == AtomicOrdering::NotAtomic)
2344
2345 // A flush without a list corresponds to atomic_thread_fence, so on a GPU
2346 // emit the fence directly rather than calling into the device runtime.
2347 if (Config.IsGPU.value_or(M.getTargetTriple().isGPU())) {
2348 StringRef ScopeName =
2349 getAtomicScopeIRString(M.getTargetTriple(), Scope).value_or("");
2350 Builder.CreateFence(AO, M.getContext().getOrInsertSyncScopeID(ScopeName));
2351 return;
2352 }
2353
2354 uint32_t SrcLocStrSize;
2355 Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
2356 Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
2358 Scope == AtomicScope::Device) {
2359 // Build call void __kmpc_flush(ident_t *loc)
2361 getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_flush), {Ident});
2362 return;
2363 }
2364 // Build call void __kmpc_flush_explicit(ident_t *loc, kmp_int32 order,
2365 // kmp_int32 scope), where order is an __ATOMIC_* value and scope is a
2366 // __MEMORY_SCOPE_* value.
2367 Value *Args[] = {Ident, Builder.getInt32(static_cast<unsigned>(toCABI(AO))),
2368 Builder.getInt32(static_cast<unsigned>(Scope))};
2370 getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_flush_explicit), Args);
2371}
2372
2374 AtomicOrdering AO, AtomicScope Scope) {
2375 if (!updateToLocation(Loc))
2376 return;
2377 emitFlush(Loc, AO, Scope);
2378}
2379
2381 Value *Message) {
2382 if (!updateToLocation(Loc))
2383 return;
2384
2385 // Build call void __kmpc_error(ident_t *loc, int severity,
2386 // const char *message)
2387 uint32_t SrcLocStrSize;
2388 Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
2389 Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
2390 // Severity: 1 = warning, 2 = fatal.
2391 Value *Severity = ConstantInt::get(Int32, IsFatal ? 2 : 1);
2392 Value *MessageArg = Message ? Message : ConstantPointerNull::get(Int8Ptr);
2393 Value *Args[] = {Ident, Severity, MessageArg};
2394
2396 Args);
2397}
2398
2400 // Build call __kmpc_omp_taskyield(loc, thread_id, 0);
2401 uint32_t SrcLocStrSize;
2402 Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
2403 Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
2404 Constant *I32Null = ConstantInt::getNullValue(Int32);
2405 Value *Args[] = {Ident, getOrCreateThreadID(Ident), I32Null};
2406
2408 getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_omp_taskyield), Args);
2409}
2410
2416
2418 const DependData &Dep) {
2419 // Store the pointer to the variable
2420 Value *Addr = Builder.CreateStructGEP(
2421 DependInfo, Entry,
2422 static_cast<unsigned int>(RTLDependInfoFields::BaseAddr));
2423 Value *DepValPtr = Builder.CreatePtrToInt(Dep.DepVal, SizeTy);
2424 Builder.CreateStore(DepValPtr, Addr);
2425 // Store the size of the variable
2426 Value *Size = Builder.CreateStructGEP(
2427 DependInfo, Entry, static_cast<unsigned int>(RTLDependInfoFields::Len));
2428 Builder.CreateStore(
2429 ConstantInt::get(SizeTy,
2430 M.getDataLayout().getTypeStoreSize(Dep.DepValueType)),
2431 Size);
2432 // Store the dependency kind
2433 Value *Flags = Builder.CreateStructGEP(
2434 DependInfo, Entry, static_cast<unsigned int>(RTLDependInfoFields::Flags));
2435 Builder.CreateStore(ConstantInt::get(Builder.getInt8Ty(),
2436 static_cast<unsigned int>(Dep.DepKind)),
2437 Flags);
2438}
2439
2440// Processes the dependencies in Dependencies and does the following
2441// - Allocates space on the stack of an array of DependInfo objects
2442// - Populates each DependInfo object with relevant information of
2443// the corresponding dependence.
2444// - All code is inserted in the entry block of the current function.
2446 OpenMPIRBuilder &OMPBuilder,
2448 // Early return if we have no dependencies to process
2449 if (Dependencies.empty())
2450 return nullptr;
2451
2452 // Given a vector of DependData objects, in this function we create an
2453 // array on the stack that holds kmp_depend_info objects corresponding
2454 // to each dependency. This is then passed to the OpenMP runtime.
2455 // For example, if there are 'n' dependencies then the following psedo
2456 // code is generated. Assume the first dependence is on a variable 'a'
2457 //
2458 // \code{c}
2459 // DepArray = alloc(n x sizeof(kmp_depend_info);
2460 // idx = 0;
2461 // DepArray[idx].base_addr = ptrtoint(&a);
2462 // DepArray[idx].len = 8;
2463 // DepArray[idx].flags = Dep.DepKind; /*(See OMPContants.h for DepKind)*/
2464 // ++idx;
2465 // DepArray[idx].base_addr = ...;
2466 // \endcode
2467
2468 IRBuilderBase &Builder = OMPBuilder.Builder;
2469 Type *DependInfo = OMPBuilder.DependInfo;
2470
2471 Value *DepArray = nullptr;
2472 Type *DepArrayTy = ArrayType::get(DependInfo, Dependencies.size());
2473 {
2474 // Use a InsertPointGuard to restore the location back along with the
2475 // insertion point.
2476 IRBuilderBase::InsertPointGuard IPGuard(Builder);
2477 Builder.SetInsertPoint(
2478 Builder.GetInsertBlock()->getParent()->getEntryBlock().getTerminator());
2479 DepArray = Builder.CreateAlloca(DepArrayTy, nullptr, ".dep.arr.addr");
2480 }
2481
2482 for (const auto &[DepIdx, Dep] : enumerate(Dependencies)) {
2483 Value *Base =
2484 Builder.CreateConstInBoundsGEP2_64(DepArrayTy, DepArray, 0, DepIdx);
2485 OMPBuilder.emitTaskDependency(Builder, Base, Dep);
2486 }
2487 return DepArray;
2488}
2489
2491 // Build call kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
2492 // global_tid);
2493 uint32_t SrcLocStrSize;
2494 Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
2495 Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
2496 Value *Args[] = {Ident, getOrCreateThreadID(Ident)};
2497
2498 // Ignore return result until untied tasks are supported.
2500 getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_omp_taskwait), Args);
2501}
2502
2504 DependenciesInfo Dependencies,
2505 bool IsNowait) {
2506 if (!updateToLocation(Loc))
2507 return;
2508
2509 Value *DepArray = nullptr;
2510 Type *DepArrayTy = nullptr;
2511 Value *NumDeps = nullptr;
2512 if (Dependencies.DepArray) {
2513 DepArray = Dependencies.DepArray;
2514 NumDeps = Dependencies.NumDeps;
2515 } else if (!Dependencies.Deps.empty()) {
2516 DepArrayTy = ArrayType::get(DependInfo, Dependencies.Deps.size());
2517 NumDeps = Builder.getInt32(Dependencies.Deps.size());
2518 {
2520 BasicBlock &entryBB =
2521 Builder.GetInsertBlock()->getParent()->getEntryBlock();
2522 Builder.SetInsertPoint(entryBB.getFirstInsertionPt());
2523 DepArray = Builder.CreateAlloca(DepArrayTy, nullptr, ".dep.arr.addr");
2524 }
2525
2526 for (const auto &[DepIdx, Dep] : enumerate(Dependencies.Deps)) {
2527 Value *Base =
2528 Builder.CreateConstInBoundsGEP2_64(DepArrayTy, DepArray, 0, DepIdx);
2529 this->emitTaskDependency(Builder, Base, Dep);
2530 }
2531 }
2532
2533 if (DepArray) {
2534 uint32_t SrcLocStrSize;
2535 Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
2536 Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
2537 Value *Args[] = {
2538 Ident,
2539 getOrCreateThreadID(Ident),
2540 NumDeps,
2541 DepArray,
2542 ConstantInt::get(Builder.getInt32Ty(), 0),
2544 ConstantInt::get(Builder.getInt32Ty(), IsNowait)};
2547 omp::RuntimeFunction::OMPRTL___kmpc_omp_taskwait_deps_51),
2548 Args);
2549 } else {
2551 }
2552}
2553
2554/// Create the task duplication function passed to kmpc_taskloop.
2555Expected<Value *> OpenMPIRBuilder::createTaskDuplicationFunction(
2556 Type *PrivatesTy, int32_t PrivatesIndex, TaskDupCallbackTy DupCB) {
2557 unsigned ProgramAddressSpace = M.getDataLayout().getProgramAddressSpace();
2558 if (!DupCB)
2560 PointerType::get(Builder.getContext(), ProgramAddressSpace));
2561
2562 // From OpenMP Runtime p_task_dup_t:
2563 // Routine optionally generated by the compiler for setting the lastprivate
2564 // flag and calling needed constructors for private/firstprivate objects (used
2565 // to form taskloop tasks from pattern task) Parameters: dest task, src task,
2566 // lastprivate flag.
2567 // typedef void (*p_task_dup_t)(kmp_task_t *, kmp_task_t *, kmp_int32);
2568
2569 auto *VoidPtrTy = PointerType::get(Builder.getContext(), ProgramAddressSpace);
2570
2571 FunctionType *DupFuncTy = FunctionType::get(
2572 Builder.getVoidTy(), {VoidPtrTy, VoidPtrTy, Builder.getInt32Ty()},
2573 /*isVarArg=*/false);
2574
2575 Function *DupFunction = Function::Create(DupFuncTy, Function::InternalLinkage,
2576 "omp_taskloop_dup", M);
2577 Value *DestTaskArg = DupFunction->getArg(0);
2578 Value *SrcTaskArg = DupFunction->getArg(1);
2579 Value *LastprivateFlagArg = DupFunction->getArg(2);
2580 DestTaskArg->setName("dest_task");
2581 SrcTaskArg->setName("src_task");
2582 LastprivateFlagArg->setName("lastprivate_flag");
2583
2584 IRBuilderBase::InsertPointGuard Guard(Builder);
2585 Builder.SetInsertPoint(
2586 BasicBlock::Create(Builder.getContext(), "entry", DupFunction));
2587
2588 auto GetTaskContextPtrFromArg = [&](Value *Arg) -> Value * {
2589 Type *TaskWithPrivatesTy =
2590 StructType::get(Builder.getContext(), {Task, PrivatesTy});
2591 Value *TaskPrivates = Builder.CreateGEP(
2592 TaskWithPrivatesTy, Arg, {Builder.getInt32(0), Builder.getInt32(1)});
2593 Value *ContextPtr = Builder.CreateGEP(
2594 PrivatesTy, TaskPrivates,
2595 {Builder.getInt32(0), Builder.getInt32(PrivatesIndex)});
2596 return ContextPtr;
2597 };
2598
2599 Value *DestTaskContextPtr = GetTaskContextPtrFromArg(DestTaskArg);
2600 Value *SrcTaskContextPtr = GetTaskContextPtrFromArg(SrcTaskArg);
2601
2602 DestTaskContextPtr->setName("destPtr");
2603 SrcTaskContextPtr->setName("srcPtr");
2604
2605 InsertPointTy AllocaIP(DupFunction->getEntryBlock().begin());
2606 InsertPointTy CodeGenIP = Builder.saveIP();
2607 Expected<IRBuilderBase::InsertPoint> AfterIPOrError =
2608 DupCB(AllocaIP, CodeGenIP, DestTaskContextPtr, SrcTaskContextPtr);
2609 if (!AfterIPOrError)
2610 return AfterIPOrError.takeError();
2611 Builder.restoreIP(*AfterIPOrError);
2612
2613 Builder.CreateRetVoid();
2614
2615 return DupFunction;
2616}
2617
2618OpenMPIRBuilder::InsertPointOrErrorTy OpenMPIRBuilder::createTaskloop(
2619 const LocationDescription &Loc, InsertPointTy AllocaIP,
2620 ArrayRef<BasicBlock *> DeallocBlocks, BodyGenCallbackTy BodyGenCB,
2621 llvm::function_ref<llvm::Expected<llvm::CanonicalLoopInfo *>()> LoopInfo,
2622 Value *LBVal, Value *UBVal, Value *StepVal, bool Untied, Value *IfCond,
2623 Value *GrainSize, bool NoGroup, int Sched, Value *Final, bool Mergeable,
2624 Value *Priority, uint64_t NumOfCollapseLoops, TaskDupCallbackTy DupCB,
2625 Value *TaskContextStructPtrVal, bool FreeAgent) {
2626
2627 if (!updateToLocation(Loc))
2628 return InsertPointTy();
2629
2630 uint32_t SrcLocStrSize;
2631 Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
2632 Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
2633
2634 BasicBlock *TaskloopExitBB =
2635 splitBB(Builder, /*CreateBranch=*/true, "taskloop.exit");
2636 BasicBlock *TaskloopBodyBB =
2637 splitBB(Builder, /*CreateBranch=*/true, "taskloop.body");
2638 BasicBlock *TaskloopAllocaBB =
2639 splitBB(Builder, /*CreateBranch=*/true, "taskloop.alloca");
2640
2641 InsertPointTy TaskloopAllocaIP = TaskloopAllocaBB->begin();
2642 InsertPointTy TaskloopBodyIP = TaskloopBodyBB->begin();
2643
2644 if (Error Err = BodyGenCB(TaskloopAllocaIP, TaskloopBodyIP, TaskloopExitBB))
2645 return Err;
2646
2647 llvm::Expected<llvm::CanonicalLoopInfo *> result = LoopInfo();
2648 if (!result) {
2649 return result.takeError();
2650 }
2651
2652 llvm::CanonicalLoopInfo *CLI = result.get();
2653 if (CLI->VirtualCollapse)
2654 CLI->reportUnsupportedVirtualCollapse();
2655 auto OI = std::make_unique<OutlineInfo>();
2656 OI->EntryBB = TaskloopAllocaBB;
2657 OI->OuterAllocBB = AllocaIP.getNodeParent();
2658 OI->ExitBB = TaskloopExitBB;
2659 OI->OuterDeallocBBs.reserve(DeallocBlocks.size());
2660 copy(DeallocBlocks, OI->OuterDeallocBBs.end());
2661
2662 // Add the thread ID argument.
2663 SmallVector<Instruction *> ToBeDeleted;
2664 // dummy instruction to be used as a fake argument
2665 OI->ExcludeArgsFromAggregate.push_back(createFakeIntVal(
2666 Builder, AllocaIP, ToBeDeleted, TaskloopAllocaIP, "global.tid", false));
2667 Value *FakeLB = createFakeIntVal(Builder, AllocaIP, ToBeDeleted,
2668 TaskloopAllocaIP, "lb", false, true);
2669 Value *FakeUB = createFakeIntVal(Builder, AllocaIP, ToBeDeleted,
2670 TaskloopAllocaIP, "ub", false, true);
2671 Value *FakeStep = createFakeIntVal(Builder, AllocaIP, ToBeDeleted,
2672 TaskloopAllocaIP, "step", false, true);
2673 // For Taskloop, we want to force the bounds being the first 3 inputs in the
2674 // aggregate struct
2675 OI->Inputs.insert(FakeLB);
2676 OI->Inputs.insert(FakeUB);
2677 OI->Inputs.insert(FakeStep);
2678 if (TaskContextStructPtrVal)
2679 OI->Inputs.insert(TaskContextStructPtrVal);
2680 assert(((TaskContextStructPtrVal && DupCB) ||
2681 (!TaskContextStructPtrVal && !DupCB)) &&
2682 "Task context struct ptr and duplication callback must be both set "
2683 "or both null");
2684
2685 // It isn't safe to run the duplication bodygen callback inside the post
2686 // outlining callback so this has to be run now before we know the real task
2687 // shareds structure type.
2688 unsigned ProgramAddressSpace = M.getDataLayout().getProgramAddressSpace();
2689 Type *PointerTy = PointerType::get(Builder.getContext(), ProgramAddressSpace);
2690 Type *FakeSharedsTy = StructType::get(
2691 Builder.getContext(),
2692 {FakeLB->getType(), FakeUB->getType(), FakeStep->getType(), PointerTy});
2693 Expected<Value *> TaskDupFnOrErr = createTaskDuplicationFunction(
2694 FakeSharedsTy,
2695 /*PrivatesIndex: the pointer after the three indices above*/ 3, DupCB);
2696 if (!TaskDupFnOrErr) {
2697 return TaskDupFnOrErr.takeError();
2698 }
2699 Value *TaskDupFn = *TaskDupFnOrErr;
2700
2701 OI->PostOutlineCB = [this, Ident, LBVal, UBVal, StepVal, Untied,
2702 TaskloopAllocaBB, CLI, TaskDupFn, ToBeDeleted, IfCond,
2703 GrainSize, NoGroup, Sched, FakeLB, FakeUB, FakeStep,
2704 FakeSharedsTy, Final, Mergeable, Priority,
2705 NumOfCollapseLoops,
2706 FreeAgent](Function &OutlinedFn) mutable {
2707 // Replace the Stale CI by appropriate RTL function call.
2708 assert(OutlinedFn.hasOneUse() &&
2709 "there must be a single user for the outlined function");
2710 CallInst *StaleCI = cast<CallInst>(OutlinedFn.user_back());
2711
2712 /* Create the casting for the Bounds Values that can be used when outlining
2713 * to replace the uses of the fakes with real values */
2714 BasicBlock *CodeReplBB = StaleCI->getParent();
2715 Builder.SetInsertPoint(CodeReplBB->getFirstInsertionPt());
2716 Value *CastedLBVal =
2717 Builder.CreateIntCast(LBVal, Builder.getInt64Ty(), true, "lb64");
2718 Value *CastedUBVal =
2719 Builder.CreateIntCast(UBVal, Builder.getInt64Ty(), true, "ub64");
2720 Value *CastedStepVal =
2721 Builder.CreateIntCast(StepVal, Builder.getInt64Ty(), true, "step64");
2722
2723 Builder.SetInsertPoint(StaleCI);
2724
2725 // Gather the arguments for emitting the runtime call for
2726 // @__kmpc_omp_task_alloc
2727 Function *TaskAllocFn =
2728 getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_omp_task_alloc);
2729
2730 Value *ThreadID = getOrCreateThreadID(Ident);
2731
2732 if (!NoGroup) {
2733 // Emit runtime call for @__kmpc_taskgroup
2734 Function *TaskgroupFn =
2735 getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_taskgroup);
2736 Builder.CreateCall(TaskgroupFn, {Ident, ThreadID});
2737 }
2738
2739 // `flags` Argument Configuration
2740 // Task is tied if (Flags & 1) == 1.
2741 // Task is untied if (Flags & 1) == 0.
2742 // Task is final if (Flags & 2) == 2.
2743 // Task is not final if (Flags & 2) == 0.
2744 // Task is mergeable if (Flags & 4) == 4.
2745 // Task is not mergeable if (Flags & 4) == 0.
2746 // Task is priority if (Flags & 32) == 32.
2747 // Task is not priority if (Flags & 32) == 0.
2748 // Task is free-agent eligible if (Flags & 128) == 128.
2749 // Task is not free-agent eligible if (Flags & 128) == 0.
2750 Value *Flags = Builder.getInt32(Untied ? 0 : 1);
2751 if (Final)
2752 Flags = Builder.CreateOr(Builder.getInt32(2), Flags);
2753 if (Mergeable)
2754 Flags = Builder.CreateOr(Builder.getInt32(4), Flags);
2755 if (Priority)
2756 Flags = Builder.CreateOr(Builder.getInt32(32), Flags);
2757 if (FreeAgent)
2758 Flags = Builder.CreateOr(Builder.getInt32(128), Flags);
2759
2760 Value *TaskSize = Builder.getInt64(
2761 divideCeil(M.getDataLayout().getTypeSizeInBits(Task), 8));
2762
2763 AllocaInst *ArgStructAlloca =
2765 assert(ArgStructAlloca &&
2766 "Unable to find the alloca instruction corresponding to arguments "
2767 "for extracted function");
2768 std::optional<TypeSize> ArgAllocSize =
2769 ArgStructAlloca->getAllocationSize(M.getDataLayout());
2770 assert(ArgAllocSize &&
2771 "Unable to determine size of arguments for extracted function");
2772 Value *SharedsSize = Builder.getInt64(ArgAllocSize->getFixedValue());
2773
2774 // Emit the @__kmpc_omp_task_alloc runtime call
2775 // The runtime call returns a pointer to an area where the task captured
2776 // variables must be copied before the task is run (TaskData)
2777 CallInst *TaskData = Builder.CreateCall(
2778 TaskAllocFn, {/*loc_ref=*/Ident, /*gtid=*/ThreadID, /*flags=*/Flags,
2779 /*sizeof_task=*/TaskSize, /*sizeof_shared=*/SharedsSize,
2780 /*task_func=*/&OutlinedFn});
2781
2782 Value *Shareds = StaleCI->getArgOperand(1);
2783 Align Alignment = TaskData->getPointerAlignment(M.getDataLayout());
2784 Value *TaskShareds = Builder.CreateLoad(VoidPtr, TaskData);
2785 Builder.CreateMemCpy(TaskShareds, Alignment, Shareds, Alignment,
2786 SharedsSize);
2787 // Get the pointer to loop lb, ub, step from task ptr
2788 // and set up the lowerbound,upperbound and step values
2789 llvm::Value *Lb = Builder.CreateGEP(
2790 FakeSharedsTy, TaskShareds, {Builder.getInt32(0), Builder.getInt32(0)});
2791
2792 llvm::Value *Ub = Builder.CreateGEP(
2793 FakeSharedsTy, TaskShareds, {Builder.getInt32(0), Builder.getInt32(1)});
2794
2795 llvm::Value *Step = Builder.CreateGEP(
2796 FakeSharedsTy, TaskShareds, {Builder.getInt32(0), Builder.getInt32(2)});
2797 llvm::Value *Loadstep = Builder.CreateLoad(Builder.getInt64Ty(), Step);
2798
2799 // set up the arguments for emitting kmpc_taskloop runtime call
2800 // setting values for ifval, nogroup, sched, grainsize, task_dup
2801 Value *IfCondVal =
2802 IfCond ? Builder.CreateIntCast(IfCond, Builder.getInt32Ty(), true)
2803 : Builder.getInt32(1);
2804 // As __kmpc_taskgroup is called manually in OMPIRBuilder, NoGroupVal should
2805 // always be 1 when calling __kmpc_taskloop to ensure it is not called again
2806 Value *NoGroupVal = Builder.getInt32(1);
2807 Value *SchedVal = Builder.getInt32(Sched);
2808 Value *GrainSizeVal =
2809 GrainSize ? Builder.CreateIntCast(GrainSize, Builder.getInt64Ty(), true)
2810 : Builder.getInt64(0);
2811 Value *TaskDup = TaskDupFn;
2812
2813 Value *Args[] = {Ident, ThreadID, TaskData, IfCondVal, Lb, Ub,
2814 Loadstep, NoGroupVal, SchedVal, GrainSizeVal, TaskDup};
2815
2816 // taskloop runtime call
2817 Function *TaskloopFn =
2818 getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_taskloop);
2819 Builder.CreateCall(TaskloopFn, Args);
2820
2821 // Emit the @__kmpc_end_taskgroup runtime call to end the taskgroup if
2822 // nogroup is not defined
2823 if (!NoGroup) {
2824 Function *EndTaskgroupFn =
2825 getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_end_taskgroup);
2826 Builder.CreateCall(EndTaskgroupFn, {Ident, ThreadID});
2827 }
2828
2829 StaleCI->eraseFromParent();
2830
2831 Builder.SetInsertPoint(TaskloopAllocaBB->begin());
2832
2833 LoadInst *SharedsOutlined =
2834 Builder.CreateLoad(VoidPtr, OutlinedFn.getArg(1));
2835 OutlinedFn.getArg(1)->replaceUsesWithIf(
2836 SharedsOutlined,
2837 [SharedsOutlined](Use &U) { return U.getUser() != SharedsOutlined; });
2838
2839 Value *IV = CLI->getIndVar();
2840 Type *IVTy = IV->getType();
2841 Constant *One = ConstantInt::get(Builder.getInt64Ty(), 1);
2842
2843 // When outlining, CodeExtractor will create GEP's to the LowerBound and
2844 // UpperBound. These GEP's can be reused for loading the tasks respective
2845 // bounds.
2846 Value *TaskLB = nullptr;
2847 Value *TaskUB = nullptr;
2848 Value *TaskStep = nullptr;
2849 Value *LoadTaskLB = nullptr;
2850 Value *LoadTaskUB = nullptr;
2851 Value *LoadTaskStep = nullptr;
2852 for (Instruction &I : *TaskloopAllocaBB) {
2853 if (I.getOpcode() == Instruction::GetElementPtr) {
2854 GetElementPtrInst &Gep = cast<GetElementPtrInst>(I);
2855 if (ConstantInt *CI = dyn_cast<ConstantInt>(Gep.getOperand(2))) {
2856 switch (CI->getZExtValue()) {
2857 case 0:
2858 TaskLB = &I;
2859 break;
2860 case 1:
2861 TaskUB = &I;
2862 break;
2863 case 2:
2864 TaskStep = &I;
2865 break;
2866 }
2867 }
2868 } else if (I.getOpcode() == Instruction::Load) {
2869 LoadInst &Load = cast<LoadInst>(I);
2870 if (Load.getPointerOperand() == TaskLB) {
2871 assert(TaskLB != nullptr && "Expected value for TaskLB");
2872 LoadTaskLB = &I;
2873 } else if (Load.getPointerOperand() == TaskUB) {
2874 assert(TaskUB != nullptr && "Expected value for TaskUB");
2875 LoadTaskUB = &I;
2876 } else if (Load.getPointerOperand() == TaskStep) {
2877 assert(TaskStep != nullptr && "Expected value for TaskStep");
2878 LoadTaskStep = &I;
2879 }
2880 }
2881 }
2882
2883 Builder.SetInsertPoint(CLI->getPreheader()->getTerminator());
2884
2885 assert(LoadTaskLB != nullptr && "Expected value for LoadTaskLB");
2886 assert(LoadTaskUB != nullptr && "Expected value for LoadTaskUB");
2887 assert(LoadTaskStep != nullptr && "Expected value for LoadTaskStep");
2888 Value *TripCountMinusOne = Builder.CreateSDiv(
2889 Builder.CreateSub(LoadTaskUB, LoadTaskLB), LoadTaskStep);
2890 Value *TripCount = Builder.CreateAdd(TripCountMinusOne, One, "trip_cnt");
2891 Value *CastedTripCount = Builder.CreateIntCast(TripCount, IVTy, true);
2892 Value *CastedTaskLB = Builder.CreateIntCast(LoadTaskLB, IVTy, true);
2893 // set the trip count in the CLI
2894 CLI->setTripCount(CastedTripCount);
2895
2896 Builder.SetInsertPoint(CLI->getBody()->getFirstInsertionPt());
2897
2898 if (NumOfCollapseLoops > 1) {
2899 llvm::SmallVector<User *> UsersToReplace;
2900 // When using the collapse clause, the bounds of the loop have to be
2901 // adjusted to properly represent the iterator of the outer loop.
2902 Value *IVPlusTaskLB = Builder.CreateAdd(
2903 CLI->getIndVar(),
2904 Builder.CreateSub(CastedTaskLB, ConstantInt::get(IVTy, 1)));
2905 // To ensure every Use is correctly captured, we first want to record
2906 // which users to replace the value in, and then replace the value.
2907 for (auto IVUse = CLI->getIndVar()->uses().begin();
2908 IVUse != CLI->getIndVar()->uses().end(); IVUse++) {
2909 User *IVUser = IVUse->getUser();
2910 if (auto *Op = dyn_cast<BinaryOperator>(IVUser)) {
2911 if (Op->getOpcode() == Instruction::URem ||
2912 Op->getOpcode() == Instruction::UDiv) {
2913 UsersToReplace.push_back(IVUser);
2914 }
2915 }
2916 }
2917 for (User *User : UsersToReplace) {
2918 User->replaceUsesOfWith(CLI->getIndVar(), IVPlusTaskLB);
2919 }
2920 } else {
2921 // The canonical loop is generated with a fixed lower bound. We need to
2922 // update the index calculation code to use the task's lower bound. The
2923 // generated code looks like this:
2924 // %omp_loop.iv = phi ...
2925 // ...
2926 // %tmp = mul [type] %omp_loop.iv, step
2927 // %user_index = add [type] tmp, lb
2928 // OpenMPIRBuilder constructs canonical loops to have exactly three uses
2929 // of the normalised induction variable:
2930 // 1. This one: converting the normalised IV to the user IV
2931 // 2. The increment (add)
2932 // 3. The comparison against the trip count (icmp)
2933 // (1) is the only use that is a mul followed by an add so this cannot
2934 // match other IR.
2935 assert(CLI->getIndVar()->getNumUses() == 3 &&
2936 "Canonical loop should have exactly three uses of the ind var");
2937 for (User *IVUser : CLI->getIndVar()->users()) {
2938 if (auto *Mul = dyn_cast<BinaryOperator>(IVUser)) {
2939 if (Mul->getOpcode() == Instruction::Mul) {
2940 for (User *MulUser : Mul->users()) {
2941 if (auto *Add = dyn_cast<BinaryOperator>(MulUser)) {
2942 if (Add->getOpcode() == Instruction::Add) {
2943 Add->setOperand(1, CastedTaskLB);
2944 }
2945 }
2946 }
2947 }
2948 }
2949 }
2950 }
2951
2952 FakeLB->replaceAllUsesWith(CastedLBVal);
2953 FakeUB->replaceAllUsesWith(CastedUBVal);
2954 FakeStep->replaceAllUsesWith(CastedStepVal);
2955 for (Instruction *I : llvm::reverse(ToBeDeleted)) {
2956 I->eraseFromParent();
2957 }
2958 };
2959
2960 addOutlineInfo(std::move(OI));
2961 Builder.SetInsertPoint(TaskloopExitBB->begin());
2962 return Builder.saveIP();
2963}
2964
2967 M.getContext(), M.getDataLayout().getPointerSizeInBits());
2969 llvm::Type::getInt32Ty(M.getContext()));
2970}
2971
2973 const LocationDescription &Loc, InsertPointTy AllocaIP,
2974 ArrayRef<BasicBlock *> DeallocBlocks, BodyGenCallbackTy BodyGenCB,
2975 bool Tied, Value *Final, Value *IfCondition,
2976 const DependenciesInfo &Dependencies, const AffinityData &Affinities,
2977 bool Mergeable, Value *EventHandle, Value *Priority, bool FreeAgent) {
2978
2979 if (!updateToLocation(Loc))
2980 return InsertPointTy();
2981
2982 uint32_t SrcLocStrSize;
2983 Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
2984 Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
2985 // The current basic block is split into four basic blocks. After outlining,
2986 // they will be mapped as follows:
2987 // ```
2988 // def current_fn() {
2989 // current_basic_block:
2990 // br label %task.exit
2991 // task.exit:
2992 // ; instructions after task
2993 // }
2994 // def outlined_fn() {
2995 // task.alloca:
2996 // br label %task.body
2997 // task.body:
2998 // ret void
2999 // }
3000 // ```
3001 BasicBlock *TaskExitBB = splitBB(Builder, /*CreateBranch=*/true, "task.exit");
3002 BasicBlock *TaskBodyBB = splitBB(Builder, /*CreateBranch=*/true, "task.body");
3003 BasicBlock *TaskAllocaBB =
3004 splitBB(Builder, /*CreateBranch=*/true, "task.alloca");
3005
3006 InsertPointTy TaskAllocaIP = TaskAllocaBB->begin();
3007 InsertPointTy TaskBodyIP = TaskBodyBB->begin();
3008 if (Error Err = BodyGenCB(TaskAllocaIP, TaskBodyIP, TaskExitBB))
3009 return Err;
3010
3011 auto OI = std::make_unique<OutlineInfo>();
3012 OI->EntryBB = TaskAllocaBB;
3013 OI->OuterAllocBB = AllocaIP.getNodeParent();
3014 OI->ExitBB = TaskExitBB;
3015 OI->OuterDeallocBBs.reserve(DeallocBlocks.size());
3016 copy(DeallocBlocks, OI->OuterDeallocBBs.end());
3017
3018 // Add the thread ID argument.
3020 OI->ExcludeArgsFromAggregate.push_back(createFakeIntVal(
3021 Builder, AllocaIP, ToBeDeleted, TaskAllocaIP, "global.tid", false));
3022
3023 OI->PostOutlineCB = [this, Ident, Tied, Final, IfCondition, Dependencies,
3024 Affinities, Mergeable, Priority, EventHandle, FreeAgent,
3025 TaskAllocaBB,
3026 ToBeDeleted](Function &OutlinedFn) mutable {
3027 // Replace the Stale CI by appropriate RTL function call.
3028 assert(OutlinedFn.hasOneUse() &&
3029 "there must be a single user for the outlined function");
3030 CallInst *StaleCI = cast<CallInst>(OutlinedFn.user_back());
3031
3032 // HasShareds is true if any variables are captured in the outlined region,
3033 // false otherwise.
3034 bool HasShareds = StaleCI->arg_size() > 1;
3035 Builder.SetInsertPoint(StaleCI);
3036
3037 // Gather the arguments for emitting the runtime call for
3038 // @__kmpc_omp_task_alloc
3039 Function *TaskAllocFn =
3040 getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_omp_task_alloc);
3041
3042 // Arguments - `loc_ref` (Ident) and `gtid` (ThreadID)
3043 // call.
3044 Value *ThreadID = getOrCreateThreadID(Ident);
3045
3046 // Argument - `flags`
3047 // Task is tied iff (Flags & 1) == 1.
3048 // Task is untied iff (Flags & 1) == 0.
3049 // Task is final iff (Flags & 2) == 2.
3050 // Task is not final iff (Flags & 2) == 0.
3051 // Task is mergeable or merged-if0 iff (Flags & 4) == 4.
3052 // Task is neither mergeable nor merged-if0 iff (Flags & 4) == 0.
3053 // Task is detachable iff (Flags & 64) == 64.
3054 // Task is not detachable iff (Flags & 64) == 0.
3055 // Task is priority iff (Flags & 32) == 32.
3056 // Task is not priority iff (Flags & 32) == 0.
3057 // Task is free-agent eligible iff (Flags & 128) == 128.
3058 // Task is not free-agent eligible iff (Flags & 128) == 0.
3059 // TODO: Handle the other flags.
3060 Value *Flags = Builder.getInt32(Tied);
3061 auto *ConstIfCondition = dyn_cast_or_null<ConstantInt>(IfCondition);
3062 bool UseMergedIf0Path = ConstIfCondition && ConstIfCondition->isZero();
3063 if (Final) {
3064 Value *FinalFlag =
3065 Builder.CreateSelect(Final, Builder.getInt32(2), Builder.getInt32(0));
3066 Flags = Builder.CreateOr(FinalFlag, Flags);
3067 }
3068
3069 if (Mergeable || UseMergedIf0Path)
3070 Flags = Builder.CreateOr(Builder.getInt32(4), Flags);
3071 if (EventHandle)
3072 Flags = Builder.CreateOr(Builder.getInt32(64), Flags);
3073 if (Priority)
3074 Flags = Builder.CreateOr(Builder.getInt32(32), Flags);
3075 if (FreeAgent)
3076 Flags = Builder.CreateOr(Builder.getInt32(128), Flags);
3077
3078 // Argument - `sizeof_kmp_task_t` (TaskSize)
3079 // Tasksize refers to the size in bytes of kmp_task_t data structure
3080 // including private vars accessed in task.
3081 // TODO: add kmp_task_t_with_privates (privates)
3082 Value *TaskSize = Builder.getInt64(
3083 divideCeil(M.getDataLayout().getTypeSizeInBits(Task), 8));
3084
3085 // Argument - `sizeof_shareds` (SharedsSize)
3086 // SharedsSize refers to the shareds array size in the kmp_task_t data
3087 // structure.
3088 Value *SharedsSize = Builder.getInt64(0);
3089 if (HasShareds) {
3090 AllocaInst *ArgStructAlloca =
3092 assert(ArgStructAlloca &&
3093 "Unable to find the alloca instruction corresponding to arguments "
3094 "for extracted function");
3095 std::optional<TypeSize> ArgAllocSize =
3096 ArgStructAlloca->getAllocationSize(M.getDataLayout());
3097 assert(ArgAllocSize &&
3098 "Unable to determine size of arguments for extracted function");
3099 SharedsSize = Builder.getInt64(ArgAllocSize->getFixedValue());
3100 }
3101 // Emit the @__kmpc_omp_task_alloc runtime call
3102 // The runtime call returns a pointer to an area where the task captured
3103 // variables must be copied before the task is run (TaskData)
3105 TaskAllocFn, {/*loc_ref=*/Ident, /*gtid=*/ThreadID, /*flags=*/Flags,
3106 /*sizeof_task=*/TaskSize, /*sizeof_shared=*/SharedsSize,
3107 /*task_func=*/&OutlinedFn});
3108
3109 if (Affinities.Count && Affinities.Info) {
3111 OMPRTL___kmpc_omp_reg_task_with_affinity);
3112
3113 createRuntimeFunctionCall(RegAffFn, {Ident, ThreadID, TaskData,
3114 Affinities.Count, Affinities.Info});
3115 }
3116
3117 // Emit detach clause initialization.
3118 // evt = (typeof(evt))__kmpc_task_allow_completion_event(loc, tid,
3119 // task_descriptor);
3120 if (EventHandle) {
3122 OMPRTL___kmpc_task_allow_completion_event);
3123 llvm::Value *EventVal =
3124 createRuntimeFunctionCall(TaskDetachFn, {Ident, ThreadID, TaskData});
3125 llvm::Value *EventHandleAddr =
3126 Builder.CreatePointerBitCastOrAddrSpaceCast(EventHandle,
3127 Builder.getPtrTy(0));
3128 EventVal = Builder.CreatePtrToInt(EventVal, Builder.getInt64Ty());
3129 Builder.CreateStore(EventVal, EventHandleAddr);
3130 }
3131 // Copy the arguments for outlined function
3132 if (HasShareds) {
3133 Value *Shareds = StaleCI->getArgOperand(1);
3134 Align Alignment = TaskData->getPointerAlignment(M.getDataLayout());
3135 Value *TaskShareds = Builder.CreateLoad(VoidPtr, TaskData);
3136 Builder.CreateMemCpy(TaskShareds, Alignment, Shareds, Alignment,
3137 SharedsSize);
3138 }
3139
3140 if (Priority) {
3141 //
3142 // The return type of "__kmpc_omp_task_alloc" is "kmp_task_t *",
3143 // we populate the priority information into the "kmp_task_t" here
3144 //
3145 // The struct "kmp_task_t" definition is available in kmp.h
3146 // kmp_task_t = { shareds, routine, part_id, data1, data2 }
3147 // data2 is used for priority
3148 //
3149 Type *Int32Ty = Builder.getInt32Ty();
3150 Constant *Zero = ConstantInt::get(Int32Ty, 0);
3151 // kmp_task_t* => { ptr }
3152 Type *TaskPtr = StructType::get(VoidPtr);
3153 Value *TaskGEP =
3154 Builder.CreateInBoundsGEP(TaskPtr, TaskData, {Zero, Zero});
3155 // kmp_task_t => { ptr, ptr, i32, ptr, ptr }
3156 Type *TaskStructType = StructType::get(
3157 VoidPtr, VoidPtr, Builder.getInt32Ty(), VoidPtr, VoidPtr);
3158 Value *PriorityData = Builder.CreateInBoundsGEP(
3159 TaskStructType, TaskGEP, {Zero, ConstantInt::get(Int32Ty, 4)});
3160 // kmp_cmplrdata_t => { ptr, ptr }
3161 Type *CmplrStructType = StructType::get(VoidPtr, VoidPtr);
3162 Value *CmplrData = Builder.CreateInBoundsGEP(CmplrStructType,
3163 PriorityData, {Zero, Zero});
3164 Builder.CreateStore(Priority, CmplrData);
3165 }
3166
3167 Value *DepArray = nullptr;
3168 Value *NumDeps = nullptr;
3169 if (Dependencies.DepArray) {
3170 DepArray = Dependencies.DepArray;
3171 NumDeps = Dependencies.NumDeps;
3172 } else if (!Dependencies.Deps.empty()) {
3173 DepArray = emitTaskDependencies(*this, Dependencies.Deps);
3174 NumDeps = Builder.getInt32(Dependencies.Deps.size());
3175 }
3176
3177 // In the presence of the `if` clause, the following IR is generated:
3178 // ...
3179 // %data = call @__kmpc_omp_task_alloc(...)
3180 // br i1 %if_condition, label %then, label %else
3181 // then:
3182 // call @__kmpc_omp_task(...)
3183 // br label %exit
3184 // else:
3185 // ;; Wait for resolution of dependencies, if any, before
3186 // ;; beginning the task
3187 // call @__kmpc_omp_wait_deps(...)
3188 // call @__kmpc_omp_task_begin_if0(...)
3189 // call @outlined_fn(...)
3190 // call @__kmpc_omp_task_complete_if0(...)
3191 // br label %exit
3192 // exit:
3193 // ...
3194 if (IfCondition && !UseMergedIf0Path) {
3195 // `SplitBlockAndInsertIfThenElse` requires the block to have a
3196 // terminator.
3197 splitBB(Builder, /*CreateBranch=*/true, "if.end");
3198 Instruction *IfTerminator =
3199 Builder.GetInsertPoint()->getParent()->getTerminator();
3200 Instruction *ThenTI = IfTerminator, *ElseTI = nullptr;
3201 Builder.SetInsertPoint(IfTerminator);
3202 SplitBlockAndInsertIfThenElse(IfCondition, IfTerminator, &ThenTI,
3203 &ElseTI);
3204 Builder.SetInsertPoint(ElseTI);
3205
3206 if (DepArray) {
3207 Function *TaskWaitFn =
3208 getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_omp_wait_deps);
3210 TaskWaitFn,
3211 {Ident, ThreadID, NumDeps, DepArray,
3212 ConstantInt::get(Builder.getInt32Ty(), 0),
3214 }
3215 Function *TaskBeginFn =
3216 getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_omp_task_begin_if0);
3217 Function *TaskCompleteFn =
3218 getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_omp_task_complete_if0);
3219 createRuntimeFunctionCall(TaskBeginFn, {Ident, ThreadID, TaskData});
3220 CallInst *CI = nullptr;
3221 if (HasShareds)
3222 CI = createRuntimeFunctionCall(&OutlinedFn, {ThreadID, TaskData});
3223 else
3224 CI = createRuntimeFunctionCall(&OutlinedFn, {ThreadID});
3225 CI->setDebugLoc(StaleCI->getDebugLoc());
3226 createRuntimeFunctionCall(TaskCompleteFn, {Ident, ThreadID, TaskData});
3227 Builder.SetInsertPoint(ThenTI);
3228 }
3229
3230 if (DepArray) {
3231 Function *TaskFn =
3232 getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_omp_task_with_deps);
3234 TaskFn,
3235 {Ident, ThreadID, TaskData, NumDeps, DepArray,
3236 ConstantInt::get(Builder.getInt32Ty(), 0),
3238
3239 } else {
3240 // Emit the @__kmpc_omp_task runtime call to spawn the task
3241 Function *TaskFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_omp_task);
3242 createRuntimeFunctionCall(TaskFn, {Ident, ThreadID, TaskData});
3243 }
3244
3245 StaleCI->eraseFromParent();
3246
3247 Builder.SetInsertPoint(TaskAllocaBB->begin());
3248 if (HasShareds) {
3249 LoadInst *Shareds = Builder.CreateLoad(VoidPtr, OutlinedFn.getArg(1));
3250 OutlinedFn.getArg(1)->replaceUsesWithIf(
3251 Shareds, [Shareds](Use &U) { return U.getUser() != Shareds; });
3252 }
3253
3254 // The insert point may refer to one of the instructions about to be
3255 // deleted. It is not needed anymore so clear it instead of leaving it
3256 // dangling.
3257 Builder.ClearInsertionPoint();
3258 for (Instruction *I : llvm::reverse(ToBeDeleted))
3259 I->eraseFromParent();
3260 };
3261
3262 addOutlineInfo(std::move(OI));
3263 Builder.SetInsertPoint(TaskExitBB->begin());
3264
3265 return Builder.saveIP();
3266}
3267
3269 const LocationDescription &Loc, InsertPointTy AllocaIP,
3270 ArrayRef<BasicBlock *> DeallocBlocks, BodyGenCallbackTy BodyGenCB) {
3271 if (!updateToLocation(Loc))
3272 return InsertPointTy();
3273
3274 uint32_t SrcLocStrSize;
3275 Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
3276 Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
3277 Value *ThreadID = getOrCreateThreadID(Ident);
3278
3279 // Emit the @__kmpc_taskgroup runtime call to start the taskgroup
3280 Function *TaskgroupFn =
3281 getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_taskgroup);
3282 createRuntimeFunctionCall(TaskgroupFn, {Ident, ThreadID});
3283
3284 BasicBlock *TaskgroupExitBB = splitBB(Builder, true, "taskgroup.exit");
3285 if (Error Err = BodyGenCB(AllocaIP, Builder.saveIP(), DeallocBlocks))
3286 return Err;
3287
3288 Builder.SetInsertPoint(TaskgroupExitBB);
3289 // Emit the @__kmpc_end_taskgroup runtime call to end the taskgroup
3290 Function *EndTaskgroupFn =
3291 getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_end_taskgroup);
3292 createRuntimeFunctionCall(EndTaskgroupFn, {Ident, ThreadID});
3293
3294 return Builder.saveIP();
3295}
3296
3298 const LocationDescription &Loc, InsertPointTy AllocaIP,
3300 FinalizeCallbackTy FiniCB, bool IsCancellable, bool IsNowait) {
3301 assert(!isConflictIP(AllocaIP, Loc.IP) && "Dedicated IP allocas required");
3302
3303 if (!updateToLocation(Loc))
3304 return Loc.IP;
3305
3306 FinalizationStack.push_back({FiniCB, OMPD_sections, IsCancellable});
3307
3308 // Each section is emitted as a switch case
3309 // Each finalization callback is handled from clang.EmitOMPSectionDirective()
3310 // -> OMP.createSection() which generates the IR for each section
3311 // Iterate through all sections and emit a switch construct:
3312 // switch (IV) {
3313 // case 0:
3314 // <SectionStmt[0]>;
3315 // break;
3316 // ...
3317 // case <NumSection> - 1:
3318 // <SectionStmt[<NumSection> - 1]>;
3319 // break;
3320 // }
3321 // ...
3322 // section_loop.after:
3323 // <FiniCB>;
3324 auto LoopBodyGenCB = [&](InsertPointTy CodeGenIP, Value *IndVar) -> Error {
3325 Builder.restoreIP(CodeGenIP);
3327 splitBBWithSuffix(Builder, /*CreateBranch=*/false, ".sections.after");
3328 Function *CurFn = Continue->getParent();
3329 SwitchInst *SwitchStmt = Builder.CreateSwitch(IndVar, Continue);
3330
3331 unsigned CaseNumber = 0;
3332 for (auto SectionCB : SectionCBs) {
3334 M.getContext(), "omp_section_loop.body.case", CurFn, Continue);
3335 SwitchStmt->addCase(Builder.getInt32(CaseNumber), CaseBB);
3336 Builder.SetInsertPoint(CaseBB);
3337 UncondBrInst *CaseEndBr = Builder.CreateBr(Continue);
3338 if (Error Err = SectionCB(InsertPointTy(), CaseEndBr->getIterator(), {}))
3339 return Err;
3340 CaseNumber++;
3341 }
3342 // remove the existing terminator from body BB since there can be no
3343 // terminators after switch/case
3344 return Error::success();
3345 };
3346 // Loop body ends here
3347 // LowerBound, UpperBound, and STride for createCanonicalLoop
3348 Type *I32Ty = Type::getInt32Ty(M.getContext());
3349 Value *LB = ConstantInt::get(I32Ty, 0);
3350 Value *UB = ConstantInt::get(I32Ty, SectionCBs.size());
3351 Value *ST = ConstantInt::get(I32Ty, 1);
3353 Loc, LoopBodyGenCB, LB, UB, ST, true, false, AllocaIP, "section_loop");
3354 if (!LoopInfo)
3355 return LoopInfo.takeError();
3356
3357 InsertPointOrErrorTy WsloopIP =
3358 applyStaticWorkshareLoop(Loc.DL, *LoopInfo, AllocaIP,
3359 WorksharingLoopType::ForStaticLoop, !IsNowait);
3360 if (!WsloopIP)
3361 return WsloopIP.takeError();
3362 InsertPointTy AfterIP = *WsloopIP;
3363
3364 BasicBlock *LoopFini = AfterIP.getNodeParent()->getSinglePredecessor();
3365 assert(LoopFini && "Bad structure of static workshare loop finalization");
3366
3367 // Apply the finalization callback in LoopAfterBB
3368 auto FiniInfo = FinalizationStack.pop_back_val();
3369 assert(FiniInfo.DK == OMPD_sections &&
3370 "Unexpected finalization stack state!");
3371 if (Error Err = FiniInfo.mergeFiniBB(Builder, LoopFini))
3372 return Err;
3373
3374 return AfterIP;
3375}
3376
3379 BodyGenCallbackTy BodyGenCB,
3380 FinalizeCallbackTy FiniCB) {
3381 if (!updateToLocation(Loc))
3382 return Loc.IP;
3383
3384 auto FiniCBWrapper = [&](InsertPointTy IP) {
3385 if (IP != IP.getNodeParent()->end())
3386 return FiniCB(IP);
3387 // This must be done otherwise any nested constructs using FinalizeOMPRegion
3388 // will fail because that function requires the Finalization Basic Block to
3389 // have a terminator, which is already removed by EmitOMPRegionBody.
3390 // IP is currently at cancelation block.
3391 // We need to backtrack to the condition block to fetch
3392 // the exit block and create a branch from cancelation
3393 // to exit block.
3395 Builder.restoreIP(IP);
3396 auto *CaseBB = Loc.IP.getNodeParent();
3397 auto *CondBB = CaseBB->getSinglePredecessor()->getSinglePredecessor();
3398 auto *ExitBB = CondBB->getTerminator()->getSuccessor(1);
3399 Instruction *I = Builder.CreateBr(ExitBB);
3400 IP = I->getIterator();
3401 return FiniCB(IP);
3402 };
3403
3404 Directive OMPD = Directive::OMPD_sections;
3405 // Since we are using Finalization Callback here, HasFinalize
3406 // and IsCancellable have to be true
3407 return EmitOMPInlinedRegion(OMPD, nullptr, nullptr, BodyGenCB, FiniCBWrapper,
3408 /*Conditional*/ false, /*hasFinalize*/ true,
3409 /*IsCancellable*/ true);
3410}
3411
3417
3418Value *OpenMPIRBuilder::getGPUThreadID() {
3421 OMPRTL___kmpc_get_hardware_thread_id_in_block),
3422 {});
3423}
3424
3425Value *OpenMPIRBuilder::getGPUWarpSize() {
3427 getOrCreateRuntimeFunction(M, OMPRTL___kmpc_get_warp_size), {});
3428}
3429
3430Value *OpenMPIRBuilder::getNVPTXWarpID() {
3431 unsigned LaneIDBits = Log2_32(Config.getGridValue().GV_Warp_Size);
3432 return Builder.CreateAShr(getGPUThreadID(), LaneIDBits, "nvptx_warp_id");
3433}
3434
3435Value *OpenMPIRBuilder::getNVPTXLaneID() {
3436 unsigned LaneIDBits = Log2_32(Config.getGridValue().GV_Warp_Size);
3437 assert(LaneIDBits < 32 && "Invalid LaneIDBits size in NVPTX device.");
3438 unsigned LaneIDMask = ~0u >> (32u - LaneIDBits);
3439 return Builder.CreateAnd(getGPUThreadID(), Builder.getInt32(LaneIDMask),
3440 "nvptx_lane_id");
3441}
3442
3443Value *OpenMPIRBuilder::castValueToType(InsertPointTy AllocaIP, Value *From,
3444 Type *ToType) {
3445 Type *FromType = From->getType();
3446 uint64_t FromSize = M.getDataLayout().getTypeStoreSize(FromType);
3447 uint64_t ToSize = M.getDataLayout().getTypeStoreSize(ToType);
3448 assert(FromSize > 0 && "From size must be greater than zero");
3449 assert(ToSize > 0 && "To size must be greater than zero");
3450 if (FromType == ToType)
3451 return From;
3452 if (FromSize == ToSize)
3453 return Builder.CreateBitCast(From, ToType);
3454 if (ToType->isIntegerTy() && FromType->isIntegerTy())
3455 return Builder.CreateIntCast(From, ToType, /*isSigned*/ true);
3456 InsertPointTy SaveIP = Builder.saveIP();
3457 Builder.restoreIP(AllocaIP);
3458 Value *CastItem = Builder.CreateAlloca(ToType);
3459 Builder.restoreIP(SaveIP);
3460
3461 Value *ValCastItem = Builder.CreatePointerBitCastOrAddrSpaceCast(
3462 CastItem, Builder.getPtrTy(0));
3463 Builder.CreateStore(From, ValCastItem);
3464 return Builder.CreateLoad(ToType, CastItem);
3465}
3466
3467Value *OpenMPIRBuilder::createRuntimeShuffleFunction(InsertPointTy AllocaIP,
3468 Value *Element,
3469 Type *ElementType,
3470 Value *Offset) {
3471 uint64_t Size = M.getDataLayout().getTypeStoreSize(ElementType);
3472 assert(Size <= 8 && "Unsupported bitwidth in shuffle instruction");
3473
3474 // Cast all types to 32- or 64-bit values before calling shuffle routines.
3475 Type *CastTy = Builder.getIntNTy(Size <= 4 ? 32 : 64);
3476 Value *ElemCast = castValueToType(AllocaIP, Element, CastTy);
3477 Value *WarpSize =
3478 Builder.CreateIntCast(getGPUWarpSize(), Builder.getInt16Ty(), true);
3480 Size <= 4 ? RuntimeFunction::OMPRTL___kmpc_shuffle_int32
3481 : RuntimeFunction::OMPRTL___kmpc_shuffle_int64);
3482 Value *WarpSizeCast =
3483 Builder.CreateIntCast(WarpSize, Builder.getInt16Ty(), /*isSigned=*/true);
3484 Value *ShuffleCall =
3485 createRuntimeFunctionCall(ShuffleFunc, {ElemCast, Offset, WarpSizeCast});
3486 // The shuffle runtime functions return a 32- or 64-bit value. Cast it back
3487 // down to the requested element type, otherwise storing the result would
3488 // write past the end of an element narrower than the shuffle width.
3489 return castValueToType(AllocaIP, ShuffleCall, ElementType);
3490}
3491
3492void OpenMPIRBuilder::shuffleAndStore(InsertPointTy AllocaIP, Value *SrcAddr,
3493 Value *DstAddr, Type *ElemType,
3494 Value *Offset, Type *ReductionArrayTy,
3495 bool IsByRefElem) {
3496 uint64_t Size = M.getDataLayout().getTypeStoreSize(ElemType);
3497 // Create the loop over the big sized data.
3498 // ptr = (void*)Elem;
3499 // ptrEnd = (void*) Elem + 1;
3500 // Step = 8;
3501 // while (ptr + Step < ptrEnd)
3502 // shuffle((int64_t)*ptr);
3503 // Step = 4;
3504 // while (ptr + Step < ptrEnd)
3505 // shuffle((int32_t)*ptr);
3506 // ...
3507 Type *IndexTy = Builder.getIndexTy(
3508 M.getDataLayout(), M.getDataLayout().getDefaultGlobalsAddressSpace());
3509 Value *ElemPtr = DstAddr;
3510 Value *Ptr = SrcAddr;
3511 for (unsigned IntSize = 8; IntSize >= 1; IntSize /= 2) {
3512 if (Size < IntSize)
3513 continue;
3514 Type *IntType = Builder.getIntNTy(IntSize * 8);
3515 Ptr = Builder.CreatePointerBitCastOrAddrSpaceCast(
3516 Ptr, Builder.getPtrTy(0), Ptr->getName() + ".ascast");
3517 Value *SrcAddrGEP =
3518 Builder.CreateGEP(ElemType, SrcAddr, {ConstantInt::get(IndexTy, 1)});
3519 ElemPtr = Builder.CreatePointerBitCastOrAddrSpaceCast(
3520 ElemPtr, Builder.getPtrTy(0), ElemPtr->getName() + ".ascast");
3521
3522 Function *CurFunc = Builder.GetInsertBlock()->getParent();
3523 if ((Size / IntSize) > 1) {
3524 Value *PtrEnd = Builder.CreatePointerBitCastOrAddrSpaceCast(
3525 SrcAddrGEP, Builder.getPtrTy());
3526 BasicBlock *PreCondBB =
3527 BasicBlock::Create(M.getContext(), ".shuffle.pre_cond");
3528 BasicBlock *ThenBB = BasicBlock::Create(M.getContext(), ".shuffle.then");
3529 BasicBlock *ExitBB = BasicBlock::Create(M.getContext(), ".shuffle.exit");
3530 BasicBlock *CurrentBB = Builder.GetInsertBlock();
3531 emitBlock(PreCondBB, CurFunc);
3532 PHINode *PhiSrc =
3533 Builder.CreatePHI(Ptr->getType(), /*NumReservedValues=*/2);
3534 PhiSrc->addIncoming(Ptr, CurrentBB);
3535 PHINode *PhiDest =
3536 Builder.CreatePHI(ElemPtr->getType(), /*NumReservedValues=*/2);
3537 PhiDest->addIncoming(ElemPtr, CurrentBB);
3538 Ptr = PhiSrc;
3539 ElemPtr = PhiDest;
3540 Value *PtrDiff = Builder.CreatePtrDiff(
3541 Builder.getInt8Ty(), PtrEnd,
3542 Builder.CreatePointerBitCastOrAddrSpaceCast(Ptr, Builder.getPtrTy()));
3543 Builder.CreateCondBr(
3544 Builder.CreateICmpSGT(PtrDiff, Builder.getInt64(IntSize - 1)), ThenBB,
3545 ExitBB);
3546 emitBlock(ThenBB, CurFunc);
3547 Value *Res = createRuntimeShuffleFunction(
3548 AllocaIP,
3549 Builder.CreateAlignedLoad(
3550 IntType, Ptr, M.getDataLayout().getPrefTypeAlign(ElemType)),
3551 IntType, Offset);
3552 Builder.CreateAlignedStore(Res, ElemPtr,
3553 M.getDataLayout().getPrefTypeAlign(ElemType));
3554 Value *LocalPtr =
3555 Builder.CreateGEP(IntType, Ptr, {ConstantInt::get(IndexTy, 1)});
3556 Value *LocalElemPtr =
3557 Builder.CreateGEP(IntType, ElemPtr, {ConstantInt::get(IndexTy, 1)});
3558 PhiSrc->addIncoming(LocalPtr, ThenBB);
3559 PhiDest->addIncoming(LocalElemPtr, ThenBB);
3560 emitBranch(PreCondBB);
3561 emitBlock(ExitBB, CurFunc);
3562 } else {
3563 // The shuffled value comes back as the chunk's integer type, so the
3564 // store covers exactly this chunk regardless of what ElemType is.
3565 Value *Res = createRuntimeShuffleFunction(
3566 AllocaIP, Builder.CreateLoad(IntType, Ptr), IntType, Offset);
3567 Builder.CreateStore(Res, ElemPtr);
3568 Ptr = Builder.CreateGEP(IntType, Ptr, {ConstantInt::get(IndexTy, 1)});
3569 ElemPtr =
3570 Builder.CreateGEP(IntType, ElemPtr, {ConstantInt::get(IndexTy, 1)});
3571 }
3572 Size = Size % IntSize;
3573 }
3574}
3575
3576Error OpenMPIRBuilder::emitReductionListCopy(
3577 InsertPointTy AllocaIP, CopyAction Action, Type *ReductionArrayTy,
3578 ArrayRef<ReductionInfo> ReductionInfos, Value *SrcBase, Value *DestBase,
3579 ArrayRef<bool> IsByRef, CopyOptionsTy CopyOptions) {
3580 Type *IndexTy = Builder.getIndexTy(
3581 M.getDataLayout(), M.getDataLayout().getDefaultGlobalsAddressSpace());
3582 Value *RemoteLaneOffset = CopyOptions.RemoteLaneOffset;
3583
3584 // Iterates, element-by-element, through the source Reduce list and
3585 // make a copy.
3586 for (auto En : enumerate(ReductionInfos)) {
3587 const ReductionInfo &RI = En.value();
3588 Value *SrcElementAddr = nullptr;
3589 AllocaInst *DestAlloca = nullptr;
3590 Value *DestElementAddr = nullptr;
3591 Value *DestElementPtrAddr = nullptr;
3592 // Should we shuffle in an element from a remote lane?
3593 bool ShuffleInElement = false;
3594 // Set to true to update the pointer in the dest Reduce list to a
3595 // newly created element.
3596 bool UpdateDestListPtr = false;
3597
3598 // Step 1.1: Get the address for the src element in the Reduce list.
3599 Value *SrcElementPtrAddr = Builder.CreateInBoundsGEP(
3600 ReductionArrayTy, SrcBase,
3601 {ConstantInt::get(IndexTy, 0), ConstantInt::get(IndexTy, En.index())});
3602 SrcElementAddr = Builder.CreateLoad(Builder.getPtrTy(), SrcElementPtrAddr);
3603
3604 // Step 1.2: Create a temporary to store the element in the destination
3605 // Reduce list.
3606 DestElementPtrAddr = Builder.CreateInBoundsGEP(
3607 ReductionArrayTy, DestBase,
3608 {ConstantInt::get(IndexTy, 0), ConstantInt::get(IndexTy, En.index())});
3609 bool IsByRefElem = (!IsByRef.empty() && IsByRef[En.index()]);
3610 switch (Action) {
3612 InsertPointTy CurIP = Builder.saveIP();
3613 Builder.restoreIP(AllocaIP);
3614
3615 Type *DestAllocaType =
3616 IsByRefElem ? RI.ByRefAllocatedType : RI.ElementType;
3617 DestAlloca = Builder.CreateAlloca(DestAllocaType, nullptr,
3618 ".omp.reduction.element");
3619 DestAlloca->setAlignment(
3620 M.getDataLayout().getPrefTypeAlign(DestAllocaType));
3621 DestElementAddr = DestAlloca;
3622 DestElementAddr =
3623 Builder.CreateAddrSpaceCast(DestElementAddr, Builder.getPtrTy(),
3624 DestElementAddr->getName() + ".ascast");
3625 Builder.restoreIP(CurIP);
3626 ShuffleInElement = true;
3627 UpdateDestListPtr = true;
3628 break;
3629 }
3631 DestElementAddr =
3632 Builder.CreateLoad(Builder.getPtrTy(), DestElementPtrAddr);
3633 break;
3634 }
3635 }
3636
3637 // Now that all active lanes have read the element in the
3638 // Reduce list, shuffle over the value from the remote lane.
3639 if (ShuffleInElement) {
3640 Type *ShuffleType = RI.ElementType;
3641 Value *ShuffleSrcAddr = SrcElementAddr;
3642 Value *ShuffleDestAddr = DestElementAddr;
3643 AllocaInst *LocalStorage = nullptr;
3644
3645 if (IsByRefElem) {
3646 assert(RI.ByRefElementType && "Expected by-ref element type to be set");
3647 assert(RI.ByRefAllocatedType &&
3648 "Expected by-ref allocated type to be set");
3649 // For by-ref reductions, we need to copy from the remote lane the
3650 // actual value of the partial reduction computed by that remote lane;
3651 // rather than, for example, a pointer to that data or, even worse, a
3652 // pointer to the descriptor of the by-ref reduction element.
3653 ShuffleType = RI.ByRefElementType;
3654
3655 if (RI.DataPtrPtrGen) {
3656 // Descriptor-based by-ref: extract data pointer from descriptor.
3657 InsertPointOrErrorTy GenResult = RI.DataPtrPtrGen(
3658 Builder.saveIP(), ShuffleSrcAddr, ShuffleSrcAddr);
3659
3660 if (!GenResult)
3661 return GenResult.takeError();
3662
3663 ShuffleSrcAddr =
3664 Builder.CreateLoad(Builder.getPtrTy(), ShuffleSrcAddr);
3665
3666 {
3667 InsertPointTy OldIP = Builder.saveIP();
3668 Builder.restoreIP(AllocaIP);
3669
3670 LocalStorage = Builder.CreateAlloca(ShuffleType);
3671 Builder.restoreIP(OldIP);
3672 ShuffleDestAddr = LocalStorage;
3673 }
3674 } else {
3675 // Non-descriptor by-ref: the pointer already references data
3676 // directly. Shuffle into the destination alloca.
3677 ShuffleDestAddr = DestElementAddr;
3678 }
3679 }
3680
3681 shuffleAndStore(AllocaIP, ShuffleSrcAddr, ShuffleDestAddr, ShuffleType,
3682 RemoteLaneOffset, ReductionArrayTy, IsByRefElem);
3683
3684 if (IsByRefElem && RI.DataPtrPtrGen) {
3685 // Copy descriptor from source and update base_ptr to shuffled data
3686 Value *DestDescriptorAddr = Builder.CreatePointerBitCastOrAddrSpaceCast(
3687 DestAlloca, Builder.getPtrTy(), ".ascast");
3688
3689 InsertPointOrErrorTy GenResult = generateReductionDescriptor(
3690 DestDescriptorAddr, LocalStorage, SrcElementAddr,
3691 RI.ByRefAllocatedType, RI.DataPtrPtrGen);
3692
3693 if (!GenResult)
3694 return GenResult.takeError();
3695 }
3696 } else {
3697 switch (RI.EvaluationKind) {
3698 case EvalKind::Scalar: {
3699 Value *Elem = Builder.CreateLoad(RI.ElementType, SrcElementAddr);
3700 // Store the source element value to the dest element address.
3701 Builder.CreateStore(Elem, DestElementAddr);
3702 break;
3703 }
3704 case EvalKind::Complex: {
3705 Value *SrcRealPtr = Builder.CreateConstInBoundsGEP2_32(
3706 RI.ElementType, SrcElementAddr, 0, 0, ".realp");
3707 Value *SrcReal = Builder.CreateLoad(
3708 RI.ElementType->getStructElementType(0), SrcRealPtr, ".real");
3709 Value *SrcImgPtr = Builder.CreateConstInBoundsGEP2_32(
3710 RI.ElementType, SrcElementAddr, 0, 1, ".imagp");
3711 Value *SrcImg = Builder.CreateLoad(
3712 RI.ElementType->getStructElementType(1), SrcImgPtr, ".imag");
3713
3714 Value *DestRealPtr = Builder.CreateConstInBoundsGEP2_32(
3715 RI.ElementType, DestElementAddr, 0, 0, ".realp");
3716 Value *DestImgPtr = Builder.CreateConstInBoundsGEP2_32(
3717 RI.ElementType, DestElementAddr, 0, 1, ".imagp");
3718 Builder.CreateStore(SrcReal, DestRealPtr);
3719 Builder.CreateStore(SrcImg, DestImgPtr);
3720 break;
3721 }
3722 case EvalKind::Aggregate: {
3723 Value *SizeVal = Builder.getInt64(
3724 M.getDataLayout().getTypeStoreSize(RI.ElementType));
3725 Builder.CreateMemCpy(
3726 DestElementAddr, M.getDataLayout().getPrefTypeAlign(RI.ElementType),
3727 SrcElementAddr, M.getDataLayout().getPrefTypeAlign(RI.ElementType),
3728 SizeVal, false);
3729 break;
3730 }
3731 };
3732 }
3733
3734 // Step 3.1: Modify reference in dest Reduce list as needed.
3735 // Modifying the reference in Reduce list to point to the newly
3736 // created element. The element is live in the current function
3737 // scope and that of functions it invokes (i.e., reduce_function).
3738 // RemoteReduceData[i] = (void*)&RemoteElem
3739 if (UpdateDestListPtr) {
3740 Value *CastDestAddr = Builder.CreatePointerBitCastOrAddrSpaceCast(
3741 DestElementAddr, Builder.getPtrTy(),
3742 DestElementAddr->getName() + ".ascast");
3743 Builder.CreateStore(CastDestAddr, DestElementPtrAddr);
3744 }
3745 }
3746
3747 return Error::success();
3748}
3749
3750Expected<Function *> OpenMPIRBuilder::emitInterWarpCopyFunction(
3751 const LocationDescription &Loc, ArrayRef<ReductionInfo> ReductionInfos,
3752 AttributeList FuncAttrs, ArrayRef<bool> IsByRef) {
3753 IRBuilder<>::InsertPointGuard IPG(Builder);
3754 LLVMContext &Ctx = M.getContext();
3755 FunctionType *FuncTy = FunctionType::get(
3756 Builder.getVoidTy(), {Builder.getPtrTy(), Builder.getInt32Ty()},
3757 /* IsVarArg */ false);
3758 Function *WcFunc =
3760 "_omp_reduction_inter_warp_copy_func", &M);
3761 WcFunc->setCallingConv(Config.getRuntimeCC());
3762 WcFunc->setAttributes(FuncAttrs);
3763 WcFunc->addParamAttr(0, Attribute::NoUndef);
3764 WcFunc->addParamAttr(1, Attribute::NoUndef);
3765 BasicBlock *EntryBB = BasicBlock::Create(M.getContext(), "entry", WcFunc);
3766 Builder.SetInsertPoint(EntryBB);
3767 Builder.SetCurrentDebugLocation(llvm::DebugLoc());
3768
3769 // ReduceList: thread local Reduce list.
3770 // At the stage of the computation when this function is called, partially
3771 // aggregated values reside in the first lane of every active warp.
3772 Argument *ReduceListArg = WcFunc->getArg(0);
3773 // NumWarps: number of warps active in the parallel region. This could
3774 // be smaller than 32 (max warps in a CTA) for partial block reduction.
3775 Argument *NumWarpsArg = WcFunc->getArg(1);
3776
3777 // This array is used as a medium to transfer, one reduce element at a time,
3778 // the data from the first lane of every warp to lanes in the first warp
3779 // in order to perform the final step of a reduction in a parallel region
3780 // (reduction across warps). The array is placed in NVPTX __shared__ memory
3781 // for reduced latency, as well as to have a distinct copy for concurrently
3782 // executing target regions. The array is declared with common linkage so
3783 // as to be shared across compilation units.
3784 StringRef TransferMediumName =
3785 "__openmp_nvptx_data_transfer_temporary_storage";
3786 GlobalVariable *TransferMedium = M.getGlobalVariable(TransferMediumName);
3787 unsigned WarpSize = Config.getGridValue().GV_Warp_Size;
3788 ArrayType *ArrayTy = ArrayType::get(Builder.getInt32Ty(), WarpSize);
3789 if (!TransferMedium) {
3790 TransferMedium = new GlobalVariable(
3791 M, ArrayTy, /*isConstant=*/false, GlobalVariable::WeakAnyLinkage,
3792 UndefValue::get(ArrayTy), TransferMediumName,
3793 /*InsertBefore=*/nullptr, GlobalVariable::NotThreadLocal,
3794 /*AddressSpace=*/3);
3795 }
3796
3797 // Get the CUDA thread id of the current OpenMP thread on the GPU.
3798 Value *GPUThreadID = getGPUThreadID();
3799 // nvptx_lane_id = nvptx_id % warpsize
3800 Value *LaneID = getNVPTXLaneID();
3801 // nvptx_warp_id = nvptx_id / warpsize
3802 Value *WarpID = getNVPTXWarpID();
3803
3804 InsertPointTy AllocaIP = Builder.GetInsertBlock()->getFirstInsertionPt();
3805 Type *Arg0Type = ReduceListArg->getType();
3806 Type *Arg1Type = NumWarpsArg->getType();
3807 Builder.restoreIP(AllocaIP);
3808 AllocaInst *ReduceListAlloca = Builder.CreateAlloca(
3809 Arg0Type, nullptr, ReduceListArg->getName() + ".addr");
3810 AllocaInst *NumWarpsAlloca =
3811 Builder.CreateAlloca(Arg1Type, nullptr, NumWarpsArg->getName() + ".addr");
3812 Value *ReduceListAddrCast = Builder.CreatePointerBitCastOrAddrSpaceCast(
3813 ReduceListAlloca, Arg0Type, ReduceListAlloca->getName() + ".ascast");
3814 Value *NumWarpsAddrCast = Builder.CreatePointerBitCastOrAddrSpaceCast(
3815 NumWarpsAlloca, Builder.getPtrTy(0),
3816 NumWarpsAlloca->getName() + ".ascast");
3817 Builder.CreateStore(ReduceListArg, ReduceListAddrCast);
3818 Builder.CreateStore(NumWarpsArg, NumWarpsAddrCast);
3819 AllocaIP = getInsertPointAfterInstr(NumWarpsAlloca);
3820 InsertPointTy CodeGenIP =
3821 getInsertPointAfterInstr(&Builder.GetInsertBlock()->back());
3822 Builder.restoreIP(CodeGenIP);
3823
3824 Value *ReduceList =
3825 Builder.CreateLoad(Builder.getPtrTy(), ReduceListAddrCast);
3826
3827 for (auto En : enumerate(ReductionInfos)) {
3828 //
3829 // Warp master copies reduce element to transfer medium in __shared__
3830 // memory.
3831 //
3832 const ReductionInfo &RI = En.value();
3833 bool IsByRefElem = !IsByRef.empty() && IsByRef[En.index()];
3834 unsigned RealTySize = M.getDataLayout().getTypeAllocSize(
3835 IsByRefElem ? RI.ByRefElementType : RI.ElementType);
3836 for (unsigned TySize = 4; TySize > 0 && RealTySize > 0; TySize /= 2) {
3837 Type *CType = Builder.getIntNTy(TySize * 8);
3838
3839 unsigned NumIters = RealTySize / TySize;
3840 if (NumIters == 0)
3841 continue;
3842 Value *Cnt = nullptr;
3843 Value *CntAddr = nullptr;
3844 BasicBlock *PrecondBB = nullptr;
3845 BasicBlock *ExitBB = nullptr;
3846 if (NumIters > 1) {
3847 CodeGenIP = Builder.saveIP();
3848 Builder.restoreIP(AllocaIP);
3849 CntAddr =
3850 Builder.CreateAlloca(Builder.getInt32Ty(), nullptr, ".cnt.addr");
3851
3852 CntAddr = Builder.CreateAddrSpaceCast(CntAddr, Builder.getPtrTy(),
3853 CntAddr->getName() + ".ascast");
3854 Builder.restoreIP(CodeGenIP);
3855 Builder.CreateStore(Constant::getNullValue(Builder.getInt32Ty()),
3856 CntAddr,
3857 /*Volatile=*/false);
3858 PrecondBB = BasicBlock::Create(Ctx, "precond");
3859 ExitBB = BasicBlock::Create(Ctx, "exit");
3860 BasicBlock *BodyBB = BasicBlock::Create(Ctx, "body");
3861 emitBlock(PrecondBB, Builder.GetInsertBlock()->getParent());
3862 Cnt = Builder.CreateLoad(Builder.getInt32Ty(), CntAddr,
3863 /*Volatile=*/false);
3864 Value *Cmp = Builder.CreateICmpULT(
3865 Cnt, ConstantInt::get(Builder.getInt32Ty(), NumIters));
3866 Builder.CreateCondBr(Cmp, BodyBB, ExitBB);
3867 emitBlock(BodyBB, Builder.GetInsertBlock()->getParent());
3868 }
3869
3870 // kmpc_barrier.
3871 InsertPointOrErrorTy BarrierIP1 =
3873 omp::Directive::OMPD_unknown,
3874 /* ForceSimpleCall */ false,
3875 /* CheckCancelFlag */ true);
3876 if (!BarrierIP1)
3877 return BarrierIP1.takeError();
3878 BasicBlock *ThenBB = BasicBlock::Create(Ctx, "then");
3879 BasicBlock *ElseBB = BasicBlock::Create(Ctx, "else");
3880 BasicBlock *MergeBB = BasicBlock::Create(Ctx, "ifcont");
3881
3882 // if (lane_id == 0)
3883 Value *IsWarpMaster = Builder.CreateIsNull(LaneID, "warp_master");
3884 Builder.CreateCondBr(IsWarpMaster, ThenBB, ElseBB);
3885 emitBlock(ThenBB, Builder.GetInsertBlock()->getParent());
3886
3887 // Reduce element = LocalReduceList[i]
3888 auto *RedListArrayTy =
3889 ArrayType::get(Builder.getPtrTy(), ReductionInfos.size());
3890 Type *IndexTy = Builder.getIndexTy(
3891 M.getDataLayout(), M.getDataLayout().getDefaultGlobalsAddressSpace());
3892 Value *ElemPtrPtr =
3893 Builder.CreateInBoundsGEP(RedListArrayTy, ReduceList,
3894 {ConstantInt::get(IndexTy, 0),
3895 ConstantInt::get(IndexTy, En.index())});
3896 // elemptr = ((CopyType*)(elemptrptr)) + I
3897 Value *ElemPtr = Builder.CreateLoad(Builder.getPtrTy(), ElemPtrPtr);
3898
3899 if (IsByRefElem && RI.DataPtrPtrGen) {
3900 InsertPointOrErrorTy GenRes =
3901 RI.DataPtrPtrGen(Builder.saveIP(), ElemPtr, ElemPtr);
3902
3903 if (!GenRes)
3904 return GenRes.takeError();
3905
3906 ElemPtr = Builder.CreateLoad(Builder.getPtrTy(), ElemPtr);
3907 }
3908
3909 if (NumIters > 1)
3910 ElemPtr = Builder.CreateGEP(Builder.getInt32Ty(), ElemPtr, Cnt);
3911
3912 // Get pointer to location in transfer medium.
3913 // MediumPtr = &medium[warp_id]
3914 Value *MediumPtr = Builder.CreateInBoundsGEP(
3915 ArrayTy, TransferMedium, {Builder.getInt64(0), WarpID});
3916 // elem = *elemptr
3917 //*MediumPtr = elem
3918 Value *Elem = Builder.CreateLoad(CType, ElemPtr);
3919 // Store the source element value to the dest element address.
3920 Builder.CreateStore(Elem, MediumPtr,
3921 /*IsVolatile*/ true);
3922 Builder.CreateBr(MergeBB);
3923
3924 // else
3925 emitBlock(ElseBB, Builder.GetInsertBlock()->getParent());
3926 Builder.CreateBr(MergeBB);
3927
3928 // endif
3929 emitBlock(MergeBB, Builder.GetInsertBlock()->getParent());
3930 InsertPointOrErrorTy BarrierIP2 =
3932 omp::Directive::OMPD_unknown,
3933 /* ForceSimpleCall */ false,
3934 /* CheckCancelFlag */ true);
3935 if (!BarrierIP2)
3936 return BarrierIP2.takeError();
3937
3938 // Warp 0 copies reduce element from transfer medium
3939 BasicBlock *W0ThenBB = BasicBlock::Create(Ctx, "then");
3940 BasicBlock *W0ElseBB = BasicBlock::Create(Ctx, "else");
3941 BasicBlock *W0MergeBB = BasicBlock::Create(Ctx, "ifcont");
3942
3943 Value *NumWarpsVal =
3944 Builder.CreateLoad(Builder.getInt32Ty(), NumWarpsAddrCast);
3945 // Up to 32 threads in warp 0 are active.
3946 Value *IsActiveThread =
3947 Builder.CreateICmpULT(GPUThreadID, NumWarpsVal, "is_active_thread");
3948 Builder.CreateCondBr(IsActiveThread, W0ThenBB, W0ElseBB);
3949
3950 emitBlock(W0ThenBB, Builder.GetInsertBlock()->getParent());
3951
3952 // SecMediumPtr = &medium[tid]
3953 // SrcMediumVal = *SrcMediumPtr
3954 Value *SrcMediumPtrVal = Builder.CreateInBoundsGEP(
3955 ArrayTy, TransferMedium, {Builder.getInt64(0), GPUThreadID});
3956 // TargetElemPtr = (CopyType*)(SrcDataAddr[i]) + I
3957 Value *TargetElemPtrPtr =
3958 Builder.CreateInBoundsGEP(RedListArrayTy, ReduceList,
3959 {ConstantInt::get(IndexTy, 0),
3960 ConstantInt::get(IndexTy, En.index())});
3961 Value *TargetElemPtrVal =
3962 Builder.CreateLoad(Builder.getPtrTy(), TargetElemPtrPtr);
3963 Value *TargetElemPtr = TargetElemPtrVal;
3964
3965 if (IsByRefElem && RI.DataPtrPtrGen) {
3966 InsertPointOrErrorTy GenRes =
3967 RI.DataPtrPtrGen(Builder.saveIP(), TargetElemPtr, TargetElemPtr);
3968
3969 if (!GenRes)
3970 return GenRes.takeError();
3971
3972 TargetElemPtr = Builder.CreateLoad(Builder.getPtrTy(), TargetElemPtr);
3973 }
3974
3975 if (NumIters > 1)
3976 TargetElemPtr =
3977 Builder.CreateGEP(Builder.getInt32Ty(), TargetElemPtr, Cnt);
3978
3979 // *TargetElemPtr = SrcMediumVal;
3980 Value *SrcMediumValue =
3981 Builder.CreateLoad(CType, SrcMediumPtrVal, /*IsVolatile*/ true);
3982 Builder.CreateStore(SrcMediumValue, TargetElemPtr);
3983 Builder.CreateBr(W0MergeBB);
3984
3985 emitBlock(W0ElseBB, Builder.GetInsertBlock()->getParent());
3986 Builder.CreateBr(W0MergeBB);
3987
3988 emitBlock(W0MergeBB, Builder.GetInsertBlock()->getParent());
3989
3990 if (NumIters > 1) {
3991 Cnt = Builder.CreateNSWAdd(
3992 Cnt, ConstantInt::get(Builder.getInt32Ty(), /*V=*/1));
3993 Builder.CreateStore(Cnt, CntAddr, /*Volatile=*/false);
3994
3995 auto *CurFn = Builder.GetInsertBlock()->getParent();
3996 emitBranch(PrecondBB);
3997 emitBlock(ExitBB, CurFn);
3998 }
3999 RealTySize %= TySize;
4000 }
4001 }
4002
4003 Builder.CreateRetVoid();
4004
4005 return WcFunc;
4006}
4007
4008Expected<Function *> OpenMPIRBuilder::emitShuffleAndReduceFunction(
4009 ArrayRef<ReductionInfo> ReductionInfos, Function *ReduceFn,
4010 AttributeList FuncAttrs, ArrayRef<bool> IsByRef) {
4011 LLVMContext &Ctx = M.getContext();
4012 IRBuilder<>::InsertPointGuard IPG(Builder);
4013 FunctionType *FuncTy =
4014 FunctionType::get(Builder.getVoidTy(),
4015 {Builder.getPtrTy(), Builder.getInt16Ty(),
4016 Builder.getInt16Ty(), Builder.getInt16Ty()},
4017 /* IsVarArg */ false);
4018 Function *SarFunc =
4020 "_omp_reduction_shuffle_and_reduce_func", &M);
4021 SarFunc->setCallingConv(Config.getRuntimeCC());
4022 SarFunc->setAttributes(FuncAttrs);
4023 SarFunc->addParamAttr(0, Attribute::NoUndef);
4024 SarFunc->addParamAttr(1, Attribute::NoUndef);
4025 SarFunc->addParamAttr(2, Attribute::NoUndef);
4026 SarFunc->addParamAttr(3, Attribute::NoUndef);
4027 SarFunc->addParamAttr(1, Attribute::SExt);
4028 SarFunc->addParamAttr(2, Attribute::SExt);
4029 SarFunc->addParamAttr(3, Attribute::SExt);
4030 BasicBlock *EntryBB = BasicBlock::Create(M.getContext(), "entry", SarFunc);
4031 Builder.SetInsertPoint(EntryBB);
4032 Builder.SetCurrentDebugLocation(llvm::DebugLoc());
4033
4034 // Thread local Reduce list used to host the values of data to be reduced.
4035 Argument *ReduceListArg = SarFunc->getArg(0);
4036 // Current lane id; could be logical.
4037 Argument *LaneIDArg = SarFunc->getArg(1);
4038 // Offset of the remote source lane relative to the current lane.
4039 Argument *RemoteLaneOffsetArg = SarFunc->getArg(2);
4040 // Algorithm version. This is expected to be known at compile time.
4041 Argument *AlgoVerArg = SarFunc->getArg(3);
4042
4043 Type *ReduceListArgType = ReduceListArg->getType();
4044 Type *LaneIDArgType = LaneIDArg->getType();
4045 Type *LaneIDArgPtrType = Builder.getPtrTy(0);
4046 Value *ReduceListAlloca = Builder.CreateAlloca(
4047 ReduceListArgType, nullptr, ReduceListArg->getName() + ".addr");
4048 Value *LaneIdAlloca = Builder.CreateAlloca(LaneIDArgType, nullptr,
4049 LaneIDArg->getName() + ".addr");
4050 Value *RemoteLaneOffsetAlloca = Builder.CreateAlloca(
4051 LaneIDArgType, nullptr, RemoteLaneOffsetArg->getName() + ".addr");
4052 Value *AlgoVerAlloca = Builder.CreateAlloca(LaneIDArgType, nullptr,
4053 AlgoVerArg->getName() + ".addr");
4054 ArrayType *RedListArrayTy =
4055 ArrayType::get(Builder.getPtrTy(), ReductionInfos.size());
4056
4057 // Create a local thread-private variable to host the Reduce list
4058 // from a remote lane.
4059 Instruction *RemoteReductionListAlloca = Builder.CreateAlloca(
4060 RedListArrayTy, nullptr, ".omp.reduction.remote_reduce_list");
4061
4062 Value *ReduceListAddrCast = Builder.CreatePointerBitCastOrAddrSpaceCast(
4063 ReduceListAlloca, ReduceListArgType,
4064 ReduceListAlloca->getName() + ".ascast");
4065 Value *LaneIdAddrCast = Builder.CreatePointerBitCastOrAddrSpaceCast(
4066 LaneIdAlloca, LaneIDArgPtrType, LaneIdAlloca->getName() + ".ascast");
4067 Value *RemoteLaneOffsetAddrCast = Builder.CreatePointerBitCastOrAddrSpaceCast(
4068 RemoteLaneOffsetAlloca, LaneIDArgPtrType,
4069 RemoteLaneOffsetAlloca->getName() + ".ascast");
4070 Value *AlgoVerAddrCast = Builder.CreatePointerBitCastOrAddrSpaceCast(
4071 AlgoVerAlloca, LaneIDArgPtrType, AlgoVerAlloca->getName() + ".ascast");
4072 Value *RemoteListAddrCast = Builder.CreatePointerBitCastOrAddrSpaceCast(
4073 RemoteReductionListAlloca, Builder.getPtrTy(),
4074 RemoteReductionListAlloca->getName() + ".ascast");
4075
4076 Builder.CreateStore(ReduceListArg, ReduceListAddrCast);
4077 Builder.CreateStore(LaneIDArg, LaneIdAddrCast);
4078 Builder.CreateStore(RemoteLaneOffsetArg, RemoteLaneOffsetAddrCast);
4079 Builder.CreateStore(AlgoVerArg, AlgoVerAddrCast);
4080
4081 Value *ReduceList = Builder.CreateLoad(ReduceListArgType, ReduceListAddrCast);
4082 Value *LaneId = Builder.CreateLoad(LaneIDArgType, LaneIdAddrCast);
4083 Value *RemoteLaneOffset =
4084 Builder.CreateLoad(LaneIDArgType, RemoteLaneOffsetAddrCast);
4085 Value *AlgoVer = Builder.CreateLoad(LaneIDArgType, AlgoVerAddrCast);
4086
4087 InsertPointTy AllocaIP = getInsertPointAfterInstr(RemoteReductionListAlloca);
4088
4089 // This loop iterates through the list of reduce elements and copies,
4090 // element by element, from a remote lane in the warp to RemoteReduceList,
4091 // hosted on the thread's stack.
4092 Error EmitRedLsCpRes = emitReductionListCopy(
4093 AllocaIP, CopyAction::RemoteLaneToThread, RedListArrayTy, ReductionInfos,
4094 ReduceList, RemoteListAddrCast, IsByRef,
4095 {RemoteLaneOffset, nullptr, nullptr});
4096
4097 if (EmitRedLsCpRes)
4098 return EmitRedLsCpRes;
4099
4100 // The actions to be performed on the Remote Reduce list is dependent
4101 // on the algorithm version.
4102 //
4103 // if (AlgoVer==0) || (AlgoVer==1 && (LaneId < Offset)) || (AlgoVer==2 &&
4104 // LaneId % 2 == 0 && Offset > 0):
4105 // do the reduction value aggregation
4106 //
4107 // The thread local variable Reduce list is mutated in place to host the
4108 // reduced data, which is the aggregated value produced from local and
4109 // remote lanes.
4110 //
4111 // Note that AlgoVer is expected to be a constant integer known at compile
4112 // time.
4113 // When AlgoVer==0, the first conjunction evaluates to true, making
4114 // the entire predicate true during compile time.
4115 // When AlgoVer==1, the second conjunction has only the second part to be
4116 // evaluated during runtime. Other conjunctions evaluates to false
4117 // during compile time.
4118 // When AlgoVer==2, the third conjunction has only the second part to be
4119 // evaluated during runtime. Other conjunctions evaluates to false
4120 // during compile time.
4121 Value *CondAlgo0 = Builder.CreateIsNull(AlgoVer);
4122 Value *Algo1 = Builder.CreateICmpEQ(AlgoVer, Builder.getInt16(1));
4123 Value *LaneComp = Builder.CreateICmpULT(LaneId, RemoteLaneOffset);
4124 Value *CondAlgo1 = Builder.CreateAnd(Algo1, LaneComp);
4125 Value *Algo2 = Builder.CreateICmpEQ(AlgoVer, Builder.getInt16(2));
4126 Value *LaneIdAnd1 = Builder.CreateAnd(LaneId, Builder.getInt16(1));
4127 Value *LaneIdComp = Builder.CreateIsNull(LaneIdAnd1);
4128 Value *Algo2AndLaneIdComp = Builder.CreateAnd(Algo2, LaneIdComp);
4129 Value *RemoteOffsetComp =
4130 Builder.CreateICmpSGT(RemoteLaneOffset, Builder.getInt16(0));
4131 Value *CondAlgo2 = Builder.CreateAnd(Algo2AndLaneIdComp, RemoteOffsetComp);
4132 Value *CA0OrCA1 = Builder.CreateOr(CondAlgo0, CondAlgo1);
4133 Value *CondReduce = Builder.CreateOr(CA0OrCA1, CondAlgo2);
4134
4135 BasicBlock *ThenBB = BasicBlock::Create(Ctx, "then");
4136 BasicBlock *ElseBB = BasicBlock::Create(Ctx, "else");
4137 BasicBlock *MergeBB = BasicBlock::Create(Ctx, "ifcont");
4138
4139 Builder.CreateCondBr(CondReduce, ThenBB, ElseBB);
4140 emitBlock(ThenBB, Builder.GetInsertBlock()->getParent());
4141 Value *LocalReduceListPtr = Builder.CreatePointerBitCastOrAddrSpaceCast(
4142 ReduceList, Builder.getPtrTy());
4143 Value *RemoteReduceListPtr = Builder.CreatePointerBitCastOrAddrSpaceCast(
4144 RemoteListAddrCast, Builder.getPtrTy());
4145 createRuntimeFunctionCall(ReduceFn, {LocalReduceListPtr, RemoteReduceListPtr})
4146 ->addFnAttr(Attribute::NoUnwind);
4147 Builder.CreateBr(MergeBB);
4148
4149 emitBlock(ElseBB, Builder.GetInsertBlock()->getParent());
4150 Builder.CreateBr(MergeBB);
4151
4152 emitBlock(MergeBB, Builder.GetInsertBlock()->getParent());
4153
4154 // if (AlgoVer==1 && (LaneId >= Offset)) copy Remote Reduce list to local
4155 // Reduce list.
4156 Algo1 = Builder.CreateICmpEQ(AlgoVer, Builder.getInt16(1));
4157 Value *LaneIdGtOffset = Builder.CreateICmpUGE(LaneId, RemoteLaneOffset);
4158 Value *CondCopy = Builder.CreateAnd(Algo1, LaneIdGtOffset);
4159
4160 BasicBlock *CpyThenBB = BasicBlock::Create(Ctx, "then");
4161 BasicBlock *CpyElseBB = BasicBlock::Create(Ctx, "else");
4162 BasicBlock *CpyMergeBB = BasicBlock::Create(Ctx, "ifcont");
4163 Builder.CreateCondBr(CondCopy, CpyThenBB, CpyElseBB);
4164
4165 emitBlock(CpyThenBB, Builder.GetInsertBlock()->getParent());
4166
4167 EmitRedLsCpRes = emitReductionListCopy(
4168 AllocaIP, CopyAction::ThreadCopy, RedListArrayTy, ReductionInfos,
4169 RemoteListAddrCast, ReduceList, IsByRef);
4170
4171 if (EmitRedLsCpRes)
4172 return EmitRedLsCpRes;
4173
4174 Builder.CreateBr(CpyMergeBB);
4175
4176 emitBlock(CpyElseBB, Builder.GetInsertBlock()->getParent());
4177 Builder.CreateBr(CpyMergeBB);
4178
4179 emitBlock(CpyMergeBB, Builder.GetInsertBlock()->getParent());
4180
4181 Builder.CreateRetVoid();
4182
4183 return SarFunc;
4184}
4185
4187OpenMPIRBuilder::generateReductionDescriptor(
4188 Value *DescriptorAddr, Value *DataPtr, Value *SrcDescriptorAddr,
4189 Type *DescriptorType,
4190 function_ref<InsertPointOrErrorTy(InsertPointTy, Value *, Value *&)>
4191 DataPtrPtrGen) {
4192
4193 // Copy the source descriptor to preserve all metadata (rank, extents,
4194 // strides, etc.)
4195 Value *DescriptorSize =
4196 Builder.getInt64(M.getDataLayout().getTypeStoreSize(DescriptorType));
4197 Builder.CreateMemCpy(
4198 DescriptorAddr, M.getDataLayout().getPrefTypeAlign(DescriptorType),
4199 SrcDescriptorAddr, M.getDataLayout().getPrefTypeAlign(DescriptorType),
4200 DescriptorSize);
4201
4202 // Update the base pointer field to point to the local shuffled data
4203 Value *DataPtrField;
4204 InsertPointOrErrorTy GenResult =
4205 DataPtrPtrGen(Builder.saveIP(), DescriptorAddr, DataPtrField);
4206
4207 if (!GenResult)
4208 return GenResult.takeError();
4209
4210 Builder.CreateStore(Builder.CreatePointerBitCastOrAddrSpaceCast(
4211 DataPtr, Builder.getPtrTy(), ".ascast"),
4212 DataPtrField);
4213
4214 return Builder.saveIP();
4215}
4216
4217Expected<Value *> OpenMPIRBuilder::createReductionDescriptorCopy(
4218 InsertPointTy AllocaIP, const ReductionInfo &RI, Value *DataPtr,
4219 Value *SrcDescriptorAddr, Type *DescriptorPtrTy, const Twine &Name) {
4220 InsertPointTy OldIP = Builder.saveIP();
4221 Builder.restoreIP(AllocaIP);
4222
4223 AllocaInst *DescriptorAlloca =
4224 Builder.CreateAlloca(RI.ByRefAllocatedType, nullptr, Name);
4225 DescriptorAlloca->setAlignment(
4226 M.getDataLayout().getPrefTypeAlign(RI.ByRefAllocatedType));
4227 Value *DescriptorAddr = Builder.CreatePointerBitCastOrAddrSpaceCast(
4228 DescriptorAlloca, DescriptorPtrTy,
4229 DescriptorAlloca->getName() + ".ascast");
4230
4231 Builder.restoreIP(OldIP);
4232
4233 InsertPointOrErrorTy GenResult =
4234 generateReductionDescriptor(DescriptorAddr, DataPtr, SrcDescriptorAddr,
4235 RI.ByRefAllocatedType, RI.DataPtrPtrGen);
4236 if (!GenResult)
4237 return GenResult.takeError();
4238
4239 return DescriptorAddr;
4240}
4241
4242Expected<Function *> OpenMPIRBuilder::emitListToGlobalCopyFunction(
4243 ArrayRef<ReductionInfo> ReductionInfos, Type *ReductionsBufferTy,
4244 AttributeList FuncAttrs, ArrayRef<bool> IsByRef) {
4245 IRBuilder<>::InsertPointGuard IPG(Builder);
4246 LLVMContext &Ctx = M.getContext();
4247 FunctionType *FuncTy = FunctionType::get(
4248 Builder.getVoidTy(),
4249 {Builder.getPtrTy(), Builder.getInt32Ty(), Builder.getPtrTy()},
4250 /* IsVarArg */ false);
4251 Function *LtGCFunc =
4253 "_omp_reduction_list_to_global_copy_func", &M);
4254 LtGCFunc->setAttributes(FuncAttrs);
4255 LtGCFunc->addParamAttr(0, Attribute::NoUndef);
4256 LtGCFunc->addParamAttr(1, Attribute::NoUndef);
4257 LtGCFunc->addParamAttr(2, Attribute::NoUndef);
4258
4259 BasicBlock *EntryBlock = BasicBlock::Create(Ctx, "entry", LtGCFunc);
4260 Builder.SetInsertPoint(EntryBlock);
4261 Builder.SetCurrentDebugLocation(llvm::DebugLoc());
4262
4263 // Buffer: global reduction buffer.
4264 Argument *BufferArg = LtGCFunc->getArg(0);
4265 // Idx: index of the buffer.
4266 Argument *IdxArg = LtGCFunc->getArg(1);
4267 // ReduceList: thread local Reduce list.
4268 Argument *ReduceListArg = LtGCFunc->getArg(2);
4269
4270 Value *BufferArgAlloca = Builder.CreateAlloca(Builder.getPtrTy(), nullptr,
4271 BufferArg->getName() + ".addr");
4272 Value *IdxArgAlloca = Builder.CreateAlloca(Builder.getInt32Ty(), nullptr,
4273 IdxArg->getName() + ".addr");
4274 Value *ReduceListArgAlloca = Builder.CreateAlloca(
4275 Builder.getPtrTy(), nullptr, ReduceListArg->getName() + ".addr");
4276 Value *BufferArgAddrCast = Builder.CreatePointerBitCastOrAddrSpaceCast(
4277 BufferArgAlloca, Builder.getPtrTy(),
4278 BufferArgAlloca->getName() + ".ascast");
4279 Value *IdxArgAddrCast = Builder.CreatePointerBitCastOrAddrSpaceCast(
4280 IdxArgAlloca, Builder.getPtrTy(), IdxArgAlloca->getName() + ".ascast");
4281 Value *ReduceListArgAddrCast = Builder.CreatePointerBitCastOrAddrSpaceCast(
4282 ReduceListArgAlloca, Builder.getPtrTy(),
4283 ReduceListArgAlloca->getName() + ".ascast");
4284
4285 Builder.CreateStore(BufferArg, BufferArgAddrCast);
4286 Builder.CreateStore(IdxArg, IdxArgAddrCast);
4287 Builder.CreateStore(ReduceListArg, ReduceListArgAddrCast);
4288
4289 Value *LocalReduceList =
4290 Builder.CreateLoad(Builder.getPtrTy(), ReduceListArgAddrCast);
4291 Value *BufferArgVal =
4292 Builder.CreateLoad(Builder.getPtrTy(), BufferArgAddrCast);
4293 Value *Idxs[] = {Builder.CreateLoad(Builder.getInt32Ty(), IdxArgAddrCast)};
4294 Type *IndexTy = Builder.getIndexTy(
4295 M.getDataLayout(), M.getDataLayout().getDefaultGlobalsAddressSpace());
4296 for (auto En : enumerate(ReductionInfos)) {
4297 const ReductionInfo &RI = En.value();
4298 auto *RedListArrayTy =
4299 ArrayType::get(Builder.getPtrTy(), ReductionInfos.size());
4300 // Reduce element = LocalReduceList[i]
4301 Value *ElemPtrPtr = Builder.CreateInBoundsGEP(
4302 RedListArrayTy, LocalReduceList,
4303 {ConstantInt::get(IndexTy, 0), ConstantInt::get(IndexTy, En.index())});
4304 // elemptr = ((CopyType*)(elemptrptr)) + I
4305 Value *ElemPtr = Builder.CreateLoad(Builder.getPtrTy(), ElemPtrPtr);
4306
4307 // Global = Buffer.VD[Idx];
4308 Value *BufferVD =
4309 Builder.CreateInBoundsGEP(ReductionsBufferTy, BufferArgVal, Idxs);
4310 Value *GlobVal = Builder.CreateConstInBoundsGEP2_32(
4311 ReductionsBufferTy, BufferVD, 0, En.index());
4312
4313 switch (RI.EvaluationKind) {
4314 case EvalKind::Scalar: {
4315 Value *TargetElement;
4316
4317 if (IsByRef.empty() || !IsByRef[En.index()]) {
4318 TargetElement = Builder.CreateLoad(RI.ElementType, ElemPtr);
4319 } else {
4320 if (RI.DataPtrPtrGen) {
4321 InsertPointOrErrorTy GenResult =
4322 RI.DataPtrPtrGen(Builder.saveIP(), ElemPtr, ElemPtr);
4323
4324 if (!GenResult)
4325 return GenResult.takeError();
4326
4327 ElemPtr = Builder.CreateLoad(Builder.getPtrTy(), ElemPtr);
4328 }
4329 TargetElement = Builder.CreateLoad(RI.ByRefElementType, ElemPtr);
4330 }
4331
4332 Builder.CreateStore(TargetElement, GlobVal);
4333 break;
4334 }
4335 case EvalKind::Complex: {
4336 Value *SrcRealPtr = Builder.CreateConstInBoundsGEP2_32(
4337 RI.ElementType, ElemPtr, 0, 0, ".realp");
4338 Value *SrcReal = Builder.CreateLoad(
4339 RI.ElementType->getStructElementType(0), SrcRealPtr, ".real");
4340 Value *SrcImgPtr = Builder.CreateConstInBoundsGEP2_32(
4341 RI.ElementType, ElemPtr, 0, 1, ".imagp");
4342 Value *SrcImg = Builder.CreateLoad(
4343 RI.ElementType->getStructElementType(1), SrcImgPtr, ".imag");
4344
4345 Value *DestRealPtr = Builder.CreateConstInBoundsGEP2_32(
4346 RI.ElementType, GlobVal, 0, 0, ".realp");
4347 Value *DestImgPtr = Builder.CreateConstInBoundsGEP2_32(
4348 RI.ElementType, GlobVal, 0, 1, ".imagp");
4349 Builder.CreateStore(SrcReal, DestRealPtr);
4350 Builder.CreateStore(SrcImg, DestImgPtr);
4351 break;
4352 }
4353 case EvalKind::Aggregate: {
4354 Value *SizeVal =
4355 Builder.getInt64(M.getDataLayout().getTypeStoreSize(RI.ElementType));
4356 Builder.CreateMemCpy(
4357 GlobVal, M.getDataLayout().getPrefTypeAlign(RI.ElementType), ElemPtr,
4358 M.getDataLayout().getPrefTypeAlign(RI.ElementType), SizeVal, false);
4359 break;
4360 }
4361 }
4362 }
4363
4364 Builder.CreateRetVoid();
4365 return LtGCFunc;
4366}
4367
4368Expected<Function *> OpenMPIRBuilder::emitListToGlobalReduceFunction(
4369 ArrayRef<ReductionInfo> ReductionInfos, Function *ReduceFn,
4370 Type *ReductionsBufferTy, AttributeList FuncAttrs, ArrayRef<bool> IsByRef) {
4371 IRBuilder<>::InsertPointGuard IPG(Builder);
4372 LLVMContext &Ctx = M.getContext();
4373 FunctionType *FuncTy = FunctionType::get(
4374 Builder.getVoidTy(),
4375 {Builder.getPtrTy(), Builder.getInt32Ty(), Builder.getPtrTy()},
4376 /* IsVarArg */ false);
4377 Function *LtGRFunc =
4379 "_omp_reduction_list_to_global_reduce_func", &M);
4380 LtGRFunc->setAttributes(FuncAttrs);
4381 LtGRFunc->addParamAttr(0, Attribute::NoUndef);
4382 LtGRFunc->addParamAttr(1, Attribute::NoUndef);
4383 LtGRFunc->addParamAttr(2, Attribute::NoUndef);
4384
4385 BasicBlock *EntryBlock = BasicBlock::Create(Ctx, "entry", LtGRFunc);
4386 Builder.SetInsertPoint(EntryBlock);
4387 Builder.SetCurrentDebugLocation(llvm::DebugLoc());
4388
4389 // Buffer: global reduction buffer.
4390 Argument *BufferArg = LtGRFunc->getArg(0);
4391 // Idx: index of the buffer.
4392 Argument *IdxArg = LtGRFunc->getArg(1);
4393 // ReduceList: thread local Reduce list.
4394 Argument *ReduceListArg = LtGRFunc->getArg(2);
4395
4396 Value *BufferArgAlloca = Builder.CreateAlloca(Builder.getPtrTy(), nullptr,
4397 BufferArg->getName() + ".addr");
4398 Value *IdxArgAlloca = Builder.CreateAlloca(Builder.getInt32Ty(), nullptr,
4399 IdxArg->getName() + ".addr");
4400 Value *ReduceListArgAlloca = Builder.CreateAlloca(
4401 Builder.getPtrTy(), nullptr, ReduceListArg->getName() + ".addr");
4402 auto *RedListArrayTy =
4403 ArrayType::get(Builder.getPtrTy(), ReductionInfos.size());
4404
4405 // 1. Build a list of reduction variables.
4406 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
4407 Value *LocalReduceList =
4408 Builder.CreateAlloca(RedListArrayTy, nullptr, ".omp.reduction.red_list");
4409
4410 InsertPointTy AllocaIP(EntryBlock->begin());
4411
4412 Value *BufferArgAddrCast = Builder.CreatePointerBitCastOrAddrSpaceCast(
4413 BufferArgAlloca, Builder.getPtrTy(),
4414 BufferArgAlloca->getName() + ".ascast");
4415 Value *IdxArgAddrCast = Builder.CreatePointerBitCastOrAddrSpaceCast(
4416 IdxArgAlloca, Builder.getPtrTy(), IdxArgAlloca->getName() + ".ascast");
4417 Value *ReduceListArgAddrCast = Builder.CreatePointerBitCastOrAddrSpaceCast(
4418 ReduceListArgAlloca, Builder.getPtrTy(),
4419 ReduceListArgAlloca->getName() + ".ascast");
4420 Value *LocalReduceListAddrCast = Builder.CreatePointerBitCastOrAddrSpaceCast(
4421 LocalReduceList, Builder.getPtrTy(),
4422 LocalReduceList->getName() + ".ascast");
4423
4424 Builder.CreateStore(BufferArg, BufferArgAddrCast);
4425 Builder.CreateStore(IdxArg, IdxArgAddrCast);
4426 Builder.CreateStore(ReduceListArg, ReduceListArgAddrCast);
4427
4428 Value *BufferVal = Builder.CreateLoad(Builder.getPtrTy(), BufferArgAddrCast);
4429 Value *Idxs[] = {Builder.CreateLoad(Builder.getInt32Ty(), IdxArgAddrCast)};
4430 Type *IndexTy = Builder.getIndexTy(
4431 M.getDataLayout(), M.getDataLayout().getDefaultGlobalsAddressSpace());
4432 for (auto En : enumerate(ReductionInfos)) {
4433 const ReductionInfo &RI = En.value();
4434
4435 Value *TargetElementPtrPtr = Builder.CreateInBoundsGEP(
4436 RedListArrayTy, LocalReduceListAddrCast,
4437 {ConstantInt::get(IndexTy, 0), ConstantInt::get(IndexTy, En.index())});
4438 Value *BufferVD =
4439 Builder.CreateInBoundsGEP(ReductionsBufferTy, BufferVal, Idxs);
4440 // Global = Buffer.VD[Idx];
4441 Value *GlobValPtr = Builder.CreateConstInBoundsGEP2_32(
4442 ReductionsBufferTy, BufferVD, 0, En.index());
4443
4444 if (!IsByRef.empty() && IsByRef[En.index()] && RI.DataPtrPtrGen) {
4445 // Get source descriptor from the reduce list argument
4446 Value *ReduceList =
4447 Builder.CreateLoad(Builder.getPtrTy(), ReduceListArgAddrCast);
4448 Value *SrcElementPtrPtr =
4449 Builder.CreateInBoundsGEP(RedListArrayTy, ReduceList,
4450 {ConstantInt::get(IndexTy, 0),
4451 ConstantInt::get(IndexTy, En.index())});
4452 Value *SrcDescriptorAddr =
4453 Builder.CreateLoad(Builder.getPtrTy(), SrcElementPtrPtr);
4454
4455 // Copy descriptor from source and update base_ptr to global buffer data
4456 Expected<Value *> ByRefAlloc = createReductionDescriptorCopy(
4457 AllocaIP, RI, GlobValPtr, SrcDescriptorAddr, Builder.getPtrTy());
4458 if (!ByRefAlloc)
4459 return ByRefAlloc.takeError();
4460
4461 Builder.CreateStore(*ByRefAlloc, TargetElementPtrPtr);
4462 } else {
4463 Builder.CreateStore(GlobValPtr, TargetElementPtrPtr);
4464 }
4465 }
4466
4467 // Call reduce_function(GlobalReduceList, ReduceList)
4468 Value *ReduceList =
4469 Builder.CreateLoad(Builder.getPtrTy(), ReduceListArgAddrCast);
4470 createRuntimeFunctionCall(ReduceFn, {LocalReduceListAddrCast, ReduceList})
4471 ->addFnAttr(Attribute::NoUnwind);
4472 Builder.CreateRetVoid();
4473 return LtGRFunc;
4474}
4475
4476Expected<Function *> OpenMPIRBuilder::emitGlobalToListCopyFunction(
4477 ArrayRef<ReductionInfo> ReductionInfos, Type *ReductionsBufferTy,
4478 AttributeList FuncAttrs, ArrayRef<bool> IsByRef) {
4479 IRBuilder<>::InsertPointGuard IPG(Builder);
4480 LLVMContext &Ctx = M.getContext();
4481 FunctionType *FuncTy = FunctionType::get(
4482 Builder.getVoidTy(),
4483 {Builder.getPtrTy(), Builder.getInt32Ty(), Builder.getPtrTy()},
4484 /* IsVarArg */ false);
4485 Function *GtLCFunc =
4487 "_omp_reduction_global_to_list_copy_func", &M);
4488 GtLCFunc->setAttributes(FuncAttrs);
4489 GtLCFunc->addParamAttr(0, Attribute::NoUndef);
4490 GtLCFunc->addParamAttr(1, Attribute::NoUndef);
4491 GtLCFunc->addParamAttr(2, Attribute::NoUndef);
4492
4493 BasicBlock *EntryBlock = BasicBlock::Create(Ctx, "entry", GtLCFunc);
4494 Builder.SetInsertPoint(EntryBlock);
4495 Builder.SetCurrentDebugLocation(llvm::DebugLoc());
4496
4497 // Buffer: global reduction buffer.
4498 Argument *BufferArg = GtLCFunc->getArg(0);
4499 // Idx: index of the buffer.
4500 Argument *IdxArg = GtLCFunc->getArg(1);
4501 // ReduceList: thread local Reduce list.
4502 Argument *ReduceListArg = GtLCFunc->getArg(2);
4503
4504 Value *BufferArgAlloca = Builder.CreateAlloca(Builder.getPtrTy(), nullptr,
4505 BufferArg->getName() + ".addr");
4506 Value *IdxArgAlloca = Builder.CreateAlloca(Builder.getInt32Ty(), nullptr,
4507 IdxArg->getName() + ".addr");
4508 Value *ReduceListArgAlloca = Builder.CreateAlloca(
4509 Builder.getPtrTy(), nullptr, ReduceListArg->getName() + ".addr");
4510 Value *BufferArgAddrCast = Builder.CreatePointerBitCastOrAddrSpaceCast(
4511 BufferArgAlloca, Builder.getPtrTy(),
4512 BufferArgAlloca->getName() + ".ascast");
4513 Value *IdxArgAddrCast = Builder.CreatePointerBitCastOrAddrSpaceCast(
4514 IdxArgAlloca, Builder.getPtrTy(), IdxArgAlloca->getName() + ".ascast");
4515 Value *ReduceListArgAddrCast = Builder.CreatePointerBitCastOrAddrSpaceCast(
4516 ReduceListArgAlloca, Builder.getPtrTy(),
4517 ReduceListArgAlloca->getName() + ".ascast");
4518 Builder.CreateStore(BufferArg, BufferArgAddrCast);
4519 Builder.CreateStore(IdxArg, IdxArgAddrCast);
4520 Builder.CreateStore(ReduceListArg, ReduceListArgAddrCast);
4521
4522 Value *LocalReduceList =
4523 Builder.CreateLoad(Builder.getPtrTy(), ReduceListArgAddrCast);
4524 Value *BufferVal = Builder.CreateLoad(Builder.getPtrTy(), BufferArgAddrCast);
4525 Value *Idxs[] = {Builder.CreateLoad(Builder.getInt32Ty(), IdxArgAddrCast)};
4526 Type *IndexTy = Builder.getIndexTy(
4527 M.getDataLayout(), M.getDataLayout().getDefaultGlobalsAddressSpace());
4528 for (auto En : enumerate(ReductionInfos)) {
4529 const OpenMPIRBuilder::ReductionInfo &RI = En.value();
4530 auto *RedListArrayTy =
4531 ArrayType::get(Builder.getPtrTy(), ReductionInfos.size());
4532 // Reduce element = LocalReduceList[i]
4533 Value *ElemPtrPtr = Builder.CreateInBoundsGEP(
4534 RedListArrayTy, LocalReduceList,
4535 {ConstantInt::get(IndexTy, 0), ConstantInt::get(IndexTy, En.index())});
4536 // elemptr = ((CopyType*)(elemptrptr)) + I
4537 Value *ElemPtr = Builder.CreateLoad(Builder.getPtrTy(), ElemPtrPtr);
4538 // Global = Buffer.VD[Idx];
4539 Value *BufferVD =
4540 Builder.CreateInBoundsGEP(ReductionsBufferTy, BufferVal, Idxs);
4541 Value *GlobValPtr = Builder.CreateConstInBoundsGEP2_32(
4542 ReductionsBufferTy, BufferVD, 0, En.index());
4543
4544 switch (RI.EvaluationKind) {
4545 case EvalKind::Scalar: {
4546 Type *ElemType = RI.ElementType;
4547
4548 if (!IsByRef.empty() && IsByRef[En.index()]) {
4549 ElemType = RI.ByRefElementType;
4550 if (RI.DataPtrPtrGen) {
4551 InsertPointOrErrorTy GenResult =
4552 RI.DataPtrPtrGen(Builder.saveIP(), ElemPtr, ElemPtr);
4553
4554 if (!GenResult)
4555 return GenResult.takeError();
4556
4557 ElemPtr = Builder.CreateLoad(Builder.getPtrTy(), ElemPtr);
4558 }
4559 }
4560
4561 Value *TargetElement = Builder.CreateLoad(ElemType, GlobValPtr);
4562 Builder.CreateStore(TargetElement, ElemPtr);
4563 break;
4564 }
4565 case EvalKind::Complex: {
4566 Value *SrcRealPtr = Builder.CreateConstInBoundsGEP2_32(
4567 RI.ElementType, GlobValPtr, 0, 0, ".realp");
4568 Value *SrcReal = Builder.CreateLoad(
4569 RI.ElementType->getStructElementType(0), SrcRealPtr, ".real");
4570 Value *SrcImgPtr = Builder.CreateConstInBoundsGEP2_32(
4571 RI.ElementType, GlobValPtr, 0, 1, ".imagp");
4572 Value *SrcImg = Builder.CreateLoad(
4573 RI.ElementType->getStructElementType(1), SrcImgPtr, ".imag");
4574
4575 Value *DestRealPtr = Builder.CreateConstInBoundsGEP2_32(
4576 RI.ElementType, ElemPtr, 0, 0, ".realp");
4577 Value *DestImgPtr = Builder.CreateConstInBoundsGEP2_32(
4578 RI.ElementType, ElemPtr, 0, 1, ".imagp");
4579 Builder.CreateStore(SrcReal, DestRealPtr);
4580 Builder.CreateStore(SrcImg, DestImgPtr);
4581 break;
4582 }
4583 case EvalKind::Aggregate: {
4584 Value *SizeVal =
4585 Builder.getInt64(M.getDataLayout().getTypeStoreSize(RI.ElementType));
4586 Builder.CreateMemCpy(
4587 ElemPtr, M.getDataLayout().getPrefTypeAlign(RI.ElementType),
4588 GlobValPtr, M.getDataLayout().getPrefTypeAlign(RI.ElementType),
4589 SizeVal, false);
4590 break;
4591 }
4592 }
4593 }
4594
4595 Builder.CreateRetVoid();
4596 return GtLCFunc;
4597}
4598
4599Expected<Function *> OpenMPIRBuilder::emitGlobalToListReduceFunction(
4600 ArrayRef<ReductionInfo> ReductionInfos, Function *ReduceFn,
4601 Type *ReductionsBufferTy, AttributeList FuncAttrs, ArrayRef<bool> IsByRef) {
4602 IRBuilder<>::InsertPointGuard IPG(Builder);
4603 LLVMContext &Ctx = M.getContext();
4604 auto *FuncTy = FunctionType::get(
4605 Builder.getVoidTy(),
4606 {Builder.getPtrTy(), Builder.getInt32Ty(), Builder.getPtrTy()},
4607 /* IsVarArg */ false);
4608 Function *GtLRFunc =
4610 "_omp_reduction_global_to_list_reduce_func", &M);
4611 GtLRFunc->setAttributes(FuncAttrs);
4612 GtLRFunc->addParamAttr(0, Attribute::NoUndef);
4613 GtLRFunc->addParamAttr(1, Attribute::NoUndef);
4614 GtLRFunc->addParamAttr(2, Attribute::NoUndef);
4615
4616 BasicBlock *EntryBlock = BasicBlock::Create(Ctx, "entry", GtLRFunc);
4617 Builder.SetInsertPoint(EntryBlock);
4618 Builder.SetCurrentDebugLocation(llvm::DebugLoc());
4619
4620 // Buffer: global reduction buffer.
4621 Argument *BufferArg = GtLRFunc->getArg(0);
4622 // Idx: index of the buffer.
4623 Argument *IdxArg = GtLRFunc->getArg(1);
4624 // ReduceList: thread local Reduce list.
4625 Argument *ReduceListArg = GtLRFunc->getArg(2);
4626
4627 Value *BufferArgAlloca = Builder.CreateAlloca(Builder.getPtrTy(), nullptr,
4628 BufferArg->getName() + ".addr");
4629 Value *IdxArgAlloca = Builder.CreateAlloca(Builder.getInt32Ty(), nullptr,
4630 IdxArg->getName() + ".addr");
4631 Value *ReduceListArgAlloca = Builder.CreateAlloca(
4632 Builder.getPtrTy(), nullptr, ReduceListArg->getName() + ".addr");
4633 ArrayType *RedListArrayTy =
4634 ArrayType::get(Builder.getPtrTy(), ReductionInfos.size());
4635
4636 // 1. Build a list of reduction variables.
4637 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
4638 Value *LocalReduceList =
4639 Builder.CreateAlloca(RedListArrayTy, nullptr, ".omp.reduction.red_list");
4640
4641 InsertPointTy AllocaIP(EntryBlock->begin());
4642
4643 Value *BufferArgAddrCast = Builder.CreatePointerBitCastOrAddrSpaceCast(
4644 BufferArgAlloca, Builder.getPtrTy(),
4645 BufferArgAlloca->getName() + ".ascast");
4646 Value *IdxArgAddrCast = Builder.CreatePointerBitCastOrAddrSpaceCast(
4647 IdxArgAlloca, Builder.getPtrTy(), IdxArgAlloca->getName() + ".ascast");
4648 Value *ReduceListArgAddrCast = Builder.CreatePointerBitCastOrAddrSpaceCast(
4649 ReduceListArgAlloca, Builder.getPtrTy(),
4650 ReduceListArgAlloca->getName() + ".ascast");
4651 Value *ReductionList = Builder.CreatePointerBitCastOrAddrSpaceCast(
4652 LocalReduceList, Builder.getPtrTy(),
4653 LocalReduceList->getName() + ".ascast");
4654
4655 Builder.CreateStore(BufferArg, BufferArgAddrCast);
4656 Builder.CreateStore(IdxArg, IdxArgAddrCast);
4657 Builder.CreateStore(ReduceListArg, ReduceListArgAddrCast);
4658
4659 Value *BufferVal = Builder.CreateLoad(Builder.getPtrTy(), BufferArgAddrCast);
4660 Value *Idxs[] = {Builder.CreateLoad(Builder.getInt32Ty(), IdxArgAddrCast)};
4661 Type *IndexTy = Builder.getIndexTy(
4662 M.getDataLayout(), M.getDataLayout().getDefaultGlobalsAddressSpace());
4663 for (auto En : enumerate(ReductionInfos)) {
4664 const ReductionInfo &RI = En.value();
4665
4666 Value *TargetElementPtrPtr = Builder.CreateInBoundsGEP(
4667 RedListArrayTy, ReductionList,
4668 {ConstantInt::get(IndexTy, 0), ConstantInt::get(IndexTy, En.index())});
4669 // Global = Buffer.VD[Idx];
4670 Value *BufferVD =
4671 Builder.CreateInBoundsGEP(ReductionsBufferTy, BufferVal, Idxs);
4672 Value *GlobValPtr = Builder.CreateConstInBoundsGEP2_32(
4673 ReductionsBufferTy, BufferVD, 0, En.index());
4674
4675 if (!IsByRef.empty() && IsByRef[En.index()] && RI.DataPtrPtrGen) {
4676 // Get source descriptor from the reduce list
4677 Value *ReduceListVal =
4678 Builder.CreateLoad(Builder.getPtrTy(), ReduceListArgAddrCast);
4679 Value *SrcElementPtrPtr =
4680 Builder.CreateInBoundsGEP(RedListArrayTy, ReduceListVal,
4681 {ConstantInt::get(IndexTy, 0),
4682 ConstantInt::get(IndexTy, En.index())});
4683 Value *SrcDescriptorAddr =
4684 Builder.CreateLoad(Builder.getPtrTy(), SrcElementPtrPtr);
4685
4686 // Copy descriptor from source and update base_ptr to global buffer data
4687 Expected<Value *> ByRefAlloc = createReductionDescriptorCopy(
4688 AllocaIP, RI, GlobValPtr, SrcDescriptorAddr, Builder.getPtrTy());
4689 if (!ByRefAlloc)
4690 return ByRefAlloc.takeError();
4691
4692 Builder.CreateStore(*ByRefAlloc, TargetElementPtrPtr);
4693 } else {
4694 Builder.CreateStore(GlobValPtr, TargetElementPtrPtr);
4695 }
4696 }
4697
4698 // Call reduce_function(ReduceList, GlobalReduceList)
4699 Value *ReduceList =
4700 Builder.CreateLoad(Builder.getPtrTy(), ReduceListArgAddrCast);
4701 createRuntimeFunctionCall(ReduceFn, {ReduceList, ReductionList})
4702 ->addFnAttr(Attribute::NoUnwind);
4703 Builder.CreateRetVoid();
4704 return GtLRFunc;
4705}
4706
4707std::string OpenMPIRBuilder::getReductionFuncName(StringRef Name) const {
4708 std::string Suffix =
4709 createPlatformSpecificName({"omp", "reduction", "reduction_func"});
4710 return (Name + Suffix).str();
4711}
4712
4713Expected<Function *> OpenMPIRBuilder::createReductionFunction(
4714 StringRef ReducerName, ArrayRef<ReductionInfo> ReductionInfos,
4716 AttributeList FuncAttrs) {
4717 IRBuilder<>::InsertPointGuard IPG(Builder);
4718 auto *FuncTy = FunctionType::get(Builder.getVoidTy(),
4719 {Builder.getPtrTy(), Builder.getPtrTy()},
4720 /* IsVarArg */ false);
4721 std::string Name = getReductionFuncName(ReducerName);
4722 Function *ReductionFunc =
4724 ReductionFunc->setCallingConv(Config.getRuntimeCC());
4725 ReductionFunc->setAttributes(FuncAttrs);
4726 ReductionFunc->addParamAttr(0, Attribute::NoUndef);
4727 ReductionFunc->addParamAttr(1, Attribute::NoUndef);
4728 BasicBlock *EntryBB =
4729 BasicBlock::Create(M.getContext(), "entry", ReductionFunc);
4730 Builder.SetInsertPoint(EntryBB);
4731 Builder.SetCurrentDebugLocation(llvm::DebugLoc());
4732
4733 // Need to alloca memory here and deal with the pointers before getting
4734 // LHS/RHS pointers out
4735 Value *LHSArrayPtr = nullptr;
4736 Value *RHSArrayPtr = nullptr;
4737 Argument *Arg0 = ReductionFunc->getArg(0);
4738 Argument *Arg1 = ReductionFunc->getArg(1);
4739 Type *Arg0Type = Arg0->getType();
4740 Type *Arg1Type = Arg1->getType();
4741
4742 Value *LHSAlloca =
4743 Builder.CreateAlloca(Arg0Type, nullptr, Arg0->getName() + ".addr");
4744 Value *RHSAlloca =
4745 Builder.CreateAlloca(Arg1Type, nullptr, Arg1->getName() + ".addr");
4746 Value *LHSAddrCast = Builder.CreatePointerBitCastOrAddrSpaceCast(
4747 LHSAlloca, Arg0Type, LHSAlloca->getName() + ".ascast");
4748 Value *RHSAddrCast = Builder.CreatePointerBitCastOrAddrSpaceCast(
4749 RHSAlloca, Arg1Type, RHSAlloca->getName() + ".ascast");
4750 Builder.CreateStore(Arg0, LHSAddrCast);
4751 Builder.CreateStore(Arg1, RHSAddrCast);
4752 LHSArrayPtr = Builder.CreateLoad(Arg0Type, LHSAddrCast);
4753 RHSArrayPtr = Builder.CreateLoad(Arg1Type, RHSAddrCast);
4754
4755 Type *RedArrayTy = ArrayType::get(Builder.getPtrTy(), ReductionInfos.size());
4756 Type *IndexTy = Builder.getIndexTy(
4757 M.getDataLayout(), M.getDataLayout().getDefaultGlobalsAddressSpace());
4758 SmallVector<Value *> LHSPtrs, RHSPtrs;
4759 for (auto En : enumerate(ReductionInfos)) {
4760 const ReductionInfo &RI = En.value();
4761 Value *RHSI8PtrPtr = Builder.CreateInBoundsGEP(
4762 RedArrayTy, RHSArrayPtr,
4763 {ConstantInt::get(IndexTy, 0), ConstantInt::get(IndexTy, En.index())});
4764 Value *RHSI8Ptr = Builder.CreateLoad(Builder.getPtrTy(), RHSI8PtrPtr);
4765 Value *RHSPtr = Builder.CreatePointerBitCastOrAddrSpaceCast(
4766 RHSI8Ptr, RI.PrivateVariable->getType(),
4767 RHSI8Ptr->getName() + ".ascast");
4768
4769 Value *LHSI8PtrPtr = Builder.CreateInBoundsGEP(
4770 RedArrayTy, LHSArrayPtr,
4771 {ConstantInt::get(IndexTy, 0), ConstantInt::get(IndexTy, En.index())});
4772 Value *LHSI8Ptr = Builder.CreateLoad(Builder.getPtrTy(), LHSI8PtrPtr);
4773 Value *LHSPtr = Builder.CreatePointerBitCastOrAddrSpaceCast(
4774 LHSI8Ptr, RI.Variable->getType(), LHSI8Ptr->getName() + ".ascast");
4775
4777 LHSPtrs.emplace_back(LHSPtr);
4778 RHSPtrs.emplace_back(RHSPtr);
4779 } else {
4780 Value *LHS = LHSPtr;
4781 Value *RHS = RHSPtr;
4782
4783 if (!IsByRef.empty() && !IsByRef[En.index()]) {
4784 LHS = Builder.CreateLoad(RI.ElementType, LHSPtr);
4785 RHS = Builder.CreateLoad(RI.ElementType, RHSPtr);
4786 }
4787
4788 Value *Reduced;
4789 InsertPointOrErrorTy AfterIP =
4790 RI.ReductionGen(Builder.saveIP(), LHS, RHS, Reduced);
4791 if (!AfterIP)
4792 return AfterIP.takeError();
4793 if (!Builder.GetInsertBlock())
4794 return ReductionFunc;
4795
4796 Builder.restoreIP(*AfterIP);
4797
4798 if (!IsByRef.empty() && !IsByRef[En.index()])
4799 Builder.CreateStore(Reduced, LHSPtr);
4800 }
4801 }
4802
4804 for (auto En : enumerate(ReductionInfos)) {
4805 unsigned Index = En.index();
4806 const ReductionInfo &RI = En.value();
4807 Value *LHSFixupPtr, *RHSFixupPtr;
4808 Builder.restoreIP(RI.ReductionGenClang(
4809 Builder.saveIP(), Index, &LHSFixupPtr, &RHSFixupPtr, ReductionFunc));
4810
4811 // Fix the CallBack code genereated to use the correct Values for the LHS
4812 // and RHS
4813 LHSFixupPtr->replaceUsesWithIf(
4814 LHSPtrs[Index], [ReductionFunc](const Use &U) {
4815 return cast<Instruction>(U.getUser())->getParent()->getParent() ==
4816 ReductionFunc;
4817 });
4818 RHSFixupPtr->replaceUsesWithIf(
4819 RHSPtrs[Index], [ReductionFunc](const Use &U) {
4820 return cast<Instruction>(U.getUser())->getParent()->getParent() ==
4821 ReductionFunc;
4822 });
4823 }
4824
4825 Builder.CreateRetVoid();
4826 // Compiling with `-O0`, `alloca`s emitted in non-entry blocks are not hoisted
4827 // to the entry block (this is dones for higher opt levels by later passes in
4828 // the pipeline). This has caused issues because non-entry `alloca`s force the
4829 // function to use dynamic stack allocations and we might run out of scratch
4830 // memory.
4831 hoistNonEntryAllocasToEntryBlock(ReductionFunc);
4832
4833 return ReductionFunc;
4834}
4835
4836static void
4838 bool IsGPU) {
4839 for (const OpenMPIRBuilder::ReductionInfo &RI : ReductionInfos) {
4840 (void)RI;
4841 assert(RI.Variable && "expected non-null variable");
4842 assert(RI.PrivateVariable && "expected non-null private variable");
4843 assert((RI.ReductionGen || RI.ReductionGenClang) &&
4844 "expected non-null reduction generator callback");
4845 if (!IsGPU) {
4846 assert(
4847 RI.Variable->getType() == RI.PrivateVariable->getType() &&
4848 "expected variables and their private equivalents to have the same "
4849 "type");
4850 }
4851 assert(RI.Variable->getType()->isPointerTy() &&
4852 "expected variables to be pointers");
4853 }
4854}
4855
4856// The atomic cross-team reduction fast path applies when every reduction in the
4857// set can be represented by an atomicrmw. Clang only populates it for scalar
4858// reductions with a supported atomic operator.
4861 return all_of(ReductionInfos, [](const OpenMPIRBuilder::ReductionInfo &RI) {
4862 return static_cast<bool>(RI.AtomicReductionGen);
4863 });
4864}
4865
4867 const LocationDescription &Loc, InsertPointTy AllocaIP,
4868 InsertPointTy CodeGenIP, ArrayRef<ReductionInfo> ReductionInfos,
4869 ArrayRef<bool> IsByRef, bool IsNoWait, bool IsTeamsReduction, bool IsSPMD,
4870 ReductionGenCBKind ReductionGenCBKind, std::optional<omp::GV> GridValue,
4871 Value *SrcLocInfo) {
4872 if (!updateToLocation(Loc))
4873 return InsertPointTy();
4874 Builder.restoreIP(CodeGenIP);
4875 Builder.SetCurrentDebugLocation(Loc.DL);
4876 checkReductionInfos(ReductionInfos, /*IsGPU*/ true);
4877 LLVMContext &Ctx = M.getContext();
4878
4879 // Source location for the ident struct
4880 if (!SrcLocInfo) {
4881 uint32_t SrcLocStrSize;
4882 Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
4883 SrcLocInfo = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
4884 }
4885
4886 if (ReductionInfos.size() == 0)
4887 return Builder.saveIP();
4888
4889 BasicBlock *ContinuationBlock = nullptr;
4891 // Copied code from createReductions
4892 BasicBlock *InsertBlock = Loc.IP.getNodeParent();
4893 ContinuationBlock = InsertBlock->splitBasicBlock(Loc.IP, "reduce.finalize");
4894 InsertBlock->getTerminator()->eraseFromParent();
4895 Builder.SetInsertPoint(InsertBlock->end());
4896 }
4897
4898 Function *CurFunc = Builder.GetInsertBlock()->getParent();
4899 AttributeList FuncAttrs;
4900 AttrBuilder AttrBldr(Ctx);
4901 for (auto Attr : CurFunc->getAttributes().getFnAttrs())
4902 AttrBldr.addAttribute(Attr);
4903 AttrBldr.removeAttribute(Attribute::OptimizeNone);
4904 FuncAttrs = FuncAttrs.addFnAttributes(Ctx, AttrBldr);
4905
4906 Expected<Function *> ReductionResult = createReductionFunction(
4907 Builder.GetInsertBlock()->getParent()->getName(), ReductionInfos, IsByRef,
4908 ReductionGenCBKind, FuncAttrs);
4909 if (!ReductionResult)
4910 return ReductionResult.takeError();
4911 Function *ReductionFunc = *ReductionResult;
4912
4913 // Set the grid value in the config needed for lowering later on
4914 if (GridValue.has_value())
4915 Config.setGridValue(GridValue.value());
4916 else
4917 Config.setGridValue(getGridValue(T, ReductionFunc));
4918
4919 // Build res = __kmpc_reduce{_nowait}(<gtid>, <n>, sizeof(RedList),
4920 // RedList, shuffle_reduce_func, interwarp_copy_func);
4921 // or
4922 // Build res = __kmpc_reduce_teams_nowait_simple(<loc>, <gtid>, <lck>);
4923 Value *Res;
4924
4925 // 1. Build a list of reduction variables.
4926 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
4927 auto Size = ReductionInfos.size();
4928 Type *PtrTy = PointerType::get(Ctx, Config.getDefaultTargetAS());
4929 Type *FuncPtrTy =
4930 Builder.getPtrTy(M.getDataLayout().getProgramAddressSpace());
4931 Type *RedArrayTy = ArrayType::get(PtrTy, Size);
4932 Value *ReductionList;
4933 {
4935 Builder.restoreIP(AllocaIP);
4936 Value *ReductionListAlloca =
4937 Builder.CreateAlloca(RedArrayTy, nullptr, ".omp.reduction.red_list");
4938 ReductionList = Builder.CreatePointerBitCastOrAddrSpaceCast(
4939 ReductionListAlloca, PtrTy, ReductionListAlloca->getName() + ".ascast");
4940 }
4941 Type *IndexTy = Builder.getIndexTy(
4942 M.getDataLayout(), M.getDataLayout().getDefaultGlobalsAddressSpace());
4943 for (auto En : enumerate(ReductionInfos)) {
4944 const ReductionInfo &RI = En.value();
4945 Value *ElemPtr = Builder.CreateInBoundsGEP(
4946 RedArrayTy, ReductionList,
4947 {ConstantInt::get(IndexTy, 0), ConstantInt::get(IndexTy, En.index())});
4948
4949 Value *PrivateVar = RI.PrivateVariable;
4950 bool IsByRefElem = !IsByRef.empty() && IsByRef[En.index()];
4951 if (IsByRefElem)
4952 PrivateVar = Builder.CreateLoad(RI.ElementType, PrivateVar);
4953
4954 Value *CastElem =
4955 Builder.CreatePointerBitCastOrAddrSpaceCast(PrivateVar, PtrTy);
4956 Builder.CreateStore(CastElem, ElemPtr);
4957 }
4958 Expected<Function *> SarFunc = emitShuffleAndReduceFunction(
4959 ReductionInfos, ReductionFunc, FuncAttrs, IsByRef);
4960
4961 if (!SarFunc)
4962 return SarFunc.takeError();
4963
4964 Expected<Function *> CopyResult =
4965 emitInterWarpCopyFunction(Loc, ReductionInfos, FuncAttrs, IsByRef);
4966 if (!CopyResult)
4967 return CopyResult.takeError();
4968 Function *WcFunc = *CopyResult;
4969
4970 Value *RL = Builder.CreatePointerBitCastOrAddrSpaceCast(ReductionList, PtrTy);
4971
4972 // NOTE: ReductionDataSize is passed as the reduce_data_size argument to
4973 // __kmpc_nvptx_parallel_reduce_nowait_v2, but the runtime implementations do
4974 // not currently use it. It is computed here conservatively as max(element
4975 // sizes) * N rather than the exact sum, which over-calculates the size for
4976 // mixed reduction types but is harmless given the argument is unused.
4977 // TODO: Consider dropping this computation if the runtime API is ever revised
4978 // to remove the unused parameter.
4979 unsigned MaxDataSize = 0;
4980 SmallVector<Type *> ReductionTypeArgs;
4981 for (auto En : enumerate(ReductionInfos)) {
4982 // Use ByRefElementType for by-ref reductions so that MaxDataSize matches
4983 // the actual data size stored in the global reduction buffer, consistent
4984 // with the ReductionsBufferTy struct used for GEP offsets below.
4985 Type *RedTypeArg = (!IsByRef.empty() && IsByRef[En.index()])
4986 ? En.value().ByRefElementType
4987 : En.value().ElementType;
4988 auto Size = M.getDataLayout().getTypeStoreSize(RedTypeArg);
4989 if (Size > MaxDataSize)
4990 MaxDataSize = Size;
4991 ReductionTypeArgs.emplace_back(RedTypeArg);
4992 }
4993 Value *ReductionDataSize =
4994 Builder.getInt64(MaxDataSize * ReductionInfos.size());
4995
4996 // Helper function to copy thread-local data back to the original reduction
4997 // list.
4998 Function *CopyScratchToListFunc = nullptr;
4999 // Thread-local storage for the reduction variables.
5000 Value *ScratchForCopyBack = nullptr;
5001 // RL pointer to which the final value from the per-thread scratch should be
5002 // copied back. (Basically RL, appropriately casted if necessary.)
5003 Value *RLForCopyBack = RL;
5004
5005 bool IsAtomicReduction =
5006 IsTeamsReduction && isAtomicableReductionSet(ReductionInfos);
5007
5008 if (!IsTeamsReduction) {
5009 Value *SarFuncCast =
5010 Builder.CreatePointerBitCastOrAddrSpaceCast(*SarFunc, FuncPtrTy);
5011 Value *WcFuncCast =
5012 Builder.CreatePointerBitCastOrAddrSpaceCast(WcFunc, FuncPtrTy);
5013 Value *Args[] = {SrcLocInfo, ReductionDataSize, RL, SarFuncCast,
5014 WcFuncCast};
5016 RuntimeFunction::OMPRTL___kmpc_nvptx_parallel_reduce_nowait_v2);
5017 Res = createRuntimeFunctionCall(Pv2Ptr, Args);
5018 } else if (IsAtomicReduction) {
5019 // Atomic cross-team reduction fast path: determine the team's main thread
5020 // that is later to fold its value atomically into the mapped variable.
5021 Function *IsMainThreadFn = getOrCreateRuntimeFunctionPtr(
5022 RuntimeFunction::OMPRTL___kmpc_is_team_main_thread);
5023 Res = createRuntimeFunctionCall(IsMainThreadFn, {});
5024 } else {
5025 StructType *ReductionsBufferTy = StructType::create(
5026 Ctx, ReductionTypeArgs, "struct._globalized_locals_ty");
5027
5028 Expected<Function *> LtGCFunc = emitListToGlobalCopyFunction(
5029 ReductionInfos, ReductionsBufferTy, FuncAttrs, IsByRef);
5030 if (!LtGCFunc)
5031 return LtGCFunc.takeError();
5032
5033 Expected<Function *> GtLCFunc = emitGlobalToListCopyFunction(
5034 ReductionInfos, ReductionsBufferTy, FuncAttrs, IsByRef);
5035 if (!GtLCFunc)
5036 return GtLCFunc.takeError();
5037
5038 Expected<Function *> GtLRFunc = emitGlobalToListReduceFunction(
5039 ReductionInfos, ReductionFunc, ReductionsBufferTy, FuncAttrs, IsByRef);
5040 if (!GtLRFunc)
5041 return GtLRFunc.takeError();
5042
5043 // The runtime's cross-team final aggregate uses the storage pointed at by
5044 // its reduce-list argument as per-thread scratch. When the surrounding
5045 // kernel is already in SPMD execution mode, clang emitted each reduction
5046 // private as a per-thread `alloca addrspace(5)`, so the original red_list
5047 // (RL) is already per-thread and nothing else is needed.
5048 //
5049 // When the kernel is in Non-SPMD execution mode at codegen time, clang's
5050 // Generic-mode globalization put the reduction private into team-shared
5051 // LDS. OpenMPOpt may later upgrade the kernel to Generic-SPMD, at which
5052 // point all threads of the last team would race on the shared LDS slot.
5053 // Emit a per-thread scratch buffer and a per-thread RL, copy the team-local
5054 // value in, and hand the per-thread RL to the runtime instead. The writer
5055 // thread copies the final value from that per-thread scratch back to RL
5056 // before running the existing combine path below.
5057
5058 // Thread-local RL (might need localization below before being passed to the
5059 // runtime).
5060 Value *RuntimeRL = RL;
5061
5062 if (!IsSPMD) {
5063 Value *PerThreadScratch;
5064
5065 {
5067 Builder.restoreIP(AllocaIP);
5068 // Allocate thread-local buffer for the reduction variables.
5069 Value *PerThreadScratchAlloca =
5070 Builder.CreateAlloca(ReductionsBufferTy, /*ArraySize=*/nullptr,
5071 ".omp.reduction.scratch");
5072 PerThreadScratch = Builder.CreatePointerBitCastOrAddrSpaceCast(
5073 PerThreadScratchAlloca, PtrTy,
5074 PerThreadScratchAlloca->getName() + ".ascast");
5075 // Allocate thread-local buffer for the pointers to the reduction
5076 // variables.
5077 Value *PerThreadRedListAlloca =
5078 Builder.CreateAlloca(RedArrayTy, /*ArraySize=*/nullptr,
5079 ".omp.reduction.per_thread_red_list");
5080 RuntimeRL = Builder.CreatePointerBitCastOrAddrSpaceCast(
5081 PerThreadRedListAlloca, PtrTy,
5082 PerThreadRedListAlloca->getName() + ".ascast");
5083 }
5084
5085 // Iterate over the reduction variables and copy the team-local value to
5086 // the thread-local buffer.
5087 for (auto En : enumerate(ReductionInfos)) {
5088 const ReductionInfo &RI = En.value();
5089 bool IsByRefElem = !IsByRef.empty() && IsByRef[En.index()];
5090
5091 Value *FieldPtr = Builder.CreateConstInBoundsGEP2_32(
5092 ReductionsBufferTy, PerThreadScratch, 0, En.index());
5093 Value *Slot = Builder.CreateConstInBoundsGEP2_32(RedArrayTy, RuntimeRL,
5094 0, En.index());
5095
5096 Value *RuntimeListEntry = FieldPtr;
5097 if (IsByRefElem && RI.DataPtrPtrGen) {
5098 Value *SrcDescriptor =
5099 Builder.CreateLoad(RI.ElementType, RI.PrivateVariable);
5100 Expected<Value *> Descriptor = createReductionDescriptorCopy(
5101 AllocaIP, RI, FieldPtr, SrcDescriptor, PtrTy);
5102 if (!Descriptor)
5103 return Descriptor.takeError();
5104 RuntimeListEntry = *Descriptor;
5105 }
5106 Builder.CreateStore(RuntimeListEntry, Slot);
5107 }
5108 // The copy helpers were emitted with default-AS (AS 0) pointer params
5109 // (see emitListToGlobalCopyFunction / emitGlobalToListCopyFunction),
5110 // but PerThreadScratch and RL live in the target's default AS, which
5111 // is non-zero on e.g. SPIRV. (See Config.getDefaultTargetAS().)
5112 Type *CopyArg0Ty = (*LtGCFunc)->getFunctionType()->getParamType(0);
5113 Type *CopyArg2Ty = (*LtGCFunc)->getFunctionType()->getParamType(2);
5114 ScratchForCopyBack = Builder.CreatePointerBitCastOrAddrSpaceCast(
5115 PerThreadScratch, CopyArg0Ty);
5116 RLForCopyBack =
5117 Builder.CreatePointerBitCastOrAddrSpaceCast(RL, CopyArg2Ty);
5118 // Use index 0 because there is no array of target values to index into,
5119 // there is only one thread-local memory slot.
5120 // restoreIP above left a stale/empty debug location; this inlinable call
5121 // to a debug-info-bearing helper needs one or the verifier rejects the
5122 // module ("!dbg attachment points at wrong subprogram") after inlining.
5123 Builder.SetCurrentDebugLocation(Loc.DL);
5124 Builder.CreateCall(
5125 *LtGCFunc, {ScratchForCopyBack, Builder.getInt32(0), RLForCopyBack});
5126 CopyScratchToListFunc = *GtLCFunc;
5127 }
5128
5129 Value *Args3[] = {SrcLocInfo, RuntimeRL, *SarFunc, WcFunc,
5130 *LtGCFunc, *GtLCFunc, *GtLRFunc};
5131
5132 Function *TeamsReduceFn = getOrCreateRuntimeFunctionPtr(
5133 RuntimeFunction::OMPRTL___kmpc_gpu_xteam_reduce_nowait);
5134 Res = createRuntimeFunctionCall(TeamsReduceFn, Args3);
5135 }
5136
5137 // 5. Build if (res == 1)
5138 BasicBlock *ExitBB = BasicBlock::Create(Ctx, ".omp.reduction.done");
5139 BasicBlock *ThenBB = BasicBlock::Create(Ctx, ".omp.reduction.then");
5140 Value *Cond = Builder.CreateICmpEQ(Res, Builder.getInt32(1));
5141 Builder.CreateCondBr(Cond, ThenBB, ExitBB);
5142
5143 // 6. Build then branch: where we have reduced values in the master
5144 // thread in each team.
5145 // __kmpc_end_reduce{_nowait}(<gtid>);
5146 // break;
5147 emitBlock(ThenBB, CurFunc);
5148
5149 // Copy the writer thread's per-thread scratch result back into the original
5150 // red-list storage before the existing combine path reads RI.PrivateVariable.
5151 // Set a debug location: this inlinable call to a debug-info-bearing helper
5152 // needs one or the verifier rejects the module after inlining.
5153 if (ScratchForCopyBack) {
5154 Builder.SetCurrentDebugLocation(Loc.DL);
5155 Builder.CreateCall(
5156 CopyScratchToListFunc,
5157 {ScratchForCopyBack, Builder.getInt32(0), RLForCopyBack});
5158 }
5159
5160 // Add emission of __kmpc_end_reduce{_nowait}(<gtid>);
5161 for (auto En : enumerate(ReductionInfos)) {
5162 const ReductionInfo &RI = En.value();
5163
5164 // Atomic cross-team fast path: each team's main thread folds its
5165 // team-reduced value directly into the mapped reduction variable with a
5166 // single atomicrmw.
5167 if (IsAtomicReduction) {
5169 Builder.saveIP(), RI.ElementType, RI.Variable, RI.PrivateVariable);
5170 if (!AfterIP)
5171 return AfterIP.takeError();
5172 Builder.restoreIP(*AfterIP);
5173 continue;
5174 }
5175
5177 Value *RedValue = RI.Variable;
5178
5179 Value *RHS =
5180 Builder.CreatePointerBitCastOrAddrSpaceCast(RI.PrivateVariable, PtrTy);
5181
5183 Value *LHSPtr, *RHSPtr;
5184 Builder.restoreIP(RI.ReductionGenClang(Builder.saveIP(), En.index(),
5185 &LHSPtr, &RHSPtr, CurFunc));
5186
5187 // Fix the CallBack code genereated to use the correct Values for the LHS
5188 // and RHS. Cast to match types before replacing (necessary to handle
5189 // different address spaces).
5190 if (LHSPtr->getType() != RedValue->getType())
5191 RedValue = Builder.CreatePointerBitCastOrAddrSpaceCast(
5192 RedValue, LHSPtr->getType());
5193 if (RHSPtr->getType() != RHS->getType())
5194 RHS =
5195 Builder.CreatePointerBitCastOrAddrSpaceCast(RHS, RHSPtr->getType());
5196
5197 LHSPtr->replaceUsesWithIf(RedValue, [ReductionFunc](const Use &U) {
5198 return cast<Instruction>(U.getUser())->getParent()->getParent() ==
5199 ReductionFunc;
5200 });
5201 RHSPtr->replaceUsesWithIf(RHS, [ReductionFunc](const Use &U) {
5202 return cast<Instruction>(U.getUser())->getParent()->getParent() ==
5203 ReductionFunc;
5204 });
5205 } else {
5206 if (IsByRef.empty() || !IsByRef[En.index()]) {
5207 RedValue = Builder.CreateLoad(ValueType, RI.Variable,
5208 "red.value." + Twine(En.index()));
5209 }
5210 Value *PrivateRedValue = Builder.CreateLoad(
5211 ValueType, RHS, "red.private.value" + Twine(En.index()));
5212 Value *Reduced;
5213 InsertPointOrErrorTy AfterIP =
5214 RI.ReductionGen(Builder.saveIP(), RedValue, PrivateRedValue, Reduced);
5215 if (!AfterIP)
5216 return AfterIP.takeError();
5217 Builder.restoreIP(*AfterIP);
5218
5219 if (!IsByRef.empty() && !IsByRef[En.index()])
5220 Builder.CreateStore(Reduced, RI.Variable);
5221 }
5222 }
5223 emitBlock(ExitBB, CurFunc);
5224 if (ContinuationBlock) {
5225 Builder.CreateBr(ContinuationBlock);
5226 Builder.SetInsertPoint(ContinuationBlock);
5227 }
5228 Config.setEmitLLVMUsed();
5229
5230 return Builder.saveIP();
5231}
5232
5234 Type *VoidTy = Type::getVoidTy(M.getContext());
5235 Type *Int8PtrTy = PointerType::getUnqual(M.getContext());
5236 auto *FuncTy =
5237 FunctionType::get(VoidTy, {Int8PtrTy, Int8PtrTy}, /* IsVarArg */ false);
5239 ".omp.reduction.func", &M);
5240}
5241
5243 Function *ReductionFunc,
5245 IRBuilder<> &Builder, ArrayRef<bool> IsByRef, bool IsGPU) {
5246 IRBuilder<>::InsertPointGuard IPG(Builder);
5247 Module *Module = ReductionFunc->getParent();
5248 BasicBlock *ReductionFuncBlock =
5249 BasicBlock::Create(Module->getContext(), "", ReductionFunc);
5250 Builder.SetInsertPoint(ReductionFuncBlock);
5251 Builder.SetCurrentDebugLocation(llvm::DebugLoc());
5252 Value *LHSArrayPtr = nullptr;
5253 Value *RHSArrayPtr = nullptr;
5254 if (IsGPU) {
5255 // Need to alloca memory here and deal with the pointers before getting
5256 // LHS/RHS pointers out
5257 //
5258 Argument *Arg0 = ReductionFunc->getArg(0);
5259 Argument *Arg1 = ReductionFunc->getArg(1);
5260 Type *Arg0Type = Arg0->getType();
5261 Type *Arg1Type = Arg1->getType();
5262
5263 Value *LHSAlloca =
5264 Builder.CreateAlloca(Arg0Type, nullptr, Arg0->getName() + ".addr");
5265 Value *RHSAlloca =
5266 Builder.CreateAlloca(Arg1Type, nullptr, Arg1->getName() + ".addr");
5267 Value *LHSAddrCast =
5268 Builder.CreatePointerBitCastOrAddrSpaceCast(LHSAlloca, Arg0Type);
5269 Value *RHSAddrCast =
5270 Builder.CreatePointerBitCastOrAddrSpaceCast(RHSAlloca, Arg1Type);
5271 Builder.CreateStore(Arg0, LHSAddrCast);
5272 Builder.CreateStore(Arg1, RHSAddrCast);
5273 LHSArrayPtr = Builder.CreateLoad(Arg0Type, LHSAddrCast);
5274 RHSArrayPtr = Builder.CreateLoad(Arg1Type, RHSAddrCast);
5275 } else {
5276 LHSArrayPtr = ReductionFunc->getArg(0);
5277 RHSArrayPtr = ReductionFunc->getArg(1);
5278 }
5279
5280 unsigned NumReductions = ReductionInfos.size();
5281 Type *RedArrayTy = ArrayType::get(Builder.getPtrTy(), NumReductions);
5282
5283 for (auto En : enumerate(ReductionInfos)) {
5284 const OpenMPIRBuilder::ReductionInfo &RI = En.value();
5285 Value *LHSI8PtrPtr = Builder.CreateConstInBoundsGEP2_64(
5286 RedArrayTy, LHSArrayPtr, 0, En.index());
5287 Value *LHSI8Ptr = Builder.CreateLoad(Builder.getPtrTy(), LHSI8PtrPtr);
5288 Value *LHSPtr = Builder.CreatePointerBitCastOrAddrSpaceCast(
5289 LHSI8Ptr, RI.Variable->getType());
5290 Value *LHS = Builder.CreateLoad(RI.ElementType, LHSPtr);
5291 Value *RHSI8PtrPtr = Builder.CreateConstInBoundsGEP2_64(
5292 RedArrayTy, RHSArrayPtr, 0, En.index());
5293 Value *RHSI8Ptr = Builder.CreateLoad(Builder.getPtrTy(), RHSI8PtrPtr);
5294 Value *RHSPtr = Builder.CreatePointerBitCastOrAddrSpaceCast(
5295 RHSI8Ptr, RI.PrivateVariable->getType());
5296 Value *RHS = Builder.CreateLoad(RI.ElementType, RHSPtr);
5297 Value *Reduced;
5299 RI.ReductionGen(Builder.saveIP(), LHS, RHS, Reduced);
5300 if (!AfterIP)
5301 return AfterIP.takeError();
5302
5303 Builder.restoreIP(*AfterIP);
5304 // TODO: Consider flagging an error.
5305 if (!Builder.GetInsertBlock())
5306 return Error::success();
5307
5308 // store is inside of the reduction region when using by-ref
5309 if (!IsByRef[En.index()])
5310 Builder.CreateStore(Reduced, LHSPtr);
5311 }
5312 Builder.CreateRetVoid();
5313 return Error::success();
5314}
5315
5317 const LocationDescription &Loc, InsertPointTy AllocaIP,
5318 ArrayRef<ReductionInfo> ReductionInfos, ArrayRef<bool> IsByRef,
5319 bool IsNoWait, bool IsTeamsReduction) {
5320 assert(ReductionInfos.size() == IsByRef.size());
5321 if (Config.isGPU())
5322 return createReductionsGPU(Loc, AllocaIP, Builder.saveIP(), ReductionInfos,
5323 IsByRef, IsNoWait, IsTeamsReduction);
5324
5325 checkReductionInfos(ReductionInfos, /*IsGPU*/ false);
5326
5327 if (!updateToLocation(Loc))
5328 return InsertPointTy();
5329
5330 if (ReductionInfos.size() == 0)
5331 return Builder.saveIP();
5332
5333 BasicBlock *InsertBlock = Loc.IP.getNodeParent();
5334 BasicBlock *ContinuationBlock =
5335 InsertBlock->splitBasicBlock(Loc.IP, "reduce.finalize");
5336 InsertBlock->getTerminator()->eraseFromParent();
5337
5338 // Create and populate array of type-erased pointers to private reduction
5339 // values.
5340 unsigned NumReductions = ReductionInfos.size();
5341 Type *RedArrayTy = ArrayType::get(Builder.getPtrTy(), NumReductions);
5342 Builder.SetInsertPoint(AllocaIP.getNodeParent()->getTerminator());
5343 Value *RedArray = Builder.CreateAlloca(RedArrayTy, nullptr, "red.array");
5344
5345 Builder.SetInsertPoint(InsertBlock->end());
5346 // Emitting the alloca moved the insertion point into the alloca block and
5347 // can clear the debug loc. Restore back to Loc.DL.
5348 Builder.SetCurrentDebugLocation(Loc.DL);
5349
5350 for (auto En : enumerate(ReductionInfos)) {
5351 unsigned Index = En.index();
5352 const ReductionInfo &RI = En.value();
5353 Value *RedArrayElemPtr = Builder.CreateConstInBoundsGEP2_64(
5354 RedArrayTy, RedArray, 0, Index, "red.array.elem." + Twine(Index));
5355 Builder.CreateStore(RI.PrivateVariable, RedArrayElemPtr);
5356 }
5357
5358 // Emit a call to the runtime function that orchestrates the reduction.
5359 // Declare the reduction function in the process.
5360 Type *IndexTy = Builder.getIndexTy(
5361 M.getDataLayout(), M.getDataLayout().getDefaultGlobalsAddressSpace());
5362 Function *Func = Builder.GetInsertBlock()->getParent();
5363 Module *Module = Func->getParent();
5364 uint32_t SrcLocStrSize;
5365 Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
5366 bool CanGenerateAtomic = all_of(ReductionInfos, [](const ReductionInfo &RI) {
5367 return RI.AtomicReductionGen;
5368 });
5369 Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize,
5370 CanGenerateAtomic
5371 ? IdentFlag::OMP_IDENT_FLAG_ATOMIC_REDUCE
5372 : IdentFlag(0));
5373 Value *ThreadId = getOrCreateThreadID(Ident);
5374 Constant *NumVariables = Builder.getInt32(NumReductions);
5375 const DataLayout &DL = Module->getDataLayout();
5376 unsigned RedArrayByteSize = DL.getTypeStoreSize(RedArrayTy);
5377 Constant *RedArraySize = ConstantInt::get(IndexTy, RedArrayByteSize);
5378 Function *ReductionFunc = getFreshReductionFunc(*Module);
5379 Value *Lock = getOMPCriticalRegionLock(".reduction");
5381 IsNoWait ? RuntimeFunction::OMPRTL___kmpc_reduce_nowait
5382 : RuntimeFunction::OMPRTL___kmpc_reduce);
5383 CallInst *ReduceCall =
5384 createRuntimeFunctionCall(ReduceFunc,
5385 {Ident, ThreadId, NumVariables, RedArraySize,
5386 RedArray, ReductionFunc, Lock},
5387 "reduce");
5388
5389 // Create final reduction entry blocks for the atomic and non-atomic case.
5390 // Emit IR that dispatches control flow to one of the blocks based on the
5391 // reduction supporting the atomic mode.
5392 BasicBlock *NonAtomicRedBlock =
5393 BasicBlock::Create(Module->getContext(), "reduce.switch.nonatomic", Func);
5394 BasicBlock *AtomicRedBlock =
5395 BasicBlock::Create(Module->getContext(), "reduce.switch.atomic", Func);
5396 SwitchInst *Switch =
5397 Builder.CreateSwitch(ReduceCall, ContinuationBlock, /* NumCases */ 2);
5398 Switch->addCase(Builder.getInt32(1), NonAtomicRedBlock);
5399 Switch->addCase(Builder.getInt32(2), AtomicRedBlock);
5400
5401 // Populate the non-atomic reduction using the elementwise reduction function.
5402 // This loads the elements from the global and private variables and reduces
5403 // them before storing back the result to the global variable.
5404 Builder.SetInsertPoint(NonAtomicRedBlock);
5405 for (auto En : enumerate(ReductionInfos)) {
5406 const ReductionInfo &RI = En.value();
5408 // We have one less load for by-ref case because that load is now inside of
5409 // the reduction region
5410 Value *RedValue = RI.Variable;
5411 if (!IsByRef[En.index()]) {
5412 RedValue = Builder.CreateLoad(ValueType, RI.Variable,
5413 "red.value." + Twine(En.index()));
5414 }
5415 Value *PrivateRedValue =
5416 Builder.CreateLoad(ValueType, RI.PrivateVariable,
5417 "red.private.value." + Twine(En.index()));
5418 Value *Reduced;
5419 InsertPointOrErrorTy AfterIP =
5420 RI.ReductionGen(Builder.saveIP(), RedValue, PrivateRedValue, Reduced);
5421 if (!AfterIP)
5422 return AfterIP.takeError();
5423 Builder.restoreIP(*AfterIP);
5424
5425 if (!Builder.GetInsertBlock())
5426 return InsertPointTy();
5427 // for by-ref case, the load is inside of the reduction region
5428 if (!IsByRef[En.index()])
5429 Builder.CreateStore(Reduced, RI.Variable);
5430 }
5431 Function *EndReduceFunc = getOrCreateRuntimeFunctionPtr(
5432 IsNoWait ? RuntimeFunction::OMPRTL___kmpc_end_reduce_nowait
5433 : RuntimeFunction::OMPRTL___kmpc_end_reduce);
5434 createRuntimeFunctionCall(EndReduceFunc, {Ident, ThreadId, Lock});
5435 Builder.CreateBr(ContinuationBlock);
5436
5437 // Populate the atomic reduction using the atomic elementwise reduction
5438 // function. There are no loads/stores here because they will be happening
5439 // inside the atomic elementwise reduction.
5440 Builder.SetInsertPoint(AtomicRedBlock);
5441 if (CanGenerateAtomic && llvm::none_of(IsByRef, [](bool P) { return P; })) {
5442 for (const ReductionInfo &RI : ReductionInfos) {
5444 Builder.saveIP(), RI.ElementType, RI.Variable, RI.PrivateVariable);
5445 if (!AfterIP)
5446 return AfterIP.takeError();
5447 Builder.restoreIP(*AfterIP);
5448 if (!Builder.GetInsertBlock())
5449 return InsertPointTy();
5450 }
5451 Builder.CreateBr(ContinuationBlock);
5452 } else {
5453 Builder.CreateUnreachable();
5454 }
5455
5456 // Populate the outlined reduction function using the elementwise reduction
5457 // function. Partial values are extracted from the type-erased array of
5458 // pointers to private variables.
5459 Error Err = populateReductionFunction(ReductionFunc, ReductionInfos, Builder,
5460 IsByRef, /*isGPU=*/false);
5461 if (Err)
5462 return Err;
5463
5464 if (!Builder.GetInsertBlock())
5465 return InsertPointTy();
5466
5467 Builder.SetInsertPoint(ContinuationBlock);
5468 return Builder.saveIP();
5469}
5470
5473 BodyGenCallbackTy BodyGenCB,
5474 FinalizeCallbackTy FiniCB) {
5475 if (!updateToLocation(Loc))
5476 return Loc.IP;
5477
5478 Directive OMPD = Directive::OMPD_master;
5479 uint32_t SrcLocStrSize;
5480 Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
5481 Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
5482 Value *ThreadId = getOrCreateThreadID(Ident);
5483 Value *Args[] = {Ident, ThreadId};
5484
5485 Function *EntryRTLFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_master);
5486 Instruction *EntryCall = createRuntimeFunctionCall(EntryRTLFn, Args);
5487
5488 Function *ExitRTLFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_end_master);
5489 Instruction *ExitCall = createRuntimeFunctionCall(ExitRTLFn, Args);
5490
5491 return EmitOMPInlinedRegion(OMPD, EntryCall, ExitCall, BodyGenCB, FiniCB,
5492 /*Conditional*/ true, /*hasFinalize*/ true);
5493}
5494
5497 BodyGenCallbackTy BodyGenCB,
5498 FinalizeCallbackTy FiniCB, Value *Filter) {
5500 if (!updateToLocation(Loc))
5501 return Loc.IP;
5502
5503 Directive OMPD = Directive::OMPD_masked;
5504 uint32_t SrcLocStrSize;
5505 Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
5506 Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
5507 Value *ThreadId = getOrCreateThreadID(Ident);
5508 Value *Args[] = {Ident, ThreadId, Filter};
5509 Value *ArgsEnd[] = {Ident, ThreadId};
5510
5511 Function *EntryRTLFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_masked);
5512 Instruction *EntryCall = createRuntimeFunctionCall(EntryRTLFn, Args);
5513
5514 Function *ExitRTLFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_end_masked);
5515 Instruction *ExitCall = createRuntimeFunctionCall(ExitRTLFn, ArgsEnd);
5516
5517 return EmitOMPInlinedRegion(OMPD, EntryCall, ExitCall, BodyGenCB, FiniCB,
5518 /*Conditional*/ true, /*hasFinalize*/ true);
5519}
5520
5522 llvm::FunctionCallee Callee,
5524 const llvm::Twine &Name) {
5525 llvm::CallInst *Call = Builder.CreateCall(
5526 Callee, Args, SmallVector<llvm::OperandBundleDef, 1>(), Name);
5527 Call->setDoesNotThrow();
5528 return Call;
5529}
5530
5531// Expects input basic block is dominated by BeforeScanBB.
5532// Once Scan directive is encountered, the code after scan directive should be
5533// dominated by AfterScanBB. Scan directive splits the code sequence to
5534// scan and input phase. Based on whether inclusive or exclusive
5535// clause is used in the scan directive and whether input loop or scan loop
5536// is lowered, it adds jumps to input and scan phase. First Scan loop is the
5537// input loop and second is the scan loop. The code generated handles only
5538// inclusive scans now.
5540 const LocationDescription &Loc, InsertPointTy AllocaIP,
5541 ArrayRef<llvm::Value *> ScanVars, ArrayRef<llvm::Type *> ScanVarsType,
5542 bool IsInclusive, ScanInfo *ScanRedInfo) {
5543 if (ScanRedInfo->OMPFirstScanLoop) {
5544 llvm::Error Err = emitScanBasedDirectiveDeclsIR(AllocaIP, ScanVars,
5545 ScanVarsType, ScanRedInfo);
5546 if (Err)
5547 return Err;
5548 }
5549 if (!updateToLocation(Loc))
5550 return Loc.IP;
5551
5552 llvm::Value *IV = ScanRedInfo->IV;
5553
5554 if (ScanRedInfo->OMPFirstScanLoop) {
5555 // Emit buffer[i] = red; at the end of the input phase.
5556 for (size_t i = 0; i < ScanVars.size(); i++) {
5557 Value *BuffPtr = (*(ScanRedInfo->ScanBuffPtrs))[ScanVars[i]];
5558 Value *Buff = Builder.CreateLoad(Builder.getPtrTy(), BuffPtr);
5559 Type *DestTy = ScanVarsType[i];
5560 Value *Val = Builder.CreateInBoundsGEP(DestTy, Buff, IV, "arrayOffset");
5561 Value *Src = Builder.CreateLoad(DestTy, ScanVars[i]);
5562
5563 Builder.CreateStore(Src, Val);
5564 }
5565 }
5566 Builder.CreateBr(ScanRedInfo->OMPScanLoopExit);
5567 emitBlock(ScanRedInfo->OMPScanDispatch,
5568 Builder.GetInsertBlock()->getParent());
5569
5570 if (!ScanRedInfo->OMPFirstScanLoop) {
5571 IV = ScanRedInfo->IV;
5572 // Emit red = buffer[i]; at the entrance to the scan phase.
5573 // TODO: if exclusive scan, the red = buffer[i-1] needs to be updated.
5574 for (size_t i = 0; i < ScanVars.size(); i++) {
5575 Value *BuffPtr = (*(ScanRedInfo->ScanBuffPtrs))[ScanVars[i]];
5576 Value *Buff = Builder.CreateLoad(Builder.getPtrTy(), BuffPtr);
5577 Type *DestTy = ScanVarsType[i];
5578 Value *SrcPtr =
5579 Builder.CreateInBoundsGEP(DestTy, Buff, IV, "arrayOffset");
5580 Value *Src = Builder.CreateLoad(DestTy, SrcPtr);
5581 Builder.CreateStore(Src, ScanVars[i]);
5582 }
5583 }
5584
5585 // TODO: Update it to CreateBr and remove dead blocks
5586 llvm::Value *CmpI = Builder.getInt1(true);
5587 if (ScanRedInfo->OMPFirstScanLoop == IsInclusive) {
5588 Builder.CreateCondBr(CmpI, ScanRedInfo->OMPBeforeScanBlock,
5589 ScanRedInfo->OMPAfterScanBlock);
5590 } else {
5591 Builder.CreateCondBr(CmpI, ScanRedInfo->OMPAfterScanBlock,
5592 ScanRedInfo->OMPBeforeScanBlock);
5593 }
5594 emitBlock(ScanRedInfo->OMPAfterScanBlock,
5595 Builder.GetInsertBlock()->getParent());
5596 Builder.SetInsertPoint(ScanRedInfo->OMPAfterScanBlock);
5597 return Builder.saveIP();
5598}
5599
5600Error OpenMPIRBuilder::emitScanBasedDirectiveDeclsIR(
5601 InsertPointTy AllocaIP, ArrayRef<Value *> ScanVars,
5602 ArrayRef<Type *> ScanVarsType, ScanInfo *ScanRedInfo) {
5603
5604 Builder.restoreIP(AllocaIP);
5605 // Create the shared pointer at alloca IP.
5606 for (size_t i = 0; i < ScanVars.size(); i++) {
5607 llvm::Value *BuffPtr =
5608 Builder.CreateAlloca(Builder.getPtrTy(), nullptr, "vla");
5609 (*(ScanRedInfo->ScanBuffPtrs))[ScanVars[i]] = BuffPtr;
5610 }
5611
5612 // Allocate temporary buffer by master thread
5613 auto BodyGenCB = [&](InsertPointTy AllocaIP, InsertPointTy CodeGenIP,
5614 ArrayRef<BasicBlock *> DeallocBlocks) -> Error {
5615 Builder.restoreIP(CodeGenIP);
5616 Value *AllocSpan =
5617 Builder.CreateAdd(ScanRedInfo->Span, Builder.getInt32(1));
5618 for (size_t i = 0; i < ScanVars.size(); i++) {
5619 Type *IntPtrTy = Builder.getInt32Ty();
5620 Value *Allocsize = Builder.CreateTypeSize(
5621 IntPtrTy, M.getDataLayout().getTypeAllocSize(ScanVarsType[i]));
5622 Value *Buff =
5623 Builder.CreateMalloc(IntPtrTy, Allocsize, AllocSpan, nullptr, "arr");
5624 Builder.CreateStore(Buff, (*(ScanRedInfo->ScanBuffPtrs))[ScanVars[i]]);
5625 }
5626 return Error::success();
5627 };
5628 // TODO: Perform finalization actions for variables. This has to be
5629 // called for variables which have destructors/finalizers.
5630 auto FiniCB = [&](InsertPointTy CodeGenIP) { return llvm::Error::success(); };
5631
5632 Builder.SetInsertPoint(ScanRedInfo->OMPScanInit->getTerminator());
5633 llvm::Value *FilterVal = Builder.getInt32(0);
5635 createMasked(Builder, BodyGenCB, FiniCB, FilterVal);
5636
5637 if (!AfterIP)
5638 return AfterIP.takeError();
5639 Builder.restoreIP(*AfterIP);
5640 BasicBlock *InputBB = Builder.GetInsertBlock();
5641 if (InputBB->hasTerminator())
5642 Builder.SetInsertPoint(InputBB->getTerminator());
5643 AfterIP = createBarrier(Builder, llvm::omp::OMPD_barrier);
5644 if (!AfterIP)
5645 return AfterIP.takeError();
5646 Builder.restoreIP(*AfterIP);
5647
5648 return Error::success();
5649}
5650
5651Error OpenMPIRBuilder::emitScanBasedDirectiveFinalsIR(
5652 ArrayRef<ReductionInfo> ReductionInfos, ScanInfo *ScanRedInfo) {
5653 auto BodyGenCB = [&](InsertPointTy AllocaIP, InsertPointTy CodeGenIP,
5654 ArrayRef<BasicBlock *> DeallocBlocks) -> Error {
5655 Builder.restoreIP(CodeGenIP);
5656 for (ReductionInfo RedInfo : ReductionInfos) {
5657 Value *PrivateVar = RedInfo.PrivateVariable;
5658 Value *OrigVar = RedInfo.Variable;
5659 Value *BuffPtr = (*(ScanRedInfo->ScanBuffPtrs))[PrivateVar];
5660 Value *Buff = Builder.CreateLoad(Builder.getPtrTy(), BuffPtr);
5661
5662 Type *SrcTy = RedInfo.ElementType;
5663 Value *Val = Builder.CreateInBoundsGEP(SrcTy, Buff, ScanRedInfo->Span,
5664 "arrayOffset");
5665 Value *Src = Builder.CreateLoad(SrcTy, Val);
5666
5667 Builder.CreateStore(Src, OrigVar);
5668 Builder.CreateFree(Buff);
5669 }
5670 return Error::success();
5671 };
5672 // TODO: Perform finalization actions for variables. This has to be
5673 // called for variables which have destructors/finalizers.
5674 auto FiniCB = [&](InsertPointTy CodeGenIP) { return llvm::Error::success(); };
5675
5676 if (Instruction *TI = ScanRedInfo->OMPScanFinish->getTerminatorOrNull())
5677 Builder.SetInsertPoint(TI);
5678 else
5679 Builder.SetInsertPoint(ScanRedInfo->OMPScanFinish);
5680
5681 llvm::Value *FilterVal = Builder.getInt32(0);
5683 createMasked(Builder, BodyGenCB, FiniCB, FilterVal);
5684
5685 if (!AfterIP)
5686 return AfterIP.takeError();
5687 Builder.restoreIP(*AfterIP);
5688 BasicBlock *InputBB = Builder.GetInsertBlock();
5689 if (InputBB->hasTerminator())
5690 Builder.SetInsertPoint(InputBB->getTerminator());
5691 AfterIP = createBarrier(Builder, llvm::omp::OMPD_barrier);
5692 if (!AfterIP)
5693 return AfterIP.takeError();
5694 Builder.restoreIP(*AfterIP);
5695 return Error::success();
5696}
5697
5699 const LocationDescription &Loc,
5701 ScanInfo *ScanRedInfo) {
5702
5703 if (!updateToLocation(Loc))
5704 return Loc.IP;
5705 auto BodyGenCB = [&](InsertPointTy AllocaIP, InsertPointTy CodeGenIP,
5706 ArrayRef<BasicBlock *> DeallocBlocks) -> Error {
5707 Builder.restoreIP(CodeGenIP);
5708 Function *CurFn = Builder.GetInsertBlock()->getParent();
5709 // for (int k = 0; k <= ceil(log2(n)); ++k)
5710 llvm::BasicBlock *LoopBB =
5711 BasicBlock::Create(CurFn->getContext(), "omp.outer.log.scan.body");
5712 llvm::BasicBlock *ExitBB =
5713 splitBB(Builder, false, "omp.outer.log.scan.exit");
5715 Builder.getModule(), (llvm::Intrinsic::ID)llvm::Intrinsic::log2,
5716 Builder.getDoubleTy());
5717 llvm::BasicBlock *InputBB = Builder.GetInsertBlock();
5718 llvm::Value *Arg =
5719 Builder.CreateUIToFP(ScanRedInfo->Span, Builder.getDoubleTy());
5720 llvm::Value *LogVal = emitNoUnwindRuntimeCall(Builder, F, Arg, "");
5722 Builder.getModule(), (llvm::Intrinsic::ID)llvm::Intrinsic::ceil,
5723 Builder.getDoubleTy());
5724 LogVal = emitNoUnwindRuntimeCall(Builder, F, LogVal, "");
5725 LogVal = Builder.CreateFPToUI(LogVal, Builder.getInt32Ty());
5726 llvm::Value *NMin1 = Builder.CreateNUWSub(
5727 ScanRedInfo->Span,
5728 llvm::ConstantInt::get(ScanRedInfo->Span->getType(), 1));
5729 Builder.SetInsertPoint(InputBB);
5730 Builder.CreateBr(LoopBB);
5731 emitBlock(LoopBB, CurFn);
5732 Builder.SetInsertPoint(LoopBB);
5733
5734 PHINode *Counter = Builder.CreatePHI(Builder.getInt32Ty(), 2);
5735 // size pow2k = 1;
5736 PHINode *Pow2K = Builder.CreatePHI(Builder.getInt32Ty(), 2);
5737 Counter->addIncoming(llvm::ConstantInt::get(Builder.getInt32Ty(), 0),
5738 InputBB);
5739 Pow2K->addIncoming(llvm::ConstantInt::get(Builder.getInt32Ty(), 1),
5740 InputBB);
5741 // for (size i = n - 1; i >= 2 ^ k; --i)
5742 // tmp[i] op= tmp[i-pow2k];
5743 llvm::BasicBlock *InnerLoopBB =
5744 BasicBlock::Create(CurFn->getContext(), "omp.inner.log.scan.body");
5745 llvm::BasicBlock *InnerExitBB =
5746 BasicBlock::Create(CurFn->getContext(), "omp.inner.log.scan.exit");
5747 llvm::Value *CmpI = Builder.CreateICmpUGE(NMin1, Pow2K);
5748 Builder.CreateCondBr(CmpI, InnerLoopBB, InnerExitBB);
5749 emitBlock(InnerLoopBB, CurFn);
5750 Builder.SetInsertPoint(InnerLoopBB);
5751 PHINode *IVal = Builder.CreatePHI(Builder.getInt32Ty(), 2);
5752 IVal->addIncoming(NMin1, LoopBB);
5753 for (ReductionInfo RedInfo : ReductionInfos) {
5754 Value *ReductionVal = RedInfo.PrivateVariable;
5755 Value *BuffPtr = (*(ScanRedInfo->ScanBuffPtrs))[ReductionVal];
5756 Value *Buff = Builder.CreateLoad(Builder.getPtrTy(), BuffPtr);
5757 Type *DestTy = RedInfo.ElementType;
5758 Value *IV = Builder.CreateAdd(IVal, Builder.getInt32(1));
5759 Value *LHSPtr =
5760 Builder.CreateInBoundsGEP(DestTy, Buff, IV, "arrayOffset");
5761 Value *OffsetIval = Builder.CreateNUWSub(IV, Pow2K);
5762 Value *RHSPtr =
5763 Builder.CreateInBoundsGEP(DestTy, Buff, OffsetIval, "arrayOffset");
5764 Value *LHS = Builder.CreateLoad(DestTy, LHSPtr);
5765 Value *RHS = Builder.CreateLoad(DestTy, RHSPtr);
5766 llvm::Value *Result;
5767 InsertPointOrErrorTy AfterIP =
5768 RedInfo.ReductionGen(Builder.saveIP(), LHS, RHS, Result);
5769 if (!AfterIP)
5770 return AfterIP.takeError();
5771 Builder.CreateStore(Result, LHSPtr);
5772 }
5773 llvm::Value *NextIVal = Builder.CreateNUWSub(
5774 IVal, llvm::ConstantInt::get(Builder.getInt32Ty(), 1));
5775 IVal->addIncoming(NextIVal, Builder.GetInsertBlock());
5776 CmpI = Builder.CreateICmpUGE(NextIVal, Pow2K);
5777 Builder.CreateCondBr(CmpI, InnerLoopBB, InnerExitBB);
5778 emitBlock(InnerExitBB, CurFn);
5779 llvm::Value *Next = Builder.CreateNUWAdd(
5780 Counter, llvm::ConstantInt::get(Counter->getType(), 1));
5781 Counter->addIncoming(Next, Builder.GetInsertBlock());
5782 // pow2k <<= 1;
5783 llvm::Value *NextPow2K = Builder.CreateShl(Pow2K, 1, "", /*HasNUW=*/true);
5784 Pow2K->addIncoming(NextPow2K, Builder.GetInsertBlock());
5785 llvm::Value *Cmp = Builder.CreateICmpNE(Next, LogVal);
5786 Builder.CreateCondBr(Cmp, LoopBB, ExitBB);
5787 Builder.SetInsertPoint(ExitBB->getFirstInsertionPt());
5788 return Error::success();
5789 };
5790
5791 // TODO: Perform finalization actions for variables. This has to be
5792 // called for variables which have destructors/finalizers.
5793 auto FiniCB = [&](InsertPointTy CodeGenIP) { return llvm::Error::success(); };
5794
5795 llvm::Value *FilterVal = Builder.getInt32(0);
5797 createMasked(Builder, BodyGenCB, FiniCB, FilterVal);
5798
5799 if (!AfterIP)
5800 return AfterIP.takeError();
5801 Builder.restoreIP(*AfterIP);
5802 AfterIP = createBarrier(Builder, llvm::omp::OMPD_barrier);
5803
5804 if (!AfterIP)
5805 return AfterIP.takeError();
5806 Builder.restoreIP(*AfterIP);
5807 Error Err = emitScanBasedDirectiveFinalsIR(ReductionInfos, ScanRedInfo);
5808 if (Err)
5809 return Err;
5810
5811 return AfterIP;
5812}
5813
5814Error OpenMPIRBuilder::emitScanBasedDirectiveIR(
5815 llvm::function_ref<Error()> InputLoopGen,
5816 llvm::function_ref<Error(LocationDescription Loc)> ScanLoopGen,
5817 ScanInfo *ScanRedInfo) {
5818
5819 {
5820 // Emit loop with input phase:
5821 // for (i: 0..<num_iters>) {
5822 // <input phase>;
5823 // buffer[i] = red;
5824 // }
5825 ScanRedInfo->OMPFirstScanLoop = true;
5826 Error Err = InputLoopGen();
5827 if (Err)
5828 return Err;
5829 }
5830 {
5831 // Emit loop with scan phase:
5832 // for (i: 0..<num_iters>) {
5833 // red = buffer[i];
5834 // <scan phase>;
5835 // }
5836 ScanRedInfo->OMPFirstScanLoop = false;
5837 Error Err = ScanLoopGen(Builder);
5838 if (Err)
5839 return Err;
5840 }
5841 return Error::success();
5842}
5843
5844void OpenMPIRBuilder::createScanBBs(ScanInfo *ScanRedInfo) {
5845 Function *Fun = Builder.GetInsertBlock()->getParent();
5846 ScanRedInfo->OMPScanDispatch =
5847 BasicBlock::Create(Fun->getContext(), "omp.inscan.dispatch");
5848 ScanRedInfo->OMPAfterScanBlock =
5849 BasicBlock::Create(Fun->getContext(), "omp.after.scan.bb");
5850 ScanRedInfo->OMPBeforeScanBlock =
5851 BasicBlock::Create(Fun->getContext(), "omp.before.scan.bb");
5852 ScanRedInfo->OMPScanLoopExit =
5853 BasicBlock::Create(Fun->getContext(), "omp.scan.loop.exit");
5854}
5856 DebugLoc DL, Value *TripCount, Function *F, BasicBlock *PreInsertBefore,
5857 BasicBlock *PostInsertBefore, const Twine &Name, bool IsCollapsed) {
5858 Module *M = F->getParent();
5859 LLVMContext &Ctx = M->getContext();
5860 Type *IndVarTy = TripCount->getType();
5861
5862 // Create the basic block structure.
5863 BasicBlock *Preheader =
5864 BasicBlock::Create(Ctx, "omp_" + Name + ".preheader", F, PreInsertBefore);
5865 BasicBlock *Header =
5866 BasicBlock::Create(Ctx, "omp_" + Name + ".header", F, PreInsertBefore);
5867 BasicBlock *Cond =
5868 BasicBlock::Create(Ctx, "omp_" + Name + ".cond", F, PreInsertBefore);
5869 BasicBlock *Body =
5870 BasicBlock::Create(Ctx, "omp_" + Name + ".body", F, PreInsertBefore);
5871 BasicBlock *Latch =
5872 BasicBlock::Create(Ctx, "omp_" + Name + ".inc", F, PostInsertBefore);
5873 BasicBlock *Exit =
5874 BasicBlock::Create(Ctx, "omp_" + Name + ".exit", F, PostInsertBefore);
5875 BasicBlock *After =
5876 BasicBlock::Create(Ctx, "omp_" + Name + ".after", F, PostInsertBefore);
5877
5878 // Use specified DebugLoc for new instructions.
5879 Builder.SetCurrentDebugLocation(DL);
5880
5881 Builder.SetInsertPoint(Preheader);
5882 Builder.CreateBr(Header);
5883
5884 Builder.SetInsertPoint(Header);
5885 PHINode *IndVarPHI = Builder.CreatePHI(IndVarTy, 2, "omp_" + Name + ".iv");
5886 IndVarPHI->addIncoming(ConstantInt::get(IndVarTy, 0), Preheader);
5887 Builder.CreateBr(Cond);
5888
5889 Builder.SetInsertPoint(Cond);
5890 Value *Cmp =
5891 Builder.CreateICmpULT(IndVarPHI, TripCount, "omp_" + Name + ".cmp");
5892 Builder.CreateCondBr(Cmp, Body, Exit);
5893
5894 Builder.SetInsertPoint(Body);
5895 Builder.CreateBr(Latch);
5896
5897 Builder.SetInsertPoint(Latch);
5898 // Decide whether the induction variable increment can carry nsw.
5899 //
5900 // Single loops: nsw is always kept (matching Clang). Any Fortran program
5901 // whose trip count overflows i32 is non-conforming per F2018 11.1.7.4.1, so
5902 // for valid programs 0 <= count <= INT_MAX always holds.
5903 //
5904 // Collapsed loops: the trip count is a product that can overflow i32 even for
5905 // a conforming program, so nsw is kept only when the product is a constant
5906 // that provably fits, dropped otherwise.
5907 bool HasNSW = Config.hasNoSignedWrap();
5908 if (HasNSW) {
5909 if (auto *CI = dyn_cast<ConstantInt>(TripCount)) {
5910 unsigned BitWidth = CI->getType()->getIntegerBitWidth();
5912 if (CI->getValue().ugt(SignedMax))
5913 HasNSW = false;
5914 } else if (IsCollapsed) {
5915 HasNSW = false;
5916 }
5917 }
5918 Value *Next =
5919 Builder.CreateAdd(IndVarPHI, ConstantInt::get(IndVarTy, 1),
5920 "omp_" + Name + ".next", /*HasNUW=*/true, HasNSW);
5921 Builder.CreateBr(Header);
5922 IndVarPHI->addIncoming(Next, Latch);
5923
5924 Builder.SetInsertPoint(Exit);
5925 Builder.CreateBr(After);
5926
5927 // Remember and return the canonical control flow.
5928 LoopInfos.emplace_front();
5929 CanonicalLoopInfo *CL = &LoopInfos.front();
5930
5931 CL->Header = Header;
5932 CL->Cond = Cond;
5933 CL->Latch = Latch;
5934 CL->Exit = Exit;
5935
5936#ifndef NDEBUG
5937 CL->assertOK();
5938#endif
5939 return CL;
5940}
5941
5944 LoopBodyGenCallbackTy BodyGenCB,
5945 Value *TripCount, const Twine &Name) {
5946 BasicBlock *BB = Loc.IP.getNodeParent();
5947 BasicBlock *NextBB = BB->getNextNode();
5948
5949 CanonicalLoopInfo *CL = createLoopSkeleton(Loc.DL, TripCount, BB->getParent(),
5950 NextBB, NextBB, Name);
5951 BasicBlock *After = CL->getAfter();
5952
5953 // If location is not set, don't connect the loop.
5954 if (updateToLocation(Loc)) {
5955 // Split the loop at the insertion point: Branch to the preheader and move
5956 // every following instruction to after the loop (the After BB). Also, the
5957 // new successor is the loop's after block.
5958 spliceBB(Builder, After, /*CreateBranch=*/false);
5959 Builder.CreateBr(CL->getPreheader());
5960 }
5961
5962 // Emit the body content. We do it after connecting the loop to the CFG to
5963 // avoid that the callback encounters degenerate BBs.
5964 if (Error Err = BodyGenCB(CL->getBodyIP(), CL->getIndVar()))
5965 return Err;
5966
5967#ifndef NDEBUG
5968 CL->assertOK();
5969#endif
5970 return CL;
5971}
5972
5974 ScanInfos.emplace_front();
5975 ScanInfo *Result = &ScanInfos.front();
5976 return Result;
5977}
5978
5982 Value *Start, Value *Stop, Value *Step, bool IsSigned, bool InclusiveStop,
5983 InsertPointTy ComputeIP, const Twine &Name, ScanInfo *ScanRedInfo) {
5984 LocationDescription ComputeLoc =
5985 ComputeIP.isValid() ? LocationDescription(ComputeIP, Loc.DL) : Loc;
5986 updateToLocation(ComputeLoc);
5987
5989
5991 ComputeLoc, Start, Stop, Step, IsSigned, InclusiveStop, Name);
5992 ScanRedInfo->Span = TripCount;
5993 ScanRedInfo->OMPScanInit = splitBB(Builder, true, "scan.init");
5994 Builder.SetInsertPoint(ScanRedInfo->OMPScanInit);
5995
5996 auto BodyGen = [=](InsertPointTy CodeGenIP, Value *IV) {
5997 Builder.restoreIP(CodeGenIP);
5998 ScanRedInfo->IV = IV;
5999 createScanBBs(ScanRedInfo);
6000 BasicBlock *InputBlock = Builder.GetInsertBlock();
6001 Instruction *Terminator = InputBlock->getTerminator();
6002 assert(Terminator->getNumSuccessors() == 1);
6003 BasicBlock *ContinueBlock = Terminator->getSuccessor(0);
6004 Terminator->setSuccessor(0, ScanRedInfo->OMPScanDispatch);
6005 emitBlock(ScanRedInfo->OMPBeforeScanBlock,
6006 Builder.GetInsertBlock()->getParent());
6007 Builder.CreateBr(ScanRedInfo->OMPScanLoopExit);
6008 emitBlock(ScanRedInfo->OMPScanLoopExit,
6009 Builder.GetInsertBlock()->getParent());
6010 Builder.CreateBr(ContinueBlock);
6011 Builder.SetInsertPoint(
6012 ScanRedInfo->OMPBeforeScanBlock->getFirstInsertionPt());
6013 return BodyGenCB(Builder.saveIP(), IV);
6014 };
6015
6016 const auto &&InputLoopGen = [&]() -> Error {
6018 createCanonicalLoop(Builder, BodyGen, Start, Stop, Step, IsSigned,
6019 InclusiveStop, ComputeIP, Name, true, ScanRedInfo);
6020 if (!LoopInfo)
6021 return LoopInfo.takeError();
6022 Result.push_back(*LoopInfo);
6023 Builder.restoreIP((*LoopInfo)->getAfterIP());
6024 return Error::success();
6025 };
6026 const auto &&ScanLoopGen = [&](LocationDescription Loc) -> Error {
6028 createCanonicalLoop(Loc, BodyGen, Start, Stop, Step, IsSigned,
6029 InclusiveStop, ComputeIP, Name, true, ScanRedInfo);
6030 if (!LoopInfo)
6031 return LoopInfo.takeError();
6032 Result.push_back(*LoopInfo);
6033 Builder.restoreIP((*LoopInfo)->getAfterIP());
6034 ScanRedInfo->OMPScanFinish = Builder.GetInsertBlock();
6035 return Error::success();
6036 };
6037 Error Err = emitScanBasedDirectiveIR(InputLoopGen, ScanLoopGen, ScanRedInfo);
6038 if (Err)
6039 return Err;
6040 return Result;
6041}
6042
6044 const LocationDescription &Loc, Value *Start, Value *Stop, Value *Step,
6045 bool IsSigned, bool InclusiveStop, const Twine &Name) {
6046
6047 // Consider the following difficulties (assuming 8-bit signed integers):
6048 // * Adding \p Step to the loop counter which passes \p Stop may overflow:
6049 // DO I = 1, 100, 50
6050 /// * A \p Step of INT_MIN cannot not be normalized to a positive direction:
6051 // DO I = 100, 0, -128
6052
6053 // Start, Stop and Step must be of the same integer type.
6054 auto *IndVarTy = cast<IntegerType>(Start->getType());
6055 assert(IndVarTy == Stop->getType() && "Stop type mismatch");
6056 assert(IndVarTy == Step->getType() && "Step type mismatch");
6057
6059
6060 ConstantInt *Zero = ConstantInt::get(IndVarTy, 0);
6061 ConstantInt *One = ConstantInt::get(IndVarTy, 1);
6062
6063 // Like Step, but always positive.
6064 Value *Incr = Step;
6065
6066 // Distance between Start and Stop; always positive.
6067 Value *Span;
6068
6069 // Condition whether there are no iterations are executed at all, e.g. because
6070 // UB < LB.
6071 Value *ZeroCmp;
6072
6073 if (IsSigned) {
6074 // Ensure that increment is positive. If not, negate and invert LB and UB.
6075 Value *IsNeg = Builder.CreateICmpSLT(Step, Zero);
6076 Incr = Builder.CreateSelect(IsNeg, Builder.CreateNeg(Step), Step);
6077 Value *LB = Builder.CreateSelect(IsNeg, Stop, Start);
6078 Value *UB = Builder.CreateSelect(IsNeg, Start, Stop);
6079 Span = Builder.CreateSub(UB, LB, "", false, true);
6080 ZeroCmp = Builder.CreateICmp(
6081 InclusiveStop ? CmpInst::ICMP_SLT : CmpInst::ICMP_SLE, UB, LB);
6082 } else {
6083 Span = Builder.CreateSub(Stop, Start, "", true);
6084 ZeroCmp = Builder.CreateICmp(
6085 InclusiveStop ? CmpInst::ICMP_ULT : CmpInst::ICMP_ULE, Stop, Start);
6086 }
6087
6088 Value *CountIfLooping;
6089 if (InclusiveStop) {
6090 CountIfLooping = Builder.CreateAdd(Builder.CreateUDiv(Span, Incr), One);
6091 } else {
6092 // Avoid incrementing past stop since it could overflow.
6093 Value *CountIfTwo = Builder.CreateAdd(
6094 Builder.CreateUDiv(Builder.CreateSub(Span, One), Incr), One);
6095 Value *OneCmp = Builder.CreateICmp(CmpInst::ICMP_ULE, Span, Incr);
6096 CountIfLooping = Builder.CreateSelect(OneCmp, One, CountIfTwo);
6097 }
6098
6099 return Builder.CreateSelect(ZeroCmp, Zero, CountIfLooping,
6100 "omp_" + Name + ".tripcount");
6101}
6102
6105 Value *Start, Value *Stop, Value *Step, bool IsSigned, bool InclusiveStop,
6106 InsertPointTy ComputeIP, const Twine &Name, bool InScan,
6107 ScanInfo *ScanRedInfo) {
6108 LocationDescription ComputeLoc =
6109 ComputeIP.isValid() ? LocationDescription(ComputeIP, Loc.DL) : Loc;
6110
6112 ComputeLoc, Start, Stop, Step, IsSigned, InclusiveStop, Name);
6113
6114 auto BodyGen = [=](InsertPointTy CodeGenIP, Value *IV) {
6115 Builder.restoreIP(CodeGenIP);
6116 Value *Span = Builder.CreateMul(IV, Step, "", /*HasNUW=*/false,
6117 /*HasNSW=*/Config.hasNoSignedWrap());
6118 Value *IndVar = Builder.CreateAdd(Span, Start, "", /*HasNUW=*/false,
6119 /*HasNSW=*/Config.hasNoSignedWrap());
6120 if (InScan)
6121 ScanRedInfo->IV = IndVar;
6122 return BodyGenCB(Builder.saveIP(), IndVar);
6123 };
6124 LocationDescription LoopLoc =
6125 ComputeIP.isValid()
6126 ? Loc
6127 : LocationDescription(Builder.saveIP(),
6128 Builder.getCurrentDebugLocation());
6129 return createCanonicalLoop(LoopLoc, BodyGen, TripCount, Name);
6130}
6131
6132// Returns an LLVM function to call for initializing loop bounds using OpenMP
6133// static scheduling for composite `distribute parallel for` depending on
6134// `type`. Only i32 and i64 are supported by the runtime. Always interpret
6135// integers as unsigned similarly to CanonicalLoopInfo.
6136static FunctionCallee
6138 OpenMPIRBuilder &OMPBuilder) {
6139 unsigned Bitwidth = Ty->getIntegerBitWidth();
6140 if (Bitwidth == 32)
6141 return OMPBuilder.getOrCreateRuntimeFunction(
6142 M, omp::RuntimeFunction::OMPRTL___kmpc_dist_for_static_init_4u);
6143 if (Bitwidth == 64)
6144 return OMPBuilder.getOrCreateRuntimeFunction(
6145 M, omp::RuntimeFunction::OMPRTL___kmpc_dist_for_static_init_8u);
6146 llvm_unreachable("unknown OpenMP loop iterator bitwidth");
6147}
6148
6149// Returns an LLVM function to call for initializing loop bounds using OpenMP
6150// static scheduling depending on `type`. Only i32 and i64 are supported by the
6151// runtime. Always interpret integers as unsigned similarly to
6152// CanonicalLoopInfo.
6154 OpenMPIRBuilder &OMPBuilder) {
6155 unsigned Bitwidth = Ty->getIntegerBitWidth();
6156 if (Bitwidth == 32)
6157 return OMPBuilder.getOrCreateRuntimeFunction(
6158 M, omp::RuntimeFunction::OMPRTL___kmpc_for_static_init_4u);
6159 if (Bitwidth == 64)
6160 return OMPBuilder.getOrCreateRuntimeFunction(
6161 M, omp::RuntimeFunction::OMPRTL___kmpc_for_static_init_8u);
6162 llvm_unreachable("unknown OpenMP loop iterator bitwidth");
6163}
6164
6165OpenMPIRBuilder::InsertPointOrErrorTy OpenMPIRBuilder::applyStaticWorkshareLoop(
6166 DebugLoc DL, CanonicalLoopInfo *CLI, InsertPointTy AllocaIP,
6167 WorksharingLoopType LoopType, bool NeedsBarrier, bool HasDistSchedule,
6168 OMPScheduleType DistScheduleSchedType) {
6169 assert(CLI->isValid() && "Requires a valid canonical loop");
6170 assert(!isConflictIP(AllocaIP, CLI->getPreheaderIP()) &&
6171 "Require dedicated allocate IP");
6172
6173 // Set up the source location value for OpenMP runtime.
6174 Builder.restoreIP(CLI->getPreheaderIP());
6175 Builder.SetCurrentDebugLocation(DL);
6176
6177 uint32_t SrcLocStrSize;
6178 Constant *SrcLocStr = getOrCreateSrcLocStr(DL, SrcLocStrSize);
6180 switch (LoopType) {
6181 case WorksharingLoopType::ForStaticLoop:
6182 Flag = OMP_IDENT_FLAG_WORK_LOOP;
6183 break;
6184 case WorksharingLoopType::DistributeStaticLoop:
6185 Flag = OMP_IDENT_FLAG_WORK_DISTRIBUTE;
6186 break;
6187 case WorksharingLoopType::DistributeForStaticLoop:
6188 Flag = OMP_IDENT_FLAG_WORK_DISTRIBUTE | OMP_IDENT_FLAG_WORK_LOOP;
6189 break;
6190 }
6191 Value *SrcLoc = getOrCreateIdent(SrcLocStr, SrcLocStrSize, Flag);
6192
6193 // Declare useful OpenMP runtime functions.
6194 Type *IVTy = CLI->getIndVarType();
6195 FunctionCallee StaticInit =
6196 LoopType == WorksharingLoopType::DistributeForStaticLoop
6197 ? getKmpcDistForStaticInitForType(IVTy, M, *this)
6198 : getKmpcForStaticInitForType(IVTy, M, *this);
6199 FunctionCallee StaticFini =
6200 getOrCreateRuntimeFunction(M, omp::OMPRTL___kmpc_for_static_fini);
6201
6202 // Allocate space for computed loop bounds as expected by the "init" function.
6203 Builder.SetInsertPoint(AllocaIP.getNodeParent()->getFirstNonPHIOrAlloca());
6204
6205 Type *I32Type = Type::getInt32Ty(M.getContext());
6206 Value *PLastIter = Builder.CreateAlloca(I32Type, nullptr, "p.lastiter");
6207 Value *PLowerBound = Builder.CreateAlloca(IVTy, nullptr, "p.lowerbound");
6208 Value *PUpperBound = Builder.CreateAlloca(IVTy, nullptr, "p.upperbound");
6209 Value *PStride = Builder.CreateAlloca(IVTy, nullptr, "p.stride");
6210 CLI->setLastIter(PLastIter);
6211
6212 // At the end of the preheader, prepare for calling the "init" function by
6213 // storing the current loop bounds into the allocated space. A canonical loop
6214 // always iterates from 0 to trip-count with step 1. Note that "init" expects
6215 // and produces an inclusive upper bound.
6216 Builder.SetInsertPoint(CLI->getPreheader()->getTerminator());
6217 Constant *Zero = ConstantInt::get(IVTy, 0);
6218 Constant *One = ConstantInt::get(IVTy, 1);
6219 Builder.CreateStore(Zero, PLowerBound);
6220 Value *UpperBound = Builder.CreateSub(CLI->getTripCount(), One);
6221 Builder.CreateStore(UpperBound, PUpperBound);
6222 Builder.CreateStore(One, PStride);
6223
6224 Value *ThreadNum =
6225 getOrCreateThreadID(getOrCreateIdent(SrcLocStr, SrcLocStrSize));
6226
6227 OMPScheduleType SchedType =
6228 (LoopType == WorksharingLoopType::DistributeStaticLoop)
6229 ? OMPScheduleType::OrderedDistribute
6231 Constant *SchedulingType =
6232 ConstantInt::get(I32Type, static_cast<int>(SchedType));
6233
6234 // Call the "init" function and update the trip count of the loop with the
6235 // value it produced.
6236 auto BuildInitCall = [LoopType, SrcLoc, ThreadNum, PLastIter, PLowerBound,
6237 PUpperBound, IVTy, PStride, One, Zero, StaticInit,
6238 this](Value *SchedulingType, auto &Builder) {
6239 SmallVector<Value *, 10> Args({SrcLoc, ThreadNum, SchedulingType, PLastIter,
6240 PLowerBound, PUpperBound});
6241 if (LoopType == WorksharingLoopType::DistributeForStaticLoop) {
6242 Value *PDistUpperBound =
6243 Builder.CreateAlloca(IVTy, nullptr, "p.distupperbound");
6244 Args.push_back(PDistUpperBound);
6245 }
6246 Args.append({PStride, One, Zero});
6247 createRuntimeFunctionCall(StaticInit, Args);
6248 };
6249 BuildInitCall(SchedulingType, Builder);
6250 if (HasDistSchedule &&
6251 LoopType != WorksharingLoopType::DistributeStaticLoop) {
6252 Constant *DistScheduleSchedType = ConstantInt::get(
6253 I32Type, static_cast<int>(omp::OMPScheduleType::OrderedDistribute));
6254 // We want to emit a second init function call for the dist_schedule clause
6255 // to the Distribute construct. This should only be done however if a
6256 // Workshare Loop is nested within a Distribute Construct
6257 BuildInitCall(DistScheduleSchedType, Builder);
6258 }
6259 Value *LowerBound = Builder.CreateLoad(IVTy, PLowerBound);
6260 Value *InclusiveUpperBound = Builder.CreateLoad(IVTy, PUpperBound);
6261 Value *TripCountMinusOne = Builder.CreateSub(InclusiveUpperBound, LowerBound);
6262 Value *TripCount = Builder.CreateAdd(TripCountMinusOne, One);
6263 if (CLI->VirtualCollapse) {
6264 bindCollapsedRange(CLI, LowerBound, TripCount);
6265#ifndef NDEBUG
6266 CLI->assertOK();
6267#endif
6268 } else {
6269 CLI->setTripCount(TripCount);
6270 }
6271
6272 // Update all uses of the induction variable except the one in the condition
6273 // block that compares it with the actual upper bound, and the increment in
6274 // the latch block.
6275
6276 if (!CLI->VirtualCollapse)
6277 CLI->mapIndVar([&](Instruction *OldIV) -> Value * {
6278 Builder.SetInsertPoint(CLI->getBody()->getFirstInsertionPt());
6279 Builder.SetCurrentDebugLocation(DL);
6280 return Builder.CreateAdd(OldIV, LowerBound, "", /*HasNUW=*/false,
6281 /*HasNSW=*/Config.hasNoSignedWrap());
6282 });
6283
6284 // In the "exit" block, call the "fini" function.
6285 Builder.SetInsertPoint(CLI->getExit()->getTerminator()->getIterator());
6286 createRuntimeFunctionCall(StaticFini, {SrcLoc, ThreadNum});
6287
6288 // Add the barrier if requested.
6289 if (NeedsBarrier) {
6290 InsertPointOrErrorTy BarrierIP =
6292 omp::Directive::OMPD_for, /* ForceSimpleCall */ false,
6293 /* CheckCancelFlag */ false);
6294 if (!BarrierIP)
6295 return BarrierIP.takeError();
6296 }
6297
6298 InsertPointTy AfterIP = CLI->getAfterIP();
6299 // TODO: Removing Virtual's outer bound requires another way to reject idle
6300 // assignments whose raw count wraps. Keep it for correctness and trip-count
6301 // information for analyses. The expected saving is small; investigate the
6302 // effects on downstream optimizations before removing it.
6303 CLI->invalidate();
6304
6305 return AfterIP;
6306}
6307
6308static void addAccessGroupMetadata(BasicBlock *Block, MDNode *AccessGroup,
6309 LoopInfo &LI);
6310static void addLoopMetadata(CanonicalLoopInfo *Loop,
6312
6314 LLVMContext &Ctx, Loop *Loop,
6316 SmallVector<Metadata *> &LoopMDList) {
6317 SmallSet<BasicBlock *, 8> Reachable;
6318
6319 // Get the basic blocks from the loop in which memref instructions
6320 // can be found.
6321 // TODO: Generalize getting all blocks inside a CanonicalizeLoopInfo,
6322 // preferably without running any passes.
6323 for (BasicBlock *Block : Loop->getBlocks()) {
6324 if (Block == CLI->getCond() || Block == CLI->getHeader())
6325 continue;
6326 Reachable.insert(Block);
6327 }
6328
6329 // Add access group metadata to memory-access instructions.
6331 for (BasicBlock *BB : Reachable)
6333 // TODO: If the loop has existing parallel access metadata, have
6334 // to combine two lists.
6335 LoopMDList.push_back(MDNode::get(
6336 Ctx, {MDString::get(Ctx, "llvm.loop.parallel_accesses"), AccessGroup}));
6337}
6338
6340OpenMPIRBuilder::applyStaticChunkedWorkshareLoop(
6341 DebugLoc DL, CanonicalLoopInfo *CLI, InsertPointTy AllocaIP,
6342 bool NeedsBarrier, Value *ChunkSize, OMPScheduleType SchedType,
6343 Value *DistScheduleChunkSize, OMPScheduleType DistScheduleSchedType) {
6344 assert(CLI->isValid() && "Requires a valid canonical loop");
6345 assert((ChunkSize || DistScheduleChunkSize) && "Chunk size is required");
6346
6347 LLVMContext &Ctx = CLI->getFunction()->getContext();
6348 Value *IV = CLI->getIndVar();
6349 Value *OrigTripCount = CLI->getTripCount();
6350 Type *IVTy = IV->getType();
6351 assert(IVTy->getIntegerBitWidth() <= 64 &&
6352 "Max supported tripcount bitwidth is 64 bits");
6353 Type *InternalIVTy = IVTy->getIntegerBitWidth() <= 32 ? Type::getInt32Ty(Ctx)
6354 : Type::getInt64Ty(Ctx);
6355 Type *I32Type = Type::getInt32Ty(M.getContext());
6356 Constant *Zero = ConstantInt::get(InternalIVTy, 0);
6357 Constant *One = ConstantInt::get(InternalIVTy, 1);
6358
6359 Function *F = CLI->getFunction();
6360 // Blocks must have terminators.
6361 // FIXME: Don't run analyses on incomplete/invalid IR.
6362 SmallVector<Instruction *> UIs;
6363 for (BasicBlock &BB : *F)
6364 if (!BB.hasTerminator())
6365 UIs.push_back(new UnreachableInst(F->getContext(), &BB));
6367 FAM.registerPass([]() { return DominatorTreeAnalysis(); });
6368 FAM.registerPass([]() { return PassInstrumentationAnalysis(); });
6369 LoopAnalysis LIA;
6370 LoopInfo &&LI = LIA.run(*F, FAM);
6371 for (Instruction *I : UIs)
6372 I->eraseFromParent();
6373 Loop *L = LI.getLoopFor(CLI->getHeader());
6374 SmallVector<Metadata *> LoopMDList;
6375 if (ChunkSize || DistScheduleChunkSize)
6376 applyParallelAccessesMetadata(CLI, Ctx, L, LI, LoopMDList);
6377 addLoopMetadata(CLI, LoopMDList);
6378
6379 // Declare useful OpenMP runtime functions.
6380 FunctionCallee StaticInit =
6381 getKmpcForStaticInitForType(InternalIVTy, M, *this);
6382 FunctionCallee StaticFini =
6383 getOrCreateRuntimeFunction(M, omp::OMPRTL___kmpc_for_static_fini);
6384
6385 // Allocate space for computed loop bounds as expected by the "init" function.
6386 Builder.restoreIP(AllocaIP);
6387 Builder.SetCurrentDebugLocation(DL);
6388 Value *PLastIter = Builder.CreateAlloca(I32Type, nullptr, "p.lastiter");
6389 Value *PLowerBound =
6390 Builder.CreateAlloca(InternalIVTy, nullptr, "p.lowerbound");
6391 Value *PUpperBound =
6392 Builder.CreateAlloca(InternalIVTy, nullptr, "p.upperbound");
6393 Value *PStride = Builder.CreateAlloca(InternalIVTy, nullptr, "p.stride");
6394 CLI->setLastIter(PLastIter);
6395
6396 // Set up the source location value for the OpenMP runtime.
6397 Builder.restoreIP(CLI->getPreheaderIP());
6398 Builder.SetCurrentDebugLocation(DL);
6399
6400 // TODO: Detect overflow in ubsan or max-out with current tripcount.
6401 Value *CastedChunkSize = Builder.CreateZExtOrTrunc(
6402 ChunkSize ? ChunkSize : Zero, InternalIVTy, "chunksize");
6403 Value *CastedDistScheduleChunkSize = Builder.CreateZExtOrTrunc(
6404 DistScheduleChunkSize ? DistScheduleChunkSize : Zero, InternalIVTy,
6405 "distschedulechunksize");
6406 Value *CastedTripCount =
6407 Builder.CreateZExt(OrigTripCount, InternalIVTy, "tripcount");
6408
6409 Constant *SchedulingType =
6410 ConstantInt::get(I32Type, static_cast<int>(SchedType));
6411 Constant *DistSchedulingType =
6412 ConstantInt::get(I32Type, static_cast<int>(DistScheduleSchedType));
6413 Builder.CreateStore(Zero, PLowerBound);
6414 Value *OrigUpperBound = Builder.CreateSub(CastedTripCount, One);
6415 Value *IsTripCountZero = Builder.CreateICmpEQ(CastedTripCount, Zero);
6416 Value *UpperBound =
6417 Builder.CreateSelect(IsTripCountZero, Zero, OrigUpperBound);
6418 Builder.CreateStore(UpperBound, PUpperBound);
6419 Builder.CreateStore(One, PStride);
6420
6421 // Call the "init" function and update the trip count of the loop with the
6422 // value it produced.
6423 uint32_t SrcLocStrSize;
6424 Constant *SrcLocStr = getOrCreateSrcLocStr(DL, SrcLocStrSize);
6425 IdentFlag Flag = OMP_IDENT_FLAG_WORK_LOOP;
6426 if (DistScheduleSchedType != OMPScheduleType::None) {
6427 Flag |= OMP_IDENT_FLAG_WORK_DISTRIBUTE;
6428 }
6429 Value *SrcLoc = getOrCreateIdent(SrcLocStr, SrcLocStrSize, Flag);
6430 Value *ThreadNum =
6431 getOrCreateThreadID(getOrCreateIdent(SrcLocStr, SrcLocStrSize));
6432 auto BuildInitCall = [StaticInit, SrcLoc, ThreadNum, PLastIter, PLowerBound,
6433 PUpperBound, PStride, One,
6434 this](Value *SchedulingType, Value *ChunkSize,
6435 auto &Builder) {
6437 StaticInit, {/*loc=*/SrcLoc, /*global_tid=*/ThreadNum,
6438 /*schedtype=*/SchedulingType, /*plastiter=*/PLastIter,
6439 /*plower=*/PLowerBound, /*pupper=*/PUpperBound,
6440 /*pstride=*/PStride, /*incr=*/One,
6441 /*chunk=*/ChunkSize});
6442 };
6443 BuildInitCall(SchedulingType, CastedChunkSize, Builder);
6444 if (DistScheduleSchedType != OMPScheduleType::None &&
6445 SchedType != OMPScheduleType::OrderedDistributeChunked &&
6446 SchedType != OMPScheduleType::OrderedDistribute) {
6447 // We want to emit a second init function call for the dist_schedule clause
6448 // to the Distribute construct. This should only be done however if a
6449 // Workshare Loop is nested within a Distribute Construct
6450 BuildInitCall(DistSchedulingType, CastedDistScheduleChunkSize, Builder);
6451 }
6452
6453 // Load values written by the "init" function.
6454 Value *FirstChunkStart =
6455 Builder.CreateLoad(InternalIVTy, PLowerBound, "omp_firstchunk.lb");
6456 Value *FirstChunkStop =
6457 Builder.CreateLoad(InternalIVTy, PUpperBound, "omp_firstchunk.ub");
6458 Value *FirstChunkEnd = Builder.CreateAdd(FirstChunkStop, One);
6459 Value *ChunkRange =
6460 Builder.CreateSub(FirstChunkEnd, FirstChunkStart, "omp_chunk.range");
6461 Value *NextChunkStride =
6462 Builder.CreateLoad(InternalIVTy, PStride, "omp_dispatch.stride");
6463
6464 // Create outer "dispatch" loop for enumerating the chunks.
6465 BasicBlock *DispatchEnter = splitBB(Builder, true);
6466 Value *DispatchCounter;
6467
6468 // It is safe to assume this didn't return an error because the callback
6469 // passed into createCanonicalLoop is the only possible error source, and it
6470 // always returns success.
6471 CanonicalLoopInfo *DispatchCLI = cantFail(createCanonicalLoop(
6472 {Builder.saveIP(), DL},
6473 [&](InsertPointTy BodyIP, Value *Counter) {
6474 DispatchCounter = Counter;
6475 return Error::success();
6476 },
6477 FirstChunkStart, CastedTripCount, NextChunkStride,
6478 /*IsSigned=*/false, /*InclusiveStop=*/false, /*ComputeIP=*/{},
6479 "dispatch"));
6480
6481 // Remember the BasicBlocks of the dispatch loop we need, then invalidate to
6482 // not have to preserve the canonical invariant.
6483 BasicBlock *DispatchBody = DispatchCLI->getBody();
6484 BasicBlock *DispatchLatch = DispatchCLI->getLatch();
6485 BasicBlock *DispatchExit = DispatchCLI->getExit();
6486 BasicBlock *DispatchAfter = DispatchCLI->getAfter();
6487 DispatchCLI->invalidate();
6488
6489 // Rewire the original loop to become the chunk loop inside the dispatch loop.
6490 redirectTo(DispatchAfter, CLI->getAfter(), DL);
6491 redirectTo(CLI->getExit(), DispatchLatch, DL);
6492 redirectTo(DispatchBody, DispatchEnter, DL);
6493
6494 // Prepare the prolog of the chunk loop.
6495 Builder.restoreIP(CLI->getPreheaderIP());
6496 Builder.SetCurrentDebugLocation(DL);
6497
6498 // Compute the number of iterations of the chunk loop.
6499 Builder.SetInsertPoint(CLI->getPreheader()->getTerminator());
6500 Value *ChunkEnd = Builder.CreateAdd(DispatchCounter, ChunkRange);
6501 Value *IsLastChunk =
6502 Builder.CreateICmpUGE(ChunkEnd, CastedTripCount, "omp_chunk.is_last");
6503 Value *CountUntilOrigTripCount =
6504 Builder.CreateSub(CastedTripCount, DispatchCounter);
6505 Value *ChunkTripCount = Builder.CreateSelect(
6506 IsLastChunk, CountUntilOrigTripCount, ChunkRange, "omp_chunk.tripcount");
6507 Value *BackcastedChunkTC =
6508 Builder.CreateTrunc(ChunkTripCount, IVTy, "omp_chunk.tripcount.trunc");
6509 CLI->setTripCount(BackcastedChunkTC);
6510
6511 // Update all uses of the induction variable except the one in the condition
6512 // block that compares it with the actual upper bound, and the increment in
6513 // the latch block.
6514 Value *BackcastedDispatchCounter =
6515 Builder.CreateTrunc(DispatchCounter, IVTy, "omp_dispatch.iv.trunc");
6516 CLI->mapIndVar([&](Instruction *) -> Value * {
6517 Builder.restoreIP(CLI->getBodyIP());
6518 return Builder.CreateAdd(IV, BackcastedDispatchCounter);
6519 });
6520
6521 // In the "exit" block, call the "fini" function.
6522 Builder.SetInsertPoint(DispatchExit->getFirstInsertionPt());
6523 createRuntimeFunctionCall(StaticFini, {SrcLoc, ThreadNum});
6524
6525 // Add the barrier if requested.
6526 if (NeedsBarrier) {
6527 InsertPointOrErrorTy AfterIP =
6528 createBarrier(LocationDescription(Builder.saveIP(), DL), OMPD_for,
6529 /*ForceSimpleCall=*/false, /*CheckCancelFlag=*/false);
6530 if (!AfterIP)
6531 return AfterIP.takeError();
6532 }
6533
6534#ifndef NDEBUG
6535 // Even though we currently do not support applying additional methods to it,
6536 // the chunk loop should remain a canonical loop.
6537 CLI->assertOK();
6538#endif
6539
6540 return DispatchAfter->getFirstInsertionPt();
6541}
6542
6543// Returns an LLVM function to call for executing an OpenMP static worksharing
6544// for loop depending on `type`. Only i32 and i64 are supported by the runtime.
6545// Always interpret integers as unsigned similarly to CanonicalLoopInfo.
6546static FunctionCallee
6548 WorksharingLoopType LoopType) {
6549 unsigned Bitwidth = Ty->getIntegerBitWidth();
6550 Module &M = OMPBuilder->M;
6551 switch (LoopType) {
6552 case WorksharingLoopType::ForStaticLoop:
6553 if (Bitwidth == 32)
6554 return OMPBuilder->getOrCreateRuntimeFunction(
6555 M, omp::RuntimeFunction::OMPRTL___kmpc_for_static_loop_4u);
6556 if (Bitwidth == 64)
6557 return OMPBuilder->getOrCreateRuntimeFunction(
6558 M, omp::RuntimeFunction::OMPRTL___kmpc_for_static_loop_8u);
6559 break;
6560 case WorksharingLoopType::DistributeStaticLoop:
6561 if (Bitwidth == 32)
6562 return OMPBuilder->getOrCreateRuntimeFunction(
6563 M, omp::RuntimeFunction::OMPRTL___kmpc_distribute_static_loop_4u);
6564 if (Bitwidth == 64)
6565 return OMPBuilder->getOrCreateRuntimeFunction(
6566 M, omp::RuntimeFunction::OMPRTL___kmpc_distribute_static_loop_8u);
6567 break;
6568 case WorksharingLoopType::DistributeForStaticLoop:
6569 if (Bitwidth == 32)
6570 return OMPBuilder->getOrCreateRuntimeFunction(
6571 M, omp::RuntimeFunction::OMPRTL___kmpc_distribute_for_static_loop_4u);
6572 if (Bitwidth == 64)
6573 return OMPBuilder->getOrCreateRuntimeFunction(
6574 M, omp::RuntimeFunction::OMPRTL___kmpc_distribute_for_static_loop_8u);
6575 break;
6576 }
6577 if (Bitwidth != 32 && Bitwidth != 64) {
6578 llvm_unreachable("Unknown OpenMP loop iterator bitwidth");
6579 }
6580 llvm_unreachable("Unknown type of OpenMP worksharing loop");
6581}
6582
6583// Inserts a call to proper OpenMP Device RTL function which handles
6584// loop worksharing.
6586 WorksharingLoopType LoopType,
6587 BasicBlock *InsertBlock, Value *Ident,
6588 Value *LoopBodyArg, Value *TripCount,
6589 Function &LoopBodyFn, bool NoLoop) {
6590 Type *TripCountTy = TripCount->getType();
6591 Module &M = OMPBuilder->M;
6592 IRBuilder<> &Builder = OMPBuilder->Builder;
6593 FunctionCallee RTLFn =
6594 getKmpcForStaticLoopForType(TripCountTy, OMPBuilder, LoopType);
6595 SmallVector<Value *, 8> RealArgs;
6596 RealArgs.push_back(Ident);
6597 RealArgs.push_back(&LoopBodyFn);
6598 RealArgs.push_back(LoopBodyArg);
6599 RealArgs.push_back(TripCount);
6600 if (LoopType == WorksharingLoopType::DistributeStaticLoop) {
6601 RealArgs.push_back(ConstantInt::get(TripCountTy, 0));
6602 RealArgs.push_back(ConstantInt::get(Builder.getInt8Ty(), 0));
6603 Builder.restoreIP(std::prev(InsertBlock->end()));
6604 OMPBuilder->createRuntimeFunctionCall(RTLFn, RealArgs);
6605 return;
6606 }
6607 FunctionCallee RTLNumThreads = OMPBuilder->getOrCreateRuntimeFunction(
6608 M, omp::RuntimeFunction::OMPRTL_omp_get_num_threads);
6609 Builder.restoreIP(std::prev(InsertBlock->end()));
6610 Value *NumThreads = OMPBuilder->createRuntimeFunctionCall(RTLNumThreads, {});
6611
6612 RealArgs.push_back(
6613 Builder.CreateZExtOrTrunc(NumThreads, TripCountTy, "num.threads.cast"));
6614 RealArgs.push_back(ConstantInt::get(TripCountTy, 0));
6615 if (LoopType == WorksharingLoopType::DistributeForStaticLoop) {
6616 RealArgs.push_back(ConstantInt::get(TripCountTy, 0));
6617 RealArgs.push_back(ConstantInt::get(Builder.getInt8Ty(), NoLoop));
6618 } else {
6619 RealArgs.push_back(ConstantInt::get(Builder.getInt8Ty(), 0));
6620 }
6621
6622 OMPBuilder->createRuntimeFunctionCall(RTLFn, RealArgs);
6623}
6624
6626 OpenMPIRBuilder *OMPIRBuilder, CanonicalLoopInfo *CLI, Value *Ident,
6627 Function &OutlinedFn, const SmallVector<Instruction *, 4> &ToBeDeleted,
6628 WorksharingLoopType LoopType, bool NoLoop) {
6629 IRBuilder<> &Builder = OMPIRBuilder->Builder;
6630 BasicBlock *Preheader = CLI->getPreheader();
6631 Value *TripCount = CLI->getTripCount();
6632
6633 // After loop body outling, the loop body contains only set up
6634 // of loop body argument structure and the call to the outlined
6635 // loop body function. Firstly, we need to move setup of loop body args
6636 // into loop preheader.
6637 Preheader->splice(std::prev(Preheader->end()), CLI->getBody(),
6638 CLI->getBody()->begin(), std::prev(CLI->getBody()->end()));
6639
6640 // The next step is to remove the whole loop. We do not it need anymore.
6641 // That's why make an unconditional branch from loop preheader to loop
6642 // exit block
6643 Builder.restoreIP(Preheader->end());
6644 Builder.SetCurrentDebugLocation(Preheader->getTerminator()->getDebugLoc());
6645 Preheader->getTerminator()->eraseFromParent();
6646 Builder.CreateBr(CLI->getExit());
6647
6648 // Delete dead loop blocks
6649 OpenMPIRBuilder::OutlineInfo CleanUpInfo;
6650 SmallPtrSet<BasicBlock *, 32> RegionBlockSet;
6651 SmallVector<BasicBlock *, 32> BlocksToBeRemoved;
6652 CleanUpInfo.EntryBB = CLI->getHeader();
6653 CleanUpInfo.ExitBB = CLI->getExit();
6654 CleanUpInfo.collectBlocks(RegionBlockSet, BlocksToBeRemoved);
6655 DeleteDeadBlocks(BlocksToBeRemoved);
6656
6657 // Find the instruction which corresponds to loop body argument structure
6658 // and remove the call to loop body function instruction.
6659 Value *LoopBodyArg;
6660 User *OutlinedFnUser = OutlinedFn.getUniqueUndroppableUser();
6661 assert(OutlinedFnUser &&
6662 "Expected unique undroppable user of outlined function");
6663 CallInst *OutlinedFnCallInstruction = dyn_cast<CallInst>(OutlinedFnUser);
6664 assert(OutlinedFnCallInstruction && "Expected outlined function call");
6665 assert((OutlinedFnCallInstruction->getParent() == Preheader) &&
6666 "Expected outlined function call to be located in loop preheader");
6667 // Check in case no argument structure has been passed.
6668 if (OutlinedFnCallInstruction->arg_size() > 1)
6669 LoopBodyArg = OutlinedFnCallInstruction->getArgOperand(1);
6670 else
6671 LoopBodyArg = Constant::getNullValue(Builder.getPtrTy());
6672 OutlinedFnCallInstruction->eraseFromParent();
6673
6674 createTargetLoopWorkshareCall(OMPIRBuilder, LoopType, Preheader, Ident,
6675 LoopBodyArg, TripCount, OutlinedFn, NoLoop);
6676
6677 for (auto &ToBeDeletedItem : ToBeDeleted)
6678 ToBeDeletedItem->eraseFromParent();
6679 CLI->invalidate();
6680}
6681
6682OpenMPIRBuilder::InsertPointOrErrorTy OpenMPIRBuilder::applyWorkshareLoopTarget(
6683 DebugLoc DL, CanonicalLoopInfo *CLI, InsertPointTy AllocaIP,
6684 WorksharingLoopType LoopType, bool NeedsBarrier, bool NoLoop,
6685 bool NeedsLastIter) {
6686 uint32_t SrcLocStrSize;
6687 Constant *SrcLocStr = getOrCreateSrcLocStr(DL, SrcLocStrSize);
6688
6689 // Mirrors host runtime reporting of last iteration by in-body computation.
6690 if (NeedsLastIter) {
6691 Type *I32Type = Type::getInt32Ty(M.getContext());
6692 Builder.restoreIP(AllocaIP);
6693 AllocaInst *PLastIter =
6694 Builder.CreateAlloca(I32Type, nullptr, "p.lastiter");
6695 CLI->setLastIter(PLastIter);
6696
6697 Builder.SetInsertPoint(CLI->getPreheader()->getTerminator());
6698 Builder.CreateStore(ConstantInt::get(I32Type, 0), PLastIter);
6699
6700 Builder.SetInsertPoint(CLI->getBody()->getFirstInsertionPt());
6701 Value *TripCount = CLI->getTripCount();
6702 Value *LastIter =
6703 Builder.CreateSub(TripCount, ConstantInt::get(TripCount->getType(), 1));
6704 Value *IsLast =
6705 Builder.CreateICmpEQ(CLI->getIndVar(), LastIter, "omp.is_last_iter");
6706 Builder.CreateStore(Builder.CreateZExt(IsLast, I32Type), PLastIter);
6707 }
6708
6710 switch (LoopType) {
6711 case WorksharingLoopType::ForStaticLoop:
6712 Flag = OMP_IDENT_FLAG_WORK_LOOP;
6713 break;
6714 case WorksharingLoopType::DistributeStaticLoop:
6715 Flag = OMP_IDENT_FLAG_WORK_DISTRIBUTE;
6716 break;
6717 case WorksharingLoopType::DistributeForStaticLoop:
6718 Flag = OMP_IDENT_FLAG_WORK_DISTRIBUTE | OMP_IDENT_FLAG_WORK_LOOP;
6719 break;
6720 }
6721 Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize, Flag);
6722
6723 auto OI = std::make_unique<OutlineInfo>();
6724 OI->OuterAllocBB = CLI->getPreheader();
6725 Function *OuterFn = CLI->getPreheader()->getParent();
6726
6727 // Instructions which need to be deleted at the end of code generation
6728 SmallVector<Instruction *, 4> ToBeDeleted;
6729
6730 OI->OuterAllocBB = AllocaIP.getNodeParent();
6731
6732 // Mark the body loop as region which needs to be extracted
6733 OI->EntryBB = CLI->getBody();
6734 OI->ExitBB = CLI->getLatch()->splitBasicBlockBefore(CLI->getLatch()->begin(),
6735 "omp.prelatch");
6736
6737 // Prepare loop body for extraction
6738 Builder.restoreIP(CLI->getPreheader()->begin());
6739
6740 // Insert new loop counter variable which will be used only in loop
6741 // body.
6742 AllocaInst *NewLoopCnt = Builder.CreateAlloca(CLI->getIndVarType(), 0, "");
6743 Instruction *NewLoopCntLoad =
6744 Builder.CreateLoad(CLI->getIndVarType(), NewLoopCnt);
6745 // New loop counter instructions are redundant in the loop preheader when
6746 // code generation for workshare loop is finshed. That's why mark them as
6747 // ready for deletion.
6748 ToBeDeleted.push_back(NewLoopCntLoad);
6749 ToBeDeleted.push_back(NewLoopCnt);
6750
6751 // Analyse loop body region. Find all input variables which are used inside
6752 // loop body region.
6753 SmallPtrSet<BasicBlock *, 32> ParallelRegionBlockSet;
6755 OI->collectBlocks(ParallelRegionBlockSet, Blocks);
6756
6757 CodeExtractorAnalysisCache CEAC(*OuterFn);
6758 CodeExtractor Extractor(Blocks,
6759 /* DominatorTree */ nullptr,
6760 /* AggregateArgs */ true,
6761 /* BlockFrequencyInfo */ nullptr,
6762 /* BranchProbabilityInfo */ nullptr,
6763 /* AssumptionCache */ nullptr,
6764 /* AllowVarArgs */ true,
6765 /* AllowAlloca */ true,
6766 /* AllocationBlock */ CLI->getPreheader(),
6767 /* DeallocationBlocks */ {},
6768 /* Suffix */ ".omp_wsloop",
6769 /* AggrArgsIn0AddrSpace */ true);
6770
6771 BasicBlock *CommonExit = nullptr;
6772 SetVector<Value *> SinkingCands, HoistingCands;
6773
6774 // Find allocas outside the loop body region which are used inside loop
6775 // body
6776 Extractor.findAllocas(CEAC, SinkingCands, HoistingCands, CommonExit);
6777
6778 // We need to model loop body region as the function f(cnt, loop_arg).
6779 // That's why we replace loop induction variable by the new counter
6780 // which will be one of loop body function argument
6782 CLI->getIndVar()->user_end());
6783 for (auto Use : Users) {
6784 if (Instruction *Inst = dyn_cast<Instruction>(Use)) {
6785 if (ParallelRegionBlockSet.count(Inst->getParent())) {
6786 Inst->replaceUsesOfWith(CLI->getIndVar(), NewLoopCntLoad);
6787 }
6788 }
6789 }
6790 // Make sure that loop counter variable is not merged into loop body
6791 // function argument structure and it is passed as separate variable
6792 OI->ExcludeArgsFromAggregate.push_back(NewLoopCntLoad);
6793
6794 // PostOutline CB is invoked when loop body function is outlined and
6795 // loop body is replaced by call to outlined function. We need to add
6796 // call to OpenMP device rtl inside loop preheader. OpenMP device rtl
6797 // function will handle loop control logic.
6798 //
6799 OI->PostOutlineCB = [=, ToBeDeletedVec =
6800 std::move(ToBeDeleted)](Function &OutlinedFn) {
6801 workshareLoopTargetCallback(this, CLI, Ident, OutlinedFn, ToBeDeletedVec,
6802 LoopType, NoLoop);
6803 };
6804 addOutlineInfo(std::move(OI));
6805
6806 // Keep the barrier outside the outlined loop body so that every thread
6807 // encounters it, including threads that execute no iterations.
6808 if (NeedsBarrier) {
6809 Builder.SetInsertPoint(CLI->getExit()->getTerminator());
6810 // Standalone distribute loops never request a barrier. For both regular
6811 // worksharing loops and combined distribute/for loops, the barrier is
6812 // associated with the worksharing loop, hence OMPD_for.
6813 InsertPointOrErrorTy BarrierIP =
6814 createBarrier(LocationDescription(Builder.saveIP(), DL), OMPD_for,
6815 /*ForceSimpleCall=*/false, /*CheckCancelFlag=*/false);
6816 if (!BarrierIP)
6817 return BarrierIP.takeError();
6818 }
6819 return CLI->getAfterIP();
6820}
6821
6824 bool NeedsBarrier, omp::ScheduleKind SchedKind, Value *ChunkSize,
6825 bool HasSimdModifier, bool HasMonotonicModifier,
6826 bool HasNonmonotonicModifier, bool HasOrderedClause,
6827 WorksharingLoopType LoopType, bool NoLoop, bool HasDistSchedule,
6828 Value *DistScheduleChunkSize, bool NeedsLastIter) {
6829 if (CLI->VirtualCollapse &&
6830 (Config.isTargetDevice() ||
6831 (SchedKind != omp::OMP_SCHEDULE_Static &&
6832 SchedKind != omp::OMP_SCHEDULE_Default) ||
6833 ChunkSize || HasOrderedClause || HasDistSchedule ||
6834 DistScheduleChunkSize || LoopType != WorksharingLoopType::ForStaticLoop))
6836 "Virtual collapse requires unchunked static worksharing");
6837 if (Config.isTargetDevice())
6838 return applyWorkshareLoopTarget(DL, CLI, AllocaIP, LoopType, NeedsBarrier,
6839 NoLoop, NeedsLastIter);
6840 OMPScheduleType EffectiveScheduleType = computeOpenMPScheduleType(
6841 SchedKind, ChunkSize, HasSimdModifier, HasMonotonicModifier,
6842 HasNonmonotonicModifier, HasOrderedClause, DistScheduleChunkSize);
6843
6844 bool IsOrdered = (EffectiveScheduleType & OMPScheduleType::ModifierOrdered) ==
6845 OMPScheduleType::ModifierOrdered;
6846 OMPScheduleType DistScheduleSchedType = OMPScheduleType::None;
6847 if (HasDistSchedule) {
6848 DistScheduleSchedType = DistScheduleChunkSize
6849 ? OMPScheduleType::OrderedDistributeChunked
6850 : OMPScheduleType::OrderedDistribute;
6851 }
6852 switch (EffectiveScheduleType & ~OMPScheduleType::ModifierMask) {
6853 case OMPScheduleType::BaseStatic:
6854 case OMPScheduleType::BaseDistribute:
6855 assert((!ChunkSize || !DistScheduleChunkSize) &&
6856 "No chunk size with static-chunked schedule");
6857 if (IsOrdered && !HasDistSchedule)
6858 return applyDynamicWorkshareLoop(DL, CLI, AllocaIP, EffectiveScheduleType,
6859 NeedsBarrier, ChunkSize);
6860 // FIXME: Monotonicity ignored?
6861 if (DistScheduleChunkSize)
6862 return applyStaticChunkedWorkshareLoop(
6863 DL, CLI, AllocaIP, NeedsBarrier, ChunkSize, EffectiveScheduleType,
6864 DistScheduleChunkSize, DistScheduleSchedType);
6865 return applyStaticWorkshareLoop(DL, CLI, AllocaIP, LoopType, NeedsBarrier,
6866 HasDistSchedule);
6867
6868 case OMPScheduleType::BaseStaticChunked:
6869 case OMPScheduleType::BaseDistributeChunked:
6870 if (IsOrdered && !HasDistSchedule)
6871 return applyDynamicWorkshareLoop(DL, CLI, AllocaIP, EffectiveScheduleType,
6872 NeedsBarrier, ChunkSize);
6873 // FIXME: Monotonicity ignored?
6874 return applyStaticChunkedWorkshareLoop(
6875 DL, CLI, AllocaIP, NeedsBarrier, ChunkSize, EffectiveScheduleType,
6876 DistScheduleChunkSize, DistScheduleSchedType);
6877
6878 case OMPScheduleType::BaseRuntime:
6879 case OMPScheduleType::BaseAuto:
6880 case OMPScheduleType::BaseGreedy:
6881 case OMPScheduleType::BaseBalanced:
6882 case OMPScheduleType::BaseSteal:
6883 case OMPScheduleType::BaseRuntimeSimd:
6884 assert(!ChunkSize &&
6885 "schedule type does not support user-defined chunk sizes");
6886 [[fallthrough]];
6887 case OMPScheduleType::BaseGuidedSimd:
6888 case OMPScheduleType::BaseDynamicChunked:
6889 case OMPScheduleType::BaseGuidedChunked:
6890 case OMPScheduleType::BaseGuidedIterativeChunked:
6891 case OMPScheduleType::BaseGuidedAnalyticalChunked:
6892 case OMPScheduleType::BaseStaticBalancedChunked:
6893 return applyDynamicWorkshareLoop(DL, CLI, AllocaIP, EffectiveScheduleType,
6894 NeedsBarrier, ChunkSize);
6895
6896 default:
6897 llvm_unreachable("Unknown/unimplemented schedule kind");
6898 }
6899}
6900
6901/// Returns an LLVM function to call for initializing loop bounds using OpenMP
6902/// dynamic scheduling depending on `type`. Only i32 and i64 are supported by
6903/// the runtime. Always interpret integers as unsigned similarly to
6904/// CanonicalLoopInfo.
6905static FunctionCallee
6907 unsigned Bitwidth = Ty->getIntegerBitWidth();
6908 if (Bitwidth == 32)
6909 return OMPBuilder.getOrCreateRuntimeFunction(
6910 M, omp::RuntimeFunction::OMPRTL___kmpc_dispatch_init_4u);
6911 if (Bitwidth == 64)
6912 return OMPBuilder.getOrCreateRuntimeFunction(
6913 M, omp::RuntimeFunction::OMPRTL___kmpc_dispatch_init_8u);
6914 llvm_unreachable("unknown OpenMP loop iterator bitwidth");
6915}
6916
6917/// Returns an LLVM function to call for updating the next loop using OpenMP
6918/// dynamic scheduling depending on `type`. Only i32 and i64 are supported by
6919/// the runtime. Always interpret integers as unsigned similarly to
6920/// CanonicalLoopInfo.
6921static FunctionCallee
6923 unsigned Bitwidth = Ty->getIntegerBitWidth();
6924 if (Bitwidth == 32)
6925 return OMPBuilder.getOrCreateRuntimeFunction(
6926 M, omp::RuntimeFunction::OMPRTL___kmpc_dispatch_next_4u);
6927 if (Bitwidth == 64)
6928 return OMPBuilder.getOrCreateRuntimeFunction(
6929 M, omp::RuntimeFunction::OMPRTL___kmpc_dispatch_next_8u);
6930 llvm_unreachable("unknown OpenMP loop iterator bitwidth");
6931}
6932
6933/// Returns an LLVM function to call for finalizing the dynamic loop using
6934/// depending on `type`. Only i32 and i64 are supported by the runtime. Always
6935/// interpret integers as unsigned similarly to CanonicalLoopInfo.
6936static FunctionCallee
6938 unsigned Bitwidth = Ty->getIntegerBitWidth();
6939 if (Bitwidth == 32)
6940 return OMPBuilder.getOrCreateRuntimeFunction(
6941 M, omp::RuntimeFunction::OMPRTL___kmpc_dispatch_fini_4u);
6942 if (Bitwidth == 64)
6943 return OMPBuilder.getOrCreateRuntimeFunction(
6944 M, omp::RuntimeFunction::OMPRTL___kmpc_dispatch_fini_8u);
6945 llvm_unreachable("unknown OpenMP loop iterator bitwidth");
6946}
6947
6949OpenMPIRBuilder::applyDynamicWorkshareLoop(DebugLoc DL, CanonicalLoopInfo *CLI,
6950 InsertPointTy AllocaIP,
6951 OMPScheduleType SchedType,
6952 bool NeedsBarrier, Value *Chunk) {
6953 assert(CLI->isValid() && "Requires a valid canonical loop");
6954 assert(!isConflictIP(AllocaIP, CLI->getPreheaderIP()) &&
6955 "Require dedicated allocate IP");
6957 "Require valid schedule type");
6958
6959 bool Ordered = (SchedType & OMPScheduleType::ModifierOrdered) ==
6960 OMPScheduleType::ModifierOrdered;
6961
6962 // Set up the source location value for OpenMP runtime.
6963 Builder.SetCurrentDebugLocation(DL);
6964
6965 uint32_t SrcLocStrSize;
6966 Constant *SrcLocStr = getOrCreateSrcLocStr(DL, SrcLocStrSize);
6967 Value *SrcLoc =
6968 getOrCreateIdent(SrcLocStr, SrcLocStrSize, OMP_IDENT_FLAG_WORK_LOOP);
6969
6970 // Declare useful OpenMP runtime functions.
6971 Value *IV = CLI->getIndVar();
6972 Type *IVTy = IV->getType();
6973 FunctionCallee DynamicInit = getKmpcForDynamicInitForType(IVTy, M, *this);
6974 FunctionCallee DynamicNext = getKmpcForDynamicNextForType(IVTy, M, *this);
6975
6976 // Allocate space for computed loop bounds as expected by the "init" function.
6977 Builder.SetInsertPoint(AllocaIP.getNodeParent()->getFirstNonPHIOrAlloca());
6978 Type *I32Type = Type::getInt32Ty(M.getContext());
6979 Value *PLastIter = Builder.CreateAlloca(I32Type, nullptr, "p.lastiter");
6980 Value *PLowerBound = Builder.CreateAlloca(IVTy, nullptr, "p.lowerbound");
6981 Value *PUpperBound = Builder.CreateAlloca(IVTy, nullptr, "p.upperbound");
6982 Value *PStride = Builder.CreateAlloca(IVTy, nullptr, "p.stride");
6983 CLI->setLastIter(PLastIter);
6984
6985 // At the end of the preheader, prepare for calling the "init" function by
6986 // storing the current loop bounds into the allocated space. A canonical loop
6987 // always iterates from 0 to trip-count with step 1. Note that "init" expects
6988 // and produces an inclusive upper bound.
6989 BasicBlock *PreHeader = CLI->getPreheader();
6990 Builder.SetInsertPoint(PreHeader->getTerminator());
6991 Constant *One = ConstantInt::get(IVTy, 1);
6992 Builder.CreateStore(One, PLowerBound);
6993 Value *UpperBound = CLI->getTripCount();
6994 Builder.CreateStore(UpperBound, PUpperBound);
6995 Builder.CreateStore(One, PStride);
6996
6997 BasicBlock *Header = CLI->getHeader();
6998 BasicBlock *Exit = CLI->getExit();
6999 BasicBlock *Cond = CLI->getCond();
7000 BasicBlock *Latch = CLI->getLatch();
7001 InsertPointTy AfterIP = CLI->getAfterIP();
7002
7003 // The CLI will be "broken" in the code below, as the loop is no longer
7004 // a valid canonical loop.
7005
7006 if (!Chunk)
7007 Chunk = One;
7008
7009 Value *ThreadNum =
7010 getOrCreateThreadID(getOrCreateIdent(SrcLocStr, SrcLocStrSize));
7011
7012 Constant *SchedulingType =
7013 ConstantInt::get(I32Type, static_cast<int>(SchedType));
7014
7015 // Call the "init" function.
7016 createRuntimeFunctionCall(DynamicInit, {SrcLoc, ThreadNum, SchedulingType,
7017 /* LowerBound */ One, UpperBound,
7018 /* step */ One, Chunk});
7019
7020 // An outer loop around the existing one.
7021 BasicBlock *OuterCond = BasicBlock::Create(
7022 PreHeader->getContext(), Twine(PreHeader->getName()) + ".outer.cond",
7023 PreHeader->getParent());
7024 // This needs to be 32-bit always, so can't use the IVTy Zero above.
7025 Builder.SetInsertPoint(OuterCond->getFirstInsertionPt());
7027 DynamicNext,
7028 {SrcLoc, ThreadNum, PLastIter, PLowerBound, PUpperBound, PStride});
7029 Constant *Zero32 = ConstantInt::get(I32Type, 0);
7030 Value *MoreWork = Builder.CreateCmp(CmpInst::ICMP_NE, Res, Zero32);
7031 Value *LowerBound =
7032 Builder.CreateSub(Builder.CreateLoad(IVTy, PLowerBound), One, "lb");
7033 Builder.CreateCondBr(MoreWork, Header, Exit);
7034
7035 // Change PHI-node in loop header to use outer cond rather than preheader,
7036 // and set IV to the LowerBound.
7037 Instruction *Phi = &Header->front();
7038 auto *PI = cast<PHINode>(Phi);
7039 PI->setIncomingBlock(0, OuterCond);
7040 PI->setIncomingValue(0, LowerBound);
7041
7042 // Then set the pre-header to jump to the OuterCond
7043 Instruction *Term = PreHeader->getTerminator();
7044 auto *Br = cast<UncondBrInst>(Term);
7045 Br->setSuccessor(OuterCond);
7046
7047 // Modify the inner condition:
7048 // * Use the UpperBound returned from the DynamicNext call.
7049 // * jump to the loop outer loop when done with one of the inner loops.
7050 Builder.SetInsertPoint(Cond->getFirstInsertionPt());
7051 UpperBound = Builder.CreateLoad(IVTy, PUpperBound, "ub");
7052 Instruction *Comp = &*Builder.GetInsertPoint();
7053 auto *CI = cast<CmpInst>(Comp);
7054 CI->setOperand(1, UpperBound);
7055 // Redirect the inner exit to branch to outer condition.
7056 Instruction *Branch = &Cond->back();
7057 auto *BI = cast<CondBrInst>(Branch);
7058 assert(BI->getSuccessor(1) == Exit);
7059 BI->setSuccessor(1, OuterCond);
7060
7061 // Call the "fini" function if "ordered" is present in wsloop directive.
7062 if (Ordered) {
7063 Builder.SetInsertPoint(&Latch->back());
7064 FunctionCallee DynamicFini = getKmpcForDynamicFiniForType(IVTy, M, *this);
7065 createRuntimeFunctionCall(DynamicFini, {SrcLoc, ThreadNum});
7066 }
7067
7068 // Add the barrier if requested.
7069 if (NeedsBarrier) {
7070 Builder.SetInsertPoint(&Exit->back());
7071 InsertPointOrErrorTy BarrierIP =
7073 omp::Directive::OMPD_for, /* ForceSimpleCall */ false,
7074 /* CheckCancelFlag */ false);
7075 if (!BarrierIP)
7076 return BarrierIP.takeError();
7077 }
7078
7079 CLI->invalidate();
7080 return AfterIP;
7081}
7082
7083/// Redirect all edges that branch to \p OldTarget to \p NewTarget. That is,
7084/// after this \p OldTarget will be orphaned.
7086 BasicBlock *NewTarget, DebugLoc DL) {
7088 redirectTo(Pred, NewTarget, DL);
7089}
7090
7092 SmallPtrSet<BasicBlock *, 8> InternalBBs(from_range, BBs);
7093 // We add a block to BBsToKeep iff we have proven it has an external use.
7095
7096 while (true) {
7097 bool Changed = false;
7098
7099 for (BasicBlock *BB : BBs) {
7100 if (BBsToKeep.contains(BB))
7101 continue;
7102
7103 for (Use &U : BB->uses()) {
7104 auto *UseInst = dyn_cast<Instruction>(U.getUser());
7105 if (!UseInst)
7106 continue;
7107 BasicBlock *UseBB = UseInst->getParent();
7108 if (!InternalBBs.contains(UseBB) || BBsToKeep.contains(UseBB)) {
7109 BBsToKeep.insert(BB);
7110 Changed = true;
7111 break;
7112 }
7113 }
7114 }
7115
7116 if (!Changed)
7117 break;
7118 }
7119
7121 BBs, [&BBsToKeep](BasicBlock *BB) { return !BBsToKeep.contains(BB); });
7122 DeleteDeadBlocks(BBsToDelete);
7123}
7124
7125/// Physical handles captured before the source descriptors are invalidated.
7132
7134OpenMPIRBuilder::planVirtualRowLoop(ArrayRef<CanonicalLoopInfo *> Loops) {
7135 // The executor inserts a guard before the outer latch. An indirect jump
7136 // by block address could bypass that guard.
7137 if (isa<IndirectBrInst>(Loops.back()->getAfter()->getTerminator()))
7139 "Virtual collapse requires unobserved canonical loop controls");
7140 // Save the original blocks and IVs before the executor changes the CFG.
7141 VirtualRowPlan Plan;
7142 Plan.Latches.push_back(Loops.front()->getLatch());
7143 for (CanonicalLoopInfo *Loop : Loops) {
7144 Plan.IndVars.push_back(cast<PHINode>(Loop->getIndVar()));
7145 Plan.Preheaders.push_back(Loop->getPreheader());
7146 }
7147 // The inner loop must return directly to the latch where the guard is added.
7148 if (Loops.front()->getBody()->getUniqueSuccessor() !=
7149 Plan.Preheaders.back() ||
7150 Loops.back()->getAfter()->getSingleSuccessor() != Plan.Latches.front())
7151 reportFatalInternalError("Virtual collapse requires direct nesting");
7152 Plan.InnerCmp = cast<CmpInst>(&Loops.back()->getCond()->front());
7153 return Plan;
7154}
7155
7156void OpenMPIRBuilder::createVirtualRowExecutor(CanonicalLoopInfo *Result,
7157 const VirtualRowPlan &Plan,
7158 ArrayRef<Value *> TripCounts,
7159 Value *Begin, Value *Count,
7160 BasicBlock *Entry) {
7161 DebugLoc DL = Builder.getCurrentDebugLocation();
7162 BasicBlock *OuterHeader = Plan.IndVars.front()->getParent();
7163 Type *IVType = Begin->getType();
7164 Constant *Zero = ConstantInt::get(IVType, 0);
7165 // A row is one invocation of the inner loop. Decode the first logical
7166 // iteration once, before entering the original loop nest.
7167 Builder.SetInsertPoint(Entry);
7168 Value *InnerBegin =
7169 Builder.CreateURem(Begin, TripCounts.back(), "omp_collapsed.begin.1");
7170 Value *OuterBegin =
7171 Builder.CreateUDiv(Begin, TripCounts.back(), "omp_collapsed.begin.0");
7172 // Include the skipped prefix of the first row so each completed row
7173 // removes one full inner trip count from Remaining.
7174 Value *InitialRemaining =
7175 Builder.CreateAdd(Count, InnerBegin, "omp_collapsed.row.remaining");
7176 Builder.CreateBr(OuterHeader);
7177
7178 Builder.SetInsertPoint(OuterHeader->getFirstNonPHIIt());
7179 Builder.SetCurrentDebugLocation(DL);
7180 PHINode *Remaining =
7181 Builder.CreatePHI(IVType, 2, "omp_collapsed.row.remaining.0");
7182 Remaining->addIncoming(InitialRemaining, Entry);
7183 // Only the first row starts at InnerBegin; subsequent rows start at zero.
7184 // For an inner trip count of one, the existing zero start is sufficient.
7185 if (!cast<ConstantInt>(TripCounts.back())->isOne()) {
7186 PHINode *Start =
7187 Builder.CreatePHI(IVType, 2, "omp_collapsed.row.start.1.0");
7188 Start->addIncoming(InnerBegin, Entry);
7189 Start->addIncoming(Zero, Plan.Latches.front());
7190 Plan.IndVars.back()->setIncomingValue(0, Start);
7191 }
7192 // Saved inner-preheader insertions must not change the IV PHI's entry edge.
7193 // Keep the original branch as their anchor and give it a PHI-free successor.
7194 auto *InnerBr = cast<UncondBrInst>(Plan.Preheaders.back()->getTerminator());
7195 BasicBlock *InnerHeader = Plan.IndVars.back()->getParent();
7196 BasicBlock *InnerEntry =
7197 BasicBlock::Create(M.getContext(), "omp_collapsed.row.preheader",
7198 InnerHeader->getParent(), InnerHeader);
7199 Builder.SetInsertPoint(InnerEntry);
7200 Builder.SetCurrentDebugLocation(DL);
7201 Builder.CreateBr(InnerHeader);
7202 InnerBr->setSuccessor(InnerEntry);
7203 Plan.IndVars.back()->setIncomingBlock(0, InnerEntry);
7204 // The final row ends at Remaining; earlier rows keep their original bound.
7205 Builder.SetInsertPoint(Plan.Preheaders.back()->getTerminator());
7206 Builder.SetCurrentDebugLocation(DL);
7207 Value *IsFinalRow = Builder.CreateICmpULE(Remaining, TripCounts.back(),
7208 "omp_collapsed.row.is_final");
7209 Value *InnerStop = Builder.CreateSelect(
7210 IsFinalRow, Remaining, TripCounts.back(), "omp_collapsed.row.stop");
7211 Plan.InnerCmp->setOperand(1, InnerStop);
7212
7213 // Only non-final rows reach the outer latch, so Remaining is greater than
7214 // the inner trip count and this subtraction cannot underflow.
7215 BasicBlock *Latch = Plan.Latches.front();
7216 Builder.SetInsertPoint(Latch->getTerminator());
7217 Builder.SetCurrentDebugLocation(DL);
7218 Value *RemainingNext = Builder.CreateSub(Remaining, TripCounts.back(),
7219 "omp_collapsed.row.remaining.next",
7220 /*HasNUW=*/true);
7221 Remaining->addIncoming(RemainingNext, Latch);
7222 // Check completion after the inner loop and its continuation, before
7223 // incrementing the outer IV. The final row exits the whole nest.
7224 BasicBlock *Guard =
7225 Latch->splitBasicBlockBefore(Latch->begin(), "omp_collapsed.row.done");
7226 Guard->getTerminator()->eraseFromParent();
7227 Builder.SetInsertPoint(Guard);
7228 Builder.CreateCondBr(IsFinalRow, Result->getExit(), Latch);
7229 Plan.IndVars.front()->setIncomingValue(0, OuterBegin);
7230 Plan.IndVars.front()->setIncomingBlock(0, Entry);
7231}
7232
7233CanonicalLoopInfo *OpenMPIRBuilder::createVirtualCollapsedLoop(
7235 const VirtualRowPlan &Plan, ArrayRef<Value *> TripCounts,
7236 Value *CollapsedTripCount) {
7237 // Reuse the outer loop's control blocks; the physical nest stays in place.
7238 LoopInfos.emplace_front();
7239 CanonicalLoopInfo *Result = &LoopInfos.front();
7240 Result->Header = Loops.front()->getHeader();
7241 Result->Cond = Loops.front()->getCond();
7242 Result->Latch = Loops.front()->getLatch();
7243 Result->Exit = Loops.front()->getExit();
7244 BasicBlock *Preheader = Plan.Preheaders.front();
7245 Function *F = Result->getFunction();
7246 Type *IVType = CollapsedTripCount->getType();
7247 Constant *Zero = ConstantInt::get(IVType, 0);
7248 // Keep initialization separate from decoding so an empty range skips both
7249 // division and the loop nest.
7250 BasicBlock *Init = BasicBlock::Create(M.getContext(), "omp_collapsed.init", F,
7251 Result->getHeader());
7252 BasicBlock *Entry = BasicBlock::Create(M.getContext(), "omp_collapsed.decode",
7253 F, Result->getHeader());
7254 Builder.SetCurrentDebugLocation(DL);
7255 Builder.SetInsertPoint(Init);
7256 // Keep explicit range copies until scheduling replaces operand zero. Create
7257 // the instructions directly so the initial constants are not folded away.
7258 auto *Begin = Builder.Insert(BinaryOperator::CreateAdd(Zero, Zero),
7259 "omp_collapsed.range.begin");
7260 auto *Count =
7261 Builder.Insert(BinaryOperator::CreateAdd(CollapsedTripCount, Zero),
7262 "omp_collapsed.range.count");
7263 Builder.CreateCondBr(Builder.CreateICmpNE(Count, Zero), Entry,
7264 Result->getExit());
7265 Result->VirtualCollapse =
7266 CanonicalLoopInfo::VirtualCollapseInfo{Begin, Count};
7267 // Route the preheader through Init. The executor reconnects the outer IV
7268 // PHI to the decode block.
7269 cast<UncondBrInst>(Preheader->getTerminator())->setSuccessor(Init);
7270 createVirtualRowExecutor(Result, Plan, TripCounts, Begin, Count, Entry);
7271 // The transformed nest is now represented by Result, not the input loops.
7272 for (CanonicalLoopInfo *Loop : Loops)
7273 Loop->invalidate();
7274#ifndef NDEBUG
7275 Result->assertOK();
7276#endif
7277 return Result;
7278}
7279
7280void OpenMPIRBuilder::bindCollapsedRange(CanonicalLoopInfo *Loop, Value *Begin,
7281 Value *Count) {
7282 // Update only the copied values; the range has no PHI predecessor to rebind.
7283 Loop->VirtualCollapse->Begin->setOperand(0, Begin);
7284 Loop->VirtualCollapse->Count->setOperand(0, Count);
7285}
7286
7287CanonicalLoopInfo *
7289 InsertPointTy ComputeIP) {
7290 assert(Loops.size() >= 1 && "At least one loop required");
7291 size_t NumLoops = Loops.size();
7292
7293 // Nothing to do if there is already just one loop.
7294 if (NumLoops == 1)
7295 return Loops.front();
7296
7297 if (Config.CollapseMapping == CollapseIVMapping::Virtual) {
7298 if (Loops.size() != 2)
7300 "Virtual collapse requires two constant-count loops");
7301 SmallVector<Value *, 4> TripCounts;
7302 for (CanonicalLoopInfo *Loop : Loops) {
7303 if (Loop->VirtualCollapse)
7304 Loop->reportUnsupportedVirtualCollapse();
7305 Value *TC = Loop->getTripCount();
7306 if (!isa<ConstantInt>(TC))
7308 "Virtual collapse requires two constant-count loops");
7309 TripCounts.push_back(TC);
7310 }
7311 VirtualRowPlan Plan = planVirtualRowLoop(Loops);
7312 // Constant counts fold the product without emitting instructions.
7313 Value *CollapsedTripCount =
7314 Builder.CreateNUWMul(TripCounts.front(), TripCounts.back());
7315 return createVirtualCollapsedLoop(DL, Loops, Plan, TripCounts,
7316 CollapsedTripCount);
7317 }
7318
7319 CanonicalLoopInfo *Outermost = Loops.front();
7320 CanonicalLoopInfo *Innermost = Loops.back();
7321 BasicBlock *OrigPreheader = Outermost->getPreheader();
7322 BasicBlock *OrigAfter = Outermost->getAfter();
7323 Function *F = OrigPreheader->getParent();
7324
7325 // Loop control blocks that may become orphaned later.
7326 SmallVector<BasicBlock *, 12> OldControlBBs;
7327 OldControlBBs.reserve(6 * Loops.size());
7329 Loop->collectControlBlocks(OldControlBBs);
7330
7331 // Setup the IRBuilder for inserting the trip count computation.
7332 Builder.SetCurrentDebugLocation(DL);
7333 if (ComputeIP.isValid())
7334 Builder.restoreIP(ComputeIP);
7335 else
7336 Builder.restoreIP(Outermost->getPreheaderIP());
7337
7338 // Derive the collapsed' loop trip count.
7339 // TODO: Find common/largest indvar type.
7340 Value *CollapsedTripCount = nullptr;
7341 for (CanonicalLoopInfo *L : Loops) {
7342 assert(L->isValid() &&
7343 "All loops to collapse must be valid canonical loops");
7344 Value *OrigTripCount = L->getTripCount();
7345 if (!CollapsedTripCount) {
7346 CollapsedTripCount = OrigTripCount;
7347 continue;
7348 }
7349
7350 // TODO: Enable UndefinedSanitizer to diagnose an overflow here.
7351 CollapsedTripCount =
7352 Builder.CreateNUWMul(CollapsedTripCount, OrigTripCount);
7353 }
7354
7355 // Create the collapsed loop control flow.
7356 CanonicalLoopInfo *Result =
7357 createLoopSkeleton(DL, CollapsedTripCount, F,
7358 OrigPreheader->getNextNode(), OrigAfter, "collapsed",
7359 /*IsCollapsed=*/true);
7360
7361 // Build the collapsed loop body code.
7362 // Start with deriving the input loop induction variables from the collapsed
7363 // one, using a divmod scheme. To preserve the original loops' order, the
7364 // innermost loop use the least significant bits.
7365 Builder.restoreIP(Result->getBodyIP());
7366
7367 Value *Leftover = Result->getIndVar();
7368 SmallVector<Value *> NewIndVars;
7369 NewIndVars.resize(NumLoops);
7370 for (int i = NumLoops - 1; i >= 1; --i) {
7371 Value *OrigTripCount = Loops[i]->getTripCount();
7372
7373 Value *NewIndVar = Builder.CreateURem(Leftover, OrigTripCount);
7374 NewIndVars[i] = NewIndVar;
7375
7376 Leftover = Builder.CreateUDiv(Leftover, OrigTripCount);
7377 }
7378 // Outermost loop gets all the remaining bits.
7379 NewIndVars[0] = Leftover;
7380
7381 // Construct the loop body control flow.
7382 // We progressively construct the branch structure following in direction of
7383 // the control flow, from the leading in-between code, the loop nest body, the
7384 // trailing in-between code, and rejoining the collapsed loop's latch.
7385 // ContinueBlock and ContinuePred keep track of the source(s) of next edge. If
7386 // the ContinueBlock is set, continue with that block. If ContinuePred, use
7387 // its predecessors as sources.
7388 BasicBlock *ContinueBlock = Result->getBody();
7389 BasicBlock *ContinuePred = nullptr;
7390 auto ContinueWith = [&ContinueBlock, &ContinuePred, DL](BasicBlock *Dest,
7391 BasicBlock *NextSrc) {
7392 if (ContinueBlock)
7393 redirectTo(ContinueBlock, Dest, DL);
7394 else
7395 redirectAllPredecessorsTo(ContinuePred, Dest, DL);
7396
7397 ContinueBlock = nullptr;
7398 ContinuePred = NextSrc;
7399 };
7400
7401 // The code before the nested loop of each level.
7402 // Because we are sinking it into the nest, it will be executed more often
7403 // that the original loop. More sophisticated schemes could keep track of what
7404 // the in-between code is and instantiate it only once per thread.
7405 for (size_t i = 0; i < NumLoops - 1; ++i)
7406 ContinueWith(Loops[i]->getBody(), Loops[i + 1]->getHeader());
7407
7408 // Connect the loop nest body.
7409 ContinueWith(Innermost->getBody(), Innermost->getLatch());
7410
7411 // The code after the nested loop at each level.
7412 for (size_t i = NumLoops - 1; i > 0; --i)
7413 ContinueWith(Loops[i]->getAfter(), Loops[i - 1]->getLatch());
7414
7415 // Connect the finished loop to the collapsed loop latch.
7416 ContinueWith(Result->getLatch(), nullptr);
7417
7418 // Replace the input loops with the new collapsed loop.
7419 redirectTo(Outermost->getPreheader(), Result->getPreheader(), DL);
7420 redirectTo(Result->getAfter(), Outermost->getAfter(), DL);
7421
7422 // Replace the input loop indvars with the derived ones.
7423 for (size_t i = 0; i < NumLoops; ++i)
7424 Loops[i]->getIndVar()->replaceAllUsesWith(NewIndVars[i]);
7425
7426 // Remove unused parts of the input loops.
7427 removeUnusedBlocksFromParent(OldControlBBs);
7428
7429 for (CanonicalLoopInfo *L : Loops)
7430 L->invalidate();
7431
7432#ifndef NDEBUG
7433 Result->assertOK();
7434#endif
7435 return Result;
7436}
7437
7438std::vector<CanonicalLoopInfo *>
7440 ArrayRef<Value *> TileSizes) {
7441 assert(TileSizes.size() == Loops.size() &&
7442 "Must pass as many tile sizes as there are loops");
7443 int NumLoops = Loops.size();
7444 assert(NumLoops >= 1 && "At least one loop to tile required");
7445
7446 CanonicalLoopInfo *OutermostLoop = Loops.front();
7447 CanonicalLoopInfo *InnermostLoop = Loops.back();
7448 Function *F = OutermostLoop->getBody()->getParent();
7449 BasicBlock *InnerEnter = InnermostLoop->getBody();
7450 BasicBlock *InnerLatch = InnermostLoop->getLatch();
7451
7452 // Loop control blocks that may become orphaned later.
7453 SmallVector<BasicBlock *, 12> OldControlBBs;
7454 OldControlBBs.reserve(6 * Loops.size());
7456 Loop->collectControlBlocks(OldControlBBs);
7457
7458 // Collect original trip counts and induction variable to be accessible by
7459 // index. Also, the structure of the original loops is not preserved during
7460 // the construction of the tiled loops, so do it before we scavenge the BBs of
7461 // any original CanonicalLoopInfo.
7462 SmallVector<Value *, 4> OrigTripCounts, OrigIndVars;
7463 for (CanonicalLoopInfo *L : Loops) {
7464 assert(L->isValid() && "All input loops must be valid canonical loops");
7465 OrigTripCounts.push_back(L->getTripCount());
7466 OrigIndVars.push_back(L->getIndVar());
7467 }
7468
7469 // Collect the code between loop headers. These may contain SSA definitions
7470 // that are used in the loop nest body. To be usable with in the innermost
7471 // body, these BasicBlocks will be sunk into the loop nest body. That is,
7472 // these instructions may be executed more often than before the tiling.
7473 // TODO: It would be sufficient to only sink them into body of the
7474 // corresponding tile loop.
7476 for (int i = 0; i < NumLoops - 1; ++i) {
7477 CanonicalLoopInfo *Surrounding = Loops[i];
7478 CanonicalLoopInfo *Nested = Loops[i + 1];
7479
7480 BasicBlock *EnterBB = Surrounding->getBody();
7481 BasicBlock *ExitBB = Nested->getHeader();
7482 InbetweenCode.emplace_back(EnterBB, ExitBB);
7483 }
7484
7485 // Compute the trip counts of the floor loops.
7486 Builder.SetCurrentDebugLocation(DL);
7487 Builder.restoreIP(OutermostLoop->getPreheaderIP());
7488 SmallVector<Value *, 4> FloorCompleteCount, FloorCount, FloorRems;
7489 for (int i = 0; i < NumLoops; ++i) {
7490 Value *TileSize = TileSizes[i];
7491 Value *OrigTripCount = OrigTripCounts[i];
7492 Type *IVType = OrigTripCount->getType();
7493
7494 Value *FloorCompleteTripCount = Builder.CreateUDiv(OrigTripCount, TileSize);
7495 Value *FloorTripRem = Builder.CreateURem(OrigTripCount, TileSize);
7496
7497 // 0 if tripcount divides the tilesize, 1 otherwise.
7498 // 1 means we need an additional iteration for a partial tile.
7499 //
7500 // Unfortunately we cannot just use the roundup-formula
7501 // (tripcount + tilesize - 1)/tilesize
7502 // because the summation might overflow. We do not want introduce undefined
7503 // behavior when the untiled loop nest did not.
7504 Value *FloorTripOverflow =
7505 Builder.CreateICmpNE(FloorTripRem, ConstantInt::get(IVType, 0));
7506
7507 FloorTripOverflow = Builder.CreateZExt(FloorTripOverflow, IVType);
7508 Value *FloorTripCount =
7509 Builder.CreateAdd(FloorCompleteTripCount, FloorTripOverflow,
7510 "omp_floor" + Twine(i) + ".tripcount", true);
7511
7512 // Remember some values for later use.
7513 FloorCompleteCount.push_back(FloorCompleteTripCount);
7514 FloorCount.push_back(FloorTripCount);
7515 FloorRems.push_back(FloorTripRem);
7516 }
7517
7518 // Generate the new loop nest, from the outermost to the innermost.
7519 std::vector<CanonicalLoopInfo *> Result;
7520 Result.reserve(NumLoops * 2);
7521
7522 // The basic block of the surrounding loop that enters the nest generated
7523 // loop.
7524 BasicBlock *Enter = OutermostLoop->getPreheader();
7525
7526 // The basic block of the surrounding loop where the inner code should
7527 // continue.
7528 BasicBlock *Continue = OutermostLoop->getAfter();
7529
7530 // Where the next loop basic block should be inserted.
7531 BasicBlock *OutroInsertBefore = InnermostLoop->getExit();
7532
7533 auto EmbeddNewLoop =
7534 [this, DL, F, InnerEnter, &Enter, &Continue, &OutroInsertBefore](
7535 Value *TripCount, const Twine &Name) -> CanonicalLoopInfo * {
7536 CanonicalLoopInfo *EmbeddedLoop = createLoopSkeleton(
7537 DL, TripCount, F, InnerEnter, OutroInsertBefore, Name);
7538 redirectTo(Enter, EmbeddedLoop->getPreheader(), DL);
7539 redirectTo(EmbeddedLoop->getAfter(), Continue, DL);
7540
7541 // Setup the position where the next embedded loop connects to this loop.
7542 Enter = EmbeddedLoop->getBody();
7543 Continue = EmbeddedLoop->getLatch();
7544 OutroInsertBefore = EmbeddedLoop->getLatch();
7545 return EmbeddedLoop;
7546 };
7547
7548 auto EmbeddNewLoops = [&Result, &EmbeddNewLoop](ArrayRef<Value *> TripCounts,
7549 const Twine &NameBase) {
7550 for (auto P : enumerate(TripCounts)) {
7551 CanonicalLoopInfo *EmbeddedLoop =
7552 EmbeddNewLoop(P.value(), NameBase + Twine(P.index()));
7553 Result.push_back(EmbeddedLoop);
7554 }
7555 };
7556
7557 EmbeddNewLoops(FloorCount, "floor");
7558
7559 // Within the innermost floor loop, emit the code that computes the tile
7560 // sizes.
7561 Builder.SetInsertPoint(Enter->getTerminator());
7562 SmallVector<Value *, 4> TileCounts;
7563 for (int i = 0; i < NumLoops; ++i) {
7564 CanonicalLoopInfo *FloorLoop = Result[i];
7565 Value *TileSize = TileSizes[i];
7566
7567 Value *FloorIsEpilogue =
7568 Builder.CreateICmpEQ(FloorLoop->getIndVar(), FloorCompleteCount[i]);
7569 Value *TileTripCount =
7570 Builder.CreateSelect(FloorIsEpilogue, FloorRems[i], TileSize);
7571
7572 TileCounts.push_back(TileTripCount);
7573 }
7574
7575 // Create the tile loops.
7576 EmbeddNewLoops(TileCounts, "tile");
7577
7578 // Insert the inbetween code into the body.
7579 BasicBlock *BodyEnter = Enter;
7580 BasicBlock *BodyEntered = nullptr;
7581 for (std::pair<BasicBlock *, BasicBlock *> P : InbetweenCode) {
7582 BasicBlock *EnterBB = P.first;
7583 BasicBlock *ExitBB = P.second;
7584
7585 if (BodyEnter)
7586 redirectTo(BodyEnter, EnterBB, DL);
7587 else
7588 redirectAllPredecessorsTo(BodyEntered, EnterBB, DL);
7589
7590 BodyEnter = nullptr;
7591 BodyEntered = ExitBB;
7592 }
7593
7594 // Append the original loop nest body into the generated loop nest body.
7595 if (BodyEnter)
7596 redirectTo(BodyEnter, InnerEnter, DL);
7597 else
7598 redirectAllPredecessorsTo(BodyEntered, InnerEnter, DL);
7600
7601 // Replace the original induction variable with an induction variable computed
7602 // from the tile and floor induction variables.
7603 Builder.restoreIP(Result.back()->getBodyIP());
7604 for (int i = 0; i < NumLoops; ++i) {
7605 CanonicalLoopInfo *FloorLoop = Result[i];
7606 CanonicalLoopInfo *TileLoop = Result[NumLoops + i];
7607 Value *OrigIndVar = OrigIndVars[i];
7608 Value *Size = TileSizes[i];
7609
7610 Value *Scale =
7611 Builder.CreateMul(Size, FloorLoop->getIndVar(), {}, /*HasNUW=*/true);
7612 Value *Shift =
7613 Builder.CreateAdd(Scale, TileLoop->getIndVar(), {}, /*HasNUW=*/true);
7614 OrigIndVar->replaceAllUsesWith(Shift);
7615 }
7616
7617 // Remove unused parts of the original loops.
7618 removeUnusedBlocksFromParent(OldControlBBs);
7619
7620 for (CanonicalLoopInfo *L : Loops)
7621 L->invalidate();
7622
7623#ifndef NDEBUG
7624 for (CanonicalLoopInfo *GenL : Result)
7625 GenL->assertOK();
7626#endif
7627 return Result;
7628}
7629
7630/// Attach metadata \p Properties to the basic block described by \p BB. If the
7631/// basic block already has metadata, the basic block properties are appended.
7634 // Nothing to do if no property to attach.
7635 if (Properties.empty())
7636 return;
7637
7638 LLVMContext &Ctx = BB->getContext();
7639 SmallVector<Metadata *> NewProperties;
7640 NewProperties.push_back(nullptr);
7641
7642 // If the basic block already has metadata, prepend it to the new metadata.
7643 MDNode *Existing = BB->getTerminator()->getMetadata(LLVMContext::MD_loop);
7644 if (Existing)
7645 append_range(NewProperties, drop_begin(Existing->operands(), 1));
7646
7647 append_range(NewProperties, Properties);
7648 MDNode *BasicBlockID = MDNode::getDistinct(Ctx, NewProperties);
7649 BasicBlockID->replaceOperandWith(0, BasicBlockID);
7650
7651 BB->getTerminator()->setMetadata(LLVMContext::MD_loop, BasicBlockID);
7652}
7653
7654/// Attach loop metadata \p Properties to the loop described by \p Loop. If the
7655/// loop already has metadata, the loop properties are appended.
7658 assert(Loop->isValid() && "Expecting a valid CanonicalLoopInfo");
7659
7660 // Attach metadata to the loop's latch
7661 BasicBlock *Latch = Loop->getLatch();
7662 assert(Latch && "A valid CanonicalLoopInfo must have a unique latch");
7664}
7665
7666/// Attach llvm.access.group metadata to the memref instructions of \p Block
7668 LoopInfo &LI) {
7669 for (Instruction &I : *Block) {
7670 if (I.mayReadOrWriteMemory()) {
7671 // TODO: This instruction may already have access group from
7672 // other pragmas e.g. #pragma clang loop vectorize. Append
7673 // so that the existing metadata is not overwritten.
7674 I.setMetadata(LLVMContext::MD_access_group, AccessGroup);
7675 }
7676 }
7677}
7678
7679CanonicalLoopInfo *
7681 CanonicalLoopInfo *firstLoop = Loops.front();
7682 CanonicalLoopInfo *lastLoop = Loops.back();
7683 Function *F = firstLoop->getPreheader()->getParent();
7684
7685 // Loop control blocks that will become orphaned later
7686 SmallVector<BasicBlock *> oldControlBBs;
7688 Loop->collectControlBlocks(oldControlBBs);
7689
7690 // Collect original trip counts
7691 SmallVector<Value *> origTripCounts;
7692 for (CanonicalLoopInfo *L : Loops) {
7693 assert(L->isValid() && "All input loops must be valid canonical loops");
7694 origTripCounts.push_back(L->getTripCount());
7695 }
7696
7697 Builder.SetCurrentDebugLocation(DL);
7698
7699 // Compute max trip count.
7700 // The fused loop will be from 0 to max(origTripCounts)
7701 BasicBlock *TCBlock = BasicBlock::Create(F->getContext(), "omp.fuse.comp.tc",
7702 F, firstLoop->getHeader());
7703 Builder.SetInsertPoint(TCBlock);
7704 Value *fusedTripCount = nullptr;
7705 for (CanonicalLoopInfo *L : Loops) {
7706 assert(L->isValid() && "All loops to fuse must be valid canonical loops");
7707 Value *origTripCount = L->getTripCount();
7708 if (!fusedTripCount) {
7709 fusedTripCount = origTripCount;
7710 continue;
7711 }
7712 Value *condTP = Builder.CreateICmpSGT(fusedTripCount, origTripCount);
7713 fusedTripCount = Builder.CreateSelect(condTP, fusedTripCount, origTripCount,
7714 ".omp.fuse.tc");
7715 }
7716
7717 // Generate new loop
7718 CanonicalLoopInfo *fused =
7719 createLoopSkeleton(DL, fusedTripCount, F, firstLoop->getBody(),
7720 lastLoop->getLatch(), "fused");
7721
7722 // Replace original loops with the fused loop
7723 // Preheader and After are not considered inside the CLI.
7724 // These are used to compute the individual TCs of the loops
7725 // so they have to be put before the resulting fused loop.
7726 // Moving them up for readability.
7727 for (size_t i = 0; i < Loops.size() - 1; ++i) {
7728 Loops[i]->getPreheader()->moveBefore(TCBlock);
7729 Loops[i]->getAfter()->moveBefore(TCBlock);
7730 }
7731 lastLoop->getPreheader()->moveBefore(TCBlock);
7732
7733 for (size_t i = 0; i < Loops.size() - 1; ++i) {
7734 redirectTo(Loops[i]->getPreheader(), Loops[i]->getAfter(), DL);
7735 redirectTo(Loops[i]->getAfter(), Loops[i + 1]->getPreheader(), DL);
7736 }
7737 redirectTo(lastLoop->getPreheader(), TCBlock, DL);
7738 redirectTo(TCBlock, fused->getPreheader(), DL);
7739 redirectTo(fused->getAfter(), lastLoop->getAfter(), DL);
7740
7741 // Build the fused body
7742 // Create new Blocks with conditions that jump to the original loop bodies
7744 SmallVector<Value *> condValues;
7745 for (size_t i = 0; i < Loops.size(); ++i) {
7746 BasicBlock *condBlock = BasicBlock::Create(
7747 F->getContext(), "omp.fused.inner.cond", F, Loops[i]->getBody());
7748 Builder.SetInsertPoint(condBlock);
7749 Value *condValue =
7750 Builder.CreateICmpSLT(fused->getIndVar(), origTripCounts[i]);
7751 condBBs.push_back(condBlock);
7752 condValues.push_back(condValue);
7753 }
7754 // Join the condition blocks with the bodies of the original loops
7755 redirectTo(fused->getBody(), condBBs[0], DL);
7756 for (size_t i = 0; i < Loops.size() - 1; ++i) {
7757 Builder.SetInsertPoint(condBBs[i]);
7758 Builder.CreateCondBr(condValues[i], Loops[i]->getBody(), condBBs[i + 1]);
7759 redirectAllPredecessorsTo(Loops[i]->getLatch(), condBBs[i + 1], DL);
7760 // Replace the IV with the fused IV
7761 Loops[i]->getIndVar()->replaceAllUsesWith(fused->getIndVar());
7762 }
7763 // Last body jumps to the created end body block
7764 Builder.SetInsertPoint(condBBs.back());
7765 Builder.CreateCondBr(condValues.back(), lastLoop->getBody(),
7766 fused->getLatch());
7767 redirectAllPredecessorsTo(lastLoop->getLatch(), fused->getLatch(), DL);
7768 // Replace the IV with the fused IV
7769 lastLoop->getIndVar()->replaceAllUsesWith(fused->getIndVar());
7770
7771 // The loop latch must have only one predecessor. Currently it is branched to
7772 // from both the last condition block and the last loop body
7773 fused->getLatch()->splitBasicBlockBefore(fused->getLatch()->begin(),
7774 "omp.fused.pre_latch");
7775
7776 // Remove unused parts
7777 removeUnusedBlocksFromParent(oldControlBBs);
7778
7779 // Invalidate old CLIs
7780 for (CanonicalLoopInfo *L : Loops)
7781 L->invalidate();
7782
7783#ifndef NDEBUG
7784 fused->assertOK();
7785#endif
7786 return fused;
7787}
7788
7789void OpenMPIRBuilder::addUnrollMetadata(CanonicalLoopInfo *Loop,
7791 assert(Loop->isValid() && "Expecting a valid CanonicalLoopInfo");
7792 if (Loop->VirtualCollapse)
7793 reportFatalInternalError("unrolling must precede Virtual collapse");
7795}
7796
7798 LLVMContext &Ctx = Builder.getContext();
7799 addUnrollMetadata(
7800 Loop, {MDNode::get(Ctx, MDString::get(Ctx, "llvm.loop.unroll.enable")),
7801 MDNode::get(Ctx, MDString::get(Ctx, "llvm.loop.unroll.full"))});
7802}
7803
7805 LLVMContext &Ctx = Builder.getContext();
7806 addUnrollMetadata(
7807 Loop, {
7808 MDNode::get(Ctx, MDString::get(Ctx, "llvm.loop.unroll.enable")),
7809 });
7810}
7811
7812void OpenMPIRBuilder::createIfVersion(CanonicalLoopInfo *CanonicalLoop,
7813 Value *IfCond, ValueToValueMapTy &VMap,
7814 LoopAnalysis &LIA, LoopInfo &LI, Loop *L,
7815 const Twine &NamePrefix) {
7816 Function *F = CanonicalLoop->getFunction();
7817
7818 // We can't do
7819 // if (cond) {
7820 // simd_loop;
7821 // } else {
7822 // non_simd_loop;
7823 // }
7824 // because then the CanonicalLoopInfo would only point to one of the loops:
7825 // leading to other constructs operating on the same loop to malfunction.
7826 // Instead generate
7827 // while (...) {
7828 // if (cond) {
7829 // simd_body;
7830 // } else {
7831 // not_simd_body;
7832 // }
7833 // }
7834 // At least for simple loops, LLVM seems able to hoist the if out of the loop
7835 // body at -O3
7836
7837 // Define where if branch should be inserted
7838 auto SplitBeforeIt = CanonicalLoop->getBody()->getFirstNonPHIIt();
7839
7840 // Create additional blocks for the if statement
7841 BasicBlock *Cond = SplitBeforeIt->getParent();
7842 llvm::LLVMContext &C = Cond->getContext();
7844 C, NamePrefix + ".if.then", Cond->getParent(), Cond->getNextNode());
7846 C, NamePrefix + ".if.else", Cond->getParent(), CanonicalLoop->getExit());
7847
7848 // Create if condition branch.
7849 Builder.SetInsertPoint(SplitBeforeIt);
7850 Instruction *BrInstr =
7851 Builder.CreateCondBr(IfCond, ThenBlock, /*ifFalse*/ ElseBlock);
7852 InsertPointTy IP(++BrInstr->getIterator());
7853 // Then block contains branch to omp loop body which needs to be vectorized
7854 spliceBB(IP, ThenBlock, false, Builder.getCurrentDebugLocation());
7855 ThenBlock->replaceSuccessorsPhiUsesWith(Cond, ThenBlock);
7856
7857 Builder.SetInsertPoint(ElseBlock);
7858
7859 // Clone loop for the else branch
7861
7862 SmallVector<BasicBlock *, 8> ExistingBlocks;
7863 ExistingBlocks.reserve(L->getNumBlocks() + 1);
7864 ExistingBlocks.push_back(ThenBlock);
7865 ExistingBlocks.append(L->block_begin(), L->block_end());
7866 // Cond is the block that has the if clause condition
7867 // LoopCond is omp_loop.cond
7868 // LoopHeader is omp_loop.header
7869 BasicBlock *LoopCond = Cond->getUniquePredecessor();
7870 BasicBlock *LoopHeader = LoopCond->getUniquePredecessor();
7871 assert(LoopCond && LoopHeader && "Invalid loop structure");
7872 for (BasicBlock *Block : ExistingBlocks) {
7873 if (Block == L->getLoopPreheader() || Block == L->getLoopLatch() ||
7874 Block == LoopHeader || Block == LoopCond || Block == Cond) {
7875 continue;
7876 }
7877 BasicBlock *NewBB = CloneBasicBlock(Block, VMap, "", F);
7878
7879 // fix name not to be omp.if.then
7880 if (Block == ThenBlock)
7881 NewBB->setName(NamePrefix + ".if.else");
7882
7883 NewBB->moveBefore(CanonicalLoop->getExit());
7884 VMap[Block] = NewBB;
7885 NewBlocks.push_back(NewBB);
7886 }
7887 remapInstructionsInBlocks(NewBlocks, VMap);
7888 Builder.CreateBr(NewBlocks.front());
7889
7890 // The loop latch must have only one predecessor. Currently it is branched to
7891 // from both the 'then' and 'else' branches.
7892 L->getLoopLatch()->splitBasicBlockBefore(L->getLoopLatch()->begin(),
7893 NamePrefix + ".pre_latch");
7894
7895 // Ensure that the then block is added to the loop so we add the attributes in
7896 // the next step
7897 L->addBasicBlockToLoop(ThenBlock, LI);
7898}
7899
7900unsigned
7902 const StringMap<bool> &Features) {
7903 if (TargetTriple.isX86()) {
7904 if (Features.lookup("avx512f"))
7905 return 512;
7906 else if (Features.lookup("avx"))
7907 return 256;
7908 return 128;
7909 }
7910 if (TargetTriple.isPPC())
7911 return 128;
7912 if (TargetTriple.isWasm())
7913 return 128;
7914 if (TargetTriple.isSystemZ())
7915 return 64;
7916 return 0;
7917}
7918
7920 MapVector<Value *, Value *> AlignedVars,
7921 Value *IfCond, OrderKind Order,
7922 ConstantInt *Simdlen, ConstantInt *Safelen) {
7923 if (CanonicalLoop->VirtualCollapse)
7924 CanonicalLoop->reportUnsupportedVirtualCollapse();
7925 LLVMContext &Ctx = Builder.getContext();
7926
7927 Function *F = CanonicalLoop->getFunction();
7928
7929 // Blocks must have terminators.
7930 // FIXME: Don't run analyses on incomplete/invalid IR.
7932 for (BasicBlock &BB : *F)
7933 if (!BB.hasTerminator())
7934 UIs.push_back(new UnreachableInst(F->getContext(), &BB));
7935
7936 // TODO: We should not rely on pass manager. Currently we use pass manager
7937 // only for getting llvm::Loop which corresponds to given CanonicalLoopInfo
7938 // object. We should have a method which returns all blocks between
7939 // CanonicalLoopInfo::getHeader() and CanonicalLoopInfo::getAfter()
7941 FAM.registerPass([]() { return DominatorTreeAnalysis(); });
7942 FAM.registerPass([]() { return LoopAnalysis(); });
7943 FAM.registerPass([]() { return PassInstrumentationAnalysis(); });
7944
7945 LoopAnalysis LIA;
7946 LoopInfo &&LI = LIA.run(*F, FAM);
7947
7948 for (Instruction *I : UIs)
7949 I->eraseFromParent();
7950
7951 Loop *L = LI.getLoopFor(CanonicalLoop->getHeader());
7952 if (AlignedVars.size()) {
7953 InsertPointTy IP = Builder.saveIP();
7954 for (auto &AlignedItem : AlignedVars) {
7955 Value *AlignedPtr = AlignedItem.first;
7956 Value *Alignment = AlignedItem.second;
7957 Instruction *loadInst = dyn_cast<Instruction>(AlignedPtr);
7958 Builder.SetInsertPoint(loadInst->getNextNode());
7959 Builder.CreateAlignmentAssumption(F->getDataLayout(), AlignedPtr,
7960 Alignment);
7961 }
7962 Builder.restoreIP(IP);
7963 }
7964
7965 if (IfCond) {
7966 ValueToValueMapTy VMap;
7967 createIfVersion(CanonicalLoop, IfCond, VMap, LIA, LI, L, "simd");
7968 }
7969
7971
7972 // Get the basic blocks from the loop in which memref instructions
7973 // can be found.
7974 // TODO: Generalize getting all blocks inside a CanonicalizeLoopInfo,
7975 // preferably without running any passes.
7976 for (BasicBlock *Block : L->getBlocks()) {
7977 if (Block == CanonicalLoop->getCond() ||
7978 Block == CanonicalLoop->getHeader())
7979 continue;
7980 Reachable.insert(Block);
7981 }
7982
7983 SmallVector<Metadata *> LoopMDList;
7984
7985 // In presence of finite 'safelen', it may be unsafe to mark all
7986 // the memory instructions parallel, because loop-carried
7987 // dependences of 'safelen' iterations are possible.
7988 // If clause order(concurrent) is specified then the memory instructions
7989 // are marked parallel even if 'safelen' is finite.
7990 if ((Safelen == nullptr) || (Order == OrderKind::OMP_ORDER_concurrent))
7991 applyParallelAccessesMetadata(CanonicalLoop, Ctx, L, LI, LoopMDList);
7992
7993 // FIXME: the IF clause shares a loop backedge for the SIMD and non-SIMD
7994 // versions so we can't add the loop attributes in that case.
7995 if (IfCond) {
7996 // we can still add llvm.loop.parallel_access
7997 addLoopMetadata(CanonicalLoop, LoopMDList);
7998 return;
7999 }
8000
8001 // Use the above access group metadata to create loop level
8002 // metadata, which should be distinct for each loop.
8003 LoopMDList.push_back(
8004 MDNode::get(Ctx, {MDString::get(Ctx, "llvm.loop.vectorize.enable")}));
8005
8006 if (Simdlen || Safelen) {
8007 // If both simdlen and safelen clauses are specified, the value of the
8008 // simdlen parameter must be less than or equal to the value of the safelen
8009 // parameter. Therefore, use safelen only in the absence of simdlen.
8010 ConstantInt *VectorizeWidth = Simdlen == nullptr ? Safelen : Simdlen;
8011 LoopMDList.push_back(
8012 MDNode::get(Ctx, {MDString::get(Ctx, "llvm.loop.vectorize.width"),
8013 ConstantAsMetadata::get(VectorizeWidth)}));
8014 }
8015
8016 addLoopMetadata(CanonicalLoop, LoopMDList);
8017}
8018
8020 int32_t Factor,
8021 CanonicalLoopInfo **UnrolledCLI) {
8022 assert(Factor >= 0 && "Unroll factor must not be negative");
8023
8024 Function *F = Loop->getFunction();
8025 LLVMContext &Ctx = F->getContext();
8026
8027 // If the unrolled loop is not used for another loop-associated directive, it
8028 // is sufficient to add metadata for the LoopUnrollPass.
8029 if (!UnrolledCLI) {
8030 SmallVector<Metadata *, 2> LoopMetadata;
8031 LoopMetadata.push_back(
8032 MDNode::get(Ctx, MDString::get(Ctx, "llvm.loop.unroll.enable")));
8033
8034 if (Factor >= 1) {
8036 ConstantInt::get(Type::getInt32Ty(Ctx), APInt(32, Factor)));
8037 LoopMetadata.push_back(MDNode::get(
8038 Ctx, {MDString::get(Ctx, "llvm.loop.unroll.count"), FactorConst}));
8039 }
8040
8041 addUnrollMetadata(Loop, LoopMetadata);
8042 return;
8043 }
8044
8045 if (Factor == 0) {
8046 if (Loop->VirtualCollapse)
8047 Loop->reportUnsupportedVirtualCollapse();
8049 }
8050
8051 // No change required with unroll factor 1.
8052 if (Factor == 1) {
8053 *UnrolledCLI = Loop;
8054 return;
8055 }
8056
8057 assert(Factor >= 2 &&
8058 "unrolling only makes sense with a factor of 2 or larger");
8059
8060 Type *IndVarTy = Loop->getIndVarType();
8061
8062 // Apply partial unrolling by tiling the loop by the unroll-factor, then fully
8063 // unroll the inner loop.
8064 Value *FactorVal =
8065 ConstantInt::get(IndVarTy, APInt(IndVarTy->getIntegerBitWidth(), Factor,
8066 /*isSigned=*/false));
8067 std::vector<CanonicalLoopInfo *> LoopNest =
8068 tileLoops(DL, {Loop}, {FactorVal});
8069 assert(LoopNest.size() == 2 && "Expect 2 loops after tiling");
8070 *UnrolledCLI = LoopNest[0];
8071 CanonicalLoopInfo *InnerLoop = LoopNest[1];
8072
8073 // LoopUnrollPass can only fully unroll loops with constant trip count.
8074 // Unroll by the unroll factor with a fallback epilog for the remainder
8075 // iterations if necessary.
8077 ConstantInt::get(Type::getInt32Ty(Ctx), APInt(32, Factor)));
8079 InnerLoop,
8080 {MDNode::get(Ctx, MDString::get(Ctx, "llvm.loop.unroll.enable")),
8082 Ctx, {MDString::get(Ctx, "llvm.loop.unroll.count"), FactorConst})});
8083
8084#ifndef NDEBUG
8085 (*UnrolledCLI)->assertOK();
8086#endif
8087}
8088
8091 llvm::Value *BufSize, llvm::Value *CpyBuf,
8092 llvm::Value *CpyFn, llvm::Value *DidIt) {
8093 if (!updateToLocation(Loc))
8094 return Loc.IP;
8095
8096 uint32_t SrcLocStrSize;
8097 Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
8098 Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
8099 Value *ThreadId = getOrCreateThreadID(Ident);
8100
8101 llvm::Value *DidItLD = Builder.CreateLoad(Builder.getInt32Ty(), DidIt);
8102
8103 Value *Args[] = {Ident, ThreadId, BufSize, CpyBuf, CpyFn, DidItLD};
8104
8105 Function *Fn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_copyprivate);
8106 createRuntimeFunctionCall(Fn, Args);
8107
8108 return Builder.saveIP();
8109}
8110
8112 const LocationDescription &Loc, BodyGenCallbackTy BodyGenCB,
8113 FinalizeCallbackTy FiniCB, bool IsNowait, ArrayRef<llvm::Value *> CPVars,
8115
8116 if (!updateToLocation(Loc))
8117 return Loc.IP;
8118
8119 // If needed allocate and initialize `DidIt` with 0.
8120 // DidIt: flag variable: 1=single thread; 0=not single thread.
8121 llvm::Value *DidIt = nullptr;
8122 if (!CPVars.empty()) {
8123 DidIt = Builder.CreateAlloca(llvm::Type::getInt32Ty(Builder.getContext()));
8124 Builder.CreateStore(Builder.getInt32(0), DidIt);
8125 }
8126
8127 Directive OMPD = Directive::OMPD_single;
8128 uint32_t SrcLocStrSize;
8129 Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
8130 Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
8131 Value *ThreadId = getOrCreateThreadID(Ident);
8132 Value *Args[] = {Ident, ThreadId};
8133
8134 Function *EntryRTLFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_single);
8135 Instruction *EntryCall = createRuntimeFunctionCall(EntryRTLFn, Args);
8136
8137 Function *ExitRTLFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_end_single);
8138 Instruction *ExitCall = createRuntimeFunctionCall(ExitRTLFn, Args);
8139
8140 auto FiniCBWrapper = [&](InsertPointTy IP) -> Error {
8141 if (Error Err = FiniCB(IP))
8142 return Err;
8143
8144 // The thread that executes the single region must set `DidIt` to 1.
8145 // This is used by __kmpc_copyprivate, to know if the caller is the
8146 // single thread or not.
8147 if (DidIt)
8148 Builder.CreateStore(Builder.getInt32(1), DidIt);
8149
8150 return Error::success();
8151 };
8152
8153 // generates the following:
8154 // if (__kmpc_single()) {
8155 // .... single region ...
8156 // __kmpc_end_single
8157 // }
8158 // __kmpc_copyprivate
8159 // __kmpc_barrier
8160
8161 InsertPointOrErrorTy AfterIP =
8162 EmitOMPInlinedRegion(OMPD, EntryCall, ExitCall, BodyGenCB, FiniCBWrapper,
8163 /*Conditional*/ true,
8164 /*hasFinalize*/ true);
8165 if (!AfterIP)
8166 return AfterIP.takeError();
8167
8168 if (DidIt) {
8169 for (size_t I = 0, E = CPVars.size(); I < E; ++I)
8170 // NOTE BufSize is currently unused, so just pass 0.
8172 /*BufSize=*/ConstantInt::get(Int64, 0), CPVars[I],
8173 CPFuncs[I], DidIt);
8174 // NOTE __kmpc_copyprivate already inserts a barrier
8175 } else if (!IsNowait) {
8176 InsertPointOrErrorTy AfterIP =
8178 omp::Directive::OMPD_unknown, /* ForceSimpleCall */ false,
8179 /* CheckCancelFlag */ false);
8180 if (!AfterIP)
8181 return AfterIP.takeError();
8182 }
8183 return Builder.saveIP();
8184}
8185
8188 BodyGenCallbackTy BodyGenCB,
8189 FinalizeCallbackTy FiniCB, bool IsNowait) {
8190
8191 if (!updateToLocation(Loc))
8192 return Loc.IP;
8193
8194 // All threads execute the scope body — no conditional entry.
8195 InsertPointOrErrorTy AfterIP = EmitOMPInlinedRegion(
8196 Directive::OMPD_scope, /*EntryCall=*/nullptr, /*ExitCall=*/nullptr,
8197 BodyGenCB, FiniCB, /*Conditional=*/false, /*HasFinalize=*/true,
8198 /*IsCancellable=*/false);
8199 if (!AfterIP)
8200 return AfterIP.takeError();
8201
8202 Builder.restoreIP(*AfterIP);
8203 if (!IsNowait) {
8204 AfterIP = createBarrier(LocationDescription(Builder.saveIP(), Loc.DL),
8205 omp::Directive::OMPD_unknown,
8206 /*ForceSimpleCall=*/false,
8207 /*CheckCancelFlag=*/false);
8208 if (!AfterIP)
8209 return AfterIP.takeError();
8210 }
8211 return Builder.saveIP();
8212}
8213
8215 const LocationDescription &Loc, BodyGenCallbackTy BodyGenCB,
8216 FinalizeCallbackTy FiniCB, StringRef CriticalName, Value *HintInst) {
8217
8218 if (!updateToLocation(Loc))
8219 return Loc.IP;
8220
8221 Directive OMPD = Directive::OMPD_critical;
8222 uint32_t SrcLocStrSize;
8223 Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
8224 Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
8225 Value *ThreadId = getOrCreateThreadID(Ident);
8226 Value *LockVar = getOMPCriticalRegionLock(CriticalName);
8227 Value *Args[] = {Ident, ThreadId, LockVar};
8228
8229 SmallVector<llvm::Value *, 4> EnterArgs(std::begin(Args), std::end(Args));
8230 Function *RTFn = nullptr;
8231 if (HintInst) {
8232 // Add Hint to entry Args and create call
8233 EnterArgs.push_back(HintInst);
8234 RTFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_critical_with_hint);
8235 } else {
8236 RTFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_critical);
8237 }
8238 Instruction *EntryCall = createRuntimeFunctionCall(RTFn, EnterArgs);
8239
8240 Function *ExitRTLFn =
8241 getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_end_critical);
8242 Instruction *ExitCall = createRuntimeFunctionCall(ExitRTLFn, Args);
8243
8244 return EmitOMPInlinedRegion(OMPD, EntryCall, ExitCall, BodyGenCB, FiniCB,
8245 /*Conditional*/ false, /*hasFinalize*/ true);
8246}
8247
8250 InsertPointTy AllocaIP, unsigned NumLoops,
8251 ArrayRef<llvm::Value *> StoreValues,
8252 const Twine &Name, bool IsDependSource) {
8253 assert(
8254 llvm::all_of(StoreValues,
8255 [](Value *SV) { return SV->getType()->isIntegerTy(64); }) &&
8256 "OpenMP runtime requires depend vec with i64 type");
8257
8258 if (!updateToLocation(Loc))
8259 return Loc.IP;
8260
8261 // Allocate space for vector and generate alloc instruction.
8262 auto *ArrI64Ty = ArrayType::get(Int64, NumLoops);
8263 Builder.restoreIP(AllocaIP);
8264 AllocaInst *ArgsBase = Builder.CreateAlloca(ArrI64Ty, nullptr, Name);
8265 ArgsBase->setAlignment(Align(8));
8267
8268 // Store the index value with offset in depend vector.
8269 for (unsigned I = 0; I < NumLoops; ++I) {
8270 Value *DependAddrGEPIter = Builder.CreateInBoundsGEP(
8271 ArrI64Ty, ArgsBase, {Builder.getInt64(0), Builder.getInt64(I)});
8272 StoreInst *STInst = Builder.CreateStore(StoreValues[I], DependAddrGEPIter);
8273 STInst->setAlignment(Align(8));
8274 }
8275
8276 Value *DependBaseAddrGEP = Builder.CreateInBoundsGEP(
8277 ArrI64Ty, ArgsBase, {Builder.getInt64(0), Builder.getInt64(0)});
8278
8279 uint32_t SrcLocStrSize;
8280 Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
8281 Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
8282 Value *ThreadId = getOrCreateThreadID(Ident);
8283 Value *Args[] = {Ident, ThreadId, DependBaseAddrGEP};
8284
8285 Function *RTLFn = nullptr;
8286 if (IsDependSource)
8287 RTLFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_doacross_post);
8288 else
8289 RTLFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_doacross_wait);
8290 createRuntimeFunctionCall(RTLFn, Args);
8291
8292 return Builder.saveIP();
8293}
8294
8296 const LocationDescription &Loc, BodyGenCallbackTy BodyGenCB,
8297 FinalizeCallbackTy FiniCB, bool IsThreads) {
8298 if (!updateToLocation(Loc))
8299 return Loc.IP;
8300
8301 Directive OMPD = Directive::OMPD_ordered_blockassoc;
8302 Instruction *EntryCall = nullptr;
8303 Instruction *ExitCall = nullptr;
8304
8305 if (IsThreads) {
8306 uint32_t SrcLocStrSize;
8307 Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
8308 Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
8309 Value *ThreadId = getOrCreateThreadID(Ident);
8310 Value *Args[] = {Ident, ThreadId};
8311
8312 Function *EntryRTLFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_ordered);
8313 EntryCall = createRuntimeFunctionCall(EntryRTLFn, Args);
8314
8315 Function *ExitRTLFn =
8316 getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_end_ordered);
8317 ExitCall = createRuntimeFunctionCall(ExitRTLFn, Args);
8318 }
8319
8320 return EmitOMPInlinedRegion(OMPD, EntryCall, ExitCall, BodyGenCB, FiniCB,
8321 /*Conditional*/ false, /*hasFinalize*/ true);
8322}
8323
8324OpenMPIRBuilder::InsertPointOrErrorTy OpenMPIRBuilder::EmitOMPInlinedRegion(
8325 Directive OMPD, Instruction *EntryCall, Instruction *ExitCall,
8326 BodyGenCallbackTy BodyGenCB, FinalizeCallbackTy FiniCB, bool Conditional,
8327 bool HasFinalize, bool IsCancellable) {
8328
8329 if (HasFinalize)
8330 FinalizationStack.push_back({FiniCB, OMPD, IsCancellable});
8331
8332 // Create inlined region's entry and body blocks, in preparation
8333 // for conditional creation
8334 BasicBlock *EntryBB = Builder.GetInsertBlock();
8335 Instruction *SplitPos = EntryBB->getTerminatorOrNull();
8337 SplitPos = new UnreachableInst(Builder.getContext(), EntryBB);
8338 SplitPos->setDebugLoc(Builder.getCurrentDebugLocation());
8339 }
8340 BasicBlock *ExitBB = EntryBB->splitBasicBlock(SplitPos, "omp_region.end");
8341 BasicBlock *FiniBB =
8342 EntryBB->splitBasicBlock(EntryBB->getTerminator(), "omp_region.finalize");
8343
8344 Builder.SetInsertPoint(EntryBB->getTerminator());
8345 emitCommonDirectiveEntry(OMPD, EntryCall, ExitBB, Conditional);
8346
8347 // generate body
8348 if (Error Err =
8349 BodyGenCB(/* AllocaIP */ InsertPointTy(),
8350 /* CodeGenIP */ Builder.saveIP(), /* DeallocBlocks */ {}))
8351 return Err;
8352
8353 // emit exit call and do any needed finalization.
8354 auto FinIP = FiniBB->getFirstInsertionPt();
8355 assert(FiniBB->getTerminator()->getNumSuccessors() == 1 &&
8356 FiniBB->getTerminator()->getSuccessor(0) == ExitBB &&
8357 "Unexpected control flow graph state!!");
8358 InsertPointOrErrorTy AfterIP =
8359 emitCommonDirectiveExit(OMPD, FinIP, ExitCall, HasFinalize);
8360 if (!AfterIP)
8361 return AfterIP.takeError();
8362
8363 // If we are skipping the region of a non conditional, remove the exit
8364 // block, and clear the builder's insertion point.
8365 assert(SplitPos->getParent() == ExitBB &&
8366 "Unexpected Insertion point location!");
8367 auto merged = MergeBlockIntoPredecessor(ExitBB);
8368 BasicBlock *ExitPredBB = SplitPos->getParent();
8369 auto InsertBB = merged ? ExitPredBB : ExitBB;
8371 SplitPos->eraseFromParent();
8372 Builder.SetInsertPoint(InsertBB);
8373
8374 return Builder.saveIP();
8375}
8376
8377OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::emitCommonDirectiveEntry(
8378 Directive OMPD, Value *EntryCall, BasicBlock *ExitBB, bool Conditional) {
8379 // if nothing to do, Return current insertion point.
8380 if (!Conditional || !EntryCall)
8381 return Builder.saveIP();
8382
8383 BasicBlock *EntryBB = Builder.GetInsertBlock();
8384 Value *CallBool = Builder.CreateIsNotNull(EntryCall);
8385 auto *ThenBB = BasicBlock::Create(M.getContext(), "omp_region.body");
8386 auto *UI = new UnreachableInst(Builder.getContext(), ThenBB);
8387
8388 // Emit thenBB and set the Builder's insertion point there for
8389 // body generation next. Place the block after the current block.
8390 Function *CurFn = EntryBB->getParent();
8391 CurFn->insert(std::next(EntryBB->getIterator()), ThenBB);
8392
8393 // Move Entry branch to end of ThenBB, and replace with conditional
8394 // branch (If-stmt)
8395 Instruction *EntryBBTI = EntryBB->getTerminator();
8396 Builder.CreateCondBr(CallBool, ThenBB, ExitBB);
8397 EntryBBTI->removeFromParent();
8398 Builder.SetInsertPoint(UI);
8399 Builder.Insert(EntryBBTI);
8400 UI->eraseFromParent();
8401 Builder.SetInsertPoint(ThenBB->getTerminator());
8402
8403 // return an insertion point to ExitBB.
8404 return ExitBB->getFirstInsertionPt();
8405}
8406
8407OpenMPIRBuilder::InsertPointOrErrorTy OpenMPIRBuilder::emitCommonDirectiveExit(
8408 omp::Directive OMPD, InsertPointTy FinIP, Instruction *ExitCall,
8409 bool HasFinalize) {
8410
8411 Builder.restoreIP(FinIP);
8412
8413 // If there is finalization to do, emit it before the exit call
8414 if (HasFinalize) {
8415 assert(!FinalizationStack.empty() &&
8416 "Unexpected finalization stack state!");
8417
8418 FinalizationInfo Fi = FinalizationStack.pop_back_val();
8419 assert(Fi.DK == OMPD && "Unexpected Directive for Finalization call!");
8420
8421 BasicBlock *FinBB = FinIP.getNodeParent();
8422 if (Error Err = Fi.mergeFiniBB(Builder, FinBB))
8423 return std::move(Err);
8424
8425 // Exit condition: insertion point is before the terminator of the new Fini
8426 // block
8427 Builder.SetInsertPoint(FinBB->getTerminator());
8428 }
8429
8430 if (!ExitCall)
8431 return Builder.saveIP();
8432
8433 // place the Exitcall as last instruction before Finalization block terminator
8434 ExitCall->removeFromParent();
8435 Builder.Insert(ExitCall);
8436
8437 return ExitCall->getIterator();
8438}
8439
8441 InsertPointTy IP, Value *MasterAddr, Value *PrivateAddr,
8442 llvm::IntegerType *IntPtrTy, bool BranchtoEnd) {
8443 if (!IP.isValid())
8444 return IP;
8445
8447
8448 // creates the following CFG structure
8449 // OMP_Entry : (MasterAddr != PrivateAddr)?
8450 // F T
8451 // | \
8452 // | copin.not.master
8453 // | /
8454 // v /
8455 // copyin.not.master.end
8456 // |
8457 // v
8458 // OMP.Entry.Next
8459
8460 BasicBlock *OMP_Entry = IP.getNodeParent();
8461 Function *CurFn = OMP_Entry->getParent();
8462 BasicBlock *CopyBegin =
8463 BasicBlock::Create(M.getContext(), "copyin.not.master", CurFn);
8464 BasicBlock *CopyEnd = nullptr;
8465
8466 // If entry block is terminated, split to preserve the branch to following
8467 // basic block (i.e. OMP.Entry.Next), otherwise, leave everything as is.
8469 CopyEnd = OMP_Entry->splitBasicBlock(OMP_Entry->getTerminator(),
8470 "copyin.not.master.end");
8471 OMP_Entry->getTerminator()->eraseFromParent();
8472 } else {
8473 CopyEnd =
8474 BasicBlock::Create(M.getContext(), "copyin.not.master.end", CurFn);
8475 }
8476
8477 Builder.SetInsertPoint(OMP_Entry);
8478 Value *MasterPtr = Builder.CreatePtrToInt(MasterAddr, IntPtrTy);
8479 Value *PrivatePtr = Builder.CreatePtrToInt(PrivateAddr, IntPtrTy);
8480 Value *cmp = Builder.CreateICmpNE(MasterPtr, PrivatePtr);
8481 Builder.CreateCondBr(cmp, CopyBegin, CopyEnd);
8482
8483 Builder.SetInsertPoint(CopyBegin);
8484 if (BranchtoEnd)
8485 Builder.SetInsertPoint(Builder.CreateBr(CopyEnd));
8486
8487 return Builder.saveIP();
8488}
8489
8491 Value *Size, Value *Allocator,
8492 std::string Name) {
8494 if (!updateToLocation(Loc))
8495 return nullptr;
8496
8497 uint32_t SrcLocStrSize;
8498 Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
8499 Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
8500 Value *ThreadId = getOrCreateThreadID(Ident);
8501 Value *Args[] = {ThreadId, Size, Allocator};
8502
8503 Function *Fn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_alloc);
8504
8505 return createRuntimeFunctionCall(Fn, Args, Name);
8506}
8507
8509 Value *Align, Value *Size,
8510 Value *Allocator,
8511 std::string Name) {
8513 if (!updateToLocation(Loc))
8514 return nullptr;
8515
8516 uint32_t SrcLocStrSize;
8517 Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
8518 Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
8519 Value *ThreadId = getOrCreateThreadID(Ident);
8520 Value *Args[] = {ThreadId, Align, Size, Allocator};
8521
8522 Function *Fn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_aligned_alloc);
8523
8524 return Builder.CreateCall(Fn, Args, Name);
8525}
8526
8528 Value *Addr, Value *Allocator,
8529 std::string Name) {
8531 if (!updateToLocation(Loc))
8532 return nullptr;
8533
8534 uint32_t SrcLocStrSize;
8535 Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
8536 Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
8537 Value *ThreadId = getOrCreateThreadID(Ident);
8538 Value *Args[] = {ThreadId, Addr, Allocator};
8539 Function *Fn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_free);
8540 return createRuntimeFunctionCall(Fn, Args, Name);
8541}
8542
8544 Value *Size,
8545 const Twine &Name) {
8548
8549 Value *Args[] = {Size};
8550 Function *Fn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_alloc_shared);
8551 CallInst *Call = Builder.CreateCall(Fn, Args, Name);
8553 M.getContext(), M.getDataLayout().getPrefTypeAlign(Int64)));
8554 return Call;
8555}
8556
8558 Type *VarType,
8559 const Twine &Name) {
8560 return createOMPAllocShared(
8561 Loc, Builder.getInt64(M.getDataLayout().getTypeAllocSize(VarType)), Name);
8562}
8563
8565 Value *Addr, Value *Size,
8566 const Twine &Name) {
8569
8570 Value *Args[] = {Addr, Size};
8571 Function *Fn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_free_shared);
8572 return Builder.CreateCall(Fn, Args, Name);
8573}
8574
8576 Value *Addr, Type *VarType,
8577 const Twine &Name) {
8578 return createOMPFreeShared(
8579 Loc, Addr, Builder.getInt64(M.getDataLayout().getTypeAllocSize(VarType)),
8580 Name);
8581}
8582
8584 const LocationDescription &Loc, Value *InteropVar,
8586 Value *DependenceAddress, bool HaveNowaitClause) {
8589
8590 uint32_t SrcLocStrSize;
8591 Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
8592 Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
8593 Value *ThreadId = getOrCreateThreadID(Ident);
8594 if (Device == nullptr)
8596 else if (Device->getType() != Int32)
8597 Device = Builder.CreateIntCast(Device, Int32, /*isSigned=*/true);
8598 Constant *InteropTypeVal = ConstantInt::get(Int32, (int)InteropType);
8599 if (NumDependences == nullptr) {
8600 NumDependences = ConstantInt::get(Int32, 0);
8601 PointerType *PointerTypeVar = PointerType::getUnqual(M.getContext());
8602 DependenceAddress = ConstantPointerNull::get(PointerTypeVar);
8603 }
8604 Value *HaveNowaitClauseVal = ConstantInt::get(Int32, HaveNowaitClause);
8605 Value *Args[] = {
8606 Ident, ThreadId, InteropVar, InteropTypeVal,
8607 Device, NumDependences, DependenceAddress, HaveNowaitClauseVal};
8608
8609 Function *Fn = getOrCreateRuntimeFunctionPtr(OMPRTL___tgt_interop_init);
8610
8611 return createRuntimeFunctionCall(Fn, Args);
8612}
8613
8615 const LocationDescription &Loc, Value *InteropVar, Value *Device,
8616 Value *NumDependences, Value *DependenceAddress, bool HaveNowaitClause) {
8619
8620 uint32_t SrcLocStrSize;
8621 Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
8622 Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
8623 Value *ThreadId = getOrCreateThreadID(Ident);
8624 if (Device == nullptr)
8626 else if (Device->getType() != Int32)
8627 Device = Builder.CreateIntCast(Device, Int32, /*isSigned=*/true);
8628 if (NumDependences == nullptr) {
8629 NumDependences = ConstantInt::get(Int32, 0);
8630 PointerType *PointerTypeVar = PointerType::getUnqual(M.getContext());
8631 DependenceAddress = ConstantPointerNull::get(PointerTypeVar);
8632 }
8633 Value *HaveNowaitClauseVal = ConstantInt::get(Int32, HaveNowaitClause);
8634 Value *Args[] = {
8635 Ident, ThreadId, InteropVar, Device,
8636 NumDependences, DependenceAddress, HaveNowaitClauseVal};
8637
8638 Function *Fn = getOrCreateRuntimeFunctionPtr(OMPRTL___tgt_interop_destroy);
8639
8640 return createRuntimeFunctionCall(Fn, Args);
8641}
8642
8644 Value *InteropVar, Value *Device,
8645 Value *NumDependences,
8646 Value *DependenceAddress,
8647 bool HaveNowaitClause) {
8650 uint32_t SrcLocStrSize;
8651 Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
8652 Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
8653 Value *ThreadId = getOrCreateThreadID(Ident);
8654 if (Device == nullptr)
8656 else if (Device->getType() != Int32)
8657 Device = Builder.CreateIntCast(Device, Int32, /*isSigned=*/true);
8658 if (NumDependences == nullptr) {
8659 NumDependences = ConstantInt::get(Int32, 0);
8660 PointerType *PointerTypeVar = PointerType::getUnqual(M.getContext());
8661 DependenceAddress = ConstantPointerNull::get(PointerTypeVar);
8662 }
8663 Value *HaveNowaitClauseVal = ConstantInt::get(Int32, HaveNowaitClause);
8664 Value *Args[] = {
8665 Ident, ThreadId, InteropVar, Device,
8666 NumDependences, DependenceAddress, HaveNowaitClauseVal};
8667
8668 Function *Fn = getOrCreateRuntimeFunctionPtr(OMPRTL___tgt_interop_use);
8669
8670 return createRuntimeFunctionCall(Fn, Args);
8671}
8672
8675 llvm::ConstantInt *Size, const llvm::Twine &Name) {
8678
8679 uint32_t SrcLocStrSize;
8680 Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
8681 Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
8682 Value *ThreadId = getOrCreateThreadID(Ident);
8683 Constant *ThreadPrivateCache =
8684 getOrCreateInternalVariable(Int8PtrPtr, Name.str());
8685 llvm::Value *Args[] = {Ident, ThreadId, Pointer, Size, ThreadPrivateCache};
8686
8687 Function *Fn =
8688 getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_threadprivate_cached);
8689
8690 return createRuntimeFunctionCall(Fn, Args);
8691}
8692
8694 const LocationDescription &Loc,
8696 assert(!Attrs.MaxThreads.empty() && !Attrs.MaxTeams.empty() &&
8697 "expected num_threads and num_teams to be specified");
8698
8699 if (!updateToLocation(Loc))
8700 return nullptr;
8701
8702 uint32_t SrcLocStrSize;
8703 Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
8704 Constant *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
8705 Constant *IsSPMDVal = ConstantInt::getSigned(Int8, Attrs.ExecFlags);
8706 Constant *UseGenericStateMachineVal = ConstantInt::getSigned(
8707 Int8, Attrs.ExecFlags != omp::OMP_TGT_EXEC_MODE_SPMD &&
8708 Attrs.ExecFlags != omp::OMP_TGT_EXEC_MODE_SPMD_NO_LOOP);
8709 Constant *MayUseNestedParallelismVal = ConstantInt::getSigned(Int8, true);
8710 Constant *DebugIndentionLevelVal = ConstantInt::getSigned(Int16, 0);
8711
8712 Function *DebugKernelWrapper = Builder.GetInsertBlock()->getParent();
8713 Function *Kernel = DebugKernelWrapper;
8714
8715 // We need to strip the debug prefix to get the correct kernel name.
8716 StringRef KernelName = Kernel->getName();
8717 const std::string DebugPrefix = "_debug__";
8718 if (KernelName.ends_with(DebugPrefix)) {
8719 KernelName = KernelName.drop_back(DebugPrefix.length());
8720 Kernel = M.getFunction(KernelName);
8721 assert(Kernel && "Expected the real kernel to exist");
8722 }
8723
8724 // Manifest the launch configuration in the metadata matching the kernel
8725 // environment.
8726 if (Attrs.MinTeams.front() > 1 || Attrs.MaxTeams.front() > 0)
8727 writeTeamsForKernel(T, *Kernel, Attrs.MinTeams.front(),
8728 Attrs.MaxTeams.front());
8729
8730 // Don't derive or write thread bounds for Bare kernels.
8731 int32_t MaxThreadsVal = Attrs.MaxThreads.front();
8732 if (Attrs.ExecFlags != omp::OMP_TGT_EXEC_MODE_BARE) {
8733 // If MaxThreads is not set and needs adjustment, select the maximum
8734 // between the default workgroup size and the MinThreads value. This is
8735 // only meaningful for targets with a known grid value (i.e. GPUs); for
8736 // other targets (e.g. host kernels) leave it unset so the runtime falls
8737 // back to its own device-specific default.
8738 if (MaxThreadsVal < 0 && UseDefaultMaxThreads && hasGridValue(T))
8739 MaxThreadsVal =
8740 std::max(int32_t(getGridValue(T, Kernel).GV_Default_WG_Size),
8741 Attrs.MinThreads.front());
8742
8743 // Generic mode runs the main thread on a warp of its own, past
8744 // thread_limit. Reserve the widest warp any target has. Not on SPIR-V,
8745 // causes problems with Level Zero.
8746 if (MaxThreadsVal > 0 &&
8747 Attrs.ExecFlags == omp::OMP_TGT_EXEC_MODE_GENERIC && hasGridValue(T) &&
8748 !T.isSPIRV())
8749 MaxThreadsVal = int32_t(
8750 std::min<int64_t>(int64_t(MaxThreadsVal) + 64,
8751 int64_t(getGridValue(T, Kernel).GV_Max_WG_Size)));
8752
8753 if (MaxThreadsVal > 0)
8754 writeThreadBoundsForKernel(T, *Kernel, Attrs.MinThreads.front(),
8755 MaxThreadsVal);
8756 }
8757
8758 Constant *MinThreads =
8759 ConstantInt::getSigned(Int32, Attrs.MinThreads.front());
8760 Constant *MaxThreads = ConstantInt::getSigned(Int32, MaxThreadsVal);
8761 Constant *MinTeams = ConstantInt::getSigned(Int32, Attrs.MinTeams.front());
8762 Constant *MaxTeams = ConstantInt::getSigned(Int32, Attrs.MaxTeams.front());
8763 Constant *ReductionDataSize =
8764 ConstantInt::getSigned(Int32, Attrs.ReductionDataSize);
8765
8766 const DataLayout &DL = M.getDataLayout();
8767
8768 Twine DynamicEnvironmentName = KernelName + "_dynamic_environment";
8769 Constant *DynamicEnvironmentInitializer =
8770 ConstantStruct::get(DynamicEnvironment, {DebugIndentionLevelVal});
8771 GlobalVariable *DynamicEnvironmentGV = new GlobalVariable(
8772 M, DynamicEnvironment, /*IsConstant=*/false, GlobalValue::WeakODRLinkage,
8773 DynamicEnvironmentInitializer, DynamicEnvironmentName,
8774 /*InsertBefore=*/nullptr, GlobalValue::NotThreadLocal,
8775 DL.getDefaultGlobalsAddressSpace());
8776 DynamicEnvironmentGV->setVisibility(GlobalValue::ProtectedVisibility);
8777
8778 Constant *DynamicEnvironment =
8779 DynamicEnvironmentGV->getType() == DynamicEnvironmentPtr
8780 ? DynamicEnvironmentGV
8781 : ConstantExpr::getAddrSpaceCast(DynamicEnvironmentGV,
8782 DynamicEnvironmentPtr);
8783
8784 Constant *ConfigurationEnvironmentInitializer = ConstantStruct::get(
8785 ConfigurationEnvironment, {
8786 UseGenericStateMachineVal,
8787 MayUseNestedParallelismVal,
8788 IsSPMDVal,
8789 MinThreads,
8790 MaxThreads,
8791 MinTeams,
8792 MaxTeams,
8793 ReductionDataSize,
8794 });
8795 Constant *KernelEnvironmentInitializer = ConstantStruct::get(
8796 KernelEnvironment, {
8797 ConfigurationEnvironmentInitializer,
8798 Ident,
8799 DynamicEnvironment,
8800 });
8801 std::string KernelEnvironmentName =
8802 (KernelName + "_kernel_environment").str();
8803 GlobalVariable *KernelEnvironmentGV = new GlobalVariable(
8804 M, KernelEnvironment, /*IsConstant=*/true, GlobalValue::WeakODRLinkage,
8805 KernelEnvironmentInitializer, KernelEnvironmentName,
8806 /*InsertBefore=*/nullptr, GlobalValue::NotThreadLocal,
8807 DL.getDefaultGlobalsAddressSpace());
8808 KernelEnvironmentGV->setVisibility(GlobalValue::ProtectedVisibility);
8809
8810 return KernelEnvironmentGV->getType() == KernelEnvironmentPtr
8811 ? KernelEnvironmentGV
8812 : ConstantExpr::getAddrSpaceCast(KernelEnvironmentGV,
8813 KernelEnvironmentPtr);
8814}
8815
8817 const LocationDescription &Loc,
8819 Constant *KernelEnvironment = emitKernelEnvironment(Loc, Attrs);
8820 if (!KernelEnvironment)
8821 return Loc.IP;
8822
8823 if (!updateToLocation(Loc))
8824 return Loc.IP;
8825
8826 Function *DebugKernelWrapper = Builder.GetInsertBlock()->getParent();
8828 omp::RuntimeFunction::OMPRTL___kmpc_target_init);
8829
8830 Value *KernelLaunchEnvironment =
8831 DebugKernelWrapper->getArg(DebugKernelWrapper->arg_size() - 1);
8832 Type *KernelLaunchEnvParamTy = Fn->getFunctionType()->getParamType(1);
8833 KernelLaunchEnvironment =
8834 KernelLaunchEnvironment->getType() == KernelLaunchEnvParamTy
8835 ? KernelLaunchEnvironment
8836 : Builder.CreateAddrSpaceCast(KernelLaunchEnvironment,
8837 KernelLaunchEnvParamTy);
8838 CallInst *ThreadKind = createRuntimeFunctionCall(
8839 Fn, {KernelEnvironment, KernelLaunchEnvironment});
8840
8841 Value *ExecUserCode = Builder.CreateICmpEQ(
8842 ThreadKind, Constant::getAllOnesValue(ThreadKind->getType()),
8843 "exec_user_code");
8844
8845 // ThreadKind = __kmpc_target_init(...)
8846 // if (ThreadKind == -1)
8847 // user_code
8848 // else
8849 // return;
8850
8851 auto *UI = Builder.CreateUnreachable();
8852 BasicBlock *CheckBB = UI->getParent();
8853 BasicBlock *UserCodeEntryBB = CheckBB->splitBasicBlock(UI, "user_code.entry");
8854
8855 BasicBlock *WorkerExitBB = BasicBlock::Create(
8856 CheckBB->getContext(), "worker.exit", CheckBB->getParent());
8857 Builder.SetInsertPoint(WorkerExitBB);
8858 Builder.CreateRetVoid();
8859
8860 auto *CheckBBTI = CheckBB->getTerminator();
8861 Builder.SetInsertPoint(CheckBBTI);
8862 Builder.CreateCondBr(ExecUserCode, UI->getParent(), WorkerExitBB);
8863
8864 CheckBBTI->eraseFromParent();
8865 UI->eraseFromParent();
8866
8867 // Continue in the "user_code" block, see diagram above and in
8868 // openmp/libomptarget/deviceRTLs/common/include/target.h .
8869 return UserCodeEntryBB->getFirstInsertionPt();
8870}
8871
8873 int32_t TeamsReductionDataSize) {
8874 if (!updateToLocation(Loc))
8875 return;
8876
8878 omp::RuntimeFunction::OMPRTL___kmpc_target_deinit);
8879
8881
8882 if (!TeamsReductionDataSize)
8883 return;
8884
8885 Function *Kernel = Builder.GetInsertBlock()->getParent();
8886 // We need to strip the debug prefix to get the correct kernel name.
8887 StringRef KernelName = Kernel->getName();
8888 const std::string DebugPrefix = "_debug__";
8889 if (KernelName.ends_with(DebugPrefix))
8890 KernelName = KernelName.drop_back(DebugPrefix.length());
8891 auto *KernelEnvironmentGV =
8892 M.getNamedGlobal((KernelName + "_kernel_environment").str());
8893 assert(KernelEnvironmentGV && "Expected kernel environment global\n");
8894 auto *KernelEnvironmentInitializer = KernelEnvironmentGV->getInitializer();
8895 auto *NewInitializer = ConstantFoldInsertValueInstruction(
8896 KernelEnvironmentInitializer,
8897 ConstantInt::get(Int32, TeamsReductionDataSize), {0, 7});
8898 KernelEnvironmentGV->setInitializer(NewInitializer);
8899}
8900
8901static void updateNVPTXAttr(Function &Kernel, StringRef Name, int32_t Value,
8902 bool Min) {
8903 if (Kernel.hasFnAttribute(Name)) {
8904 int32_t OldLimit = Kernel.getFnAttributeAsParsedInteger(Name);
8905 Value = Min ? std::min(OldLimit, Value) : std::max(OldLimit, Value);
8906 }
8907 Kernel.addFnAttr(Name, llvm::utostr(Value));
8908}
8909
8910std::pair<int32_t, int32_t>
8912 int32_t ThreadLimit =
8913 Kernel.getFnAttributeAsParsedInteger("omp_target_thread_limit");
8914
8915 if (T.isAMDGPU()) {
8916 const auto &Attr = Kernel.getFnAttribute("amdgpu-flat-work-group-size");
8917 if (!Attr.isValid() || !Attr.isStringAttribute())
8918 return {0, ThreadLimit};
8919 auto [LBStr, UBStr] = Attr.getValueAsString().split(',');
8920 int32_t LB, UB;
8921 if (!llvm::to_integer(UBStr, UB, 10))
8922 return {0, ThreadLimit};
8923 UB = ThreadLimit ? std::min(ThreadLimit, UB) : UB;
8924 if (!llvm::to_integer(LBStr, LB, 10))
8925 return {0, UB};
8926 return {LB, UB};
8927 }
8928
8929 if (Kernel.hasFnAttribute(NVVMAttr::MaxNTID)) {
8930 int32_t UB = Kernel.getFnAttributeAsParsedInteger(NVVMAttr::MaxNTID);
8931 return {0, ThreadLimit ? std::min(ThreadLimit, UB) : UB};
8932 }
8933 return {0, ThreadLimit};
8934}
8935
8937 Function &Kernel, int32_t LB,
8938 int32_t UB) {
8939 Kernel.addFnAttr("omp_target_thread_limit", std::to_string(UB));
8940
8941 if (T.isAMDGPU()) {
8942 Kernel.addFnAttr("amdgpu-flat-work-group-size",
8943 llvm::utostr(LB) + "," + llvm::utostr(UB));
8944 return;
8945 }
8946
8948}
8949
8950std::pair<int32_t, int32_t>
8952 // TODO: Read from backend annotations if available.
8953 return {0, Kernel.getFnAttributeAsParsedInteger("omp_target_num_teams")};
8954}
8955
8957 int32_t LB, int32_t UB) {
8958 if (UB > 0) {
8959 if (T.isNVPTX())
8961 if (T.isAMDGPU())
8962 Kernel.addFnAttr("amdgpu-max-num-workgroups", llvm::utostr(UB) + ",1,1");
8963 }
8964
8965 Kernel.addFnAttr("omp_target_num_teams", std::to_string(LB));
8966}
8967
8968void OpenMPIRBuilder::setOutlinedTargetRegionFunctionAttributes(
8969 Function *OutlinedFn) {
8970 if (Config.isTargetDevice()) {
8972 // TODO: Determine if DSO local can be set to true.
8973 OutlinedFn->setDSOLocal(false);
8975 if (T.isAMDGCN())
8977 else if (T.isNVPTX())
8979 else if (T.isSPIRV())
8981 }
8982}
8983
8984Constant *OpenMPIRBuilder::createOutlinedFunctionID(Function *OutlinedFn,
8985 StringRef EntryFnIDName) {
8986 if (Config.isTargetDevice()) {
8987 assert(OutlinedFn && "The outlined function must exist if embedded");
8988 return OutlinedFn;
8989 }
8990
8991 return new GlobalVariable(
8992 M, Builder.getInt8Ty(), /*isConstant=*/true, GlobalValue::WeakAnyLinkage,
8993 Constant::getNullValue(Builder.getInt8Ty()), EntryFnIDName);
8994}
8995
8996Constant *OpenMPIRBuilder::createTargetRegionEntryAddr(Function *OutlinedFn,
8997 StringRef EntryFnName) {
8998 if (OutlinedFn)
8999 return OutlinedFn;
9000
9001 assert(!M.getGlobalVariable(EntryFnName, true) &&
9002 "Named kernel already exists?");
9003 return new GlobalVariable(
9004 M, Builder.getInt8Ty(), /*isConstant=*/true, GlobalValue::InternalLinkage,
9005 Constant::getNullValue(Builder.getInt8Ty()), EntryFnName);
9006}
9007
9009 TargetRegionEntryInfo &EntryInfo,
9010 FunctionGenCallback &GenerateFunctionCallback, bool IsOffloadEntry,
9011 Function *&OutlinedFn, Constant *&OutlinedFnID) {
9012
9013 SmallString<64> EntryFnName;
9014 OffloadInfoManager.getTargetRegionEntryFnName(EntryFnName, EntryInfo);
9015
9016 if (Config.isTargetDevice() || !Config.openMPOffloadMandatory()) {
9017 Expected<Function *> CBResult = GenerateFunctionCallback(EntryFnName);
9018 if (!CBResult)
9019 return CBResult.takeError();
9020 OutlinedFn = *CBResult;
9021 } else {
9022 OutlinedFn = nullptr;
9023 }
9024
9025 // If this target outline function is not an offload entry, we don't need to
9026 // register it. This may be in the case of a false if clause, or if there are
9027 // no OpenMP targets.
9028 if (!IsOffloadEntry)
9029 return Error::success();
9030
9031 std::string EntryFnIDName =
9032 Config.isTargetDevice()
9033 ? std::string(EntryFnName)
9034 : createPlatformSpecificName({EntryFnName, "region_id"});
9035
9036 OutlinedFnID = registerTargetRegionFunction(EntryInfo, OutlinedFn,
9037 EntryFnName, EntryFnIDName);
9038 return Error::success();
9039}
9040
9042 TargetRegionEntryInfo &EntryInfo, Function *OutlinedFn,
9043 StringRef EntryFnName, StringRef EntryFnIDName) {
9044 if (OutlinedFn)
9045 setOutlinedTargetRegionFunctionAttributes(OutlinedFn);
9046 auto OutlinedFnID = createOutlinedFunctionID(OutlinedFn, EntryFnIDName);
9047 auto EntryAddr = createTargetRegionEntryAddr(OutlinedFn, EntryFnName);
9048 OffloadInfoManager.registerTargetRegionEntryInfo(
9049 EntryInfo, EntryAddr, OutlinedFnID,
9051 return OutlinedFnID;
9052}
9053
9055 const LocationDescription &Loc, InsertPointTy AllocaIP,
9056 InsertPointTy CodeGenIP, ArrayRef<BasicBlock *> DeallocBlocks,
9057 Value *DeviceID, Value *IfCond, TargetDataInfo &Info,
9058 GenMapInfoCallbackTy GenMapInfoCB, CustomMapperCallbackTy CustomMapperCB,
9059 omp::RuntimeFunction *MapperFunc,
9061 BodyGenTy BodyGenType)>
9062 BodyGenCB,
9063 function_ref<void(unsigned int, Value *)> DeviceAddrCB, Value *SrcLocInfo) {
9064 if (!updateToLocation(Loc))
9065 return InsertPointTy();
9066
9067 Builder.restoreIP(CodeGenIP);
9068
9069 bool IsStandAlone = !BodyGenCB;
9070 MapInfosTy *MapInfo;
9071 // Generate the code for the opening of the data environment. Capture all the
9072 // arguments of the runtime call by reference because they are used in the
9073 // closing of the region.
9074 auto BeginThenGen = [&](InsertPointTy AllocaIP, InsertPointTy CodeGenIP,
9075 ArrayRef<BasicBlock *> DeallocBlocks) -> Error {
9076 MapInfo = &GenMapInfoCB(Builder.saveIP());
9077 if (Error Err = emitOffloadingArrays(
9078 AllocaIP, Builder.saveIP(), *MapInfo, Info, CustomMapperCB,
9079 /*IsNonContiguous=*/true, DeviceAddrCB))
9080 return Err;
9081
9082 TargetDataRTArgs RTArgs;
9084
9085 // Emit the number of elements in the offloading arrays.
9086 Value *PointerNum = Builder.getInt32(Info.NumberOfPtrs);
9087
9088 // Source location for the ident struct
9089 if (!SrcLocInfo) {
9090 uint32_t SrcLocStrSize;
9091 Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
9092 SrcLocInfo = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
9093 }
9094
9095 SmallVector<llvm::Value *, 13> OffloadingArgs = {
9096 SrcLocInfo, DeviceID,
9097 PointerNum, RTArgs.BasePointersArray,
9098 RTArgs.PointersArray, RTArgs.SizesArray,
9099 RTArgs.MapTypesArray, RTArgs.MapNamesArray,
9100 RTArgs.MappersArray};
9101
9102 if (IsStandAlone) {
9103 assert(MapperFunc && "MapperFunc missing for standalone target data");
9104
9105 auto TaskBodyCB = [&](Value *, Value *,
9107 if (Info.HasNoWait) {
9108 OffloadingArgs.append({llvm::Constant::getNullValue(Int32),
9112 }
9113
9115 OffloadingArgs);
9116
9117 if (Info.HasNoWait) {
9118 BasicBlock *OffloadContBlock =
9119 BasicBlock::Create(Builder.getContext(), "omp_offload.cont");
9120 Function *CurFn = Builder.GetInsertBlock()->getParent();
9121 emitBlock(OffloadContBlock, CurFn, /*IsFinished=*/true);
9122 Builder.restoreIP(Builder.saveIP());
9123 }
9124 return Error::success();
9125 };
9126
9127 bool RequiresOuterTargetTask = Info.HasNoWait;
9128 if (!RequiresOuterTargetTask)
9129 cantFail(TaskBodyCB(/*DeviceID=*/nullptr, /*RTLoc=*/nullptr,
9130 /*TargetTaskAllocaIP=*/{}));
9131 else
9132 cantFail(emitTargetTask(TaskBodyCB, DeviceID, SrcLocInfo, AllocaIP,
9133 /*Dependencies=*/{}, RTArgs, Info.HasNoWait));
9134 } else {
9135 Function *BeginMapperFunc = getOrCreateRuntimeFunctionPtr(
9136 omp::OMPRTL___tgt_target_data_begin_mapper);
9137
9138 createRuntimeFunctionCall(BeginMapperFunc, OffloadingArgs);
9139
9140 for (auto DeviceMap : Info.DevicePtrInfoMap) {
9141 if (isa<AllocaInst>(DeviceMap.second.second)) {
9142 auto *LI =
9143 Builder.CreateLoad(Builder.getPtrTy(), DeviceMap.second.first);
9144 Builder.CreateStore(LI, DeviceMap.second.second);
9145 }
9146 }
9147
9148 // If device pointer privatization is required, emit the body of the
9149 // region here. It will have to be duplicated: with and without
9150 // privatization.
9151 InsertPointOrErrorTy AfterIP =
9152 BodyGenCB(Builder.saveIP(), BodyGenTy::Priv);
9153 if (!AfterIP)
9154 return AfterIP.takeError();
9155 Builder.restoreIP(*AfterIP);
9156 }
9157 return Error::success();
9158 };
9159
9160 // If we need device pointer privatization, we need to emit the body of the
9161 // region with no privatization in the 'else' branch of the conditional.
9162 // Otherwise, we don't have to do anything.
9163 auto BeginElseGen = [&](InsertPointTy AllocaIP, InsertPointTy CodeGenIP,
9164 ArrayRef<BasicBlock *> DeallocBlocks) -> Error {
9165 InsertPointOrErrorTy AfterIP =
9166 BodyGenCB(Builder.saveIP(), BodyGenTy::DupNoPriv);
9167 if (!AfterIP)
9168 return AfterIP.takeError();
9169 Builder.restoreIP(*AfterIP);
9170 return Error::success();
9171 };
9172
9173 // Generate code for the closing of the data region.
9174 auto EndThenGen = [&](InsertPointTy AllocaIP, InsertPointTy CodeGenIP,
9175 ArrayRef<BasicBlock *> DeallocBlocks) {
9176 TargetDataRTArgs RTArgs;
9177 Info.EmitDebug = !MapInfo->Names.empty();
9178 emitOffloadingArraysArgument(Builder, RTArgs, Info, /*ForEndCall=*/true);
9179
9180 // Emit the number of elements in the offloading arrays.
9181 Value *PointerNum = Builder.getInt32(Info.NumberOfPtrs);
9182
9183 // Source location for the ident struct
9184 if (!SrcLocInfo) {
9185 uint32_t SrcLocStrSize;
9186 Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
9187 SrcLocInfo = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
9188 }
9189
9190 Value *OffloadingArgs[] = {SrcLocInfo, DeviceID,
9191 PointerNum, RTArgs.BasePointersArray,
9192 RTArgs.PointersArray, RTArgs.SizesArray,
9193 RTArgs.MapTypesArray, RTArgs.MapNamesArray,
9194 RTArgs.MappersArray};
9195 Function *EndMapperFunc =
9196 getOrCreateRuntimeFunctionPtr(omp::OMPRTL___tgt_target_data_end_mapper);
9197
9198 createRuntimeFunctionCall(EndMapperFunc, OffloadingArgs);
9199 return Error::success();
9200 };
9201
9202 // We don't have to do anything to close the region if the if clause evaluates
9203 // to false.
9204 auto EndElseGen = [&](InsertPointTy AllocaIP, InsertPointTy CodeGenIP,
9205 ArrayRef<BasicBlock *> DeallocBlocks) {
9206 return Error::success();
9207 };
9208
9209 Error Err = [&]() -> Error {
9210 if (BodyGenCB) {
9211 Error Err = [&]() {
9212 if (IfCond)
9213 return emitIfClause(IfCond, BeginThenGen, BeginElseGen, AllocaIP);
9214 return BeginThenGen(AllocaIP, Builder.saveIP(), DeallocBlocks);
9215 }();
9216
9217 if (Err)
9218 return Err;
9219
9220 // If we don't require privatization of device pointers, we emit the body
9221 // in between the runtime calls. This avoids duplicating the body code.
9222 InsertPointOrErrorTy AfterIP =
9223 BodyGenCB(Builder.saveIP(), BodyGenTy::NoPriv);
9224 if (!AfterIP)
9225 return AfterIP.takeError();
9226 restoreIPandDebugLoc(Builder, *AfterIP);
9227
9228 if (IfCond)
9229 return emitIfClause(IfCond, EndThenGen, EndElseGen, AllocaIP);
9230 return EndThenGen(AllocaIP, Builder.saveIP(), DeallocBlocks);
9231 }
9232 if (IfCond)
9233 return emitIfClause(IfCond, BeginThenGen, EndElseGen, AllocaIP);
9234 return BeginThenGen(AllocaIP, Builder.saveIP(), DeallocBlocks);
9235 }();
9236
9237 if (Err)
9238 return Err;
9239
9240 return Builder.saveIP();
9241}
9242
9245 bool IsGPUDistribute) {
9246 assert((IVSize == 32 || IVSize == 64) &&
9247 "IV size is not compatible with the omp runtime");
9248 RuntimeFunction Name;
9249 if (IsGPUDistribute)
9250 Name = IVSize == 32
9251 ? (IVSigned ? omp::OMPRTL___kmpc_distribute_static_init_4
9252 : omp::OMPRTL___kmpc_distribute_static_init_4u)
9253 : (IVSigned ? omp::OMPRTL___kmpc_distribute_static_init_8
9254 : omp::OMPRTL___kmpc_distribute_static_init_8u);
9255 else
9256 Name = IVSize == 32 ? (IVSigned ? omp::OMPRTL___kmpc_for_static_init_4
9257 : omp::OMPRTL___kmpc_for_static_init_4u)
9258 : (IVSigned ? omp::OMPRTL___kmpc_for_static_init_8
9259 : omp::OMPRTL___kmpc_for_static_init_8u);
9260
9261 return getOrCreateRuntimeFunction(M, Name);
9262}
9263
9265 bool IVSigned) {
9266 assert((IVSize == 32 || IVSize == 64) &&
9267 "IV size is not compatible with the omp runtime");
9268 RuntimeFunction Name = IVSize == 32
9269 ? (IVSigned ? omp::OMPRTL___kmpc_dispatch_init_4
9270 : omp::OMPRTL___kmpc_dispatch_init_4u)
9271 : (IVSigned ? omp::OMPRTL___kmpc_dispatch_init_8
9272 : omp::OMPRTL___kmpc_dispatch_init_8u);
9273
9274 return getOrCreateRuntimeFunction(M, Name);
9275}
9276
9278 bool IVSigned) {
9279 assert((IVSize == 32 || IVSize == 64) &&
9280 "IV size is not compatible with the omp runtime");
9281 RuntimeFunction Name = IVSize == 32
9282 ? (IVSigned ? omp::OMPRTL___kmpc_dispatch_next_4
9283 : omp::OMPRTL___kmpc_dispatch_next_4u)
9284 : (IVSigned ? omp::OMPRTL___kmpc_dispatch_next_8
9285 : omp::OMPRTL___kmpc_dispatch_next_8u);
9286
9287 return getOrCreateRuntimeFunction(M, Name);
9288}
9289
9291 bool IVSigned) {
9292 assert((IVSize == 32 || IVSize == 64) &&
9293 "IV size is not compatible with the omp runtime");
9294 RuntimeFunction Name = IVSize == 32
9295 ? (IVSigned ? omp::OMPRTL___kmpc_dispatch_fini_4
9296 : omp::OMPRTL___kmpc_dispatch_fini_4u)
9297 : (IVSigned ? omp::OMPRTL___kmpc_dispatch_fini_8
9298 : omp::OMPRTL___kmpc_dispatch_fini_8u);
9299
9300 return getOrCreateRuntimeFunction(M, Name);
9301}
9302
9304 return getOrCreateRuntimeFunction(M, omp::OMPRTL___kmpc_dispatch_deinit);
9305}
9306
9308 OpenMPIRBuilder &OMPBuilder, IRBuilderBase &Builder, Function *Func,
9309 DenseMap<Value *, std::tuple<Value *, unsigned>> &ValueReplacementMap) {
9310
9311 DISubprogram *NewSP = Func->getSubprogram();
9312 if (!NewSP)
9313 return;
9314
9316
9317 auto GetUpdatedDIVariable = [&](DILocalVariable *OldVar, unsigned arg) {
9318 DILocalVariable *&NewVar = RemappedVariables[OldVar];
9319 // Only use cached variable if the arg number matches. This is important
9320 // so that DIVariable created for privatized variables are not discarded.
9321 if (NewVar && (arg == NewVar->getArg()))
9322 return NewVar;
9323
9325 Builder.getContext(), OldVar->getScope(), OldVar->getName(),
9326 OldVar->getFile(), OldVar->getLine(), OldVar->getType(), arg,
9327 OldVar->getFlags(), OldVar->getAlignInBits(), OldVar->getAnnotations());
9328 return NewVar;
9329 };
9330
9331 auto UpdateDebugRecord = [&](auto *DR) {
9332 DILocalVariable *OldVar = DR->getVariable();
9333 unsigned ArgNo = 0;
9334 for (auto Loc : DR->location_ops()) {
9335 auto Iter = ValueReplacementMap.find(Loc);
9336 if (Iter != ValueReplacementMap.end()) {
9337 DR->replaceVariableLocationOp(Loc, std::get<0>(Iter->second));
9338 ArgNo = std::get<1>(Iter->second) + 1;
9339 }
9340 }
9341 if (ArgNo != 0)
9342 DR->setVariable(GetUpdatedDIVariable(OldVar, ArgNo));
9343 };
9344
9346 auto MoveDebugRecordToCorrectBlock = [&](DbgVariableRecord *DVR) {
9347 if (DVR->getNumVariableLocationOps() != 1u) {
9348 DVR->setKillLocation();
9349 return;
9350 }
9351 Value *Loc = DVR->getVariableLocationOp(0u);
9352 BasicBlock *CurBB = DVR->getParent();
9353 BasicBlock *RequiredBB = nullptr;
9354
9355 if (Instruction *LocInst = dyn_cast<Instruction>(Loc))
9356 RequiredBB = LocInst->getParent();
9357 else if (isa<llvm::Argument>(Loc))
9358 RequiredBB = &DVR->getFunction()->getEntryBlock();
9359
9360 if (RequiredBB && RequiredBB != CurBB) {
9361 assert(!RequiredBB->empty());
9362 RequiredBB->insertDbgRecordBefore(DVR->clone(),
9363 RequiredBB->back().getIterator());
9364 DVRsToDelete.push_back(DVR);
9365 }
9366 };
9367
9368 // The location and scope of variable records still point to
9369 // the parent function of the target region. Update them.
9370 for (Instruction &I : instructions(Func)) {
9371 for (DbgVariableRecord &DVR : filterDbgVars(I.getDbgRecordRange())) {
9372 UpdateDebugRecord(&DVR);
9373 MoveDebugRecordToCorrectBlock(&DVR);
9374 }
9375 }
9376 for (auto *DVR : DVRsToDelete)
9377 DVR->getMarker()->MarkedInstr->dropOneDbgRecord(DVR);
9378 // An extra argument is passed to the device. Create the debug data for it.
9379 if (OMPBuilder.Config.isTargetDevice()) {
9380 DICompileUnit *CU = NewSP->getUnit();
9381 Module *M = Func->getParent();
9382 DIBuilder DB(*M, true, CU);
9383 DIType *VoidPtrTy =
9384 DB.createQualifiedType(dwarf::DW_TAG_pointer_type, nullptr);
9385 unsigned ArgNo = Func->arg_size();
9386 DILocalVariable *Var = DB.createParameterVariable(
9387 NewSP, "dyn_ptr", ArgNo, NewSP->getFile(), /*LineNo=*/0, VoidPtrTy,
9388 /*AlwaysPreserve=*/false, DINode::DIFlags::FlagArtificial);
9389 auto Loc = DILocation::get(Func->getContext(), 0, 0, NewSP, 0);
9390 Argument *LastArg = Func->getArg(Func->arg_size() - 1);
9391 DB.insertDeclare(LastArg, Var, DB.createExpression(), Loc,
9392 &(*Func->begin()));
9393 }
9394}
9395
9397 if (Operator::getOpcode(V) == Instruction::AddrSpaceCast)
9398 return cast<Operator>(V)->getOperand(0);
9399 return V;
9400}
9401
9403 OpenMPIRBuilder &OMPBuilder, IRBuilderBase &Builder,
9405 StringRef FuncName, SmallVectorImpl<Value *> &Inputs,
9408 DebugLoc OutlinedFnLoc) {
9409 SmallVector<Type *> ParameterTypes;
9410 if (OMPBuilder.Config.isTargetDevice()) {
9411 // All parameters to target devices are passed as pointers
9412 // or i64. This assumes 64-bit address spaces/pointers.
9413 for (auto &Arg : Inputs)
9414 ParameterTypes.push_back(Arg->getType()->isPointerTy()
9415 ? Arg->getType()
9416 : Type::getInt64Ty(Builder.getContext()));
9417 } else {
9418 for (auto &Arg : Inputs)
9419 ParameterTypes.push_back(Arg->getType());
9420 }
9421
9422 // The implicit dyn_ptr argument is always the last parameter on both host
9423 // and device so the argument counts match without runtime manipulation.
9424 auto *PtrTy = PointerType::getUnqual(Builder.getContext());
9425 ParameterTypes.push_back(PtrTy);
9426
9427 auto BB = Builder.GetInsertBlock();
9428 auto M = BB->getModule();
9429 auto FuncType = FunctionType::get(Builder.getVoidTy(), ParameterTypes,
9430 /*isVarArg*/ false);
9431 auto Func =
9432 Function::Create(FuncType, GlobalValue::InternalLinkage, FuncName, M);
9433
9434 // Forward target-cpu and target-features function attributes from the
9435 // original function to the new outlined function.
9436 Function *ParentFn = Builder.GetInsertBlock()->getParent();
9437
9438 auto TargetCpuAttr = ParentFn->getFnAttribute("target-cpu");
9439 if (TargetCpuAttr.isStringAttribute())
9440 Func->addFnAttr(TargetCpuAttr);
9441
9442 auto TargetFeaturesAttr = ParentFn->getFnAttribute("target-features");
9443 if (TargetFeaturesAttr.isStringAttribute())
9444 Func->addFnAttr(TargetFeaturesAttr);
9445
9446 if (OMPBuilder.Config.isTargetDevice()) {
9447 Value *ExecMode =
9448 OMPBuilder.emitKernelExecutionMode(FuncName, DefaultAttrs.ExecFlags);
9449 OMPBuilder.emitUsed("llvm.compiler.used", {ExecMode});
9450 }
9451
9452 // Save insert point.
9453 IRBuilder<>::InsertPointGuard IPG(Builder);
9454 // We will generate the entries in the outlined function but the debug
9455 // location is still pointing to the parent function, which is the wrong
9456 // scope. OutlinedFnLoc, when the caller provides one, is the same source
9457 // position scoped to the subprogram that will be attached to the outlined
9458 // function, so it is what everything emitted below needs.
9459 Builder.SetCurrentDebugLocation(OutlinedFnLoc);
9460
9461 // Generate the region into the function.
9462 BasicBlock *EntryBB = BasicBlock::Create(Builder.getContext(), "entry", Func);
9463 Builder.SetInsertPoint(EntryBB);
9464
9465 // Insert target init call in the device compilation pass. On the host
9466 // (e.g. a non-GPU offload target), there is no runtime init/deinit
9467 // sequence, but the runtime still needs a '<kernel>_kernel_environment'
9468 // global to know how the kernel was configured, so emit it directly.
9469 if (OMPBuilder.Config.isTargetDevice())
9470 Builder.restoreIP(OMPBuilder.createTargetInit(Builder, DefaultAttrs));
9471 else
9472 OMPBuilder.emitKernelEnvironment(Builder, DefaultAttrs);
9473
9474 BasicBlock *UserCodeEntryBB = Builder.GetInsertBlock();
9475
9476 // As we embed the user code in the middle of our target region after we
9477 // generate entry code, we must move what allocas we can into the entry
9478 // block to avoid possible breaking optimisations
9480
9481 BasicBlock *ExitBB = splitBB(Builder, /*CreateBranch=*/true, "target.exit");
9482 BasicBlock *OutlinedBodyBB =
9483 splitBB(Builder, /*CreateBranch=*/true, "outlined.body");
9485 CBFunc(Builder.saveIP(), OutlinedBodyBB->begin(), ExitBB);
9486 if (!AfterIP)
9487 return AfterIP.takeError();
9488 Builder.SetInsertPoint(ExitBB);
9489 // The body callback builds the body with its own IRBuilder and cannot reach
9490 // this one directly. But a body holding another OpenMP construct, a nested
9491 // parallel say, calls OpenMPIRBuilder::createParallel, and that can leave
9492 // this Builder pointing at the wrong debug location, or at none at all. The
9493 // epilogue below belongs to the target construct rather than to whatever the
9494 // body emitted last, so re-establish the location the prologue was emitted
9495 // with.
9496 Builder.SetCurrentDebugLocation(OutlinedFnLoc);
9497
9498 // Insert target deinit call in the device compilation pass.
9499 if (OMPBuilder.Config.isTargetDevice())
9500 OMPBuilder.createTargetDeinit(Builder);
9501
9502 // Insert return instruction.
9503 Builder.CreateRetVoid();
9504
9505 // New Alloca IP at entry point of created device function.
9506 Builder.SetInsertPoint(EntryBB->getFirstNonPHIIt());
9507 auto AllocaIP = Builder.saveIP();
9508
9509 Builder.SetInsertPoint(UserCodeEntryBB->getFirstNonPHIOrPseudoProbe());
9510
9511 // Do not include the artificial dyn_ptr argument.
9512 const auto &ArgRange = make_range(Func->arg_begin(), Func->arg_end() - 1);
9513
9515
9516 auto ReplaceValue = [](Value *Input, Value *InputCopy, Function *Func) {
9517 // Things like GEP's can come in the form of Constants. Constants and
9518 // ConstantExpr's do not have access to the knowledge of what they're
9519 // contained in, so we must dig a little to find an instruction so we
9520 // can tell if they're used inside of the function we're outlining. We
9521 // also replace the original constant expression with a new instruction
9522 // equivalent; an instruction as it allows easy modification in the
9523 // following loop, as we can now know the constant (instruction) is
9524 // owned by our target function and replaceUsesOfWith can now be invoked
9525 // on it (cannot do this with constants it seems). A brand new one also
9526 // allows us to be cautious as it is perhaps possible the old expression
9527 // was used inside of the function but exists and is used externally
9528 // (unlikely by the nature of a Constant, but still).
9529 // NOTE: We cannot remove dead constants that have been rewritten to
9530 // instructions at this stage, we run the risk of breaking later lowering
9531 // by doing so as we could still be in the process of lowering the module
9532 // from MLIR to LLVM-IR and the MLIR lowering may still require the original
9533 // constants we have created rewritten versions of.
9534 if (auto *Const = dyn_cast<Constant>(Input))
9535 convertUsersOfConstantsToInstructions(Const, Func, false);
9536
9537 // Collect users before iterating over them to avoid invalidating the
9538 // iteration in case a user uses Input more than once (e.g. a call
9539 // instruction).
9540 SetVector<User *> Users(Input->users().begin(), Input->users().end());
9541 // Collect all the instructions
9543 if (auto *Instr = dyn_cast<Instruction>(User))
9544 if (Instr->getFunction() == Func)
9545 Instr->replaceUsesOfWith(Input, InputCopy);
9546 };
9547
9548 SmallVector<std::pair<Value *, Value *>> DeferredReplacement;
9549
9550 // Rewrite uses of input valus to parameters.
9551 for (auto InArg : zip(Inputs, ArgRange)) {
9552 Value *Input = std::get<0>(InArg);
9553 Argument &Arg = std::get<1>(InArg);
9554 Value *InputCopy = nullptr;
9555
9556 llvm::OpenMPIRBuilder::InsertPointOrErrorTy AfterIP = ArgAccessorFuncCB(
9557 Arg, Input, InputCopy, AllocaIP, Builder.saveIP(), ExitBB->begin());
9558 if (!AfterIP)
9559 return AfterIP.takeError();
9560 Builder.restoreIP(*AfterIP);
9561 ValueReplacementMap[Input] = std::make_tuple(InputCopy, Arg.getArgNo());
9562
9563 // In certain cases a Global may be set up for replacement, however, this
9564 // Global may be used in multiple arguments to the kernel, just segmented
9565 // apart, for example, if we have a global array, that is sectioned into
9566 // multiple mappings (technically not legal in OpenMP, but there is a case
9567 // in Fortran for Common Blocks where this is neccesary), we will end up
9568 // with GEP's into this array inside the kernel, that refer to the Global
9569 // but are technically separate arguments to the kernel for all intents and
9570 // purposes. If we have mapped a segment that requires a GEP into the 0-th
9571 // index, it will fold into an referal to the Global, if we then encounter
9572 // this folded GEP during replacement all of the references to the
9573 // Global in the kernel will be replaced with the argument we have generated
9574 // that corresponds to it, including any other GEP's that refer to the
9575 // Global that may be other arguments. This will invalidate all of the other
9576 // preceding mapped arguments that refer to the same global that may be
9577 // separate segments. To prevent this, we defer global processing until all
9578 // other processing has been performed.
9581 DeferredReplacement.push_back(std::make_pair(Input, InputCopy));
9582 continue;
9583 }
9584
9586 continue;
9587
9588 ReplaceValue(Input, InputCopy, Func);
9589 }
9590
9591 // Replace all of our deferred Input values, currently just Globals.
9592 for (auto Deferred : DeferredReplacement)
9593 ReplaceValue(std::get<0>(Deferred), std::get<1>(Deferred), Func);
9594
9595 FixupDebugInfoForOutlinedFunction(OMPBuilder, Builder, Func,
9596 ValueReplacementMap);
9597 return Func;
9598}
9599/// Given a task descriptor, TaskWithPrivates, return the pointer to the block
9600/// of pointers containing shared data between the parent task and the created
9601/// task.
9603 Value *TaskWithPrivates) {
9604 LLVMContext &Ctx = Builder.getContext();
9605 return Builder.CreateLoad(PointerType::getUnqual(Ctx), TaskWithPrivates);
9606}
9607/// Create an entry point for a target task with the following.
9608/// It'll have the following signature
9609/// void @.omp_target_task_proxy_func(i32 %thread.id, ptr %task)
9610/// This function is called from emitTargetTask once the
9611/// code to launch the target kernel has been outlined already.
9612/// NumOffloadingArrays is the number of offloading arrays that we need to copy
9613/// into the task structure so that the deferred target task can access this
9614/// data even after the stack frame of the generating task has been rolled
9615/// back. Offloading arrays contain base pointers, pointers, sizes etc
9616/// of the data that the target kernel will access. These in effect are the
9617/// non-empty arrays of pointers held by OpenMPIRBuilder::TargetDataRTArgs.
9619 OpenMPIRBuilder &OMPBuilder, IRBuilderBase &Builder, CallInst *StaleCI,
9620 StructType *PrivatesTy, StructType *TaskWithPrivatesTy,
9621 const size_t NumOffloadingArrays, const int SharedArgsOperandNo) {
9622
9623 // If NumOffloadingArrays is non-zero, PrivatesTy better not be nullptr.
9624 // This is because PrivatesTy is the type of the structure in which
9625 // we pass the offloading arrays to the deferred target task.
9626 assert((!NumOffloadingArrays || PrivatesTy) &&
9627 "PrivatesTy cannot be nullptr when there are offloadingArrays"
9628 "to privatize");
9629
9630 Module &M = OMPBuilder.M;
9631 // KernelLaunchFunction is the target launch function, i.e.
9632 // the function that sets up kernel arguments and calls
9633 // __tgt_target_kernel to launch the kernel on the device.
9634 //
9635 Function *KernelLaunchFunction = StaleCI->getCalledFunction();
9636
9637 // StaleCI is the CallInst which is the call to the outlined
9638 // target kernel launch function. If there are local live-in values
9639 // that the outlined function uses then these are aggregated into a structure
9640 // which is passed as the second argument. If there are no local live-in
9641 // values or if all values used by the outlined kernel are global variables,
9642 // then there's only one argument, the threadID. So, StaleCI can be
9643 //
9644 // %structArg = alloca { ptr, ptr }, align 8
9645 // %gep_ = getelementptr { ptr, ptr }, ptr %structArg, i32 0, i32 0
9646 // store ptr %20, ptr %gep_, align 8
9647 // %gep_8 = getelementptr { ptr, ptr }, ptr %structArg, i32 0, i32 1
9648 // store ptr %21, ptr %gep_8, align 8
9649 // call void @_QQmain..omp_par.1(i32 %global.tid.val6, ptr %structArg)
9650 //
9651 // OR
9652 //
9653 // call void @_QQmain..omp_par.1(i32 %global.tid.val6)
9654 LLVMContext &Ctx = StaleCI->getParent()->getContext();
9655
9656 Type *ThreadIDTy = Type::getInt32Ty(Ctx);
9657 Type *TaskPtrTy = OMPBuilder.TaskPtr;
9658 [[maybe_unused]] Type *TaskTy = OMPBuilder.Task;
9659
9660 auto ProxyFnTy =
9661 FunctionType::get(Builder.getVoidTy(), {ThreadIDTy, TaskPtrTy},
9662 /* isVarArg */ false);
9663 auto ProxyFn = Function::Create(ProxyFnTy, GlobalValue::InternalLinkage,
9664 ".omp_target_task_proxy_func", M);
9665 Value *ThreadId = ProxyFn->getArg(0);
9666 Value *TaskWithPrivates = ProxyFn->getArg(1);
9667 ThreadId->setName("thread.id");
9668 TaskWithPrivates->setName("task");
9669
9670 bool HasShareds = SharedArgsOperandNo > 0;
9671 bool HasOffloadingArrays = NumOffloadingArrays > 0;
9672 IRBuilder<>::InsertPointGuard IPG(Builder);
9673 BasicBlock *EntryBB =
9674 BasicBlock::Create(Builder.getContext(), "entry", ProxyFn);
9675 Builder.SetInsertPoint(EntryBB);
9676 Builder.SetCurrentDebugLocation(llvm::DebugLoc());
9677
9678 SmallVector<Value *> KernelLaunchArgs;
9679 KernelLaunchArgs.reserve(StaleCI->arg_size());
9680 KernelLaunchArgs.push_back(ThreadId);
9681
9682 if (HasOffloadingArrays) {
9683 assert(TaskTy != TaskWithPrivatesTy &&
9684 "If there are offloading arrays to pass to the target"
9685 "TaskTy cannot be the same as TaskWithPrivatesTy");
9686 (void)TaskTy;
9687 Value *Privates =
9688 Builder.CreateStructGEP(TaskWithPrivatesTy, TaskWithPrivates, 1);
9689 for (unsigned int i = 0; i < NumOffloadingArrays; ++i)
9690 KernelLaunchArgs.push_back(
9691 Builder.CreateStructGEP(PrivatesTy, Privates, i));
9692 }
9693
9694 if (HasShareds) {
9695 auto *ArgStructAlloca =
9696 dyn_cast<AllocaInst>(StaleCI->getArgOperand(SharedArgsOperandNo));
9697 assert(ArgStructAlloca &&
9698 "Unable to find the alloca instruction corresponding to arguments "
9699 "for extracted function");
9700 auto *ArgStructType = cast<StructType>(ArgStructAlloca->getAllocatedType());
9701 std::optional<TypeSize> ArgAllocSize =
9702 ArgStructAlloca->getAllocationSize(M.getDataLayout());
9703 assert(ArgStructType && ArgAllocSize &&
9704 "Unable to determine size of arguments for extracted function");
9705 uint64_t StructSize = ArgAllocSize->getFixedValue();
9706
9707 AllocaInst *NewArgStructAlloca =
9708 Builder.CreateAlloca(ArgStructType, nullptr, "structArg");
9709
9710 Value *SharedsSize = Builder.getInt64(StructSize);
9711
9712 LoadInst *LoadShared =
9713 loadSharedDataFromTaskDescriptor(Builder, TaskWithPrivates);
9714
9715 Builder.CreateMemCpy(
9716 NewArgStructAlloca, NewArgStructAlloca->getAlign(), LoadShared,
9717 LoadShared->getPointerAlignment(M.getDataLayout()), SharedsSize);
9718 KernelLaunchArgs.push_back(NewArgStructAlloca);
9719 }
9720 OMPBuilder.createRuntimeFunctionCall(KernelLaunchFunction, KernelLaunchArgs);
9721 Builder.CreateRetVoid();
9722 return ProxyFn;
9723}
9725
9726 if (auto *GEP = dyn_cast<GetElementPtrInst>(V))
9727 return GEP->getSourceElementType();
9728 if (auto *Alloca = dyn_cast<AllocaInst>(V))
9729 return Alloca->getAllocatedType();
9730
9731 llvm_unreachable("Unhandled Instruction type");
9732 return nullptr;
9733}
9734// This function returns a struct that has at most two members.
9735// The first member is always %struct.kmp_task_ompbuilder_t, that is the task
9736// descriptor. The second member, if needed, is a struct containing arrays
9737// that need to be passed to the offloaded target kernel. For example,
9738// if .offload_baseptrs, .offload_ptrs and .offload_sizes have to be passed to
9739// the target kernel and their types are [3 x ptr], [3 x ptr] and [3 x i64]
9740// respectively, then the types created by this function are
9741//
9742// %struct.privates = type { [3 x ptr], [3 x ptr], [3 x i64] }
9743// %struct.task_with_privates = type { %struct.kmp_task_ompbuilder_t,
9744// %struct.privates }
9745// %struct.task_with_privates is returned by this function.
9746// If there aren't any offloading arrays to pass to the target kernel,
9747// %struct.kmp_task_ompbuilder_t is returned.
9748static StructType *
9750 ArrayRef<Value *> OffloadingArraysToPrivatize,
9751 ArrayRef<Type *> DescriptorTypes) {
9752
9753 if (OffloadingArraysToPrivatize.empty() && DescriptorTypes.empty())
9754 return OMPIRBuilder.Task;
9755
9756 SmallVector<Type *, 4> StructFieldTypes;
9757 for (Value *V : OffloadingArraysToPrivatize) {
9758 assert(V->getType()->isPointerTy() &&
9759 "Expected pointer to array to privatize. Got a non-pointer value "
9760 "instead");
9761 Type *ArrayTy = getOffloadingArrayType(V);
9762 assert(ArrayTy && "ArrayType cannot be nullptr");
9763 StructFieldTypes.push_back(ArrayTy);
9764 }
9765 llvm::append_range(StructFieldTypes, DescriptorTypes);
9766 StructType *PrivatesStructTy =
9767 StructType::create(StructFieldTypes, "struct.privates");
9768 return StructType::create({OMPIRBuilder.Task, PrivatesStructTy},
9769 "struct.task_with_privates");
9770}
9772 OpenMPIRBuilder &OMPBuilder, IRBuilderBase &Builder, bool IsOffloadEntry,
9773 TargetRegionEntryInfo &EntryInfo,
9775 Function *&OutlinedFn, Constant *&OutlinedFnID,
9779 DebugLoc OutlinedFnLoc) {
9780
9781 OpenMPIRBuilder::FunctionGenCallback &&GenerateOutlinedFunction =
9782 [&](StringRef EntryFnName) {
9783 return createOutlinedFunction(OMPBuilder, Builder, DefaultAttrs,
9784 EntryFnName, Inputs, CBFunc,
9785 ArgAccessorFuncCB, OutlinedFnLoc);
9786 };
9787
9788 return OMPBuilder.emitTargetRegionFunction(
9789 EntryInfo, GenerateOutlinedFunction, IsOffloadEntry, OutlinedFn,
9790 OutlinedFnID);
9791}
9792
9794 TargetTaskBodyCallbackTy TaskBodyCB, Value *DeviceID, Value *RTLoc,
9796 const DependenciesInfo &Dependencies, const TargetDataRTArgs &RTArgs,
9797 bool HasNoWait) {
9798
9799 // The following explains the code-gen scenario for the `target` directive. A
9800 // similar scneario is followed for other device-related directives (e.g.
9801 // `target enter data`) but in similar fashion since we only need to emit task
9802 // that encapsulates the proper runtime call.
9803 //
9804 // When we arrive at this function, the target region itself has been
9805 // outlined into the function OutlinedFn.
9806 // So at ths point, for
9807 // --------------------------------------------------------------
9808 // void user_code_that_offloads(...) {
9809 // omp target depend(..) map(from:a) map(to:b) private(i)
9810 // do i = 1, 10
9811 // a(i) = b(i) + n
9812 // }
9813 //
9814 // --------------------------------------------------------------
9815 //
9816 // we have
9817 //
9818 // --------------------------------------------------------------
9819 //
9820 // void user_code_that_offloads(...) {
9821 // %.offload_baseptrs = alloca [2 x ptr], align 8
9822 // %.offload_ptrs = alloca [2 x ptr], align 8
9823 // %.offload_mappers = alloca [2 x ptr], align 8
9824 // ;; target region has been outlined and now we need to
9825 // ;; offload to it via a target task.
9826 // }
9827 // void outlined_device_function(ptr a, ptr b, ptr n) {
9828 // n = *n_ptr;
9829 // do i = 1, 10
9830 // a(i) = b(i) + n
9831 // }
9832 //
9833 // We have to now do the following
9834 // (i) Make an offloading call to outlined_device_function using the OpenMP
9835 // RTL. See 'kernel_launch_function' in the pseudo code below. This is
9836 // emitted by emitKernelLaunch
9837 // (ii) Create a task entry point function that calls kernel_launch_function
9838 // and is the entry point for the target task. See
9839 // '@.omp_target_task_proxy_func in the pseudocode below.
9840 // (iii) Create a task with the task entry point created in (ii)
9841 //
9842 // That is we create the following
9843 // struct task_with_privates {
9844 // struct kmp_task_ompbuilder_t task_struct;
9845 // struct privates {
9846 // [2 x ptr] ; baseptrs
9847 // [2 x ptr] ; ptrs
9848 // [2 x i64] ; sizes
9849 // }
9850 // }
9851 // void user_code_that_offloads(...) {
9852 // %.offload_baseptrs = alloca [2 x ptr], align 8
9853 // %.offload_ptrs = alloca [2 x ptr], align 8
9854 // %.offload_sizes = alloca [2 x i64], align 8
9855 //
9856 // %structArg = alloca { ptr, ptr, ptr }, align 8
9857 // %strucArg[0] = a
9858 // %strucArg[1] = b
9859 // %strucArg[2] = &n
9860 //
9861 // target_task_with_privates = @__kmpc_omp_target_task_alloc(...,
9862 // sizeof(kmp_task_ompbuilder_t),
9863 // sizeof(structArg),
9864 // @.omp_target_task_proxy_func,
9865 // ...)
9866 // memcpy(target_task_with_privates->task_struct->shareds, %structArg,
9867 // sizeof(structArg))
9868 // memcpy(target_task_with_privates->privates->baseptrs,
9869 // offload_baseptrs, sizeof(offload_baseptrs)
9870 // memcpy(target_task_with_privates->privates->ptrs,
9871 // offload_ptrs, sizeof(offload_ptrs)
9872 // memcpy(target_task_with_privates->privates->sizes,
9873 // offload_sizes, sizeof(offload_sizes)
9874 // dependencies_array = ...
9875 // ;; if nowait not present
9876 // call @__kmpc_omp_wait_deps(..., dependencies_array)
9877 // call @__kmpc_omp_task_begin_if0(...)
9878 // call @ @.omp_target_task_proxy_func(i32 thread_id, ptr
9879 // %target_task_with_privates)
9880 // call @__kmpc_omp_task_complete_if0(...)
9881 // }
9882 //
9883 // define internal void @.omp_target_task_proxy_func(i32 %thread.id,
9884 // ptr %task) {
9885 // %structArg = alloca {ptr, ptr, ptr}
9886 // %task_ptr = getelementptr(%task, 0, 0)
9887 // %shared_data = load (getelementptr %task_ptr, 0, 0)
9888 // mempcy(%structArg, %shared_data, sizeof(%structArg))
9889 //
9890 // %offloading_arrays = getelementptr(%task, 0, 1)
9891 // %offload_baseptrs = getelementptr(%offloading_arrays, 0, 0)
9892 // %offload_ptrs = getelementptr(%offloading_arrays, 0, 1)
9893 // %offload_sizes = getelementptr(%offloading_arrays, 0, 2)
9894 // kernel_launch_function(%thread.id, %offload_baseptrs, %offload_ptrs,
9895 // %offload_sizes, %structArg)
9896 // }
9897 //
9898 // We need the proxy function because the signature of the task entry point
9899 // expected by kmpc_omp_task is always the same and will be different from
9900 // that of the kernel_launch function.
9901 //
9902 // kernel_launch_function is generated by emitKernelLaunch and has the
9903 // always_inline attribute. For this example, it'll look like so:
9904 // void kernel_launch_function(%thread_id, %offload_baseptrs, %offload_ptrs,
9905 // %offload_sizes, %structArg) alwaysinline {
9906 // %kernel_args = alloca %struct.__tgt_kernel_arguments, align 8
9907 // ; load aggregated data from %structArg
9908 // ; setup kernel_args using offload_baseptrs, offload_ptrs and
9909 // ; offload_sizes
9910 // call i32 @__tgt_target_kernel(...,
9911 // outlined_device_function,
9912 // ptr %kernel_args)
9913 // }
9914 // void outlined_device_function(ptr a, ptr b, ptr n) {
9915 // n = *n_ptr;
9916 // do i = 1, 10
9917 // a(i) = b(i) + n
9918 // }
9919 //
9920 BasicBlock *TargetTaskBodyBB =
9921 splitBB(Builder, /*CreateBranch=*/true, "target.task.body");
9922 BasicBlock *TargetTaskAllocaBB =
9923 splitBB(Builder, /*CreateBranch=*/true, "target.task.alloca");
9924
9925 InsertPointTy TargetTaskAllocaIP(TargetTaskAllocaBB->begin());
9926 InsertPointTy TargetTaskBodyIP(TargetTaskBodyBB->begin());
9927
9928 auto OI = std::make_unique<OutlineInfo>();
9929 OI->EntryBB = TargetTaskAllocaBB;
9930 OI->OuterAllocBB = AllocaIP.getNodeParent();
9931
9932 // Add the thread ID argument.
9934 OI->ExcludeArgsFromAggregate.push_back(createFakeIntVal(
9935 Builder, AllocaIP, ToBeDeleted, TargetTaskAllocaIP, "global.tid", false));
9936
9937 // Generate the task body which will subsequently be outlined.
9938 Builder.restoreIP(TargetTaskBodyIP);
9939 if (Error Err = TaskBodyCB(DeviceID, RTLoc, TargetTaskAllocaIP))
9940 return Err;
9941
9942 // The outliner (CodeExtractor) extract a sequence or vector of blocks that
9943 // it is given. These blocks are enumerated by
9944 // OpenMPIRBuilder::OutlineInfo::collectBlocks which expects the OI.ExitBlock
9945 // to be outside the region. In other words, OI.ExitBlock is expected to be
9946 // the start of the region after the outlining. We used to set OI.ExitBlock
9947 // to the InsertBlock after TaskBodyCB is done. This is fine in most cases
9948 // except when the task body is a single basic block. In that case,
9949 // OI.ExitBlock is set to the single task body block and will get left out of
9950 // the outlining process. So, simply create a new empty block to which we
9951 // uncoditionally branch from where TaskBodyCB left off
9952 OI->ExitBB = BasicBlock::Create(Builder.getContext(), "target.task.cont");
9953 emitBlock(OI->ExitBB, Builder.GetInsertBlock()->getParent(),
9954 /*IsFinished=*/true);
9955
9956 SmallVector<Value *, 2> OffloadingArraysToPrivatize;
9957 bool NeedsTargetTask = HasNoWait && DeviceID;
9958 if (NeedsTargetTask) {
9959 for (auto *V :
9960 {RTArgs.BasePointersArray, RTArgs.PointersArray, RTArgs.MappersArray,
9961 RTArgs.MapNamesArray, RTArgs.MapTypesArray, RTArgs.MapTypesArrayEnd,
9962 RTArgs.SizesArray}) {
9964 OffloadingArraysToPrivatize.push_back(V);
9965 OI->ExcludeArgsFromAggregate.push_back(V);
9966 }
9967 }
9968 }
9969 auto NonContiguousDescriptors = RTArgs.NonContiguousDescriptors;
9970 if (!NeedsTargetTask)
9971 NonContiguousDescriptors.clear();
9972 OI->PostOutlineCB = [this, ToBeDeleted, Dependencies, NeedsTargetTask,
9973 DeviceID, OffloadingArraysToPrivatize,
9974 NonContiguousDescriptors,
9975 PointersArray =
9976 RTArgs.PointersArray](Function &OutlinedFn) mutable {
9977 assert(OutlinedFn.hasOneUse() &&
9978 "there must be a single user for the outlined function");
9979
9980 CallInst *StaleCI = cast<CallInst>(OutlinedFn.user_back());
9981
9982 // The first argument of StaleCI is always the thread id.
9983 // The next few arguments are the pointers to offloading arrays
9984 // if any. (see OffloadingArraysToPrivatize)
9985 // Finally, all other local values that are live-in into the outlined region
9986 // end up in a structure whose pointer is passed as the last argument. This
9987 // piece of data is passed in the "shared" field of the task structure. So,
9988 // we know we have to pass shareds to the task if the number of arguments is
9989 // greater than OffloadingArraysToPrivatize.size() + 1 The 1 is for the
9990 // thread id. Further, for safety, we assert that the number of arguments of
9991 // StaleCI is exactly OffloadingArraysToPrivatize.size() + 2
9992 const unsigned int NumStaleCIArgs = StaleCI->arg_size();
9993 bool HasShareds = NumStaleCIArgs > OffloadingArraysToPrivatize.size() + 1;
9994 assert((!HasShareds ||
9995 NumStaleCIArgs == (OffloadingArraysToPrivatize.size() + 2)) &&
9996 "Wrong number of arguments for StaleCI when shareds are present");
9997 int SharedArgOperandNo =
9998 HasShareds ? OffloadingArraysToPrivatize.size() + 1 : 0;
9999
10000 // Descriptor storage is not an argument to the outlined function. It is
10001 // reached indirectly through the task-private pointer array.
10002 SmallVector<Type *, 2> DescriptorTypes;
10003 for (const auto &Descriptor : NonContiguousDescriptors)
10004 DescriptorTypes.push_back(Descriptor.Storage->getAllocatedType());
10005 StructType *TaskWithPrivatesTy = createTaskWithPrivatesTy(
10006 *this, OffloadingArraysToPrivatize, DescriptorTypes);
10007 StructType *PrivatesTy = nullptr;
10008
10009 if (!OffloadingArraysToPrivatize.empty())
10010 PrivatesTy =
10011 static_cast<StructType *>(TaskWithPrivatesTy->getElementType(1));
10012
10014 *this, Builder, StaleCI, PrivatesTy, TaskWithPrivatesTy,
10015 OffloadingArraysToPrivatize.size(), SharedArgOperandNo);
10016
10017 LLVM_DEBUG(dbgs() << "Proxy task entry function created: " << *ProxyFn
10018 << "\n");
10019
10020 Builder.SetInsertPoint(StaleCI);
10021
10022 // Gather the arguments for emitting the runtime call.
10023 uint32_t SrcLocStrSize;
10024 Constant *SrcLocStr =
10026 Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
10027
10028 // @__kmpc_omp_task_alloc or @__kmpc_omp_target_task_alloc
10029 //
10030 // If `HasNoWait == true`, we call @__kmpc_omp_target_task_alloc to provide
10031 // the DeviceID to the deferred task and also since
10032 // @__kmpc_omp_target_task_alloc creates an untied/async task.
10033 Function *TaskAllocFn =
10034 !NeedsTargetTask
10035 ? getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_omp_task_alloc)
10037 OMPRTL___kmpc_omp_target_task_alloc);
10038
10039 // Arguments - `loc_ref` (Ident) and `gtid` (ThreadID)
10040 // call.
10041 Value *ThreadID = getOrCreateThreadID(Ident);
10042
10043 // Argument - `sizeof_kmp_task_t` (TaskSize)
10044 // Tasksize refers to the size in bytes of kmp_task_t data structure
10045 // plus any other data to be passed to the target task, if any, which
10046 // is packed into a struct. kmp_task_t and the struct so created are
10047 // packed into a wrapper struct whose type is TaskWithPrivatesTy.
10048 Value *TaskSize = Builder.getInt64(
10049 M.getDataLayout().getTypeStoreSize(TaskWithPrivatesTy));
10050
10051 // Argument - `sizeof_shareds` (SharedsSize)
10052 // SharedsSize refers to the shareds array size in the kmp_task_t data
10053 // structure.
10054 Value *SharedsSize = Builder.getInt64(0);
10055 if (HasShareds) {
10056 auto *ArgStructAlloca =
10057 dyn_cast<AllocaInst>(StaleCI->getArgOperand(SharedArgOperandNo));
10058 assert(ArgStructAlloca &&
10059 "Unable to find the alloca instruction corresponding to arguments "
10060 "for extracted function");
10061 std::optional<TypeSize> ArgAllocSize =
10062 ArgStructAlloca->getAllocationSize(M.getDataLayout());
10063 assert(ArgAllocSize &&
10064 "Unable to determine size of arguments for extracted function");
10065 SharedsSize = Builder.getInt64(ArgAllocSize->getFixedValue());
10066 }
10067
10068 // Argument - `flags`
10069 // Task is tied iff (Flags & 1) == 1.
10070 // Task is untied iff (Flags & 1) == 0.
10071 // Task is final iff (Flags & 2) == 2.
10072 // Task is not final iff (Flags & 2) == 0.
10073 // A target task is not final and is untied.
10074 Value *Flags = Builder.getInt32(0);
10075
10076 // Emit the @__kmpc_omp_task_alloc runtime call
10077 // The runtime call returns a pointer to an area where the task captured
10078 // variables must be copied before the task is run (TaskData)
10079 CallInst *TaskData = nullptr;
10080
10081 SmallVector<llvm::Value *> TaskAllocArgs = {
10082 /*loc_ref=*/Ident, /*gtid=*/ThreadID,
10083 /*flags=*/Flags,
10084 /*sizeof_task=*/TaskSize, /*sizeof_shared=*/SharedsSize,
10085 /*task_func=*/ProxyFn};
10086
10087 if (NeedsTargetTask) {
10088 assert(DeviceID && "Expected non-empty device ID.");
10089 TaskAllocArgs.push_back(DeviceID);
10090 }
10091
10092 TaskData = createRuntimeFunctionCall(TaskAllocFn, TaskAllocArgs);
10093
10094 Align Alignment = TaskData->getPointerAlignment(M.getDataLayout());
10095 if (HasShareds) {
10096 Value *Shareds = StaleCI->getArgOperand(SharedArgOperandNo);
10097 Value *TaskShareds = loadSharedDataFromTaskDescriptor(Builder, TaskData);
10098 Builder.CreateMemCpy(TaskShareds, Alignment, Shareds, Alignment,
10099 SharedsSize);
10100 }
10101 if (!OffloadingArraysToPrivatize.empty()) {
10102 Value *Privates =
10103 Builder.CreateStructGEP(TaskWithPrivatesTy, TaskData, 1);
10104 Value *PrivatePointersArray = nullptr;
10105 for (unsigned int i = 0; i < OffloadingArraysToPrivatize.size(); ++i) {
10106 Value *PtrToPrivatize = OffloadingArraysToPrivatize[i];
10107 [[maybe_unused]] Type *ArrayType =
10108 getOffloadingArrayType(PtrToPrivatize);
10109 assert(ArrayType && "ArrayType cannot be nullptr");
10110
10111 Type *ElementType = PrivatesTy->getElementType(i);
10112 assert(ElementType == ArrayType &&
10113 "ElementType should match ArrayType");
10114 (void)ArrayType;
10115
10116 Value *Dst = Builder.CreateStructGEP(PrivatesTy, Privates, i);
10117 Builder.CreateMemCpy(
10118 Dst, Alignment, PtrToPrivatize, Alignment,
10119 Builder.getInt64(M.getDataLayout().getTypeStoreSize(ElementType)));
10120 if (PtrToPrivatize == PointersArray)
10121 PrivatePointersArray = Dst;
10122 }
10123 // Snapshot the encounter-time bounds before enqueueing the task, then
10124 // redirect its pointer entries to descriptors owned by that task.
10125 for (auto [I, Descriptor] : llvm::enumerate(NonContiguousDescriptors)) {
10126 assert(PrivatePointersArray && "missing task-private pointer array");
10127 Value *Dst = Builder.CreateStructGEP(
10128 PrivatesTy, Privates, OffloadingArraysToPrivatize.size() + I);
10129 Builder.CreateMemCpy(
10130 Dst, Alignment, Descriptor.Storage, Descriptor.Storage->getAlign(),
10131 Builder.getInt64(M.getDataLayout().getTypeStoreSize(
10132 Descriptor.Storage->getAllocatedType())));
10133 Value *Entry = Builder.CreateConstInBoundsGEP2_32(
10134 getOffloadingArrayType(PointersArray), PrivatePointersArray, 0,
10135 Descriptor.MapIndex);
10136 Builder.CreateAlignedStore(Dst, Entry, Alignment);
10137 }
10138 }
10139
10140 Value *DepArray = nullptr;
10141 Value *NumDeps = nullptr;
10142 if (Dependencies.DepArray) {
10143 DepArray = Dependencies.DepArray;
10144 NumDeps = Dependencies.NumDeps;
10145 } else if (!Dependencies.Deps.empty()) {
10146 DepArray = emitTaskDependencies(*this, Dependencies.Deps);
10147 NumDeps = Builder.getInt32(Dependencies.Deps.size());
10148 }
10149
10150 // ---------------------------------------------------------------
10151 // V5.2 13.8 target construct
10152 // If the nowait clause is present, execution of the target task
10153 // may be deferred. If the nowait clause is not present, the target task is
10154 // an included task.
10155 // ---------------------------------------------------------------
10156 // The above means that the lack of a nowait on the target construct
10157 // translates to '#pragma omp task if(0)'
10158 if (!NeedsTargetTask) {
10159 if (DepArray) {
10160 Function *TaskWaitFn =
10161 getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_omp_wait_deps);
10163 TaskWaitFn,
10164 {/*loc_ref=*/Ident, /*gtid=*/ThreadID,
10165 /*ndeps=*/NumDeps,
10166 /*dep_list=*/DepArray,
10167 /*ndeps_noalias=*/ConstantInt::get(Builder.getInt32Ty(), 0),
10168 /*noalias_dep_list=*/
10170 }
10171 // Included task.
10172 Function *TaskBeginFn =
10173 getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_omp_task_begin_if0);
10174 Function *TaskCompleteFn =
10175 getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_omp_task_complete_if0);
10176 createRuntimeFunctionCall(TaskBeginFn, {Ident, ThreadID, TaskData});
10177 CallInst *CI = createRuntimeFunctionCall(ProxyFn, {ThreadID, TaskData});
10178 CI->setDebugLoc(StaleCI->getDebugLoc());
10179 createRuntimeFunctionCall(TaskCompleteFn, {Ident, ThreadID, TaskData});
10180 } else if (DepArray) {
10181 // HasNoWait - meaning the task may be deferred. Call
10182 // __kmpc_omp_task_with_deps if there are dependencies,
10183 // else call __kmpc_omp_task
10184 Function *TaskFn =
10185 getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_omp_task_with_deps);
10187 TaskFn,
10188 {Ident, ThreadID, TaskData, NumDeps, DepArray,
10189 ConstantInt::get(Builder.getInt32Ty(), 0),
10191 } else {
10192 // Emit the @__kmpc_omp_task runtime call to spawn the task
10193 Function *TaskFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_omp_task);
10194 createRuntimeFunctionCall(TaskFn, {Ident, ThreadID, TaskData});
10195 }
10196
10197 Builder.ClearInsertionPoint();
10198 StaleCI->eraseFromParent();
10199 for (Instruction *I : llvm::reverse(ToBeDeleted))
10200 I->eraseFromParent();
10201 };
10202 addOutlineInfo(std::move(OI));
10203
10204 LLVM_DEBUG(dbgs() << "Insert block after emitKernelLaunch = \n"
10205 << *(Builder.GetInsertBlock()) << "\n");
10206 LLVM_DEBUG(dbgs() << "Module after emitKernelLaunch = \n"
10207 << *(Builder.getModule()) << "\n");
10208 return Builder.saveIP();
10209}
10210
10212 InsertPointTy AllocaIP, InsertPointTy CodeGenIP, TargetDataInfo &Info,
10213 TargetDataRTArgs &RTArgs, MapInfosTy &CombinedInfo,
10214 CustomMapperCallbackTy CustomMapperCB, bool IsNonContiguous,
10215 bool ForEndCall, function_ref<void(unsigned int, Value *)> DeviceAddrCB) {
10216 if (Error Err =
10217 emitOffloadingArrays(AllocaIP, CodeGenIP, CombinedInfo, Info,
10218 CustomMapperCB, IsNonContiguous, DeviceAddrCB))
10219 return Err;
10220 emitOffloadingArraysArgument(Builder, RTArgs, Info, ForEndCall);
10221 return Error::success();
10222}
10223
10225 OpenMPIRBuilder &OMPBuilder, IRBuilderBase &Builder, Value *RTLocOverride,
10230 Value *IfCond, Function *OutlinedFn, Constant *OutlinedFnID,
10234 const OpenMPIRBuilder::DependenciesInfo &Dependencies, bool HasNoWait,
10235 Value *DynCGroupMem, OMPDynGroupprivateFallbackType DynCGroupMemFallback) {
10236 // Generate a function call to the host fallback implementation of the target
10237 // region. This is called by the host when no offload entry was generated for
10238 // the target region and when the offloading call fails at runtime.
10239 auto &&EmitTargetCallFallbackCB = [&](OpenMPIRBuilder::InsertPointTy IP)
10241 Builder.restoreIP(IP);
10242 // Ensure the host fallback has the same dyn_ptr ABI as the device.
10243 SmallVector<Value *> FallbackArgs(Args.begin(), Args.end());
10244 FallbackArgs.push_back(
10245 Constant::getNullValue(PointerType::getUnqual(Builder.getContext())));
10246 OMPBuilder.createRuntimeFunctionCall(OutlinedFn, FallbackArgs);
10247 return Builder.saveIP();
10248 };
10249
10250 bool HasDependencies = !Dependencies.empty();
10251 bool RequiresOuterTargetTask = HasNoWait || HasDependencies;
10252
10254
10255 auto TaskBodyCB =
10256 [&](Value *DeviceID, Value *RTLoc,
10257 IRBuilderBase::InsertPoint TargetTaskAllocaIP) -> Error {
10258 // Assume no error was returned because EmitTargetCallFallbackCB doesn't
10259 // produce any.
10261 // emitKernelLaunch makes the necessary runtime call to offload the
10262 // kernel. We then outline all that code into a separate function
10263 // ('kernel_launch_function' in the pseudo code above). This function is
10264 // then called by the target task proxy function (see
10265 // '@.omp_target_task_proxy_func' in the pseudo code above)
10266 // "@.omp_target_task_proxy_func' is generated by
10267 // emitTargetTaskProxyFunction.
10268 if (OutlinedFnID && DeviceID)
10269 return OMPBuilder.emitKernelLaunch(Builder, OutlinedFnID,
10270 EmitTargetCallFallbackCB, KArgs,
10271 DeviceID, RTLoc, TargetTaskAllocaIP);
10272
10273 // We only need to do the outlining if `DeviceID` is set to avoid calling
10274 // `emitKernelLaunch` if we want to code-gen for the host; e.g. if we are
10275 // generating the `else` branch of an `if` clause.
10276 //
10277 // When OutlinedFnID is set to nullptr, then it's not an offloading call.
10278 // In this case, we execute the host implementation directly.
10279 return EmitTargetCallFallbackCB(OMPBuilder.Builder.saveIP());
10280 }());
10281
10282 OMPBuilder.Builder.restoreIP(AfterIP);
10283 return Error::success();
10284 };
10285
10286 auto &&EmitTargetCallElse =
10287 [&](OpenMPIRBuilder::InsertPointTy AllocaIP,
10289 ArrayRef<BasicBlock *> DeallocBlocks) -> Error {
10290 // Assume no error was returned because EmitTargetCallFallbackCB doesn't
10291 // produce any.
10293 if (RequiresOuterTargetTask) {
10294 // Arguments that are intended to be directly forwarded to an
10295 // emitKernelLaunch call are pased as nullptr, since
10296 // OutlinedFnID=nullptr results in that call not being done.
10298 return OMPBuilder.emitTargetTask(TaskBodyCB, /*DeviceID=*/nullptr,
10299 /*RTLoc=*/nullptr, AllocaIP,
10300 Dependencies, EmptyRTArgs, HasNoWait);
10301 }
10302 return EmitTargetCallFallbackCB(Builder.saveIP());
10303 }());
10304
10305 Builder.restoreIP(AfterIP);
10306 return Error::success();
10307 };
10308
10309 auto &&EmitTargetCallThen =
10310 [&](OpenMPIRBuilder::InsertPointTy AllocaIP,
10312 ArrayRef<BasicBlock *> DeallocBlocks) -> Error {
10313 Info.HasNoWait = HasNoWait;
10314 OpenMPIRBuilder::MapInfosTy &MapInfo = GenMapInfoCB(Builder.saveIP());
10315
10317 if (Error Err = OMPBuilder.emitOffloadingArraysAndArgs(
10318 AllocaIP, Builder.saveIP(), Info, RTArgs, MapInfo, CustomMapperCB,
10319 /*IsNonContiguous=*/true,
10320 /*ForEndCall=*/false))
10321 return Err;
10322
10323 SmallVector<Value *, 3> NumTeamsC;
10324 for (auto [DefaultVal, RuntimeVal] :
10325 zip_equal(DefaultAttrs.MaxTeams, RuntimeAttrs.MaxTeams))
10326 NumTeamsC.push_back(RuntimeVal ? RuntimeVal
10327 : Builder.getInt32(DefaultVal));
10328
10329 // Calculate number of threads: 0 if no clauses specified, otherwise it is
10330 // the minimum between optional THREAD_LIMIT and NUM_THREADS clauses.
10331 auto InitMaxThreadsClause = [&Builder](Value *Clause) {
10332 if (Clause)
10333 Clause = Builder.CreateIntCast(Clause, Builder.getInt32Ty(),
10334 /*isSigned=*/false);
10335 return Clause;
10336 };
10337 auto CombineMaxThreadsClauses = [&Builder](Value *Clause, Value *&Result) {
10338 if (Clause)
10339 Result =
10340 Result ? Builder.CreateSelect(Builder.CreateICmpULT(Result, Clause),
10341 Result, Clause)
10342 : Clause;
10343 };
10344
10345 // If a multi-dimensional THREAD_LIMIT is set, it is the OMPX_BARE case, so
10346 // the NUM_THREADS clause is overriden by THREAD_LIMIT.
10347 SmallVector<Value *, 3> NumThreadsC;
10348 Value *MaxThreadsClause =
10349 RuntimeAttrs.TeamsThreadLimit.size() == 1
10350 ? InitMaxThreadsClause(RuntimeAttrs.MaxThreads.front())
10351 : nullptr;
10352
10353 for (auto [TeamsVal, TargetVal] : zip_equal(
10354 RuntimeAttrs.TeamsThreadLimit, RuntimeAttrs.TargetThreadLimit)) {
10355 Value *TeamsThreadLimitClause = InitMaxThreadsClause(TeamsVal);
10356 Value *NumThreads = InitMaxThreadsClause(TargetVal);
10357
10358 CombineMaxThreadsClauses(TeamsThreadLimitClause, NumThreads);
10359 CombineMaxThreadsClauses(MaxThreadsClause, NumThreads);
10360
10361 NumThreadsC.push_back(NumThreads ? NumThreads : Builder.getInt32(0));
10362 }
10363
10364 unsigned NumTargetItems = Info.NumberOfPtrs;
10365 Value *RTLoc = RTLocOverride;
10366 if (!RTLoc) {
10367 uint32_t SrcLocStrSize;
10368 Constant *SrcLocStr =
10369 OMPBuilder.getOrCreateDefaultSrcLocStr(SrcLocStrSize);
10370 RTLoc = OMPBuilder.getOrCreateIdent(SrcLocStr, SrcLocStrSize,
10371 llvm::omp::IdentFlag(0), 0);
10372 }
10373
10374 Value *TripCount = RuntimeAttrs.LoopTripCount
10375 ? Builder.CreateIntCast(RuntimeAttrs.LoopTripCount,
10376 Builder.getInt64Ty(),
10377 /*isSigned=*/false)
10378 : Builder.getInt64(0);
10379
10380 // Request zero groupprivate bytes by default.
10381 if (!DynCGroupMem)
10382 DynCGroupMem = Builder.getInt32(0);
10383
10385 NumTargetItems, RTArgs, TripCount, NumTeamsC, NumThreadsC, DynCGroupMem,
10386 HasNoWait, /*StrictBlocks=*/false, /*StrictThreads=*/false,
10387 DynCGroupMemFallback);
10388
10389 // Assume no error was returned because TaskBodyCB and
10390 // EmitTargetCallFallbackCB don't produce any.
10392 // The presence of certain clauses on the target directive require the
10393 // explicit generation of the target task.
10394 if (RequiresOuterTargetTask)
10395 return OMPBuilder.emitTargetTask(TaskBodyCB, RuntimeAttrs.DeviceID,
10396 RTLoc, AllocaIP, Dependencies,
10397 KArgs.RTArgs, Info.HasNoWait);
10398
10399 return OMPBuilder.emitKernelLaunch(
10400 Builder, OutlinedFnID, EmitTargetCallFallbackCB, KArgs,
10401 RuntimeAttrs.DeviceID, RTLoc, AllocaIP);
10402 }());
10403
10404 Builder.restoreIP(AfterIP);
10405 return Error::success();
10406 };
10407
10408 // If we don't have an ID for the target region, it means an offload entry
10409 // wasn't created. In this case we just run the host fallback directly and
10410 // ignore any potential 'if' clauses.
10411 if (!OutlinedFnID)
10412 return EmitTargetCallElse(AllocaIP, Builder.saveIP(), DeallocBlocks);
10413
10414 // If there's no 'if' clause, only generate the kernel launch code path.
10415 if (!IfCond)
10416 return EmitTargetCallThen(AllocaIP, Builder.saveIP(), DeallocBlocks);
10417
10418 return OMPBuilder.emitIfClause(IfCond, EmitTargetCallThen, EmitTargetCallElse,
10419 AllocaIP);
10420}
10421
10423 const LocationDescription &Loc, bool IsOffloadEntry, InsertPointTy AllocaIP,
10424 InsertPointTy CodeGenIP, ArrayRef<BasicBlock *> DeallocBlocks,
10425 TargetDataInfo &Info, TargetRegionEntryInfo &EntryInfo,
10426 const TargetKernelDefaultAttrs &DefaultAttrs,
10427 const TargetKernelRuntimeAttrs &RuntimeAttrs, Value *IfCond,
10428 SmallVectorImpl<Value *> &Inputs, GenMapInfoCallbackTy GenMapInfoCB,
10431 CustomMapperCallbackTy CustomMapperCB, const DependenciesInfo &Dependencies,
10432 bool HasNowait, Value *DynCGroupMem,
10433 OMPDynGroupprivateFallbackType DynCGroupMemFallback, DebugLoc OutlinedFnLoc,
10434 Value *RTLocOverride) {
10435
10436 if (!updateToLocation(Loc))
10437 return InsertPointTy();
10438
10439 Builder.restoreIP(CodeGenIP);
10440
10441 Function *OutlinedFn;
10442 Constant *OutlinedFnID = nullptr;
10443 // The target region is outlined into its own function. The LLVM IR for
10444 // the target region itself is generated using the callbacks CBFunc
10445 // and ArgAccessorFuncCB
10447 *this, Builder, IsOffloadEntry, EntryInfo, DefaultAttrs, OutlinedFn,
10448 OutlinedFnID, Inputs, CBFunc, ArgAccessorFuncCB, OutlinedFnLoc))
10449 return Err;
10450
10451 // If we are not on the target device, then we need to generate code
10452 // to make a remote call (offload) to the previously outlined function
10453 // that represents the target region. Do that now.
10454 if (!Config.isTargetDevice()) {
10455 if (Error Err = emitTargetCall(
10456 *this, Builder, RTLocOverride, AllocaIP, DeallocBlocks, Info,
10457 DefaultAttrs, RuntimeAttrs, IfCond, OutlinedFn, OutlinedFnID,
10458 Inputs, GenMapInfoCB, CustomMapperCB, Dependencies, HasNowait,
10459 DynCGroupMem, DynCGroupMemFallback))
10460 return Err;
10461 }
10462 return Builder.saveIP();
10463}
10464
10465std::string OpenMPIRBuilder::getNameWithSeparators(ArrayRef<StringRef> Parts,
10466 StringRef FirstSeparator,
10467 StringRef Separator) {
10468 SmallString<128> Buffer;
10469 llvm::raw_svector_ostream OS(Buffer);
10470 StringRef Sep = FirstSeparator;
10471 for (StringRef Part : Parts) {
10472 OS << Sep << Part;
10473 Sep = Separator;
10474 }
10475 return OS.str().str();
10476}
10477
10478std::string
10480 return OpenMPIRBuilder::getNameWithSeparators(Parts, Config.firstSeparator(),
10481 Config.separator());
10482}
10483
10485 Type *Ty, const StringRef &Name, std::optional<unsigned> AddressSpace) {
10486 auto &Elem = *InternalVars.try_emplace(Name, nullptr).first;
10487 if (Elem.second) {
10488 assert(Elem.second->getValueType() == Ty &&
10489 "OMP internal variable has different type than requested");
10490 } else {
10491 // TODO: investigate the appropriate linkage type used for the global
10492 // variable for possibly changing that to internal or private, or maybe
10493 // create different versions of the function for different OMP internal
10494 // variables.
10495 const DataLayout &DL = M.getDataLayout();
10496 // TODO: Investigate why AMDGPU expects AS 0 for globals even though the
10497 // default global AS is 1.
10498 // See double-target-call-with-declare-target.f90 and
10499 // declare-target-vars-in-target-region.f90 libomptarget
10500 // tests.
10501 unsigned AddressSpaceVal = AddressSpace ? *AddressSpace
10502 : M.getTargetTriple().isAMDGPU()
10503 ? 0
10504 : DL.getDefaultGlobalsAddressSpace();
10505 auto Linkage = this->M.getTargetTriple().isWasm()
10508 auto *GV = new GlobalVariable(M, Ty, /*IsConstant=*/false, Linkage,
10509 Constant::getNullValue(Ty), Elem.first(),
10510 /*InsertBefore=*/nullptr,
10511 GlobalValue::NotThreadLocal, AddressSpaceVal);
10512 const llvm::Align TypeAlign = DL.getABITypeAlign(Ty);
10513 const llvm::Align PtrAlign = DL.getPointerABIAlignment(AddressSpaceVal);
10514 GV->setAlignment(std::max(TypeAlign, PtrAlign));
10515 Elem.second = GV;
10516 }
10517
10518 return Elem.second;
10519}
10520
10521Value *OpenMPIRBuilder::getOMPCriticalRegionLock(StringRef CriticalName) {
10522 std::string Prefix = Twine("gomp_critical_user_", CriticalName).str();
10523 std::string Name = getNameWithSeparators({Prefix, "var"}, ".", ".");
10524 return getOrCreateInternalVariable(KmpCriticalNameTy, Name);
10525}
10526
10528 LLVMContext &Ctx = Builder.getContext();
10529 Value *Null =
10530 Constant::getNullValue(PointerType::getUnqual(BasePtr->getContext()));
10531 Value *SizeGep =
10532 Builder.CreateGEP(BasePtr->getType(), Null, Builder.getInt32(1));
10533 Value *SizePtrToInt = Builder.CreatePtrToInt(SizeGep, Type::getInt64Ty(Ctx));
10534 return SizePtrToInt;
10535}
10536
10539 std::string VarName) {
10540 llvm::Constant *MaptypesArrayInit =
10541 llvm::ConstantDataArray::get(M.getContext(), Mappings);
10542 auto *MaptypesArrayGlobal = new llvm::GlobalVariable(
10543 M, MaptypesArrayInit->getType(),
10544 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage, MaptypesArrayInit,
10545 VarName);
10546 MaptypesArrayGlobal->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
10547 return MaptypesArrayGlobal;
10548}
10549
10551 InsertPointTy AllocaIP,
10552 unsigned NumOperands,
10553 struct MapperAllocas &MapperAllocas) {
10554 if (!updateToLocation(Loc))
10555 return;
10556
10557 auto *ArrI8PtrTy = ArrayType::get(Int8Ptr, NumOperands);
10558 auto *ArrI64Ty = ArrayType::get(Int64, NumOperands);
10559 Builder.restoreIP(AllocaIP);
10560 AllocaInst *ArgsBase = Builder.CreateAlloca(
10561 ArrI8PtrTy, /* ArraySize = */ nullptr, ".offload_baseptrs");
10562 AllocaInst *Args = Builder.CreateAlloca(ArrI8PtrTy, /* ArraySize = */ nullptr,
10563 ".offload_ptrs");
10564 AllocaInst *ArgSizes = Builder.CreateAlloca(
10565 ArrI64Ty, /* ArraySize = */ nullptr, ".offload_sizes");
10567 MapperAllocas.ArgsBase = ArgsBase;
10568 MapperAllocas.Args = Args;
10569 MapperAllocas.ArgSizes = ArgSizes;
10570}
10571
10573 Function *MapperFunc, Value *SrcLocInfo,
10574 Value *MaptypesArg, Value *MapnamesArg,
10576 int64_t DeviceID, unsigned NumOperands) {
10577 if (!updateToLocation(Loc))
10578 return;
10579
10580 auto *ArrI8PtrTy = ArrayType::get(Int8Ptr, NumOperands);
10581 auto *ArrI64Ty = ArrayType::get(Int64, NumOperands);
10582 Value *ArgsBaseGEP =
10583 Builder.CreateInBoundsGEP(ArrI8PtrTy, MapperAllocas.ArgsBase,
10584 {Builder.getInt32(0), Builder.getInt32(0)});
10585 Value *ArgsGEP =
10586 Builder.CreateInBoundsGEP(ArrI8PtrTy, MapperAllocas.Args,
10587 {Builder.getInt32(0), Builder.getInt32(0)});
10588 Value *ArgSizesGEP =
10589 Builder.CreateInBoundsGEP(ArrI64Ty, MapperAllocas.ArgSizes,
10590 {Builder.getInt32(0), Builder.getInt32(0)});
10591 Value *NullPtr =
10592 Constant::getNullValue(PointerType::getUnqual(Int8Ptr->getContext()));
10593 createRuntimeFunctionCall(MapperFunc, {SrcLocInfo, Builder.getInt64(DeviceID),
10594 Builder.getInt32(NumOperands),
10595 ArgsBaseGEP, ArgsGEP, ArgSizesGEP,
10596 MaptypesArg, MapnamesArg, NullPtr});
10597}
10598
10600 TargetDataRTArgs &RTArgs,
10601 TargetDataInfo &Info,
10602 bool ForEndCall) {
10603 assert((!ForEndCall || Info.separateBeginEndCalls()) &&
10604 "expected region end call to runtime only when end call is separate");
10605 auto UnqualPtrTy = PointerType::getUnqual(M.getContext());
10606 auto VoidPtrTy = UnqualPtrTy;
10607 auto VoidPtrPtrTy = UnqualPtrTy;
10608 auto Int64Ty = Type::getInt64Ty(M.getContext());
10609 auto Int64PtrTy = UnqualPtrTy;
10610
10611 RTArgs.NonContiguousDescriptors = Info.RTArgs.NonContiguousDescriptors;
10612 if (!Info.NumberOfPtrs) {
10613 RTArgs.BasePointersArray = ConstantPointerNull::get(VoidPtrPtrTy);
10614 RTArgs.PointersArray = ConstantPointerNull::get(VoidPtrPtrTy);
10615 RTArgs.SizesArray = ConstantPointerNull::get(Int64PtrTy);
10616 RTArgs.MapTypesArray = ConstantPointerNull::get(Int64PtrTy);
10617 RTArgs.MapNamesArray = ConstantPointerNull::get(VoidPtrPtrTy);
10618 RTArgs.MappersArray = ConstantPointerNull::get(VoidPtrPtrTy);
10619 return;
10620 }
10621
10622 RTArgs.BasePointersArray = Builder.CreateConstInBoundsGEP2_32(
10623 ArrayType::get(VoidPtrTy, Info.NumberOfPtrs),
10624 Info.RTArgs.BasePointersArray,
10625 /*Idx0=*/0, /*Idx1=*/0);
10626 RTArgs.PointersArray = Builder.CreateConstInBoundsGEP2_32(
10627 ArrayType::get(VoidPtrTy, Info.NumberOfPtrs), Info.RTArgs.PointersArray,
10628 /*Idx0=*/0,
10629 /*Idx1=*/0);
10630 RTArgs.SizesArray = Builder.CreateConstInBoundsGEP2_32(
10631 ArrayType::get(Int64Ty, Info.NumberOfPtrs), Info.RTArgs.SizesArray,
10632 /*Idx0=*/0, /*Idx1=*/0);
10633 RTArgs.MapTypesArray = Builder.CreateConstInBoundsGEP2_32(
10634 ArrayType::get(Int64Ty, Info.NumberOfPtrs),
10635 ForEndCall && Info.RTArgs.MapTypesArrayEnd ? Info.RTArgs.MapTypesArrayEnd
10636 : Info.RTArgs.MapTypesArray,
10637 /*Idx0=*/0,
10638 /*Idx1=*/0);
10639
10640 // Only emit the mapper information arrays if debug information is
10641 // requested.
10642 if (!Info.EmitDebug)
10643 RTArgs.MapNamesArray = ConstantPointerNull::get(VoidPtrPtrTy);
10644 else
10645 RTArgs.MapNamesArray = Builder.CreateConstInBoundsGEP2_32(
10646 ArrayType::get(VoidPtrTy, Info.NumberOfPtrs), Info.RTArgs.MapNamesArray,
10647 /*Idx0=*/0,
10648 /*Idx1=*/0);
10649 // If there is no user-defined mapper, set the mapper array to nullptr to
10650 // avoid an unnecessary data privatization
10651 if (!Info.HasMapper)
10652 RTArgs.MappersArray = ConstantPointerNull::get(VoidPtrPtrTy);
10653 else
10654 RTArgs.MappersArray =
10655 Builder.CreatePointerCast(Info.RTArgs.MappersArray, VoidPtrPtrTy);
10656}
10657
10659 InsertPointTy CodeGenIP,
10660 MapInfosTy &CombinedInfo,
10661 TargetDataInfo &Info) {
10663 CombinedInfo.NonContigInfo;
10664
10665 // Build an array of struct descriptor_dim and then assign it to
10666 // offload_args.
10667 //
10668 // struct descriptor_dim {
10669 // uint64_t offset;
10670 // uint64_t count;
10671 // uint64_t stride
10672 // };
10673 Type *Int64Ty = Builder.getInt64Ty();
10675 M.getContext(), ArrayRef<Type *>({Int64Ty, Int64Ty, Int64Ty}),
10676 "struct.descriptor_dim");
10677
10678 enum { OffsetFD = 0, CountFD, StrideFD };
10679 // We need two index variable here since the size of "Dims" is the same as
10680 // the size of Components, however, the size of offset, count, and stride is
10681 // equal to the size of base declaration that is non-contiguous.
10682 for (unsigned I = 0, L = 0, E = NonContigInfo.Dims.size(); I < E; ++I) {
10683 // Skip emitting ir if dimension size is 1 since it cannot be
10684 // non-contiguous.
10685 if (NonContigInfo.Dims[I] == 1)
10686 continue;
10687 Builder.restoreIP(AllocaIP);
10688 ArrayType *ArrayTy = ArrayType::get(DimTy, NonContigInfo.Dims[I]);
10689 AllocaInst *DimsAddr =
10690 Builder.CreateAlloca(ArrayTy, /* ArraySize = */ nullptr, "dims");
10691 Info.RTArgs.NonContiguousDescriptors.push_back({I, DimsAddr});
10692 Builder.restoreIP(CodeGenIP);
10693 for (unsigned II = 0, EE = NonContigInfo.Dims[I]; II < EE; ++II) {
10694 unsigned RevIdx = EE - II - 1;
10695 Value *DimsLVal = Builder.CreateInBoundsGEP(
10696 ArrayTy, DimsAddr, {Builder.getInt64(0), Builder.getInt64(II)});
10697 // Offset
10698 Value *OffsetLVal = Builder.CreateStructGEP(DimTy, DimsLVal, OffsetFD);
10699 Builder.CreateAlignedStore(
10700 NonContigInfo.Offsets[L][RevIdx], OffsetLVal,
10701 M.getDataLayout().getPrefTypeAlign(OffsetLVal->getType()));
10702 // Count
10703 Value *CountLVal = Builder.CreateStructGEP(DimTy, DimsLVal, CountFD);
10704 Builder.CreateAlignedStore(
10705 NonContigInfo.Counts[L][RevIdx], CountLVal,
10706 M.getDataLayout().getPrefTypeAlign(CountLVal->getType()));
10707 // Stride
10708 Value *StrideLVal = Builder.CreateStructGEP(DimTy, DimsLVal, StrideFD);
10709 Builder.CreateAlignedStore(
10710 NonContigInfo.Strides[L][RevIdx], StrideLVal,
10711 M.getDataLayout().getPrefTypeAlign(CountLVal->getType()));
10712 }
10713 // args[I] = &dims
10714 Builder.restoreIP(CodeGenIP);
10715 Value *DAddr = Builder.CreatePointerBitCastOrAddrSpaceCast(
10716 DimsAddr, Builder.getPtrTy());
10717 Value *P = Builder.CreateConstInBoundsGEP2_32(
10718 ArrayType::get(Builder.getPtrTy(), Info.NumberOfPtrs),
10719 Info.RTArgs.PointersArray, 0, I);
10720 Builder.CreateAlignedStore(
10721 DAddr, P, M.getDataLayout().getPrefTypeAlign(Builder.getPtrTy()));
10722 ++L;
10723 }
10724}
10725
10726void OpenMPIRBuilder::emitUDMapperArrayInitOrDel(
10727 Function *MapperFn, Value *MapperHandle, Value *Base, Value *Begin,
10728 Value *Size, Value *MapType, Value *MapName, TypeSize ElementSize,
10729 BasicBlock *ExitBB, bool IsInit) {
10730 StringRef Prefix = IsInit ? ".init" : ".del";
10731
10732 // Evaluate if this is an array section.
10734 M.getContext(), createPlatformSpecificName({"omp.array", Prefix}));
10735 Value *IsArray =
10736 Builder.CreateICmpSGT(Size, Builder.getInt64(1), "omp.arrayinit.isarray");
10737 Value *DeleteBit = Builder.CreateAnd(
10738 MapType,
10739 Builder.getInt64(
10740 static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>>(
10741 OpenMPOffloadMappingFlags::OMP_MAP_DELETE)));
10742 Value *DeleteCond;
10743 Value *Cond;
10744 if (IsInit) {
10745 // base != begin?
10746 Value *BaseIsBegin = Builder.CreateICmpNE(Base, Begin);
10747 Cond = Builder.CreateOr(IsArray, BaseIsBegin);
10748 DeleteCond = Builder.CreateIsNull(
10749 DeleteBit,
10750 createPlatformSpecificName({"omp.array", Prefix, ".delete"}));
10751 } else {
10752 Cond = IsArray;
10753 DeleteCond = Builder.CreateIsNotNull(
10754 DeleteBit,
10755 createPlatformSpecificName({"omp.array", Prefix, ".delete"}));
10756 }
10757 Cond = Builder.CreateAnd(Cond, DeleteCond);
10758 Builder.CreateCondBr(Cond, BodyBB, ExitBB);
10759
10760 emitBlock(BodyBB, MapperFn);
10761 // Get the array size by multiplying element size and element number (i.e., \p
10762 // Size).
10763 Value *ArraySize = Builder.CreateNUWMul(Size, Builder.getInt64(ElementSize));
10764 // Remove OMP_MAP_TO and OMP_MAP_FROM from the map type, so that it achieves
10765 // memory allocation/deletion purpose only.
10766 Value *MapTypeArg = Builder.CreateAnd(
10767 MapType,
10768 Builder.getInt64(
10769 ~static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>>(
10770 OpenMPOffloadMappingFlags::OMP_MAP_TO |
10771 OpenMPOffloadMappingFlags::OMP_MAP_FROM)));
10772 MapTypeArg = Builder.CreateOr(
10773 MapTypeArg,
10774 Builder.getInt64(
10775 static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>>(
10776 OpenMPOffloadMappingFlags::OMP_MAP_IMPLICIT)));
10777
10778 // Call the runtime API __tgt_push_mapper_component to fill up the runtime
10779 // data structure.
10780 Value *OffloadingArgs[] = {MapperHandle, Base, Begin,
10781 ArraySize, MapTypeArg, MapName};
10783 getOrCreateRuntimeFunction(M, OMPRTL___tgt_push_mapper_component),
10784 OffloadingArgs);
10785}
10786
10789 llvm::Value *BeginArg)>
10790 GenMapInfoCB,
10791 Type *ElemTy, StringRef FuncName, CustomMapperCallbackTy CustomMapperCB,
10792 bool PreserveMemberOfFlags, bool PropagatePresentToPointeeStorage,
10793 bool PropagatePresentToNonPointeeStorage) {
10794 SmallVector<Type *> Params;
10795 Params.emplace_back(Builder.getPtrTy());
10796 Params.emplace_back(Builder.getPtrTy());
10797 Params.emplace_back(Builder.getPtrTy());
10798 Params.emplace_back(Builder.getInt64Ty());
10799 Params.emplace_back(Builder.getInt64Ty());
10800 Params.emplace_back(Builder.getPtrTy());
10801
10802 auto *FnTy =
10803 FunctionType::get(Builder.getVoidTy(), Params, /* IsVarArg */ false);
10804
10805 Function *MapperFn =
10807 MapperFn->addFnAttr(Attribute::NoInline);
10808 MapperFn->addFnAttr(Attribute::NoUnwind);
10809 MapperFn->addParamAttr(0, Attribute::NoUndef);
10810 MapperFn->addParamAttr(1, Attribute::NoUndef);
10811 MapperFn->addParamAttr(2, Attribute::NoUndef);
10812 MapperFn->addParamAttr(3, Attribute::NoUndef);
10813 MapperFn->addParamAttr(4, Attribute::NoUndef);
10814 MapperFn->addParamAttr(5, Attribute::NoUndef);
10815
10816 // Start the mapper function code generation.
10817 BasicBlock *EntryBB = BasicBlock::Create(M.getContext(), "entry", MapperFn);
10819 Builder.SetInsertPoint(EntryBB);
10820 Builder.SetCurrentDebugLocation(llvm::DebugLoc());
10821
10822 Value *MapperHandle = MapperFn->getArg(0);
10823 Value *BaseIn = MapperFn->getArg(1);
10824 Value *BeginIn = MapperFn->getArg(2);
10825 Value *Size = MapperFn->getArg(3);
10826 Value *MapType = MapperFn->getArg(4);
10827 Value *MapName = MapperFn->getArg(5);
10828
10829 // Compute the starting and end addresses of array elements.
10830 // Prepare common arguments for array initiation and deletion.
10831 // Convert the size in bytes into the number of array elements.
10832 TypeSize ElementSize = M.getDataLayout().getTypeStoreSize(ElemTy);
10833 Size = Builder.CreateExactUDiv(Size, Builder.getInt64(ElementSize));
10834 Value *PtrBegin = BeginIn;
10835 Value *PtrEnd = Builder.CreateGEP(ElemTy, PtrBegin, Size);
10836
10837 // Emit array initiation if this is an array section and \p MapType indicates
10838 // that memory allocation is required.
10839 BasicBlock *HeadBB = BasicBlock::Create(M.getContext(), "omp.arraymap.head");
10840 emitUDMapperArrayInitOrDel(MapperFn, MapperHandle, BaseIn, BeginIn, Size,
10841 MapType, MapName, ElementSize, HeadBB,
10842 /*IsInit=*/true);
10843
10844 // Emit a for loop to iterate through SizeArg of elements and map all of them.
10845
10846 // Emit the loop header block.
10847 emitBlock(HeadBB, MapperFn);
10848 BasicBlock *BodyBB = BasicBlock::Create(M.getContext(), "omp.arraymap.body");
10849 BasicBlock *DoneBB = BasicBlock::Create(M.getContext(), "omp.done");
10850 // Evaluate whether the initial condition is satisfied.
10851 Value *IsEmpty =
10852 Builder.CreateICmpEQ(PtrBegin, PtrEnd, "omp.arraymap.isempty");
10853 Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
10854
10855 // Emit the loop body block.
10856 emitBlock(BodyBB, MapperFn);
10857 BasicBlock *LastBB = BodyBB;
10858 PHINode *PtrPHI =
10859 Builder.CreatePHI(PtrBegin->getType(), 2, "omp.arraymap.ptrcurrent");
10860 PtrPHI->addIncoming(PtrBegin, HeadBB);
10861
10862 // Get map clause information. Fill up the arrays with all mapped variables.
10863 MapInfosOrErrorTy Info = GenMapInfoCB(Builder.saveIP(), PtrPHI, BeginIn);
10864 if (!Info)
10865 return Info.takeError();
10866
10867 // Number of components already in the mapper handle, shifted into the
10868 // MEMBER_OF field; assigned below, once a conditional leading parent (if
10869 // any) has been pushed, and read by pushComponent through the reference
10870 // capture.
10871 Value *ShiftedPreviousSize = nullptr;
10872
10873 // Emits a single mapper sub-component: computes the MEMBER_OF-adjusted map
10874 // type, applies map-type-modifier propagation, and pushes it either via a
10875 // child mapper function or __tgt_push_mapper_component. Returns the last
10876 // basic block emitted, so callers can update the outer per-array-element
10877 // loop's PHI incoming block.
10878 //
10879 // Add MEMBER_OF (ShiftedPreviousSize) to group this sub-map with the
10880 // current array element (N = __tgt_mapper_num_components() at loop body
10881 // start).
10882 //
10883 // Example 1:
10884 // struct S { int x; int *p; };
10885 //
10886 // mapper: #pragma omp declare mapper(id: S s) map(s.x, s.p[0:10])
10887 // use: S arr[2]; ... map(arr)
10888 // entries per element:
10889 //
10890 // &arr[i], &arr[i].x, sizeof(int), MEMBER_OF(N)|TO|FROM
10891 // &arr[i].p[0], &arr[i].p[0], 10*sizeof(int), TO|FROM (*)
10892 // &arr[i].p, &arr[i].p[0], sizeof(int*), ATTACH (**)
10893 //
10894 // Example 2:
10895 // struct S1 { int x; int y; };
10896 // struct S2 { int z; S1 *s1p; };
10897 //
10898 // mapper: #pragma omp declare mapper(S2 s2) map(s2.z, s2.s1p->x,
10899 // s2.s1p->y)
10900 // use: S2 arr[2]; ... map(arr)
10901 // entries per element:
10902 //
10903 // &arr[i], &arr[i].z, sizeof(int), MEMBER_OF(N)|TO|FROM
10904 // &arr[i].s1p[0], &arr[i].s1p->x, sizeof(s1p->x..y), ALLOC (*)
10905 // &arr[i].s1p[0], &arr[i].s1p->x, 4, MEMBER_OF(N+2)|TO|FROM (*)(***)
10906 // &arr[i].s1p[0], &arr[i].s1p->y, 4, MEMBER_OF(N+2)|TO|FROM (*)(***)
10907 // &arr[i].s1p, &arr[i].s1p->x, sizeof(ptr), ATTACH (**)
10908 //
10909 // x/y carry inner MEMBER_OF(2)
10910 // which is shifted by N to become MEMBER_OF(N+2).
10911 //
10912 // HasAttachPtr is set on all of the s1p entries except the ATTACH one:
10913 // the combined ALLOC entry for the s1p->x..y block, and the individual
10914 // x/y entries that are MEMBER_OF that block, all describe storage
10915 // reached through the attach ptr arr[i].s1p.
10916 //
10917 // Entries of the following kinds do NOT receive a new outer MEMBER_OF
10918 // linking them to the parent struct:
10919 //
10920 // * (*) Entries with HasAttachPtr: they represent pointee data that
10921 // occupies a different storage block than the struct being mapped, so
10922 // they are not a member of it. They may still be MEMBER_OF an entry
10923 // within that pointee block, in which case those pre-existing bits are
10924 // shifted -- see (***).
10925 // * (**) ATTACH entries: they are not a member of anything — they just
10926 // link a ptr to its ptee.
10927 // * All entries when PreserveMemberOfFlags is set (the Flang/MLIR path):
10928 // its pre-shaped entries already carry their final MEMBER_OF bits.
10929 // TODO: set HasAttachPtr from Flang for entries whose storage is the
10930 // pointee's (e.g. s%p(0:10)) and drop PreserveMemberOfFlags in favor of
10931 // it.
10932 //
10933 // (***) If such an entry already has its own MEMBER_OF bits (e.g. the
10934 // s1p->x/y entries above), those bits are still shifted by N.
10935 auto pushComponent = [&](Value *CurBaseArg, Value *CurBeginArg,
10936 Value *CurSizeArg, Value *CurNameArg,
10937 uint64_t RawType, bool HasAttachPtrFlag,
10938 Function *ChildMapperFn) -> BasicBlock * {
10939 Value *OriMapType = Builder.getInt64(RawType);
10940 constexpr uint64_t MemberOfMask =
10941 static_cast<uint64_t>(OpenMPOffloadMappingFlags::OMP_MAP_MEMBER_OF);
10942 constexpr uint64_t AttachBit =
10943 static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>>(
10944 OpenMPOffloadMappingFlags::OMP_MAP_ATTACH);
10945 constexpr uint64_t PtrAndObjBit =
10946 static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>>(
10947 OpenMPOffloadMappingFlags::OMP_MAP_PTR_AND_OBJ);
10948
10949 Value *MemberMapType;
10950 if (PreserveMemberOfFlags || (RawType & AttachBit) || HasAttachPtrFlag) {
10951 if (RawType & MemberOfMask)
10952 MemberMapType = Builder.CreateNUWAdd(OriMapType, ShiftedPreviousSize);
10953 else
10954 MemberMapType = OriMapType;
10955 } else {
10956 MemberMapType = Builder.CreateNUWAdd(OriMapType, ShiftedPreviousSize);
10957 }
10958
10959 // Combine the map type inherited from user-defined mapper with that
10960 // specified in the program. According to the OMP_MAP_TO and OMP_MAP_FROM
10961 // bits of the \a MapType, which is the input argument of the mapper
10962 // function, the following code will set the OMP_MAP_TO and OMP_MAP_FROM
10963 // bits of MemberMapType.
10964 // [OpenMP 5.0], 1.2.6. map-type decay.
10965 // | alloc | to | from | tofrom | release | delete
10966 // ----------------------------------------------------------
10967 // alloc | alloc | alloc | alloc | alloc | release | delete
10968 // to | alloc | to | alloc | to | release | delete
10969 // from | alloc | alloc | from | from | release | delete
10970 // tofrom | alloc | to | from | tofrom | release | delete
10971 Value *LeftToFrom = Builder.CreateAnd(
10972 MapType,
10973 Builder.getInt64(
10974 static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>>(
10975 OpenMPOffloadMappingFlags::OMP_MAP_TO |
10976 OpenMPOffloadMappingFlags::OMP_MAP_FROM)));
10977 BasicBlock *AllocBB = BasicBlock::Create(M.getContext(), "omp.type.alloc");
10978 BasicBlock *AllocElseBB =
10979 BasicBlock::Create(M.getContext(), "omp.type.alloc.else");
10980 BasicBlock *ToBB = BasicBlock::Create(M.getContext(), "omp.type.to");
10981 BasicBlock *ToElseBB =
10982 BasicBlock::Create(M.getContext(), "omp.type.to.else");
10983 BasicBlock *FromBB = BasicBlock::Create(M.getContext(), "omp.type.from");
10984 BasicBlock *EndBB = BasicBlock::Create(M.getContext(), "omp.type.end");
10985 Value *IsAlloc = Builder.CreateIsNull(LeftToFrom);
10986 Builder.CreateCondBr(IsAlloc, AllocBB, AllocElseBB);
10987 // In case of alloc, clear OMP_MAP_TO and OMP_MAP_FROM.
10988 emitBlock(AllocBB, MapperFn);
10989 Value *AllocMapType = Builder.CreateAnd(
10990 MemberMapType,
10991 Builder.getInt64(
10992 ~static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>>(
10993 OpenMPOffloadMappingFlags::OMP_MAP_TO |
10994 OpenMPOffloadMappingFlags::OMP_MAP_FROM)));
10995 Builder.CreateBr(EndBB);
10996 emitBlock(AllocElseBB, MapperFn);
10997 Value *IsTo = Builder.CreateICmpEQ(
10998 LeftToFrom,
10999 Builder.getInt64(
11000 static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>>(
11001 OpenMPOffloadMappingFlags::OMP_MAP_TO)));
11002 Builder.CreateCondBr(IsTo, ToBB, ToElseBB);
11003 // In case of to, clear OMP_MAP_FROM.
11004 emitBlock(ToBB, MapperFn);
11005 Value *ToMapType = Builder.CreateAnd(
11006 MemberMapType,
11007 Builder.getInt64(
11008 ~static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>>(
11009 OpenMPOffloadMappingFlags::OMP_MAP_FROM)));
11010 Builder.CreateBr(EndBB);
11011 emitBlock(ToElseBB, MapperFn);
11012 Value *IsFrom = Builder.CreateICmpEQ(
11013 LeftToFrom,
11014 Builder.getInt64(
11015 static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>>(
11016 OpenMPOffloadMappingFlags::OMP_MAP_FROM)));
11017 Builder.CreateCondBr(IsFrom, FromBB, EndBB);
11018 // In case of from, clear OMP_MAP_TO.
11019 emitBlock(FromBB, MapperFn);
11020 Value *FromMapType = Builder.CreateAnd(
11021 MemberMapType,
11022 Builder.getInt64(
11023 ~static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>>(
11024 OpenMPOffloadMappingFlags::OMP_MAP_TO)));
11025 // In case of tofrom, do nothing.
11026 emitBlock(EndBB, MapperFn);
11027 PHINode *CurMapType =
11028 Builder.CreatePHI(Builder.getInt64Ty(), 4, "omp.maptype");
11029 CurMapType->addIncoming(AllocMapType, AllocBB);
11030 CurMapType->addIncoming(ToMapType, ToBB);
11031 CurMapType->addIncoming(FromMapType, FromBB);
11032 CurMapType->addIncoming(MemberMapType, ToElseBB);
11033
11034 // Propagate map-type-modifying bits from the outer map clause to each map
11035 // inserted by the mapper.
11036 //
11037 // OpenMP 6.0:281:34: The effect of the mapper modifier is to remove the
11038 // list item from the map clause and to apply the clauses specified in the
11039 // declared mapper to the construct on which the map clause appears...
11040 // If any modifier with the map-type-modifying property appears in the map
11041 // clause then the effect is as if that modifier appears in each map clause
11042 // specified in the declared mapper.
11043 //
11044 // Map-type-modifying bits: ALWAYS, DELETE, CLOSE, PRESENT.
11045 //
11046 // ALWAYS/DELETE/CLOSE are propagated to every (non-ATTACH) entry.
11047 //
11048 // PRESENT propagation is controlled independently for entries describing
11049 // pointee storage (HasAttachPtr) and entries describing non-pointee
11050 // storage. This lets frontends select current Clang behavior (pointee only)
11051 // or OpenMP 6.x behavior for mapper propagation (all eligible storage).
11052 // PRESENT is not propagated to ATTACH or PTR_AND_OBJ entries.
11053 //
11054 // Pointee storage is gated on \p PropagatePresentToPointeeStorage (set by
11055 // caller only for OpenMP >= 6.0). Before 6.0 the present modifier is
11056 // treated as not applying to the pointee: the spec committee confirmed the
11057 // divergence between the present "motion" modifier (to/from) and the
11058 // present map-type modifier (map) was unintentional, to be fixed as an
11059 // OpenMP 6.0 erratum, so for 5.2 present is ignored for the pointee for
11060 // both map and to/from.
11061 //
11062 // Non-pointee storage is gated on \p PropagatePresentToNonPointeeStorage:
11063 // PRESENT is ten propagated to the struct's own members (e.g. the s.x,
11064 // s.y of map(present, mapper(id): s)) so that an absent member triggers
11065 // the present-check.
11066 //
11067 // Present cannot be mapped to members with PTR_AND_OBJ, a single combined
11068 // entry allocates the whole struct (including the pointer's storage),
11069 // so propagating PRESENT to it would wrongly require the pointer's
11070 // pointee to be present.
11071 uint64_t ModifierBits =
11072 static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>>(
11073 OpenMPOffloadMappingFlags::OMP_MAP_ALWAYS |
11074 OpenMPOffloadMappingFlags::OMP_MAP_DELETE |
11075 OpenMPOffloadMappingFlags::OMP_MAP_CLOSE);
11076 bool IsPresentEligibleStorage = !(RawType & (AttachBit | PtrAndObjBit));
11077 bool PropagatePresent =
11078 IsPresentEligibleStorage &&
11079 (HasAttachPtrFlag ? PropagatePresentToPointeeStorage
11080 : PropagatePresentToNonPointeeStorage);
11081 if (PropagatePresent)
11082 ModifierBits |=
11083 static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>>(
11084 OpenMPOffloadMappingFlags::OMP_MAP_PRESENT);
11085 Value *ImportedModifierBits =
11086 Builder.CreateAnd(MapType, Builder.getInt64(ModifierBits));
11087 Value *CurMapTypeWithModifiers = Builder.CreateOr(
11088 CurMapType, ImportedModifierBits, "omp.maptype.with.modifiers");
11089
11090 // ATTACH entries must not receive map-type-modifying bits: ATTACH|ALWAYS is
11091 // reserved for the attach(always) map-type modifier, and other modifier
11092 // bits (DELETE, CLOSE) have no meaning for an ATTACH entry.
11093 Value *FinalMapType =
11094 (RawType & AttachBit) ? CurMapType : CurMapTypeWithModifiers;
11095
11096 Value *OffloadingArgs[] = {MapperHandle, CurBaseArg, CurBeginArg,
11097 CurSizeArg, FinalMapType, CurNameArg};
11098 if (ChildMapperFn) {
11099 // Call the corresponding mapper function.
11100 createRuntimeFunctionCall(ChildMapperFn, OffloadingArgs)
11101 ->setDoesNotThrow();
11102 } else {
11103 // Call the runtime API __tgt_push_mapper_component to fill up the runtime
11104 // data structure.
11106 getOrCreateRuntimeFunction(M, OMPRTL___tgt_push_mapper_component),
11107 OffloadingArgs);
11108 }
11109 return EndBB;
11110 };
11111
11112 // A leading parent synthesized for the dynamic segments is pushed only when
11113 // some segment will contribute components. Its own map type carries no
11114 // MEMBER_OF bits, so it does not read ShiftedPreviousSize.
11115 unsigned FirstStaticIdx = 0;
11116 if (Info->LeadingParentCond) {
11117 assert(PreserveMemberOfFlags &&
11118 "conditional leading parent requires pre-shaped MEMBER_OF flags");
11119 assert(!Info->BasePointers.empty() && "no leading parent component");
11120 BasicBlock *PushBB =
11121 BasicBlock::Create(M.getContext(), "omp.iterparent.push");
11122 BasicBlock *ContBB =
11123 BasicBlock::Create(M.getContext(), "omp.iterparent.cont");
11124 Builder.CreateCondBr(Info->LeadingParentCond, PushBB, ContBB);
11125 emitBlock(PushBB, MapperFn);
11126 Value *CurNameArg = Info->Names.size()
11127 ? Info->Names[0]
11128 : Constant::getNullValue(Builder.getPtrTy());
11129 pushComponent(
11130 Info->BasePointers[0], Info->Pointers[0], Info->Sizes[0], CurNameArg,
11131 static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>>(
11132 Info->Types[0]),
11133 Info->HasAttachPtr[0], /*ChildMapperFn=*/nullptr);
11134 Builder.CreateBr(ContBB);
11135 emitBlock(ContBB, MapperFn);
11136 LastBB = ContBB;
11137 FirstStaticIdx = 1;
11138 }
11139
11140 // Call the runtime API __tgt_mapper_num_components to get the number of
11141 // pre-existing components. The compile-time MEMBER_OF indices count the
11142 // leading parent as component 0 whether or not it was pushed; reading the
11143 // count after that push and subtracting one yields the right base in both
11144 // cases (N if pushed, N - 1 if skipped, N being the count at body start).
11145 Value *OffloadingArgs[] = {MapperHandle};
11146 Value *PreviousSize = createRuntimeFunctionCall(
11147 getOrCreateRuntimeFunction(M, OMPRTL___tgt_mapper_num_components),
11148 OffloadingArgs);
11149 if (Info->LeadingParentCond)
11150 PreviousSize = Builder.CreateSub(PreviousSize, Builder.getInt64(1));
11151 ShiftedPreviousSize =
11152 Builder.CreateShl(PreviousSize, Builder.getInt64(getFlagMemberOffset()));
11153
11154 // Fill up the runtime mapper handle for all statically-known components.
11155 for (unsigned I = FirstStaticIdx; I < Info->BasePointers.size(); ++I) {
11156 Value *CurNameArg = Info->Names.size()
11157 ? Info->Names[I]
11158 : Constant::getNullValue(Builder.getPtrTy());
11159 Expected<Function *> ChildMapperFn = CustomMapperCB(I);
11160 if (!ChildMapperFn)
11161 return ChildMapperFn.takeError();
11162 LastBB = pushComponent(
11163 Info->BasePointers[I], Info->Pointers[I], Info->Sizes[I], CurNameArg,
11164 static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>>(
11165 Info->Types[I]),
11166 Info->HasAttachPtr[I], *ChildMapperFn);
11167 }
11168
11169 // Fill up the runtime mapper handle for components whose count is only
11170 // known at runtime (produced by an `iterator` modifier on the mapper's own
11171 // map clause): push each one individually, from inside a generated loop,
11172 // via the same __tgt_push_mapper_component call used above.
11173 for (MapInfosTy::DynamicSegment &Seg : Info->DynamicSegments) {
11175 auto BodyGen = [&](InsertPointTy BodyIP, Value *LinearIV) -> Error {
11176 Builder.restoreIP(BodyIP);
11178 Seg.GenEntry(Builder, LinearIV);
11179 if (!EntryOrErr)
11180 return EntryOrErr.takeError();
11181 SmallVector<Value *, 3> &Entry = *EntryOrErr;
11182 pushComponent(
11183 Entry[0], Entry[1], Entry[2],
11184 Constant::getNullValue(Builder.getPtrTy()),
11185 static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>>(
11186 Seg.Type),
11187 Seg.HasAttachPtr, Seg.ChildMapperFn);
11188 return Error::success();
11189 };
11190 InsertPointOrErrorTy AfterIP =
11191 createIteratorLoop(Loc, Seg.Count, BodyGen, "mapper.iterator");
11192 if (!AfterIP)
11193 return AfterIP.takeError();
11194 Builder.restoreIP(*AfterIP);
11195 LastBB = Builder.GetInsertBlock();
11196 }
11197
11198 // Update the pointer to point to the next element that needs to be mapped,
11199 // and check whether we have mapped all elements.
11200 Value *PtrNext = Builder.CreateConstGEP1_32(ElemTy, PtrPHI, /*Idx0=*/1,
11201 "omp.arraymap.next");
11202 PtrPHI->addIncoming(PtrNext, LastBB);
11203 Value *IsDone = Builder.CreateICmpEQ(PtrNext, PtrEnd, "omp.arraymap.isdone");
11204 BasicBlock *ExitBB = BasicBlock::Create(M.getContext(), "omp.arraymap.exit");
11205 Builder.CreateCondBr(IsDone, ExitBB, BodyBB);
11206
11207 emitBlock(ExitBB, MapperFn);
11208 // Emit array deletion if this is an array section and \p MapType indicates
11209 // that deletion is required.
11210 emitUDMapperArrayInitOrDel(MapperFn, MapperHandle, BaseIn, BeginIn, Size,
11211 MapType, MapName, ElementSize, DoneBB,
11212 /*IsInit=*/false);
11213
11214 // Emit the function exit block.
11215 emitBlock(DoneBB, MapperFn, /*IsFinished=*/true);
11216
11217 Builder.CreateRetVoid();
11218 return MapperFn;
11219}
11220
11222 InsertPointTy AllocaIP, InsertPointTy CodeGenIP, MapInfosTy &CombinedInfo,
11223 TargetDataInfo &Info, CustomMapperCallbackTy CustomMapperCB,
11224 bool IsNonContiguous,
11225 function_ref<void(unsigned int, Value *)> DeviceAddrCB) {
11226
11227 // Reset the array information.
11228 Info.clearArrayInfo();
11229 Info.NumberOfPtrs = CombinedInfo.BasePointers.size();
11230
11231 if (Info.NumberOfPtrs == 0)
11232 return Error::success();
11233
11234 Builder.restoreIP(AllocaIP);
11235 // Detect if we have any capture size requiring runtime evaluation of the
11236 // size so that a constant array could be eventually used.
11237 ArrayType *PointerArrayType =
11238 ArrayType::get(Builder.getPtrTy(), Info.NumberOfPtrs);
11239
11240 Info.RTArgs.BasePointersArray = Builder.CreateAlloca(
11241 PointerArrayType, /* ArraySize = */ nullptr, ".offload_baseptrs");
11242
11243 Info.RTArgs.PointersArray = Builder.CreateAlloca(
11244 PointerArrayType, /* ArraySize = */ nullptr, ".offload_ptrs");
11245 AllocaInst *MappersArray = Builder.CreateAlloca(
11246 PointerArrayType, /* ArraySize = */ nullptr, ".offload_mappers");
11247 Info.RTArgs.MappersArray = MappersArray;
11248
11249 // If we don't have any VLA types or other types that require runtime
11250 // evaluation, we can use a constant array for the map sizes, otherwise we
11251 // need to fill up the arrays as we do for the pointers.
11252 Type *Int64Ty = Builder.getInt64Ty();
11253 SmallVector<Constant *> ConstSizes(CombinedInfo.Sizes.size(),
11254 ConstantInt::get(Int64Ty, 0));
11255 SmallBitVector RuntimeSizes(CombinedInfo.Sizes.size());
11256 for (unsigned I = 0, E = CombinedInfo.Sizes.size(); I < E; ++I) {
11257 bool IsNonContigEntry =
11258 IsNonContiguous &&
11259 (static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>>(
11260 CombinedInfo.Types[I] &
11261 OpenMPOffloadMappingFlags::OMP_MAP_NON_CONTIG) != 0);
11262 // For NON_CONTIG entries, ArgSizes stores the dimension count (number of
11263 // descriptor_dim records), not the byte size.
11264 if (IsNonContigEntry) {
11265 assert(I < CombinedInfo.NonContigInfo.Dims.size() &&
11266 "Index must be in-bounds for NON_CONTIG Dims array");
11267 const uint64_t DimCount = CombinedInfo.NonContigInfo.Dims[I];
11268 assert(DimCount > 0 && "NON_CONTIG DimCount must be > 0");
11269 ConstSizes[I] = ConstantInt::get(Int64Ty, DimCount);
11270 continue;
11271 }
11272 if (auto *CI = dyn_cast<Constant>(CombinedInfo.Sizes[I])) {
11273 if (!isa<ConstantExpr>(CI) && !isa<GlobalValue>(CI)) {
11274 ConstSizes[I] = CI;
11275 continue;
11276 }
11277 }
11278 RuntimeSizes.set(I);
11279 }
11280
11281 if (RuntimeSizes.all()) {
11282 ArrayType *SizeArrayType = ArrayType::get(Int64Ty, Info.NumberOfPtrs);
11283 Info.RTArgs.SizesArray = Builder.CreateAlloca(
11284 SizeArrayType, /* ArraySize = */ nullptr, ".offload_sizes");
11285 restoreIPandDebugLoc(Builder, CodeGenIP);
11286 } else {
11287 auto *SizesArrayInit = ConstantArray::get(
11288 ArrayType::get(Int64Ty, ConstSizes.size()), ConstSizes);
11289 std::string Name = createPlatformSpecificName({"offload_sizes"});
11290 auto *SizesArrayGbl =
11291 new GlobalVariable(M, SizesArrayInit->getType(), /*isConstant=*/true,
11292 GlobalValue::PrivateLinkage, SizesArrayInit, Name);
11293 SizesArrayGbl->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
11294
11295 if (!RuntimeSizes.any()) {
11296 Info.RTArgs.SizesArray = SizesArrayGbl;
11297 } else {
11298 unsigned IndexSize = M.getDataLayout().getIndexSizeInBits(0);
11299 Align OffloadSizeAlign = M.getDataLayout().getABIIntegerTypeAlignment(64);
11300 ArrayType *SizeArrayType = ArrayType::get(Int64Ty, Info.NumberOfPtrs);
11301 AllocaInst *Buffer = Builder.CreateAlloca(
11302 SizeArrayType, /* ArraySize = */ nullptr, ".offload_sizes");
11303 Buffer->setAlignment(OffloadSizeAlign);
11304 restoreIPandDebugLoc(Builder, CodeGenIP);
11305 Builder.CreateMemCpy(
11306 Buffer, M.getDataLayout().getPrefTypeAlign(Buffer->getType()),
11307 SizesArrayGbl, OffloadSizeAlign,
11308 Builder.getIntN(
11309 IndexSize,
11310 Buffer->getAllocationSize(M.getDataLayout())->getFixedValue()));
11311
11312 Info.RTArgs.SizesArray = Buffer;
11313 }
11314 restoreIPandDebugLoc(Builder, CodeGenIP);
11315 }
11316
11317 // The map types are always constant so we don't need to generate code to
11318 // fill arrays. Instead, we create an array constant.
11320 for (auto mapFlag : CombinedInfo.Types)
11321 Mapping.push_back(
11322 static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>>(
11323 mapFlag));
11324 std::string MaptypesName = createPlatformSpecificName({"offload_maptypes"});
11325 auto *MapTypesArrayGbl = createOffloadMaptypes(Mapping, MaptypesName);
11326 Info.RTArgs.MapTypesArray = MapTypesArrayGbl;
11327
11328 // The information types are only built if provided.
11329 if (!CombinedInfo.Names.empty()) {
11330 auto *MapNamesArrayGbl = createOffloadMapnames(
11331 CombinedInfo.Names, createPlatformSpecificName({"offload_mapnames"}));
11332 Info.RTArgs.MapNamesArray = MapNamesArrayGbl;
11333 Info.EmitDebug = true;
11334 } else {
11335 Info.RTArgs.MapNamesArray =
11337 Info.EmitDebug = false;
11338 }
11339
11340 // If there's a present map type modifier, it must not be applied to the end
11341 // of a region, so generate a separate map type array in that case.
11342 if (Info.separateBeginEndCalls()) {
11343 bool EndMapTypesDiffer = false;
11344 for (uint64_t &Type : Mapping) {
11345 if (Type & static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>>(
11346 OpenMPOffloadMappingFlags::OMP_MAP_PRESENT)) {
11347 Type &= ~static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>>(
11348 OpenMPOffloadMappingFlags::OMP_MAP_PRESENT);
11349 EndMapTypesDiffer = true;
11350 }
11351 }
11352 if (EndMapTypesDiffer) {
11353 MapTypesArrayGbl = createOffloadMaptypes(Mapping, MaptypesName);
11354 Info.RTArgs.MapTypesArrayEnd = MapTypesArrayGbl;
11355 }
11356 }
11357
11358 PointerType *PtrTy = Builder.getPtrTy();
11359 for (unsigned I = 0; I < Info.NumberOfPtrs; ++I) {
11360 Value *BPVal = CombinedInfo.BasePointers[I];
11361 Value *BP = Builder.CreateConstInBoundsGEP2_32(
11362 ArrayType::get(PtrTy, Info.NumberOfPtrs), Info.RTArgs.BasePointersArray,
11363 0, I);
11364 Builder.CreateAlignedStore(BPVal, BP,
11365 M.getDataLayout().getPrefTypeAlign(PtrTy));
11366
11367 if (Info.requiresDevicePointerInfo()) {
11368 if (CombinedInfo.DevicePointers[I] == DeviceInfoTy::Pointer) {
11369 CodeGenIP = Builder.saveIP();
11370 Builder.restoreIP(AllocaIP);
11371 Info.DevicePtrInfoMap[BPVal] = {BP, Builder.CreateAlloca(PtrTy)};
11372 restoreIPandDebugLoc(Builder, CodeGenIP);
11373 if (DeviceAddrCB)
11374 DeviceAddrCB(I, Info.DevicePtrInfoMap[BPVal].second);
11375 } else if (CombinedInfo.DevicePointers[I] == DeviceInfoTy::Address) {
11376 Info.DevicePtrInfoMap[BPVal] = {BP, BP};
11377 if (DeviceAddrCB)
11378 DeviceAddrCB(I, BP);
11379 }
11380 }
11381
11382 Value *PVal = CombinedInfo.Pointers[I];
11383 Value *P = Builder.CreateConstInBoundsGEP2_32(
11384 ArrayType::get(PtrTy, Info.NumberOfPtrs), Info.RTArgs.PointersArray, 0,
11385 I);
11386 // TODO: Check alignment correct.
11387 Builder.CreateAlignedStore(PVal, P,
11388 M.getDataLayout().getPrefTypeAlign(PtrTy));
11389
11390 if (RuntimeSizes.test(I)) {
11391 Value *S = Builder.CreateConstInBoundsGEP2_32(
11392 ArrayType::get(Int64Ty, Info.NumberOfPtrs), Info.RTArgs.SizesArray,
11393 /*Idx0=*/0,
11394 /*Idx1=*/I);
11395 Builder.CreateAlignedStore(Builder.CreateIntCast(CombinedInfo.Sizes[I],
11396 Int64Ty,
11397 /*isSigned=*/true),
11398 S, M.getDataLayout().getPrefTypeAlign(PtrTy));
11399 }
11400 // Fill up the mapper array.
11401 unsigned IndexSize = M.getDataLayout().getIndexSizeInBits(0);
11402 Value *MFunc = ConstantPointerNull::get(PtrTy);
11403
11404 auto CustomMFunc = CustomMapperCB(I);
11405 if (!CustomMFunc)
11406 return CustomMFunc.takeError();
11407 if (*CustomMFunc)
11408 MFunc = Builder.CreatePointerCast(*CustomMFunc, PtrTy);
11409
11410 Value *MAddr = Builder.CreateInBoundsGEP(
11411 PointerArrayType, MappersArray,
11412 {Builder.getIntN(IndexSize, 0), Builder.getIntN(IndexSize, I)});
11413 Builder.CreateAlignedStore(
11414 MFunc, MAddr, M.getDataLayout().getPrefTypeAlign(MAddr->getType()));
11415 }
11416
11417 if (!IsNonContiguous || CombinedInfo.NonContigInfo.Offsets.empty() ||
11418 Info.NumberOfPtrs == 0)
11419 return Error::success();
11420 emitNonContiguousDescriptor(AllocaIP, CodeGenIP, CombinedInfo, Info);
11421 return Error::success();
11422}
11423
11425 BasicBlock *CurBB = Builder.GetInsertBlock();
11426
11427 if (!CurBB || CurBB->hasTerminator()) {
11428 // If there is no insert point or the previous block is already
11429 // terminated, don't touch it.
11430 } else {
11431 // Otherwise, create a fall-through branch.
11432 Builder.CreateBr(Target);
11433 }
11434
11435 Builder.ClearInsertionPoint();
11436}
11437
11439 bool IsFinished) {
11440 BasicBlock *CurBB = Builder.GetInsertBlock();
11441
11442 // Fall out of the current block (if necessary).
11443 emitBranch(BB);
11444
11445 if (IsFinished && BB->use_empty()) {
11446 BB->eraseFromParent();
11447 return;
11448 }
11449
11450 // Place the block after the current block, if possible, or else at
11451 // the end of the function.
11452 if (CurBB && CurBB->getParent())
11453 CurFn->insert(std::next(CurBB->getIterator()), BB);
11454 else
11455 CurFn->insert(CurFn->end(), BB);
11456 Builder.SetInsertPoint(BB);
11457}
11458
11460 BodyGenCallbackTy ElseGen,
11461 InsertPointTy AllocaIP,
11462 ArrayRef<BasicBlock *> DeallocBlocks) {
11463 // If the condition constant folds and can be elided, try to avoid emitting
11464 // the condition and the dead arm of the if/else.
11465 if (auto *CI = dyn_cast<ConstantInt>(Cond)) {
11466 auto CondConstant = CI->getSExtValue();
11467 if (CondConstant)
11468 return ThenGen(AllocaIP, Builder.saveIP(), DeallocBlocks);
11469
11470 return ElseGen(AllocaIP, Builder.saveIP(), DeallocBlocks);
11471 }
11472
11473 Function *CurFn = Builder.GetInsertBlock()->getParent();
11474
11475 // Otherwise, the condition did not fold, or we couldn't elide it. Just
11476 // emit the conditional branch.
11477 BasicBlock *ThenBlock = BasicBlock::Create(M.getContext(), "omp_if.then");
11478 BasicBlock *ElseBlock = BasicBlock::Create(M.getContext(), "omp_if.else");
11479 BasicBlock *ContBlock = BasicBlock::Create(M.getContext(), "omp_if.end");
11480 Builder.CreateCondBr(Cond, ThenBlock, ElseBlock);
11481 // Emit the 'then' code.
11482 emitBlock(ThenBlock, CurFn);
11483 if (Error Err = ThenGen(AllocaIP, Builder.saveIP(), DeallocBlocks)) {
11484 // Let the function own the blocks not emitted yet so they are freed.
11485 ElseBlock->insertInto(CurFn);
11486 ContBlock->insertInto(CurFn);
11487 return Err;
11488 }
11489 emitBranch(ContBlock);
11490 // Emit the 'else' code if present.
11491 // There is no need to emit line number for unconditional branch.
11492 emitBlock(ElseBlock, CurFn);
11493 if (Error Err = ElseGen(AllocaIP, Builder.saveIP(), DeallocBlocks)) {
11494 ContBlock->insertInto(CurFn);
11495 return Err;
11496 }
11497 // There is no need to emit line number for unconditional branch.
11498 emitBranch(ContBlock);
11499 // Emit the continuation block for code after the if.
11500 emitBlock(ContBlock, CurFn, /*IsFinished=*/true);
11501 return Error::success();
11502}
11503
11507 AtomicOrdering AO, InsertPointTy AllocaIP) {
11508 if (!updateToLocation(Loc))
11509 return Loc.IP;
11510
11511 assert(X.Var->getType()->isPointerTy() &&
11512 "OMP Atomic expects a pointer to target memory");
11513 Type *XElemTy = X.ElemTy;
11514 assert((XElemTy->isFloatingPointTy() || XElemTy->isIntegerTy() ||
11515 XElemTy->isPointerTy() || XElemTy->isStructTy()) &&
11516 "OMP atomic read expected a scalar type");
11517
11518 Value *XRead = nullptr;
11519
11520 if (XElemTy->isIntegerTy()) {
11521 LoadInst *XLD =
11522 Builder.CreateLoad(XElemTy, X.Var, X.IsVolatile, "omp.atomic.read");
11523 XLD->setAtomic(AO);
11524 XRead = cast<Value>(XLD);
11525 } else if (XElemTy->isStructTy()) {
11526 // FIXME: Add checks to ensure __atomic_load is emitted iff the
11527 // target does not support `atomicrmw` of the size of the struct
11528 LoadInst *OldVal = Builder.CreateLoad(XElemTy, X.Var, "omp.atomic.read");
11529 OldVal->setAtomic(AO);
11530 const DataLayout &DL = OldVal->getDataLayout();
11531 unsigned LoadSize = DL.getTypeStoreSize(XElemTy);
11532 OpenMPIRBuilder::AtomicInfo atomicInfo(
11533 &Builder, XElemTy, LoadSize * 8, LoadSize * 8, OldVal->getAlign(),
11534 OldVal->getAlign(), true /* UseLibcall */, AllocaIP, X.Var);
11535 auto AtomicLoadRes = atomicInfo.EmitAtomicLoadLibcall(AO);
11536 XRead = AtomicLoadRes.first;
11537 OldVal->eraseFromParent();
11538 } else {
11539 // We need to perform atomic op as integer
11540 IntegerType *IntCastTy =
11541 IntegerType::get(M.getContext(), XElemTy->getScalarSizeInBits());
11542 LoadInst *XLoad =
11543 Builder.CreateLoad(IntCastTy, X.Var, X.IsVolatile, "omp.atomic.load");
11544 XLoad->setAtomic(AO);
11545 if (XElemTy->isFloatingPointTy()) {
11546 XRead = Builder.CreateBitCast(XLoad, XElemTy, "atomic.flt.cast");
11547 } else {
11548 XRead = Builder.CreateIntToPtr(XLoad, XElemTy, "atomic.ptr.cast");
11549 }
11550 }
11551 Builder.CreateStore(XRead, V.Var, V.IsVolatile);
11552 return Builder.saveIP();
11553}
11554
11557 AtomicOpValue &X, Value *Expr,
11558 AtomicOrdering AO, InsertPointTy AllocaIP) {
11559 if (!updateToLocation(Loc))
11560 return Loc.IP;
11561
11562 assert(X.Var->getType()->isPointerTy() &&
11563 "OMP Atomic expects a pointer to target memory");
11564 Type *XElemTy = X.ElemTy;
11565 assert((XElemTy->isFloatingPointTy() || XElemTy->isIntegerTy() ||
11566 XElemTy->isPointerTy() || XElemTy->isStructTy()) &&
11567 "OMP atomic write expected a scalar type");
11568
11569 if (XElemTy->isIntegerTy()) {
11570 StoreInst *XSt = Builder.CreateStore(Expr, X.Var, X.IsVolatile);
11571 XSt->setAtomic(AO);
11572 } else if (XElemTy->isStructTy()) {
11573 LoadInst *OldVal = Builder.CreateLoad(XElemTy, X.Var, "omp.atomic.read");
11574 const DataLayout &DL = OldVal->getDataLayout();
11575 unsigned LoadSize = DL.getTypeStoreSize(XElemTy);
11576 OpenMPIRBuilder::AtomicInfo atomicInfo(
11577 &Builder, XElemTy, LoadSize * 8, LoadSize * 8, OldVal->getAlign(),
11578 OldVal->getAlign(), true /* UseLibcall */, AllocaIP, X.Var);
11579 atomicInfo.EmitAtomicStoreLibcall(AO, Expr);
11580 OldVal->eraseFromParent();
11581 } else {
11582 // We need to bitcast and perform atomic op as integers
11583 IntegerType *IntCastTy =
11584 IntegerType::get(M.getContext(), XElemTy->getScalarSizeInBits());
11585 Value *ExprCast =
11586 Builder.CreateBitCast(Expr, IntCastTy, "atomic.src.int.cast");
11587 StoreInst *XSt = Builder.CreateStore(ExprCast, X.Var, X.IsVolatile);
11588 XSt->setAtomic(AO);
11589 }
11590
11591 return Builder.saveIP();
11592}
11593
11596 Value *Expr, AtomicOrdering AO, AtomicRMWInst::BinOp RMWOp,
11597 AtomicUpdateCallbackTy &UpdateOp, bool IsXBinopExpr,
11598 bool IsIgnoreDenormalMode, bool IsFineGrainedMemory, bool IsRemoteMemory) {
11599 assert(!isConflictIP(Loc.IP, AllocaIP) && "IPs must not be ambiguous");
11600 if (!updateToLocation(Loc))
11601 return Loc.IP;
11602
11603 LLVM_DEBUG({
11604 Type *XTy = X.Var->getType();
11605 assert(XTy->isPointerTy() &&
11606 "OMP Atomic expects a pointer to target memory");
11607 Type *XElemTy = X.ElemTy;
11608 assert((XElemTy->isFloatingPointTy() || XElemTy->isIntegerTy() ||
11609 XElemTy->isPointerTy() || XElemTy->isStructTy()) &&
11610 "OMP atomic update expected a scalar or struct type");
11611 });
11612
11613 Expected<std::pair<Value *, Value *>> AtomicResult = emitAtomicUpdate(
11614 AllocaIP, X.Var, X.ElemTy, Expr, AO, RMWOp, UpdateOp, X.IsVolatile,
11615 IsXBinopExpr, IsIgnoreDenormalMode, IsFineGrainedMemory, IsRemoteMemory);
11616 if (!AtomicResult)
11617 return AtomicResult.takeError();
11618 return Builder.saveIP();
11619}
11620
11621// FIXME: Duplicating AtomicExpand
11622Value *OpenMPIRBuilder::emitRMWOpAsInstruction(Value *Src1, Value *Src2,
11623 AtomicRMWInst::BinOp RMWOp) {
11624 switch (RMWOp) {
11625 case AtomicRMWInst::Add:
11626 return Builder.CreateAdd(Src1, Src2);
11627 case AtomicRMWInst::Sub:
11628 return Builder.CreateSub(Src1, Src2);
11629 case AtomicRMWInst::And:
11630 return Builder.CreateAnd(Src1, Src2);
11632 return Builder.CreateNeg(Builder.CreateAnd(Src1, Src2));
11633 case AtomicRMWInst::Or:
11634 return Builder.CreateOr(Src1, Src2);
11635 case AtomicRMWInst::Xor:
11636 return Builder.CreateXor(Src1, Src2);
11637 case AtomicRMWInst::Max:
11638 return Builder.CreateBinaryIntrinsic(Intrinsic::smax, Src1, Src2);
11639 case AtomicRMWInst::Min:
11640 return Builder.CreateBinaryIntrinsic(Intrinsic::smin, Src1, Src2);
11642 return Builder.CreateBinaryIntrinsic(Intrinsic::umax, Src1, Src2);
11644 return Builder.CreateBinaryIntrinsic(Intrinsic::umin, Src1, Src2);
11646 return Builder.CreateFAdd(Src1, Src2);
11648 return Builder.CreateFSub(Src1, Src2);
11650 return Builder.CreateMaxNum(Src1, Src2);
11652 return Builder.CreateMinNum(Src1, Src2);
11654 return Builder.CreateMaximum(Src1, Src2);
11656 return Builder.CreateMinimum(Src1, Src2);
11665 llvm_unreachable("Unsupported atomic update operation");
11666 }
11667 llvm_unreachable("Unsupported atomic update operation");
11668}
11669
11671 // Loads cannot use Release or AcquireRelease ordering. This load is
11672 // just the initial value for the cmpxchg loop; the cmpxchg itself
11673 // retains the original ordering.
11674 AtomicOrdering LoadAO = AO;
11675
11676 if (AO == AtomicOrdering::Release) {
11678 } else if (AO == AtomicOrdering::AcquireRelease) {
11679 LoadAO = AtomicOrdering::Acquire;
11680 }
11681
11682 return LoadAO;
11683}
11684
11685Expected<std::pair<Value *, Value *>> OpenMPIRBuilder::emitAtomicUpdate(
11686 InsertPointTy AllocaIP, Value *X, Type *XElemTy, Value *Expr,
11688 AtomicUpdateCallbackTy &UpdateOp, bool VolatileX, bool IsXBinopExpr,
11689 bool IsIgnoreDenormalMode, bool IsFineGrainedMemory, bool IsRemoteMemory) {
11690 // TODO: handle the case where XElemTy is not byte-sized or not a power of 2.
11691 bool emitRMWOp = false;
11692 switch (RMWOp) {
11693 case AtomicRMWInst::Add:
11694 case AtomicRMWInst::And:
11696 case AtomicRMWInst::Or:
11697 case AtomicRMWInst::Xor:
11699 case AtomicRMWInst::Max:
11700 case AtomicRMWInst::Min:
11708 emitRMWOp = XElemTy;
11709 break;
11710 case AtomicRMWInst::Sub:
11712 emitRMWOp = (IsXBinopExpr && XElemTy);
11713 break;
11714 default:
11715 emitRMWOp = false;
11716 }
11717 emitRMWOp &=
11718 (XElemTy->isIntegerTy() || XElemTy->isFloatTy() || XElemTy->isDoubleTy());
11719
11720 std::pair<Value *, Value *> Res;
11721 if (emitRMWOp) {
11722 AtomicRMWInst *RMWInst =
11723 Builder.CreateAtomicRMW(RMWOp, X, Expr, llvm::MaybeAlign(), AO);
11724 if (IsIgnoreDenormalMode)
11725 RMWInst->setMetadata(llvm::LLVMContext::MD_atomic_ignore_denormal_mode,
11726 llvm::MDNode::get(Builder.getContext(), {}));
11727 if (T.isAMDGPU()) {
11728 if (!IsFineGrainedMemory)
11729 RMWInst->setMetadata("amdgpu.no.fine.grained.memory",
11730 llvm::MDNode::get(Builder.getContext(), {}));
11731 if (!IsRemoteMemory)
11732 RMWInst->setMetadata("amdgpu.no.remote.memory",
11733 llvm::MDNode::get(Builder.getContext(), {}));
11734 }
11735 Res.first = RMWInst;
11736 // not needed except in case of postfix captures. Generate anyway for
11737 // consistency with the else part. Will be removed with any DCE pass.
11738 // AtomicRMWInst::Xchg does not have a coressponding instruction.
11739 if (RMWOp == AtomicRMWInst::Xchg)
11740 Res.second = Res.first;
11741 else
11742 Res.second = emitRMWOpAsInstruction(Res.first, Expr, RMWOp);
11743 } else if (XElemTy->isStructTy()) {
11744 LoadInst *OldVal =
11745 Builder.CreateLoad(XElemTy, X, X->getName() + ".atomic.load");
11747 OldVal->setAtomic(LoadAO);
11748 const DataLayout &LoadDL = OldVal->getDataLayout();
11749 unsigned LoadSize = LoadDL.getTypeStoreSize(XElemTy);
11750
11751 OpenMPIRBuilder::AtomicInfo atomicInfo(
11752 &Builder, XElemTy, LoadSize * 8, LoadSize * 8, OldVal->getAlign(),
11753 OldVal->getAlign(), true /* UseLibcall */, AllocaIP, X);
11754 auto AtomicLoadRes = atomicInfo.EmitAtomicLoadLibcall(AO);
11755 BasicBlock *CurBB = Builder.GetInsertBlock();
11756 Instruction *CurBBTI = CurBB->getTerminatorOrNull();
11757 CurBBTI = CurBBTI ? CurBBTI : Builder.CreateUnreachable();
11758 BasicBlock *ExitBB =
11759 CurBB->splitBasicBlock(CurBBTI, X->getName() + ".atomic.exit");
11760 BasicBlock *ContBB = CurBB->splitBasicBlock(CurBB->getTerminator(),
11761 X->getName() + ".atomic.cont");
11762 ContBB->getTerminator()->eraseFromParent();
11763 Builder.restoreIP(AllocaIP);
11764 AllocaInst *NewAtomicAddr = Builder.CreateAlloca(XElemTy);
11765 NewAtomicAddr->setName(X->getName() + "x.new.val");
11766 Builder.SetInsertPoint(ContBB);
11767 llvm::PHINode *PHI = Builder.CreatePHI(OldVal->getType(), 2);
11768 PHI->addIncoming(AtomicLoadRes.first, CurBB);
11769 Value *OldExprVal = PHI;
11770 Expected<Value *> CBResult = UpdateOp(OldExprVal, Builder);
11771 if (!CBResult)
11772 return CBResult.takeError();
11773 Value *Upd = *CBResult;
11774 Builder.CreateStore(Upd, NewAtomicAddr);
11777 auto Result = atomicInfo.EmitAtomicCompareExchangeLibcall(
11778 AtomicLoadRes.second, NewAtomicAddr, AO, Failure);
11779 LoadInst *PHILoad = Builder.CreateLoad(XElemTy, Result.first);
11780 PHI->addIncoming(PHILoad, Builder.GetInsertBlock());
11781 Builder.CreateCondBr(Result.second, ExitBB, ContBB);
11782 OldVal->eraseFromParent();
11783 Res.first = OldExprVal;
11784 Res.second = Upd;
11785
11786 if (UnreachableInst *ExitTI =
11788 CurBBTI->eraseFromParent();
11789 Builder.SetInsertPoint(ExitBB);
11790 } else {
11791 Builder.SetInsertPoint(ExitTI);
11792 }
11793 } else {
11794 IntegerType *IntCastTy =
11795 IntegerType::get(M.getContext(), XElemTy->getScalarSizeInBits());
11796 LoadInst *OldVal =
11797 Builder.CreateLoad(IntCastTy, X, X->getName() + ".atomic.load");
11799 OldVal->setAtomic(LoadAO);
11800 // CurBB
11801 // | /---\
11802 // ContBB |
11803 // | \---/
11804 // ExitBB
11805 BasicBlock *CurBB = Builder.GetInsertBlock();
11806 Instruction *CurBBTI = CurBB->getTerminatorOrNull();
11807 CurBBTI = CurBBTI ? CurBBTI : Builder.CreateUnreachable();
11808 BasicBlock *ExitBB =
11809 CurBB->splitBasicBlock(CurBBTI, X->getName() + ".atomic.exit");
11810 BasicBlock *ContBB = CurBB->splitBasicBlock(CurBB->getTerminator(),
11811 X->getName() + ".atomic.cont");
11812 ContBB->getTerminator()->eraseFromParent();
11813 Builder.restoreIP(AllocaIP);
11814 AllocaInst *NewAtomicAddr = Builder.CreateAlloca(XElemTy);
11815 NewAtomicAddr->setName(X->getName() + "x.new.val");
11816 Builder.SetInsertPoint(ContBB);
11817 llvm::PHINode *PHI = Builder.CreatePHI(OldVal->getType(), 2);
11818 PHI->addIncoming(OldVal, CurBB);
11819 bool IsIntTy = XElemTy->isIntegerTy();
11820 Value *OldExprVal = PHI;
11821 if (!IsIntTy) {
11822 if (XElemTy->isFloatingPointTy()) {
11823 OldExprVal = Builder.CreateBitCast(PHI, XElemTy,
11824 X->getName() + ".atomic.fltCast");
11825 } else {
11826 OldExprVal = Builder.CreateIntToPtr(PHI, XElemTy,
11827 X->getName() + ".atomic.ptrCast");
11828 }
11829 }
11830
11831 Expected<Value *> CBResult = UpdateOp(OldExprVal, Builder);
11832 if (!CBResult)
11833 return CBResult.takeError();
11834 Value *Upd = *CBResult;
11835 Builder.CreateStore(Upd, NewAtomicAddr);
11836 LoadInst *DesiredVal = Builder.CreateLoad(IntCastTy, NewAtomicAddr);
11839 AtomicCmpXchgInst *Result = Builder.CreateAtomicCmpXchg(
11840 X, PHI, DesiredVal, llvm::MaybeAlign(), AO, Failure);
11841 Result->setVolatile(VolatileX);
11842 Value *PreviousVal = Builder.CreateExtractValue(Result, /*Idxs=*/0);
11843 Value *SuccessFailureVal = Builder.CreateExtractValue(Result, /*Idxs=*/1);
11844 PHI->addIncoming(PreviousVal, Builder.GetInsertBlock());
11845 Builder.CreateCondBr(SuccessFailureVal, ExitBB, ContBB);
11846
11847 Res.first = OldExprVal;
11848 Res.second = Upd;
11849
11850 // set Insertion point in exit block
11851 if (UnreachableInst *ExitTI =
11853 CurBBTI->eraseFromParent();
11854 Builder.SetInsertPoint(ExitBB);
11855 } else {
11856 Builder.SetInsertPoint(ExitTI);
11857 }
11858 }
11859
11860 return Res;
11861}
11862
11865 AtomicOpValue &V, Value *Expr, AtomicOrdering AO,
11866 AtomicRMWInst::BinOp RMWOp, AtomicUpdateCallbackTy &UpdateOp,
11867 bool UpdateExpr, bool IsPostfixUpdate, bool IsXBinopExpr,
11868 bool IsIgnoreDenormalMode, bool IsFineGrainedMemory, bool IsRemoteMemory) {
11869 if (!updateToLocation(Loc))
11870 return Loc.IP;
11871
11872 LLVM_DEBUG({
11873 Type *XTy = X.Var->getType();
11874 assert(XTy->isPointerTy() &&
11875 "OMP Atomic expects a pointer to target memory");
11876 Type *XElemTy = X.ElemTy;
11877 assert((XElemTy->isFloatingPointTy() || XElemTy->isIntegerTy() ||
11878 XElemTy->isPointerTy() || XElemTy->isStructTy()) &&
11879 "OMP atomic capture expected a scalar or struct type");
11880 });
11881
11882 // If UpdateExpr is 'x' updated with some `expr` not based on 'x',
11883 // 'x' is simply atomically rewritten with 'expr'.
11884 AtomicRMWInst::BinOp AtomicOp = (UpdateExpr ? RMWOp : AtomicRMWInst::Xchg);
11885 Expected<std::pair<Value *, Value *>> AtomicResult = emitAtomicUpdate(
11886 AllocaIP, X.Var, X.ElemTy, Expr, AO, AtomicOp, UpdateOp, X.IsVolatile,
11887 IsXBinopExpr, IsIgnoreDenormalMode, IsFineGrainedMemory, IsRemoteMemory);
11888 if (!AtomicResult)
11889 return AtomicResult.takeError();
11890 Value *CapturedVal =
11891 (IsPostfixUpdate ? AtomicResult->first : AtomicResult->second);
11892 Builder.CreateStore(CapturedVal, V.Var, V.IsVolatile);
11893
11894 return Builder.saveIP();
11895}
11896
11900 omp::OMPAtomicCompareOp Op, bool IsXBinopExpr, bool IsPostfixUpdate,
11901 bool IsFailOnly, bool IsWeak) {
11902
11904 return createAtomicCompare(Loc, X, V, R, E, D, AO, Op, IsXBinopExpr,
11905 IsPostfixUpdate, IsFailOnly, Failure, IsWeak);
11906}
11907
11911 omp::OMPAtomicCompareOp Op, bool IsXBinopExpr, bool IsPostfixUpdate,
11912 bool IsFailOnly, AtomicOrdering Failure, bool IsWeak) {
11913
11914 if (!updateToLocation(Loc))
11915 return Loc.IP;
11916
11917 assert(X.Var->getType()->isPointerTy() &&
11918 "OMP atomic expects a pointer to target memory");
11919 // compare capture
11920 if (V.Var) {
11921 assert(V.Var->getType()->isPointerTy() && "v.var must be of pointer type");
11922 assert(V.ElemTy == X.ElemTy && "x and v must be of same type");
11923 }
11924
11925 bool IsInteger = E->getType()->isIntegerTy();
11926
11927 if (Op == OMPAtomicCompareOp::EQ) {
11928 // OldValue and SuccessOrFail are set below and used in the shared V.Var /
11929 // R.Var handling.
11930 Value *OldValue = nullptr;
11931 Value *SuccessOrFail = nullptr;
11932
11933 if (!IsInteger && HandleFPNegZero) {
11934 // IEEE 754 special cases for cmpxchg (which is bitwise):
11935 // 1. -0.0 == +0.0 but they have different bit patterns.
11936 // 2. NaN != NaN but identical NaN bit patterns would match.
11937 //
11938 // CurBB:
11939 // %e_int = bitcast E to intN
11940 // %d_int = bitcast D to intN
11941 // %x_curr = load atomic intN, X
11942 // %x_fp = bitcast %x_curr to FP
11943 // %e_is_nan = fcmp uno E, E
11944 // %x_is_nan = fcmp uno %x_fp, %x_fp
11945 // %either_nan = or %e_is_nan, %x_is_nan
11946 // br %either_nan, NaNBB, NotNaNBB
11947 // NaNBB: ; NaN == anything is always false
11948 // br ExitBB
11949 // NotNaNBB:
11950 // %x_is_zero = fcmp oeq %x_fp, 0.0
11951 // %e_is_zero = fcmp oeq E, 0.0
11952 // %both_zero = and %x_is_zero, %e_is_zero
11953 // br %both_zero, ZeroBB, NormalBB
11954 // ZeroBB: ; both ±0.0 → x = d
11955 // cmpxchg X, %x_curr, %d_int
11956 // br ExitBB
11957 // NormalBB: ; original path
11958 // cmpxchg X, %e_int, %d_int
11959 // br ExitBB
11960 // ExitBB:
11961 // phi merge
11962 IntegerType *IntCastTy =
11963 IntegerType::get(M.getContext(), X.ElemTy->getScalarSizeInBits());
11964 Value *EBCast = Builder.CreateBitCast(E, IntCastTy);
11965 Value *DBCast = Builder.CreateBitCast(D, IntCastTy);
11966
11967 // Load X atomically.
11968 LoadInst *XCurr = Builder.CreateLoad(IntCastTy, X.Var,
11969 X.Var->getName() + ".atomic.load");
11971 Value *XFP = Builder.CreateBitCast(XCurr, X.ElemTy);
11972
11973 // IEEE 754: NaN != NaN, but cmpxchg would succeed if E and X have
11974 // the same NaN bit pattern. Skip cmpxchg when either is NaN.
11975 Value *EIsNaN = Builder.CreateFCmpUNO(E, E, "atomic.e.isnan");
11976 Value *XIsNaN = Builder.CreateFCmpUNO(XFP, XFP, "atomic.x.isnan");
11977 Value *EitherNaN = Builder.CreateOr(EIsNaN, XIsNaN, "atomic.either.nan");
11978
11979 BasicBlock *CurBB = Builder.GetInsertBlock();
11980 Function *F = CurBB->getParent();
11981 Instruction *CurBBTI = CurBB->getTerminatorOrNull();
11982 CurBBTI = CurBBTI ? CurBBTI : Builder.CreateUnreachable();
11983 BasicBlock *ExitBB =
11984 CurBB->splitBasicBlock(CurBBTI, X.Var->getName() + ".atomic.exit");
11986 M.getContext(), X.Var->getName() + ".atomic.nan", F, ExitBB);
11987 BasicBlock *NotNaNBB = BasicBlock::Create(
11988 M.getContext(), X.Var->getName() + ".atomic.notnan", F, ExitBB);
11990 M.getContext(), X.Var->getName() + ".atomic.zero", F, ExitBB);
11991 BasicBlock *NormalBB = BasicBlock::Create(
11992 M.getContext(), X.Var->getName() + ".atomic.normal", F, ExitBB);
11993
11994 // If either E or X is NaN → NaNBB (always fails), else check for ±0.0.
11995 CurBB->getTerminator()->eraseFromParent();
11996 Builder.SetInsertPoint(CurBB);
11997 Builder.CreateCondBr(EitherNaN, NaNBB, NotNaNBB);
11998
11999 // NaNBB: NaN == anything is always false; skip cmpxchg.
12000 Builder.SetInsertPoint(NaNBB);
12001 Builder.CreateBr(ExitBB);
12002
12003 // NotNaNBB: check both X and E for ±0.0.
12004 Builder.SetInsertPoint(NotNaNBB);
12005 Value *XIsZero =
12006 Builder.CreateFCmpOEQ(XFP, ConstantFP::getZero(X.ElemTy),
12007 X.Var->getName() + ".atomic.xiszero");
12008 Value *EIsZero = Builder.CreateFCmpOEQ(E, ConstantFP::getZero(X.ElemTy),
12009 "atomic.e.iszero");
12010 Value *BothZero = Builder.CreateAnd(XIsZero, EIsZero, "atomic.both.zero");
12011 Builder.CreateCondBr(BothZero, ZeroBB, NormalBB);
12012
12013 // ZeroBB: cmpxchg with X's loaded bit-pattern.
12014 Builder.SetInsertPoint(ZeroBB);
12015 AtomicCmpXchgInst *ResZero = Builder.CreateAtomicCmpXchg(
12016 X.Var, XCurr, DBCast, MaybeAlign(), AO, Failure);
12017 ResZero->setWeak(IsWeak);
12018 Value *OldZero = Builder.CreateExtractValue(ResZero, /*Idxs=*/0);
12019 Value *OkZero = Builder.CreateExtractValue(ResZero, /*Idxs=*/1);
12020 Builder.CreateBr(ExitBB);
12021
12022 // NormalBB: original bitwise cmpxchg.
12023 Builder.SetInsertPoint(NormalBB);
12024 AtomicCmpXchgInst *ResNormal = Builder.CreateAtomicCmpXchg(
12025 X.Var, EBCast, DBCast, MaybeAlign(), AO, Failure);
12026 ResNormal->setWeak(IsWeak);
12027 Value *OldNormal = Builder.CreateExtractValue(ResNormal, /*Idxs=*/0);
12028 Value *OkNormal = Builder.CreateExtractValue(ResNormal, /*Idxs=*/1);
12029 Builder.CreateBr(ExitBB);
12030
12031 // ExitBB: merge results from NaN, Zero, and Normal paths.
12032 Builder.SetInsertPoint(ExitBB->begin());
12033 PHINode *OldIntPHI =
12034 Builder.CreatePHI(IntCastTy, 3, X.Var->getName() + ".atomic.old");
12035 OldIntPHI->addIncoming(XCurr, NaNBB);
12036 OldIntPHI->addIncoming(OldZero, ZeroBB);
12037 OldIntPHI->addIncoming(OldNormal, NormalBB);
12038 PHINode *SuccessPHI = Builder.CreatePHI(Builder.getInt1Ty(), 3,
12039 X.Var->getName() + ".atomic.ok");
12040 SuccessPHI->addIncoming(Builder.getFalse(), NaNBB);
12041 SuccessPHI->addIncoming(OkZero, ZeroBB);
12042 SuccessPHI->addIncoming(OkNormal, NormalBB);
12043
12044 if (isa<UnreachableInst>(ExitBB->getTerminator())) {
12045 CurBBTI->eraseFromParent();
12046 Builder.SetInsertPoint(ExitBB);
12047 } else {
12048 Builder.SetInsertPoint(&*ExitBB->getFirstNonPHIIt());
12049 }
12050
12051 OldValue = Builder.CreateBitCast(OldIntPHI, X.ElemTy,
12052 X.Var->getName() + ".atomic.old.fp");
12053 SuccessOrFail = SuccessPHI;
12054 } else {
12055 AtomicCmpXchgInst *Result = nullptr;
12056 if (!IsInteger) {
12057 IntegerType *IntCastTy =
12058 IntegerType::get(M.getContext(), X.ElemTy->getScalarSizeInBits());
12059 Value *EBCast = Builder.CreateBitCast(E, IntCastTy);
12060 Value *DBCast = Builder.CreateBitCast(D, IntCastTy);
12061 Result = Builder.CreateAtomicCmpXchg(X.Var, EBCast, DBCast,
12062 MaybeAlign(), AO, Failure);
12063 } else {
12064 Result =
12065 Builder.CreateAtomicCmpXchg(X.Var, E, D, MaybeAlign(), AO, Failure);
12066 }
12067 Result->setWeak(IsWeak);
12068
12069 if (V.Var) {
12070 OldValue = Builder.CreateExtractValue(Result, /*Idxs=*/0);
12071 if (!IsInteger)
12072 OldValue = Builder.CreateBitCast(OldValue, X.ElemTy);
12073 assert(OldValue->getType() == V.ElemTy &&
12074 "OldValue and V must be of same type");
12075 if (IsPostfixUpdate) {
12076 Builder.CreateStore(OldValue, V.Var, V.IsVolatile);
12077 } else {
12078 SuccessOrFail = Builder.CreateExtractValue(Result, /*Idxs=*/1);
12079 if (IsFailOnly) {
12080 BasicBlock *CurBB = Builder.GetInsertBlock();
12081 Instruction *CurBBTI = CurBB->getTerminatorOrNull();
12082 CurBBTI = CurBBTI ? CurBBTI : Builder.CreateUnreachable();
12083 BasicBlock *ExitBB = CurBB->splitBasicBlock(
12084 CurBBTI, X.Var->getName() + ".atomic.exit");
12085 BasicBlock *ContBB = CurBB->splitBasicBlock(
12086 CurBB->getTerminator(), X.Var->getName() + ".atomic.cont");
12087 ContBB->getTerminator()->eraseFromParent();
12088 CurBB->getTerminator()->eraseFromParent();
12089
12090 Builder.CreateCondBr(SuccessOrFail, ExitBB, ContBB);
12091
12092 Builder.SetInsertPoint(ContBB);
12093 Builder.CreateStore(OldValue, V.Var);
12094 Builder.CreateBr(ExitBB);
12095
12096 if (UnreachableInst *ExitTI =
12098 CurBBTI->eraseFromParent();
12099 Builder.SetInsertPoint(ExitBB);
12100 } else {
12101 Builder.SetInsertPoint(ExitTI);
12102 }
12103 } else {
12104 Value *CapturedValue =
12105 Builder.CreateSelect(SuccessOrFail, E, OldValue);
12106 Builder.CreateStore(CapturedValue, V.Var, V.IsVolatile);
12107 }
12108 }
12109 }
12110 // The comparison result has to be stored.
12111 if (R.Var) {
12112 assert(R.Var->getType()->isPointerTy() &&
12113 "r.var must be of pointer type");
12114 assert(R.ElemTy->isIntegerTy() && "r must be of integral type");
12115
12116 Value *SuccessFailureVal =
12117 Builder.CreateExtractValue(Result, /*Idxs=*/1);
12118 Value *ResultCast =
12119 R.IsSigned ? Builder.CreateSExt(SuccessFailureVal, R.ElemTy)
12120 : Builder.CreateZExt(SuccessFailureVal, R.ElemTy);
12121 Builder.CreateStore(ResultCast, R.Var, R.IsVolatile);
12122 }
12123 }
12124
12125 // For the HandleFPNegZero path, handle V.Var and R.Var using the
12126 // pre-computed OldValue and SuccessOrFail.
12127 if (HandleFPNegZero && !IsInteger) {
12128 if (V.Var) {
12129 assert(OldValue->getType() == V.ElemTy &&
12130 "OldValue and V must be of same type");
12131 if (IsPostfixUpdate) {
12132 Builder.CreateStore(OldValue, V.Var, V.IsVolatile);
12133 } else {
12134 if (IsFailOnly) {
12135 BasicBlock *CurBB = Builder.GetInsertBlock();
12136 Instruction *CurBBTI = CurBB->getTerminatorOrNull();
12137 CurBBTI = CurBBTI ? CurBBTI : Builder.CreateUnreachable();
12138 BasicBlock *ExitBB = CurBB->splitBasicBlock(
12139 CurBBTI, X.Var->getName() + ".atomic.exit");
12140 BasicBlock *ContBB = CurBB->splitBasicBlock(
12141 CurBB->getTerminator(), X.Var->getName() + ".atomic.cont");
12142 ContBB->getTerminator()->eraseFromParent();
12143 CurBB->getTerminator()->eraseFromParent();
12144
12145 Builder.CreateCondBr(SuccessOrFail, ExitBB, ContBB);
12146
12147 Builder.SetInsertPoint(ContBB);
12148 Builder.CreateStore(OldValue, V.Var);
12149 Builder.CreateBr(ExitBB);
12150
12151 if (UnreachableInst *ExitTI =
12153 CurBBTI->eraseFromParent();
12154 Builder.SetInsertPoint(ExitBB);
12155 } else {
12156 Builder.SetInsertPoint(ExitTI);
12157 }
12158 } else {
12159 Value *CapturedValue =
12160 Builder.CreateSelect(SuccessOrFail, E, OldValue);
12161 Builder.CreateStore(CapturedValue, V.Var, V.IsVolatile);
12162 }
12163 }
12164 }
12165 // The comparison result has to be stored.
12166 if (R.Var) {
12167 assert(R.Var->getType()->isPointerTy() &&
12168 "r.var must be of pointer type");
12169 assert(R.ElemTy->isIntegerTy() && "r must be of integral type");
12170
12171 Value *ResultCast = R.IsSigned
12172 ? Builder.CreateSExt(SuccessOrFail, R.ElemTy)
12173 : Builder.CreateZExt(SuccessOrFail, R.ElemTy);
12174 Builder.CreateStore(ResultCast, R.Var, R.IsVolatile);
12175 }
12176 }
12177 } else {
12178 assert((Op == OMPAtomicCompareOp::MAX || Op == OMPAtomicCompareOp::MIN) &&
12179 "Op should be either max or min at this point");
12180 assert(!IsFailOnly && "IsFailOnly is only valid when the comparison is ==");
12181
12182 // Reverse the ordop as the OpenMP forms are different from LLVM forms.
12183 // Let's take max as example.
12184 // OpenMP form:
12185 // x = x > expr ? expr : x;
12186 // LLVM form:
12187 // *ptr = *ptr > val ? *ptr : val;
12188 // We need to transform to LLVM form.
12189 // x = x <= expr ? x : expr;
12191 if (IsXBinopExpr) {
12192 if (IsInteger) {
12193 if (X.IsSigned)
12194 NewOp = Op == OMPAtomicCompareOp::MAX ? AtomicRMWInst::Min
12196 else
12197 NewOp = Op == OMPAtomicCompareOp::MAX ? AtomicRMWInst::UMin
12199 } else {
12200 NewOp = Op == OMPAtomicCompareOp::MAX ? AtomicRMWInst::FMin
12202 }
12203 } else {
12204 if (IsInteger) {
12205 if (X.IsSigned)
12206 NewOp = Op == OMPAtomicCompareOp::MAX ? AtomicRMWInst::Max
12208 else
12209 NewOp = Op == OMPAtomicCompareOp::MAX ? AtomicRMWInst::UMax
12211 } else {
12212 NewOp = Op == OMPAtomicCompareOp::MAX ? AtomicRMWInst::FMax
12214 }
12215 }
12216
12217 AtomicRMWInst *OldValue =
12218 Builder.CreateAtomicRMW(NewOp, X.Var, E, MaybeAlign(), AO);
12219 if (V.Var) {
12220 Value *CapturedValue = nullptr;
12221 if (IsPostfixUpdate) {
12222 CapturedValue = OldValue;
12223 } else {
12224 CmpInst::Predicate Pred;
12225 switch (NewOp) {
12226 case AtomicRMWInst::Max:
12227 Pred = CmpInst::ICMP_SGT;
12228 break;
12230 Pred = CmpInst::ICMP_UGT;
12231 break;
12233 Pred = CmpInst::FCMP_OGT;
12234 break;
12235 case AtomicRMWInst::Min:
12236 Pred = CmpInst::ICMP_SLT;
12237 break;
12239 Pred = CmpInst::ICMP_ULT;
12240 break;
12242 Pred = CmpInst::FCMP_OLT;
12243 break;
12244 default:
12245 llvm_unreachable("unexpected comparison op");
12246 }
12247 Value *NonAtomicCmp = Builder.CreateCmp(Pred, OldValue, E);
12248 CapturedValue = Builder.CreateSelect(NonAtomicCmp, E, OldValue);
12249 }
12250 Builder.CreateStore(CapturedValue, V.Var, V.IsVolatile);
12251 }
12252 }
12253
12254 return Builder.saveIP();
12255}
12256
12259 BodyGenCallbackTy BodyGenCB, Value *NumTeamsLower,
12260 Value *NumTeamsUpper, Value *ThreadLimit,
12261 Value *IfExpr) {
12262 if (!updateToLocation(Loc))
12263 return InsertPointTy();
12264
12265 uint32_t SrcLocStrSize;
12266 Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
12267 Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
12268 Function *CurrentFunction = Builder.GetInsertBlock()->getParent();
12269
12270 // Outer allocation basicblock is the entry block of the current function.
12271 BasicBlock &OuterAllocaBB = CurrentFunction->getEntryBlock();
12272 if (&OuterAllocaBB == Builder.GetInsertBlock()) {
12273 BasicBlock *BodyBB = splitBB(Builder, /*CreateBranch=*/true, "teams.entry");
12274 Builder.SetInsertPoint(BodyBB->begin());
12275 }
12276
12277 // The current basic block is split into four basic blocks. After outlining,
12278 // they will be mapped as follows:
12279 // ```
12280 // def current_fn() {
12281 // current_basic_block:
12282 // br label %teams.exit
12283 // teams.exit:
12284 // ; instructions after teams
12285 // }
12286 //
12287 // def outlined_fn() {
12288 // teams.alloca:
12289 // br label %teams.body
12290 // teams.body:
12291 // ; instructions within teams body
12292 // }
12293 // ```
12294 BasicBlock *ExitBB = splitBB(Builder, /*CreateBranch=*/true, "teams.exit");
12295 BasicBlock *BodyBB = splitBB(Builder, /*CreateBranch=*/true, "teams.body");
12296 BasicBlock *AllocaBB =
12297 splitBB(Builder, /*CreateBranch=*/true, "teams.alloca");
12298
12299 bool SubClausesPresent =
12300 (NumTeamsLower || NumTeamsUpper || ThreadLimit || IfExpr);
12301 // Push num_teams
12302 if (!Config.isTargetDevice() && SubClausesPresent) {
12303 assert((NumTeamsLower == nullptr || NumTeamsUpper != nullptr) &&
12304 "if lowerbound is non-null, then upperbound must also be non-null "
12305 "for bounds on num_teams");
12306
12307 if (NumTeamsUpper == nullptr)
12308 NumTeamsUpper = Builder.getInt32(0);
12309
12310 if (NumTeamsLower == nullptr)
12311 NumTeamsLower = NumTeamsUpper;
12312
12313 if (IfExpr) {
12314 assert(IfExpr->getType()->isIntegerTy() &&
12315 "argument to if clause must be an integer value");
12316
12317 // upper = ifexpr ? upper : 1
12318 if (IfExpr->getType() != Int1)
12319 IfExpr = Builder.CreateICmpNE(IfExpr,
12320 ConstantInt::get(IfExpr->getType(), 0));
12321 NumTeamsUpper = Builder.CreateSelect(
12322 IfExpr, NumTeamsUpper, Builder.getInt32(1), "numTeamsUpper");
12323
12324 // lower = ifexpr ? lower : 1
12325 NumTeamsLower = Builder.CreateSelect(
12326 IfExpr, NumTeamsLower, Builder.getInt32(1), "numTeamsLower");
12327 }
12328
12329 if (ThreadLimit == nullptr)
12330 ThreadLimit = Builder.getInt32(0);
12331
12332 // The __kmpc_push_num_teams_51 function expects int32 as the arguments. So,
12333 // truncate or sign extend the passed values to match the int32 parameters.
12334 Value *NumTeamsLowerInt32 =
12335 Builder.CreateSExtOrTrunc(NumTeamsLower, Builder.getInt32Ty());
12336 Value *NumTeamsUpperInt32 =
12337 Builder.CreateSExtOrTrunc(NumTeamsUpper, Builder.getInt32Ty());
12338 Value *ThreadLimitInt32 =
12339 Builder.CreateSExtOrTrunc(ThreadLimit, Builder.getInt32Ty());
12340
12341 Value *ThreadNum = getOrCreateThreadID(Ident);
12342
12344 getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_push_num_teams_51),
12345 {Ident, ThreadNum, NumTeamsLowerInt32, NumTeamsUpperInt32,
12346 ThreadLimitInt32});
12347 }
12348 // Generate the body of teams.
12349 InsertPointTy AllocaIP(AllocaBB->begin());
12350 InsertPointTy CodeGenIP(BodyBB->begin());
12351 if (Error Err = BodyGenCB(AllocaIP, CodeGenIP, ExitBB))
12352 return Err;
12353
12354 auto OI = std::make_unique<OutlineInfo>();
12355 OI->EntryBB = AllocaBB;
12356 OI->ExitBB = ExitBB;
12357 OI->OuterAllocBB = &OuterAllocaBB;
12358
12359 // Insert fake values for global tid and bound tid.
12361 InsertPointTy OuterAllocaIP(OuterAllocaBB.begin());
12362 OI->ExcludeArgsFromAggregate.push_back(createFakeIntVal(
12363 Builder, OuterAllocaIP, ToBeDeleted, AllocaIP, "gid", true));
12364 OI->ExcludeArgsFromAggregate.push_back(createFakeIntVal(
12365 Builder, OuterAllocaIP, ToBeDeleted, AllocaIP, "tid", true));
12366
12367 auto HostPostOutlineCB = [this, Ident,
12368 ToBeDeleted](Function &OutlinedFn) mutable {
12369 // The stale call instruction will be replaced with a new call instruction
12370 // for runtime call with the outlined function.
12371
12372 assert(OutlinedFn.hasOneUse() &&
12373 "there must be a single user for the outlined function");
12374 CallInst *StaleCI = cast<CallInst>(OutlinedFn.user_back());
12375 ToBeDeleted.push_back(StaleCI);
12376
12377 assert((OutlinedFn.arg_size() == 2 || OutlinedFn.arg_size() == 3) &&
12378 "Outlined function must have two or three arguments only");
12379
12380 bool HasShared = OutlinedFn.arg_size() == 3;
12381
12382 OutlinedFn.getArg(0)->setName("global.tid.ptr");
12383 OutlinedFn.getArg(1)->setName("bound.tid.ptr");
12384 if (HasShared)
12385 OutlinedFn.getArg(2)->setName("data");
12386
12387 // Call to the runtime function for teams in the current function.
12388 assert(StaleCI && "Error while outlining - no CallInst user found for the "
12389 "outlined function.");
12390 Builder.SetInsertPoint(StaleCI);
12391 SmallVector<Value *> Args = {
12392 Ident, Builder.getInt32(StaleCI->arg_size() - 2), &OutlinedFn};
12393 if (HasShared)
12394 Args.push_back(StaleCI->getArgOperand(2));
12397 omp::RuntimeFunction::OMPRTL___kmpc_fork_teams),
12398 Args);
12399
12400 Builder.ClearInsertionPoint();
12401 for (Instruction *I : llvm::reverse(ToBeDeleted))
12402 I->eraseFromParent();
12403 };
12404
12405 if (!Config.isTargetDevice())
12406 OI->PostOutlineCB = HostPostOutlineCB;
12407
12408 addOutlineInfo(std::move(OI));
12409
12410 Builder.SetInsertPoint(ExitBB);
12411
12412 return Builder.saveIP();
12413}
12414
12416 const LocationDescription &Loc, InsertPointTy OuterAllocIP,
12417 ArrayRef<BasicBlock *> OuterDeallocBlocks, BodyGenCallbackTy BodyGenCB) {
12418 if (!updateToLocation(Loc))
12419 return InsertPointTy();
12420
12421 BasicBlock *OuterAllocaBB = OuterAllocIP.getNodeParent();
12422
12423 if (OuterAllocaBB == Builder.GetInsertBlock()) {
12424 BasicBlock *BodyBB =
12425 splitBB(Builder, /*CreateBranch=*/true, "distribute.entry");
12426 Builder.SetInsertPoint(BodyBB->begin());
12427 }
12428 BasicBlock *ExitBB =
12429 splitBB(Builder, /*CreateBranch=*/true, "distribute.exit");
12430 BasicBlock *BodyBB =
12431 splitBB(Builder, /*CreateBranch=*/true, "distribute.body");
12432 BasicBlock *AllocaBB =
12433 splitBB(Builder, /*CreateBranch=*/true, "distribute.alloca");
12434
12435 // Generate the body of distribute clause
12436 InsertPointTy AllocaIP(AllocaBB->begin());
12437 InsertPointTy CodeGenIP(BodyBB->begin());
12438 if (Error Err = BodyGenCB(AllocaIP, CodeGenIP, ExitBB))
12439 return Err;
12440
12441 // When using target we use different runtime functions which require a
12442 // callback.
12443 if (Config.isTargetDevice()) {
12444 auto OI = std::make_unique<OutlineInfo>();
12445 OI->OuterAllocBB = OuterAllocIP.getNodeParent();
12446 OI->EntryBB = AllocaBB;
12447 OI->ExitBB = ExitBB;
12448 OI->OuterDeallocBBs.reserve(OuterDeallocBlocks.size());
12449 copy(OuterDeallocBlocks, OI->OuterDeallocBBs.end());
12450
12451 addOutlineInfo(std::move(OI));
12452 }
12453 Builder.SetInsertPoint(ExitBB);
12454
12455 return Builder.saveIP();
12456}
12457
12460 std::string VarName) {
12461 llvm::Constant *MapNamesArrayInit = llvm::ConstantArray::get(
12463 Names.size()),
12464 Names);
12465 auto *MapNamesArrayGlobal = new llvm::GlobalVariable(
12466 M, MapNamesArrayInit->getType(),
12467 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage, MapNamesArrayInit,
12468 VarName);
12469 return MapNamesArrayGlobal;
12470}
12471
12472// Create all simple and struct types exposed by the runtime and remember
12473// the llvm::PointerTypes of them for easy access later.
12474void OpenMPIRBuilder::initializeTypes(Module &M) {
12475 LLVMContext &Ctx = M.getContext();
12476 StructType *T;
12477 unsigned DefaultTargetAS = Config.getDefaultTargetAS();
12478 unsigned ProgramAS = M.getDataLayout().getProgramAddressSpace();
12479#define OMP_TYPE(VarName, InitValue) VarName = InitValue;
12480#define OMP_ARRAY_TYPE(VarName, ElemTy, ArraySize) \
12481 VarName##Ty = ArrayType::get(ElemTy, ArraySize); \
12482 VarName##PtrTy = PointerType::get(Ctx, DefaultTargetAS);
12483#define OMP_FUNCTION_TYPE(VarName, IsVarArg, ReturnType, ...) \
12484 VarName = FunctionType::get(ReturnType, {__VA_ARGS__}, IsVarArg); \
12485 VarName##Ptr = PointerType::get(Ctx, ProgramAS);
12486#define OMP_STRUCT_TYPE(VarName, StructName, Packed, ...) \
12487 T = StructType::getTypeByName(Ctx, StructName); \
12488 if (!T) \
12489 T = StructType::create(Ctx, {__VA_ARGS__}, StructName, Packed); \
12490 VarName = T; \
12491 VarName##Ptr = PointerType::get(Ctx, DefaultTargetAS);
12492#include "llvm/Frontend/OpenMP/OMPKinds.def"
12493}
12494
12497 SmallVectorImpl<BasicBlock *> &BlockVector) {
12499 BlockSet.insert(EntryBB);
12500 BlockSet.insert(ExitBB);
12501
12502 Worklist.push_back(EntryBB);
12503 while (!Worklist.empty()) {
12504 BasicBlock *BB = Worklist.pop_back_val();
12505 BlockVector.push_back(BB);
12506 for (BasicBlock *SuccBB : successors(BB))
12507 if (BlockSet.insert(SuccBB).second)
12508 Worklist.push_back(SuccBB);
12509 }
12510}
12511
12512std::unique_ptr<CodeExtractor>
12514 bool ArgsInZeroAddressSpace,
12515 Twine Suffix) {
12516 return std::make_unique<CodeExtractor>(
12517 Blocks, /* DominatorTree */ nullptr,
12518 /* AggregateArgs */ true,
12519 /* BlockFrequencyInfo */ nullptr,
12520 /* BranchProbabilityInfo */ nullptr,
12521 /* AssumptionCache */ nullptr,
12522 /* AllowVarArgs */ true,
12523 /* AllowAlloca */ true,
12524 /* AllocationBlock*/ OuterAllocBB,
12525 /* DeallocationBlocks */ ArrayRef<BasicBlock *>(),
12526 /* Suffix */ Suffix.str(), ArgsInZeroAddressSpace);
12527}
12528
12529std::unique_ptr<CodeExtractor> DeviceSharedMemOutlineInfo::createCodeExtractor(
12530 ArrayRef<BasicBlock *> Blocks, bool ArgsInZeroAddressSpace, Twine Suffix) {
12531 return std::make_unique<DeviceSharedMemCodeExtractor>(
12532 OMPBuilder, Blocks, /* DominatorTree */ nullptr,
12533 /* AggregateArgs */ true,
12534 /* BlockFrequencyInfo */ nullptr,
12535 /* BranchProbabilityInfo */ nullptr,
12536 /* AssumptionCache */ nullptr,
12537 /* AllowVarArgs */ true,
12538 /* AllowAlloca */ true,
12539 /* AllocationBlock*/ OuterAllocBB,
12540 /* DeallocationBlocks */ OuterDeallocBBs.empty()
12542 : OuterDeallocBBs,
12543 /* Suffix */ Suffix.str(), ArgsInZeroAddressSpace);
12544}
12545
12547 uint64_t Size, int32_t Flags,
12549 StringRef Name) {
12550 if (!Config.isGPU()) {
12553 Name.empty() ? Addr->getName() : Name, Size, Flags, /*Data=*/0);
12554 return;
12555 }
12556 // TODO: Add support for global variables on the device after declare target
12557 // support.
12558 Function *Fn = dyn_cast<Function>(Addr);
12559 if (!Fn)
12560 return;
12561
12562 // Add a function attribute for the kernel.
12563 Fn->addFnAttr("kernel");
12564 if (T.isAMDGCN())
12565 Fn->addFnAttr("uniform-work-group-size");
12566 Fn->addFnAttr(Attribute::MustProgress);
12567}
12568
12569// We only generate metadata for function that contain target regions.
12572
12573 // If there are no entries, we don't need to do anything.
12574 if (OffloadInfoManager.empty())
12575 return;
12576
12577 LLVMContext &C = M.getContext();
12580 16>
12581 OrderedEntries(OffloadInfoManager.size());
12582
12583 // Auxiliary methods to create metadata values and strings.
12584 auto &&GetMDInt = [this](unsigned V) {
12585 return ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), V));
12586 };
12587
12588 auto &&GetMDString = [&C](StringRef V) { return MDString::get(C, V); };
12589
12590 // Create the offloading info metadata node.
12591 NamedMDNode *MD = M.getOrInsertNamedMetadata("omp_offload.info");
12592 auto &&TargetRegionMetadataEmitter =
12593 [&C, MD, &OrderedEntries, &GetMDInt, &GetMDString](
12594 const TargetRegionEntryInfo &EntryInfo,
12596 // Generate metadata for target regions. Each entry of this metadata
12597 // contains:
12598 // - Entry 0 -> Kind of this type of metadata (0).
12599 // - Entry 1 -> Device ID of the file where the entry was identified.
12600 // - Entry 2 -> File ID of the file where the entry was identified.
12601 // - Entry 3 -> Mangled name of the function where the entry was
12602 // identified.
12603 // - Entry 4 -> Line in the file where the entry was identified.
12604 // - Entry 5 -> Count of regions at this DeviceID/FilesID/Line.
12605 // - Entry 6 -> Order the entry was created.
12606 // The first element of the metadata node is the kind.
12607 Metadata *Ops[] = {
12608 GetMDInt(E.getKind()), GetMDInt(EntryInfo.DeviceID),
12609 GetMDInt(EntryInfo.FileID), GetMDString(EntryInfo.ParentName),
12610 GetMDInt(EntryInfo.Line), GetMDInt(EntryInfo.Count),
12611 GetMDInt(E.getOrder())};
12612
12613 // Save this entry in the right position of the ordered entries array.
12614 OrderedEntries[E.getOrder()] = std::make_pair(&E, EntryInfo);
12615
12616 // Add metadata to the named metadata node.
12617 MD->addOperand(MDNode::get(C, Ops));
12618 };
12619
12620 OffloadInfoManager.actOnTargetRegionEntriesInfo(TargetRegionMetadataEmitter);
12621
12622 // Create function that emits metadata for each device global variable entry;
12623 auto &&DeviceGlobalVarMetadataEmitter =
12624 [&C, &OrderedEntries, &GetMDInt, &GetMDString, MD](
12625 StringRef MangledName,
12627 // Generate metadata for global variables. Each entry of this metadata
12628 // contains:
12629 // - Entry 0 -> Kind of this type of metadata (1).
12630 // - Entry 1 -> Mangled name of the variable.
12631 // - Entry 2 -> Declare target kind.
12632 // - Entry 3 -> Order the entry was created.
12633 // The first element of the metadata node is the kind.
12634 Metadata *Ops[] = {GetMDInt(E.getKind()), GetMDString(MangledName),
12635 GetMDInt(E.getFlags()), GetMDInt(E.getOrder())};
12636
12637 // Save this entry in the right position of the ordered entries array.
12638 TargetRegionEntryInfo varInfo(MangledName, 0, 0, 0);
12639 OrderedEntries[E.getOrder()] = std::make_pair(&E, varInfo);
12640
12641 // Add metadata to the named metadata node.
12642 MD->addOperand(MDNode::get(C, Ops));
12643 };
12644
12645 OffloadInfoManager.actOnDeviceGlobalVarEntriesInfo(
12646 DeviceGlobalVarMetadataEmitter);
12647
12648 for (const auto &E : OrderedEntries) {
12649 assert(E.first && "All ordered entries must exist!");
12650 if (const auto *CE =
12652 E.first)) {
12653 if (!CE->getID() || !CE->getAddress()) {
12654 // Do not blame the entry if the parent funtion is not emitted.
12655 TargetRegionEntryInfo EntryInfo = E.second;
12656 StringRef FnName = EntryInfo.ParentName;
12657 if (!M.getNamedValue(FnName))
12658 continue;
12659 ErrorFn(EMIT_MD_TARGET_REGION_ERROR, EntryInfo);
12660 continue;
12661 }
12662 createOffloadEntry(CE->getID(), CE->getAddress(),
12663 /*Size=*/0, CE->getFlags(),
12665 } else if (const auto *CE = dyn_cast<
12667 E.first)) {
12670 CE->getFlags());
12671 switch (Flags) {
12674 if (Config.isTargetDevice() && Config.hasRequiresUnifiedSharedMemory())
12675 continue;
12676 if (!CE->getAddress()) {
12677 ErrorFn(EMIT_MD_DECLARE_TARGET_ERROR, E.second);
12678 continue;
12679 }
12680 // The vaiable has no definition - no need to add the entry.
12681 if (CE->getVarSize() == 0)
12682 continue;
12683 break;
12685 assert(((Config.isTargetDevice() && !CE->getAddress()) ||
12686 (!Config.isTargetDevice() && CE->getAddress())) &&
12687 "Declaret target link address is set.");
12688 if (Config.isTargetDevice())
12689 continue;
12690 if (!CE->getAddress()) {
12692 continue;
12693 }
12694 break;
12697 if (!CE->getAddress()) {
12698 ErrorFn(EMIT_MD_GLOBAL_VAR_INDIRECT_ERROR, E.second);
12699 continue;
12700 }
12701 break;
12702 default:
12703 break;
12704 }
12705
12706 // Hidden or internal symbols on the device are not externally visible.
12707 // We should not attempt to register them by creating an offloading
12708 // entry. Indirect variables are handled separately on the device.
12709 if (auto *GV = dyn_cast<GlobalValue>(CE->getAddress()))
12710 if ((GV->hasLocalLinkage() || GV->hasHiddenVisibility()) &&
12711 (Flags !=
12713 Flags != OffloadEntriesInfoManager::
12714 OMPTargetGlobalVarEntryIndirectVTable))
12715 continue;
12716
12717 // Indirect globals need to use a special name that doesn't match the name
12718 // of the associated host global.
12720 Flags ==
12722 createOffloadEntry(CE->getAddress(), CE->getAddress(), CE->getVarSize(),
12723 Flags, CE->getLinkage(), CE->getVarName());
12724 else
12725 createOffloadEntry(CE->getAddress(), CE->getAddress(), CE->getVarSize(),
12726 Flags, CE->getLinkage());
12727
12728 } else {
12729 llvm_unreachable("Unsupported entry kind.");
12730 }
12731 }
12732
12733 // Emit requires directive globals to a special entry so the runtime can
12734 // register them when the device image is loaded.
12735 // TODO: This reduces the offloading entries to a 32-bit integer. Offloading
12736 // entries should be redesigned to better suit this use-case.
12737 if (Config.hasRequiresFlags() && !Config.isTargetDevice())
12741 ".requires", /*Size=*/0,
12743 Config.getRequiresFlags());
12744}
12745
12748 unsigned FileID, unsigned Line, unsigned Count) {
12749 raw_svector_ostream OS(Name);
12750 OS << KernelNamePrefix << llvm::format("%x", DeviceID)
12751 << llvm::format("_%x_", FileID) << ParentName << "_l" << Line;
12752 if (Count)
12753 OS << "_" << Count;
12754}
12755
12757 SmallVectorImpl<char> &Name, const TargetRegionEntryInfo &EntryInfo) {
12758 unsigned NewCount = getTargetRegionEntryInfoCount(EntryInfo);
12760 Name, EntryInfo.ParentName, EntryInfo.DeviceID, EntryInfo.FileID,
12761 EntryInfo.Line, NewCount);
12762}
12763
12766 vfs::FileSystem &VFS,
12767 StringRef ParentName) {
12768 sys::fs::UniqueID ID(0xdeadf17e, 0);
12769 auto FileIDInfo = CallBack();
12770 uint64_t FileID = 0;
12771 if (ErrorOr<vfs::Status> Status = VFS.status(std::get<0>(FileIDInfo))) {
12772 ID = Status->getUniqueID();
12773 FileID = Status->getUniqueID().getFile();
12774 } else {
12775 // If the inode ID could not be determined, create a hash value
12776 // the current file name and use that as an ID.
12777 FileID = hash_value(std::get<0>(FileIDInfo));
12778 }
12779
12780 return TargetRegionEntryInfo(ParentName, ID.getDevice(), FileID,
12781 std::get<1>(FileIDInfo));
12782}
12783
12785 unsigned Offset = 0;
12786 for (uint64_t Remain =
12787 static_cast<std::underlying_type_t<omp::OpenMPOffloadMappingFlags>>(
12789 !(Remain & 1); Remain = Remain >> 1)
12790 Offset++;
12791 return Offset;
12792}
12793
12796 // Rotate by getFlagMemberOffset() bits.
12797 return static_cast<omp::OpenMPOffloadMappingFlags>(((uint64_t)Position + 1)
12798 << getFlagMemberOffset());
12799}
12800
12803 omp::OpenMPOffloadMappingFlags MemberOfFlag) {
12804 // If the entry is PTR_AND_OBJ but has not been marked with the special
12805 // placeholder value 0xFFFF in the MEMBER_OF field, then it should not be
12806 // marked as MEMBER_OF.
12807 if (static_cast<std::underlying_type_t<omp::OpenMPOffloadMappingFlags>>(
12809 static_cast<std::underlying_type_t<omp::OpenMPOffloadMappingFlags>>(
12812 return;
12813
12814 // Entries with ATTACH are not members-of anything. They are handled
12815 // separately by the runtime after other maps have been handled.
12816 if (static_cast<std::underlying_type_t<omp::OpenMPOffloadMappingFlags>>(
12818 return;
12819
12820 // Reset the placeholder value to prepare the flag for the assignment of the
12821 // proper MEMBER_OF value.
12822 Flags &= ~omp::OpenMPOffloadMappingFlags::OMP_MAP_MEMBER_OF;
12823 Flags |= MemberOfFlag;
12824}
12825
12829 bool IsDeclaration, bool IsExternallyVisible,
12830 TargetRegionEntryInfo EntryInfo, StringRef MangledName,
12831 std::vector<GlobalVariable *> &GeneratedRefs, bool OpenMPSIMD,
12832 std::vector<Triple> TargetTriple, Type *LlvmPtrTy,
12833 std::function<Constant *()> GlobalInitializer,
12834 std::function<GlobalValue::LinkageTypes()> VariableLinkage) {
12835 // TODO: convert this to utilise the IRBuilder Config rather than
12836 // a passed down argument.
12837 if (OpenMPSIMD)
12838 return nullptr;
12839
12842 CaptureClause ==
12844 Config.hasRequiresUnifiedSharedMemory())) {
12845 SmallString<64> PtrName;
12846 {
12847 raw_svector_ostream OS(PtrName);
12848 OS << MangledName;
12849 if (!IsExternallyVisible)
12850 OS << format("_%x", EntryInfo.FileID);
12851 OS << "_decl_tgt_ref_ptr";
12852 }
12853
12854 Value *Ptr = M.getNamedValue(PtrName);
12855
12856 if (!Ptr) {
12857 GlobalValue *GlobalValue = M.getNamedValue(MangledName);
12858 Ptr = getOrCreateInternalVariable(LlvmPtrTy, PtrName);
12859
12860 auto *GV = cast<GlobalVariable>(Ptr);
12861 GV->setLinkage(GlobalValue::WeakAnyLinkage);
12862
12863 if (!Config.isTargetDevice()) {
12864 if (GlobalInitializer)
12865 GV->setInitializer(GlobalInitializer());
12866 else
12867 GV->setInitializer(GlobalValue);
12868 }
12869
12871 CaptureClause, DeviceClause, IsDeclaration, IsExternallyVisible,
12872 EntryInfo, MangledName, GeneratedRefs, OpenMPSIMD, TargetTriple,
12873 GlobalInitializer, VariableLinkage, LlvmPtrTy, cast<Constant>(Ptr));
12874 }
12875
12876 return cast<Constant>(Ptr);
12877 }
12878
12879 return nullptr;
12880}
12881
12885 bool IsDeclaration, bool IsExternallyVisible,
12886 TargetRegionEntryInfo EntryInfo, StringRef MangledName,
12887 std::vector<GlobalVariable *> &GeneratedRefs, bool OpenMPSIMD,
12888 std::vector<Triple> TargetTriple,
12889 std::function<Constant *()> GlobalInitializer,
12890 std::function<GlobalValue::LinkageTypes()> VariableLinkage, Type *LlvmPtrTy,
12891 Constant *Addr) {
12893 (TargetTriple.empty() && !Config.isTargetDevice()))
12894 return;
12895
12897 StringRef VarName;
12898 int64_t VarSize;
12900
12902 CaptureClause ==
12904 !Config.hasRequiresUnifiedSharedMemory()) {
12906 VarName = MangledName;
12907 GlobalValue *LlvmVal = M.getNamedValue(VarName);
12908
12909 if (!IsDeclaration)
12910 VarSize = divideCeil(
12911 M.getDataLayout().getTypeSizeInBits(LlvmVal->getValueType()), 8);
12912 else
12913 VarSize = 0;
12914 Linkage = (VariableLinkage) ? VariableLinkage() : LlvmVal->getLinkage();
12915
12916 // This is a workaround carried over from Clang which prevents undesired
12917 // optimisation of internal variables.
12918 if (Config.isTargetDevice() &&
12919 (!IsExternallyVisible || Linkage == GlobalValue::LinkOnceODRLinkage)) {
12920 // Do not create a "ref-variable" if the original is not also available
12921 // on the host.
12922 if (!OffloadInfoManager.hasDeviceGlobalVarEntryInfo(VarName))
12923 return;
12924
12925 std::string RefName = createPlatformSpecificName({VarName, "ref"});
12926
12927 if (!M.getNamedValue(RefName)) {
12928 Constant *AddrRef =
12929 getOrCreateInternalVariable(Addr->getType(), RefName);
12930 auto *GvAddrRef = cast<GlobalVariable>(AddrRef);
12931 GvAddrRef->setConstant(true);
12932 GvAddrRef->setLinkage(GlobalValue::InternalLinkage);
12933 GvAddrRef->setInitializer(Addr);
12934 GeneratedRefs.push_back(GvAddrRef);
12935 }
12936 }
12937 } else {
12940 else
12942
12943 if (Config.isTargetDevice()) {
12944 VarName = (Addr) ? Addr->getName() : "";
12945 Addr = nullptr;
12946 } else {
12948 CaptureClause, DeviceClause, IsDeclaration, IsExternallyVisible,
12949 EntryInfo, MangledName, GeneratedRefs, OpenMPSIMD, TargetTriple,
12950 LlvmPtrTy, GlobalInitializer, VariableLinkage);
12951 VarName = (Addr) ? Addr->getName() : "";
12952 }
12953 VarSize = M.getDataLayout().getPointerSize();
12955 }
12956
12957 OffloadInfoManager.registerDeviceGlobalVarEntryInfo(VarName, Addr, VarSize,
12958 Flags, Linkage);
12959}
12960
12961/// Loads all the offload entries information from the host IR
12962/// metadata.
12964 // If we are in target mode, load the metadata from the host IR. This code has
12965 // to match the metadata creation in createOffloadEntriesAndInfoMetadata().
12966
12967 NamedMDNode *MD = M.getNamedMetadata(ompOffloadInfoName);
12968 if (!MD)
12969 return;
12970
12971 for (MDNode *MN : MD->operands()) {
12972 auto &&GetMDInt = [MN](unsigned Idx) {
12973 auto *V = cast<ConstantAsMetadata>(MN->getOperand(Idx));
12974 return cast<ConstantInt>(V->getValue())->getZExtValue();
12975 };
12976
12977 auto &&GetMDString = [MN](unsigned Idx) {
12978 auto *V = cast<MDString>(MN->getOperand(Idx));
12979 return V->getString();
12980 };
12981
12982 switch (GetMDInt(0)) {
12983 default:
12984 llvm_unreachable("Unexpected metadata!");
12985 break;
12986 case OffloadEntriesInfoManager::OffloadEntryInfo::
12987 OffloadingEntryInfoTargetRegion: {
12988 TargetRegionEntryInfo EntryInfo(/*ParentName=*/GetMDString(3),
12989 /*DeviceID=*/GetMDInt(1),
12990 /*FileID=*/GetMDInt(2),
12991 /*Line=*/GetMDInt(4),
12992 /*Count=*/GetMDInt(5));
12993 OffloadInfoManager.initializeTargetRegionEntryInfo(EntryInfo,
12994 /*Order=*/GetMDInt(6));
12995 break;
12996 }
12997 case OffloadEntriesInfoManager::OffloadEntryInfo::
12998 OffloadingEntryInfoDeviceGlobalVar:
12999 OffloadInfoManager.initializeDeviceGlobalVarEntryInfo(
13000 /*MangledName=*/GetMDString(1),
13002 /*Flags=*/GetMDInt(2)),
13003 /*Order=*/GetMDInt(3));
13004 break;
13005 }
13006 }
13007}
13008
13010 StringRef HostFilePath) {
13011 if (HostFilePath.empty())
13012 return;
13013
13014 auto Buf = VFS.getBufferForFile(HostFilePath);
13015 if (std::error_code Err = Buf.getError()) {
13016 report_fatal_error(("error opening host file from host file path inside of "
13017 "OpenMPIRBuilder: " +
13018 Err.message())
13019 .c_str());
13020 }
13021
13022 LLVMContext Ctx;
13024 Ctx, parseBitcodeFile(Buf.get()->getMemBufferRef(), Ctx));
13025 if (std::error_code Err = M.getError()) {
13027 ("error parsing host file inside of OpenMPIRBuilder: " + Err.message())
13028 .c_str());
13029 }
13030
13031 loadOffloadInfoMetadata(*M.get());
13032}
13033
13036 llvm::StringRef Name) {
13037 Builder.restoreIP(Loc.IP);
13038
13039 BasicBlock *CurBB = Builder.GetInsertBlock();
13040 assert(CurBB &&
13041 "expected a valid insertion block for creating an iterator loop");
13042 Function *F = CurBB->getParent();
13043
13044 InsertPointTy SplitIP = Builder.saveIP();
13045 if (SplitIP == CurBB->end())
13046 if (Instruction *Terminator = CurBB->getTerminatorOrNull())
13047 SplitIP = Terminator->getIterator();
13048
13049 BasicBlock *ContBB =
13050 splitBB(SplitIP, /*CreateBranch=*/false,
13051 Builder.getCurrentDebugLocation(), "omp.it.cont");
13052
13053 CanonicalLoopInfo *CLI =
13054 createLoopSkeleton(Builder.getCurrentDebugLocation(), TripCount, F,
13055 /*PreInsertBefore=*/ContBB,
13056 /*PostInsertBefore=*/ContBB, Name);
13057
13058 // Enter loop from original block.
13059 redirectTo(CurBB, CLI->getPreheader(), Builder.getCurrentDebugLocation());
13060
13061 // Remove the unconditional branch inserted by createLoopSkeleton in the body
13062 if (Instruction *T = CLI->getBody()->getTerminatorOrNull())
13063 T->eraseFromParent();
13064
13065 InsertPointTy BodyIP = CLI->getBodyIP();
13066 // Blocks that exist before BodyGen, other than the body and latch, are
13067 // outside the loop body.
13068 SmallPtrSet<BasicBlock *, 32> ExistingBlocks;
13069 for (BasicBlock &Block : *F)
13070 ExistingBlocks.insert(&Block);
13071 if (llvm::Error Err = BodyGen(BodyIP, CLI->getIndVar()))
13072 return Err;
13073
13074 // The body may span several blocks. Branch its single unterminated block to
13075 // the latch; otherwise some block must already branch there.
13076 BasicBlock *Latch = CLI->getLatch();
13077 BasicBlock *OpenBB = nullptr;
13078 bool ReachesLatch = false;
13079 SmallVector<BasicBlock *> Worklist{CLI->getBody()};
13080 SmallPtrSet<BasicBlock *, 8> Visited{CLI->getBody()};
13081 while (!Worklist.empty()) {
13082 BasicBlock *BB = Worklist.pop_back_val();
13083 if (!BB->hasTerminator()) {
13084 if (OpenBB)
13086 "iterator bodygen must leave at most one unterminated block",
13088 OpenBB = BB;
13089 continue;
13090 }
13091 for (BasicBlock *Succ : successors(BB)) {
13092 if (Succ == Latch) {
13093 ReachesLatch = true;
13094 continue;
13095 }
13096 if (Succ != CLI->getBody() && ExistingBlocks.contains(Succ))
13098 "iterator bodygen must not branch out of the loop body",
13100 if (Visited.insert(Succ).second)
13101 Worklist.push_back(Succ);
13102 }
13103 }
13104
13105 if (OpenBB) {
13106 Builder.SetInsertPoint(OpenBB);
13107 Builder.CreateBr(Latch);
13108 } else if (!ReachesLatch) {
13109 return make_error<StringError>("iterator bodygen must reach the loop latch",
13111 }
13112
13113 // Link After -> ContBB
13114 Builder.SetInsertPoint(CLI->getAfter()->begin());
13115 if (!CLI->getAfter()->hasTerminator())
13116 Builder.CreateBr(ContBB);
13117
13118 return ContBB->begin();
13119}
13120
13121/// Mangle the parameter part of the vector function name according to
13122/// their OpenMP classification. The mangling function is defined in
13123/// section 4.5 of the AAVFABI(2021Q1).
13124static std::string mangleVectorParameters(
13126 SmallString<256> Buffer;
13127 llvm::raw_svector_ostream Out(Buffer);
13128 for (const auto &ParamAttr : ParamAttrs) {
13129 switch (ParamAttr.Kind) {
13131 Out << 'l';
13132 break;
13134 Out << 'R';
13135 break;
13137 Out << 'U';
13138 break;
13140 Out << 'L';
13141 break;
13143 Out << 'u';
13144 break;
13146 Out << 'v';
13147 break;
13148 }
13149 if (ParamAttr.HasVarStride)
13150 Out << "s" << ParamAttr.StrideOrArg;
13151 else if (ParamAttr.Kind ==
13153 ParamAttr.Kind ==
13155 ParamAttr.Kind ==
13157 ParamAttr.Kind ==
13159 // Don't print the step value if it is not present or if it is
13160 // equal to 1.
13161 if (ParamAttr.StrideOrArg < 0)
13162 Out << 'n' << -ParamAttr.StrideOrArg;
13163 else if (ParamAttr.StrideOrArg != 1)
13164 Out << ParamAttr.StrideOrArg;
13165 }
13166
13167 if (!!ParamAttr.Alignment)
13168 Out << 'a' << ParamAttr.Alignment;
13169 }
13170
13171 return std::string(Out.str());
13172}
13173
13175 llvm::Function *Fn, unsigned NumElts, const llvm::APSInt &VLENVal,
13177 struct ISADataTy {
13178 char ISA;
13179 unsigned VecRegSize;
13180 };
13181 ISADataTy ISAData[] = {
13182 {'b', 128}, // SSE
13183 {'c', 256}, // AVX
13184 {'d', 256}, // AVX2
13185 {'e', 512}, // AVX512
13186 };
13188 switch (Branch) {
13190 Masked.push_back('N');
13191 Masked.push_back('M');
13192 break;
13194 Masked.push_back('N');
13195 break;
13197 Masked.push_back('M');
13198 break;
13199 }
13200 for (char Mask : Masked) {
13201 for (const ISADataTy &Data : ISAData) {
13203 llvm::raw_svector_ostream Out(Buffer);
13204 Out << "_ZGV" << Data.ISA << Mask;
13205 if (!VLENVal) {
13206 assert(NumElts && "Non-zero simdlen/cdtsize expected");
13207 Out << llvm::APSInt::getUnsigned(Data.VecRegSize / NumElts);
13208 } else {
13209 Out << VLENVal;
13210 }
13211 Out << mangleVectorParameters(ParamAttrs);
13212 Out << '_' << Fn->getName();
13213 Fn->addFnAttr(Out.str());
13214 }
13215 }
13216}
13217
13218// Function used to add the attribute. The parameter `VLEN` is templated to
13219// allow the use of `x` when targeting scalable functions for SVE.
13220template <typename T>
13221static void addAArch64VectorName(T VLEN, StringRef LMask, StringRef Prefix,
13222 char ISA, StringRef ParSeq,
13223 StringRef MangledName, bool OutputBecomesInput,
13224 llvm::Function *Fn) {
13225 SmallString<256> Buffer;
13226 llvm::raw_svector_ostream Out(Buffer);
13227 Out << Prefix << ISA << LMask << VLEN;
13228 if (OutputBecomesInput)
13229 Out << 'v';
13230 Out << ParSeq << '_' << MangledName;
13231 Fn->addFnAttr(Out.str());
13232}
13233
13234// Helper function to generate the Advanced SIMD names depending on the value
13235// of the NDS when simdlen is not present.
13236static void addAArch64AdvSIMDNDSNames(unsigned NDS, StringRef Mask,
13237 StringRef Prefix, char ISA,
13238 StringRef ParSeq, StringRef MangledName,
13239 bool OutputBecomesInput,
13240 llvm::Function *Fn) {
13241 switch (NDS) {
13242 case 8:
13243 addAArch64VectorName(8, Mask, Prefix, ISA, ParSeq, MangledName,
13244 OutputBecomesInput, Fn);
13245 addAArch64VectorName(16, Mask, Prefix, ISA, ParSeq, MangledName,
13246 OutputBecomesInput, Fn);
13247 break;
13248 case 16:
13249 addAArch64VectorName(4, Mask, Prefix, ISA, ParSeq, MangledName,
13250 OutputBecomesInput, Fn);
13251 addAArch64VectorName(8, Mask, Prefix, ISA, ParSeq, MangledName,
13252 OutputBecomesInput, Fn);
13253 break;
13254 case 32:
13255 addAArch64VectorName(2, Mask, Prefix, ISA, ParSeq, MangledName,
13256 OutputBecomesInput, Fn);
13257 addAArch64VectorName(4, Mask, Prefix, ISA, ParSeq, MangledName,
13258 OutputBecomesInput, Fn);
13259 break;
13260 case 64:
13261 case 128:
13262 addAArch64VectorName(2, Mask, Prefix, ISA, ParSeq, MangledName,
13263 OutputBecomesInput, Fn);
13264 break;
13265 default:
13266 llvm_unreachable("Scalar type is too wide.");
13267 }
13268}
13269
13270/// Emit vector function attributes for AArch64, as defined in the AAVFABI.
13272 llvm::Function *Fn, unsigned UserVLEN,
13274 char ISA, unsigned NarrowestDataSize, bool OutputBecomesInput) {
13275 assert((ISA == 'n' || ISA == 's') && "Expected ISA either 's' or 'n'.");
13276
13277 // Sort out parameter sequence.
13278 const std::string ParSeq = mangleVectorParameters(ParamAttrs);
13279 StringRef Prefix = "_ZGV";
13280 StringRef MangledName = Fn->getName();
13281
13282 // Generate simdlen from user input (if any).
13283 if (UserVLEN) {
13284 if (ISA == 's') {
13285 // SVE generates only a masked function.
13286 addAArch64VectorName(UserVLEN, "M", Prefix, ISA, ParSeq, MangledName,
13287 OutputBecomesInput, Fn);
13288 return;
13289 }
13290
13291 switch (Branch) {
13293 addAArch64VectorName(UserVLEN, "N", Prefix, ISA, ParSeq, MangledName,
13294 OutputBecomesInput, Fn);
13295 addAArch64VectorName(UserVLEN, "M", Prefix, ISA, ParSeq, MangledName,
13296 OutputBecomesInput, Fn);
13297 break;
13299 addAArch64VectorName(UserVLEN, "M", Prefix, ISA, ParSeq, MangledName,
13300 OutputBecomesInput, Fn);
13301 break;
13303 addAArch64VectorName(UserVLEN, "N", Prefix, ISA, ParSeq, MangledName,
13304 OutputBecomesInput, Fn);
13305 break;
13306 }
13307 return;
13308 }
13309
13310 if (ISA == 's') {
13311 // SVE, section 3.4.1, item 1.
13312 addAArch64VectorName("x", "M", Prefix, ISA, ParSeq, MangledName,
13313 OutputBecomesInput, Fn);
13314 return;
13315 }
13316
13317 switch (Branch) {
13319 addAArch64AdvSIMDNDSNames(NarrowestDataSize, "N", Prefix, ISA, ParSeq,
13320 MangledName, OutputBecomesInput, Fn);
13321 addAArch64AdvSIMDNDSNames(NarrowestDataSize, "M", Prefix, ISA, ParSeq,
13322 MangledName, OutputBecomesInput, Fn);
13323 break;
13325 addAArch64AdvSIMDNDSNames(NarrowestDataSize, "M", Prefix, ISA, ParSeq,
13326 MangledName, OutputBecomesInput, Fn);
13327 break;
13329 addAArch64AdvSIMDNDSNames(NarrowestDataSize, "N", Prefix, ISA, ParSeq,
13330 MangledName, OutputBecomesInput, Fn);
13331 break;
13332 }
13333}
13334
13335//===----------------------------------------------------------------------===//
13336// OffloadEntriesInfoManager
13337//===----------------------------------------------------------------------===//
13338
13340 return OffloadEntriesTargetRegion.empty() &&
13341 OffloadEntriesDeviceGlobalVar.empty();
13342}
13343
13344unsigned OffloadEntriesInfoManager::getTargetRegionEntryInfoCount(
13345 const TargetRegionEntryInfo &EntryInfo) const {
13346 auto It = OffloadEntriesTargetRegionCount.find(
13347 getTargetRegionEntryCountKey(EntryInfo));
13348 if (It == OffloadEntriesTargetRegionCount.end())
13349 return 0;
13350 return It->second;
13351}
13352
13353void OffloadEntriesInfoManager::incrementTargetRegionEntryInfoCount(
13354 const TargetRegionEntryInfo &EntryInfo) {
13355 OffloadEntriesTargetRegionCount[getTargetRegionEntryCountKey(EntryInfo)] =
13356 EntryInfo.Count + 1;
13357}
13358
13359/// Initialize target region entry.
13361 const TargetRegionEntryInfo &EntryInfo, unsigned Order) {
13362 OffloadEntriesTargetRegion[EntryInfo] =
13363 OffloadEntryInfoTargetRegion(Order, /*Addr=*/nullptr, /*ID=*/nullptr,
13365 ++OffloadingEntriesNum;
13366}
13367
13369 TargetRegionEntryInfo EntryInfo, Constant *Addr, Constant *ID,
13371 assert(EntryInfo.Count == 0 && "expected default EntryInfo");
13372
13373 // Update the EntryInfo with the next available count for this location.
13374 EntryInfo.Count = getTargetRegionEntryInfoCount(EntryInfo);
13375
13376 // If we are emitting code for a target, the entry is already initialized,
13377 // only has to be registered.
13378 if (OMPBuilder->Config.isTargetDevice()) {
13379 // This could happen if the device compilation is invoked standalone.
13380 if (!hasTargetRegionEntryInfo(EntryInfo)) {
13381 return;
13382 }
13383 auto &Entry = OffloadEntriesTargetRegion[EntryInfo];
13384 Entry.setAddress(Addr);
13385 Entry.setID(ID);
13386 Entry.setFlags(Flags);
13387 } else {
13389 hasTargetRegionEntryInfo(EntryInfo, /*IgnoreAddressId*/ true))
13390 return;
13391 assert(!hasTargetRegionEntryInfo(EntryInfo) &&
13392 "Target region entry already registered!");
13393 OffloadEntryInfoTargetRegion Entry(OffloadingEntriesNum, Addr, ID, Flags);
13394 OffloadEntriesTargetRegion[EntryInfo] = Entry;
13395 ++OffloadingEntriesNum;
13396 }
13397 incrementTargetRegionEntryInfoCount(EntryInfo);
13398}
13399
13401 TargetRegionEntryInfo EntryInfo, bool IgnoreAddressId) const {
13402
13403 // Update the EntryInfo with the next available count for this location.
13404 EntryInfo.Count = getTargetRegionEntryInfoCount(EntryInfo);
13405
13406 auto It = OffloadEntriesTargetRegion.find(EntryInfo);
13407 if (It == OffloadEntriesTargetRegion.end()) {
13408 return false;
13409 }
13410 // Fail if this entry is already registered.
13411 if (!IgnoreAddressId && (It->second.getAddress() || It->second.getID()))
13412 return false;
13413 return true;
13414}
13415
13417 const OffloadTargetRegionEntryInfoActTy &Action) {
13418 // Scan all target region entries and perform the provided action.
13419 for (const auto &It : OffloadEntriesTargetRegion) {
13420 Action(It.first, It.second);
13421 }
13422}
13423
13425 StringRef Name, OMPTargetGlobalVarEntryKind Flags, unsigned Order) {
13426 OffloadEntriesDeviceGlobalVar.try_emplace(Name, Order, Flags);
13427 ++OffloadingEntriesNum;
13428}
13429
13431 StringRef VarName, Constant *Addr, int64_t VarSize,
13433 if (OMPBuilder->Config.isTargetDevice()) {
13434 // This could happen if the device compilation is invoked standalone.
13435 if (!hasDeviceGlobalVarEntryInfo(VarName))
13436 return;
13437 auto &Entry = OffloadEntriesDeviceGlobalVar[VarName];
13438 if (Entry.getAddress() && hasDeviceGlobalVarEntryInfo(VarName)) {
13439 if (Entry.getVarSize() == 0) {
13440 Entry.setVarSize(VarSize);
13441 Entry.setLinkage(Linkage);
13442 }
13443 return;
13444 }
13445 Entry.setVarSize(VarSize);
13446 Entry.setLinkage(Linkage);
13447 Entry.setAddress(Addr);
13448 } else {
13449 if (hasDeviceGlobalVarEntryInfo(VarName)) {
13450 auto &Entry = OffloadEntriesDeviceGlobalVar[VarName];
13451 assert(Entry.isValid() && Entry.getFlags() == Flags &&
13452 "Entry not initialized!");
13453 if (Entry.getVarSize() == 0) {
13454 Entry.setVarSize(VarSize);
13455 Entry.setLinkage(Linkage);
13456 }
13457 return;
13458 }
13460 Flags ==
13462 OffloadEntriesDeviceGlobalVar.try_emplace(VarName, OffloadingEntriesNum,
13463 Addr, VarSize, Flags, Linkage,
13464 VarName.str());
13465 else
13466 OffloadEntriesDeviceGlobalVar.try_emplace(
13467 VarName, OffloadingEntriesNum, Addr, VarSize, Flags, Linkage, "");
13468 ++OffloadingEntriesNum;
13469 }
13470}
13471
13474 // Scan all target region entries and perform the provided action.
13475 for (const auto &E : OffloadEntriesDeviceGlobalVar)
13476 Action(E.getKey(), E.getValue());
13477}
13478
13479//===----------------------------------------------------------------------===//
13480// CanonicalLoopInfo
13481//===----------------------------------------------------------------------===//
13482
13483void CanonicalLoopInfo::reportUnsupportedVirtualCollapse() const {
13484 assert(isValid() && "Requires a valid canonical loop");
13485 assert(VirtualCollapse && "Requires Virtual collapse state");
13487 "virtual collapse must be the final structural loop transformation");
13488}
13489
13490void CanonicalLoopInfo::collectControlBlocks(
13492 if (VirtualCollapse)
13493 reportUnsupportedVirtualCollapse();
13494 // We only count those BBs as control block for which we do not need to
13495 // reverse the CFG, i.e. not the loop body which can contain arbitrary control
13496 // flow. For consistency, this also means we do not add the Body block, which
13497 // is just the entry to the body code.
13498 BBs.reserve(BBs.size() + 6);
13499 BBs.append({getPreheader(), Header, Cond, Latch, Exit, getAfter()});
13500}
13501
13502BasicBlock *CanonicalLoopInfo::getVirtualCollapseInit() const {
13503 return VirtualCollapse ? VirtualCollapse->Count->getParent() : nullptr;
13504}
13505
13507 assert(isValid() && "Requires a valid canonical loop");
13508 if (VirtualCollapse)
13509 return getVirtualCollapseInit()->getSinglePredecessor();
13510
13511 for (BasicBlock *Pred : predecessors(Header)) {
13512 if (Pred != Latch)
13513 return Pred;
13514 }
13515 llvm_unreachable("Missing preheader");
13516}
13517
13518void CanonicalLoopInfo::setTripCount(Value *TripCount) {
13519 assert(isValid() && "Requires a valid canonical loop");
13520
13521 Instruction *CmpI = &getCond()->front();
13522 assert(isa<CmpInst>(CmpI) && "First inst must compare IV with TripCount");
13523 CmpI->setOperand(1, TripCount);
13524
13525#ifndef NDEBUG
13526 assertOK();
13527#endif
13528}
13529
13530void CanonicalLoopInfo::mapIndVar(
13531 llvm::function_ref<Value *(Instruction *)> Updater) {
13532 assert(isValid() && "Requires a valid canonical loop");
13533
13534 Instruction *OldIV = getIndVar();
13535
13536 // Record all uses excluding those introduced by the updater. Uses by the
13537 // CanonicalLoopInfo itself to keep track of the number of iterations are
13538 // excluded.
13539 SmallVector<Use *> ReplacableUses;
13540 for (Use &U : OldIV->uses()) {
13541 auto *User = dyn_cast<Instruction>(U.getUser());
13542 if (!User)
13543 continue;
13544 if (User->getParent() == getCond())
13545 continue;
13546 if (User->getParent() == getLatch())
13547 continue;
13548 ReplacableUses.push_back(&U);
13549 }
13550
13551 // Run the updater that may introduce new uses
13552 Value *NewIV = Updater(OldIV);
13553
13554 // Replace the old uses with the value returned by the updater.
13555 for (Use *U : ReplacableUses)
13556 U->set(NewIV);
13557
13558#ifndef NDEBUG
13559 assertOK();
13560#endif
13561}
13562
13564#ifndef NDEBUG
13565 // No constraints if this object currently does not describe a loop.
13566 if (!isValid())
13567 return;
13568
13569 bool IsVirtual = VirtualCollapse.has_value();
13570 BasicBlock *Preheader = getPreheader();
13571 BasicBlock *Init = getVirtualCollapseInit();
13572 BasicBlock *IndVarEntry = Preheader;
13573 if (IsVirtual) {
13574 auto *Guard = cast<CondBrInst>(Init->getTerminator());
13575 IndVarEntry = Guard->getSuccessor(0);
13576 assert(IndVarEntry->getSinglePredecessor() == Init);
13577 assert(IndVarEntry->getSingleSuccessor() == Header);
13578 assert(Guard->getSuccessor(1) == Exit);
13579 assert(VirtualCollapse->Begin->getParent() == Init);
13580 for (BinaryOperator *Copy :
13581 {VirtualCollapse->Begin, VirtualCollapse->Count}) {
13582 auto *Zero = dyn_cast<ConstantInt>(Copy->getOperand(1));
13583 assert(Copy->getOpcode() == Instruction::Add && Zero && Zero->isZero() &&
13584 "Virtual range copies must add zero");
13585 }
13586 auto *NonEmpty = cast<ICmpInst>(Guard->getCondition());
13587 assert(NonEmpty->getPredicate() == ICmpInst::ICMP_NE &&
13588 NonEmpty->getOperand(0) == VirtualCollapse->Count &&
13589 cast<ConstantInt>(NonEmpty->getOperand(1))->isZero() &&
13590 "Collapsed guard must skip empty ranges with zero count");
13591 }
13592
13593 // Validate the retained physical loop without exposing a logical body or IV.
13594 BasicBlock *Body =
13595 IsVirtual ? cast<CondBrInst>(Cond->getTerminator())->getSuccessor(0)
13596 : getBody();
13597 BasicBlock *After = getAfter();
13598
13599 // Verify standard control-flow we use for OpenMP loops.
13600 assert(Preheader);
13601 assert(isa<UncondBrInst>(Preheader->getTerminator()) &&
13602 "Preheader must terminate with unconditional branch");
13603 if (IsVirtual)
13604 assert(Preheader->getSingleSuccessor() == Init &&
13605 "Preheader must jump to collapsed initialization");
13606 else
13607 assert(Preheader->getSingleSuccessor() == Header &&
13608 "Preheader must jump to header");
13609
13610 assert(Header);
13611 assert(isa<UncondBrInst>(Header->getTerminator()) &&
13612 "Header must terminate with unconditional branch");
13613 assert(Header->getSingleSuccessor() == Cond &&
13614 "Header must jump to exiting block");
13615
13616 assert(Cond);
13617 assert(Cond->getSinglePredecessor() == Header &&
13618 "Exiting block only reachable from header");
13619
13620 assert(isa<CondBrInst>(Cond->getTerminator()) &&
13621 "Exiting block must terminate with conditional branch");
13622 assert(cast<CondBrInst>(Cond->getTerminator())->getSuccessor(0) == Body &&
13623 "Exiting block's first successor jump to the body");
13624 assert(cast<CondBrInst>(Cond->getTerminator())->getSuccessor(1) == Exit &&
13625 "Exiting block's second successor must exit the loop");
13626
13627 assert(Body);
13628 assert(Body->getSinglePredecessor() == Cond &&
13629 "Body only reachable from exiting block");
13630 assert(!isa<PHINode>(Body->front()));
13631
13632 assert(Latch);
13633 assert(isa<UncondBrInst>(Latch->getTerminator()) &&
13634 "Latch must terminate with unconditional branch");
13635 assert(Latch->getSingleSuccessor() == Header && "Latch must jump to header");
13636 // TODO: To support simple redirecting of the end of the body code that has
13637 // multiple; introduce another auxiliary basic block like preheader and after.
13638 assert(Latch->getSinglePredecessor() != nullptr);
13639 assert(!isa<PHINode>(Latch->front()));
13640
13641 assert(Exit);
13642 assert(isa<UncondBrInst>(Exit->getTerminator()) &&
13643 "Exit block must terminate with unconditional branch");
13644 assert(Exit->getSingleSuccessor() == After &&
13645 "Exit block must jump to after block");
13646
13647 assert(After);
13648 assert(After->getSinglePredecessor() == Exit &&
13649 "After block only reachable from exit block");
13650 assert(After->empty() || !isa<PHINode>(After->front()));
13651
13652 Instruction *IndVar = IsVirtual ? &Header->front() : getIndVar();
13653 assert(IndVar && "Canonical induction variable not found?");
13654 assert(isa<IntegerType>(IndVar->getType()) &&
13655 "Induction variable must be an integer");
13656 assert(cast<PHINode>(IndVar)->getParent() == Header &&
13657 "Induction variable must be a PHI in the loop header");
13658 assert(cast<PHINode>(IndVar)->getIncomingBlock(0) == IndVarEntry);
13659 if (!IsVirtual)
13660 assert(cast<ConstantInt>(cast<PHINode>(IndVar)->getIncomingValue(0))
13661 ->isZero());
13662 assert(cast<PHINode>(IndVar)->getIncomingBlock(1) == Latch);
13663
13664 auto *NextIndVar = cast<PHINode>(IndVar)->getIncomingValue(1);
13665 assert(cast<Instruction>(NextIndVar)->getParent() == Latch);
13666 assert(cast<BinaryOperator>(NextIndVar)->getOpcode() == BinaryOperator::Add);
13667 assert(cast<BinaryOperator>(NextIndVar)->getOperand(0) == IndVar);
13668 assert(cast<ConstantInt>(cast<BinaryOperator>(NextIndVar)->getOperand(1))
13669 ->isOne());
13670
13671 Value *TripCount =
13672 IsVirtual ? cast<CmpInst>(&Cond->front())->getOperand(1) : getTripCount();
13673 assert(TripCount && "Loop trip count not found?");
13674 assert(IndVar->getType() == TripCount->getType() &&
13675 "Trip count and induction variable must have the same type");
13676
13677 auto *CmpI = cast<CmpInst>(&Cond->front());
13678 assert(CmpI->getPredicate() == CmpInst::ICMP_ULT &&
13679 "Exit condition must be a signed less-than comparison");
13680 assert(CmpI->getOperand(0) == IndVar &&
13681 "Exit condition must compare the induction variable");
13682 assert(CmpI->getOperand(1) == TripCount &&
13683 "Exit condition must compare with the trip count");
13684#endif
13685}
13686
13688 Header = nullptr;
13689 Cond = nullptr;
13690 Latch = nullptr;
13691 Exit = nullptr;
13692 VirtualCollapse.reset();
13693}
SDValue Pred
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
Rewrite undef for PHI
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static cl::opt< ITMode > IT(cl::desc("IT block support"), cl::Hidden, cl::init(DefaultIT), cl::values(clEnumValN(DefaultIT, "arm-default-it", "Generate any type of IT block"), clEnumValN(RestrictedIT, "arm-restrict-it", "Disallow complex IT blocks")))
Expand Atomic instructions
@ ParamAttr
This file contains the simple types necessary to represent the attributes associated with functions a...
static const Function * getParent(const Value *V)
#define X(NUM, ENUM, NAME)
Definition ELF.h:665
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")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
Hexagon Common GEP
Hexagon Hardware Loops
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
This header defines various interfaces for pass management in LLVM.
iv Induction Variable Users
Definition IVUsers.cpp:48
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT, AssumptionCache *AC)
Definition Lint.cpp:550
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
This file contains the declarations for metadata subclasses.
#define T
uint64_t IntrinsicInst * II
#define OMP_KERNEL_ARG_VERSION
Provides definitions for Target specific Grid Values.
static Value * removeASCastIfPresent(Value *V)
static void createTargetLoopWorkshareCall(OpenMPIRBuilder *OMPBuilder, WorksharingLoopType LoopType, BasicBlock *InsertBlock, Value *Ident, Value *LoopBodyArg, Value *TripCount, Function &LoopBodyFn, bool NoLoop)
Value * createFakeIntVal(IRBuilderBase &Builder, OpenMPIRBuilder::InsertPointTy OuterAllocaIP, llvm::SmallVectorImpl< Instruction * > &ToBeDeleted, OpenMPIRBuilder::InsertPointTy InnerAllocaIP, const Twine &Name="", bool AsPtr=true, bool Is64Bit=false)
static Function * createTargetParallelWrapper(OpenMPIRBuilder *OMPIRBuilder, Function &OutlinedFn)
Create wrapper function used to gather the outlined function's argument structure from a shared buffe...
static void redirectTo(BasicBlock *Source, BasicBlock *Target, DebugLoc DL)
Make Source branch to Target.
static FunctionCallee getKmpcDistForStaticInitForType(Type *Ty, Module &M, OpenMPIRBuilder &OMPBuilder)
static void applyParallelAccessesMetadata(CanonicalLoopInfo *CLI, LLVMContext &Ctx, Loop *Loop, LoopInfo &LoopInfo, SmallVector< Metadata * > &LoopMDList)
static void checkRuntimeCallDebugLocs(Module &M)
Assert that every direct call to an OpenMP runtime function in M has a debug location if its function...
static Expected< Function * > createOutlinedFunction(OpenMPIRBuilder &OMPBuilder, IRBuilderBase &Builder, const OpenMPIRBuilder::TargetKernelDefaultAttrs &DefaultAttrs, StringRef FuncName, SmallVectorImpl< Value * > &Inputs, OpenMPIRBuilder::TargetBodyGenCallbackTy &CBFunc, OpenMPIRBuilder::TargetGenArgAccessorsCallbackTy &ArgAccessorFuncCB, DebugLoc OutlinedFnLoc)
static void addAArch64VectorName(T VLEN, StringRef LMask, StringRef Prefix, char ISA, StringRef ParSeq, StringRef MangledName, bool OutputBecomesInput, llvm::Function *Fn)
static FunctionCallee getKmpcForDynamicFiniForType(Type *Ty, Module &M, OpenMPIRBuilder &OMPBuilder)
Returns an LLVM function to call for finalizing the dynamic loop using depending on type.
static void FixupDebugInfoForOutlinedFunction(OpenMPIRBuilder &OMPBuilder, IRBuilderBase &Builder, Function *Func, DenseMap< Value *, std::tuple< Value *, unsigned > > &ValueReplacementMap)
static OMPScheduleType getOpenMPOrderingScheduleType(OMPScheduleType BaseScheduleType, bool HasOrderedClause)
Adds ordering modifier flags to schedule type.
static OMPScheduleType getOpenMPMonotonicityScheduleType(OMPScheduleType ScheduleType, bool HasSimdModifier, bool HasMonotonic, bool HasNonmonotonic, bool HasOrderedClause)
Adds monotonicity modifier flags to schedule type.
static std::string mangleVectorParameters(ArrayRef< llvm::OpenMPIRBuilder::DeclareSimdAttrTy > ParamAttrs)
Mangle the parameter part of the vector function name according to their OpenMP classification.
static bool isGenericKernel(Function &Fn)
static void workshareLoopTargetCallback(OpenMPIRBuilder *OMPIRBuilder, CanonicalLoopInfo *CLI, Value *Ident, Function &OutlinedFn, const SmallVector< Instruction *, 4 > &ToBeDeleted, WorksharingLoopType LoopType, bool NoLoop)
static bool isValidWorkshareLoopScheduleType(OMPScheduleType SchedType)
static bool isAtomicableReductionSet(ArrayRef< OpenMPIRBuilder::ReductionInfo > ReductionInfos)
static llvm::CallInst * emitNoUnwindRuntimeCall(IRBuilder<> &Builder, llvm::FunctionCallee Callee, ArrayRef< llvm::Value * > Args, const llvm::Twine &Name)
static bool isRuntimeFunctionName(StringRef Name)
Return true if Name names an OpenMP runtime function.
static Error populateReductionFunction(Function *ReductionFunc, ArrayRef< OpenMPIRBuilder::ReductionInfo > ReductionInfos, IRBuilder<> &Builder, ArrayRef< bool > IsByRef, bool IsGPU)
static Function * getFreshReductionFunc(Module &M)
static void raiseUserConstantDataAllocasToEntryBlock(IRBuilderBase &Builder, Function *Function)
static FunctionCallee getKmpcForDynamicNextForType(Type *Ty, Module &M, OpenMPIRBuilder &OMPBuilder)
Returns an LLVM function to call for updating the next loop using OpenMP dynamic scheduling depending...
static bool isConflictIP(IRBuilder<>::InsertPoint IP1, IRBuilder<>::InsertPoint IP2)
Return whether IP1 and IP2 are ambiguous, i.e.
static void checkReductionInfos(ArrayRef< OpenMPIRBuilder::ReductionInfo > ReductionInfos, bool IsGPU)
static Type * getOffloadingArrayType(Value *V)
static OMPScheduleType getOpenMPBaseScheduleType(llvm::omp::ScheduleKind ClauseKind, bool HasChunks, bool HasSimdModifier, bool HasDistScheduleChunks)
Determine which scheduling algorithm to use, determined from schedule clause arguments.
static OMPScheduleType computeOpenMPScheduleType(ScheduleKind ClauseKind, bool HasChunks, bool HasSimdModifier, bool HasMonotonicModifier, bool HasNonmonotonicModifier, bool HasOrderedClause, bool HasDistScheduleChunks)
Determine the schedule type using schedule and ordering clause arguments.
static FunctionCallee getKmpcForDynamicInitForType(Type *Ty, Module &M, OpenMPIRBuilder &OMPBuilder)
Returns an LLVM function to call for initializing loop bounds using OpenMP dynamic scheduling dependi...
static std::optional< omp::OMPTgtExecModeFlags > getTargetKernelExecMode(Function &Kernel)
Given a function, if it represents the entry point of a target kernel, this returns the execution mod...
static cl::opt< bool > UseDefaultMaxThreads("openmp-ir-builder-use-default-max-threads", cl::Hidden, cl::desc("Use a default max threads if none is provided."), cl::init(true))
static Error emitTargetOutlinedFunction(OpenMPIRBuilder &OMPBuilder, IRBuilderBase &Builder, bool IsOffloadEntry, TargetRegionEntryInfo &EntryInfo, const OpenMPIRBuilder::TargetKernelDefaultAttrs &DefaultAttrs, Function *&OutlinedFn, Constant *&OutlinedFnID, SmallVectorImpl< Value * > &Inputs, OpenMPIRBuilder::TargetBodyGenCallbackTy &CBFunc, OpenMPIRBuilder::TargetGenArgAccessorsCallbackTy &ArgAccessorFuncCB, DebugLoc OutlinedFnLoc)
static Value * emitTaskDependencies(OpenMPIRBuilder &OMPBuilder, const SmallVectorImpl< OpenMPIRBuilder::DependData > &Dependencies)
static void updateNVPTXAttr(Function &Kernel, StringRef Name, int32_t Value, bool Min)
static OpenMPIRBuilder::InsertPointTy getInsertPointAfterInstr(Instruction *I)
static void redirectAllPredecessorsTo(BasicBlock *OldTarget, BasicBlock *NewTarget, DebugLoc DL)
Redirect all edges that branch to OldTarget to NewTarget.
static void hoistNonEntryAllocasToEntryBlock(llvm::BasicBlock &Block)
static FunctionCallee getKmpcForStaticInitForType(Type *Ty, Module &M, OpenMPIRBuilder &OMPBuilder)
static void addAccessGroupMetadata(BasicBlock *Block, MDNode *AccessGroup, LoopInfo &LI)
Attach llvm.access.group metadata to the memref instructions of Block.
static void addBasicBlockMetadata(BasicBlock *BB, ArrayRef< Metadata * > Properties)
Attach metadata Properties to the basic block described by BB.
static void restoreIPandDebugLoc(llvm::IRBuilderBase &Builder, llvm::IRBuilderBase::InsertPoint IP)
This is a wrapper over IRBuilderBase::restoreIP that also restores a current debug location when the ...
static cl::opt< bool > OptimisticAttributes("openmp-ir-builder-optimistic-attributes", cl::Hidden, cl::desc("Use optimistic attributes describing " "'as-if' properties of runtime calls."), cl::init(false))
static bool hasGridValue(const Triple &T)
static StructType * createTaskWithPrivatesTy(OpenMPIRBuilder &OMPIRBuilder, ArrayRef< Value * > OffloadingArraysToPrivatize, ArrayRef< Type * > DescriptorTypes)
static FunctionCallee getKmpcForStaticLoopForType(Type *Ty, OpenMPIRBuilder *OMPBuilder, WorksharingLoopType LoopType)
static const omp::GV & getGridValue(const Triple &T, Function *Kernel)
static void addAArch64AdvSIMDNDSNames(unsigned NDS, StringRef Mask, StringRef Prefix, char ISA, StringRef ParSeq, StringRef MangledName, bool OutputBecomesInput, llvm::Function *Fn)
static Error emitTargetCall(OpenMPIRBuilder &OMPBuilder, IRBuilderBase &Builder, Value *RTLocOverride, OpenMPIRBuilder::InsertPointTy AllocaIP, ArrayRef< BasicBlock * > DeallocBlocks, OpenMPIRBuilder::TargetDataInfo &Info, const OpenMPIRBuilder::TargetKernelDefaultAttrs &DefaultAttrs, const OpenMPIRBuilder::TargetKernelRuntimeAttrs &RuntimeAttrs, Value *IfCond, Function *OutlinedFn, Constant *OutlinedFnID, SmallVectorImpl< Value * > &Args, OpenMPIRBuilder::GenMapInfoCallbackTy GenMapInfoCB, OpenMPIRBuilder::CustomMapperCallbackTy CustomMapperCB, const OpenMPIRBuilder::DependenciesInfo &Dependencies, bool HasNoWait, Value *DynCGroupMem, OMPDynGroupprivateFallbackType DynCGroupMemFallback)
static LoadInst * loadSharedDataFromTaskDescriptor(IRBuilderBase &Builder, Value *TaskWithPrivates)
Given a task descriptor, TaskWithPrivates, return the pointer to the block of pointers containing sha...
static Function * emitTargetTaskProxyFunction(OpenMPIRBuilder &OMPBuilder, IRBuilderBase &Builder, CallInst *StaleCI, StructType *PrivatesTy, StructType *TaskWithPrivatesTy, const size_t NumOffloadingArrays, const int SharedArgsOperandNo)
Create an entry point for a target task with the following.
static void addLoopMetadata(CanonicalLoopInfo *Loop, ArrayRef< Metadata * > Properties)
Attach loop metadata Properties to the loop described by Loop.
static AtomicOrdering TransformReleaseAcquireRelease(AtomicOrdering AO)
static void removeUnusedBlocksFromParent(ArrayRef< BasicBlock * > BBs)
static void targetParallelCallback(OpenMPIRBuilder *OMPIRBuilder, Function &OutlinedFn, Function *OuterFn, BasicBlock *OuterAllocaBB, Value *Ident, Value *IfCondition, Value *NumThreads, Instruction *PrivTID, AllocaInst *PrivTIDAddr, Value *ThreadID, const SmallVector< Instruction *, 4 > &ToBeDeleted)
static void hostParallelCallback(OpenMPIRBuilder *OMPIRBuilder, Function &OutlinedFn, Function *OuterFn, Value *Ident, Value *IfCondition, Instruction *PrivTID, AllocaInst *PrivTIDAddr, const SmallVector< Instruction *, 4 > &ToBeDeleted)
#define P(N)
FunctionAnalysisManager FAM
Function * Fun
This file defines the Pass Instrumentation classes that provide instrumentation points into the pass ...
SmallVector< MachineOperand, 4 > Cond
Remove Loads Into Fake Uses
static bool isValid(const char C)
Returns true if C is a valid mangled character: <0-9a-zA-Z_>.
SmallPtrSet< BasicBlock *, 0 > BlockSet
This file implements the SmallBitVector class.
This file defines the SmallSet class.
This file defines less commonly used SmallVector utilities.
This file contains some functions that are useful when dealing with strings.
StringSet - A set-like wrapper for the StringMap.
#define LLVM_DEBUG(...)
Definition Debug.h:119
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
Defines the virtual file system interface vfs::FileSystem.
Value * RHS
Value * LHS
static const uint32_t IV[8]
Definition blake3_impl.h:83
The Input class is used to parse a yaml document into in-memory structs and vectors.
Class for arbitrary precision integers.
Definition APInt.h:78
static APInt getSignedMaxValue(unsigned numBits)
Gets maximum signed value of APInt for a specific bit width.
Definition APInt.h:205
An arbitrary precision integer that knows its signedness.
Definition APSInt.h:24
static APSInt getUnsigned(uint64_t X)
Definition APSInt.h:349
This class represents a conversion between pointers from one address space to another.
an instruction to allocate memory on the stack
Align getAlign() const
Return the alignment of the memory that is being allocated by the instruction.
PointerType * getType() const
Overload to return most specific pointer type.
Type * getAllocatedType() const
Return the type that is being allocated by the instruction.
unsigned getAddressSpace() const
Return the address space for the allocation.
LLVM_ABI std::optional< TypeSize > getAllocationSize(const DataLayout &DL) const
Get allocation size in bytes.
LLVM_ABI bool isArrayAllocation() const
Return true if there is an allocation size parameter to the allocation instruction that is not 1.
void setAlignment(Align Align)
const Value * getArraySize() const
Get the number of elements allocated.
bool registerPass(PassBuilderT &&PassBuilder)
Register an analysis pass with the manager.
This class represents an incoming formal argument to a Function.
Definition Argument.h:32
unsigned getArgNo() const
Return the index of this formal argument in its containing function.
Definition Argument.h:50
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
const T & back() const
Get the last element.
Definition ArrayRef.h:150
iterator end() const
Definition ArrayRef.h:130
size_t size() const
Get the array size.
Definition ArrayRef.h:141
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
Class to represent array types.
static LLVM_ABI ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
An instruction that atomically checks whether a specified value is in a memory location,...
void setWeak(bool IsWeak)
static AtomicOrdering getStrongestFailureOrdering(AtomicOrdering SuccessOrdering)
Returns the strongest permitted ordering on failure, given the desired ordering on success.
LLVM_ABI std::pair< LoadInst *, AllocaInst * > EmitAtomicLoadLibcall(AtomicOrdering AO)
Definition Atomic.cpp:109
LLVM_ABI void EmitAtomicStoreLibcall(AtomicOrdering AO, Value *Source)
Definition Atomic.cpp:150
an instruction that atomically reads a memory location, combines it with another value,...
BinOp
This enumeration lists the possible modifications atomicrmw can make.
@ Add
*p = old + v
@ FAdd
*p = old + v
@ USubCond
Subtract only if no unsigned overflow.
@ FMinimum
*p = minimum(old, v) minimum matches the behavior of llvm.minimum.
@ Min
*p = old <signed v ? old : v
@ Sub
*p = old - v
@ And
*p = old & v
@ Xor
*p = old ^ v
@ USubSat
*p = usub.sat(old, v) usub.sat matches the behavior of llvm.usub.sat.
@ FMaximum
*p = maximum(old, v) maximum matches the behavior of llvm.maximum.
@ FSub
*p = old - v
@ UIncWrap
Increment one up to a maximum value.
@ Max
*p = old >signed v ? old : v
@ UMin
*p = old <unsigned v ? old : v
@ FMin
*p = minnum(old, v) minnum matches the behavior of llvm.minnum.
@ UMax
*p = old >unsigned v ? old : v
@ FMaximumNum
*p = maximumnum(old, v) maximumnum matches the behavior of llvm.maximumnum.
@ FMax
*p = maxnum(old, v) maxnum matches the behavior of llvm.maxnum.
@ UDecWrap
Decrement one until a minimum value or zero.
@ FMinimumNum
*p = minimumnum(old, v) minimumnum matches the behavior of llvm.minimumnum.
@ Nand
*p = ~(old & v)
This class holds the attributes for a particular argument, parameter, function, or return value.
Definition Attributes.h:448
LLVM_ABI AttributeSet addAttributes(LLVMContext &C, AttributeSet AS) const
Add attributes to the attribute set.
LLVM_ABI AttributeSet addAttribute(LLVMContext &C, Attribute::AttrKind Kind) const
Add an argument attribute.
static LLVM_ABI Attribute getWithAlignment(LLVMContext &Context, Align Alignment)
Return a uniquified Attribute object that has the specific alignment set.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
LLVM_ABI void replaceSuccessorsPhiUsesWith(BasicBlock *Old, BasicBlock *New)
Update all phi nodes in this basic block's successors to refer to basic block New instead of basic bl...
iterator end()
Definition BasicBlock.h:453
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:440
LLVM_ABI const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
LLVM_ABI BasicBlock * splitBasicBlock(iterator I, const Twine &BBName="")
Split the basic block into two basic blocks at the specified instruction.
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
reverse_iterator rbegin()
Definition BasicBlock.h:456
bool hasTerminator() const LLVM_READONLY
Returns whether the block has a terminator.
Definition BasicBlock.h:232
bool empty() const
Definition BasicBlock.h:462
const Instruction & back() const
Definition BasicBlock.h:465
LLVM_ABI BasicBlock * splitBasicBlockBefore(iterator I, const Twine &BBName="")
Split the basic block into two basic blocks at the specified instruction and insert the new basic blo...
LLVM_ABI InstListType::const_iterator getFirstNonPHIIt() const
Returns an iterator to the first instruction in this block that is not a PHINode instruction.
LLVM_ABI void insertDbgRecordBefore(DbgRecord *DR, InstListType::iterator Here)
Insert a DbgRecord into a block at the position given by Here.
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition BasicBlock.h:206
LLVM_ABI const BasicBlock * getUniqueSuccessor() const
Return the successor of this block if it has a unique successor.
LLVM_ABI const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
const Instruction & front() const
Definition BasicBlock.h:463
InstListType::reverse_iterator reverse_iterator
Definition BasicBlock.h:172
LLVM_ABI const BasicBlock * getUniquePredecessor() const
Return the predecessor of this block if it has a unique predecessor block.
const Instruction * getTerminatorOrNull() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition BasicBlock.h:248
LLVM_ABI const BasicBlock * getSingleSuccessor() const
Return the successor of this block if it has a single successor.
LLVM_ABI InstListType::const_iterator getFirstNonPHIOrPseudoProbe() const
Returns an iterator to the first instruction in this block that is not a PHINode or a pseudo operatio...
LLVM_ABI void insertInto(Function *Parent, BasicBlock *InsertBefore=nullptr)
Insert unlinked basic block into a function.
LLVM_ABI SymbolTableList< BasicBlock >::iterator eraseFromParent()
Unlink 'this' from the containing function and delete it.
reverse_iterator rend()
Definition BasicBlock.h:458
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
LLVM_ABI LLVMContext & getContext() const
Get the context in which this basic block lives.
void moveBefore(BasicBlock *MovePos)
Unlink this basic block from its current function and insert it into the function that MovePos lives ...
Definition BasicBlock.h:367
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
void splice(BasicBlock::iterator ToIt, BasicBlock *FromBB)
Transfer all instructions from FromBB to this basic block at ToIt.
Definition BasicBlock.h:638
LLVM_ABI void removePredecessor(BasicBlock *Pred, bool KeepOneInputPHIs=false)
Update PHI nodes in this BasicBlock before removal of predecessor Pred.
void setDoesNotThrow()
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
User::op_iterator arg_begin()
Return the iterator pointing to the beginning of the argument list.
Value * getArgOperand(unsigned i) const
User::op_iterator arg_end()
Return the iterator pointing to the end of the argument list.
unsigned arg_size() const
This class represents a function call, abstracting a target machine's calling convention.
Class to represented the control flow structure of an OpenMP canonical loop.
Value * getTripCount() const
Returns the llvm::Value containing the number of loop iterations.
BasicBlock * getHeader() const
The header is the entry for each iteration.
LLVM_ABI void assertOK() const
Consistency self-check.
Type * getIndVarType() const
Return the type of the induction variable (and the trip count).
BasicBlock * getBody() const
The body block is the single entry for a loop iteration and not controlled by CanonicalLoopInfo.
bool isValid() const
Returns whether this object currently represents the IR of a loop.
void setLastIter(Value *IterVar)
Sets the last iteration variable for this loop.
OpenMPIRBuilder::InsertPointTy getAfterIP() const
Return the insertion point for user code after the loop.
OpenMPIRBuilder::InsertPointTy getBodyIP() const
Return the insertion point for user code in the body.
BasicBlock * getAfter() const
The after block is intended for clean-up code such as lifetime end markers.
Function * getFunction() const
LLVM_ABI void invalidate()
Invalidate this loop.
BasicBlock * getLatch() const
Reaching the latch indicates the end of the loop body code.
OpenMPIRBuilder::InsertPointTy getPreheaderIP() const
Return the insertion point for user code before the loop.
BasicBlock * getCond() const
The condition block computes whether there is another loop iteration.
BasicBlock * getExit() const
Reaching the exit indicates no more iterations are being executed.
LLVM_ABI BasicBlock * getPreheader() const
The preheader ensures that there is only a single edge entering the loop.
Instruction * getIndVar() const
Returns the instruction representing the current logical induction variable.
This class is the base class for the comparison instructions.
Definition InstrTypes.h:728
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
@ ICMP_SLT
signed less than
Definition InstrTypes.h:769
@ ICMP_SLE
signed less or equal
Definition InstrTypes.h:770
@ FCMP_OLT
0 1 0 0 True if ordered and less than
Definition InstrTypes.h:746
@ FCMP_OGT
0 0 1 0 True if ordered and greater than
Definition InstrTypes.h:744
@ ICMP_UGT
unsigned greater than
Definition InstrTypes.h:763
@ ICMP_SGT
signed greater than
Definition InstrTypes.h:767
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:765
@ ICMP_NE
not equal
Definition InstrTypes.h:762
@ ICMP_ULE
unsigned less or equal
Definition InstrTypes.h:766
A cache for the CodeExtractor analysis.
Utility class for extracting code into a new function.
static LLVM_ABI Constant * get(ArrayType *T, ArrayRef< Constant * > V)
static ConstantAsMetadata * get(Constant *C)
Definition Metadata.h:549
static Constant * get(LLVMContext &Context, ArrayRef< ElementTy > Elts)
get() constructor - Return a constant with array type with an element count and element type matching...
Definition Constants.h:878
static LLVM_ABI Constant * getString(LLVMContext &Context, StringRef Initializer, bool AddNull=true, bool ByteString=false)
This method constructs a CDS and initializes it with a text string.
static LLVM_ABI Constant * getPointerCast(Constant *C, Type *Ty)
Create a BitCast, AddrSpaceCast, or a PtrToInt cast constant expression.
static LLVM_ABI Constant * getPointerBitCastOrAddrSpaceCast(Constant *C, Type *Ty)
Create a BitCast or AddrSpaceCast for a pointer type depending on the address space.
static LLVM_ABI Constant * getAddrSpaceCast(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static LLVM_ABI ConstantFP * getZero(Type *Ty, bool Negative=false)
This is the shared class of boolean and integer constants.
Definition Constants.h:87
static ConstantInt * getSigned(IntegerType *Ty, int64_t V, bool ImplicitTrunc=false)
Return a ConstantInt with the specified value for the specified type.
Definition Constants.h:135
static LLVM_ABI ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
static LLVM_ABI Constant * get(StructType *T, ArrayRef< Constant * > V)
This is an important base class in LLVM.
Definition Constant.h:44
static LLVM_ABI Constant * getAllOnesValue(Type *Ty)
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
DILocalScope * getScope() const
Get the local scope for this variable.
DINodeArray getAnnotations() const
DIFile * getFile() const
Subprogram description. Uses SubclassData1.
Base class for types.
uint32_t getAlignInBits() const
DIFile * getFile() const
DIType * getType() const
unsigned getLine() const
StringRef getName() const
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
TypeSize getTypeStoreSize(Type *Ty) const
Returns the maximum number of bytes that may be overwritten by storing the specified type.
Definition DataLayout.h:582
Record of a variable value-assignment, aka a non instruction representation of the dbg....
A debug info location.
Definition DebugLoc.h:127
Analysis pass which computes a DominatorTree.
Definition Dominators.h:241
bool properlyDominates(const DomTreeNodeBase< NodeT > *A, const DomTreeNodeBase< NodeT > *B) const
properlyDominates - Returns true iff A dominates B and A != B.
Represents either an error or a value T.
Definition ErrorOr.h:56
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
static ErrorSuccess success()
Create a success value.
Definition Error.h:336
Tagged union holding either a T or a Error.
Definition Error.h:485
Error takeError()
Take ownership of the stored error.
Definition Error.h:612
reference get()
Returns a reference to the stored T value.
Definition Error.h:582
A handy container for a FunctionType+Callee-pointer pair, which can be passed around as a single enti...
Class to represent function types.
Type * getParamType(unsigned i) const
Parameter type accessors.
static LLVM_ABI FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
void addFnAttr(Attribute::AttrKind Kind)
Add function attributes to this function.
Definition Function.cpp:641
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
Definition Function.h:169
const BasicBlock & getEntryBlock() const
Definition Function.h:803
Argument * arg_iterator
Definition Function.h:73
bool empty() const
Definition Function.h:853
FunctionType * getFunctionType() const
Returns the FunctionType for me.
Definition Function.h:212
void removeFromParent()
removeFromParent - This method unlinks 'this' from the containing module, but does not delete it.
Definition Function.cpp:447
Attribute getFnAttribute(Attribute::AttrKind Kind) const
Return the attribute for the given attribute kind.
Definition Function.cpp:766
DISubprogram * getSubprogram() const
Get the attached subprogram.
AttributeList getAttributes() const
Return the attribute list for this Function.
Definition Function.h:329
const Function & getFunction() const
Definition Function.h:167
iterator begin()
Definition Function.h:847
arg_iterator arg_begin()
Definition Function.h:862
void setAttributes(AttributeList Attrs)
Set the attribute list for this Function.
Definition Function.h:332
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
Definition Function.cpp:352
void addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind)
adds the attribute to the list of attributes for the given arg.
Definition Function.cpp:669
Function::iterator insert(Function::iterator Position, BasicBlock *BB)
Insert BB in the basic block list at Position.
Definition Function.h:749
size_t arg_size() const
Definition Function.h:895
Type * getReturnType() const
Returns the type of the ret val.
Definition Function.h:217
iterator end()
Definition Function.h:849
void setCallingConv(CallingConv::ID CC)
Definition Function.h:277
Argument * getArg(unsigned i) const
Definition Function.h:880
LLVM_ABI void addMetadata(unsigned KindID, MDNode &MD)
Add a metadata attachment.
LinkageTypes getLinkage() const
void setLinkage(LinkageTypes LT)
Module * getParent()
Get the module that this global value is contained inside of...
void setDSOLocal(bool Local)
PointerType * getType() const
Global values are always pointers.
@ HiddenVisibility
The GV is hidden.
Definition GlobalValue.h:69
@ ProtectedVisibility
The GV is protected.
Definition GlobalValue.h:70
void setVisibility(VisibilityTypes V)
LinkageTypes
An enumeration for the kinds of linkage for global values.
Definition GlobalValue.h:52
@ PrivateLinkage
Like Internal, but omit from symbol table.
Definition GlobalValue.h:61
@ CommonLinkage
Tentative definitions.
Definition GlobalValue.h:63
@ InternalLinkage
Rename collisions when linking (static functions).
Definition GlobalValue.h:60
@ WeakODRLinkage
Same, but only replaced by something equivalent.
Definition GlobalValue.h:58
@ WeakAnyLinkage
Keep one copy of named function when linking (weak)
Definition GlobalValue.h:57
@ AppendingLinkage
Special purpose, only applies to global arrays.
Definition GlobalValue.h:59
@ LinkOnceODRLinkage
Same, but only replaced by something equivalent.
Definition GlobalValue.h:56
Type * getValueType() const
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
Common base class shared among various IRBuilders.
Definition IRBuilder.h:111
InsertPoint saveIP() const
Returns the current insert point.
Definition IRBuilder.h:257
BasicBlock::iterator InsertPoint
InsertPoint - A saved insertion point.
Definition IRBuilder.h:254
void restoreIP(InsertPoint IP)
Sets the current insert point to a previously-saved location.
Definition IRBuilder.h:267
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2990
LLVM_ABI void removeFromParent()
This method unlinks 'this' from the containing basic block, but does not delete it.
LLVM_ABI unsigned getNumSuccessors() const LLVM_READONLY
Return the number of successors that this instruction has.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
LLVM_ABI void moveBefore(InstListType::iterator InsertPos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
LLVM_ABI BasicBlock * getSuccessor(unsigned Idx) const LLVM_READONLY
Return the specified successor. This instruction must be a terminator.
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
user_iterator user_begin()
user_iterator user_end()
LLVM_ABI void moveBeforePreserving(InstListType::iterator MovePos)
Perform a moveBefore operation, while signalling that the caller intends to preserve the original ord...
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
LLVM_ABI void insertAfter(Instruction *InsertPos)
Insert an unlinked instruction into a basic block immediately after the specified instruction.
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this instruction belongs to.
Class to represent integer types.
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition Type.cpp:333
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
An instruction for reading from memory.
void setAtomic(AtomicOrdering Ordering, SyncScope::ID SSID=SyncScope::System)
Sets the ordering constraint and the synchronization scope ID of this load instruction.
Align getAlign() const
Return the alignment of the access that is being performed.
Analysis pass that exposes the LoopInfo for a function.
Definition LoopInfo.h:598
LLVM_ABI LoopInfo run(Function &F, FunctionAnalysisManager &AM)
ArrayRef< BlockT * > getBlocks() const
Get a list of the basic blocks which make up this loop.
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
This class represents a loop nest and can be used to query its properties.
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
LLVM_ABI MDNode * createCallbackEncoding(unsigned CalleeArgNo, ArrayRef< int > Arguments, bool VarArgsArePassed)
Return metadata describing a callback (see llvm::AbstractCallSite).
Metadata node.
Definition Metadata.h:1087
LLVM_ABI void replaceOperandWith(unsigned I, Metadata *New)
Replace a specific operand.
static MDTuple * getDistinct(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1596
ArrayRef< MDOperand > operands() const
Definition Metadata.h:1441
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1588
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
Definition Metadata.cpp:595
This class implements a map that also provides access to all stored values in a deterministic order.
Definition MapVector.h:39
size_type size() const
Definition MapVector.h:59
Root of the metadata hierarchy.
Definition Metadata.h:65
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
LLVMContext & getContext() const
Get the global data context.
Definition Module.h:332
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
Definition Module.h:325
A tuple of MDNodes.
Definition Metadata.h:1806
iterator_range< op_iterator > operands()
Definition Metadata.h:1902
LLVM_ABI void addOperand(MDNode *M)
Class that manages information about offload code regions and data.
function_ref< void(StringRef, const OffloadEntryInfoDeviceGlobalVar &)> OffloadDeviceGlobalVarEntryInfoActTy
Applies action Action on all registered entries.
OMPTargetDeviceClauseKind
Kind of device clause for declare target variables and functions NOTE: Currently not used as a part o...
@ OMPTargetDeviceClauseAny
The target is marked for all devices.
LLVM_ABI void registerDeviceGlobalVarEntryInfo(StringRef VarName, Constant *Addr, int64_t VarSize, OMPTargetGlobalVarEntryKind Flags, GlobalValue::LinkageTypes Linkage)
Register device global variable entry.
LLVM_ABI void initializeDeviceGlobalVarEntryInfo(StringRef Name, OMPTargetGlobalVarEntryKind Flags, unsigned Order)
Initialize device global variable entry.
LLVM_ABI void actOnDeviceGlobalVarEntriesInfo(const OffloadDeviceGlobalVarEntryInfoActTy &Action)
OMPTargetRegionEntryKind
Kind of the target registry entry.
@ OMPTargetRegionEntryTargetRegion
Mark the entry as target region.
LLVM_ABI void getTargetRegionEntryFnName(SmallVectorImpl< char > &Name, const TargetRegionEntryInfo &EntryInfo)
LLVM_ABI bool hasTargetRegionEntryInfo(TargetRegionEntryInfo EntryInfo, bool IgnoreAddressId=false) const
Return true if a target region entry with the provided information exists.
LLVM_ABI void registerTargetRegionEntryInfo(TargetRegionEntryInfo EntryInfo, Constant *Addr, Constant *ID, OMPTargetRegionEntryKind Flags)
Register target region entry.
LLVM_ABI void actOnTargetRegionEntriesInfo(const OffloadTargetRegionEntryInfoActTy &Action)
LLVM_ABI void initializeTargetRegionEntryInfo(const TargetRegionEntryInfo &EntryInfo, unsigned Order)
Initialize target region entry.
OMPTargetGlobalVarEntryKind
Kind of the global variable entry..
@ OMPTargetGlobalVarEntryEnter
Mark the entry as a declare target enter.
@ OMPTargetGlobalRegisterRequires
Mark the entry as a register requires global.
@ OMPTargetGlobalVarEntryIndirect
Mark the entry as a declare target indirect global.
@ OMPTargetGlobalVarEntryLink
Mark the entry as a to declare target link.
@ OMPTargetGlobalVarEntryTo
Mark the entry as a to declare target.
@ OMPTargetGlobalVarEntryIndirectVTable
Mark the entry as a declare target indirect vtable.
function_ref< void(const TargetRegionEntryInfo &EntryInfo, const OffloadEntryInfoTargetRegion &)> OffloadTargetRegionEntryInfoActTy
brief Applies action Action on all registered entries.
bool hasDeviceGlobalVarEntryInfo(StringRef VarName) const
Checks if the variable with the given name has been registered already.
LLVM_ABI bool empty() const
Return true if a there are no entries defined.
std::optional< bool > IsTargetDevice
Flag to define whether to generate code for the role of the OpenMP host (if set to false) or device (...
std::optional< bool > IsGPU
Flag for specifying if the compilation is done for an accelerator.
LLVM_ABI int64_t getRequiresFlags() const
Returns requires directive clauses as flags compatible with those expected by libomptarget.
std::optional< bool > OpenMPOffloadMandatory
Flag for specifying if offloading is mandatory.
LLVM_ABI void setHasRequiresReverseOffload(bool Value)
LLVM_ABI bool hasRequiresUnifiedSharedMemory() const
LLVM_ABI void setHasRequiresUnifiedSharedMemory(bool Value)
unsigned getDefaultTargetAS() const
LLVM_ABI bool hasRequiresDynamicAllocators() const
LLVM_ABI void setHasRequiresUnifiedAddress(bool Value)
LLVM_ABI void setHasRequiresDynamicAllocators(bool Value)
LLVM_ABI bool hasRequiresReverseOffload() const
LLVM_ABI bool hasRequiresUnifiedAddress() const
Struct that keeps the information that should be kept throughout a 'target data' region.
An interface to create LLVM-IR for OpenMP directives.
LLVM_ABI InsertPointOrErrorTy createOrderedThreadsSimd(const LocationDescription &Loc, BodyGenCallbackTy BodyGenCB, FinalizeCallbackTy FiniCB, bool IsThreads)
Generator for 'omp ordered [threads | simd]'.
LLVM_ABI void emitAArch64DeclareSimdFunction(llvm::Function *Fn, unsigned VLENVal, llvm::ArrayRef< DeclareSimdAttrTy > ParamAttrs, DeclareSimdBranch Branch, char ISA, unsigned NarrowestDataSize, bool OutputBecomesInput)
Emit AArch64 vector-function ABI attributes for a declare simd function.
LLVM_ABI Constant * getOrCreateIdent(Constant *SrcLocStr, uint32_t SrcLocStrSize, omp::IdentFlag Flags=omp::IdentFlag(0), unsigned Reserve2Flags=0)
Return an ident_t* encoding the source location SrcLocStr and Flags.
LLVM_ABI void emitFlush(const LocationDescription &Loc, AtomicOrdering AO=AtomicOrdering::SequentiallyConsistent, AtomicScope Scope=AtomicScope::Device)
Generate a flush: a fence on a GPU, and a runtime call otherwise.
LLVM_ABI void registerDeclareTargetGlobalReplacement(GlobalValue *Original, GlobalValue *Replacement)
Register a module-scope replacement of a declare target global variable.
LLVM_ABI FunctionCallee getOrCreateRuntimeFunction(Module &M, omp::RuntimeFunction FnID)
Return the function declaration for the runtime function with FnID.
LLVM_ABI InsertPointOrErrorTy createCancel(const LocationDescription &Loc, Value *IfCondition, omp::Directive CanceledDirective)
Generator for 'omp cancel'.
std::function< Expected< Function * >(StringRef FunctionName)> FunctionGenCallback
Functions used to generate a function with the given name.
LLVM_ABI CallInst * createOMPAllocShared(const LocationDescription &Loc, Value *Size, const Twine &Name=Twine(""))
Create a runtime call for kmpc_alloc_shared.
ReductionGenCBKind
Enum class for the RedctionGen CallBack type to be used.
LLVM_ABI CanonicalLoopInfo * collapseLoops(DebugLoc DL, ArrayRef< CanonicalLoopInfo * > Loops, InsertPointTy ComputeIP)
Collapse a loop nest using Config.CollapseMapping.
LLVM_ABI void createTaskyield(const LocationDescription &Loc)
Generator for 'omp taskyield'.
std::function< Error(InsertPointTy CodeGenIP)> FinalizeCallbackTy
Callback type for variable finalization (think destructors).
LLVM_ABI void emitBranch(BasicBlock *Target)
LLVM_ABI Error emitCancelationCheckImpl(Value *CancelFlag, omp::Directive CanceledDirective)
Generate control flow and cleanup for cancellation.
static LLVM_ABI void writeThreadBoundsForKernel(const Triple &T, Function &Kernel, int32_t LB, int32_t UB)
LLVM_ABI void emitTaskwaitImpl(const LocationDescription &Loc)
Generate a taskwait runtime call.
LLVM_ABI Constant * registerTargetRegionFunction(TargetRegionEntryInfo &EntryInfo, Function *OutlinedFunction, StringRef EntryFnName, StringRef EntryFnIDName)
Registers the given function and sets up the attribtues of the function Returns the FunctionID.
LLVM_ABI GlobalVariable * emitKernelExecutionMode(StringRef KernelName, omp::OMPTgtExecModeFlags Mode)
Emit the kernel execution mode.
LLVM_ABI void initialize()
Initialize the internal state, this will put structures types and potentially other helpers into the ...
LLVM_ABI InsertPointTy createAtomicCompare(const LocationDescription &Loc, AtomicOpValue &X, AtomicOpValue &V, AtomicOpValue &R, Value *E, Value *D, AtomicOrdering AO, omp::OMPAtomicCompareOp Op, bool IsXBinopExpr, bool IsPostfixUpdate, bool IsFailOnly, bool IsWeak=false)
LLVM_ABI InsertPointTy createAtomicWrite(const LocationDescription &Loc, AtomicOpValue &X, Value *Expr, AtomicOrdering AO, InsertPointTy AllocaIP)
Emit atomic write for : X = Expr — Only Scalar data types.
LLVM_ABI void loadOffloadInfoMetadata(Module &M)
Loads all the offload entries information from the host IR metadata.
function_ref< MapInfosTy &(InsertPointTy CodeGenIP)> GenMapInfoCallbackTy
Callback type for creating the map infos for the kernel parameters.
LLVM_ABI Error emitOffloadingArrays(InsertPointTy AllocaIP, InsertPointTy CodeGenIP, MapInfosTy &CombinedInfo, TargetDataInfo &Info, CustomMapperCallbackTy CustomMapperCB, bool IsNonContiguous=false, function_ref< void(unsigned int, Value *)> DeviceAddrCB=nullptr)
Emit the arrays used to pass the captures and map information to the offloading runtime library.
LLVM_ABI void unrollLoopFull(DebugLoc DL, CanonicalLoopInfo *Loop)
Fully unroll a loop.
function_ref< Error(InsertPointTy CodeGenIP, Value *IndVar)> LoopBodyGenCallbackTy
Callback type for loop body code generation.
LLVM_ABI InsertPointOrErrorTy emitScanReduction(const LocationDescription &Loc, ArrayRef< llvm::OpenMPIRBuilder::ReductionInfo > ReductionInfos, ScanInfo *ScanRedInfo)
This function performs the scan reduction of the values updated in the input phase.
LLVM_ABI InsertPointOrErrorTy createScope(const LocationDescription &Loc, BodyGenCallbackTy BodyGenCB, FinalizeCallbackTy FiniCB, bool IsNowait)
Generator for 'omp scope'.
static LLVM_ABI std::pair< int32_t, int32_t > readThreadBoundsForKernel(const Triple &T, Function &Kernel)
}
OpenMPIRBuilderConfig Config
The OpenMPIRBuilder Configuration.
LLVM_ABI CallInst * createOMPInteropDestroy(const LocationDescription &Loc, Value *InteropVar, Value *Device, Value *NumDependences, Value *DependenceAddress, bool HaveNowaitClause)
Create a runtime call for __tgt_interop_destroy.
LLVM_ABI void emitUsed(StringRef Name, ArrayRef< llvm::WeakTrackingVH > List)
Emit the llvm.used metadata.
LLVM_ABI InsertPointOrErrorTy createSingle(const LocationDescription &Loc, BodyGenCallbackTy BodyGenCB, FinalizeCallbackTy FiniCB, bool IsNowait, ArrayRef< llvm::Value * > CPVars={}, ArrayRef< llvm::Function * > CPFuncs={})
Generator for 'omp single'.
LLVM_ABI InsertPointOrErrorTy createTarget(const LocationDescription &Loc, bool IsOffloadEntry, OpenMPIRBuilder::InsertPointTy AllocaIP, OpenMPIRBuilder::InsertPointTy CodeGenIP, ArrayRef< BasicBlock * > DeallocBlocks, TargetDataInfo &Info, TargetRegionEntryInfo &EntryInfo, const TargetKernelDefaultAttrs &DefaultAttrs, const TargetKernelRuntimeAttrs &RuntimeAttrs, Value *IfCond, SmallVectorImpl< Value * > &Inputs, GenMapInfoCallbackTy GenMapInfoCB, TargetBodyGenCallbackTy BodyGenCB, TargetGenArgAccessorsCallbackTy ArgAccessorFuncCB, CustomMapperCallbackTy CustomMapperCB, const DependenciesInfo &Dependencies={}, bool HasNowait=false, Value *DynCGroupMem=nullptr, omp::OMPDynGroupprivateFallbackType DynCGroupMemFallback=omp::OMPDynGroupprivateFallbackType::Abort, DebugLoc OutlinedFnLoc={}, Value *RTLocOverride=nullptr)
Generator for 'omp target'.
LLVM_ABI InsertPointOrErrorTy createTeams(const LocationDescription &Loc, BodyGenCallbackTy BodyGenCB, Value *NumTeamsLower=nullptr, Value *NumTeamsUpper=nullptr, Value *ThreadLimit=nullptr, Value *IfExpr=nullptr)
Generator for #omp teams
std::forward_list< CanonicalLoopInfo > LoopInfos
Collection of owned canonical loop objects that eventually need to be free'd.
LLVM_ABI llvm::StructType * getKmpTaskAffinityInfoTy()
Return the LLVM struct type matching runtime kmp_task_affinity_info_t.
LLVM_ABI Constant * emitKernelEnvironment(const LocationDescription &Loc, const llvm::OpenMPIRBuilder::TargetKernelDefaultAttrs &Attrs)
The omp target interface.
LLVM_ABI std::string createPlatformSpecificName(ArrayRef< StringRef > Parts) const
Get the create a name using the platform specific separators.
LLVM_ABI FunctionCallee createDispatchNextFunction(unsigned IVSize, bool IVSigned)
Returns __kmpc_dispatch_next_* runtime function for the specified size IVSize and sign IVSigned.
static LLVM_ABI void getKernelArgsVector(TargetKernelArgs &KernelArgs, IRBuilderBase &Builder, SmallVector< Value * > &ArgsVector)
Create the kernel args vector used by emitTargetKernel.
LLVM_ABI void createFlush(const LocationDescription &Loc, AtomicOrdering AO=AtomicOrdering::SequentiallyConsistent, AtomicScope Scope=AtomicScope::Device)
Generator for 'omp flush'.
LLVM_ABI void unrollLoopHeuristic(DebugLoc DL, CanonicalLoopInfo *Loop)
Fully or partially unroll a loop.
LLVM_ABI omp::OpenMPOffloadMappingFlags getMemberOfFlag(unsigned Position)
Get OMP_MAP_MEMBER_OF flag with extra bits reserved based on the position given.
LLVM_ABI void addAttributes(omp::RuntimeFunction FnID, Function &Fn)
Add attributes known for FnID to Fn.
LLVM_ABI Expected< Function * > emitUserDefinedMapper(function_ref< MapInfosOrErrorTy(InsertPointTy CodeGenIP, llvm::Value *PtrPHI, llvm::Value *BeginArg)> PrivAndGenMapInfoCB, llvm::Type *ElemTy, StringRef FuncName, CustomMapperCallbackTy CustomMapperCB, bool PreserveMemberOfFlags=false, bool PropagatePresentToPointeeStorage=false, bool PropagatePresentToNonPointeeStorage=false)
Emit the user-defined mapper function.
Module & M
The underlying LLVM-IR module.
StringMap< Constant * > SrcLocStrMap
Map to remember source location strings.
LLVM_ABI void createMapperAllocas(const LocationDescription &Loc, InsertPointTy AllocaIP, unsigned NumOperands, struct MapperAllocas &MapperAllocas)
Create the allocas instruction used in call to mapper functions.
SmallVector< DeclareTargetGlobalReplacement, 8 > DeclareTargetGlobalReplacements
Collection of declare target globals to rewrite uses of during device module finalizaiton.
LLVM_ABI Constant * getOrCreateSrcLocStr(StringRef LocStr, uint32_t &SrcLocStrSize)
Return the (LLVM-IR) string describing the source location LocStr.
LLVM_ABI Error emitTargetRegionFunction(TargetRegionEntryInfo &EntryInfo, FunctionGenCallback &GenerateFunctionCallback, bool IsOffloadEntry, Function *&OutlinedFn, Constant *&OutlinedFnID)
Create a unique name for the entry function using the source location information of the current targ...
LLVM_ABI InsertPointOrErrorTy createIteratorLoop(LocationDescription Loc, llvm::Value *TripCount, IteratorBodyGenTy BodyGen, llvm::StringRef Name="iterator")
Create a canonical iterator loop at the current insertion point.
LLVM_ABI Expected< SmallVector< llvm::CanonicalLoopInfo * > > createCanonicalScanLoops(const LocationDescription &Loc, LoopBodyGenCallbackTy BodyGenCB, Value *Start, Value *Stop, Value *Step, bool IsSigned, bool InclusiveStop, InsertPointTy ComputeIP, const Twine &Name, ScanInfo *ScanRedInfo)
Generator for the control flow structure of an OpenMP canonical loops if the parent directive has an ...
LLVM_ABI FunctionCallee createDispatchFiniFunction(unsigned IVSize, bool IVSigned)
Returns __kmpc_dispatch_fini_* runtime function for the specified size IVSize and sign IVSigned.
function_ref< InsertPointOrErrorTy( InsertPointTy AllocaIP, InsertPointTy CodeGenIP, ArrayRef< BasicBlock * > DeallocBlocks)> TargetBodyGenCallbackTy
LLVM_ABI void unrollLoopPartial(DebugLoc DL, CanonicalLoopInfo *Loop, int32_t Factor, CanonicalLoopInfo **UnrolledCLI)
Partially unroll a loop.
function_ref< Error(Value *DeviceID, Value *RTLoc, IRBuilderBase::InsertPoint TargetTaskAllocaIP)> TargetTaskBodyCallbackTy
Callback type for generating the bodies of device directives that require outer target tasks (e....
Expected< MapInfosTy & > MapInfosOrErrorTy
bool HandleFPNegZero
Emit atomic compare for constructs: — Only scalar data types cond-expr-stmt: x = x ordop expr ?
LLVM_ABI void emitTaskyieldImpl(const LocationDescription &Loc)
Generate a taskyield runtime call.
LLVM_ABI void emitMapperCall(const LocationDescription &Loc, Function *MapperFunc, Value *SrcLocInfo, Value *MaptypesArg, Value *MapnamesArg, struct MapperAllocas &MapperAllocas, int64_t DeviceID, unsigned NumOperands)
Create the call for the target mapper function.
LLVM_ABI InsertPointOrErrorTy createDistribute(const LocationDescription &Loc, InsertPointTy AllocaIP, ArrayRef< BasicBlock * > DeallocBlocks, BodyGenCallbackTy BodyGenCB)
Generator for #omp distribute
function_ref< Expected< Function * >(unsigned int)> CustomMapperCallbackTy
LLVM_ABI InsertPointTy createOrderedDepend(const LocationDescription &Loc, InsertPointTy AllocaIP, unsigned NumLoops, ArrayRef< llvm::Value * > StoreValues, const Twine &Name, bool IsDependSource)
Generator for 'omp ordered depend (source | sink)'.
LLVM_ABI InsertPointTy createCopyinClauseBlocks(InsertPointTy IP, Value *MasterAddr, Value *PrivateAddr, llvm::IntegerType *IntPtrTy, bool BranchtoEnd=true)
Generate conditional branch and relevant BasicBlocks through which private threads copy the 'copyin' ...
function_ref< InsertPointOrErrorTy( InsertPointTy AllocaIP, InsertPointTy CodeGenIP, Value &Original, Value &Inner, Value *&ReplVal)> PrivatizeCallbackTy
Callback type for variable privatization (think copy & default constructor).
LLVM_ABI bool isFinalized()
Check whether the finalize function has already run.
SmallVector< FinalizationInfo, 8 > FinalizationStack
The finalization stack made up of finalize callbacks currently in-flight, wrapped into FinalizationIn...
LLVM_ABI std::vector< CanonicalLoopInfo * > tileLoops(DebugLoc DL, ArrayRef< CanonicalLoopInfo * > Loops, ArrayRef< Value * > TileSizes)
Tile a loop nest.
LLVM_ABI CallInst * createOMPInteropInit(const LocationDescription &Loc, Value *InteropVar, omp::OMPInteropType InteropType, Value *Device, Value *NumDependences, Value *DependenceAddress, bool HaveNowaitClause)
Create a runtime call for __tgt_interop_init.
LLVM_ABI Error emitIfClause(Value *Cond, BodyGenCallbackTy ThenGen, BodyGenCallbackTy ElseGen, InsertPointTy AllocaIP={}, ArrayRef< BasicBlock * > DeallocBlocks={})
Emits code for OpenMP 'if' clause using specified BodyGenCallbackTy Here is the logic: if (Cond) { Th...
LLVM_ABI void finalize(Function *Fn=nullptr)
Finalize the underlying module, e.g., by outlining regions.
LLVM_ABI Function * getOrCreateRuntimeFunctionPtr(omp::RuntimeFunction FnID)
void addOutlineInfo(std::unique_ptr< OutlineInfo > &&OI)
Add a new region that will be outlined later.
LLVM_ABI InsertPointTy createTargetInit(const LocationDescription &Loc, const llvm::OpenMPIRBuilder::TargetKernelDefaultAttrs &Attrs)
Create a runtime call for kmpc_target_init.
LLVM_ABI InsertPointOrErrorTy createReductions(const LocationDescription &Loc, InsertPointTy AllocaIP, ArrayRef< ReductionInfo > ReductionInfos, ArrayRef< bool > IsByRef, bool IsNoWait=false, bool IsTeamsReduction=false)
Generator for 'omp reduction'.
const Triple T
The target triple of the underlying module.
DenseMap< std::pair< Constant *, uint64_t >, Constant * > IdentMap
Map to remember existing ident_t*.
LLVM_ABI CallInst * createOMPFree(const LocationDescription &Loc, Value *Addr, Value *Allocator, std::string Name="")
Create a runtime call for kmpc_free.
LLVM_ABI InsertPointOrErrorTy createReductionsGPU(const LocationDescription &Loc, InsertPointTy AllocaIP, InsertPointTy CodeGenIP, ArrayRef< ReductionInfo > ReductionInfos, ArrayRef< bool > IsByRef, bool IsNoWait=false, bool IsTeamsReduction=false, bool IsSPMD=false, ReductionGenCBKind ReductionGenCBKind=ReductionGenCBKind::MLIR, std::optional< omp::GV > GridValue={}, Value *SrcLocInfo=nullptr)
Design of OpenMP reductions on the GPU.
LLVM_ABI FunctionCallee createForStaticInitFunction(unsigned IVSize, bool IVSigned, bool IsGPUDistribute)
Returns __kmpc_for_static_init_* runtime function for the specified size IVSize and sign IVSigned.
LLVM_ABI CallInst * createOMPAlloc(const LocationDescription &Loc, Value *Size, Value *Allocator, std::string Name="")
Create a runtime call for kmpc_alloc.
LLVM_ABI void emitNonContiguousDescriptor(InsertPointTy AllocaIP, InsertPointTy CodeGenIP, MapInfosTy &CombinedInfo, TargetDataInfo &Info)
Emit an array of struct descriptors to be assigned to the offload args.
LLVM_ABI InsertPointOrErrorTy createSection(const LocationDescription &Loc, BodyGenCallbackTy BodyGenCB, FinalizeCallbackTy FiniCB)
Generator for 'omp section'.
LLVM_ABI InsertPointOrErrorTy createTaskgroup(const LocationDescription &Loc, InsertPointTy AllocaIP, ArrayRef< BasicBlock * > DeallocBlocks, BodyGenCallbackTy BodyGenCB)
Generator for the taskgroup construct.
LLVM_ABI InsertPointOrErrorTy createParallel(const LocationDescription &Loc, InsertPointTy AllocaIP, ArrayRef< BasicBlock * > DeallocBlocks, BodyGenCallbackTy BodyGenCB, PrivatizeCallbackTy PrivCB, FinalizeCallbackTy FiniCB, Value *IfCondition, Value *NumThreads, omp::ProcBindKind ProcBind, bool IsCancellable)
Generator for 'omp parallel'.
function_ref< InsertPointOrErrorTy(InsertPointTy)> EmitFallbackCallbackTy
Callback function type for functions emitting the host fallback code that is executed when the kernel...
static LLVM_ABI TargetRegionEntryInfo getTargetEntryUniqueInfo(FileIdentifierInfoCallbackTy CallBack, vfs::FileSystem &VFS, StringRef ParentName="")
Creates a unique info for a target entry when provided a filename and line number from.
LLVM_ABI void emitTaskDependency(IRBuilderBase &Builder, Value *Entry, const DependData &Dep)
Store one kmp_depend_info entry at the given Entry pointer.
LLVM_ABI void emitBlock(BasicBlock *BB, Function *CurFn, bool IsFinished=false)
LLVM_ABI Value * getOrCreateThreadID(Value *Ident)
Return the current thread ID.
LLVM_ABI InsertPointOrErrorTy createMaster(const LocationDescription &Loc, BodyGenCallbackTy BodyGenCB, FinalizeCallbackTy FiniCB)
Generator for 'omp master'.
LLVM_ABI InsertPointOrErrorTy createTargetData(const LocationDescription &Loc, InsertPointTy AllocaIP, InsertPointTy CodeGenIP, ArrayRef< BasicBlock * > DeallocBlocks, Value *DeviceID, Value *IfCond, TargetDataInfo &Info, GenMapInfoCallbackTy GenMapInfoCB, CustomMapperCallbackTy CustomMapperCB, omp::RuntimeFunction *MapperFunc=nullptr, function_ref< InsertPointOrErrorTy(InsertPointTy CodeGenIP, BodyGenTy BodyGenType)> BodyGenCB=nullptr, function_ref< void(unsigned int, Value *)> DeviceAddrCB=nullptr, Value *SrcLocInfo=nullptr)
Generator for 'omp target data'.
LLVM_ABI CallInst * createRuntimeFunctionCall(FunctionCallee Callee, ArrayRef< Value * > Args, StringRef Name="")
LLVM_ABI InsertPointOrErrorTy emitKernelLaunch(const LocationDescription &Loc, Value *OutlinedFnID, EmitFallbackCallbackTy EmitTargetCallFallbackCB, TargetKernelArgs &Args, Value *DeviceID, Value *RTLoc, InsertPointTy AllocaIP)
Generate a target region entry call and host fallback call.
StringMap< GlobalVariable *, BumpPtrAllocator > InternalVars
An ordered map of auto-generated variables to their unique names.
LLVM_ABI InsertPointOrErrorTy createCancellationPoint(const LocationDescription &Loc, omp::Directive CanceledDirective)
Generator for 'omp cancellation point'.
LLVM_ABI CallInst * createOMPAlignedAlloc(const LocationDescription &Loc, Value *Align, Value *Size, Value *Allocator, std::string Name="")
Create a runtime call for kmpc_align_alloc.
LLVM_ABI FunctionCallee createDispatchInitFunction(unsigned IVSize, bool IVSigned)
Returns __kmpc_dispatch_init_* runtime function for the specified size IVSize and sign IVSigned.
LLVM_ABI InsertPointOrErrorTy createScan(const LocationDescription &Loc, InsertPointTy AllocaIP, ArrayRef< llvm::Value * > ScanVars, ArrayRef< llvm::Type * > ScanVarsType, bool IsInclusive, ScanInfo *ScanRedInfo)
This directive split and directs the control flow to input phase blocks or scan phase blocks based on...
LLVM_ABI CallInst * createOMPFreeShared(const LocationDescription &Loc, Value *Addr, Value *Size, const Twine &Name=Twine(""))
Create a runtime call for kmpc_free_shared.
LLVM_ABI CallInst * createOMPInteropUse(const LocationDescription &Loc, Value *InteropVar, Value *Device, Value *NumDependences, Value *DependenceAddress, bool HaveNowaitClause)
Create a runtime call for __tgt_interop_use.
IRBuilder<>::InsertPoint InsertPointTy
Type used throughout for insertion points.
LLVM_ABI GlobalVariable * getOrCreateInternalVariable(Type *Ty, const StringRef &Name, std::optional< unsigned > AddressSpace={})
Gets (if variable with the given name already exist) or creates internal global variable with the spe...
LLVM_ABI GlobalVariable * createOffloadMapnames(SmallVectorImpl< llvm::Constant * > &Names, std::string VarName)
Create the global variable holding the offload names information.
LLVM_ABI InsertPointOrErrorTy createTask(const LocationDescription &Loc, InsertPointTy AllocaIP, ArrayRef< BasicBlock * > DeallocBlocks, BodyGenCallbackTy BodyGenCB, bool Tied=true, Value *Final=nullptr, Value *IfCondition=nullptr, const DependenciesInfo &Dependencies={}, const AffinityData &Affinities={}, bool Mergeable=false, Value *EventHandle=nullptr, Value *Priority=nullptr, bool FreeAgent=false)
Generator for #omp taskloop
std::forward_list< ScanInfo > ScanInfos
Collection of owned ScanInfo objects that eventually need to be free'd.
static LLVM_ABI void writeTeamsForKernel(const Triple &T, Function &Kernel, int32_t LB, int32_t UB)
LLVM_ABI Value * calculateCanonicalLoopTripCount(const LocationDescription &Loc, Value *Start, Value *Stop, Value *Step, bool IsSigned, bool InclusiveStop, const Twine &Name="loop")
Calculate the trip count of a canonical loop.
LLVM_ABI InsertPointOrErrorTy createBarrier(const LocationDescription &Loc, omp::Directive Kind, bool ForceSimpleCall=false, bool CheckCancelFlag=true)
Emitter methods for OpenMP directives.
LLVM_ABI void setCorrectMemberOfFlag(omp::OpenMPOffloadMappingFlags &Flags, omp::OpenMPOffloadMappingFlags MemberOfFlag)
Given an initial flag set, this function modifies it to contain the passed in MemberOfFlag generated ...
LLVM_ABI Error emitOffloadingArraysAndArgs(InsertPointTy AllocaIP, InsertPointTy CodeGenIP, TargetDataInfo &Info, TargetDataRTArgs &RTArgs, MapInfosTy &CombinedInfo, CustomMapperCallbackTy CustomMapperCB, bool IsNonContiguous=false, bool ForEndCall=false, function_ref< void(unsigned int, Value *)> DeviceAddrCB=nullptr)
Allocates memory for and populates the arrays required for offloading (offload_{baseptrs|ptrs|mappers...
LLVM_ABI Constant * getOrCreateDefaultSrcLocStr(uint32_t &SrcLocStrSize)
Return the (LLVM-IR) string describing the default source location.
LLVM_ABI InsertPointOrErrorTy createCritical(const LocationDescription &Loc, BodyGenCallbackTy BodyGenCB, FinalizeCallbackTy FiniCB, StringRef CriticalName, Value *HintInst)
Generator for 'omp critical'.
LLVM_ABI void createError(const LocationDescription &Loc, bool IsFatal, Value *Message)
Generate a call to the runtime to emit the diagnostic of an OpenMP error directive with at(execution)...
LLVM_ABI void createOffloadEntry(Constant *ID, Constant *Addr, uint64_t Size, int32_t Flags, GlobalValue::LinkageTypes, StringRef Name="")
Creates offloading entry for the provided entry ID ID, address Addr, size Size, and flags Flags.
static LLVM_ABI unsigned getOpenMPDefaultSimdAlign(const Triple &TargetTriple, const StringMap< bool > &Features)
Get the default alignment value for given target.
LLVM_ABI unsigned getFlagMemberOffset()
Get the offset of the OMP_MAP_MEMBER_OF field.
LLVM_ABI InsertPointOrErrorTy createAtomicCapture(const LocationDescription &Loc, InsertPointTy AllocaIP, AtomicOpValue &X, AtomicOpValue &V, Value *Expr, AtomicOrdering AO, AtomicRMWInst::BinOp RMWOp, AtomicUpdateCallbackTy &UpdateOp, bool UpdateExpr, bool IsPostfixUpdate, bool IsXBinopExpr, bool IsIgnoreDenormalMode=false, bool IsFineGrainedMemory=false, bool IsRemoteMemory=false)
Emit atomic update for constructs: — Only Scalar data types V = X; X = X BinOp Expr ,...
LLVM_ABI CanonicalLoopInfo * createLoopSkeleton(DebugLoc DL, Value *TripCount, Function *F, BasicBlock *PreInsertBefore, BasicBlock *PostInsertBefore, const Twine &Name={}, bool IsCollapsed=false)
Create the control flow structure of a canonical OpenMP loop.
LLVM_ABI void createOffloadEntriesAndInfoMetadata(EmitMetadataErrorReportFunctionTy &ErrorReportFunction)
LLVM_ABI void applySimd(CanonicalLoopInfo *Loop, MapVector< Value *, Value * > AlignedVars, Value *IfCond, omp::OrderKind Order, ConstantInt *Simdlen, ConstantInt *Safelen)
Add metadata to simd-ize a loop.
SmallVector< std::unique_ptr< OutlineInfo >, 16 > OutlineInfos
Collection of regions that need to be outlined during finalization.
LLVM_ABI InsertPointOrErrorTy createAtomicUpdate(const LocationDescription &Loc, InsertPointTy AllocaIP, AtomicOpValue &X, Value *Expr, AtomicOrdering AO, AtomicRMWInst::BinOp RMWOp, AtomicUpdateCallbackTy &UpdateOp, bool IsXBinopExpr, bool IsIgnoreDenormalMode=false, bool IsFineGrainedMemory=false, bool IsRemoteMemory=false)
Emit atomic update for constructs: X = X BinOp Expr ,or X = Expr BinOp X For complex Operations: X = ...
std::function< std::tuple< std::string, uint64_t >()> FileIdentifierInfoCallbackTy
bool isLastFinalizationInfoCancellable(omp::Directive DK)
Return true if the last entry in the finalization stack is of kind DK and cancellable.
LLVM_ABI InsertPointTy emitTargetKernel(const LocationDescription &Loc, InsertPointTy AllocaIP, Value *&Return, Value *Ident, Value *DeviceID, Value *NumTeams, Value *NumThreads, Value *HostPtr, ArrayRef< Value * > KernelArgs)
Generate a target region entry call.
LLVM_ABI GlobalVariable * createOffloadMaptypes(SmallVectorImpl< uint64_t > &Mappings, std::string VarName)
Create the global variable holding the offload mappings information.
LLVM_ABI CallInst * createCachedThreadPrivate(const LocationDescription &Loc, llvm::Value *Pointer, llvm::ConstantInt *Size, const llvm::Twine &Name=Twine(""))
Create a runtime call for kmpc_threadprivate_cached.
IRBuilder Builder
The LLVM-IR Builder used to create IR.
LLVM_ABI GlobalValue * createGlobalFlag(unsigned Value, StringRef Name)
Create a hidden global flag Name in the module with initial value Value.
LLVM_ABI void emitOffloadingArraysArgument(IRBuilderBase &Builder, OpenMPIRBuilder::TargetDataRTArgs &RTArgs, OpenMPIRBuilder::TargetDataInfo &Info, bool ForEndCall=false)
Emit the arguments to be passed to the runtime library based on the arrays of base pointers,...
LLVM_ABI InsertPointOrErrorTy createMasked(const LocationDescription &Loc, BodyGenCallbackTy BodyGenCB, FinalizeCallbackTy FiniCB, Value *Filter)
Generator for 'omp masked'.
LLVM_ABI Expected< CanonicalLoopInfo * > createCanonicalLoop(const LocationDescription &Loc, LoopBodyGenCallbackTy BodyGenCB, Value *TripCount, const Twine &Name="loop")
Generator for the control flow structure of an OpenMP canonical loop.
function_ref< Expected< InsertPointTy >( InsertPointTy AllocaIP, InsertPointTy CodeGenIP, Value *DestPtr, Value *SrcPtr)> TaskDupCallbackTy
Callback type for task duplication function code generation.
LLVM_ABI Value * getSizeInBytes(Value *BasePtr)
Computes the size of type in bytes.
llvm::function_ref< llvm::Error( InsertPointTy BodyIP, llvm::Value *LinearIV)> IteratorBodyGenTy
LLVM_ABI FunctionCallee createDispatchDeinitFunction()
Returns __kmpc_dispatch_deinit runtime function.
LLVM_ABI void registerTargetGlobalVariable(OffloadEntriesInfoManager::OMPTargetGlobalVarEntryKind CaptureClause, OffloadEntriesInfoManager::OMPTargetDeviceClauseKind DeviceClause, bool IsDeclaration, bool IsExternallyVisible, TargetRegionEntryInfo EntryInfo, StringRef MangledName, std::vector< GlobalVariable * > &GeneratedRefs, bool OpenMPSIMD, std::vector< Triple > TargetTriple, std::function< Constant *()> GlobalInitializer, std::function< GlobalValue::LinkageTypes()> VariableLinkage, Type *LlvmPtrTy, Constant *Addr)
Registers a target variable for device or host.
LLVM_ABI void createTargetDeinit(const LocationDescription &Loc, int32_t TeamsReductionDataSize=0)
Create a runtime call for kmpc_target_deinit.
BodyGenTy
Type of BodyGen to use for region codegen.
LLVM_ABI CanonicalLoopInfo * fuseLoops(DebugLoc DL, ArrayRef< CanonicalLoopInfo * > Loops)
Fuse a sequence of loops.
LLVM_ABI void emitX86DeclareSimdFunction(llvm::Function *Fn, unsigned NumElements, const llvm::APSInt &VLENVal, llvm::ArrayRef< DeclareSimdAttrTy > ParamAttrs, DeclareSimdBranch Branch)
Emit x86 vector-function ABI attributes for a declare simd function.
SmallVector< llvm::Function *, 16 > ConstantAllocaRaiseCandidates
A collection of candidate target functions that's constant allocas will attempt to be raised on a cal...
OffloadEntriesInfoManager OffloadInfoManager
Info manager to keep track of target regions.
static LLVM_ABI std::pair< int32_t, int32_t > readTeamBoundsForKernel(const Triple &T, Function &Kernel)
Read/write a bounds on teams for Kernel.
const std::string ompOffloadInfoName
OMP Offload Info Metadata name string.
LLVM_ABI InsertPointOrErrorTy applyWorkshareLoop(DebugLoc DL, CanonicalLoopInfo *CLI, InsertPointTy AllocaIP, bool NeedsBarrier, llvm::omp::ScheduleKind SchedKind=llvm::omp::OMP_SCHEDULE_Default, Value *ChunkSize=nullptr, bool HasSimdModifier=false, bool HasMonotonicModifier=false, bool HasNonmonotonicModifier=false, bool HasOrderedClause=false, omp::WorksharingLoopType LoopType=omp::WorksharingLoopType::ForStaticLoop, bool NoLoop=false, bool HasDistSchedule=false, Value *DistScheduleChunkSize=nullptr, bool NeedsLastIter=false)
Modifies the canonical loop to be a workshare loop.
Expected< InsertPointTy > InsertPointOrErrorTy
Type used to represent an insertion point or an error value.
LLVM_ABI InsertPointTy createCopyPrivate(const LocationDescription &Loc, llvm::Value *BufSize, llvm::Value *CpyBuf, llvm::Value *CpyFn, llvm::Value *DidIt)
Generator for __kmpc_copyprivate.
LLVM_ABI InsertPointOrErrorTy createSections(const LocationDescription &Loc, InsertPointTy AllocaIP, ArrayRef< StorableBodyGenCallbackTy > SectionCBs, PrivatizeCallbackTy PrivCB, FinalizeCallbackTy FiniCB, bool IsCancellable, bool IsNowait)
Generator for 'omp sections'.
std::function< void(EmitMetadataErrorKind, TargetRegionEntryInfo)> EmitMetadataErrorReportFunctionTy
Callback function type.
function_ref< InsertPointOrErrorTy( Argument &Arg, Value *Input, Value *&RetVal, InsertPointTy AllocaIP, InsertPointTy CodeGenIP, ArrayRef< InsertPointTy > DeallocIPs)> TargetGenArgAccessorsCallbackTy
LLVM_ABI Expected< ScanInfo * > scanInfoInitialize()
Creates a ScanInfo object, allocates and returns the pointer.
LLVM_ABI InsertPointOrErrorTy emitTargetTask(TargetTaskBodyCallbackTy TaskBodyCB, Value *DeviceID, Value *RTLoc, OpenMPIRBuilder::InsertPointTy AllocaIP, const DependenciesInfo &Dependencies, const TargetDataRTArgs &RTArgs, bool HasNoWait)
Generate a target-task for the target construct.
LLVM_ABI InsertPointTy createAtomicRead(const LocationDescription &Loc, AtomicOpValue &X, AtomicOpValue &V, AtomicOrdering AO, InsertPointTy AllocaIP)
Emit atomic Read for : V = X — Only Scalar data types.
function_ref< Error(InsertPointTy AllocaIP, InsertPointTy CodeGenIP, ArrayRef< BasicBlock * > DeallocBlocks)> BodyGenCallbackTy
Callback type for body (=inner region) code generation.
bool updateToLocation(const LocationDescription &Loc)
Update the internal location to Loc.
LLVM_ABI Constant * getAddrOfDeclareTargetVar(OffloadEntriesInfoManager::OMPTargetGlobalVarEntryKind CaptureClause, OffloadEntriesInfoManager::OMPTargetDeviceClauseKind DeviceClause, bool IsDeclaration, bool IsExternallyVisible, TargetRegionEntryInfo EntryInfo, StringRef MangledName, std::vector< GlobalVariable * > &GeneratedRefs, bool OpenMPSIMD, std::vector< Triple > TargetTriple, Type *LlvmPtrTy, std::function< Constant *()> GlobalInitializer, std::function< GlobalValue::LinkageTypes()> VariableLinkage)
Retrieve (or create if non-existent) the address of a declare target variable, used in conjunction wi...
LLVM_ABI void createTaskwait(const LocationDescription &Loc, DependenciesInfo Dependencies={}, bool IsNowait=false)
Generator for 'omp taskwait'.
origPtr *with the address space normalization required by the runtime entry point *The NULL descriptor makes the runtime walk the enclosing taskgroups to *find the matching task_reduction registration for the item The lookups *are emitted at p Loc
EmitMetadataErrorKind
The kind of errors that can occur when emitting the offload entries and metadata.
unsigned getOpcode() const
Return the opcode for this Instruction or ConstantExpr.
Definition Operator.h:43
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
Pseudo-analysis pass that exposes the PassInstrumentation to pass managers.
Class to represent pointers.
static PointerType * getUnqual(LLVMContext &C)
This constructs an opaque pointer to an object in the default address space (address space zero).
static LLVM_ABI PointerType * get(LLVMContext &C, unsigned AddressSpace)
This constructs an opaque pointer to an object in a numbered address space.
Definition Type.cpp:882
PostDominatorTree Class - Concrete subclass of DominatorTree that is used to compute the post-dominat...
ScanInfo holds the information to assist in lowering of Scan reduction.
llvm::SmallDenseMap< llvm::Value *, llvm::Value * > * ScanBuffPtrs
Maps the private reduction variable to the pointer of the temporary buffer.
llvm::BasicBlock * OMPScanLoopExit
Exit block of loop body.
llvm::Value * IV
Keeps track of value of iteration variable for input/scan loop to be used for Scan directive lowering...
llvm::BasicBlock * OMPAfterScanBlock
Dominates the body of the loop before scan directive.
llvm::BasicBlock * OMPScanInit
Block before loop body where scan initializations are done.
llvm::BasicBlock * OMPBeforeScanBlock
Dominates the body of the loop before scan directive.
llvm::BasicBlock * OMPScanFinish
Block after loop body where scan finalizations are done.
llvm::Value * Span
Stores the span of canonical loop being lowered to be used for temporary buffer allocation or Finaliz...
bool OMPFirstScanLoop
If true, it indicates Input phase is lowered; else it indicates ScanPhase is lowered.
llvm::BasicBlock * OMPScanDispatch
Controls the flow to before or after scan blocks.
A vector that has set insertion semantics.
Definition SetVector.h:57
bool remove_if(UnaryPredicate P)
Remove items from the set vector based on a predicate function.
Definition SetVector.h:236
bool empty() const
Determine if the SetVector is empty or not.
Definition SetVector.h:100
This is a 'bitvector' (really, a variable-sized bit array), optimized for the case when the array is ...
SmallBitVector & set()
bool test(unsigned Idx) const
Returns true if bit Idx is set.
bool all() const
Returns true if all bits are set.
bool any() const
Returns true if any bit is set.
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition SmallSet.h:134
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition SmallString.h:28
void append(StringRef RHS)
Append from a StringRef.
Definition SmallString.h:70
StringRef str() const
Explicit conversion to StringRef.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void reserve(size_type N)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void resize(size_type N)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
void setAlignment(Align Align)
void setAtomic(AtomicOrdering Ordering, SyncScope::ID SSID=SyncScope::System)
Sets the ordering constraint and the synchronization scope ID of this store instruction.
StringMap - This is an unconventional map that is specialized for handling keys that are "strings",...
Definition StringMap.h:129
ValueTy lookup(StringRef Key) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
Definition StringMap.h:250
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
std::string str() const
Get the contents as an std::string.
Definition StringRef.h:222
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
constexpr size_t size() const
Get the string size.
Definition StringRef.h:144
size_t count(char C) const
Return the number of occurrences of C in the string.
Definition StringRef.h:463
bool ends_with(StringRef Suffix) const
Check if this string ends with the given Suffix.
Definition StringRef.h:270
StringRef drop_back(size_t N=1) const
Return a StringRef equal to 'this' but with the last N elements dropped.
Definition StringRef.h:634
StringSet - A wrapper for StringMap that provides set-like functionality.
Definition StringSet.h:27
bool contains(StringRef key) const
Check if the set contains the given key.
Definition StringSet.h:62
Class to represent struct types.
static LLVM_ABI StructType * get(LLVMContext &Context, ArrayRef< Type * > Elements, bool isPacked=false)
This static method is the primary way to create a literal StructType.
Definition Type.cpp:462
static LLVM_ABI StructType * create(LLVMContext &Context, StringRef Name)
This creates an identified struct.
Definition Type.cpp:657
Type * getElementType(unsigned N) const
Multiway switch.
LLVM_ABI void addCase(ConstantInt *OnVal, BasicBlock *Dest)
Add an entry to the switch instruction.
Target - Wrapper for Target specific information.
Triple - Helper class for working with autoconf configuration names.
Definition Triple.h:48
bool isPPC() const
Tests whether the target is PowerPC (32- or 64-bit LE or BE).
Definition Triple.h:1146
bool isX86() const
Tests whether the target is x86 (32- or 64-bit).
Definition Triple.h:1203
bool isWasm() const
Tests whether the target is wasm (32- and 64-bit).
Definition Triple.h:1217
bool isSystemZ() const
Tests whether the target is SystemZ.
Definition Triple.h:1200
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
LLVM_ABI std::string str() const
Return the twine contents as a std::string.
Definition Twine.cpp:17
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
Definition Type.cpp:295
LLVM_ABI unsigned getIntegerBitWidth() const
LLVM_ABI Type * getStructElementType(unsigned N) const
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:294
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:277
bool isFloatTy() const
Return true if this is 'float', a 32-bit IEEE fp type.
Definition Type.h:155
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
static LLVM_ABI Type * getVoidTy(LLVMContext &C)
Definition Type.cpp:267
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.h:354
bool isStructTy() const
True if this is an instance of StructType.
Definition Type.h:271
bool isDoubleTy() const
Return true if this is 'double', a 64-bit IEEE fp type.
Definition Type.h:158
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
Definition Type.h:186
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition Type.cpp:298
bool isVoidTy() const
Return true if this is 'void'.
Definition Type.h:141
Unconditional Branch instruction.
static UncondBrInst * Create(BasicBlock *Target, InsertPosition InsertBefore=nullptr)
static LLVM_ABI UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
This function has undefined behavior.
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
void setOperand(unsigned i, Value *Val)
Definition User.h:212
Value * getOperand(unsigned i) const
Definition User.h:207
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
Definition Value.cpp:389
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:441
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:548
iterator_range< user_iterator > users()
Definition Value.h:428
User * user_back()
Definition Value.h:414
LLVM_ABI Align getPointerAlignment(const DataLayout &DL) const
Returns an alignment of the pointer value.
Definition Value.cpp:985
LLVM_ABI bool hasNUses(unsigned N) const
Return true if this Value has exactly N uses.
Definition Value.cpp:142
LLVM_ABI User * getUniqueUndroppableUser()
Return true if there is exactly one unique user of this value that cannot be dropped (that user can h...
Definition Value.cpp:180
bool use_empty() const
Definition Value.h:348
LLVM_ABI bool replaceUsesWithIf(Value *New, llvm::function_ref< bool(Use &U)> ShouldReplace)
Go through the uses list for this definition and make each use point to "V" if the callback ShouldRep...
Definition Value.cpp:556
iterator_range< use_iterator > uses()
Definition Value.h:382
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:314
An efficient, type-erasing, non-owning reference to a callable.
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
Definition ilist_node.h:348
A raw_ostream that writes to an SmallVector or SmallString.
The virtual file system interface.
llvm::ErrorOr< std::unique_ptr< llvm::MemoryBuffer > > getBufferForFile(const Twine &Name, int64_t FileSize=-1, bool RequiresNullTerminator=true, bool IsVolatile=false, bool IsText=true)
This is a convenience method that opens a file, gets its content and then closes the file.
virtual llvm::ErrorOr< Status > status(const Twine &Path)=0
Get the status of the entry at Path, if one exists.
CallInst * Call
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
@ Entry
Definition COFF.h:862
@ AMDGPU_KERNEL
Used for AMDGPU code object kernels.
@ SPIR_KERNEL
Used for SPIR kernel functions.
@ PTX_Kernel
Call to a PTX kernel. Passes all arguments in parameter space.
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > OverloadTys={})
Look up the Function declaration of the intrinsic id in the Module M.
Flag
These should be considered private to the implementation of the MCInstrDesc class.
constexpr StringLiteral MaxNTID("nvvm.maxntid")
constexpr StringLiteral MaxClusterRank("nvvm.maxclusterrank")
initializer< Ty > init(const Ty &Val)
@ User
could "use" a pointer
LLVM_ABI GlobalVariable * emitOffloadingEntry(Module &M, object::OffloadKind Kind, Constant *Addr, StringRef Name, uint64_t Size, uint32_t Flags, uint64_t Data, Constant *AuxAddr=nullptr)
Definition Utility.cpp:104
OpenMPOffloadMappingFlags
Values for bit flags used to specify the mapping type for offloading.
@ OMP_MAP_PTR_AND_OBJ
The element being mapped is a pointer-pointee pair; both the pointer and the pointee should be mapped...
@ OMP_MAP_MEMBER_OF
The 16 MSBs of the flags indicate whether the entry is member of some struct/class.
IdentFlag
IDs for all omp runtime library ident_t flag encodings (see their defintion in openmp/runtime/src/kmp...
RuntimeFunction
IDs for all omp runtime library (RTL) functions.
constexpr const GV & getAMDGPUGridValues()
constexpr unsigned DefaultPartialUnrollFactor
Unroll factor for a partial unroll without an explicit factor, when the unrolled loop must be materia...
static constexpr GV SPIRVGridValues
For generic SPIR-V GPUs.
OMPDynGroupprivateFallbackType
The fallback types for the dyn_groupprivate clause.
static constexpr GV NVPTXGridValues
For Nvidia GPUs.
@ OMP_TGT_EXEC_MODE_SPMD_NO_LOOP
Function * Kernel
Summary of a kernel (=entry point for target offloading).
Definition OpenMPOpt.h:21
WorksharingLoopType
A type of worksharing loop construct.
OMPAtomicCompareOp
Atomic compare operations. Currently OpenMP only supports ==, >, and <.
EnumSet< Property > Properties
NodeAddr< PhiNode * > Phi
Definition RDFGraph.h:390
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:316
LLVM_ABI BasicBlock * splitBBWithSuffix(IRBuilderBase &Builder, bool CreateBranch, llvm::Twine Suffix=".split")
Like splitBB, but reuses the current block's name for the new name.
@ Offset
Definition DWP.cpp:577
detail::zippy< detail::zip_shortest, T, U, Args... > zip(T &&t, U &&u, Args &&...args)
zip iterator for two or more iteratable types.
Definition STLExtras.h:846
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
hash_code hash_value(const FixedPointSemantics &Val)
LLVM_ABI Expected< std::unique_ptr< Module > > parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context, ParserCallbacks Callbacks={})
Read the specified bitcode file, returning the module.
AtomicScope
Target-neutral memory synchronization scopes.
Definition AtomicScope.h:23
detail::zippy< detail::zip_first, T, U, Args... > zip_equal(T &&t, U &&u, Args &&...args)
zip iterator that assumes that all iteratees have the same length.
Definition STLExtras.h:856
LLVM_ABI BasicBlock * CloneBasicBlock(const BasicBlock *BB, ValueToValueMapTy &VMap, const Twine &NameSuffix="", Function *F=nullptr, ClonedCodeInfo *CodeInfo=nullptr, bool MapAtoms=true)
Return a copy of the specified basic block, but without embedding the block into a particular functio...
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2575
unsigned getPointerAddressSpace(const Type *T)
Definition SPIRVUtils.h:381
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
auto successors(const MachineBasicBlock *BB)
@ Load
The value being inserted comes from a load (InsertElement only).
LLVM_ABI std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
Definition Error.cpp:94
testing::Matcher< const detail::ErrorHolder & > Failed()
Definition Error.h:198
constexpr from_range_t from_range
auto dyn_cast_if_present(const Y &Val)
dyn_cast_if_present<X> - Functionally identical to dyn_cast, except that a null (or none in the case ...
Definition Casting.h:732
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
LLVM_ENABLE_BITMASK_ENUMS_IN_NAMESPACE()
LLVM_ABI BasicBlock * splitBB(IRBuilderBase::InsertPoint IP, bool CreateBranch, DebugLoc DL, llvm::Twine Name={})
Split a BasicBlock at an InsertPoint, even if the block is degenerate (missing the terminator).
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2229
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:649
std::string utostr(uint64_t X, bool isNeg=false)
void * PointerTy
ErrorOr< T > expectedToErrorOrAndEmitErrors(LLVMContext &Ctx, Expected< T > Val)
bool isa_and_nonnull(const Y &Val)
Definition Casting.h:676
LLVM_ABI void reportFatalInternalError(Error Err)
Report a fatal error that indicates a bug in LLVM.
Definition Error.cpp:173
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
LLVM_ABI bool convertUsersOfConstantsToInstructions(ArrayRef< Constant * > Consts, Function *RestrictToFunc=nullptr, bool RemoveDeadConstants=true, bool IncludeSelf=false)
Replace constant expressions users of the given constants with instructions.
unsigned Log2_32(uint32_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
Definition MathExtras.h:326
AtomicOrderingCABI toCABI(AtomicOrdering AO)
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
LLVM_ABI void SplitBlockAndInsertIfThenElse(Value *Cond, BasicBlock::iterator SplitBefore, Instruction **ThenTerm, Instruction **ElseTerm, MDNode *BranchWeights=nullptr, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr)
SplitBlockAndInsertIfThenElse is similar to SplitBlockAndInsertIfThen, but also creates the ElseBlock...
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1769
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
Definition Format.h:102
Error make_error(ArgTs &&... Args)
Make a Error instance representing failure using the given error info type.
Definition Error.h:340
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
AtomicOrdering
Atomic ordering for LLVM's memory model.
constexpr T divideCeil(U Numerator, V Denominator)
Returns the integer ceil(Numerator / Denominator).
Definition MathExtras.h:389
void cantFail(Error Err, const char *Msg=nullptr)
Report a fatal error if Err is a failure value.
Definition Error.h:769
LLVM_ABI bool MergeBlockIntoPredecessor(BasicBlock *BB, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, MemoryDependenceResults *MemDep=nullptr, bool PredecessorWithTwoSuccessors=false, DominatorTree *DT=nullptr)
Attempts to merge a block into its predecessor, if possible.
@ Mul
Product of integers.
@ Add
Sum of integers.
LLVM_ABI BasicBlock * SplitBlock(BasicBlock *Old, BasicBlock::iterator SplitPt, DominatorTree *DT, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, const Twine &BBName="")
Split the specified block at the specified instruction.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
IntPtrTy
Definition InstrProf.h:82
DWARFExpression::Operation Op
LLVM_ABI void remapInstructionsInBlocks(ArrayRef< BasicBlock * > Blocks, ValueToValueMapTy &VMap)
Remaps instructions in Blocks using the mapping in VMap.
ArrayRef(const T &OneElt) -> ArrayRef< T >
OutputIt copy(R &&Range, OutputIt Out)
Definition STLExtras.h:1901
constexpr unsigned BitWidth
ValueMap< const Value *, WeakTrackingVH > ValueToValueMapTy
LLVM_ABI void spliceBB(IRBuilderBase::InsertPoint IP, BasicBlock *New, bool CreateBranch, DebugLoc DL)
Move the instruction after an InsertPoint to the beginning of another BasicBlock.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
constexpr auto seq(T Begin, T End)
Iterate over an integral type from Begin up to - but not including - End.
Definition Sequence.h:341
std::optional< StringRef > getAtomicScopeIRString(const Triple &T, AtomicScope S, bool IsSingleAddressSpace=false)
Returns the LLVM IR syncscope string that T uses to spell S.
Definition AtomicScope.h:34
auto predecessors(const MachineBasicBlock *BB)
auto filter_to_vector(ContainerTy &&C, PredicateFn &&Pred)
Filter a range to a SmallVector with the element types deduced.
PointerUnion< const Value *, const PseudoSourceValue * > ValueType
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Next
Definition InstrProf.h:147
LLVM_ABI Constant * ConstantFoldInsertValueInstruction(Constant *Agg, Constant *Val, ArrayRef< unsigned > Idxs)
Attempt to constant fold an insertvalue instruction with the specified operands and indices.
@ Continue
Definition DWP.h:26
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
LLVM_ABI void DeleteDeadBlocks(ArrayRef< BasicBlock * > BBs, DomTreeUpdater *DTU=nullptr, bool KeepOneInputPHIs=false)
Delete the specified blocks from BB.
bool to_integer(StringRef S, N &Num, unsigned Base=0)
Convert the string S to an integer of the specified type using the radix Base. If Base is 0,...
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
static auto filterDbgVars(iterator_range< simple_ilist< DbgRecord >::iterator > R)
Filter the DbgRecord range to DbgVariableRecord types only and downcast.
Physical handles captured before the source descriptors are invalidated.
SmallVector< PHINode *, 4 > IndVars
SmallVector< BasicBlock *, 4 > Preheaders
SmallVector< BasicBlock *, 4 > Latches
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Definition Alignment.h:111
A struct to pack the relevant information for an OpenMP affinity clause.
a struct to pack relevant information while generating atomic Ops
A struct to pack the relevant information for an OpenMP depend clause.
omp::RTLDependenceKindTy DepKind
A struct to pack static and dynamic dependency information for a task.
LLVM_ABI Error mergeFiniBB(IRBuilderBase &Builder, BasicBlock *ExistingFiniBB)
For cases where there is an unavoidable existing finalization block (e.g.
LLVM_ABI Expected< BasicBlock * > getFiniBB(IRBuilderBase &Builder)
The basic block to which control should be transferred to implement the FiniCB.
Description of a LLVM-IR insertion point (IP) and a debug/source location (filename,...
Represents a group of mapper sub-components produced by an iterator modifier on a declare mapper's ma...
omp::OpenMPOffloadMappingFlags Type
Map type/HasAttachPtr, constant across the segment.
Value * Count
Runtime (i64) trip count for this segment.
Function * ChildMapperFn
User-defined mapper to invoke for this segment's component, if the underlying map clause carries one ...
std::function< Expected< SmallVector< Value *, 3 > >(IRBuilderBase &, Value *)> GenEntry
Emits the code computing one iteration's (BasePointer, Pointer, Size) triple, given the loop's linear...
This structure contains combined information generated for mappable clauses, including base pointers,...
MapDeviceInfoArrayTy DevicePointers
StructNonContiguousInfo NonContigInfo
Helper that contains information about regions we need to outline during finalization.
void collectBlocks(SmallPtrSetImpl< BasicBlock * > &BlockSet, SmallVectorImpl< BasicBlock * > &BlockVector)
Collect all blocks in between EntryBB and ExitBB in both the given vector and set.
virtual std::unique_ptr< CodeExtractor > createCodeExtractor(ArrayRef< BasicBlock * > Blocks, bool ArgsInZeroAddressSpace, Twine Suffix=Twine(""))
Create a CodeExtractor instance based on the information stored in this structure,...
Information about an OpenMP reduction.
EvalKind EvaluationKind
Reduction evaluation kind - scalar, complex or aggregate.
ReductionGenAtomicCBTy AtomicReductionGen
Callback for generating the atomic reduction body, may be null.
ReductionGenCBTy ReductionGen
Callback for generating the reduction body.
Value * Variable
Reduction variable of pointer type.
Value * PrivateVariable
Thread-private partial reduction variable.
ReductionGenClangCBTy ReductionGenClang
Clang callback for generating the reduction body.
Type * ElementType
Reduction element type, must match pointee type of variable.
ReductionGenDataPtrPtrCBTy DataPtrPtrGen
Container for the arguments used to pass data to the runtime library.
Value * SizesArray
The array of sizes passed to the runtime library.
Value * PointersArray
The array of section pointers passed to the runtime library.
Value * MappersArray
The array of user-defined mappers passed to the runtime library.
Value * MapTypesArrayEnd
The array of map types passed to the runtime library for the end of the region, or nullptr if there a...
Value * BasePointersArray
The array of base pointer passed to the runtime library.
Value * MapTypesArray
The array of map types passed to the runtime library for the beginning of the region or for the entir...
SmallVector< NonContiguousDescriptor, 2 > NonContiguousDescriptors
Descriptors referenced by PointersArray need their own task-private copies when the runtime call is d...
Value * MapNamesArray
The array of original declaration names of mapped pointers sent to the runtime library for debugging.
Data structure that contains the needed information to construct the kernel args vector.
bool StrictBlocks
True if the kernel strictly requires the number of blocks and threads above to run.
ArrayRef< Value * > NumThreads
The number of threads.
TargetDataRTArgs RTArgs
Arguments passed to the runtime library.
Value * NumIterations
The number of iterations.
Value * DynCGroupMem
The size of the dynamic shared memory.
unsigned NumTargetItems
Number of arguments passed to the runtime library.
bool HasNoWait
True if the kernel has 'no wait' clause.
ArrayRef< Value * > NumTeams
The number of teams.
omp::OMPDynGroupprivateFallbackType DynCGroupMemFallback
The fallback mechanism for the shared memory.
Container to pass the default attributes with which a kernel must be launched, used to set kernel att...
Container to pass LLVM IR runtime values or constants related to the number of teams and threads with...
Value * DeviceID
Device ID value used in the kernel launch.
Value * LoopTripCount
Total number of iterations of the SPMD or Generic-SPMD kernel or null if it is a generic kernel.
SmallVector< Value * > MaxThreads
'parallel' construct 'num_threads' clause value, if present and it is an SPMD kernel.
Data structure to contain the information needed to uniquely identify a target entry.
static LLVM_ABI void getTargetRegionEntryFnName(SmallVectorImpl< char > &Name, StringRef ParentName, unsigned DeviceID, unsigned FileID, unsigned Line, unsigned Count)
static constexpr const char * KernelNamePrefix
The prefix used for kernel names.
Defines various target-specific GPU grid values that must be consistent between host RTL (plugin),...