LLVM 18.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
16#include "llvm/ADT/SmallSet.h"
18#include "llvm/ADT/StringRef.h"
27#include "llvm/IR/Attributes.h"
28#include "llvm/IR/BasicBlock.h"
29#include "llvm/IR/CFG.h"
30#include "llvm/IR/CallingConv.h"
31#include "llvm/IR/Constant.h"
32#include "llvm/IR/Constants.h"
35#include "llvm/IR/Function.h"
37#include "llvm/IR/IRBuilder.h"
38#include "llvm/IR/LLVMContext.h"
39#include "llvm/IR/MDBuilder.h"
40#include "llvm/IR/Metadata.h"
41#include "llvm/IR/PassManager.h"
42#include "llvm/IR/Value.h"
54
55#include <cstdint>
56#include <optional>
57
58#define DEBUG_TYPE "openmp-ir-builder"
59
60using namespace llvm;
61using namespace omp;
62
63static cl::opt<bool>
64 OptimisticAttributes("openmp-ir-builder-optimistic-attributes", cl::Hidden,
65 cl::desc("Use optimistic attributes describing "
66 "'as-if' properties of runtime calls."),
67 cl::init(false));
68
70 "openmp-ir-builder-unroll-threshold-factor", cl::Hidden,
71 cl::desc("Factor for the unroll threshold to account for code "
72 "simplifications still taking place"),
73 cl::init(1.5));
74
75#ifndef NDEBUG
76/// Return whether IP1 and IP2 are ambiguous, i.e. that inserting instructions
77/// at position IP1 may change the meaning of IP2 or vice-versa. This is because
78/// an InsertPoint stores the instruction before something is inserted. For
79/// instance, if both point to the same instruction, two IRBuilders alternating
80/// creating instruction will cause the instructions to be interleaved.
83 if (!IP1.isSet() || !IP2.isSet())
84 return false;
85 return IP1.getBlock() == IP2.getBlock() && IP1.getPoint() == IP2.getPoint();
86}
87
89 // Valid ordered/unordered and base algorithm combinations.
90 switch (SchedType & ~OMPScheduleType::MonotonicityMask) {
91 case OMPScheduleType::UnorderedStaticChunked:
92 case OMPScheduleType::UnorderedStatic:
93 case OMPScheduleType::UnorderedDynamicChunked:
94 case OMPScheduleType::UnorderedGuidedChunked:
95 case OMPScheduleType::UnorderedRuntime:
96 case OMPScheduleType::UnorderedAuto:
97 case OMPScheduleType::UnorderedTrapezoidal:
98 case OMPScheduleType::UnorderedGreedy:
99 case OMPScheduleType::UnorderedBalanced:
100 case OMPScheduleType::UnorderedGuidedIterativeChunked:
101 case OMPScheduleType::UnorderedGuidedAnalyticalChunked:
102 case OMPScheduleType::UnorderedSteal:
103 case OMPScheduleType::UnorderedStaticBalancedChunked:
104 case OMPScheduleType::UnorderedGuidedSimd:
105 case OMPScheduleType::UnorderedRuntimeSimd:
106 case OMPScheduleType::OrderedStaticChunked:
107 case OMPScheduleType::OrderedStatic:
108 case OMPScheduleType::OrderedDynamicChunked:
109 case OMPScheduleType::OrderedGuidedChunked:
110 case OMPScheduleType::OrderedRuntime:
111 case OMPScheduleType::OrderedAuto:
112 case OMPScheduleType::OrderdTrapezoidal:
113 case OMPScheduleType::NomergeUnorderedStaticChunked:
114 case OMPScheduleType::NomergeUnorderedStatic:
115 case OMPScheduleType::NomergeUnorderedDynamicChunked:
116 case OMPScheduleType::NomergeUnorderedGuidedChunked:
117 case OMPScheduleType::NomergeUnorderedRuntime:
118 case OMPScheduleType::NomergeUnorderedAuto:
119 case OMPScheduleType::NomergeUnorderedTrapezoidal:
120 case OMPScheduleType::NomergeUnorderedGreedy:
121 case OMPScheduleType::NomergeUnorderedBalanced:
122 case OMPScheduleType::NomergeUnorderedGuidedIterativeChunked:
123 case OMPScheduleType::NomergeUnorderedGuidedAnalyticalChunked:
124 case OMPScheduleType::NomergeUnorderedSteal:
125 case OMPScheduleType::NomergeOrderedStaticChunked:
126 case OMPScheduleType::NomergeOrderedStatic:
127 case OMPScheduleType::NomergeOrderedDynamicChunked:
128 case OMPScheduleType::NomergeOrderedGuidedChunked:
129 case OMPScheduleType::NomergeOrderedRuntime:
130 case OMPScheduleType::NomergeOrderedAuto:
131 case OMPScheduleType::NomergeOrderedTrapezoidal:
132 break;
133 default:
134 return false;
135 }
136
137 // Must not set both monotonicity modifiers at the same time.
138 OMPScheduleType MonotonicityFlags =
139 SchedType & OMPScheduleType::MonotonicityMask;
140 if (MonotonicityFlags == OMPScheduleType::MonotonicityMask)
141 return false;
142
143 return true;
144}
145#endif
146
147/// Determine which scheduling algorithm to use, determined from schedule clause
148/// arguments.
149static OMPScheduleType
150getOpenMPBaseScheduleType(llvm::omp::ScheduleKind ClauseKind, bool HasChunks,
151 bool HasSimdModifier) {
152 // Currently, the default schedule it static.
153 switch (ClauseKind) {
154 case OMP_SCHEDULE_Default:
155 case OMP_SCHEDULE_Static:
156 return HasChunks ? OMPScheduleType::BaseStaticChunked
157 : OMPScheduleType::BaseStatic;
158 case OMP_SCHEDULE_Dynamic:
159 return OMPScheduleType::BaseDynamicChunked;
160 case OMP_SCHEDULE_Guided:
161 return HasSimdModifier ? OMPScheduleType::BaseGuidedSimd
162 : OMPScheduleType::BaseGuidedChunked;
163 case OMP_SCHEDULE_Auto:
165 case OMP_SCHEDULE_Runtime:
166 return HasSimdModifier ? OMPScheduleType::BaseRuntimeSimd
167 : OMPScheduleType::BaseRuntime;
168 }
169 llvm_unreachable("unhandled schedule clause argument");
170}
171
172/// Adds ordering modifier flags to schedule type.
173static OMPScheduleType
175 bool HasOrderedClause) {
176 assert((BaseScheduleType & OMPScheduleType::ModifierMask) ==
177 OMPScheduleType::None &&
178 "Must not have ordering nor monotonicity flags already set");
179
180 OMPScheduleType OrderingModifier = HasOrderedClause
181 ? OMPScheduleType::ModifierOrdered
182 : OMPScheduleType::ModifierUnordered;
183 OMPScheduleType OrderingScheduleType = BaseScheduleType | OrderingModifier;
184
185 // Unsupported combinations
186 if (OrderingScheduleType ==
187 (OMPScheduleType::BaseGuidedSimd | OMPScheduleType::ModifierOrdered))
188 return OMPScheduleType::OrderedGuidedChunked;
189 else if (OrderingScheduleType == (OMPScheduleType::BaseRuntimeSimd |
190 OMPScheduleType::ModifierOrdered))
191 return OMPScheduleType::OrderedRuntime;
192
193 return OrderingScheduleType;
194}
195
196/// Adds monotonicity modifier flags to schedule type.
197static OMPScheduleType
199 bool HasSimdModifier, bool HasMonotonic,
200 bool HasNonmonotonic, bool HasOrderedClause) {
201 assert((ScheduleType & OMPScheduleType::MonotonicityMask) ==
202 OMPScheduleType::None &&
203 "Must not have monotonicity flags already set");
204 assert((!HasMonotonic || !HasNonmonotonic) &&
205 "Monotonic and Nonmonotonic are contradicting each other");
206
207 if (HasMonotonic) {
208 return ScheduleType | OMPScheduleType::ModifierMonotonic;
209 } else if (HasNonmonotonic) {
210 return ScheduleType | OMPScheduleType::ModifierNonmonotonic;
211 } else {
212 // OpenMP 5.1, 2.11.4 Worksharing-Loop Construct, Description.
213 // If the static schedule kind is specified or if the ordered clause is
214 // specified, and if the nonmonotonic modifier is not specified, the
215 // effect is as if the monotonic modifier is specified. Otherwise, unless
216 // the monotonic modifier is specified, the effect is as if the
217 // nonmonotonic modifier is specified.
218 OMPScheduleType BaseScheduleType =
219 ScheduleType & ~OMPScheduleType::ModifierMask;
220 if ((BaseScheduleType == OMPScheduleType::BaseStatic) ||
221 (BaseScheduleType == OMPScheduleType::BaseStaticChunked) ||
222 HasOrderedClause) {
223 // The monotonic is used by default in openmp runtime library, so no need
224 // to set it.
225 return ScheduleType;
226 } else {
227 return ScheduleType | OMPScheduleType::ModifierNonmonotonic;
228 }
229 }
230}
231
232/// Determine the schedule type using schedule and ordering clause arguments.
233static OMPScheduleType
234computeOpenMPScheduleType(ScheduleKind ClauseKind, bool HasChunks,
235 bool HasSimdModifier, bool HasMonotonicModifier,
236 bool HasNonmonotonicModifier, bool HasOrderedClause) {
237 OMPScheduleType BaseSchedule =
238 getOpenMPBaseScheduleType(ClauseKind, HasChunks, HasSimdModifier);
239 OMPScheduleType OrderedSchedule =
240 getOpenMPOrderingScheduleType(BaseSchedule, HasOrderedClause);
242 OrderedSchedule, HasSimdModifier, HasMonotonicModifier,
243 HasNonmonotonicModifier, HasOrderedClause);
244
246 return Result;
247}
248
249/// Make \p Source branch to \p Target.
250///
251/// Handles two situations:
252/// * \p Source already has an unconditional branch.
253/// * \p Source is a degenerate block (no terminator because the BB is
254/// the current head of the IR construction).
256 if (Instruction *Term = Source->getTerminator()) {
257 auto *Br = cast<BranchInst>(Term);
258 assert(!Br->isConditional() &&
259 "BB's terminator must be an unconditional branch (or degenerate)");
260 BasicBlock *Succ = Br->getSuccessor(0);
261 Succ->removePredecessor(Source, /*KeepOneInputPHIs=*/true);
262 Br->setSuccessor(0, Target);
263 return;
264 }
265
266 auto *NewBr = BranchInst::Create(Target, Source);
267 NewBr->setDebugLoc(DL);
268}
269
271 bool CreateBranch) {
272 assert(New->getFirstInsertionPt() == New->begin() &&
273 "Target BB must not have PHI nodes");
274
275 // Move instructions to new block.
276 BasicBlock *Old = IP.getBlock();
277 New->splice(New->begin(), Old, IP.getPoint(), Old->end());
278
279 if (CreateBranch)
280 BranchInst::Create(New, Old);
281}
282
283void llvm::spliceBB(IRBuilder<> &Builder, BasicBlock *New, bool CreateBranch) {
284 DebugLoc DebugLoc = Builder.getCurrentDebugLocation();
285 BasicBlock *Old = Builder.GetInsertBlock();
286
287 spliceBB(Builder.saveIP(), New, CreateBranch);
288 if (CreateBranch)
289 Builder.SetInsertPoint(Old->getTerminator());
290 else
291 Builder.SetInsertPoint(Old);
292
293 // SetInsertPoint also updates the Builder's debug location, but we want to
294 // keep the one the Builder was configured to use.
295 Builder.SetCurrentDebugLocation(DebugLoc);
296}
297
300 BasicBlock *Old = IP.getBlock();
302 Old->getContext(), Name.isTriviallyEmpty() ? Old->getName() : Name,
303 Old->getParent(), Old->getNextNode());
304 spliceBB(IP, New, CreateBranch);
305 New->replaceSuccessorsPhiUsesWith(Old, New);
306 return New;
307}
308
309BasicBlock *llvm::splitBB(IRBuilderBase &Builder, bool CreateBranch,
311 DebugLoc DebugLoc = Builder.getCurrentDebugLocation();
312 BasicBlock *New = splitBB(Builder.saveIP(), CreateBranch, Name);
313 if (CreateBranch)
314 Builder.SetInsertPoint(Builder.GetInsertBlock()->getTerminator());
315 else
316 Builder.SetInsertPoint(Builder.GetInsertBlock());
317 // SetInsertPoint also updates the Builder's debug location, but we want to
318 // keep the one the Builder was configured to use.
319 Builder.SetCurrentDebugLocation(DebugLoc);
320 return New;
321}
322
323BasicBlock *llvm::splitBB(IRBuilder<> &Builder, bool CreateBranch,
325 DebugLoc DebugLoc = Builder.getCurrentDebugLocation();
326 BasicBlock *New = splitBB(Builder.saveIP(), CreateBranch, Name);
327 if (CreateBranch)
328 Builder.SetInsertPoint(Builder.GetInsertBlock()->getTerminator());
329 else
330 Builder.SetInsertPoint(Builder.GetInsertBlock());
331 // SetInsertPoint also updates the Builder's debug location, but we want to
332 // keep the one the Builder was configured to use.
333 Builder.SetCurrentDebugLocation(DebugLoc);
334 return New;
335}
336
338 llvm::Twine Suffix) {
339 BasicBlock *Old = Builder.GetInsertBlock();
340 return splitBB(Builder, CreateBranch, Old->getName() + Suffix);
341}
342
343//===----------------------------------------------------------------------===//
344// OpenMPIRBuilderConfig
345//===----------------------------------------------------------------------===//
346
347namespace {
349/// Values for bit flags for marking which requires clauses have been used.
350enum OpenMPOffloadingRequiresDirFlags {
351 /// flag undefined.
352 OMP_REQ_UNDEFINED = 0x000,
353 /// no requires directive present.
354 OMP_REQ_NONE = 0x001,
355 /// reverse_offload clause.
356 OMP_REQ_REVERSE_OFFLOAD = 0x002,
357 /// unified_address clause.
358 OMP_REQ_UNIFIED_ADDRESS = 0x004,
359 /// unified_shared_memory clause.
360 OMP_REQ_UNIFIED_SHARED_MEMORY = 0x008,
361 /// dynamic_allocators clause.
362 OMP_REQ_DYNAMIC_ALLOCATORS = 0x010,
363 LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/OMP_REQ_DYNAMIC_ALLOCATORS)
364};
365
366} // anonymous namespace
367
369 : RequiresFlags(OMP_REQ_UNDEFINED) {}
370
372 bool IsTargetDevice, bool IsGPU, bool OpenMPOffloadMandatory,
373 bool HasRequiresReverseOffload, bool HasRequiresUnifiedAddress,
374 bool HasRequiresUnifiedSharedMemory, bool HasRequiresDynamicAllocators)
375 : IsTargetDevice(IsTargetDevice), IsGPU(IsGPU),
376 OpenMPOffloadMandatory(OpenMPOffloadMandatory),
377 RequiresFlags(OMP_REQ_UNDEFINED) {
378 if (HasRequiresReverseOffload)
379 RequiresFlags |= OMP_REQ_REVERSE_OFFLOAD;
380 if (HasRequiresUnifiedAddress)
381 RequiresFlags |= OMP_REQ_UNIFIED_ADDRESS;
382 if (HasRequiresUnifiedSharedMemory)
383 RequiresFlags |= OMP_REQ_UNIFIED_SHARED_MEMORY;
384 if (HasRequiresDynamicAllocators)
385 RequiresFlags |= OMP_REQ_DYNAMIC_ALLOCATORS;
386}
387
389 return RequiresFlags & OMP_REQ_REVERSE_OFFLOAD;
390}
391
393 return RequiresFlags & OMP_REQ_UNIFIED_ADDRESS;
394}
395
397 return RequiresFlags & OMP_REQ_UNIFIED_SHARED_MEMORY;
398}
399
401 return RequiresFlags & OMP_REQ_DYNAMIC_ALLOCATORS;
402}
403
405 return hasRequiresFlags() ? RequiresFlags
406 : static_cast<int64_t>(OMP_REQ_NONE);
407}
408
410 if (Value)
411 RequiresFlags |= OMP_REQ_REVERSE_OFFLOAD;
412 else
413 RequiresFlags &= ~OMP_REQ_REVERSE_OFFLOAD;
414}
415
417 if (Value)
418 RequiresFlags |= OMP_REQ_UNIFIED_ADDRESS;
419 else
420 RequiresFlags &= ~OMP_REQ_UNIFIED_ADDRESS;
421}
422
424 if (Value)
425 RequiresFlags |= OMP_REQ_UNIFIED_SHARED_MEMORY;
426 else
427 RequiresFlags &= ~OMP_REQ_UNIFIED_SHARED_MEMORY;
428}
429
431 if (Value)
432 RequiresFlags |= OMP_REQ_DYNAMIC_ALLOCATORS;
433 else
434 RequiresFlags &= ~OMP_REQ_DYNAMIC_ALLOCATORS;
435}
436
437//===----------------------------------------------------------------------===//
438// OpenMPIRBuilder
439//===----------------------------------------------------------------------===//
440
442 IRBuilderBase &Builder,
443 SmallVector<Value *> &ArgsVector) {
445 Value *PointerNum = Builder.getInt32(KernelArgs.NumTargetItems);
448 Value *Flags = Builder.getInt64(KernelArgs.HasNoWait);
449
450 Value *NumTeams3D =
451 Builder.CreateInsertValue(ZeroArray, KernelArgs.NumTeams, {0});
452 Value *NumThreads3D =
453 Builder.CreateInsertValue(ZeroArray, KernelArgs.NumThreads, {0});
454
455 ArgsVector = {Version,
456 PointerNum,
457 KernelArgs.RTArgs.BasePointersArray,
458 KernelArgs.RTArgs.PointersArray,
459 KernelArgs.RTArgs.SizesArray,
460 KernelArgs.RTArgs.MapTypesArray,
461 KernelArgs.RTArgs.MapNamesArray,
462 KernelArgs.RTArgs.MappersArray,
463 KernelArgs.NumIterations,
464 Flags,
465 NumTeams3D,
466 NumThreads3D,
467 KernelArgs.DynCGGroupMem};
468}
469
471 LLVMContext &Ctx = Fn.getContext();
473
474 // Get the function's current attributes.
475 auto Attrs = Fn.getAttributes();
476 auto FnAttrs = Attrs.getFnAttrs();
477 auto RetAttrs = Attrs.getRetAttrs();
479 for (size_t ArgNo = 0; ArgNo < Fn.arg_size(); ++ArgNo)
480 ArgAttrs.emplace_back(Attrs.getParamAttrs(ArgNo));
481
482 // Add AS to FnAS while taking special care with integer extensions.
483 auto addAttrSet = [&](AttributeSet &FnAS, const AttributeSet &AS,
484 bool Param = true) -> void {
485 bool HasSignExt = AS.hasAttribute(Attribute::SExt);
486 bool HasZeroExt = AS.hasAttribute(Attribute::ZExt);
487 if (HasSignExt || HasZeroExt) {
488 assert(AS.getNumAttributes() == 1 &&
489 "Currently not handling extension attr combined with others.");
490 if (Param) {
491 if (auto AK = TargetLibraryInfo::getExtAttrForI32Param(T, HasSignExt))
492 FnAS = FnAS.addAttribute(Ctx, AK);
493 } else if (auto AK =
494 TargetLibraryInfo::getExtAttrForI32Return(T, HasSignExt))
495 FnAS = FnAS.addAttribute(Ctx, AK);
496 } else {
497 FnAS = FnAS.addAttributes(Ctx, AS);
498 }
499 };
500
501#define OMP_ATTRS_SET(VarName, AttrSet) AttributeSet VarName = AttrSet;
502#include "llvm/Frontend/OpenMP/OMPKinds.def"
503
504 // Add attributes to the function declaration.
505 switch (FnID) {
506#define OMP_RTL_ATTRS(Enum, FnAttrSet, RetAttrSet, ArgAttrSets) \
507 case Enum: \
508 FnAttrs = FnAttrs.addAttributes(Ctx, FnAttrSet); \
509 addAttrSet(RetAttrs, RetAttrSet, /*Param*/ false); \
510 for (size_t ArgNo = 0; ArgNo < ArgAttrSets.size(); ++ArgNo) \
511 addAttrSet(ArgAttrs[ArgNo], ArgAttrSets[ArgNo]); \
512 Fn.setAttributes(AttributeList::get(Ctx, FnAttrs, RetAttrs, ArgAttrs)); \
513 break;
514#include "llvm/Frontend/OpenMP/OMPKinds.def"
515 default:
516 // Attributes are optional.
517 break;
518 }
519}
520
523 FunctionType *FnTy = nullptr;
524 Function *Fn = nullptr;
525
526 // Try to find the declation in the module first.
527 switch (FnID) {
528#define OMP_RTL(Enum, Str, IsVarArg, ReturnType, ...) \
529 case Enum: \
530 FnTy = FunctionType::get(ReturnType, ArrayRef<Type *>{__VA_ARGS__}, \
531 IsVarArg); \
532 Fn = M.getFunction(Str); \
533 break;
534#include "llvm/Frontend/OpenMP/OMPKinds.def"
535 }
536
537 if (!Fn) {
538 // Create a new declaration if we need one.
539 switch (FnID) {
540#define OMP_RTL(Enum, Str, ...) \
541 case Enum: \
542 Fn = Function::Create(FnTy, GlobalValue::ExternalLinkage, Str, M); \
543 break;
544#include "llvm/Frontend/OpenMP/OMPKinds.def"
545 }
546
547 // Add information if the runtime function takes a callback function
548 if (FnID == OMPRTL___kmpc_fork_call || FnID == OMPRTL___kmpc_fork_teams) {
549 if (!Fn->hasMetadata(LLVMContext::MD_callback)) {
550 LLVMContext &Ctx = Fn->getContext();
551 MDBuilder MDB(Ctx);
552 // Annotate the callback behavior of the runtime function:
553 // - The callback callee is argument number 2 (microtask).
554 // - The first two arguments of the callback callee are unknown (-1).
555 // - All variadic arguments to the runtime function are passed to the
556 // callback callee.
557 Fn->addMetadata(
558 LLVMContext::MD_callback,
560 2, {-1, -1}, /* VarArgsArePassed */ true)}));
561 }
562 }
563
564 LLVM_DEBUG(dbgs() << "Created OpenMP runtime function " << Fn->getName()
565 << " with type " << *Fn->getFunctionType() << "\n");
566 addAttributes(FnID, *Fn);
567
568 } else {
569 LLVM_DEBUG(dbgs() << "Found OpenMP runtime function " << Fn->getName()
570 << " with type " << *Fn->getFunctionType() << "\n");
571 }
572
573 assert(Fn && "Failed to create OpenMP runtime function");
574
575 return {FnTy, Fn};
576}
577
580 auto *Fn = dyn_cast<llvm::Function>(RTLFn.getCallee());
581 assert(Fn && "Failed to create OpenMP runtime function pointer");
582 return Fn;
583}
584
585void OpenMPIRBuilder::initialize() { initializeTypes(M); }
586
588 SmallPtrSet<BasicBlock *, 32> ParallelRegionBlockSet;
590 SmallVector<OutlineInfo, 16> DeferredOutlines;
591 for (OutlineInfo &OI : OutlineInfos) {
592 // Skip functions that have not finalized yet; may happen with nested
593 // function generation.
594 if (Fn && OI.getFunction() != Fn) {
595 DeferredOutlines.push_back(OI);
596 continue;
597 }
598
599 ParallelRegionBlockSet.clear();
600 Blocks.clear();
601 OI.collectBlocks(ParallelRegionBlockSet, Blocks);
602
603 Function *OuterFn = OI.getFunction();
604 CodeExtractorAnalysisCache CEAC(*OuterFn);
605 CodeExtractor Extractor(Blocks, /* DominatorTree */ nullptr,
606 /* AggregateArgs */ true,
607 /* BlockFrequencyInfo */ nullptr,
608 /* BranchProbabilityInfo */ nullptr,
609 /* AssumptionCache */ nullptr,
610 /* AllowVarArgs */ true,
611 /* AllowAlloca */ true,
612 /* AllocaBlock*/ OI.OuterAllocaBB,
613 /* Suffix */ ".omp_par");
614
615 LLVM_DEBUG(dbgs() << "Before outlining: " << *OuterFn << "\n");
616 LLVM_DEBUG(dbgs() << "Entry " << OI.EntryBB->getName()
617 << " Exit: " << OI.ExitBB->getName() << "\n");
618 assert(Extractor.isEligible() &&
619 "Expected OpenMP outlining to be possible!");
620
621 for (auto *V : OI.ExcludeArgsFromAggregate)
622 Extractor.excludeArgFromAggregate(V);
623
624 Function *OutlinedFn = Extractor.extractCodeRegion(CEAC);
625
626 LLVM_DEBUG(dbgs() << "After outlining: " << *OuterFn << "\n");
627 LLVM_DEBUG(dbgs() << " Outlined function: " << *OutlinedFn << "\n");
628 assert(OutlinedFn->getReturnType()->isVoidTy() &&
629 "OpenMP outlined functions should not return a value!");
630
631 // For compability with the clang CG we move the outlined function after the
632 // one with the parallel region.
633 OutlinedFn->removeFromParent();
634 M.getFunctionList().insertAfter(OuterFn->getIterator(), OutlinedFn);
635
636 // Remove the artificial entry introduced by the extractor right away, we
637 // made our own entry block after all.
638 {
639 BasicBlock &ArtificialEntry = OutlinedFn->getEntryBlock();
640 assert(ArtificialEntry.getUniqueSuccessor() == OI.EntryBB);
641 assert(OI.EntryBB->getUniquePredecessor() == &ArtificialEntry);
642 // Move instructions from the to-be-deleted ArtificialEntry to the entry
643 // basic block of the parallel region. CodeExtractor generates
644 // instructions to unwrap the aggregate argument and may sink
645 // allocas/bitcasts for values that are solely used in the outlined region
646 // and do not escape.
647 assert(!ArtificialEntry.empty() &&
648 "Expected instructions to add in the outlined region entry");
649 for (BasicBlock::reverse_iterator It = ArtificialEntry.rbegin(),
650 End = ArtificialEntry.rend();
651 It != End;) {
652 Instruction &I = *It;
653 It++;
654
655 if (I.isTerminator())
656 continue;
657
658 I.moveBeforePreserving(*OI.EntryBB, OI.EntryBB->getFirstInsertionPt());
659 }
660
661 OI.EntryBB->moveBefore(&ArtificialEntry);
662 ArtificialEntry.eraseFromParent();
663 }
664 assert(&OutlinedFn->getEntryBlock() == OI.EntryBB);
665 assert(OutlinedFn && OutlinedFn->getNumUses() == 1);
666
667 // Run a user callback, e.g. to add attributes.
668 if (OI.PostOutlineCB)
669 OI.PostOutlineCB(*OutlinedFn);
670 }
671
672 // Remove work items that have been completed.
673 OutlineInfos = std::move(DeferredOutlines);
674
675 EmitMetadataErrorReportFunctionTy &&ErrorReportFn =
676 [](EmitMetadataErrorKind Kind,
677 const TargetRegionEntryInfo &EntryInfo) -> void {
678 errs() << "Error of kind: " << Kind
679 << " when emitting offload entries and metadata during "
680 "OMPIRBuilder finalization \n";
681 };
682
685}
686
688 assert(OutlineInfos.empty() && "There must be no outstanding outlinings");
689}
690
693 auto *GV =
694 new GlobalVariable(M, I32Ty,
695 /* isConstant = */ true, GlobalValue::WeakODRLinkage,
696 ConstantInt::get(I32Ty, Value), Name);
697 GV->setVisibility(GlobalValue::HiddenVisibility);
698
699 return GV;
700}
701
703 uint32_t SrcLocStrSize,
704 IdentFlag LocFlags,
705 unsigned Reserve2Flags) {
706 // Enable "C-mode".
707 LocFlags |= OMP_IDENT_FLAG_KMPC;
708
709 Constant *&Ident =
710 IdentMap[{SrcLocStr, uint64_t(LocFlags) << 31 | Reserve2Flags}];
711 if (!Ident) {
713 Constant *IdentData[] = {I32Null,
714 ConstantInt::get(Int32, uint32_t(LocFlags)),
715 ConstantInt::get(Int32, Reserve2Flags),
716 ConstantInt::get(Int32, SrcLocStrSize), SrcLocStr};
717 Constant *Initializer =
718 ConstantStruct::get(OpenMPIRBuilder::Ident, IdentData);
719
720 // Look for existing encoding of the location + flags, not needed but
721 // minimizes the difference to the existing solution while we transition.
722 for (GlobalVariable &GV : M.globals())
723 if (GV.getValueType() == OpenMPIRBuilder::Ident && GV.hasInitializer())
724 if (GV.getInitializer() == Initializer)
725 Ident = &GV;
726
727 if (!Ident) {
728 auto *GV = new GlobalVariable(
729 M, OpenMPIRBuilder::Ident,
730 /* isConstant = */ true, GlobalValue::PrivateLinkage, Initializer, "",
733 GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
734 GV->setAlignment(Align(8));
735 Ident = GV;
736 }
737 }
738
740}
741
743 uint32_t &SrcLocStrSize) {
744 SrcLocStrSize = LocStr.size();
745 Constant *&SrcLocStr = SrcLocStrMap[LocStr];
746 if (!SrcLocStr) {
747 Constant *Initializer =
749
750 // Look for existing encoding of the location, not needed but minimizes the
751 // difference to the existing solution while we transition.
752 for (GlobalVariable &GV : M.globals())
753 if (GV.isConstant() && GV.hasInitializer() &&
754 GV.getInitializer() == Initializer)
755 return SrcLocStr = ConstantExpr::getPointerCast(&GV, Int8Ptr);
756
757 SrcLocStr = Builder.CreateGlobalStringPtr(LocStr, /* Name */ "",
758 /* AddressSpace */ 0, &M);
759 }
760 return SrcLocStr;
761}
762
764 StringRef FileName,
765 unsigned Line, unsigned Column,
766 uint32_t &SrcLocStrSize) {
767 SmallString<128> Buffer;
768 Buffer.push_back(';');
769 Buffer.append(FileName);
770 Buffer.push_back(';');
771 Buffer.append(FunctionName);
772 Buffer.push_back(';');
773 Buffer.append(std::to_string(Line));
774 Buffer.push_back(';');
775 Buffer.append(std::to_string(Column));
776 Buffer.push_back(';');
777 Buffer.push_back(';');
778 return getOrCreateSrcLocStr(Buffer.str(), SrcLocStrSize);
779}
780
781Constant *
783 StringRef UnknownLoc = ";unknown;unknown;0;0;;";
784 return getOrCreateSrcLocStr(UnknownLoc, SrcLocStrSize);
785}
786
788 uint32_t &SrcLocStrSize,
789 Function *F) {
790 DILocation *DIL = DL.get();
791 if (!DIL)
792 return getOrCreateDefaultSrcLocStr(SrcLocStrSize);
793 StringRef FileName = M.getName();
794 if (DIFile *DIF = DIL->getFile())
795 if (std::optional<StringRef> Source = DIF->getSource())
796 FileName = *Source;
797 StringRef Function = DIL->getScope()->getSubprogram()->getName();
798 if (Function.empty() && F)
799 Function = F->getName();
800 return getOrCreateSrcLocStr(Function, FileName, DIL->getLine(),
801 DIL->getColumn(), SrcLocStrSize);
802}
803
805 uint32_t &SrcLocStrSize) {
806 return getOrCreateSrcLocStr(Loc.DL, SrcLocStrSize,
807 Loc.IP.getBlock()->getParent());
808}
809
811 return Builder.CreateCall(
812 getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_global_thread_num), Ident,
813 "omp_global_thread_num");
814}
815
818 bool ForceSimpleCall, bool CheckCancelFlag) {
819 if (!updateToLocation(Loc))
820 return Loc.IP;
821 return emitBarrierImpl(Loc, DK, ForceSimpleCall, CheckCancelFlag);
822}
823
826 bool ForceSimpleCall, bool CheckCancelFlag) {
827 // Build call __kmpc_cancel_barrier(loc, thread_id) or
828 // __kmpc_barrier(loc, thread_id);
829
830 IdentFlag BarrierLocFlags;
831 switch (Kind) {
832 case OMPD_for:
833 BarrierLocFlags = OMP_IDENT_FLAG_BARRIER_IMPL_FOR;
834 break;
835 case OMPD_sections:
836 BarrierLocFlags = OMP_IDENT_FLAG_BARRIER_IMPL_SECTIONS;
837 break;
838 case OMPD_single:
839 BarrierLocFlags = OMP_IDENT_FLAG_BARRIER_IMPL_SINGLE;
840 break;
841 case OMPD_barrier:
842 BarrierLocFlags = OMP_IDENT_FLAG_BARRIER_EXPL;
843 break;
844 default:
845 BarrierLocFlags = OMP_IDENT_FLAG_BARRIER_IMPL;
846 break;
847 }
848
849 uint32_t SrcLocStrSize;
850 Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
851 Value *Args[] = {
852 getOrCreateIdent(SrcLocStr, SrcLocStrSize, BarrierLocFlags),
853 getOrCreateThreadID(getOrCreateIdent(SrcLocStr, SrcLocStrSize))};
854
855 // If we are in a cancellable parallel region, barriers are cancellation
856 // points.
857 // TODO: Check why we would force simple calls or to ignore the cancel flag.
858 bool UseCancelBarrier =
859 !ForceSimpleCall && isLastFinalizationInfoCancellable(OMPD_parallel);
860
861 Value *Result =
863 UseCancelBarrier ? OMPRTL___kmpc_cancel_barrier
864 : OMPRTL___kmpc_barrier),
865 Args);
866
867 if (UseCancelBarrier && CheckCancelFlag)
868 emitCancelationCheckImpl(Result, OMPD_parallel);
869
870 return Builder.saveIP();
871}
872
875 Value *IfCondition,
876 omp::Directive CanceledDirective) {
877 if (!updateToLocation(Loc))
878 return Loc.IP;
879
880 // LLVM utilities like blocks with terminators.
881 auto *UI = Builder.CreateUnreachable();
882
883 Instruction *ThenTI = UI, *ElseTI = nullptr;
884 if (IfCondition)
885 SplitBlockAndInsertIfThenElse(IfCondition, UI, &ThenTI, &ElseTI);
886 Builder.SetInsertPoint(ThenTI);
887
888 Value *CancelKind = nullptr;
889 switch (CanceledDirective) {
890#define OMP_CANCEL_KIND(Enum, Str, DirectiveEnum, Value) \
891 case DirectiveEnum: \
892 CancelKind = Builder.getInt32(Value); \
893 break;
894#include "llvm/Frontend/OpenMP/OMPKinds.def"
895 default:
896 llvm_unreachable("Unknown cancel kind!");
897 }
898
899 uint32_t SrcLocStrSize;
900 Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
901 Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
902 Value *Args[] = {Ident, getOrCreateThreadID(Ident), CancelKind};
903 Value *Result = Builder.CreateCall(
904 getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_cancel), Args);
905 auto ExitCB = [this, CanceledDirective, Loc](InsertPointTy IP) {
906 if (CanceledDirective == OMPD_parallel) {
908 Builder.restoreIP(IP);
910 omp::Directive::OMPD_unknown, /* ForceSimpleCall */ false,
911 /* CheckCancelFlag */ false);
912 }
913 };
914
915 // The actual cancel logic is shared with others, e.g., cancel_barriers.
916 emitCancelationCheckImpl(Result, CanceledDirective, ExitCB);
917
918 // Update the insertion point and remove the terminator we introduced.
919 Builder.SetInsertPoint(UI->getParent());
920 UI->eraseFromParent();
921
922 return Builder.saveIP();
923}
924
926 uint64_t Size, int32_t Flags,
928 Type *Int8PtrTy = Type::getInt8PtrTy(M.getContext());
931
933
934 // Create the constant string used to look up the symbol in the device.
935 auto *Str =
936 new llvm::GlobalVariable(M, AddrName->getType(), /*isConstant=*/true,
938 ".omp_offloading.entry_name");
939 Str->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
940
941 // Construct the offloading entry.
942 Constant *EntryData[] = {
945 ConstantInt::get(SizeTy, Size),
948 };
949 Constant *EntryInitializer =
950 ConstantStruct::get(OpenMPIRBuilder::OffloadEntry, EntryData);
951
952 auto *Entry = new GlobalVariable(
953 M, OpenMPIRBuilder::OffloadEntry,
954 /* isConstant = */ true, GlobalValue::WeakAnyLinkage, EntryInitializer,
955 ".omp_offloading.entry." + Name, nullptr, GlobalValue::NotThreadLocal,
957
958 // The entry has to be created in the section the linker expects it to be.
959 Entry->setSection(SectionName);
960 Entry->setAlignment(Align(1));
961}
962
964 const LocationDescription &Loc, InsertPointTy AllocaIP, Value *&Return,
965 Value *Ident, Value *DeviceID, Value *NumTeams, Value *NumThreads,
966 Value *HostPtr, ArrayRef<Value *> KernelArgs) {
967 if (!updateToLocation(Loc))
968 return Loc.IP;
969
970 Builder.restoreIP(AllocaIP);
971 auto *KernelArgsPtr =
972 Builder.CreateAlloca(OpenMPIRBuilder::KernelArgs, nullptr, "kernel_args");
973 Builder.restoreIP(Loc.IP);
974
975 for (unsigned I = 0, Size = KernelArgs.size(); I != Size; ++I) {
976 llvm::Value *Arg =
977 Builder.CreateStructGEP(OpenMPIRBuilder::KernelArgs, KernelArgsPtr, I);
979 KernelArgs[I], Arg,
980 M.getDataLayout().getPrefTypeAlign(KernelArgs[I]->getType()));
981 }
982
983 SmallVector<Value *> OffloadingArgs{Ident, DeviceID, NumTeams,
984 NumThreads, HostPtr, KernelArgsPtr};
985
986 Return = Builder.CreateCall(
987 getOrCreateRuntimeFunction(M, OMPRTL___tgt_target_kernel),
988 OffloadingArgs);
989
990 return Builder.saveIP();
991}
992
994 const LocationDescription &Loc, Function *OutlinedFn, Value *OutlinedFnID,
995 EmitFallbackCallbackTy emitTargetCallFallbackCB, TargetKernelArgs &Args,
996 Value *DeviceID, Value *RTLoc, InsertPointTy AllocaIP) {
997
998 if (!updateToLocation(Loc))
999 return Loc.IP;
1000
1001 Builder.restoreIP(Loc.IP);
1002 // On top of the arrays that were filled up, the target offloading call
1003 // takes as arguments the device id as well as the host pointer. The host
1004 // pointer is used by the runtime library to identify the current target
1005 // region, so it only has to be unique and not necessarily point to
1006 // anything. It could be the pointer to the outlined function that
1007 // implements the target region, but we aren't using that so that the
1008 // compiler doesn't need to keep that, and could therefore inline the host
1009 // function if proven worthwhile during optimization.
1010
1011 // From this point on, we need to have an ID of the target region defined.
1012 assert(OutlinedFnID && "Invalid outlined function ID!");
1013 (void)OutlinedFnID;
1014
1015 // Return value of the runtime offloading call.
1016 Value *Return = nullptr;
1017
1018 // Arguments for the target kernel.
1019 SmallVector<Value *> ArgsVector;
1020 getKernelArgsVector(Args, Builder, ArgsVector);
1021
1022 // The target region is an outlined function launched by the runtime
1023 // via calls to __tgt_target_kernel().
1024 //
1025 // Note that on the host and CPU targets, the runtime implementation of
1026 // these calls simply call the outlined function without forking threads.
1027 // The outlined functions themselves have runtime calls to
1028 // __kmpc_fork_teams() and __kmpc_fork() for this purpose, codegen'd by
1029 // the compiler in emitTeamsCall() and emitParallelCall().
1030 //
1031 // In contrast, on the NVPTX target, the implementation of
1032 // __tgt_target_teams() launches a GPU kernel with the requested number
1033 // of teams and threads so no additional calls to the runtime are required.
1034 // Check the error code and execute the host version if required.
1035 Builder.restoreIP(emitTargetKernel(Builder, AllocaIP, Return, RTLoc, DeviceID,
1036 Args.NumTeams, Args.NumThreads,
1037 OutlinedFnID, ArgsVector));
1038
1039 BasicBlock *OffloadFailedBlock =
1040 BasicBlock::Create(Builder.getContext(), "omp_offload.failed");
1041 BasicBlock *OffloadContBlock =
1042 BasicBlock::Create(Builder.getContext(), "omp_offload.cont");
1044 Builder.CreateCondBr(Failed, OffloadFailedBlock, OffloadContBlock);
1045
1046 auto CurFn = Builder.GetInsertBlock()->getParent();
1047 emitBlock(OffloadFailedBlock, CurFn);
1048 Builder.restoreIP(emitTargetCallFallbackCB(Builder.saveIP()));
1049 emitBranch(OffloadContBlock);
1050 emitBlock(OffloadContBlock, CurFn, /*IsFinished=*/true);
1051 return Builder.saveIP();
1052}
1053
1055 omp::Directive CanceledDirective,
1056 FinalizeCallbackTy ExitCB) {
1057 assert(isLastFinalizationInfoCancellable(CanceledDirective) &&
1058 "Unexpected cancellation!");
1059
1060 // For a cancel barrier we create two new blocks.
1062 BasicBlock *NonCancellationBlock;
1063 if (Builder.GetInsertPoint() == BB->end()) {
1064 // TODO: This branch will not be needed once we moved to the
1065 // OpenMPIRBuilder codegen completely.
1066 NonCancellationBlock = BasicBlock::Create(
1067 BB->getContext(), BB->getName() + ".cont", BB->getParent());
1068 } else {
1069 NonCancellationBlock = SplitBlock(BB, &*Builder.GetInsertPoint());
1072 }
1073 BasicBlock *CancellationBlock = BasicBlock::Create(
1074 BB->getContext(), BB->getName() + ".cncl", BB->getParent());
1075
1076 // Jump to them based on the return value.
1077 Value *Cmp = Builder.CreateIsNull(CancelFlag);
1078 Builder.CreateCondBr(Cmp, NonCancellationBlock, CancellationBlock,
1079 /* TODO weight */ nullptr, nullptr);
1080
1081 // From the cancellation block we finalize all variables and go to the
1082 // post finalization block that is known to the FiniCB callback.
1083 Builder.SetInsertPoint(CancellationBlock);
1084 if (ExitCB)
1085 ExitCB(Builder.saveIP());
1086 auto &FI = FinalizationStack.back();
1087 FI.FiniCB(Builder.saveIP());
1088
1089 // The continuation block is where code generation continues.
1090 Builder.SetInsertPoint(NonCancellationBlock, NonCancellationBlock->begin());
1091}
1092
1094 const LocationDescription &Loc, InsertPointTy OuterAllocaIP,
1095 BodyGenCallbackTy BodyGenCB, PrivatizeCallbackTy PrivCB,
1096 FinalizeCallbackTy FiniCB, Value *IfCondition, Value *NumThreads,
1097 omp::ProcBindKind ProcBind, bool IsCancellable) {
1098 assert(!isConflictIP(Loc.IP, OuterAllocaIP) && "IPs must not be ambiguous");
1099
1100 if (!updateToLocation(Loc))
1101 return Loc.IP;
1102
1103 uint32_t SrcLocStrSize;
1104 Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
1105 Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
1106 Value *ThreadID = getOrCreateThreadID(Ident);
1107
1108 if (NumThreads) {
1109 // Build call __kmpc_push_num_threads(&Ident, global_tid, num_threads)
1110 Value *Args[] = {
1111 Ident, ThreadID,
1112 Builder.CreateIntCast(NumThreads, Int32, /*isSigned*/ false)};
1114 getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_push_num_threads), Args);
1115 }
1116
1117 if (ProcBind != OMP_PROC_BIND_default) {
1118 // Build call __kmpc_push_proc_bind(&Ident, global_tid, proc_bind)
1119 Value *Args[] = {
1120 Ident, ThreadID,
1121 ConstantInt::get(Int32, unsigned(ProcBind), /*isSigned=*/true)};
1123 getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_push_proc_bind), Args);
1124 }
1125
1126 BasicBlock *InsertBB = Builder.GetInsertBlock();
1127 Function *OuterFn = InsertBB->getParent();
1128
1129 // Save the outer alloca block because the insertion iterator may get
1130 // invalidated and we still need this later.
1131 BasicBlock *OuterAllocaBlock = OuterAllocaIP.getBlock();
1132
1133 // Vector to remember instructions we used only during the modeling but which
1134 // we want to delete at the end.
1136
1137 // Change the location to the outer alloca insertion point to create and
1138 // initialize the allocas we pass into the parallel region.
1139 Builder.restoreIP(OuterAllocaIP);
1140 AllocaInst *TIDAddr = Builder.CreateAlloca(Int32, nullptr, "tid.addr");
1141 AllocaInst *ZeroAddr = Builder.CreateAlloca(Int32, nullptr, "zero.addr");
1142
1143 // We only need TIDAddr and ZeroAddr for modeling purposes to get the
1144 // associated arguments in the outlined function, so we delete them later.
1145 ToBeDeleted.push_back(TIDAddr);
1146 ToBeDeleted.push_back(ZeroAddr);
1147
1148 // Create an artificial insertion point that will also ensure the blocks we
1149 // are about to split are not degenerated.
1150 auto *UI = new UnreachableInst(Builder.getContext(), InsertBB);
1151
1152 BasicBlock *EntryBB = UI->getParent();
1153 BasicBlock *PRegEntryBB = EntryBB->splitBasicBlock(UI, "omp.par.entry");
1154 BasicBlock *PRegBodyBB = PRegEntryBB->splitBasicBlock(UI, "omp.par.region");
1155 BasicBlock *PRegPreFiniBB =
1156 PRegBodyBB->splitBasicBlock(UI, "omp.par.pre_finalize");
1157 BasicBlock *PRegExitBB = PRegPreFiniBB->splitBasicBlock(UI, "omp.par.exit");
1158
1159 auto FiniCBWrapper = [&](InsertPointTy IP) {
1160 // Hide "open-ended" blocks from the given FiniCB by setting the right jump
1161 // target to the region exit block.
1162 if (IP.getBlock()->end() == IP.getPoint()) {
1164 Builder.restoreIP(IP);
1165 Instruction *I = Builder.CreateBr(PRegExitBB);
1166 IP = InsertPointTy(I->getParent(), I->getIterator());
1167 }
1168 assert(IP.getBlock()->getTerminator()->getNumSuccessors() == 1 &&
1169 IP.getBlock()->getTerminator()->getSuccessor(0) == PRegExitBB &&
1170 "Unexpected insertion point for finalization call!");
1171 return FiniCB(IP);
1172 };
1173
1174 FinalizationStack.push_back({FiniCBWrapper, OMPD_parallel, IsCancellable});
1175
1176 // Generate the privatization allocas in the block that will become the entry
1177 // of the outlined function.
1178 Builder.SetInsertPoint(PRegEntryBB->getTerminator());
1179 InsertPointTy InnerAllocaIP = Builder.saveIP();
1180
1181 AllocaInst *PrivTIDAddr =
1182 Builder.CreateAlloca(Int32, nullptr, "tid.addr.local");
1183 Instruction *PrivTID = Builder.CreateLoad(Int32, PrivTIDAddr, "tid");
1184
1185 // Add some fake uses for OpenMP provided arguments.
1186 ToBeDeleted.push_back(Builder.CreateLoad(Int32, TIDAddr, "tid.addr.use"));
1187 Instruction *ZeroAddrUse =
1188 Builder.CreateLoad(Int32, ZeroAddr, "zero.addr.use");
1189 ToBeDeleted.push_back(ZeroAddrUse);
1190
1191 // EntryBB
1192 // |
1193 // V
1194 // PRegionEntryBB <- Privatization allocas are placed here.
1195 // |
1196 // V
1197 // PRegionBodyBB <- BodeGen is invoked here.
1198 // |
1199 // V
1200 // PRegPreFiniBB <- The block we will start finalization from.
1201 // |
1202 // V
1203 // PRegionExitBB <- A common exit to simplify block collection.
1204 //
1205
1206 LLVM_DEBUG(dbgs() << "Before body codegen: " << *OuterFn << "\n");
1207
1208 // Let the caller create the body.
1209 assert(BodyGenCB && "Expected body generation callback!");
1210 InsertPointTy CodeGenIP(PRegBodyBB, PRegBodyBB->begin());
1211 BodyGenCB(InnerAllocaIP, CodeGenIP);
1212
1213 LLVM_DEBUG(dbgs() << "After body codegen: " << *OuterFn << "\n");
1214 FunctionCallee RTLFn;
1215 if (IfCondition)
1216 RTLFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_fork_call_if);
1217 else
1218 RTLFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_fork_call);
1219
1220 if (auto *F = dyn_cast<llvm::Function>(RTLFn.getCallee())) {
1221 if (!F->hasMetadata(llvm::LLVMContext::MD_callback)) {
1222 llvm::LLVMContext &Ctx = F->getContext();
1223 MDBuilder MDB(Ctx);
1224 // Annotate the callback behavior of the __kmpc_fork_call:
1225 // - The callback callee is argument number 2 (microtask).
1226 // - The first two arguments of the callback callee are unknown (-1).
1227 // - All variadic arguments to the __kmpc_fork_call are passed to the
1228 // callback callee.
1229 F->addMetadata(
1230 llvm::LLVMContext::MD_callback,
1232 Ctx, {MDB.createCallbackEncoding(2, {-1, -1},
1233 /* VarArgsArePassed */ true)}));
1234 }
1235 }
1236
1237 OutlineInfo OI;
1238 OI.PostOutlineCB = [=](Function &OutlinedFn) {
1239 // Add some known attributes.
1240 OutlinedFn.addParamAttr(0, Attribute::NoAlias);
1241 OutlinedFn.addParamAttr(1, Attribute::NoAlias);
1242 OutlinedFn.addFnAttr(Attribute::NoUnwind);
1243 OutlinedFn.addFnAttr(Attribute::NoRecurse);
1244
1245 assert(OutlinedFn.arg_size() >= 2 &&
1246 "Expected at least tid and bounded tid as arguments");
1247 unsigned NumCapturedVars =
1248 OutlinedFn.arg_size() - /* tid & bounded tid */ 2;
1249
1250 CallInst *CI = cast<CallInst>(OutlinedFn.user_back());
1251 CI->getParent()->setName("omp_parallel");
1253
1254 // Build call __kmpc_fork_call[_if](Ident, n, microtask, var1, .., varn);
1255 Value *ForkCallArgs[] = {
1256 Ident, Builder.getInt32(NumCapturedVars),
1257 Builder.CreateBitCast(&OutlinedFn, ParallelTaskPtr)};
1258
1259 SmallVector<Value *, 16> RealArgs;
1260 RealArgs.append(std::begin(ForkCallArgs), std::end(ForkCallArgs));
1261 if (IfCondition) {
1262 Value *Cond = Builder.CreateSExtOrTrunc(IfCondition,
1264 RealArgs.push_back(Cond);
1265 }
1266 RealArgs.append(CI->arg_begin() + /* tid & bound tid */ 2, CI->arg_end());
1267
1268 // __kmpc_fork_call_if always expects a void ptr as the last argument
1269 // If there are no arguments, pass a null pointer.
1270 auto PtrTy = Type::getInt8PtrTy(M.getContext());
1271 if (IfCondition && NumCapturedVars == 0) {
1273 RealArgs.push_back(Void);
1274 }
1275 if (IfCondition && RealArgs.back()->getType() != PtrTy)
1276 RealArgs.back() = Builder.CreateBitCast(RealArgs.back(), PtrTy);
1277
1278 Builder.CreateCall(RTLFn, RealArgs);
1279
1280 LLVM_DEBUG(dbgs() << "With fork_call placed: "
1281 << *Builder.GetInsertBlock()->getParent() << "\n");
1282
1283 InsertPointTy ExitIP(PRegExitBB, PRegExitBB->end());
1284
1285 // Initialize the local TID stack location with the argument value.
1286 Builder.SetInsertPoint(PrivTID);
1287 Function::arg_iterator OutlinedAI = OutlinedFn.arg_begin();
1288 Builder.CreateStore(Builder.CreateLoad(Int32, OutlinedAI), PrivTIDAddr);
1289
1290 CI->eraseFromParent();
1291
1292 for (Instruction *I : ToBeDeleted)
1293 I->eraseFromParent();
1294 };
1295
1296 // Adjust the finalization stack, verify the adjustment, and call the
1297 // finalize function a last time to finalize values between the pre-fini
1298 // block and the exit block if we left the parallel "the normal way".
1299 auto FiniInfo = FinalizationStack.pop_back_val();
1300 (void)FiniInfo;
1301 assert(FiniInfo.DK == OMPD_parallel &&
1302 "Unexpected finalization stack state!");
1303
1304 Instruction *PRegPreFiniTI = PRegPreFiniBB->getTerminator();
1305
1306 InsertPointTy PreFiniIP(PRegPreFiniBB, PRegPreFiniTI->getIterator());
1307 FiniCB(PreFiniIP);
1308
1309 OI.OuterAllocaBB = OuterAllocaBlock;
1310 OI.EntryBB = PRegEntryBB;
1311 OI.ExitBB = PRegExitBB;
1312
1313 SmallPtrSet<BasicBlock *, 32> ParallelRegionBlockSet;
1315 OI.collectBlocks(ParallelRegionBlockSet, Blocks);
1316
1317 // Ensure a single exit node for the outlined region by creating one.
1318 // We might have multiple incoming edges to the exit now due to finalizations,
1319 // e.g., cancel calls that cause the control flow to leave the region.
1320 BasicBlock *PRegOutlinedExitBB = PRegExitBB;
1321 PRegExitBB = SplitBlock(PRegExitBB, &*PRegExitBB->getFirstInsertionPt());
1322 PRegOutlinedExitBB->setName("omp.par.outlined.exit");
1323 Blocks.push_back(PRegOutlinedExitBB);
1324
1325 CodeExtractorAnalysisCache CEAC(*OuterFn);
1326 CodeExtractor Extractor(Blocks, /* DominatorTree */ nullptr,
1327 /* AggregateArgs */ false,
1328 /* BlockFrequencyInfo */ nullptr,
1329 /* BranchProbabilityInfo */ nullptr,
1330 /* AssumptionCache */ nullptr,
1331 /* AllowVarArgs */ true,
1332 /* AllowAlloca */ true,
1333 /* AllocationBlock */ OuterAllocaBlock,
1334 /* Suffix */ ".omp_par");
1335
1336 // Find inputs to, outputs from the code region.
1337 BasicBlock *CommonExit = nullptr;
1338 SetVector<Value *> Inputs, Outputs, SinkingCands, HoistingCands;
1339 Extractor.findAllocas(CEAC, SinkingCands, HoistingCands, CommonExit);
1340 Extractor.findInputsOutputs(Inputs, Outputs, SinkingCands);
1341
1342 LLVM_DEBUG(dbgs() << "Before privatization: " << *OuterFn << "\n");
1343
1344 FunctionCallee TIDRTLFn =
1345 getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_global_thread_num);
1346
1347 auto PrivHelper = [&](Value &V) {
1348 if (&V == TIDAddr || &V == ZeroAddr) {
1349 OI.ExcludeArgsFromAggregate.push_back(&V);
1350 return;
1351 }
1352
1354 for (Use &U : V.uses())
1355 if (auto *UserI = dyn_cast<Instruction>(U.getUser()))
1356 if (ParallelRegionBlockSet.count(UserI->getParent()))
1357 Uses.insert(&U);
1358
1359 // __kmpc_fork_call expects extra arguments as pointers. If the input
1360 // already has a pointer type, everything is fine. Otherwise, store the
1361 // value onto stack and load it back inside the to-be-outlined region. This
1362 // will ensure only the pointer will be passed to the function.
1363 // FIXME: if there are more than 15 trailing arguments, they must be
1364 // additionally packed in a struct.
1365 Value *Inner = &V;
1366 if (!V.getType()->isPointerTy()) {
1368 LLVM_DEBUG(llvm::dbgs() << "Forwarding input as pointer: " << V << "\n");
1369
1370 Builder.restoreIP(OuterAllocaIP);
1371 Value *Ptr =
1372 Builder.CreateAlloca(V.getType(), nullptr, V.getName() + ".reloaded");
1373
1374 // Store to stack at end of the block that currently branches to the entry
1375 // block of the to-be-outlined region.
1376 Builder.SetInsertPoint(InsertBB,
1377 InsertBB->getTerminator()->getIterator());
1378 Builder.CreateStore(&V, Ptr);
1379
1380 // Load back next to allocations in the to-be-outlined region.
1381 Builder.restoreIP(InnerAllocaIP);
1382 Inner = Builder.CreateLoad(V.getType(), Ptr);
1383 }
1384
1385 Value *ReplacementValue = nullptr;
1386 CallInst *CI = dyn_cast<CallInst>(&V);
1387 if (CI && CI->getCalledFunction() == TIDRTLFn.getCallee()) {
1388 ReplacementValue = PrivTID;
1389 } else {
1391 PrivCB(InnerAllocaIP, Builder.saveIP(), V, *Inner, ReplacementValue));
1392 assert(ReplacementValue &&
1393 "Expected copy/create callback to set replacement value!");
1394 if (ReplacementValue == &V)
1395 return;
1396 }
1397
1398 for (Use *UPtr : Uses)
1399 UPtr->set(ReplacementValue);
1400 };
1401
1402 // Reset the inner alloca insertion as it will be used for loading the values
1403 // wrapped into pointers before passing them into the to-be-outlined region.
1404 // Configure it to insert immediately after the fake use of zero address so
1405 // that they are available in the generated body and so that the
1406 // OpenMP-related values (thread ID and zero address pointers) remain leading
1407 // in the argument list.
1408 InnerAllocaIP = IRBuilder<>::InsertPoint(
1409 ZeroAddrUse->getParent(), ZeroAddrUse->getNextNode()->getIterator());
1410
1411 // Reset the outer alloca insertion point to the entry of the relevant block
1412 // in case it was invalidated.
1413 OuterAllocaIP = IRBuilder<>::InsertPoint(
1414 OuterAllocaBlock, OuterAllocaBlock->getFirstInsertionPt());
1415
1416 for (Value *Input : Inputs) {
1417 LLVM_DEBUG(dbgs() << "Captured input: " << *Input << "\n");
1418 PrivHelper(*Input);
1419 }
1420 LLVM_DEBUG({
1421 for (Value *Output : Outputs)
1422 LLVM_DEBUG(dbgs() << "Captured output: " << *Output << "\n");
1423 });
1424 assert(Outputs.empty() &&
1425 "OpenMP outlining should not produce live-out values!");
1426
1427 LLVM_DEBUG(dbgs() << "After privatization: " << *OuterFn << "\n");
1428 LLVM_DEBUG({
1429 for (auto *BB : Blocks)
1430 dbgs() << " PBR: " << BB->getName() << "\n";
1431 });
1432
1433 // Register the outlined info.
1434 addOutlineInfo(std::move(OI));
1435
1436 InsertPointTy AfterIP(UI->getParent(), UI->getParent()->end());
1437 UI->eraseFromParent();
1438
1439 return AfterIP;
1440}
1441
1443 // Build call void __kmpc_flush(ident_t *loc)
1444 uint32_t SrcLocStrSize;
1445 Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
1446 Value *Args[] = {getOrCreateIdent(SrcLocStr, SrcLocStrSize)};
1447
1448 Builder.CreateCall(getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_flush), Args);
1449}
1450
1452 if (!updateToLocation(Loc))
1453 return;
1454 emitFlush(Loc);
1455}
1456
1458 // Build call kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
1459 // global_tid);
1460 uint32_t SrcLocStrSize;
1461 Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
1462 Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
1463 Value *Args[] = {Ident, getOrCreateThreadID(Ident)};
1464
1465 // Ignore return result until untied tasks are supported.
1466 Builder.CreateCall(getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_omp_taskwait),
1467 Args);
1468}
1469
1471 if (!updateToLocation(Loc))
1472 return;
1473 emitTaskwaitImpl(Loc);
1474}
1475
1477 // Build call __kmpc_omp_taskyield(loc, thread_id, 0);
1478 uint32_t SrcLocStrSize;
1479 Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
1480 Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
1482 Value *Args[] = {Ident, getOrCreateThreadID(Ident), I32Null};
1483
1484 Builder.CreateCall(getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_omp_taskyield),
1485 Args);
1486}
1487
1489 if (!updateToLocation(Loc))
1490 return;
1491 emitTaskyieldImpl(Loc);
1492}
1493
1496 InsertPointTy AllocaIP, BodyGenCallbackTy BodyGenCB,
1497 bool Tied, Value *Final, Value *IfCondition,
1498 SmallVector<DependData> Dependencies) {
1499 if (!updateToLocation(Loc))
1500 return InsertPointTy();
1501
1502 uint32_t SrcLocStrSize;
1503 Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
1504 Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
1505 // The current basic block is split into four basic blocks. After outlining,
1506 // they will be mapped as follows:
1507 // ```
1508 // def current_fn() {
1509 // current_basic_block:
1510 // br label %task.exit
1511 // task.exit:
1512 // ; instructions after task
1513 // }
1514 // def outlined_fn() {
1515 // task.alloca:
1516 // br label %task.body
1517 // task.body:
1518 // ret void
1519 // }
1520 // ```
1521 BasicBlock *TaskExitBB = splitBB(Builder, /*CreateBranch=*/true, "task.exit");
1522 BasicBlock *TaskBodyBB = splitBB(Builder, /*CreateBranch=*/true, "task.body");
1523 BasicBlock *TaskAllocaBB =
1524 splitBB(Builder, /*CreateBranch=*/true, "task.alloca");
1525
1526 OutlineInfo OI;
1527 OI.EntryBB = TaskAllocaBB;
1528 OI.OuterAllocaBB = AllocaIP.getBlock();
1529 OI.ExitBB = TaskExitBB;
1530 OI.PostOutlineCB = [this, Ident, Tied, Final, IfCondition,
1531 Dependencies](Function &OutlinedFn) {
1532 // The input IR here looks like the following-
1533 // ```
1534 // func @current_fn() {
1535 // outlined_fn(%args)
1536 // }
1537 // func @outlined_fn(%args) { ... }
1538 // ```
1539 //
1540 // This is changed to the following-
1541 //
1542 // ```
1543 // func @current_fn() {
1544 // runtime_call(..., wrapper_fn, ...)
1545 // }
1546 // func @wrapper_fn(..., %args) {
1547 // outlined_fn(%args)
1548 // }
1549 // func @outlined_fn(%args) { ... }
1550 // ```
1551
1552 // The stale call instruction will be replaced with a new call instruction
1553 // for runtime call with a wrapper function.
1554 assert(OutlinedFn.getNumUses() == 1 &&
1555 "there must be a single user for the outlined function");
1556 CallInst *StaleCI = cast<CallInst>(OutlinedFn.user_back());
1557
1558 // HasShareds is true if any variables are captured in the outlined region,
1559 // false otherwise.
1560 bool HasShareds = StaleCI->arg_size() > 0;
1561 Builder.SetInsertPoint(StaleCI);
1562
1563 // Gather the arguments for emitting the runtime call for
1564 // @__kmpc_omp_task_alloc
1565 Function *TaskAllocFn =
1566 getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_omp_task_alloc);
1567
1568 // Arguments - `loc_ref` (Ident) and `gtid` (ThreadID)
1569 // call.
1570 Value *ThreadID = getOrCreateThreadID(Ident);
1571
1572 // Argument - `flags`
1573 // Task is tied iff (Flags & 1) == 1.
1574 // Task is untied iff (Flags & 1) == 0.
1575 // Task is final iff (Flags & 2) == 2.
1576 // Task is not final iff (Flags & 2) == 0.
1577 // TODO: Handle the other flags.
1578 Value *Flags = Builder.getInt32(Tied);
1579 if (Final) {
1580 Value *FinalFlag =
1582 Flags = Builder.CreateOr(FinalFlag, Flags);
1583 }
1584
1585 // Argument - `sizeof_kmp_task_t` (TaskSize)
1586 // Tasksize refers to the size in bytes of kmp_task_t data structure
1587 // including private vars accessed in task.
1588 // TODO: add kmp_task_t_with_privates (privates)
1589 Value *TaskSize = Builder.getInt64(
1591
1592 // Argument - `sizeof_shareds` (SharedsSize)
1593 // SharedsSize refers to the shareds array size in the kmp_task_t data
1594 // structure.
1595 Value *SharedsSize = Builder.getInt64(0);
1596 if (HasShareds) {
1597 AllocaInst *ArgStructAlloca =
1598 dyn_cast<AllocaInst>(StaleCI->getArgOperand(0));
1599 assert(ArgStructAlloca &&
1600 "Unable to find the alloca instruction corresponding to arguments "
1601 "for extracted function");
1602 StructType *ArgStructType =
1603 dyn_cast<StructType>(ArgStructAlloca->getAllocatedType());
1604 assert(ArgStructType && "Unable to find struct type corresponding to "
1605 "arguments for extracted function");
1606 SharedsSize =
1608 }
1609
1610 // Argument - task_entry (the wrapper function)
1611 // If the outlined function has some captured variables (i.e. HasShareds is
1612 // true), then the wrapper function will have an additional argument (the
1613 // struct containing captured variables). Otherwise, no such argument will
1614 // be present.
1615 SmallVector<Type *> WrapperArgTys{Builder.getInt32Ty()};
1616 if (HasShareds)
1617 WrapperArgTys.push_back(OutlinedFn.getArg(0)->getType());
1618 FunctionCallee WrapperFuncVal = M.getOrInsertFunction(
1619 (Twine(OutlinedFn.getName()) + ".wrapper").str(),
1620 FunctionType::get(Builder.getInt32Ty(), WrapperArgTys, false));
1621 Function *WrapperFunc = dyn_cast<Function>(WrapperFuncVal.getCallee());
1622
1623 // Emit the @__kmpc_omp_task_alloc runtime call
1624 // The runtime call returns a pointer to an area where the task captured
1625 // variables must be copied before the task is run (TaskData)
1626 CallInst *TaskData = Builder.CreateCall(
1627 TaskAllocFn, {/*loc_ref=*/Ident, /*gtid=*/ThreadID, /*flags=*/Flags,
1628 /*sizeof_task=*/TaskSize, /*sizeof_shared=*/SharedsSize,
1629 /*task_func=*/WrapperFunc});
1630
1631 // Copy the arguments for outlined function
1632 if (HasShareds) {
1633 Value *Shareds = StaleCI->getArgOperand(0);
1634 Align Alignment = TaskData->getPointerAlignment(M.getDataLayout());
1635 Value *TaskShareds = Builder.CreateLoad(VoidPtr, TaskData);
1636 Builder.CreateMemCpy(TaskShareds, Alignment, Shareds, Alignment,
1637 SharedsSize);
1638 }
1639
1640 Value *DepArrayPtr = nullptr;
1641 if (Dependencies.size()) {
1642 InsertPointTy OldIP = Builder.saveIP();
1644 &OldIP.getBlock()->getParent()->getEntryBlock().back());
1645
1646 Type *DepArrayTy = ArrayType::get(DependInfo, Dependencies.size());
1647 Value *DepArray =
1648 Builder.CreateAlloca(DepArrayTy, nullptr, ".dep.arr.addr");
1649
1650 unsigned P = 0;
1651 for (const DependData &Dep : Dependencies) {
1652 Value *Base =
1653 Builder.CreateConstInBoundsGEP2_64(DepArrayTy, DepArray, 0, P);
1654 // Store the pointer to the variable
1656 DependInfo, Base,
1657 static_cast<unsigned int>(RTLDependInfoFields::BaseAddr));
1658 Value *DepValPtr =
1660 Builder.CreateStore(DepValPtr, Addr);
1661 // Store the size of the variable
1663 DependInfo, Base,
1664 static_cast<unsigned int>(RTLDependInfoFields::Len));
1666 Dep.DepValueType)),
1667 Size);
1668 // Store the dependency kind
1670 DependInfo, Base,
1671 static_cast<unsigned int>(RTLDependInfoFields::Flags));
1674 static_cast<unsigned int>(Dep.DepKind)),
1675 Flags);
1676 ++P;
1677 }
1678
1679 DepArrayPtr = Builder.CreateBitCast(DepArray, Builder.getInt8PtrTy());
1680 Builder.restoreIP(OldIP);
1681 }
1682
1683 // In the presence of the `if` clause, the following IR is generated:
1684 // ...
1685 // %data = call @__kmpc_omp_task_alloc(...)
1686 // br i1 %if_condition, label %then, label %else
1687 // then:
1688 // call @__kmpc_omp_task(...)
1689 // br label %exit
1690 // else:
1691 // call @__kmpc_omp_task_begin_if0(...)
1692 // call @wrapper_fn(...)
1693 // call @__kmpc_omp_task_complete_if0(...)
1694 // br label %exit
1695 // exit:
1696 // ...
1697 if (IfCondition) {
1698 // `SplitBlockAndInsertIfThenElse` requires the block to have a
1699 // terminator.
1700 BasicBlock *NewBasicBlock =
1701 splitBB(Builder, /*CreateBranch=*/true, "if.end");
1702 Instruction *IfTerminator =
1703 NewBasicBlock->getSinglePredecessor()->getTerminator();
1704 Instruction *ThenTI = IfTerminator, *ElseTI = nullptr;
1705 Builder.SetInsertPoint(IfTerminator);
1706 SplitBlockAndInsertIfThenElse(IfCondition, IfTerminator, &ThenTI,
1707 &ElseTI);
1708 Builder.SetInsertPoint(ElseTI);
1709 Function *TaskBeginFn =
1710 getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_omp_task_begin_if0);
1711 Function *TaskCompleteFn =
1712 getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_omp_task_complete_if0);
1713 Builder.CreateCall(TaskBeginFn, {Ident, ThreadID, TaskData});
1714 if (HasShareds)
1715 Builder.CreateCall(WrapperFunc, {ThreadID, TaskData});
1716 else
1717 Builder.CreateCall(WrapperFunc, {ThreadID});
1718 Builder.CreateCall(TaskCompleteFn, {Ident, ThreadID, TaskData});
1719 Builder.SetInsertPoint(ThenTI);
1720 }
1721
1722 if (Dependencies.size()) {
1723 Function *TaskFn =
1724 getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_omp_task_with_deps);
1726 TaskFn,
1727 {Ident, ThreadID, TaskData, Builder.getInt32(Dependencies.size()),
1728 DepArrayPtr, ConstantInt::get(Builder.getInt32Ty(), 0),
1730
1731 } else {
1732 // Emit the @__kmpc_omp_task runtime call to spawn the task
1733 Function *TaskFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_omp_task);
1734 Builder.CreateCall(TaskFn, {Ident, ThreadID, TaskData});
1735 }
1736
1737 StaleCI->eraseFromParent();
1738
1739 // Emit the body for wrapper function
1740 BasicBlock *WrapperEntryBB =
1741 BasicBlock::Create(M.getContext(), "", WrapperFunc);
1742 Builder.SetInsertPoint(WrapperEntryBB);
1743 if (HasShareds) {
1744 llvm::Value *Shareds =
1745 Builder.CreateLoad(VoidPtr, WrapperFunc->getArg(1));
1746 Builder.CreateCall(&OutlinedFn, {Shareds});
1747 } else {
1748 Builder.CreateCall(&OutlinedFn);
1749 }
1751 };
1752
1753 addOutlineInfo(std::move(OI));
1754
1755 InsertPointTy TaskAllocaIP =
1756 InsertPointTy(TaskAllocaBB, TaskAllocaBB->begin());
1757 InsertPointTy TaskBodyIP = InsertPointTy(TaskBodyBB, TaskBodyBB->begin());
1758 BodyGenCB(TaskAllocaIP, TaskBodyIP);
1759 Builder.SetInsertPoint(TaskExitBB, TaskExitBB->begin());
1760
1761 return Builder.saveIP();
1762}
1763
1766 InsertPointTy AllocaIP,
1767 BodyGenCallbackTy BodyGenCB) {
1768 if (!updateToLocation(Loc))
1769 return InsertPointTy();
1770
1771 uint32_t SrcLocStrSize;
1772 Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
1773 Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
1774 Value *ThreadID = getOrCreateThreadID(Ident);
1775
1776 // Emit the @__kmpc_taskgroup runtime call to start the taskgroup
1777 Function *TaskgroupFn =
1778 getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_taskgroup);
1779 Builder.CreateCall(TaskgroupFn, {Ident, ThreadID});
1780
1781 BasicBlock *TaskgroupExitBB = splitBB(Builder, true, "taskgroup.exit");
1782 BodyGenCB(AllocaIP, Builder.saveIP());
1783
1784 Builder.SetInsertPoint(TaskgroupExitBB);
1785 // Emit the @__kmpc_end_taskgroup runtime call to end the taskgroup
1786 Function *EndTaskgroupFn =
1787 getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_end_taskgroup);
1788 Builder.CreateCall(EndTaskgroupFn, {Ident, ThreadID});
1789
1790 return Builder.saveIP();
1791}
1792
1794 const LocationDescription &Loc, InsertPointTy AllocaIP,
1796 FinalizeCallbackTy FiniCB, bool IsCancellable, bool IsNowait) {
1797 assert(!isConflictIP(AllocaIP, Loc.IP) && "Dedicated IP allocas required");
1798
1799 if (!updateToLocation(Loc))
1800 return Loc.IP;
1801
1802 auto FiniCBWrapper = [&](InsertPointTy IP) {
1803 if (IP.getBlock()->end() != IP.getPoint())
1804 return FiniCB(IP);
1805 // This must be done otherwise any nested constructs using FinalizeOMPRegion
1806 // will fail because that function requires the Finalization Basic Block to
1807 // have a terminator, which is already removed by EmitOMPRegionBody.
1808 // IP is currently at cancelation block.
1809 // We need to backtrack to the condition block to fetch
1810 // the exit block and create a branch from cancelation
1811 // to exit block.
1813 Builder.restoreIP(IP);
1814 auto *CaseBB = IP.getBlock()->getSinglePredecessor();
1815 auto *CondBB = CaseBB->getSinglePredecessor()->getSinglePredecessor();
1816 auto *ExitBB = CondBB->getTerminator()->getSuccessor(1);
1817 Instruction *I = Builder.CreateBr(ExitBB);
1818 IP = InsertPointTy(I->getParent(), I->getIterator());
1819 return FiniCB(IP);
1820 };
1821
1822 FinalizationStack.push_back({FiniCBWrapper, OMPD_sections, IsCancellable});
1823
1824 // Each section is emitted as a switch case
1825 // Each finalization callback is handled from clang.EmitOMPSectionDirective()
1826 // -> OMP.createSection() which generates the IR for each section
1827 // Iterate through all sections and emit a switch construct:
1828 // switch (IV) {
1829 // case 0:
1830 // <SectionStmt[0]>;
1831 // break;
1832 // ...
1833 // case <NumSection> - 1:
1834 // <SectionStmt[<NumSection> - 1]>;
1835 // break;
1836 // }
1837 // ...
1838 // section_loop.after:
1839 // <FiniCB>;
1840 auto LoopBodyGenCB = [&](InsertPointTy CodeGenIP, Value *IndVar) {
1841 Builder.restoreIP(CodeGenIP);
1842 BasicBlock *Continue =
1843 splitBBWithSuffix(Builder, /*CreateBranch=*/false, ".sections.after");
1844 Function *CurFn = Continue->getParent();
1845 SwitchInst *SwitchStmt = Builder.CreateSwitch(IndVar, Continue);
1846
1847 unsigned CaseNumber = 0;
1848 for (auto SectionCB : SectionCBs) {
1850 M.getContext(), "omp_section_loop.body.case", CurFn, Continue);
1851 SwitchStmt->addCase(Builder.getInt32(CaseNumber), CaseBB);
1852 Builder.SetInsertPoint(CaseBB);
1853 BranchInst *CaseEndBr = Builder.CreateBr(Continue);
1854 SectionCB(InsertPointTy(),
1855 {CaseEndBr->getParent(), CaseEndBr->getIterator()});
1856 CaseNumber++;
1857 }
1858 // remove the existing terminator from body BB since there can be no
1859 // terminators after switch/case
1860 };
1861 // Loop body ends here
1862 // LowerBound, UpperBound, and STride for createCanonicalLoop
1863 Type *I32Ty = Type::getInt32Ty(M.getContext());
1864 Value *LB = ConstantInt::get(I32Ty, 0);
1865 Value *UB = ConstantInt::get(I32Ty, SectionCBs.size());
1866 Value *ST = ConstantInt::get(I32Ty, 1);
1868 Loc, LoopBodyGenCB, LB, UB, ST, true, false, AllocaIP, "section_loop");
1869 InsertPointTy AfterIP =
1870 applyStaticWorkshareLoop(Loc.DL, LoopInfo, AllocaIP, !IsNowait);
1871
1872 // Apply the finalization callback in LoopAfterBB
1873 auto FiniInfo = FinalizationStack.pop_back_val();
1874 assert(FiniInfo.DK == OMPD_sections &&
1875 "Unexpected finalization stack state!");
1876 if (FinalizeCallbackTy &CB = FiniInfo.FiniCB) {
1877 Builder.restoreIP(AfterIP);
1878 BasicBlock *FiniBB =
1879 splitBBWithSuffix(Builder, /*CreateBranch=*/true, "sections.fini");
1880 CB(Builder.saveIP());
1881 AfterIP = {FiniBB, FiniBB->begin()};
1882 }
1883
1884 return AfterIP;
1885}
1886
1889 BodyGenCallbackTy BodyGenCB,
1890 FinalizeCallbackTy FiniCB) {
1891 if (!updateToLocation(Loc))
1892 return Loc.IP;
1893
1894 auto FiniCBWrapper = [&](InsertPointTy IP) {
1895 if (IP.getBlock()->end() != IP.getPoint())
1896 return FiniCB(IP);
1897 // This must be done otherwise any nested constructs using FinalizeOMPRegion
1898 // will fail because that function requires the Finalization Basic Block to
1899 // have a terminator, which is already removed by EmitOMPRegionBody.
1900 // IP is currently at cancelation block.
1901 // We need to backtrack to the condition block to fetch
1902 // the exit block and create a branch from cancelation
1903 // to exit block.
1905 Builder.restoreIP(IP);
1906 auto *CaseBB = Loc.IP.getBlock();
1907 auto *CondBB = CaseBB->getSinglePredecessor()->getSinglePredecessor();
1908 auto *ExitBB = CondBB->getTerminator()->getSuccessor(1);
1909 Instruction *I = Builder.CreateBr(ExitBB);
1910 IP = InsertPointTy(I->getParent(), I->getIterator());
1911 return FiniCB(IP);
1912 };
1913
1914 Directive OMPD = Directive::OMPD_sections;
1915 // Since we are using Finalization Callback here, HasFinalize
1916 // and IsCancellable have to be true
1917 return EmitOMPInlinedRegion(OMPD, nullptr, nullptr, BodyGenCB, FiniCBWrapper,
1918 /*Conditional*/ false, /*hasFinalize*/ true,
1919 /*IsCancellable*/ true);
1920}
1921
1922/// Create a function with a unique name and a "void (i8*, i8*)" signature in
1923/// the given module and return it.
1925 Type *VoidTy = Type::getVoidTy(M.getContext());
1926 Type *Int8PtrTy = Type::getInt8PtrTy(M.getContext());
1927 auto *FuncTy =
1928 FunctionType::get(VoidTy, {Int8PtrTy, Int8PtrTy}, /* IsVarArg */ false);
1930 M.getDataLayout().getDefaultGlobalsAddressSpace(),
1931 ".omp.reduction.func", &M);
1932}
1933
1935 const LocationDescription &Loc, InsertPointTy AllocaIP,
1936 ArrayRef<ReductionInfo> ReductionInfos, bool IsNoWait) {
1937 for (const ReductionInfo &RI : ReductionInfos) {
1938 (void)RI;
1939 assert(RI.Variable && "expected non-null variable");
1940 assert(RI.PrivateVariable && "expected non-null private variable");
1941 assert(RI.ReductionGen && "expected non-null reduction generator callback");
1942 assert(RI.Variable->getType() == RI.PrivateVariable->getType() &&
1943 "expected variables and their private equivalents to have the same "
1944 "type");
1945 assert(RI.Variable->getType()->isPointerTy() &&
1946 "expected variables to be pointers");
1947 }
1948
1949 if (!updateToLocation(Loc))
1950 return InsertPointTy();
1951
1952 BasicBlock *InsertBlock = Loc.IP.getBlock();
1953 BasicBlock *ContinuationBlock =
1954 InsertBlock->splitBasicBlock(Loc.IP.getPoint(), "reduce.finalize");
1955 InsertBlock->getTerminator()->eraseFromParent();
1956
1957 // Create and populate array of type-erased pointers to private reduction
1958 // values.
1959 unsigned NumReductions = ReductionInfos.size();
1960 Type *RedArrayTy = ArrayType::get(Builder.getInt8PtrTy(), NumReductions);
1961 Builder.restoreIP(AllocaIP);
1962 Value *RedArray = Builder.CreateAlloca(RedArrayTy, nullptr, "red.array");
1963
1964 Builder.SetInsertPoint(InsertBlock, InsertBlock->end());
1965
1966 for (auto En : enumerate(ReductionInfos)) {
1967 unsigned Index = En.index();
1968 const ReductionInfo &RI = En.value();
1969 Value *RedArrayElemPtr = Builder.CreateConstInBoundsGEP2_64(
1970 RedArrayTy, RedArray, 0, Index, "red.array.elem." + Twine(Index));
1971 Value *Casted =
1973 "private.red.var." + Twine(Index) + ".casted");
1974 Builder.CreateStore(Casted, RedArrayElemPtr);
1975 }
1976
1977 // Emit a call to the runtime function that orchestrates the reduction.
1978 // Declare the reduction function in the process.
1980 Module *Module = Func->getParent();
1981 Value *RedArrayPtr =
1982 Builder.CreateBitCast(RedArray, Builder.getInt8PtrTy(), "red.array.ptr");
1983 uint32_t SrcLocStrSize;
1984 Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
1985 bool CanGenerateAtomic =
1986 llvm::all_of(ReductionInfos, [](const ReductionInfo &RI) {
1987 return RI.AtomicReductionGen;
1988 });
1989 Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize,
1990 CanGenerateAtomic
1991 ? IdentFlag::OMP_IDENT_FLAG_ATOMIC_REDUCE
1992 : IdentFlag(0));
1993 Value *ThreadId = getOrCreateThreadID(Ident);
1994 Constant *NumVariables = Builder.getInt32(NumReductions);
1995 const DataLayout &DL = Module->getDataLayout();
1996 unsigned RedArrayByteSize = DL.getTypeStoreSize(RedArrayTy);
1997 Constant *RedArraySize = Builder.getInt64(RedArrayByteSize);
1998 Function *ReductionFunc = getFreshReductionFunc(*Module);
1999 Value *Lock = getOMPCriticalRegionLock(".reduction");
2001 IsNoWait ? RuntimeFunction::OMPRTL___kmpc_reduce_nowait
2002 : RuntimeFunction::OMPRTL___kmpc_reduce);
2003 CallInst *ReduceCall =
2004 Builder.CreateCall(ReduceFunc,
2005 {Ident, ThreadId, NumVariables, RedArraySize,
2006 RedArrayPtr, ReductionFunc, Lock},
2007 "reduce");
2008
2009 // Create final reduction entry blocks for the atomic and non-atomic case.
2010 // Emit IR that dispatches control flow to one of the blocks based on the
2011 // reduction supporting the atomic mode.
2012 BasicBlock *NonAtomicRedBlock =
2013 BasicBlock::Create(Module->getContext(), "reduce.switch.nonatomic", Func);
2014 BasicBlock *AtomicRedBlock =
2015 BasicBlock::Create(Module->getContext(), "reduce.switch.atomic", Func);
2016 SwitchInst *Switch =
2017 Builder.CreateSwitch(ReduceCall, ContinuationBlock, /* NumCases */ 2);
2018 Switch->addCase(Builder.getInt32(1), NonAtomicRedBlock);
2019 Switch->addCase(Builder.getInt32(2), AtomicRedBlock);
2020
2021 // Populate the non-atomic reduction using the elementwise reduction function.
2022 // This loads the elements from the global and private variables and reduces
2023 // them before storing back the result to the global variable.
2024 Builder.SetInsertPoint(NonAtomicRedBlock);
2025 for (auto En : enumerate(ReductionInfos)) {
2026 const ReductionInfo &RI = En.value();
2028 Value *RedValue = Builder.CreateLoad(ValueType, RI.Variable,
2029 "red.value." + Twine(En.index()));
2030 Value *PrivateRedValue =
2032 "red.private.value." + Twine(En.index()));
2033 Value *Reduced;
2035 RI.ReductionGen(Builder.saveIP(), RedValue, PrivateRedValue, Reduced));
2036 if (!Builder.GetInsertBlock())
2037 return InsertPointTy();
2038 Builder.CreateStore(Reduced, RI.Variable);
2039 }
2040 Function *EndReduceFunc = getOrCreateRuntimeFunctionPtr(
2041 IsNoWait ? RuntimeFunction::OMPRTL___kmpc_end_reduce_nowait
2042 : RuntimeFunction::OMPRTL___kmpc_end_reduce);
2043 Builder.CreateCall(EndReduceFunc, {Ident, ThreadId, Lock});
2044 Builder.CreateBr(ContinuationBlock);
2045
2046 // Populate the atomic reduction using the atomic elementwise reduction
2047 // function. There are no loads/stores here because they will be happening
2048 // inside the atomic elementwise reduction.
2049 Builder.SetInsertPoint(AtomicRedBlock);
2050 if (CanGenerateAtomic) {
2051 for (const ReductionInfo &RI : ReductionInfos) {
2053 RI.Variable, RI.PrivateVariable));
2054 if (!Builder.GetInsertBlock())
2055 return InsertPointTy();
2056 }
2057 Builder.CreateBr(ContinuationBlock);
2058 } else {
2060 }
2061
2062 // Populate the outlined reduction function using the elementwise reduction
2063 // function. Partial values are extracted from the type-erased array of
2064 // pointers to private variables.
2065 BasicBlock *ReductionFuncBlock =
2066 BasicBlock::Create(Module->getContext(), "", ReductionFunc);
2067 Builder.SetInsertPoint(ReductionFuncBlock);
2068 Value *LHSArrayPtr = ReductionFunc->getArg(0);
2069 Value *RHSArrayPtr = ReductionFunc->getArg(1);
2070
2071 for (auto En : enumerate(ReductionInfos)) {
2072 const ReductionInfo &RI = En.value();
2074 RedArrayTy, LHSArrayPtr, 0, En.index());
2075 Value *LHSI8Ptr = Builder.CreateLoad(Builder.getInt8PtrTy(), LHSI8PtrPtr);
2076 Value *LHSPtr = Builder.CreateBitCast(LHSI8Ptr, RI.Variable->getType());
2077 Value *LHS = Builder.CreateLoad(RI.ElementType, LHSPtr);
2079 RedArrayTy, RHSArrayPtr, 0, En.index());
2080 Value *RHSI8Ptr = Builder.CreateLoad(Builder.getInt8PtrTy(), RHSI8PtrPtr);
2081 Value *RHSPtr =
2083 Value *RHS = Builder.CreateLoad(RI.ElementType, RHSPtr);
2084 Value *Reduced;
2086 if (!Builder.GetInsertBlock())
2087 return InsertPointTy();
2088 Builder.CreateStore(Reduced, LHSPtr);
2089 }
2091
2092 Builder.SetInsertPoint(ContinuationBlock);
2093 return Builder.saveIP();
2094}
2095
2098 BodyGenCallbackTy BodyGenCB,
2099 FinalizeCallbackTy FiniCB) {
2100
2101 if (!updateToLocation(Loc))
2102 return Loc.IP;
2103
2104 Directive OMPD = Directive::OMPD_master;
2105 uint32_t SrcLocStrSize;
2106 Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
2107 Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
2108 Value *ThreadId = getOrCreateThreadID(Ident);
2109 Value *Args[] = {Ident, ThreadId};
2110
2111 Function *EntryRTLFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_master);
2112 Instruction *EntryCall = Builder.CreateCall(EntryRTLFn, Args);
2113
2114 Function *ExitRTLFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_end_master);
2115 Instruction *ExitCall = Builder.CreateCall(ExitRTLFn, Args);
2116
2117 return EmitOMPInlinedRegion(OMPD, EntryCall, ExitCall, BodyGenCB, FiniCB,
2118 /*Conditional*/ true, /*hasFinalize*/ true);
2119}
2120
2123 BodyGenCallbackTy BodyGenCB,
2124 FinalizeCallbackTy FiniCB, Value *Filter) {
2125 if (!updateToLocation(Loc))
2126 return Loc.IP;
2127
2128 Directive OMPD = Directive::OMPD_masked;
2129 uint32_t SrcLocStrSize;
2130 Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
2131 Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
2132 Value *ThreadId = getOrCreateThreadID(Ident);
2133 Value *Args[] = {Ident, ThreadId, Filter};
2134 Value *ArgsEnd[] = {Ident, ThreadId};
2135
2136 Function *EntryRTLFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_masked);
2137 Instruction *EntryCall = Builder.CreateCall(EntryRTLFn, Args);
2138
2139 Function *ExitRTLFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_end_masked);
2140 Instruction *ExitCall = Builder.CreateCall(ExitRTLFn, ArgsEnd);
2141
2142 return EmitOMPInlinedRegion(OMPD, EntryCall, ExitCall, BodyGenCB, FiniCB,
2143 /*Conditional*/ true, /*hasFinalize*/ true);
2144}
2145
2147 DebugLoc DL, Value *TripCount, Function *F, BasicBlock *PreInsertBefore,
2148 BasicBlock *PostInsertBefore, const Twine &Name) {
2149 Module *M = F->getParent();
2150 LLVMContext &Ctx = M->getContext();
2151 Type *IndVarTy = TripCount->getType();
2152
2153 // Create the basic block structure.
2154 BasicBlock *Preheader =
2155 BasicBlock::Create(Ctx, "omp_" + Name + ".preheader", F, PreInsertBefore);
2156 BasicBlock *Header =
2157 BasicBlock::Create(Ctx, "omp_" + Name + ".header", F, PreInsertBefore);
2158 BasicBlock *Cond =
2159 BasicBlock::Create(Ctx, "omp_" + Name + ".cond", F, PreInsertBefore);
2160 BasicBlock *Body =
2161 BasicBlock::Create(Ctx, "omp_" + Name + ".body", F, PreInsertBefore);
2162 BasicBlock *Latch =
2163 BasicBlock::Create(Ctx, "omp_" + Name + ".inc", F, PostInsertBefore);
2164 BasicBlock *Exit =
2165 BasicBlock::Create(Ctx, "omp_" + Name + ".exit", F, PostInsertBefore);
2166 BasicBlock *After =
2167 BasicBlock::Create(Ctx, "omp_" + Name + ".after", F, PostInsertBefore);
2168
2169 // Use specified DebugLoc for new instructions.
2171
2172 Builder.SetInsertPoint(Preheader);
2173 Builder.CreateBr(Header);
2174
2175 Builder.SetInsertPoint(Header);
2176 PHINode *IndVarPHI = Builder.CreatePHI(IndVarTy, 2, "omp_" + Name + ".iv");
2177 IndVarPHI->addIncoming(ConstantInt::get(IndVarTy, 0), Preheader);
2179
2181 Value *Cmp =
2182 Builder.CreateICmpULT(IndVarPHI, TripCount, "omp_" + Name + ".cmp");
2183 Builder.CreateCondBr(Cmp, Body, Exit);
2184
2185 Builder.SetInsertPoint(Body);
2186 Builder.CreateBr(Latch);
2187
2188 Builder.SetInsertPoint(Latch);
2189 Value *Next = Builder.CreateAdd(IndVarPHI, ConstantInt::get(IndVarTy, 1),
2190 "omp_" + Name + ".next", /*HasNUW=*/true);
2191 Builder.CreateBr(Header);
2192 IndVarPHI->addIncoming(Next, Latch);
2193
2194 Builder.SetInsertPoint(Exit);
2195 Builder.CreateBr(After);
2196
2197 // Remember and return the canonical control flow.
2198 LoopInfos.emplace_front();
2199 CanonicalLoopInfo *CL = &LoopInfos.front();
2200
2201 CL->Header = Header;
2202 CL->Cond = Cond;
2203 CL->Latch = Latch;
2204 CL->Exit = Exit;
2205
2206#ifndef NDEBUG
2207 CL->assertOK();
2208#endif
2209 return CL;
2210}
2211
2214 LoopBodyGenCallbackTy BodyGenCB,
2215 Value *TripCount, const Twine &Name) {
2216 BasicBlock *BB = Loc.IP.getBlock();
2217 BasicBlock *NextBB = BB->getNextNode();
2218
2219 CanonicalLoopInfo *CL = createLoopSkeleton(Loc.DL, TripCount, BB->getParent(),
2220 NextBB, NextBB, Name);
2221 BasicBlock *After = CL->getAfter();
2222
2223 // If location is not set, don't connect the loop.
2224 if (updateToLocation(Loc)) {
2225 // Split the loop at the insertion point: Branch to the preheader and move
2226 // every following instruction to after the loop (the After BB). Also, the
2227 // new successor is the loop's after block.
2228 spliceBB(Builder, After, /*CreateBranch=*/false);
2230 }
2231
2232 // Emit the body content. We do it after connecting the loop to the CFG to
2233 // avoid that the callback encounters degenerate BBs.
2234 BodyGenCB(CL->getBodyIP(), CL->getIndVar());
2235
2236#ifndef NDEBUG
2237 CL->assertOK();
2238#endif
2239 return CL;
2240}
2241
2243 const LocationDescription &Loc, LoopBodyGenCallbackTy BodyGenCB,
2244 Value *Start, Value *Stop, Value *Step, bool IsSigned, bool InclusiveStop,
2245 InsertPointTy ComputeIP, const Twine &Name) {
2246
2247 // Consider the following difficulties (assuming 8-bit signed integers):
2248 // * Adding \p Step to the loop counter which passes \p Stop may overflow:
2249 // DO I = 1, 100, 50
2250 /// * A \p Step of INT_MIN cannot not be normalized to a positive direction:
2251 // DO I = 100, 0, -128
2252
2253 // Start, Stop and Step must be of the same integer type.
2254 auto *IndVarTy = cast<IntegerType>(Start->getType());
2255 assert(IndVarTy == Stop->getType() && "Stop type mismatch");
2256 assert(IndVarTy == Step->getType() && "Step type mismatch");
2257
2258 LocationDescription ComputeLoc =
2259 ComputeIP.isSet() ? LocationDescription(ComputeIP, Loc.DL) : Loc;
2260 updateToLocation(ComputeLoc);
2261
2262 ConstantInt *Zero = ConstantInt::get(IndVarTy, 0);
2263 ConstantInt *One = ConstantInt::get(IndVarTy, 1);
2264
2265 // Like Step, but always positive.
2266 Value *Incr = Step;
2267
2268 // Distance between Start and Stop; always positive.
2269 Value *Span;
2270
2271 // Condition whether there are no iterations are executed at all, e.g. because
2272 // UB < LB.
2273 Value *ZeroCmp;
2274
2275 if (IsSigned) {
2276 // Ensure that increment is positive. If not, negate and invert LB and UB.
2277 Value *IsNeg = Builder.CreateICmpSLT(Step, Zero);
2278 Incr = Builder.CreateSelect(IsNeg, Builder.CreateNeg(Step), Step);
2279 Value *LB = Builder.CreateSelect(IsNeg, Stop, Start);
2280 Value *UB = Builder.CreateSelect(IsNeg, Start, Stop);
2281 Span = Builder.CreateSub(UB, LB, "", false, true);
2282 ZeroCmp = Builder.CreateICmp(
2283 InclusiveStop ? CmpInst::ICMP_SLT : CmpInst::ICMP_SLE, UB, LB);
2284 } else {
2285 Span = Builder.CreateSub(Stop, Start, "", true);
2286 ZeroCmp = Builder.CreateICmp(
2287 InclusiveStop ? CmpInst::ICMP_ULT : CmpInst::ICMP_ULE, Stop, Start);
2288 }
2289
2290 Value *CountIfLooping;
2291 if (InclusiveStop) {
2292 CountIfLooping = Builder.CreateAdd(Builder.CreateUDiv(Span, Incr), One);
2293 } else {
2294 // Avoid incrementing past stop since it could overflow.
2295 Value *CountIfTwo = Builder.CreateAdd(
2296 Builder.CreateUDiv(Builder.CreateSub(Span, One), Incr), One);
2297 Value *OneCmp = Builder.CreateICmp(CmpInst::ICMP_ULE, Span, Incr);
2298 CountIfLooping = Builder.CreateSelect(OneCmp, One, CountIfTwo);
2299 }
2300 Value *TripCount = Builder.CreateSelect(ZeroCmp, Zero, CountIfLooping,
2301 "omp_" + Name + ".tripcount");
2302
2303 auto BodyGen = [=](InsertPointTy CodeGenIP, Value *IV) {
2304 Builder.restoreIP(CodeGenIP);
2305 Value *Span = Builder.CreateMul(IV, Step);
2306 Value *IndVar = Builder.CreateAdd(Span, Start);
2307 BodyGenCB(Builder.saveIP(), IndVar);
2308 };
2309 LocationDescription LoopLoc = ComputeIP.isSet() ? Loc.IP : Builder.saveIP();
2310 return createCanonicalLoop(LoopLoc, BodyGen, TripCount, Name);
2311}
2312
2313// Returns an LLVM function to call for initializing loop bounds using OpenMP
2314// static scheduling depending on `type`. Only i32 and i64 are supported by the
2315// runtime. Always interpret integers as unsigned similarly to
2316// CanonicalLoopInfo.
2318 OpenMPIRBuilder &OMPBuilder) {
2319 unsigned Bitwidth = Ty->getIntegerBitWidth();
2320 if (Bitwidth == 32)
2321 return OMPBuilder.getOrCreateRuntimeFunction(
2322 M, omp::RuntimeFunction::OMPRTL___kmpc_for_static_init_4u);
2323 if (Bitwidth == 64)
2324 return OMPBuilder.getOrCreateRuntimeFunction(
2325 M, omp::RuntimeFunction::OMPRTL___kmpc_for_static_init_8u);
2326 llvm_unreachable("unknown OpenMP loop iterator bitwidth");
2327}
2328
2330OpenMPIRBuilder::applyStaticWorkshareLoop(DebugLoc DL, CanonicalLoopInfo *CLI,
2331 InsertPointTy AllocaIP,
2332 bool NeedsBarrier) {
2333 assert(CLI->isValid() && "Requires a valid canonical loop");
2334 assert(!isConflictIP(AllocaIP, CLI->getPreheaderIP()) &&
2335 "Require dedicated allocate IP");
2336
2337 // Set up the source location value for OpenMP runtime.
2340
2341 uint32_t SrcLocStrSize;
2342 Constant *SrcLocStr = getOrCreateSrcLocStr(DL, SrcLocStrSize);
2343 Value *SrcLoc = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
2344
2345 // Declare useful OpenMP runtime functions.
2346 Value *IV = CLI->getIndVar();
2347 Type *IVTy = IV->getType();
2348 FunctionCallee StaticInit = getKmpcForStaticInitForType(IVTy, M, *this);
2349 FunctionCallee StaticFini =
2350 getOrCreateRuntimeFunction(M, omp::OMPRTL___kmpc_for_static_fini);
2351
2352 // Allocate space for computed loop bounds as expected by the "init" function.
2353 Builder.restoreIP(AllocaIP);
2354 Type *I32Type = Type::getInt32Ty(M.getContext());
2355 Value *PLastIter = Builder.CreateAlloca(I32Type, nullptr, "p.lastiter");
2356 Value *PLowerBound = Builder.CreateAlloca(IVTy, nullptr, "p.lowerbound");
2357 Value *PUpperBound = Builder.CreateAlloca(IVTy, nullptr, "p.upperbound");
2358 Value *PStride = Builder.CreateAlloca(IVTy, nullptr, "p.stride");
2359
2360 // At the end of the preheader, prepare for calling the "init" function by
2361 // storing the current loop bounds into the allocated space. A canonical loop
2362 // always iterates from 0 to trip-count with step 1. Note that "init" expects
2363 // and produces an inclusive upper bound.
2365 Constant *Zero = ConstantInt::get(IVTy, 0);
2366 Constant *One = ConstantInt::get(IVTy, 1);
2367 Builder.CreateStore(Zero, PLowerBound);
2368 Value *UpperBound = Builder.CreateSub(CLI->getTripCount(), One);
2369 Builder.CreateStore(UpperBound, PUpperBound);
2370 Builder.CreateStore(One, PStride);
2371
2372 Value *ThreadNum = getOrCreateThreadID(SrcLoc);
2373
2374 Constant *SchedulingType = ConstantInt::get(
2375 I32Type, static_cast<int>(OMPScheduleType::UnorderedStatic));
2376
2377 // Call the "init" function and update the trip count of the loop with the
2378 // value it produced.
2379 Builder.CreateCall(StaticInit,
2380 {SrcLoc, ThreadNum, SchedulingType, PLastIter, PLowerBound,
2381 PUpperBound, PStride, One, Zero});
2382 Value *LowerBound = Builder.CreateLoad(IVTy, PLowerBound);
2383 Value *InclusiveUpperBound = Builder.CreateLoad(IVTy, PUpperBound);
2384 Value *TripCountMinusOne = Builder.CreateSub(InclusiveUpperBound, LowerBound);
2385 Value *TripCount = Builder.CreateAdd(TripCountMinusOne, One);
2386 CLI->setTripCount(TripCount);
2387
2388 // Update all uses of the induction variable except the one in the condition
2389 // block that compares it with the actual upper bound, and the increment in
2390 // the latch block.
2391
2392 CLI->mapIndVar([&](Instruction *OldIV) -> Value * {
2394 CLI->getBody()->getFirstInsertionPt());
2396 return Builder.CreateAdd(OldIV, LowerBound);
2397 });
2398
2399 // In the "exit" block, call the "fini" function.
2401 CLI->getExit()->getTerminator()->getIterator());
2402 Builder.CreateCall(StaticFini, {SrcLoc, ThreadNum});
2403
2404 // Add the barrier if requested.
2405 if (NeedsBarrier)
2406 createBarrier(LocationDescription(Builder.saveIP(), DL),
2407 omp::Directive::OMPD_for, /* ForceSimpleCall */ false,
2408 /* CheckCancelFlag */ false);
2409
2410 InsertPointTy AfterIP = CLI->getAfterIP();
2411 CLI->invalidate();
2412
2413 return AfterIP;
2414}
2415
2416OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::applyStaticChunkedWorkshareLoop(
2417 DebugLoc DL, CanonicalLoopInfo *CLI, InsertPointTy AllocaIP,
2418 bool NeedsBarrier, Value *ChunkSize) {
2419 assert(CLI->isValid() && "Requires a valid canonical loop");
2420 assert(ChunkSize && "Chunk size is required");
2421
2422 LLVMContext &Ctx = CLI->getFunction()->getContext();
2423 Value *IV = CLI->getIndVar();
2424 Value *OrigTripCount = CLI->getTripCount();
2425 Type *IVTy = IV->getType();
2426 assert(IVTy->getIntegerBitWidth() <= 64 &&
2427 "Max supported tripcount bitwidth is 64 bits");
2428 Type *InternalIVTy = IVTy->getIntegerBitWidth() <= 32 ? Type::getInt32Ty(Ctx)
2429 : Type::getInt64Ty(Ctx);
2430 Type *I32Type = Type::getInt32Ty(M.getContext());
2431 Constant *Zero = ConstantInt::get(InternalIVTy, 0);
2432 Constant *One = ConstantInt::get(InternalIVTy, 1);
2433
2434 // Declare useful OpenMP runtime functions.
2435 FunctionCallee StaticInit =
2436 getKmpcForStaticInitForType(InternalIVTy, M, *this);
2437 FunctionCallee StaticFini =
2438 getOrCreateRuntimeFunction(M, omp::OMPRTL___kmpc_for_static_fini);
2439
2440 // Allocate space for computed loop bounds as expected by the "init" function.
2441 Builder.restoreIP(AllocaIP);
2443 Value *PLastIter = Builder.CreateAlloca(I32Type, nullptr, "p.lastiter");
2444 Value *PLowerBound =
2445 Builder.CreateAlloca(InternalIVTy, nullptr, "p.lowerbound");
2446 Value *PUpperBound =
2447 Builder.CreateAlloca(InternalIVTy, nullptr, "p.upperbound");
2448 Value *PStride = Builder.CreateAlloca(InternalIVTy, nullptr, "p.stride");
2449
2450 // Set up the source location value for the OpenMP runtime.
2453
2454 // TODO: Detect overflow in ubsan or max-out with current tripcount.
2455 Value *CastedChunkSize =
2456 Builder.CreateZExtOrTrunc(ChunkSize, InternalIVTy, "chunksize");
2457 Value *CastedTripCount =
2458 Builder.CreateZExt(OrigTripCount, InternalIVTy, "tripcount");
2459
2460 Constant *SchedulingType = ConstantInt::get(
2461 I32Type, static_cast<int>(OMPScheduleType::UnorderedStaticChunked));
2462 Builder.CreateStore(Zero, PLowerBound);
2463 Value *OrigUpperBound = Builder.CreateSub(CastedTripCount, One);
2464 Builder.CreateStore(OrigUpperBound, PUpperBound);
2465 Builder.CreateStore(One, PStride);
2466
2467 // Call the "init" function and update the trip count of the loop with the
2468 // value it produced.
2469 uint32_t SrcLocStrSize;
2470 Constant *SrcLocStr = getOrCreateSrcLocStr(DL, SrcLocStrSize);
2471 Value *SrcLoc = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
2472 Value *ThreadNum = getOrCreateThreadID(SrcLoc);
2473 Builder.CreateCall(StaticInit,
2474 {/*loc=*/SrcLoc, /*global_tid=*/ThreadNum,
2475 /*schedtype=*/SchedulingType, /*plastiter=*/PLastIter,
2476 /*plower=*/PLowerBound, /*pupper=*/PUpperBound,
2477 /*pstride=*/PStride, /*incr=*/One,
2478 /*chunk=*/CastedChunkSize});
2479
2480 // Load values written by the "init" function.
2481 Value *FirstChunkStart =
2482 Builder.CreateLoad(InternalIVTy, PLowerBound, "omp_firstchunk.lb");
2483 Value *FirstChunkStop =
2484 Builder.CreateLoad(InternalIVTy, PUpperBound, "omp_firstchunk.ub");
2485 Value *FirstChunkEnd = Builder.CreateAdd(FirstChunkStop, One);
2486 Value *ChunkRange =
2487 Builder.CreateSub(FirstChunkEnd, FirstChunkStart, "omp_chunk.range");
2488 Value *NextChunkStride =
2489 Builder.CreateLoad(InternalIVTy, PStride, "omp_dispatch.stride");
2490
2491 // Create outer "dispatch" loop for enumerating the chunks.
2492 BasicBlock *DispatchEnter = splitBB(Builder, true);
2493 Value *DispatchCounter;
2495 {Builder.saveIP(), DL},
2496 [&](InsertPointTy BodyIP, Value *Counter) { DispatchCounter = Counter; },
2497 FirstChunkStart, CastedTripCount, NextChunkStride,
2498 /*IsSigned=*/false, /*InclusiveStop=*/false, /*ComputeIP=*/{},
2499 "dispatch");
2500
2501 // Remember the BasicBlocks of the dispatch loop we need, then invalidate to
2502 // not have to preserve the canonical invariant.
2503 BasicBlock *DispatchBody = DispatchCLI->getBody();
2504 BasicBlock *DispatchLatch = DispatchCLI->getLatch();
2505 BasicBlock *DispatchExit = DispatchCLI->getExit();
2506 BasicBlock *DispatchAfter = DispatchCLI->getAfter();
2507 DispatchCLI->invalidate();
2508
2509 // Rewire the original loop to become the chunk loop inside the dispatch loop.
2510 redirectTo(DispatchAfter, CLI->getAfter(), DL);
2511 redirectTo(CLI->getExit(), DispatchLatch, DL);
2512 redirectTo(DispatchBody, DispatchEnter, DL);
2513
2514 // Prepare the prolog of the chunk loop.
2517
2518 // Compute the number of iterations of the chunk loop.
2520 Value *ChunkEnd = Builder.CreateAdd(DispatchCounter, ChunkRange);
2521 Value *IsLastChunk =
2522 Builder.CreateICmpUGE(ChunkEnd, CastedTripCount, "omp_chunk.is_last");
2523 Value *CountUntilOrigTripCount =
2524 Builder.CreateSub(CastedTripCount, DispatchCounter);
2525 Value *ChunkTripCount = Builder.CreateSelect(
2526 IsLastChunk, CountUntilOrigTripCount, ChunkRange, "omp_chunk.tripcount");
2527 Value *BackcastedChunkTC =
2528 Builder.CreateTrunc(ChunkTripCount, IVTy, "omp_chunk.tripcount.trunc");
2529 CLI->setTripCount(BackcastedChunkTC);
2530
2531 // Update all uses of the induction variable except the one in the condition
2532 // block that compares it with the actual upper bound, and the increment in
2533 // the latch block.
2534 Value *BackcastedDispatchCounter =
2535 Builder.CreateTrunc(DispatchCounter, IVTy, "omp_dispatch.iv.trunc");
2536 CLI->mapIndVar([&](Instruction *) -> Value * {
2537 Builder.restoreIP(CLI->getBodyIP());
2538 return Builder.CreateAdd(IV, BackcastedDispatchCounter);
2539 });
2540
2541 // In the "exit" block, call the "fini" function.
2542 Builder.SetInsertPoint(DispatchExit, DispatchExit->getFirstInsertionPt());
2543 Builder.CreateCall(StaticFini, {SrcLoc, ThreadNum});
2544
2545 // Add the barrier if requested.
2546 if (NeedsBarrier)
2547 createBarrier(LocationDescription(Builder.saveIP(), DL), OMPD_for,
2548 /*ForceSimpleCall=*/false, /*CheckCancelFlag=*/false);
2549
2550#ifndef NDEBUG
2551 // Even though we currently do not support applying additional methods to it,
2552 // the chunk loop should remain a canonical loop.
2553 CLI->assertOK();
2554#endif
2555
2556 return {DispatchAfter, DispatchAfter->getFirstInsertionPt()};
2557}
2558
2561 bool NeedsBarrier, llvm::omp::ScheduleKind SchedKind,
2562 llvm::Value *ChunkSize, bool HasSimdModifier, bool HasMonotonicModifier,
2563 bool HasNonmonotonicModifier, bool HasOrderedClause) {
2564 OMPScheduleType EffectiveScheduleType = computeOpenMPScheduleType(
2565 SchedKind, ChunkSize, HasSimdModifier, HasMonotonicModifier,
2566 HasNonmonotonicModifier, HasOrderedClause);
2567
2568 bool IsOrdered = (EffectiveScheduleType & OMPScheduleType::ModifierOrdered) ==
2569 OMPScheduleType::ModifierOrdered;
2570 switch (EffectiveScheduleType & ~OMPScheduleType::ModifierMask) {
2571 case OMPScheduleType::BaseStatic:
2572 assert(!ChunkSize && "No chunk size with static-chunked schedule");
2573 if (IsOrdered)
2574 return applyDynamicWorkshareLoop(DL, CLI, AllocaIP, EffectiveScheduleType,
2575 NeedsBarrier, ChunkSize);
2576 // FIXME: Monotonicity ignored?
2577 return applyStaticWorkshareLoop(DL, CLI, AllocaIP, NeedsBarrier);
2578
2579 case OMPScheduleType::BaseStaticChunked:
2580 if (IsOrdered)
2581 return applyDynamicWorkshareLoop(DL, CLI, AllocaIP, EffectiveScheduleType,
2582 NeedsBarrier, ChunkSize);
2583 // FIXME: Monotonicity ignored?
2584 return applyStaticChunkedWorkshareLoop(DL, CLI, AllocaIP, NeedsBarrier,
2585 ChunkSize);
2586
2587 case OMPScheduleType::BaseRuntime:
2588 case OMPScheduleType::BaseAuto:
2589 case OMPScheduleType::BaseGreedy:
2590 case OMPScheduleType::BaseBalanced:
2591 case OMPScheduleType::BaseSteal:
2592 case OMPScheduleType::BaseGuidedSimd:
2593 case OMPScheduleType::BaseRuntimeSimd:
2594 assert(!ChunkSize &&
2595 "schedule type does not support user-defined chunk sizes");
2596 [[fallthrough]];
2597 case OMPScheduleType::BaseDynamicChunked:
2598 case OMPScheduleType::BaseGuidedChunked:
2599 case OMPScheduleType::BaseGuidedIterativeChunked:
2600 case OMPScheduleType::BaseGuidedAnalyticalChunked:
2601 case OMPScheduleType::BaseStaticBalancedChunked:
2602 return applyDynamicWorkshareLoop(DL, CLI, AllocaIP, EffectiveScheduleType,
2603 NeedsBarrier, ChunkSize);
2604
2605 default:
2606 llvm_unreachable("Unknown/unimplemented schedule kind");
2607 }
2608}
2609
2610/// Returns an LLVM function to call for initializing loop bounds using OpenMP
2611/// dynamic scheduling depending on `type`. Only i32 and i64 are supported by
2612/// the runtime. Always interpret integers as unsigned similarly to
2613/// CanonicalLoopInfo.
2614static FunctionCallee
2616 unsigned Bitwidth = Ty->getIntegerBitWidth();
2617 if (Bitwidth == 32)
2618 return OMPBuilder.getOrCreateRuntimeFunction(
2619 M, omp::RuntimeFunction::OMPRTL___kmpc_dispatch_init_4u);
2620 if (Bitwidth == 64)
2621 return OMPBuilder.getOrCreateRuntimeFunction(
2622 M, omp::RuntimeFunction::OMPRTL___kmpc_dispatch_init_8u);
2623 llvm_unreachable("unknown OpenMP loop iterator bitwidth");
2624}
2625
2626/// Returns an LLVM function to call for updating the next loop using OpenMP
2627/// dynamic scheduling depending on `type`. Only i32 and i64 are supported by
2628/// the runtime. Always interpret integers as unsigned similarly to
2629/// CanonicalLoopInfo.
2630static FunctionCallee
2632 unsigned Bitwidth = Ty->getIntegerBitWidth();
2633 if (Bitwidth == 32)
2634 return OMPBuilder.getOrCreateRuntimeFunction(
2635 M, omp::RuntimeFunction::OMPRTL___kmpc_dispatch_next_4u);
2636 if (Bitwidth == 64)
2637 return OMPBuilder.getOrCreateRuntimeFunction(
2638 M, omp::RuntimeFunction::OMPRTL___kmpc_dispatch_next_8u);
2639 llvm_unreachable("unknown OpenMP loop iterator bitwidth");
2640}
2641
2642/// Returns an LLVM function to call for finalizing the dynamic loop using
2643/// depending on `type`. Only i32 and i64 are supported by the runtime. Always
2644/// interpret integers as unsigned similarly to CanonicalLoopInfo.
2645static FunctionCallee
2647 unsigned Bitwidth = Ty->getIntegerBitWidth();
2648 if (Bitwidth == 32)
2649 return OMPBuilder.getOrCreateRuntimeFunction(
2650 M, omp::RuntimeFunction::OMPRTL___kmpc_dispatch_fini_4u);
2651 if (Bitwidth == 64)
2652 return OMPBuilder.getOrCreateRuntimeFunction(
2653 M, omp::RuntimeFunction::OMPRTL___kmpc_dispatch_fini_8u);
2654 llvm_unreachable("unknown OpenMP loop iterator bitwidth");
2655}
2656
2657OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::applyDynamicWorkshareLoop(
2658 DebugLoc DL, CanonicalLoopInfo *CLI, InsertPointTy AllocaIP,
2659 OMPScheduleType SchedType, bool NeedsBarrier, Value *Chunk) {
2660 assert(CLI->isValid() && "Requires a valid canonical loop");
2661 assert(!isConflictIP(AllocaIP, CLI->getPreheaderIP()) &&
2662 "Require dedicated allocate IP");
2664 "Require valid schedule type");
2665
2666 bool Ordered = (SchedType & OMPScheduleType::ModifierOrdered) ==
2667 OMPScheduleType::ModifierOrdered;
2668
2669 // Set up the source location value for OpenMP runtime.
2671
2672 uint32_t SrcLocStrSize;
2673 Constant *SrcLocStr = getOrCreateSrcLocStr(DL, SrcLocStrSize);
2674 Value *SrcLoc = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
2675
2676 // Declare useful OpenMP runtime functions.
2677 Value *IV = CLI->getIndVar();
2678 Type *IVTy = IV->getType();
2679 FunctionCallee DynamicInit = getKmpcForDynamicInitForType(IVTy, M, *this);
2680 FunctionCallee DynamicNext = getKmpcForDynamicNextForType(IVTy, M, *this);
2681
2682 // Allocate space for computed loop bounds as expected by the "init" function.
2683 Builder.restoreIP(AllocaIP);
2684 Type *I32Type = Type::getInt32Ty(M.getContext());
2685 Value *PLastIter = Builder.CreateAlloca(I32Type, nullptr, "p.lastiter");
2686 Value *PLowerBound = Builder.CreateAlloca(IVTy, nullptr, "p.lowerbound");
2687 Value *PUpperBound = Builder.CreateAlloca(IVTy, nullptr, "p.upperbound");
2688 Value *PStride = Builder.CreateAlloca(IVTy, nullptr, "p.stride");
2689
2690 // At the end of the preheader, prepare for calling the "init" function by
2691 // storing the current loop bounds into the allocated space. A canonical loop
2692 // always iterates from 0 to trip-count with step 1. Note that "init" expects
2693 // and produces an inclusive upper bound.
2694 BasicBlock *PreHeader = CLI->getPreheader();
2695 Builder.SetInsertPoint(PreHeader->getTerminator());
2696 Constant *One = ConstantInt::get(IVTy, 1);
2697 Builder.CreateStore(One, PLowerBound);
2698 Value *UpperBound = CLI->getTripCount();
2699 Builder.CreateStore(UpperBound, PUpperBound);
2700 Builder.CreateStore(One, PStride);
2701
2702 BasicBlock *Header = CLI->getHeader();
2703 BasicBlock *Exit = CLI->getExit();
2704 BasicBlock *Cond = CLI->getCond();
2705 BasicBlock *Latch = CLI->getLatch();
2706 InsertPointTy AfterIP = CLI->getAfterIP();
2707
2708 // The CLI will be "broken" in the code below, as the loop is no longer
2709 // a valid canonical loop.
2710
2711 if (!Chunk)
2712 Chunk = One;
2713
2714 Value *ThreadNum = getOrCreateThreadID(SrcLoc);
2715
2716 Constant *SchedulingType =
2717 ConstantInt::get(I32Type, static_cast<int>(SchedType));
2718
2719 // Call the "init" function.
2720 Builder.CreateCall(DynamicInit,
2721 {SrcLoc, ThreadNum, SchedulingType, /* LowerBound */ One,
2722 UpperBound, /* step */ One, Chunk});
2723
2724 // An outer loop around the existing one.
2725 BasicBlock *OuterCond = BasicBlock::Create(
2726 PreHeader->getContext(), Twine(PreHeader->getName()) + ".outer.cond",
2727 PreHeader->getParent());
2728 // This needs to be 32-bit always, so can't use the IVTy Zero above.
2729 Builder.SetInsertPoint(OuterCond, OuterCond->getFirstInsertionPt());
2730 Value *Res =
2731 Builder.CreateCall(DynamicNext, {SrcLoc, ThreadNum, PLastIter,
2732 PLowerBound, PUpperBound, PStride});
2733 Constant *Zero32 = ConstantInt::get(I32Type, 0);
2734 Value *MoreWork = Builder.CreateCmp(CmpInst::ICMP_NE, Res, Zero32);
2735 Value *LowerBound =
2736 Builder.CreateSub(Builder.CreateLoad(IVTy, PLowerBound), One, "lb");
2737 Builder.CreateCondBr(MoreWork, Header, Exit);
2738
2739 // Change PHI-node in loop header to use outer cond rather than preheader,
2740 // and set IV to the LowerBound.
2741 Instruction *Phi = &Header->front();
2742 auto *PI = cast<PHINode>(Phi);
2743 PI->setIncomingBlock(0, OuterCond);
2744 PI->setIncomingValue(0, LowerBound);
2745
2746 // Then set the pre-header to jump to the OuterCond
2747 Instruction *Term = PreHeader->getTerminator();
2748 auto *Br = cast<BranchInst>(Term);
2749 Br->setSuccessor(0, OuterCond);
2750
2751 // Modify the inner condition:
2752 // * Use the UpperBound returned from the DynamicNext call.
2753 // * jump to the loop outer loop when done with one of the inner loops.
2754 Builder.SetInsertPoint(Cond, Cond->getFirstInsertionPt());
2755 UpperBound = Builder.CreateLoad(IVTy, PUpperBound, "ub");
2757 auto *CI = cast<CmpInst>(Comp);
2758 CI->setOperand(1, UpperBound);
2759 // Redirect the inner exit to branch to outer condition.
2760 Instruction *Branch = &Cond->back();
2761 auto *BI = cast<BranchInst>(Branch);
2762 assert(BI->getSuccessor(1) == Exit);
2763 BI->setSuccessor(1, OuterCond);
2764
2765 // Call the "fini" function if "ordered" is present in wsloop directive.
2766 if (Ordered) {
2767 Builder.SetInsertPoint(&Latch->back());
2768 FunctionCallee DynamicFini = getKmpcForDynamicFiniForType(IVTy, M, *this);
2769 Builder.CreateCall(DynamicFini, {SrcLoc, ThreadNum});
2770 }
2771
2772 // Add the barrier if requested.
2773 if (NeedsBarrier) {
2774 Builder.SetInsertPoint(&Exit->back());
2775 createBarrier(LocationDescription(Builder.saveIP(), DL),
2776 omp::Directive::OMPD_for, /* ForceSimpleCall */ false,
2777 /* CheckCancelFlag */ false);
2778 }
2779
2780 CLI->invalidate();
2781 return AfterIP;
2782}
2783
2784/// Redirect all edges that branch to \p OldTarget to \p NewTarget. That is,
2785/// after this \p OldTarget will be orphaned.
2787 BasicBlock *NewTarget, DebugLoc DL) {
2788 for (BasicBlock *Pred : make_early_inc_range(predecessors(OldTarget)))
2789 redirectTo(Pred, NewTarget, DL);
2790}
2791
2792/// Determine which blocks in \p BBs are reachable from outside and remove the
2793/// ones that are not reachable from the function.
2795 SmallPtrSet<BasicBlock *, 6> BBsToErase{BBs.begin(), BBs.end()};
2796 auto HasRemainingUses = [&BBsToErase](BasicBlock *BB) {
2797 for (Use &U : BB->uses()) {
2798 auto *UseInst = dyn_cast<Instruction>(U.getUser());
2799 if (!UseInst)
2800 continue;
2801 if (BBsToErase.count(UseInst->getParent()))
2802 continue;
2803 return true;
2804 }
2805 return false;
2806 };
2807
2808 while (true) {
2809 bool Changed = false;
2810 for (BasicBlock *BB : make_early_inc_range(BBsToErase)) {
2811 if (HasRemainingUses(BB)) {
2812 BBsToErase.erase(BB);
2813 Changed = true;
2814 }
2815 }
2816 if (!Changed)
2817 break;
2818 }
2819
2820 SmallVector<BasicBlock *, 7> BBVec(BBsToErase.begin(), BBsToErase.end());
2821 DeleteDeadBlocks(BBVec);
2822}
2823
2826 InsertPointTy ComputeIP) {
2827 assert(Loops.size() >= 1 && "At least one loop required");
2828 size_t NumLoops = Loops.size();
2829
2830 // Nothing to do if there is already just one loop.
2831 if (NumLoops == 1)
2832 return Loops.front();
2833
2834 CanonicalLoopInfo *Outermost = Loops.front();
2835 CanonicalLoopInfo *Innermost = Loops.back();
2836 BasicBlock *OrigPreheader = Outermost->getPreheader();
2837 BasicBlock *OrigAfter = Outermost->getAfter();
2838 Function *F = OrigPreheader->getParent();
2839
2840 // Loop control blocks that may become orphaned later.
2841 SmallVector<BasicBlock *, 12> OldControlBBs;
2842 OldControlBBs.reserve(6 * Loops.size());
2844 Loop->collectControlBlocks(OldControlBBs);
2845
2846 // Setup the IRBuilder for inserting the trip count computation.
2848 if (ComputeIP.isSet())
2849 Builder.restoreIP(ComputeIP);
2850 else
2851 Builder.restoreIP(Outermost->getPreheaderIP());
2852
2853 // Derive the collapsed' loop trip count.
2854 // TODO: Find common/largest indvar type.
2855 Value *CollapsedTripCount = nullptr;
2856 for (CanonicalLoopInfo *L : Loops) {
2857 assert(L->isValid() &&
2858 "All loops to collapse must be valid canonical loops");
2859 Value *OrigTripCount = L->getTripCount();
2860 if (!CollapsedTripCount) {
2861 CollapsedTripCount = OrigTripCount;
2862 continue;
2863 }
2864
2865 // TODO: Enable UndefinedSanitizer to diagnose an overflow here.
2866 CollapsedTripCount = Builder.CreateMul(CollapsedTripCount, OrigTripCount,
2867 {}, /*HasNUW=*/true);
2868 }
2869
2870 // Create the collapsed loop control flow.
2871 CanonicalLoopInfo *Result =
2872 createLoopSkeleton(DL, CollapsedTripCount, F,
2873 OrigPreheader->getNextNode(), OrigAfter, "collapsed");
2874
2875 // Build the collapsed loop body code.
2876 // Start with deriving the input loop induction variables from the collapsed
2877 // one, using a divmod scheme. To preserve the original loops' order, the
2878 // innermost loop use the least significant bits.
2879 Builder.restoreIP(Result->getBodyIP());
2880
2881 Value *Leftover = Result->getIndVar();
2882 SmallVector<Value *> NewIndVars;
2883 NewIndVars.resize(NumLoops);
2884 for (int i = NumLoops - 1; i >= 1; --i) {
2885 Value *OrigTripCount = Loops[i]->getTripCount();
2886
2887 Value *NewIndVar = Builder.CreateURem(Leftover, OrigTripCount);
2888 NewIndVars[i] = NewIndVar;
2889
2890 Leftover = Builder.CreateUDiv(Leftover, OrigTripCount);
2891 }
2892 // Outermost loop gets all the remaining bits.
2893 NewIndVars[0] = Leftover;
2894
2895 // Construct the loop body control flow.
2896 // We progressively construct the branch structure following in direction of
2897 // the control flow, from the leading in-between code, the loop nest body, the
2898 // trailing in-between code, and rejoining the collapsed loop's latch.
2899 // ContinueBlock and ContinuePred keep track of the source(s) of next edge. If
2900 // the ContinueBlock is set, continue with that block. If ContinuePred, use
2901 // its predecessors as sources.
2902 BasicBlock *ContinueBlock = Result->getBody();
2903 BasicBlock *ContinuePred = nullptr;
2904 auto ContinueWith = [&ContinueBlock, &ContinuePred, DL](BasicBlock *Dest,
2905 BasicBlock *NextSrc) {
2906 if (ContinueBlock)
2907 redirectTo(ContinueBlock, Dest, DL);
2908 else
2909 redirectAllPredecessorsTo(ContinuePred, Dest, DL);
2910
2911 ContinueBlock = nullptr;
2912 ContinuePred = NextSrc;
2913 };
2914
2915 // The code before the nested loop of each level.
2916 // Because we are sinking it into the nest, it will be executed more often
2917 // that the original loop. More sophisticated schemes could keep track of what
2918 // the in-between code is and instantiate it only once per thread.
2919 for (size_t i = 0; i < NumLoops - 1; ++i)
2920 ContinueWith(Loops[i]->getBody(), Loops[i + 1]->getHeader());
2921
2922 // Connect the loop nest body.
2923 ContinueWith(Innermost->getBody(), Innermost->getLatch());
2924
2925 // The code after the nested loop at each level.
2926 for (size_t i = NumLoops - 1; i > 0; --i)
2927 ContinueWith(Loops[i]->getAfter(), Loops[i - 1]->getLatch());
2928
2929 // Connect the finished loop to the collapsed loop latch.
2930 ContinueWith(Result->getLatch(), nullptr);
2931
2932 // Replace the input loops with the new collapsed loop.
2933 redirectTo(Outermost->getPreheader(), Result->getPreheader(), DL);
2934 redirectTo(Result->getAfter(), Outermost->getAfter(), DL);
2935
2936 // Replace the input loop indvars with the derived ones.
2937 for (size_t i = 0; i < NumLoops; ++i)
2938 Loops[i]->getIndVar()->replaceAllUsesWith(NewIndVars[i]);
2939
2940 // Remove unused parts of the input loops.
2941 removeUnusedBlocksFromParent(OldControlBBs);
2942
2943 for (CanonicalLoopInfo *L : Loops)
2944 L->invalidate();
2945
2946#ifndef NDEBUG
2947 Result->assertOK();
2948#endif
2949 return Result;
2950}
2951
2952std::vector<CanonicalLoopInfo *>
2954 ArrayRef<Value *> TileSizes) {
2955 assert(TileSizes.size() == Loops.size() &&
2956 "Must pass as many tile sizes as there are loops");
2957 int NumLoops = Loops.size();
2958 assert(NumLoops >= 1 && "At least one loop to tile required");
2959
2960 CanonicalLoopInfo *OutermostLoop = Loops.front();
2961 CanonicalLoopInfo *InnermostLoop = Loops.back();
2962 Function *F = OutermostLoop->getBody()->getParent();
2963 BasicBlock *InnerEnter = InnermostLoop->getBody();
2964 BasicBlock *InnerLatch = InnermostLoop->getLatch();
2965
2966 // Loop control blocks that may become orphaned later.
2967 SmallVector<BasicBlock *, 12> OldControlBBs;
2968 OldControlBBs.reserve(6 * Loops.size());
2970 Loop->collectControlBlocks(OldControlBBs);
2971
2972 // Collect original trip counts and induction variable to be accessible by
2973 // index. Also, the structure of the original loops is not preserved during
2974 // the construction of the tiled loops, so do it before we scavenge the BBs of
2975 // any original CanonicalLoopInfo.
2976 SmallVector<Value *, 4> OrigTripCounts, OrigIndVars;
2977 for (CanonicalLoopInfo *L : Loops) {
2978 assert(L->isValid() && "All input loops must be valid canonical loops");
2979 OrigTripCounts.push_back(L->getTripCount());
2980 OrigIndVars.push_back(L->getIndVar());
2981 }
2982
2983 // Collect the code between loop headers. These may contain SSA definitions
2984 // that are used in the loop nest body. To be usable with in the innermost
2985 // body, these BasicBlocks will be sunk into the loop nest body. That is,
2986 // these instructions may be executed more often than before the tiling.
2987 // TODO: It would be sufficient to only sink them into body of the
2988 // corresponding tile loop.
2990 for (int i = 0; i < NumLoops - 1; ++i) {
2991 CanonicalLoopInfo *Surrounding = Loops[i];
2992 CanonicalLoopInfo *Nested = Loops[i + 1];
2993
2994 BasicBlock *EnterBB = Surrounding->getBody();
2995 BasicBlock *ExitBB = Nested->getHeader();
2996 InbetweenCode.emplace_back(EnterBB, ExitBB);
2997 }
2998
2999 // Compute the trip counts of the floor loops.
3001 Builder.restoreIP(OutermostLoop->getPreheaderIP());
3002 SmallVector<Value *, 4> FloorCount, FloorRems;
3003 for (int i = 0; i < NumLoops; ++i) {
3004 Value *TileSize = TileSizes[i];
3005 Value *OrigTripCount = OrigTripCounts[i];
3006 Type *IVType = OrigTripCount->getType();
3007
3008 Value *FloorTripCount = Builder.CreateUDiv(OrigTripCount, TileSize);
3009 Value *FloorTripRem = Builder.CreateURem(OrigTripCount, TileSize);
3010
3011 // 0 if tripcount divides the tilesize, 1 otherwise.
3012 // 1 means we need an additional iteration for a partial tile.
3013 //
3014 // Unfortunately we cannot just use the roundup-formula
3015 // (tripcount + tilesize - 1)/tilesize
3016 // because the summation might overflow. We do not want introduce undefined
3017 // behavior when the untiled loop nest did not.
3018 Value *FloorTripOverflow =
3019 Builder.CreateICmpNE(FloorTripRem, ConstantInt::get(IVType, 0));
3020
3021 FloorTripOverflow = Builder.CreateZExt(FloorTripOverflow, IVType);
3022 FloorTripCount =
3023 Builder.CreateAdd(FloorTripCount, FloorTripOverflow,
3024 "omp_floor" + Twine(i) + ".tripcount", true);
3025
3026 // Remember some values for later use.
3027 FloorCount.push_back(FloorTripCount);
3028 FloorRems.push_back(FloorTripRem);
3029 }
3030
3031 // Generate the new loop nest, from the outermost to the innermost.
3032 std::vector<CanonicalLoopInfo *> Result;
3033 Result.reserve(NumLoops * 2);
3034
3035 // The basic block of the surrounding loop that enters the nest generated
3036 // loop.
3037 BasicBlock *Enter = OutermostLoop->getPreheader();
3038
3039 // The basic block of the surrounding loop where the inner code should
3040 // continue.
3041 BasicBlock *Continue = OutermostLoop->getAfter();
3042
3043 // Where the next loop basic block should be inserted.
3044 BasicBlock *OutroInsertBefore = InnermostLoop->getExit();
3045
3046 auto EmbeddNewLoop =
3047 [this, DL, F, InnerEnter, &Enter, &Continue, &OutroInsertBefore](
3048 Value *TripCount, const Twine &Name) -> CanonicalLoopInfo * {
3049 CanonicalLoopInfo *EmbeddedLoop = createLoopSkeleton(
3050 DL, TripCount, F, InnerEnter, OutroInsertBefore, Name);
3051 redirectTo(Enter, EmbeddedLoop->getPreheader(), DL);
3052 redirectTo(EmbeddedLoop->getAfter(), Continue, DL);
3053
3054 // Setup the position where the next embedded loop connects to this loop.
3055 Enter = EmbeddedLoop->getBody();
3056 Continue = EmbeddedLoop->getLatch();
3057 OutroInsertBefore = EmbeddedLoop->getLatch();
3058 return EmbeddedLoop;
3059 };
3060
3061 auto EmbeddNewLoops = [&Result, &EmbeddNewLoop](ArrayRef<Value *> TripCounts,
3062 const Twine &NameBase) {
3063 for (auto P : enumerate(TripCounts)) {
3064 CanonicalLoopInfo *EmbeddedLoop =
3065 EmbeddNewLoop(P.value(), NameBase + Twine(P.index()));
3066 Result.push_back(EmbeddedLoop);
3067 }
3068 };
3069
3070 EmbeddNewLoops(FloorCount, "floor");
3071
3072 // Within the innermost floor loop, emit the code that computes the tile
3073 // sizes.
3075 SmallVector<Value *, 4> TileCounts;
3076 for (int i = 0; i < NumLoops; ++i) {
3077 CanonicalLoopInfo *FloorLoop = Result[i];
3078 Value *TileSize = TileSizes[i];
3079
3080 Value *FloorIsEpilogue =
3081 Builder.CreateICmpEQ(FloorLoop->getIndVar(), FloorCount[i]);
3082 Value *TileTripCount =
3083 Builder.CreateSelect(FloorIsEpilogue, FloorRems[i], TileSize);
3084
3085 TileCounts.push_back(TileTripCount);
3086 }
3087
3088 // Create the tile loops.
3089 EmbeddNewLoops(TileCounts, "tile");
3090
3091 // Insert the inbetween code into the body.
3092 BasicBlock *BodyEnter = Enter;
3093 BasicBlock *BodyEntered = nullptr;
3094 for (std::pair<BasicBlock *, BasicBlock *> P : InbetweenCode) {
3095 BasicBlock *EnterBB = P.first;
3096 BasicBlock *ExitBB = P.second;
3097
3098 if (BodyEnter)
3099 redirectTo(BodyEnter, EnterBB, DL);
3100 else
3101 redirectAllPredecessorsTo(BodyEntered, EnterBB, DL);
3102
3103 BodyEnter = nullptr;
3104 BodyEntered = ExitBB;
3105 }
3106
3107 // Append the original loop nest body into the generated loop nest body.
3108 if (BodyEnter)
3109 redirectTo(BodyEnter, InnerEnter, DL);
3110 else
3111 redirectAllPredecessorsTo(BodyEntered, InnerEnter, DL);
3112 redirectAllPredecessorsTo(InnerLatch, Continue, DL);
3113
3114 // Replace the original induction variable with an induction variable computed
3115 // from the tile and floor induction variables.
3116 Builder.restoreIP(Result.back()->getBodyIP());
3117 for (int i = 0; i < NumLoops; ++i) {
3118 CanonicalLoopInfo *FloorLoop = Result[i];
3119 CanonicalLoopInfo *TileLoop = Result[NumLoops + i];
3120 Value *OrigIndVar = OrigIndVars[i];
3121 Value *Size = TileSizes[i];
3122
3123 Value *Scale =
3124 Builder.CreateMul(Size, FloorLoop->getIndVar(), {}, /*HasNUW=*/true);
3125 Value *Shift =
3126 Builder.CreateAdd(Scale, TileLoop->getIndVar(), {}, /*HasNUW=*/true);
3127 OrigIndVar->replaceAllUsesWith(Shift);
3128 }
3129
3130 // Remove unused parts of the original loops.
3131 removeUnusedBlocksFromParent(OldControlBBs);
3132
3133 for (CanonicalLoopInfo *L : Loops)
3134 L->invalidate();
3135
3136#ifndef NDEBUG
3137 for (CanonicalLoopInfo *GenL : Result)
3138 GenL->assertOK();
3139#endif
3140 return Result;
3141}
3142
3143/// Attach metadata \p Properties to the basic block described by \p BB. If the
3144/// basic block already has metadata, the basic block properties are appended.
3146 ArrayRef<Metadata *> Properties) {
3147 // Nothing to do if no property to attach.
3148 if (Properties.empty())
3149 return;
3150
3151 LLVMContext &Ctx = BB->getContext();
3152 SmallVector<Metadata *> NewProperties;
3153 NewProperties.push_back(nullptr);
3154
3155 // If the basic block already has metadata, prepend it to the new metadata.
3156 MDNode *Existing = BB->getTerminator()->getMetadata(LLVMContext::MD_loop);
3157 if (Existing)
3158 append_range(NewProperties, drop_begin(Existing->operands(), 1));
3159
3160 append_range(NewProperties, Properties);
3161 MDNode *BasicBlockID = MDNode::getDistinct(Ctx, NewProperties);
3162 BasicBlockID->replaceOperandWith(0, BasicBlockID);
3163
3164 BB->getTerminator()->setMetadata(LLVMContext::MD_loop, BasicBlockID);
3165}
3166
3167/// Attach loop metadata \p Properties to the loop described by \p Loop. If the
3168/// loop already has metadata, the loop properties are appended.
3170 ArrayRef<Metadata *> Properties) {
3171 assert(Loop->isValid() && "Expecting a valid CanonicalLoopInfo");
3172
3173 // Attach metadata to the loop's latch
3174 BasicBlock *Latch = Loop->getLatch();
3175 assert(Latch && "A valid CanonicalLoopInfo must have a unique latch");
3176 addBasicBlockMetadata(Latch, Properties);
3177}
3178
3179/// Attach llvm.access.group metadata to the memref instructions of \p Block
3180static void addSimdMetadata(BasicBlock *Block, MDNode *AccessGroup,
3181 LoopInfo &LI) {
3182 for (Instruction &I : *Block) {
3183 if (I.mayReadOrWriteMemory()) {
3184 // TODO: This instruction may already have access group from
3185 // other pragmas e.g. #pragma clang loop vectorize. Append
3186 // so that the existing metadata is not overwritten.
3187 I.setMetadata(LLVMContext::MD_access_group, AccessGroup);
3188 }
3189 }
3190}
3191
3195 Loop, {MDNode::get(Ctx, MDString::get(Ctx, "llvm.loop.unroll.enable")),
3196 MDNode::get(Ctx, MDString::get(Ctx, "llvm.loop.unroll.full"))});
3197}
3198
3202 Loop, {
3203 MDNode::get(Ctx, MDString::get(Ctx, "llvm.loop.unroll.enable")),
3204 });
3205}
3206
3207void OpenMPIRBuilder::createIfVersion(CanonicalLoopInfo *CanonicalLoop,
3208 Value *IfCond, ValueToValueMapTy &VMap,
3209 const Twine &NamePrefix) {
3210 Function *F = CanonicalLoop->getFunction();
3211
3212 // Define where if branch should be inserted
3213 Instruction *SplitBefore;
3214 if (Instruction::classof(IfCond)) {
3215 SplitBefore = dyn_cast<Instruction>(IfCond);
3216 } else {
3217 SplitBefore = CanonicalLoop->getPreheader()->getTerminator();
3218 }
3219
3220 // TODO: We should not rely on pass manager. Currently we use pass manager
3221 // only for getting llvm::Loop which corresponds to given CanonicalLoopInfo
3222 // object. We should have a method which returns all blocks between
3223 // CanonicalLoopInfo::getHeader() and CanonicalLoopInfo::getAfter()
3225 FAM.registerPass([]() { return DominatorTreeAnalysis(); });
3226 FAM.registerPass([]() { return LoopAnalysis(); });
3227 FAM.registerPass([]() { return PassInstrumentationAnalysis(); });
3228
3229 // Get the loop which needs to be cloned
3230 LoopAnalysis LIA;
3231 LoopInfo &&LI = LIA.run(*F, FAM);
3232 Loop *L = LI.getLoopFor(CanonicalLoop->getHeader());
3233
3234 // Create additional blocks for the if statement
3235 BasicBlock *Head = SplitBefore->getParent();
3236 Instruction *HeadOldTerm = Head->getTerminator();
3237 llvm::LLVMContext &C = Head->getContext();
3239 C, NamePrefix + ".if.then", Head->getParent(), Head->getNextNode());
3241 C, NamePrefix + ".if.else", Head->getParent(), CanonicalLoop->getExit());
3242
3243 // Create if condition branch.
3244 Builder.SetInsertPoint(HeadOldTerm);
3245 Instruction *BrInstr =
3246 Builder.CreateCondBr(IfCond, ThenBlock, /*ifFalse*/ ElseBlock);
3247 InsertPointTy IP{BrInstr->getParent(), ++BrInstr->getIterator()};
3248 // Then block contains branch to omp loop which needs to be vectorized
3249 spliceBB(IP, ThenBlock, false);
3250 ThenBlock->replaceSuccessorsPhiUsesWith(Head, ThenBlock);
3251
3252 Builder.SetInsertPoint(ElseBlock);
3253
3254 // Clone loop for the else branch
3256
3257 VMap[CanonicalLoop->getPreheader()] = ElseBlock;
3258 for (BasicBlock *Block : L->getBlocks()) {
3259 BasicBlock *NewBB = CloneBasicBlock(Block, VMap, "", F);
3260 NewBB->moveBefore(CanonicalLoop->getExit());
3261 VMap[Block] = NewBB;
3262 NewBlocks.push_back(NewBB);
3263 }
3264 remapInstructionsInBlocks(NewBlocks, VMap);
3265 Builder.CreateBr(NewBlocks.front());
3266}
3267
3268unsigned
3270 const StringMap<bool> &Features) {
3271 if (TargetTriple.isX86()) {
3272 if (Features.lookup("avx512f"))
3273 return 512;
3274 else if (Features.lookup("avx"))
3275 return 256;
3276 return 128;
3277 }
3278 if (TargetTriple.isPPC())
3279 return 128;
3280 if (TargetTriple.isWasm())
3281 return 128;
3282 return 0;
3283}
3284
3286 MapVector<Value *, Value *> AlignedVars,
3287 Value *IfCond, OrderKind Order,
3288 ConstantInt *Simdlen, ConstantInt *Safelen) {
3290
3291 Function *F = CanonicalLoop->getFunction();
3292
3293 // TODO: We should not rely on pass manager. Currently we use pass manager
3294 // only for getting llvm::Loop which corresponds to given CanonicalLoopInfo
3295 // object. We should have a method which returns all blocks between
3296 // CanonicalLoopInfo::getHeader() and CanonicalLoopInfo::getAfter()
3298 FAM.registerPass([]() { return DominatorTreeAnalysis(); });
3299 FAM.registerPass([]() { return LoopAnalysis(); });
3300 FAM.registerPass([]() { return PassInstrumentationAnalysis(); });
3301
3302 LoopAnalysis LIA;
3303 LoopInfo &&LI = LIA.run(*F, FAM);
3304
3305 Loop *L = LI.getLoopFor(CanonicalLoop->getHeader());
3306 if (AlignedVars.size()) {
3308 Builder.SetInsertPoint(CanonicalLoop->getPreheader()->getTerminator());
3309 for (auto &AlignedItem : AlignedVars) {
3310 Value *AlignedPtr = AlignedItem.first;
3311 Value *Alignment = AlignedItem.second;
3312 Builder.CreateAlignmentAssumption(F->getParent()->getDataLayout(),
3313 AlignedPtr, Alignment);
3314 }
3315 Builder.restoreIP(IP);
3316 }
3317
3318 if (IfCond) {
3319 ValueToValueMapTy VMap;
3320 createIfVersion(CanonicalLoop, IfCond, VMap, "simd");
3321 // Add metadata to the cloned loop which disables vectorization
3322 Value *MappedLatch = VMap.lookup(CanonicalLoop->getLatch());
3323 assert(MappedLatch &&
3324 "Cannot find value which corresponds to original loop latch");
3325 assert(isa<BasicBlock>(MappedLatch) &&
3326 "Cannot cast mapped latch block value to BasicBlock");
3327 BasicBlock *NewLatchBlock = dyn_cast<BasicBlock>(MappedLatch);
3328 ConstantAsMetadata *BoolConst =
3331 NewLatchBlock,
3332 {MDNode::get(Ctx, {MDString::get(Ctx, "llvm.loop.vectorize.enable"),
3333 BoolConst})});
3334 }
3335
3336 SmallSet<BasicBlock *, 8> Reachable;
3337
3338 // Get the basic blocks from the loop in which memref instructions
3339 // can be found.
3340 // TODO: Generalize getting all blocks inside a CanonicalizeLoopInfo,
3341 // preferably without running any passes.
3342 for (BasicBlock *Block : L->getBlocks()) {
3343 if (Block == CanonicalLoop->getCond() ||
3344 Block == CanonicalLoop->getHeader())
3345 continue;
3346 Reachable.insert(Block);
3347 }
3348
3349 SmallVector<Metadata *> LoopMDList;
3350
3351 // In presence of finite 'safelen', it may be unsafe to mark all
3352 // the memory instructions parallel, because loop-carried
3353 // dependences of 'safelen' iterations are possible.
3354 // If clause order(concurrent) is specified then the memory instructions
3355 // are marked parallel even if 'safelen' is finite.
3356 if ((Safelen == nullptr) || (Order == OrderKind::OMP_ORDER_concurrent)) {
3357 // Add access group metadata to memory-access instructions.
3358 MDNode *AccessGroup = MDNode::getDistinct(Ctx, {});
3359 for (BasicBlock *BB : Reachable)
3360 addSimdMetadata(BB, AccessGroup, LI);
3361 // TODO: If the loop has existing parallel access metadata, have
3362 // to combine two lists.
3363 LoopMDList.push_back(MDNode::get(
3364 Ctx, {MDString::get(Ctx, "llvm.loop.parallel_accesses"), AccessGroup}));
3365 }
3366
3367 // Use the above access group metadata to create loop level
3368 // metadata, which should be distinct for each loop.
3369 ConstantAsMetadata *BoolConst =
3371 LoopMDList.push_back(MDNode::get(
3372 Ctx, {MDString::get(Ctx, "llvm.loop.vectorize.enable"), BoolConst}));
3373
3374 if (Simdlen || Safelen) {
3375 // If both simdlen and safelen clauses are specified, the value of the
3376 // simdlen parameter must be less than or equal to the value of the safelen
3377 // parameter. Therefore, use safelen only in the absence of simdlen.
3378 ConstantInt *VectorizeWidth = Simdlen == nullptr ? Safelen : Simdlen;
3379 LoopMDList.push_back(
3380 MDNode::get(Ctx, {MDString::get(Ctx, "llvm.loop.vectorize.width"),
3381 ConstantAsMetadata::get(VectorizeWidth)}));
3382 }
3383
3384 addLoopMetadata(CanonicalLoop, LoopMDList);
3385}
3386
3387/// Create the TargetMachine object to query the backend for optimization
3388/// preferences.
3389///
3390/// Ideally, this would be passed from the front-end to the OpenMPBuilder, but
3391/// e.g. Clang does not pass it to its CodeGen layer and creates it only when
3392/// needed for the LLVM pass pipline. We use some default options to avoid
3393/// having to pass too many settings from the frontend that probably do not
3394/// matter.
3395///
3396/// Currently, TargetMachine is only used sometimes by the unrollLoopPartial
3397/// method. If we are going to use TargetMachine for more purposes, especially
3398/// those that are sensitive to TargetOptions, RelocModel and CodeModel, it
3399/// might become be worth requiring front-ends to pass on their TargetMachine,
3400/// or at least cache it between methods. Note that while fontends such as Clang
3401/// have just a single main TargetMachine per translation unit, "target-cpu" and
3402/// "target-features" that determine the TargetMachine are per-function and can
3403/// be overrided using __attribute__((target("OPTIONS"))).
3404static std::unique_ptr<TargetMachine>
3406 Module *M = F->getParent();
3407
3408 StringRef CPU = F->getFnAttribute("target-cpu").getValueAsString();
3409 StringRef Features = F->getFnAttribute("target-features").getValueAsString();
3410 const std::string &Triple = M->getTargetTriple();
3411
3412 std::string Error;
3414 if (!TheTarget)
3415 return {};
3416
3418 return std::unique_ptr<TargetMachine>(TheTarget->createTargetMachine(
3419 Triple, CPU, Features, Options, /*RelocModel=*/std::nullopt,
3420 /*CodeModel=*/std::nullopt, OptLevel));
3421}
3422
3423/// Heuristically determine the best-performant unroll factor for \p CLI. This
3424/// depends on the target processor. We are re-using the same heuristics as the
3425/// LoopUnrollPass.
3427 Function *F = CLI->getFunction();
3428
3429 // Assume the user requests the most aggressive unrolling, even if the rest of
3430 // the code is optimized using a lower setting.
3432 std::unique_ptr<TargetMachine> TM = createTargetMachine(F, OptLevel);
3433
3435 FAM.registerPass([]() { return TargetLibraryAnalysis(); });
3436 FAM.registerPass([]() { return AssumptionAnalysis(); });
3437 FAM.registerPass([]() { return DominatorTreeAnalysis(); });
3438 FAM.registerPass([]() { return LoopAnalysis(); });
3439 FAM.registerPass([]() { return ScalarEvolutionAnalysis(); });
3440 FAM.registerPass([]() { return PassInstrumentationAnalysis(); });
3441 TargetIRAnalysis TIRA;
3442 if (TM)
3443 TIRA = TargetIRAnalysis(
3444 [&](const Function &F) { return TM->getTargetTransformInfo(F); });
3445 FAM.registerPass([&]() { return TIRA; });
3446
3447 TargetIRAnalysis::Result &&TTI = TIRA.run(*F, FAM);
3449 ScalarEvolution &&SE = SEA.run(*F, FAM);
3451 DominatorTree &&DT = DTA.run(*F, FAM);
3452 LoopAnalysis LIA;
3453 LoopInfo &&LI = LIA.run(*F, FAM);
3455 AssumptionCache &&AC = ACT.run(*F, FAM);
3457
3458 Loop *L = LI.getLoopFor(CLI->getHeader());
3459 assert(L && "Expecting CanonicalLoopInfo to be recognized as a loop");
3460
3463 /*BlockFrequencyInfo=*/nullptr,
3464 /*ProfileSummaryInfo=*/nullptr, ORE, static_cast<int>(OptLevel),
3465 /*UserThreshold=*/std::nullopt,
3466 /*UserCount=*/std::nullopt,
3467 /*UserAllowPartial=*/true,
3468 /*UserAllowRuntime=*/true,
3469 /*UserUpperBound=*/std::nullopt,
3470 /*UserFullUnrollMaxCount=*/std::nullopt);
3471
3472 UP.Force = true;
3473
3474 // Account for additional optimizations taking place before the LoopUnrollPass
3475 // would unroll the loop.
3478
3479 // Use normal unroll factors even if the rest of the code is optimized for
3480 // size.
3483
3484 LLVM_DEBUG(dbgs() << "Unroll heuristic thresholds:\n"
3485 << " Threshold=" << UP.Threshold << "\n"
3486 << " PartialThreshold=" << UP.PartialThreshold << "\n"
3487 << " OptSizeThreshold=" << UP.OptSizeThreshold << "\n"
3488 << " PartialOptSizeThreshold="
3489 << UP.PartialOptSizeThreshold << "\n");
3490
3491 // Disable peeling.
3494 /*UserAllowPeeling=*/false,
3495 /*UserAllowProfileBasedPeeling=*/false,
3496 /*UnrollingSpecficValues=*/false);
3497
3499 CodeMetrics::collectEphemeralValues(L, &AC, EphValues);
3500
3501 // Assume that reads and writes to stack variables can be eliminated by
3502 // Mem2Reg, SROA or LICM. That is, don't count them towards the loop body's
3503 // size.
3504 for (BasicBlock *BB : L->blocks()) {
3505 for (Instruction &I : *BB) {
3506 Value *Ptr;
3507 if (auto *Load = dyn_cast<LoadInst>(&I)) {
3508 Ptr = Load->getPointerOperand();
3509 } else if (auto *Store = dyn_cast<StoreInst>(&I)) {
3510 Ptr = Store->getPointerOperand();
3511 } else
3512 continue;
3513
3514 Ptr = Ptr->stripPointerCasts();
3515
3516 if (auto *Alloca = dyn_cast<AllocaInst>(Ptr)) {
3517 if (Alloca->getParent() == &F->getEntryBlock())
3518 EphValues.insert(&I);
3519 }
3520 }
3521 }
3522
3523 unsigned NumInlineCandidates;
3524 bool NotDuplicatable;
3525 bool Convergent;
3526 InstructionCost LoopSizeIC =
3527 ApproximateLoopSize(L, NumInlineCandidates, NotDuplicatable, Convergent,
3528 TTI, EphValues, UP.BEInsns);
3529 LLVM_DEBUG(dbgs() << "Estimated loop size is " << LoopSizeIC << "\n");
3530
3531 // Loop is not unrollable if the loop contains certain instructions.
3532 if (NotDuplicatable || Convergent || !LoopSizeIC.isValid()) {
3533 LLVM_DEBUG(dbgs() << "Loop not considered unrollable\n");
3534 return 1;
3535 }
3536 unsigned LoopSize = *LoopSizeIC.getValue();
3537
3538 // TODO: Determine trip count of \p CLI if constant, computeUnrollCount might
3539 // be able to use it.
3540 int TripCount = 0;
3541 int MaxTripCount = 0;
3542 bool MaxOrZero = false;
3543 unsigned TripMultiple = 0;
3544
3545 bool UseUpperBound = false;
3546 computeUnrollCount(L, TTI, DT, &LI, &AC, SE, EphValues, &ORE, TripCount,
3547 MaxTripCount, MaxOrZero, TripMultiple, LoopSize, UP, PP,
3548 UseUpperBound);
3549 unsigned Factor = UP.Count;
3550 LLVM_DEBUG(dbgs() << "Suggesting unroll factor of " << Factor << "\n");
3551
3552 // This function returns 1 to signal to not unroll a loop.
3553 if (Factor == 0)
3554 return 1;
3555 return Factor;
3556}
3557
3559 int32_t Factor,
3560 CanonicalLoopInfo **UnrolledCLI) {
3561 assert(Factor >= 0 && "Unroll factor must not be negative");
3562
3563 Function *F = Loop->getFunction();
3564 LLVMContext &Ctx = F->getContext();
3565
3566 // If the unrolled loop is not used for another loop-associated directive, it
3567 // is sufficient to add metadata for the LoopUnrollPass.
3568 if (!UnrolledCLI) {
3569 SmallVector<Metadata *, 2> LoopMetadata;
3570 LoopMetadata.push_back(
3571 MDNode::get(Ctx, MDString::get(Ctx, "llvm.loop.unroll.enable")));
3572
3573 if (Factor >= 1) {
3575 ConstantInt::get(Type::getInt32Ty(Ctx), APInt(32, Factor)));
3576 LoopMetadata.push_back(MDNode::get(
3577 Ctx, {MDString::get(Ctx, "llvm.loop.unroll.count"), FactorConst}));
3578 }
3579
3580 addLoopMetadata(Loop, LoopMetadata);
3581 return;
3582 }
3583
3584 // Heuristically determine the unroll factor.
3585 if (Factor == 0)
3587
3588 // No change required with unroll factor 1.
3589 if (Factor == 1) {
3590 *UnrolledCLI = Loop;
3591 return;
3592 }
3593
3594 assert(Factor >= 2 &&
3595 "unrolling only makes sense with a factor of 2 or larger");
3596
3597 Type *IndVarTy = Loop->getIndVarType();
3598
3599 // Apply partial unrolling by tiling the loop by the unroll-factor, then fully
3600 // unroll the inner loop.
3601 Value *FactorVal =
3602 ConstantInt::get(IndVarTy, APInt(IndVarTy->getIntegerBitWidth(), Factor,
3603 /*isSigned=*/false));
3604 std::vector<CanonicalLoopInfo *> LoopNest =
3605 tileLoops(DL, {Loop}, {FactorVal});
3606 assert(LoopNest.size() == 2 && "Expect 2 loops after tiling");
3607 *UnrolledCLI = LoopNest[0];
3608 CanonicalLoopInfo *InnerLoop = LoopNest[1];
3609
3610 // LoopUnrollPass can only fully unroll loops with constant trip count.
3611 // Unroll by the unroll factor with a fallback epilog for the remainder
3612 // iterations if necessary.
3614 ConstantInt::get(Type::getInt32Ty(Ctx), APInt(32, Factor)));
3616 InnerLoop,
3617 {MDNode::get(Ctx, MDString::get(Ctx, "llvm.loop.unroll.enable")),
3619 Ctx, {MDString::get(Ctx, "llvm.loop.unroll.count"), FactorConst})});
3620
3621#ifndef NDEBUG
3622 (*UnrolledCLI)->assertOK();
3623#endif
3624}
3625
3628 llvm::Value *BufSize, llvm::Value *CpyBuf,
3629 llvm::Value *CpyFn, llvm::Value *DidIt) {
3630 if (!updateToLocation(Loc))
3631 return Loc.IP;
3632
3633 uint32_t SrcLocStrSize;
3634 Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
3635 Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
3636 Value *ThreadId = getOrCreateThreadID(Ident);
3637
3638 llvm::Value *DidItLD = Builder.CreateLoad(Builder.getInt32Ty(), DidIt);
3639
3640 Value *Args[] = {Ident, ThreadId, BufSize, CpyBuf, CpyFn, DidItLD};
3641
3642 Function *Fn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_copyprivate);
3643 Builder.CreateCall(Fn, Args);
3644
3645 return Builder.saveIP();
3646}
3647
3649 const LocationDescription &Loc, BodyGenCallbackTy BodyGenCB,
3650 FinalizeCallbackTy FiniCB, bool IsNowait, llvm::Value *DidIt) {
3651
3652 if (!updateToLocation(Loc))
3653 return Loc.IP;
3654
3655 // If needed (i.e. not null), initialize `DidIt` with 0
3656 if (DidIt) {
3658 }
3659
3660 Directive OMPD = Directive::OMPD_single;
3661 uint32_t SrcLocStrSize;
3662 Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
3663 Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
3664 Value *ThreadId = getOrCreateThreadID(Ident);
3665 Value *Args[] = {Ident, ThreadId};
3666
3667 Function *EntryRTLFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_single);
3668 Instruction *EntryCall = Builder.CreateCall(EntryRTLFn, Args);
3669
3670 Function *ExitRTLFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_end_single);
3671 Instruction *ExitCall = Builder.CreateCall(ExitRTLFn, Args);
3672
3673 // generates the following:
3674 // if (__kmpc_single()) {
3675 // .... single region ...
3676 // __kmpc_end_single
3677 // }
3678 // __kmpc_barrier
3679
3680 EmitOMPInlinedRegion(OMPD, EntryCall, ExitCall, BodyGenCB, FiniCB,
3681 /*Conditional*/ true,
3682 /*hasFinalize*/ true);
3683 if (!IsNowait)
3685 omp::Directive::OMPD_unknown, /* ForceSimpleCall */ false,
3686 /* CheckCancelFlag */ false);
3687 return Builder.saveIP();
3688}
3689
3691 const LocationDescription &Loc, BodyGenCallbackTy BodyGenCB,
3692 FinalizeCallbackTy FiniCB, StringRef CriticalName, Value *HintInst) {
3693
3694 if (!updateToLocation(Loc))
3695 return Loc.IP;
3696
3697 Directive OMPD = Directive::OMPD_critical;
3698 uint32_t SrcLocStrSize;
3699 Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
3700 Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
3701 Value *ThreadId = getOrCreateThreadID(Ident);
3702 Value *LockVar = getOMPCriticalRegionLock(CriticalName);
3703 Value *Args[] = {Ident, ThreadId, LockVar};
3704
3705 SmallVector<llvm::Value *, 4> EnterArgs(std::begin(Args), std::end(Args));
3706 Function *RTFn = nullptr;
3707 if (HintInst) {
3708 // Add Hint to entry Args and create call
3709 EnterArgs.push_back(HintInst);
3710 RTFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_critical_with_hint);
3711 } else {
3712 RTFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_critical);
3713 }
3714 Instruction *EntryCall = Builder.CreateCall(RTFn, EnterArgs);
3715
3716 Function *ExitRTLFn =
3717 getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_end_critical);
3718 Instruction *ExitCall = Builder.CreateCall(ExitRTLFn, Args);
3719
3720 return EmitOMPInlinedRegion(OMPD, EntryCall, ExitCall, BodyGenCB, FiniCB,
3721 /*Conditional*/ false, /*hasFinalize*/ true);
3722}
3723
3726 InsertPointTy AllocaIP, unsigned NumLoops,
3727 ArrayRef<llvm::Value *> StoreValues,
3728 const Twine &Name, bool IsDependSource) {
3729 assert(
3730 llvm::all_of(StoreValues,
3731 [](Value *SV) { return SV->getType()->isIntegerTy(64); }) &&
3732 "OpenMP runtime requires depend vec with i64 type");
3733
3734 if (!updateToLocation(Loc))
3735 return Loc.IP;
3736
3737 // Allocate space for vector and generate alloc instruction.
3738 auto *ArrI64Ty = ArrayType::get(Int64, NumLoops);
3739 Builder.restoreIP(AllocaIP);
3740 AllocaInst *ArgsBase = Builder.CreateAlloca(ArrI64Ty, nullptr, Name);
3741 ArgsBase->setAlignment(Align(8));
3742 Builder.restoreIP(Loc.IP);
3743
3744 // Store the index value with offset in depend vector.
3745 for (unsigned I = 0; I < NumLoops; ++I) {
3746 Value *DependAddrGEPIter = Builder.CreateInBoundsGEP(
3747 ArrI64Ty, ArgsBase, {Builder.getInt64(0), Builder.getInt64(I)});
3748 StoreInst *STInst = Builder.CreateStore(StoreValues[I], DependAddrGEPIter);
3749 STInst->setAlignment(Align(8));
3750 }
3751
3752 Value *DependBaseAddrGEP = Builder.CreateInBoundsGEP(
3753 ArrI64Ty, ArgsBase, {Builder.getInt64(0), Builder.getInt64(0)});
3754
3755 uint32_t SrcLocStrSize;
3756 Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
3757 Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
3758 Value *ThreadId = getOrCreateThreadID(Ident);
3759 Value *Args[] = {Ident, ThreadId, DependBaseAddrGEP};
3760
3761 Function *RTLFn = nullptr;
3762 if (IsDependSource)
3763 RTLFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_doacross_post);
3764 else
3765 RTLFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_doacross_wait);
3766 Builder.CreateCall(RTLFn, Args);
3767
3768 return Builder.saveIP();
3769}
3770
3772 const LocationDescription &Loc, BodyGenCallbackTy BodyGenCB,
3773 FinalizeCallbackTy FiniCB, bool IsThreads) {
3774 if (!updateToLocation(Loc))
3775 return Loc.IP;
3776
3777 Directive OMPD = Directive::OMPD_ordered;
3778 Instruction *EntryCall = nullptr;
3779 Instruction *ExitCall = nullptr;
3780
3781 if (IsThreads) {
3782 uint32_t SrcLocStrSize;
3783 Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
3784 Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
3785 Value *ThreadId = getOrCreateThreadID(Ident);
3786 Value *Args[] = {Ident, ThreadId};
3787
3788 Function *EntryRTLFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_ordered);
3789 EntryCall = Builder.CreateCall(EntryRTLFn, Args);
3790
3791 Function *ExitRTLFn =
3792 getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_end_ordered);
3793 ExitCall = Builder.CreateCall(ExitRTLFn, Args);
3794 }
3795
3796 return EmitOMPInlinedRegion(OMPD, EntryCall, ExitCall, BodyGenCB, FiniCB,
3797 /*Conditional*/ false, /*hasFinalize*/ true);
3798}
3799
3800OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::EmitOMPInlinedRegion(
3801 Directive OMPD, Instruction *EntryCall, Instruction *ExitCall,
3802 BodyGenCallbackTy BodyGenCB, FinalizeCallbackTy FiniCB, bool Conditional,
3803 bool HasFinalize, bool IsCancellable) {
3804
3805 if (HasFinalize)
3806 FinalizationStack.push_back({FiniCB, OMPD, IsCancellable});
3807
3808 // Create inlined region's entry and body blocks, in preparation
3809 // for conditional creation
3810 BasicBlock *EntryBB = Builder.GetInsertBlock();
3811 Instruction *SplitPos = EntryBB->getTerminator();
3812 if (!isa_and_nonnull<BranchInst>(SplitPos))
3813 SplitPos = new UnreachableInst(Builder.getContext(), EntryBB);
3814 BasicBlock *ExitBB = EntryBB->splitBasicBlock(SplitPos, "omp_region.end");
3815 BasicBlock *FiniBB =
3816 EntryBB->splitBasicBlock(EntryBB->getTerminator(), "omp_region.finalize");
3817
3819 emitCommonDirectiveEntry(OMPD, EntryCall, ExitBB, Conditional);
3820
3821 // generate body
3822 BodyGenCB(/* AllocaIP */ InsertPointTy(),
3823 /* CodeGenIP */ Builder.saveIP());
3824
3825 // emit exit call and do any needed finalization.
3826 auto FinIP = InsertPointTy(FiniBB, FiniBB->getFirstInsertionPt());
3827 assert(FiniBB->getTerminator()->getNumSuccessors() == 1 &&
3828 FiniBB->getTerminator()->getSuccessor(0) == ExitBB &&
3829 "Unexpected control flow graph state!!");
3830 emitCommonDirectiveExit(OMPD, FinIP, ExitCall, HasFinalize);
3831 assert(FiniBB->getUniquePredecessor()->getUniqueSuccessor() == FiniBB &&
3832 "Unexpected Control Flow State!");
3834
3835 // If we are skipping the region of a non conditional, remove the exit
3836 // block, and clear the builder's insertion point.
3837 assert(SplitPos->getParent() == ExitBB &&
3838 "Unexpected Insertion point location!");
3839 auto merged = MergeBlockIntoPredecessor(ExitBB);
3840 BasicBlock *ExitPredBB = SplitPos->getParent();
3841 auto InsertBB = merged ? ExitPredBB : ExitBB;
3842 if (!isa_and_nonnull<BranchInst>(SplitPos))
3843 SplitPos->eraseFromParent();
3844 Builder.SetInsertPoint(InsertBB);
3845
3846 return Builder.saveIP();
3847}
3848
3849OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::emitCommonDirectiveEntry(
3850 Directive OMPD, Value *EntryCall, BasicBlock *ExitBB, bool Conditional) {
3851 // if nothing to do, Return current insertion point.
3852 if (!Conditional || !EntryCall)
3853 return Builder.saveIP();
3854
3855 BasicBlock *EntryBB = Builder.GetInsertBlock();
3856 Value *CallBool = Builder.CreateIsNotNull(EntryCall);
3857 auto *ThenBB = BasicBlock::Create(M.getContext(), "omp_region.body");
3858 auto *UI = new UnreachableInst(Builder.getContext(), ThenBB);
3859
3860 // Emit thenBB and set the Builder's insertion point there for
3861 // body generation next. Place the block after the current block.
3862 Function *CurFn = EntryBB->getParent();
3863 CurFn->insert(std::next(EntryBB->getIterator()), ThenBB);
3864
3865 // Move Entry branch to end of ThenBB, and replace with conditional
3866 // branch (If-stmt)
3867 Instruction *EntryBBTI = EntryBB->getTerminator();
3868 Builder.CreateCondBr(CallBool, ThenBB, ExitBB);
3869 EntryBBTI->removeFromParent();
3871 Builder.Insert(EntryBBTI);
3872 UI->eraseFromParent();
3873 Builder.SetInsertPoint(ThenBB->getTerminator());
3874
3875 // return an insertion point to ExitBB.
3876 return IRBuilder<>::InsertPoint(ExitBB, ExitBB->getFirstInsertionPt());
3877}
3878
3879OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::emitCommonDirectiveExit(
3880 omp::Directive OMPD, InsertPointTy FinIP, Instruction *ExitCall,
3881 bool HasFinalize) {
3882
3883 Builder.restoreIP(FinIP);
3884
3885 // If there is finalization to do, emit it before the exit call
3886 if (HasFinalize) {
3887 assert(!FinalizationStack.empty() &&
3888 "Unexpected finalization stack state!");
3889
3890 FinalizationInfo Fi = FinalizationStack.pop_back_val();
3891 assert(Fi.DK == OMPD && "Unexpected Directive for Finalization call!");
3892
3893 Fi.FiniCB(FinIP);
3894
3895 BasicBlock *FiniBB = FinIP.getBlock();
3896 Instruction *FiniBBTI = FiniBB->getTerminator();
3897
3898 // set Builder IP for call creation
3899 Builder.SetInsertPoint(FiniBBTI);
3900 }
3901
3902 if (!ExitCall)
3903 return Builder.saveIP();
3904
3905 // place the Exitcall as last instruction before Finalization block terminator
3906 ExitCall->removeFromParent();
3907 Builder.Insert(ExitCall);
3908
3909 return IRBuilder<>::InsertPoint(ExitCall->getParent(),
3910 ExitCall->getIterator());
3911}
3912
3914 InsertPointTy IP, Value *MasterAddr, Value *PrivateAddr,
3915 llvm::IntegerType *IntPtrTy, bool BranchtoEnd) {
3916 if (!IP.isSet())
3917 return IP;
3918
3920
3921 // creates the following CFG structure
3922 // OMP_Entry : (MasterAddr != PrivateAddr)?
3923 // F T
3924 // | \
3925 // | copin.not.master
3926 // | /
3927 // v /
3928 // copyin.not.master.end
3929 // |
3930 // v
3931 // OMP.Entry.Next
3932
3933 BasicBlock *OMP_Entry = IP.getBlock();
3934 Function *CurFn = OMP_Entry->getParent();
3935 BasicBlock *CopyBegin =
3936 BasicBlock::Create(M.getContext(), "copyin.not.master", CurFn);
3937 BasicBlock *CopyEnd = nullptr;
3938
3939 // If entry block is terminated, split to preserve the branch to following
3940 // basic block (i.e. OMP.Entry.Next), otherwise, leave everything as is.
3941 if (isa_and_nonnull<BranchInst>(OMP_Entry->getTerminator())) {
3942 CopyEnd = OMP_Entry->splitBasicBlock(OMP_Entry->getTerminator(),
3943 "copyin.not.master.end");
3944 OMP_Entry->getTerminator()->eraseFromParent();
3945 } else {
3946 CopyEnd =
3947 BasicBlock::Create(M.getContext(), "copyin.not.master.end", CurFn);
3948 }
3949
3950 Builder.SetInsertPoint(OMP_Entry);
3951 Value *MasterPtr = Builder.CreatePtrToInt(MasterAddr, IntPtrTy);
3952 Value *PrivatePtr = Builder.CreatePtrToInt(PrivateAddr, IntPtrTy);
3953 Value *cmp = Builder.CreateICmpNE(MasterPtr, PrivatePtr);
3954 Builder.CreateCondBr(cmp, CopyBegin, CopyEnd);
3955
3956 Builder.SetInsertPoint(CopyBegin);
3957 if (BranchtoEnd)
3959
3960 return Builder.saveIP();
3961}
3962
3964 Value *Size, Value *Allocator,
3965 std::string Name) {
3967 Builder.restoreIP(Loc.IP);
3968
3969 uint32_t SrcLocStrSize;
3970 Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
3971 Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
3972 Value *ThreadId = getOrCreateThreadID(Ident);
3973 Value *Args[] = {ThreadId, Size, Allocator};
3974
3975 Function *Fn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_alloc);
3976
3977 return Builder.CreateCall(Fn, Args, Name);
3978}
3979
3981 Value *Addr, Value *Allocator,
3982 std::string Name) {
3984 Builder.restoreIP(Loc.IP);
3985
3986 uint32_t SrcLocStrSize;
3987 Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
3988 Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
3989 Value *ThreadId = getOrCreateThreadID(Ident);
3990 Value *Args[] = {ThreadId, Addr, Allocator};
3991 Function *Fn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_free);
3992 return Builder.CreateCall(Fn, Args, Name);
3993}
3994
3996 const LocationDescription &Loc, Value *InteropVar,
3997 omp::OMPInteropType InteropType, Value *Device, Value *NumDependences,
3998 Value *DependenceAddress, bool HaveNowaitClause) {
4000 Builder.restoreIP(Loc.IP);
4001
4002 uint32_t SrcLocStrSize;
4003 Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
4004 Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
4005 Value *ThreadId = getOrCreateThreadID(Ident);
4006 if (Device == nullptr)
4007 Device = ConstantInt::get(Int32, -1);
4008 Constant *InteropTypeVal = ConstantInt::get(Int32, (int)InteropType);
4009 if (NumDependences == nullptr) {
4010 NumDependences = ConstantInt::get(Int32, 0);
4011 PointerType *PointerTypeVar = Type::getInt8PtrTy(M.getContext());
4012 DependenceAddress = ConstantPointerNull::get(PointerTypeVar);
4013 }
4014 Value *HaveNowaitClauseVal = ConstantInt::get(Int32, HaveNowaitClause);
4015 Value *Args[] = {
4016 Ident, ThreadId, InteropVar, InteropTypeVal,
4017 Device, NumDependences, DependenceAddress, HaveNowaitClauseVal};
4018
4019 Function *Fn = getOrCreateRuntimeFunctionPtr(OMPRTL___tgt_interop_init);
4020
4021 return Builder.CreateCall(Fn, Args);
4022}
4023
4025 const LocationDescription &Loc, Value *InteropVar, Value *Device,
4026 Value *NumDependences, Value *DependenceAddress, bool HaveNowaitClause) {
4028 Builder.restoreIP(Loc.IP);
4029
4030 uint32_t SrcLocStrSize;
4031 Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
4032 Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
4033 Value *ThreadId = getOrCreateThreadID(Ident);
4034 if (Device == nullptr)
4035 Device = ConstantInt::get(Int32, -1);
4036 if (NumDependences == nullptr) {
4037 NumDependences = ConstantInt::get(Int32, 0);
4038 PointerType *PointerTypeVar = Type::getInt8PtrTy(M.getContext());
4039 DependenceAddress = ConstantPointerNull::get(PointerTypeVar);
4040 }
4041 Value *HaveNowaitClauseVal = ConstantInt::get(Int32, HaveNowaitClause);
4042 Value *Args[] = {
4043 Ident, ThreadId, InteropVar, Device,
4044 NumDependences, DependenceAddress, HaveNowaitClauseVal};
4045
4046 Function *Fn = getOrCreateRuntimeFunctionPtr(OMPRTL___tgt_interop_destroy);
4047
4048 return Builder.CreateCall(Fn, Args);
4049}
4050
4052 Value *InteropVar, Value *Device,
4053 Value *NumDependences,
4054 Value *DependenceAddress,
4055 bool HaveNowaitClause) {
4057 Builder.restoreIP(Loc.IP);
4058 uint32_t SrcLocStrSize;
4059 Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
4060 Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
4061 Value *ThreadId = getOrCreateThreadID(Ident);
4062 if (Device == nullptr)
4063 Device = ConstantInt::get(Int32, -1);
4064 if (NumDependences == nullptr) {
4065 NumDependences = ConstantInt::get(Int32, 0);
4066 PointerType *PointerTypeVar = Type::getInt8PtrTy(M.getContext());
4067 DependenceAddress = ConstantPointerNull::get(PointerTypeVar);
4068 }
4069 Value *HaveNowaitClauseVal = ConstantInt::get(Int32, HaveNowaitClause);
4070 Value *Args[] = {
4071 Ident, ThreadId, InteropVar, Device,
4072 NumDependences, DependenceAddress, HaveNowaitClauseVal};
4073
4074 Function *Fn = getOrCreateRuntimeFunctionPtr(OMPRTL___tgt_interop_use);
4075
4076 return Builder.CreateCall(Fn, Args);
4077}
4078
4080 const LocationDescription &Loc, llvm::Value *Pointer,
4083 Builder.restoreIP(Loc.IP);
4084
4085 uint32_t SrcLocStrSize;
4086 Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
4087 Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
4088 Value *ThreadId = getOrCreateThreadID(Ident);
4089 Constant *ThreadPrivateCache =
4090 getOrCreateInternalVariable(Int8PtrPtr, Name.str());
4091 llvm::Value *Args[] = {Ident, ThreadId, Pointer, Size, ThreadPrivateCache};
4092
4093 Function *Fn =
4094 getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_threadprivate_cached);
4095
4096 return Builder.CreateCall(Fn, Args);
4097}
4098
4101 if (!updateToLocation(Loc))
4102 return Loc.IP;
4103
4104 uint32_t SrcLocStrSize;
4105 Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
4106 Constant *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
4108 IntegerType::getInt8Ty(Int8->getContext()),
4110 ConstantInt *UseGenericStateMachineVal = ConstantInt::getSigned(
4111 IntegerType::getInt8Ty(Int8->getContext()), !IsSPMD);
4112 ConstantInt *MayUseNestedParallelismVal =
4113 ConstantInt::getSigned(IntegerType::getInt8Ty(Int8->getContext()), true);
4114 ConstantInt *DebugIndentionLevelVal =
4115 ConstantInt::getSigned(IntegerType::getInt16Ty(Int8->getContext()), 0);
4116
4117 // We need to strip the debug prefix to get the correct kernel name.
4119 StringRef KernelName = Kernel->getName();
4120 const std::string DebugPrefix = "_debug__";
4121 if (KernelName.ends_with(DebugPrefix))
4122 KernelName = KernelName.drop_back(DebugPrefix.length());
4123
4125 omp::RuntimeFunction::OMPRTL___kmpc_target_init);
4126 const DataLayout &DL = Fn->getParent()->getDataLayout();
4127
4128 Twine DynamicEnvironmentName = KernelName + "_dynamic_environment";
4129 Constant *DynamicEnvironmentInitializer =
4130 ConstantStruct::get(DynamicEnvironment, {DebugIndentionLevelVal});
4131 GlobalVariable *DynamicEnvironmentGV = new GlobalVariable(
4132 M, DynamicEnvironment, /*IsConstant=*/false, GlobalValue::WeakODRLinkage,
4133 DynamicEnvironmentInitializer, DynamicEnvironmentName,
4134 /*InsertBefore=*/nullptr, GlobalValue::NotThreadLocal,
4135 DL.getDefaultGlobalsAddressSpace());
4136 DynamicEnvironmentGV->setVisibility(GlobalValue::ProtectedVisibility);
4137
4138 Constant *DynamicEnvironment =
4139 DynamicEnvironmentGV->getType() == DynamicEnvironmentPtr
4140 ? DynamicEnvironmentGV
4141 : ConstantExpr::getAddrSpaceCast(DynamicEnvironmentGV,
4142 DynamicEnvironmentPtr);
4143
4144 Constant *ConfigurationEnvironmentInitializer = ConstantStruct::get(
4145 ConfigurationEnvironment, {
4146 UseGenericStateMachineVal,
4147 MayUseNestedParallelismVal,
4148 IsSPMDVal,
4149 });
4150 Constant *KernelEnvironmentInitializer = ConstantStruct::get(
4151 KernelEnvironment, {
4152 ConfigurationEnvironmentInitializer,
4153 Ident,
4154 DynamicEnvironment,
4155 });
4156 Twine KernelEnvironmentName = KernelName + "_kernel_environment";
4157 GlobalVariable *KernelEnvironmentGV = new GlobalVariable(
4158 M, KernelEnvironment, /*IsConstant=*/true, GlobalValue::WeakODRLinkage,
4159 KernelEnvironmentInitializer, KernelEnvironmentName,
4160 /*InsertBefore=*/nullptr, GlobalValue::NotThreadLocal,
4161 DL.getDefaultGlobalsAddressSpace());
4162 KernelEnvironmentGV->setVisibility(GlobalValue::ProtectedVisibility);
4163
4164 Constant *KernelEnvironment =
4165 KernelEnvironmentGV->getType() == KernelEnvironmentPtr
4166 ? KernelEnvironmentGV
4167 : ConstantExpr::getAddrSpaceCast(KernelEnvironmentGV,
4168 KernelEnvironmentPtr);
4169 CallInst *ThreadKind = Builder.CreateCall(Fn, {KernelEnvironment});
4170
4171 Value *ExecUserCode = Builder.CreateICmpEQ(
4172 ThreadKind, ConstantInt::get(ThreadKind->getType(), -1),
4173 "exec_user_code");
4174
4175 // ThreadKind = __kmpc_target_init(...)
4176 // if (ThreadKind == -1)
4177 // user_code
4178 // else
4179 // return;
4180
4181 auto *UI = Builder.CreateUnreachable();
4182 BasicBlock *CheckBB = UI->getParent();
4183 BasicBlock *UserCodeEntryBB = CheckBB->splitBasicBlock(UI, "user_code.entry");
4184
4185 BasicBlock *WorkerExitBB = BasicBlock::Create(
4186 CheckBB->getContext(), "worker.exit", CheckBB->getParent());
4187 Builder.SetInsertPoint(WorkerExitBB);
4189
4190 auto *CheckBBTI = CheckBB->getTerminator();
4191 Builder.SetInsertPoint(CheckBBTI);
4192 Builder.CreateCondBr(ExecUserCode, UI->getParent(), WorkerExitBB);
4193
4194 CheckBBTI->eraseFromParent();
4195 UI->eraseFromParent();
4196
4197 // Continue in the "user_code" block, see diagram above and in
4198 // openmp/libomptarget/deviceRTLs/common/include/target.h .
4199 return InsertPointTy(UserCodeEntryBB, UserCodeEntryBB->getFirstInsertionPt());
4200}
4201
4203 if (!updateToLocation(Loc))
4204 return;
4205
4207 omp::RuntimeFunction::OMPRTL___kmpc_target_deinit);
4208
4209 Builder.CreateCall(Fn, {});
4210}
4211
4214 StringRef Features =
4215 Kernel->getFnAttribute("target-features").getValueAsString();
4216 if (Features.count("+wavefrontsize64"))
4217 return omp::getAMDGPUGridValues<64>();
4218 return omp::getAMDGPUGridValues<32>();
4219 }
4221
4222 return omp::NVPTXGridValues;
4223 llvm_unreachable("No grid value available for this architecture!");
4224}
4225
4226void OpenMPIRBuilder::setOutlinedTargetRegionFunctionAttributes(
4227 Function *OutlinedFn, int32_t NumTeams, int32_t NumThreads) {
4228 if (Config.isTargetDevice()) {
4230 // TODO: Determine if DSO local can be set to true.
4231 OutlinedFn->setDSOLocal(false);
4235 }
4236
4237 if (NumTeams > 0)
4238 OutlinedFn->addFnAttr("omp_target_num_teams", std::to_string(NumTeams));
4239
4240 if (NumThreads == -1 && Config.isGPU())
4241 NumThreads = getGridValue(OutlinedFn).GV_Default_WG_Size;
4242
4243 if (NumThreads > 0) {
4244 if (OutlinedFn->getCallingConv() == CallingConv::AMDGPU_KERNEL) {
4245 OutlinedFn->addFnAttr("amdgpu-flat-work-group-size",
4246 "1," + llvm::utostr(NumThreads));
4247 } else {
4248 // Update the "maxntidx" metadata for NVIDIA, or add it.
4249 NamedMDNode *MD = M.getOrInsertNamedMetadata("nvvm.annotations");
4250 MDNode *ExistingOp = nullptr;
4251 for (auto *Op : MD->operands()) {
4252 if (Op->getNumOperands() != 3)
4253 continue;
4254 auto *Kernel = dyn_cast<ConstantAsMetadata>(Op->getOperand(0));
4255 if (!Kernel || Kernel->getValue() != OutlinedFn)
4256 continue;
4257 auto *Prop = dyn_cast<MDString>(Op->getOperand(1));
4258 if (!Prop || Prop->getString() != "maxntidx")
4259 continue;
4260 ExistingOp = Op;
4261 break;
4262 }
4263 if (ExistingOp) {
4264 auto *OldVal = dyn_cast<ConstantAsMetadata>(ExistingOp->getOperand(2));
4265 int32_t OldLimit =
4266 cast<ConstantInt>(OldVal->getValue())->getZExtValue();
4267 ExistingOp->replaceOperandWith(
4269 ConstantInt::get(OldVal->getValue()->getType(),
4270 std::min(OldLimit, NumThreads))));
4271 } else {
4272 LLVMContext &Ctx = M.getContext();
4273 Metadata *MDVals[] = {ConstantAsMetadata::get(OutlinedFn),
4274 MDString::get(Ctx, "maxntidx"),
4276 Type::getInt32Ty(Ctx), NumThreads))};
4277 // Append metadata to nvvm.annotations
4278 MD->addOperand(MDNode::get(Ctx, MDVals));
4279 }
4280 }
4281 OutlinedFn->addFnAttr("omp_target_thread_limit",
4282 std::to_string(NumThreads));
4283 }
4284}
4285
4286Constant *OpenMPIRBuilder::createOutlinedFunctionID(Function *OutlinedFn,
4287 StringRef EntryFnIDName) {
4288 if (Config.isTargetDevice()) {
4289 assert(OutlinedFn && "The outlined function must exist if embedded");
4290 return ConstantExpr::getBitCast(OutlinedFn, Builder.getInt8PtrTy());
4291 }
4292
4293 return new GlobalVariable(
4294 M, Builder.getInt8Ty(), /*isConstant=*/true, GlobalValue::WeakAnyLinkage,
4295 Constant::getNullValue(Builder.getInt8Ty()), EntryFnIDName);
4296}
4297
4298Constant *OpenMPIRBuilder::createTargetRegionEntryAddr(Function *OutlinedFn,
4299 StringRef EntryFnName) {
4300 if (OutlinedFn)
4301 return OutlinedFn;
4302
4303 assert(!M.getGlobalVariable(EntryFnName, true) &&
4304 "Named kernel already exists?");
4305 return new GlobalVariable(
4306 M, Builder.getInt8Ty(), /*isConstant=*/true, GlobalValue::InternalLinkage,
4307 Constant::getNullValue(Builder.getInt8Ty()), EntryFnName);
4308}
4309
4311 TargetRegionEntryInfo &EntryInfo,
4312 FunctionGenCallback &GenerateFunctionCallback, int32_t NumTeams,
4313 int32_t NumThreads, bool IsOffloadEntry, Function *&OutlinedFn,
4314 Constant *&OutlinedFnID) {
4315
4316 SmallString<64> EntryFnName;
4317 OffloadInfoManager.getTargetRegionEntryFnName(EntryFnName, EntryInfo);
4318
4320 ? GenerateFunctionCallback(EntryFnName)
4321 : nullptr;
4322
4323 // If this target outline function is not an offload entry, we don't need to
4324 // register it. This may be in the case of a false if clause, or if there are
4325 // no OpenMP targets.
4326 if (!IsOffloadEntry)
4327 return;
4328
4329 std::string EntryFnIDName =
4331 ? std::string(EntryFnName)
4332 : createPlatformSpecificName({EntryFnName, "region_id"});
4333
4334 OutlinedFnID = registerTargetRegionFunction(
4335 EntryInfo, OutlinedFn, EntryFnName, EntryFnIDName, NumTeams, NumThreads);
4336}
4337
4339 TargetRegionEntryInfo &EntryInfo, Function *OutlinedFn,
4340 StringRef EntryFnName, StringRef EntryFnIDName, int32_t NumTeams,
4341 int32_t NumThreads) {
4342 if (OutlinedFn)
4343 setOutlinedTargetRegionFunctionAttributes(OutlinedFn, NumTeams, NumThreads);
4344 auto OutlinedFnID = createOutlinedFunctionID(OutlinedFn, EntryFnIDName);
4345 auto EntryAddr = createTargetRegionEntryAddr(OutlinedFn, EntryFnName);
4347 EntryInfo, EntryAddr, OutlinedFnID,
4349 return OutlinedFnID;
4350}
4351
4353 const LocationDescription &Loc, InsertPointTy AllocaIP,
4354 InsertPointTy CodeGenIP, Value *DeviceID, Value *IfCond,
4355 TargetDataInfo &Info, GenMapInfoCallbackTy GenMapInfoCB,
4356 omp::RuntimeFunction *MapperFunc,
4357 function_ref<InsertPointTy(InsertPointTy CodeGenIP, BodyGenTy BodyGenType)>
4358 BodyGenCB,
4359 function_ref<void(unsigned int, Value *)> DeviceAddrCB,
4360 function_ref<Value *(unsigned int)> CustomMapperCB, Value *SrcLocInfo) {
4361 if (!updateToLocation(Loc))
4362 return InsertPointTy();
4363
4364 Builder.restoreIP(CodeGenIP);
4365 bool IsStandAlone = !BodyGenCB;
4366 MapInfosTy *MapInfo;
4367 // Generate the code for the opening of the data environment. Capture all the
4368 // arguments of the runtime call by reference because they are used in the
4369 // closing of the region.
4370 auto BeginThenGen = [&](InsertPointTy AllocaIP, InsertPointTy CodeGenIP) {
4371 MapInfo = &GenMapInfoCB(Builder.saveIP());
4372 emitOffloadingArrays(AllocaIP, Builder.saveIP(), *MapInfo, Info,
4373 /*IsNonContiguous=*/true, DeviceAddrCB,
4374 CustomMapperCB);
4375
4376 TargetDataRTArgs RTArgs;
4378 !MapInfo->Names.empty());
4379
4380 // Emit the number of elements in the offloading arrays.
4381 Value *PointerNum = Builder.getInt32(Info.NumberOfPtrs);
4382
4383 // Source location for the ident struct
4384 if (!SrcLocInfo) {
4385 uint32_t SrcLocStrSize;
4386 Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
4387 SrcLocInfo = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
4388 }
4389
4390 Value *OffloadingArgs[] = {SrcLocInfo, DeviceID,
4391 PointerNum, RTArgs.BasePointersArray,
4392 RTArgs.PointersArray, RTArgs.SizesArray,
4393 RTArgs.MapTypesArray, RTArgs.MapNamesArray,
4394 RTArgs.MappersArray};
4395
4396 if (IsStandAlone) {
4397 assert(MapperFunc && "MapperFunc missing for standalone target data");
4399 OffloadingArgs);
4400 } else {
4401 Function *BeginMapperFunc = getOrCreateRuntimeFunctionPtr(
4402 omp::OMPRTL___tgt_target_data_begin_mapper);
4403
4404 Builder.CreateCall(BeginMapperFunc, OffloadingArgs);
4405
4406 for (auto DeviceMap : Info.DevicePtrInfoMap) {
4407 if (isa<AllocaInst>(DeviceMap.second.second)) {
4408 auto *LI =
4409 Builder.CreateLoad(Builder.getPtrTy(), DeviceMap.second.first);
4410 Builder.CreateStore(LI, DeviceMap.second.second);
4411 }
4412 }
4413
4414 // If device pointer privatization is required, emit the body of the
4415 // region here. It will have to be duplicated: with and without
4416 // privatization.
4418 }
4419 };
4420
4421 // If we need device pointer privatization, we need to emit the body of the
4422 // region with no privatization in the 'else' branch of the conditional.
4423 // Otherwise, we don't have to do anything.
4424 auto BeginElseGen = [&](InsertPointTy AllocaIP, InsertPointTy CodeGenIP) {
4426 };
4427
4428 // Generate code for the closing of the data region.
4429 auto EndThenGen = [&](InsertPointTy AllocaIP, InsertPointTy CodeGenIP) {
4430 TargetDataRTArgs RTArgs;