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