xref: /freebsd/contrib/llvm-project/llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp (revision 59c8e88e72633afbc47a4ace0d2170d00d51f7dc)
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 
15 #include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
16 #include "llvm/ADT/SmallSet.h"
17 #include "llvm/ADT/StringRef.h"
18 #include "llvm/Analysis/AssumptionCache.h"
19 #include "llvm/Analysis/CodeMetrics.h"
20 #include "llvm/Analysis/LoopInfo.h"
21 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
22 #include "llvm/Analysis/ScalarEvolution.h"
23 #include "llvm/Analysis/TargetLibraryInfo.h"
24 #include "llvm/Bitcode/BitcodeReader.h"
25 #include "llvm/IR/Attributes.h"
26 #include "llvm/IR/CFG.h"
27 #include "llvm/IR/Constants.h"
28 #include "llvm/IR/DebugInfoMetadata.h"
29 #include "llvm/IR/DerivedTypes.h"
30 #include "llvm/IR/GlobalVariable.h"
31 #include "llvm/IR/IRBuilder.h"
32 #include "llvm/IR/MDBuilder.h"
33 #include "llvm/IR/PassManager.h"
34 #include "llvm/IR/Value.h"
35 #include "llvm/MC/TargetRegistry.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/FileSystem.h"
38 #include "llvm/Target/TargetMachine.h"
39 #include "llvm/Target/TargetOptions.h"
40 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
41 #include "llvm/Transforms/Utils/Cloning.h"
42 #include "llvm/Transforms/Utils/CodeExtractor.h"
43 #include "llvm/Transforms/Utils/LoopPeel.h"
44 #include "llvm/Transforms/Utils/UnrollLoop.h"
45 
46 #include <cstdint>
47 #include <optional>
48 
49 #define DEBUG_TYPE "openmp-ir-builder"
50 
51 using namespace llvm;
52 using namespace omp;
53 
54 static cl::opt<bool>
55     OptimisticAttributes("openmp-ir-builder-optimistic-attributes", cl::Hidden,
56                          cl::desc("Use optimistic attributes describing "
57                                   "'as-if' properties of runtime calls."),
58                          cl::init(false));
59 
60 static cl::opt<double> UnrollThresholdFactor(
61     "openmp-ir-builder-unroll-threshold-factor", cl::Hidden,
62     cl::desc("Factor for the unroll threshold to account for code "
63              "simplifications still taking place"),
64     cl::init(1.5));
65 
66 #ifndef NDEBUG
67 /// Return whether IP1 and IP2 are ambiguous, i.e. that inserting instructions
68 /// at position IP1 may change the meaning of IP2 or vice-versa. This is because
69 /// an InsertPoint stores the instruction before something is inserted. For
70 /// instance, if both point to the same instruction, two IRBuilders alternating
71 /// creating instruction will cause the instructions to be interleaved.
72 static bool isConflictIP(IRBuilder<>::InsertPoint IP1,
73                          IRBuilder<>::InsertPoint IP2) {
74   if (!IP1.isSet() || !IP2.isSet())
75     return false;
76   return IP1.getBlock() == IP2.getBlock() && IP1.getPoint() == IP2.getPoint();
77 }
78 
79 static bool isValidWorkshareLoopScheduleType(OMPScheduleType SchedType) {
80   // Valid ordered/unordered and base algorithm combinations.
81   switch (SchedType & ~OMPScheduleType::MonotonicityMask) {
82   case OMPScheduleType::UnorderedStaticChunked:
83   case OMPScheduleType::UnorderedStatic:
84   case OMPScheduleType::UnorderedDynamicChunked:
85   case OMPScheduleType::UnorderedGuidedChunked:
86   case OMPScheduleType::UnorderedRuntime:
87   case OMPScheduleType::UnorderedAuto:
88   case OMPScheduleType::UnorderedTrapezoidal:
89   case OMPScheduleType::UnorderedGreedy:
90   case OMPScheduleType::UnorderedBalanced:
91   case OMPScheduleType::UnorderedGuidedIterativeChunked:
92   case OMPScheduleType::UnorderedGuidedAnalyticalChunked:
93   case OMPScheduleType::UnorderedSteal:
94   case OMPScheduleType::UnorderedStaticBalancedChunked:
95   case OMPScheduleType::UnorderedGuidedSimd:
96   case OMPScheduleType::UnorderedRuntimeSimd:
97   case OMPScheduleType::OrderedStaticChunked:
98   case OMPScheduleType::OrderedStatic:
99   case OMPScheduleType::OrderedDynamicChunked:
100   case OMPScheduleType::OrderedGuidedChunked:
101   case OMPScheduleType::OrderedRuntime:
102   case OMPScheduleType::OrderedAuto:
103   case OMPScheduleType::OrderdTrapezoidal:
104   case OMPScheduleType::NomergeUnorderedStaticChunked:
105   case OMPScheduleType::NomergeUnorderedStatic:
106   case OMPScheduleType::NomergeUnorderedDynamicChunked:
107   case OMPScheduleType::NomergeUnorderedGuidedChunked:
108   case OMPScheduleType::NomergeUnorderedRuntime:
109   case OMPScheduleType::NomergeUnorderedAuto:
110   case OMPScheduleType::NomergeUnorderedTrapezoidal:
111   case OMPScheduleType::NomergeUnorderedGreedy:
112   case OMPScheduleType::NomergeUnorderedBalanced:
113   case OMPScheduleType::NomergeUnorderedGuidedIterativeChunked:
114   case OMPScheduleType::NomergeUnorderedGuidedAnalyticalChunked:
115   case OMPScheduleType::NomergeUnorderedSteal:
116   case OMPScheduleType::NomergeOrderedStaticChunked:
117   case OMPScheduleType::NomergeOrderedStatic:
118   case OMPScheduleType::NomergeOrderedDynamicChunked:
119   case OMPScheduleType::NomergeOrderedGuidedChunked:
120   case OMPScheduleType::NomergeOrderedRuntime:
121   case OMPScheduleType::NomergeOrderedAuto:
122   case OMPScheduleType::NomergeOrderedTrapezoidal:
123     break;
124   default:
125     return false;
126   }
127 
128   // Must not set both monotonicity modifiers at the same time.
129   OMPScheduleType MonotonicityFlags =
130       SchedType & OMPScheduleType::MonotonicityMask;
131   if (MonotonicityFlags == OMPScheduleType::MonotonicityMask)
132     return false;
133 
134   return true;
135 }
136 #endif
137 
138 /// Determine which scheduling algorithm to use, determined from schedule clause
139 /// arguments.
140 static OMPScheduleType
141 getOpenMPBaseScheduleType(llvm::omp::ScheduleKind ClauseKind, bool HasChunks,
142                           bool HasSimdModifier) {
143   // Currently, the default schedule it static.
144   switch (ClauseKind) {
145   case OMP_SCHEDULE_Default:
146   case OMP_SCHEDULE_Static:
147     return HasChunks ? OMPScheduleType::BaseStaticChunked
148                      : OMPScheduleType::BaseStatic;
149   case OMP_SCHEDULE_Dynamic:
150     return OMPScheduleType::BaseDynamicChunked;
151   case OMP_SCHEDULE_Guided:
152     return HasSimdModifier ? OMPScheduleType::BaseGuidedSimd
153                            : OMPScheduleType::BaseGuidedChunked;
154   case OMP_SCHEDULE_Auto:
155     return llvm::omp::OMPScheduleType::BaseAuto;
156   case OMP_SCHEDULE_Runtime:
157     return HasSimdModifier ? OMPScheduleType::BaseRuntimeSimd
158                            : OMPScheduleType::BaseRuntime;
159   }
160   llvm_unreachable("unhandled schedule clause argument");
161 }
162 
163 /// Adds ordering modifier flags to schedule type.
164 static OMPScheduleType
165 getOpenMPOrderingScheduleType(OMPScheduleType BaseScheduleType,
166                               bool HasOrderedClause) {
167   assert((BaseScheduleType & OMPScheduleType::ModifierMask) ==
168              OMPScheduleType::None &&
169          "Must not have ordering nor monotonicity flags already set");
170 
171   OMPScheduleType OrderingModifier = HasOrderedClause
172                                          ? OMPScheduleType::ModifierOrdered
173                                          : OMPScheduleType::ModifierUnordered;
174   OMPScheduleType OrderingScheduleType = BaseScheduleType | OrderingModifier;
175 
176   // Unsupported combinations
177   if (OrderingScheduleType ==
178       (OMPScheduleType::BaseGuidedSimd | OMPScheduleType::ModifierOrdered))
179     return OMPScheduleType::OrderedGuidedChunked;
180   else if (OrderingScheduleType == (OMPScheduleType::BaseRuntimeSimd |
181                                     OMPScheduleType::ModifierOrdered))
182     return OMPScheduleType::OrderedRuntime;
183 
184   return OrderingScheduleType;
185 }
186 
187 /// Adds monotonicity modifier flags to schedule type.
188 static OMPScheduleType
189 getOpenMPMonotonicityScheduleType(OMPScheduleType ScheduleType,
190                                   bool HasSimdModifier, bool HasMonotonic,
191                                   bool HasNonmonotonic, bool HasOrderedClause) {
192   assert((ScheduleType & OMPScheduleType::MonotonicityMask) ==
193              OMPScheduleType::None &&
194          "Must not have monotonicity flags already set");
195   assert((!HasMonotonic || !HasNonmonotonic) &&
196          "Monotonic and Nonmonotonic are contradicting each other");
197 
198   if (HasMonotonic) {
199     return ScheduleType | OMPScheduleType::ModifierMonotonic;
200   } else if (HasNonmonotonic) {
201     return ScheduleType | OMPScheduleType::ModifierNonmonotonic;
202   } else {
203     // OpenMP 5.1, 2.11.4 Worksharing-Loop Construct, Description.
204     // If the static schedule kind is specified or if the ordered clause is
205     // specified, and if the nonmonotonic modifier is not specified, the
206     // effect is as if the monotonic modifier is specified. Otherwise, unless
207     // the monotonic modifier is specified, the effect is as if the
208     // nonmonotonic modifier is specified.
209     OMPScheduleType BaseScheduleType =
210         ScheduleType & ~OMPScheduleType::ModifierMask;
211     if ((BaseScheduleType == OMPScheduleType::BaseStatic) ||
212         (BaseScheduleType == OMPScheduleType::BaseStaticChunked) ||
213         HasOrderedClause) {
214       // The monotonic is used by default in openmp runtime library, so no need
215       // to set it.
216       return ScheduleType;
217     } else {
218       return ScheduleType | OMPScheduleType::ModifierNonmonotonic;
219     }
220   }
221 }
222 
223 /// Determine the schedule type using schedule and ordering clause arguments.
224 static OMPScheduleType
225 computeOpenMPScheduleType(ScheduleKind ClauseKind, bool HasChunks,
226                           bool HasSimdModifier, bool HasMonotonicModifier,
227                           bool HasNonmonotonicModifier, bool HasOrderedClause) {
228   OMPScheduleType BaseSchedule =
229       getOpenMPBaseScheduleType(ClauseKind, HasChunks, HasSimdModifier);
230   OMPScheduleType OrderedSchedule =
231       getOpenMPOrderingScheduleType(BaseSchedule, HasOrderedClause);
232   OMPScheduleType Result = getOpenMPMonotonicityScheduleType(
233       OrderedSchedule, HasSimdModifier, HasMonotonicModifier,
234       HasNonmonotonicModifier, HasOrderedClause);
235 
236   assert(isValidWorkshareLoopScheduleType(Result));
237   return Result;
238 }
239 
240 /// Make \p Source branch to \p Target.
241 ///
242 /// Handles two situations:
243 /// * \p Source already has an unconditional branch.
244 /// * \p Source is a degenerate block (no terminator because the BB is
245 ///             the current head of the IR construction).
246 static void redirectTo(BasicBlock *Source, BasicBlock *Target, DebugLoc DL) {
247   if (Instruction *Term = Source->getTerminator()) {
248     auto *Br = cast<BranchInst>(Term);
249     assert(!Br->isConditional() &&
250            "BB's terminator must be an unconditional branch (or degenerate)");
251     BasicBlock *Succ = Br->getSuccessor(0);
252     Succ->removePredecessor(Source, /*KeepOneInputPHIs=*/true);
253     Br->setSuccessor(0, Target);
254     return;
255   }
256 
257   auto *NewBr = BranchInst::Create(Target, Source);
258   NewBr->setDebugLoc(DL);
259 }
260 
261 void llvm::spliceBB(IRBuilderBase::InsertPoint IP, BasicBlock *New,
262                     bool CreateBranch) {
263   assert(New->getFirstInsertionPt() == New->begin() &&
264          "Target BB must not have PHI nodes");
265 
266   // Move instructions to new block.
267   BasicBlock *Old = IP.getBlock();
268   New->splice(New->begin(), Old, IP.getPoint(), Old->end());
269 
270   if (CreateBranch)
271     BranchInst::Create(New, Old);
272 }
273 
274 void llvm::spliceBB(IRBuilder<> &Builder, BasicBlock *New, bool CreateBranch) {
275   DebugLoc DebugLoc = Builder.getCurrentDebugLocation();
276   BasicBlock *Old = Builder.GetInsertBlock();
277 
278   spliceBB(Builder.saveIP(), New, CreateBranch);
279   if (CreateBranch)
280     Builder.SetInsertPoint(Old->getTerminator());
281   else
282     Builder.SetInsertPoint(Old);
283 
284   // SetInsertPoint also updates the Builder's debug location, but we want to
285   // keep the one the Builder was configured to use.
286   Builder.SetCurrentDebugLocation(DebugLoc);
287 }
288 
289 BasicBlock *llvm::splitBB(IRBuilderBase::InsertPoint IP, bool CreateBranch,
290                           llvm::Twine Name) {
291   BasicBlock *Old = IP.getBlock();
292   BasicBlock *New = BasicBlock::Create(
293       Old->getContext(), Name.isTriviallyEmpty() ? Old->getName() : Name,
294       Old->getParent(), Old->getNextNode());
295   spliceBB(IP, New, CreateBranch);
296   New->replaceSuccessorsPhiUsesWith(Old, New);
297   return New;
298 }
299 
300 BasicBlock *llvm::splitBB(IRBuilderBase &Builder, bool CreateBranch,
301                           llvm::Twine Name) {
302   DebugLoc DebugLoc = Builder.getCurrentDebugLocation();
303   BasicBlock *New = splitBB(Builder.saveIP(), CreateBranch, Name);
304   if (CreateBranch)
305     Builder.SetInsertPoint(Builder.GetInsertBlock()->getTerminator());
306   else
307     Builder.SetInsertPoint(Builder.GetInsertBlock());
308   // SetInsertPoint also updates the Builder's debug location, but we want to
309   // keep the one the Builder was configured to use.
310   Builder.SetCurrentDebugLocation(DebugLoc);
311   return New;
312 }
313 
314 BasicBlock *llvm::splitBB(IRBuilder<> &Builder, bool CreateBranch,
315                           llvm::Twine Name) {
316   DebugLoc DebugLoc = Builder.getCurrentDebugLocation();
317   BasicBlock *New = splitBB(Builder.saveIP(), CreateBranch, Name);
318   if (CreateBranch)
319     Builder.SetInsertPoint(Builder.GetInsertBlock()->getTerminator());
320   else
321     Builder.SetInsertPoint(Builder.GetInsertBlock());
322   // SetInsertPoint also updates the Builder's debug location, but we want to
323   // keep the one the Builder was configured to use.
324   Builder.SetCurrentDebugLocation(DebugLoc);
325   return New;
326 }
327 
328 BasicBlock *llvm::splitBBWithSuffix(IRBuilderBase &Builder, bool CreateBranch,
329                                     llvm::Twine Suffix) {
330   BasicBlock *Old = Builder.GetInsertBlock();
331   return splitBB(Builder, CreateBranch, Old->getName() + Suffix);
332 }
333 
334 void OpenMPIRBuilder::getKernelArgsVector(TargetKernelArgs &KernelArgs,
335                                           IRBuilderBase &Builder,
336                                           SmallVector<Value *> &ArgsVector) {
337   Value *Version = Builder.getInt32(OMP_KERNEL_ARG_VERSION);
338   Value *PointerNum = Builder.getInt32(KernelArgs.NumTargetItems);
339   auto Int32Ty = Type::getInt32Ty(Builder.getContext());
340   Value *ZeroArray = Constant::getNullValue(ArrayType::get(Int32Ty, 3));
341   Value *Flags = Builder.getInt64(KernelArgs.HasNoWait);
342 
343   Value *NumTeams3D =
344       Builder.CreateInsertValue(ZeroArray, KernelArgs.NumTeams, {0});
345   Value *NumThreads3D =
346       Builder.CreateInsertValue(ZeroArray, KernelArgs.NumThreads, {0});
347 
348   ArgsVector = {Version,
349                 PointerNum,
350                 KernelArgs.RTArgs.BasePointersArray,
351                 KernelArgs.RTArgs.PointersArray,
352                 KernelArgs.RTArgs.SizesArray,
353                 KernelArgs.RTArgs.MapTypesArray,
354                 KernelArgs.RTArgs.MapNamesArray,
355                 KernelArgs.RTArgs.MappersArray,
356                 KernelArgs.NumIterations,
357                 Flags,
358                 NumTeams3D,
359                 NumThreads3D,
360                 KernelArgs.DynCGGroupMem};
361 }
362 
363 void OpenMPIRBuilder::addAttributes(omp::RuntimeFunction FnID, Function &Fn) {
364   LLVMContext &Ctx = Fn.getContext();
365   Triple T(M.getTargetTriple());
366 
367   // Get the function's current attributes.
368   auto Attrs = Fn.getAttributes();
369   auto FnAttrs = Attrs.getFnAttrs();
370   auto RetAttrs = Attrs.getRetAttrs();
371   SmallVector<AttributeSet, 4> ArgAttrs;
372   for (size_t ArgNo = 0; ArgNo < Fn.arg_size(); ++ArgNo)
373     ArgAttrs.emplace_back(Attrs.getParamAttrs(ArgNo));
374 
375   // Add AS to FnAS while taking special care with integer extensions.
376   auto addAttrSet = [&](AttributeSet &FnAS, const AttributeSet &AS,
377                         bool Param = true) -> void {
378     bool HasSignExt = AS.hasAttribute(Attribute::SExt);
379     bool HasZeroExt = AS.hasAttribute(Attribute::ZExt);
380     if (HasSignExt || HasZeroExt) {
381       assert(AS.getNumAttributes() == 1 &&
382              "Currently not handling extension attr combined with others.");
383       if (Param) {
384         if (auto AK = TargetLibraryInfo::getExtAttrForI32Param(T, HasSignExt))
385           FnAS = FnAS.addAttribute(Ctx, AK);
386       } else
387         if (auto AK = TargetLibraryInfo::getExtAttrForI32Return(T, HasSignExt))
388           FnAS = FnAS.addAttribute(Ctx, AK);
389     } else {
390       FnAS = FnAS.addAttributes(Ctx, AS);
391     }
392   };
393 
394 #define OMP_ATTRS_SET(VarName, AttrSet) AttributeSet VarName = AttrSet;
395 #include "llvm/Frontend/OpenMP/OMPKinds.def"
396 
397   // Add attributes to the function declaration.
398   switch (FnID) {
399 #define OMP_RTL_ATTRS(Enum, FnAttrSet, RetAttrSet, ArgAttrSets)                \
400   case Enum:                                                                   \
401     FnAttrs = FnAttrs.addAttributes(Ctx, FnAttrSet);                           \
402     addAttrSet(RetAttrs, RetAttrSet, /*Param*/false);                          \
403     for (size_t ArgNo = 0; ArgNo < ArgAttrSets.size(); ++ArgNo)                \
404       addAttrSet(ArgAttrs[ArgNo], ArgAttrSets[ArgNo]);                         \
405     Fn.setAttributes(AttributeList::get(Ctx, FnAttrs, RetAttrs, ArgAttrs));    \
406     break;
407 #include "llvm/Frontend/OpenMP/OMPKinds.def"
408   default:
409     // Attributes are optional.
410     break;
411   }
412 }
413 
414 FunctionCallee
415 OpenMPIRBuilder::getOrCreateRuntimeFunction(Module &M, RuntimeFunction FnID) {
416   FunctionType *FnTy = nullptr;
417   Function *Fn = nullptr;
418 
419   // Try to find the declation in the module first.
420   switch (FnID) {
421 #define OMP_RTL(Enum, Str, IsVarArg, ReturnType, ...)                          \
422   case Enum:                                                                   \
423     FnTy = FunctionType::get(ReturnType, ArrayRef<Type *>{__VA_ARGS__},        \
424                              IsVarArg);                                        \
425     Fn = M.getFunction(Str);                                                   \
426     break;
427 #include "llvm/Frontend/OpenMP/OMPKinds.def"
428   }
429 
430   if (!Fn) {
431     // Create a new declaration if we need one.
432     switch (FnID) {
433 #define OMP_RTL(Enum, Str, ...)                                                \
434   case Enum:                                                                   \
435     Fn = Function::Create(FnTy, GlobalValue::ExternalLinkage, Str, M);         \
436     break;
437 #include "llvm/Frontend/OpenMP/OMPKinds.def"
438     }
439 
440     // Add information if the runtime function takes a callback function
441     if (FnID == OMPRTL___kmpc_fork_call || FnID == OMPRTL___kmpc_fork_teams) {
442       if (!Fn->hasMetadata(LLVMContext::MD_callback)) {
443         LLVMContext &Ctx = Fn->getContext();
444         MDBuilder MDB(Ctx);
445         // Annotate the callback behavior of the runtime function:
446         //  - The callback callee is argument number 2 (microtask).
447         //  - The first two arguments of the callback callee are unknown (-1).
448         //  - All variadic arguments to the runtime function are passed to the
449         //    callback callee.
450         Fn->addMetadata(
451             LLVMContext::MD_callback,
452             *MDNode::get(Ctx, {MDB.createCallbackEncoding(
453                                   2, {-1, -1}, /* VarArgsArePassed */ true)}));
454       }
455     }
456 
457     LLVM_DEBUG(dbgs() << "Created OpenMP runtime function " << Fn->getName()
458                       << " with type " << *Fn->getFunctionType() << "\n");
459     addAttributes(FnID, *Fn);
460 
461   } else {
462     LLVM_DEBUG(dbgs() << "Found OpenMP runtime function " << Fn->getName()
463                       << " with type " << *Fn->getFunctionType() << "\n");
464   }
465 
466   assert(Fn && "Failed to create OpenMP runtime function");
467 
468   return {FnTy, Fn};
469 }
470 
471 Function *OpenMPIRBuilder::getOrCreateRuntimeFunctionPtr(RuntimeFunction FnID) {
472   FunctionCallee RTLFn = getOrCreateRuntimeFunction(M, FnID);
473   auto *Fn = dyn_cast<llvm::Function>(RTLFn.getCallee());
474   assert(Fn && "Failed to create OpenMP runtime function pointer");
475   return Fn;
476 }
477 
478 void OpenMPIRBuilder::initialize(StringRef HostFilePath) {
479   initializeTypes(M);
480 
481   if (HostFilePath.empty())
482     return;
483 
484   auto Buf = MemoryBuffer::getFile(HostFilePath);
485   if (std::error_code Err = Buf.getError()) {
486     report_fatal_error(("error opening host file from host file path inside of "
487                         "OpenMPIRBuilder: " +
488                         Err.message())
489                            .c_str());
490   }
491 
492   LLVMContext Ctx;
493   auto M = expectedToErrorOrAndEmitErrors(
494       Ctx, parseBitcodeFile(Buf.get()->getMemBufferRef(), Ctx));
495   if (std::error_code Err = M.getError()) {
496     report_fatal_error(
497         ("error parsing host file inside of OpenMPIRBuilder: " + Err.message())
498             .c_str());
499   }
500 
501   loadOffloadInfoMetadata(*M.get());
502 }
503 
504 void OpenMPIRBuilder::finalize(Function *Fn) {
505   SmallPtrSet<BasicBlock *, 32> ParallelRegionBlockSet;
506   SmallVector<BasicBlock *, 32> Blocks;
507   SmallVector<OutlineInfo, 16> DeferredOutlines;
508   for (OutlineInfo &OI : OutlineInfos) {
509     // Skip functions that have not finalized yet; may happen with nested
510     // function generation.
511     if (Fn && OI.getFunction() != Fn) {
512       DeferredOutlines.push_back(OI);
513       continue;
514     }
515 
516     ParallelRegionBlockSet.clear();
517     Blocks.clear();
518     OI.collectBlocks(ParallelRegionBlockSet, Blocks);
519 
520     Function *OuterFn = OI.getFunction();
521     CodeExtractorAnalysisCache CEAC(*OuterFn);
522     CodeExtractor Extractor(Blocks, /* DominatorTree */ nullptr,
523                             /* AggregateArgs */ true,
524                             /* BlockFrequencyInfo */ nullptr,
525                             /* BranchProbabilityInfo */ nullptr,
526                             /* AssumptionCache */ nullptr,
527                             /* AllowVarArgs */ true,
528                             /* AllowAlloca */ true,
529                             /* AllocaBlock*/ OI.OuterAllocaBB,
530                             /* Suffix */ ".omp_par");
531 
532     LLVM_DEBUG(dbgs() << "Before     outlining: " << *OuterFn << "\n");
533     LLVM_DEBUG(dbgs() << "Entry " << OI.EntryBB->getName()
534                       << " Exit: " << OI.ExitBB->getName() << "\n");
535     assert(Extractor.isEligible() &&
536            "Expected OpenMP outlining to be possible!");
537 
538     for (auto *V : OI.ExcludeArgsFromAggregate)
539       Extractor.excludeArgFromAggregate(V);
540 
541     Function *OutlinedFn = Extractor.extractCodeRegion(CEAC);
542 
543     LLVM_DEBUG(dbgs() << "After      outlining: " << *OuterFn << "\n");
544     LLVM_DEBUG(dbgs() << "   Outlined function: " << *OutlinedFn << "\n");
545     assert(OutlinedFn->getReturnType()->isVoidTy() &&
546            "OpenMP outlined functions should not return a value!");
547 
548     // For compability with the clang CG we move the outlined function after the
549     // one with the parallel region.
550     OutlinedFn->removeFromParent();
551     M.getFunctionList().insertAfter(OuterFn->getIterator(), OutlinedFn);
552 
553     // Remove the artificial entry introduced by the extractor right away, we
554     // made our own entry block after all.
555     {
556       BasicBlock &ArtificialEntry = OutlinedFn->getEntryBlock();
557       assert(ArtificialEntry.getUniqueSuccessor() == OI.EntryBB);
558       assert(OI.EntryBB->getUniquePredecessor() == &ArtificialEntry);
559       // Move instructions from the to-be-deleted ArtificialEntry to the entry
560       // basic block of the parallel region. CodeExtractor generates
561       // instructions to unwrap the aggregate argument and may sink
562       // allocas/bitcasts for values that are solely used in the outlined region
563       // and do not escape.
564       assert(!ArtificialEntry.empty() &&
565              "Expected instructions to add in the outlined region entry");
566       for (BasicBlock::reverse_iterator It = ArtificialEntry.rbegin(),
567                                         End = ArtificialEntry.rend();
568            It != End;) {
569         Instruction &I = *It;
570         It++;
571 
572         if (I.isTerminator())
573           continue;
574 
575         I.moveBefore(*OI.EntryBB, OI.EntryBB->getFirstInsertionPt());
576       }
577 
578       OI.EntryBB->moveBefore(&ArtificialEntry);
579       ArtificialEntry.eraseFromParent();
580     }
581     assert(&OutlinedFn->getEntryBlock() == OI.EntryBB);
582     assert(OutlinedFn && OutlinedFn->getNumUses() == 1);
583 
584     // Run a user callback, e.g. to add attributes.
585     if (OI.PostOutlineCB)
586       OI.PostOutlineCB(*OutlinedFn);
587   }
588 
589   // Remove work items that have been completed.
590   OutlineInfos = std::move(DeferredOutlines);
591 
592   EmitMetadataErrorReportFunctionTy &&ErrorReportFn =
593       [](EmitMetadataErrorKind Kind,
594          const TargetRegionEntryInfo &EntryInfo) -> void {
595     errs() << "Error of kind: " << Kind
596            << " when emitting offload entries and metadata during "
597               "OMPIRBuilder finalization \n";
598   };
599 
600   if (!OffloadInfoManager.empty())
601     createOffloadEntriesAndInfoMetadata(ErrorReportFn);
602 }
603 
604 OpenMPIRBuilder::~OpenMPIRBuilder() {
605   assert(OutlineInfos.empty() && "There must be no outstanding outlinings");
606 }
607 
608 GlobalValue *OpenMPIRBuilder::createGlobalFlag(unsigned Value, StringRef Name) {
609   IntegerType *I32Ty = Type::getInt32Ty(M.getContext());
610   auto *GV =
611       new GlobalVariable(M, I32Ty,
612                          /* isConstant = */ true, GlobalValue::WeakODRLinkage,
613                          ConstantInt::get(I32Ty, Value), Name);
614   GV->setVisibility(GlobalValue::HiddenVisibility);
615 
616   return GV;
617 }
618 
619 Constant *OpenMPIRBuilder::getOrCreateIdent(Constant *SrcLocStr,
620                                             uint32_t SrcLocStrSize,
621                                             IdentFlag LocFlags,
622                                             unsigned Reserve2Flags) {
623   // Enable "C-mode".
624   LocFlags |= OMP_IDENT_FLAG_KMPC;
625 
626   Constant *&Ident =
627       IdentMap[{SrcLocStr, uint64_t(LocFlags) << 31 | Reserve2Flags}];
628   if (!Ident) {
629     Constant *I32Null = ConstantInt::getNullValue(Int32);
630     Constant *IdentData[] = {I32Null,
631                              ConstantInt::get(Int32, uint32_t(LocFlags)),
632                              ConstantInt::get(Int32, Reserve2Flags),
633                              ConstantInt::get(Int32, SrcLocStrSize), SrcLocStr};
634     Constant *Initializer =
635         ConstantStruct::get(OpenMPIRBuilder::Ident, IdentData);
636 
637     // Look for existing encoding of the location + flags, not needed but
638     // minimizes the difference to the existing solution while we transition.
639     for (GlobalVariable &GV : M.globals())
640       if (GV.getValueType() == OpenMPIRBuilder::Ident && GV.hasInitializer())
641         if (GV.getInitializer() == Initializer)
642           Ident = &GV;
643 
644     if (!Ident) {
645       auto *GV = new GlobalVariable(
646           M, OpenMPIRBuilder::Ident,
647           /* isConstant = */ true, GlobalValue::PrivateLinkage, Initializer, "",
648           nullptr, GlobalValue::NotThreadLocal,
649           M.getDataLayout().getDefaultGlobalsAddressSpace());
650       GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
651       GV->setAlignment(Align(8));
652       Ident = GV;
653     }
654   }
655 
656   return ConstantExpr::getPointerBitCastOrAddrSpaceCast(Ident, IdentPtr);
657 }
658 
659 Constant *OpenMPIRBuilder::getOrCreateSrcLocStr(StringRef LocStr,
660                                                 uint32_t &SrcLocStrSize) {
661   SrcLocStrSize = LocStr.size();
662   Constant *&SrcLocStr = SrcLocStrMap[LocStr];
663   if (!SrcLocStr) {
664     Constant *Initializer =
665         ConstantDataArray::getString(M.getContext(), LocStr);
666 
667     // Look for existing encoding of the location, not needed but minimizes the
668     // difference to the existing solution while we transition.
669     for (GlobalVariable &GV : M.globals())
670       if (GV.isConstant() && GV.hasInitializer() &&
671           GV.getInitializer() == Initializer)
672         return SrcLocStr = ConstantExpr::getPointerCast(&GV, Int8Ptr);
673 
674     SrcLocStr = Builder.CreateGlobalStringPtr(LocStr, /* Name */ "",
675                                               /* AddressSpace */ 0, &M);
676   }
677   return SrcLocStr;
678 }
679 
680 Constant *OpenMPIRBuilder::getOrCreateSrcLocStr(StringRef FunctionName,
681                                                 StringRef FileName,
682                                                 unsigned Line, unsigned Column,
683                                                 uint32_t &SrcLocStrSize) {
684   SmallString<128> Buffer;
685   Buffer.push_back(';');
686   Buffer.append(FileName);
687   Buffer.push_back(';');
688   Buffer.append(FunctionName);
689   Buffer.push_back(';');
690   Buffer.append(std::to_string(Line));
691   Buffer.push_back(';');
692   Buffer.append(std::to_string(Column));
693   Buffer.push_back(';');
694   Buffer.push_back(';');
695   return getOrCreateSrcLocStr(Buffer.str(), SrcLocStrSize);
696 }
697 
698 Constant *
699 OpenMPIRBuilder::getOrCreateDefaultSrcLocStr(uint32_t &SrcLocStrSize) {
700   StringRef UnknownLoc = ";unknown;unknown;0;0;;";
701   return getOrCreateSrcLocStr(UnknownLoc, SrcLocStrSize);
702 }
703 
704 Constant *OpenMPIRBuilder::getOrCreateSrcLocStr(DebugLoc DL,
705                                                 uint32_t &SrcLocStrSize,
706                                                 Function *F) {
707   DILocation *DIL = DL.get();
708   if (!DIL)
709     return getOrCreateDefaultSrcLocStr(SrcLocStrSize);
710   StringRef FileName = M.getName();
711   if (DIFile *DIF = DIL->getFile())
712     if (std::optional<StringRef> Source = DIF->getSource())
713       FileName = *Source;
714   StringRef Function = DIL->getScope()->getSubprogram()->getName();
715   if (Function.empty() && F)
716     Function = F->getName();
717   return getOrCreateSrcLocStr(Function, FileName, DIL->getLine(),
718                               DIL->getColumn(), SrcLocStrSize);
719 }
720 
721 Constant *OpenMPIRBuilder::getOrCreateSrcLocStr(const LocationDescription &Loc,
722                                                 uint32_t &SrcLocStrSize) {
723   return getOrCreateSrcLocStr(Loc.DL, SrcLocStrSize,
724                               Loc.IP.getBlock()->getParent());
725 }
726 
727 Value *OpenMPIRBuilder::getOrCreateThreadID(Value *Ident) {
728   return Builder.CreateCall(
729       getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_global_thread_num), Ident,
730       "omp_global_thread_num");
731 }
732 
733 OpenMPIRBuilder::InsertPointTy
734 OpenMPIRBuilder::createBarrier(const LocationDescription &Loc, Directive DK,
735                                bool ForceSimpleCall, bool CheckCancelFlag) {
736   if (!updateToLocation(Loc))
737     return Loc.IP;
738   return emitBarrierImpl(Loc, DK, ForceSimpleCall, CheckCancelFlag);
739 }
740 
741 OpenMPIRBuilder::InsertPointTy
742 OpenMPIRBuilder::emitBarrierImpl(const LocationDescription &Loc, Directive Kind,
743                                  bool ForceSimpleCall, bool CheckCancelFlag) {
744   // Build call __kmpc_cancel_barrier(loc, thread_id) or
745   //            __kmpc_barrier(loc, thread_id);
746 
747   IdentFlag BarrierLocFlags;
748   switch (Kind) {
749   case OMPD_for:
750     BarrierLocFlags = OMP_IDENT_FLAG_BARRIER_IMPL_FOR;
751     break;
752   case OMPD_sections:
753     BarrierLocFlags = OMP_IDENT_FLAG_BARRIER_IMPL_SECTIONS;
754     break;
755   case OMPD_single:
756     BarrierLocFlags = OMP_IDENT_FLAG_BARRIER_IMPL_SINGLE;
757     break;
758   case OMPD_barrier:
759     BarrierLocFlags = OMP_IDENT_FLAG_BARRIER_EXPL;
760     break;
761   default:
762     BarrierLocFlags = OMP_IDENT_FLAG_BARRIER_IMPL;
763     break;
764   }
765 
766   uint32_t SrcLocStrSize;
767   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
768   Value *Args[] = {
769       getOrCreateIdent(SrcLocStr, SrcLocStrSize, BarrierLocFlags),
770       getOrCreateThreadID(getOrCreateIdent(SrcLocStr, SrcLocStrSize))};
771 
772   // If we are in a cancellable parallel region, barriers are cancellation
773   // points.
774   // TODO: Check why we would force simple calls or to ignore the cancel flag.
775   bool UseCancelBarrier =
776       !ForceSimpleCall && isLastFinalizationInfoCancellable(OMPD_parallel);
777 
778   Value *Result =
779       Builder.CreateCall(getOrCreateRuntimeFunctionPtr(
780                              UseCancelBarrier ? OMPRTL___kmpc_cancel_barrier
781                                               : OMPRTL___kmpc_barrier),
782                          Args);
783 
784   if (UseCancelBarrier && CheckCancelFlag)
785     emitCancelationCheckImpl(Result, OMPD_parallel);
786 
787   return Builder.saveIP();
788 }
789 
790 OpenMPIRBuilder::InsertPointTy
791 OpenMPIRBuilder::createCancel(const LocationDescription &Loc,
792                               Value *IfCondition,
793                               omp::Directive CanceledDirective) {
794   if (!updateToLocation(Loc))
795     return Loc.IP;
796 
797   // LLVM utilities like blocks with terminators.
798   auto *UI = Builder.CreateUnreachable();
799 
800   Instruction *ThenTI = UI, *ElseTI = nullptr;
801   if (IfCondition)
802     SplitBlockAndInsertIfThenElse(IfCondition, UI, &ThenTI, &ElseTI);
803   Builder.SetInsertPoint(ThenTI);
804 
805   Value *CancelKind = nullptr;
806   switch (CanceledDirective) {
807 #define OMP_CANCEL_KIND(Enum, Str, DirectiveEnum, Value)                       \
808   case DirectiveEnum:                                                          \
809     CancelKind = Builder.getInt32(Value);                                      \
810     break;
811 #include "llvm/Frontend/OpenMP/OMPKinds.def"
812   default:
813     llvm_unreachable("Unknown cancel kind!");
814   }
815 
816   uint32_t SrcLocStrSize;
817   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
818   Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
819   Value *Args[] = {Ident, getOrCreateThreadID(Ident), CancelKind};
820   Value *Result = Builder.CreateCall(
821       getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_cancel), Args);
822   auto ExitCB = [this, CanceledDirective, Loc](InsertPointTy IP) {
823     if (CanceledDirective == OMPD_parallel) {
824       IRBuilder<>::InsertPointGuard IPG(Builder);
825       Builder.restoreIP(IP);
826       createBarrier(LocationDescription(Builder.saveIP(), Loc.DL),
827                     omp::Directive::OMPD_unknown, /* ForceSimpleCall */ false,
828                     /* CheckCancelFlag */ false);
829     }
830   };
831 
832   // The actual cancel logic is shared with others, e.g., cancel_barriers.
833   emitCancelationCheckImpl(Result, CanceledDirective, ExitCB);
834 
835   // Update the insertion point and remove the terminator we introduced.
836   Builder.SetInsertPoint(UI->getParent());
837   UI->eraseFromParent();
838 
839   return Builder.saveIP();
840 }
841 
842 void OpenMPIRBuilder::emitOffloadingEntry(Constant *Addr, StringRef Name,
843                                           uint64_t Size, int32_t Flags,
844                                           StringRef SectionName) {
845   Type *Int8PtrTy = Type::getInt8PtrTy(M.getContext());
846   Type *Int32Ty = Type::getInt32Ty(M.getContext());
847   Type *SizeTy = M.getDataLayout().getIntPtrType(M.getContext());
848 
849   Constant *AddrName = ConstantDataArray::getString(M.getContext(), Name);
850 
851   // Create the constant string used to look up the symbol in the device.
852   auto *Str =
853       new llvm::GlobalVariable(M, AddrName->getType(), /*isConstant=*/true,
854                                llvm::GlobalValue::InternalLinkage, AddrName,
855                                ".omp_offloading.entry_name");
856   Str->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
857 
858   // Construct the offloading entry.
859   Constant *EntryData[] = {
860       ConstantExpr::getPointerBitCastOrAddrSpaceCast(Addr, Int8PtrTy),
861       ConstantExpr::getPointerBitCastOrAddrSpaceCast(Str, Int8PtrTy),
862       ConstantInt::get(SizeTy, Size),
863       ConstantInt::get(Int32Ty, Flags),
864       ConstantInt::get(Int32Ty, 0),
865   };
866   Constant *EntryInitializer =
867       ConstantStruct::get(OpenMPIRBuilder::OffloadEntry, EntryData);
868 
869   auto *Entry = new GlobalVariable(
870       M, OpenMPIRBuilder::OffloadEntry,
871       /* isConstant = */ true, GlobalValue::WeakAnyLinkage, EntryInitializer,
872       ".omp_offloading.entry." + Name, nullptr, GlobalValue::NotThreadLocal,
873       M.getDataLayout().getDefaultGlobalsAddressSpace());
874 
875   // The entry has to be created in the section the linker expects it to be.
876   Entry->setSection(SectionName);
877   Entry->setAlignment(Align(1));
878 }
879 
880 OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::emitTargetKernel(
881     const LocationDescription &Loc, InsertPointTy AllocaIP, Value *&Return,
882     Value *Ident, Value *DeviceID, Value *NumTeams, Value *NumThreads,
883     Value *HostPtr, ArrayRef<Value *> KernelArgs) {
884   if (!updateToLocation(Loc))
885     return Loc.IP;
886 
887   Builder.restoreIP(AllocaIP);
888   auto *KernelArgsPtr =
889       Builder.CreateAlloca(OpenMPIRBuilder::KernelArgs, nullptr, "kernel_args");
890   Builder.restoreIP(Loc.IP);
891 
892   for (unsigned I = 0, Size = KernelArgs.size(); I != Size; ++I) {
893     llvm::Value *Arg =
894         Builder.CreateStructGEP(OpenMPIRBuilder::KernelArgs, KernelArgsPtr, I);
895     Builder.CreateAlignedStore(
896         KernelArgs[I], Arg,
897         M.getDataLayout().getPrefTypeAlign(KernelArgs[I]->getType()));
898   }
899 
900   SmallVector<Value *> OffloadingArgs{Ident,      DeviceID, NumTeams,
901                                       NumThreads, HostPtr,  KernelArgsPtr};
902 
903   Return = Builder.CreateCall(
904       getOrCreateRuntimeFunction(M, OMPRTL___tgt_target_kernel),
905       OffloadingArgs);
906 
907   return Builder.saveIP();
908 }
909 
910 OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::emitKernelLaunch(
911     const LocationDescription &Loc, Function *OutlinedFn, Value *OutlinedFnID,
912     EmitFallbackCallbackTy emitTargetCallFallbackCB, TargetKernelArgs &Args,
913     Value *DeviceID, Value *RTLoc, InsertPointTy AllocaIP) {
914 
915   if (!updateToLocation(Loc))
916     return Loc.IP;
917 
918   Builder.restoreIP(Loc.IP);
919   // On top of the arrays that were filled up, the target offloading call
920   // takes as arguments the device id as well as the host pointer. The host
921   // pointer is used by the runtime library to identify the current target
922   // region, so it only has to be unique and not necessarily point to
923   // anything. It could be the pointer to the outlined function that
924   // implements the target region, but we aren't using that so that the
925   // compiler doesn't need to keep that, and could therefore inline the host
926   // function if proven worthwhile during optimization.
927 
928   // From this point on, we need to have an ID of the target region defined.
929   assert(OutlinedFnID && "Invalid outlined function ID!");
930   (void)OutlinedFnID;
931 
932   // Return value of the runtime offloading call.
933   Value *Return;
934 
935   // Arguments for the target kernel.
936   SmallVector<Value *> ArgsVector;
937   getKernelArgsVector(Args, Builder, ArgsVector);
938 
939   // The target region is an outlined function launched by the runtime
940   // via calls to __tgt_target_kernel().
941   //
942   // Note that on the host and CPU targets, the runtime implementation of
943   // these calls simply call the outlined function without forking threads.
944   // The outlined functions themselves have runtime calls to
945   // __kmpc_fork_teams() and __kmpc_fork() for this purpose, codegen'd by
946   // the compiler in emitTeamsCall() and emitParallelCall().
947   //
948   // In contrast, on the NVPTX target, the implementation of
949   // __tgt_target_teams() launches a GPU kernel with the requested number
950   // of teams and threads so no additional calls to the runtime are required.
951   // Check the error code and execute the host version if required.
952   Builder.restoreIP(emitTargetKernel(Builder, AllocaIP, Return, RTLoc, DeviceID,
953                                      Args.NumTeams, Args.NumThreads,
954                                      OutlinedFnID, ArgsVector));
955 
956   BasicBlock *OffloadFailedBlock =
957       BasicBlock::Create(Builder.getContext(), "omp_offload.failed");
958   BasicBlock *OffloadContBlock =
959       BasicBlock::Create(Builder.getContext(), "omp_offload.cont");
960   Value *Failed = Builder.CreateIsNotNull(Return);
961   Builder.CreateCondBr(Failed, OffloadFailedBlock, OffloadContBlock);
962 
963   auto CurFn = Builder.GetInsertBlock()->getParent();
964   emitBlock(OffloadFailedBlock, CurFn);
965   Builder.restoreIP(emitTargetCallFallbackCB(Builder.saveIP()));
966   emitBranch(OffloadContBlock);
967   emitBlock(OffloadContBlock, CurFn, /*IsFinished=*/true);
968   return Builder.saveIP();
969 }
970 
971 void OpenMPIRBuilder::emitCancelationCheckImpl(Value *CancelFlag,
972                                                omp::Directive CanceledDirective,
973                                                FinalizeCallbackTy ExitCB) {
974   assert(isLastFinalizationInfoCancellable(CanceledDirective) &&
975          "Unexpected cancellation!");
976 
977   // For a cancel barrier we create two new blocks.
978   BasicBlock *BB = Builder.GetInsertBlock();
979   BasicBlock *NonCancellationBlock;
980   if (Builder.GetInsertPoint() == BB->end()) {
981     // TODO: This branch will not be needed once we moved to the
982     // OpenMPIRBuilder codegen completely.
983     NonCancellationBlock = BasicBlock::Create(
984         BB->getContext(), BB->getName() + ".cont", BB->getParent());
985   } else {
986     NonCancellationBlock = SplitBlock(BB, &*Builder.GetInsertPoint());
987     BB->getTerminator()->eraseFromParent();
988     Builder.SetInsertPoint(BB);
989   }
990   BasicBlock *CancellationBlock = BasicBlock::Create(
991       BB->getContext(), BB->getName() + ".cncl", BB->getParent());
992 
993   // Jump to them based on the return value.
994   Value *Cmp = Builder.CreateIsNull(CancelFlag);
995   Builder.CreateCondBr(Cmp, NonCancellationBlock, CancellationBlock,
996                        /* TODO weight */ nullptr, nullptr);
997 
998   // From the cancellation block we finalize all variables and go to the
999   // post finalization block that is known to the FiniCB callback.
1000   Builder.SetInsertPoint(CancellationBlock);
1001   if (ExitCB)
1002     ExitCB(Builder.saveIP());
1003   auto &FI = FinalizationStack.back();
1004   FI.FiniCB(Builder.saveIP());
1005 
1006   // The continuation block is where code generation continues.
1007   Builder.SetInsertPoint(NonCancellationBlock, NonCancellationBlock->begin());
1008 }
1009 
1010 IRBuilder<>::InsertPoint OpenMPIRBuilder::createParallel(
1011     const LocationDescription &Loc, InsertPointTy OuterAllocaIP,
1012     BodyGenCallbackTy BodyGenCB, PrivatizeCallbackTy PrivCB,
1013     FinalizeCallbackTy FiniCB, Value *IfCondition, Value *NumThreads,
1014     omp::ProcBindKind ProcBind, bool IsCancellable) {
1015   assert(!isConflictIP(Loc.IP, OuterAllocaIP) && "IPs must not be ambiguous");
1016 
1017   if (!updateToLocation(Loc))
1018     return Loc.IP;
1019 
1020   uint32_t SrcLocStrSize;
1021   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
1022   Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
1023   Value *ThreadID = getOrCreateThreadID(Ident);
1024 
1025   if (NumThreads) {
1026     // Build call __kmpc_push_num_threads(&Ident, global_tid, num_threads)
1027     Value *Args[] = {
1028         Ident, ThreadID,
1029         Builder.CreateIntCast(NumThreads, Int32, /*isSigned*/ false)};
1030     Builder.CreateCall(
1031         getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_push_num_threads), Args);
1032   }
1033 
1034   if (ProcBind != OMP_PROC_BIND_default) {
1035     // Build call __kmpc_push_proc_bind(&Ident, global_tid, proc_bind)
1036     Value *Args[] = {
1037         Ident, ThreadID,
1038         ConstantInt::get(Int32, unsigned(ProcBind), /*isSigned=*/true)};
1039     Builder.CreateCall(
1040         getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_push_proc_bind), Args);
1041   }
1042 
1043   BasicBlock *InsertBB = Builder.GetInsertBlock();
1044   Function *OuterFn = InsertBB->getParent();
1045 
1046   // Save the outer alloca block because the insertion iterator may get
1047   // invalidated and we still need this later.
1048   BasicBlock *OuterAllocaBlock = OuterAllocaIP.getBlock();
1049 
1050   // Vector to remember instructions we used only during the modeling but which
1051   // we want to delete at the end.
1052   SmallVector<Instruction *, 4> ToBeDeleted;
1053 
1054   // Change the location to the outer alloca insertion point to create and
1055   // initialize the allocas we pass into the parallel region.
1056   Builder.restoreIP(OuterAllocaIP);
1057   AllocaInst *TIDAddr = Builder.CreateAlloca(Int32, nullptr, "tid.addr");
1058   AllocaInst *ZeroAddr = Builder.CreateAlloca(Int32, nullptr, "zero.addr");
1059 
1060   // We only need TIDAddr and ZeroAddr for modeling purposes to get the
1061   // associated arguments in the outlined function, so we delete them later.
1062   ToBeDeleted.push_back(TIDAddr);
1063   ToBeDeleted.push_back(ZeroAddr);
1064 
1065   // Create an artificial insertion point that will also ensure the blocks we
1066   // are about to split are not degenerated.
1067   auto *UI = new UnreachableInst(Builder.getContext(), InsertBB);
1068 
1069   BasicBlock *EntryBB = UI->getParent();
1070   BasicBlock *PRegEntryBB = EntryBB->splitBasicBlock(UI, "omp.par.entry");
1071   BasicBlock *PRegBodyBB = PRegEntryBB->splitBasicBlock(UI, "omp.par.region");
1072   BasicBlock *PRegPreFiniBB =
1073       PRegBodyBB->splitBasicBlock(UI, "omp.par.pre_finalize");
1074   BasicBlock *PRegExitBB = PRegPreFiniBB->splitBasicBlock(UI, "omp.par.exit");
1075 
1076   auto FiniCBWrapper = [&](InsertPointTy IP) {
1077     // Hide "open-ended" blocks from the given FiniCB by setting the right jump
1078     // target to the region exit block.
1079     if (IP.getBlock()->end() == IP.getPoint()) {
1080       IRBuilder<>::InsertPointGuard IPG(Builder);
1081       Builder.restoreIP(IP);
1082       Instruction *I = Builder.CreateBr(PRegExitBB);
1083       IP = InsertPointTy(I->getParent(), I->getIterator());
1084     }
1085     assert(IP.getBlock()->getTerminator()->getNumSuccessors() == 1 &&
1086            IP.getBlock()->getTerminator()->getSuccessor(0) == PRegExitBB &&
1087            "Unexpected insertion point for finalization call!");
1088     return FiniCB(IP);
1089   };
1090 
1091   FinalizationStack.push_back({FiniCBWrapper, OMPD_parallel, IsCancellable});
1092 
1093   // Generate the privatization allocas in the block that will become the entry
1094   // of the outlined function.
1095   Builder.SetInsertPoint(PRegEntryBB->getTerminator());
1096   InsertPointTy InnerAllocaIP = Builder.saveIP();
1097 
1098   AllocaInst *PrivTIDAddr =
1099       Builder.CreateAlloca(Int32, nullptr, "tid.addr.local");
1100   Instruction *PrivTID = Builder.CreateLoad(Int32, PrivTIDAddr, "tid");
1101 
1102   // Add some fake uses for OpenMP provided arguments.
1103   ToBeDeleted.push_back(Builder.CreateLoad(Int32, TIDAddr, "tid.addr.use"));
1104   Instruction *ZeroAddrUse =
1105       Builder.CreateLoad(Int32, ZeroAddr, "zero.addr.use");
1106   ToBeDeleted.push_back(ZeroAddrUse);
1107 
1108   // EntryBB
1109   //   |
1110   //   V
1111   // PRegionEntryBB         <- Privatization allocas are placed here.
1112   //   |
1113   //   V
1114   // PRegionBodyBB          <- BodeGen is invoked here.
1115   //   |
1116   //   V
1117   // PRegPreFiniBB          <- The block we will start finalization from.
1118   //   |
1119   //   V
1120   // PRegionExitBB          <- A common exit to simplify block collection.
1121   //
1122 
1123   LLVM_DEBUG(dbgs() << "Before body codegen: " << *OuterFn << "\n");
1124 
1125   // Let the caller create the body.
1126   assert(BodyGenCB && "Expected body generation callback!");
1127   InsertPointTy CodeGenIP(PRegBodyBB, PRegBodyBB->begin());
1128   BodyGenCB(InnerAllocaIP, CodeGenIP);
1129 
1130   LLVM_DEBUG(dbgs() << "After  body codegen: " << *OuterFn << "\n");
1131   FunctionCallee RTLFn;
1132   if (IfCondition)
1133     RTLFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_fork_call_if);
1134   else
1135     RTLFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_fork_call);
1136 
1137   if (auto *F = dyn_cast<llvm::Function>(RTLFn.getCallee())) {
1138     if (!F->hasMetadata(llvm::LLVMContext::MD_callback)) {
1139       llvm::LLVMContext &Ctx = F->getContext();
1140       MDBuilder MDB(Ctx);
1141       // Annotate the callback behavior of the __kmpc_fork_call:
1142       //  - The callback callee is argument number 2 (microtask).
1143       //  - The first two arguments of the callback callee are unknown (-1).
1144       //  - All variadic arguments to the __kmpc_fork_call are passed to the
1145       //    callback callee.
1146       F->addMetadata(
1147           llvm::LLVMContext::MD_callback,
1148           *llvm::MDNode::get(
1149               Ctx, {MDB.createCallbackEncoding(2, {-1, -1},
1150                                                /* VarArgsArePassed */ true)}));
1151     }
1152   }
1153 
1154   OutlineInfo OI;
1155   OI.PostOutlineCB = [=](Function &OutlinedFn) {
1156     // Add some known attributes.
1157     OutlinedFn.addParamAttr(0, Attribute::NoAlias);
1158     OutlinedFn.addParamAttr(1, Attribute::NoAlias);
1159     OutlinedFn.addFnAttr(Attribute::NoUnwind);
1160     OutlinedFn.addFnAttr(Attribute::NoRecurse);
1161 
1162     assert(OutlinedFn.arg_size() >= 2 &&
1163            "Expected at least tid and bounded tid as arguments");
1164     unsigned NumCapturedVars =
1165         OutlinedFn.arg_size() - /* tid & bounded tid */ 2;
1166 
1167     CallInst *CI = cast<CallInst>(OutlinedFn.user_back());
1168     CI->getParent()->setName("omp_parallel");
1169     Builder.SetInsertPoint(CI);
1170 
1171     // Build call __kmpc_fork_call[_if](Ident, n, microtask, var1, .., varn);
1172     Value *ForkCallArgs[] = {
1173         Ident, Builder.getInt32(NumCapturedVars),
1174         Builder.CreateBitCast(&OutlinedFn, ParallelTaskPtr)};
1175 
1176     SmallVector<Value *, 16> RealArgs;
1177     RealArgs.append(std::begin(ForkCallArgs), std::end(ForkCallArgs));
1178     if (IfCondition) {
1179       Value *Cond = Builder.CreateSExtOrTrunc(IfCondition,
1180                                               Type::getInt32Ty(M.getContext()));
1181       RealArgs.push_back(Cond);
1182     }
1183     RealArgs.append(CI->arg_begin() + /* tid & bound tid */ 2, CI->arg_end());
1184 
1185     // __kmpc_fork_call_if always expects a void ptr as the last argument
1186     // If there are no arguments, pass a null pointer.
1187     auto PtrTy = Type::getInt8PtrTy(M.getContext());
1188     if (IfCondition && NumCapturedVars == 0) {
1189       llvm::Value *Void = ConstantPointerNull::get(PtrTy);
1190       RealArgs.push_back(Void);
1191     }
1192     if (IfCondition && RealArgs.back()->getType() != PtrTy)
1193       RealArgs.back() = Builder.CreateBitCast(RealArgs.back(), PtrTy);
1194 
1195     Builder.CreateCall(RTLFn, RealArgs);
1196 
1197     LLVM_DEBUG(dbgs() << "With fork_call placed: "
1198                       << *Builder.GetInsertBlock()->getParent() << "\n");
1199 
1200     InsertPointTy ExitIP(PRegExitBB, PRegExitBB->end());
1201 
1202     // Initialize the local TID stack location with the argument value.
1203     Builder.SetInsertPoint(PrivTID);
1204     Function::arg_iterator OutlinedAI = OutlinedFn.arg_begin();
1205     Builder.CreateStore(Builder.CreateLoad(Int32, OutlinedAI), PrivTIDAddr);
1206 
1207     CI->eraseFromParent();
1208 
1209     for (Instruction *I : ToBeDeleted)
1210       I->eraseFromParent();
1211   };
1212 
1213   // Adjust the finalization stack, verify the adjustment, and call the
1214   // finalize function a last time to finalize values between the pre-fini
1215   // block and the exit block if we left the parallel "the normal way".
1216   auto FiniInfo = FinalizationStack.pop_back_val();
1217   (void)FiniInfo;
1218   assert(FiniInfo.DK == OMPD_parallel &&
1219          "Unexpected finalization stack state!");
1220 
1221   Instruction *PRegPreFiniTI = PRegPreFiniBB->getTerminator();
1222 
1223   InsertPointTy PreFiniIP(PRegPreFiniBB, PRegPreFiniTI->getIterator());
1224   FiniCB(PreFiniIP);
1225 
1226   OI.OuterAllocaBB = OuterAllocaBlock;
1227   OI.EntryBB = PRegEntryBB;
1228   OI.ExitBB = PRegExitBB;
1229 
1230   SmallPtrSet<BasicBlock *, 32> ParallelRegionBlockSet;
1231   SmallVector<BasicBlock *, 32> Blocks;
1232   OI.collectBlocks(ParallelRegionBlockSet, Blocks);
1233 
1234   // Ensure a single exit node for the outlined region by creating one.
1235   // We might have multiple incoming edges to the exit now due to finalizations,
1236   // e.g., cancel calls that cause the control flow to leave the region.
1237   BasicBlock *PRegOutlinedExitBB = PRegExitBB;
1238   PRegExitBB = SplitBlock(PRegExitBB, &*PRegExitBB->getFirstInsertionPt());
1239   PRegOutlinedExitBB->setName("omp.par.outlined.exit");
1240   Blocks.push_back(PRegOutlinedExitBB);
1241 
1242   CodeExtractorAnalysisCache CEAC(*OuterFn);
1243   CodeExtractor Extractor(Blocks, /* DominatorTree */ nullptr,
1244                           /* AggregateArgs */ false,
1245                           /* BlockFrequencyInfo */ nullptr,
1246                           /* BranchProbabilityInfo */ nullptr,
1247                           /* AssumptionCache */ nullptr,
1248                           /* AllowVarArgs */ true,
1249                           /* AllowAlloca */ true,
1250                           /* AllocationBlock */ OuterAllocaBlock,
1251                           /* Suffix */ ".omp_par");
1252 
1253   // Find inputs to, outputs from the code region.
1254   BasicBlock *CommonExit = nullptr;
1255   SetVector<Value *> Inputs, Outputs, SinkingCands, HoistingCands;
1256   Extractor.findAllocas(CEAC, SinkingCands, HoistingCands, CommonExit);
1257   Extractor.findInputsOutputs(Inputs, Outputs, SinkingCands);
1258 
1259   LLVM_DEBUG(dbgs() << "Before privatization: " << *OuterFn << "\n");
1260 
1261   FunctionCallee TIDRTLFn =
1262       getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_global_thread_num);
1263 
1264   auto PrivHelper = [&](Value &V) {
1265     if (&V == TIDAddr || &V == ZeroAddr) {
1266       OI.ExcludeArgsFromAggregate.push_back(&V);
1267       return;
1268     }
1269 
1270     SetVector<Use *> Uses;
1271     for (Use &U : V.uses())
1272       if (auto *UserI = dyn_cast<Instruction>(U.getUser()))
1273         if (ParallelRegionBlockSet.count(UserI->getParent()))
1274           Uses.insert(&U);
1275 
1276     // __kmpc_fork_call expects extra arguments as pointers. If the input
1277     // already has a pointer type, everything is fine. Otherwise, store the
1278     // value onto stack and load it back inside the to-be-outlined region. This
1279     // will ensure only the pointer will be passed to the function.
1280     // FIXME: if there are more than 15 trailing arguments, they must be
1281     // additionally packed in a struct.
1282     Value *Inner = &V;
1283     if (!V.getType()->isPointerTy()) {
1284       IRBuilder<>::InsertPointGuard Guard(Builder);
1285       LLVM_DEBUG(llvm::dbgs() << "Forwarding input as pointer: " << V << "\n");
1286 
1287       Builder.restoreIP(OuterAllocaIP);
1288       Value *Ptr =
1289           Builder.CreateAlloca(V.getType(), nullptr, V.getName() + ".reloaded");
1290 
1291       // Store to stack at end of the block that currently branches to the entry
1292       // block of the to-be-outlined region.
1293       Builder.SetInsertPoint(InsertBB,
1294                              InsertBB->getTerminator()->getIterator());
1295       Builder.CreateStore(&V, Ptr);
1296 
1297       // Load back next to allocations in the to-be-outlined region.
1298       Builder.restoreIP(InnerAllocaIP);
1299       Inner = Builder.CreateLoad(V.getType(), Ptr);
1300     }
1301 
1302     Value *ReplacementValue = nullptr;
1303     CallInst *CI = dyn_cast<CallInst>(&V);
1304     if (CI && CI->getCalledFunction() == TIDRTLFn.getCallee()) {
1305       ReplacementValue = PrivTID;
1306     } else {
1307       Builder.restoreIP(
1308           PrivCB(InnerAllocaIP, Builder.saveIP(), V, *Inner, ReplacementValue));
1309       assert(ReplacementValue &&
1310              "Expected copy/create callback to set replacement value!");
1311       if (ReplacementValue == &V)
1312         return;
1313     }
1314 
1315     for (Use *UPtr : Uses)
1316       UPtr->set(ReplacementValue);
1317   };
1318 
1319   // Reset the inner alloca insertion as it will be used for loading the values
1320   // wrapped into pointers before passing them into the to-be-outlined region.
1321   // Configure it to insert immediately after the fake use of zero address so
1322   // that they are available in the generated body and so that the
1323   // OpenMP-related values (thread ID and zero address pointers) remain leading
1324   // in the argument list.
1325   InnerAllocaIP = IRBuilder<>::InsertPoint(
1326       ZeroAddrUse->getParent(), ZeroAddrUse->getNextNode()->getIterator());
1327 
1328   // Reset the outer alloca insertion point to the entry of the relevant block
1329   // in case it was invalidated.
1330   OuterAllocaIP = IRBuilder<>::InsertPoint(
1331       OuterAllocaBlock, OuterAllocaBlock->getFirstInsertionPt());
1332 
1333   for (Value *Input : Inputs) {
1334     LLVM_DEBUG(dbgs() << "Captured input: " << *Input << "\n");
1335     PrivHelper(*Input);
1336   }
1337   LLVM_DEBUG({
1338     for (Value *Output : Outputs)
1339       LLVM_DEBUG(dbgs() << "Captured output: " << *Output << "\n");
1340   });
1341   assert(Outputs.empty() &&
1342          "OpenMP outlining should not produce live-out values!");
1343 
1344   LLVM_DEBUG(dbgs() << "After  privatization: " << *OuterFn << "\n");
1345   LLVM_DEBUG({
1346     for (auto *BB : Blocks)
1347       dbgs() << " PBR: " << BB->getName() << "\n";
1348   });
1349 
1350   // Register the outlined info.
1351   addOutlineInfo(std::move(OI));
1352 
1353   InsertPointTy AfterIP(UI->getParent(), UI->getParent()->end());
1354   UI->eraseFromParent();
1355 
1356   return AfterIP;
1357 }
1358 
1359 void OpenMPIRBuilder::emitFlush(const LocationDescription &Loc) {
1360   // Build call void __kmpc_flush(ident_t *loc)
1361   uint32_t SrcLocStrSize;
1362   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
1363   Value *Args[] = {getOrCreateIdent(SrcLocStr, SrcLocStrSize)};
1364 
1365   Builder.CreateCall(getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_flush), Args);
1366 }
1367 
1368 void OpenMPIRBuilder::createFlush(const LocationDescription &Loc) {
1369   if (!updateToLocation(Loc))
1370     return;
1371   emitFlush(Loc);
1372 }
1373 
1374 void OpenMPIRBuilder::emitTaskwaitImpl(const LocationDescription &Loc) {
1375   // Build call kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
1376   // global_tid);
1377   uint32_t SrcLocStrSize;
1378   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
1379   Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
1380   Value *Args[] = {Ident, getOrCreateThreadID(Ident)};
1381 
1382   // Ignore return result until untied tasks are supported.
1383   Builder.CreateCall(getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_omp_taskwait),
1384                      Args);
1385 }
1386 
1387 void OpenMPIRBuilder::createTaskwait(const LocationDescription &Loc) {
1388   if (!updateToLocation(Loc))
1389     return;
1390   emitTaskwaitImpl(Loc);
1391 }
1392 
1393 void OpenMPIRBuilder::emitTaskyieldImpl(const LocationDescription &Loc) {
1394   // Build call __kmpc_omp_taskyield(loc, thread_id, 0);
1395   uint32_t SrcLocStrSize;
1396   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
1397   Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
1398   Constant *I32Null = ConstantInt::getNullValue(Int32);
1399   Value *Args[] = {Ident, getOrCreateThreadID(Ident), I32Null};
1400 
1401   Builder.CreateCall(getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_omp_taskyield),
1402                      Args);
1403 }
1404 
1405 void OpenMPIRBuilder::createTaskyield(const LocationDescription &Loc) {
1406   if (!updateToLocation(Loc))
1407     return;
1408   emitTaskyieldImpl(Loc);
1409 }
1410 
1411 OpenMPIRBuilder::InsertPointTy
1412 OpenMPIRBuilder::createTask(const LocationDescription &Loc,
1413                             InsertPointTy AllocaIP, BodyGenCallbackTy BodyGenCB,
1414                             bool Tied, Value *Final, Value *IfCondition,
1415                             SmallVector<DependData> Dependencies) {
1416   if (!updateToLocation(Loc))
1417     return InsertPointTy();
1418 
1419   uint32_t SrcLocStrSize;
1420   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
1421   Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
1422   // The current basic block is split into four basic blocks. After outlining,
1423   // they will be mapped as follows:
1424   // ```
1425   // def current_fn() {
1426   //   current_basic_block:
1427   //     br label %task.exit
1428   //   task.exit:
1429   //     ; instructions after task
1430   // }
1431   // def outlined_fn() {
1432   //   task.alloca:
1433   //     br label %task.body
1434   //   task.body:
1435   //     ret void
1436   // }
1437   // ```
1438   BasicBlock *TaskExitBB = splitBB(Builder, /*CreateBranch=*/true, "task.exit");
1439   BasicBlock *TaskBodyBB = splitBB(Builder, /*CreateBranch=*/true, "task.body");
1440   BasicBlock *TaskAllocaBB =
1441       splitBB(Builder, /*CreateBranch=*/true, "task.alloca");
1442 
1443   OutlineInfo OI;
1444   OI.EntryBB = TaskAllocaBB;
1445   OI.OuterAllocaBB = AllocaIP.getBlock();
1446   OI.ExitBB = TaskExitBB;
1447   OI.PostOutlineCB = [this, Ident, Tied, Final, IfCondition,
1448                       Dependencies](Function &OutlinedFn) {
1449     // The input IR here looks like the following-
1450     // ```
1451     // func @current_fn() {
1452     //   outlined_fn(%args)
1453     // }
1454     // func @outlined_fn(%args) { ... }
1455     // ```
1456     //
1457     // This is changed to the following-
1458     //
1459     // ```
1460     // func @current_fn() {
1461     //   runtime_call(..., wrapper_fn, ...)
1462     // }
1463     // func @wrapper_fn(..., %args) {
1464     //   outlined_fn(%args)
1465     // }
1466     // func @outlined_fn(%args) { ... }
1467     // ```
1468 
1469     // The stale call instruction will be replaced with a new call instruction
1470     // for runtime call with a wrapper function.
1471     assert(OutlinedFn.getNumUses() == 1 &&
1472            "there must be a single user for the outlined function");
1473     CallInst *StaleCI = cast<CallInst>(OutlinedFn.user_back());
1474 
1475     // HasTaskData is true if any variables are captured in the outlined region,
1476     // false otherwise.
1477     bool HasTaskData = StaleCI->arg_size() > 0;
1478     Builder.SetInsertPoint(StaleCI);
1479 
1480     // Gather the arguments for emitting the runtime call for
1481     // @__kmpc_omp_task_alloc
1482     Function *TaskAllocFn =
1483         getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_omp_task_alloc);
1484 
1485     // Arguments - `loc_ref` (Ident) and `gtid` (ThreadID)
1486     // call.
1487     Value *ThreadID = getOrCreateThreadID(Ident);
1488 
1489     // Argument - `flags`
1490     // Task is tied iff (Flags & 1) == 1.
1491     // Task is untied iff (Flags & 1) == 0.
1492     // Task is final iff (Flags & 2) == 2.
1493     // Task is not final iff (Flags & 2) == 0.
1494     // TODO: Handle the other flags.
1495     Value *Flags = Builder.getInt32(Tied);
1496     if (Final) {
1497       Value *FinalFlag =
1498           Builder.CreateSelect(Final, Builder.getInt32(2), Builder.getInt32(0));
1499       Flags = Builder.CreateOr(FinalFlag, Flags);
1500     }
1501 
1502     // Argument - `sizeof_kmp_task_t` (TaskSize)
1503     // Tasksize refers to the size in bytes of kmp_task_t data structure
1504     // including private vars accessed in task.
1505     Value *TaskSize = Builder.getInt64(0);
1506     if (HasTaskData) {
1507       AllocaInst *ArgStructAlloca =
1508           dyn_cast<AllocaInst>(StaleCI->getArgOperand(0));
1509       assert(ArgStructAlloca &&
1510              "Unable to find the alloca instruction corresponding to arguments "
1511              "for extracted function");
1512       StructType *ArgStructType =
1513           dyn_cast<StructType>(ArgStructAlloca->getAllocatedType());
1514       assert(ArgStructType && "Unable to find struct type corresponding to "
1515                               "arguments for extracted function");
1516       TaskSize =
1517           Builder.getInt64(M.getDataLayout().getTypeStoreSize(ArgStructType));
1518     }
1519 
1520     // TODO: Argument - sizeof_shareds
1521 
1522     // Argument - task_entry (the wrapper function)
1523     // If the outlined function has some captured variables (i.e. HasTaskData is
1524     // true), then the wrapper function will have an additional argument (the
1525     // struct containing captured variables). Otherwise, no such argument will
1526     // be present.
1527     SmallVector<Type *> WrapperArgTys{Builder.getInt32Ty()};
1528     if (HasTaskData)
1529       WrapperArgTys.push_back(OutlinedFn.getArg(0)->getType());
1530     FunctionCallee WrapperFuncVal = M.getOrInsertFunction(
1531         (Twine(OutlinedFn.getName()) + ".wrapper").str(),
1532         FunctionType::get(Builder.getInt32Ty(), WrapperArgTys, false));
1533     Function *WrapperFunc = dyn_cast<Function>(WrapperFuncVal.getCallee());
1534 
1535     // Emit the @__kmpc_omp_task_alloc runtime call
1536     // The runtime call returns a pointer to an area where the task captured
1537     // variables must be copied before the task is run (NewTaskData)
1538     CallInst *NewTaskData = Builder.CreateCall(
1539         TaskAllocFn,
1540         {/*loc_ref=*/Ident, /*gtid=*/ThreadID, /*flags=*/Flags,
1541          /*sizeof_task=*/TaskSize, /*sizeof_shared=*/Builder.getInt64(0),
1542          /*task_func=*/WrapperFunc});
1543 
1544     // Copy the arguments for outlined function
1545     if (HasTaskData) {
1546       Value *TaskData = StaleCI->getArgOperand(0);
1547       Align Alignment = TaskData->getPointerAlignment(M.getDataLayout());
1548       Builder.CreateMemCpy(NewTaskData, Alignment, TaskData, Alignment,
1549                            TaskSize);
1550     }
1551 
1552     Value *DepArrayPtr = nullptr;
1553     if (Dependencies.size()) {
1554       InsertPointTy OldIP = Builder.saveIP();
1555       Builder.SetInsertPoint(
1556           &OldIP.getBlock()->getParent()->getEntryBlock().back());
1557 
1558       Type *DepArrayTy = ArrayType::get(DependInfo, Dependencies.size());
1559       Value *DepArray =
1560           Builder.CreateAlloca(DepArrayTy, nullptr, ".dep.arr.addr");
1561 
1562       unsigned P = 0;
1563       for (const DependData &Dep : Dependencies) {
1564         Value *Base =
1565             Builder.CreateConstInBoundsGEP2_64(DepArrayTy, DepArray, 0, P);
1566         // Store the pointer to the variable
1567         Value *Addr = Builder.CreateStructGEP(
1568             DependInfo, Base,
1569             static_cast<unsigned int>(RTLDependInfoFields::BaseAddr));
1570         Value *DepValPtr =
1571             Builder.CreatePtrToInt(Dep.DepVal, Builder.getInt64Ty());
1572         Builder.CreateStore(DepValPtr, Addr);
1573         // Store the size of the variable
1574         Value *Size = Builder.CreateStructGEP(
1575             DependInfo, Base,
1576             static_cast<unsigned int>(RTLDependInfoFields::Len));
1577         Builder.CreateStore(Builder.getInt64(M.getDataLayout().getTypeStoreSize(
1578                                 Dep.DepValueType)),
1579                             Size);
1580         // Store the dependency kind
1581         Value *Flags = Builder.CreateStructGEP(
1582             DependInfo, Base,
1583             static_cast<unsigned int>(RTLDependInfoFields::Flags));
1584         Builder.CreateStore(
1585             ConstantInt::get(Builder.getInt8Ty(),
1586                              static_cast<unsigned int>(Dep.DepKind)),
1587             Flags);
1588         ++P;
1589       }
1590 
1591       DepArrayPtr = Builder.CreateBitCast(DepArray, Builder.getInt8PtrTy());
1592       Builder.restoreIP(OldIP);
1593     }
1594 
1595     // In the presence of the `if` clause, the following IR is generated:
1596     //    ...
1597     //    %data = call @__kmpc_omp_task_alloc(...)
1598     //    br i1 %if_condition, label %then, label %else
1599     //  then:
1600     //    call @__kmpc_omp_task(...)
1601     //    br label %exit
1602     //  else:
1603     //    call @__kmpc_omp_task_begin_if0(...)
1604     //    call @wrapper_fn(...)
1605     //    call @__kmpc_omp_task_complete_if0(...)
1606     //    br label %exit
1607     //  exit:
1608     //    ...
1609     if (IfCondition) {
1610       // `SplitBlockAndInsertIfThenElse` requires the block to have a
1611       // terminator.
1612       BasicBlock *NewBasicBlock =
1613           splitBB(Builder, /*CreateBranch=*/true, "if.end");
1614       Instruction *IfTerminator =
1615           NewBasicBlock->getSinglePredecessor()->getTerminator();
1616       Instruction *ThenTI = IfTerminator, *ElseTI = nullptr;
1617       Builder.SetInsertPoint(IfTerminator);
1618       SplitBlockAndInsertIfThenElse(IfCondition, IfTerminator, &ThenTI,
1619                                     &ElseTI);
1620       Builder.SetInsertPoint(ElseTI);
1621       Function *TaskBeginFn =
1622           getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_omp_task_begin_if0);
1623       Function *TaskCompleteFn =
1624           getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_omp_task_complete_if0);
1625       Builder.CreateCall(TaskBeginFn, {Ident, ThreadID, NewTaskData});
1626       if (HasTaskData)
1627         Builder.CreateCall(WrapperFunc, {ThreadID, NewTaskData});
1628       else
1629         Builder.CreateCall(WrapperFunc, {ThreadID});
1630       Builder.CreateCall(TaskCompleteFn, {Ident, ThreadID, NewTaskData});
1631       Builder.SetInsertPoint(ThenTI);
1632     }
1633 
1634     if (Dependencies.size()) {
1635       Function *TaskFn =
1636           getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_omp_task_with_deps);
1637       Builder.CreateCall(
1638           TaskFn,
1639           {Ident, ThreadID, NewTaskData, Builder.getInt32(Dependencies.size()),
1640            DepArrayPtr, ConstantInt::get(Builder.getInt32Ty(), 0),
1641            ConstantPointerNull::get(Type::getInt8PtrTy(M.getContext()))});
1642 
1643     } else {
1644       // Emit the @__kmpc_omp_task runtime call to spawn the task
1645       Function *TaskFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_omp_task);
1646       Builder.CreateCall(TaskFn, {Ident, ThreadID, NewTaskData});
1647     }
1648 
1649     StaleCI->eraseFromParent();
1650 
1651     // Emit the body for wrapper function
1652     BasicBlock *WrapperEntryBB =
1653         BasicBlock::Create(M.getContext(), "", WrapperFunc);
1654     Builder.SetInsertPoint(WrapperEntryBB);
1655     if (HasTaskData)
1656       Builder.CreateCall(&OutlinedFn, {WrapperFunc->getArg(1)});
1657     else
1658       Builder.CreateCall(&OutlinedFn);
1659     Builder.CreateRet(Builder.getInt32(0));
1660   };
1661 
1662   addOutlineInfo(std::move(OI));
1663 
1664   InsertPointTy TaskAllocaIP =
1665       InsertPointTy(TaskAllocaBB, TaskAllocaBB->begin());
1666   InsertPointTy TaskBodyIP = InsertPointTy(TaskBodyBB, TaskBodyBB->begin());
1667   BodyGenCB(TaskAllocaIP, TaskBodyIP);
1668   Builder.SetInsertPoint(TaskExitBB, TaskExitBB->begin());
1669 
1670   return Builder.saveIP();
1671 }
1672 
1673 OpenMPIRBuilder::InsertPointTy
1674 OpenMPIRBuilder::createTaskgroup(const LocationDescription &Loc,
1675                                  InsertPointTy AllocaIP,
1676                                  BodyGenCallbackTy BodyGenCB) {
1677   if (!updateToLocation(Loc))
1678     return InsertPointTy();
1679 
1680   uint32_t SrcLocStrSize;
1681   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
1682   Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
1683   Value *ThreadID = getOrCreateThreadID(Ident);
1684 
1685   // Emit the @__kmpc_taskgroup runtime call to start the taskgroup
1686   Function *TaskgroupFn =
1687       getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_taskgroup);
1688   Builder.CreateCall(TaskgroupFn, {Ident, ThreadID});
1689 
1690   BasicBlock *TaskgroupExitBB = splitBB(Builder, true, "taskgroup.exit");
1691   BodyGenCB(AllocaIP, Builder.saveIP());
1692 
1693   Builder.SetInsertPoint(TaskgroupExitBB);
1694   // Emit the @__kmpc_end_taskgroup runtime call to end the taskgroup
1695   Function *EndTaskgroupFn =
1696       getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_end_taskgroup);
1697   Builder.CreateCall(EndTaskgroupFn, {Ident, ThreadID});
1698 
1699   return Builder.saveIP();
1700 }
1701 
1702 OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::createSections(
1703     const LocationDescription &Loc, InsertPointTy AllocaIP,
1704     ArrayRef<StorableBodyGenCallbackTy> SectionCBs, PrivatizeCallbackTy PrivCB,
1705     FinalizeCallbackTy FiniCB, bool IsCancellable, bool IsNowait) {
1706   assert(!isConflictIP(AllocaIP, Loc.IP) && "Dedicated IP allocas required");
1707 
1708   if (!updateToLocation(Loc))
1709     return Loc.IP;
1710 
1711   auto FiniCBWrapper = [&](InsertPointTy IP) {
1712     if (IP.getBlock()->end() != IP.getPoint())
1713       return FiniCB(IP);
1714     // This must be done otherwise any nested constructs using FinalizeOMPRegion
1715     // will fail because that function requires the Finalization Basic Block to
1716     // have a terminator, which is already removed by EmitOMPRegionBody.
1717     // IP is currently at cancelation block.
1718     // We need to backtrack to the condition block to fetch
1719     // the exit block and create a branch from cancelation
1720     // to exit block.
1721     IRBuilder<>::InsertPointGuard IPG(Builder);
1722     Builder.restoreIP(IP);
1723     auto *CaseBB = IP.getBlock()->getSinglePredecessor();
1724     auto *CondBB = CaseBB->getSinglePredecessor()->getSinglePredecessor();
1725     auto *ExitBB = CondBB->getTerminator()->getSuccessor(1);
1726     Instruction *I = Builder.CreateBr(ExitBB);
1727     IP = InsertPointTy(I->getParent(), I->getIterator());
1728     return FiniCB(IP);
1729   };
1730 
1731   FinalizationStack.push_back({FiniCBWrapper, OMPD_sections, IsCancellable});
1732 
1733   // Each section is emitted as a switch case
1734   // Each finalization callback is handled from clang.EmitOMPSectionDirective()
1735   // -> OMP.createSection() which generates the IR for each section
1736   // Iterate through all sections and emit a switch construct:
1737   // switch (IV) {
1738   //   case 0:
1739   //     <SectionStmt[0]>;
1740   //     break;
1741   // ...
1742   //   case <NumSection> - 1:
1743   //     <SectionStmt[<NumSection> - 1]>;
1744   //     break;
1745   // }
1746   // ...
1747   // section_loop.after:
1748   // <FiniCB>;
1749   auto LoopBodyGenCB = [&](InsertPointTy CodeGenIP, Value *IndVar) {
1750     Builder.restoreIP(CodeGenIP);
1751     BasicBlock *Continue =
1752         splitBBWithSuffix(Builder, /*CreateBranch=*/false, ".sections.after");
1753     Function *CurFn = Continue->getParent();
1754     SwitchInst *SwitchStmt = Builder.CreateSwitch(IndVar, Continue);
1755 
1756     unsigned CaseNumber = 0;
1757     for (auto SectionCB : SectionCBs) {
1758       BasicBlock *CaseBB = BasicBlock::Create(
1759           M.getContext(), "omp_section_loop.body.case", CurFn, Continue);
1760       SwitchStmt->addCase(Builder.getInt32(CaseNumber), CaseBB);
1761       Builder.SetInsertPoint(CaseBB);
1762       BranchInst *CaseEndBr = Builder.CreateBr(Continue);
1763       SectionCB(InsertPointTy(),
1764                 {CaseEndBr->getParent(), CaseEndBr->getIterator()});
1765       CaseNumber++;
1766     }
1767     // remove the existing terminator from body BB since there can be no
1768     // terminators after switch/case
1769   };
1770   // Loop body ends here
1771   // LowerBound, UpperBound, and STride for createCanonicalLoop
1772   Type *I32Ty = Type::getInt32Ty(M.getContext());
1773   Value *LB = ConstantInt::get(I32Ty, 0);
1774   Value *UB = ConstantInt::get(I32Ty, SectionCBs.size());
1775   Value *ST = ConstantInt::get(I32Ty, 1);
1776   llvm::CanonicalLoopInfo *LoopInfo = createCanonicalLoop(
1777       Loc, LoopBodyGenCB, LB, UB, ST, true, false, AllocaIP, "section_loop");
1778   InsertPointTy AfterIP =
1779       applyStaticWorkshareLoop(Loc.DL, LoopInfo, AllocaIP, !IsNowait);
1780 
1781   // Apply the finalization callback in LoopAfterBB
1782   auto FiniInfo = FinalizationStack.pop_back_val();
1783   assert(FiniInfo.DK == OMPD_sections &&
1784          "Unexpected finalization stack state!");
1785   if (FinalizeCallbackTy &CB = FiniInfo.FiniCB) {
1786     Builder.restoreIP(AfterIP);
1787     BasicBlock *FiniBB =
1788         splitBBWithSuffix(Builder, /*CreateBranch=*/true, "sections.fini");
1789     CB(Builder.saveIP());
1790     AfterIP = {FiniBB, FiniBB->begin()};
1791   }
1792 
1793   return AfterIP;
1794 }
1795 
1796 OpenMPIRBuilder::InsertPointTy
1797 OpenMPIRBuilder::createSection(const LocationDescription &Loc,
1798                                BodyGenCallbackTy BodyGenCB,
1799                                FinalizeCallbackTy FiniCB) {
1800   if (!updateToLocation(Loc))
1801     return Loc.IP;
1802 
1803   auto FiniCBWrapper = [&](InsertPointTy IP) {
1804     if (IP.getBlock()->end() != IP.getPoint())
1805       return FiniCB(IP);
1806     // This must be done otherwise any nested constructs using FinalizeOMPRegion
1807     // will fail because that function requires the Finalization Basic Block to
1808     // have a terminator, which is already removed by EmitOMPRegionBody.
1809     // IP is currently at cancelation block.
1810     // We need to backtrack to the condition block to fetch
1811     // the exit block and create a branch from cancelation
1812     // to exit block.
1813     IRBuilder<>::InsertPointGuard IPG(Builder);
1814     Builder.restoreIP(IP);
1815     auto *CaseBB = Loc.IP.getBlock();
1816     auto *CondBB = CaseBB->getSinglePredecessor()->getSinglePredecessor();
1817     auto *ExitBB = CondBB->getTerminator()->getSuccessor(1);
1818     Instruction *I = Builder.CreateBr(ExitBB);
1819     IP = InsertPointTy(I->getParent(), I->getIterator());
1820     return FiniCB(IP);
1821   };
1822 
1823   Directive OMPD = Directive::OMPD_sections;
1824   // Since we are using Finalization Callback here, HasFinalize
1825   // and IsCancellable have to be true
1826   return EmitOMPInlinedRegion(OMPD, nullptr, nullptr, BodyGenCB, FiniCBWrapper,
1827                               /*Conditional*/ false, /*hasFinalize*/ true,
1828                               /*IsCancellable*/ true);
1829 }
1830 
1831 /// Create a function with a unique name and a "void (i8*, i8*)" signature in
1832 /// the given module and return it.
1833 Function *getFreshReductionFunc(Module &M) {
1834   Type *VoidTy = Type::getVoidTy(M.getContext());
1835   Type *Int8PtrTy = Type::getInt8PtrTy(M.getContext());
1836   auto *FuncTy =
1837       FunctionType::get(VoidTy, {Int8PtrTy, Int8PtrTy}, /* IsVarArg */ false);
1838   return Function::Create(FuncTy, GlobalVariable::InternalLinkage,
1839                           M.getDataLayout().getDefaultGlobalsAddressSpace(),
1840                           ".omp.reduction.func", &M);
1841 }
1842 
1843 OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::createReductions(
1844     const LocationDescription &Loc, InsertPointTy AllocaIP,
1845     ArrayRef<ReductionInfo> ReductionInfos, bool IsNoWait) {
1846   for (const ReductionInfo &RI : ReductionInfos) {
1847     (void)RI;
1848     assert(RI.Variable && "expected non-null variable");
1849     assert(RI.PrivateVariable && "expected non-null private variable");
1850     assert(RI.ReductionGen && "expected non-null reduction generator callback");
1851     assert(RI.Variable->getType() == RI.PrivateVariable->getType() &&
1852            "expected variables and their private equivalents to have the same "
1853            "type");
1854     assert(RI.Variable->getType()->isPointerTy() &&
1855            "expected variables to be pointers");
1856   }
1857 
1858   if (!updateToLocation(Loc))
1859     return InsertPointTy();
1860 
1861   BasicBlock *InsertBlock = Loc.IP.getBlock();
1862   BasicBlock *ContinuationBlock =
1863       InsertBlock->splitBasicBlock(Loc.IP.getPoint(), "reduce.finalize");
1864   InsertBlock->getTerminator()->eraseFromParent();
1865 
1866   // Create and populate array of type-erased pointers to private reduction
1867   // values.
1868   unsigned NumReductions = ReductionInfos.size();
1869   Type *RedArrayTy = ArrayType::get(Builder.getInt8PtrTy(), NumReductions);
1870   Builder.restoreIP(AllocaIP);
1871   Value *RedArray = Builder.CreateAlloca(RedArrayTy, nullptr, "red.array");
1872 
1873   Builder.SetInsertPoint(InsertBlock, InsertBlock->end());
1874 
1875   for (auto En : enumerate(ReductionInfos)) {
1876     unsigned Index = En.index();
1877     const ReductionInfo &RI = En.value();
1878     Value *RedArrayElemPtr = Builder.CreateConstInBoundsGEP2_64(
1879         RedArrayTy, RedArray, 0, Index, "red.array.elem." + Twine(Index));
1880     Value *Casted =
1881         Builder.CreateBitCast(RI.PrivateVariable, Builder.getInt8PtrTy(),
1882                               "private.red.var." + Twine(Index) + ".casted");
1883     Builder.CreateStore(Casted, RedArrayElemPtr);
1884   }
1885 
1886   // Emit a call to the runtime function that orchestrates the reduction.
1887   // Declare the reduction function in the process.
1888   Function *Func = Builder.GetInsertBlock()->getParent();
1889   Module *Module = Func->getParent();
1890   Value *RedArrayPtr =
1891       Builder.CreateBitCast(RedArray, Builder.getInt8PtrTy(), "red.array.ptr");
1892   uint32_t SrcLocStrSize;
1893   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
1894   bool CanGenerateAtomic =
1895       llvm::all_of(ReductionInfos, [](const ReductionInfo &RI) {
1896         return RI.AtomicReductionGen;
1897       });
1898   Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize,
1899                                   CanGenerateAtomic
1900                                       ? IdentFlag::OMP_IDENT_FLAG_ATOMIC_REDUCE
1901                                       : IdentFlag(0));
1902   Value *ThreadId = getOrCreateThreadID(Ident);
1903   Constant *NumVariables = Builder.getInt32(NumReductions);
1904   const DataLayout &DL = Module->getDataLayout();
1905   unsigned RedArrayByteSize = DL.getTypeStoreSize(RedArrayTy);
1906   Constant *RedArraySize = Builder.getInt64(RedArrayByteSize);
1907   Function *ReductionFunc = getFreshReductionFunc(*Module);
1908   Value *Lock = getOMPCriticalRegionLock(".reduction");
1909   Function *ReduceFunc = getOrCreateRuntimeFunctionPtr(
1910       IsNoWait ? RuntimeFunction::OMPRTL___kmpc_reduce_nowait
1911                : RuntimeFunction::OMPRTL___kmpc_reduce);
1912   CallInst *ReduceCall =
1913       Builder.CreateCall(ReduceFunc,
1914                          {Ident, ThreadId, NumVariables, RedArraySize,
1915                           RedArrayPtr, ReductionFunc, Lock},
1916                          "reduce");
1917 
1918   // Create final reduction entry blocks for the atomic and non-atomic case.
1919   // Emit IR that dispatches control flow to one of the blocks based on the
1920   // reduction supporting the atomic mode.
1921   BasicBlock *NonAtomicRedBlock =
1922       BasicBlock::Create(Module->getContext(), "reduce.switch.nonatomic", Func);
1923   BasicBlock *AtomicRedBlock =
1924       BasicBlock::Create(Module->getContext(), "reduce.switch.atomic", Func);
1925   SwitchInst *Switch =
1926       Builder.CreateSwitch(ReduceCall, ContinuationBlock, /* NumCases */ 2);
1927   Switch->addCase(Builder.getInt32(1), NonAtomicRedBlock);
1928   Switch->addCase(Builder.getInt32(2), AtomicRedBlock);
1929 
1930   // Populate the non-atomic reduction using the elementwise reduction function.
1931   // This loads the elements from the global and private variables and reduces
1932   // them before storing back the result to the global variable.
1933   Builder.SetInsertPoint(NonAtomicRedBlock);
1934   for (auto En : enumerate(ReductionInfos)) {
1935     const ReductionInfo &RI = En.value();
1936     Type *ValueType = RI.ElementType;
1937     Value *RedValue = Builder.CreateLoad(ValueType, RI.Variable,
1938                                          "red.value." + Twine(En.index()));
1939     Value *PrivateRedValue =
1940         Builder.CreateLoad(ValueType, RI.PrivateVariable,
1941                            "red.private.value." + Twine(En.index()));
1942     Value *Reduced;
1943     Builder.restoreIP(
1944         RI.ReductionGen(Builder.saveIP(), RedValue, PrivateRedValue, Reduced));
1945     if (!Builder.GetInsertBlock())
1946       return InsertPointTy();
1947     Builder.CreateStore(Reduced, RI.Variable);
1948   }
1949   Function *EndReduceFunc = getOrCreateRuntimeFunctionPtr(
1950       IsNoWait ? RuntimeFunction::OMPRTL___kmpc_end_reduce_nowait
1951                : RuntimeFunction::OMPRTL___kmpc_end_reduce);
1952   Builder.CreateCall(EndReduceFunc, {Ident, ThreadId, Lock});
1953   Builder.CreateBr(ContinuationBlock);
1954 
1955   // Populate the atomic reduction using the atomic elementwise reduction
1956   // function. There are no loads/stores here because they will be happening
1957   // inside the atomic elementwise reduction.
1958   Builder.SetInsertPoint(AtomicRedBlock);
1959   if (CanGenerateAtomic) {
1960     for (const ReductionInfo &RI : ReductionInfos) {
1961       Builder.restoreIP(RI.AtomicReductionGen(Builder.saveIP(), RI.ElementType,
1962                                               RI.Variable, RI.PrivateVariable));
1963       if (!Builder.GetInsertBlock())
1964         return InsertPointTy();
1965     }
1966     Builder.CreateBr(ContinuationBlock);
1967   } else {
1968     Builder.CreateUnreachable();
1969   }
1970 
1971   // Populate the outlined reduction function using the elementwise reduction
1972   // function. Partial values are extracted from the type-erased array of
1973   // pointers to private variables.
1974   BasicBlock *ReductionFuncBlock =
1975       BasicBlock::Create(Module->getContext(), "", ReductionFunc);
1976   Builder.SetInsertPoint(ReductionFuncBlock);
1977   Value *LHSArrayPtr = ReductionFunc->getArg(0);
1978   Value *RHSArrayPtr = ReductionFunc->getArg(1);
1979 
1980   for (auto En : enumerate(ReductionInfos)) {
1981     const ReductionInfo &RI = En.value();
1982     Value *LHSI8PtrPtr = Builder.CreateConstInBoundsGEP2_64(
1983         RedArrayTy, LHSArrayPtr, 0, En.index());
1984     Value *LHSI8Ptr = Builder.CreateLoad(Builder.getInt8PtrTy(), LHSI8PtrPtr);
1985     Value *LHSPtr = Builder.CreateBitCast(LHSI8Ptr, RI.Variable->getType());
1986     Value *LHS = Builder.CreateLoad(RI.ElementType, LHSPtr);
1987     Value *RHSI8PtrPtr = Builder.CreateConstInBoundsGEP2_64(
1988         RedArrayTy, RHSArrayPtr, 0, En.index());
1989     Value *RHSI8Ptr = Builder.CreateLoad(Builder.getInt8PtrTy(), RHSI8PtrPtr);
1990     Value *RHSPtr =
1991         Builder.CreateBitCast(RHSI8Ptr, RI.PrivateVariable->getType());
1992     Value *RHS = Builder.CreateLoad(RI.ElementType, RHSPtr);
1993     Value *Reduced;
1994     Builder.restoreIP(RI.ReductionGen(Builder.saveIP(), LHS, RHS, Reduced));
1995     if (!Builder.GetInsertBlock())
1996       return InsertPointTy();
1997     Builder.CreateStore(Reduced, LHSPtr);
1998   }
1999   Builder.CreateRetVoid();
2000 
2001   Builder.SetInsertPoint(ContinuationBlock);
2002   return Builder.saveIP();
2003 }
2004 
2005 OpenMPIRBuilder::InsertPointTy
2006 OpenMPIRBuilder::createMaster(const LocationDescription &Loc,
2007                               BodyGenCallbackTy BodyGenCB,
2008                               FinalizeCallbackTy FiniCB) {
2009 
2010   if (!updateToLocation(Loc))
2011     return Loc.IP;
2012 
2013   Directive OMPD = Directive::OMPD_master;
2014   uint32_t SrcLocStrSize;
2015   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
2016   Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
2017   Value *ThreadId = getOrCreateThreadID(Ident);
2018   Value *Args[] = {Ident, ThreadId};
2019 
2020   Function *EntryRTLFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_master);
2021   Instruction *EntryCall = Builder.CreateCall(EntryRTLFn, Args);
2022 
2023   Function *ExitRTLFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_end_master);
2024   Instruction *ExitCall = Builder.CreateCall(ExitRTLFn, Args);
2025 
2026   return EmitOMPInlinedRegion(OMPD, EntryCall, ExitCall, BodyGenCB, FiniCB,
2027                               /*Conditional*/ true, /*hasFinalize*/ true);
2028 }
2029 
2030 OpenMPIRBuilder::InsertPointTy
2031 OpenMPIRBuilder::createMasked(const LocationDescription &Loc,
2032                               BodyGenCallbackTy BodyGenCB,
2033                               FinalizeCallbackTy FiniCB, Value *Filter) {
2034   if (!updateToLocation(Loc))
2035     return Loc.IP;
2036 
2037   Directive OMPD = Directive::OMPD_masked;
2038   uint32_t SrcLocStrSize;
2039   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
2040   Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
2041   Value *ThreadId = getOrCreateThreadID(Ident);
2042   Value *Args[] = {Ident, ThreadId, Filter};
2043   Value *ArgsEnd[] = {Ident, ThreadId};
2044 
2045   Function *EntryRTLFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_masked);
2046   Instruction *EntryCall = Builder.CreateCall(EntryRTLFn, Args);
2047 
2048   Function *ExitRTLFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_end_masked);
2049   Instruction *ExitCall = Builder.CreateCall(ExitRTLFn, ArgsEnd);
2050 
2051   return EmitOMPInlinedRegion(OMPD, EntryCall, ExitCall, BodyGenCB, FiniCB,
2052                               /*Conditional*/ true, /*hasFinalize*/ true);
2053 }
2054 
2055 CanonicalLoopInfo *OpenMPIRBuilder::createLoopSkeleton(
2056     DebugLoc DL, Value *TripCount, Function *F, BasicBlock *PreInsertBefore,
2057     BasicBlock *PostInsertBefore, const Twine &Name) {
2058   Module *M = F->getParent();
2059   LLVMContext &Ctx = M->getContext();
2060   Type *IndVarTy = TripCount->getType();
2061 
2062   // Create the basic block structure.
2063   BasicBlock *Preheader =
2064       BasicBlock::Create(Ctx, "omp_" + Name + ".preheader", F, PreInsertBefore);
2065   BasicBlock *Header =
2066       BasicBlock::Create(Ctx, "omp_" + Name + ".header", F, PreInsertBefore);
2067   BasicBlock *Cond =
2068       BasicBlock::Create(Ctx, "omp_" + Name + ".cond", F, PreInsertBefore);
2069   BasicBlock *Body =
2070       BasicBlock::Create(Ctx, "omp_" + Name + ".body", F, PreInsertBefore);
2071   BasicBlock *Latch =
2072       BasicBlock::Create(Ctx, "omp_" + Name + ".inc", F, PostInsertBefore);
2073   BasicBlock *Exit =
2074       BasicBlock::Create(Ctx, "omp_" + Name + ".exit", F, PostInsertBefore);
2075   BasicBlock *After =
2076       BasicBlock::Create(Ctx, "omp_" + Name + ".after", F, PostInsertBefore);
2077 
2078   // Use specified DebugLoc for new instructions.
2079   Builder.SetCurrentDebugLocation(DL);
2080 
2081   Builder.SetInsertPoint(Preheader);
2082   Builder.CreateBr(Header);
2083 
2084   Builder.SetInsertPoint(Header);
2085   PHINode *IndVarPHI = Builder.CreatePHI(IndVarTy, 2, "omp_" + Name + ".iv");
2086   IndVarPHI->addIncoming(ConstantInt::get(IndVarTy, 0), Preheader);
2087   Builder.CreateBr(Cond);
2088 
2089   Builder.SetInsertPoint(Cond);
2090   Value *Cmp =
2091       Builder.CreateICmpULT(IndVarPHI, TripCount, "omp_" + Name + ".cmp");
2092   Builder.CreateCondBr(Cmp, Body, Exit);
2093 
2094   Builder.SetInsertPoint(Body);
2095   Builder.CreateBr(Latch);
2096 
2097   Builder.SetInsertPoint(Latch);
2098   Value *Next = Builder.CreateAdd(IndVarPHI, ConstantInt::get(IndVarTy, 1),
2099                                   "omp_" + Name + ".next", /*HasNUW=*/true);
2100   Builder.CreateBr(Header);
2101   IndVarPHI->addIncoming(Next, Latch);
2102 
2103   Builder.SetInsertPoint(Exit);
2104   Builder.CreateBr(After);
2105 
2106   // Remember and return the canonical control flow.
2107   LoopInfos.emplace_front();
2108   CanonicalLoopInfo *CL = &LoopInfos.front();
2109 
2110   CL->Header = Header;
2111   CL->Cond = Cond;
2112   CL->Latch = Latch;
2113   CL->Exit = Exit;
2114 
2115 #ifndef NDEBUG
2116   CL->assertOK();
2117 #endif
2118   return CL;
2119 }
2120 
2121 CanonicalLoopInfo *
2122 OpenMPIRBuilder::createCanonicalLoop(const LocationDescription &Loc,
2123                                      LoopBodyGenCallbackTy BodyGenCB,
2124                                      Value *TripCount, const Twine &Name) {
2125   BasicBlock *BB = Loc.IP.getBlock();
2126   BasicBlock *NextBB = BB->getNextNode();
2127 
2128   CanonicalLoopInfo *CL = createLoopSkeleton(Loc.DL, TripCount, BB->getParent(),
2129                                              NextBB, NextBB, Name);
2130   BasicBlock *After = CL->getAfter();
2131 
2132   // If location is not set, don't connect the loop.
2133   if (updateToLocation(Loc)) {
2134     // Split the loop at the insertion point: Branch to the preheader and move
2135     // every following instruction to after the loop (the After BB). Also, the
2136     // new successor is the loop's after block.
2137     spliceBB(Builder, After, /*CreateBranch=*/false);
2138     Builder.CreateBr(CL->getPreheader());
2139   }
2140 
2141   // Emit the body content. We do it after connecting the loop to the CFG to
2142   // avoid that the callback encounters degenerate BBs.
2143   BodyGenCB(CL->getBodyIP(), CL->getIndVar());
2144 
2145 #ifndef NDEBUG
2146   CL->assertOK();
2147 #endif
2148   return CL;
2149 }
2150 
2151 CanonicalLoopInfo *OpenMPIRBuilder::createCanonicalLoop(
2152     const LocationDescription &Loc, LoopBodyGenCallbackTy BodyGenCB,
2153     Value *Start, Value *Stop, Value *Step, bool IsSigned, bool InclusiveStop,
2154     InsertPointTy ComputeIP, const Twine &Name) {
2155 
2156   // Consider the following difficulties (assuming 8-bit signed integers):
2157   //  * Adding \p Step to the loop counter which passes \p Stop may overflow:
2158   //      DO I = 1, 100, 50
2159   ///  * A \p Step of INT_MIN cannot not be normalized to a positive direction:
2160   //      DO I = 100, 0, -128
2161 
2162   // Start, Stop and Step must be of the same integer type.
2163   auto *IndVarTy = cast<IntegerType>(Start->getType());
2164   assert(IndVarTy == Stop->getType() && "Stop type mismatch");
2165   assert(IndVarTy == Step->getType() && "Step type mismatch");
2166 
2167   LocationDescription ComputeLoc =
2168       ComputeIP.isSet() ? LocationDescription(ComputeIP, Loc.DL) : Loc;
2169   updateToLocation(ComputeLoc);
2170 
2171   ConstantInt *Zero = ConstantInt::get(IndVarTy, 0);
2172   ConstantInt *One = ConstantInt::get(IndVarTy, 1);
2173 
2174   // Like Step, but always positive.
2175   Value *Incr = Step;
2176 
2177   // Distance between Start and Stop; always positive.
2178   Value *Span;
2179 
2180   // Condition whether there are no iterations are executed at all, e.g. because
2181   // UB < LB.
2182   Value *ZeroCmp;
2183 
2184   if (IsSigned) {
2185     // Ensure that increment is positive. If not, negate and invert LB and UB.
2186     Value *IsNeg = Builder.CreateICmpSLT(Step, Zero);
2187     Incr = Builder.CreateSelect(IsNeg, Builder.CreateNeg(Step), Step);
2188     Value *LB = Builder.CreateSelect(IsNeg, Stop, Start);
2189     Value *UB = Builder.CreateSelect(IsNeg, Start, Stop);
2190     Span = Builder.CreateSub(UB, LB, "", false, true);
2191     ZeroCmp = Builder.CreateICmp(
2192         InclusiveStop ? CmpInst::ICMP_SLT : CmpInst::ICMP_SLE, UB, LB);
2193   } else {
2194     Span = Builder.CreateSub(Stop, Start, "", true);
2195     ZeroCmp = Builder.CreateICmp(
2196         InclusiveStop ? CmpInst::ICMP_ULT : CmpInst::ICMP_ULE, Stop, Start);
2197   }
2198 
2199   Value *CountIfLooping;
2200   if (InclusiveStop) {
2201     CountIfLooping = Builder.CreateAdd(Builder.CreateUDiv(Span, Incr), One);
2202   } else {
2203     // Avoid incrementing past stop since it could overflow.
2204     Value *CountIfTwo = Builder.CreateAdd(
2205         Builder.CreateUDiv(Builder.CreateSub(Span, One), Incr), One);
2206     Value *OneCmp = Builder.CreateICmp(CmpInst::ICMP_ULE, Span, Incr);
2207     CountIfLooping = Builder.CreateSelect(OneCmp, One, CountIfTwo);
2208   }
2209   Value *TripCount = Builder.CreateSelect(ZeroCmp, Zero, CountIfLooping,
2210                                           "omp_" + Name + ".tripcount");
2211 
2212   auto BodyGen = [=](InsertPointTy CodeGenIP, Value *IV) {
2213     Builder.restoreIP(CodeGenIP);
2214     Value *Span = Builder.CreateMul(IV, Step);
2215     Value *IndVar = Builder.CreateAdd(Span, Start);
2216     BodyGenCB(Builder.saveIP(), IndVar);
2217   };
2218   LocationDescription LoopLoc = ComputeIP.isSet() ? Loc.IP : Builder.saveIP();
2219   return createCanonicalLoop(LoopLoc, BodyGen, TripCount, Name);
2220 }
2221 
2222 // Returns an LLVM function to call for initializing loop bounds using OpenMP
2223 // static scheduling depending on `type`. Only i32 and i64 are supported by the
2224 // runtime. Always interpret integers as unsigned similarly to
2225 // CanonicalLoopInfo.
2226 static FunctionCallee getKmpcForStaticInitForType(Type *Ty, Module &M,
2227                                                   OpenMPIRBuilder &OMPBuilder) {
2228   unsigned Bitwidth = Ty->getIntegerBitWidth();
2229   if (Bitwidth == 32)
2230     return OMPBuilder.getOrCreateRuntimeFunction(
2231         M, omp::RuntimeFunction::OMPRTL___kmpc_for_static_init_4u);
2232   if (Bitwidth == 64)
2233     return OMPBuilder.getOrCreateRuntimeFunction(
2234         M, omp::RuntimeFunction::OMPRTL___kmpc_for_static_init_8u);
2235   llvm_unreachable("unknown OpenMP loop iterator bitwidth");
2236 }
2237 
2238 OpenMPIRBuilder::InsertPointTy
2239 OpenMPIRBuilder::applyStaticWorkshareLoop(DebugLoc DL, CanonicalLoopInfo *CLI,
2240                                           InsertPointTy AllocaIP,
2241                                           bool NeedsBarrier) {
2242   assert(CLI->isValid() && "Requires a valid canonical loop");
2243   assert(!isConflictIP(AllocaIP, CLI->getPreheaderIP()) &&
2244          "Require dedicated allocate IP");
2245 
2246   // Set up the source location value for OpenMP runtime.
2247   Builder.restoreIP(CLI->getPreheaderIP());
2248   Builder.SetCurrentDebugLocation(DL);
2249 
2250   uint32_t SrcLocStrSize;
2251   Constant *SrcLocStr = getOrCreateSrcLocStr(DL, SrcLocStrSize);
2252   Value *SrcLoc = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
2253 
2254   // Declare useful OpenMP runtime functions.
2255   Value *IV = CLI->getIndVar();
2256   Type *IVTy = IV->getType();
2257   FunctionCallee StaticInit = getKmpcForStaticInitForType(IVTy, M, *this);
2258   FunctionCallee StaticFini =
2259       getOrCreateRuntimeFunction(M, omp::OMPRTL___kmpc_for_static_fini);
2260 
2261   // Allocate space for computed loop bounds as expected by the "init" function.
2262   Builder.restoreIP(AllocaIP);
2263   Type *I32Type = Type::getInt32Ty(M.getContext());
2264   Value *PLastIter = Builder.CreateAlloca(I32Type, nullptr, "p.lastiter");
2265   Value *PLowerBound = Builder.CreateAlloca(IVTy, nullptr, "p.lowerbound");
2266   Value *PUpperBound = Builder.CreateAlloca(IVTy, nullptr, "p.upperbound");
2267   Value *PStride = Builder.CreateAlloca(IVTy, nullptr, "p.stride");
2268 
2269   // At the end of the preheader, prepare for calling the "init" function by
2270   // storing the current loop bounds into the allocated space. A canonical loop
2271   // always iterates from 0 to trip-count with step 1. Note that "init" expects
2272   // and produces an inclusive upper bound.
2273   Builder.SetInsertPoint(CLI->getPreheader()->getTerminator());
2274   Constant *Zero = ConstantInt::get(IVTy, 0);
2275   Constant *One = ConstantInt::get(IVTy, 1);
2276   Builder.CreateStore(Zero, PLowerBound);
2277   Value *UpperBound = Builder.CreateSub(CLI->getTripCount(), One);
2278   Builder.CreateStore(UpperBound, PUpperBound);
2279   Builder.CreateStore(One, PStride);
2280 
2281   Value *ThreadNum = getOrCreateThreadID(SrcLoc);
2282 
2283   Constant *SchedulingType = ConstantInt::get(
2284       I32Type, static_cast<int>(OMPScheduleType::UnorderedStatic));
2285 
2286   // Call the "init" function and update the trip count of the loop with the
2287   // value it produced.
2288   Builder.CreateCall(StaticInit,
2289                      {SrcLoc, ThreadNum, SchedulingType, PLastIter, PLowerBound,
2290                       PUpperBound, PStride, One, Zero});
2291   Value *LowerBound = Builder.CreateLoad(IVTy, PLowerBound);
2292   Value *InclusiveUpperBound = Builder.CreateLoad(IVTy, PUpperBound);
2293   Value *TripCountMinusOne = Builder.CreateSub(InclusiveUpperBound, LowerBound);
2294   Value *TripCount = Builder.CreateAdd(TripCountMinusOne, One);
2295   CLI->setTripCount(TripCount);
2296 
2297   // Update all uses of the induction variable except the one in the condition
2298   // block that compares it with the actual upper bound, and the increment in
2299   // the latch block.
2300 
2301   CLI->mapIndVar([&](Instruction *OldIV) -> Value * {
2302     Builder.SetInsertPoint(CLI->getBody(),
2303                            CLI->getBody()->getFirstInsertionPt());
2304     Builder.SetCurrentDebugLocation(DL);
2305     return Builder.CreateAdd(OldIV, LowerBound);
2306   });
2307 
2308   // In the "exit" block, call the "fini" function.
2309   Builder.SetInsertPoint(CLI->getExit(),
2310                          CLI->getExit()->getTerminator()->getIterator());
2311   Builder.CreateCall(StaticFini, {SrcLoc, ThreadNum});
2312 
2313   // Add the barrier if requested.
2314   if (NeedsBarrier)
2315     createBarrier(LocationDescription(Builder.saveIP(), DL),
2316                   omp::Directive::OMPD_for, /* ForceSimpleCall */ false,
2317                   /* CheckCancelFlag */ false);
2318 
2319   InsertPointTy AfterIP = CLI->getAfterIP();
2320   CLI->invalidate();
2321 
2322   return AfterIP;
2323 }
2324 
2325 OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::applyStaticChunkedWorkshareLoop(
2326     DebugLoc DL, CanonicalLoopInfo *CLI, InsertPointTy AllocaIP,
2327     bool NeedsBarrier, Value *ChunkSize) {
2328   assert(CLI->isValid() && "Requires a valid canonical loop");
2329   assert(ChunkSize && "Chunk size is required");
2330 
2331   LLVMContext &Ctx = CLI->getFunction()->getContext();
2332   Value *IV = CLI->getIndVar();
2333   Value *OrigTripCount = CLI->getTripCount();
2334   Type *IVTy = IV->getType();
2335   assert(IVTy->getIntegerBitWidth() <= 64 &&
2336          "Max supported tripcount bitwidth is 64 bits");
2337   Type *InternalIVTy = IVTy->getIntegerBitWidth() <= 32 ? Type::getInt32Ty(Ctx)
2338                                                         : Type::getInt64Ty(Ctx);
2339   Type *I32Type = Type::getInt32Ty(M.getContext());
2340   Constant *Zero = ConstantInt::get(InternalIVTy, 0);
2341   Constant *One = ConstantInt::get(InternalIVTy, 1);
2342 
2343   // Declare useful OpenMP runtime functions.
2344   FunctionCallee StaticInit =
2345       getKmpcForStaticInitForType(InternalIVTy, M, *this);
2346   FunctionCallee StaticFini =
2347       getOrCreateRuntimeFunction(M, omp::OMPRTL___kmpc_for_static_fini);
2348 
2349   // Allocate space for computed loop bounds as expected by the "init" function.
2350   Builder.restoreIP(AllocaIP);
2351   Builder.SetCurrentDebugLocation(DL);
2352   Value *PLastIter = Builder.CreateAlloca(I32Type, nullptr, "p.lastiter");
2353   Value *PLowerBound =
2354       Builder.CreateAlloca(InternalIVTy, nullptr, "p.lowerbound");
2355   Value *PUpperBound =
2356       Builder.CreateAlloca(InternalIVTy, nullptr, "p.upperbound");
2357   Value *PStride = Builder.CreateAlloca(InternalIVTy, nullptr, "p.stride");
2358 
2359   // Set up the source location value for the OpenMP runtime.
2360   Builder.restoreIP(CLI->getPreheaderIP());
2361   Builder.SetCurrentDebugLocation(DL);
2362 
2363   // TODO: Detect overflow in ubsan or max-out with current tripcount.
2364   Value *CastedChunkSize =
2365       Builder.CreateZExtOrTrunc(ChunkSize, InternalIVTy, "chunksize");
2366   Value *CastedTripCount =
2367       Builder.CreateZExt(OrigTripCount, InternalIVTy, "tripcount");
2368 
2369   Constant *SchedulingType = ConstantInt::get(
2370       I32Type, static_cast<int>(OMPScheduleType::UnorderedStaticChunked));
2371   Builder.CreateStore(Zero, PLowerBound);
2372   Value *OrigUpperBound = Builder.CreateSub(CastedTripCount, One);
2373   Builder.CreateStore(OrigUpperBound, PUpperBound);
2374   Builder.CreateStore(One, PStride);
2375 
2376   // Call the "init" function and update the trip count of the loop with the
2377   // value it produced.
2378   uint32_t SrcLocStrSize;
2379   Constant *SrcLocStr = getOrCreateSrcLocStr(DL, SrcLocStrSize);
2380   Value *SrcLoc = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
2381   Value *ThreadNum = getOrCreateThreadID(SrcLoc);
2382   Builder.CreateCall(StaticInit,
2383                      {/*loc=*/SrcLoc, /*global_tid=*/ThreadNum,
2384                       /*schedtype=*/SchedulingType, /*plastiter=*/PLastIter,
2385                       /*plower=*/PLowerBound, /*pupper=*/PUpperBound,
2386                       /*pstride=*/PStride, /*incr=*/One,
2387                       /*chunk=*/CastedChunkSize});
2388 
2389   // Load values written by the "init" function.
2390   Value *FirstChunkStart =
2391       Builder.CreateLoad(InternalIVTy, PLowerBound, "omp_firstchunk.lb");
2392   Value *FirstChunkStop =
2393       Builder.CreateLoad(InternalIVTy, PUpperBound, "omp_firstchunk.ub");
2394   Value *FirstChunkEnd = Builder.CreateAdd(FirstChunkStop, One);
2395   Value *ChunkRange =
2396       Builder.CreateSub(FirstChunkEnd, FirstChunkStart, "omp_chunk.range");
2397   Value *NextChunkStride =
2398       Builder.CreateLoad(InternalIVTy, PStride, "omp_dispatch.stride");
2399 
2400   // Create outer "dispatch" loop for enumerating the chunks.
2401   BasicBlock *DispatchEnter = splitBB(Builder, true);
2402   Value *DispatchCounter;
2403   CanonicalLoopInfo *DispatchCLI = createCanonicalLoop(
2404       {Builder.saveIP(), DL},
2405       [&](InsertPointTy BodyIP, Value *Counter) { DispatchCounter = Counter; },
2406       FirstChunkStart, CastedTripCount, NextChunkStride,
2407       /*IsSigned=*/false, /*InclusiveStop=*/false, /*ComputeIP=*/{},
2408       "dispatch");
2409 
2410   // Remember the BasicBlocks of the dispatch loop we need, then invalidate to
2411   // not have to preserve the canonical invariant.
2412   BasicBlock *DispatchBody = DispatchCLI->getBody();
2413   BasicBlock *DispatchLatch = DispatchCLI->getLatch();
2414   BasicBlock *DispatchExit = DispatchCLI->getExit();
2415   BasicBlock *DispatchAfter = DispatchCLI->getAfter();
2416   DispatchCLI->invalidate();
2417 
2418   // Rewire the original loop to become the chunk loop inside the dispatch loop.
2419   redirectTo(DispatchAfter, CLI->getAfter(), DL);
2420   redirectTo(CLI->getExit(), DispatchLatch, DL);
2421   redirectTo(DispatchBody, DispatchEnter, DL);
2422 
2423   // Prepare the prolog of the chunk loop.
2424   Builder.restoreIP(CLI->getPreheaderIP());
2425   Builder.SetCurrentDebugLocation(DL);
2426 
2427   // Compute the number of iterations of the chunk loop.
2428   Builder.SetInsertPoint(CLI->getPreheader()->getTerminator());
2429   Value *ChunkEnd = Builder.CreateAdd(DispatchCounter, ChunkRange);
2430   Value *IsLastChunk =
2431       Builder.CreateICmpUGE(ChunkEnd, CastedTripCount, "omp_chunk.is_last");
2432   Value *CountUntilOrigTripCount =
2433       Builder.CreateSub(CastedTripCount, DispatchCounter);
2434   Value *ChunkTripCount = Builder.CreateSelect(
2435       IsLastChunk, CountUntilOrigTripCount, ChunkRange, "omp_chunk.tripcount");
2436   Value *BackcastedChunkTC =
2437       Builder.CreateTrunc(ChunkTripCount, IVTy, "omp_chunk.tripcount.trunc");
2438   CLI->setTripCount(BackcastedChunkTC);
2439 
2440   // Update all uses of the induction variable except the one in the condition
2441   // block that compares it with the actual upper bound, and the increment in
2442   // the latch block.
2443   Value *BackcastedDispatchCounter =
2444       Builder.CreateTrunc(DispatchCounter, IVTy, "omp_dispatch.iv.trunc");
2445   CLI->mapIndVar([&](Instruction *) -> Value * {
2446     Builder.restoreIP(CLI->getBodyIP());
2447     return Builder.CreateAdd(IV, BackcastedDispatchCounter);
2448   });
2449 
2450   // In the "exit" block, call the "fini" function.
2451   Builder.SetInsertPoint(DispatchExit, DispatchExit->getFirstInsertionPt());
2452   Builder.CreateCall(StaticFini, {SrcLoc, ThreadNum});
2453 
2454   // Add the barrier if requested.
2455   if (NeedsBarrier)
2456     createBarrier(LocationDescription(Builder.saveIP(), DL), OMPD_for,
2457                   /*ForceSimpleCall=*/false, /*CheckCancelFlag=*/false);
2458 
2459 #ifndef NDEBUG
2460   // Even though we currently do not support applying additional methods to it,
2461   // the chunk loop should remain a canonical loop.
2462   CLI->assertOK();
2463 #endif
2464 
2465   return {DispatchAfter, DispatchAfter->getFirstInsertionPt()};
2466 }
2467 
2468 OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::applyWorkshareLoop(
2469     DebugLoc DL, CanonicalLoopInfo *CLI, InsertPointTy AllocaIP,
2470     bool NeedsBarrier, llvm::omp::ScheduleKind SchedKind,
2471     llvm::Value *ChunkSize, bool HasSimdModifier, bool HasMonotonicModifier,
2472     bool HasNonmonotonicModifier, bool HasOrderedClause) {
2473   OMPScheduleType EffectiveScheduleType = computeOpenMPScheduleType(
2474       SchedKind, ChunkSize, HasSimdModifier, HasMonotonicModifier,
2475       HasNonmonotonicModifier, HasOrderedClause);
2476 
2477   bool IsOrdered = (EffectiveScheduleType & OMPScheduleType::ModifierOrdered) ==
2478                    OMPScheduleType::ModifierOrdered;
2479   switch (EffectiveScheduleType & ~OMPScheduleType::ModifierMask) {
2480   case OMPScheduleType::BaseStatic:
2481     assert(!ChunkSize && "No chunk size with static-chunked schedule");
2482     if (IsOrdered)
2483       return applyDynamicWorkshareLoop(DL, CLI, AllocaIP, EffectiveScheduleType,
2484                                        NeedsBarrier, ChunkSize);
2485     // FIXME: Monotonicity ignored?
2486     return applyStaticWorkshareLoop(DL, CLI, AllocaIP, NeedsBarrier);
2487 
2488   case OMPScheduleType::BaseStaticChunked:
2489     if (IsOrdered)
2490       return applyDynamicWorkshareLoop(DL, CLI, AllocaIP, EffectiveScheduleType,
2491                                        NeedsBarrier, ChunkSize);
2492     // FIXME: Monotonicity ignored?
2493     return applyStaticChunkedWorkshareLoop(DL, CLI, AllocaIP, NeedsBarrier,
2494                                            ChunkSize);
2495 
2496   case OMPScheduleType::BaseRuntime:
2497   case OMPScheduleType::BaseAuto:
2498   case OMPScheduleType::BaseGreedy:
2499   case OMPScheduleType::BaseBalanced:
2500   case OMPScheduleType::BaseSteal:
2501   case OMPScheduleType::BaseGuidedSimd:
2502   case OMPScheduleType::BaseRuntimeSimd:
2503     assert(!ChunkSize &&
2504            "schedule type does not support user-defined chunk sizes");
2505     [[fallthrough]];
2506   case OMPScheduleType::BaseDynamicChunked:
2507   case OMPScheduleType::BaseGuidedChunked:
2508   case OMPScheduleType::BaseGuidedIterativeChunked:
2509   case OMPScheduleType::BaseGuidedAnalyticalChunked:
2510   case OMPScheduleType::BaseStaticBalancedChunked:
2511     return applyDynamicWorkshareLoop(DL, CLI, AllocaIP, EffectiveScheduleType,
2512                                      NeedsBarrier, ChunkSize);
2513 
2514   default:
2515     llvm_unreachable("Unknown/unimplemented schedule kind");
2516   }
2517 }
2518 
2519 /// Returns an LLVM function to call for initializing loop bounds using OpenMP
2520 /// dynamic scheduling depending on `type`. Only i32 and i64 are supported by
2521 /// the runtime. Always interpret integers as unsigned similarly to
2522 /// CanonicalLoopInfo.
2523 static FunctionCallee
2524 getKmpcForDynamicInitForType(Type *Ty, Module &M, OpenMPIRBuilder &OMPBuilder) {
2525   unsigned Bitwidth = Ty->getIntegerBitWidth();
2526   if (Bitwidth == 32)
2527     return OMPBuilder.getOrCreateRuntimeFunction(
2528         M, omp::RuntimeFunction::OMPRTL___kmpc_dispatch_init_4u);
2529   if (Bitwidth == 64)
2530     return OMPBuilder.getOrCreateRuntimeFunction(
2531         M, omp::RuntimeFunction::OMPRTL___kmpc_dispatch_init_8u);
2532   llvm_unreachable("unknown OpenMP loop iterator bitwidth");
2533 }
2534 
2535 /// Returns an LLVM function to call for updating the next loop using OpenMP
2536 /// dynamic scheduling depending on `type`. Only i32 and i64 are supported by
2537 /// the runtime. Always interpret integers as unsigned similarly to
2538 /// CanonicalLoopInfo.
2539 static FunctionCallee
2540 getKmpcForDynamicNextForType(Type *Ty, Module &M, OpenMPIRBuilder &OMPBuilder) {
2541   unsigned Bitwidth = Ty->getIntegerBitWidth();
2542   if (Bitwidth == 32)
2543     return OMPBuilder.getOrCreateRuntimeFunction(
2544         M, omp::RuntimeFunction::OMPRTL___kmpc_dispatch_next_4u);
2545   if (Bitwidth == 64)
2546     return OMPBuilder.getOrCreateRuntimeFunction(
2547         M, omp::RuntimeFunction::OMPRTL___kmpc_dispatch_next_8u);
2548   llvm_unreachable("unknown OpenMP loop iterator bitwidth");
2549 }
2550 
2551 /// Returns an LLVM function to call for finalizing the dynamic loop using
2552 /// depending on `type`. Only i32 and i64 are supported by the runtime. Always
2553 /// interpret integers as unsigned similarly to CanonicalLoopInfo.
2554 static FunctionCallee
2555 getKmpcForDynamicFiniForType(Type *Ty, Module &M, OpenMPIRBuilder &OMPBuilder) {
2556   unsigned Bitwidth = Ty->getIntegerBitWidth();
2557   if (Bitwidth == 32)
2558     return OMPBuilder.getOrCreateRuntimeFunction(
2559         M, omp::RuntimeFunction::OMPRTL___kmpc_dispatch_fini_4u);
2560   if (Bitwidth == 64)
2561     return OMPBuilder.getOrCreateRuntimeFunction(
2562         M, omp::RuntimeFunction::OMPRTL___kmpc_dispatch_fini_8u);
2563   llvm_unreachable("unknown OpenMP loop iterator bitwidth");
2564 }
2565 
2566 OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::applyDynamicWorkshareLoop(
2567     DebugLoc DL, CanonicalLoopInfo *CLI, InsertPointTy AllocaIP,
2568     OMPScheduleType SchedType, bool NeedsBarrier, Value *Chunk) {
2569   assert(CLI->isValid() && "Requires a valid canonical loop");
2570   assert(!isConflictIP(AllocaIP, CLI->getPreheaderIP()) &&
2571          "Require dedicated allocate IP");
2572   assert(isValidWorkshareLoopScheduleType(SchedType) &&
2573          "Require valid schedule type");
2574 
2575   bool Ordered = (SchedType & OMPScheduleType::ModifierOrdered) ==
2576                  OMPScheduleType::ModifierOrdered;
2577 
2578   // Set up the source location value for OpenMP runtime.
2579   Builder.SetCurrentDebugLocation(DL);
2580 
2581   uint32_t SrcLocStrSize;
2582   Constant *SrcLocStr = getOrCreateSrcLocStr(DL, SrcLocStrSize);
2583   Value *SrcLoc = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
2584 
2585   // Declare useful OpenMP runtime functions.
2586   Value *IV = CLI->getIndVar();
2587   Type *IVTy = IV->getType();
2588   FunctionCallee DynamicInit = getKmpcForDynamicInitForType(IVTy, M, *this);
2589   FunctionCallee DynamicNext = getKmpcForDynamicNextForType(IVTy, M, *this);
2590 
2591   // Allocate space for computed loop bounds as expected by the "init" function.
2592   Builder.restoreIP(AllocaIP);
2593   Type *I32Type = Type::getInt32Ty(M.getContext());
2594   Value *PLastIter = Builder.CreateAlloca(I32Type, nullptr, "p.lastiter");
2595   Value *PLowerBound = Builder.CreateAlloca(IVTy, nullptr, "p.lowerbound");
2596   Value *PUpperBound = Builder.CreateAlloca(IVTy, nullptr, "p.upperbound");
2597   Value *PStride = Builder.CreateAlloca(IVTy, nullptr, "p.stride");
2598 
2599   // At the end of the preheader, prepare for calling the "init" function by
2600   // storing the current loop bounds into the allocated space. A canonical loop
2601   // always iterates from 0 to trip-count with step 1. Note that "init" expects
2602   // and produces an inclusive upper bound.
2603   BasicBlock *PreHeader = CLI->getPreheader();
2604   Builder.SetInsertPoint(PreHeader->getTerminator());
2605   Constant *One = ConstantInt::get(IVTy, 1);
2606   Builder.CreateStore(One, PLowerBound);
2607   Value *UpperBound = CLI->getTripCount();
2608   Builder.CreateStore(UpperBound, PUpperBound);
2609   Builder.CreateStore(One, PStride);
2610 
2611   BasicBlock *Header = CLI->getHeader();
2612   BasicBlock *Exit = CLI->getExit();
2613   BasicBlock *Cond = CLI->getCond();
2614   BasicBlock *Latch = CLI->getLatch();
2615   InsertPointTy AfterIP = CLI->getAfterIP();
2616 
2617   // The CLI will be "broken" in the code below, as the loop is no longer
2618   // a valid canonical loop.
2619 
2620   if (!Chunk)
2621     Chunk = One;
2622 
2623   Value *ThreadNum = getOrCreateThreadID(SrcLoc);
2624 
2625   Constant *SchedulingType =
2626       ConstantInt::get(I32Type, static_cast<int>(SchedType));
2627 
2628   // Call the "init" function.
2629   Builder.CreateCall(DynamicInit,
2630                      {SrcLoc, ThreadNum, SchedulingType, /* LowerBound */ One,
2631                       UpperBound, /* step */ One, Chunk});
2632 
2633   // An outer loop around the existing one.
2634   BasicBlock *OuterCond = BasicBlock::Create(
2635       PreHeader->getContext(), Twine(PreHeader->getName()) + ".outer.cond",
2636       PreHeader->getParent());
2637   // This needs to be 32-bit always, so can't use the IVTy Zero above.
2638   Builder.SetInsertPoint(OuterCond, OuterCond->getFirstInsertionPt());
2639   Value *Res =
2640       Builder.CreateCall(DynamicNext, {SrcLoc, ThreadNum, PLastIter,
2641                                        PLowerBound, PUpperBound, PStride});
2642   Constant *Zero32 = ConstantInt::get(I32Type, 0);
2643   Value *MoreWork = Builder.CreateCmp(CmpInst::ICMP_NE, Res, Zero32);
2644   Value *LowerBound =
2645       Builder.CreateSub(Builder.CreateLoad(IVTy, PLowerBound), One, "lb");
2646   Builder.CreateCondBr(MoreWork, Header, Exit);
2647 
2648   // Change PHI-node in loop header to use outer cond rather than preheader,
2649   // and set IV to the LowerBound.
2650   Instruction *Phi = &Header->front();
2651   auto *PI = cast<PHINode>(Phi);
2652   PI->setIncomingBlock(0, OuterCond);
2653   PI->setIncomingValue(0, LowerBound);
2654 
2655   // Then set the pre-header to jump to the OuterCond
2656   Instruction *Term = PreHeader->getTerminator();
2657   auto *Br = cast<BranchInst>(Term);
2658   Br->setSuccessor(0, OuterCond);
2659 
2660   // Modify the inner condition:
2661   // * Use the UpperBound returned from the DynamicNext call.
2662   // * jump to the loop outer loop when done with one of the inner loops.
2663   Builder.SetInsertPoint(Cond, Cond->getFirstInsertionPt());
2664   UpperBound = Builder.CreateLoad(IVTy, PUpperBound, "ub");
2665   Instruction *Comp = &*Builder.GetInsertPoint();
2666   auto *CI = cast<CmpInst>(Comp);
2667   CI->setOperand(1, UpperBound);
2668   // Redirect the inner exit to branch to outer condition.
2669   Instruction *Branch = &Cond->back();
2670   auto *BI = cast<BranchInst>(Branch);
2671   assert(BI->getSuccessor(1) == Exit);
2672   BI->setSuccessor(1, OuterCond);
2673 
2674   // Call the "fini" function if "ordered" is present in wsloop directive.
2675   if (Ordered) {
2676     Builder.SetInsertPoint(&Latch->back());
2677     FunctionCallee DynamicFini = getKmpcForDynamicFiniForType(IVTy, M, *this);
2678     Builder.CreateCall(DynamicFini, {SrcLoc, ThreadNum});
2679   }
2680 
2681   // Add the barrier if requested.
2682   if (NeedsBarrier) {
2683     Builder.SetInsertPoint(&Exit->back());
2684     createBarrier(LocationDescription(Builder.saveIP(), DL),
2685                   omp::Directive::OMPD_for, /* ForceSimpleCall */ false,
2686                   /* CheckCancelFlag */ false);
2687   }
2688 
2689   CLI->invalidate();
2690   return AfterIP;
2691 }
2692 
2693 /// Redirect all edges that branch to \p OldTarget to \p NewTarget. That is,
2694 /// after this \p OldTarget will be orphaned.
2695 static void redirectAllPredecessorsTo(BasicBlock *OldTarget,
2696                                       BasicBlock *NewTarget, DebugLoc DL) {
2697   for (BasicBlock *Pred : make_early_inc_range(predecessors(OldTarget)))
2698     redirectTo(Pred, NewTarget, DL);
2699 }
2700 
2701 /// Determine which blocks in \p BBs are reachable from outside and remove the
2702 /// ones that are not reachable from the function.
2703 static void removeUnusedBlocksFromParent(ArrayRef<BasicBlock *> BBs) {
2704   SmallPtrSet<BasicBlock *, 6> BBsToErase{BBs.begin(), BBs.end()};
2705   auto HasRemainingUses = [&BBsToErase](BasicBlock *BB) {
2706     for (Use &U : BB->uses()) {
2707       auto *UseInst = dyn_cast<Instruction>(U.getUser());
2708       if (!UseInst)
2709         continue;
2710       if (BBsToErase.count(UseInst->getParent()))
2711         continue;
2712       return true;
2713     }
2714     return false;
2715   };
2716 
2717   while (true) {
2718     bool Changed = false;
2719     for (BasicBlock *BB : make_early_inc_range(BBsToErase)) {
2720       if (HasRemainingUses(BB)) {
2721         BBsToErase.erase(BB);
2722         Changed = true;
2723       }
2724     }
2725     if (!Changed)
2726       break;
2727   }
2728 
2729   SmallVector<BasicBlock *, 7> BBVec(BBsToErase.begin(), BBsToErase.end());
2730   DeleteDeadBlocks(BBVec);
2731 }
2732 
2733 CanonicalLoopInfo *
2734 OpenMPIRBuilder::collapseLoops(DebugLoc DL, ArrayRef<CanonicalLoopInfo *> Loops,
2735                                InsertPointTy ComputeIP) {
2736   assert(Loops.size() >= 1 && "At least one loop required");
2737   size_t NumLoops = Loops.size();
2738 
2739   // Nothing to do if there is already just one loop.
2740   if (NumLoops == 1)
2741     return Loops.front();
2742 
2743   CanonicalLoopInfo *Outermost = Loops.front();
2744   CanonicalLoopInfo *Innermost = Loops.back();
2745   BasicBlock *OrigPreheader = Outermost->getPreheader();
2746   BasicBlock *OrigAfter = Outermost->getAfter();
2747   Function *F = OrigPreheader->getParent();
2748 
2749   // Loop control blocks that may become orphaned later.
2750   SmallVector<BasicBlock *, 12> OldControlBBs;
2751   OldControlBBs.reserve(6 * Loops.size());
2752   for (CanonicalLoopInfo *Loop : Loops)
2753     Loop->collectControlBlocks(OldControlBBs);
2754 
2755   // Setup the IRBuilder for inserting the trip count computation.
2756   Builder.SetCurrentDebugLocation(DL);
2757   if (ComputeIP.isSet())
2758     Builder.restoreIP(ComputeIP);
2759   else
2760     Builder.restoreIP(Outermost->getPreheaderIP());
2761 
2762   // Derive the collapsed' loop trip count.
2763   // TODO: Find common/largest indvar type.
2764   Value *CollapsedTripCount = nullptr;
2765   for (CanonicalLoopInfo *L : Loops) {
2766     assert(L->isValid() &&
2767            "All loops to collapse must be valid canonical loops");
2768     Value *OrigTripCount = L->getTripCount();
2769     if (!CollapsedTripCount) {
2770       CollapsedTripCount = OrigTripCount;
2771       continue;
2772     }
2773 
2774     // TODO: Enable UndefinedSanitizer to diagnose an overflow here.
2775     CollapsedTripCount = Builder.CreateMul(CollapsedTripCount, OrigTripCount,
2776                                            {}, /*HasNUW=*/true);
2777   }
2778 
2779   // Create the collapsed loop control flow.
2780   CanonicalLoopInfo *Result =
2781       createLoopSkeleton(DL, CollapsedTripCount, F,
2782                          OrigPreheader->getNextNode(), OrigAfter, "collapsed");
2783 
2784   // Build the collapsed loop body code.
2785   // Start with deriving the input loop induction variables from the collapsed
2786   // one, using a divmod scheme. To preserve the original loops' order, the
2787   // innermost loop use the least significant bits.
2788   Builder.restoreIP(Result->getBodyIP());
2789 
2790   Value *Leftover = Result->getIndVar();
2791   SmallVector<Value *> NewIndVars;
2792   NewIndVars.resize(NumLoops);
2793   for (int i = NumLoops - 1; i >= 1; --i) {
2794     Value *OrigTripCount = Loops[i]->getTripCount();
2795 
2796     Value *NewIndVar = Builder.CreateURem(Leftover, OrigTripCount);
2797     NewIndVars[i] = NewIndVar;
2798 
2799     Leftover = Builder.CreateUDiv(Leftover, OrigTripCount);
2800   }
2801   // Outermost loop gets all the remaining bits.
2802   NewIndVars[0] = Leftover;
2803 
2804   // Construct the loop body control flow.
2805   // We progressively construct the branch structure following in direction of
2806   // the control flow, from the leading in-between code, the loop nest body, the
2807   // trailing in-between code, and rejoining the collapsed loop's latch.
2808   // ContinueBlock and ContinuePred keep track of the source(s) of next edge. If
2809   // the ContinueBlock is set, continue with that block. If ContinuePred, use
2810   // its predecessors as sources.
2811   BasicBlock *ContinueBlock = Result->getBody();
2812   BasicBlock *ContinuePred = nullptr;
2813   auto ContinueWith = [&ContinueBlock, &ContinuePred, DL](BasicBlock *Dest,
2814                                                           BasicBlock *NextSrc) {
2815     if (ContinueBlock)
2816       redirectTo(ContinueBlock, Dest, DL);
2817     else
2818       redirectAllPredecessorsTo(ContinuePred, Dest, DL);
2819 
2820     ContinueBlock = nullptr;
2821     ContinuePred = NextSrc;
2822   };
2823 
2824   // The code before the nested loop of each level.
2825   // Because we are sinking it into the nest, it will be executed more often
2826   // that the original loop. More sophisticated schemes could keep track of what
2827   // the in-between code is and instantiate it only once per thread.
2828   for (size_t i = 0; i < NumLoops - 1; ++i)
2829     ContinueWith(Loops[i]->getBody(), Loops[i + 1]->getHeader());
2830 
2831   // Connect the loop nest body.
2832   ContinueWith(Innermost->getBody(), Innermost->getLatch());
2833 
2834   // The code after the nested loop at each level.
2835   for (size_t i = NumLoops - 1; i > 0; --i)
2836     ContinueWith(Loops[i]->getAfter(), Loops[i - 1]->getLatch());
2837 
2838   // Connect the finished loop to the collapsed loop latch.
2839   ContinueWith(Result->getLatch(), nullptr);
2840 
2841   // Replace the input loops with the new collapsed loop.
2842   redirectTo(Outermost->getPreheader(), Result->getPreheader(), DL);
2843   redirectTo(Result->getAfter(), Outermost->getAfter(), DL);
2844 
2845   // Replace the input loop indvars with the derived ones.
2846   for (size_t i = 0; i < NumLoops; ++i)
2847     Loops[i]->getIndVar()->replaceAllUsesWith(NewIndVars[i]);
2848 
2849   // Remove unused parts of the input loops.
2850   removeUnusedBlocksFromParent(OldControlBBs);
2851 
2852   for (CanonicalLoopInfo *L : Loops)
2853     L->invalidate();
2854 
2855 #ifndef NDEBUG
2856   Result->assertOK();
2857 #endif
2858   return Result;
2859 }
2860 
2861 std::vector<CanonicalLoopInfo *>
2862 OpenMPIRBuilder::tileLoops(DebugLoc DL, ArrayRef<CanonicalLoopInfo *> Loops,
2863                            ArrayRef<Value *> TileSizes) {
2864   assert(TileSizes.size() == Loops.size() &&
2865          "Must pass as many tile sizes as there are loops");
2866   int NumLoops = Loops.size();
2867   assert(NumLoops >= 1 && "At least one loop to tile required");
2868 
2869   CanonicalLoopInfo *OutermostLoop = Loops.front();
2870   CanonicalLoopInfo *InnermostLoop = Loops.back();
2871   Function *F = OutermostLoop->getBody()->getParent();
2872   BasicBlock *InnerEnter = InnermostLoop->getBody();
2873   BasicBlock *InnerLatch = InnermostLoop->getLatch();
2874 
2875   // Loop control blocks that may become orphaned later.
2876   SmallVector<BasicBlock *, 12> OldControlBBs;
2877   OldControlBBs.reserve(6 * Loops.size());
2878   for (CanonicalLoopInfo *Loop : Loops)
2879     Loop->collectControlBlocks(OldControlBBs);
2880 
2881   // Collect original trip counts and induction variable to be accessible by
2882   // index. Also, the structure of the original loops is not preserved during
2883   // the construction of the tiled loops, so do it before we scavenge the BBs of
2884   // any original CanonicalLoopInfo.
2885   SmallVector<Value *, 4> OrigTripCounts, OrigIndVars;
2886   for (CanonicalLoopInfo *L : Loops) {
2887     assert(L->isValid() && "All input loops must be valid canonical loops");
2888     OrigTripCounts.push_back(L->getTripCount());
2889     OrigIndVars.push_back(L->getIndVar());
2890   }
2891 
2892   // Collect the code between loop headers. These may contain SSA definitions
2893   // that are used in the loop nest body. To be usable with in the innermost
2894   // body, these BasicBlocks will be sunk into the loop nest body. That is,
2895   // these instructions may be executed more often than before the tiling.
2896   // TODO: It would be sufficient to only sink them into body of the
2897   // corresponding tile loop.
2898   SmallVector<std::pair<BasicBlock *, BasicBlock *>, 4> InbetweenCode;
2899   for (int i = 0; i < NumLoops - 1; ++i) {
2900     CanonicalLoopInfo *Surrounding = Loops[i];
2901     CanonicalLoopInfo *Nested = Loops[i + 1];
2902 
2903     BasicBlock *EnterBB = Surrounding->getBody();
2904     BasicBlock *ExitBB = Nested->getHeader();
2905     InbetweenCode.emplace_back(EnterBB, ExitBB);
2906   }
2907 
2908   // Compute the trip counts of the floor loops.
2909   Builder.SetCurrentDebugLocation(DL);
2910   Builder.restoreIP(OutermostLoop->getPreheaderIP());
2911   SmallVector<Value *, 4> FloorCount, FloorRems;
2912   for (int i = 0; i < NumLoops; ++i) {
2913     Value *TileSize = TileSizes[i];
2914     Value *OrigTripCount = OrigTripCounts[i];
2915     Type *IVType = OrigTripCount->getType();
2916 
2917     Value *FloorTripCount = Builder.CreateUDiv(OrigTripCount, TileSize);
2918     Value *FloorTripRem = Builder.CreateURem(OrigTripCount, TileSize);
2919 
2920     // 0 if tripcount divides the tilesize, 1 otherwise.
2921     // 1 means we need an additional iteration for a partial tile.
2922     //
2923     // Unfortunately we cannot just use the roundup-formula
2924     //   (tripcount + tilesize - 1)/tilesize
2925     // because the summation might overflow. We do not want introduce undefined
2926     // behavior when the untiled loop nest did not.
2927     Value *FloorTripOverflow =
2928         Builder.CreateICmpNE(FloorTripRem, ConstantInt::get(IVType, 0));
2929 
2930     FloorTripOverflow = Builder.CreateZExt(FloorTripOverflow, IVType);
2931     FloorTripCount =
2932         Builder.CreateAdd(FloorTripCount, FloorTripOverflow,
2933                           "omp_floor" + Twine(i) + ".tripcount", true);
2934 
2935     // Remember some values for later use.
2936     FloorCount.push_back(FloorTripCount);
2937     FloorRems.push_back(FloorTripRem);
2938   }
2939 
2940   // Generate the new loop nest, from the outermost to the innermost.
2941   std::vector<CanonicalLoopInfo *> Result;
2942   Result.reserve(NumLoops * 2);
2943 
2944   // The basic block of the surrounding loop that enters the nest generated
2945   // loop.
2946   BasicBlock *Enter = OutermostLoop->getPreheader();
2947 
2948   // The basic block of the surrounding loop where the inner code should
2949   // continue.
2950   BasicBlock *Continue = OutermostLoop->getAfter();
2951 
2952   // Where the next loop basic block should be inserted.
2953   BasicBlock *OutroInsertBefore = InnermostLoop->getExit();
2954 
2955   auto EmbeddNewLoop =
2956       [this, DL, F, InnerEnter, &Enter, &Continue, &OutroInsertBefore](
2957           Value *TripCount, const Twine &Name) -> CanonicalLoopInfo * {
2958     CanonicalLoopInfo *EmbeddedLoop = createLoopSkeleton(
2959         DL, TripCount, F, InnerEnter, OutroInsertBefore, Name);
2960     redirectTo(Enter, EmbeddedLoop->getPreheader(), DL);
2961     redirectTo(EmbeddedLoop->getAfter(), Continue, DL);
2962 
2963     // Setup the position where the next embedded loop connects to this loop.
2964     Enter = EmbeddedLoop->getBody();
2965     Continue = EmbeddedLoop->getLatch();
2966     OutroInsertBefore = EmbeddedLoop->getLatch();
2967     return EmbeddedLoop;
2968   };
2969 
2970   auto EmbeddNewLoops = [&Result, &EmbeddNewLoop](ArrayRef<Value *> TripCounts,
2971                                                   const Twine &NameBase) {
2972     for (auto P : enumerate(TripCounts)) {
2973       CanonicalLoopInfo *EmbeddedLoop =
2974           EmbeddNewLoop(P.value(), NameBase + Twine(P.index()));
2975       Result.push_back(EmbeddedLoop);
2976     }
2977   };
2978 
2979   EmbeddNewLoops(FloorCount, "floor");
2980 
2981   // Within the innermost floor loop, emit the code that computes the tile
2982   // sizes.
2983   Builder.SetInsertPoint(Enter->getTerminator());
2984   SmallVector<Value *, 4> TileCounts;
2985   for (int i = 0; i < NumLoops; ++i) {
2986     CanonicalLoopInfo *FloorLoop = Result[i];
2987     Value *TileSize = TileSizes[i];
2988 
2989     Value *FloorIsEpilogue =
2990         Builder.CreateICmpEQ(FloorLoop->getIndVar(), FloorCount[i]);
2991     Value *TileTripCount =
2992         Builder.CreateSelect(FloorIsEpilogue, FloorRems[i], TileSize);
2993 
2994     TileCounts.push_back(TileTripCount);
2995   }
2996 
2997   // Create the tile loops.
2998   EmbeddNewLoops(TileCounts, "tile");
2999 
3000   // Insert the inbetween code into the body.
3001   BasicBlock *BodyEnter = Enter;
3002   BasicBlock *BodyEntered = nullptr;
3003   for (std::pair<BasicBlock *, BasicBlock *> P : InbetweenCode) {
3004     BasicBlock *EnterBB = P.first;
3005     BasicBlock *ExitBB = P.second;
3006 
3007     if (BodyEnter)
3008       redirectTo(BodyEnter, EnterBB, DL);
3009     else
3010       redirectAllPredecessorsTo(BodyEntered, EnterBB, DL);
3011 
3012     BodyEnter = nullptr;
3013     BodyEntered = ExitBB;
3014   }
3015 
3016   // Append the original loop nest body into the generated loop nest body.
3017   if (BodyEnter)
3018     redirectTo(BodyEnter, InnerEnter, DL);
3019   else
3020     redirectAllPredecessorsTo(BodyEntered, InnerEnter, DL);
3021   redirectAllPredecessorsTo(InnerLatch, Continue, DL);
3022 
3023   // Replace the original induction variable with an induction variable computed
3024   // from the tile and floor induction variables.
3025   Builder.restoreIP(Result.back()->getBodyIP());
3026   for (int i = 0; i < NumLoops; ++i) {
3027     CanonicalLoopInfo *FloorLoop = Result[i];
3028     CanonicalLoopInfo *TileLoop = Result[NumLoops + i];
3029     Value *OrigIndVar = OrigIndVars[i];
3030     Value *Size = TileSizes[i];
3031 
3032     Value *Scale =
3033         Builder.CreateMul(Size, FloorLoop->getIndVar(), {}, /*HasNUW=*/true);
3034     Value *Shift =
3035         Builder.CreateAdd(Scale, TileLoop->getIndVar(), {}, /*HasNUW=*/true);
3036     OrigIndVar->replaceAllUsesWith(Shift);
3037   }
3038 
3039   // Remove unused parts of the original loops.
3040   removeUnusedBlocksFromParent(OldControlBBs);
3041 
3042   for (CanonicalLoopInfo *L : Loops)
3043     L->invalidate();
3044 
3045 #ifndef NDEBUG
3046   for (CanonicalLoopInfo *GenL : Result)
3047     GenL->assertOK();
3048 #endif
3049   return Result;
3050 }
3051 
3052 /// Attach metadata \p Properties to the basic block described by \p BB. If the
3053 /// basic block already has metadata, the basic block properties are appended.
3054 static void addBasicBlockMetadata(BasicBlock *BB,
3055                                   ArrayRef<Metadata *> Properties) {
3056   // Nothing to do if no property to attach.
3057   if (Properties.empty())
3058     return;
3059 
3060   LLVMContext &Ctx = BB->getContext();
3061   SmallVector<Metadata *> NewProperties;
3062   NewProperties.push_back(nullptr);
3063 
3064   // If the basic block already has metadata, prepend it to the new metadata.
3065   MDNode *Existing = BB->getTerminator()->getMetadata(LLVMContext::MD_loop);
3066   if (Existing)
3067     append_range(NewProperties, drop_begin(Existing->operands(), 1));
3068 
3069   append_range(NewProperties, Properties);
3070   MDNode *BasicBlockID = MDNode::getDistinct(Ctx, NewProperties);
3071   BasicBlockID->replaceOperandWith(0, BasicBlockID);
3072 
3073   BB->getTerminator()->setMetadata(LLVMContext::MD_loop, BasicBlockID);
3074 }
3075 
3076 /// Attach loop metadata \p Properties to the loop described by \p Loop. If the
3077 /// loop already has metadata, the loop properties are appended.
3078 static void addLoopMetadata(CanonicalLoopInfo *Loop,
3079                             ArrayRef<Metadata *> Properties) {
3080   assert(Loop->isValid() && "Expecting a valid CanonicalLoopInfo");
3081 
3082   // Attach metadata to the loop's latch
3083   BasicBlock *Latch = Loop->getLatch();
3084   assert(Latch && "A valid CanonicalLoopInfo must have a unique latch");
3085   addBasicBlockMetadata(Latch, Properties);
3086 }
3087 
3088 /// Attach llvm.access.group metadata to the memref instructions of \p Block
3089 static void addSimdMetadata(BasicBlock *Block, MDNode *AccessGroup,
3090                             LoopInfo &LI) {
3091   for (Instruction &I : *Block) {
3092     if (I.mayReadOrWriteMemory()) {
3093       // TODO: This instruction may already have access group from
3094       // other pragmas e.g. #pragma clang loop vectorize.  Append
3095       // so that the existing metadata is not overwritten.
3096       I.setMetadata(LLVMContext::MD_access_group, AccessGroup);
3097     }
3098   }
3099 }
3100 
3101 void OpenMPIRBuilder::unrollLoopFull(DebugLoc, CanonicalLoopInfo *Loop) {
3102   LLVMContext &Ctx = Builder.getContext();
3103   addLoopMetadata(
3104       Loop, {MDNode::get(Ctx, MDString::get(Ctx, "llvm.loop.unroll.enable")),
3105              MDNode::get(Ctx, MDString::get(Ctx, "llvm.loop.unroll.full"))});
3106 }
3107 
3108 void OpenMPIRBuilder::unrollLoopHeuristic(DebugLoc, CanonicalLoopInfo *Loop) {
3109   LLVMContext &Ctx = Builder.getContext();
3110   addLoopMetadata(
3111       Loop, {
3112                 MDNode::get(Ctx, MDString::get(Ctx, "llvm.loop.unroll.enable")),
3113             });
3114 }
3115 
3116 void OpenMPIRBuilder::createIfVersion(CanonicalLoopInfo *CanonicalLoop,
3117                                       Value *IfCond, ValueToValueMapTy &VMap,
3118                                       const Twine &NamePrefix) {
3119   Function *F = CanonicalLoop->getFunction();
3120 
3121   // Define where if branch should be inserted
3122   Instruction *SplitBefore;
3123   if (Instruction::classof(IfCond)) {
3124     SplitBefore = dyn_cast<Instruction>(IfCond);
3125   } else {
3126     SplitBefore = CanonicalLoop->getPreheader()->getTerminator();
3127   }
3128 
3129   // TODO: We should not rely on pass manager. Currently we use pass manager
3130   // only for getting llvm::Loop which corresponds to given CanonicalLoopInfo
3131   // object. We should have a method  which returns all blocks between
3132   // CanonicalLoopInfo::getHeader() and CanonicalLoopInfo::getAfter()
3133   FunctionAnalysisManager FAM;
3134   FAM.registerPass([]() { return DominatorTreeAnalysis(); });
3135   FAM.registerPass([]() { return LoopAnalysis(); });
3136   FAM.registerPass([]() { return PassInstrumentationAnalysis(); });
3137 
3138   // Get the loop which needs to be cloned
3139   LoopAnalysis LIA;
3140   LoopInfo &&LI = LIA.run(*F, FAM);
3141   Loop *L = LI.getLoopFor(CanonicalLoop->getHeader());
3142 
3143   // Create additional blocks for the if statement
3144   BasicBlock *Head = SplitBefore->getParent();
3145   Instruction *HeadOldTerm = Head->getTerminator();
3146   llvm::LLVMContext &C = Head->getContext();
3147   llvm::BasicBlock *ThenBlock = llvm::BasicBlock::Create(
3148       C, NamePrefix + ".if.then", Head->getParent(), Head->getNextNode());
3149   llvm::BasicBlock *ElseBlock = llvm::BasicBlock::Create(
3150       C, NamePrefix + ".if.else", Head->getParent(), CanonicalLoop->getExit());
3151 
3152   // Create if condition branch.
3153   Builder.SetInsertPoint(HeadOldTerm);
3154   Instruction *BrInstr =
3155       Builder.CreateCondBr(IfCond, ThenBlock, /*ifFalse*/ ElseBlock);
3156   InsertPointTy IP{BrInstr->getParent(), ++BrInstr->getIterator()};
3157   // Then block contains branch to omp loop which needs to be vectorized
3158   spliceBB(IP, ThenBlock, false);
3159   ThenBlock->replaceSuccessorsPhiUsesWith(Head, ThenBlock);
3160 
3161   Builder.SetInsertPoint(ElseBlock);
3162 
3163   // Clone loop for the else branch
3164   SmallVector<BasicBlock *, 8> NewBlocks;
3165 
3166   VMap[CanonicalLoop->getPreheader()] = ElseBlock;
3167   for (BasicBlock *Block : L->getBlocks()) {
3168     BasicBlock *NewBB = CloneBasicBlock(Block, VMap, "", F);
3169     NewBB->moveBefore(CanonicalLoop->getExit());
3170     VMap[Block] = NewBB;
3171     NewBlocks.push_back(NewBB);
3172   }
3173   remapInstructionsInBlocks(NewBlocks, VMap);
3174   Builder.CreateBr(NewBlocks.front());
3175 }
3176 
3177 unsigned
3178 OpenMPIRBuilder::getOpenMPDefaultSimdAlign(const Triple &TargetTriple,
3179                                            const StringMap<bool> &Features) {
3180   if (TargetTriple.isX86()) {
3181     if (Features.lookup("avx512f"))
3182       return 512;
3183     else if (Features.lookup("avx"))
3184       return 256;
3185     return 128;
3186   }
3187   if (TargetTriple.isPPC())
3188     return 128;
3189   if (TargetTriple.isWasm())
3190     return 128;
3191   return 0;
3192 }
3193 
3194 void OpenMPIRBuilder::applySimd(CanonicalLoopInfo *CanonicalLoop,
3195                                 MapVector<Value *, Value *> AlignedVars,
3196                                 Value *IfCond, OrderKind Order,
3197                                 ConstantInt *Simdlen, ConstantInt *Safelen) {
3198   LLVMContext &Ctx = Builder.getContext();
3199 
3200   Function *F = CanonicalLoop->getFunction();
3201 
3202   // TODO: We should not rely on pass manager. Currently we use pass manager
3203   // only for getting llvm::Loop which corresponds to given CanonicalLoopInfo
3204   // object. We should have a method  which returns all blocks between
3205   // CanonicalLoopInfo::getHeader() and CanonicalLoopInfo::getAfter()
3206   FunctionAnalysisManager FAM;
3207   FAM.registerPass([]() { return DominatorTreeAnalysis(); });
3208   FAM.registerPass([]() { return LoopAnalysis(); });
3209   FAM.registerPass([]() { return PassInstrumentationAnalysis(); });
3210 
3211   LoopAnalysis LIA;
3212   LoopInfo &&LI = LIA.run(*F, FAM);
3213 
3214   Loop *L = LI.getLoopFor(CanonicalLoop->getHeader());
3215   if (AlignedVars.size()) {
3216     InsertPointTy IP = Builder.saveIP();
3217     Builder.SetInsertPoint(CanonicalLoop->getPreheader()->getTerminator());
3218     for (auto &AlignedItem : AlignedVars) {
3219       Value *AlignedPtr = AlignedItem.first;
3220       Value *Alignment = AlignedItem.second;
3221       Builder.CreateAlignmentAssumption(F->getParent()->getDataLayout(),
3222                                         AlignedPtr, Alignment);
3223     }
3224     Builder.restoreIP(IP);
3225   }
3226 
3227   if (IfCond) {
3228     ValueToValueMapTy VMap;
3229     createIfVersion(CanonicalLoop, IfCond, VMap, "simd");
3230     // Add metadata to the cloned loop which disables vectorization
3231     Value *MappedLatch = VMap.lookup(CanonicalLoop->getLatch());
3232     assert(MappedLatch &&
3233            "Cannot find value which corresponds to original loop latch");
3234     assert(isa<BasicBlock>(MappedLatch) &&
3235            "Cannot cast mapped latch block value to BasicBlock");
3236     BasicBlock *NewLatchBlock = dyn_cast<BasicBlock>(MappedLatch);
3237     ConstantAsMetadata *BoolConst =
3238         ConstantAsMetadata::get(ConstantInt::getFalse(Type::getInt1Ty(Ctx)));
3239     addBasicBlockMetadata(
3240         NewLatchBlock,
3241         {MDNode::get(Ctx, {MDString::get(Ctx, "llvm.loop.vectorize.enable"),
3242                            BoolConst})});
3243   }
3244 
3245   SmallSet<BasicBlock *, 8> Reachable;
3246 
3247   // Get the basic blocks from the loop in which memref instructions
3248   // can be found.
3249   // TODO: Generalize getting all blocks inside a CanonicalizeLoopInfo,
3250   // preferably without running any passes.
3251   for (BasicBlock *Block : L->getBlocks()) {
3252     if (Block == CanonicalLoop->getCond() ||
3253         Block == CanonicalLoop->getHeader())
3254       continue;
3255     Reachable.insert(Block);
3256   }
3257 
3258   SmallVector<Metadata *> LoopMDList;
3259 
3260   // In presence of finite 'safelen', it may be unsafe to mark all
3261   // the memory instructions parallel, because loop-carried
3262   // dependences of 'safelen' iterations are possible.
3263   // If clause order(concurrent) is specified then the memory instructions
3264   // are marked parallel even if 'safelen' is finite.
3265   if ((Safelen == nullptr) || (Order == OrderKind::OMP_ORDER_concurrent)) {
3266     // Add access group metadata to memory-access instructions.
3267     MDNode *AccessGroup = MDNode::getDistinct(Ctx, {});
3268     for (BasicBlock *BB : Reachable)
3269       addSimdMetadata(BB, AccessGroup, LI);
3270     // TODO:  If the loop has existing parallel access metadata, have
3271     // to combine two lists.
3272     LoopMDList.push_back(MDNode::get(
3273         Ctx, {MDString::get(Ctx, "llvm.loop.parallel_accesses"), AccessGroup}));
3274   }
3275 
3276   // Use the above access group metadata to create loop level
3277   // metadata, which should be distinct for each loop.
3278   ConstantAsMetadata *BoolConst =
3279       ConstantAsMetadata::get(ConstantInt::getTrue(Type::getInt1Ty(Ctx)));
3280   LoopMDList.push_back(MDNode::get(
3281       Ctx, {MDString::get(Ctx, "llvm.loop.vectorize.enable"), BoolConst}));
3282 
3283   if (Simdlen || Safelen) {
3284     // If both simdlen and safelen clauses are specified, the value of the
3285     // simdlen parameter must be less than or equal to the value of the safelen
3286     // parameter. Therefore, use safelen only in the absence of simdlen.
3287     ConstantInt *VectorizeWidth = Simdlen == nullptr ? Safelen : Simdlen;
3288     LoopMDList.push_back(
3289         MDNode::get(Ctx, {MDString::get(Ctx, "llvm.loop.vectorize.width"),
3290                           ConstantAsMetadata::get(VectorizeWidth)}));
3291   }
3292 
3293   addLoopMetadata(CanonicalLoop, LoopMDList);
3294 }
3295 
3296 /// Create the TargetMachine object to query the backend for optimization
3297 /// preferences.
3298 ///
3299 /// Ideally, this would be passed from the front-end to the OpenMPBuilder, but
3300 /// e.g. Clang does not pass it to its CodeGen layer and creates it only when
3301 /// needed for the LLVM pass pipline. We use some default options to avoid
3302 /// having to pass too many settings from the frontend that probably do not
3303 /// matter.
3304 ///
3305 /// Currently, TargetMachine is only used sometimes by the unrollLoopPartial
3306 /// method. If we are going to use TargetMachine for more purposes, especially
3307 /// those that are sensitive to TargetOptions, RelocModel and CodeModel, it
3308 /// might become be worth requiring front-ends to pass on their TargetMachine,
3309 /// or at least cache it between methods. Note that while fontends such as Clang
3310 /// have just a single main TargetMachine per translation unit, "target-cpu" and
3311 /// "target-features" that determine the TargetMachine are per-function and can
3312 /// be overrided using __attribute__((target("OPTIONS"))).
3313 static std::unique_ptr<TargetMachine>
3314 createTargetMachine(Function *F, CodeGenOpt::Level OptLevel) {
3315   Module *M = F->getParent();
3316 
3317   StringRef CPU = F->getFnAttribute("target-cpu").getValueAsString();
3318   StringRef Features = F->getFnAttribute("target-features").getValueAsString();
3319   const std::string &Triple = M->getTargetTriple();
3320 
3321   std::string Error;
3322   const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
3323   if (!TheTarget)
3324     return {};
3325 
3326   llvm::TargetOptions Options;
3327   return std::unique_ptr<TargetMachine>(TheTarget->createTargetMachine(
3328       Triple, CPU, Features, Options, /*RelocModel=*/std::nullopt,
3329       /*CodeModel=*/std::nullopt, OptLevel));
3330 }
3331 
3332 /// Heuristically determine the best-performant unroll factor for \p CLI. This
3333 /// depends on the target processor. We are re-using the same heuristics as the
3334 /// LoopUnrollPass.
3335 static int32_t computeHeuristicUnrollFactor(CanonicalLoopInfo *CLI) {
3336   Function *F = CLI->getFunction();
3337 
3338   // Assume the user requests the most aggressive unrolling, even if the rest of
3339   // the code is optimized using a lower setting.
3340   CodeGenOpt::Level OptLevel = CodeGenOpt::Aggressive;
3341   std::unique_ptr<TargetMachine> TM = createTargetMachine(F, OptLevel);
3342 
3343   FunctionAnalysisManager FAM;
3344   FAM.registerPass([]() { return TargetLibraryAnalysis(); });
3345   FAM.registerPass([]() { return AssumptionAnalysis(); });
3346   FAM.registerPass([]() { return DominatorTreeAnalysis(); });
3347   FAM.registerPass([]() { return LoopAnalysis(); });
3348   FAM.registerPass([]() { return ScalarEvolutionAnalysis(); });
3349   FAM.registerPass([]() { return PassInstrumentationAnalysis(); });
3350   TargetIRAnalysis TIRA;
3351   if (TM)
3352     TIRA = TargetIRAnalysis(
3353         [&](const Function &F) { return TM->getTargetTransformInfo(F); });
3354   FAM.registerPass([&]() { return TIRA; });
3355 
3356   TargetIRAnalysis::Result &&TTI = TIRA.run(*F, FAM);
3357   ScalarEvolutionAnalysis SEA;
3358   ScalarEvolution &&SE = SEA.run(*F, FAM);
3359   DominatorTreeAnalysis DTA;
3360   DominatorTree &&DT = DTA.run(*F, FAM);
3361   LoopAnalysis LIA;
3362   LoopInfo &&LI = LIA.run(*F, FAM);
3363   AssumptionAnalysis ACT;
3364   AssumptionCache &&AC = ACT.run(*F, FAM);
3365   OptimizationRemarkEmitter ORE{F};
3366 
3367   Loop *L = LI.getLoopFor(CLI->getHeader());
3368   assert(L && "Expecting CanonicalLoopInfo to be recognized as a loop");
3369 
3370   TargetTransformInfo::UnrollingPreferences UP =
3371       gatherUnrollingPreferences(L, SE, TTI,
3372                                  /*BlockFrequencyInfo=*/nullptr,
3373                                  /*ProfileSummaryInfo=*/nullptr, ORE, OptLevel,
3374                                  /*UserThreshold=*/std::nullopt,
3375                                  /*UserCount=*/std::nullopt,
3376                                  /*UserAllowPartial=*/true,
3377                                  /*UserAllowRuntime=*/true,
3378                                  /*UserUpperBound=*/std::nullopt,
3379                                  /*UserFullUnrollMaxCount=*/std::nullopt);
3380 
3381   UP.Force = true;
3382 
3383   // Account for additional optimizations taking place before the LoopUnrollPass
3384   // would unroll the loop.
3385   UP.Threshold *= UnrollThresholdFactor;
3386   UP.PartialThreshold *= UnrollThresholdFactor;
3387 
3388   // Use normal unroll factors even if the rest of the code is optimized for
3389   // size.
3390   UP.OptSizeThreshold = UP.Threshold;
3391   UP.PartialOptSizeThreshold = UP.PartialThreshold;
3392 
3393   LLVM_DEBUG(dbgs() << "Unroll heuristic thresholds:\n"
3394                     << "  Threshold=" << UP.Threshold << "\n"
3395                     << "  PartialThreshold=" << UP.PartialThreshold << "\n"
3396                     << "  OptSizeThreshold=" << UP.OptSizeThreshold << "\n"
3397                     << "  PartialOptSizeThreshold="
3398                     << UP.PartialOptSizeThreshold << "\n");
3399 
3400   // Disable peeling.
3401   TargetTransformInfo::PeelingPreferences PP =
3402       gatherPeelingPreferences(L, SE, TTI,
3403                                /*UserAllowPeeling=*/false,
3404                                /*UserAllowProfileBasedPeeling=*/false,
3405                                /*UnrollingSpecficValues=*/false);
3406 
3407   SmallPtrSet<const Value *, 32> EphValues;
3408   CodeMetrics::collectEphemeralValues(L, &AC, EphValues);
3409 
3410   // Assume that reads and writes to stack variables can be eliminated by
3411   // Mem2Reg, SROA or LICM. That is, don't count them towards the loop body's
3412   // size.
3413   for (BasicBlock *BB : L->blocks()) {
3414     for (Instruction &I : *BB) {
3415       Value *Ptr;
3416       if (auto *Load = dyn_cast<LoadInst>(&I)) {
3417         Ptr = Load->getPointerOperand();
3418       } else if (auto *Store = dyn_cast<StoreInst>(&I)) {
3419         Ptr = Store->getPointerOperand();
3420       } else
3421         continue;
3422 
3423       Ptr = Ptr->stripPointerCasts();
3424 
3425       if (auto *Alloca = dyn_cast<AllocaInst>(Ptr)) {
3426         if (Alloca->getParent() == &F->getEntryBlock())
3427           EphValues.insert(&I);
3428       }
3429     }
3430   }
3431 
3432   unsigned NumInlineCandidates;
3433   bool NotDuplicatable;
3434   bool Convergent;
3435   InstructionCost LoopSizeIC =
3436       ApproximateLoopSize(L, NumInlineCandidates, NotDuplicatable, Convergent,
3437                           TTI, EphValues, UP.BEInsns);
3438   LLVM_DEBUG(dbgs() << "Estimated loop size is " << LoopSizeIC << "\n");
3439 
3440   // Loop is not unrollable if the loop contains certain instructions.
3441   if (NotDuplicatable || Convergent || !LoopSizeIC.isValid()) {
3442     LLVM_DEBUG(dbgs() << "Loop not considered unrollable\n");
3443     return 1;
3444   }
3445   unsigned LoopSize = *LoopSizeIC.getValue();
3446 
3447   // TODO: Determine trip count of \p CLI if constant, computeUnrollCount might
3448   // be able to use it.
3449   int TripCount = 0;
3450   int MaxTripCount = 0;
3451   bool MaxOrZero = false;
3452   unsigned TripMultiple = 0;
3453 
3454   bool UseUpperBound = false;
3455   computeUnrollCount(L, TTI, DT, &LI, &AC, SE, EphValues, &ORE, TripCount,
3456                      MaxTripCount, MaxOrZero, TripMultiple, LoopSize, UP, PP,
3457                      UseUpperBound);
3458   unsigned Factor = UP.Count;
3459   LLVM_DEBUG(dbgs() << "Suggesting unroll factor of " << Factor << "\n");
3460 
3461   // This function returns 1 to signal to not unroll a loop.
3462   if (Factor == 0)
3463     return 1;
3464   return Factor;
3465 }
3466 
3467 void OpenMPIRBuilder::unrollLoopPartial(DebugLoc DL, CanonicalLoopInfo *Loop,
3468                                         int32_t Factor,
3469                                         CanonicalLoopInfo **UnrolledCLI) {
3470   assert(Factor >= 0 && "Unroll factor must not be negative");
3471 
3472   Function *F = Loop->getFunction();
3473   LLVMContext &Ctx = F->getContext();
3474 
3475   // If the unrolled loop is not used for another loop-associated directive, it
3476   // is sufficient to add metadata for the LoopUnrollPass.
3477   if (!UnrolledCLI) {
3478     SmallVector<Metadata *, 2> LoopMetadata;
3479     LoopMetadata.push_back(
3480         MDNode::get(Ctx, MDString::get(Ctx, "llvm.loop.unroll.enable")));
3481 
3482     if (Factor >= 1) {
3483       ConstantAsMetadata *FactorConst = ConstantAsMetadata::get(
3484           ConstantInt::get(Type::getInt32Ty(Ctx), APInt(32, Factor)));
3485       LoopMetadata.push_back(MDNode::get(
3486           Ctx, {MDString::get(Ctx, "llvm.loop.unroll.count"), FactorConst}));
3487     }
3488 
3489     addLoopMetadata(Loop, LoopMetadata);
3490     return;
3491   }
3492 
3493   // Heuristically determine the unroll factor.
3494   if (Factor == 0)
3495     Factor = computeHeuristicUnrollFactor(Loop);
3496 
3497   // No change required with unroll factor 1.
3498   if (Factor == 1) {
3499     *UnrolledCLI = Loop;
3500     return;
3501   }
3502 
3503   assert(Factor >= 2 &&
3504          "unrolling only makes sense with a factor of 2 or larger");
3505 
3506   Type *IndVarTy = Loop->getIndVarType();
3507 
3508   // Apply partial unrolling by tiling the loop by the unroll-factor, then fully
3509   // unroll the inner loop.
3510   Value *FactorVal =
3511       ConstantInt::get(IndVarTy, APInt(IndVarTy->getIntegerBitWidth(), Factor,
3512                                        /*isSigned=*/false));
3513   std::vector<CanonicalLoopInfo *> LoopNest =
3514       tileLoops(DL, {Loop}, {FactorVal});
3515   assert(LoopNest.size() == 2 && "Expect 2 loops after tiling");
3516   *UnrolledCLI = LoopNest[0];
3517   CanonicalLoopInfo *InnerLoop = LoopNest[1];
3518 
3519   // LoopUnrollPass can only fully unroll loops with constant trip count.
3520   // Unroll by the unroll factor with a fallback epilog for the remainder
3521   // iterations if necessary.
3522   ConstantAsMetadata *FactorConst = ConstantAsMetadata::get(
3523       ConstantInt::get(Type::getInt32Ty(Ctx), APInt(32, Factor)));
3524   addLoopMetadata(
3525       InnerLoop,
3526       {MDNode::get(Ctx, MDString::get(Ctx, "llvm.loop.unroll.enable")),
3527        MDNode::get(
3528            Ctx, {MDString::get(Ctx, "llvm.loop.unroll.count"), FactorConst})});
3529 
3530 #ifndef NDEBUG
3531   (*UnrolledCLI)->assertOK();
3532 #endif
3533 }
3534 
3535 OpenMPIRBuilder::InsertPointTy
3536 OpenMPIRBuilder::createCopyPrivate(const LocationDescription &Loc,
3537                                    llvm::Value *BufSize, llvm::Value *CpyBuf,
3538                                    llvm::Value *CpyFn, llvm::Value *DidIt) {
3539   if (!updateToLocation(Loc))
3540     return Loc.IP;
3541 
3542   uint32_t SrcLocStrSize;
3543   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
3544   Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
3545   Value *ThreadId = getOrCreateThreadID(Ident);
3546 
3547   llvm::Value *DidItLD = Builder.CreateLoad(Builder.getInt32Ty(), DidIt);
3548 
3549   Value *Args[] = {Ident, ThreadId, BufSize, CpyBuf, CpyFn, DidItLD};
3550 
3551   Function *Fn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_copyprivate);
3552   Builder.CreateCall(Fn, Args);
3553 
3554   return Builder.saveIP();
3555 }
3556 
3557 OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::createSingle(
3558     const LocationDescription &Loc, BodyGenCallbackTy BodyGenCB,
3559     FinalizeCallbackTy FiniCB, bool IsNowait, llvm::Value *DidIt) {
3560 
3561   if (!updateToLocation(Loc))
3562     return Loc.IP;
3563 
3564   // If needed (i.e. not null), initialize `DidIt` with 0
3565   if (DidIt) {
3566     Builder.CreateStore(Builder.getInt32(0), DidIt);
3567   }
3568 
3569   Directive OMPD = Directive::OMPD_single;
3570   uint32_t SrcLocStrSize;
3571   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
3572   Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
3573   Value *ThreadId = getOrCreateThreadID(Ident);
3574   Value *Args[] = {Ident, ThreadId};
3575 
3576   Function *EntryRTLFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_single);
3577   Instruction *EntryCall = Builder.CreateCall(EntryRTLFn, Args);
3578 
3579   Function *ExitRTLFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_end_single);
3580   Instruction *ExitCall = Builder.CreateCall(ExitRTLFn, Args);
3581 
3582   // generates the following:
3583   // if (__kmpc_single()) {
3584   //		.... single region ...
3585   // 		__kmpc_end_single
3586   // }
3587   // __kmpc_barrier
3588 
3589   EmitOMPInlinedRegion(OMPD, EntryCall, ExitCall, BodyGenCB, FiniCB,
3590                        /*Conditional*/ true,
3591                        /*hasFinalize*/ true);
3592   if (!IsNowait)
3593     createBarrier(LocationDescription(Builder.saveIP(), Loc.DL),
3594                   omp::Directive::OMPD_unknown, /* ForceSimpleCall */ false,
3595                   /* CheckCancelFlag */ false);
3596   return Builder.saveIP();
3597 }
3598 
3599 OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::createCritical(
3600     const LocationDescription &Loc, BodyGenCallbackTy BodyGenCB,
3601     FinalizeCallbackTy FiniCB, StringRef CriticalName, Value *HintInst) {
3602 
3603   if (!updateToLocation(Loc))
3604     return Loc.IP;
3605 
3606   Directive OMPD = Directive::OMPD_critical;
3607   uint32_t SrcLocStrSize;
3608   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
3609   Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
3610   Value *ThreadId = getOrCreateThreadID(Ident);
3611   Value *LockVar = getOMPCriticalRegionLock(CriticalName);
3612   Value *Args[] = {Ident, ThreadId, LockVar};
3613 
3614   SmallVector<llvm::Value *, 4> EnterArgs(std::begin(Args), std::end(Args));
3615   Function *RTFn = nullptr;
3616   if (HintInst) {
3617     // Add Hint to entry Args and create call
3618     EnterArgs.push_back(HintInst);
3619     RTFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_critical_with_hint);
3620   } else {
3621     RTFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_critical);
3622   }
3623   Instruction *EntryCall = Builder.CreateCall(RTFn, EnterArgs);
3624 
3625   Function *ExitRTLFn =
3626       getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_end_critical);
3627   Instruction *ExitCall = Builder.CreateCall(ExitRTLFn, Args);
3628 
3629   return EmitOMPInlinedRegion(OMPD, EntryCall, ExitCall, BodyGenCB, FiniCB,
3630                               /*Conditional*/ false, /*hasFinalize*/ true);
3631 }
3632 
3633 OpenMPIRBuilder::InsertPointTy
3634 OpenMPIRBuilder::createOrderedDepend(const LocationDescription &Loc,
3635                                      InsertPointTy AllocaIP, unsigned NumLoops,
3636                                      ArrayRef<llvm::Value *> StoreValues,
3637                                      const Twine &Name, bool IsDependSource) {
3638   assert(
3639       llvm::all_of(StoreValues,
3640                    [](Value *SV) { return SV->getType()->isIntegerTy(64); }) &&
3641       "OpenMP runtime requires depend vec with i64 type");
3642 
3643   if (!updateToLocation(Loc))
3644     return Loc.IP;
3645 
3646   // Allocate space for vector and generate alloc instruction.
3647   auto *ArrI64Ty = ArrayType::get(Int64, NumLoops);
3648   Builder.restoreIP(AllocaIP);
3649   AllocaInst *ArgsBase = Builder.CreateAlloca(ArrI64Ty, nullptr, Name);
3650   ArgsBase->setAlignment(Align(8));
3651   Builder.restoreIP(Loc.IP);
3652 
3653   // Store the index value with offset in depend vector.
3654   for (unsigned I = 0; I < NumLoops; ++I) {
3655     Value *DependAddrGEPIter = Builder.CreateInBoundsGEP(
3656         ArrI64Ty, ArgsBase, {Builder.getInt64(0), Builder.getInt64(I)});
3657     StoreInst *STInst = Builder.CreateStore(StoreValues[I], DependAddrGEPIter);
3658     STInst->setAlignment(Align(8));
3659   }
3660 
3661   Value *DependBaseAddrGEP = Builder.CreateInBoundsGEP(
3662       ArrI64Ty, ArgsBase, {Builder.getInt64(0), Builder.getInt64(0)});
3663 
3664   uint32_t SrcLocStrSize;
3665   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
3666   Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
3667   Value *ThreadId = getOrCreateThreadID(Ident);
3668   Value *Args[] = {Ident, ThreadId, DependBaseAddrGEP};
3669 
3670   Function *RTLFn = nullptr;
3671   if (IsDependSource)
3672     RTLFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_doacross_post);
3673   else
3674     RTLFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_doacross_wait);
3675   Builder.CreateCall(RTLFn, Args);
3676 
3677   return Builder.saveIP();
3678 }
3679 
3680 OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::createOrderedThreadsSimd(
3681     const LocationDescription &Loc, BodyGenCallbackTy BodyGenCB,
3682     FinalizeCallbackTy FiniCB, bool IsThreads) {
3683   if (!updateToLocation(Loc))
3684     return Loc.IP;
3685 
3686   Directive OMPD = Directive::OMPD_ordered;
3687   Instruction *EntryCall = nullptr;
3688   Instruction *ExitCall = nullptr;
3689 
3690   if (IsThreads) {
3691     uint32_t SrcLocStrSize;
3692     Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
3693     Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
3694     Value *ThreadId = getOrCreateThreadID(Ident);
3695     Value *Args[] = {Ident, ThreadId};
3696 
3697     Function *EntryRTLFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_ordered);
3698     EntryCall = Builder.CreateCall(EntryRTLFn, Args);
3699 
3700     Function *ExitRTLFn =
3701         getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_end_ordered);
3702     ExitCall = Builder.CreateCall(ExitRTLFn, Args);
3703   }
3704 
3705   return EmitOMPInlinedRegion(OMPD, EntryCall, ExitCall, BodyGenCB, FiniCB,
3706                               /*Conditional*/ false, /*hasFinalize*/ true);
3707 }
3708 
3709 OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::EmitOMPInlinedRegion(
3710     Directive OMPD, Instruction *EntryCall, Instruction *ExitCall,
3711     BodyGenCallbackTy BodyGenCB, FinalizeCallbackTy FiniCB, bool Conditional,
3712     bool HasFinalize, bool IsCancellable) {
3713 
3714   if (HasFinalize)
3715     FinalizationStack.push_back({FiniCB, OMPD, IsCancellable});
3716 
3717   // Create inlined region's entry and body blocks, in preparation
3718   // for conditional creation
3719   BasicBlock *EntryBB = Builder.GetInsertBlock();
3720   Instruction *SplitPos = EntryBB->getTerminator();
3721   if (!isa_and_nonnull<BranchInst>(SplitPos))
3722     SplitPos = new UnreachableInst(Builder.getContext(), EntryBB);
3723   BasicBlock *ExitBB = EntryBB->splitBasicBlock(SplitPos, "omp_region.end");
3724   BasicBlock *FiniBB =
3725       EntryBB->splitBasicBlock(EntryBB->getTerminator(), "omp_region.finalize");
3726 
3727   Builder.SetInsertPoint(EntryBB->getTerminator());
3728   emitCommonDirectiveEntry(OMPD, EntryCall, ExitBB, Conditional);
3729 
3730   // generate body
3731   BodyGenCB(/* AllocaIP */ InsertPointTy(),
3732             /* CodeGenIP */ Builder.saveIP());
3733 
3734   // emit exit call and do any needed finalization.
3735   auto FinIP = InsertPointTy(FiniBB, FiniBB->getFirstInsertionPt());
3736   assert(FiniBB->getTerminator()->getNumSuccessors() == 1 &&
3737          FiniBB->getTerminator()->getSuccessor(0) == ExitBB &&
3738          "Unexpected control flow graph state!!");
3739   emitCommonDirectiveExit(OMPD, FinIP, ExitCall, HasFinalize);
3740   assert(FiniBB->getUniquePredecessor()->getUniqueSuccessor() == FiniBB &&
3741          "Unexpected Control Flow State!");
3742   MergeBlockIntoPredecessor(FiniBB);
3743 
3744   // If we are skipping the region of a non conditional, remove the exit
3745   // block, and clear the builder's insertion point.
3746   assert(SplitPos->getParent() == ExitBB &&
3747          "Unexpected Insertion point location!");
3748   auto merged = MergeBlockIntoPredecessor(ExitBB);
3749   BasicBlock *ExitPredBB = SplitPos->getParent();
3750   auto InsertBB = merged ? ExitPredBB : ExitBB;
3751   if (!isa_and_nonnull<BranchInst>(SplitPos))
3752     SplitPos->eraseFromParent();
3753   Builder.SetInsertPoint(InsertBB);
3754 
3755   return Builder.saveIP();
3756 }
3757 
3758 OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::emitCommonDirectiveEntry(
3759     Directive OMPD, Value *EntryCall, BasicBlock *ExitBB, bool Conditional) {
3760   // if nothing to do, Return current insertion point.
3761   if (!Conditional || !EntryCall)
3762     return Builder.saveIP();
3763 
3764   BasicBlock *EntryBB = Builder.GetInsertBlock();
3765   Value *CallBool = Builder.CreateIsNotNull(EntryCall);
3766   auto *ThenBB = BasicBlock::Create(M.getContext(), "omp_region.body");
3767   auto *UI = new UnreachableInst(Builder.getContext(), ThenBB);
3768 
3769   // Emit thenBB and set the Builder's insertion point there for
3770   // body generation next. Place the block after the current block.
3771   Function *CurFn = EntryBB->getParent();
3772   CurFn->insert(std::next(EntryBB->getIterator()), ThenBB);
3773 
3774   // Move Entry branch to end of ThenBB, and replace with conditional
3775   // branch (If-stmt)
3776   Instruction *EntryBBTI = EntryBB->getTerminator();
3777   Builder.CreateCondBr(CallBool, ThenBB, ExitBB);
3778   EntryBBTI->removeFromParent();
3779   Builder.SetInsertPoint(UI);
3780   Builder.Insert(EntryBBTI);
3781   UI->eraseFromParent();
3782   Builder.SetInsertPoint(ThenBB->getTerminator());
3783 
3784   // return an insertion point to ExitBB.
3785   return IRBuilder<>::InsertPoint(ExitBB, ExitBB->getFirstInsertionPt());
3786 }
3787 
3788 OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::emitCommonDirectiveExit(
3789     omp::Directive OMPD, InsertPointTy FinIP, Instruction *ExitCall,
3790     bool HasFinalize) {
3791 
3792   Builder.restoreIP(FinIP);
3793 
3794   // If there is finalization to do, emit it before the exit call
3795   if (HasFinalize) {
3796     assert(!FinalizationStack.empty() &&
3797            "Unexpected finalization stack state!");
3798 
3799     FinalizationInfo Fi = FinalizationStack.pop_back_val();
3800     assert(Fi.DK == OMPD && "Unexpected Directive for Finalization call!");
3801 
3802     Fi.FiniCB(FinIP);
3803 
3804     BasicBlock *FiniBB = FinIP.getBlock();
3805     Instruction *FiniBBTI = FiniBB->getTerminator();
3806 
3807     // set Builder IP for call creation
3808     Builder.SetInsertPoint(FiniBBTI);
3809   }
3810 
3811   if (!ExitCall)
3812     return Builder.saveIP();
3813 
3814   // place the Exitcall as last instruction before Finalization block terminator
3815   ExitCall->removeFromParent();
3816   Builder.Insert(ExitCall);
3817 
3818   return IRBuilder<>::InsertPoint(ExitCall->getParent(),
3819                                   ExitCall->getIterator());
3820 }
3821 
3822 OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::createCopyinClauseBlocks(
3823     InsertPointTy IP, Value *MasterAddr, Value *PrivateAddr,
3824     llvm::IntegerType *IntPtrTy, bool BranchtoEnd) {
3825   if (!IP.isSet())
3826     return IP;
3827 
3828   IRBuilder<>::InsertPointGuard IPG(Builder);
3829 
3830   // creates the following CFG structure
3831   //	   OMP_Entry : (MasterAddr != PrivateAddr)?
3832   //       F     T
3833   //       |      \
3834   //       |     copin.not.master
3835   //       |      /
3836   //       v     /
3837   //   copyin.not.master.end
3838   //		     |
3839   //         v
3840   //   OMP.Entry.Next
3841 
3842   BasicBlock *OMP_Entry = IP.getBlock();
3843   Function *CurFn = OMP_Entry->getParent();
3844   BasicBlock *CopyBegin =
3845       BasicBlock::Create(M.getContext(), "copyin.not.master", CurFn);
3846   BasicBlock *CopyEnd = nullptr;
3847 
3848   // If entry block is terminated, split to preserve the branch to following
3849   // basic block (i.e. OMP.Entry.Next), otherwise, leave everything as is.
3850   if (isa_and_nonnull<BranchInst>(OMP_Entry->getTerminator())) {
3851     CopyEnd = OMP_Entry->splitBasicBlock(OMP_Entry->getTerminator(),
3852                                          "copyin.not.master.end");
3853     OMP_Entry->getTerminator()->eraseFromParent();
3854   } else {
3855     CopyEnd =
3856         BasicBlock::Create(M.getContext(), "copyin.not.master.end", CurFn);
3857   }
3858 
3859   Builder.SetInsertPoint(OMP_Entry);
3860   Value *MasterPtr = Builder.CreatePtrToInt(MasterAddr, IntPtrTy);
3861   Value *PrivatePtr = Builder.CreatePtrToInt(PrivateAddr, IntPtrTy);
3862   Value *cmp = Builder.CreateICmpNE(MasterPtr, PrivatePtr);
3863   Builder.CreateCondBr(cmp, CopyBegin, CopyEnd);
3864 
3865   Builder.SetInsertPoint(CopyBegin);
3866   if (BranchtoEnd)
3867     Builder.SetInsertPoint(Builder.CreateBr(CopyEnd));
3868 
3869   return Builder.saveIP();
3870 }
3871 
3872 CallInst *OpenMPIRBuilder::createOMPAlloc(const LocationDescription &Loc,
3873                                           Value *Size, Value *Allocator,
3874                                           std::string Name) {
3875   IRBuilder<>::InsertPointGuard IPG(Builder);
3876   Builder.restoreIP(Loc.IP);
3877 
3878   uint32_t SrcLocStrSize;
3879   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
3880   Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
3881   Value *ThreadId = getOrCreateThreadID(Ident);
3882   Value *Args[] = {ThreadId, Size, Allocator};
3883 
3884   Function *Fn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_alloc);
3885 
3886   return Builder.CreateCall(Fn, Args, Name);
3887 }
3888 
3889 CallInst *OpenMPIRBuilder::createOMPFree(const LocationDescription &Loc,
3890                                          Value *Addr, Value *Allocator,
3891                                          std::string Name) {
3892   IRBuilder<>::InsertPointGuard IPG(Builder);
3893   Builder.restoreIP(Loc.IP);
3894 
3895   uint32_t SrcLocStrSize;
3896   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
3897   Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
3898   Value *ThreadId = getOrCreateThreadID(Ident);
3899   Value *Args[] = {ThreadId, Addr, Allocator};
3900   Function *Fn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_free);
3901   return Builder.CreateCall(Fn, Args, Name);
3902 }
3903 
3904 CallInst *OpenMPIRBuilder::createOMPInteropInit(
3905     const LocationDescription &Loc, Value *InteropVar,
3906     omp::OMPInteropType InteropType, Value *Device, Value *NumDependences,
3907     Value *DependenceAddress, bool HaveNowaitClause) {
3908   IRBuilder<>::InsertPointGuard IPG(Builder);
3909   Builder.restoreIP(Loc.IP);
3910 
3911   uint32_t SrcLocStrSize;
3912   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
3913   Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
3914   Value *ThreadId = getOrCreateThreadID(Ident);
3915   if (Device == nullptr)
3916     Device = ConstantInt::get(Int32, -1);
3917   Constant *InteropTypeVal = ConstantInt::get(Int32, (int)InteropType);
3918   if (NumDependences == nullptr) {
3919     NumDependences = ConstantInt::get(Int32, 0);
3920     PointerType *PointerTypeVar = Type::getInt8PtrTy(M.getContext());
3921     DependenceAddress = ConstantPointerNull::get(PointerTypeVar);
3922   }
3923   Value *HaveNowaitClauseVal = ConstantInt::get(Int32, HaveNowaitClause);
3924   Value *Args[] = {
3925       Ident,  ThreadId,       InteropVar,        InteropTypeVal,
3926       Device, NumDependences, DependenceAddress, HaveNowaitClauseVal};
3927 
3928   Function *Fn = getOrCreateRuntimeFunctionPtr(OMPRTL___tgt_interop_init);
3929 
3930   return Builder.CreateCall(Fn, Args);
3931 }
3932 
3933 CallInst *OpenMPIRBuilder::createOMPInteropDestroy(
3934     const LocationDescription &Loc, Value *InteropVar, Value *Device,
3935     Value *NumDependences, Value *DependenceAddress, bool HaveNowaitClause) {
3936   IRBuilder<>::InsertPointGuard IPG(Builder);
3937   Builder.restoreIP(Loc.IP);
3938 
3939   uint32_t SrcLocStrSize;
3940   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
3941   Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
3942   Value *ThreadId = getOrCreateThreadID(Ident);
3943   if (Device == nullptr)
3944     Device = ConstantInt::get(Int32, -1);
3945   if (NumDependences == nullptr) {
3946     NumDependences = ConstantInt::get(Int32, 0);
3947     PointerType *PointerTypeVar = Type::getInt8PtrTy(M.getContext());
3948     DependenceAddress = ConstantPointerNull::get(PointerTypeVar);
3949   }
3950   Value *HaveNowaitClauseVal = ConstantInt::get(Int32, HaveNowaitClause);
3951   Value *Args[] = {
3952       Ident,          ThreadId,          InteropVar,         Device,
3953       NumDependences, DependenceAddress, HaveNowaitClauseVal};
3954 
3955   Function *Fn = getOrCreateRuntimeFunctionPtr(OMPRTL___tgt_interop_destroy);
3956 
3957   return Builder.CreateCall(Fn, Args);
3958 }
3959 
3960 CallInst *OpenMPIRBuilder::createOMPInteropUse(const LocationDescription &Loc,
3961                                                Value *InteropVar, Value *Device,
3962                                                Value *NumDependences,
3963                                                Value *DependenceAddress,
3964                                                bool HaveNowaitClause) {
3965   IRBuilder<>::InsertPointGuard IPG(Builder);
3966   Builder.restoreIP(Loc.IP);
3967   uint32_t SrcLocStrSize;
3968   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
3969   Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
3970   Value *ThreadId = getOrCreateThreadID(Ident);
3971   if (Device == nullptr)
3972     Device = ConstantInt::get(Int32, -1);
3973   if (NumDependences == nullptr) {
3974     NumDependences = ConstantInt::get(Int32, 0);
3975     PointerType *PointerTypeVar = Type::getInt8PtrTy(M.getContext());
3976     DependenceAddress = ConstantPointerNull::get(PointerTypeVar);
3977   }
3978   Value *HaveNowaitClauseVal = ConstantInt::get(Int32, HaveNowaitClause);
3979   Value *Args[] = {
3980       Ident,          ThreadId,          InteropVar,         Device,
3981       NumDependences, DependenceAddress, HaveNowaitClauseVal};
3982 
3983   Function *Fn = getOrCreateRuntimeFunctionPtr(OMPRTL___tgt_interop_use);
3984 
3985   return Builder.CreateCall(Fn, Args);
3986 }
3987 
3988 CallInst *OpenMPIRBuilder::createCachedThreadPrivate(
3989     const LocationDescription &Loc, llvm::Value *Pointer,
3990     llvm::ConstantInt *Size, const llvm::Twine &Name) {
3991   IRBuilder<>::InsertPointGuard IPG(Builder);
3992   Builder.restoreIP(Loc.IP);
3993 
3994   uint32_t SrcLocStrSize;
3995   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
3996   Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
3997   Value *ThreadId = getOrCreateThreadID(Ident);
3998   Constant *ThreadPrivateCache =
3999       getOrCreateInternalVariable(Int8PtrPtr, Name.str());
4000   llvm::Value *Args[] = {Ident, ThreadId, Pointer, Size, ThreadPrivateCache};
4001 
4002   Function *Fn =
4003       getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_threadprivate_cached);
4004 
4005   return Builder.CreateCall(Fn, Args);
4006 }
4007 
4008 OpenMPIRBuilder::InsertPointTy
4009 OpenMPIRBuilder::createTargetInit(const LocationDescription &Loc, bool IsSPMD) {
4010   if (!updateToLocation(Loc))
4011     return Loc.IP;
4012 
4013   uint32_t SrcLocStrSize;
4014   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
4015   Constant *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
4016   ConstantInt *IsSPMDVal = ConstantInt::getSigned(
4017       IntegerType::getInt8Ty(Int8->getContext()),
4018       IsSPMD ? OMP_TGT_EXEC_MODE_SPMD : OMP_TGT_EXEC_MODE_GENERIC);
4019   ConstantInt *UseGenericStateMachine =
4020       ConstantInt::getBool(Int32->getContext(), !IsSPMD);
4021 
4022   Function *Fn = getOrCreateRuntimeFunctionPtr(
4023       omp::RuntimeFunction::OMPRTL___kmpc_target_init);
4024 
4025   CallInst *ThreadKind = Builder.CreateCall(
4026       Fn, {Ident, IsSPMDVal, UseGenericStateMachine});
4027 
4028   Value *ExecUserCode = Builder.CreateICmpEQ(
4029       ThreadKind, ConstantInt::get(ThreadKind->getType(), -1),
4030       "exec_user_code");
4031 
4032   // ThreadKind = __kmpc_target_init(...)
4033   // if (ThreadKind == -1)
4034   //   user_code
4035   // else
4036   //   return;
4037 
4038   auto *UI = Builder.CreateUnreachable();
4039   BasicBlock *CheckBB = UI->getParent();
4040   BasicBlock *UserCodeEntryBB = CheckBB->splitBasicBlock(UI, "user_code.entry");
4041 
4042   BasicBlock *WorkerExitBB = BasicBlock::Create(
4043       CheckBB->getContext(), "worker.exit", CheckBB->getParent());
4044   Builder.SetInsertPoint(WorkerExitBB);
4045   Builder.CreateRetVoid();
4046 
4047   auto *CheckBBTI = CheckBB->getTerminator();
4048   Builder.SetInsertPoint(CheckBBTI);
4049   Builder.CreateCondBr(ExecUserCode, UI->getParent(), WorkerExitBB);
4050 
4051   CheckBBTI->eraseFromParent();
4052   UI->eraseFromParent();
4053 
4054   // Continue in the "user_code" block, see diagram above and in
4055   // openmp/libomptarget/deviceRTLs/common/include/target.h .
4056   return InsertPointTy(UserCodeEntryBB, UserCodeEntryBB->getFirstInsertionPt());
4057 }
4058 
4059 void OpenMPIRBuilder::createTargetDeinit(const LocationDescription &Loc,
4060                                          bool IsSPMD) {
4061   if (!updateToLocation(Loc))
4062     return;
4063 
4064   uint32_t SrcLocStrSize;
4065   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
4066   Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
4067   ConstantInt *IsSPMDVal = ConstantInt::getSigned(
4068       IntegerType::getInt8Ty(Int8->getContext()),
4069       IsSPMD ? OMP_TGT_EXEC_MODE_SPMD : OMP_TGT_EXEC_MODE_GENERIC);
4070 
4071   Function *Fn = getOrCreateRuntimeFunctionPtr(
4072       omp::RuntimeFunction::OMPRTL___kmpc_target_deinit);
4073 
4074   Builder.CreateCall(Fn, {Ident, IsSPMDVal});
4075 }
4076 
4077 void OpenMPIRBuilder::setOutlinedTargetRegionFunctionAttributes(
4078     Function *OutlinedFn, int32_t NumTeams, int32_t NumThreads) {
4079   if (Config.isTargetDevice()) {
4080     OutlinedFn->setLinkage(GlobalValue::WeakODRLinkage);
4081     // TODO: Determine if DSO local can be set to true.
4082     OutlinedFn->setDSOLocal(false);
4083     OutlinedFn->setVisibility(GlobalValue::ProtectedVisibility);
4084     if (Triple(M.getTargetTriple()).isAMDGCN())
4085       OutlinedFn->setCallingConv(CallingConv::AMDGPU_KERNEL);
4086   }
4087 
4088   if (NumTeams > 0)
4089     OutlinedFn->addFnAttr("omp_target_num_teams", std::to_string(NumTeams));
4090   if (NumThreads > 0)
4091     OutlinedFn->addFnAttr("omp_target_thread_limit",
4092                           std::to_string(NumThreads));
4093 }
4094 
4095 Constant *OpenMPIRBuilder::createOutlinedFunctionID(Function *OutlinedFn,
4096                                                     StringRef EntryFnIDName) {
4097   if (Config.isTargetDevice()) {
4098     assert(OutlinedFn && "The outlined function must exist if embedded");
4099     return ConstantExpr::getBitCast(OutlinedFn, Builder.getInt8PtrTy());
4100   }
4101 
4102   return new GlobalVariable(
4103       M, Builder.getInt8Ty(), /*isConstant=*/true, GlobalValue::WeakAnyLinkage,
4104       Constant::getNullValue(Builder.getInt8Ty()), EntryFnIDName);
4105 }
4106 
4107 Constant *OpenMPIRBuilder::createTargetRegionEntryAddr(Function *OutlinedFn,
4108                                                        StringRef EntryFnName) {
4109   if (OutlinedFn)
4110     return OutlinedFn;
4111 
4112   assert(!M.getGlobalVariable(EntryFnName, true) &&
4113          "Named kernel already exists?");
4114   return new GlobalVariable(
4115       M, Builder.getInt8Ty(), /*isConstant=*/true, GlobalValue::InternalLinkage,
4116       Constant::getNullValue(Builder.getInt8Ty()), EntryFnName);
4117 }
4118 
4119 void OpenMPIRBuilder::emitTargetRegionFunction(
4120     TargetRegionEntryInfo &EntryInfo,
4121     FunctionGenCallback &GenerateFunctionCallback, int32_t NumTeams,
4122     int32_t NumThreads, bool IsOffloadEntry, Function *&OutlinedFn,
4123     Constant *&OutlinedFnID) {
4124 
4125   SmallString<64> EntryFnName;
4126   OffloadInfoManager.getTargetRegionEntryFnName(EntryFnName, EntryInfo);
4127 
4128   OutlinedFn = Config.isTargetDevice() || !Config.openMPOffloadMandatory()
4129                    ? GenerateFunctionCallback(EntryFnName)
4130                    : nullptr;
4131 
4132   // If this target outline function is not an offload entry, we don't need to
4133   // register it. This may be in the case of a false if clause, or if there are
4134   // no OpenMP targets.
4135   if (!IsOffloadEntry)
4136     return;
4137 
4138   std::string EntryFnIDName =
4139       Config.isTargetDevice()
4140           ? std::string(EntryFnName)
4141           : createPlatformSpecificName({EntryFnName, "region_id"});
4142 
4143   OutlinedFnID = registerTargetRegionFunction(
4144       EntryInfo, OutlinedFn, EntryFnName, EntryFnIDName, NumTeams, NumThreads);
4145 }
4146 
4147 Constant *OpenMPIRBuilder::registerTargetRegionFunction(
4148     TargetRegionEntryInfo &EntryInfo, Function *OutlinedFn,
4149     StringRef EntryFnName, StringRef EntryFnIDName, int32_t NumTeams,
4150     int32_t NumThreads) {
4151   if (OutlinedFn)
4152     setOutlinedTargetRegionFunctionAttributes(OutlinedFn, NumTeams, NumThreads);
4153   auto OutlinedFnID = createOutlinedFunctionID(OutlinedFn, EntryFnIDName);
4154   auto EntryAddr = createTargetRegionEntryAddr(OutlinedFn, EntryFnName);
4155   OffloadInfoManager.registerTargetRegionEntryInfo(
4156       EntryInfo, EntryAddr, OutlinedFnID,
4157       OffloadEntriesInfoManager::OMPTargetRegionEntryTargetRegion);
4158   return OutlinedFnID;
4159 }
4160 
4161 OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::createTargetData(
4162     const LocationDescription &Loc, InsertPointTy AllocaIP,
4163     InsertPointTy CodeGenIP, Value *DeviceID, Value *IfCond,
4164     TargetDataInfo &Info,
4165     function_ref<MapInfosTy &(InsertPointTy CodeGenIP)> GenMapInfoCB,
4166     omp::RuntimeFunction *MapperFunc,
4167     function_ref<InsertPointTy(InsertPointTy CodeGenIP, BodyGenTy BodyGenType)>
4168         BodyGenCB,
4169     function_ref<void(unsigned int, Value *)> DeviceAddrCB,
4170     function_ref<Value *(unsigned int)> CustomMapperCB, Value *SrcLocInfo) {
4171   if (!updateToLocation(Loc))
4172     return InsertPointTy();
4173 
4174   Builder.restoreIP(CodeGenIP);
4175   bool IsStandAlone = !BodyGenCB;
4176   MapInfosTy *MapInfo;
4177   // Generate the code for the opening of the data environment. Capture all the
4178   // arguments of the runtime call by reference because they are used in the
4179   // closing of the region.
4180   auto BeginThenGen = [&](InsertPointTy AllocaIP, InsertPointTy CodeGenIP) {
4181     MapInfo = &GenMapInfoCB(Builder.saveIP());
4182     emitOffloadingArrays(AllocaIP, Builder.saveIP(), *MapInfo, Info,
4183                          /*IsNonContiguous=*/true, DeviceAddrCB,
4184                          CustomMapperCB);
4185 
4186     TargetDataRTArgs RTArgs;
4187     emitOffloadingArraysArgument(Builder, RTArgs, Info,
4188                                  !MapInfo->Names.empty());
4189 
4190     // Emit the number of elements in the offloading arrays.
4191     Value *PointerNum = Builder.getInt32(Info.NumberOfPtrs);
4192 
4193     // Source location for the ident struct
4194     if (!SrcLocInfo) {
4195       uint32_t SrcLocStrSize;
4196       Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
4197       SrcLocInfo = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
4198     }
4199 
4200     Value *OffloadingArgs[] = {SrcLocInfo,           DeviceID,
4201                                PointerNum,           RTArgs.BasePointersArray,
4202                                RTArgs.PointersArray, RTArgs.SizesArray,
4203                                RTArgs.MapTypesArray, RTArgs.MapNamesArray,
4204                                RTArgs.MappersArray};
4205 
4206     if (IsStandAlone) {
4207       assert(MapperFunc && "MapperFunc missing for standalone target data");
4208       Builder.CreateCall(getOrCreateRuntimeFunctionPtr(*MapperFunc),
4209                          OffloadingArgs);
4210     } else {
4211       Function *BeginMapperFunc = getOrCreateRuntimeFunctionPtr(
4212           omp::OMPRTL___tgt_target_data_begin_mapper);
4213 
4214       Builder.CreateCall(BeginMapperFunc, OffloadingArgs);
4215 
4216       for (auto DeviceMap : Info.DevicePtrInfoMap) {
4217         if (isa<AllocaInst>(DeviceMap.second.second)) {
4218           auto *LI =
4219               Builder.CreateLoad(Builder.getPtrTy(), DeviceMap.second.first);
4220           Builder.CreateStore(LI, DeviceMap.second.second);
4221         }
4222       }
4223 
4224       // If device pointer privatization is required, emit the body of the
4225       // region here. It will have to be duplicated: with and without
4226       // privatization.
4227       Builder.restoreIP(BodyGenCB(Builder.saveIP(), BodyGenTy::Priv));
4228     }
4229   };
4230 
4231   // If we need device pointer privatization, we need to emit the body of the
4232   // region with no privatization in the 'else' branch of the conditional.
4233   // Otherwise, we don't have to do anything.
4234   auto BeginElseGen = [&](InsertPointTy AllocaIP, InsertPointTy CodeGenIP) {
4235     Builder.restoreIP(BodyGenCB(Builder.saveIP(), BodyGenTy::DupNoPriv));
4236   };
4237 
4238   // Generate code for the closing of the data region.
4239   auto EndThenGen = [&](InsertPointTy AllocaIP, InsertPointTy CodeGenIP) {
4240     TargetDataRTArgs RTArgs;
4241     emitOffloadingArraysArgument(Builder, RTArgs, Info, !MapInfo->Names.empty(),
4242                                  /*ForEndCall=*/true);
4243 
4244     // Emit the number of elements in the offloading arrays.
4245     Value *PointerNum = Builder.getInt32(Info.NumberOfPtrs);
4246 
4247     // Source location for the ident struct
4248     if (!SrcLocInfo) {
4249       uint32_t SrcLocStrSize;
4250       Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
4251       SrcLocInfo = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
4252     }
4253 
4254     Value *OffloadingArgs[] = {SrcLocInfo,           DeviceID,
4255                                PointerNum,           RTArgs.BasePointersArray,
4256                                RTArgs.PointersArray, RTArgs.SizesArray,
4257                                RTArgs.MapTypesArray, RTArgs.MapNamesArray,
4258                                RTArgs.MappersArray};
4259     Function *EndMapperFunc =
4260         getOrCreateRuntimeFunctionPtr(omp::OMPRTL___tgt_target_data_end_mapper);
4261 
4262     Builder.CreateCall(EndMapperFunc, OffloadingArgs);
4263   };
4264 
4265   // We don't have to do anything to close the region if the if clause evaluates
4266   // to false.
4267   auto EndElseGen = [&](InsertPointTy AllocaIP, InsertPointTy CodeGenIP) {};
4268 
4269   if (BodyGenCB) {
4270     if (IfCond) {
4271       emitIfClause(IfCond, BeginThenGen, BeginElseGen, AllocaIP);
4272     } else {
4273       BeginThenGen(AllocaIP, Builder.saveIP());
4274     }
4275 
4276     // If we don't require privatization of device pointers, we emit the body in
4277     // between the runtime calls. This avoids duplicating the body code.
4278     Builder.restoreIP(BodyGenCB(Builder.saveIP(), BodyGenTy::NoPriv));
4279 
4280     if (IfCond) {
4281       emitIfClause(IfCond, EndThenGen, EndElseGen, AllocaIP);
4282     } else {
4283       EndThenGen(AllocaIP, Builder.saveIP());
4284     }
4285   } else {
4286     if (IfCond) {
4287       emitIfClause(IfCond, BeginThenGen, EndElseGen, AllocaIP);
4288     } else {
4289       BeginThenGen(AllocaIP, Builder.saveIP());
4290     }
4291   }
4292 
4293   return Builder.saveIP();
4294 }
4295 
4296 static Function *
4297 createOutlinedFunction(OpenMPIRBuilder &OMPBuilder, IRBuilderBase &Builder,
4298                        StringRef FuncName, SmallVectorImpl<Value *> &Inputs,
4299                        OpenMPIRBuilder::TargetBodyGenCallbackTy &CBFunc) {
4300   SmallVector<Type *> ParameterTypes;
4301   for (auto &Arg : Inputs)
4302     ParameterTypes.push_back(Arg->getType());
4303 
4304   auto FuncType = FunctionType::get(Builder.getVoidTy(), ParameterTypes,
4305                                     /*isVarArg*/ false);
4306   auto Func = Function::Create(FuncType, GlobalValue::InternalLinkage, FuncName,
4307                                Builder.GetInsertBlock()->getModule());
4308 
4309   // Save insert point.
4310   auto OldInsertPoint = Builder.saveIP();
4311 
4312   // Generate the region into the function.
4313   BasicBlock *EntryBB = BasicBlock::Create(Builder.getContext(), "entry", Func);
4314   Builder.SetInsertPoint(EntryBB);
4315 
4316   // Insert target init call in the device compilation pass.
4317   if (OMPBuilder.Config.isTargetDevice())
4318     Builder.restoreIP(OMPBuilder.createTargetInit(Builder, /*IsSPMD*/ false));
4319 
4320   Builder.restoreIP(CBFunc(Builder.saveIP(), Builder.saveIP()));
4321 
4322   // Insert target deinit call in the device compilation pass.
4323   if (OMPBuilder.Config.isTargetDevice())
4324     OMPBuilder.createTargetDeinit(Builder, /*IsSPMD*/ false);
4325 
4326   // Insert return instruction.
4327   Builder.CreateRetVoid();
4328 
4329   // Rewrite uses of input valus to parameters.
4330   for (auto InArg : zip(Inputs, Func->args())) {
4331     Value *Input = std::get<0>(InArg);
4332     Argument &Arg = std::get<1>(InArg);
4333 
4334     // Collect all the instructions
4335     for (User *User : make_early_inc_range(Input->users()))
4336       if (auto Instr = dyn_cast<Instruction>(User))
4337         if (Instr->getFunction() == Func)
4338           Instr->replaceUsesOfWith(Input, &Arg);
4339   }
4340 
4341   // Restore insert point.
4342   Builder.restoreIP(OldInsertPoint);
4343 
4344   return Func;
4345 }
4346 
4347 static void
4348 emitTargetOutlinedFunction(OpenMPIRBuilder &OMPBuilder, IRBuilderBase &Builder,
4349                            TargetRegionEntryInfo &EntryInfo,
4350                            Function *&OutlinedFn, int32_t NumTeams,
4351                            int32_t NumThreads, SmallVectorImpl<Value *> &Inputs,
4352                            OpenMPIRBuilder::TargetBodyGenCallbackTy &CBFunc) {
4353 
4354   OpenMPIRBuilder::FunctionGenCallback &&GenerateOutlinedFunction =
4355       [&OMPBuilder, &Builder, &Inputs, &CBFunc](StringRef EntryFnName) {
4356         return createOutlinedFunction(OMPBuilder, Builder, EntryFnName, Inputs,
4357                                       CBFunc);
4358       };
4359 
4360   Constant *OutlinedFnID;
4361   OMPBuilder.emitTargetRegionFunction(EntryInfo, GenerateOutlinedFunction,
4362                                       NumTeams, NumThreads, true, OutlinedFn,
4363                                       OutlinedFnID);
4364 }
4365 
4366 static void emitTargetCall(IRBuilderBase &Builder, Function *OutlinedFn,
4367                            SmallVectorImpl<Value *> &Args) {
4368   // TODO: Add kernel launch call
4369   Builder.CreateCall(OutlinedFn, Args);
4370 }
4371 
4372 OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::createTarget(
4373     const LocationDescription &Loc, OpenMPIRBuilder::InsertPointTy CodeGenIP,
4374     TargetRegionEntryInfo &EntryInfo, int32_t NumTeams, int32_t NumThreads,
4375     SmallVectorImpl<Value *> &Args, TargetBodyGenCallbackTy CBFunc) {
4376   if (!updateToLocation(Loc))
4377     return InsertPointTy();
4378 
4379   Builder.restoreIP(CodeGenIP);
4380 
4381   Function *OutlinedFn;
4382   emitTargetOutlinedFunction(*this, Builder, EntryInfo, OutlinedFn, NumTeams,
4383                              NumThreads, Args, CBFunc);
4384   if (!Config.isTargetDevice())
4385     emitTargetCall(Builder, OutlinedFn, Args);
4386   return Builder.saveIP();
4387 }
4388 
4389 std::string OpenMPIRBuilder::getNameWithSeparators(ArrayRef<StringRef> Parts,
4390                                                    StringRef FirstSeparator,
4391                                                    StringRef Separator) {
4392   SmallString<128> Buffer;
4393   llvm::raw_svector_ostream OS(Buffer);
4394   StringRef Sep = FirstSeparator;
4395   for (StringRef Part : Parts) {
4396     OS << Sep << Part;
4397     Sep = Separator;
4398   }
4399   return OS.str().str();
4400 }
4401 
4402 std::string
4403 OpenMPIRBuilder::createPlatformSpecificName(ArrayRef<StringRef> Parts) const {
4404   return OpenMPIRBuilder::getNameWithSeparators(Parts, Config.firstSeparator(),
4405                                                 Config.separator());
4406 }
4407 
4408 GlobalVariable *
4409 OpenMPIRBuilder::getOrCreateInternalVariable(Type *Ty, const StringRef &Name,
4410                                              unsigned AddressSpace) {
4411   auto &Elem = *InternalVars.try_emplace(Name, nullptr).first;
4412   if (Elem.second) {
4413     assert(Elem.second->getValueType() == Ty &&
4414            "OMP internal variable has different type than requested");
4415   } else {
4416     // TODO: investigate the appropriate linkage type used for the global
4417     // variable for possibly changing that to internal or private, or maybe
4418     // create different versions of the function for different OMP internal
4419     // variables.
4420     auto *GV = new GlobalVariable(
4421         M, Ty, /*IsConstant=*/false, GlobalValue::CommonLinkage,
4422         Constant::getNullValue(Ty), Elem.first(),
4423         /*InsertBefore=*/nullptr, GlobalValue::NotThreadLocal, AddressSpace);
4424     GV->setAlignment(M.getDataLayout().getABITypeAlign(Ty));
4425     Elem.second = GV;
4426   }
4427 
4428   return Elem.second;
4429 }
4430 
4431 Value *OpenMPIRBuilder::getOMPCriticalRegionLock(StringRef CriticalName) {
4432   std::string Prefix = Twine("gomp_critical_user_", CriticalName).str();
4433   std::string Name = getNameWithSeparators({Prefix, "var"}, ".", ".");
4434   return getOrCreateInternalVariable(KmpCriticalNameTy, Name);
4435 }
4436 
4437 Value *OpenMPIRBuilder::getSizeInBytes(Value *BasePtr) {
4438   LLVMContext &Ctx = Builder.getContext();
4439   Value *Null =
4440       Constant::getNullValue(PointerType::getUnqual(BasePtr->getContext()));
4441   Value *SizeGep =
4442       Builder.CreateGEP(BasePtr->getType(), Null, Builder.getInt32(1));
4443   Value *SizePtrToInt = Builder.CreatePtrToInt(SizeGep, Type::getInt64Ty(Ctx));
4444   return SizePtrToInt;
4445 }
4446 
4447 GlobalVariable *
4448 OpenMPIRBuilder::createOffloadMaptypes(SmallVectorImpl<uint64_t> &Mappings,
4449                                        std::string VarName) {
4450   llvm::Constant *MaptypesArrayInit =
4451       llvm::ConstantDataArray::get(M.getContext(), Mappings);
4452   auto *MaptypesArrayGlobal = new llvm::GlobalVariable(
4453       M, MaptypesArrayInit->getType(),
4454       /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage, MaptypesArrayInit,
4455       VarName);
4456   MaptypesArrayGlobal->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4457   return MaptypesArrayGlobal;
4458 }
4459 
4460 void OpenMPIRBuilder::createMapperAllocas(const LocationDescription &Loc,
4461                                           InsertPointTy AllocaIP,
4462                                           unsigned NumOperands,
4463                                           struct MapperAllocas &MapperAllocas) {
4464   if (!updateToLocation(Loc))
4465     return;
4466 
4467   auto *ArrI8PtrTy = ArrayType::get(Int8Ptr, NumOperands);
4468   auto *ArrI64Ty = ArrayType::get(Int64, NumOperands);
4469   Builder.restoreIP(AllocaIP);
4470   AllocaInst *ArgsBase = Builder.CreateAlloca(
4471       ArrI8PtrTy, /* ArraySize = */ nullptr, ".offload_baseptrs");
4472   AllocaInst *Args = Builder.CreateAlloca(ArrI8PtrTy, /* ArraySize = */ nullptr,
4473                                           ".offload_ptrs");
4474   AllocaInst *ArgSizes = Builder.CreateAlloca(
4475       ArrI64Ty, /* ArraySize = */ nullptr, ".offload_sizes");
4476   Builder.restoreIP(Loc.IP);
4477   MapperAllocas.ArgsBase = ArgsBase;
4478   MapperAllocas.Args = Args;
4479   MapperAllocas.ArgSizes = ArgSizes;
4480 }
4481 
4482 void OpenMPIRBuilder::emitMapperCall(const LocationDescription &Loc,
4483                                      Function *MapperFunc, Value *SrcLocInfo,
4484                                      Value *MaptypesArg, Value *MapnamesArg,
4485                                      struct MapperAllocas &MapperAllocas,
4486                                      int64_t DeviceID, unsigned NumOperands) {
4487   if (!updateToLocation(Loc))
4488     return;
4489 
4490   auto *ArrI8PtrTy = ArrayType::get(Int8Ptr, NumOperands);
4491   auto *ArrI64Ty = ArrayType::get(Int64, NumOperands);
4492   Value *ArgsBaseGEP =
4493       Builder.CreateInBoundsGEP(ArrI8PtrTy, MapperAllocas.ArgsBase,
4494                                 {Builder.getInt32(0), Builder.getInt32(0)});
4495   Value *ArgsGEP =
4496       Builder.CreateInBoundsGEP(ArrI8PtrTy, MapperAllocas.Args,
4497                                 {Builder.getInt32(0), Builder.getInt32(0)});
4498   Value *ArgSizesGEP =
4499       Builder.CreateInBoundsGEP(ArrI64Ty, MapperAllocas.ArgSizes,
4500                                 {Builder.getInt32(0), Builder.getInt32(0)});
4501   Value *NullPtr =
4502       Constant::getNullValue(PointerType::getUnqual(Int8Ptr->getContext()));
4503   Builder.CreateCall(MapperFunc,
4504                      {SrcLocInfo, Builder.getInt64(DeviceID),
4505                       Builder.getInt32(NumOperands), ArgsBaseGEP, ArgsGEP,
4506                       ArgSizesGEP, MaptypesArg, MapnamesArg, NullPtr});
4507 }
4508 
4509 void OpenMPIRBuilder::emitOffloadingArraysArgument(IRBuilderBase &Builder,
4510                                                    TargetDataRTArgs &RTArgs,
4511                                                    TargetDataInfo &Info,
4512                                                    bool EmitDebug,
4513                                                    bool ForEndCall) {
4514   assert((!ForEndCall || Info.separateBeginEndCalls()) &&
4515          "expected region end call to runtime only when end call is separate");
4516   auto VoidPtrTy = Type::getInt8PtrTy(M.getContext());
4517   auto VoidPtrPtrTy = VoidPtrTy->getPointerTo(0);
4518   auto Int64Ty = Type::getInt64Ty(M.getContext());
4519   auto Int64PtrTy = Type::getInt64PtrTy(M.getContext());
4520 
4521   if (!Info.NumberOfPtrs) {
4522     RTArgs.BasePointersArray = ConstantPointerNull::get(VoidPtrPtrTy);
4523     RTArgs.PointersArray = ConstantPointerNull::get(VoidPtrPtrTy);
4524     RTArgs.SizesArray = ConstantPointerNull::get(Int64PtrTy);
4525     RTArgs.MapTypesArray = ConstantPointerNull::get(Int64PtrTy);
4526     RTArgs.MapNamesArray = ConstantPointerNull::get(VoidPtrPtrTy);
4527     RTArgs.MappersArray = ConstantPointerNull::get(VoidPtrPtrTy);
4528     return;
4529   }
4530 
4531   RTArgs.BasePointersArray = Builder.CreateConstInBoundsGEP2_32(
4532       ArrayType::get(VoidPtrTy, Info.NumberOfPtrs),
4533       Info.RTArgs.BasePointersArray,
4534       /*Idx0=*/0, /*Idx1=*/0);
4535   RTArgs.PointersArray = Builder.CreateConstInBoundsGEP2_32(
4536       ArrayType::get(VoidPtrTy, Info.NumberOfPtrs), Info.RTArgs.PointersArray,
4537       /*Idx0=*/0,
4538       /*Idx1=*/0);
4539   RTArgs.SizesArray = Builder.CreateConstInBoundsGEP2_32(
4540       ArrayType::get(Int64Ty, Info.NumberOfPtrs), Info.RTArgs.SizesArray,
4541       /*Idx0=*/0, /*Idx1=*/0);
4542   RTArgs.MapTypesArray = Builder.CreateConstInBoundsGEP2_32(
4543       ArrayType::get(Int64Ty, Info.NumberOfPtrs),
4544       ForEndCall && Info.RTArgs.MapTypesArrayEnd ? Info.RTArgs.MapTypesArrayEnd
4545                                                  : Info.RTArgs.MapTypesArray,
4546       /*Idx0=*/0,
4547       /*Idx1=*/0);
4548 
4549   // Only emit the mapper information arrays if debug information is
4550   // requested.
4551   if (!EmitDebug)
4552     RTArgs.MapNamesArray = ConstantPointerNull::get(VoidPtrPtrTy);
4553   else
4554     RTArgs.MapNamesArray = Builder.CreateConstInBoundsGEP2_32(
4555         ArrayType::get(VoidPtrTy, Info.NumberOfPtrs), Info.RTArgs.MapNamesArray,
4556         /*Idx0=*/0,
4557         /*Idx1=*/0);
4558   // If there is no user-defined mapper, set the mapper array to nullptr to
4559   // avoid an unnecessary data privatization
4560   if (!Info.HasMapper)
4561     RTArgs.MappersArray = ConstantPointerNull::get(VoidPtrPtrTy);
4562   else
4563     RTArgs.MappersArray =
4564         Builder.CreatePointerCast(Info.RTArgs.MappersArray, VoidPtrPtrTy);
4565 }
4566 
4567 void OpenMPIRBuilder::emitNonContiguousDescriptor(InsertPointTy AllocaIP,
4568                                                   InsertPointTy CodeGenIP,
4569                                                   MapInfosTy &CombinedInfo,
4570                                                   TargetDataInfo &Info) {
4571   MapInfosTy::StructNonContiguousInfo &NonContigInfo =
4572       CombinedInfo.NonContigInfo;
4573 
4574   // Build an array of struct descriptor_dim and then assign it to
4575   // offload_args.
4576   //
4577   // struct descriptor_dim {
4578   //  uint64_t offset;
4579   //  uint64_t count;
4580   //  uint64_t stride
4581   // };
4582   Type *Int64Ty = Builder.getInt64Ty();
4583   StructType *DimTy = StructType::create(
4584       M.getContext(), ArrayRef<Type *>({Int64Ty, Int64Ty, Int64Ty}),
4585       "struct.descriptor_dim");
4586 
4587   enum { OffsetFD = 0, CountFD, StrideFD };
4588   // We need two index variable here since the size of "Dims" is the same as
4589   // the size of Components, however, the size of offset, count, and stride is
4590   // equal to the size of base declaration that is non-contiguous.
4591   for (unsigned I = 0, L = 0, E = NonContigInfo.Dims.size(); I < E; ++I) {
4592     // Skip emitting ir if dimension size is 1 since it cannot be
4593     // non-contiguous.
4594     if (NonContigInfo.Dims[I] == 1)
4595       continue;
4596     Builder.restoreIP(AllocaIP);
4597     ArrayType *ArrayTy = ArrayType::get(DimTy, NonContigInfo.Dims[I]);
4598     AllocaInst *DimsAddr =
4599         Builder.CreateAlloca(ArrayTy, /* ArraySize = */ nullptr, "dims");
4600     Builder.restoreIP(CodeGenIP);
4601     for (unsigned II = 0, EE = NonContigInfo.Dims[I]; II < EE; ++II) {
4602       unsigned RevIdx = EE - II - 1;
4603       Value *DimsLVal = Builder.CreateInBoundsGEP(
4604           DimsAddr->getAllocatedType(), DimsAddr,
4605           {Builder.getInt64(0), Builder.getInt64(II)});
4606       // Offset
4607       Value *OffsetLVal = Builder.CreateStructGEP(DimTy, DimsLVal, OffsetFD);
4608       Builder.CreateAlignedStore(
4609           NonContigInfo.Offsets[L][RevIdx], OffsetLVal,
4610           M.getDataLayout().getPrefTypeAlign(OffsetLVal->getType()));
4611       // Count
4612       Value *CountLVal = Builder.CreateStructGEP(DimTy, DimsLVal, CountFD);
4613       Builder.CreateAlignedStore(
4614           NonContigInfo.Counts[L][RevIdx], CountLVal,
4615           M.getDataLayout().getPrefTypeAlign(CountLVal->getType()));
4616       // Stride
4617       Value *StrideLVal = Builder.CreateStructGEP(DimTy, DimsLVal, StrideFD);
4618       Builder.CreateAlignedStore(
4619           NonContigInfo.Strides[L][RevIdx], StrideLVal,
4620           M.getDataLayout().getPrefTypeAlign(CountLVal->getType()));
4621     }
4622     // args[I] = &dims
4623     Builder.restoreIP(CodeGenIP);
4624     Value *DAddr = Builder.CreatePointerBitCastOrAddrSpaceCast(
4625         DimsAddr, Builder.getInt8PtrTy());
4626     Value *P = Builder.CreateConstInBoundsGEP2_32(
4627         ArrayType::get(Builder.getInt8PtrTy(), Info.NumberOfPtrs),
4628         Info.RTArgs.PointersArray, 0, I);
4629     Builder.CreateAlignedStore(
4630         DAddr, P, M.getDataLayout().getPrefTypeAlign(Builder.getInt8PtrTy()));
4631     ++L;
4632   }
4633 }
4634 
4635 void OpenMPIRBuilder::emitOffloadingArrays(
4636     InsertPointTy AllocaIP, InsertPointTy CodeGenIP, MapInfosTy &CombinedInfo,
4637     TargetDataInfo &Info, bool IsNonContiguous,
4638     function_ref<void(unsigned int, Value *)> DeviceAddrCB,
4639     function_ref<Value *(unsigned int)> CustomMapperCB) {
4640 
4641   // Reset the array information.
4642   Info.clearArrayInfo();
4643   Info.NumberOfPtrs = CombinedInfo.BasePointers.size();
4644 
4645   if (Info.NumberOfPtrs == 0)
4646     return;
4647 
4648   Builder.restoreIP(AllocaIP);
4649   // Detect if we have any capture size requiring runtime evaluation of the
4650   // size so that a constant array could be eventually used.
4651   ArrayType *PointerArrayType =
4652       ArrayType::get(Builder.getInt8PtrTy(), Info.NumberOfPtrs);
4653 
4654   Info.RTArgs.BasePointersArray = Builder.CreateAlloca(
4655       PointerArrayType, /* ArraySize = */ nullptr, ".offload_baseptrs");
4656 
4657   Info.RTArgs.PointersArray = Builder.CreateAlloca(
4658       PointerArrayType, /* ArraySize = */ nullptr, ".offload_ptrs");
4659   AllocaInst *MappersArray = Builder.CreateAlloca(
4660       PointerArrayType, /* ArraySize = */ nullptr, ".offload_mappers");
4661   Info.RTArgs.MappersArray = MappersArray;
4662 
4663   // If we don't have any VLA types or other types that require runtime
4664   // evaluation, we can use a constant array for the map sizes, otherwise we
4665   // need to fill up the arrays as we do for the pointers.
4666   Type *Int64Ty = Builder.getInt64Ty();
4667   SmallVector<Constant *> ConstSizes(CombinedInfo.Sizes.size(),
4668                                      ConstantInt::get(Builder.getInt64Ty(), 0));
4669   SmallBitVector RuntimeSizes(CombinedInfo.Sizes.size());
4670   for (unsigned I = 0, E = CombinedInfo.Sizes.size(); I < E; ++I) {
4671     if (auto *CI = dyn_cast<Constant>(CombinedInfo.Sizes[I])) {
4672       if (!isa<ConstantExpr>(CI) && !isa<GlobalValue>(CI)) {
4673         if (IsNonContiguous &&
4674             static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>>(
4675                 CombinedInfo.Types[I] &
4676                 OpenMPOffloadMappingFlags::OMP_MAP_NON_CONTIG))
4677           ConstSizes[I] = ConstantInt::get(Builder.getInt64Ty(),
4678                                            CombinedInfo.NonContigInfo.Dims[I]);
4679         else
4680           ConstSizes[I] = CI;
4681         continue;
4682       }
4683     }
4684     RuntimeSizes.set(I);
4685   }
4686 
4687   if (RuntimeSizes.all()) {
4688     ArrayType *SizeArrayType = ArrayType::get(Int64Ty, Info.NumberOfPtrs);
4689     Info.RTArgs.SizesArray = Builder.CreateAlloca(
4690         SizeArrayType, /* ArraySize = */ nullptr, ".offload_sizes");
4691     Builder.restoreIP(CodeGenIP);
4692   } else {
4693     auto *SizesArrayInit = ConstantArray::get(
4694         ArrayType::get(Int64Ty, ConstSizes.size()), ConstSizes);
4695     std::string Name = createPlatformSpecificName({"offload_sizes"});
4696     auto *SizesArrayGbl =
4697         new GlobalVariable(M, SizesArrayInit->getType(), /*isConstant=*/true,
4698                            GlobalValue::PrivateLinkage, SizesArrayInit, Name);
4699     SizesArrayGbl->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
4700 
4701     if (!RuntimeSizes.any()) {
4702       Info.RTArgs.SizesArray = SizesArrayGbl;
4703     } else {
4704       unsigned IndexSize = M.getDataLayout().getIndexSizeInBits(0);
4705       Align OffloadSizeAlign = M.getDataLayout().getABIIntegerTypeAlignment(64);
4706       ArrayType *SizeArrayType = ArrayType::get(Int64Ty, Info.NumberOfPtrs);
4707       AllocaInst *Buffer = Builder.CreateAlloca(
4708           SizeArrayType, /* ArraySize = */ nullptr, ".offload_sizes");
4709       Buffer->setAlignment(OffloadSizeAlign);
4710       Builder.restoreIP(CodeGenIP);
4711       Value *GblConstPtr = Builder.CreatePointerBitCastOrAddrSpaceCast(
4712           SizesArrayGbl, Int64Ty->getPointerTo());
4713       Builder.CreateMemCpy(
4714           Buffer, M.getDataLayout().getPrefTypeAlign(Buffer->getType()),
4715           GblConstPtr, OffloadSizeAlign,
4716           Builder.getIntN(
4717               IndexSize,
4718               Buffer->getAllocationSize(M.getDataLayout())->getFixedValue()));
4719 
4720       Info.RTArgs.SizesArray = Buffer;
4721     }
4722     Builder.restoreIP(CodeGenIP);
4723   }
4724 
4725   // The map types are always constant so we don't need to generate code to
4726   // fill arrays. Instead, we create an array constant.
4727   SmallVector<uint64_t, 4> Mapping;
4728   for (auto mapFlag : CombinedInfo.Types)
4729     Mapping.push_back(
4730         static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>>(
4731             mapFlag));
4732   std::string MaptypesName = createPlatformSpecificName({"offload_maptypes"});
4733   auto *MapTypesArrayGbl = createOffloadMaptypes(Mapping, MaptypesName);
4734   Info.RTArgs.MapTypesArray = MapTypesArrayGbl;
4735 
4736   // The information types are only built if provided.
4737   if (!CombinedInfo.Names.empty()) {
4738     std::string MapnamesName = createPlatformSpecificName({"offload_mapnames"});
4739     auto *MapNamesArrayGbl =
4740         createOffloadMapnames(CombinedInfo.Names, MapnamesName);
4741     Info.RTArgs.MapNamesArray = MapNamesArrayGbl;
4742   } else {
4743     Info.RTArgs.MapNamesArray = Constant::getNullValue(
4744         Type::getInt8Ty(Builder.getContext())->getPointerTo());
4745   }
4746 
4747   // If there's a present map type modifier, it must not be applied to the end
4748   // of a region, so generate a separate map type array in that case.
4749   if (Info.separateBeginEndCalls()) {
4750     bool EndMapTypesDiffer = false;
4751     for (uint64_t &Type : Mapping) {
4752       if (Type & static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>>(
4753                      OpenMPOffloadMappingFlags::OMP_MAP_PRESENT)) {
4754         Type &= ~static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>>(
4755             OpenMPOffloadMappingFlags::OMP_MAP_PRESENT);
4756         EndMapTypesDiffer = true;
4757       }
4758     }
4759     if (EndMapTypesDiffer) {
4760       MapTypesArrayGbl = createOffloadMaptypes(Mapping, MaptypesName);
4761       Info.RTArgs.MapTypesArrayEnd = MapTypesArrayGbl;
4762     }
4763   }
4764 
4765   for (unsigned I = 0; I < Info.NumberOfPtrs; ++I) {
4766     Value *BPVal = CombinedInfo.BasePointers[I];
4767     Value *BP = Builder.CreateConstInBoundsGEP2_32(
4768         ArrayType::get(Builder.getInt8PtrTy(), Info.NumberOfPtrs),
4769         Info.RTArgs.BasePointersArray, 0, I);
4770     BP = Builder.CreatePointerBitCastOrAddrSpaceCast(
4771         BP, BPVal->getType()->getPointerTo(/*AddrSpace=*/0));
4772     Builder.CreateAlignedStore(
4773         BPVal, BP, M.getDataLayout().getPrefTypeAlign(Builder.getInt8PtrTy()));
4774 
4775     if (Info.requiresDevicePointerInfo()) {
4776       if (CombinedInfo.DevicePointers[I] == DeviceInfoTy::Pointer) {
4777         CodeGenIP = Builder.saveIP();
4778         Builder.restoreIP(AllocaIP);
4779         Info.DevicePtrInfoMap[BPVal] = {
4780             BP, Builder.CreateAlloca(Builder.getPtrTy())};
4781         Builder.restoreIP(CodeGenIP);
4782         assert(DeviceAddrCB &&
4783                "DeviceAddrCB missing for DevicePtr code generation");
4784         DeviceAddrCB(I, Info.DevicePtrInfoMap[BPVal].second);
4785       } else if (CombinedInfo.DevicePointers[I] == DeviceInfoTy::Address) {
4786         Info.DevicePtrInfoMap[BPVal] = {BP, BP};
4787         assert(DeviceAddrCB &&
4788                "DeviceAddrCB missing for DevicePtr code generation");
4789         DeviceAddrCB(I, BP);
4790       }
4791     }
4792 
4793     Value *PVal = CombinedInfo.Pointers[I];
4794     Value *P = Builder.CreateConstInBoundsGEP2_32(
4795         ArrayType::get(Builder.getInt8PtrTy(), Info.NumberOfPtrs),
4796         Info.RTArgs.PointersArray, 0, I);
4797     P = Builder.CreatePointerBitCastOrAddrSpaceCast(
4798         P, PVal->getType()->getPointerTo(/*AddrSpace=*/0));
4799     // TODO: Check alignment correct.
4800     Builder.CreateAlignedStore(
4801         PVal, P, M.getDataLayout().getPrefTypeAlign(Builder.getInt8PtrTy()));
4802 
4803     if (RuntimeSizes.test(I)) {
4804       Value *S = Builder.CreateConstInBoundsGEP2_32(
4805           ArrayType::get(Int64Ty, Info.NumberOfPtrs), Info.RTArgs.SizesArray,
4806           /*Idx0=*/0,
4807           /*Idx1=*/I);
4808       Builder.CreateAlignedStore(
4809           Builder.CreateIntCast(CombinedInfo.Sizes[I], Int64Ty,
4810                                 /*isSigned=*/true),
4811           S, M.getDataLayout().getPrefTypeAlign(Builder.getInt8PtrTy()));
4812     }
4813     // Fill up the mapper array.
4814     unsigned IndexSize = M.getDataLayout().getIndexSizeInBits(0);
4815     Value *MFunc = ConstantPointerNull::get(Builder.getInt8PtrTy());
4816     if (CustomMapperCB)
4817       if (Value *CustomMFunc = CustomMapperCB(I))
4818         MFunc = Builder.CreatePointerCast(CustomMFunc, Builder.getInt8PtrTy());
4819     Value *MAddr = Builder.CreateInBoundsGEP(
4820         MappersArray->getAllocatedType(), MappersArray,
4821         {Builder.getIntN(IndexSize, 0), Builder.getIntN(IndexSize, I)});
4822     Builder.CreateAlignedStore(
4823         MFunc, MAddr, M.getDataLayout().getPrefTypeAlign(MAddr->getType()));
4824   }
4825 
4826   if (!IsNonContiguous || CombinedInfo.NonContigInfo.Offsets.empty() ||
4827       Info.NumberOfPtrs == 0)
4828     return;
4829   emitNonContiguousDescriptor(AllocaIP, CodeGenIP, CombinedInfo, Info);
4830 }
4831 
4832 void OpenMPIRBuilder::emitBranch(BasicBlock *Target) {
4833   BasicBlock *CurBB = Builder.GetInsertBlock();
4834 
4835   if (!CurBB || CurBB->getTerminator()) {
4836     // If there is no insert point or the previous block is already
4837     // terminated, don't touch it.
4838   } else {
4839     // Otherwise, create a fall-through branch.
4840     Builder.CreateBr(Target);
4841   }
4842 
4843   Builder.ClearInsertionPoint();
4844 }
4845 
4846 void OpenMPIRBuilder::emitBlock(BasicBlock *BB, Function *CurFn,
4847                                 bool IsFinished) {
4848   BasicBlock *CurBB = Builder.GetInsertBlock();
4849 
4850   // Fall out of the current block (if necessary).
4851   emitBranch(BB);
4852 
4853   if (IsFinished && BB->use_empty()) {
4854     BB->eraseFromParent();
4855     return;
4856   }
4857 
4858   // Place the block after the current block, if possible, or else at
4859   // the end of the function.
4860   if (CurBB && CurBB->getParent())
4861     CurFn->insert(std::next(CurBB->getIterator()), BB);
4862   else
4863     CurFn->insert(CurFn->end(), BB);
4864   Builder.SetInsertPoint(BB);
4865 }
4866 
4867 void OpenMPIRBuilder::emitIfClause(Value *Cond, BodyGenCallbackTy ThenGen,
4868                                    BodyGenCallbackTy ElseGen,
4869                                    InsertPointTy AllocaIP) {
4870   // If the condition constant folds and can be elided, try to avoid emitting
4871   // the condition and the dead arm of the if/else.
4872   if (auto *CI = dyn_cast<ConstantInt>(Cond)) {
4873     auto CondConstant = CI->getSExtValue();
4874     if (CondConstant)
4875       ThenGen(AllocaIP, Builder.saveIP());
4876     else
4877       ElseGen(AllocaIP, Builder.saveIP());
4878     return;
4879   }
4880 
4881   Function *CurFn = Builder.GetInsertBlock()->getParent();
4882 
4883   // Otherwise, the condition did not fold, or we couldn't elide it.  Just
4884   // emit the conditional branch.
4885   BasicBlock *ThenBlock = BasicBlock::Create(M.getContext(), "omp_if.then");
4886   BasicBlock *ElseBlock = BasicBlock::Create(M.getContext(), "omp_if.else");
4887   BasicBlock *ContBlock = BasicBlock::Create(M.getContext(), "omp_if.end");
4888   Builder.CreateCondBr(Cond, ThenBlock, ElseBlock);
4889   // Emit the 'then' code.
4890   emitBlock(ThenBlock, CurFn);
4891   ThenGen(AllocaIP, Builder.saveIP());
4892   emitBranch(ContBlock);
4893   // Emit the 'else' code if present.
4894   // There is no need to emit line number for unconditional branch.
4895   emitBlock(ElseBlock, CurFn);
4896   ElseGen(AllocaIP, Builder.saveIP());
4897   // There is no need to emit line number for unconditional branch.
4898   emitBranch(ContBlock);
4899   // Emit the continuation block for code after the if.
4900   emitBlock(ContBlock, CurFn, /*IsFinished=*/true);
4901 }
4902 
4903 bool OpenMPIRBuilder::checkAndEmitFlushAfterAtomic(
4904     const LocationDescription &Loc, llvm::AtomicOrdering AO, AtomicKind AK) {
4905   assert(!(AO == AtomicOrdering::NotAtomic ||
4906            AO == llvm::AtomicOrdering::Unordered) &&
4907          "Unexpected Atomic Ordering.");
4908 
4909   bool Flush = false;
4910   llvm::AtomicOrdering FlushAO = AtomicOrdering::Monotonic;
4911 
4912   switch (AK) {
4913   case Read:
4914     if (AO == AtomicOrdering::Acquire || AO == AtomicOrdering::AcquireRelease ||
4915         AO == AtomicOrdering::SequentiallyConsistent) {
4916       FlushAO = AtomicOrdering::Acquire;
4917       Flush = true;
4918     }
4919     break;
4920   case Write:
4921   case Compare:
4922   case Update:
4923     if (AO == AtomicOrdering::Release || AO == AtomicOrdering::AcquireRelease ||
4924         AO == AtomicOrdering::SequentiallyConsistent) {
4925       FlushAO = AtomicOrdering::Release;
4926       Flush = true;
4927     }
4928     break;
4929   case Capture:
4930     switch (AO) {
4931     case AtomicOrdering::Acquire:
4932       FlushAO = AtomicOrdering::Acquire;
4933       Flush = true;
4934       break;
4935     case AtomicOrdering::Release:
4936       FlushAO = AtomicOrdering::Release;
4937       Flush = true;
4938       break;
4939     case AtomicOrdering::AcquireRelease:
4940     case AtomicOrdering::SequentiallyConsistent:
4941       FlushAO = AtomicOrdering::AcquireRelease;
4942       Flush = true;
4943       break;
4944     default:
4945       // do nothing - leave silently.
4946       break;
4947     }
4948   }
4949 
4950   if (Flush) {
4951     // Currently Flush RT call still doesn't take memory_ordering, so for when
4952     // that happens, this tries to do the resolution of which atomic ordering
4953     // to use with but issue the flush call
4954     // TODO: pass `FlushAO` after memory ordering support is added
4955     (void)FlushAO;
4956     emitFlush(Loc);
4957   }
4958 
4959   // for AO == AtomicOrdering::Monotonic and  all other case combinations
4960   // do nothing
4961   return Flush;
4962 }
4963 
4964 OpenMPIRBuilder::InsertPointTy
4965 OpenMPIRBuilder::createAtomicRead(const LocationDescription &Loc,
4966                                   AtomicOpValue &X, AtomicOpValue &V,
4967                                   AtomicOrdering AO) {
4968   if (!updateToLocation(Loc))
4969     return Loc.IP;
4970 
4971   assert(X.Var->getType()->isPointerTy() &&
4972          "OMP Atomic expects a pointer to target memory");
4973   Type *XElemTy = X.ElemTy;
4974   assert((XElemTy->isFloatingPointTy() || XElemTy->isIntegerTy() ||
4975           XElemTy->isPointerTy()) &&
4976          "OMP atomic read expected a scalar type");
4977 
4978   Value *XRead = nullptr;
4979 
4980   if (XElemTy->isIntegerTy()) {
4981     LoadInst *XLD =
4982         Builder.CreateLoad(XElemTy, X.Var, X.IsVolatile, "omp.atomic.read");
4983     XLD->setAtomic(AO);
4984     XRead = cast<Value>(XLD);
4985   } else {
4986     // We need to perform atomic op as integer
4987     IntegerType *IntCastTy =
4988         IntegerType::get(M.getContext(), XElemTy->getScalarSizeInBits());
4989     LoadInst *XLoad =
4990         Builder.CreateLoad(IntCastTy, X.Var, X.IsVolatile, "omp.atomic.load");
4991     XLoad->setAtomic(AO);
4992     if (XElemTy->isFloatingPointTy()) {
4993       XRead = Builder.CreateBitCast(XLoad, XElemTy, "atomic.flt.cast");
4994     } else {
4995       XRead = Builder.CreateIntToPtr(XLoad, XElemTy, "atomic.ptr.cast");
4996     }
4997   }
4998   checkAndEmitFlushAfterAtomic(Loc, AO, AtomicKind::Read);
4999   Builder.CreateStore(XRead, V.Var, V.IsVolatile);
5000   return Builder.saveIP();
5001 }
5002 
5003 OpenMPIRBuilder::InsertPointTy
5004 OpenMPIRBuilder::createAtomicWrite(const LocationDescription &Loc,
5005                                    AtomicOpValue &X, Value *Expr,
5006                                    AtomicOrdering AO) {
5007   if (!updateToLocation(Loc))
5008     return Loc.IP;
5009 
5010   Type *XTy = X.Var->getType();
5011   assert(XTy->isPointerTy() && "OMP Atomic expects a pointer to target memory");
5012   Type *XElemTy = X.ElemTy;
5013   assert((XElemTy->isFloatingPointTy() || XElemTy->isIntegerTy() ||
5014           XElemTy->isPointerTy()) &&
5015          "OMP atomic write expected a scalar type");
5016 
5017   if (XElemTy->isIntegerTy()) {
5018     StoreInst *XSt = Builder.CreateStore(Expr, X.Var, X.IsVolatile);
5019     XSt->setAtomic(AO);
5020   } else {
5021     // We need to bitcast and perform atomic op as integers
5022     unsigned Addrspace = cast<PointerType>(XTy)->getAddressSpace();
5023     IntegerType *IntCastTy =
5024         IntegerType::get(M.getContext(), XElemTy->getScalarSizeInBits());
5025     Value *XBCast = Builder.CreateBitCast(
5026         X.Var, IntCastTy->getPointerTo(Addrspace), "atomic.dst.int.cast");
5027     Value *ExprCast =
5028         Builder.CreateBitCast(Expr, IntCastTy, "atomic.src.int.cast");
5029     StoreInst *XSt = Builder.CreateStore(ExprCast, XBCast, X.IsVolatile);
5030     XSt->setAtomic(AO);
5031   }
5032 
5033   checkAndEmitFlushAfterAtomic(Loc, AO, AtomicKind::Write);
5034   return Builder.saveIP();
5035 }
5036 
5037 OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::createAtomicUpdate(
5038     const LocationDescription &Loc, InsertPointTy AllocaIP, AtomicOpValue &X,
5039     Value *Expr, AtomicOrdering AO, AtomicRMWInst::BinOp RMWOp,
5040     AtomicUpdateCallbackTy &UpdateOp, bool IsXBinopExpr) {
5041   assert(!isConflictIP(Loc.IP, AllocaIP) && "IPs must not be ambiguous");
5042   if (!updateToLocation(Loc))
5043     return Loc.IP;
5044 
5045   LLVM_DEBUG({
5046     Type *XTy = X.Var->getType();
5047     assert(XTy->isPointerTy() &&
5048            "OMP Atomic expects a pointer to target memory");
5049     Type *XElemTy = X.ElemTy;
5050     assert((XElemTy->isFloatingPointTy() || XElemTy->isIntegerTy() ||
5051             XElemTy->isPointerTy()) &&
5052            "OMP atomic update expected a scalar type");
5053     assert((RMWOp != AtomicRMWInst::Max) && (RMWOp != AtomicRMWInst::Min) &&
5054            (RMWOp != AtomicRMWInst::UMax) && (RMWOp != AtomicRMWInst::UMin) &&
5055            "OpenMP atomic does not support LT or GT operations");
5056   });
5057 
5058   emitAtomicUpdate(AllocaIP, X.Var, X.ElemTy, Expr, AO, RMWOp, UpdateOp,
5059                    X.IsVolatile, IsXBinopExpr);
5060   checkAndEmitFlushAfterAtomic(Loc, AO, AtomicKind::Update);
5061   return Builder.saveIP();
5062 }
5063 
5064 // FIXME: Duplicating AtomicExpand
5065 Value *OpenMPIRBuilder::emitRMWOpAsInstruction(Value *Src1, Value *Src2,
5066                                                AtomicRMWInst::BinOp RMWOp) {
5067   switch (RMWOp) {
5068   case AtomicRMWInst::Add:
5069     return Builder.CreateAdd(Src1, Src2);
5070   case AtomicRMWInst::Sub:
5071     return Builder.CreateSub(Src1, Src2);
5072   case AtomicRMWInst::And:
5073     return Builder.CreateAnd(Src1, Src2);
5074   case AtomicRMWInst::Nand:
5075     return Builder.CreateNeg(Builder.CreateAnd(Src1, Src2));
5076   case AtomicRMWInst::Or:
5077     return Builder.CreateOr(Src1, Src2);
5078   case AtomicRMWInst::Xor:
5079     return Builder.CreateXor(Src1, Src2);
5080   case AtomicRMWInst::Xchg:
5081   case AtomicRMWInst::FAdd:
5082   case AtomicRMWInst::FSub:
5083   case AtomicRMWInst::BAD_BINOP:
5084   case AtomicRMWInst::Max:
5085   case AtomicRMWInst::Min:
5086   case AtomicRMWInst::UMax:
5087   case AtomicRMWInst::UMin:
5088   case AtomicRMWInst::FMax:
5089   case AtomicRMWInst::FMin:
5090   case AtomicRMWInst::UIncWrap:
5091   case AtomicRMWInst::UDecWrap:
5092     llvm_unreachable("Unsupported atomic update operation");
5093   }
5094   llvm_unreachable("Unsupported atomic update operation");
5095 }
5096 
5097 std::pair<Value *, Value *> OpenMPIRBuilder::emitAtomicUpdate(
5098     InsertPointTy AllocaIP, Value *X, Type *XElemTy, Value *Expr,
5099     AtomicOrdering AO, AtomicRMWInst::BinOp RMWOp,
5100     AtomicUpdateCallbackTy &UpdateOp, bool VolatileX, bool IsXBinopExpr) {
5101   // TODO: handle the case where XElemTy is not byte-sized or not a power of 2
5102   // or a complex datatype.
5103   bool emitRMWOp = false;
5104   switch (RMWOp) {
5105   case AtomicRMWInst::Add:
5106   case AtomicRMWInst::And:
5107   case AtomicRMWInst::Nand:
5108   case AtomicRMWInst::Or:
5109   case AtomicRMWInst::Xor:
5110   case AtomicRMWInst::Xchg:
5111     emitRMWOp = XElemTy;
5112     break;
5113   case AtomicRMWInst::Sub:
5114     emitRMWOp = (IsXBinopExpr && XElemTy);
5115     break;
5116   default:
5117     emitRMWOp = false;
5118   }
5119   emitRMWOp &= XElemTy->isIntegerTy();
5120 
5121   std::pair<Value *, Value *> Res;
5122   if (emitRMWOp) {
5123     Res.first = Builder.CreateAtomicRMW(RMWOp, X, Expr, llvm::MaybeAlign(), AO);
5124     // not needed except in case of postfix captures. Generate anyway for
5125     // consistency with the else part. Will be removed with any DCE pass.
5126     // AtomicRMWInst::Xchg does not have a coressponding instruction.
5127     if (RMWOp == AtomicRMWInst::Xchg)
5128       Res.second = Res.first;
5129     else
5130       Res.second = emitRMWOpAsInstruction(Res.first, Expr, RMWOp);
5131   } else {
5132     IntegerType *IntCastTy =
5133         IntegerType::get(M.getContext(), XElemTy->getScalarSizeInBits());
5134     LoadInst *OldVal =
5135         Builder.CreateLoad(IntCastTy, X, X->getName() + ".atomic.load");
5136     OldVal->setAtomic(AO);
5137     // CurBB
5138     // |     /---\
5139 		// ContBB    |
5140     // |     \---/
5141     // ExitBB
5142     BasicBlock *CurBB = Builder.GetInsertBlock();
5143     Instruction *CurBBTI = CurBB->getTerminator();
5144     CurBBTI = CurBBTI ? CurBBTI : Builder.CreateUnreachable();
5145     BasicBlock *ExitBB =
5146         CurBB->splitBasicBlock(CurBBTI, X->getName() + ".atomic.exit");
5147     BasicBlock *ContBB = CurBB->splitBasicBlock(CurBB->getTerminator(),
5148                                                 X->getName() + ".atomic.cont");
5149     ContBB->getTerminator()->eraseFromParent();
5150     Builder.restoreIP(AllocaIP);
5151     AllocaInst *NewAtomicAddr = Builder.CreateAlloca(XElemTy);
5152     NewAtomicAddr->setName(X->getName() + "x.new.val");
5153     Builder.SetInsertPoint(ContBB);
5154     llvm::PHINode *PHI = Builder.CreatePHI(OldVal->getType(), 2);
5155     PHI->addIncoming(OldVal, CurBB);
5156     bool IsIntTy = XElemTy->isIntegerTy();
5157     Value *OldExprVal = PHI;
5158     if (!IsIntTy) {
5159       if (XElemTy->isFloatingPointTy()) {
5160         OldExprVal = Builder.CreateBitCast(PHI, XElemTy,
5161                                            X->getName() + ".atomic.fltCast");
5162       } else {
5163         OldExprVal = Builder.CreateIntToPtr(PHI, XElemTy,
5164                                             X->getName() + ".atomic.ptrCast");
5165       }
5166     }
5167 
5168     Value *Upd = UpdateOp(OldExprVal, Builder);
5169     Builder.CreateStore(Upd, NewAtomicAddr);
5170     LoadInst *DesiredVal = Builder.CreateLoad(IntCastTy, NewAtomicAddr);
5171     AtomicOrdering Failure =
5172         llvm::AtomicCmpXchgInst::getStrongestFailureOrdering(AO);
5173     AtomicCmpXchgInst *Result = Builder.CreateAtomicCmpXchg(
5174         X, PHI, DesiredVal, llvm::MaybeAlign(), AO, Failure);
5175     Result->setVolatile(VolatileX);
5176     Value *PreviousVal = Builder.CreateExtractValue(Result, /*Idxs=*/0);
5177     Value *SuccessFailureVal = Builder.CreateExtractValue(Result, /*Idxs=*/1);
5178     PHI->addIncoming(PreviousVal, Builder.GetInsertBlock());
5179     Builder.CreateCondBr(SuccessFailureVal, ExitBB, ContBB);
5180 
5181     Res.first = OldExprVal;
5182     Res.second = Upd;
5183 
5184     // set Insertion point in exit block
5185     if (UnreachableInst *ExitTI =
5186             dyn_cast<UnreachableInst>(ExitBB->getTerminator())) {
5187       CurBBTI->eraseFromParent();
5188       Builder.SetInsertPoint(ExitBB);
5189     } else {
5190       Builder.SetInsertPoint(ExitTI);
5191     }
5192   }
5193 
5194   return Res;
5195 }
5196 
5197 OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::createAtomicCapture(
5198     const LocationDescription &Loc, InsertPointTy AllocaIP, AtomicOpValue &X,
5199     AtomicOpValue &V, Value *Expr, AtomicOrdering AO,
5200     AtomicRMWInst::BinOp RMWOp, AtomicUpdateCallbackTy &UpdateOp,
5201     bool UpdateExpr, bool IsPostfixUpdate, bool IsXBinopExpr) {
5202   if (!updateToLocation(Loc))
5203     return Loc.IP;
5204 
5205   LLVM_DEBUG({
5206     Type *XTy = X.Var->getType();
5207     assert(XTy->isPointerTy() &&
5208            "OMP Atomic expects a pointer to target memory");
5209     Type *XElemTy = X.ElemTy;
5210     assert((XElemTy->isFloatingPointTy() || XElemTy->isIntegerTy() ||
5211             XElemTy->isPointerTy()) &&
5212            "OMP atomic capture expected a scalar type");
5213     assert((RMWOp != AtomicRMWInst::Max) && (RMWOp != AtomicRMWInst::Min) &&
5214            "OpenMP atomic does not support LT or GT operations");
5215   });
5216 
5217   // If UpdateExpr is 'x' updated with some `expr` not based on 'x',
5218   // 'x' is simply atomically rewritten with 'expr'.
5219   AtomicRMWInst::BinOp AtomicOp = (UpdateExpr ? RMWOp : AtomicRMWInst::Xchg);
5220   std::pair<Value *, Value *> Result =
5221       emitAtomicUpdate(AllocaIP, X.Var, X.ElemTy, Expr, AO, AtomicOp, UpdateOp,
5222                        X.IsVolatile, IsXBinopExpr);
5223 
5224   Value *CapturedVal = (IsPostfixUpdate ? Result.first : Result.second);
5225   Builder.CreateStore(CapturedVal, V.Var, V.IsVolatile);
5226 
5227   checkAndEmitFlushAfterAtomic(Loc, AO, AtomicKind::Capture);
5228   return Builder.saveIP();
5229 }
5230 
5231 OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::createAtomicCompare(
5232     const LocationDescription &Loc, AtomicOpValue &X, AtomicOpValue &V,
5233     AtomicOpValue &R, Value *E, Value *D, AtomicOrdering AO,
5234     omp::OMPAtomicCompareOp Op, bool IsXBinopExpr, bool IsPostfixUpdate,
5235     bool IsFailOnly) {
5236 
5237   if (!updateToLocation(Loc))
5238     return Loc.IP;
5239 
5240   assert(X.Var->getType()->isPointerTy() &&
5241          "OMP atomic expects a pointer to target memory");
5242   // compare capture
5243   if (V.Var) {
5244     assert(V.Var->getType()->isPointerTy() && "v.var must be of pointer type");
5245     assert(V.ElemTy == X.ElemTy && "x and v must be of same type");
5246   }
5247 
5248   bool IsInteger = E->getType()->isIntegerTy();
5249 
5250   if (Op == OMPAtomicCompareOp::EQ) {
5251     AtomicOrdering Failure = AtomicCmpXchgInst::getStrongestFailureOrdering(AO);
5252     AtomicCmpXchgInst *Result = nullptr;
5253     if (!IsInteger) {
5254       IntegerType *IntCastTy =
5255           IntegerType::get(M.getContext(), X.ElemTy->getScalarSizeInBits());
5256       Value *EBCast = Builder.CreateBitCast(E, IntCastTy);
5257       Value *DBCast = Builder.CreateBitCast(D, IntCastTy);
5258       Result = Builder.CreateAtomicCmpXchg(X.Var, EBCast, DBCast, MaybeAlign(),
5259                                            AO, Failure);
5260     } else {
5261       Result =
5262           Builder.CreateAtomicCmpXchg(X.Var, E, D, MaybeAlign(), AO, Failure);
5263     }
5264 
5265     if (V.Var) {
5266       Value *OldValue = Builder.CreateExtractValue(Result, /*Idxs=*/0);
5267       if (!IsInteger)
5268         OldValue = Builder.CreateBitCast(OldValue, X.ElemTy);
5269       assert(OldValue->getType() == V.ElemTy &&
5270              "OldValue and V must be of same type");
5271       if (IsPostfixUpdate) {
5272         Builder.CreateStore(OldValue, V.Var, V.IsVolatile);
5273       } else {
5274         Value *SuccessOrFail = Builder.CreateExtractValue(Result, /*Idxs=*/1);
5275         if (IsFailOnly) {
5276           // CurBB----
5277           //   |     |
5278           //   v     |
5279           // ContBB  |
5280           //   |     |
5281           //   v     |
5282           // ExitBB <-
5283           //
5284           // where ContBB only contains the store of old value to 'v'.
5285           BasicBlock *CurBB = Builder.GetInsertBlock();
5286           Instruction *CurBBTI = CurBB->getTerminator();
5287           CurBBTI = CurBBTI ? CurBBTI : Builder.CreateUnreachable();
5288           BasicBlock *ExitBB = CurBB->splitBasicBlock(
5289               CurBBTI, X.Var->getName() + ".atomic.exit");
5290           BasicBlock *ContBB = CurBB->splitBasicBlock(
5291               CurBB->getTerminator(), X.Var->getName() + ".atomic.cont");
5292           ContBB->getTerminator()->eraseFromParent();
5293           CurBB->getTerminator()->eraseFromParent();
5294 
5295           Builder.CreateCondBr(SuccessOrFail, ExitBB, ContBB);
5296 
5297           Builder.SetInsertPoint(ContBB);
5298           Builder.CreateStore(OldValue, V.Var);
5299           Builder.CreateBr(ExitBB);
5300 
5301           if (UnreachableInst *ExitTI =
5302                   dyn_cast<UnreachableInst>(ExitBB->getTerminator())) {
5303             CurBBTI->eraseFromParent();
5304             Builder.SetInsertPoint(ExitBB);
5305           } else {
5306             Builder.SetInsertPoint(ExitTI);
5307           }
5308         } else {
5309           Value *CapturedValue =
5310               Builder.CreateSelect(SuccessOrFail, E, OldValue);
5311           Builder.CreateStore(CapturedValue, V.Var, V.IsVolatile);
5312         }
5313       }
5314     }
5315     // The comparison result has to be stored.
5316     if (R.Var) {
5317       assert(R.Var->getType()->isPointerTy() &&
5318              "r.var must be of pointer type");
5319       assert(R.ElemTy->isIntegerTy() && "r must be of integral type");
5320 
5321       Value *SuccessFailureVal = Builder.CreateExtractValue(Result, /*Idxs=*/1);
5322       Value *ResultCast = R.IsSigned
5323                               ? Builder.CreateSExt(SuccessFailureVal, R.ElemTy)
5324                               : Builder.CreateZExt(SuccessFailureVal, R.ElemTy);
5325       Builder.CreateStore(ResultCast, R.Var, R.IsVolatile);
5326     }
5327   } else {
5328     assert((Op == OMPAtomicCompareOp::MAX || Op == OMPAtomicCompareOp::MIN) &&
5329            "Op should be either max or min at this point");
5330     assert(!IsFailOnly && "IsFailOnly is only valid when the comparison is ==");
5331 
5332     // Reverse the ordop as the OpenMP forms are different from LLVM forms.
5333     // Let's take max as example.
5334     // OpenMP form:
5335     // x = x > expr ? expr : x;
5336     // LLVM form:
5337     // *ptr = *ptr > val ? *ptr : val;
5338     // We need to transform to LLVM form.
5339     // x = x <= expr ? x : expr;
5340     AtomicRMWInst::BinOp NewOp;
5341     if (IsXBinopExpr) {
5342       if (IsInteger) {
5343         if (X.IsSigned)
5344           NewOp = Op == OMPAtomicCompareOp::MAX ? AtomicRMWInst::Min
5345                                                 : AtomicRMWInst::Max;
5346         else
5347           NewOp = Op == OMPAtomicCompareOp::MAX ? AtomicRMWInst::UMin
5348                                                 : AtomicRMWInst::UMax;
5349       } else {
5350         NewOp = Op == OMPAtomicCompareOp::MAX ? AtomicRMWInst::FMin
5351                                               : AtomicRMWInst::FMax;
5352       }
5353     } else {
5354       if (IsInteger) {
5355         if (X.IsSigned)
5356           NewOp = Op == OMPAtomicCompareOp::MAX ? AtomicRMWInst::Max
5357                                                 : AtomicRMWInst::Min;
5358         else
5359           NewOp = Op == OMPAtomicCompareOp::MAX ? AtomicRMWInst::UMax
5360                                                 : AtomicRMWInst::UMin;
5361       } else {
5362         NewOp = Op == OMPAtomicCompareOp::MAX ? AtomicRMWInst::FMax
5363                                               : AtomicRMWInst::FMin;
5364       }
5365     }
5366 
5367     AtomicRMWInst *OldValue =
5368         Builder.CreateAtomicRMW(NewOp, X.Var, E, MaybeAlign(), AO);
5369     if (V.Var) {
5370       Value *CapturedValue = nullptr;
5371       if (IsPostfixUpdate) {
5372         CapturedValue = OldValue;
5373       } else {
5374         CmpInst::Predicate Pred;
5375         switch (NewOp) {
5376         case AtomicRMWInst::Max:
5377           Pred = CmpInst::ICMP_SGT;
5378           break;
5379         case AtomicRMWInst::UMax:
5380           Pred = CmpInst::ICMP_UGT;
5381           break;
5382         case AtomicRMWInst::FMax:
5383           Pred = CmpInst::FCMP_OGT;
5384           break;
5385         case AtomicRMWInst::Min:
5386           Pred = CmpInst::ICMP_SLT;
5387           break;
5388         case AtomicRMWInst::UMin:
5389           Pred = CmpInst::ICMP_ULT;
5390           break;
5391         case AtomicRMWInst::FMin:
5392           Pred = CmpInst::FCMP_OLT;
5393           break;
5394         default:
5395           llvm_unreachable("unexpected comparison op");
5396         }
5397         Value *NonAtomicCmp = Builder.CreateCmp(Pred, OldValue, E);
5398         CapturedValue = Builder.CreateSelect(NonAtomicCmp, E, OldValue);
5399       }
5400       Builder.CreateStore(CapturedValue, V.Var, V.IsVolatile);
5401     }
5402   }
5403 
5404   checkAndEmitFlushAfterAtomic(Loc, AO, AtomicKind::Compare);
5405 
5406   return Builder.saveIP();
5407 }
5408 
5409 GlobalVariable *
5410 OpenMPIRBuilder::createOffloadMapnames(SmallVectorImpl<llvm::Constant *> &Names,
5411                                        std::string VarName) {
5412   llvm::Constant *MapNamesArrayInit = llvm::ConstantArray::get(
5413       llvm::ArrayType::get(
5414           llvm::Type::getInt8Ty(M.getContext())->getPointerTo(), Names.size()),
5415       Names);
5416   auto *MapNamesArrayGlobal = new llvm::GlobalVariable(
5417       M, MapNamesArrayInit->getType(),
5418       /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage, MapNamesArrayInit,
5419       VarName);
5420   return MapNamesArrayGlobal;
5421 }
5422 
5423 // Create all simple and struct types exposed by the runtime and remember
5424 // the llvm::PointerTypes of them for easy access later.
5425 void OpenMPIRBuilder::initializeTypes(Module &M) {
5426   LLVMContext &Ctx = M.getContext();
5427   StructType *T;
5428 #define OMP_TYPE(VarName, InitValue) VarName = InitValue;
5429 #define OMP_ARRAY_TYPE(VarName, ElemTy, ArraySize)                             \
5430   VarName##Ty = ArrayType::get(ElemTy, ArraySize);                             \
5431   VarName##PtrTy = PointerType::getUnqual(VarName##Ty);
5432 #define OMP_FUNCTION_TYPE(VarName, IsVarArg, ReturnType, ...)                  \
5433   VarName = FunctionType::get(ReturnType, {__VA_ARGS__}, IsVarArg);            \
5434   VarName##Ptr = PointerType::getUnqual(VarName);
5435 #define OMP_STRUCT_TYPE(VarName, StructName, Packed, ...)                      \
5436   T = StructType::getTypeByName(Ctx, StructName);                              \
5437   if (!T)                                                                      \
5438     T = StructType::create(Ctx, {__VA_ARGS__}, StructName, Packed);            \
5439   VarName = T;                                                                 \
5440   VarName##Ptr = PointerType::getUnqual(T);
5441 #include "llvm/Frontend/OpenMP/OMPKinds.def"
5442 }
5443 
5444 void OpenMPIRBuilder::OutlineInfo::collectBlocks(
5445     SmallPtrSetImpl<BasicBlock *> &BlockSet,
5446     SmallVectorImpl<BasicBlock *> &BlockVector) {
5447   SmallVector<BasicBlock *, 32> Worklist;
5448   BlockSet.insert(EntryBB);
5449   BlockSet.insert(ExitBB);
5450 
5451   Worklist.push_back(EntryBB);
5452   while (!Worklist.empty()) {
5453     BasicBlock *BB = Worklist.pop_back_val();
5454     BlockVector.push_back(BB);
5455     for (BasicBlock *SuccBB : successors(BB))
5456       if (BlockSet.insert(SuccBB).second)
5457         Worklist.push_back(SuccBB);
5458   }
5459 }
5460 
5461 void OpenMPIRBuilder::createOffloadEntry(Constant *ID, Constant *Addr,
5462                                          uint64_t Size, int32_t Flags,
5463                                          GlobalValue::LinkageTypes) {
5464   if (!Config.isGPU()) {
5465     emitOffloadingEntry(ID, Addr->getName(), Size, Flags);
5466     return;
5467   }
5468   // TODO: Add support for global variables on the device after declare target
5469   // support.
5470   Function *Fn = dyn_cast<Function>(Addr);
5471   if (!Fn)
5472     return;
5473 
5474   Module &M = *(Fn->getParent());
5475   LLVMContext &Ctx = M.getContext();
5476 
5477   // Get "nvvm.annotations" metadata node.
5478   NamedMDNode *MD = M.getOrInsertNamedMetadata("nvvm.annotations");
5479 
5480   Metadata *MDVals[] = {
5481       ConstantAsMetadata::get(Fn), MDString::get(Ctx, "kernel"),
5482       ConstantAsMetadata::get(ConstantInt::get(Type::getInt32Ty(Ctx), 1))};
5483   // Append metadata to nvvm.annotations.
5484   MD->addOperand(MDNode::get(Ctx, MDVals));
5485 
5486   // Add a function attribute for the kernel.
5487   Fn->addFnAttr(Attribute::get(Ctx, "kernel"));
5488   if (Triple(M.getTargetTriple()).isAMDGCN())
5489     Fn->addFnAttr("uniform-work-group-size", "true");
5490   Fn->addFnAttr(Attribute::MustProgress);
5491 }
5492 
5493 // We only generate metadata for function that contain target regions.
5494 void OpenMPIRBuilder::createOffloadEntriesAndInfoMetadata(
5495     EmitMetadataErrorReportFunctionTy &ErrorFn) {
5496 
5497   // If there are no entries, we don't need to do anything.
5498   if (OffloadInfoManager.empty())
5499     return;
5500 
5501   LLVMContext &C = M.getContext();
5502   SmallVector<std::pair<const OffloadEntriesInfoManager::OffloadEntryInfo *,
5503                         TargetRegionEntryInfo>,
5504               16>
5505       OrderedEntries(OffloadInfoManager.size());
5506 
5507   // Auxiliary methods to create metadata values and strings.
5508   auto &&GetMDInt = [this](unsigned V) {
5509     return ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), V));
5510   };
5511 
5512   auto &&GetMDString = [&C](StringRef V) { return MDString::get(C, V); };
5513 
5514   // Create the offloading info metadata node.
5515   NamedMDNode *MD = M.getOrInsertNamedMetadata("omp_offload.info");
5516   auto &&TargetRegionMetadataEmitter =
5517       [&C, MD, &OrderedEntries, &GetMDInt, &GetMDString](
5518           const TargetRegionEntryInfo &EntryInfo,
5519           const OffloadEntriesInfoManager::OffloadEntryInfoTargetRegion &E) {
5520         // Generate metadata for target regions. Each entry of this metadata
5521         // contains:
5522         // - Entry 0 -> Kind of this type of metadata (0).
5523         // - Entry 1 -> Device ID of the file where the entry was identified.
5524         // - Entry 2 -> File ID of the file where the entry was identified.
5525         // - Entry 3 -> Mangled name of the function where the entry was
5526         // identified.
5527         // - Entry 4 -> Line in the file where the entry was identified.
5528         // - Entry 5 -> Count of regions at this DeviceID/FilesID/Line.
5529         // - Entry 6 -> Order the entry was created.
5530         // The first element of the metadata node is the kind.
5531         Metadata *Ops[] = {
5532             GetMDInt(E.getKind()),      GetMDInt(EntryInfo.DeviceID),
5533             GetMDInt(EntryInfo.FileID), GetMDString(EntryInfo.ParentName),
5534             GetMDInt(EntryInfo.Line),   GetMDInt(EntryInfo.Count),
5535             GetMDInt(E.getOrder())};
5536 
5537         // Save this entry in the right position of the ordered entries array.
5538         OrderedEntries[E.getOrder()] = std::make_pair(&E, EntryInfo);
5539 
5540         // Add metadata to the named metadata node.
5541         MD->addOperand(MDNode::get(C, Ops));
5542       };
5543 
5544   OffloadInfoManager.actOnTargetRegionEntriesInfo(TargetRegionMetadataEmitter);
5545 
5546   // Create function that emits metadata for each device global variable entry;
5547   auto &&DeviceGlobalVarMetadataEmitter =
5548       [&C, &OrderedEntries, &GetMDInt, &GetMDString, MD](
5549           StringRef MangledName,
5550           const OffloadEntriesInfoManager::OffloadEntryInfoDeviceGlobalVar &E) {
5551         // Generate metadata for global variables. Each entry of this metadata
5552         // contains:
5553         // - Entry 0 -> Kind of this type of metadata (1).
5554         // - Entry 1 -> Mangled name of the variable.
5555         // - Entry 2 -> Declare target kind.
5556         // - Entry 3 -> Order the entry was created.
5557         // The first element of the metadata node is the kind.
5558         Metadata *Ops[] = {GetMDInt(E.getKind()), GetMDString(MangledName),
5559                            GetMDInt(E.getFlags()), GetMDInt(E.getOrder())};
5560 
5561         // Save this entry in the right position of the ordered entries array.
5562         TargetRegionEntryInfo varInfo(MangledName, 0, 0, 0);
5563         OrderedEntries[E.getOrder()] = std::make_pair(&E, varInfo);
5564 
5565         // Add metadata to the named metadata node.
5566         MD->addOperand(MDNode::get(C, Ops));
5567       };
5568 
5569   OffloadInfoManager.actOnDeviceGlobalVarEntriesInfo(
5570       DeviceGlobalVarMetadataEmitter);
5571 
5572   for (const auto &E : OrderedEntries) {
5573     assert(E.first && "All ordered entries must exist!");
5574     if (const auto *CE =
5575             dyn_cast<OffloadEntriesInfoManager::OffloadEntryInfoTargetRegion>(
5576                 E.first)) {
5577       if (!CE->getID() || !CE->getAddress()) {
5578         // Do not blame the entry if the parent funtion is not emitted.
5579         TargetRegionEntryInfo EntryInfo = E.second;
5580         StringRef FnName = EntryInfo.ParentName;
5581         if (!M.getNamedValue(FnName))
5582           continue;
5583         ErrorFn(EMIT_MD_TARGET_REGION_ERROR, EntryInfo);
5584         continue;
5585       }
5586       createOffloadEntry(CE->getID(), CE->getAddress(),
5587                          /*Size=*/0, CE->getFlags(),
5588                          GlobalValue::WeakAnyLinkage);
5589     } else if (const auto *CE = dyn_cast<
5590                    OffloadEntriesInfoManager::OffloadEntryInfoDeviceGlobalVar>(
5591                    E.first)) {
5592       OffloadEntriesInfoManager::OMPTargetGlobalVarEntryKind Flags =
5593           static_cast<OffloadEntriesInfoManager::OMPTargetGlobalVarEntryKind>(
5594               CE->getFlags());
5595       switch (Flags) {
5596       case OffloadEntriesInfoManager::OMPTargetGlobalVarEntryEnter:
5597       case OffloadEntriesInfoManager::OMPTargetGlobalVarEntryTo:
5598         if (Config.isTargetDevice() && Config.hasRequiresUnifiedSharedMemory())
5599           continue;
5600         if (!CE->getAddress()) {
5601           ErrorFn(EMIT_MD_DECLARE_TARGET_ERROR, E.second);
5602           continue;
5603         }
5604         // The vaiable has no definition - no need to add the entry.
5605         if (CE->getVarSize() == 0)
5606           continue;
5607         break;
5608       case OffloadEntriesInfoManager::OMPTargetGlobalVarEntryLink:
5609         assert(((Config.isTargetDevice() && !CE->getAddress()) ||
5610                 (!Config.isTargetDevice() && CE->getAddress())) &&
5611                "Declaret target link address is set.");
5612         if (Config.isTargetDevice())
5613           continue;
5614         if (!CE->getAddress()) {
5615           ErrorFn(EMIT_MD_GLOBAL_VAR_LINK_ERROR, TargetRegionEntryInfo());
5616           continue;
5617         }
5618         break;
5619       default:
5620         break;
5621       }
5622 
5623       // Hidden or internal symbols on the device are not externally visible.
5624       // We should not attempt to register them by creating an offloading
5625       // entry.
5626       if (auto *GV = dyn_cast<GlobalValue>(CE->getAddress()))
5627         if (GV->hasLocalLinkage() || GV->hasHiddenVisibility())
5628           continue;
5629 
5630       createOffloadEntry(CE->getAddress(), CE->getAddress(), CE->getVarSize(),
5631                          Flags, CE->getLinkage());
5632 
5633     } else {
5634       llvm_unreachable("Unsupported entry kind.");
5635     }
5636   }
5637 }
5638 
5639 void TargetRegionEntryInfo::getTargetRegionEntryFnName(
5640     SmallVectorImpl<char> &Name, StringRef ParentName, unsigned DeviceID,
5641     unsigned FileID, unsigned Line, unsigned Count) {
5642   raw_svector_ostream OS(Name);
5643   OS << "__omp_offloading" << llvm::format("_%x", DeviceID)
5644      << llvm::format("_%x_", FileID) << ParentName << "_l" << Line;
5645   if (Count)
5646     OS << "_" << Count;
5647 }
5648 
5649 void OffloadEntriesInfoManager::getTargetRegionEntryFnName(
5650     SmallVectorImpl<char> &Name, const TargetRegionEntryInfo &EntryInfo) {
5651   unsigned NewCount = getTargetRegionEntryInfoCount(EntryInfo);
5652   TargetRegionEntryInfo::getTargetRegionEntryFnName(
5653       Name, EntryInfo.ParentName, EntryInfo.DeviceID, EntryInfo.FileID,
5654       EntryInfo.Line, NewCount);
5655 }
5656 
5657 TargetRegionEntryInfo
5658 OpenMPIRBuilder::getTargetEntryUniqueInfo(FileIdentifierInfoCallbackTy CallBack,
5659                                           StringRef ParentName) {
5660   sys::fs::UniqueID ID;
5661   auto FileIDInfo = CallBack();
5662   if (auto EC = sys::fs::getUniqueID(std::get<0>(FileIDInfo), ID)) {
5663     report_fatal_error(("Unable to get unique ID for file, during "
5664                         "getTargetEntryUniqueInfo, error message: " +
5665                         EC.message())
5666                            .c_str());
5667   }
5668 
5669   return TargetRegionEntryInfo(ParentName, ID.getDevice(), ID.getFile(),
5670                                std::get<1>(FileIDInfo));
5671 }
5672 
5673 Constant *OpenMPIRBuilder::getAddrOfDeclareTargetVar(
5674     OffloadEntriesInfoManager::OMPTargetGlobalVarEntryKind CaptureClause,
5675     OffloadEntriesInfoManager::OMPTargetDeviceClauseKind DeviceClause,
5676     bool IsDeclaration, bool IsExternallyVisible,
5677     TargetRegionEntryInfo EntryInfo, StringRef MangledName,
5678     std::vector<GlobalVariable *> &GeneratedRefs, bool OpenMPSIMD,
5679     std::vector<Triple> TargetTriple, Type *LlvmPtrTy,
5680     std::function<Constant *()> GlobalInitializer,
5681     std::function<GlobalValue::LinkageTypes()> VariableLinkage) {
5682   // TODO: convert this to utilise the IRBuilder Config rather than
5683   // a passed down argument.
5684   if (OpenMPSIMD)
5685     return nullptr;
5686 
5687   if (CaptureClause == OffloadEntriesInfoManager::OMPTargetGlobalVarEntryLink ||
5688       ((CaptureClause == OffloadEntriesInfoManager::OMPTargetGlobalVarEntryTo ||
5689         CaptureClause ==
5690             OffloadEntriesInfoManager::OMPTargetGlobalVarEntryEnter) &&
5691        Config.hasRequiresUnifiedSharedMemory())) {
5692     SmallString<64> PtrName;
5693     {
5694       raw_svector_ostream OS(PtrName);
5695       OS << MangledName;
5696       if (!IsExternallyVisible)
5697         OS << format("_%x", EntryInfo.FileID);
5698       OS << "_decl_tgt_ref_ptr";
5699     }
5700 
5701     Value *Ptr = M.getNamedValue(PtrName);
5702 
5703     if (!Ptr) {
5704       GlobalValue *GlobalValue = M.getNamedValue(MangledName);
5705       Ptr = getOrCreateInternalVariable(LlvmPtrTy, PtrName);
5706 
5707       auto *GV = cast<GlobalVariable>(Ptr);
5708       GV->setLinkage(GlobalValue::WeakAnyLinkage);
5709 
5710       if (!Config.isTargetDevice()) {
5711         if (GlobalInitializer)
5712           GV->setInitializer(GlobalInitializer());
5713         else
5714           GV->setInitializer(GlobalValue);
5715       }
5716 
5717       registerTargetGlobalVariable(
5718           CaptureClause, DeviceClause, IsDeclaration, IsExternallyVisible,
5719           EntryInfo, MangledName, GeneratedRefs, OpenMPSIMD, TargetTriple,
5720           GlobalInitializer, VariableLinkage, LlvmPtrTy, cast<Constant>(Ptr));
5721     }
5722 
5723     return cast<Constant>(Ptr);
5724   }
5725 
5726   return nullptr;
5727 }
5728 
5729 void OpenMPIRBuilder::registerTargetGlobalVariable(
5730     OffloadEntriesInfoManager::OMPTargetGlobalVarEntryKind CaptureClause,
5731     OffloadEntriesInfoManager::OMPTargetDeviceClauseKind DeviceClause,
5732     bool IsDeclaration, bool IsExternallyVisible,
5733     TargetRegionEntryInfo EntryInfo, StringRef MangledName,
5734     std::vector<GlobalVariable *> &GeneratedRefs, bool OpenMPSIMD,
5735     std::vector<Triple> TargetTriple,
5736     std::function<Constant *()> GlobalInitializer,
5737     std::function<GlobalValue::LinkageTypes()> VariableLinkage, Type *LlvmPtrTy,
5738     Constant *Addr) {
5739   if (DeviceClause != OffloadEntriesInfoManager::OMPTargetDeviceClauseAny ||
5740       (TargetTriple.empty() && !Config.isTargetDevice()))
5741     return;
5742 
5743   OffloadEntriesInfoManager::OMPTargetGlobalVarEntryKind Flags;
5744   StringRef VarName;
5745   int64_t VarSize;
5746   GlobalValue::LinkageTypes Linkage;
5747 
5748   if ((CaptureClause == OffloadEntriesInfoManager::OMPTargetGlobalVarEntryTo ||
5749        CaptureClause ==
5750            OffloadEntriesInfoManager::OMPTargetGlobalVarEntryEnter) &&
5751       !Config.hasRequiresUnifiedSharedMemory()) {
5752     Flags = OffloadEntriesInfoManager::OMPTargetGlobalVarEntryTo;
5753     VarName = MangledName;
5754     GlobalValue *LlvmVal = M.getNamedValue(VarName);
5755 
5756     if (!IsDeclaration)
5757       VarSize = divideCeil(
5758           M.getDataLayout().getTypeSizeInBits(LlvmVal->getValueType()), 8);
5759     else
5760       VarSize = 0;
5761     Linkage = (VariableLinkage) ? VariableLinkage() : LlvmVal->getLinkage();
5762 
5763     // This is a workaround carried over from Clang which prevents undesired
5764     // optimisation of internal variables.
5765     if (Config.isTargetDevice() &&
5766         (!IsExternallyVisible || Linkage == GlobalValue::LinkOnceODRLinkage)) {
5767       // Do not create a "ref-variable" if the original is not also available
5768       // on the host.
5769       if (!OffloadInfoManager.hasDeviceGlobalVarEntryInfo(VarName))
5770         return;
5771 
5772       std::string RefName = createPlatformSpecificName({VarName, "ref"});
5773 
5774       if (!M.getNamedValue(RefName)) {
5775         Constant *AddrRef =
5776             getOrCreateInternalVariable(Addr->getType(), RefName);
5777         auto *GvAddrRef = cast<GlobalVariable>(AddrRef);
5778         GvAddrRef->setConstant(true);
5779         GvAddrRef->setLinkage(GlobalValue::InternalLinkage);
5780         GvAddrRef->setInitializer(Addr);
5781         GeneratedRefs.push_back(GvAddrRef);
5782       }
5783     }
5784   } else {
5785     if (CaptureClause == OffloadEntriesInfoManager::OMPTargetGlobalVarEntryLink)
5786       Flags = OffloadEntriesInfoManager::OMPTargetGlobalVarEntryLink;
5787     else
5788       Flags = OffloadEntriesInfoManager::OMPTargetGlobalVarEntryTo;
5789 
5790     if (Config.isTargetDevice()) {
5791       VarName = (Addr) ? Addr->getName() : "";
5792       Addr = nullptr;
5793     } else {
5794       Addr = getAddrOfDeclareTargetVar(
5795           CaptureClause, DeviceClause, IsDeclaration, IsExternallyVisible,
5796           EntryInfo, MangledName, GeneratedRefs, OpenMPSIMD, TargetTriple,
5797           LlvmPtrTy, GlobalInitializer, VariableLinkage);
5798       VarName = (Addr) ? Addr->getName() : "";
5799     }
5800     VarSize = M.getDataLayout().getPointerSize();
5801     Linkage = GlobalValue::WeakAnyLinkage;
5802   }
5803 
5804   OffloadInfoManager.registerDeviceGlobalVarEntryInfo(VarName, Addr, VarSize,
5805                                                       Flags, Linkage);
5806 }
5807 
5808 /// Loads all the offload entries information from the host IR
5809 /// metadata.
5810 void OpenMPIRBuilder::loadOffloadInfoMetadata(Module &M) {
5811   // If we are in target mode, load the metadata from the host IR. This code has
5812   // to match the metadata creation in createOffloadEntriesAndInfoMetadata().
5813 
5814   NamedMDNode *MD = M.getNamedMetadata(ompOffloadInfoName);
5815   if (!MD)
5816     return;
5817 
5818   for (MDNode *MN : MD->operands()) {
5819     auto &&GetMDInt = [MN](unsigned Idx) {
5820       auto *V = cast<ConstantAsMetadata>(MN->getOperand(Idx));
5821       return cast<ConstantInt>(V->getValue())->getZExtValue();
5822     };
5823 
5824     auto &&GetMDString = [MN](unsigned Idx) {
5825       auto *V = cast<MDString>(MN->getOperand(Idx));
5826       return V->getString();
5827     };
5828 
5829     switch (GetMDInt(0)) {
5830     default:
5831       llvm_unreachable("Unexpected metadata!");
5832       break;
5833     case OffloadEntriesInfoManager::OffloadEntryInfo::
5834         OffloadingEntryInfoTargetRegion: {
5835       TargetRegionEntryInfo EntryInfo(/*ParentName=*/GetMDString(3),
5836                                       /*DeviceID=*/GetMDInt(1),
5837                                       /*FileID=*/GetMDInt(2),
5838                                       /*Line=*/GetMDInt(4),
5839                                       /*Count=*/GetMDInt(5));
5840       OffloadInfoManager.initializeTargetRegionEntryInfo(EntryInfo,
5841                                                          /*Order=*/GetMDInt(6));
5842       break;
5843     }
5844     case OffloadEntriesInfoManager::OffloadEntryInfo::
5845         OffloadingEntryInfoDeviceGlobalVar:
5846       OffloadInfoManager.initializeDeviceGlobalVarEntryInfo(
5847           /*MangledName=*/GetMDString(1),
5848           static_cast<OffloadEntriesInfoManager::OMPTargetGlobalVarEntryKind>(
5849               /*Flags=*/GetMDInt(2)),
5850           /*Order=*/GetMDInt(3));
5851       break;
5852     }
5853   }
5854 }
5855 
5856 bool OffloadEntriesInfoManager::empty() const {
5857   return OffloadEntriesTargetRegion.empty() &&
5858          OffloadEntriesDeviceGlobalVar.empty();
5859 }
5860 
5861 unsigned OffloadEntriesInfoManager::getTargetRegionEntryInfoCount(
5862     const TargetRegionEntryInfo &EntryInfo) const {
5863   auto It = OffloadEntriesTargetRegionCount.find(
5864       getTargetRegionEntryCountKey(EntryInfo));
5865   if (It == OffloadEntriesTargetRegionCount.end())
5866     return 0;
5867   return It->second;
5868 }
5869 
5870 void OffloadEntriesInfoManager::incrementTargetRegionEntryInfoCount(
5871     const TargetRegionEntryInfo &EntryInfo) {
5872   OffloadEntriesTargetRegionCount[getTargetRegionEntryCountKey(EntryInfo)] =
5873       EntryInfo.Count + 1;
5874 }
5875 
5876 /// Initialize target region entry.
5877 void OffloadEntriesInfoManager::initializeTargetRegionEntryInfo(
5878     const TargetRegionEntryInfo &EntryInfo, unsigned Order) {
5879   OffloadEntriesTargetRegion[EntryInfo] =
5880       OffloadEntryInfoTargetRegion(Order, /*Addr=*/nullptr, /*ID=*/nullptr,
5881                                    OMPTargetRegionEntryTargetRegion);
5882   ++OffloadingEntriesNum;
5883 }
5884 
5885 void OffloadEntriesInfoManager::registerTargetRegionEntryInfo(
5886     TargetRegionEntryInfo EntryInfo, Constant *Addr, Constant *ID,
5887     OMPTargetRegionEntryKind Flags) {
5888   assert(EntryInfo.Count == 0 && "expected default EntryInfo");
5889 
5890   // Update the EntryInfo with the next available count for this location.
5891   EntryInfo.Count = getTargetRegionEntryInfoCount(EntryInfo);
5892 
5893   // If we are emitting code for a target, the entry is already initialized,
5894   // only has to be registered.
5895   if (OMPBuilder->Config.isTargetDevice()) {
5896     // This could happen if the device compilation is invoked standalone.
5897     if (!hasTargetRegionEntryInfo(EntryInfo)) {
5898       return;
5899     }
5900     auto &Entry = OffloadEntriesTargetRegion[EntryInfo];
5901     Entry.setAddress(Addr);
5902     Entry.setID(ID);
5903     Entry.setFlags(Flags);
5904   } else {
5905     if (Flags == OffloadEntriesInfoManager::OMPTargetRegionEntryTargetRegion &&
5906         hasTargetRegionEntryInfo(EntryInfo, /*IgnoreAddressId*/ true))
5907       return;
5908     assert(!hasTargetRegionEntryInfo(EntryInfo) &&
5909            "Target region entry already registered!");
5910     OffloadEntryInfoTargetRegion Entry(OffloadingEntriesNum, Addr, ID, Flags);
5911     OffloadEntriesTargetRegion[EntryInfo] = Entry;
5912     ++OffloadingEntriesNum;
5913   }
5914   incrementTargetRegionEntryInfoCount(EntryInfo);
5915 }
5916 
5917 bool OffloadEntriesInfoManager::hasTargetRegionEntryInfo(
5918     TargetRegionEntryInfo EntryInfo, bool IgnoreAddressId) const {
5919 
5920   // Update the EntryInfo with the next available count for this location.
5921   EntryInfo.Count = getTargetRegionEntryInfoCount(EntryInfo);
5922 
5923   auto It = OffloadEntriesTargetRegion.find(EntryInfo);
5924   if (It == OffloadEntriesTargetRegion.end()) {
5925     return false;
5926   }
5927   // Fail if this entry is already registered.
5928   if (!IgnoreAddressId && (It->second.getAddress() || It->second.getID()))
5929     return false;
5930   return true;
5931 }
5932 
5933 void OffloadEntriesInfoManager::actOnTargetRegionEntriesInfo(
5934     const OffloadTargetRegionEntryInfoActTy &Action) {
5935   // Scan all target region entries and perform the provided action.
5936   for (const auto &It : OffloadEntriesTargetRegion) {
5937     Action(It.first, It.second);
5938   }
5939 }
5940 
5941 void OffloadEntriesInfoManager::initializeDeviceGlobalVarEntryInfo(
5942     StringRef Name, OMPTargetGlobalVarEntryKind Flags, unsigned Order) {
5943   OffloadEntriesDeviceGlobalVar.try_emplace(Name, Order, Flags);
5944   ++OffloadingEntriesNum;
5945 }
5946 
5947 void OffloadEntriesInfoManager::registerDeviceGlobalVarEntryInfo(
5948     StringRef VarName, Constant *Addr, int64_t VarSize,
5949     OMPTargetGlobalVarEntryKind Flags, GlobalValue::LinkageTypes Linkage) {
5950   if (OMPBuilder->Config.isTargetDevice()) {
5951     // This could happen if the device compilation is invoked standalone.
5952     if (!hasDeviceGlobalVarEntryInfo(VarName))
5953       return;
5954     auto &Entry = OffloadEntriesDeviceGlobalVar[VarName];
5955     if (Entry.getAddress() && hasDeviceGlobalVarEntryInfo(VarName)) {
5956       if (Entry.getVarSize() == 0) {
5957         Entry.setVarSize(VarSize);
5958         Entry.setLinkage(Linkage);
5959       }
5960       return;
5961     }
5962     Entry.setVarSize(VarSize);
5963     Entry.setLinkage(Linkage);
5964     Entry.setAddress(Addr);
5965   } else {
5966     if (hasDeviceGlobalVarEntryInfo(VarName)) {
5967       auto &Entry = OffloadEntriesDeviceGlobalVar[VarName];
5968       assert(Entry.isValid() && Entry.getFlags() == Flags &&
5969              "Entry not initialized!");
5970       if (Entry.getVarSize() == 0) {
5971         Entry.setVarSize(VarSize);
5972         Entry.setLinkage(Linkage);
5973       }
5974       return;
5975     }
5976     OffloadEntriesDeviceGlobalVar.try_emplace(VarName, OffloadingEntriesNum,
5977                                               Addr, VarSize, Flags, Linkage);
5978     ++OffloadingEntriesNum;
5979   }
5980 }
5981 
5982 void OffloadEntriesInfoManager::actOnDeviceGlobalVarEntriesInfo(
5983     const OffloadDeviceGlobalVarEntryInfoActTy &Action) {
5984   // Scan all target region entries and perform the provided action.
5985   for (const auto &E : OffloadEntriesDeviceGlobalVar)
5986     Action(E.getKey(), E.getValue());
5987 }
5988 
5989 void CanonicalLoopInfo::collectControlBlocks(
5990     SmallVectorImpl<BasicBlock *> &BBs) {
5991   // We only count those BBs as control block for which we do not need to
5992   // reverse the CFG, i.e. not the loop body which can contain arbitrary control
5993   // flow. For consistency, this also means we do not add the Body block, which
5994   // is just the entry to the body code.
5995   BBs.reserve(BBs.size() + 6);
5996   BBs.append({getPreheader(), Header, Cond, Latch, Exit, getAfter()});
5997 }
5998 
5999 BasicBlock *CanonicalLoopInfo::getPreheader() const {
6000   assert(isValid() && "Requires a valid canonical loop");
6001   for (BasicBlock *Pred : predecessors(Header)) {
6002     if (Pred != Latch)
6003       return Pred;
6004   }
6005   llvm_unreachable("Missing preheader");
6006 }
6007 
6008 void CanonicalLoopInfo::setTripCount(Value *TripCount) {
6009   assert(isValid() && "Requires a valid canonical loop");
6010 
6011   Instruction *CmpI = &getCond()->front();
6012   assert(isa<CmpInst>(CmpI) && "First inst must compare IV with TripCount");
6013   CmpI->setOperand(1, TripCount);
6014 
6015 #ifndef NDEBUG
6016   assertOK();
6017 #endif
6018 }
6019 
6020 void CanonicalLoopInfo::mapIndVar(
6021     llvm::function_ref<Value *(Instruction *)> Updater) {
6022   assert(isValid() && "Requires a valid canonical loop");
6023 
6024   Instruction *OldIV = getIndVar();
6025 
6026   // Record all uses excluding those introduced by the updater. Uses by the
6027   // CanonicalLoopInfo itself to keep track of the number of iterations are
6028   // excluded.
6029   SmallVector<Use *> ReplacableUses;
6030   for (Use &U : OldIV->uses()) {
6031     auto *User = dyn_cast<Instruction>(U.getUser());
6032     if (!User)
6033       continue;
6034     if (User->getParent() == getCond())
6035       continue;
6036     if (User->getParent() == getLatch())
6037       continue;
6038     ReplacableUses.push_back(&U);
6039   }
6040 
6041   // Run the updater that may introduce new uses
6042   Value *NewIV = Updater(OldIV);
6043 
6044   // Replace the old uses with the value returned by the updater.
6045   for (Use *U : ReplacableUses)
6046     U->set(NewIV);
6047 
6048 #ifndef NDEBUG
6049   assertOK();
6050 #endif
6051 }
6052 
6053 void CanonicalLoopInfo::assertOK() const {
6054 #ifndef NDEBUG
6055   // No constraints if this object currently does not describe a loop.
6056   if (!isValid())
6057     return;
6058 
6059   BasicBlock *Preheader = getPreheader();
6060   BasicBlock *Body = getBody();
6061   BasicBlock *After = getAfter();
6062 
6063   // Verify standard control-flow we use for OpenMP loops.
6064   assert(Preheader);
6065   assert(isa<BranchInst>(Preheader->getTerminator()) &&
6066          "Preheader must terminate with unconditional branch");
6067   assert(Preheader->getSingleSuccessor() == Header &&
6068          "Preheader must jump to header");
6069 
6070   assert(Header);
6071   assert(isa<BranchInst>(Header->getTerminator()) &&
6072          "Header must terminate with unconditional branch");
6073   assert(Header->getSingleSuccessor() == Cond &&
6074          "Header must jump to exiting block");
6075 
6076   assert(Cond);
6077   assert(Cond->getSinglePredecessor() == Header &&
6078          "Exiting block only reachable from header");
6079 
6080   assert(isa<BranchInst>(Cond->getTerminator()) &&
6081          "Exiting block must terminate with conditional branch");
6082   assert(size(successors(Cond)) == 2 &&
6083          "Exiting block must have two successors");
6084   assert(cast<BranchInst>(Cond->getTerminator())->getSuccessor(0) == Body &&
6085          "Exiting block's first successor jump to the body");
6086   assert(cast<BranchInst>(Cond->getTerminator())->getSuccessor(1) == Exit &&
6087          "Exiting block's second successor must exit the loop");
6088 
6089   assert(Body);
6090   assert(Body->getSinglePredecessor() == Cond &&
6091          "Body only reachable from exiting block");
6092   assert(!isa<PHINode>(Body->front()));
6093 
6094   assert(Latch);
6095   assert(isa<BranchInst>(Latch->getTerminator()) &&
6096          "Latch must terminate with unconditional branch");
6097   assert(Latch->getSingleSuccessor() == Header && "Latch must jump to header");
6098   // TODO: To support simple redirecting of the end of the body code that has
6099   // multiple; introduce another auxiliary basic block like preheader and after.
6100   assert(Latch->getSinglePredecessor() != nullptr);
6101   assert(!isa<PHINode>(Latch->front()));
6102 
6103   assert(Exit);
6104   assert(isa<BranchInst>(Exit->getTerminator()) &&
6105          "Exit block must terminate with unconditional branch");
6106   assert(Exit->getSingleSuccessor() == After &&
6107          "Exit block must jump to after block");
6108 
6109   assert(After);
6110   assert(After->getSinglePredecessor() == Exit &&
6111          "After block only reachable from exit block");
6112   assert(After->empty() || !isa<PHINode>(After->front()));
6113 
6114   Instruction *IndVar = getIndVar();
6115   assert(IndVar && "Canonical induction variable not found?");
6116   assert(isa<IntegerType>(IndVar->getType()) &&
6117          "Induction variable must be an integer");
6118   assert(cast<PHINode>(IndVar)->getParent() == Header &&
6119          "Induction variable must be a PHI in the loop header");
6120   assert(cast<PHINode>(IndVar)->getIncomingBlock(0) == Preheader);
6121   assert(
6122       cast<ConstantInt>(cast<PHINode>(IndVar)->getIncomingValue(0))->isZero());
6123   assert(cast<PHINode>(IndVar)->getIncomingBlock(1) == Latch);
6124 
6125   auto *NextIndVar = cast<PHINode>(IndVar)->getIncomingValue(1);
6126   assert(cast<Instruction>(NextIndVar)->getParent() == Latch);
6127   assert(cast<BinaryOperator>(NextIndVar)->getOpcode() == BinaryOperator::Add);
6128   assert(cast<BinaryOperator>(NextIndVar)->getOperand(0) == IndVar);
6129   assert(cast<ConstantInt>(cast<BinaryOperator>(NextIndVar)->getOperand(1))
6130              ->isOne());
6131 
6132   Value *TripCount = getTripCount();
6133   assert(TripCount && "Loop trip count not found?");
6134   assert(IndVar->getType() == TripCount->getType() &&
6135          "Trip count and induction variable must have the same type");
6136 
6137   auto *CmpI = cast<CmpInst>(&Cond->front());
6138   assert(CmpI->getPredicate() == CmpInst::ICMP_ULT &&
6139          "Exit condition must be a signed less-than comparison");
6140   assert(CmpI->getOperand(0) == IndVar &&
6141          "Exit condition must compare the induction variable");
6142   assert(CmpI->getOperand(1) == TripCount &&
6143          "Exit condition must compare with the trip count");
6144 #endif
6145 }
6146 
6147 void CanonicalLoopInfo::invalidate() {
6148   Header = nullptr;
6149   Cond = nullptr;
6150   Latch = nullptr;
6151   Exit = nullptr;
6152 }
6153