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