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