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