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::emitOffloadingEntry(Constant *Addr, StringRef Name,
757                                           uint64_t Size, int32_t Flags,
758                                           StringRef SectionName) {
759   Type *Int8PtrTy = Type::getInt8PtrTy(M.getContext());
760   Type *Int32Ty = Type::getInt32Ty(M.getContext());
761   Type *SizeTy = M.getDataLayout().getIntPtrType(M.getContext());
762 
763   Constant *AddrName = ConstantDataArray::getString(M.getContext(), Name);
764 
765   // Create the constant string used to look up the symbol in the device.
766   auto *Str =
767       new llvm::GlobalVariable(M, AddrName->getType(), /*isConstant=*/true,
768                                llvm::GlobalValue::InternalLinkage, AddrName,
769                                ".omp_offloading.entry_name");
770   Str->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
771 
772   // Construct the offloading entry.
773   Constant *EntryData[] = {
774       ConstantExpr::getPointerBitCastOrAddrSpaceCast(Addr, Int8PtrTy),
775       ConstantExpr::getPointerBitCastOrAddrSpaceCast(Str, Int8PtrTy),
776       ConstantInt::get(SizeTy, Size),
777       ConstantInt::get(Int32Ty, Flags),
778       ConstantInt::get(Int32Ty, 0),
779   };
780   Constant *EntryInitializer =
781       ConstantStruct::get(OpenMPIRBuilder::OffloadEntry, EntryData);
782 
783   auto *Entry = new GlobalVariable(
784       M, OpenMPIRBuilder::OffloadEntry,
785       /* isConstant = */ true, GlobalValue::WeakAnyLinkage, EntryInitializer,
786       ".omp_offloading.entry." + Name, nullptr, GlobalValue::NotThreadLocal,
787       M.getDataLayout().getDefaultGlobalsAddressSpace());
788 
789   // The entry has to be created in the section the linker expects it to be.
790   Entry->setSection(SectionName);
791   Entry->setAlignment(Align(1));
792 }
793 
794 void OpenMPIRBuilder::emitCancelationCheckImpl(Value *CancelFlag,
795                                                omp::Directive CanceledDirective,
796                                                FinalizeCallbackTy ExitCB) {
797   assert(isLastFinalizationInfoCancellable(CanceledDirective) &&
798          "Unexpected cancellation!");
799 
800   // For a cancel barrier we create two new blocks.
801   BasicBlock *BB = Builder.GetInsertBlock();
802   BasicBlock *NonCancellationBlock;
803   if (Builder.GetInsertPoint() == BB->end()) {
804     // TODO: This branch will not be needed once we moved to the
805     // OpenMPIRBuilder codegen completely.
806     NonCancellationBlock = BasicBlock::Create(
807         BB->getContext(), BB->getName() + ".cont", BB->getParent());
808   } else {
809     NonCancellationBlock = SplitBlock(BB, &*Builder.GetInsertPoint());
810     BB->getTerminator()->eraseFromParent();
811     Builder.SetInsertPoint(BB);
812   }
813   BasicBlock *CancellationBlock = BasicBlock::Create(
814       BB->getContext(), BB->getName() + ".cncl", BB->getParent());
815 
816   // Jump to them based on the return value.
817   Value *Cmp = Builder.CreateIsNull(CancelFlag);
818   Builder.CreateCondBr(Cmp, NonCancellationBlock, CancellationBlock,
819                        /* TODO weight */ nullptr, nullptr);
820 
821   // From the cancellation block we finalize all variables and go to the
822   // post finalization block that is known to the FiniCB callback.
823   Builder.SetInsertPoint(CancellationBlock);
824   if (ExitCB)
825     ExitCB(Builder.saveIP());
826   auto &FI = FinalizationStack.back();
827   FI.FiniCB(Builder.saveIP());
828 
829   // The continuation block is where code generation continues.
830   Builder.SetInsertPoint(NonCancellationBlock, NonCancellationBlock->begin());
831 }
832 
833 IRBuilder<>::InsertPoint OpenMPIRBuilder::createParallel(
834     const LocationDescription &Loc, InsertPointTy OuterAllocaIP,
835     BodyGenCallbackTy BodyGenCB, PrivatizeCallbackTy PrivCB,
836     FinalizeCallbackTy FiniCB, Value *IfCondition, Value *NumThreads,
837     omp::ProcBindKind ProcBind, bool IsCancellable) {
838   assert(!isConflictIP(Loc.IP, OuterAllocaIP) && "IPs must not be ambiguous");
839 
840   if (!updateToLocation(Loc))
841     return Loc.IP;
842 
843   uint32_t SrcLocStrSize;
844   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
845   Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
846   Value *ThreadID = getOrCreateThreadID(Ident);
847 
848   if (NumThreads) {
849     // Build call __kmpc_push_num_threads(&Ident, global_tid, num_threads)
850     Value *Args[] = {
851         Ident, ThreadID,
852         Builder.CreateIntCast(NumThreads, Int32, /*isSigned*/ false)};
853     Builder.CreateCall(
854         getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_push_num_threads), Args);
855   }
856 
857   if (ProcBind != OMP_PROC_BIND_default) {
858     // Build call __kmpc_push_proc_bind(&Ident, global_tid, proc_bind)
859     Value *Args[] = {
860         Ident, ThreadID,
861         ConstantInt::get(Int32, unsigned(ProcBind), /*isSigned=*/true)};
862     Builder.CreateCall(
863         getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_push_proc_bind), Args);
864   }
865 
866   BasicBlock *InsertBB = Builder.GetInsertBlock();
867   Function *OuterFn = InsertBB->getParent();
868 
869   // Save the outer alloca block because the insertion iterator may get
870   // invalidated and we still need this later.
871   BasicBlock *OuterAllocaBlock = OuterAllocaIP.getBlock();
872 
873   // Vector to remember instructions we used only during the modeling but which
874   // we want to delete at the end.
875   SmallVector<Instruction *, 4> ToBeDeleted;
876 
877   // Change the location to the outer alloca insertion point to create and
878   // initialize the allocas we pass into the parallel region.
879   Builder.restoreIP(OuterAllocaIP);
880   AllocaInst *TIDAddr = Builder.CreateAlloca(Int32, nullptr, "tid.addr");
881   AllocaInst *ZeroAddr = Builder.CreateAlloca(Int32, nullptr, "zero.addr");
882 
883   // If there is an if condition we actually use the TIDAddr and ZeroAddr in the
884   // program, otherwise we only need them for modeling purposes to get the
885   // associated arguments in the outlined function. In the former case,
886   // initialize the allocas properly, in the latter case, delete them later.
887   if (IfCondition) {
888     Builder.CreateStore(Constant::getNullValue(Int32), TIDAddr);
889     Builder.CreateStore(Constant::getNullValue(Int32), ZeroAddr);
890   } else {
891     ToBeDeleted.push_back(TIDAddr);
892     ToBeDeleted.push_back(ZeroAddr);
893   }
894 
895   // Create an artificial insertion point that will also ensure the blocks we
896   // are about to split are not degenerated.
897   auto *UI = new UnreachableInst(Builder.getContext(), InsertBB);
898 
899   Instruction *ThenTI = UI, *ElseTI = nullptr;
900   if (IfCondition)
901     SplitBlockAndInsertIfThenElse(IfCondition, UI, &ThenTI, &ElseTI);
902 
903   BasicBlock *ThenBB = ThenTI->getParent();
904   BasicBlock *PRegEntryBB = ThenBB->splitBasicBlock(ThenTI, "omp.par.entry");
905   BasicBlock *PRegBodyBB =
906       PRegEntryBB->splitBasicBlock(ThenTI, "omp.par.region");
907   BasicBlock *PRegPreFiniBB =
908       PRegBodyBB->splitBasicBlock(ThenTI, "omp.par.pre_finalize");
909   BasicBlock *PRegExitBB =
910       PRegPreFiniBB->splitBasicBlock(ThenTI, "omp.par.exit");
911 
912   auto FiniCBWrapper = [&](InsertPointTy IP) {
913     // Hide "open-ended" blocks from the given FiniCB by setting the right jump
914     // target to the region exit block.
915     if (IP.getBlock()->end() == IP.getPoint()) {
916       IRBuilder<>::InsertPointGuard IPG(Builder);
917       Builder.restoreIP(IP);
918       Instruction *I = Builder.CreateBr(PRegExitBB);
919       IP = InsertPointTy(I->getParent(), I->getIterator());
920     }
921     assert(IP.getBlock()->getTerminator()->getNumSuccessors() == 1 &&
922            IP.getBlock()->getTerminator()->getSuccessor(0) == PRegExitBB &&
923            "Unexpected insertion point for finalization call!");
924     return FiniCB(IP);
925   };
926 
927   FinalizationStack.push_back({FiniCBWrapper, OMPD_parallel, IsCancellable});
928 
929   // Generate the privatization allocas in the block that will become the entry
930   // of the outlined function.
931   Builder.SetInsertPoint(PRegEntryBB->getTerminator());
932   InsertPointTy InnerAllocaIP = Builder.saveIP();
933 
934   AllocaInst *PrivTIDAddr =
935       Builder.CreateAlloca(Int32, nullptr, "tid.addr.local");
936   Instruction *PrivTID = Builder.CreateLoad(Int32, PrivTIDAddr, "tid");
937 
938   // Add some fake uses for OpenMP provided arguments.
939   ToBeDeleted.push_back(Builder.CreateLoad(Int32, TIDAddr, "tid.addr.use"));
940   Instruction *ZeroAddrUse =
941       Builder.CreateLoad(Int32, ZeroAddr, "zero.addr.use");
942   ToBeDeleted.push_back(ZeroAddrUse);
943 
944   // ThenBB
945   //   |
946   //   V
947   // PRegionEntryBB         <- Privatization allocas are placed here.
948   //   |
949   //   V
950   // PRegionBodyBB          <- BodeGen is invoked here.
951   //   |
952   //   V
953   // PRegPreFiniBB          <- The block we will start finalization from.
954   //   |
955   //   V
956   // PRegionExitBB          <- A common exit to simplify block collection.
957   //
958 
959   LLVM_DEBUG(dbgs() << "Before body codegen: " << *OuterFn << "\n");
960 
961   // Let the caller create the body.
962   assert(BodyGenCB && "Expected body generation callback!");
963   InsertPointTy CodeGenIP(PRegBodyBB, PRegBodyBB->begin());
964   BodyGenCB(InnerAllocaIP, CodeGenIP);
965 
966   LLVM_DEBUG(dbgs() << "After  body codegen: " << *OuterFn << "\n");
967 
968   FunctionCallee RTLFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_fork_call);
969   if (auto *F = dyn_cast<llvm::Function>(RTLFn.getCallee())) {
970     if (!F->hasMetadata(llvm::LLVMContext::MD_callback)) {
971       llvm::LLVMContext &Ctx = F->getContext();
972       MDBuilder MDB(Ctx);
973       // Annotate the callback behavior of the __kmpc_fork_call:
974       //  - The callback callee is argument number 2 (microtask).
975       //  - The first two arguments of the callback callee are unknown (-1).
976       //  - All variadic arguments to the __kmpc_fork_call are passed to the
977       //    callback callee.
978       F->addMetadata(
979           llvm::LLVMContext::MD_callback,
980           *llvm::MDNode::get(
981               Ctx, {MDB.createCallbackEncoding(2, {-1, -1},
982                                                /* VarArgsArePassed */ true)}));
983     }
984   }
985 
986   OutlineInfo OI;
987   OI.PostOutlineCB = [=](Function &OutlinedFn) {
988     // Add some known attributes.
989     OutlinedFn.addParamAttr(0, Attribute::NoAlias);
990     OutlinedFn.addParamAttr(1, Attribute::NoAlias);
991     OutlinedFn.addFnAttr(Attribute::NoUnwind);
992     OutlinedFn.addFnAttr(Attribute::NoRecurse);
993 
994     assert(OutlinedFn.arg_size() >= 2 &&
995            "Expected at least tid and bounded tid as arguments");
996     unsigned NumCapturedVars =
997         OutlinedFn.arg_size() - /* tid & bounded tid */ 2;
998 
999     CallInst *CI = cast<CallInst>(OutlinedFn.user_back());
1000     CI->getParent()->setName("omp_parallel");
1001     Builder.SetInsertPoint(CI);
1002 
1003     // Build call __kmpc_fork_call(Ident, n, microtask, var1, .., varn);
1004     Value *ForkCallArgs[] = {
1005         Ident, Builder.getInt32(NumCapturedVars),
1006         Builder.CreateBitCast(&OutlinedFn, ParallelTaskPtr)};
1007 
1008     SmallVector<Value *, 16> RealArgs;
1009     RealArgs.append(std::begin(ForkCallArgs), std::end(ForkCallArgs));
1010     RealArgs.append(CI->arg_begin() + /* tid & bound tid */ 2, CI->arg_end());
1011 
1012     Builder.CreateCall(RTLFn, RealArgs);
1013 
1014     LLVM_DEBUG(dbgs() << "With fork_call placed: "
1015                       << *Builder.GetInsertBlock()->getParent() << "\n");
1016 
1017     InsertPointTy ExitIP(PRegExitBB, PRegExitBB->end());
1018 
1019     // Initialize the local TID stack location with the argument value.
1020     Builder.SetInsertPoint(PrivTID);
1021     Function::arg_iterator OutlinedAI = OutlinedFn.arg_begin();
1022     Builder.CreateStore(Builder.CreateLoad(Int32, OutlinedAI), PrivTIDAddr);
1023 
1024     // If no "if" clause was present we do not need the call created during
1025     // outlining, otherwise we reuse it in the serialized parallel region.
1026     if (!ElseTI) {
1027       CI->eraseFromParent();
1028     } else {
1029 
1030       // If an "if" clause was present we are now generating the serialized
1031       // version into the "else" branch.
1032       Builder.SetInsertPoint(ElseTI);
1033 
1034       // Build calls __kmpc_serialized_parallel(&Ident, GTid);
1035       Value *SerializedParallelCallArgs[] = {Ident, ThreadID};
1036       Builder.CreateCall(
1037           getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_serialized_parallel),
1038           SerializedParallelCallArgs);
1039 
1040       // OutlinedFn(&GTid, &zero, CapturedStruct);
1041       CI->removeFromParent();
1042       Builder.Insert(CI);
1043 
1044       // __kmpc_end_serialized_parallel(&Ident, GTid);
1045       Value *EndArgs[] = {Ident, ThreadID};
1046       Builder.CreateCall(
1047           getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_end_serialized_parallel),
1048           EndArgs);
1049 
1050       LLVM_DEBUG(dbgs() << "With serialized parallel region: "
1051                         << *Builder.GetInsertBlock()->getParent() << "\n");
1052     }
1053 
1054     for (Instruction *I : ToBeDeleted)
1055       I->eraseFromParent();
1056   };
1057 
1058   // Adjust the finalization stack, verify the adjustment, and call the
1059   // finalize function a last time to finalize values between the pre-fini
1060   // block and the exit block if we left the parallel "the normal way".
1061   auto FiniInfo = FinalizationStack.pop_back_val();
1062   (void)FiniInfo;
1063   assert(FiniInfo.DK == OMPD_parallel &&
1064          "Unexpected finalization stack state!");
1065 
1066   Instruction *PRegPreFiniTI = PRegPreFiniBB->getTerminator();
1067 
1068   InsertPointTy PreFiniIP(PRegPreFiniBB, PRegPreFiniTI->getIterator());
1069   FiniCB(PreFiniIP);
1070 
1071   OI.OuterAllocaBB = OuterAllocaBlock;
1072   OI.EntryBB = PRegEntryBB;
1073   OI.ExitBB = PRegExitBB;
1074 
1075   SmallPtrSet<BasicBlock *, 32> ParallelRegionBlockSet;
1076   SmallVector<BasicBlock *, 32> Blocks;
1077   OI.collectBlocks(ParallelRegionBlockSet, Blocks);
1078 
1079   // Ensure a single exit node for the outlined region by creating one.
1080   // We might have multiple incoming edges to the exit now due to finalizations,
1081   // e.g., cancel calls that cause the control flow to leave the region.
1082   BasicBlock *PRegOutlinedExitBB = PRegExitBB;
1083   PRegExitBB = SplitBlock(PRegExitBB, &*PRegExitBB->getFirstInsertionPt());
1084   PRegOutlinedExitBB->setName("omp.par.outlined.exit");
1085   Blocks.push_back(PRegOutlinedExitBB);
1086 
1087   CodeExtractorAnalysisCache CEAC(*OuterFn);
1088   CodeExtractor Extractor(Blocks, /* DominatorTree */ nullptr,
1089                           /* AggregateArgs */ false,
1090                           /* BlockFrequencyInfo */ nullptr,
1091                           /* BranchProbabilityInfo */ nullptr,
1092                           /* AssumptionCache */ nullptr,
1093                           /* AllowVarArgs */ true,
1094                           /* AllowAlloca */ true,
1095                           /* AllocationBlock */ OuterAllocaBlock,
1096                           /* Suffix */ ".omp_par");
1097 
1098   // Find inputs to, outputs from the code region.
1099   BasicBlock *CommonExit = nullptr;
1100   SetVector<Value *> Inputs, Outputs, SinkingCands, HoistingCands;
1101   Extractor.findAllocas(CEAC, SinkingCands, HoistingCands, CommonExit);
1102   Extractor.findInputsOutputs(Inputs, Outputs, SinkingCands);
1103 
1104   LLVM_DEBUG(dbgs() << "Before privatization: " << *OuterFn << "\n");
1105 
1106   FunctionCallee TIDRTLFn =
1107       getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_global_thread_num);
1108 
1109   auto PrivHelper = [&](Value &V) {
1110     if (&V == TIDAddr || &V == ZeroAddr) {
1111       OI.ExcludeArgsFromAggregate.push_back(&V);
1112       return;
1113     }
1114 
1115     SetVector<Use *> Uses;
1116     for (Use &U : V.uses())
1117       if (auto *UserI = dyn_cast<Instruction>(U.getUser()))
1118         if (ParallelRegionBlockSet.count(UserI->getParent()))
1119           Uses.insert(&U);
1120 
1121     // __kmpc_fork_call expects extra arguments as pointers. If the input
1122     // already has a pointer type, everything is fine. Otherwise, store the
1123     // value onto stack and load it back inside the to-be-outlined region. This
1124     // will ensure only the pointer will be passed to the function.
1125     // FIXME: if there are more than 15 trailing arguments, they must be
1126     // additionally packed in a struct.
1127     Value *Inner = &V;
1128     if (!V.getType()->isPointerTy()) {
1129       IRBuilder<>::InsertPointGuard Guard(Builder);
1130       LLVM_DEBUG(llvm::dbgs() << "Forwarding input as pointer: " << V << "\n");
1131 
1132       Builder.restoreIP(OuterAllocaIP);
1133       Value *Ptr =
1134           Builder.CreateAlloca(V.getType(), nullptr, V.getName() + ".reloaded");
1135 
1136       // Store to stack at end of the block that currently branches to the entry
1137       // block of the to-be-outlined region.
1138       Builder.SetInsertPoint(InsertBB,
1139                              InsertBB->getTerminator()->getIterator());
1140       Builder.CreateStore(&V, Ptr);
1141 
1142       // Load back next to allocations in the to-be-outlined region.
1143       Builder.restoreIP(InnerAllocaIP);
1144       Inner = Builder.CreateLoad(V.getType(), Ptr);
1145     }
1146 
1147     Value *ReplacementValue = nullptr;
1148     CallInst *CI = dyn_cast<CallInst>(&V);
1149     if (CI && CI->getCalledFunction() == TIDRTLFn.getCallee()) {
1150       ReplacementValue = PrivTID;
1151     } else {
1152       Builder.restoreIP(
1153           PrivCB(InnerAllocaIP, Builder.saveIP(), V, *Inner, ReplacementValue));
1154       assert(ReplacementValue &&
1155              "Expected copy/create callback to set replacement value!");
1156       if (ReplacementValue == &V)
1157         return;
1158     }
1159 
1160     for (Use *UPtr : Uses)
1161       UPtr->set(ReplacementValue);
1162   };
1163 
1164   // Reset the inner alloca insertion as it will be used for loading the values
1165   // wrapped into pointers before passing them into the to-be-outlined region.
1166   // Configure it to insert immediately after the fake use of zero address so
1167   // that they are available in the generated body and so that the
1168   // OpenMP-related values (thread ID and zero address pointers) remain leading
1169   // in the argument list.
1170   InnerAllocaIP = IRBuilder<>::InsertPoint(
1171       ZeroAddrUse->getParent(), ZeroAddrUse->getNextNode()->getIterator());
1172 
1173   // Reset the outer alloca insertion point to the entry of the relevant block
1174   // in case it was invalidated.
1175   OuterAllocaIP = IRBuilder<>::InsertPoint(
1176       OuterAllocaBlock, OuterAllocaBlock->getFirstInsertionPt());
1177 
1178   for (Value *Input : Inputs) {
1179     LLVM_DEBUG(dbgs() << "Captured input: " << *Input << "\n");
1180     PrivHelper(*Input);
1181   }
1182   LLVM_DEBUG({
1183     for (Value *Output : Outputs)
1184       LLVM_DEBUG(dbgs() << "Captured output: " << *Output << "\n");
1185   });
1186   assert(Outputs.empty() &&
1187          "OpenMP outlining should not produce live-out values!");
1188 
1189   LLVM_DEBUG(dbgs() << "After  privatization: " << *OuterFn << "\n");
1190   LLVM_DEBUG({
1191     for (auto *BB : Blocks)
1192       dbgs() << " PBR: " << BB->getName() << "\n";
1193   });
1194 
1195   // Register the outlined info.
1196   addOutlineInfo(std::move(OI));
1197 
1198   InsertPointTy AfterIP(UI->getParent(), UI->getParent()->end());
1199   UI->eraseFromParent();
1200 
1201   return AfterIP;
1202 }
1203 
1204 void OpenMPIRBuilder::emitFlush(const LocationDescription &Loc) {
1205   // Build call void __kmpc_flush(ident_t *loc)
1206   uint32_t SrcLocStrSize;
1207   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
1208   Value *Args[] = {getOrCreateIdent(SrcLocStr, SrcLocStrSize)};
1209 
1210   Builder.CreateCall(getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_flush), Args);
1211 }
1212 
1213 void OpenMPIRBuilder::createFlush(const LocationDescription &Loc) {
1214   if (!updateToLocation(Loc))
1215     return;
1216   emitFlush(Loc);
1217 }
1218 
1219 void OpenMPIRBuilder::emitTaskwaitImpl(const LocationDescription &Loc) {
1220   // Build call kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
1221   // global_tid);
1222   uint32_t SrcLocStrSize;
1223   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
1224   Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
1225   Value *Args[] = {Ident, getOrCreateThreadID(Ident)};
1226 
1227   // Ignore return result until untied tasks are supported.
1228   Builder.CreateCall(getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_omp_taskwait),
1229                      Args);
1230 }
1231 
1232 void OpenMPIRBuilder::createTaskwait(const LocationDescription &Loc) {
1233   if (!updateToLocation(Loc))
1234     return;
1235   emitTaskwaitImpl(Loc);
1236 }
1237 
1238 void OpenMPIRBuilder::emitTaskyieldImpl(const LocationDescription &Loc) {
1239   // Build call __kmpc_omp_taskyield(loc, thread_id, 0);
1240   uint32_t SrcLocStrSize;
1241   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
1242   Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
1243   Constant *I32Null = ConstantInt::getNullValue(Int32);
1244   Value *Args[] = {Ident, getOrCreateThreadID(Ident), I32Null};
1245 
1246   Builder.CreateCall(getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_omp_taskyield),
1247                      Args);
1248 }
1249 
1250 void OpenMPIRBuilder::createTaskyield(const LocationDescription &Loc) {
1251   if (!updateToLocation(Loc))
1252     return;
1253   emitTaskyieldImpl(Loc);
1254 }
1255 
1256 OpenMPIRBuilder::InsertPointTy
1257 OpenMPIRBuilder::createTask(const LocationDescription &Loc,
1258                             InsertPointTy AllocaIP, BodyGenCallbackTy BodyGenCB,
1259                             bool Tied) {
1260   if (!updateToLocation(Loc))
1261     return InsertPointTy();
1262 
1263   // The current basic block is split into four basic blocks. After outlining,
1264   // they will be mapped as follows:
1265   // ```
1266   // def current_fn() {
1267   //   current_basic_block:
1268   //     br label %task.exit
1269   //   task.exit:
1270   //     ; instructions after task
1271   // }
1272   // def outlined_fn() {
1273   //   task.alloca:
1274   //     br label %task.body
1275   //   task.body:
1276   //     ret void
1277   // }
1278   // ```
1279   BasicBlock *TaskExitBB = splitBB(Builder, /*CreateBranch=*/true, "task.exit");
1280   BasicBlock *TaskBodyBB = splitBB(Builder, /*CreateBranch=*/true, "task.body");
1281   BasicBlock *TaskAllocaBB =
1282       splitBB(Builder, /*CreateBranch=*/true, "task.alloca");
1283 
1284   OutlineInfo OI;
1285   OI.EntryBB = TaskAllocaBB;
1286   OI.OuterAllocaBB = AllocaIP.getBlock();
1287   OI.ExitBB = TaskExitBB;
1288   OI.PostOutlineCB = [this, &Loc, Tied](Function &OutlinedFn) {
1289     // The input IR here looks like the following-
1290     // ```
1291     // func @current_fn() {
1292     //   outlined_fn(%args)
1293     // }
1294     // func @outlined_fn(%args) { ... }
1295     // ```
1296     //
1297     // This is changed to the following-
1298     //
1299     // ```
1300     // func @current_fn() {
1301     //   runtime_call(..., wrapper_fn, ...)
1302     // }
1303     // func @wrapper_fn(..., %args) {
1304     //   outlined_fn(%args)
1305     // }
1306     // func @outlined_fn(%args) { ... }
1307     // ```
1308 
1309     // The stale call instruction will be replaced with a new call instruction
1310     // for runtime call with a wrapper function.
1311     assert(OutlinedFn.getNumUses() == 1 &&
1312            "there must be a single user for the outlined function");
1313     CallInst *StaleCI = cast<CallInst>(OutlinedFn.user_back());
1314 
1315     // HasTaskData is true if any variables are captured in the outlined region,
1316     // false otherwise.
1317     bool HasTaskData = StaleCI->arg_size() > 0;
1318     Builder.SetInsertPoint(StaleCI);
1319 
1320     // Gather the arguments for emitting the runtime call for
1321     // @__kmpc_omp_task_alloc
1322     Function *TaskAllocFn =
1323         getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_omp_task_alloc);
1324 
1325     // Arguments - `loc_ref` (Ident) and `gtid` (ThreadID)
1326     // call.
1327     uint32_t SrcLocStrSize;
1328     Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
1329     Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
1330     Value *ThreadID = getOrCreateThreadID(Ident);
1331 
1332     // Argument - `flags`
1333     // If task is tied, then (Flags & 1) == 1.
1334     // If task is untied, then (Flags & 1) == 0.
1335     // TODO: Handle the other flags.
1336     Value *Flags = Builder.getInt32(Tied);
1337 
1338     // Argument - `sizeof_kmp_task_t` (TaskSize)
1339     // Tasksize refers to the size in bytes of kmp_task_t data structure
1340     // including private vars accessed in task.
1341     Value *TaskSize = Builder.getInt64(0);
1342     if (HasTaskData) {
1343       AllocaInst *ArgStructAlloca =
1344           dyn_cast<AllocaInst>(StaleCI->getArgOperand(0));
1345       assert(ArgStructAlloca &&
1346              "Unable to find the alloca instruction corresponding to arguments "
1347              "for extracted function");
1348       StructType *ArgStructType =
1349           dyn_cast<StructType>(ArgStructAlloca->getAllocatedType());
1350       assert(ArgStructType && "Unable to find struct type corresponding to "
1351                               "arguments for extracted function");
1352       TaskSize =
1353           Builder.getInt64(M.getDataLayout().getTypeStoreSize(ArgStructType));
1354     }
1355 
1356     // TODO: Argument - sizeof_shareds
1357 
1358     // Argument - task_entry (the wrapper function)
1359     // If the outlined function has some captured variables (i.e. HasTaskData is
1360     // true), then the wrapper function will have an additional argument (the
1361     // struct containing captured variables). Otherwise, no such argument will
1362     // be present.
1363     SmallVector<Type *> WrapperArgTys{Builder.getInt32Ty()};
1364     if (HasTaskData)
1365       WrapperArgTys.push_back(OutlinedFn.getArg(0)->getType());
1366     FunctionCallee WrapperFuncVal = M.getOrInsertFunction(
1367         (Twine(OutlinedFn.getName()) + ".wrapper").str(),
1368         FunctionType::get(Builder.getInt32Ty(), WrapperArgTys, false));
1369     Function *WrapperFunc = dyn_cast<Function>(WrapperFuncVal.getCallee());
1370     PointerType *WrapperFuncBitcastType =
1371         FunctionType::get(Builder.getInt32Ty(),
1372                           {Builder.getInt32Ty(), Builder.getInt8PtrTy()}, false)
1373             ->getPointerTo();
1374     Value *WrapperFuncBitcast =
1375         ConstantExpr::getBitCast(WrapperFunc, WrapperFuncBitcastType);
1376 
1377     // Emit the @__kmpc_omp_task_alloc runtime call
1378     // The runtime call returns a pointer to an area where the task captured
1379     // variables must be copied before the task is run (NewTaskData)
1380     CallInst *NewTaskData = Builder.CreateCall(
1381         TaskAllocFn,
1382         {/*loc_ref=*/Ident, /*gtid=*/ThreadID, /*flags=*/Flags,
1383          /*sizeof_task=*/TaskSize, /*sizeof_shared=*/Builder.getInt64(0),
1384          /*task_func=*/WrapperFuncBitcast});
1385 
1386     // Copy the arguments for outlined function
1387     if (HasTaskData) {
1388       Value *TaskData = StaleCI->getArgOperand(0);
1389       Align Alignment = TaskData->getPointerAlignment(M.getDataLayout());
1390       Builder.CreateMemCpy(NewTaskData, Alignment, TaskData, Alignment,
1391                            TaskSize);
1392     }
1393 
1394     // Emit the @__kmpc_omp_task runtime call to spawn the task
1395     Function *TaskFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_omp_task);
1396     Builder.CreateCall(TaskFn, {Ident, ThreadID, NewTaskData});
1397 
1398     StaleCI->eraseFromParent();
1399 
1400     // Emit the body for wrapper function
1401     BasicBlock *WrapperEntryBB =
1402         BasicBlock::Create(M.getContext(), "", WrapperFunc);
1403     Builder.SetInsertPoint(WrapperEntryBB);
1404     if (HasTaskData)
1405       Builder.CreateCall(&OutlinedFn, {WrapperFunc->getArg(1)});
1406     else
1407       Builder.CreateCall(&OutlinedFn);
1408     Builder.CreateRet(Builder.getInt32(0));
1409   };
1410 
1411   addOutlineInfo(std::move(OI));
1412 
1413   InsertPointTy TaskAllocaIP =
1414       InsertPointTy(TaskAllocaBB, TaskAllocaBB->begin());
1415   InsertPointTy TaskBodyIP = InsertPointTy(TaskBodyBB, TaskBodyBB->begin());
1416   BodyGenCB(TaskAllocaIP, TaskBodyIP);
1417   Builder.SetInsertPoint(TaskExitBB);
1418 
1419   return Builder.saveIP();
1420 }
1421 
1422 OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::createSections(
1423     const LocationDescription &Loc, InsertPointTy AllocaIP,
1424     ArrayRef<StorableBodyGenCallbackTy> SectionCBs, PrivatizeCallbackTy PrivCB,
1425     FinalizeCallbackTy FiniCB, bool IsCancellable, bool IsNowait) {
1426   assert(!isConflictIP(AllocaIP, Loc.IP) && "Dedicated IP allocas required");
1427 
1428   if (!updateToLocation(Loc))
1429     return Loc.IP;
1430 
1431   auto FiniCBWrapper = [&](InsertPointTy IP) {
1432     if (IP.getBlock()->end() != IP.getPoint())
1433       return FiniCB(IP);
1434     // This must be done otherwise any nested constructs using FinalizeOMPRegion
1435     // will fail because that function requires the Finalization Basic Block to
1436     // have a terminator, which is already removed by EmitOMPRegionBody.
1437     // IP is currently at cancelation block.
1438     // We need to backtrack to the condition block to fetch
1439     // the exit block and create a branch from cancelation
1440     // to exit block.
1441     IRBuilder<>::InsertPointGuard IPG(Builder);
1442     Builder.restoreIP(IP);
1443     auto *CaseBB = IP.getBlock()->getSinglePredecessor();
1444     auto *CondBB = CaseBB->getSinglePredecessor()->getSinglePredecessor();
1445     auto *ExitBB = CondBB->getTerminator()->getSuccessor(1);
1446     Instruction *I = Builder.CreateBr(ExitBB);
1447     IP = InsertPointTy(I->getParent(), I->getIterator());
1448     return FiniCB(IP);
1449   };
1450 
1451   FinalizationStack.push_back({FiniCBWrapper, OMPD_sections, IsCancellable});
1452 
1453   // Each section is emitted as a switch case
1454   // Each finalization callback is handled from clang.EmitOMPSectionDirective()
1455   // -> OMP.createSection() which generates the IR for each section
1456   // Iterate through all sections and emit a switch construct:
1457   // switch (IV) {
1458   //   case 0:
1459   //     <SectionStmt[0]>;
1460   //     break;
1461   // ...
1462   //   case <NumSection> - 1:
1463   //     <SectionStmt[<NumSection> - 1]>;
1464   //     break;
1465   // }
1466   // ...
1467   // section_loop.after:
1468   // <FiniCB>;
1469   auto LoopBodyGenCB = [&](InsertPointTy CodeGenIP, Value *IndVar) {
1470     Builder.restoreIP(CodeGenIP);
1471     BasicBlock *Continue =
1472         splitBBWithSuffix(Builder, /*CreateBranch=*/false, ".sections.after");
1473     Function *CurFn = Continue->getParent();
1474     SwitchInst *SwitchStmt = Builder.CreateSwitch(IndVar, Continue);
1475 
1476     unsigned CaseNumber = 0;
1477     for (auto SectionCB : SectionCBs) {
1478       BasicBlock *CaseBB = BasicBlock::Create(
1479           M.getContext(), "omp_section_loop.body.case", CurFn, Continue);
1480       SwitchStmt->addCase(Builder.getInt32(CaseNumber), CaseBB);
1481       Builder.SetInsertPoint(CaseBB);
1482       BranchInst *CaseEndBr = Builder.CreateBr(Continue);
1483       SectionCB(InsertPointTy(),
1484                 {CaseEndBr->getParent(), CaseEndBr->getIterator()});
1485       CaseNumber++;
1486     }
1487     // remove the existing terminator from body BB since there can be no
1488     // terminators after switch/case
1489   };
1490   // Loop body ends here
1491   // LowerBound, UpperBound, and STride for createCanonicalLoop
1492   Type *I32Ty = Type::getInt32Ty(M.getContext());
1493   Value *LB = ConstantInt::get(I32Ty, 0);
1494   Value *UB = ConstantInt::get(I32Ty, SectionCBs.size());
1495   Value *ST = ConstantInt::get(I32Ty, 1);
1496   llvm::CanonicalLoopInfo *LoopInfo = createCanonicalLoop(
1497       Loc, LoopBodyGenCB, LB, UB, ST, true, false, AllocaIP, "section_loop");
1498   InsertPointTy AfterIP =
1499       applyStaticWorkshareLoop(Loc.DL, LoopInfo, AllocaIP, !IsNowait);
1500 
1501   // Apply the finalization callback in LoopAfterBB
1502   auto FiniInfo = FinalizationStack.pop_back_val();
1503   assert(FiniInfo.DK == OMPD_sections &&
1504          "Unexpected finalization stack state!");
1505   if (FinalizeCallbackTy &CB = FiniInfo.FiniCB) {
1506     Builder.restoreIP(AfterIP);
1507     BasicBlock *FiniBB =
1508         splitBBWithSuffix(Builder, /*CreateBranch=*/true, "sections.fini");
1509     CB(Builder.saveIP());
1510     AfterIP = {FiniBB, FiniBB->begin()};
1511   }
1512 
1513   return AfterIP;
1514 }
1515 
1516 OpenMPIRBuilder::InsertPointTy
1517 OpenMPIRBuilder::createSection(const LocationDescription &Loc,
1518                                BodyGenCallbackTy BodyGenCB,
1519                                FinalizeCallbackTy FiniCB) {
1520   if (!updateToLocation(Loc))
1521     return Loc.IP;
1522 
1523   auto FiniCBWrapper = [&](InsertPointTy IP) {
1524     if (IP.getBlock()->end() != IP.getPoint())
1525       return FiniCB(IP);
1526     // This must be done otherwise any nested constructs using FinalizeOMPRegion
1527     // will fail because that function requires the Finalization Basic Block to
1528     // have a terminator, which is already removed by EmitOMPRegionBody.
1529     // IP is currently at cancelation block.
1530     // We need to backtrack to the condition block to fetch
1531     // the exit block and create a branch from cancelation
1532     // to exit block.
1533     IRBuilder<>::InsertPointGuard IPG(Builder);
1534     Builder.restoreIP(IP);
1535     auto *CaseBB = Loc.IP.getBlock();
1536     auto *CondBB = CaseBB->getSinglePredecessor()->getSinglePredecessor();
1537     auto *ExitBB = CondBB->getTerminator()->getSuccessor(1);
1538     Instruction *I = Builder.CreateBr(ExitBB);
1539     IP = InsertPointTy(I->getParent(), I->getIterator());
1540     return FiniCB(IP);
1541   };
1542 
1543   Directive OMPD = Directive::OMPD_sections;
1544   // Since we are using Finalization Callback here, HasFinalize
1545   // and IsCancellable have to be true
1546   return EmitOMPInlinedRegion(OMPD, nullptr, nullptr, BodyGenCB, FiniCBWrapper,
1547                               /*Conditional*/ false, /*hasFinalize*/ true,
1548                               /*IsCancellable*/ true);
1549 }
1550 
1551 /// Create a function with a unique name and a "void (i8*, i8*)" signature in
1552 /// the given module and return it.
1553 Function *getFreshReductionFunc(Module &M) {
1554   Type *VoidTy = Type::getVoidTy(M.getContext());
1555   Type *Int8PtrTy = Type::getInt8PtrTy(M.getContext());
1556   auto *FuncTy =
1557       FunctionType::get(VoidTy, {Int8PtrTy, Int8PtrTy}, /* IsVarArg */ false);
1558   return Function::Create(FuncTy, GlobalVariable::InternalLinkage,
1559                           M.getDataLayout().getDefaultGlobalsAddressSpace(),
1560                           ".omp.reduction.func", &M);
1561 }
1562 
1563 OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::createReductions(
1564     const LocationDescription &Loc, InsertPointTy AllocaIP,
1565     ArrayRef<ReductionInfo> ReductionInfos, bool IsNoWait) {
1566   for (const ReductionInfo &RI : ReductionInfos) {
1567     (void)RI;
1568     assert(RI.Variable && "expected non-null variable");
1569     assert(RI.PrivateVariable && "expected non-null private variable");
1570     assert(RI.ReductionGen && "expected non-null reduction generator callback");
1571     assert(RI.Variable->getType() == RI.PrivateVariable->getType() &&
1572            "expected variables and their private equivalents to have the same "
1573            "type");
1574     assert(RI.Variable->getType()->isPointerTy() &&
1575            "expected variables to be pointers");
1576   }
1577 
1578   if (!updateToLocation(Loc))
1579     return InsertPointTy();
1580 
1581   BasicBlock *InsertBlock = Loc.IP.getBlock();
1582   BasicBlock *ContinuationBlock =
1583       InsertBlock->splitBasicBlock(Loc.IP.getPoint(), "reduce.finalize");
1584   InsertBlock->getTerminator()->eraseFromParent();
1585 
1586   // Create and populate array of type-erased pointers to private reduction
1587   // values.
1588   unsigned NumReductions = ReductionInfos.size();
1589   Type *RedArrayTy = ArrayType::get(Builder.getInt8PtrTy(), NumReductions);
1590   Builder.restoreIP(AllocaIP);
1591   Value *RedArray = Builder.CreateAlloca(RedArrayTy, nullptr, "red.array");
1592 
1593   Builder.SetInsertPoint(InsertBlock, InsertBlock->end());
1594 
1595   for (auto En : enumerate(ReductionInfos)) {
1596     unsigned Index = En.index();
1597     const ReductionInfo &RI = En.value();
1598     Value *RedArrayElemPtr = Builder.CreateConstInBoundsGEP2_64(
1599         RedArrayTy, RedArray, 0, Index, "red.array.elem." + Twine(Index));
1600     Value *Casted =
1601         Builder.CreateBitCast(RI.PrivateVariable, Builder.getInt8PtrTy(),
1602                               "private.red.var." + Twine(Index) + ".casted");
1603     Builder.CreateStore(Casted, RedArrayElemPtr);
1604   }
1605 
1606   // Emit a call to the runtime function that orchestrates the reduction.
1607   // Declare the reduction function in the process.
1608   Function *Func = Builder.GetInsertBlock()->getParent();
1609   Module *Module = Func->getParent();
1610   Value *RedArrayPtr =
1611       Builder.CreateBitCast(RedArray, Builder.getInt8PtrTy(), "red.array.ptr");
1612   uint32_t SrcLocStrSize;
1613   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
1614   bool CanGenerateAtomic =
1615       llvm::all_of(ReductionInfos, [](const ReductionInfo &RI) {
1616         return RI.AtomicReductionGen;
1617       });
1618   Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize,
1619                                   CanGenerateAtomic
1620                                       ? IdentFlag::OMP_IDENT_FLAG_ATOMIC_REDUCE
1621                                       : IdentFlag(0));
1622   Value *ThreadId = getOrCreateThreadID(Ident);
1623   Constant *NumVariables = Builder.getInt32(NumReductions);
1624   const DataLayout &DL = Module->getDataLayout();
1625   unsigned RedArrayByteSize = DL.getTypeStoreSize(RedArrayTy);
1626   Constant *RedArraySize = Builder.getInt64(RedArrayByteSize);
1627   Function *ReductionFunc = getFreshReductionFunc(*Module);
1628   Value *Lock = getOMPCriticalRegionLock(".reduction");
1629   Function *ReduceFunc = getOrCreateRuntimeFunctionPtr(
1630       IsNoWait ? RuntimeFunction::OMPRTL___kmpc_reduce_nowait
1631                : RuntimeFunction::OMPRTL___kmpc_reduce);
1632   CallInst *ReduceCall =
1633       Builder.CreateCall(ReduceFunc,
1634                          {Ident, ThreadId, NumVariables, RedArraySize,
1635                           RedArrayPtr, ReductionFunc, Lock},
1636                          "reduce");
1637 
1638   // Create final reduction entry blocks for the atomic and non-atomic case.
1639   // Emit IR that dispatches control flow to one of the blocks based on the
1640   // reduction supporting the atomic mode.
1641   BasicBlock *NonAtomicRedBlock =
1642       BasicBlock::Create(Module->getContext(), "reduce.switch.nonatomic", Func);
1643   BasicBlock *AtomicRedBlock =
1644       BasicBlock::Create(Module->getContext(), "reduce.switch.atomic", Func);
1645   SwitchInst *Switch =
1646       Builder.CreateSwitch(ReduceCall, ContinuationBlock, /* NumCases */ 2);
1647   Switch->addCase(Builder.getInt32(1), NonAtomicRedBlock);
1648   Switch->addCase(Builder.getInt32(2), AtomicRedBlock);
1649 
1650   // Populate the non-atomic reduction using the elementwise reduction function.
1651   // This loads the elements from the global and private variables and reduces
1652   // them before storing back the result to the global variable.
1653   Builder.SetInsertPoint(NonAtomicRedBlock);
1654   for (auto En : enumerate(ReductionInfos)) {
1655     const ReductionInfo &RI = En.value();
1656     Type *ValueType = RI.ElementType;
1657     Value *RedValue = Builder.CreateLoad(ValueType, RI.Variable,
1658                                          "red.value." + Twine(En.index()));
1659     Value *PrivateRedValue =
1660         Builder.CreateLoad(ValueType, RI.PrivateVariable,
1661                            "red.private.value." + Twine(En.index()));
1662     Value *Reduced;
1663     Builder.restoreIP(
1664         RI.ReductionGen(Builder.saveIP(), RedValue, PrivateRedValue, Reduced));
1665     if (!Builder.GetInsertBlock())
1666       return InsertPointTy();
1667     Builder.CreateStore(Reduced, RI.Variable);
1668   }
1669   Function *EndReduceFunc = getOrCreateRuntimeFunctionPtr(
1670       IsNoWait ? RuntimeFunction::OMPRTL___kmpc_end_reduce_nowait
1671                : RuntimeFunction::OMPRTL___kmpc_end_reduce);
1672   Builder.CreateCall(EndReduceFunc, {Ident, ThreadId, Lock});
1673   Builder.CreateBr(ContinuationBlock);
1674 
1675   // Populate the atomic reduction using the atomic elementwise reduction
1676   // function. There are no loads/stores here because they will be happening
1677   // inside the atomic elementwise reduction.
1678   Builder.SetInsertPoint(AtomicRedBlock);
1679   if (CanGenerateAtomic) {
1680     for (const ReductionInfo &RI : ReductionInfos) {
1681       Builder.restoreIP(RI.AtomicReductionGen(Builder.saveIP(), RI.ElementType,
1682                                               RI.Variable, RI.PrivateVariable));
1683       if (!Builder.GetInsertBlock())
1684         return InsertPointTy();
1685     }
1686     Builder.CreateBr(ContinuationBlock);
1687   } else {
1688     Builder.CreateUnreachable();
1689   }
1690 
1691   // Populate the outlined reduction function using the elementwise reduction
1692   // function. Partial values are extracted from the type-erased array of
1693   // pointers to private variables.
1694   BasicBlock *ReductionFuncBlock =
1695       BasicBlock::Create(Module->getContext(), "", ReductionFunc);
1696   Builder.SetInsertPoint(ReductionFuncBlock);
1697   Value *LHSArrayPtr = Builder.CreateBitCast(ReductionFunc->getArg(0),
1698                                              RedArrayTy->getPointerTo());
1699   Value *RHSArrayPtr = Builder.CreateBitCast(ReductionFunc->getArg(1),
1700                                              RedArrayTy->getPointerTo());
1701   for (auto En : enumerate(ReductionInfos)) {
1702     const ReductionInfo &RI = En.value();
1703     Value *LHSI8PtrPtr = Builder.CreateConstInBoundsGEP2_64(
1704         RedArrayTy, LHSArrayPtr, 0, En.index());
1705     Value *LHSI8Ptr = Builder.CreateLoad(Builder.getInt8PtrTy(), LHSI8PtrPtr);
1706     Value *LHSPtr = Builder.CreateBitCast(LHSI8Ptr, RI.Variable->getType());
1707     Value *LHS = Builder.CreateLoad(RI.ElementType, LHSPtr);
1708     Value *RHSI8PtrPtr = Builder.CreateConstInBoundsGEP2_64(
1709         RedArrayTy, RHSArrayPtr, 0, En.index());
1710     Value *RHSI8Ptr = Builder.CreateLoad(Builder.getInt8PtrTy(), RHSI8PtrPtr);
1711     Value *RHSPtr =
1712         Builder.CreateBitCast(RHSI8Ptr, RI.PrivateVariable->getType());
1713     Value *RHS = Builder.CreateLoad(RI.ElementType, RHSPtr);
1714     Value *Reduced;
1715     Builder.restoreIP(RI.ReductionGen(Builder.saveIP(), LHS, RHS, Reduced));
1716     if (!Builder.GetInsertBlock())
1717       return InsertPointTy();
1718     Builder.CreateStore(Reduced, LHSPtr);
1719   }
1720   Builder.CreateRetVoid();
1721 
1722   Builder.SetInsertPoint(ContinuationBlock);
1723   return Builder.saveIP();
1724 }
1725 
1726 OpenMPIRBuilder::InsertPointTy
1727 OpenMPIRBuilder::createMaster(const LocationDescription &Loc,
1728                               BodyGenCallbackTy BodyGenCB,
1729                               FinalizeCallbackTy FiniCB) {
1730 
1731   if (!updateToLocation(Loc))
1732     return Loc.IP;
1733 
1734   Directive OMPD = Directive::OMPD_master;
1735   uint32_t SrcLocStrSize;
1736   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
1737   Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
1738   Value *ThreadId = getOrCreateThreadID(Ident);
1739   Value *Args[] = {Ident, ThreadId};
1740 
1741   Function *EntryRTLFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_master);
1742   Instruction *EntryCall = Builder.CreateCall(EntryRTLFn, Args);
1743 
1744   Function *ExitRTLFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_end_master);
1745   Instruction *ExitCall = Builder.CreateCall(ExitRTLFn, Args);
1746 
1747   return EmitOMPInlinedRegion(OMPD, EntryCall, ExitCall, BodyGenCB, FiniCB,
1748                               /*Conditional*/ true, /*hasFinalize*/ true);
1749 }
1750 
1751 OpenMPIRBuilder::InsertPointTy
1752 OpenMPIRBuilder::createMasked(const LocationDescription &Loc,
1753                               BodyGenCallbackTy BodyGenCB,
1754                               FinalizeCallbackTy FiniCB, Value *Filter) {
1755   if (!updateToLocation(Loc))
1756     return Loc.IP;
1757 
1758   Directive OMPD = Directive::OMPD_masked;
1759   uint32_t SrcLocStrSize;
1760   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
1761   Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
1762   Value *ThreadId = getOrCreateThreadID(Ident);
1763   Value *Args[] = {Ident, ThreadId, Filter};
1764   Value *ArgsEnd[] = {Ident, ThreadId};
1765 
1766   Function *EntryRTLFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_masked);
1767   Instruction *EntryCall = Builder.CreateCall(EntryRTLFn, Args);
1768 
1769   Function *ExitRTLFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_end_masked);
1770   Instruction *ExitCall = Builder.CreateCall(ExitRTLFn, ArgsEnd);
1771 
1772   return EmitOMPInlinedRegion(OMPD, EntryCall, ExitCall, BodyGenCB, FiniCB,
1773                               /*Conditional*/ true, /*hasFinalize*/ true);
1774 }
1775 
1776 CanonicalLoopInfo *OpenMPIRBuilder::createLoopSkeleton(
1777     DebugLoc DL, Value *TripCount, Function *F, BasicBlock *PreInsertBefore,
1778     BasicBlock *PostInsertBefore, const Twine &Name) {
1779   Module *M = F->getParent();
1780   LLVMContext &Ctx = M->getContext();
1781   Type *IndVarTy = TripCount->getType();
1782 
1783   // Create the basic block structure.
1784   BasicBlock *Preheader =
1785       BasicBlock::Create(Ctx, "omp_" + Name + ".preheader", F, PreInsertBefore);
1786   BasicBlock *Header =
1787       BasicBlock::Create(Ctx, "omp_" + Name + ".header", F, PreInsertBefore);
1788   BasicBlock *Cond =
1789       BasicBlock::Create(Ctx, "omp_" + Name + ".cond", F, PreInsertBefore);
1790   BasicBlock *Body =
1791       BasicBlock::Create(Ctx, "omp_" + Name + ".body", F, PreInsertBefore);
1792   BasicBlock *Latch =
1793       BasicBlock::Create(Ctx, "omp_" + Name + ".inc", F, PostInsertBefore);
1794   BasicBlock *Exit =
1795       BasicBlock::Create(Ctx, "omp_" + Name + ".exit", F, PostInsertBefore);
1796   BasicBlock *After =
1797       BasicBlock::Create(Ctx, "omp_" + Name + ".after", F, PostInsertBefore);
1798 
1799   // Use specified DebugLoc for new instructions.
1800   Builder.SetCurrentDebugLocation(DL);
1801 
1802   Builder.SetInsertPoint(Preheader);
1803   Builder.CreateBr(Header);
1804 
1805   Builder.SetInsertPoint(Header);
1806   PHINode *IndVarPHI = Builder.CreatePHI(IndVarTy, 2, "omp_" + Name + ".iv");
1807   IndVarPHI->addIncoming(ConstantInt::get(IndVarTy, 0), Preheader);
1808   Builder.CreateBr(Cond);
1809 
1810   Builder.SetInsertPoint(Cond);
1811   Value *Cmp =
1812       Builder.CreateICmpULT(IndVarPHI, TripCount, "omp_" + Name + ".cmp");
1813   Builder.CreateCondBr(Cmp, Body, Exit);
1814 
1815   Builder.SetInsertPoint(Body);
1816   Builder.CreateBr(Latch);
1817 
1818   Builder.SetInsertPoint(Latch);
1819   Value *Next = Builder.CreateAdd(IndVarPHI, ConstantInt::get(IndVarTy, 1),
1820                                   "omp_" + Name + ".next", /*HasNUW=*/true);
1821   Builder.CreateBr(Header);
1822   IndVarPHI->addIncoming(Next, Latch);
1823 
1824   Builder.SetInsertPoint(Exit);
1825   Builder.CreateBr(After);
1826 
1827   // Remember and return the canonical control flow.
1828   LoopInfos.emplace_front();
1829   CanonicalLoopInfo *CL = &LoopInfos.front();
1830 
1831   CL->Header = Header;
1832   CL->Cond = Cond;
1833   CL->Latch = Latch;
1834   CL->Exit = Exit;
1835 
1836 #ifndef NDEBUG
1837   CL->assertOK();
1838 #endif
1839   return CL;
1840 }
1841 
1842 CanonicalLoopInfo *
1843 OpenMPIRBuilder::createCanonicalLoop(const LocationDescription &Loc,
1844                                      LoopBodyGenCallbackTy BodyGenCB,
1845                                      Value *TripCount, const Twine &Name) {
1846   BasicBlock *BB = Loc.IP.getBlock();
1847   BasicBlock *NextBB = BB->getNextNode();
1848 
1849   CanonicalLoopInfo *CL = createLoopSkeleton(Loc.DL, TripCount, BB->getParent(),
1850                                              NextBB, NextBB, Name);
1851   BasicBlock *After = CL->getAfter();
1852 
1853   // If location is not set, don't connect the loop.
1854   if (updateToLocation(Loc)) {
1855     // Split the loop at the insertion point: Branch to the preheader and move
1856     // every following instruction to after the loop (the After BB). Also, the
1857     // new successor is the loop's after block.
1858     spliceBB(Builder, After, /*CreateBranch=*/false);
1859     Builder.CreateBr(CL->getPreheader());
1860   }
1861 
1862   // Emit the body content. We do it after connecting the loop to the CFG to
1863   // avoid that the callback encounters degenerate BBs.
1864   BodyGenCB(CL->getBodyIP(), CL->getIndVar());
1865 
1866 #ifndef NDEBUG
1867   CL->assertOK();
1868 #endif
1869   return CL;
1870 }
1871 
1872 CanonicalLoopInfo *OpenMPIRBuilder::createCanonicalLoop(
1873     const LocationDescription &Loc, LoopBodyGenCallbackTy BodyGenCB,
1874     Value *Start, Value *Stop, Value *Step, bool IsSigned, bool InclusiveStop,
1875     InsertPointTy ComputeIP, const Twine &Name) {
1876 
1877   // Consider the following difficulties (assuming 8-bit signed integers):
1878   //  * Adding \p Step to the loop counter which passes \p Stop may overflow:
1879   //      DO I = 1, 100, 50
1880   ///  * A \p Step of INT_MIN cannot not be normalized to a positive direction:
1881   //      DO I = 100, 0, -128
1882 
1883   // Start, Stop and Step must be of the same integer type.
1884   auto *IndVarTy = cast<IntegerType>(Start->getType());
1885   assert(IndVarTy == Stop->getType() && "Stop type mismatch");
1886   assert(IndVarTy == Step->getType() && "Step type mismatch");
1887 
1888   LocationDescription ComputeLoc =
1889       ComputeIP.isSet() ? LocationDescription(ComputeIP, Loc.DL) : Loc;
1890   updateToLocation(ComputeLoc);
1891 
1892   ConstantInt *Zero = ConstantInt::get(IndVarTy, 0);
1893   ConstantInt *One = ConstantInt::get(IndVarTy, 1);
1894 
1895   // Like Step, but always positive.
1896   Value *Incr = Step;
1897 
1898   // Distance between Start and Stop; always positive.
1899   Value *Span;
1900 
1901   // Condition whether there are no iterations are executed at all, e.g. because
1902   // UB < LB.
1903   Value *ZeroCmp;
1904 
1905   if (IsSigned) {
1906     // Ensure that increment is positive. If not, negate and invert LB and UB.
1907     Value *IsNeg = Builder.CreateICmpSLT(Step, Zero);
1908     Incr = Builder.CreateSelect(IsNeg, Builder.CreateNeg(Step), Step);
1909     Value *LB = Builder.CreateSelect(IsNeg, Stop, Start);
1910     Value *UB = Builder.CreateSelect(IsNeg, Start, Stop);
1911     Span = Builder.CreateSub(UB, LB, "", false, true);
1912     ZeroCmp = Builder.CreateICmp(
1913         InclusiveStop ? CmpInst::ICMP_SLT : CmpInst::ICMP_SLE, UB, LB);
1914   } else {
1915     Span = Builder.CreateSub(Stop, Start, "", true);
1916     ZeroCmp = Builder.CreateICmp(
1917         InclusiveStop ? CmpInst::ICMP_ULT : CmpInst::ICMP_ULE, Stop, Start);
1918   }
1919 
1920   Value *CountIfLooping;
1921   if (InclusiveStop) {
1922     CountIfLooping = Builder.CreateAdd(Builder.CreateUDiv(Span, Incr), One);
1923   } else {
1924     // Avoid incrementing past stop since it could overflow.
1925     Value *CountIfTwo = Builder.CreateAdd(
1926         Builder.CreateUDiv(Builder.CreateSub(Span, One), Incr), One);
1927     Value *OneCmp = Builder.CreateICmp(
1928         InclusiveStop ? CmpInst::ICMP_ULT : CmpInst::ICMP_ULE, Span, Incr);
1929     CountIfLooping = Builder.CreateSelect(OneCmp, One, CountIfTwo);
1930   }
1931   Value *TripCount = Builder.CreateSelect(ZeroCmp, Zero, CountIfLooping,
1932                                           "omp_" + Name + ".tripcount");
1933 
1934   auto BodyGen = [=](InsertPointTy CodeGenIP, Value *IV) {
1935     Builder.restoreIP(CodeGenIP);
1936     Value *Span = Builder.CreateMul(IV, Step);
1937     Value *IndVar = Builder.CreateAdd(Span, Start);
1938     BodyGenCB(Builder.saveIP(), IndVar);
1939   };
1940   LocationDescription LoopLoc = ComputeIP.isSet() ? Loc.IP : Builder.saveIP();
1941   return createCanonicalLoop(LoopLoc, BodyGen, TripCount, Name);
1942 }
1943 
1944 // Returns an LLVM function to call for initializing loop bounds using OpenMP
1945 // static scheduling depending on `type`. Only i32 and i64 are supported by the
1946 // runtime. Always interpret integers as unsigned similarly to
1947 // CanonicalLoopInfo.
1948 static FunctionCallee getKmpcForStaticInitForType(Type *Ty, Module &M,
1949                                                   OpenMPIRBuilder &OMPBuilder) {
1950   unsigned Bitwidth = Ty->getIntegerBitWidth();
1951   if (Bitwidth == 32)
1952     return OMPBuilder.getOrCreateRuntimeFunction(
1953         M, omp::RuntimeFunction::OMPRTL___kmpc_for_static_init_4u);
1954   if (Bitwidth == 64)
1955     return OMPBuilder.getOrCreateRuntimeFunction(
1956         M, omp::RuntimeFunction::OMPRTL___kmpc_for_static_init_8u);
1957   llvm_unreachable("unknown OpenMP loop iterator bitwidth");
1958 }
1959 
1960 OpenMPIRBuilder::InsertPointTy
1961 OpenMPIRBuilder::applyStaticWorkshareLoop(DebugLoc DL, CanonicalLoopInfo *CLI,
1962                                           InsertPointTy AllocaIP,
1963                                           bool NeedsBarrier) {
1964   assert(CLI->isValid() && "Requires a valid canonical loop");
1965   assert(!isConflictIP(AllocaIP, CLI->getPreheaderIP()) &&
1966          "Require dedicated allocate IP");
1967 
1968   // Set up the source location value for OpenMP runtime.
1969   Builder.restoreIP(CLI->getPreheaderIP());
1970   Builder.SetCurrentDebugLocation(DL);
1971 
1972   uint32_t SrcLocStrSize;
1973   Constant *SrcLocStr = getOrCreateSrcLocStr(DL, SrcLocStrSize);
1974   Value *SrcLoc = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
1975 
1976   // Declare useful OpenMP runtime functions.
1977   Value *IV = CLI->getIndVar();
1978   Type *IVTy = IV->getType();
1979   FunctionCallee StaticInit = getKmpcForStaticInitForType(IVTy, M, *this);
1980   FunctionCallee StaticFini =
1981       getOrCreateRuntimeFunction(M, omp::OMPRTL___kmpc_for_static_fini);
1982 
1983   // Allocate space for computed loop bounds as expected by the "init" function.
1984   Builder.restoreIP(AllocaIP);
1985   Type *I32Type = Type::getInt32Ty(M.getContext());
1986   Value *PLastIter = Builder.CreateAlloca(I32Type, nullptr, "p.lastiter");
1987   Value *PLowerBound = Builder.CreateAlloca(IVTy, nullptr, "p.lowerbound");
1988   Value *PUpperBound = Builder.CreateAlloca(IVTy, nullptr, "p.upperbound");
1989   Value *PStride = Builder.CreateAlloca(IVTy, nullptr, "p.stride");
1990 
1991   // At the end of the preheader, prepare for calling the "init" function by
1992   // storing the current loop bounds into the allocated space. A canonical loop
1993   // always iterates from 0 to trip-count with step 1. Note that "init" expects
1994   // and produces an inclusive upper bound.
1995   Builder.SetInsertPoint(CLI->getPreheader()->getTerminator());
1996   Constant *Zero = ConstantInt::get(IVTy, 0);
1997   Constant *One = ConstantInt::get(IVTy, 1);
1998   Builder.CreateStore(Zero, PLowerBound);
1999   Value *UpperBound = Builder.CreateSub(CLI->getTripCount(), One);
2000   Builder.CreateStore(UpperBound, PUpperBound);
2001   Builder.CreateStore(One, PStride);
2002 
2003   Value *ThreadNum = getOrCreateThreadID(SrcLoc);
2004 
2005   Constant *SchedulingType = ConstantInt::get(
2006       I32Type, static_cast<int>(OMPScheduleType::UnorderedStatic));
2007 
2008   // Call the "init" function and update the trip count of the loop with the
2009   // value it produced.
2010   Builder.CreateCall(StaticInit,
2011                      {SrcLoc, ThreadNum, SchedulingType, PLastIter, PLowerBound,
2012                       PUpperBound, PStride, One, Zero});
2013   Value *LowerBound = Builder.CreateLoad(IVTy, PLowerBound);
2014   Value *InclusiveUpperBound = Builder.CreateLoad(IVTy, PUpperBound);
2015   Value *TripCountMinusOne = Builder.CreateSub(InclusiveUpperBound, LowerBound);
2016   Value *TripCount = Builder.CreateAdd(TripCountMinusOne, One);
2017   CLI->setTripCount(TripCount);
2018 
2019   // Update all uses of the induction variable except the one in the condition
2020   // block that compares it with the actual upper bound, and the increment in
2021   // the latch block.
2022 
2023   CLI->mapIndVar([&](Instruction *OldIV) -> Value * {
2024     Builder.SetInsertPoint(CLI->getBody(),
2025                            CLI->getBody()->getFirstInsertionPt());
2026     Builder.SetCurrentDebugLocation(DL);
2027     return Builder.CreateAdd(OldIV, LowerBound);
2028   });
2029 
2030   // In the "exit" block, call the "fini" function.
2031   Builder.SetInsertPoint(CLI->getExit(),
2032                          CLI->getExit()->getTerminator()->getIterator());
2033   Builder.CreateCall(StaticFini, {SrcLoc, ThreadNum});
2034 
2035   // Add the barrier if requested.
2036   if (NeedsBarrier)
2037     createBarrier(LocationDescription(Builder.saveIP(), DL),
2038                   omp::Directive::OMPD_for, /* ForceSimpleCall */ false,
2039                   /* CheckCancelFlag */ false);
2040 
2041   InsertPointTy AfterIP = CLI->getAfterIP();
2042   CLI->invalidate();
2043 
2044   return AfterIP;
2045 }
2046 
2047 OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::applyStaticChunkedWorkshareLoop(
2048     DebugLoc DL, CanonicalLoopInfo *CLI, InsertPointTy AllocaIP,
2049     bool NeedsBarrier, Value *ChunkSize) {
2050   assert(CLI->isValid() && "Requires a valid canonical loop");
2051   assert(ChunkSize && "Chunk size is required");
2052 
2053   LLVMContext &Ctx = CLI->getFunction()->getContext();
2054   Value *IV = CLI->getIndVar();
2055   Value *OrigTripCount = CLI->getTripCount();
2056   Type *IVTy = IV->getType();
2057   assert(IVTy->getIntegerBitWidth() <= 64 &&
2058          "Max supported tripcount bitwidth is 64 bits");
2059   Type *InternalIVTy = IVTy->getIntegerBitWidth() <= 32 ? Type::getInt32Ty(Ctx)
2060                                                         : Type::getInt64Ty(Ctx);
2061   Type *I32Type = Type::getInt32Ty(M.getContext());
2062   Constant *Zero = ConstantInt::get(InternalIVTy, 0);
2063   Constant *One = ConstantInt::get(InternalIVTy, 1);
2064 
2065   // Declare useful OpenMP runtime functions.
2066   FunctionCallee StaticInit =
2067       getKmpcForStaticInitForType(InternalIVTy, M, *this);
2068   FunctionCallee StaticFini =
2069       getOrCreateRuntimeFunction(M, omp::OMPRTL___kmpc_for_static_fini);
2070 
2071   // Allocate space for computed loop bounds as expected by the "init" function.
2072   Builder.restoreIP(AllocaIP);
2073   Builder.SetCurrentDebugLocation(DL);
2074   Value *PLastIter = Builder.CreateAlloca(I32Type, nullptr, "p.lastiter");
2075   Value *PLowerBound =
2076       Builder.CreateAlloca(InternalIVTy, nullptr, "p.lowerbound");
2077   Value *PUpperBound =
2078       Builder.CreateAlloca(InternalIVTy, nullptr, "p.upperbound");
2079   Value *PStride = Builder.CreateAlloca(InternalIVTy, nullptr, "p.stride");
2080 
2081   // Set up the source location value for the OpenMP runtime.
2082   Builder.restoreIP(CLI->getPreheaderIP());
2083   Builder.SetCurrentDebugLocation(DL);
2084 
2085   // TODO: Detect overflow in ubsan or max-out with current tripcount.
2086   Value *CastedChunkSize =
2087       Builder.CreateZExtOrTrunc(ChunkSize, InternalIVTy, "chunksize");
2088   Value *CastedTripCount =
2089       Builder.CreateZExt(OrigTripCount, InternalIVTy, "tripcount");
2090 
2091   Constant *SchedulingType = ConstantInt::get(
2092       I32Type, static_cast<int>(OMPScheduleType::UnorderedStaticChunked));
2093   Builder.CreateStore(Zero, PLowerBound);
2094   Value *OrigUpperBound = Builder.CreateSub(CastedTripCount, One);
2095   Builder.CreateStore(OrigUpperBound, PUpperBound);
2096   Builder.CreateStore(One, PStride);
2097 
2098   // Call the "init" function and update the trip count of the loop with the
2099   // value it produced.
2100   uint32_t SrcLocStrSize;
2101   Constant *SrcLocStr = getOrCreateSrcLocStr(DL, SrcLocStrSize);
2102   Value *SrcLoc = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
2103   Value *ThreadNum = getOrCreateThreadID(SrcLoc);
2104   Builder.CreateCall(StaticInit,
2105                      {/*loc=*/SrcLoc, /*global_tid=*/ThreadNum,
2106                       /*schedtype=*/SchedulingType, /*plastiter=*/PLastIter,
2107                       /*plower=*/PLowerBound, /*pupper=*/PUpperBound,
2108                       /*pstride=*/PStride, /*incr=*/One,
2109                       /*chunk=*/CastedChunkSize});
2110 
2111   // Load values written by the "init" function.
2112   Value *FirstChunkStart =
2113       Builder.CreateLoad(InternalIVTy, PLowerBound, "omp_firstchunk.lb");
2114   Value *FirstChunkStop =
2115       Builder.CreateLoad(InternalIVTy, PUpperBound, "omp_firstchunk.ub");
2116   Value *FirstChunkEnd = Builder.CreateAdd(FirstChunkStop, One);
2117   Value *ChunkRange =
2118       Builder.CreateSub(FirstChunkEnd, FirstChunkStart, "omp_chunk.range");
2119   Value *NextChunkStride =
2120       Builder.CreateLoad(InternalIVTy, PStride, "omp_dispatch.stride");
2121 
2122   // Create outer "dispatch" loop for enumerating the chunks.
2123   BasicBlock *DispatchEnter = splitBB(Builder, true);
2124   Value *DispatchCounter;
2125   CanonicalLoopInfo *DispatchCLI = createCanonicalLoop(
2126       {Builder.saveIP(), DL},
2127       [&](InsertPointTy BodyIP, Value *Counter) { DispatchCounter = Counter; },
2128       FirstChunkStart, CastedTripCount, NextChunkStride,
2129       /*IsSigned=*/false, /*InclusiveStop=*/false, /*ComputeIP=*/{},
2130       "dispatch");
2131 
2132   // Remember the BasicBlocks of the dispatch loop we need, then invalidate to
2133   // not have to preserve the canonical invariant.
2134   BasicBlock *DispatchBody = DispatchCLI->getBody();
2135   BasicBlock *DispatchLatch = DispatchCLI->getLatch();
2136   BasicBlock *DispatchExit = DispatchCLI->getExit();
2137   BasicBlock *DispatchAfter = DispatchCLI->getAfter();
2138   DispatchCLI->invalidate();
2139 
2140   // Rewire the original loop to become the chunk loop inside the dispatch loop.
2141   redirectTo(DispatchAfter, CLI->getAfter(), DL);
2142   redirectTo(CLI->getExit(), DispatchLatch, DL);
2143   redirectTo(DispatchBody, DispatchEnter, DL);
2144 
2145   // Prepare the prolog of the chunk loop.
2146   Builder.restoreIP(CLI->getPreheaderIP());
2147   Builder.SetCurrentDebugLocation(DL);
2148 
2149   // Compute the number of iterations of the chunk loop.
2150   Builder.SetInsertPoint(CLI->getPreheader()->getTerminator());
2151   Value *ChunkEnd = Builder.CreateAdd(DispatchCounter, ChunkRange);
2152   Value *IsLastChunk =
2153       Builder.CreateICmpUGE(ChunkEnd, CastedTripCount, "omp_chunk.is_last");
2154   Value *CountUntilOrigTripCount =
2155       Builder.CreateSub(CastedTripCount, DispatchCounter);
2156   Value *ChunkTripCount = Builder.CreateSelect(
2157       IsLastChunk, CountUntilOrigTripCount, ChunkRange, "omp_chunk.tripcount");
2158   Value *BackcastedChunkTC =
2159       Builder.CreateTrunc(ChunkTripCount, IVTy, "omp_chunk.tripcount.trunc");
2160   CLI->setTripCount(BackcastedChunkTC);
2161 
2162   // Update all uses of the induction variable except the one in the condition
2163   // block that compares it with the actual upper bound, and the increment in
2164   // the latch block.
2165   Value *BackcastedDispatchCounter =
2166       Builder.CreateTrunc(DispatchCounter, IVTy, "omp_dispatch.iv.trunc");
2167   CLI->mapIndVar([&](Instruction *) -> Value * {
2168     Builder.restoreIP(CLI->getBodyIP());
2169     return Builder.CreateAdd(IV, BackcastedDispatchCounter);
2170   });
2171 
2172   // In the "exit" block, call the "fini" function.
2173   Builder.SetInsertPoint(DispatchExit, DispatchExit->getFirstInsertionPt());
2174   Builder.CreateCall(StaticFini, {SrcLoc, ThreadNum});
2175 
2176   // Add the barrier if requested.
2177   if (NeedsBarrier)
2178     createBarrier(LocationDescription(Builder.saveIP(), DL), OMPD_for,
2179                   /*ForceSimpleCall=*/false, /*CheckCancelFlag=*/false);
2180 
2181 #ifndef NDEBUG
2182   // Even though we currently do not support applying additional methods to it,
2183   // the chunk loop should remain a canonical loop.
2184   CLI->assertOK();
2185 #endif
2186 
2187   return {DispatchAfter, DispatchAfter->getFirstInsertionPt()};
2188 }
2189 
2190 OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::applyWorkshareLoop(
2191     DebugLoc DL, CanonicalLoopInfo *CLI, InsertPointTy AllocaIP,
2192     bool NeedsBarrier, llvm::omp::ScheduleKind SchedKind,
2193     llvm::Value *ChunkSize, bool HasSimdModifier, bool HasMonotonicModifier,
2194     bool HasNonmonotonicModifier, bool HasOrderedClause) {
2195   OMPScheduleType EffectiveScheduleType = computeOpenMPScheduleType(
2196       SchedKind, ChunkSize, HasSimdModifier, HasMonotonicModifier,
2197       HasNonmonotonicModifier, HasOrderedClause);
2198 
2199   bool IsOrdered = (EffectiveScheduleType & OMPScheduleType::ModifierOrdered) ==
2200                    OMPScheduleType::ModifierOrdered;
2201   switch (EffectiveScheduleType & ~OMPScheduleType::ModifierMask) {
2202   case OMPScheduleType::BaseStatic:
2203     assert(!ChunkSize && "No chunk size with static-chunked schedule");
2204     if (IsOrdered)
2205       return applyDynamicWorkshareLoop(DL, CLI, AllocaIP, EffectiveScheduleType,
2206                                        NeedsBarrier, ChunkSize);
2207     // FIXME: Monotonicity ignored?
2208     return applyStaticWorkshareLoop(DL, CLI, AllocaIP, NeedsBarrier);
2209 
2210   case OMPScheduleType::BaseStaticChunked:
2211     if (IsOrdered)
2212       return applyDynamicWorkshareLoop(DL, CLI, AllocaIP, EffectiveScheduleType,
2213                                        NeedsBarrier, ChunkSize);
2214     // FIXME: Monotonicity ignored?
2215     return applyStaticChunkedWorkshareLoop(DL, CLI, AllocaIP, NeedsBarrier,
2216                                            ChunkSize);
2217 
2218   case OMPScheduleType::BaseRuntime:
2219   case OMPScheduleType::BaseAuto:
2220   case OMPScheduleType::BaseGreedy:
2221   case OMPScheduleType::BaseBalanced:
2222   case OMPScheduleType::BaseSteal:
2223   case OMPScheduleType::BaseGuidedSimd:
2224   case OMPScheduleType::BaseRuntimeSimd:
2225     assert(!ChunkSize &&
2226            "schedule type does not support user-defined chunk sizes");
2227     LLVM_FALLTHROUGH;
2228   case OMPScheduleType::BaseDynamicChunked:
2229   case OMPScheduleType::BaseGuidedChunked:
2230   case OMPScheduleType::BaseGuidedIterativeChunked:
2231   case OMPScheduleType::BaseGuidedAnalyticalChunked:
2232   case OMPScheduleType::BaseStaticBalancedChunked:
2233     return applyDynamicWorkshareLoop(DL, CLI, AllocaIP, EffectiveScheduleType,
2234                                      NeedsBarrier, ChunkSize);
2235 
2236   default:
2237     llvm_unreachable("Unknown/unimplemented schedule kind");
2238   }
2239 }
2240 
2241 /// Returns an LLVM function to call for initializing loop bounds using OpenMP
2242 /// dynamic scheduling depending on `type`. Only i32 and i64 are supported by
2243 /// the runtime. Always interpret integers as unsigned similarly to
2244 /// CanonicalLoopInfo.
2245 static FunctionCallee
2246 getKmpcForDynamicInitForType(Type *Ty, Module &M, OpenMPIRBuilder &OMPBuilder) {
2247   unsigned Bitwidth = Ty->getIntegerBitWidth();
2248   if (Bitwidth == 32)
2249     return OMPBuilder.getOrCreateRuntimeFunction(
2250         M, omp::RuntimeFunction::OMPRTL___kmpc_dispatch_init_4u);
2251   if (Bitwidth == 64)
2252     return OMPBuilder.getOrCreateRuntimeFunction(
2253         M, omp::RuntimeFunction::OMPRTL___kmpc_dispatch_init_8u);
2254   llvm_unreachable("unknown OpenMP loop iterator bitwidth");
2255 }
2256 
2257 /// Returns an LLVM function to call for updating the next loop using OpenMP
2258 /// dynamic scheduling depending on `type`. Only i32 and i64 are supported by
2259 /// the runtime. Always interpret integers as unsigned similarly to
2260 /// CanonicalLoopInfo.
2261 static FunctionCallee
2262 getKmpcForDynamicNextForType(Type *Ty, Module &M, OpenMPIRBuilder &OMPBuilder) {
2263   unsigned Bitwidth = Ty->getIntegerBitWidth();
2264   if (Bitwidth == 32)
2265     return OMPBuilder.getOrCreateRuntimeFunction(
2266         M, omp::RuntimeFunction::OMPRTL___kmpc_dispatch_next_4u);
2267   if (Bitwidth == 64)
2268     return OMPBuilder.getOrCreateRuntimeFunction(
2269         M, omp::RuntimeFunction::OMPRTL___kmpc_dispatch_next_8u);
2270   llvm_unreachable("unknown OpenMP loop iterator bitwidth");
2271 }
2272 
2273 /// Returns an LLVM function to call for finalizing the dynamic loop using
2274 /// depending on `type`. Only i32 and i64 are supported by the runtime. Always
2275 /// interpret integers as unsigned similarly to CanonicalLoopInfo.
2276 static FunctionCallee
2277 getKmpcForDynamicFiniForType(Type *Ty, Module &M, OpenMPIRBuilder &OMPBuilder) {
2278   unsigned Bitwidth = Ty->getIntegerBitWidth();
2279   if (Bitwidth == 32)
2280     return OMPBuilder.getOrCreateRuntimeFunction(
2281         M, omp::RuntimeFunction::OMPRTL___kmpc_dispatch_fini_4u);
2282   if (Bitwidth == 64)
2283     return OMPBuilder.getOrCreateRuntimeFunction(
2284         M, omp::RuntimeFunction::OMPRTL___kmpc_dispatch_fini_8u);
2285   llvm_unreachable("unknown OpenMP loop iterator bitwidth");
2286 }
2287 
2288 OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::applyDynamicWorkshareLoop(
2289     DebugLoc DL, CanonicalLoopInfo *CLI, InsertPointTy AllocaIP,
2290     OMPScheduleType SchedType, bool NeedsBarrier, Value *Chunk) {
2291   assert(CLI->isValid() && "Requires a valid canonical loop");
2292   assert(!isConflictIP(AllocaIP, CLI->getPreheaderIP()) &&
2293          "Require dedicated allocate IP");
2294   assert(isValidWorkshareLoopScheduleType(SchedType) &&
2295          "Require valid schedule type");
2296 
2297   bool Ordered = (SchedType & OMPScheduleType::ModifierOrdered) ==
2298                  OMPScheduleType::ModifierOrdered;
2299 
2300   // Set up the source location value for OpenMP runtime.
2301   Builder.SetCurrentDebugLocation(DL);
2302 
2303   uint32_t SrcLocStrSize;
2304   Constant *SrcLocStr = getOrCreateSrcLocStr(DL, SrcLocStrSize);
2305   Value *SrcLoc = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
2306 
2307   // Declare useful OpenMP runtime functions.
2308   Value *IV = CLI->getIndVar();
2309   Type *IVTy = IV->getType();
2310   FunctionCallee DynamicInit = getKmpcForDynamicInitForType(IVTy, M, *this);
2311   FunctionCallee DynamicNext = getKmpcForDynamicNextForType(IVTy, M, *this);
2312 
2313   // Allocate space for computed loop bounds as expected by the "init" function.
2314   Builder.restoreIP(AllocaIP);
2315   Type *I32Type = Type::getInt32Ty(M.getContext());
2316   Value *PLastIter = Builder.CreateAlloca(I32Type, nullptr, "p.lastiter");
2317   Value *PLowerBound = Builder.CreateAlloca(IVTy, nullptr, "p.lowerbound");
2318   Value *PUpperBound = Builder.CreateAlloca(IVTy, nullptr, "p.upperbound");
2319   Value *PStride = Builder.CreateAlloca(IVTy, nullptr, "p.stride");
2320 
2321   // At the end of the preheader, prepare for calling the "init" function by
2322   // storing the current loop bounds into the allocated space. A canonical loop
2323   // always iterates from 0 to trip-count with step 1. Note that "init" expects
2324   // and produces an inclusive upper bound.
2325   BasicBlock *PreHeader = CLI->getPreheader();
2326   Builder.SetInsertPoint(PreHeader->getTerminator());
2327   Constant *One = ConstantInt::get(IVTy, 1);
2328   Builder.CreateStore(One, PLowerBound);
2329   Value *UpperBound = CLI->getTripCount();
2330   Builder.CreateStore(UpperBound, PUpperBound);
2331   Builder.CreateStore(One, PStride);
2332 
2333   BasicBlock *Header = CLI->getHeader();
2334   BasicBlock *Exit = CLI->getExit();
2335   BasicBlock *Cond = CLI->getCond();
2336   BasicBlock *Latch = CLI->getLatch();
2337   InsertPointTy AfterIP = CLI->getAfterIP();
2338 
2339   // The CLI will be "broken" in the code below, as the loop is no longer
2340   // a valid canonical loop.
2341 
2342   if (!Chunk)
2343     Chunk = One;
2344 
2345   Value *ThreadNum = getOrCreateThreadID(SrcLoc);
2346 
2347   Constant *SchedulingType =
2348       ConstantInt::get(I32Type, static_cast<int>(SchedType));
2349 
2350   // Call the "init" function.
2351   Builder.CreateCall(DynamicInit,
2352                      {SrcLoc, ThreadNum, SchedulingType, /* LowerBound */ One,
2353                       UpperBound, /* step */ One, Chunk});
2354 
2355   // An outer loop around the existing one.
2356   BasicBlock *OuterCond = BasicBlock::Create(
2357       PreHeader->getContext(), Twine(PreHeader->getName()) + ".outer.cond",
2358       PreHeader->getParent());
2359   // This needs to be 32-bit always, so can't use the IVTy Zero above.
2360   Builder.SetInsertPoint(OuterCond, OuterCond->getFirstInsertionPt());
2361   Value *Res =
2362       Builder.CreateCall(DynamicNext, {SrcLoc, ThreadNum, PLastIter,
2363                                        PLowerBound, PUpperBound, PStride});
2364   Constant *Zero32 = ConstantInt::get(I32Type, 0);
2365   Value *MoreWork = Builder.CreateCmp(CmpInst::ICMP_NE, Res, Zero32);
2366   Value *LowerBound =
2367       Builder.CreateSub(Builder.CreateLoad(IVTy, PLowerBound), One, "lb");
2368   Builder.CreateCondBr(MoreWork, Header, Exit);
2369 
2370   // Change PHI-node in loop header to use outer cond rather than preheader,
2371   // and set IV to the LowerBound.
2372   Instruction *Phi = &Header->front();
2373   auto *PI = cast<PHINode>(Phi);
2374   PI->setIncomingBlock(0, OuterCond);
2375   PI->setIncomingValue(0, LowerBound);
2376 
2377   // Then set the pre-header to jump to the OuterCond
2378   Instruction *Term = PreHeader->getTerminator();
2379   auto *Br = cast<BranchInst>(Term);
2380   Br->setSuccessor(0, OuterCond);
2381 
2382   // Modify the inner condition:
2383   // * Use the UpperBound returned from the DynamicNext call.
2384   // * jump to the loop outer loop when done with one of the inner loops.
2385   Builder.SetInsertPoint(Cond, Cond->getFirstInsertionPt());
2386   UpperBound = Builder.CreateLoad(IVTy, PUpperBound, "ub");
2387   Instruction *Comp = &*Builder.GetInsertPoint();
2388   auto *CI = cast<CmpInst>(Comp);
2389   CI->setOperand(1, UpperBound);
2390   // Redirect the inner exit to branch to outer condition.
2391   Instruction *Branch = &Cond->back();
2392   auto *BI = cast<BranchInst>(Branch);
2393   assert(BI->getSuccessor(1) == Exit);
2394   BI->setSuccessor(1, OuterCond);
2395 
2396   // Call the "fini" function if "ordered" is present in wsloop directive.
2397   if (Ordered) {
2398     Builder.SetInsertPoint(&Latch->back());
2399     FunctionCallee DynamicFini = getKmpcForDynamicFiniForType(IVTy, M, *this);
2400     Builder.CreateCall(DynamicFini, {SrcLoc, ThreadNum});
2401   }
2402 
2403   // Add the barrier if requested.
2404   if (NeedsBarrier) {
2405     Builder.SetInsertPoint(&Exit->back());
2406     createBarrier(LocationDescription(Builder.saveIP(), DL),
2407                   omp::Directive::OMPD_for, /* ForceSimpleCall */ false,
2408                   /* CheckCancelFlag */ false);
2409   }
2410 
2411   CLI->invalidate();
2412   return AfterIP;
2413 }
2414 
2415 /// Redirect all edges that branch to \p OldTarget to \p NewTarget. That is,
2416 /// after this \p OldTarget will be orphaned.
2417 static void redirectAllPredecessorsTo(BasicBlock *OldTarget,
2418                                       BasicBlock *NewTarget, DebugLoc DL) {
2419   for (BasicBlock *Pred : make_early_inc_range(predecessors(OldTarget)))
2420     redirectTo(Pred, NewTarget, DL);
2421 }
2422 
2423 /// Determine which blocks in \p BBs are reachable from outside and remove the
2424 /// ones that are not reachable from the function.
2425 static void removeUnusedBlocksFromParent(ArrayRef<BasicBlock *> BBs) {
2426   SmallPtrSet<BasicBlock *, 6> BBsToErase{BBs.begin(), BBs.end()};
2427   auto HasRemainingUses = [&BBsToErase](BasicBlock *BB) {
2428     for (Use &U : BB->uses()) {
2429       auto *UseInst = dyn_cast<Instruction>(U.getUser());
2430       if (!UseInst)
2431         continue;
2432       if (BBsToErase.count(UseInst->getParent()))
2433         continue;
2434       return true;
2435     }
2436     return false;
2437   };
2438 
2439   while (true) {
2440     bool Changed = false;
2441     for (BasicBlock *BB : make_early_inc_range(BBsToErase)) {
2442       if (HasRemainingUses(BB)) {
2443         BBsToErase.erase(BB);
2444         Changed = true;
2445       }
2446     }
2447     if (!Changed)
2448       break;
2449   }
2450 
2451   SmallVector<BasicBlock *, 7> BBVec(BBsToErase.begin(), BBsToErase.end());
2452   DeleteDeadBlocks(BBVec);
2453 }
2454 
2455 CanonicalLoopInfo *
2456 OpenMPIRBuilder::collapseLoops(DebugLoc DL, ArrayRef<CanonicalLoopInfo *> Loops,
2457                                InsertPointTy ComputeIP) {
2458   assert(Loops.size() >= 1 && "At least one loop required");
2459   size_t NumLoops = Loops.size();
2460 
2461   // Nothing to do if there is already just one loop.
2462   if (NumLoops == 1)
2463     return Loops.front();
2464 
2465   CanonicalLoopInfo *Outermost = Loops.front();
2466   CanonicalLoopInfo *Innermost = Loops.back();
2467   BasicBlock *OrigPreheader = Outermost->getPreheader();
2468   BasicBlock *OrigAfter = Outermost->getAfter();
2469   Function *F = OrigPreheader->getParent();
2470 
2471   // Loop control blocks that may become orphaned later.
2472   SmallVector<BasicBlock *, 12> OldControlBBs;
2473   OldControlBBs.reserve(6 * Loops.size());
2474   for (CanonicalLoopInfo *Loop : Loops)
2475     Loop->collectControlBlocks(OldControlBBs);
2476 
2477   // Setup the IRBuilder for inserting the trip count computation.
2478   Builder.SetCurrentDebugLocation(DL);
2479   if (ComputeIP.isSet())
2480     Builder.restoreIP(ComputeIP);
2481   else
2482     Builder.restoreIP(Outermost->getPreheaderIP());
2483 
2484   // Derive the collapsed' loop trip count.
2485   // TODO: Find common/largest indvar type.
2486   Value *CollapsedTripCount = nullptr;
2487   for (CanonicalLoopInfo *L : Loops) {
2488     assert(L->isValid() &&
2489            "All loops to collapse must be valid canonical loops");
2490     Value *OrigTripCount = L->getTripCount();
2491     if (!CollapsedTripCount) {
2492       CollapsedTripCount = OrigTripCount;
2493       continue;
2494     }
2495 
2496     // TODO: Enable UndefinedSanitizer to diagnose an overflow here.
2497     CollapsedTripCount = Builder.CreateMul(CollapsedTripCount, OrigTripCount,
2498                                            {}, /*HasNUW=*/true);
2499   }
2500 
2501   // Create the collapsed loop control flow.
2502   CanonicalLoopInfo *Result =
2503       createLoopSkeleton(DL, CollapsedTripCount, F,
2504                          OrigPreheader->getNextNode(), OrigAfter, "collapsed");
2505 
2506   // Build the collapsed loop body code.
2507   // Start with deriving the input loop induction variables from the collapsed
2508   // one, using a divmod scheme. To preserve the original loops' order, the
2509   // innermost loop use the least significant bits.
2510   Builder.restoreIP(Result->getBodyIP());
2511 
2512   Value *Leftover = Result->getIndVar();
2513   SmallVector<Value *> NewIndVars;
2514   NewIndVars.resize(NumLoops);
2515   for (int i = NumLoops - 1; i >= 1; --i) {
2516     Value *OrigTripCount = Loops[i]->getTripCount();
2517 
2518     Value *NewIndVar = Builder.CreateURem(Leftover, OrigTripCount);
2519     NewIndVars[i] = NewIndVar;
2520 
2521     Leftover = Builder.CreateUDiv(Leftover, OrigTripCount);
2522   }
2523   // Outermost loop gets all the remaining bits.
2524   NewIndVars[0] = Leftover;
2525 
2526   // Construct the loop body control flow.
2527   // We progressively construct the branch structure following in direction of
2528   // the control flow, from the leading in-between code, the loop nest body, the
2529   // trailing in-between code, and rejoining the collapsed loop's latch.
2530   // ContinueBlock and ContinuePred keep track of the source(s) of next edge. If
2531   // the ContinueBlock is set, continue with that block. If ContinuePred, use
2532   // its predecessors as sources.
2533   BasicBlock *ContinueBlock = Result->getBody();
2534   BasicBlock *ContinuePred = nullptr;
2535   auto ContinueWith = [&ContinueBlock, &ContinuePred, DL](BasicBlock *Dest,
2536                                                           BasicBlock *NextSrc) {
2537     if (ContinueBlock)
2538       redirectTo(ContinueBlock, Dest, DL);
2539     else
2540       redirectAllPredecessorsTo(ContinuePred, Dest, DL);
2541 
2542     ContinueBlock = nullptr;
2543     ContinuePred = NextSrc;
2544   };
2545 
2546   // The code before the nested loop of each level.
2547   // Because we are sinking it into the nest, it will be executed more often
2548   // that the original loop. More sophisticated schemes could keep track of what
2549   // the in-between code is and instantiate it only once per thread.
2550   for (size_t i = 0; i < NumLoops - 1; ++i)
2551     ContinueWith(Loops[i]->getBody(), Loops[i + 1]->getHeader());
2552 
2553   // Connect the loop nest body.
2554   ContinueWith(Innermost->getBody(), Innermost->getLatch());
2555 
2556   // The code after the nested loop at each level.
2557   for (size_t i = NumLoops - 1; i > 0; --i)
2558     ContinueWith(Loops[i]->getAfter(), Loops[i - 1]->getLatch());
2559 
2560   // Connect the finished loop to the collapsed loop latch.
2561   ContinueWith(Result->getLatch(), nullptr);
2562 
2563   // Replace the input loops with the new collapsed loop.
2564   redirectTo(Outermost->getPreheader(), Result->getPreheader(), DL);
2565   redirectTo(Result->getAfter(), Outermost->getAfter(), DL);
2566 
2567   // Replace the input loop indvars with the derived ones.
2568   for (size_t i = 0; i < NumLoops; ++i)
2569     Loops[i]->getIndVar()->replaceAllUsesWith(NewIndVars[i]);
2570 
2571   // Remove unused parts of the input loops.
2572   removeUnusedBlocksFromParent(OldControlBBs);
2573 
2574   for (CanonicalLoopInfo *L : Loops)
2575     L->invalidate();
2576 
2577 #ifndef NDEBUG
2578   Result->assertOK();
2579 #endif
2580   return Result;
2581 }
2582 
2583 std::vector<CanonicalLoopInfo *>
2584 OpenMPIRBuilder::tileLoops(DebugLoc DL, ArrayRef<CanonicalLoopInfo *> Loops,
2585                            ArrayRef<Value *> TileSizes) {
2586   assert(TileSizes.size() == Loops.size() &&
2587          "Must pass as many tile sizes as there are loops");
2588   int NumLoops = Loops.size();
2589   assert(NumLoops >= 1 && "At least one loop to tile required");
2590 
2591   CanonicalLoopInfo *OutermostLoop = Loops.front();
2592   CanonicalLoopInfo *InnermostLoop = Loops.back();
2593   Function *F = OutermostLoop->getBody()->getParent();
2594   BasicBlock *InnerEnter = InnermostLoop->getBody();
2595   BasicBlock *InnerLatch = InnermostLoop->getLatch();
2596 
2597   // Loop control blocks that may become orphaned later.
2598   SmallVector<BasicBlock *, 12> OldControlBBs;
2599   OldControlBBs.reserve(6 * Loops.size());
2600   for (CanonicalLoopInfo *Loop : Loops)
2601     Loop->collectControlBlocks(OldControlBBs);
2602 
2603   // Collect original trip counts and induction variable to be accessible by
2604   // index. Also, the structure of the original loops is not preserved during
2605   // the construction of the tiled loops, so do it before we scavenge the BBs of
2606   // any original CanonicalLoopInfo.
2607   SmallVector<Value *, 4> OrigTripCounts, OrigIndVars;
2608   for (CanonicalLoopInfo *L : Loops) {
2609     assert(L->isValid() && "All input loops must be valid canonical loops");
2610     OrigTripCounts.push_back(L->getTripCount());
2611     OrigIndVars.push_back(L->getIndVar());
2612   }
2613 
2614   // Collect the code between loop headers. These may contain SSA definitions
2615   // that are used in the loop nest body. To be usable with in the innermost
2616   // body, these BasicBlocks will be sunk into the loop nest body. That is,
2617   // these instructions may be executed more often than before the tiling.
2618   // TODO: It would be sufficient to only sink them into body of the
2619   // corresponding tile loop.
2620   SmallVector<std::pair<BasicBlock *, BasicBlock *>, 4> InbetweenCode;
2621   for (int i = 0; i < NumLoops - 1; ++i) {
2622     CanonicalLoopInfo *Surrounding = Loops[i];
2623     CanonicalLoopInfo *Nested = Loops[i + 1];
2624 
2625     BasicBlock *EnterBB = Surrounding->getBody();
2626     BasicBlock *ExitBB = Nested->getHeader();
2627     InbetweenCode.emplace_back(EnterBB, ExitBB);
2628   }
2629 
2630   // Compute the trip counts of the floor loops.
2631   Builder.SetCurrentDebugLocation(DL);
2632   Builder.restoreIP(OutermostLoop->getPreheaderIP());
2633   SmallVector<Value *, 4> FloorCount, FloorRems;
2634   for (int i = 0; i < NumLoops; ++i) {
2635     Value *TileSize = TileSizes[i];
2636     Value *OrigTripCount = OrigTripCounts[i];
2637     Type *IVType = OrigTripCount->getType();
2638 
2639     Value *FloorTripCount = Builder.CreateUDiv(OrigTripCount, TileSize);
2640     Value *FloorTripRem = Builder.CreateURem(OrigTripCount, TileSize);
2641 
2642     // 0 if tripcount divides the tilesize, 1 otherwise.
2643     // 1 means we need an additional iteration for a partial tile.
2644     //
2645     // Unfortunately we cannot just use the roundup-formula
2646     //   (tripcount + tilesize - 1)/tilesize
2647     // because the summation might overflow. We do not want introduce undefined
2648     // behavior when the untiled loop nest did not.
2649     Value *FloorTripOverflow =
2650         Builder.CreateICmpNE(FloorTripRem, ConstantInt::get(IVType, 0));
2651 
2652     FloorTripOverflow = Builder.CreateZExt(FloorTripOverflow, IVType);
2653     FloorTripCount =
2654         Builder.CreateAdd(FloorTripCount, FloorTripOverflow,
2655                           "omp_floor" + Twine(i) + ".tripcount", true);
2656 
2657     // Remember some values for later use.
2658     FloorCount.push_back(FloorTripCount);
2659     FloorRems.push_back(FloorTripRem);
2660   }
2661 
2662   // Generate the new loop nest, from the outermost to the innermost.
2663   std::vector<CanonicalLoopInfo *> Result;
2664   Result.reserve(NumLoops * 2);
2665 
2666   // The basic block of the surrounding loop that enters the nest generated
2667   // loop.
2668   BasicBlock *Enter = OutermostLoop->getPreheader();
2669 
2670   // The basic block of the surrounding loop where the inner code should
2671   // continue.
2672   BasicBlock *Continue = OutermostLoop->getAfter();
2673 
2674   // Where the next loop basic block should be inserted.
2675   BasicBlock *OutroInsertBefore = InnermostLoop->getExit();
2676 
2677   auto EmbeddNewLoop =
2678       [this, DL, F, InnerEnter, &Enter, &Continue, &OutroInsertBefore](
2679           Value *TripCount, const Twine &Name) -> CanonicalLoopInfo * {
2680     CanonicalLoopInfo *EmbeddedLoop = createLoopSkeleton(
2681         DL, TripCount, F, InnerEnter, OutroInsertBefore, Name);
2682     redirectTo(Enter, EmbeddedLoop->getPreheader(), DL);
2683     redirectTo(EmbeddedLoop->getAfter(), Continue, DL);
2684 
2685     // Setup the position where the next embedded loop connects to this loop.
2686     Enter = EmbeddedLoop->getBody();
2687     Continue = EmbeddedLoop->getLatch();
2688     OutroInsertBefore = EmbeddedLoop->getLatch();
2689     return EmbeddedLoop;
2690   };
2691 
2692   auto EmbeddNewLoops = [&Result, &EmbeddNewLoop](ArrayRef<Value *> TripCounts,
2693                                                   const Twine &NameBase) {
2694     for (auto P : enumerate(TripCounts)) {
2695       CanonicalLoopInfo *EmbeddedLoop =
2696           EmbeddNewLoop(P.value(), NameBase + Twine(P.index()));
2697       Result.push_back(EmbeddedLoop);
2698     }
2699   };
2700 
2701   EmbeddNewLoops(FloorCount, "floor");
2702 
2703   // Within the innermost floor loop, emit the code that computes the tile
2704   // sizes.
2705   Builder.SetInsertPoint(Enter->getTerminator());
2706   SmallVector<Value *, 4> TileCounts;
2707   for (int i = 0; i < NumLoops; ++i) {
2708     CanonicalLoopInfo *FloorLoop = Result[i];
2709     Value *TileSize = TileSizes[i];
2710 
2711     Value *FloorIsEpilogue =
2712         Builder.CreateICmpEQ(FloorLoop->getIndVar(), FloorCount[i]);
2713     Value *TileTripCount =
2714         Builder.CreateSelect(FloorIsEpilogue, FloorRems[i], TileSize);
2715 
2716     TileCounts.push_back(TileTripCount);
2717   }
2718 
2719   // Create the tile loops.
2720   EmbeddNewLoops(TileCounts, "tile");
2721 
2722   // Insert the inbetween code into the body.
2723   BasicBlock *BodyEnter = Enter;
2724   BasicBlock *BodyEntered = nullptr;
2725   for (std::pair<BasicBlock *, BasicBlock *> P : InbetweenCode) {
2726     BasicBlock *EnterBB = P.first;
2727     BasicBlock *ExitBB = P.second;
2728 
2729     if (BodyEnter)
2730       redirectTo(BodyEnter, EnterBB, DL);
2731     else
2732       redirectAllPredecessorsTo(BodyEntered, EnterBB, DL);
2733 
2734     BodyEnter = nullptr;
2735     BodyEntered = ExitBB;
2736   }
2737 
2738   // Append the original loop nest body into the generated loop nest body.
2739   if (BodyEnter)
2740     redirectTo(BodyEnter, InnerEnter, DL);
2741   else
2742     redirectAllPredecessorsTo(BodyEntered, InnerEnter, DL);
2743   redirectAllPredecessorsTo(InnerLatch, Continue, DL);
2744 
2745   // Replace the original induction variable with an induction variable computed
2746   // from the tile and floor induction variables.
2747   Builder.restoreIP(Result.back()->getBodyIP());
2748   for (int i = 0; i < NumLoops; ++i) {
2749     CanonicalLoopInfo *FloorLoop = Result[i];
2750     CanonicalLoopInfo *TileLoop = Result[NumLoops + i];
2751     Value *OrigIndVar = OrigIndVars[i];
2752     Value *Size = TileSizes[i];
2753 
2754     Value *Scale =
2755         Builder.CreateMul(Size, FloorLoop->getIndVar(), {}, /*HasNUW=*/true);
2756     Value *Shift =
2757         Builder.CreateAdd(Scale, TileLoop->getIndVar(), {}, /*HasNUW=*/true);
2758     OrigIndVar->replaceAllUsesWith(Shift);
2759   }
2760 
2761   // Remove unused parts of the original loops.
2762   removeUnusedBlocksFromParent(OldControlBBs);
2763 
2764   for (CanonicalLoopInfo *L : Loops)
2765     L->invalidate();
2766 
2767 #ifndef NDEBUG
2768   for (CanonicalLoopInfo *GenL : Result)
2769     GenL->assertOK();
2770 #endif
2771   return Result;
2772 }
2773 
2774 /// Attach loop metadata \p Properties to the loop described by \p Loop. If the
2775 /// loop already has metadata, the loop properties are appended.
2776 static void addLoopMetadata(CanonicalLoopInfo *Loop,
2777                             ArrayRef<Metadata *> Properties) {
2778   assert(Loop->isValid() && "Expecting a valid CanonicalLoopInfo");
2779 
2780   // Nothing to do if no property to attach.
2781   if (Properties.empty())
2782     return;
2783 
2784   LLVMContext &Ctx = Loop->getFunction()->getContext();
2785   SmallVector<Metadata *> NewLoopProperties;
2786   NewLoopProperties.push_back(nullptr);
2787 
2788   // If the loop already has metadata, prepend it to the new metadata.
2789   BasicBlock *Latch = Loop->getLatch();
2790   assert(Latch && "A valid CanonicalLoopInfo must have a unique latch");
2791   MDNode *Existing = Latch->getTerminator()->getMetadata(LLVMContext::MD_loop);
2792   if (Existing)
2793     append_range(NewLoopProperties, drop_begin(Existing->operands(), 1));
2794 
2795   append_range(NewLoopProperties, Properties);
2796   MDNode *LoopID = MDNode::getDistinct(Ctx, NewLoopProperties);
2797   LoopID->replaceOperandWith(0, LoopID);
2798 
2799   Latch->getTerminator()->setMetadata(LLVMContext::MD_loop, LoopID);
2800 }
2801 
2802 /// Attach llvm.access.group metadata to the memref instructions of \p Block
2803 static void addSimdMetadata(BasicBlock *Block, MDNode *AccessGroup,
2804                             LoopInfo &LI) {
2805   for (Instruction &I : *Block) {
2806     if (I.mayReadOrWriteMemory()) {
2807       // TODO: This instruction may already have access group from
2808       // other pragmas e.g. #pragma clang loop vectorize.  Append
2809       // so that the existing metadata is not overwritten.
2810       I.setMetadata(LLVMContext::MD_access_group, AccessGroup);
2811     }
2812   }
2813 }
2814 
2815 void OpenMPIRBuilder::unrollLoopFull(DebugLoc, CanonicalLoopInfo *Loop) {
2816   LLVMContext &Ctx = Builder.getContext();
2817   addLoopMetadata(
2818       Loop, {MDNode::get(Ctx, MDString::get(Ctx, "llvm.loop.unroll.enable")),
2819              MDNode::get(Ctx, MDString::get(Ctx, "llvm.loop.unroll.full"))});
2820 }
2821 
2822 void OpenMPIRBuilder::unrollLoopHeuristic(DebugLoc, CanonicalLoopInfo *Loop) {
2823   LLVMContext &Ctx = Builder.getContext();
2824   addLoopMetadata(
2825       Loop, {
2826                 MDNode::get(Ctx, MDString::get(Ctx, "llvm.loop.unroll.enable")),
2827             });
2828 }
2829 
2830 void OpenMPIRBuilder::applySimd(DebugLoc, CanonicalLoopInfo *CanonicalLoop) {
2831   LLVMContext &Ctx = Builder.getContext();
2832 
2833   Function *F = CanonicalLoop->getFunction();
2834 
2835   FunctionAnalysisManager FAM;
2836   FAM.registerPass([]() { return DominatorTreeAnalysis(); });
2837   FAM.registerPass([]() { return LoopAnalysis(); });
2838   FAM.registerPass([]() { return PassInstrumentationAnalysis(); });
2839 
2840   LoopAnalysis LIA;
2841   LoopInfo &&LI = LIA.run(*F, FAM);
2842 
2843   Loop *L = LI.getLoopFor(CanonicalLoop->getHeader());
2844 
2845   SmallSet<BasicBlock *, 8> Reachable;
2846 
2847   // Get the basic blocks from the loop in which memref instructions
2848   // can be found.
2849   // TODO: Generalize getting all blocks inside a CanonicalizeLoopInfo,
2850   // preferably without running any passes.
2851   for (BasicBlock *Block : L->getBlocks()) {
2852     if (Block == CanonicalLoop->getCond() ||
2853         Block == CanonicalLoop->getHeader())
2854       continue;
2855     Reachable.insert(Block);
2856   }
2857 
2858   // Add access group metadata to memory-access instructions.
2859   MDNode *AccessGroup = MDNode::getDistinct(Ctx, {});
2860   for (BasicBlock *BB : Reachable)
2861     addSimdMetadata(BB, AccessGroup, LI);
2862 
2863   // Use the above access group metadata to create loop level
2864   // metadata, which should be distinct for each loop.
2865   ConstantAsMetadata *BoolConst =
2866       ConstantAsMetadata::get(ConstantInt::getTrue(Type::getInt1Ty(Ctx)));
2867   // TODO:  If the loop has existing parallel access metadata, have
2868   // to combine two lists.
2869   addLoopMetadata(
2870       CanonicalLoop,
2871       {MDNode::get(Ctx, {MDString::get(Ctx, "llvm.loop.parallel_accesses"),
2872                          AccessGroup}),
2873        MDNode::get(Ctx, {MDString::get(Ctx, "llvm.loop.vectorize.enable"),
2874                          BoolConst})});
2875 }
2876 
2877 /// Create the TargetMachine object to query the backend for optimization
2878 /// preferences.
2879 ///
2880 /// Ideally, this would be passed from the front-end to the OpenMPBuilder, but
2881 /// e.g. Clang does not pass it to its CodeGen layer and creates it only when
2882 /// needed for the LLVM pass pipline. We use some default options to avoid
2883 /// having to pass too many settings from the frontend that probably do not
2884 /// matter.
2885 ///
2886 /// Currently, TargetMachine is only used sometimes by the unrollLoopPartial
2887 /// method. If we are going to use TargetMachine for more purposes, especially
2888 /// those that are sensitive to TargetOptions, RelocModel and CodeModel, it
2889 /// might become be worth requiring front-ends to pass on their TargetMachine,
2890 /// or at least cache it between methods. Note that while fontends such as Clang
2891 /// have just a single main TargetMachine per translation unit, "target-cpu" and
2892 /// "target-features" that determine the TargetMachine are per-function and can
2893 /// be overrided using __attribute__((target("OPTIONS"))).
2894 static std::unique_ptr<TargetMachine>
2895 createTargetMachine(Function *F, CodeGenOpt::Level OptLevel) {
2896   Module *M = F->getParent();
2897 
2898   StringRef CPU = F->getFnAttribute("target-cpu").getValueAsString();
2899   StringRef Features = F->getFnAttribute("target-features").getValueAsString();
2900   const std::string &Triple = M->getTargetTriple();
2901 
2902   std::string Error;
2903   const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
2904   if (!TheTarget)
2905     return {};
2906 
2907   llvm::TargetOptions Options;
2908   return std::unique_ptr<TargetMachine>(TheTarget->createTargetMachine(
2909       Triple, CPU, Features, Options, /*RelocModel=*/None, /*CodeModel=*/None,
2910       OptLevel));
2911 }
2912 
2913 /// Heuristically determine the best-performant unroll factor for \p CLI. This
2914 /// depends on the target processor. We are re-using the same heuristics as the
2915 /// LoopUnrollPass.
2916 static int32_t computeHeuristicUnrollFactor(CanonicalLoopInfo *CLI) {
2917   Function *F = CLI->getFunction();
2918 
2919   // Assume the user requests the most aggressive unrolling, even if the rest of
2920   // the code is optimized using a lower setting.
2921   CodeGenOpt::Level OptLevel = CodeGenOpt::Aggressive;
2922   std::unique_ptr<TargetMachine> TM = createTargetMachine(F, OptLevel);
2923 
2924   FunctionAnalysisManager FAM;
2925   FAM.registerPass([]() { return TargetLibraryAnalysis(); });
2926   FAM.registerPass([]() { return AssumptionAnalysis(); });
2927   FAM.registerPass([]() { return DominatorTreeAnalysis(); });
2928   FAM.registerPass([]() { return LoopAnalysis(); });
2929   FAM.registerPass([]() { return ScalarEvolutionAnalysis(); });
2930   FAM.registerPass([]() { return PassInstrumentationAnalysis(); });
2931   TargetIRAnalysis TIRA;
2932   if (TM)
2933     TIRA = TargetIRAnalysis(
2934         [&](const Function &F) { return TM->getTargetTransformInfo(F); });
2935   FAM.registerPass([&]() { return TIRA; });
2936 
2937   TargetIRAnalysis::Result &&TTI = TIRA.run(*F, FAM);
2938   ScalarEvolutionAnalysis SEA;
2939   ScalarEvolution &&SE = SEA.run(*F, FAM);
2940   DominatorTreeAnalysis DTA;
2941   DominatorTree &&DT = DTA.run(*F, FAM);
2942   LoopAnalysis LIA;
2943   LoopInfo &&LI = LIA.run(*F, FAM);
2944   AssumptionAnalysis ACT;
2945   AssumptionCache &&AC = ACT.run(*F, FAM);
2946   OptimizationRemarkEmitter ORE{F};
2947 
2948   Loop *L = LI.getLoopFor(CLI->getHeader());
2949   assert(L && "Expecting CanonicalLoopInfo to be recognized as a loop");
2950 
2951   TargetTransformInfo::UnrollingPreferences UP =
2952       gatherUnrollingPreferences(L, SE, TTI,
2953                                  /*BlockFrequencyInfo=*/nullptr,
2954                                  /*ProfileSummaryInfo=*/nullptr, ORE, OptLevel,
2955                                  /*UserThreshold=*/None,
2956                                  /*UserCount=*/None,
2957                                  /*UserAllowPartial=*/true,
2958                                  /*UserAllowRuntime=*/true,
2959                                  /*UserUpperBound=*/None,
2960                                  /*UserFullUnrollMaxCount=*/None);
2961 
2962   UP.Force = true;
2963 
2964   // Account for additional optimizations taking place before the LoopUnrollPass
2965   // would unroll the loop.
2966   UP.Threshold *= UnrollThresholdFactor;
2967   UP.PartialThreshold *= UnrollThresholdFactor;
2968 
2969   // Use normal unroll factors even if the rest of the code is optimized for
2970   // size.
2971   UP.OptSizeThreshold = UP.Threshold;
2972   UP.PartialOptSizeThreshold = UP.PartialThreshold;
2973 
2974   LLVM_DEBUG(dbgs() << "Unroll heuristic thresholds:\n"
2975                     << "  Threshold=" << UP.Threshold << "\n"
2976                     << "  PartialThreshold=" << UP.PartialThreshold << "\n"
2977                     << "  OptSizeThreshold=" << UP.OptSizeThreshold << "\n"
2978                     << "  PartialOptSizeThreshold="
2979                     << UP.PartialOptSizeThreshold << "\n");
2980 
2981   // Disable peeling.
2982   TargetTransformInfo::PeelingPreferences PP =
2983       gatherPeelingPreferences(L, SE, TTI,
2984                                /*UserAllowPeeling=*/false,
2985                                /*UserAllowProfileBasedPeeling=*/false,
2986                                /*UnrollingSpecficValues=*/false);
2987 
2988   SmallPtrSet<const Value *, 32> EphValues;
2989   CodeMetrics::collectEphemeralValues(L, &AC, EphValues);
2990 
2991   // Assume that reads and writes to stack variables can be eliminated by
2992   // Mem2Reg, SROA or LICM. That is, don't count them towards the loop body's
2993   // size.
2994   for (BasicBlock *BB : L->blocks()) {
2995     for (Instruction &I : *BB) {
2996       Value *Ptr;
2997       if (auto *Load = dyn_cast<LoadInst>(&I)) {
2998         Ptr = Load->getPointerOperand();
2999       } else if (auto *Store = dyn_cast<StoreInst>(&I)) {
3000         Ptr = Store->getPointerOperand();
3001       } else
3002         continue;
3003 
3004       Ptr = Ptr->stripPointerCasts();
3005 
3006       if (auto *Alloca = dyn_cast<AllocaInst>(Ptr)) {
3007         if (Alloca->getParent() == &F->getEntryBlock())
3008           EphValues.insert(&I);
3009       }
3010     }
3011   }
3012 
3013   unsigned NumInlineCandidates;
3014   bool NotDuplicatable;
3015   bool Convergent;
3016   unsigned LoopSize =
3017       ApproximateLoopSize(L, NumInlineCandidates, NotDuplicatable, Convergent,
3018                           TTI, EphValues, UP.BEInsns);
3019   LLVM_DEBUG(dbgs() << "Estimated loop size is " << LoopSize << "\n");
3020 
3021   // Loop is not unrollable if the loop contains certain instructions.
3022   if (NotDuplicatable || Convergent) {
3023     LLVM_DEBUG(dbgs() << "Loop not considered unrollable\n");
3024     return 1;
3025   }
3026 
3027   // TODO: Determine trip count of \p CLI if constant, computeUnrollCount might
3028   // be able to use it.
3029   int TripCount = 0;
3030   int MaxTripCount = 0;
3031   bool MaxOrZero = false;
3032   unsigned TripMultiple = 0;
3033 
3034   bool UseUpperBound = false;
3035   computeUnrollCount(L, TTI, DT, &LI, SE, EphValues, &ORE, TripCount,
3036                      MaxTripCount, MaxOrZero, TripMultiple, LoopSize, UP, PP,
3037                      UseUpperBound);
3038   unsigned Factor = UP.Count;
3039   LLVM_DEBUG(dbgs() << "Suggesting unroll factor of " << Factor << "\n");
3040 
3041   // This function returns 1 to signal to not unroll a loop.
3042   if (Factor == 0)
3043     return 1;
3044   return Factor;
3045 }
3046 
3047 void OpenMPIRBuilder::unrollLoopPartial(DebugLoc DL, CanonicalLoopInfo *Loop,
3048                                         int32_t Factor,
3049                                         CanonicalLoopInfo **UnrolledCLI) {
3050   assert(Factor >= 0 && "Unroll factor must not be negative");
3051 
3052   Function *F = Loop->getFunction();
3053   LLVMContext &Ctx = F->getContext();
3054 
3055   // If the unrolled loop is not used for another loop-associated directive, it
3056   // is sufficient to add metadata for the LoopUnrollPass.
3057   if (!UnrolledCLI) {
3058     SmallVector<Metadata *, 2> LoopMetadata;
3059     LoopMetadata.push_back(
3060         MDNode::get(Ctx, MDString::get(Ctx, "llvm.loop.unroll.enable")));
3061 
3062     if (Factor >= 1) {
3063       ConstantAsMetadata *FactorConst = ConstantAsMetadata::get(
3064           ConstantInt::get(Type::getInt32Ty(Ctx), APInt(32, Factor)));
3065       LoopMetadata.push_back(MDNode::get(
3066           Ctx, {MDString::get(Ctx, "llvm.loop.unroll.count"), FactorConst}));
3067     }
3068 
3069     addLoopMetadata(Loop, LoopMetadata);
3070     return;
3071   }
3072 
3073   // Heuristically determine the unroll factor.
3074   if (Factor == 0)
3075     Factor = computeHeuristicUnrollFactor(Loop);
3076 
3077   // No change required with unroll factor 1.
3078   if (Factor == 1) {
3079     *UnrolledCLI = Loop;
3080     return;
3081   }
3082 
3083   assert(Factor >= 2 &&
3084          "unrolling only makes sense with a factor of 2 or larger");
3085 
3086   Type *IndVarTy = Loop->getIndVarType();
3087 
3088   // Apply partial unrolling by tiling the loop by the unroll-factor, then fully
3089   // unroll the inner loop.
3090   Value *FactorVal =
3091       ConstantInt::get(IndVarTy, APInt(IndVarTy->getIntegerBitWidth(), Factor,
3092                                        /*isSigned=*/false));
3093   std::vector<CanonicalLoopInfo *> LoopNest =
3094       tileLoops(DL, {Loop}, {FactorVal});
3095   assert(LoopNest.size() == 2 && "Expect 2 loops after tiling");
3096   *UnrolledCLI = LoopNest[0];
3097   CanonicalLoopInfo *InnerLoop = LoopNest[1];
3098 
3099   // LoopUnrollPass can only fully unroll loops with constant trip count.
3100   // Unroll by the unroll factor with a fallback epilog for the remainder
3101   // iterations if necessary.
3102   ConstantAsMetadata *FactorConst = ConstantAsMetadata::get(
3103       ConstantInt::get(Type::getInt32Ty(Ctx), APInt(32, Factor)));
3104   addLoopMetadata(
3105       InnerLoop,
3106       {MDNode::get(Ctx, MDString::get(Ctx, "llvm.loop.unroll.enable")),
3107        MDNode::get(
3108            Ctx, {MDString::get(Ctx, "llvm.loop.unroll.count"), FactorConst})});
3109 
3110 #ifndef NDEBUG
3111   (*UnrolledCLI)->assertOK();
3112 #endif
3113 }
3114 
3115 OpenMPIRBuilder::InsertPointTy
3116 OpenMPIRBuilder::createCopyPrivate(const LocationDescription &Loc,
3117                                    llvm::Value *BufSize, llvm::Value *CpyBuf,
3118                                    llvm::Value *CpyFn, llvm::Value *DidIt) {
3119   if (!updateToLocation(Loc))
3120     return Loc.IP;
3121 
3122   uint32_t SrcLocStrSize;
3123   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
3124   Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
3125   Value *ThreadId = getOrCreateThreadID(Ident);
3126 
3127   llvm::Value *DidItLD = Builder.CreateLoad(Builder.getInt32Ty(), DidIt);
3128 
3129   Value *Args[] = {Ident, ThreadId, BufSize, CpyBuf, CpyFn, DidItLD};
3130 
3131   Function *Fn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_copyprivate);
3132   Builder.CreateCall(Fn, Args);
3133 
3134   return Builder.saveIP();
3135 }
3136 
3137 OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::createSingle(
3138     const LocationDescription &Loc, BodyGenCallbackTy BodyGenCB,
3139     FinalizeCallbackTy FiniCB, bool IsNowait, llvm::Value *DidIt) {
3140 
3141   if (!updateToLocation(Loc))
3142     return Loc.IP;
3143 
3144   // If needed (i.e. not null), initialize `DidIt` with 0
3145   if (DidIt) {
3146     Builder.CreateStore(Builder.getInt32(0), DidIt);
3147   }
3148 
3149   Directive OMPD = Directive::OMPD_single;
3150   uint32_t SrcLocStrSize;
3151   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
3152   Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
3153   Value *ThreadId = getOrCreateThreadID(Ident);
3154   Value *Args[] = {Ident, ThreadId};
3155 
3156   Function *EntryRTLFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_single);
3157   Instruction *EntryCall = Builder.CreateCall(EntryRTLFn, Args);
3158 
3159   Function *ExitRTLFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_end_single);
3160   Instruction *ExitCall = Builder.CreateCall(ExitRTLFn, Args);
3161 
3162   // generates the following:
3163   // if (__kmpc_single()) {
3164   //		.... single region ...
3165   // 		__kmpc_end_single
3166   // }
3167   // __kmpc_barrier
3168 
3169   EmitOMPInlinedRegion(OMPD, EntryCall, ExitCall, BodyGenCB, FiniCB,
3170                        /*Conditional*/ true,
3171                        /*hasFinalize*/ true);
3172   if (!IsNowait)
3173     createBarrier(LocationDescription(Builder.saveIP(), Loc.DL),
3174                   omp::Directive::OMPD_unknown, /* ForceSimpleCall */ false,
3175                   /* CheckCancelFlag */ false);
3176   return Builder.saveIP();
3177 }
3178 
3179 OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::createCritical(
3180     const LocationDescription &Loc, BodyGenCallbackTy BodyGenCB,
3181     FinalizeCallbackTy FiniCB, StringRef CriticalName, Value *HintInst) {
3182 
3183   if (!updateToLocation(Loc))
3184     return Loc.IP;
3185 
3186   Directive OMPD = Directive::OMPD_critical;
3187   uint32_t SrcLocStrSize;
3188   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
3189   Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
3190   Value *ThreadId = getOrCreateThreadID(Ident);
3191   Value *LockVar = getOMPCriticalRegionLock(CriticalName);
3192   Value *Args[] = {Ident, ThreadId, LockVar};
3193 
3194   SmallVector<llvm::Value *, 4> EnterArgs(std::begin(Args), std::end(Args));
3195   Function *RTFn = nullptr;
3196   if (HintInst) {
3197     // Add Hint to entry Args and create call
3198     EnterArgs.push_back(HintInst);
3199     RTFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_critical_with_hint);
3200   } else {
3201     RTFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_critical);
3202   }
3203   Instruction *EntryCall = Builder.CreateCall(RTFn, EnterArgs);
3204 
3205   Function *ExitRTLFn =
3206       getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_end_critical);
3207   Instruction *ExitCall = Builder.CreateCall(ExitRTLFn, Args);
3208 
3209   return EmitOMPInlinedRegion(OMPD, EntryCall, ExitCall, BodyGenCB, FiniCB,
3210                               /*Conditional*/ false, /*hasFinalize*/ true);
3211 }
3212 
3213 OpenMPIRBuilder::InsertPointTy
3214 OpenMPIRBuilder::createOrderedDepend(const LocationDescription &Loc,
3215                                      InsertPointTy AllocaIP, unsigned NumLoops,
3216                                      ArrayRef<llvm::Value *> StoreValues,
3217                                      const Twine &Name, bool IsDependSource) {
3218   for (size_t I = 0; I < StoreValues.size(); I++)
3219     assert(StoreValues[I]->getType()->isIntegerTy(64) &&
3220            "OpenMP runtime requires depend vec with i64 type");
3221 
3222   if (!updateToLocation(Loc))
3223     return Loc.IP;
3224 
3225   // Allocate space for vector and generate alloc instruction.
3226   auto *ArrI64Ty = ArrayType::get(Int64, NumLoops);
3227   Builder.restoreIP(AllocaIP);
3228   AllocaInst *ArgsBase = Builder.CreateAlloca(ArrI64Ty, nullptr, Name);
3229   ArgsBase->setAlignment(Align(8));
3230   Builder.restoreIP(Loc.IP);
3231 
3232   // Store the index value with offset in depend vector.
3233   for (unsigned I = 0; I < NumLoops; ++I) {
3234     Value *DependAddrGEPIter = Builder.CreateInBoundsGEP(
3235         ArrI64Ty, ArgsBase, {Builder.getInt64(0), Builder.getInt64(I)});
3236     StoreInst *STInst = Builder.CreateStore(StoreValues[I], DependAddrGEPIter);
3237     STInst->setAlignment(Align(8));
3238   }
3239 
3240   Value *DependBaseAddrGEP = Builder.CreateInBoundsGEP(
3241       ArrI64Ty, ArgsBase, {Builder.getInt64(0), Builder.getInt64(0)});
3242 
3243   uint32_t SrcLocStrSize;
3244   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
3245   Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
3246   Value *ThreadId = getOrCreateThreadID(Ident);
3247   Value *Args[] = {Ident, ThreadId, DependBaseAddrGEP};
3248 
3249   Function *RTLFn = nullptr;
3250   if (IsDependSource)
3251     RTLFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_doacross_post);
3252   else
3253     RTLFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_doacross_wait);
3254   Builder.CreateCall(RTLFn, Args);
3255 
3256   return Builder.saveIP();
3257 }
3258 
3259 OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::createOrderedThreadsSimd(
3260     const LocationDescription &Loc, BodyGenCallbackTy BodyGenCB,
3261     FinalizeCallbackTy FiniCB, bool IsThreads) {
3262   if (!updateToLocation(Loc))
3263     return Loc.IP;
3264 
3265   Directive OMPD = Directive::OMPD_ordered;
3266   Instruction *EntryCall = nullptr;
3267   Instruction *ExitCall = nullptr;
3268 
3269   if (IsThreads) {
3270     uint32_t SrcLocStrSize;
3271     Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
3272     Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
3273     Value *ThreadId = getOrCreateThreadID(Ident);
3274     Value *Args[] = {Ident, ThreadId};
3275 
3276     Function *EntryRTLFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_ordered);
3277     EntryCall = Builder.CreateCall(EntryRTLFn, Args);
3278 
3279     Function *ExitRTLFn =
3280         getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_end_ordered);
3281     ExitCall = Builder.CreateCall(ExitRTLFn, Args);
3282   }
3283 
3284   return EmitOMPInlinedRegion(OMPD, EntryCall, ExitCall, BodyGenCB, FiniCB,
3285                               /*Conditional*/ false, /*hasFinalize*/ true);
3286 }
3287 
3288 OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::EmitOMPInlinedRegion(
3289     Directive OMPD, Instruction *EntryCall, Instruction *ExitCall,
3290     BodyGenCallbackTy BodyGenCB, FinalizeCallbackTy FiniCB, bool Conditional,
3291     bool HasFinalize, bool IsCancellable) {
3292 
3293   if (HasFinalize)
3294     FinalizationStack.push_back({FiniCB, OMPD, IsCancellable});
3295 
3296   // Create inlined region's entry and body blocks, in preparation
3297   // for conditional creation
3298   BasicBlock *EntryBB = Builder.GetInsertBlock();
3299   Instruction *SplitPos = EntryBB->getTerminator();
3300   if (!isa_and_nonnull<BranchInst>(SplitPos))
3301     SplitPos = new UnreachableInst(Builder.getContext(), EntryBB);
3302   BasicBlock *ExitBB = EntryBB->splitBasicBlock(SplitPos, "omp_region.end");
3303   BasicBlock *FiniBB =
3304       EntryBB->splitBasicBlock(EntryBB->getTerminator(), "omp_region.finalize");
3305 
3306   Builder.SetInsertPoint(EntryBB->getTerminator());
3307   emitCommonDirectiveEntry(OMPD, EntryCall, ExitBB, Conditional);
3308 
3309   // generate body
3310   BodyGenCB(/* AllocaIP */ InsertPointTy(),
3311             /* CodeGenIP */ Builder.saveIP());
3312 
3313   // emit exit call and do any needed finalization.
3314   auto FinIP = InsertPointTy(FiniBB, FiniBB->getFirstInsertionPt());
3315   assert(FiniBB->getTerminator()->getNumSuccessors() == 1 &&
3316          FiniBB->getTerminator()->getSuccessor(0) == ExitBB &&
3317          "Unexpected control flow graph state!!");
3318   emitCommonDirectiveExit(OMPD, FinIP, ExitCall, HasFinalize);
3319   assert(FiniBB->getUniquePredecessor()->getUniqueSuccessor() == FiniBB &&
3320          "Unexpected Control Flow State!");
3321   MergeBlockIntoPredecessor(FiniBB);
3322 
3323   // If we are skipping the region of a non conditional, remove the exit
3324   // block, and clear the builder's insertion point.
3325   assert(SplitPos->getParent() == ExitBB &&
3326          "Unexpected Insertion point location!");
3327   auto merged = MergeBlockIntoPredecessor(ExitBB);
3328   BasicBlock *ExitPredBB = SplitPos->getParent();
3329   auto InsertBB = merged ? ExitPredBB : ExitBB;
3330   if (!isa_and_nonnull<BranchInst>(SplitPos))
3331     SplitPos->eraseFromParent();
3332   Builder.SetInsertPoint(InsertBB);
3333 
3334   return Builder.saveIP();
3335 }
3336 
3337 OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::emitCommonDirectiveEntry(
3338     Directive OMPD, Value *EntryCall, BasicBlock *ExitBB, bool Conditional) {
3339   // if nothing to do, Return current insertion point.
3340   if (!Conditional || !EntryCall)
3341     return Builder.saveIP();
3342 
3343   BasicBlock *EntryBB = Builder.GetInsertBlock();
3344   Value *CallBool = Builder.CreateIsNotNull(EntryCall);
3345   auto *ThenBB = BasicBlock::Create(M.getContext(), "omp_region.body");
3346   auto *UI = new UnreachableInst(Builder.getContext(), ThenBB);
3347 
3348   // Emit thenBB and set the Builder's insertion point there for
3349   // body generation next. Place the block after the current block.
3350   Function *CurFn = EntryBB->getParent();
3351   CurFn->getBasicBlockList().insertAfter(EntryBB->getIterator(), ThenBB);
3352 
3353   // Move Entry branch to end of ThenBB, and replace with conditional
3354   // branch (If-stmt)
3355   Instruction *EntryBBTI = EntryBB->getTerminator();
3356   Builder.CreateCondBr(CallBool, ThenBB, ExitBB);
3357   EntryBBTI->removeFromParent();
3358   Builder.SetInsertPoint(UI);
3359   Builder.Insert(EntryBBTI);
3360   UI->eraseFromParent();
3361   Builder.SetInsertPoint(ThenBB->getTerminator());
3362 
3363   // return an insertion point to ExitBB.
3364   return IRBuilder<>::InsertPoint(ExitBB, ExitBB->getFirstInsertionPt());
3365 }
3366 
3367 OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::emitCommonDirectiveExit(
3368     omp::Directive OMPD, InsertPointTy FinIP, Instruction *ExitCall,
3369     bool HasFinalize) {
3370 
3371   Builder.restoreIP(FinIP);
3372 
3373   // If there is finalization to do, emit it before the exit call
3374   if (HasFinalize) {
3375     assert(!FinalizationStack.empty() &&
3376            "Unexpected finalization stack state!");
3377 
3378     FinalizationInfo Fi = FinalizationStack.pop_back_val();
3379     assert(Fi.DK == OMPD && "Unexpected Directive for Finalization call!");
3380 
3381     Fi.FiniCB(FinIP);
3382 
3383     BasicBlock *FiniBB = FinIP.getBlock();
3384     Instruction *FiniBBTI = FiniBB->getTerminator();
3385 
3386     // set Builder IP for call creation
3387     Builder.SetInsertPoint(FiniBBTI);
3388   }
3389 
3390   if (!ExitCall)
3391     return Builder.saveIP();
3392 
3393   // place the Exitcall as last instruction before Finalization block terminator
3394   ExitCall->removeFromParent();
3395   Builder.Insert(ExitCall);
3396 
3397   return IRBuilder<>::InsertPoint(ExitCall->getParent(),
3398                                   ExitCall->getIterator());
3399 }
3400 
3401 OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::createCopyinClauseBlocks(
3402     InsertPointTy IP, Value *MasterAddr, Value *PrivateAddr,
3403     llvm::IntegerType *IntPtrTy, bool BranchtoEnd) {
3404   if (!IP.isSet())
3405     return IP;
3406 
3407   IRBuilder<>::InsertPointGuard IPG(Builder);
3408 
3409   // creates the following CFG structure
3410   //	   OMP_Entry : (MasterAddr != PrivateAddr)?
3411   //       F     T
3412   //       |      \
3413   //       |     copin.not.master
3414   //       |      /
3415   //       v     /
3416   //   copyin.not.master.end
3417   //		     |
3418   //         v
3419   //   OMP.Entry.Next
3420 
3421   BasicBlock *OMP_Entry = IP.getBlock();
3422   Function *CurFn = OMP_Entry->getParent();
3423   BasicBlock *CopyBegin =
3424       BasicBlock::Create(M.getContext(), "copyin.not.master", CurFn);
3425   BasicBlock *CopyEnd = nullptr;
3426 
3427   // If entry block is terminated, split to preserve the branch to following
3428   // basic block (i.e. OMP.Entry.Next), otherwise, leave everything as is.
3429   if (isa_and_nonnull<BranchInst>(OMP_Entry->getTerminator())) {
3430     CopyEnd = OMP_Entry->splitBasicBlock(OMP_Entry->getTerminator(),
3431                                          "copyin.not.master.end");
3432     OMP_Entry->getTerminator()->eraseFromParent();
3433   } else {
3434     CopyEnd =
3435         BasicBlock::Create(M.getContext(), "copyin.not.master.end", CurFn);
3436   }
3437 
3438   Builder.SetInsertPoint(OMP_Entry);
3439   Value *MasterPtr = Builder.CreatePtrToInt(MasterAddr, IntPtrTy);
3440   Value *PrivatePtr = Builder.CreatePtrToInt(PrivateAddr, IntPtrTy);
3441   Value *cmp = Builder.CreateICmpNE(MasterPtr, PrivatePtr);
3442   Builder.CreateCondBr(cmp, CopyBegin, CopyEnd);
3443 
3444   Builder.SetInsertPoint(CopyBegin);
3445   if (BranchtoEnd)
3446     Builder.SetInsertPoint(Builder.CreateBr(CopyEnd));
3447 
3448   return Builder.saveIP();
3449 }
3450 
3451 CallInst *OpenMPIRBuilder::createOMPAlloc(const LocationDescription &Loc,
3452                                           Value *Size, Value *Allocator,
3453                                           std::string Name) {
3454   IRBuilder<>::InsertPointGuard IPG(Builder);
3455   Builder.restoreIP(Loc.IP);
3456 
3457   uint32_t SrcLocStrSize;
3458   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
3459   Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
3460   Value *ThreadId = getOrCreateThreadID(Ident);
3461   Value *Args[] = {ThreadId, Size, Allocator};
3462 
3463   Function *Fn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_alloc);
3464 
3465   return Builder.CreateCall(Fn, Args, Name);
3466 }
3467 
3468 CallInst *OpenMPIRBuilder::createOMPFree(const LocationDescription &Loc,
3469                                          Value *Addr, Value *Allocator,
3470                                          std::string Name) {
3471   IRBuilder<>::InsertPointGuard IPG(Builder);
3472   Builder.restoreIP(Loc.IP);
3473 
3474   uint32_t SrcLocStrSize;
3475   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
3476   Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
3477   Value *ThreadId = getOrCreateThreadID(Ident);
3478   Value *Args[] = {ThreadId, Addr, Allocator};
3479   Function *Fn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_free);
3480   return Builder.CreateCall(Fn, Args, Name);
3481 }
3482 
3483 CallInst *OpenMPIRBuilder::createOMPInteropInit(
3484     const LocationDescription &Loc, Value *InteropVar,
3485     omp::OMPInteropType InteropType, Value *Device, Value *NumDependences,
3486     Value *DependenceAddress, bool HaveNowaitClause) {
3487   IRBuilder<>::InsertPointGuard IPG(Builder);
3488   Builder.restoreIP(Loc.IP);
3489 
3490   uint32_t SrcLocStrSize;
3491   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
3492   Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
3493   Value *ThreadId = getOrCreateThreadID(Ident);
3494   if (Device == nullptr)
3495     Device = ConstantInt::get(Int32, -1);
3496   Constant *InteropTypeVal = ConstantInt::get(Int64, (int)InteropType);
3497   if (NumDependences == nullptr) {
3498     NumDependences = ConstantInt::get(Int32, 0);
3499     PointerType *PointerTypeVar = Type::getInt8PtrTy(M.getContext());
3500     DependenceAddress = ConstantPointerNull::get(PointerTypeVar);
3501   }
3502   Value *HaveNowaitClauseVal = ConstantInt::get(Int32, HaveNowaitClause);
3503   Value *Args[] = {
3504       Ident,  ThreadId,       InteropVar,        InteropTypeVal,
3505       Device, NumDependences, DependenceAddress, HaveNowaitClauseVal};
3506 
3507   Function *Fn = getOrCreateRuntimeFunctionPtr(OMPRTL___tgt_interop_init);
3508 
3509   return Builder.CreateCall(Fn, Args);
3510 }
3511 
3512 CallInst *OpenMPIRBuilder::createOMPInteropDestroy(
3513     const LocationDescription &Loc, Value *InteropVar, Value *Device,
3514     Value *NumDependences, Value *DependenceAddress, bool HaveNowaitClause) {
3515   IRBuilder<>::InsertPointGuard IPG(Builder);
3516   Builder.restoreIP(Loc.IP);
3517 
3518   uint32_t SrcLocStrSize;
3519   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
3520   Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
3521   Value *ThreadId = getOrCreateThreadID(Ident);
3522   if (Device == nullptr)
3523     Device = ConstantInt::get(Int32, -1);
3524   if (NumDependences == nullptr) {
3525     NumDependences = ConstantInt::get(Int32, 0);
3526     PointerType *PointerTypeVar = Type::getInt8PtrTy(M.getContext());
3527     DependenceAddress = ConstantPointerNull::get(PointerTypeVar);
3528   }
3529   Value *HaveNowaitClauseVal = ConstantInt::get(Int32, HaveNowaitClause);
3530   Value *Args[] = {
3531       Ident,          ThreadId,          InteropVar,         Device,
3532       NumDependences, DependenceAddress, HaveNowaitClauseVal};
3533 
3534   Function *Fn = getOrCreateRuntimeFunctionPtr(OMPRTL___tgt_interop_destroy);
3535 
3536   return Builder.CreateCall(Fn, Args);
3537 }
3538 
3539 CallInst *OpenMPIRBuilder::createOMPInteropUse(const LocationDescription &Loc,
3540                                                Value *InteropVar, Value *Device,
3541                                                Value *NumDependences,
3542                                                Value *DependenceAddress,
3543                                                bool HaveNowaitClause) {
3544   IRBuilder<>::InsertPointGuard IPG(Builder);
3545   Builder.restoreIP(Loc.IP);
3546   uint32_t SrcLocStrSize;
3547   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
3548   Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
3549   Value *ThreadId = getOrCreateThreadID(Ident);
3550   if (Device == nullptr)
3551     Device = ConstantInt::get(Int32, -1);
3552   if (NumDependences == nullptr) {
3553     NumDependences = ConstantInt::get(Int32, 0);
3554     PointerType *PointerTypeVar = Type::getInt8PtrTy(M.getContext());
3555     DependenceAddress = ConstantPointerNull::get(PointerTypeVar);
3556   }
3557   Value *HaveNowaitClauseVal = ConstantInt::get(Int32, HaveNowaitClause);
3558   Value *Args[] = {
3559       Ident,          ThreadId,          InteropVar,         Device,
3560       NumDependences, DependenceAddress, HaveNowaitClauseVal};
3561 
3562   Function *Fn = getOrCreateRuntimeFunctionPtr(OMPRTL___tgt_interop_use);
3563 
3564   return Builder.CreateCall(Fn, Args);
3565 }
3566 
3567 CallInst *OpenMPIRBuilder::createCachedThreadPrivate(
3568     const LocationDescription &Loc, llvm::Value *Pointer,
3569     llvm::ConstantInt *Size, const llvm::Twine &Name) {
3570   IRBuilder<>::InsertPointGuard IPG(Builder);
3571   Builder.restoreIP(Loc.IP);
3572 
3573   uint32_t SrcLocStrSize;
3574   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
3575   Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
3576   Value *ThreadId = getOrCreateThreadID(Ident);
3577   Constant *ThreadPrivateCache =
3578       getOrCreateOMPInternalVariable(Int8PtrPtr, Name);
3579   llvm::Value *Args[] = {Ident, ThreadId, Pointer, Size, ThreadPrivateCache};
3580 
3581   Function *Fn =
3582       getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_threadprivate_cached);
3583 
3584   return Builder.CreateCall(Fn, Args);
3585 }
3586 
3587 OpenMPIRBuilder::InsertPointTy
3588 OpenMPIRBuilder::createTargetInit(const LocationDescription &Loc, bool IsSPMD,
3589                                   bool RequiresFullRuntime) {
3590   if (!updateToLocation(Loc))
3591     return Loc.IP;
3592 
3593   uint32_t SrcLocStrSize;
3594   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
3595   Constant *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
3596   ConstantInt *IsSPMDVal = ConstantInt::getSigned(
3597       IntegerType::getInt8Ty(Int8->getContext()),
3598       IsSPMD ? OMP_TGT_EXEC_MODE_SPMD : OMP_TGT_EXEC_MODE_GENERIC);
3599   ConstantInt *UseGenericStateMachine =
3600       ConstantInt::getBool(Int32->getContext(), !IsSPMD);
3601   ConstantInt *RequiresFullRuntimeVal =
3602       ConstantInt::getBool(Int32->getContext(), RequiresFullRuntime);
3603 
3604   Function *Fn = getOrCreateRuntimeFunctionPtr(
3605       omp::RuntimeFunction::OMPRTL___kmpc_target_init);
3606 
3607   CallInst *ThreadKind = Builder.CreateCall(
3608       Fn, {Ident, IsSPMDVal, UseGenericStateMachine, RequiresFullRuntimeVal});
3609 
3610   Value *ExecUserCode = Builder.CreateICmpEQ(
3611       ThreadKind, ConstantInt::get(ThreadKind->getType(), -1),
3612       "exec_user_code");
3613 
3614   // ThreadKind = __kmpc_target_init(...)
3615   // if (ThreadKind == -1)
3616   //   user_code
3617   // else
3618   //   return;
3619 
3620   auto *UI = Builder.CreateUnreachable();
3621   BasicBlock *CheckBB = UI->getParent();
3622   BasicBlock *UserCodeEntryBB = CheckBB->splitBasicBlock(UI, "user_code.entry");
3623 
3624   BasicBlock *WorkerExitBB = BasicBlock::Create(
3625       CheckBB->getContext(), "worker.exit", CheckBB->getParent());
3626   Builder.SetInsertPoint(WorkerExitBB);
3627   Builder.CreateRetVoid();
3628 
3629   auto *CheckBBTI = CheckBB->getTerminator();
3630   Builder.SetInsertPoint(CheckBBTI);
3631   Builder.CreateCondBr(ExecUserCode, UI->getParent(), WorkerExitBB);
3632 
3633   CheckBBTI->eraseFromParent();
3634   UI->eraseFromParent();
3635 
3636   // Continue in the "user_code" block, see diagram above and in
3637   // openmp/libomptarget/deviceRTLs/common/include/target.h .
3638   return InsertPointTy(UserCodeEntryBB, UserCodeEntryBB->getFirstInsertionPt());
3639 }
3640 
3641 void OpenMPIRBuilder::createTargetDeinit(const LocationDescription &Loc,
3642                                          bool IsSPMD,
3643                                          bool RequiresFullRuntime) {
3644   if (!updateToLocation(Loc))
3645     return;
3646 
3647   uint32_t SrcLocStrSize;
3648   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
3649   Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
3650   ConstantInt *IsSPMDVal = ConstantInt::getSigned(
3651       IntegerType::getInt8Ty(Int8->getContext()),
3652       IsSPMD ? OMP_TGT_EXEC_MODE_SPMD : OMP_TGT_EXEC_MODE_GENERIC);
3653   ConstantInt *RequiresFullRuntimeVal =
3654       ConstantInt::getBool(Int32->getContext(), RequiresFullRuntime);
3655 
3656   Function *Fn = getOrCreateRuntimeFunctionPtr(
3657       omp::RuntimeFunction::OMPRTL___kmpc_target_deinit);
3658 
3659   Builder.CreateCall(Fn, {Ident, IsSPMDVal, RequiresFullRuntimeVal});
3660 }
3661 
3662 std::string OpenMPIRBuilder::getNameWithSeparators(ArrayRef<StringRef> Parts,
3663                                                    StringRef FirstSeparator,
3664                                                    StringRef Separator) {
3665   SmallString<128> Buffer;
3666   llvm::raw_svector_ostream OS(Buffer);
3667   StringRef Sep = FirstSeparator;
3668   for (StringRef Part : Parts) {
3669     OS << Sep << Part;
3670     Sep = Separator;
3671   }
3672   return OS.str().str();
3673 }
3674 
3675 Constant *OpenMPIRBuilder::getOrCreateOMPInternalVariable(
3676     llvm::Type *Ty, const llvm::Twine &Name, unsigned AddressSpace) {
3677   // TODO: Replace the twine arg with stringref to get rid of the conversion
3678   // logic. However This is taken from current implementation in clang as is.
3679   // Since this method is used in many places exclusively for OMP internal use
3680   // we will keep it as is for temporarily until we move all users to the
3681   // builder and then, if possible, fix it everywhere in one go.
3682   SmallString<256> Buffer;
3683   llvm::raw_svector_ostream Out(Buffer);
3684   Out << Name;
3685   StringRef RuntimeName = Out.str();
3686   auto &Elem = *InternalVars.try_emplace(RuntimeName, nullptr).first;
3687   if (Elem.second) {
3688     assert(cast<PointerType>(Elem.second->getType())
3689                ->isOpaqueOrPointeeTypeMatches(Ty) &&
3690            "OMP internal variable has different type than requested");
3691   } else {
3692     // TODO: investigate the appropriate linkage type used for the global
3693     // variable for possibly changing that to internal or private, or maybe
3694     // create different versions of the function for different OMP internal
3695     // variables.
3696     Elem.second = new llvm::GlobalVariable(
3697         M, Ty, /*IsConstant*/ false, llvm::GlobalValue::CommonLinkage,
3698         llvm::Constant::getNullValue(Ty), Elem.first(),
3699         /*InsertBefore=*/nullptr, llvm::GlobalValue::NotThreadLocal,
3700         AddressSpace);
3701   }
3702 
3703   return Elem.second;
3704 }
3705 
3706 Value *OpenMPIRBuilder::getOMPCriticalRegionLock(StringRef CriticalName) {
3707   std::string Prefix = Twine("gomp_critical_user_", CriticalName).str();
3708   std::string Name = getNameWithSeparators({Prefix, "var"}, ".", ".");
3709   return getOrCreateOMPInternalVariable(KmpCriticalNameTy, Name);
3710 }
3711 
3712 GlobalVariable *
3713 OpenMPIRBuilder::createOffloadMaptypes(SmallVectorImpl<uint64_t> &Mappings,
3714                                        std::string VarName) {
3715   llvm::Constant *MaptypesArrayInit =
3716       llvm::ConstantDataArray::get(M.getContext(), Mappings);
3717   auto *MaptypesArrayGlobal = new llvm::GlobalVariable(
3718       M, MaptypesArrayInit->getType(),
3719       /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage, MaptypesArrayInit,
3720       VarName);
3721   MaptypesArrayGlobal->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3722   return MaptypesArrayGlobal;
3723 }
3724 
3725 void OpenMPIRBuilder::createMapperAllocas(const LocationDescription &Loc,
3726                                           InsertPointTy AllocaIP,
3727                                           unsigned NumOperands,
3728                                           struct MapperAllocas &MapperAllocas) {
3729   if (!updateToLocation(Loc))
3730     return;
3731 
3732   auto *ArrI8PtrTy = ArrayType::get(Int8Ptr, NumOperands);
3733   auto *ArrI64Ty = ArrayType::get(Int64, NumOperands);
3734   Builder.restoreIP(AllocaIP);
3735   AllocaInst *ArgsBase = Builder.CreateAlloca(ArrI8PtrTy);
3736   AllocaInst *Args = Builder.CreateAlloca(ArrI8PtrTy);
3737   AllocaInst *ArgSizes = Builder.CreateAlloca(ArrI64Ty);
3738   Builder.restoreIP(Loc.IP);
3739   MapperAllocas.ArgsBase = ArgsBase;
3740   MapperAllocas.Args = Args;
3741   MapperAllocas.ArgSizes = ArgSizes;
3742 }
3743 
3744 void OpenMPIRBuilder::emitMapperCall(const LocationDescription &Loc,
3745                                      Function *MapperFunc, Value *SrcLocInfo,
3746                                      Value *MaptypesArg, Value *MapnamesArg,
3747                                      struct MapperAllocas &MapperAllocas,
3748                                      int64_t DeviceID, unsigned NumOperands) {
3749   if (!updateToLocation(Loc))
3750     return;
3751 
3752   auto *ArrI8PtrTy = ArrayType::get(Int8Ptr, NumOperands);
3753   auto *ArrI64Ty = ArrayType::get(Int64, NumOperands);
3754   Value *ArgsBaseGEP =
3755       Builder.CreateInBoundsGEP(ArrI8PtrTy, MapperAllocas.ArgsBase,
3756                                 {Builder.getInt32(0), Builder.getInt32(0)});
3757   Value *ArgsGEP =
3758       Builder.CreateInBoundsGEP(ArrI8PtrTy, MapperAllocas.Args,
3759                                 {Builder.getInt32(0), Builder.getInt32(0)});
3760   Value *ArgSizesGEP =
3761       Builder.CreateInBoundsGEP(ArrI64Ty, MapperAllocas.ArgSizes,
3762                                 {Builder.getInt32(0), Builder.getInt32(0)});
3763   Value *NullPtr = Constant::getNullValue(Int8Ptr->getPointerTo());
3764   Builder.CreateCall(MapperFunc,
3765                      {SrcLocInfo, Builder.getInt64(DeviceID),
3766                       Builder.getInt32(NumOperands), ArgsBaseGEP, ArgsGEP,
3767                       ArgSizesGEP, MaptypesArg, MapnamesArg, NullPtr});
3768 }
3769 
3770 bool OpenMPIRBuilder::checkAndEmitFlushAfterAtomic(
3771     const LocationDescription &Loc, llvm::AtomicOrdering AO, AtomicKind AK) {
3772   assert(!(AO == AtomicOrdering::NotAtomic ||
3773            AO == llvm::AtomicOrdering::Unordered) &&
3774          "Unexpected Atomic Ordering.");
3775 
3776   bool Flush = false;
3777   llvm::AtomicOrdering FlushAO = AtomicOrdering::Monotonic;
3778 
3779   switch (AK) {
3780   case Read:
3781     if (AO == AtomicOrdering::Acquire || AO == AtomicOrdering::AcquireRelease ||
3782         AO == AtomicOrdering::SequentiallyConsistent) {
3783       FlushAO = AtomicOrdering::Acquire;
3784       Flush = true;
3785     }
3786     break;
3787   case Write:
3788   case Compare:
3789   case Update:
3790     if (AO == AtomicOrdering::Release || AO == AtomicOrdering::AcquireRelease ||
3791         AO == AtomicOrdering::SequentiallyConsistent) {
3792       FlushAO = AtomicOrdering::Release;
3793       Flush = true;
3794     }
3795     break;
3796   case Capture:
3797     switch (AO) {
3798     case AtomicOrdering::Acquire:
3799       FlushAO = AtomicOrdering::Acquire;
3800       Flush = true;
3801       break;
3802     case AtomicOrdering::Release:
3803       FlushAO = AtomicOrdering::Release;
3804       Flush = true;
3805       break;
3806     case AtomicOrdering::AcquireRelease:
3807     case AtomicOrdering::SequentiallyConsistent:
3808       FlushAO = AtomicOrdering::AcquireRelease;
3809       Flush = true;
3810       break;
3811     default:
3812       // do nothing - leave silently.
3813       break;
3814     }
3815   }
3816 
3817   if (Flush) {
3818     // Currently Flush RT call still doesn't take memory_ordering, so for when
3819     // that happens, this tries to do the resolution of which atomic ordering
3820     // to use with but issue the flush call
3821     // TODO: pass `FlushAO` after memory ordering support is added
3822     (void)FlushAO;
3823     emitFlush(Loc);
3824   }
3825 
3826   // for AO == AtomicOrdering::Monotonic and  all other case combinations
3827   // do nothing
3828   return Flush;
3829 }
3830 
3831 OpenMPIRBuilder::InsertPointTy
3832 OpenMPIRBuilder::createAtomicRead(const LocationDescription &Loc,
3833                                   AtomicOpValue &X, AtomicOpValue &V,
3834                                   AtomicOrdering AO) {
3835   if (!updateToLocation(Loc))
3836     return Loc.IP;
3837 
3838   Type *XTy = X.Var->getType();
3839   assert(XTy->isPointerTy() && "OMP Atomic expects a pointer to target memory");
3840   Type *XElemTy = X.ElemTy;
3841   assert((XElemTy->isFloatingPointTy() || XElemTy->isIntegerTy() ||
3842           XElemTy->isPointerTy()) &&
3843          "OMP atomic read expected a scalar type");
3844 
3845   Value *XRead = nullptr;
3846 
3847   if (XElemTy->isIntegerTy()) {
3848     LoadInst *XLD =
3849         Builder.CreateLoad(XElemTy, X.Var, X.IsVolatile, "omp.atomic.read");
3850     XLD->setAtomic(AO);
3851     XRead = cast<Value>(XLD);
3852   } else {
3853     // We need to bitcast and perform atomic op as integer
3854     unsigned Addrspace = cast<PointerType>(XTy)->getAddressSpace();
3855     IntegerType *IntCastTy =
3856         IntegerType::get(M.getContext(), XElemTy->getScalarSizeInBits());
3857     Value *XBCast = Builder.CreateBitCast(
3858         X.Var, IntCastTy->getPointerTo(Addrspace), "atomic.src.int.cast");
3859     LoadInst *XLoad =
3860         Builder.CreateLoad(IntCastTy, XBCast, X.IsVolatile, "omp.atomic.load");
3861     XLoad->setAtomic(AO);
3862     if (XElemTy->isFloatingPointTy()) {
3863       XRead = Builder.CreateBitCast(XLoad, XElemTy, "atomic.flt.cast");
3864     } else {
3865       XRead = Builder.CreateIntToPtr(XLoad, XElemTy, "atomic.ptr.cast");
3866     }
3867   }
3868   checkAndEmitFlushAfterAtomic(Loc, AO, AtomicKind::Read);
3869   Builder.CreateStore(XRead, V.Var, V.IsVolatile);
3870   return Builder.saveIP();
3871 }
3872 
3873 OpenMPIRBuilder::InsertPointTy
3874 OpenMPIRBuilder::createAtomicWrite(const LocationDescription &Loc,
3875                                    AtomicOpValue &X, Value *Expr,
3876                                    AtomicOrdering AO) {
3877   if (!updateToLocation(Loc))
3878     return Loc.IP;
3879 
3880   Type *XTy = X.Var->getType();
3881   assert(XTy->isPointerTy() && "OMP Atomic expects a pointer to target memory");
3882   Type *XElemTy = X.ElemTy;
3883   assert((XElemTy->isFloatingPointTy() || XElemTy->isIntegerTy() ||
3884           XElemTy->isPointerTy()) &&
3885          "OMP atomic write expected a scalar type");
3886 
3887   if (XElemTy->isIntegerTy()) {
3888     StoreInst *XSt = Builder.CreateStore(Expr, X.Var, X.IsVolatile);
3889     XSt->setAtomic(AO);
3890   } else {
3891     // We need to bitcast and perform atomic op as integers
3892     unsigned Addrspace = cast<PointerType>(XTy)->getAddressSpace();
3893     IntegerType *IntCastTy =
3894         IntegerType::get(M.getContext(), XElemTy->getScalarSizeInBits());
3895     Value *XBCast = Builder.CreateBitCast(
3896         X.Var, IntCastTy->getPointerTo(Addrspace), "atomic.dst.int.cast");
3897     Value *ExprCast =
3898         Builder.CreateBitCast(Expr, IntCastTy, "atomic.src.int.cast");
3899     StoreInst *XSt = Builder.CreateStore(ExprCast, XBCast, X.IsVolatile);
3900     XSt->setAtomic(AO);
3901   }
3902 
3903   checkAndEmitFlushAfterAtomic(Loc, AO, AtomicKind::Write);
3904   return Builder.saveIP();
3905 }
3906 
3907 OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::createAtomicUpdate(
3908     const LocationDescription &Loc, InsertPointTy AllocaIP, AtomicOpValue &X,
3909     Value *Expr, AtomicOrdering AO, AtomicRMWInst::BinOp RMWOp,
3910     AtomicUpdateCallbackTy &UpdateOp, bool IsXBinopExpr) {
3911   assert(!isConflictIP(Loc.IP, AllocaIP) && "IPs must not be ambiguous");
3912   if (!updateToLocation(Loc))
3913     return Loc.IP;
3914 
3915   LLVM_DEBUG({
3916     Type *XTy = X.Var->getType();
3917     assert(XTy->isPointerTy() &&
3918            "OMP Atomic expects a pointer to target memory");
3919     Type *XElemTy = X.ElemTy;
3920     assert((XElemTy->isFloatingPointTy() || XElemTy->isIntegerTy() ||
3921             XElemTy->isPointerTy()) &&
3922            "OMP atomic update expected a scalar type");
3923     assert((RMWOp != AtomicRMWInst::Max) && (RMWOp != AtomicRMWInst::Min) &&
3924            (RMWOp != AtomicRMWInst::UMax) && (RMWOp != AtomicRMWInst::UMin) &&
3925            "OpenMP atomic does not support LT or GT operations");
3926   });
3927 
3928   emitAtomicUpdate(AllocaIP, X.Var, X.ElemTy, Expr, AO, RMWOp, UpdateOp,
3929                    X.IsVolatile, IsXBinopExpr);
3930   checkAndEmitFlushAfterAtomic(Loc, AO, AtomicKind::Update);
3931   return Builder.saveIP();
3932 }
3933 
3934 Value *OpenMPIRBuilder::emitRMWOpAsInstruction(Value *Src1, Value *Src2,
3935                                                AtomicRMWInst::BinOp RMWOp) {
3936   switch (RMWOp) {
3937   case AtomicRMWInst::Add:
3938     return Builder.CreateAdd(Src1, Src2);
3939   case AtomicRMWInst::Sub:
3940     return Builder.CreateSub(Src1, Src2);
3941   case AtomicRMWInst::And:
3942     return Builder.CreateAnd(Src1, Src2);
3943   case AtomicRMWInst::Nand:
3944     return Builder.CreateNeg(Builder.CreateAnd(Src1, Src2));
3945   case AtomicRMWInst::Or:
3946     return Builder.CreateOr(Src1, Src2);
3947   case AtomicRMWInst::Xor:
3948     return Builder.CreateXor(Src1, Src2);
3949   case AtomicRMWInst::Xchg:
3950   case AtomicRMWInst::FAdd:
3951   case AtomicRMWInst::FSub:
3952   case AtomicRMWInst::BAD_BINOP:
3953   case AtomicRMWInst::Max:
3954   case AtomicRMWInst::Min:
3955   case AtomicRMWInst::UMax:
3956   case AtomicRMWInst::UMin:
3957     llvm_unreachable("Unsupported atomic update operation");
3958   }
3959   llvm_unreachable("Unsupported atomic update operation");
3960 }
3961 
3962 std::pair<Value *, Value *> OpenMPIRBuilder::emitAtomicUpdate(
3963     InsertPointTy AllocaIP, Value *X, Type *XElemTy, Value *Expr,
3964     AtomicOrdering AO, AtomicRMWInst::BinOp RMWOp,
3965     AtomicUpdateCallbackTy &UpdateOp, bool VolatileX, bool IsXBinopExpr) {
3966   // TODO: handle the case where XElemTy is not byte-sized or not a power of 2
3967   // or a complex datatype.
3968   bool emitRMWOp = false;
3969   switch (RMWOp) {
3970   case AtomicRMWInst::Add:
3971   case AtomicRMWInst::And:
3972   case AtomicRMWInst::Nand:
3973   case AtomicRMWInst::Or:
3974   case AtomicRMWInst::Xor:
3975   case AtomicRMWInst::Xchg:
3976     emitRMWOp = XElemTy;
3977     break;
3978   case AtomicRMWInst::Sub:
3979     emitRMWOp = (IsXBinopExpr && XElemTy);
3980     break;
3981   default:
3982     emitRMWOp = false;
3983   }
3984   emitRMWOp &= XElemTy->isIntegerTy();
3985 
3986   std::pair<Value *, Value *> Res;
3987   if (emitRMWOp) {
3988     Res.first = Builder.CreateAtomicRMW(RMWOp, X, Expr, llvm::MaybeAlign(), AO);
3989     // not needed except in case of postfix captures. Generate anyway for
3990     // consistency with the else part. Will be removed with any DCE pass.
3991     // AtomicRMWInst::Xchg does not have a coressponding instruction.
3992     if (RMWOp == AtomicRMWInst::Xchg)
3993       Res.second = Res.first;
3994     else
3995       Res.second = emitRMWOpAsInstruction(Res.first, Expr, RMWOp);
3996   } else {
3997     unsigned Addrspace = cast<PointerType>(X->getType())->getAddressSpace();
3998     IntegerType *IntCastTy =
3999         IntegerType::get(M.getContext(), XElemTy->getScalarSizeInBits());
4000     Value *XBCast =
4001         Builder.CreateBitCast(X, IntCastTy->getPointerTo(Addrspace));
4002     LoadInst *OldVal =
4003         Builder.CreateLoad(IntCastTy, XBCast, X->getName() + ".atomic.load");
4004     OldVal->setAtomic(AO);
4005     // CurBB
4006     // |     /---\
4007 		// ContBB    |
4008     // |     \---/
4009     // ExitBB
4010     BasicBlock *CurBB = Builder.GetInsertBlock();
4011     Instruction *CurBBTI = CurBB->getTerminator();
4012     CurBBTI = CurBBTI ? CurBBTI : Builder.CreateUnreachable();
4013     BasicBlock *ExitBB =
4014         CurBB->splitBasicBlock(CurBBTI, X->getName() + ".atomic.exit");
4015     BasicBlock *ContBB = CurBB->splitBasicBlock(CurBB->getTerminator(),
4016                                                 X->getName() + ".atomic.cont");
4017     ContBB->getTerminator()->eraseFromParent();
4018     Builder.restoreIP(AllocaIP);
4019     AllocaInst *NewAtomicAddr = Builder.CreateAlloca(XElemTy);
4020     NewAtomicAddr->setName(X->getName() + "x.new.val");
4021     Builder.SetInsertPoint(ContBB);
4022     llvm::PHINode *PHI = Builder.CreatePHI(OldVal->getType(), 2);
4023     PHI->addIncoming(OldVal, CurBB);
4024     IntegerType *NewAtomicCastTy =
4025         IntegerType::get(M.getContext(), XElemTy->getScalarSizeInBits());
4026     bool IsIntTy = XElemTy->isIntegerTy();
4027     Value *NewAtomicIntAddr =
4028         (IsIntTy)
4029             ? NewAtomicAddr
4030             : Builder.CreateBitCast(NewAtomicAddr,
4031                                     NewAtomicCastTy->getPointerTo(Addrspace));
4032     Value *OldExprVal = PHI;
4033     if (!IsIntTy) {
4034       if (XElemTy->isFloatingPointTy()) {
4035         OldExprVal = Builder.CreateBitCast(PHI, XElemTy,
4036                                            X->getName() + ".atomic.fltCast");
4037       } else {
4038         OldExprVal = Builder.CreateIntToPtr(PHI, XElemTy,
4039                                             X->getName() + ".atomic.ptrCast");
4040       }
4041     }
4042 
4043     Value *Upd = UpdateOp(OldExprVal, Builder);
4044     Builder.CreateStore(Upd, NewAtomicAddr);
4045     LoadInst *DesiredVal = Builder.CreateLoad(IntCastTy, NewAtomicIntAddr);
4046     Value *XAddr =
4047         (IsIntTy)
4048             ? X
4049             : Builder.CreateBitCast(X, IntCastTy->getPointerTo(Addrspace));
4050     AtomicOrdering Failure =
4051         llvm::AtomicCmpXchgInst::getStrongestFailureOrdering(AO);
4052     AtomicCmpXchgInst *Result = Builder.CreateAtomicCmpXchg(
4053         XAddr, PHI, DesiredVal, llvm::MaybeAlign(), AO, Failure);
4054     Result->setVolatile(VolatileX);
4055     Value *PreviousVal = Builder.CreateExtractValue(Result, /*Idxs=*/0);
4056     Value *SuccessFailureVal = Builder.CreateExtractValue(Result, /*Idxs=*/1);
4057     PHI->addIncoming(PreviousVal, Builder.GetInsertBlock());
4058     Builder.CreateCondBr(SuccessFailureVal, ExitBB, ContBB);
4059 
4060     Res.first = OldExprVal;
4061     Res.second = Upd;
4062 
4063     // set Insertion point in exit block
4064     if (UnreachableInst *ExitTI =
4065             dyn_cast<UnreachableInst>(ExitBB->getTerminator())) {
4066       CurBBTI->eraseFromParent();
4067       Builder.SetInsertPoint(ExitBB);
4068     } else {
4069       Builder.SetInsertPoint(ExitTI);
4070     }
4071   }
4072 
4073   return Res;
4074 }
4075 
4076 OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::createAtomicCapture(
4077     const LocationDescription &Loc, InsertPointTy AllocaIP, AtomicOpValue &X,
4078     AtomicOpValue &V, Value *Expr, AtomicOrdering AO,
4079     AtomicRMWInst::BinOp RMWOp, AtomicUpdateCallbackTy &UpdateOp,
4080     bool UpdateExpr, bool IsPostfixUpdate, bool IsXBinopExpr) {
4081   if (!updateToLocation(Loc))
4082     return Loc.IP;
4083 
4084   LLVM_DEBUG({
4085     Type *XTy = X.Var->getType();
4086     assert(XTy->isPointerTy() &&
4087            "OMP Atomic expects a pointer to target memory");
4088     Type *XElemTy = X.ElemTy;
4089     assert((XElemTy->isFloatingPointTy() || XElemTy->isIntegerTy() ||
4090             XElemTy->isPointerTy()) &&
4091            "OMP atomic capture expected a scalar type");
4092     assert((RMWOp != AtomicRMWInst::Max) && (RMWOp != AtomicRMWInst::Min) &&
4093            "OpenMP atomic does not support LT or GT operations");
4094   });
4095 
4096   // If UpdateExpr is 'x' updated with some `expr` not based on 'x',
4097   // 'x' is simply atomically rewritten with 'expr'.
4098   AtomicRMWInst::BinOp AtomicOp = (UpdateExpr ? RMWOp : AtomicRMWInst::Xchg);
4099   std::pair<Value *, Value *> Result =
4100       emitAtomicUpdate(AllocaIP, X.Var, X.ElemTy, Expr, AO, AtomicOp, UpdateOp,
4101                        X.IsVolatile, IsXBinopExpr);
4102 
4103   Value *CapturedVal = (IsPostfixUpdate ? Result.first : Result.second);
4104   Builder.CreateStore(CapturedVal, V.Var, V.IsVolatile);
4105 
4106   checkAndEmitFlushAfterAtomic(Loc, AO, AtomicKind::Capture);
4107   return Builder.saveIP();
4108 }
4109 
4110 OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::createAtomicCompare(
4111     const LocationDescription &Loc, AtomicOpValue &X, AtomicOpValue &V,
4112     AtomicOpValue &R, Value *E, Value *D, AtomicOrdering AO,
4113     omp::OMPAtomicCompareOp Op, bool IsXBinopExpr, bool IsPostfixUpdate,
4114     bool IsFailOnly) {
4115 
4116   if (!updateToLocation(Loc))
4117     return Loc.IP;
4118 
4119   assert(X.Var->getType()->isPointerTy() &&
4120          "OMP atomic expects a pointer to target memory");
4121   assert((X.ElemTy->isIntegerTy() || X.ElemTy->isPointerTy()) &&
4122          "OMP atomic compare expected a integer scalar type");
4123   // compare capture
4124   if (V.Var) {
4125     assert(V.Var->getType()->isPointerTy() && "v.var must be of pointer type");
4126     assert(V.ElemTy == X.ElemTy && "x and v must be of same type");
4127   }
4128 
4129   if (Op == OMPAtomicCompareOp::EQ) {
4130     AtomicOrdering Failure = AtomicCmpXchgInst::getStrongestFailureOrdering(AO);
4131     AtomicCmpXchgInst *Result =
4132         Builder.CreateAtomicCmpXchg(X.Var, E, D, MaybeAlign(), AO, Failure);
4133     if (V.Var) {
4134       Value *OldValue = Builder.CreateExtractValue(Result, /*Idxs=*/0);
4135       assert(OldValue->getType() == V.ElemTy &&
4136              "OldValue and V must be of same type");
4137       if (IsPostfixUpdate) {
4138         Builder.CreateStore(OldValue, V.Var, V.IsVolatile);
4139       } else {
4140         Value *SuccessOrFail = Builder.CreateExtractValue(Result, /*Idxs=*/1);
4141         if (IsFailOnly) {
4142           // CurBB----
4143           //   |     |
4144           //   v     |
4145           // ContBB  |
4146           //   |     |
4147           //   v     |
4148           // ExitBB <-
4149           //
4150           // where ContBB only contains the store of old value to 'v'.
4151           BasicBlock *CurBB = Builder.GetInsertBlock();
4152           Instruction *CurBBTI = CurBB->getTerminator();
4153           CurBBTI = CurBBTI ? CurBBTI : Builder.CreateUnreachable();
4154           BasicBlock *ExitBB = CurBB->splitBasicBlock(
4155               CurBBTI, X.Var->getName() + ".atomic.exit");
4156           BasicBlock *ContBB = CurBB->splitBasicBlock(
4157               CurBB->getTerminator(), X.Var->getName() + ".atomic.cont");
4158           ContBB->getTerminator()->eraseFromParent();
4159           CurBB->getTerminator()->eraseFromParent();
4160 
4161           Builder.CreateCondBr(SuccessOrFail, ExitBB, ContBB);
4162 
4163           Builder.SetInsertPoint(ContBB);
4164           Builder.CreateStore(OldValue, V.Var);
4165           Builder.CreateBr(ExitBB);
4166 
4167           if (UnreachableInst *ExitTI =
4168                   dyn_cast<UnreachableInst>(ExitBB->getTerminator())) {
4169             CurBBTI->eraseFromParent();
4170             Builder.SetInsertPoint(ExitBB);
4171           } else {
4172             Builder.SetInsertPoint(ExitTI);
4173           }
4174         } else {
4175           Value *CapturedValue =
4176               Builder.CreateSelect(SuccessOrFail, E, OldValue);
4177           Builder.CreateStore(CapturedValue, V.Var, V.IsVolatile);
4178         }
4179       }
4180     }
4181     // The comparison result has to be stored.
4182     if (R.Var) {
4183       assert(R.Var->getType()->isPointerTy() &&
4184              "r.var must be of pointer type");
4185       assert(R.ElemTy->isIntegerTy() && "r must be of integral type");
4186 
4187       Value *SuccessFailureVal = Builder.CreateExtractValue(Result, /*Idxs=*/1);
4188       Value *ResultCast = R.IsSigned
4189                               ? Builder.CreateSExt(SuccessFailureVal, R.ElemTy)
4190                               : Builder.CreateZExt(SuccessFailureVal, R.ElemTy);
4191       Builder.CreateStore(ResultCast, R.Var, R.IsVolatile);
4192     }
4193   } else {
4194     assert((Op == OMPAtomicCompareOp::MAX || Op == OMPAtomicCompareOp::MIN) &&
4195            "Op should be either max or min at this point");
4196     assert(!IsFailOnly && "IsFailOnly is only valid when the comparison is ==");
4197 
4198     // Reverse the ordop as the OpenMP forms are different from LLVM forms.
4199     // Let's take max as example.
4200     // OpenMP form:
4201     // x = x > expr ? expr : x;
4202     // LLVM form:
4203     // *ptr = *ptr > val ? *ptr : val;
4204     // We need to transform to LLVM form.
4205     // x = x <= expr ? x : expr;
4206     AtomicRMWInst::BinOp NewOp;
4207     if (IsXBinopExpr) {
4208       if (X.IsSigned)
4209         NewOp = Op == OMPAtomicCompareOp::MAX ? AtomicRMWInst::Min
4210                                               : AtomicRMWInst::Max;
4211       else
4212         NewOp = Op == OMPAtomicCompareOp::MAX ? AtomicRMWInst::UMin
4213                                               : AtomicRMWInst::UMax;
4214     } else {
4215       if (X.IsSigned)
4216         NewOp = Op == OMPAtomicCompareOp::MAX ? AtomicRMWInst::Max
4217                                               : AtomicRMWInst::Min;
4218       else
4219         NewOp = Op == OMPAtomicCompareOp::MAX ? AtomicRMWInst::UMax
4220                                               : AtomicRMWInst::UMin;
4221     }
4222 
4223     AtomicRMWInst *OldValue =
4224         Builder.CreateAtomicRMW(NewOp, X.Var, E, MaybeAlign(), AO);
4225     if (V.Var) {
4226       Value *CapturedValue = nullptr;
4227       if (IsPostfixUpdate) {
4228         CapturedValue = OldValue;
4229       } else {
4230         CmpInst::Predicate Pred;
4231         switch (NewOp) {
4232         case AtomicRMWInst::Max:
4233           Pred = CmpInst::ICMP_SGT;
4234           break;
4235         case AtomicRMWInst::UMax:
4236           Pred = CmpInst::ICMP_UGT;
4237           break;
4238         case AtomicRMWInst::Min:
4239           Pred = CmpInst::ICMP_SLT;
4240           break;
4241         case AtomicRMWInst::UMin:
4242           Pred = CmpInst::ICMP_ULT;
4243           break;
4244         default:
4245           llvm_unreachable("unexpected comparison op");
4246         }
4247         Value *NonAtomicCmp = Builder.CreateCmp(Pred, OldValue, E);
4248         CapturedValue = Builder.CreateSelect(NonAtomicCmp, E, OldValue);
4249       }
4250       Builder.CreateStore(CapturedValue, V.Var, V.IsVolatile);
4251     }
4252   }
4253 
4254   checkAndEmitFlushAfterAtomic(Loc, AO, AtomicKind::Compare);
4255 
4256   return Builder.saveIP();
4257 }
4258 
4259 GlobalVariable *
4260 OpenMPIRBuilder::createOffloadMapnames(SmallVectorImpl<llvm::Constant *> &Names,
4261                                        std::string VarName) {
4262   llvm::Constant *MapNamesArrayInit = llvm::ConstantArray::get(
4263       llvm::ArrayType::get(
4264           llvm::Type::getInt8Ty(M.getContext())->getPointerTo(), Names.size()),
4265       Names);
4266   auto *MapNamesArrayGlobal = new llvm::GlobalVariable(
4267       M, MapNamesArrayInit->getType(),
4268       /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage, MapNamesArrayInit,
4269       VarName);
4270   return MapNamesArrayGlobal;
4271 }
4272 
4273 // Create all simple and struct types exposed by the runtime and remember
4274 // the llvm::PointerTypes of them for easy access later.
4275 void OpenMPIRBuilder::initializeTypes(Module &M) {
4276   LLVMContext &Ctx = M.getContext();
4277   StructType *T;
4278 #define OMP_TYPE(VarName, InitValue) VarName = InitValue;
4279 #define OMP_ARRAY_TYPE(VarName, ElemTy, ArraySize)                             \
4280   VarName##Ty = ArrayType::get(ElemTy, ArraySize);                             \
4281   VarName##PtrTy = PointerType::getUnqual(VarName##Ty);
4282 #define OMP_FUNCTION_TYPE(VarName, IsVarArg, ReturnType, ...)                  \
4283   VarName = FunctionType::get(ReturnType, {__VA_ARGS__}, IsVarArg);            \
4284   VarName##Ptr = PointerType::getUnqual(VarName);
4285 #define OMP_STRUCT_TYPE(VarName, StructName, ...)                              \
4286   T = StructType::getTypeByName(Ctx, StructName);                              \
4287   if (!T)                                                                      \
4288     T = StructType::create(Ctx, {__VA_ARGS__}, StructName);                    \
4289   VarName = T;                                                                 \
4290   VarName##Ptr = PointerType::getUnqual(T);
4291 #include "llvm/Frontend/OpenMP/OMPKinds.def"
4292 }
4293 
4294 void OpenMPIRBuilder::OutlineInfo::collectBlocks(
4295     SmallPtrSetImpl<BasicBlock *> &BlockSet,
4296     SmallVectorImpl<BasicBlock *> &BlockVector) {
4297   SmallVector<BasicBlock *, 32> Worklist;
4298   BlockSet.insert(EntryBB);
4299   BlockSet.insert(ExitBB);
4300 
4301   Worklist.push_back(EntryBB);
4302   while (!Worklist.empty()) {
4303     BasicBlock *BB = Worklist.pop_back_val();
4304     BlockVector.push_back(BB);
4305     for (BasicBlock *SuccBB : successors(BB))
4306       if (BlockSet.insert(SuccBB).second)
4307         Worklist.push_back(SuccBB);
4308   }
4309 }
4310 
4311 void CanonicalLoopInfo::collectControlBlocks(
4312     SmallVectorImpl<BasicBlock *> &BBs) {
4313   // We only count those BBs as control block for which we do not need to
4314   // reverse the CFG, i.e. not the loop body which can contain arbitrary control
4315   // flow. For consistency, this also means we do not add the Body block, which
4316   // is just the entry to the body code.
4317   BBs.reserve(BBs.size() + 6);
4318   BBs.append({getPreheader(), Header, Cond, Latch, Exit, getAfter()});
4319 }
4320 
4321 BasicBlock *CanonicalLoopInfo::getPreheader() const {
4322   assert(isValid() && "Requires a valid canonical loop");
4323   for (BasicBlock *Pred : predecessors(Header)) {
4324     if (Pred != Latch)
4325       return Pred;
4326   }
4327   llvm_unreachable("Missing preheader");
4328 }
4329 
4330 void CanonicalLoopInfo::setTripCount(Value *TripCount) {
4331   assert(isValid() && "Requires a valid canonical loop");
4332 
4333   Instruction *CmpI = &getCond()->front();
4334   assert(isa<CmpInst>(CmpI) && "First inst must compare IV with TripCount");
4335   CmpI->setOperand(1, TripCount);
4336 
4337 #ifndef NDEBUG
4338   assertOK();
4339 #endif
4340 }
4341 
4342 void CanonicalLoopInfo::mapIndVar(
4343     llvm::function_ref<Value *(Instruction *)> Updater) {
4344   assert(isValid() && "Requires a valid canonical loop");
4345 
4346   Instruction *OldIV = getIndVar();
4347 
4348   // Record all uses excluding those introduced by the updater. Uses by the
4349   // CanonicalLoopInfo itself to keep track of the number of iterations are
4350   // excluded.
4351   SmallVector<Use *> ReplacableUses;
4352   for (Use &U : OldIV->uses()) {
4353     auto *User = dyn_cast<Instruction>(U.getUser());
4354     if (!User)
4355       continue;
4356     if (User->getParent() == getCond())
4357       continue;
4358     if (User->getParent() == getLatch())
4359       continue;
4360     ReplacableUses.push_back(&U);
4361   }
4362 
4363   // Run the updater that may introduce new uses
4364   Value *NewIV = Updater(OldIV);
4365 
4366   // Replace the old uses with the value returned by the updater.
4367   for (Use *U : ReplacableUses)
4368     U->set(NewIV);
4369 
4370 #ifndef NDEBUG
4371   assertOK();
4372 #endif
4373 }
4374 
4375 void CanonicalLoopInfo::assertOK() const {
4376 #ifndef NDEBUG
4377   // No constraints if this object currently does not describe a loop.
4378   if (!isValid())
4379     return;
4380 
4381   BasicBlock *Preheader = getPreheader();
4382   BasicBlock *Body = getBody();
4383   BasicBlock *After = getAfter();
4384 
4385   // Verify standard control-flow we use for OpenMP loops.
4386   assert(Preheader);
4387   assert(isa<BranchInst>(Preheader->getTerminator()) &&
4388          "Preheader must terminate with unconditional branch");
4389   assert(Preheader->getSingleSuccessor() == Header &&
4390          "Preheader must jump to header");
4391 
4392   assert(Header);
4393   assert(isa<BranchInst>(Header->getTerminator()) &&
4394          "Header must terminate with unconditional branch");
4395   assert(Header->getSingleSuccessor() == Cond &&
4396          "Header must jump to exiting block");
4397 
4398   assert(Cond);
4399   assert(Cond->getSinglePredecessor() == Header &&
4400          "Exiting block only reachable from header");
4401 
4402   assert(isa<BranchInst>(Cond->getTerminator()) &&
4403          "Exiting block must terminate with conditional branch");
4404   assert(size(successors(Cond)) == 2 &&
4405          "Exiting block must have two successors");
4406   assert(cast<BranchInst>(Cond->getTerminator())->getSuccessor(0) == Body &&
4407          "Exiting block's first successor jump to the body");
4408   assert(cast<BranchInst>(Cond->getTerminator())->getSuccessor(1) == Exit &&
4409          "Exiting block's second successor must exit the loop");
4410 
4411   assert(Body);
4412   assert(Body->getSinglePredecessor() == Cond &&
4413          "Body only reachable from exiting block");
4414   assert(!isa<PHINode>(Body->front()));
4415 
4416   assert(Latch);
4417   assert(isa<BranchInst>(Latch->getTerminator()) &&
4418          "Latch must terminate with unconditional branch");
4419   assert(Latch->getSingleSuccessor() == Header && "Latch must jump to header");
4420   // TODO: To support simple redirecting of the end of the body code that has
4421   // multiple; introduce another auxiliary basic block like preheader and after.
4422   assert(Latch->getSinglePredecessor() != nullptr);
4423   assert(!isa<PHINode>(Latch->front()));
4424 
4425   assert(Exit);
4426   assert(isa<BranchInst>(Exit->getTerminator()) &&
4427          "Exit block must terminate with unconditional branch");
4428   assert(Exit->getSingleSuccessor() == After &&
4429          "Exit block must jump to after block");
4430 
4431   assert(After);
4432   assert(After->getSinglePredecessor() == Exit &&
4433          "After block only reachable from exit block");
4434   assert(After->empty() || !isa<PHINode>(After->front()));
4435 
4436   Instruction *IndVar = getIndVar();
4437   assert(IndVar && "Canonical induction variable not found?");
4438   assert(isa<IntegerType>(IndVar->getType()) &&
4439          "Induction variable must be an integer");
4440   assert(cast<PHINode>(IndVar)->getParent() == Header &&
4441          "Induction variable must be a PHI in the loop header");
4442   assert(cast<PHINode>(IndVar)->getIncomingBlock(0) == Preheader);
4443   assert(
4444       cast<ConstantInt>(cast<PHINode>(IndVar)->getIncomingValue(0))->isZero());
4445   assert(cast<PHINode>(IndVar)->getIncomingBlock(1) == Latch);
4446 
4447   auto *NextIndVar = cast<PHINode>(IndVar)->getIncomingValue(1);
4448   assert(cast<Instruction>(NextIndVar)->getParent() == Latch);
4449   assert(cast<BinaryOperator>(NextIndVar)->getOpcode() == BinaryOperator::Add);
4450   assert(cast<BinaryOperator>(NextIndVar)->getOperand(0) == IndVar);
4451   assert(cast<ConstantInt>(cast<BinaryOperator>(NextIndVar)->getOperand(1))
4452              ->isOne());
4453 
4454   Value *TripCount = getTripCount();
4455   assert(TripCount && "Loop trip count not found?");
4456   assert(IndVar->getType() == TripCount->getType() &&
4457          "Trip count and induction variable must have the same type");
4458 
4459   auto *CmpI = cast<CmpInst>(&Cond->front());
4460   assert(CmpI->getPredicate() == CmpInst::ICMP_ULT &&
4461          "Exit condition must be a signed less-than comparison");
4462   assert(CmpI->getOperand(0) == IndVar &&
4463          "Exit condition must compare the induction variable");
4464   assert(CmpI->getOperand(1) == TripCount &&
4465          "Exit condition must compare with the trip count");
4466 #endif
4467 }
4468 
4469 void CanonicalLoopInfo::invalidate() {
4470   Header = nullptr;
4471   Cond = nullptr;
4472   Latch = nullptr;
4473   Exit = nullptr;
4474 }
4475