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 
17 #include "llvm/ADT/StringRef.h"
18 #include "llvm/ADT/Triple.h"
19 #include "llvm/IR/CFG.h"
20 #include "llvm/IR/DebugInfo.h"
21 #include "llvm/IR/IRBuilder.h"
22 #include "llvm/IR/MDBuilder.h"
23 #include "llvm/Support/CommandLine.h"
24 #include "llvm/Support/Error.h"
25 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
26 #include "llvm/Transforms/Utils/CodeExtractor.h"
27 
28 #include <sstream>
29 
30 #define DEBUG_TYPE "openmp-ir-builder"
31 
32 using namespace llvm;
33 using namespace omp;
34 
35 static cl::opt<bool>
36     OptimisticAttributes("openmp-ir-builder-optimistic-attributes", cl::Hidden,
37                          cl::desc("Use optimistic attributes describing "
38                                   "'as-if' properties of runtime calls."),
39                          cl::init(false));
40 
41 void OpenMPIRBuilder::addAttributes(omp::RuntimeFunction FnID, Function &Fn) {
42   LLVMContext &Ctx = Fn.getContext();
43 
44   // Get the function's current attributes.
45   auto Attrs = Fn.getAttributes();
46   auto FnAttrs = Attrs.getFnAttributes();
47   auto RetAttrs = Attrs.getRetAttributes();
48   SmallVector<AttributeSet, 4> ArgAttrs;
49   for (size_t ArgNo = 0; ArgNo < Fn.arg_size(); ++ArgNo)
50     ArgAttrs.emplace_back(Attrs.getParamAttributes(ArgNo));
51 
52 #define OMP_ATTRS_SET(VarName, AttrSet) AttributeSet VarName = AttrSet;
53 #include "llvm/Frontend/OpenMP/OMPKinds.def"
54 
55   // Add attributes to the function declaration.
56   switch (FnID) {
57 #define OMP_RTL_ATTRS(Enum, FnAttrSet, RetAttrSet, ArgAttrSets)                \
58   case Enum:                                                                   \
59     FnAttrs = FnAttrs.addAttributes(Ctx, FnAttrSet);                           \
60     RetAttrs = RetAttrs.addAttributes(Ctx, RetAttrSet);                        \
61     for (size_t ArgNo = 0; ArgNo < ArgAttrSets.size(); ++ArgNo)                \
62       ArgAttrs[ArgNo] =                                                        \
63           ArgAttrs[ArgNo].addAttributes(Ctx, ArgAttrSets[ArgNo]);              \
64     Fn.setAttributes(AttributeList::get(Ctx, FnAttrs, RetAttrs, ArgAttrs));    \
65     break;
66 #include "llvm/Frontend/OpenMP/OMPKinds.def"
67   default:
68     // Attributes are optional.
69     break;
70   }
71 }
72 
73 FunctionCallee
74 OpenMPIRBuilder::getOrCreateRuntimeFunction(Module &M, RuntimeFunction FnID) {
75   FunctionType *FnTy = nullptr;
76   Function *Fn = nullptr;
77 
78   // Try to find the declation in the module first.
79   switch (FnID) {
80 #define OMP_RTL(Enum, Str, IsVarArg, ReturnType, ...)                          \
81   case Enum:                                                                   \
82     FnTy = FunctionType::get(ReturnType, ArrayRef<Type *>{__VA_ARGS__},        \
83                              IsVarArg);                                        \
84     Fn = M.getFunction(Str);                                                   \
85     break;
86 #include "llvm/Frontend/OpenMP/OMPKinds.def"
87   }
88 
89   if (!Fn) {
90     // Create a new declaration if we need one.
91     switch (FnID) {
92 #define OMP_RTL(Enum, Str, ...)                                                \
93   case Enum:                                                                   \
94     Fn = Function::Create(FnTy, GlobalValue::ExternalLinkage, Str, M);         \
95     break;
96 #include "llvm/Frontend/OpenMP/OMPKinds.def"
97     }
98 
99     // Add information if the runtime function takes a callback function
100     if (FnID == OMPRTL___kmpc_fork_call || FnID == OMPRTL___kmpc_fork_teams) {
101       if (!Fn->hasMetadata(LLVMContext::MD_callback)) {
102         LLVMContext &Ctx = Fn->getContext();
103         MDBuilder MDB(Ctx);
104         // Annotate the callback behavior of the runtime function:
105         //  - The callback callee is argument number 2 (microtask).
106         //  - The first two arguments of the callback callee are unknown (-1).
107         //  - All variadic arguments to the runtime function are passed to the
108         //    callback callee.
109         Fn->addMetadata(
110             LLVMContext::MD_callback,
111             *MDNode::get(Ctx, {MDB.createCallbackEncoding(
112                                   2, {-1, -1}, /* VarArgsArePassed */ true)}));
113       }
114     }
115 
116     LLVM_DEBUG(dbgs() << "Created OpenMP runtime function " << Fn->getName()
117                       << " with type " << *Fn->getFunctionType() << "\n");
118     addAttributes(FnID, *Fn);
119 
120   } else {
121     LLVM_DEBUG(dbgs() << "Found OpenMP runtime function " << Fn->getName()
122                       << " with type " << *Fn->getFunctionType() << "\n");
123   }
124 
125   assert(Fn && "Failed to create OpenMP runtime function");
126 
127   // Cast the function to the expected type if necessary
128   Constant *C = ConstantExpr::getBitCast(Fn, FnTy->getPointerTo());
129   return {FnTy, C};
130 }
131 
132 Function *OpenMPIRBuilder::getOrCreateRuntimeFunctionPtr(RuntimeFunction FnID) {
133   FunctionCallee RTLFn = getOrCreateRuntimeFunction(M, FnID);
134   auto *Fn = dyn_cast<llvm::Function>(RTLFn.getCallee());
135   assert(Fn && "Failed to create OpenMP runtime function pointer");
136   return Fn;
137 }
138 
139 void OpenMPIRBuilder::initialize() { initializeTypes(M); }
140 
141 void OpenMPIRBuilder::finalize(Function *Fn, bool AllowExtractorSinking) {
142   SmallPtrSet<BasicBlock *, 32> ParallelRegionBlockSet;
143   SmallVector<BasicBlock *, 32> Blocks;
144   SmallVector<OutlineInfo, 16> DeferredOutlines;
145   for (OutlineInfo &OI : OutlineInfos) {
146     // Skip functions that have not finalized yet; may happen with nested
147     // function generation.
148     if (Fn && OI.getFunction() != Fn) {
149       DeferredOutlines.push_back(OI);
150       continue;
151     }
152 
153     ParallelRegionBlockSet.clear();
154     Blocks.clear();
155     OI.collectBlocks(ParallelRegionBlockSet, Blocks);
156 
157     Function *OuterFn = OI.getFunction();
158     CodeExtractorAnalysisCache CEAC(*OuterFn);
159     CodeExtractor Extractor(Blocks, /* DominatorTree */ nullptr,
160                             /* AggregateArgs */ false,
161                             /* BlockFrequencyInfo */ nullptr,
162                             /* BranchProbabilityInfo */ nullptr,
163                             /* AssumptionCache */ nullptr,
164                             /* AllowVarArgs */ true,
165                             /* AllowAlloca */ true,
166                             /* Suffix */ ".omp_par");
167 
168     LLVM_DEBUG(dbgs() << "Before     outlining: " << *OuterFn << "\n");
169     LLVM_DEBUG(dbgs() << "Entry " << OI.EntryBB->getName()
170                       << " Exit: " << OI.ExitBB->getName() << "\n");
171     assert(Extractor.isEligible() &&
172            "Expected OpenMP outlining to be possible!");
173 
174     Function *OutlinedFn = Extractor.extractCodeRegion(CEAC);
175 
176     LLVM_DEBUG(dbgs() << "After      outlining: " << *OuterFn << "\n");
177     LLVM_DEBUG(dbgs() << "   Outlined function: " << *OutlinedFn << "\n");
178     assert(OutlinedFn->getReturnType()->isVoidTy() &&
179            "OpenMP outlined functions should not return a value!");
180 
181     // For compability with the clang CG we move the outlined function after the
182     // one with the parallel region.
183     OutlinedFn->removeFromParent();
184     M.getFunctionList().insertAfter(OuterFn->getIterator(), OutlinedFn);
185 
186     // Remove the artificial entry introduced by the extractor right away, we
187     // made our own entry block after all.
188     {
189       BasicBlock &ArtificialEntry = OutlinedFn->getEntryBlock();
190       assert(ArtificialEntry.getUniqueSuccessor() == OI.EntryBB);
191       assert(OI.EntryBB->getUniquePredecessor() == &ArtificialEntry);
192       if (AllowExtractorSinking) {
193         // Move instructions from the to-be-deleted ArtificialEntry to the entry
194         // basic block of the parallel region. CodeExtractor may have sunk
195         // allocas/bitcasts for values that are solely used in the outlined
196         // region and do not escape.
197         assert(!ArtificialEntry.empty() &&
198                "Expected instructions to sink in the outlined region");
199         for (BasicBlock::iterator It = ArtificialEntry.begin(),
200                                   End = ArtificialEntry.end();
201              It != End;) {
202           Instruction &I = *It;
203           It++;
204 
205           if (I.isTerminator())
206             continue;
207 
208           I.moveBefore(*OI.EntryBB, OI.EntryBB->getFirstInsertionPt());
209         }
210       }
211       OI.EntryBB->moveBefore(&ArtificialEntry);
212       ArtificialEntry.eraseFromParent();
213     }
214     assert(&OutlinedFn->getEntryBlock() == OI.EntryBB);
215     assert(OutlinedFn && OutlinedFn->getNumUses() == 1);
216 
217     // Run a user callback, e.g. to add attributes.
218     if (OI.PostOutlineCB)
219       OI.PostOutlineCB(*OutlinedFn);
220   }
221 
222   // Remove work items that have been completed.
223   OutlineInfos = std::move(DeferredOutlines);
224 }
225 
226 OpenMPIRBuilder::~OpenMPIRBuilder() {
227   assert(OutlineInfos.empty() && "There must be no outstanding outlinings");
228 }
229 
230 Value *OpenMPIRBuilder::getOrCreateIdent(Constant *SrcLocStr,
231                                          IdentFlag LocFlags,
232                                          unsigned Reserve2Flags) {
233   // Enable "C-mode".
234   LocFlags |= OMP_IDENT_FLAG_KMPC;
235 
236   Value *&Ident =
237       IdentMap[{SrcLocStr, uint64_t(LocFlags) << 31 | Reserve2Flags}];
238   if (!Ident) {
239     Constant *I32Null = ConstantInt::getNullValue(Int32);
240     Constant *IdentData[] = {
241         I32Null, ConstantInt::get(Int32, uint32_t(LocFlags)),
242         ConstantInt::get(Int32, Reserve2Flags), I32Null, SrcLocStr};
243     Constant *Initializer = ConstantStruct::get(
244         cast<StructType>(IdentPtr->getPointerElementType()), IdentData);
245 
246     // Look for existing encoding of the location + flags, not needed but
247     // minimizes the difference to the existing solution while we transition.
248     for (GlobalVariable &GV : M.getGlobalList())
249       if (GV.getType() == IdentPtr && GV.hasInitializer())
250         if (GV.getInitializer() == Initializer)
251           return Ident = &GV;
252 
253     auto *GV = new GlobalVariable(M, IdentPtr->getPointerElementType(),
254                                   /* isConstant = */ true,
255                                   GlobalValue::PrivateLinkage, Initializer);
256     GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
257     GV->setAlignment(Align(8));
258     Ident = GV;
259   }
260   return Builder.CreatePointerCast(Ident, IdentPtr);
261 }
262 
263 Type *OpenMPIRBuilder::getLanemaskType() {
264   LLVMContext &Ctx = M.getContext();
265   Triple triple(M.getTargetTriple());
266 
267   // This test is adequate until deviceRTL has finer grained lane widths
268   return triple.isAMDGCN() ? Type::getInt64Ty(Ctx) : Type::getInt32Ty(Ctx);
269 }
270 
271 Constant *OpenMPIRBuilder::getOrCreateSrcLocStr(StringRef LocStr) {
272   Constant *&SrcLocStr = SrcLocStrMap[LocStr];
273   if (!SrcLocStr) {
274     Constant *Initializer =
275         ConstantDataArray::getString(M.getContext(), LocStr);
276 
277     // Look for existing encoding of the location, not needed but minimizes the
278     // difference to the existing solution while we transition.
279     for (GlobalVariable &GV : M.getGlobalList())
280       if (GV.isConstant() && GV.hasInitializer() &&
281           GV.getInitializer() == Initializer)
282         return SrcLocStr = ConstantExpr::getPointerCast(&GV, Int8Ptr);
283 
284     SrcLocStr = Builder.CreateGlobalStringPtr(LocStr, /* Name */ "",
285                                               /* AddressSpace */ 0, &M);
286   }
287   return SrcLocStr;
288 }
289 
290 Constant *OpenMPIRBuilder::getOrCreateSrcLocStr(StringRef FunctionName,
291                                                 StringRef FileName,
292                                                 unsigned Line,
293                                                 unsigned Column) {
294   SmallString<128> Buffer;
295   Buffer.push_back(';');
296   Buffer.append(FileName);
297   Buffer.push_back(';');
298   Buffer.append(FunctionName);
299   Buffer.push_back(';');
300   Buffer.append(std::to_string(Line));
301   Buffer.push_back(';');
302   Buffer.append(std::to_string(Column));
303   Buffer.push_back(';');
304   Buffer.push_back(';');
305   return getOrCreateSrcLocStr(Buffer.str());
306 }
307 
308 Constant *OpenMPIRBuilder::getOrCreateDefaultSrcLocStr() {
309   return getOrCreateSrcLocStr(";unknown;unknown;0;0;;");
310 }
311 
312 Constant *
313 OpenMPIRBuilder::getOrCreateSrcLocStr(const LocationDescription &Loc) {
314   DILocation *DIL = Loc.DL.get();
315   if (!DIL)
316     return getOrCreateDefaultSrcLocStr();
317   StringRef FileName = M.getName();
318   if (DIFile *DIF = DIL->getFile())
319     if (Optional<StringRef> Source = DIF->getSource())
320       FileName = *Source;
321   StringRef Function = DIL->getScope()->getSubprogram()->getName();
322   Function =
323       !Function.empty() ? Function : Loc.IP.getBlock()->getParent()->getName();
324   return getOrCreateSrcLocStr(Function, FileName, DIL->getLine(),
325                               DIL->getColumn());
326 }
327 
328 Value *OpenMPIRBuilder::getOrCreateThreadID(Value *Ident) {
329   return Builder.CreateCall(
330       getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_global_thread_num), Ident,
331       "omp_global_thread_num");
332 }
333 
334 OpenMPIRBuilder::InsertPointTy
335 OpenMPIRBuilder::createBarrier(const LocationDescription &Loc, Directive DK,
336                                bool ForceSimpleCall, bool CheckCancelFlag) {
337   if (!updateToLocation(Loc))
338     return Loc.IP;
339   return emitBarrierImpl(Loc, DK, ForceSimpleCall, CheckCancelFlag);
340 }
341 
342 OpenMPIRBuilder::InsertPointTy
343 OpenMPIRBuilder::emitBarrierImpl(const LocationDescription &Loc, Directive Kind,
344                                  bool ForceSimpleCall, bool CheckCancelFlag) {
345   // Build call __kmpc_cancel_barrier(loc, thread_id) or
346   //            __kmpc_barrier(loc, thread_id);
347 
348   IdentFlag BarrierLocFlags;
349   switch (Kind) {
350   case OMPD_for:
351     BarrierLocFlags = OMP_IDENT_FLAG_BARRIER_IMPL_FOR;
352     break;
353   case OMPD_sections:
354     BarrierLocFlags = OMP_IDENT_FLAG_BARRIER_IMPL_SECTIONS;
355     break;
356   case OMPD_single:
357     BarrierLocFlags = OMP_IDENT_FLAG_BARRIER_IMPL_SINGLE;
358     break;
359   case OMPD_barrier:
360     BarrierLocFlags = OMP_IDENT_FLAG_BARRIER_EXPL;
361     break;
362   default:
363     BarrierLocFlags = OMP_IDENT_FLAG_BARRIER_IMPL;
364     break;
365   }
366 
367   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc);
368   Value *Args[] = {getOrCreateIdent(SrcLocStr, BarrierLocFlags),
369                    getOrCreateThreadID(getOrCreateIdent(SrcLocStr))};
370 
371   // If we are in a cancellable parallel region, barriers are cancellation
372   // points.
373   // TODO: Check why we would force simple calls or to ignore the cancel flag.
374   bool UseCancelBarrier =
375       !ForceSimpleCall && isLastFinalizationInfoCancellable(OMPD_parallel);
376 
377   Value *Result =
378       Builder.CreateCall(getOrCreateRuntimeFunctionPtr(
379                              UseCancelBarrier ? OMPRTL___kmpc_cancel_barrier
380                                               : OMPRTL___kmpc_barrier),
381                          Args);
382 
383   if (UseCancelBarrier && CheckCancelFlag)
384     emitCancelationCheckImpl(Result, OMPD_parallel);
385 
386   return Builder.saveIP();
387 }
388 
389 OpenMPIRBuilder::InsertPointTy
390 OpenMPIRBuilder::createCancel(const LocationDescription &Loc,
391                               Value *IfCondition,
392                               omp::Directive CanceledDirective) {
393   if (!updateToLocation(Loc))
394     return Loc.IP;
395 
396   // LLVM utilities like blocks with terminators.
397   auto *UI = Builder.CreateUnreachable();
398 
399   Instruction *ThenTI = UI, *ElseTI = nullptr;
400   if (IfCondition)
401     SplitBlockAndInsertIfThenElse(IfCondition, UI, &ThenTI, &ElseTI);
402   Builder.SetInsertPoint(ThenTI);
403 
404   Value *CancelKind = nullptr;
405   switch (CanceledDirective) {
406 #define OMP_CANCEL_KIND(Enum, Str, DirectiveEnum, Value)                       \
407   case DirectiveEnum:                                                          \
408     CancelKind = Builder.getInt32(Value);                                      \
409     break;
410 #include "llvm/Frontend/OpenMP/OMPKinds.def"
411   default:
412     llvm_unreachable("Unknown cancel kind!");
413   }
414 
415   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc);
416   Value *Ident = getOrCreateIdent(SrcLocStr);
417   Value *Args[] = {Ident, getOrCreateThreadID(Ident), CancelKind};
418   Value *Result = Builder.CreateCall(
419       getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_cancel), Args);
420 
421   // The actual cancel logic is shared with others, e.g., cancel_barriers.
422   emitCancelationCheckImpl(Result, CanceledDirective);
423 
424   // Update the insertion point and remove the terminator we introduced.
425   Builder.SetInsertPoint(UI->getParent());
426   UI->eraseFromParent();
427 
428   return Builder.saveIP();
429 }
430 
431 void OpenMPIRBuilder::emitCancelationCheckImpl(
432     Value *CancelFlag, omp::Directive CanceledDirective) {
433   assert(isLastFinalizationInfoCancellable(CanceledDirective) &&
434          "Unexpected cancellation!");
435 
436   // For a cancel barrier we create two new blocks.
437   BasicBlock *BB = Builder.GetInsertBlock();
438   BasicBlock *NonCancellationBlock;
439   if (Builder.GetInsertPoint() == BB->end()) {
440     // TODO: This branch will not be needed once we moved to the
441     // OpenMPIRBuilder codegen completely.
442     NonCancellationBlock = BasicBlock::Create(
443         BB->getContext(), BB->getName() + ".cont", BB->getParent());
444   } else {
445     NonCancellationBlock = SplitBlock(BB, &*Builder.GetInsertPoint());
446     BB->getTerminator()->eraseFromParent();
447     Builder.SetInsertPoint(BB);
448   }
449   BasicBlock *CancellationBlock = BasicBlock::Create(
450       BB->getContext(), BB->getName() + ".cncl", BB->getParent());
451 
452   // Jump to them based on the return value.
453   Value *Cmp = Builder.CreateIsNull(CancelFlag);
454   Builder.CreateCondBr(Cmp, NonCancellationBlock, CancellationBlock,
455                        /* TODO weight */ nullptr, nullptr);
456 
457   // From the cancellation block we finalize all variables and go to the
458   // post finalization block that is known to the FiniCB callback.
459   Builder.SetInsertPoint(CancellationBlock);
460   auto &FI = FinalizationStack.back();
461   FI.FiniCB(Builder.saveIP());
462 
463   // The continuation block is where code generation continues.
464   Builder.SetInsertPoint(NonCancellationBlock, NonCancellationBlock->begin());
465 }
466 
467 IRBuilder<>::InsertPoint OpenMPIRBuilder::createParallel(
468     const LocationDescription &Loc, InsertPointTy OuterAllocaIP,
469     BodyGenCallbackTy BodyGenCB, PrivatizeCallbackTy PrivCB,
470     FinalizeCallbackTy FiniCB, Value *IfCondition, Value *NumThreads,
471     omp::ProcBindKind ProcBind, bool IsCancellable) {
472   if (!updateToLocation(Loc))
473     return Loc.IP;
474 
475   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc);
476   Value *Ident = getOrCreateIdent(SrcLocStr);
477   Value *ThreadID = getOrCreateThreadID(Ident);
478 
479   if (NumThreads) {
480     // Build call __kmpc_push_num_threads(&Ident, global_tid, num_threads)
481     Value *Args[] = {
482         Ident, ThreadID,
483         Builder.CreateIntCast(NumThreads, Int32, /*isSigned*/ false)};
484     Builder.CreateCall(
485         getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_push_num_threads), Args);
486   }
487 
488   if (ProcBind != OMP_PROC_BIND_default) {
489     // Build call __kmpc_push_proc_bind(&Ident, global_tid, proc_bind)
490     Value *Args[] = {
491         Ident, ThreadID,
492         ConstantInt::get(Int32, unsigned(ProcBind), /*isSigned=*/true)};
493     Builder.CreateCall(
494         getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_push_proc_bind), Args);
495   }
496 
497   BasicBlock *InsertBB = Builder.GetInsertBlock();
498   Function *OuterFn = InsertBB->getParent();
499 
500   // Save the outer alloca block because the insertion iterator may get
501   // invalidated and we still need this later.
502   BasicBlock *OuterAllocaBlock = OuterAllocaIP.getBlock();
503 
504   // Vector to remember instructions we used only during the modeling but which
505   // we want to delete at the end.
506   SmallVector<Instruction *, 4> ToBeDeleted;
507 
508   // Change the location to the outer alloca insertion point to create and
509   // initialize the allocas we pass into the parallel region.
510   Builder.restoreIP(OuterAllocaIP);
511   AllocaInst *TIDAddr = Builder.CreateAlloca(Int32, nullptr, "tid.addr");
512   AllocaInst *ZeroAddr = Builder.CreateAlloca(Int32, nullptr, "zero.addr");
513 
514   // If there is an if condition we actually use the TIDAddr and ZeroAddr in the
515   // program, otherwise we only need them for modeling purposes to get the
516   // associated arguments in the outlined function. In the former case,
517   // initialize the allocas properly, in the latter case, delete them later.
518   if (IfCondition) {
519     Builder.CreateStore(Constant::getNullValue(Int32), TIDAddr);
520     Builder.CreateStore(Constant::getNullValue(Int32), ZeroAddr);
521   } else {
522     ToBeDeleted.push_back(TIDAddr);
523     ToBeDeleted.push_back(ZeroAddr);
524   }
525 
526   // Create an artificial insertion point that will also ensure the blocks we
527   // are about to split are not degenerated.
528   auto *UI = new UnreachableInst(Builder.getContext(), InsertBB);
529 
530   Instruction *ThenTI = UI, *ElseTI = nullptr;
531   if (IfCondition)
532     SplitBlockAndInsertIfThenElse(IfCondition, UI, &ThenTI, &ElseTI);
533 
534   BasicBlock *ThenBB = ThenTI->getParent();
535   BasicBlock *PRegEntryBB = ThenBB->splitBasicBlock(ThenTI, "omp.par.entry");
536   BasicBlock *PRegBodyBB =
537       PRegEntryBB->splitBasicBlock(ThenTI, "omp.par.region");
538   BasicBlock *PRegPreFiniBB =
539       PRegBodyBB->splitBasicBlock(ThenTI, "omp.par.pre_finalize");
540   BasicBlock *PRegExitBB =
541       PRegPreFiniBB->splitBasicBlock(ThenTI, "omp.par.exit");
542 
543   auto FiniCBWrapper = [&](InsertPointTy IP) {
544     // Hide "open-ended" blocks from the given FiniCB by setting the right jump
545     // target to the region exit block.
546     if (IP.getBlock()->end() == IP.getPoint()) {
547       IRBuilder<>::InsertPointGuard IPG(Builder);
548       Builder.restoreIP(IP);
549       Instruction *I = Builder.CreateBr(PRegExitBB);
550       IP = InsertPointTy(I->getParent(), I->getIterator());
551     }
552     assert(IP.getBlock()->getTerminator()->getNumSuccessors() == 1 &&
553            IP.getBlock()->getTerminator()->getSuccessor(0) == PRegExitBB &&
554            "Unexpected insertion point for finalization call!");
555     return FiniCB(IP);
556   };
557 
558   FinalizationStack.push_back({FiniCBWrapper, OMPD_parallel, IsCancellable});
559 
560   // Generate the privatization allocas in the block that will become the entry
561   // of the outlined function.
562   Builder.SetInsertPoint(PRegEntryBB->getTerminator());
563   InsertPointTy InnerAllocaIP = Builder.saveIP();
564 
565   AllocaInst *PrivTIDAddr =
566       Builder.CreateAlloca(Int32, nullptr, "tid.addr.local");
567   Instruction *PrivTID = Builder.CreateLoad(Int32, PrivTIDAddr, "tid");
568 
569   // Add some fake uses for OpenMP provided arguments.
570   ToBeDeleted.push_back(Builder.CreateLoad(Int32, TIDAddr, "tid.addr.use"));
571   Instruction *ZeroAddrUse = Builder.CreateLoad(Int32, ZeroAddr,
572                                                 "zero.addr.use");
573   ToBeDeleted.push_back(ZeroAddrUse);
574 
575   // ThenBB
576   //   |
577   //   V
578   // PRegionEntryBB         <- Privatization allocas are placed here.
579   //   |
580   //   V
581   // PRegionBodyBB          <- BodeGen is invoked here.
582   //   |
583   //   V
584   // PRegPreFiniBB          <- The block we will start finalization from.
585   //   |
586   //   V
587   // PRegionExitBB          <- A common exit to simplify block collection.
588   //
589 
590   LLVM_DEBUG(dbgs() << "Before body codegen: " << *OuterFn << "\n");
591 
592   // Let the caller create the body.
593   assert(BodyGenCB && "Expected body generation callback!");
594   InsertPointTy CodeGenIP(PRegBodyBB, PRegBodyBB->begin());
595   BodyGenCB(InnerAllocaIP, CodeGenIP, *PRegPreFiniBB);
596 
597   LLVM_DEBUG(dbgs() << "After  body codegen: " << *OuterFn << "\n");
598 
599   FunctionCallee RTLFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_fork_call);
600   if (auto *F = dyn_cast<llvm::Function>(RTLFn.getCallee())) {
601     if (!F->hasMetadata(llvm::LLVMContext::MD_callback)) {
602       llvm::LLVMContext &Ctx = F->getContext();
603       MDBuilder MDB(Ctx);
604       // Annotate the callback behavior of the __kmpc_fork_call:
605       //  - The callback callee is argument number 2 (microtask).
606       //  - The first two arguments of the callback callee are unknown (-1).
607       //  - All variadic arguments to the __kmpc_fork_call are passed to the
608       //    callback callee.
609       F->addMetadata(
610           llvm::LLVMContext::MD_callback,
611           *llvm::MDNode::get(
612               Ctx, {MDB.createCallbackEncoding(2, {-1, -1},
613                                                /* VarArgsArePassed */ true)}));
614     }
615   }
616 
617   OutlineInfo OI;
618   OI.PostOutlineCB = [=](Function &OutlinedFn) {
619     // Add some known attributes.
620     OutlinedFn.addParamAttr(0, Attribute::NoAlias);
621     OutlinedFn.addParamAttr(1, Attribute::NoAlias);
622     OutlinedFn.addFnAttr(Attribute::NoUnwind);
623     OutlinedFn.addFnAttr(Attribute::NoRecurse);
624 
625     assert(OutlinedFn.arg_size() >= 2 &&
626            "Expected at least tid and bounded tid as arguments");
627     unsigned NumCapturedVars =
628         OutlinedFn.arg_size() - /* tid & bounded tid */ 2;
629 
630     CallInst *CI = cast<CallInst>(OutlinedFn.user_back());
631     CI->getParent()->setName("omp_parallel");
632     Builder.SetInsertPoint(CI);
633 
634     // Build call __kmpc_fork_call(Ident, n, microtask, var1, .., varn);
635     Value *ForkCallArgs[] = {
636         Ident, Builder.getInt32(NumCapturedVars),
637         Builder.CreateBitCast(&OutlinedFn, ParallelTaskPtr)};
638 
639     SmallVector<Value *, 16> RealArgs;
640     RealArgs.append(std::begin(ForkCallArgs), std::end(ForkCallArgs));
641     RealArgs.append(CI->arg_begin() + /* tid & bound tid */ 2, CI->arg_end());
642 
643     Builder.CreateCall(RTLFn, RealArgs);
644 
645     LLVM_DEBUG(dbgs() << "With fork_call placed: "
646                       << *Builder.GetInsertBlock()->getParent() << "\n");
647 
648     InsertPointTy ExitIP(PRegExitBB, PRegExitBB->end());
649 
650     // Initialize the local TID stack location with the argument value.
651     Builder.SetInsertPoint(PrivTID);
652     Function::arg_iterator OutlinedAI = OutlinedFn.arg_begin();
653     Builder.CreateStore(Builder.CreateLoad(Int32, OutlinedAI), PrivTIDAddr);
654 
655     // If no "if" clause was present we do not need the call created during
656     // outlining, otherwise we reuse it in the serialized parallel region.
657     if (!ElseTI) {
658       CI->eraseFromParent();
659     } else {
660 
661       // If an "if" clause was present we are now generating the serialized
662       // version into the "else" branch.
663       Builder.SetInsertPoint(ElseTI);
664 
665       // Build calls __kmpc_serialized_parallel(&Ident, GTid);
666       Value *SerializedParallelCallArgs[] = {Ident, ThreadID};
667       Builder.CreateCall(
668           getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_serialized_parallel),
669           SerializedParallelCallArgs);
670 
671       // OutlinedFn(&GTid, &zero, CapturedStruct);
672       CI->removeFromParent();
673       Builder.Insert(CI);
674 
675       // __kmpc_end_serialized_parallel(&Ident, GTid);
676       Value *EndArgs[] = {Ident, ThreadID};
677       Builder.CreateCall(
678           getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_end_serialized_parallel),
679           EndArgs);
680 
681       LLVM_DEBUG(dbgs() << "With serialized parallel region: "
682                         << *Builder.GetInsertBlock()->getParent() << "\n");
683     }
684 
685     for (Instruction *I : ToBeDeleted)
686       I->eraseFromParent();
687   };
688 
689   // Adjust the finalization stack, verify the adjustment, and call the
690   // finalize function a last time to finalize values between the pre-fini
691   // block and the exit block if we left the parallel "the normal way".
692   auto FiniInfo = FinalizationStack.pop_back_val();
693   (void)FiniInfo;
694   assert(FiniInfo.DK == OMPD_parallel &&
695          "Unexpected finalization stack state!");
696 
697   Instruction *PRegPreFiniTI = PRegPreFiniBB->getTerminator();
698 
699   InsertPointTy PreFiniIP(PRegPreFiniBB, PRegPreFiniTI->getIterator());
700   FiniCB(PreFiniIP);
701 
702   OI.EntryBB = PRegEntryBB;
703   OI.ExitBB = PRegExitBB;
704 
705   SmallPtrSet<BasicBlock *, 32> ParallelRegionBlockSet;
706   SmallVector<BasicBlock *, 32> Blocks;
707   OI.collectBlocks(ParallelRegionBlockSet, Blocks);
708 
709   // Ensure a single exit node for the outlined region by creating one.
710   // We might have multiple incoming edges to the exit now due to finalizations,
711   // e.g., cancel calls that cause the control flow to leave the region.
712   BasicBlock *PRegOutlinedExitBB = PRegExitBB;
713   PRegExitBB = SplitBlock(PRegExitBB, &*PRegExitBB->getFirstInsertionPt());
714   PRegOutlinedExitBB->setName("omp.par.outlined.exit");
715   Blocks.push_back(PRegOutlinedExitBB);
716 
717   CodeExtractorAnalysisCache CEAC(*OuterFn);
718   CodeExtractor Extractor(Blocks, /* DominatorTree */ nullptr,
719                           /* AggregateArgs */ false,
720                           /* BlockFrequencyInfo */ nullptr,
721                           /* BranchProbabilityInfo */ nullptr,
722                           /* AssumptionCache */ nullptr,
723                           /* AllowVarArgs */ true,
724                           /* AllowAlloca */ true,
725                           /* Suffix */ ".omp_par");
726 
727   // Find inputs to, outputs from the code region.
728   BasicBlock *CommonExit = nullptr;
729   SetVector<Value *> Inputs, Outputs, SinkingCands, HoistingCands;
730   Extractor.findAllocas(CEAC, SinkingCands, HoistingCands, CommonExit);
731   Extractor.findInputsOutputs(Inputs, Outputs, SinkingCands);
732 
733   LLVM_DEBUG(dbgs() << "Before privatization: " << *OuterFn << "\n");
734 
735   FunctionCallee TIDRTLFn =
736       getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_global_thread_num);
737 
738   auto PrivHelper = [&](Value &V) {
739     if (&V == TIDAddr || &V == ZeroAddr)
740       return;
741 
742     SetVector<Use *> Uses;
743     for (Use &U : V.uses())
744       if (auto *UserI = dyn_cast<Instruction>(U.getUser()))
745         if (ParallelRegionBlockSet.count(UserI->getParent()))
746           Uses.insert(&U);
747 
748     // __kmpc_fork_call expects extra arguments as pointers. If the input
749     // already has a pointer type, everything is fine. Otherwise, store the
750     // value onto stack and load it back inside the to-be-outlined region. This
751     // will ensure only the pointer will be passed to the function.
752     // FIXME: if there are more than 15 trailing arguments, they must be
753     // additionally packed in a struct.
754     Value *Inner = &V;
755     if (!V.getType()->isPointerTy()) {
756       IRBuilder<>::InsertPointGuard Guard(Builder);
757       LLVM_DEBUG(llvm::dbgs() << "Forwarding input as pointer: " << V << "\n");
758 
759       Builder.restoreIP(OuterAllocaIP);
760       Value *Ptr =
761           Builder.CreateAlloca(V.getType(), nullptr, V.getName() + ".reloaded");
762 
763       // Store to stack at end of the block that currently branches to the entry
764       // block of the to-be-outlined region.
765       Builder.SetInsertPoint(InsertBB,
766                              InsertBB->getTerminator()->getIterator());
767       Builder.CreateStore(&V, Ptr);
768 
769       // Load back next to allocations in the to-be-outlined region.
770       Builder.restoreIP(InnerAllocaIP);
771       Inner = Builder.CreateLoad(V.getType(), Ptr);
772     }
773 
774     Value *ReplacementValue = nullptr;
775     CallInst *CI = dyn_cast<CallInst>(&V);
776     if (CI && CI->getCalledFunction() == TIDRTLFn.getCallee()) {
777       ReplacementValue = PrivTID;
778     } else {
779       Builder.restoreIP(
780           PrivCB(InnerAllocaIP, Builder.saveIP(), V, *Inner, ReplacementValue));
781       assert(ReplacementValue &&
782              "Expected copy/create callback to set replacement value!");
783       if (ReplacementValue == &V)
784         return;
785     }
786 
787     for (Use *UPtr : Uses)
788       UPtr->set(ReplacementValue);
789   };
790 
791   // Reset the inner alloca insertion as it will be used for loading the values
792   // wrapped into pointers before passing them into the to-be-outlined region.
793   // Configure it to insert immediately after the fake use of zero address so
794   // that they are available in the generated body and so that the
795   // OpenMP-related values (thread ID and zero address pointers) remain leading
796   // in the argument list.
797   InnerAllocaIP = IRBuilder<>::InsertPoint(
798       ZeroAddrUse->getParent(), ZeroAddrUse->getNextNode()->getIterator());
799 
800   // Reset the outer alloca insertion point to the entry of the relevant block
801   // in case it was invalidated.
802   OuterAllocaIP = IRBuilder<>::InsertPoint(
803       OuterAllocaBlock, OuterAllocaBlock->getFirstInsertionPt());
804 
805   for (Value *Input : Inputs) {
806     LLVM_DEBUG(dbgs() << "Captured input: " << *Input << "\n");
807     PrivHelper(*Input);
808   }
809   LLVM_DEBUG({
810     for (Value *Output : Outputs)
811       LLVM_DEBUG(dbgs() << "Captured output: " << *Output << "\n");
812   });
813   assert(Outputs.empty() &&
814          "OpenMP outlining should not produce live-out values!");
815 
816   LLVM_DEBUG(dbgs() << "After  privatization: " << *OuterFn << "\n");
817   LLVM_DEBUG({
818     for (auto *BB : Blocks)
819       dbgs() << " PBR: " << BB->getName() << "\n";
820   });
821 
822   // Register the outlined info.
823   addOutlineInfo(std::move(OI));
824 
825   InsertPointTy AfterIP(UI->getParent(), UI->getParent()->end());
826   UI->eraseFromParent();
827 
828   return AfterIP;
829 }
830 
831 void OpenMPIRBuilder::emitFlush(const LocationDescription &Loc) {
832   // Build call void __kmpc_flush(ident_t *loc)
833   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc);
834   Value *Args[] = {getOrCreateIdent(SrcLocStr)};
835 
836   Builder.CreateCall(getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_flush), Args);
837 }
838 
839 void OpenMPIRBuilder::createFlush(const LocationDescription &Loc) {
840   if (!updateToLocation(Loc))
841     return;
842   emitFlush(Loc);
843 }
844 
845 void OpenMPIRBuilder::emitTaskwaitImpl(const LocationDescription &Loc) {
846   // Build call kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
847   // global_tid);
848   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc);
849   Value *Ident = getOrCreateIdent(SrcLocStr);
850   Value *Args[] = {Ident, getOrCreateThreadID(Ident)};
851 
852   // Ignore return result until untied tasks are supported.
853   Builder.CreateCall(getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_omp_taskwait),
854                      Args);
855 }
856 
857 void OpenMPIRBuilder::createTaskwait(const LocationDescription &Loc) {
858   if (!updateToLocation(Loc))
859     return;
860   emitTaskwaitImpl(Loc);
861 }
862 
863 void OpenMPIRBuilder::emitTaskyieldImpl(const LocationDescription &Loc) {
864   // Build call __kmpc_omp_taskyield(loc, thread_id, 0);
865   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc);
866   Value *Ident = getOrCreateIdent(SrcLocStr);
867   Constant *I32Null = ConstantInt::getNullValue(Int32);
868   Value *Args[] = {Ident, getOrCreateThreadID(Ident), I32Null};
869 
870   Builder.CreateCall(getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_omp_taskyield),
871                      Args);
872 }
873 
874 void OpenMPIRBuilder::createTaskyield(const LocationDescription &Loc) {
875   if (!updateToLocation(Loc))
876     return;
877   emitTaskyieldImpl(Loc);
878 }
879 
880 OpenMPIRBuilder::InsertPointTy
881 OpenMPIRBuilder::createMaster(const LocationDescription &Loc,
882                               BodyGenCallbackTy BodyGenCB,
883                               FinalizeCallbackTy FiniCB) {
884 
885   if (!updateToLocation(Loc))
886     return Loc.IP;
887 
888   Directive OMPD = Directive::OMPD_master;
889   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc);
890   Value *Ident = getOrCreateIdent(SrcLocStr);
891   Value *ThreadId = getOrCreateThreadID(Ident);
892   Value *Args[] = {Ident, ThreadId};
893 
894   Function *EntryRTLFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_master);
895   Instruction *EntryCall = Builder.CreateCall(EntryRTLFn, Args);
896 
897   Function *ExitRTLFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_end_master);
898   Instruction *ExitCall = Builder.CreateCall(ExitRTLFn, Args);
899 
900   return EmitOMPInlinedRegion(OMPD, EntryCall, ExitCall, BodyGenCB, FiniCB,
901                               /*Conditional*/ true, /*hasFinalize*/ true);
902 }
903 
904 OpenMPIRBuilder::InsertPointTy
905 OpenMPIRBuilder::createMasked(const LocationDescription &Loc,
906                               BodyGenCallbackTy BodyGenCB,
907                               FinalizeCallbackTy FiniCB, Value *Filter) {
908   if (!updateToLocation(Loc))
909     return Loc.IP;
910 
911   Directive OMPD = Directive::OMPD_masked;
912   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc);
913   Value *Ident = getOrCreateIdent(SrcLocStr);
914   Value *ThreadId = getOrCreateThreadID(Ident);
915   Value *Args[] = {Ident, ThreadId, Filter};
916   Value *ArgsEnd[] = {Ident, ThreadId};
917 
918   Function *EntryRTLFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_masked);
919   Instruction *EntryCall = Builder.CreateCall(EntryRTLFn, Args);
920 
921   Function *ExitRTLFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_end_masked);
922   Instruction *ExitCall = Builder.CreateCall(ExitRTLFn, ArgsEnd);
923 
924   return EmitOMPInlinedRegion(OMPD, EntryCall, ExitCall, BodyGenCB, FiniCB,
925                               /*Conditional*/ true, /*hasFinalize*/ true);
926 }
927 
928 CanonicalLoopInfo *OpenMPIRBuilder::createLoopSkeleton(
929     DebugLoc DL, Value *TripCount, Function *F, BasicBlock *PreInsertBefore,
930     BasicBlock *PostInsertBefore, const Twine &Name) {
931   Module *M = F->getParent();
932   LLVMContext &Ctx = M->getContext();
933   Type *IndVarTy = TripCount->getType();
934 
935   // Create the basic block structure.
936   BasicBlock *Preheader =
937       BasicBlock::Create(Ctx, "omp_" + Name + ".preheader", F, PreInsertBefore);
938   BasicBlock *Header =
939       BasicBlock::Create(Ctx, "omp_" + Name + ".header", F, PreInsertBefore);
940   BasicBlock *Cond =
941       BasicBlock::Create(Ctx, "omp_" + Name + ".cond", F, PreInsertBefore);
942   BasicBlock *Body =
943       BasicBlock::Create(Ctx, "omp_" + Name + ".body", F, PreInsertBefore);
944   BasicBlock *Latch =
945       BasicBlock::Create(Ctx, "omp_" + Name + ".inc", F, PostInsertBefore);
946   BasicBlock *Exit =
947       BasicBlock::Create(Ctx, "omp_" + Name + ".exit", F, PostInsertBefore);
948   BasicBlock *After =
949       BasicBlock::Create(Ctx, "omp_" + Name + ".after", F, PostInsertBefore);
950 
951   // Use specified DebugLoc for new instructions.
952   Builder.SetCurrentDebugLocation(DL);
953 
954   Builder.SetInsertPoint(Preheader);
955   Builder.CreateBr(Header);
956 
957   Builder.SetInsertPoint(Header);
958   PHINode *IndVarPHI = Builder.CreatePHI(IndVarTy, 2, "omp_" + Name + ".iv");
959   IndVarPHI->addIncoming(ConstantInt::get(IndVarTy, 0), Preheader);
960   Builder.CreateBr(Cond);
961 
962   Builder.SetInsertPoint(Cond);
963   Value *Cmp =
964       Builder.CreateICmpULT(IndVarPHI, TripCount, "omp_" + Name + ".cmp");
965   Builder.CreateCondBr(Cmp, Body, Exit);
966 
967   Builder.SetInsertPoint(Body);
968   Builder.CreateBr(Latch);
969 
970   Builder.SetInsertPoint(Latch);
971   Value *Next = Builder.CreateAdd(IndVarPHI, ConstantInt::get(IndVarTy, 1),
972                                   "omp_" + Name + ".next", /*HasNUW=*/true);
973   Builder.CreateBr(Header);
974   IndVarPHI->addIncoming(Next, Latch);
975 
976   Builder.SetInsertPoint(Exit);
977   Builder.CreateBr(After);
978 
979   // Remember and return the canonical control flow.
980   LoopInfos.emplace_front();
981   CanonicalLoopInfo *CL = &LoopInfos.front();
982 
983   CL->Preheader = Preheader;
984   CL->Header = Header;
985   CL->Cond = Cond;
986   CL->Body = Body;
987   CL->Latch = Latch;
988   CL->Exit = Exit;
989   CL->After = After;
990 
991   CL->IsValid = true;
992 
993 #ifndef NDEBUG
994   CL->assertOK();
995 #endif
996   return CL;
997 }
998 
999 CanonicalLoopInfo *
1000 OpenMPIRBuilder::createCanonicalLoop(const LocationDescription &Loc,
1001                                      LoopBodyGenCallbackTy BodyGenCB,
1002                                      Value *TripCount, const Twine &Name) {
1003   BasicBlock *BB = Loc.IP.getBlock();
1004   BasicBlock *NextBB = BB->getNextNode();
1005 
1006   CanonicalLoopInfo *CL = createLoopSkeleton(Loc.DL, TripCount, BB->getParent(),
1007                                              NextBB, NextBB, Name);
1008   BasicBlock *After = CL->getAfter();
1009 
1010   // If location is not set, don't connect the loop.
1011   if (updateToLocation(Loc)) {
1012     // Split the loop at the insertion point: Branch to the preheader and move
1013     // every following instruction to after the loop (the After BB). Also, the
1014     // new successor is the loop's after block.
1015     Builder.CreateBr(CL->Preheader);
1016     After->getInstList().splice(After->begin(), BB->getInstList(),
1017                                 Builder.GetInsertPoint(), BB->end());
1018     After->replaceSuccessorsPhiUsesWith(BB, After);
1019   }
1020 
1021   // Emit the body content. We do it after connecting the loop to the CFG to
1022   // avoid that the callback encounters degenerate BBs.
1023   BodyGenCB(CL->getBodyIP(), CL->getIndVar());
1024 
1025 #ifndef NDEBUG
1026   CL->assertOK();
1027 #endif
1028   return CL;
1029 }
1030 
1031 CanonicalLoopInfo *OpenMPIRBuilder::createCanonicalLoop(
1032     const LocationDescription &Loc, LoopBodyGenCallbackTy BodyGenCB,
1033     Value *Start, Value *Stop, Value *Step, bool IsSigned, bool InclusiveStop,
1034     InsertPointTy ComputeIP, const Twine &Name) {
1035 
1036   // Consider the following difficulties (assuming 8-bit signed integers):
1037   //  * Adding \p Step to the loop counter which passes \p Stop may overflow:
1038   //      DO I = 1, 100, 50
1039   ///  * A \p Step of INT_MIN cannot not be normalized to a positive direction:
1040   //      DO I = 100, 0, -128
1041 
1042   // Start, Stop and Step must be of the same integer type.
1043   auto *IndVarTy = cast<IntegerType>(Start->getType());
1044   assert(IndVarTy == Stop->getType() && "Stop type mismatch");
1045   assert(IndVarTy == Step->getType() && "Step type mismatch");
1046 
1047   LocationDescription ComputeLoc =
1048       ComputeIP.isSet() ? LocationDescription(ComputeIP, Loc.DL) : Loc;
1049   updateToLocation(ComputeLoc);
1050 
1051   ConstantInt *Zero = ConstantInt::get(IndVarTy, 0);
1052   ConstantInt *One = ConstantInt::get(IndVarTy, 1);
1053 
1054   // Like Step, but always positive.
1055   Value *Incr = Step;
1056 
1057   // Distance between Start and Stop; always positive.
1058   Value *Span;
1059 
1060   // Condition whether there are no iterations are executed at all, e.g. because
1061   // UB < LB.
1062   Value *ZeroCmp;
1063 
1064   if (IsSigned) {
1065     // Ensure that increment is positive. If not, negate and invert LB and UB.
1066     Value *IsNeg = Builder.CreateICmpSLT(Step, Zero);
1067     Incr = Builder.CreateSelect(IsNeg, Builder.CreateNeg(Step), Step);
1068     Value *LB = Builder.CreateSelect(IsNeg, Stop, Start);
1069     Value *UB = Builder.CreateSelect(IsNeg, Start, Stop);
1070     Span = Builder.CreateSub(UB, LB, "", false, true);
1071     ZeroCmp = Builder.CreateICmp(
1072         InclusiveStop ? CmpInst::ICMP_SLT : CmpInst::ICMP_SLE, UB, LB);
1073   } else {
1074     Span = Builder.CreateSub(Stop, Start, "", true);
1075     ZeroCmp = Builder.CreateICmp(
1076         InclusiveStop ? CmpInst::ICMP_ULT : CmpInst::ICMP_ULE, Stop, Start);
1077   }
1078 
1079   Value *CountIfLooping;
1080   if (InclusiveStop) {
1081     CountIfLooping = Builder.CreateAdd(Builder.CreateUDiv(Span, Incr), One);
1082   } else {
1083     // Avoid incrementing past stop since it could overflow.
1084     Value *CountIfTwo = Builder.CreateAdd(
1085         Builder.CreateUDiv(Builder.CreateSub(Span, One), Incr), One);
1086     Value *OneCmp = Builder.CreateICmp(
1087         InclusiveStop ? CmpInst::ICMP_ULT : CmpInst::ICMP_ULE, Span, Incr);
1088     CountIfLooping = Builder.CreateSelect(OneCmp, One, CountIfTwo);
1089   }
1090   Value *TripCount = Builder.CreateSelect(ZeroCmp, Zero, CountIfLooping,
1091                                           "omp_" + Name + ".tripcount");
1092 
1093   auto BodyGen = [=](InsertPointTy CodeGenIP, Value *IV) {
1094     Builder.restoreIP(CodeGenIP);
1095     Value *Span = Builder.CreateMul(IV, Step);
1096     Value *IndVar = Builder.CreateAdd(Span, Start);
1097     BodyGenCB(Builder.saveIP(), IndVar);
1098   };
1099   LocationDescription LoopLoc = ComputeIP.isSet() ? Loc.IP : Builder.saveIP();
1100   return createCanonicalLoop(LoopLoc, BodyGen, TripCount, Name);
1101 }
1102 
1103 // Returns an LLVM function to call for initializing loop bounds using OpenMP
1104 // static scheduling depending on `type`. Only i32 and i64 are supported by the
1105 // runtime. Always interpret integers as unsigned similarly to
1106 // CanonicalLoopInfo.
1107 static FunctionCallee getKmpcForStaticInitForType(Type *Ty, Module &M,
1108                                                   OpenMPIRBuilder &OMPBuilder) {
1109   unsigned Bitwidth = Ty->getIntegerBitWidth();
1110   if (Bitwidth == 32)
1111     return OMPBuilder.getOrCreateRuntimeFunction(
1112         M, omp::RuntimeFunction::OMPRTL___kmpc_for_static_init_4u);
1113   if (Bitwidth == 64)
1114     return OMPBuilder.getOrCreateRuntimeFunction(
1115         M, omp::RuntimeFunction::OMPRTL___kmpc_for_static_init_8u);
1116   llvm_unreachable("unknown OpenMP loop iterator bitwidth");
1117 }
1118 
1119 // Sets the number of loop iterations to the given value. This value must be
1120 // valid in the condition block (i.e., defined in the preheader) and is
1121 // interpreted as an unsigned integer.
1122 void setCanonicalLoopTripCount(CanonicalLoopInfo *CLI, Value *TripCount) {
1123   Instruction *CmpI = &CLI->getCond()->front();
1124   assert(isa<CmpInst>(CmpI) && "First inst must compare IV with TripCount");
1125   CmpI->setOperand(1, TripCount);
1126   CLI->assertOK();
1127 }
1128 
1129 CanonicalLoopInfo *OpenMPIRBuilder::createStaticWorkshareLoop(
1130     const LocationDescription &Loc, CanonicalLoopInfo *CLI,
1131     InsertPointTy AllocaIP, bool NeedsBarrier, Value *Chunk) {
1132   // Set up the source location value for OpenMP runtime.
1133   if (!updateToLocation(Loc))
1134     return nullptr;
1135 
1136   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc);
1137   Value *SrcLoc = getOrCreateIdent(SrcLocStr);
1138 
1139   // Declare useful OpenMP runtime functions.
1140   Value *IV = CLI->getIndVar();
1141   Type *IVTy = IV->getType();
1142   FunctionCallee StaticInit = getKmpcForStaticInitForType(IVTy, M, *this);
1143   FunctionCallee StaticFini =
1144       getOrCreateRuntimeFunction(M, omp::OMPRTL___kmpc_for_static_fini);
1145 
1146   // Allocate space for computed loop bounds as expected by the "init" function.
1147   Builder.restoreIP(AllocaIP);
1148   Type *I32Type = Type::getInt32Ty(M.getContext());
1149   Value *PLastIter = Builder.CreateAlloca(I32Type, nullptr, "p.lastiter");
1150   Value *PLowerBound = Builder.CreateAlloca(IVTy, nullptr, "p.lowerbound");
1151   Value *PUpperBound = Builder.CreateAlloca(IVTy, nullptr, "p.upperbound");
1152   Value *PStride = Builder.CreateAlloca(IVTy, nullptr, "p.stride");
1153 
1154   // At the end of the preheader, prepare for calling the "init" function by
1155   // storing the current loop bounds into the allocated space. A canonical loop
1156   // always iterates from 0 to trip-count with step 1. Note that "init" expects
1157   // and produces an inclusive upper bound.
1158   Builder.SetInsertPoint(CLI->getPreheader()->getTerminator());
1159   Constant *Zero = ConstantInt::get(IVTy, 0);
1160   Constant *One = ConstantInt::get(IVTy, 1);
1161   Builder.CreateStore(Zero, PLowerBound);
1162   Value *UpperBound = Builder.CreateSub(CLI->getTripCount(), One);
1163   Builder.CreateStore(UpperBound, PUpperBound);
1164   Builder.CreateStore(One, PStride);
1165 
1166   if (!Chunk)
1167     Chunk = One;
1168 
1169   Value *ThreadNum = getOrCreateThreadID(SrcLoc);
1170 
1171   Constant *SchedulingType =
1172       ConstantInt::get(I32Type, static_cast<int>(OMPScheduleType::Static));
1173 
1174   // Call the "init" function and update the trip count of the loop with the
1175   // value it produced.
1176   Builder.CreateCall(StaticInit,
1177                      {SrcLoc, ThreadNum, SchedulingType, PLastIter, PLowerBound,
1178                       PUpperBound, PStride, One, Chunk});
1179   Value *LowerBound = Builder.CreateLoad(IVTy, PLowerBound);
1180   Value *InclusiveUpperBound = Builder.CreateLoad(IVTy, PUpperBound);
1181   Value *TripCountMinusOne = Builder.CreateSub(InclusiveUpperBound, LowerBound);
1182   Value *TripCount = Builder.CreateAdd(TripCountMinusOne, One);
1183   setCanonicalLoopTripCount(CLI, TripCount);
1184 
1185   // Update all uses of the induction variable except the one in the condition
1186   // block that compares it with the actual upper bound, and the increment in
1187   // the latch block.
1188   // TODO: this can eventually move to CanonicalLoopInfo or to a new
1189   // CanonicalLoopInfoUpdater interface.
1190   Builder.SetInsertPoint(CLI->getBody(), CLI->getBody()->getFirstInsertionPt());
1191   Value *UpdatedIV = Builder.CreateAdd(IV, LowerBound);
1192   IV->replaceUsesWithIf(UpdatedIV, [&](Use &U) {
1193     auto *Instr = dyn_cast<Instruction>(U.getUser());
1194     return !Instr ||
1195            (Instr->getParent() != CLI->getCond() &&
1196             Instr->getParent() != CLI->getLatch() && Instr != UpdatedIV);
1197   });
1198 
1199   // In the "exit" block, call the "fini" function.
1200   Builder.SetInsertPoint(CLI->getExit(),
1201                          CLI->getExit()->getTerminator()->getIterator());
1202   Builder.CreateCall(StaticFini, {SrcLoc, ThreadNum});
1203 
1204   // Add the barrier if requested.
1205   if (NeedsBarrier)
1206     createBarrier(LocationDescription(Builder.saveIP(), Loc.DL),
1207                   omp::Directive::OMPD_for, /* ForceSimpleCall */ false,
1208                   /* CheckCancelFlag */ false);
1209 
1210   CLI->assertOK();
1211   return CLI;
1212 }
1213 
1214 CanonicalLoopInfo *OpenMPIRBuilder::createWorkshareLoop(
1215     const LocationDescription &Loc, CanonicalLoopInfo *CLI,
1216     InsertPointTy AllocaIP, bool NeedsBarrier) {
1217   // Currently only supports static schedules.
1218   return createStaticWorkshareLoop(Loc, CLI, AllocaIP, NeedsBarrier);
1219 }
1220 
1221 /// Returns an LLVM function to call for initializing loop bounds using OpenMP
1222 /// dynamic scheduling depending on `type`. Only i32 and i64 are supported by
1223 /// the runtime. Always interpret integers as unsigned similarly to
1224 /// CanonicalLoopInfo.
1225 static FunctionCallee
1226 getKmpcForDynamicInitForType(Type *Ty, Module &M, OpenMPIRBuilder &OMPBuilder) {
1227   unsigned Bitwidth = Ty->getIntegerBitWidth();
1228   if (Bitwidth == 32)
1229     return OMPBuilder.getOrCreateRuntimeFunction(
1230         M, omp::RuntimeFunction::OMPRTL___kmpc_dispatch_init_4u);
1231   if (Bitwidth == 64)
1232     return OMPBuilder.getOrCreateRuntimeFunction(
1233         M, omp::RuntimeFunction::OMPRTL___kmpc_dispatch_init_8u);
1234   llvm_unreachable("unknown OpenMP loop iterator bitwidth");
1235 }
1236 
1237 /// Returns an LLVM function to call for updating the next loop using OpenMP
1238 /// dynamic scheduling depending on `type`. Only i32 and i64 are supported by
1239 /// the runtime. Always interpret integers as unsigned similarly to
1240 /// CanonicalLoopInfo.
1241 static FunctionCallee
1242 getKmpcForDynamicNextForType(Type *Ty, Module &M, OpenMPIRBuilder &OMPBuilder) {
1243   unsigned Bitwidth = Ty->getIntegerBitWidth();
1244   if (Bitwidth == 32)
1245     return OMPBuilder.getOrCreateRuntimeFunction(
1246         M, omp::RuntimeFunction::OMPRTL___kmpc_dispatch_next_4u);
1247   if (Bitwidth == 64)
1248     return OMPBuilder.getOrCreateRuntimeFunction(
1249         M, omp::RuntimeFunction::OMPRTL___kmpc_dispatch_next_8u);
1250   llvm_unreachable("unknown OpenMP loop iterator bitwidth");
1251 }
1252 
1253 OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::createDynamicWorkshareLoop(
1254     const LocationDescription &Loc, CanonicalLoopInfo *CLI,
1255     InsertPointTy AllocaIP, bool NeedsBarrier, Value *Chunk) {
1256   // Set up the source location value for OpenMP runtime.
1257   Builder.SetCurrentDebugLocation(Loc.DL);
1258 
1259   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc);
1260   Value *SrcLoc = getOrCreateIdent(SrcLocStr);
1261 
1262   // Declare useful OpenMP runtime functions.
1263   Value *IV = CLI->getIndVar();
1264   Type *IVTy = IV->getType();
1265   FunctionCallee DynamicInit = getKmpcForDynamicInitForType(IVTy, M, *this);
1266   FunctionCallee DynamicNext = getKmpcForDynamicNextForType(IVTy, M, *this);
1267 
1268   // Allocate space for computed loop bounds as expected by the "init" function.
1269   Builder.restoreIP(AllocaIP);
1270   Type *I32Type = Type::getInt32Ty(M.getContext());
1271   Value *PLastIter = Builder.CreateAlloca(I32Type, nullptr, "p.lastiter");
1272   Value *PLowerBound = Builder.CreateAlloca(IVTy, nullptr, "p.lowerbound");
1273   Value *PUpperBound = Builder.CreateAlloca(IVTy, nullptr, "p.upperbound");
1274   Value *PStride = Builder.CreateAlloca(IVTy, nullptr, "p.stride");
1275 
1276   // At the end of the preheader, prepare for calling the "init" function by
1277   // storing the current loop bounds into the allocated space. A canonical loop
1278   // always iterates from 0 to trip-count with step 1. Note that "init" expects
1279   // and produces an inclusive upper bound.
1280   BasicBlock *PreHeader = CLI->getPreheader();
1281   Builder.SetInsertPoint(PreHeader->getTerminator());
1282   Constant *One = ConstantInt::get(IVTy, 1);
1283   Builder.CreateStore(One, PLowerBound);
1284   Value *UpperBound = CLI->getTripCount();
1285   Builder.CreateStore(UpperBound, PUpperBound);
1286   Builder.CreateStore(One, PStride);
1287 
1288   BasicBlock *Header = CLI->getHeader();
1289   BasicBlock *Exit = CLI->getExit();
1290   BasicBlock *Cond = CLI->getCond();
1291   InsertPointTy AfterIP = CLI->getAfterIP();
1292 
1293   // The CLI will be "broken" in the code below, as the loop is no longer
1294   // a valid canonical loop.
1295 
1296   if (!Chunk)
1297     Chunk = One;
1298 
1299   Value *ThreadNum = getOrCreateThreadID(SrcLoc);
1300 
1301   OMPScheduleType DynamicSchedType =
1302       OMPScheduleType::DynamicChunked | OMPScheduleType::ModifierNonmonotonic;
1303   Constant *SchedulingType =
1304       ConstantInt::get(I32Type, static_cast<int>(DynamicSchedType));
1305 
1306   // Call the "init" function.
1307   Builder.CreateCall(DynamicInit,
1308                      {SrcLoc, ThreadNum, SchedulingType, /* LowerBound */ One,
1309                       UpperBound, /* step */ One, Chunk});
1310 
1311   // An outer loop around the existing one.
1312   BasicBlock *OuterCond = BasicBlock::Create(
1313       PreHeader->getContext(), Twine(PreHeader->getName()) + ".outer.cond",
1314       PreHeader->getParent());
1315   // This needs to be 32-bit always, so can't use the IVTy Zero above.
1316   Builder.SetInsertPoint(OuterCond, OuterCond->getFirstInsertionPt());
1317   Value *Res =
1318       Builder.CreateCall(DynamicNext, {SrcLoc, ThreadNum, PLastIter,
1319                                        PLowerBound, PUpperBound, PStride});
1320   Constant *Zero32 = ConstantInt::get(I32Type, 0);
1321   Value *MoreWork = Builder.CreateCmp(CmpInst::ICMP_NE, Res, Zero32);
1322   Value *LowerBound =
1323       Builder.CreateSub(Builder.CreateLoad(IVTy, PLowerBound), One, "lb");
1324   Builder.CreateCondBr(MoreWork, Header, Exit);
1325 
1326   // Change PHI-node in loop header to use outer cond rather than preheader,
1327   // and set IV to the LowerBound.
1328   Instruction *Phi = &Header->front();
1329   auto *PI = cast<PHINode>(Phi);
1330   PI->setIncomingBlock(0, OuterCond);
1331   PI->setIncomingValue(0, LowerBound);
1332 
1333   // Then set the pre-header to jump to the OuterCond
1334   Instruction *Term = PreHeader->getTerminator();
1335   auto *Br = cast<BranchInst>(Term);
1336   Br->setSuccessor(0, OuterCond);
1337 
1338   // Modify the inner condition:
1339   // * Use the UpperBound returned from the DynamicNext call.
1340   // * jump to the loop outer loop when done with one of the inner loops.
1341   Builder.SetInsertPoint(Cond, Cond->getFirstInsertionPt());
1342   UpperBound = Builder.CreateLoad(IVTy, PUpperBound, "ub");
1343   Instruction *Comp = &*Builder.GetInsertPoint();
1344   auto *CI = cast<CmpInst>(Comp);
1345   CI->setOperand(1, UpperBound);
1346   // Redirect the inner exit to branch to outer condition.
1347   Instruction *Branch = &Cond->back();
1348   auto *BI = cast<BranchInst>(Branch);
1349   assert(BI->getSuccessor(1) == Exit);
1350   BI->setSuccessor(1, OuterCond);
1351 
1352   // Add the barrier if requested.
1353   if (NeedsBarrier) {
1354     Builder.SetInsertPoint(&Exit->back());
1355     createBarrier(LocationDescription(Builder.saveIP(), Loc.DL),
1356                   omp::Directive::OMPD_for, /* ForceSimpleCall */ false,
1357                   /* CheckCancelFlag */ false);
1358   }
1359 
1360   return AfterIP;
1361 }
1362 
1363 /// Make \p Source branch to \p Target.
1364 ///
1365 /// Handles two situations:
1366 /// * \p Source already has an unconditional branch.
1367 /// * \p Source is a degenerate block (no terminator because the BB is
1368 ///             the current head of the IR construction).
1369 static void redirectTo(BasicBlock *Source, BasicBlock *Target, DebugLoc DL) {
1370   if (Instruction *Term = Source->getTerminator()) {
1371     auto *Br = cast<BranchInst>(Term);
1372     assert(!Br->isConditional() &&
1373            "BB's terminator must be an unconditional branch (or degenerate)");
1374     BasicBlock *Succ = Br->getSuccessor(0);
1375     Succ->removePredecessor(Source, /*KeepOneInputPHIs=*/true);
1376     Br->setSuccessor(0, Target);
1377     return;
1378   }
1379 
1380   auto *NewBr = BranchInst::Create(Target, Source);
1381   NewBr->setDebugLoc(DL);
1382 }
1383 
1384 /// Redirect all edges that branch to \p OldTarget to \p NewTarget. That is,
1385 /// after this \p OldTarget will be orphaned.
1386 static void redirectAllPredecessorsTo(BasicBlock *OldTarget,
1387                                       BasicBlock *NewTarget, DebugLoc DL) {
1388   for (BasicBlock *Pred : make_early_inc_range(predecessors(OldTarget)))
1389     redirectTo(Pred, NewTarget, DL);
1390 }
1391 
1392 /// Determine which blocks in \p BBs are reachable from outside and remove the
1393 /// ones that are not reachable from the function.
1394 static void removeUnusedBlocksFromParent(ArrayRef<BasicBlock *> BBs) {
1395   SmallPtrSet<BasicBlock *, 6> BBsToErase{BBs.begin(), BBs.end()};
1396   auto HasRemainingUses = [&BBsToErase](BasicBlock *BB) {
1397     for (Use &U : BB->uses()) {
1398       auto *UseInst = dyn_cast<Instruction>(U.getUser());
1399       if (!UseInst)
1400         continue;
1401       if (BBsToErase.count(UseInst->getParent()))
1402         continue;
1403       return true;
1404     }
1405     return false;
1406   };
1407 
1408   while (true) {
1409     bool Changed = false;
1410     for (BasicBlock *BB : make_early_inc_range(BBsToErase)) {
1411       if (HasRemainingUses(BB)) {
1412         BBsToErase.erase(BB);
1413         Changed = true;
1414       }
1415     }
1416     if (!Changed)
1417       break;
1418   }
1419 
1420   SmallVector<BasicBlock *, 7> BBVec(BBsToErase.begin(), BBsToErase.end());
1421   DeleteDeadBlocks(BBVec);
1422 }
1423 
1424 CanonicalLoopInfo *
1425 OpenMPIRBuilder::collapseLoops(DebugLoc DL, ArrayRef<CanonicalLoopInfo *> Loops,
1426                                InsertPointTy ComputeIP) {
1427   assert(Loops.size() >= 1 && "At least one loop required");
1428   size_t NumLoops = Loops.size();
1429 
1430   // Nothing to do if there is already just one loop.
1431   if (NumLoops == 1)
1432     return Loops.front();
1433 
1434   CanonicalLoopInfo *Outermost = Loops.front();
1435   CanonicalLoopInfo *Innermost = Loops.back();
1436   BasicBlock *OrigPreheader = Outermost->getPreheader();
1437   BasicBlock *OrigAfter = Outermost->getAfter();
1438   Function *F = OrigPreheader->getParent();
1439 
1440   // Setup the IRBuilder for inserting the trip count computation.
1441   Builder.SetCurrentDebugLocation(DL);
1442   if (ComputeIP.isSet())
1443     Builder.restoreIP(ComputeIP);
1444   else
1445     Builder.restoreIP(Outermost->getPreheaderIP());
1446 
1447   // Derive the collapsed' loop trip count.
1448   // TODO: Find common/largest indvar type.
1449   Value *CollapsedTripCount = nullptr;
1450   for (CanonicalLoopInfo *L : Loops) {
1451     Value *OrigTripCount = L->getTripCount();
1452     if (!CollapsedTripCount) {
1453       CollapsedTripCount = OrigTripCount;
1454       continue;
1455     }
1456 
1457     // TODO: Enable UndefinedSanitizer to diagnose an overflow here.
1458     CollapsedTripCount = Builder.CreateMul(CollapsedTripCount, OrigTripCount,
1459                                            {}, /*HasNUW=*/true);
1460   }
1461 
1462   // Create the collapsed loop control flow.
1463   CanonicalLoopInfo *Result =
1464       createLoopSkeleton(DL, CollapsedTripCount, F,
1465                          OrigPreheader->getNextNode(), OrigAfter, "collapsed");
1466 
1467   // Build the collapsed loop body code.
1468   // Start with deriving the input loop induction variables from the collapsed
1469   // one, using a divmod scheme. To preserve the original loops' order, the
1470   // innermost loop use the least significant bits.
1471   Builder.restoreIP(Result->getBodyIP());
1472 
1473   Value *Leftover = Result->getIndVar();
1474   SmallVector<Value *> NewIndVars;
1475   NewIndVars.set_size(NumLoops);
1476   for (int i = NumLoops - 1; i >= 1; --i) {
1477     Value *OrigTripCount = Loops[i]->getTripCount();
1478 
1479     Value *NewIndVar = Builder.CreateURem(Leftover, OrigTripCount);
1480     NewIndVars[i] = NewIndVar;
1481 
1482     Leftover = Builder.CreateUDiv(Leftover, OrigTripCount);
1483   }
1484   // Outermost loop gets all the remaining bits.
1485   NewIndVars[0] = Leftover;
1486 
1487   // Construct the loop body control flow.
1488   // We progressively construct the branch structure following in direction of
1489   // the control flow, from the leading in-between code, the loop nest body, the
1490   // trailing in-between code, and rejoining the collapsed loop's latch.
1491   // ContinueBlock and ContinuePred keep track of the source(s) of next edge. If
1492   // the ContinueBlock is set, continue with that block. If ContinuePred, use
1493   // its predecessors as sources.
1494   BasicBlock *ContinueBlock = Result->getBody();
1495   BasicBlock *ContinuePred = nullptr;
1496   auto ContinueWith = [&ContinueBlock, &ContinuePred, DL](BasicBlock *Dest,
1497                                                           BasicBlock *NextSrc) {
1498     if (ContinueBlock)
1499       redirectTo(ContinueBlock, Dest, DL);
1500     else
1501       redirectAllPredecessorsTo(ContinuePred, Dest, DL);
1502 
1503     ContinueBlock = nullptr;
1504     ContinuePred = NextSrc;
1505   };
1506 
1507   // The code before the nested loop of each level.
1508   // Because we are sinking it into the nest, it will be executed more often
1509   // that the original loop. More sophisticated schemes could keep track of what
1510   // the in-between code is and instantiate it only once per thread.
1511   for (size_t i = 0; i < NumLoops - 1; ++i)
1512     ContinueWith(Loops[i]->getBody(), Loops[i + 1]->getHeader());
1513 
1514   // Connect the loop nest body.
1515   ContinueWith(Innermost->getBody(), Innermost->getLatch());
1516 
1517   // The code after the nested loop at each level.
1518   for (size_t i = NumLoops - 1; i > 0; --i)
1519     ContinueWith(Loops[i]->getAfter(), Loops[i - 1]->getLatch());
1520 
1521   // Connect the finished loop to the collapsed loop latch.
1522   ContinueWith(Result->getLatch(), nullptr);
1523 
1524   // Replace the input loops with the new collapsed loop.
1525   redirectTo(Outermost->getPreheader(), Result->getPreheader(), DL);
1526   redirectTo(Result->getAfter(), Outermost->getAfter(), DL);
1527 
1528   // Replace the input loop indvars with the derived ones.
1529   for (size_t i = 0; i < NumLoops; ++i)
1530     Loops[i]->getIndVar()->replaceAllUsesWith(NewIndVars[i]);
1531 
1532   // Remove unused parts of the input loops.
1533   SmallVector<BasicBlock *, 12> OldControlBBs;
1534   OldControlBBs.reserve(6 * Loops.size());
1535   for (CanonicalLoopInfo *Loop : Loops)
1536     Loop->collectControlBlocks(OldControlBBs);
1537   removeUnusedBlocksFromParent(OldControlBBs);
1538 
1539 #ifndef NDEBUG
1540   Result->assertOK();
1541 #endif
1542   return Result;
1543 }
1544 
1545 std::vector<CanonicalLoopInfo *>
1546 OpenMPIRBuilder::tileLoops(DebugLoc DL, ArrayRef<CanonicalLoopInfo *> Loops,
1547                            ArrayRef<Value *> TileSizes) {
1548   assert(TileSizes.size() == Loops.size() &&
1549          "Must pass as many tile sizes as there are loops");
1550   int NumLoops = Loops.size();
1551   assert(NumLoops >= 1 && "At least one loop to tile required");
1552 
1553   CanonicalLoopInfo *OutermostLoop = Loops.front();
1554   CanonicalLoopInfo *InnermostLoop = Loops.back();
1555   Function *F = OutermostLoop->getBody()->getParent();
1556   BasicBlock *InnerEnter = InnermostLoop->getBody();
1557   BasicBlock *InnerLatch = InnermostLoop->getLatch();
1558 
1559   // Collect original trip counts and induction variable to be accessible by
1560   // index. Also, the structure of the original loops is not preserved during
1561   // the construction of the tiled loops, so do it before we scavenge the BBs of
1562   // any original CanonicalLoopInfo.
1563   SmallVector<Value *, 4> OrigTripCounts, OrigIndVars;
1564   for (CanonicalLoopInfo *L : Loops) {
1565     OrigTripCounts.push_back(L->getTripCount());
1566     OrigIndVars.push_back(L->getIndVar());
1567   }
1568 
1569   // Collect the code between loop headers. These may contain SSA definitions
1570   // that are used in the loop nest body. To be usable with in the innermost
1571   // body, these BasicBlocks will be sunk into the loop nest body. That is,
1572   // these instructions may be executed more often than before the tiling.
1573   // TODO: It would be sufficient to only sink them into body of the
1574   // corresponding tile loop.
1575   SmallVector<std::pair<BasicBlock *, BasicBlock *>, 4> InbetweenCode;
1576   for (int i = 0; i < NumLoops - 1; ++i) {
1577     CanonicalLoopInfo *Surrounding = Loops[i];
1578     CanonicalLoopInfo *Nested = Loops[i + 1];
1579 
1580     BasicBlock *EnterBB = Surrounding->getBody();
1581     BasicBlock *ExitBB = Nested->getHeader();
1582     InbetweenCode.emplace_back(EnterBB, ExitBB);
1583   }
1584 
1585   // Compute the trip counts of the floor loops.
1586   Builder.SetCurrentDebugLocation(DL);
1587   Builder.restoreIP(OutermostLoop->getPreheaderIP());
1588   SmallVector<Value *, 4> FloorCount, FloorRems;
1589   for (int i = 0; i < NumLoops; ++i) {
1590     Value *TileSize = TileSizes[i];
1591     Value *OrigTripCount = OrigTripCounts[i];
1592     Type *IVType = OrigTripCount->getType();
1593 
1594     Value *FloorTripCount = Builder.CreateUDiv(OrigTripCount, TileSize);
1595     Value *FloorTripRem = Builder.CreateURem(OrigTripCount, TileSize);
1596 
1597     // 0 if tripcount divides the tilesize, 1 otherwise.
1598     // 1 means we need an additional iteration for a partial tile.
1599     //
1600     // Unfortunately we cannot just use the roundup-formula
1601     //   (tripcount + tilesize - 1)/tilesize
1602     // because the summation might overflow. We do not want introduce undefined
1603     // behavior when the untiled loop nest did not.
1604     Value *FloorTripOverflow =
1605         Builder.CreateICmpNE(FloorTripRem, ConstantInt::get(IVType, 0));
1606 
1607     FloorTripOverflow = Builder.CreateZExt(FloorTripOverflow, IVType);
1608     FloorTripCount =
1609         Builder.CreateAdd(FloorTripCount, FloorTripOverflow,
1610                           "omp_floor" + Twine(i) + ".tripcount", true);
1611 
1612     // Remember some values for later use.
1613     FloorCount.push_back(FloorTripCount);
1614     FloorRems.push_back(FloorTripRem);
1615   }
1616 
1617   // Generate the new loop nest, from the outermost to the innermost.
1618   std::vector<CanonicalLoopInfo *> Result;
1619   Result.reserve(NumLoops * 2);
1620 
1621   // The basic block of the surrounding loop that enters the nest generated
1622   // loop.
1623   BasicBlock *Enter = OutermostLoop->getPreheader();
1624 
1625   // The basic block of the surrounding loop where the inner code should
1626   // continue.
1627   BasicBlock *Continue = OutermostLoop->getAfter();
1628 
1629   // Where the next loop basic block should be inserted.
1630   BasicBlock *OutroInsertBefore = InnermostLoop->getExit();
1631 
1632   auto EmbeddNewLoop =
1633       [this, DL, F, InnerEnter, &Enter, &Continue, &OutroInsertBefore](
1634           Value *TripCount, const Twine &Name) -> CanonicalLoopInfo * {
1635     CanonicalLoopInfo *EmbeddedLoop = createLoopSkeleton(
1636         DL, TripCount, F, InnerEnter, OutroInsertBefore, Name);
1637     redirectTo(Enter, EmbeddedLoop->getPreheader(), DL);
1638     redirectTo(EmbeddedLoop->getAfter(), Continue, DL);
1639 
1640     // Setup the position where the next embedded loop connects to this loop.
1641     Enter = EmbeddedLoop->getBody();
1642     Continue = EmbeddedLoop->getLatch();
1643     OutroInsertBefore = EmbeddedLoop->getLatch();
1644     return EmbeddedLoop;
1645   };
1646 
1647   auto EmbeddNewLoops = [&Result, &EmbeddNewLoop](ArrayRef<Value *> TripCounts,
1648                                                   const Twine &NameBase) {
1649     for (auto P : enumerate(TripCounts)) {
1650       CanonicalLoopInfo *EmbeddedLoop =
1651           EmbeddNewLoop(P.value(), NameBase + Twine(P.index()));
1652       Result.push_back(EmbeddedLoop);
1653     }
1654   };
1655 
1656   EmbeddNewLoops(FloorCount, "floor");
1657 
1658   // Within the innermost floor loop, emit the code that computes the tile
1659   // sizes.
1660   Builder.SetInsertPoint(Enter->getTerminator());
1661   SmallVector<Value *, 4> TileCounts;
1662   for (int i = 0; i < NumLoops; ++i) {
1663     CanonicalLoopInfo *FloorLoop = Result[i];
1664     Value *TileSize = TileSizes[i];
1665 
1666     Value *FloorIsEpilogue =
1667         Builder.CreateICmpEQ(FloorLoop->getIndVar(), FloorCount[i]);
1668     Value *TileTripCount =
1669         Builder.CreateSelect(FloorIsEpilogue, FloorRems[i], TileSize);
1670 
1671     TileCounts.push_back(TileTripCount);
1672   }
1673 
1674   // Create the tile loops.
1675   EmbeddNewLoops(TileCounts, "tile");
1676 
1677   // Insert the inbetween code into the body.
1678   BasicBlock *BodyEnter = Enter;
1679   BasicBlock *BodyEntered = nullptr;
1680   for (std::pair<BasicBlock *, BasicBlock *> P : InbetweenCode) {
1681     BasicBlock *EnterBB = P.first;
1682     BasicBlock *ExitBB = P.second;
1683 
1684     if (BodyEnter)
1685       redirectTo(BodyEnter, EnterBB, DL);
1686     else
1687       redirectAllPredecessorsTo(BodyEntered, EnterBB, DL);
1688 
1689     BodyEnter = nullptr;
1690     BodyEntered = ExitBB;
1691   }
1692 
1693   // Append the original loop nest body into the generated loop nest body.
1694   if (BodyEnter)
1695     redirectTo(BodyEnter, InnerEnter, DL);
1696   else
1697     redirectAllPredecessorsTo(BodyEntered, InnerEnter, DL);
1698   redirectAllPredecessorsTo(InnerLatch, Continue, DL);
1699 
1700   // Replace the original induction variable with an induction variable computed
1701   // from the tile and floor induction variables.
1702   Builder.restoreIP(Result.back()->getBodyIP());
1703   for (int i = 0; i < NumLoops; ++i) {
1704     CanonicalLoopInfo *FloorLoop = Result[i];
1705     CanonicalLoopInfo *TileLoop = Result[NumLoops + i];
1706     Value *OrigIndVar = OrigIndVars[i];
1707     Value *Size = TileSizes[i];
1708 
1709     Value *Scale =
1710         Builder.CreateMul(Size, FloorLoop->getIndVar(), {}, /*HasNUW=*/true);
1711     Value *Shift =
1712         Builder.CreateAdd(Scale, TileLoop->getIndVar(), {}, /*HasNUW=*/true);
1713     OrigIndVar->replaceAllUsesWith(Shift);
1714   }
1715 
1716   // Remove unused parts of the original loops.
1717   SmallVector<BasicBlock *, 12> OldControlBBs;
1718   OldControlBBs.reserve(6 * Loops.size());
1719   for (CanonicalLoopInfo *Loop : Loops)
1720     Loop->collectControlBlocks(OldControlBBs);
1721   removeUnusedBlocksFromParent(OldControlBBs);
1722 
1723 #ifndef NDEBUG
1724   for (CanonicalLoopInfo *GenL : Result)
1725     GenL->assertOK();
1726 #endif
1727   return Result;
1728 }
1729 
1730 OpenMPIRBuilder::InsertPointTy
1731 OpenMPIRBuilder::createCopyPrivate(const LocationDescription &Loc,
1732                                    llvm::Value *BufSize, llvm::Value *CpyBuf,
1733                                    llvm::Value *CpyFn, llvm::Value *DidIt) {
1734   if (!updateToLocation(Loc))
1735     return Loc.IP;
1736 
1737   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc);
1738   Value *Ident = getOrCreateIdent(SrcLocStr);
1739   Value *ThreadId = getOrCreateThreadID(Ident);
1740 
1741   llvm::Value *DidItLD = Builder.CreateLoad(Builder.getInt32Ty(), DidIt);
1742 
1743   Value *Args[] = {Ident, ThreadId, BufSize, CpyBuf, CpyFn, DidItLD};
1744 
1745   Function *Fn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_copyprivate);
1746   Builder.CreateCall(Fn, Args);
1747 
1748   return Builder.saveIP();
1749 }
1750 
1751 OpenMPIRBuilder::InsertPointTy
1752 OpenMPIRBuilder::createSingle(const LocationDescription &Loc,
1753                               BodyGenCallbackTy BodyGenCB,
1754                               FinalizeCallbackTy FiniCB, llvm::Value *DidIt) {
1755 
1756   if (!updateToLocation(Loc))
1757     return Loc.IP;
1758 
1759   // If needed (i.e. not null), initialize `DidIt` with 0
1760   if (DidIt) {
1761     Builder.CreateStore(Builder.getInt32(0), DidIt);
1762   }
1763 
1764   Directive OMPD = Directive::OMPD_single;
1765   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc);
1766   Value *Ident = getOrCreateIdent(SrcLocStr);
1767   Value *ThreadId = getOrCreateThreadID(Ident);
1768   Value *Args[] = {Ident, ThreadId};
1769 
1770   Function *EntryRTLFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_single);
1771   Instruction *EntryCall = Builder.CreateCall(EntryRTLFn, Args);
1772 
1773   Function *ExitRTLFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_end_single);
1774   Instruction *ExitCall = Builder.CreateCall(ExitRTLFn, Args);
1775 
1776   // generates the following:
1777   // if (__kmpc_single()) {
1778   //		.... single region ...
1779   // 		__kmpc_end_single
1780   // }
1781 
1782   return EmitOMPInlinedRegion(OMPD, EntryCall, ExitCall, BodyGenCB, FiniCB,
1783                               /*Conditional*/ true, /*hasFinalize*/ true);
1784 }
1785 
1786 OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::createCritical(
1787     const LocationDescription &Loc, BodyGenCallbackTy BodyGenCB,
1788     FinalizeCallbackTy FiniCB, StringRef CriticalName, Value *HintInst) {
1789 
1790   if (!updateToLocation(Loc))
1791     return Loc.IP;
1792 
1793   Directive OMPD = Directive::OMPD_critical;
1794   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc);
1795   Value *Ident = getOrCreateIdent(SrcLocStr);
1796   Value *ThreadId = getOrCreateThreadID(Ident);
1797   Value *LockVar = getOMPCriticalRegionLock(CriticalName);
1798   Value *Args[] = {Ident, ThreadId, LockVar};
1799 
1800   SmallVector<llvm::Value *, 4> EnterArgs(std::begin(Args), std::end(Args));
1801   Function *RTFn = nullptr;
1802   if (HintInst) {
1803     // Add Hint to entry Args and create call
1804     EnterArgs.push_back(HintInst);
1805     RTFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_critical_with_hint);
1806   } else {
1807     RTFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_critical);
1808   }
1809   Instruction *EntryCall = Builder.CreateCall(RTFn, EnterArgs);
1810 
1811   Function *ExitRTLFn =
1812       getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_end_critical);
1813   Instruction *ExitCall = Builder.CreateCall(ExitRTLFn, Args);
1814 
1815   return EmitOMPInlinedRegion(OMPD, EntryCall, ExitCall, BodyGenCB, FiniCB,
1816                               /*Conditional*/ false, /*hasFinalize*/ true);
1817 }
1818 
1819 OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::EmitOMPInlinedRegion(
1820     Directive OMPD, Instruction *EntryCall, Instruction *ExitCall,
1821     BodyGenCallbackTy BodyGenCB, FinalizeCallbackTy FiniCB, bool Conditional,
1822     bool HasFinalize) {
1823 
1824   if (HasFinalize)
1825     FinalizationStack.push_back({FiniCB, OMPD, /*IsCancellable*/ false});
1826 
1827   // Create inlined region's entry and body blocks, in preparation
1828   // for conditional creation
1829   BasicBlock *EntryBB = Builder.GetInsertBlock();
1830   Instruction *SplitPos = EntryBB->getTerminator();
1831   if (!isa_and_nonnull<BranchInst>(SplitPos))
1832     SplitPos = new UnreachableInst(Builder.getContext(), EntryBB);
1833   BasicBlock *ExitBB = EntryBB->splitBasicBlock(SplitPos, "omp_region.end");
1834   BasicBlock *FiniBB =
1835       EntryBB->splitBasicBlock(EntryBB->getTerminator(), "omp_region.finalize");
1836 
1837   Builder.SetInsertPoint(EntryBB->getTerminator());
1838   emitCommonDirectiveEntry(OMPD, EntryCall, ExitBB, Conditional);
1839 
1840   // generate body
1841   BodyGenCB(/* AllocaIP */ InsertPointTy(),
1842             /* CodeGenIP */ Builder.saveIP(), *FiniBB);
1843 
1844   // If we didn't emit a branch to FiniBB during body generation, it means
1845   // FiniBB is unreachable (e.g. while(1);). stop generating all the
1846   // unreachable blocks, and remove anything we are not going to use.
1847   auto SkipEmittingRegion = FiniBB->hasNPredecessors(0);
1848   if (SkipEmittingRegion) {
1849     FiniBB->eraseFromParent();
1850     ExitCall->eraseFromParent();
1851     // Discard finalization if we have it.
1852     if (HasFinalize) {
1853       assert(!FinalizationStack.empty() &&
1854              "Unexpected finalization stack state!");
1855       FinalizationStack.pop_back();
1856     }
1857   } else {
1858     // emit exit call and do any needed finalization.
1859     auto FinIP = InsertPointTy(FiniBB, FiniBB->getFirstInsertionPt());
1860     assert(FiniBB->getTerminator()->getNumSuccessors() == 1 &&
1861            FiniBB->getTerminator()->getSuccessor(0) == ExitBB &&
1862            "Unexpected control flow graph state!!");
1863     emitCommonDirectiveExit(OMPD, FinIP, ExitCall, HasFinalize);
1864     assert(FiniBB->getUniquePredecessor()->getUniqueSuccessor() == FiniBB &&
1865            "Unexpected Control Flow State!");
1866     MergeBlockIntoPredecessor(FiniBB);
1867   }
1868 
1869   // If we are skipping the region of a non conditional, remove the exit
1870   // block, and clear the builder's insertion point.
1871   assert(SplitPos->getParent() == ExitBB &&
1872          "Unexpected Insertion point location!");
1873   if (!Conditional && SkipEmittingRegion) {
1874     ExitBB->eraseFromParent();
1875     Builder.ClearInsertionPoint();
1876   } else {
1877     auto merged = MergeBlockIntoPredecessor(ExitBB);
1878     BasicBlock *ExitPredBB = SplitPos->getParent();
1879     auto InsertBB = merged ? ExitPredBB : ExitBB;
1880     if (!isa_and_nonnull<BranchInst>(SplitPos))
1881       SplitPos->eraseFromParent();
1882     Builder.SetInsertPoint(InsertBB);
1883   }
1884 
1885   return Builder.saveIP();
1886 }
1887 
1888 OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::emitCommonDirectiveEntry(
1889     Directive OMPD, Value *EntryCall, BasicBlock *ExitBB, bool Conditional) {
1890 
1891   // if nothing to do, Return current insertion point.
1892   if (!Conditional)
1893     return Builder.saveIP();
1894 
1895   BasicBlock *EntryBB = Builder.GetInsertBlock();
1896   Value *CallBool = Builder.CreateIsNotNull(EntryCall);
1897   auto *ThenBB = BasicBlock::Create(M.getContext(), "omp_region.body");
1898   auto *UI = new UnreachableInst(Builder.getContext(), ThenBB);
1899 
1900   // Emit thenBB and set the Builder's insertion point there for
1901   // body generation next. Place the block after the current block.
1902   Function *CurFn = EntryBB->getParent();
1903   CurFn->getBasicBlockList().insertAfter(EntryBB->getIterator(), ThenBB);
1904 
1905   // Move Entry branch to end of ThenBB, and replace with conditional
1906   // branch (If-stmt)
1907   Instruction *EntryBBTI = EntryBB->getTerminator();
1908   Builder.CreateCondBr(CallBool, ThenBB, ExitBB);
1909   EntryBBTI->removeFromParent();
1910   Builder.SetInsertPoint(UI);
1911   Builder.Insert(EntryBBTI);
1912   UI->eraseFromParent();
1913   Builder.SetInsertPoint(ThenBB->getTerminator());
1914 
1915   // return an insertion point to ExitBB.
1916   return IRBuilder<>::InsertPoint(ExitBB, ExitBB->getFirstInsertionPt());
1917 }
1918 
1919 OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::emitCommonDirectiveExit(
1920     omp::Directive OMPD, InsertPointTy FinIP, Instruction *ExitCall,
1921     bool HasFinalize) {
1922 
1923   Builder.restoreIP(FinIP);
1924 
1925   // If there is finalization to do, emit it before the exit call
1926   if (HasFinalize) {
1927     assert(!FinalizationStack.empty() &&
1928            "Unexpected finalization stack state!");
1929 
1930     FinalizationInfo Fi = FinalizationStack.pop_back_val();
1931     assert(Fi.DK == OMPD && "Unexpected Directive for Finalization call!");
1932 
1933     Fi.FiniCB(FinIP);
1934 
1935     BasicBlock *FiniBB = FinIP.getBlock();
1936     Instruction *FiniBBTI = FiniBB->getTerminator();
1937 
1938     // set Builder IP for call creation
1939     Builder.SetInsertPoint(FiniBBTI);
1940   }
1941 
1942   // place the Exitcall as last instruction before Finalization block terminator
1943   ExitCall->removeFromParent();
1944   Builder.Insert(ExitCall);
1945 
1946   return IRBuilder<>::InsertPoint(ExitCall->getParent(),
1947                                   ExitCall->getIterator());
1948 }
1949 
1950 OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::createCopyinClauseBlocks(
1951     InsertPointTy IP, Value *MasterAddr, Value *PrivateAddr,
1952     llvm::IntegerType *IntPtrTy, bool BranchtoEnd) {
1953   if (!IP.isSet())
1954     return IP;
1955 
1956   IRBuilder<>::InsertPointGuard IPG(Builder);
1957 
1958   // creates the following CFG structure
1959   //	   OMP_Entry : (MasterAddr != PrivateAddr)?
1960   //       F     T
1961   //       |      \
1962   //       |     copin.not.master
1963   //       |      /
1964   //       v     /
1965   //   copyin.not.master.end
1966   //		     |
1967   //         v
1968   //   OMP.Entry.Next
1969 
1970   BasicBlock *OMP_Entry = IP.getBlock();
1971   Function *CurFn = OMP_Entry->getParent();
1972   BasicBlock *CopyBegin =
1973       BasicBlock::Create(M.getContext(), "copyin.not.master", CurFn);
1974   BasicBlock *CopyEnd = nullptr;
1975 
1976   // If entry block is terminated, split to preserve the branch to following
1977   // basic block (i.e. OMP.Entry.Next), otherwise, leave everything as is.
1978   if (isa_and_nonnull<BranchInst>(OMP_Entry->getTerminator())) {
1979     CopyEnd = OMP_Entry->splitBasicBlock(OMP_Entry->getTerminator(),
1980                                          "copyin.not.master.end");
1981     OMP_Entry->getTerminator()->eraseFromParent();
1982   } else {
1983     CopyEnd =
1984         BasicBlock::Create(M.getContext(), "copyin.not.master.end", CurFn);
1985   }
1986 
1987   Builder.SetInsertPoint(OMP_Entry);
1988   Value *MasterPtr = Builder.CreatePtrToInt(MasterAddr, IntPtrTy);
1989   Value *PrivatePtr = Builder.CreatePtrToInt(PrivateAddr, IntPtrTy);
1990   Value *cmp = Builder.CreateICmpNE(MasterPtr, PrivatePtr);
1991   Builder.CreateCondBr(cmp, CopyBegin, CopyEnd);
1992 
1993   Builder.SetInsertPoint(CopyBegin);
1994   if (BranchtoEnd)
1995     Builder.SetInsertPoint(Builder.CreateBr(CopyEnd));
1996 
1997   return Builder.saveIP();
1998 }
1999 
2000 CallInst *OpenMPIRBuilder::createOMPAlloc(const LocationDescription &Loc,
2001                                           Value *Size, Value *Allocator,
2002                                           std::string Name) {
2003   IRBuilder<>::InsertPointGuard IPG(Builder);
2004   Builder.restoreIP(Loc.IP);
2005 
2006   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc);
2007   Value *Ident = getOrCreateIdent(SrcLocStr);
2008   Value *ThreadId = getOrCreateThreadID(Ident);
2009   Value *Args[] = {ThreadId, Size, Allocator};
2010 
2011   Function *Fn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_alloc);
2012 
2013   return Builder.CreateCall(Fn, Args, Name);
2014 }
2015 
2016 CallInst *OpenMPIRBuilder::createOMPFree(const LocationDescription &Loc,
2017                                          Value *Addr, Value *Allocator,
2018                                          std::string Name) {
2019   IRBuilder<>::InsertPointGuard IPG(Builder);
2020   Builder.restoreIP(Loc.IP);
2021 
2022   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc);
2023   Value *Ident = getOrCreateIdent(SrcLocStr);
2024   Value *ThreadId = getOrCreateThreadID(Ident);
2025   Value *Args[] = {ThreadId, Addr, Allocator};
2026   Function *Fn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_free);
2027   return Builder.CreateCall(Fn, Args, Name);
2028 }
2029 
2030 CallInst *OpenMPIRBuilder::createCachedThreadPrivate(
2031     const LocationDescription &Loc, llvm::Value *Pointer,
2032     llvm::ConstantInt *Size, const llvm::Twine &Name) {
2033   IRBuilder<>::InsertPointGuard IPG(Builder);
2034   Builder.restoreIP(Loc.IP);
2035 
2036   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc);
2037   Value *Ident = getOrCreateIdent(SrcLocStr);
2038   Value *ThreadId = getOrCreateThreadID(Ident);
2039   Constant *ThreadPrivateCache =
2040       getOrCreateOMPInternalVariable(Int8PtrPtr, Name);
2041   llvm::Value *Args[] = {Ident, ThreadId, Pointer, Size, ThreadPrivateCache};
2042 
2043   Function *Fn =
2044       getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_threadprivate_cached);
2045 
2046   return Builder.CreateCall(Fn, Args);
2047 }
2048 
2049 std::string OpenMPIRBuilder::getNameWithSeparators(ArrayRef<StringRef> Parts,
2050                                                    StringRef FirstSeparator,
2051                                                    StringRef Separator) {
2052   SmallString<128> Buffer;
2053   llvm::raw_svector_ostream OS(Buffer);
2054   StringRef Sep = FirstSeparator;
2055   for (StringRef Part : Parts) {
2056     OS << Sep << Part;
2057     Sep = Separator;
2058   }
2059   return OS.str().str();
2060 }
2061 
2062 Constant *OpenMPIRBuilder::getOrCreateOMPInternalVariable(
2063     llvm::Type *Ty, const llvm::Twine &Name, unsigned AddressSpace) {
2064   // TODO: Replace the twine arg with stringref to get rid of the conversion
2065   // logic. However This is taken from current implementation in clang as is.
2066   // Since this method is used in many places exclusively for OMP internal use
2067   // we will keep it as is for temporarily until we move all users to the
2068   // builder and then, if possible, fix it everywhere in one go.
2069   SmallString<256> Buffer;
2070   llvm::raw_svector_ostream Out(Buffer);
2071   Out << Name;
2072   StringRef RuntimeName = Out.str();
2073   auto &Elem = *InternalVars.try_emplace(RuntimeName, nullptr).first;
2074   if (Elem.second) {
2075     assert(Elem.second->getType()->getPointerElementType() == Ty &&
2076            "OMP internal variable has different type than requested");
2077   } else {
2078     // TODO: investigate the appropriate linkage type used for the global
2079     // variable for possibly changing that to internal or private, or maybe
2080     // create different versions of the function for different OMP internal
2081     // variables.
2082     Elem.second = new llvm::GlobalVariable(
2083         M, Ty, /*IsConstant*/ false, llvm::GlobalValue::CommonLinkage,
2084         llvm::Constant::getNullValue(Ty), Elem.first(),
2085         /*InsertBefore=*/nullptr, llvm::GlobalValue::NotThreadLocal,
2086         AddressSpace);
2087   }
2088 
2089   return Elem.second;
2090 }
2091 
2092 Value *OpenMPIRBuilder::getOMPCriticalRegionLock(StringRef CriticalName) {
2093   std::string Prefix = Twine("gomp_critical_user_", CriticalName).str();
2094   std::string Name = getNameWithSeparators({Prefix, "var"}, ".", ".");
2095   return getOrCreateOMPInternalVariable(KmpCriticalNameTy, Name);
2096 }
2097 
2098 // Create all simple and struct types exposed by the runtime and remember
2099 // the llvm::PointerTypes of them for easy access later.
2100 void OpenMPIRBuilder::initializeTypes(Module &M) {
2101   LLVMContext &Ctx = M.getContext();
2102   StructType *T;
2103 #define OMP_TYPE(VarName, InitValue) VarName = InitValue;
2104 #define OMP_ARRAY_TYPE(VarName, ElemTy, ArraySize)                             \
2105   VarName##Ty = ArrayType::get(ElemTy, ArraySize);                             \
2106   VarName##PtrTy = PointerType::getUnqual(VarName##Ty);
2107 #define OMP_FUNCTION_TYPE(VarName, IsVarArg, ReturnType, ...)                  \
2108   VarName = FunctionType::get(ReturnType, {__VA_ARGS__}, IsVarArg);            \
2109   VarName##Ptr = PointerType::getUnqual(VarName);
2110 #define OMP_STRUCT_TYPE(VarName, StructName, ...)                              \
2111   T = StructType::getTypeByName(Ctx, StructName);                              \
2112   if (!T)                                                                      \
2113     T = StructType::create(Ctx, {__VA_ARGS__}, StructName);                    \
2114   VarName = T;                                                                 \
2115   VarName##Ptr = PointerType::getUnqual(T);
2116 #include "llvm/Frontend/OpenMP/OMPKinds.def"
2117 }
2118 
2119 void OpenMPIRBuilder::OutlineInfo::collectBlocks(
2120     SmallPtrSetImpl<BasicBlock *> &BlockSet,
2121     SmallVectorImpl<BasicBlock *> &BlockVector) {
2122   SmallVector<BasicBlock *, 32> Worklist;
2123   BlockSet.insert(EntryBB);
2124   BlockSet.insert(ExitBB);
2125 
2126   Worklist.push_back(EntryBB);
2127   while (!Worklist.empty()) {
2128     BasicBlock *BB = Worklist.pop_back_val();
2129     BlockVector.push_back(BB);
2130     for (BasicBlock *SuccBB : successors(BB))
2131       if (BlockSet.insert(SuccBB).second)
2132         Worklist.push_back(SuccBB);
2133   }
2134 }
2135 
2136 void CanonicalLoopInfo::collectControlBlocks(
2137     SmallVectorImpl<BasicBlock *> &BBs) {
2138   // We only count those BBs as control block for which we do not need to
2139   // reverse the CFG, i.e. not the loop body which can contain arbitrary control
2140   // flow. For consistency, this also means we do not add the Body block, which
2141   // is just the entry to the body code.
2142   BBs.reserve(BBs.size() + 6);
2143   BBs.append({Preheader, Header, Cond, Latch, Exit, After});
2144 }
2145 
2146 void CanonicalLoopInfo::assertOK() const {
2147 #ifndef NDEBUG
2148   if (!IsValid)
2149     return;
2150 
2151   // Verify standard control-flow we use for OpenMP loops.
2152   assert(Preheader);
2153   assert(isa<BranchInst>(Preheader->getTerminator()) &&
2154          "Preheader must terminate with unconditional branch");
2155   assert(Preheader->getSingleSuccessor() == Header &&
2156          "Preheader must jump to header");
2157 
2158   assert(Header);
2159   assert(isa<BranchInst>(Header->getTerminator()) &&
2160          "Header must terminate with unconditional branch");
2161   assert(Header->getSingleSuccessor() == Cond &&
2162          "Header must jump to exiting block");
2163 
2164   assert(Cond);
2165   assert(Cond->getSinglePredecessor() == Header &&
2166          "Exiting block only reachable from header");
2167 
2168   assert(isa<BranchInst>(Cond->getTerminator()) &&
2169          "Exiting block must terminate with conditional branch");
2170   assert(size(successors(Cond)) == 2 &&
2171          "Exiting block must have two successors");
2172   assert(cast<BranchInst>(Cond->getTerminator())->getSuccessor(0) == Body &&
2173          "Exiting block's first successor jump to the body");
2174   assert(cast<BranchInst>(Cond->getTerminator())->getSuccessor(1) == Exit &&
2175          "Exiting block's second successor must exit the loop");
2176 
2177   assert(Body);
2178   assert(Body->getSinglePredecessor() == Cond &&
2179          "Body only reachable from exiting block");
2180   assert(!isa<PHINode>(Body->front()));
2181 
2182   assert(Latch);
2183   assert(isa<BranchInst>(Latch->getTerminator()) &&
2184          "Latch must terminate with unconditional branch");
2185   assert(Latch->getSingleSuccessor() == Header && "Latch must jump to header");
2186   // TODO: To support simple redirecting of the end of the body code that has
2187   // multiple; introduce another auxiliary basic block like preheader and after.
2188   assert(Latch->getSinglePredecessor() != nullptr);
2189   assert(!isa<PHINode>(Latch->front()));
2190 
2191   assert(Exit);
2192   assert(isa<BranchInst>(Exit->getTerminator()) &&
2193          "Exit block must terminate with unconditional branch");
2194   assert(Exit->getSingleSuccessor() == After &&
2195          "Exit block must jump to after block");
2196 
2197   assert(After);
2198   assert(After->getSinglePredecessor() == Exit &&
2199          "After block only reachable from exit block");
2200   assert(After->empty() || !isa<PHINode>(After->front()));
2201 
2202   Instruction *IndVar = getIndVar();
2203   assert(IndVar && "Canonical induction variable not found?");
2204   assert(isa<IntegerType>(IndVar->getType()) &&
2205          "Induction variable must be an integer");
2206   assert(cast<PHINode>(IndVar)->getParent() == Header &&
2207          "Induction variable must be a PHI in the loop header");
2208   assert(cast<PHINode>(IndVar)->getIncomingBlock(0) == Preheader);
2209   assert(
2210       cast<ConstantInt>(cast<PHINode>(IndVar)->getIncomingValue(0))->isZero());
2211   assert(cast<PHINode>(IndVar)->getIncomingBlock(1) == Latch);
2212 
2213   auto *NextIndVar = cast<PHINode>(IndVar)->getIncomingValue(1);
2214   assert(cast<Instruction>(NextIndVar)->getParent() == Latch);
2215   assert(cast<BinaryOperator>(NextIndVar)->getOpcode() == BinaryOperator::Add);
2216   assert(cast<BinaryOperator>(NextIndVar)->getOperand(0) == IndVar);
2217   assert(cast<ConstantInt>(cast<BinaryOperator>(NextIndVar)->getOperand(1))
2218              ->isOne());
2219 
2220   Value *TripCount = getTripCount();
2221   assert(TripCount && "Loop trip count not found?");
2222   assert(IndVar->getType() == TripCount->getType() &&
2223          "Trip count and induction variable must have the same type");
2224 
2225   auto *CmpI = cast<CmpInst>(&Cond->front());
2226   assert(CmpI->getPredicate() == CmpInst::ICMP_ULT &&
2227          "Exit condition must be a signed less-than comparison");
2228   assert(CmpI->getOperand(0) == IndVar &&
2229          "Exit condition must compare the induction variable");
2230   assert(CmpI->getOperand(1) == TripCount &&
2231          "Exit condition must compare with the trip count");
2232 #endif
2233 }
2234