1 //===- llvm/unittest/IR/OpenMPIRBuilderTest.cpp - OpenMPIRBuilder tests ---===//
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 
9 #include "llvm/Frontend/OpenMP/OMPConstants.h"
10 #include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
11 #include "llvm/IR/BasicBlock.h"
12 #include "llvm/IR/DIBuilder.h"
13 #include "llvm/IR/Function.h"
14 #include "llvm/IR/InstIterator.h"
15 #include "llvm/IR/LLVMContext.h"
16 #include "llvm/IR/Module.h"
17 #include "llvm/IR/Verifier.h"
18 #include "llvm/Passes/PassBuilder.h"
19 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
20 #include "gtest/gtest.h"
21 
22 using namespace llvm;
23 using namespace omp;
24 
25 namespace {
26 
27 /// Create an instruction that uses the values in \p Values. We use "printf"
28 /// just because it is often used for this purpose in test code, but it is never
29 /// executed here.
30 static CallInst *createPrintfCall(IRBuilder<> &Builder, StringRef FormatStr,
31                                   ArrayRef<Value *> Values) {
32   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
33 
34   GlobalVariable *GV = Builder.CreateGlobalString(FormatStr, "", 0, M);
35   Constant *Zero = ConstantInt::get(Type::getInt32Ty(M->getContext()), 0);
36   Constant *Indices[] = {Zero, Zero};
37   Constant *FormatStrConst =
38       ConstantExpr::getInBoundsGetElementPtr(GV->getValueType(), GV, Indices);
39 
40   Function *PrintfDecl = M->getFunction("printf");
41   if (!PrintfDecl) {
42     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
43     FunctionType *Ty = FunctionType::get(Builder.getInt32Ty(), true);
44     PrintfDecl = Function::Create(Ty, Linkage, "printf", M);
45   }
46 
47   SmallVector<Value *, 4> Args;
48   Args.push_back(FormatStrConst);
49   Args.append(Values.begin(), Values.end());
50   return Builder.CreateCall(PrintfDecl, Args);
51 }
52 
53 /// Verify that blocks in \p RefOrder are corresponds to the depth-first visit
54 /// order the control flow of \p F.
55 ///
56 /// This is an easy way to verify the branching structure of the CFG without
57 /// checking every branch instruction individually. For the CFG of a
58 /// CanonicalLoopInfo, the Cond BB's terminating branch's first edge is entering
59 /// the body, i.e. the DFS order corresponds to the execution order with one
60 /// loop iteration.
61 static testing::AssertionResult
62 verifyDFSOrder(Function *F, ArrayRef<BasicBlock *> RefOrder) {
63   ArrayRef<BasicBlock *>::iterator It = RefOrder.begin();
64   ArrayRef<BasicBlock *>::iterator E = RefOrder.end();
65 
66   df_iterator_default_set<BasicBlock *, 16> Visited;
67   auto DFS = llvm::depth_first_ext(&F->getEntryBlock(), Visited);
68 
69   BasicBlock *Prev = nullptr;
70   for (BasicBlock *BB : DFS) {
71     if (It != E && BB == *It) {
72       Prev = *It;
73       ++It;
74     }
75   }
76 
77   if (It == E)
78     return testing::AssertionSuccess();
79   if (!Prev)
80     return testing::AssertionFailure()
81            << "Did not find " << (*It)->getName() << " in control flow";
82   return testing::AssertionFailure()
83          << "Expected " << Prev->getName() << " before " << (*It)->getName()
84          << " in control flow";
85 }
86 
87 /// Verify that blocks in \p RefOrder are in the same relative order in the
88 /// linked lists of blocks in \p F. The linked list may contain additional
89 /// blocks in-between.
90 ///
91 /// While the order in the linked list is not relevant for semantics, keeping
92 /// the order roughly in execution order makes its printout easier to read.
93 static testing::AssertionResult
94 verifyListOrder(Function *F, ArrayRef<BasicBlock *> RefOrder) {
95   ArrayRef<BasicBlock *>::iterator It = RefOrder.begin();
96   ArrayRef<BasicBlock *>::iterator E = RefOrder.end();
97 
98   BasicBlock *Prev = nullptr;
99   for (BasicBlock &BB : *F) {
100     if (It != E && &BB == *It) {
101       Prev = *It;
102       ++It;
103     }
104   }
105 
106   if (It == E)
107     return testing::AssertionSuccess();
108   if (!Prev)
109     return testing::AssertionFailure() << "Did not find " << (*It)->getName()
110                                        << " in function " << F->getName();
111   return testing::AssertionFailure()
112          << "Expected " << Prev->getName() << " before " << (*It)->getName()
113          << " in function " << F->getName();
114 }
115 
116 /// Populate Calls with call instructions calling the function with the given
117 /// FnID from the given function F.
118 static void findCalls(Function *F, omp::RuntimeFunction FnID,
119                       OpenMPIRBuilder &OMPBuilder,
120                       SmallVectorImpl<CallInst *> &Calls) {
121   Function *Fn = OMPBuilder.getOrCreateRuntimeFunctionPtr(FnID);
122   for (BasicBlock &BB : *F) {
123     for (Instruction &I : BB) {
124       auto *Call = dyn_cast<CallInst>(&I);
125       if (Call && Call->getCalledFunction() == Fn)
126         Calls.push_back(Call);
127     }
128   }
129 }
130 
131 /// Assuming \p F contains only one call to the function with the given \p FnID,
132 /// return that call.
133 static CallInst *findSingleCall(Function *F, omp::RuntimeFunction FnID,
134                                 OpenMPIRBuilder &OMPBuilder) {
135   SmallVector<CallInst *, 1> Calls;
136   findCalls(F, FnID, OMPBuilder, Calls);
137   EXPECT_EQ(1u, Calls.size());
138   if (Calls.size() != 1)
139     return nullptr;
140   return Calls.front();
141 }
142 
143 static omp::ScheduleKind getSchedKind(omp::OMPScheduleType SchedType) {
144   switch (SchedType & ~omp::OMPScheduleType::ModifierMask) {
145   case omp::OMPScheduleType::BaseDynamicChunked:
146     return omp::OMP_SCHEDULE_Dynamic;
147   case omp::OMPScheduleType::BaseGuidedChunked:
148     return omp::OMP_SCHEDULE_Guided;
149   case omp::OMPScheduleType::BaseAuto:
150     return omp::OMP_SCHEDULE_Auto;
151   case omp::OMPScheduleType::BaseRuntime:
152     return omp::OMP_SCHEDULE_Runtime;
153   default:
154     llvm_unreachable("unknown type for this test");
155   }
156 }
157 
158 class OpenMPIRBuilderTest : public testing::Test {
159 protected:
160   void SetUp() override {
161     M.reset(new Module("MyModule", Ctx));
162     FunctionType *FTy =
163         FunctionType::get(Type::getVoidTy(Ctx), {Type::getInt32Ty(Ctx)},
164                           /*isVarArg=*/false);
165     F = Function::Create(FTy, Function::ExternalLinkage, "", M.get());
166     BB = BasicBlock::Create(Ctx, "", F);
167 
168     DIBuilder DIB(*M);
169     auto File = DIB.createFile("test.dbg", "/src", llvm::None,
170                                Optional<StringRef>("/src/test.dbg"));
171     auto CU =
172         DIB.createCompileUnit(dwarf::DW_LANG_C, File, "llvm-C", true, "", 0);
173     auto Type = DIB.createSubroutineType(DIB.getOrCreateTypeArray(None));
174     auto SP = DIB.createFunction(
175         CU, "foo", "", File, 1, Type, 1, DINode::FlagZero,
176         DISubprogram::SPFlagDefinition | DISubprogram::SPFlagOptimized);
177     F->setSubprogram(SP);
178     auto Scope = DIB.createLexicalBlockFile(SP, File, 0);
179     DIB.finalize();
180     DL = DILocation::get(Ctx, 3, 7, Scope);
181   }
182 
183   void TearDown() override {
184     BB = nullptr;
185     M.reset();
186   }
187 
188   /// Create a function with a simple loop that calls printf using the logical
189   /// loop counter for use with tests that need a CanonicalLoopInfo object.
190   CanonicalLoopInfo *buildSingleLoopFunction(DebugLoc DL,
191                                              OpenMPIRBuilder &OMPBuilder,
192                                              int UseIVBits,
193                                              CallInst **Call = nullptr,
194                                              BasicBlock **BodyCode = nullptr) {
195     OMPBuilder.initialize();
196     F->setName("func");
197 
198     IRBuilder<> Builder(BB);
199     OpenMPIRBuilder::LocationDescription Loc({Builder.saveIP(), DL});
200     Value *TripCount = F->getArg(0);
201 
202     Type *IVType = Type::getIntNTy(Builder.getContext(), UseIVBits);
203     Value *CastedTripCount =
204         Builder.CreateZExtOrTrunc(TripCount, IVType, "tripcount");
205 
206     auto LoopBodyGenCB = [&](OpenMPIRBuilder::InsertPointTy CodeGenIP,
207                              llvm::Value *LC) {
208       Builder.restoreIP(CodeGenIP);
209       if (BodyCode)
210         *BodyCode = Builder.GetInsertBlock();
211 
212       // Add something that consumes the induction variable to the body.
213       CallInst *CallInst = createPrintfCall(Builder, "%d\\n", {LC});
214       if (Call)
215         *Call = CallInst;
216     };
217     CanonicalLoopInfo *Loop =
218         OMPBuilder.createCanonicalLoop(Loc, LoopBodyGenCB, CastedTripCount);
219 
220     // Finalize the function.
221     Builder.restoreIP(Loop->getAfterIP());
222     Builder.CreateRetVoid();
223 
224     return Loop;
225   }
226 
227   LLVMContext Ctx;
228   std::unique_ptr<Module> M;
229   Function *F;
230   BasicBlock *BB;
231   DebugLoc DL;
232 };
233 
234 class OpenMPIRBuilderTestWithParams
235     : public OpenMPIRBuilderTest,
236       public ::testing::WithParamInterface<omp::OMPScheduleType> {};
237 
238 class OpenMPIRBuilderTestWithIVBits
239     : public OpenMPIRBuilderTest,
240       public ::testing::WithParamInterface<int> {};
241 
242 // Returns the value stored in the given allocation. Returns null if the given
243 // value is not a result of an InstTy instruction, if no value is stored or if
244 // there is more than one store.
245 template <typename InstTy> static Value *findStoredValue(Value *AllocaValue) {
246   Instruction *Inst = dyn_cast<InstTy>(AllocaValue);
247   if (!Inst)
248     return nullptr;
249   StoreInst *Store = nullptr;
250   for (Use &U : Inst->uses()) {
251     if (auto *CandidateStore = dyn_cast<StoreInst>(U.getUser())) {
252       EXPECT_EQ(Store, nullptr);
253       Store = CandidateStore;
254     }
255   }
256   if (!Store)
257     return nullptr;
258   return Store->getValueOperand();
259 }
260 
261 // Returns the value stored in the aggregate argument of an outlined function,
262 // or nullptr if it is not found.
263 static Value *findStoredValueInAggregateAt(LLVMContext &Ctx, Value *Aggregate,
264                                            unsigned Idx) {
265   GetElementPtrInst *GEPAtIdx = nullptr;
266   // Find GEP instruction at that index.
267   for (User *Usr : Aggregate->users()) {
268     GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Usr);
269     if (!GEP)
270       continue;
271 
272     if (GEP->getOperand(2) != ConstantInt::get(Type::getInt32Ty(Ctx), Idx))
273       continue;
274 
275     EXPECT_EQ(GEPAtIdx, nullptr);
276     GEPAtIdx = GEP;
277   }
278 
279   EXPECT_NE(GEPAtIdx, nullptr);
280   EXPECT_EQ(GEPAtIdx->getNumUses(), 1U);
281 
282   // Find the value stored to the aggregate.
283   StoreInst *StoreToAgg = dyn_cast<StoreInst>(*GEPAtIdx->user_begin());
284   Value *StoredAggValue = StoreToAgg->getValueOperand();
285 
286   Value *StoredValue = nullptr;
287 
288   // Find the value stored to the value stored in the aggregate.
289   for (User *Usr : StoredAggValue->users()) {
290     StoreInst *Store = dyn_cast<StoreInst>(Usr);
291     if (!Store)
292       continue;
293 
294     if (Store->getPointerOperand() != StoredAggValue)
295       continue;
296 
297     EXPECT_EQ(StoredValue, nullptr);
298     StoredValue = Store->getValueOperand();
299   }
300 
301   return StoredValue;
302 }
303 
304 // Returns the aggregate that the value is originating from.
305 static Value *findAggregateFromValue(Value *V) {
306   // Expects a load instruction that loads from the aggregate.
307   LoadInst *Load = dyn_cast<LoadInst>(V);
308   EXPECT_NE(Load, nullptr);
309   // Find the GEP instruction used in the load instruction.
310   GetElementPtrInst *GEP =
311       dyn_cast<GetElementPtrInst>(Load->getPointerOperand());
312   EXPECT_NE(GEP, nullptr);
313   // Find the aggregate used in the GEP instruction.
314   Value *Aggregate = GEP->getPointerOperand();
315 
316   return Aggregate;
317 }
318 
319 TEST_F(OpenMPIRBuilderTest, CreateBarrier) {
320   OpenMPIRBuilder OMPBuilder(*M);
321   OMPBuilder.initialize();
322 
323   IRBuilder<> Builder(BB);
324 
325   OMPBuilder.createBarrier({IRBuilder<>::InsertPoint()}, OMPD_for);
326   EXPECT_TRUE(M->global_empty());
327   EXPECT_EQ(M->size(), 1U);
328   EXPECT_EQ(F->size(), 1U);
329   EXPECT_EQ(BB->size(), 0U);
330 
331   OpenMPIRBuilder::LocationDescription Loc({Builder.saveIP()});
332   OMPBuilder.createBarrier(Loc, OMPD_for);
333   EXPECT_FALSE(M->global_empty());
334   EXPECT_EQ(M->size(), 3U);
335   EXPECT_EQ(F->size(), 1U);
336   EXPECT_EQ(BB->size(), 2U);
337 
338   CallInst *GTID = dyn_cast<CallInst>(&BB->front());
339   EXPECT_NE(GTID, nullptr);
340   EXPECT_EQ(GTID->arg_size(), 1U);
341   EXPECT_EQ(GTID->getCalledFunction()->getName(), "__kmpc_global_thread_num");
342   EXPECT_FALSE(GTID->getCalledFunction()->doesNotAccessMemory());
343   EXPECT_FALSE(GTID->getCalledFunction()->doesNotFreeMemory());
344 
345   CallInst *Barrier = dyn_cast<CallInst>(GTID->getNextNode());
346   EXPECT_NE(Barrier, nullptr);
347   EXPECT_EQ(Barrier->arg_size(), 2U);
348   EXPECT_EQ(Barrier->getCalledFunction()->getName(), "__kmpc_barrier");
349   EXPECT_FALSE(Barrier->getCalledFunction()->doesNotAccessMemory());
350   EXPECT_FALSE(Barrier->getCalledFunction()->doesNotFreeMemory());
351 
352   EXPECT_EQ(cast<CallInst>(Barrier)->getArgOperand(1), GTID);
353 
354   Builder.CreateUnreachable();
355   EXPECT_FALSE(verifyModule(*M, &errs()));
356 }
357 
358 TEST_F(OpenMPIRBuilderTest, CreateCancel) {
359   using InsertPointTy = OpenMPIRBuilder::InsertPointTy;
360   OpenMPIRBuilder OMPBuilder(*M);
361   OMPBuilder.initialize();
362 
363   BasicBlock *CBB = BasicBlock::Create(Ctx, "", F);
364   new UnreachableInst(Ctx, CBB);
365   auto FiniCB = [&](InsertPointTy IP) {
366     ASSERT_NE(IP.getBlock(), nullptr);
367     ASSERT_EQ(IP.getBlock()->end(), IP.getPoint());
368     BranchInst::Create(CBB, IP.getBlock());
369   };
370   OMPBuilder.pushFinalizationCB({FiniCB, OMPD_parallel, true});
371 
372   IRBuilder<> Builder(BB);
373 
374   OpenMPIRBuilder::LocationDescription Loc({Builder.saveIP()});
375   auto NewIP = OMPBuilder.createCancel(Loc, nullptr, OMPD_parallel);
376   Builder.restoreIP(NewIP);
377   EXPECT_FALSE(M->global_empty());
378   EXPECT_EQ(M->size(), 4U);
379   EXPECT_EQ(F->size(), 4U);
380   EXPECT_EQ(BB->size(), 4U);
381 
382   CallInst *GTID = dyn_cast<CallInst>(&BB->front());
383   EXPECT_NE(GTID, nullptr);
384   EXPECT_EQ(GTID->arg_size(), 1U);
385   EXPECT_EQ(GTID->getCalledFunction()->getName(), "__kmpc_global_thread_num");
386   EXPECT_FALSE(GTID->getCalledFunction()->doesNotAccessMemory());
387   EXPECT_FALSE(GTID->getCalledFunction()->doesNotFreeMemory());
388 
389   CallInst *Cancel = dyn_cast<CallInst>(GTID->getNextNode());
390   EXPECT_NE(Cancel, nullptr);
391   EXPECT_EQ(Cancel->arg_size(), 3U);
392   EXPECT_EQ(Cancel->getCalledFunction()->getName(), "__kmpc_cancel");
393   EXPECT_FALSE(Cancel->getCalledFunction()->doesNotAccessMemory());
394   EXPECT_FALSE(Cancel->getCalledFunction()->doesNotFreeMemory());
395   EXPECT_EQ(Cancel->getNumUses(), 1U);
396   Instruction *CancelBBTI = Cancel->getParent()->getTerminator();
397   EXPECT_EQ(CancelBBTI->getNumSuccessors(), 2U);
398   EXPECT_EQ(CancelBBTI->getSuccessor(0), NewIP.getBlock());
399   EXPECT_EQ(CancelBBTI->getSuccessor(1)->size(), 3U);
400   CallInst *GTID1 = dyn_cast<CallInst>(&CancelBBTI->getSuccessor(1)->front());
401   EXPECT_NE(GTID1, nullptr);
402   EXPECT_EQ(GTID1->arg_size(), 1U);
403   EXPECT_EQ(GTID1->getCalledFunction()->getName(), "__kmpc_global_thread_num");
404   EXPECT_FALSE(GTID1->getCalledFunction()->doesNotAccessMemory());
405   EXPECT_FALSE(GTID1->getCalledFunction()->doesNotFreeMemory());
406   CallInst *Barrier = dyn_cast<CallInst>(GTID1->getNextNode());
407   EXPECT_NE(Barrier, nullptr);
408   EXPECT_EQ(Barrier->arg_size(), 2U);
409   EXPECT_EQ(Barrier->getCalledFunction()->getName(), "__kmpc_cancel_barrier");
410   EXPECT_FALSE(Barrier->getCalledFunction()->doesNotAccessMemory());
411   EXPECT_FALSE(Barrier->getCalledFunction()->doesNotFreeMemory());
412   EXPECT_EQ(Barrier->getNumUses(), 0U);
413   EXPECT_EQ(CancelBBTI->getSuccessor(1)->getTerminator()->getNumSuccessors(),
414             1U);
415   EXPECT_EQ(CancelBBTI->getSuccessor(1)->getTerminator()->getSuccessor(0), CBB);
416 
417   EXPECT_EQ(cast<CallInst>(Cancel)->getArgOperand(1), GTID);
418 
419   OMPBuilder.popFinalizationCB();
420 
421   Builder.CreateUnreachable();
422   EXPECT_FALSE(verifyModule(*M, &errs()));
423 }
424 
425 TEST_F(OpenMPIRBuilderTest, CreateCancelIfCond) {
426   using InsertPointTy = OpenMPIRBuilder::InsertPointTy;
427   OpenMPIRBuilder OMPBuilder(*M);
428   OMPBuilder.initialize();
429 
430   BasicBlock *CBB = BasicBlock::Create(Ctx, "", F);
431   new UnreachableInst(Ctx, CBB);
432   auto FiniCB = [&](InsertPointTy IP) {
433     ASSERT_NE(IP.getBlock(), nullptr);
434     ASSERT_EQ(IP.getBlock()->end(), IP.getPoint());
435     BranchInst::Create(CBB, IP.getBlock());
436   };
437   OMPBuilder.pushFinalizationCB({FiniCB, OMPD_parallel, true});
438 
439   IRBuilder<> Builder(BB);
440 
441   OpenMPIRBuilder::LocationDescription Loc({Builder.saveIP()});
442   auto NewIP = OMPBuilder.createCancel(Loc, Builder.getTrue(), OMPD_parallel);
443   Builder.restoreIP(NewIP);
444   EXPECT_FALSE(M->global_empty());
445   EXPECT_EQ(M->size(), 4U);
446   EXPECT_EQ(F->size(), 7U);
447   EXPECT_EQ(BB->size(), 1U);
448   ASSERT_TRUE(isa<BranchInst>(BB->getTerminator()));
449   ASSERT_EQ(BB->getTerminator()->getNumSuccessors(), 2U);
450   BB = BB->getTerminator()->getSuccessor(0);
451   EXPECT_EQ(BB->size(), 4U);
452 
453   CallInst *GTID = dyn_cast<CallInst>(&BB->front());
454   EXPECT_NE(GTID, nullptr);
455   EXPECT_EQ(GTID->arg_size(), 1U);
456   EXPECT_EQ(GTID->getCalledFunction()->getName(), "__kmpc_global_thread_num");
457   EXPECT_FALSE(GTID->getCalledFunction()->doesNotAccessMemory());
458   EXPECT_FALSE(GTID->getCalledFunction()->doesNotFreeMemory());
459 
460   CallInst *Cancel = dyn_cast<CallInst>(GTID->getNextNode());
461   EXPECT_NE(Cancel, nullptr);
462   EXPECT_EQ(Cancel->arg_size(), 3U);
463   EXPECT_EQ(Cancel->getCalledFunction()->getName(), "__kmpc_cancel");
464   EXPECT_FALSE(Cancel->getCalledFunction()->doesNotAccessMemory());
465   EXPECT_FALSE(Cancel->getCalledFunction()->doesNotFreeMemory());
466   EXPECT_EQ(Cancel->getNumUses(), 1U);
467   Instruction *CancelBBTI = Cancel->getParent()->getTerminator();
468   EXPECT_EQ(CancelBBTI->getNumSuccessors(), 2U);
469   EXPECT_EQ(CancelBBTI->getSuccessor(0)->size(), 1U);
470   EXPECT_EQ(CancelBBTI->getSuccessor(0)->getUniqueSuccessor(),
471             NewIP.getBlock());
472   EXPECT_EQ(CancelBBTI->getSuccessor(1)->size(), 3U);
473   CallInst *GTID1 = dyn_cast<CallInst>(&CancelBBTI->getSuccessor(1)->front());
474   EXPECT_NE(GTID1, nullptr);
475   EXPECT_EQ(GTID1->arg_size(), 1U);
476   EXPECT_EQ(GTID1->getCalledFunction()->getName(), "__kmpc_global_thread_num");
477   EXPECT_FALSE(GTID1->getCalledFunction()->doesNotAccessMemory());
478   EXPECT_FALSE(GTID1->getCalledFunction()->doesNotFreeMemory());
479   CallInst *Barrier = dyn_cast<CallInst>(GTID1->getNextNode());
480   EXPECT_NE(Barrier, nullptr);
481   EXPECT_EQ(Barrier->arg_size(), 2U);
482   EXPECT_EQ(Barrier->getCalledFunction()->getName(), "__kmpc_cancel_barrier");
483   EXPECT_FALSE(Barrier->getCalledFunction()->doesNotAccessMemory());
484   EXPECT_FALSE(Barrier->getCalledFunction()->doesNotFreeMemory());
485   EXPECT_EQ(Barrier->getNumUses(), 0U);
486   EXPECT_EQ(CancelBBTI->getSuccessor(1)->getTerminator()->getNumSuccessors(),
487             1U);
488   EXPECT_EQ(CancelBBTI->getSuccessor(1)->getTerminator()->getSuccessor(0), CBB);
489 
490   EXPECT_EQ(cast<CallInst>(Cancel)->getArgOperand(1), GTID);
491 
492   OMPBuilder.popFinalizationCB();
493 
494   Builder.CreateUnreachable();
495   EXPECT_FALSE(verifyModule(*M, &errs()));
496 }
497 
498 TEST_F(OpenMPIRBuilderTest, CreateCancelBarrier) {
499   using InsertPointTy = OpenMPIRBuilder::InsertPointTy;
500   OpenMPIRBuilder OMPBuilder(*M);
501   OMPBuilder.initialize();
502 
503   BasicBlock *CBB = BasicBlock::Create(Ctx, "", F);
504   new UnreachableInst(Ctx, CBB);
505   auto FiniCB = [&](InsertPointTy IP) {
506     ASSERT_NE(IP.getBlock(), nullptr);
507     ASSERT_EQ(IP.getBlock()->end(), IP.getPoint());
508     BranchInst::Create(CBB, IP.getBlock());
509   };
510   OMPBuilder.pushFinalizationCB({FiniCB, OMPD_parallel, true});
511 
512   IRBuilder<> Builder(BB);
513 
514   OpenMPIRBuilder::LocationDescription Loc({Builder.saveIP()});
515   auto NewIP = OMPBuilder.createBarrier(Loc, OMPD_for);
516   Builder.restoreIP(NewIP);
517   EXPECT_FALSE(M->global_empty());
518   EXPECT_EQ(M->size(), 3U);
519   EXPECT_EQ(F->size(), 4U);
520   EXPECT_EQ(BB->size(), 4U);
521 
522   CallInst *GTID = dyn_cast<CallInst>(&BB->front());
523   EXPECT_NE(GTID, nullptr);
524   EXPECT_EQ(GTID->arg_size(), 1U);
525   EXPECT_EQ(GTID->getCalledFunction()->getName(), "__kmpc_global_thread_num");
526   EXPECT_FALSE(GTID->getCalledFunction()->doesNotAccessMemory());
527   EXPECT_FALSE(GTID->getCalledFunction()->doesNotFreeMemory());
528 
529   CallInst *Barrier = dyn_cast<CallInst>(GTID->getNextNode());
530   EXPECT_NE(Barrier, nullptr);
531   EXPECT_EQ(Barrier->arg_size(), 2U);
532   EXPECT_EQ(Barrier->getCalledFunction()->getName(), "__kmpc_cancel_barrier");
533   EXPECT_FALSE(Barrier->getCalledFunction()->doesNotAccessMemory());
534   EXPECT_FALSE(Barrier->getCalledFunction()->doesNotFreeMemory());
535   EXPECT_EQ(Barrier->getNumUses(), 1U);
536   Instruction *BarrierBBTI = Barrier->getParent()->getTerminator();
537   EXPECT_EQ(BarrierBBTI->getNumSuccessors(), 2U);
538   EXPECT_EQ(BarrierBBTI->getSuccessor(0), NewIP.getBlock());
539   EXPECT_EQ(BarrierBBTI->getSuccessor(1)->size(), 1U);
540   EXPECT_EQ(BarrierBBTI->getSuccessor(1)->getTerminator()->getNumSuccessors(),
541             1U);
542   EXPECT_EQ(BarrierBBTI->getSuccessor(1)->getTerminator()->getSuccessor(0),
543             CBB);
544 
545   EXPECT_EQ(cast<CallInst>(Barrier)->getArgOperand(1), GTID);
546 
547   OMPBuilder.popFinalizationCB();
548 
549   Builder.CreateUnreachable();
550   EXPECT_FALSE(verifyModule(*M, &errs()));
551 }
552 
553 TEST_F(OpenMPIRBuilderTest, DbgLoc) {
554   OpenMPIRBuilder OMPBuilder(*M);
555   OMPBuilder.initialize();
556   F->setName("func");
557 
558   IRBuilder<> Builder(BB);
559 
560   OpenMPIRBuilder::LocationDescription Loc({Builder.saveIP(), DL});
561   OMPBuilder.createBarrier(Loc, OMPD_for);
562   CallInst *GTID = dyn_cast<CallInst>(&BB->front());
563   CallInst *Barrier = dyn_cast<CallInst>(GTID->getNextNode());
564   EXPECT_EQ(GTID->getDebugLoc(), DL);
565   EXPECT_EQ(Barrier->getDebugLoc(), DL);
566   EXPECT_TRUE(isa<GlobalVariable>(Barrier->getOperand(0)));
567   if (!isa<GlobalVariable>(Barrier->getOperand(0)))
568     return;
569   GlobalVariable *Ident = cast<GlobalVariable>(Barrier->getOperand(0));
570   EXPECT_TRUE(Ident->hasInitializer());
571   if (!Ident->hasInitializer())
572     return;
573   Constant *Initializer = Ident->getInitializer();
574   EXPECT_TRUE(
575       isa<GlobalVariable>(Initializer->getOperand(4)->stripPointerCasts()));
576   GlobalVariable *SrcStrGlob =
577       cast<GlobalVariable>(Initializer->getOperand(4)->stripPointerCasts());
578   if (!SrcStrGlob)
579     return;
580   EXPECT_TRUE(isa<ConstantDataArray>(SrcStrGlob->getInitializer()));
581   ConstantDataArray *SrcSrc =
582       dyn_cast<ConstantDataArray>(SrcStrGlob->getInitializer());
583   if (!SrcSrc)
584     return;
585   EXPECT_EQ(SrcSrc->getAsCString(), ";/src/test.dbg;foo;3;7;;");
586 }
587 
588 TEST_F(OpenMPIRBuilderTest, ParallelSimple) {
589   using InsertPointTy = OpenMPIRBuilder::InsertPointTy;
590   OpenMPIRBuilder OMPBuilder(*M);
591   OMPBuilder.initialize();
592   F->setName("func");
593   IRBuilder<> Builder(BB);
594 
595   BasicBlock *EnterBB = BasicBlock::Create(Ctx, "parallel.enter", F);
596   Builder.CreateBr(EnterBB);
597   Builder.SetInsertPoint(EnterBB);
598   OpenMPIRBuilder::LocationDescription Loc({Builder.saveIP(), DL});
599 
600   AllocaInst *PrivAI = nullptr;
601 
602   unsigned NumBodiesGenerated = 0;
603   unsigned NumPrivatizedVars = 0;
604   unsigned NumFinalizationPoints = 0;
605 
606   auto BodyGenCB = [&](InsertPointTy AllocaIP, InsertPointTy CodeGenIP,
607                        BasicBlock &ContinuationIP) {
608     ++NumBodiesGenerated;
609 
610     Builder.restoreIP(AllocaIP);
611     PrivAI = Builder.CreateAlloca(F->arg_begin()->getType());
612     Builder.CreateStore(F->arg_begin(), PrivAI);
613 
614     Builder.restoreIP(CodeGenIP);
615     Value *PrivLoad =
616         Builder.CreateLoad(PrivAI->getAllocatedType(), PrivAI, "local.use");
617     Value *Cmp = Builder.CreateICmpNE(F->arg_begin(), PrivLoad);
618     Instruction *ThenTerm, *ElseTerm;
619     SplitBlockAndInsertIfThenElse(Cmp, CodeGenIP.getBlock()->getTerminator(),
620                                   &ThenTerm, &ElseTerm);
621 
622     Builder.SetInsertPoint(ThenTerm);
623     Builder.CreateBr(&ContinuationIP);
624     ThenTerm->eraseFromParent();
625   };
626 
627   auto PrivCB = [&](InsertPointTy AllocaIP, InsertPointTy CodeGenIP,
628                     Value &Orig, Value &Inner,
629                     Value *&ReplacementValue) -> InsertPointTy {
630     ++NumPrivatizedVars;
631 
632     if (!isa<AllocaInst>(Orig)) {
633       EXPECT_EQ(&Orig, F->arg_begin());
634       ReplacementValue = &Inner;
635       return CodeGenIP;
636     }
637 
638     // Since the original value is an allocation, it has a pointer type and
639     // therefore no additional wrapping should happen.
640     EXPECT_EQ(&Orig, &Inner);
641 
642     // Trivial copy (=firstprivate).
643     Builder.restoreIP(AllocaIP);
644     Type *VTy = ReplacementValue->getType();
645     Value *V = Builder.CreateLoad(VTy, &Inner, Orig.getName() + ".reload");
646     ReplacementValue = Builder.CreateAlloca(VTy, 0, Orig.getName() + ".copy");
647     Builder.restoreIP(CodeGenIP);
648     Builder.CreateStore(V, ReplacementValue);
649     return CodeGenIP;
650   };
651 
652   auto FiniCB = [&](InsertPointTy CodeGenIP) { ++NumFinalizationPoints; };
653 
654   IRBuilder<>::InsertPoint AllocaIP(&F->getEntryBlock(),
655                                     F->getEntryBlock().getFirstInsertionPt());
656   IRBuilder<>::InsertPoint AfterIP =
657       OMPBuilder.createParallel(Loc, AllocaIP, BodyGenCB, PrivCB, FiniCB,
658                                 nullptr, nullptr, OMP_PROC_BIND_default, false);
659   EXPECT_EQ(NumBodiesGenerated, 1U);
660   EXPECT_EQ(NumPrivatizedVars, 1U);
661   EXPECT_EQ(NumFinalizationPoints, 1U);
662 
663   Builder.restoreIP(AfterIP);
664   Builder.CreateRetVoid();
665 
666   OMPBuilder.finalize();
667 
668   EXPECT_NE(PrivAI, nullptr);
669   Function *OutlinedFn = PrivAI->getFunction();
670   EXPECT_NE(F, OutlinedFn);
671   EXPECT_FALSE(verifyModule(*M, &errs()));
672   EXPECT_TRUE(OutlinedFn->hasFnAttribute(Attribute::NoUnwind));
673   EXPECT_TRUE(OutlinedFn->hasFnAttribute(Attribute::NoRecurse));
674   EXPECT_TRUE(OutlinedFn->hasParamAttribute(0, Attribute::NoAlias));
675   EXPECT_TRUE(OutlinedFn->hasParamAttribute(1, Attribute::NoAlias));
676 
677   EXPECT_TRUE(OutlinedFn->hasInternalLinkage());
678   EXPECT_EQ(OutlinedFn->arg_size(), 3U);
679 
680   EXPECT_EQ(&OutlinedFn->getEntryBlock(), PrivAI->getParent());
681   EXPECT_EQ(OutlinedFn->getNumUses(), 1U);
682   User *Usr = OutlinedFn->user_back();
683   ASSERT_TRUE(isa<ConstantExpr>(Usr));
684   CallInst *ForkCI = dyn_cast<CallInst>(Usr->user_back());
685   ASSERT_NE(ForkCI, nullptr);
686 
687   EXPECT_EQ(ForkCI->getCalledFunction()->getName(), "__kmpc_fork_call");
688   EXPECT_EQ(ForkCI->arg_size(), 4U);
689   EXPECT_TRUE(isa<GlobalVariable>(ForkCI->getArgOperand(0)));
690   EXPECT_EQ(ForkCI->getArgOperand(1),
691             ConstantInt::get(Type::getInt32Ty(Ctx), 1U));
692   EXPECT_EQ(ForkCI->getArgOperand(2), Usr);
693   Value *StoredValue =
694       findStoredValueInAggregateAt(Ctx, ForkCI->getArgOperand(3), 0);
695   EXPECT_EQ(StoredValue, F->arg_begin());
696 }
697 
698 TEST_F(OpenMPIRBuilderTest, ParallelNested) {
699   using InsertPointTy = OpenMPIRBuilder::InsertPointTy;
700   OpenMPIRBuilder OMPBuilder(*M);
701   OMPBuilder.initialize();
702   F->setName("func");
703   IRBuilder<> Builder(BB);
704 
705   BasicBlock *EnterBB = BasicBlock::Create(Ctx, "parallel.enter", F);
706   Builder.CreateBr(EnterBB);
707   Builder.SetInsertPoint(EnterBB);
708   OpenMPIRBuilder::LocationDescription Loc({Builder.saveIP(), DL});
709 
710   unsigned NumInnerBodiesGenerated = 0;
711   unsigned NumOuterBodiesGenerated = 0;
712   unsigned NumFinalizationPoints = 0;
713 
714   auto InnerBodyGenCB = [&](InsertPointTy AllocaIP, InsertPointTy CodeGenIP,
715                             BasicBlock &ContinuationIP) {
716     ++NumInnerBodiesGenerated;
717   };
718 
719   auto PrivCB = [&](InsertPointTy AllocaIP, InsertPointTy CodeGenIP,
720                     Value &Orig, Value &Inner,
721                     Value *&ReplacementValue) -> InsertPointTy {
722     // Trivial copy (=firstprivate).
723     Builder.restoreIP(AllocaIP);
724     Type *VTy = ReplacementValue->getType();
725     Value *V = Builder.CreateLoad(VTy, &Inner, Orig.getName() + ".reload");
726     ReplacementValue = Builder.CreateAlloca(VTy, 0, Orig.getName() + ".copy");
727     Builder.restoreIP(CodeGenIP);
728     Builder.CreateStore(V, ReplacementValue);
729     return CodeGenIP;
730   };
731 
732   auto FiniCB = [&](InsertPointTy CodeGenIP) { ++NumFinalizationPoints; };
733 
734   auto OuterBodyGenCB = [&](InsertPointTy AllocaIP, InsertPointTy CodeGenIP,
735                             BasicBlock &ContinuationIP) {
736     ++NumOuterBodiesGenerated;
737     Builder.restoreIP(CodeGenIP);
738     BasicBlock *CGBB = CodeGenIP.getBlock();
739     BasicBlock *NewBB = SplitBlock(CGBB, &*CodeGenIP.getPoint());
740     CGBB->getTerminator()->eraseFromParent();
741     ;
742 
743     IRBuilder<>::InsertPoint AfterIP = OMPBuilder.createParallel(
744         InsertPointTy(CGBB, CGBB->end()), AllocaIP, InnerBodyGenCB, PrivCB,
745         FiniCB, nullptr, nullptr, OMP_PROC_BIND_default, false);
746 
747     Builder.restoreIP(AfterIP);
748     Builder.CreateBr(NewBB);
749   };
750 
751   IRBuilder<>::InsertPoint AllocaIP(&F->getEntryBlock(),
752                                     F->getEntryBlock().getFirstInsertionPt());
753   IRBuilder<>::InsertPoint AfterIP =
754       OMPBuilder.createParallel(Loc, AllocaIP, OuterBodyGenCB, PrivCB, FiniCB,
755                                 nullptr, nullptr, OMP_PROC_BIND_default, false);
756 
757   EXPECT_EQ(NumInnerBodiesGenerated, 1U);
758   EXPECT_EQ(NumOuterBodiesGenerated, 1U);
759   EXPECT_EQ(NumFinalizationPoints, 2U);
760 
761   Builder.restoreIP(AfterIP);
762   Builder.CreateRetVoid();
763 
764   OMPBuilder.finalize();
765 
766   EXPECT_EQ(M->size(), 5U);
767   for (Function &OutlinedFn : *M) {
768     if (F == &OutlinedFn || OutlinedFn.isDeclaration())
769       continue;
770     EXPECT_FALSE(verifyModule(*M, &errs()));
771     EXPECT_TRUE(OutlinedFn.hasFnAttribute(Attribute::NoUnwind));
772     EXPECT_TRUE(OutlinedFn.hasFnAttribute(Attribute::NoRecurse));
773     EXPECT_TRUE(OutlinedFn.hasParamAttribute(0, Attribute::NoAlias));
774     EXPECT_TRUE(OutlinedFn.hasParamAttribute(1, Attribute::NoAlias));
775 
776     EXPECT_TRUE(OutlinedFn.hasInternalLinkage());
777     EXPECT_EQ(OutlinedFn.arg_size(), 2U);
778 
779     EXPECT_EQ(OutlinedFn.getNumUses(), 1U);
780     User *Usr = OutlinedFn.user_back();
781     ASSERT_TRUE(isa<ConstantExpr>(Usr));
782     CallInst *ForkCI = dyn_cast<CallInst>(Usr->user_back());
783     ASSERT_NE(ForkCI, nullptr);
784 
785     EXPECT_EQ(ForkCI->getCalledFunction()->getName(), "__kmpc_fork_call");
786     EXPECT_EQ(ForkCI->arg_size(), 3U);
787     EXPECT_TRUE(isa<GlobalVariable>(ForkCI->getArgOperand(0)));
788     EXPECT_EQ(ForkCI->getArgOperand(1),
789               ConstantInt::get(Type::getInt32Ty(Ctx), 0U));
790     EXPECT_EQ(ForkCI->getArgOperand(2), Usr);
791   }
792 }
793 
794 TEST_F(OpenMPIRBuilderTest, ParallelNested2Inner) {
795   using InsertPointTy = OpenMPIRBuilder::InsertPointTy;
796   OpenMPIRBuilder OMPBuilder(*M);
797   OMPBuilder.initialize();
798   F->setName("func");
799   IRBuilder<> Builder(BB);
800 
801   BasicBlock *EnterBB = BasicBlock::Create(Ctx, "parallel.enter", F);
802   Builder.CreateBr(EnterBB);
803   Builder.SetInsertPoint(EnterBB);
804   OpenMPIRBuilder::LocationDescription Loc({Builder.saveIP(), DL});
805 
806   unsigned NumInnerBodiesGenerated = 0;
807   unsigned NumOuterBodiesGenerated = 0;
808   unsigned NumFinalizationPoints = 0;
809 
810   auto InnerBodyGenCB = [&](InsertPointTy AllocaIP, InsertPointTy CodeGenIP,
811                             BasicBlock &ContinuationIP) {
812     ++NumInnerBodiesGenerated;
813   };
814 
815   auto PrivCB = [&](InsertPointTy AllocaIP, InsertPointTy CodeGenIP,
816                     Value &Orig, Value &Inner,
817                     Value *&ReplacementValue) -> InsertPointTy {
818     // Trivial copy (=firstprivate).
819     Builder.restoreIP(AllocaIP);
820     Type *VTy = ReplacementValue->getType();
821     Value *V = Builder.CreateLoad(VTy, &Inner, Orig.getName() + ".reload");
822     ReplacementValue = Builder.CreateAlloca(VTy, 0, Orig.getName() + ".copy");
823     Builder.restoreIP(CodeGenIP);
824     Builder.CreateStore(V, ReplacementValue);
825     return CodeGenIP;
826   };
827 
828   auto FiniCB = [&](InsertPointTy CodeGenIP) { ++NumFinalizationPoints; };
829 
830   auto OuterBodyGenCB = [&](InsertPointTy AllocaIP, InsertPointTy CodeGenIP,
831                             BasicBlock &ContinuationIP) {
832     ++NumOuterBodiesGenerated;
833     Builder.restoreIP(CodeGenIP);
834     BasicBlock *CGBB = CodeGenIP.getBlock();
835     BasicBlock *NewBB1 = SplitBlock(CGBB, &*CodeGenIP.getPoint());
836     BasicBlock *NewBB2 = SplitBlock(NewBB1, &*NewBB1->getFirstInsertionPt());
837     CGBB->getTerminator()->eraseFromParent();
838     ;
839     NewBB1->getTerminator()->eraseFromParent();
840     ;
841 
842     IRBuilder<>::InsertPoint AfterIP1 = OMPBuilder.createParallel(
843         InsertPointTy(CGBB, CGBB->end()), AllocaIP, InnerBodyGenCB, PrivCB,
844         FiniCB, nullptr, nullptr, OMP_PROC_BIND_default, false);
845 
846     Builder.restoreIP(AfterIP1);
847     Builder.CreateBr(NewBB1);
848 
849     IRBuilder<>::InsertPoint AfterIP2 = OMPBuilder.createParallel(
850         InsertPointTy(NewBB1, NewBB1->end()), AllocaIP, InnerBodyGenCB, PrivCB,
851         FiniCB, nullptr, nullptr, OMP_PROC_BIND_default, false);
852 
853     Builder.restoreIP(AfterIP2);
854     Builder.CreateBr(NewBB2);
855   };
856 
857   IRBuilder<>::InsertPoint AllocaIP(&F->getEntryBlock(),
858                                     F->getEntryBlock().getFirstInsertionPt());
859   IRBuilder<>::InsertPoint AfterIP =
860       OMPBuilder.createParallel(Loc, AllocaIP, OuterBodyGenCB, PrivCB, FiniCB,
861                                 nullptr, nullptr, OMP_PROC_BIND_default, false);
862 
863   EXPECT_EQ(NumInnerBodiesGenerated, 2U);
864   EXPECT_EQ(NumOuterBodiesGenerated, 1U);
865   EXPECT_EQ(NumFinalizationPoints, 3U);
866 
867   Builder.restoreIP(AfterIP);
868   Builder.CreateRetVoid();
869 
870   OMPBuilder.finalize();
871 
872   EXPECT_EQ(M->size(), 6U);
873   for (Function &OutlinedFn : *M) {
874     if (F == &OutlinedFn || OutlinedFn.isDeclaration())
875       continue;
876     EXPECT_FALSE(verifyModule(*M, &errs()));
877     EXPECT_TRUE(OutlinedFn.hasFnAttribute(Attribute::NoUnwind));
878     EXPECT_TRUE(OutlinedFn.hasFnAttribute(Attribute::NoRecurse));
879     EXPECT_TRUE(OutlinedFn.hasParamAttribute(0, Attribute::NoAlias));
880     EXPECT_TRUE(OutlinedFn.hasParamAttribute(1, Attribute::NoAlias));
881 
882     EXPECT_TRUE(OutlinedFn.hasInternalLinkage());
883     EXPECT_EQ(OutlinedFn.arg_size(), 2U);
884 
885     unsigned NumAllocas = 0;
886     for (Instruction &I : instructions(OutlinedFn))
887       NumAllocas += isa<AllocaInst>(I);
888     EXPECT_EQ(NumAllocas, 1U);
889 
890     EXPECT_EQ(OutlinedFn.getNumUses(), 1U);
891     User *Usr = OutlinedFn.user_back();
892     ASSERT_TRUE(isa<ConstantExpr>(Usr));
893     CallInst *ForkCI = dyn_cast<CallInst>(Usr->user_back());
894     ASSERT_NE(ForkCI, nullptr);
895 
896     EXPECT_EQ(ForkCI->getCalledFunction()->getName(), "__kmpc_fork_call");
897     EXPECT_EQ(ForkCI->arg_size(), 3U);
898     EXPECT_TRUE(isa<GlobalVariable>(ForkCI->getArgOperand(0)));
899     EXPECT_EQ(ForkCI->getArgOperand(1),
900               ConstantInt::get(Type::getInt32Ty(Ctx), 0U));
901     EXPECT_EQ(ForkCI->getArgOperand(2), Usr);
902   }
903 }
904 
905 TEST_F(OpenMPIRBuilderTest, ParallelIfCond) {
906   using InsertPointTy = OpenMPIRBuilder::InsertPointTy;
907   OpenMPIRBuilder OMPBuilder(*M);
908   OMPBuilder.initialize();
909   F->setName("func");
910   IRBuilder<> Builder(BB);
911 
912   BasicBlock *EnterBB = BasicBlock::Create(Ctx, "parallel.enter", F);
913   Builder.CreateBr(EnterBB);
914   Builder.SetInsertPoint(EnterBB);
915   OpenMPIRBuilder::LocationDescription Loc({Builder.saveIP(), DL});
916 
917   AllocaInst *PrivAI = nullptr;
918 
919   unsigned NumBodiesGenerated = 0;
920   unsigned NumPrivatizedVars = 0;
921   unsigned NumFinalizationPoints = 0;
922 
923   auto BodyGenCB = [&](InsertPointTy AllocaIP, InsertPointTy CodeGenIP,
924                        BasicBlock &ContinuationIP) {
925     ++NumBodiesGenerated;
926 
927     Builder.restoreIP(AllocaIP);
928     PrivAI = Builder.CreateAlloca(F->arg_begin()->getType());
929     Builder.CreateStore(F->arg_begin(), PrivAI);
930 
931     Builder.restoreIP(CodeGenIP);
932     Value *PrivLoad =
933         Builder.CreateLoad(PrivAI->getAllocatedType(), PrivAI, "local.use");
934     Value *Cmp = Builder.CreateICmpNE(F->arg_begin(), PrivLoad);
935     Instruction *ThenTerm, *ElseTerm;
936     SplitBlockAndInsertIfThenElse(Cmp, CodeGenIP.getBlock()->getTerminator(),
937                                   &ThenTerm, &ElseTerm);
938 
939     Builder.SetInsertPoint(ThenTerm);
940     Builder.CreateBr(&ContinuationIP);
941     ThenTerm->eraseFromParent();
942   };
943 
944   auto PrivCB = [&](InsertPointTy AllocaIP, InsertPointTy CodeGenIP,
945                     Value &Orig, Value &Inner,
946                     Value *&ReplacementValue) -> InsertPointTy {
947     ++NumPrivatizedVars;
948 
949     if (!isa<AllocaInst>(Orig)) {
950       EXPECT_EQ(&Orig, F->arg_begin());
951       ReplacementValue = &Inner;
952       return CodeGenIP;
953     }
954 
955     // Since the original value is an allocation, it has a pointer type and
956     // therefore no additional wrapping should happen.
957     EXPECT_EQ(&Orig, &Inner);
958 
959     // Trivial copy (=firstprivate).
960     Builder.restoreIP(AllocaIP);
961     Type *VTy = ReplacementValue->getType();
962     Value *V = Builder.CreateLoad(VTy, &Inner, Orig.getName() + ".reload");
963     ReplacementValue = Builder.CreateAlloca(VTy, 0, Orig.getName() + ".copy");
964     Builder.restoreIP(CodeGenIP);
965     Builder.CreateStore(V, ReplacementValue);
966     return CodeGenIP;
967   };
968 
969   auto FiniCB = [&](InsertPointTy CodeGenIP) {
970     ++NumFinalizationPoints;
971     // No destructors.
972   };
973 
974   IRBuilder<>::InsertPoint AllocaIP(&F->getEntryBlock(),
975                                     F->getEntryBlock().getFirstInsertionPt());
976   IRBuilder<>::InsertPoint AfterIP =
977       OMPBuilder.createParallel(Loc, AllocaIP, BodyGenCB, PrivCB, FiniCB,
978                                 Builder.CreateIsNotNull(F->arg_begin()),
979                                 nullptr, OMP_PROC_BIND_default, false);
980 
981   EXPECT_EQ(NumBodiesGenerated, 1U);
982   EXPECT_EQ(NumPrivatizedVars, 1U);
983   EXPECT_EQ(NumFinalizationPoints, 1U);
984 
985   Builder.restoreIP(AfterIP);
986   Builder.CreateRetVoid();
987   OMPBuilder.finalize();
988 
989   EXPECT_NE(PrivAI, nullptr);
990   Function *OutlinedFn = PrivAI->getFunction();
991   EXPECT_NE(F, OutlinedFn);
992   EXPECT_FALSE(verifyModule(*M, &errs()));
993 
994   EXPECT_TRUE(OutlinedFn->hasInternalLinkage());
995   EXPECT_EQ(OutlinedFn->arg_size(), 3U);
996 
997   EXPECT_EQ(&OutlinedFn->getEntryBlock(), PrivAI->getParent());
998   ASSERT_EQ(OutlinedFn->getNumUses(), 2U);
999 
1000   CallInst *DirectCI = nullptr;
1001   CallInst *ForkCI = nullptr;
1002   for (User *Usr : OutlinedFn->users()) {
1003     if (isa<CallInst>(Usr)) {
1004       ASSERT_EQ(DirectCI, nullptr);
1005       DirectCI = cast<CallInst>(Usr);
1006     } else {
1007       ASSERT_TRUE(isa<ConstantExpr>(Usr));
1008       ASSERT_EQ(Usr->getNumUses(), 1U);
1009       ASSERT_TRUE(isa<CallInst>(Usr->user_back()));
1010       ForkCI = cast<CallInst>(Usr->user_back());
1011     }
1012   }
1013 
1014   EXPECT_EQ(ForkCI->getCalledFunction()->getName(), "__kmpc_fork_call");
1015   EXPECT_EQ(ForkCI->arg_size(), 4U);
1016   EXPECT_TRUE(isa<GlobalVariable>(ForkCI->getArgOperand(0)));
1017   EXPECT_EQ(ForkCI->getArgOperand(1),
1018             ConstantInt::get(Type::getInt32Ty(Ctx), 1));
1019   Value *StoredForkArg =
1020       findStoredValueInAggregateAt(Ctx, ForkCI->getArgOperand(3), 0);
1021   EXPECT_EQ(StoredForkArg, F->arg_begin());
1022 
1023   EXPECT_EQ(DirectCI->getCalledFunction(), OutlinedFn);
1024   EXPECT_EQ(DirectCI->arg_size(), 3U);
1025   EXPECT_TRUE(isa<AllocaInst>(DirectCI->getArgOperand(0)));
1026   EXPECT_TRUE(isa<AllocaInst>(DirectCI->getArgOperand(1)));
1027   Value *StoredDirectArg =
1028       findStoredValueInAggregateAt(Ctx, DirectCI->getArgOperand(2), 0);
1029   EXPECT_EQ(StoredDirectArg, F->arg_begin());
1030 }
1031 
1032 TEST_F(OpenMPIRBuilderTest, ParallelCancelBarrier) {
1033   using InsertPointTy = OpenMPIRBuilder::InsertPointTy;
1034   OpenMPIRBuilder OMPBuilder(*M);
1035   OMPBuilder.initialize();
1036   F->setName("func");
1037   IRBuilder<> Builder(BB);
1038 
1039   BasicBlock *EnterBB = BasicBlock::Create(Ctx, "parallel.enter", F);
1040   Builder.CreateBr(EnterBB);
1041   Builder.SetInsertPoint(EnterBB);
1042   OpenMPIRBuilder::LocationDescription Loc({Builder.saveIP(), DL});
1043 
1044   unsigned NumBodiesGenerated = 0;
1045   unsigned NumPrivatizedVars = 0;
1046   unsigned NumFinalizationPoints = 0;
1047 
1048   CallInst *CheckedBarrier = nullptr;
1049   auto BodyGenCB = [&](InsertPointTy AllocaIP, InsertPointTy CodeGenIP,
1050                        BasicBlock &ContinuationIP) {
1051     ++NumBodiesGenerated;
1052 
1053     Builder.restoreIP(CodeGenIP);
1054 
1055     // Create three barriers, two cancel barriers but only one checked.
1056     Function *CBFn, *BFn;
1057 
1058     Builder.restoreIP(
1059         OMPBuilder.createBarrier(Builder.saveIP(), OMPD_parallel));
1060 
1061     CBFn = M->getFunction("__kmpc_cancel_barrier");
1062     BFn = M->getFunction("__kmpc_barrier");
1063     ASSERT_NE(CBFn, nullptr);
1064     ASSERT_EQ(BFn, nullptr);
1065     ASSERT_EQ(CBFn->getNumUses(), 1U);
1066     ASSERT_TRUE(isa<CallInst>(CBFn->user_back()));
1067     ASSERT_EQ(CBFn->user_back()->getNumUses(), 1U);
1068     CheckedBarrier = cast<CallInst>(CBFn->user_back());
1069 
1070     Builder.restoreIP(
1071         OMPBuilder.createBarrier(Builder.saveIP(), OMPD_parallel, true));
1072     CBFn = M->getFunction("__kmpc_cancel_barrier");
1073     BFn = M->getFunction("__kmpc_barrier");
1074     ASSERT_NE(CBFn, nullptr);
1075     ASSERT_NE(BFn, nullptr);
1076     ASSERT_EQ(CBFn->getNumUses(), 1U);
1077     ASSERT_EQ(BFn->getNumUses(), 1U);
1078     ASSERT_TRUE(isa<CallInst>(BFn->user_back()));
1079     ASSERT_EQ(BFn->user_back()->getNumUses(), 0U);
1080 
1081     Builder.restoreIP(OMPBuilder.createBarrier(Builder.saveIP(), OMPD_parallel,
1082                                                false, false));
1083     ASSERT_EQ(CBFn->getNumUses(), 2U);
1084     ASSERT_EQ(BFn->getNumUses(), 1U);
1085     ASSERT_TRUE(CBFn->user_back() != CheckedBarrier);
1086     ASSERT_TRUE(isa<CallInst>(CBFn->user_back()));
1087     ASSERT_EQ(CBFn->user_back()->getNumUses(), 0U);
1088   };
1089 
1090   auto PrivCB = [&](InsertPointTy, InsertPointTy, Value &V, Value &,
1091                     Value *&) -> InsertPointTy {
1092     ++NumPrivatizedVars;
1093     llvm_unreachable("No privatization callback call expected!");
1094   };
1095 
1096   FunctionType *FakeDestructorTy =
1097       FunctionType::get(Type::getVoidTy(Ctx), {Type::getInt32Ty(Ctx)},
1098                         /*isVarArg=*/false);
1099   auto *FakeDestructor = Function::Create(
1100       FakeDestructorTy, Function::ExternalLinkage, "fakeDestructor", M.get());
1101 
1102   auto FiniCB = [&](InsertPointTy IP) {
1103     ++NumFinalizationPoints;
1104     Builder.restoreIP(IP);
1105     Builder.CreateCall(FakeDestructor,
1106                        {Builder.getInt32(NumFinalizationPoints)});
1107   };
1108 
1109   IRBuilder<>::InsertPoint AllocaIP(&F->getEntryBlock(),
1110                                     F->getEntryBlock().getFirstInsertionPt());
1111   IRBuilder<>::InsertPoint AfterIP =
1112       OMPBuilder.createParallel(Loc, AllocaIP, BodyGenCB, PrivCB, FiniCB,
1113                                 Builder.CreateIsNotNull(F->arg_begin()),
1114                                 nullptr, OMP_PROC_BIND_default, true);
1115 
1116   EXPECT_EQ(NumBodiesGenerated, 1U);
1117   EXPECT_EQ(NumPrivatizedVars, 0U);
1118   EXPECT_EQ(NumFinalizationPoints, 2U);
1119   EXPECT_EQ(FakeDestructor->getNumUses(), 2U);
1120 
1121   Builder.restoreIP(AfterIP);
1122   Builder.CreateRetVoid();
1123   OMPBuilder.finalize();
1124 
1125   EXPECT_FALSE(verifyModule(*M, &errs()));
1126 
1127   BasicBlock *ExitBB = nullptr;
1128   for (const User *Usr : FakeDestructor->users()) {
1129     const CallInst *CI = dyn_cast<CallInst>(Usr);
1130     ASSERT_EQ(CI->getCalledFunction(), FakeDestructor);
1131     ASSERT_TRUE(isa<BranchInst>(CI->getNextNode()));
1132     ASSERT_EQ(CI->getNextNode()->getNumSuccessors(), 1U);
1133     if (ExitBB)
1134       ASSERT_EQ(CI->getNextNode()->getSuccessor(0), ExitBB);
1135     else
1136       ExitBB = CI->getNextNode()->getSuccessor(0);
1137     ASSERT_EQ(ExitBB->size(), 1U);
1138     if (!isa<ReturnInst>(ExitBB->front())) {
1139       ASSERT_TRUE(isa<BranchInst>(ExitBB->front()));
1140       ASSERT_EQ(cast<BranchInst>(ExitBB->front()).getNumSuccessors(), 1U);
1141       ASSERT_TRUE(isa<ReturnInst>(
1142           cast<BranchInst>(ExitBB->front()).getSuccessor(0)->front()));
1143     }
1144   }
1145 }
1146 
1147 TEST_F(OpenMPIRBuilderTest, ParallelForwardAsPointers) {
1148   OpenMPIRBuilder OMPBuilder(*M);
1149   OMPBuilder.initialize();
1150   F->setName("func");
1151   IRBuilder<> Builder(BB);
1152   OpenMPIRBuilder::LocationDescription Loc({Builder.saveIP(), DL});
1153   using InsertPointTy = OpenMPIRBuilder::InsertPointTy;
1154 
1155   Type *I32Ty = Type::getInt32Ty(M->getContext());
1156   Type *I32PtrTy = Type::getInt32PtrTy(M->getContext());
1157   Type *StructTy = StructType::get(I32Ty, I32PtrTy);
1158   Type *StructPtrTy = StructTy->getPointerTo();
1159   StructType *ArgStructTy =
1160       StructType::get(I32PtrTy, StructPtrTy, I32PtrTy, StructPtrTy);
1161   Type *VoidTy = Type::getVoidTy(M->getContext());
1162   FunctionCallee RetI32Func = M->getOrInsertFunction("ret_i32", I32Ty);
1163   FunctionCallee TakeI32Func =
1164       M->getOrInsertFunction("take_i32", VoidTy, I32Ty);
1165   FunctionCallee RetI32PtrFunc = M->getOrInsertFunction("ret_i32ptr", I32PtrTy);
1166   FunctionCallee TakeI32PtrFunc =
1167       M->getOrInsertFunction("take_i32ptr", VoidTy, I32PtrTy);
1168   FunctionCallee RetStructFunc = M->getOrInsertFunction("ret_struct", StructTy);
1169   FunctionCallee TakeStructFunc =
1170       M->getOrInsertFunction("take_struct", VoidTy, StructTy);
1171   FunctionCallee RetStructPtrFunc =
1172       M->getOrInsertFunction("ret_structptr", StructPtrTy);
1173   FunctionCallee TakeStructPtrFunc =
1174       M->getOrInsertFunction("take_structPtr", VoidTy, StructPtrTy);
1175   Value *I32Val = Builder.CreateCall(RetI32Func);
1176   Value *I32PtrVal = Builder.CreateCall(RetI32PtrFunc);
1177   Value *StructVal = Builder.CreateCall(RetStructFunc);
1178   Value *StructPtrVal = Builder.CreateCall(RetStructPtrFunc);
1179 
1180   Instruction *Internal;
1181   auto BodyGenCB = [&](InsertPointTy AllocaIP, InsertPointTy CodeGenIP,
1182                        BasicBlock &ContinuationBB) {
1183     IRBuilder<>::InsertPointGuard Guard(Builder);
1184     Builder.restoreIP(CodeGenIP);
1185     Internal = Builder.CreateCall(TakeI32Func, I32Val);
1186     Builder.CreateCall(TakeI32PtrFunc, I32PtrVal);
1187     Builder.CreateCall(TakeStructFunc, StructVal);
1188     Builder.CreateCall(TakeStructPtrFunc, StructPtrVal);
1189   };
1190   auto PrivCB = [&](InsertPointTy AllocaIP, InsertPointTy CodeGenIP, Value &,
1191                     Value &Inner, Value *&ReplacementValue) {
1192     ReplacementValue = &Inner;
1193     return CodeGenIP;
1194   };
1195   auto FiniCB = [](InsertPointTy) {};
1196 
1197   IRBuilder<>::InsertPoint AllocaIP(&F->getEntryBlock(),
1198                                     F->getEntryBlock().getFirstInsertionPt());
1199   IRBuilder<>::InsertPoint AfterIP =
1200       OMPBuilder.createParallel(Loc, AllocaIP, BodyGenCB, PrivCB, FiniCB,
1201                                 nullptr, nullptr, OMP_PROC_BIND_default, false);
1202   Builder.restoreIP(AfterIP);
1203   Builder.CreateRetVoid();
1204 
1205   OMPBuilder.finalize();
1206 
1207   EXPECT_FALSE(verifyModule(*M, &errs()));
1208   Function *OutlinedFn = Internal->getFunction();
1209 
1210   Type *Arg2Type = OutlinedFn->getArg(2)->getType();
1211   EXPECT_TRUE(Arg2Type->isPointerTy());
1212   EXPECT_TRUE(
1213       cast<PointerType>(Arg2Type)->isOpaqueOrPointeeTypeMatches(ArgStructTy));
1214 }
1215 
1216 TEST_F(OpenMPIRBuilderTest, CanonicalLoopSimple) {
1217   using InsertPointTy = OpenMPIRBuilder::InsertPointTy;
1218   OpenMPIRBuilder OMPBuilder(*M);
1219   OMPBuilder.initialize();
1220   IRBuilder<> Builder(BB);
1221   OpenMPIRBuilder::LocationDescription Loc({Builder.saveIP(), DL});
1222   Value *TripCount = F->getArg(0);
1223 
1224   unsigned NumBodiesGenerated = 0;
1225   auto LoopBodyGenCB = [&](InsertPointTy CodeGenIP, llvm::Value *LC) {
1226     NumBodiesGenerated += 1;
1227 
1228     Builder.restoreIP(CodeGenIP);
1229 
1230     Value *Cmp = Builder.CreateICmpEQ(LC, TripCount);
1231     Instruction *ThenTerm, *ElseTerm;
1232     SplitBlockAndInsertIfThenElse(Cmp, CodeGenIP.getBlock()->getTerminator(),
1233                                   &ThenTerm, &ElseTerm);
1234   };
1235 
1236   CanonicalLoopInfo *Loop =
1237       OMPBuilder.createCanonicalLoop(Loc, LoopBodyGenCB, TripCount);
1238 
1239   Builder.restoreIP(Loop->getAfterIP());
1240   ReturnInst *RetInst = Builder.CreateRetVoid();
1241   OMPBuilder.finalize();
1242 
1243   Loop->assertOK();
1244   EXPECT_FALSE(verifyModule(*M, &errs()));
1245 
1246   EXPECT_EQ(NumBodiesGenerated, 1U);
1247 
1248   // Verify control flow structure (in addition to Loop->assertOK()).
1249   EXPECT_EQ(Loop->getPreheader()->getSinglePredecessor(), &F->getEntryBlock());
1250   EXPECT_EQ(Loop->getAfter(), Builder.GetInsertBlock());
1251 
1252   Instruction *IndVar = Loop->getIndVar();
1253   EXPECT_TRUE(isa<PHINode>(IndVar));
1254   EXPECT_EQ(IndVar->getType(), TripCount->getType());
1255   EXPECT_EQ(IndVar->getParent(), Loop->getHeader());
1256 
1257   EXPECT_EQ(Loop->getTripCount(), TripCount);
1258 
1259   BasicBlock *Body = Loop->getBody();
1260   Instruction *CmpInst = &Body->getInstList().front();
1261   EXPECT_TRUE(isa<ICmpInst>(CmpInst));
1262   EXPECT_EQ(CmpInst->getOperand(0), IndVar);
1263 
1264   BasicBlock *LatchPred = Loop->getLatch()->getSinglePredecessor();
1265   EXPECT_TRUE(llvm::all_of(successors(Body), [=](BasicBlock *SuccBB) {
1266     return SuccBB->getSingleSuccessor() == LatchPred;
1267   }));
1268 
1269   EXPECT_EQ(&Loop->getAfter()->front(), RetInst);
1270 }
1271 
1272 TEST_F(OpenMPIRBuilderTest, CanonicalLoopBounds) {
1273   using InsertPointTy = OpenMPIRBuilder::InsertPointTy;
1274   OpenMPIRBuilder OMPBuilder(*M);
1275   OMPBuilder.initialize();
1276   IRBuilder<> Builder(BB);
1277 
1278   // Check the trip count is computed correctly. We generate the canonical loop
1279   // but rely on the IRBuilder's constant folder to compute the final result
1280   // since all inputs are constant. To verify overflow situations, limit the
1281   // trip count / loop counter widths to 16 bits.
1282   auto EvalTripCount = [&](int64_t Start, int64_t Stop, int64_t Step,
1283                            bool IsSigned, bool InclusiveStop) -> int64_t {
1284     OpenMPIRBuilder::LocationDescription Loc({Builder.saveIP(), DL});
1285     Type *LCTy = Type::getInt16Ty(Ctx);
1286     Value *StartVal = ConstantInt::get(LCTy, Start);
1287     Value *StopVal = ConstantInt::get(LCTy, Stop);
1288     Value *StepVal = ConstantInt::get(LCTy, Step);
1289     auto LoopBodyGenCB = [&](InsertPointTy CodeGenIP, llvm::Value *LC) {};
1290     CanonicalLoopInfo *Loop =
1291         OMPBuilder.createCanonicalLoop(Loc, LoopBodyGenCB, StartVal, StopVal,
1292                                        StepVal, IsSigned, InclusiveStop);
1293     Loop->assertOK();
1294     Builder.restoreIP(Loop->getAfterIP());
1295     Value *TripCount = Loop->getTripCount();
1296     return cast<ConstantInt>(TripCount)->getValue().getZExtValue();
1297   };
1298 
1299   EXPECT_EQ(EvalTripCount(0, 0, 1, false, false), 0);
1300   EXPECT_EQ(EvalTripCount(0, 1, 2, false, false), 1);
1301   EXPECT_EQ(EvalTripCount(0, 42, 1, false, false), 42);
1302   EXPECT_EQ(EvalTripCount(0, 42, 2, false, false), 21);
1303   EXPECT_EQ(EvalTripCount(21, 42, 1, false, false), 21);
1304   EXPECT_EQ(EvalTripCount(0, 5, 5, false, false), 1);
1305   EXPECT_EQ(EvalTripCount(0, 9, 5, false, false), 2);
1306   EXPECT_EQ(EvalTripCount(0, 11, 5, false, false), 3);
1307   EXPECT_EQ(EvalTripCount(0, 0xFFFF, 1, false, false), 0xFFFF);
1308   EXPECT_EQ(EvalTripCount(0xFFFF, 0, 1, false, false), 0);
1309   EXPECT_EQ(EvalTripCount(0xFFFE, 0xFFFF, 1, false, false), 1);
1310   EXPECT_EQ(EvalTripCount(0, 0xFFFF, 0x100, false, false), 0x100);
1311   EXPECT_EQ(EvalTripCount(0, 0xFFFF, 0xFFFF, false, false), 1);
1312 
1313   EXPECT_EQ(EvalTripCount(0, 6, 5, false, false), 2);
1314   EXPECT_EQ(EvalTripCount(0, 0xFFFF, 0xFFFE, false, false), 2);
1315   EXPECT_EQ(EvalTripCount(0, 0, 1, false, true), 1);
1316   EXPECT_EQ(EvalTripCount(0, 0, 0xFFFF, false, true), 1);
1317   EXPECT_EQ(EvalTripCount(0, 0xFFFE, 1, false, true), 0xFFFF);
1318   EXPECT_EQ(EvalTripCount(0, 0xFFFE, 2, false, true), 0x8000);
1319 
1320   EXPECT_EQ(EvalTripCount(0, 0, -1, true, false), 0);
1321   EXPECT_EQ(EvalTripCount(0, 1, -1, true, true), 0);
1322   EXPECT_EQ(EvalTripCount(20, 5, -5, true, false), 3);
1323   EXPECT_EQ(EvalTripCount(20, 5, -5, true, true), 4);
1324   EXPECT_EQ(EvalTripCount(-4, -2, 2, true, false), 1);
1325   EXPECT_EQ(EvalTripCount(-4, -3, 2, true, false), 1);
1326   EXPECT_EQ(EvalTripCount(-4, -2, 2, true, true), 2);
1327 
1328   EXPECT_EQ(EvalTripCount(INT16_MIN, 0, 1, true, false), 0x8000);
1329   EXPECT_EQ(EvalTripCount(INT16_MIN, 0, 1, true, true), 0x8001);
1330   EXPECT_EQ(EvalTripCount(INT16_MIN, 0x7FFF, 1, true, false), 0xFFFF);
1331   EXPECT_EQ(EvalTripCount(INT16_MIN + 1, 0x7FFF, 1, true, true), 0xFFFF);
1332   EXPECT_EQ(EvalTripCount(INT16_MIN, 0, 0x7FFF, true, false), 2);
1333   EXPECT_EQ(EvalTripCount(0x7FFF, 0, -1, true, false), 0x7FFF);
1334   EXPECT_EQ(EvalTripCount(0, INT16_MIN, -1, true, false), 0x8000);
1335   EXPECT_EQ(EvalTripCount(0, INT16_MIN, -16, true, false), 0x800);
1336   EXPECT_EQ(EvalTripCount(0x7FFF, INT16_MIN, -1, true, false), 0xFFFF);
1337   EXPECT_EQ(EvalTripCount(0x7FFF, 1, INT16_MIN, true, false), 1);
1338   EXPECT_EQ(EvalTripCount(0x7FFF, -1, INT16_MIN, true, true), 2);
1339 
1340   // Finalize the function and verify it.
1341   Builder.CreateRetVoid();
1342   OMPBuilder.finalize();
1343   EXPECT_FALSE(verifyModule(*M, &errs()));
1344 }
1345 
1346 TEST_F(OpenMPIRBuilderTest, CollapseNestedLoops) {
1347   using InsertPointTy = OpenMPIRBuilder::InsertPointTy;
1348   OpenMPIRBuilder OMPBuilder(*M);
1349   OMPBuilder.initialize();
1350   F->setName("func");
1351 
1352   IRBuilder<> Builder(BB);
1353 
1354   Type *LCTy = F->getArg(0)->getType();
1355   Constant *One = ConstantInt::get(LCTy, 1);
1356   Constant *Two = ConstantInt::get(LCTy, 2);
1357   Value *OuterTripCount =
1358       Builder.CreateAdd(F->getArg(0), Two, "tripcount.outer");
1359   Value *InnerTripCount =
1360       Builder.CreateAdd(F->getArg(0), One, "tripcount.inner");
1361 
1362   // Fix an insertion point for ComputeIP.
1363   BasicBlock *LoopNextEnter =
1364       BasicBlock::Create(M->getContext(), "loopnest.enter", F,
1365                          Builder.GetInsertBlock()->getNextNode());
1366   BranchInst *EnterBr = Builder.CreateBr(LoopNextEnter);
1367   InsertPointTy ComputeIP{EnterBr->getParent(), EnterBr->getIterator()};
1368 
1369   Builder.SetInsertPoint(LoopNextEnter);
1370   OpenMPIRBuilder::LocationDescription OuterLoc(Builder.saveIP(), DL);
1371 
1372   CanonicalLoopInfo *InnerLoop = nullptr;
1373   CallInst *InbetweenLead = nullptr;
1374   CallInst *InbetweenTrail = nullptr;
1375   CallInst *Call = nullptr;
1376   auto OuterLoopBodyGenCB = [&](InsertPointTy OuterCodeGenIP, Value *OuterLC) {
1377     Builder.restoreIP(OuterCodeGenIP);
1378     InbetweenLead =
1379         createPrintfCall(Builder, "In-between lead i=%d\\n", {OuterLC});
1380 
1381     auto InnerLoopBodyGenCB = [&](InsertPointTy InnerCodeGenIP,
1382                                   Value *InnerLC) {
1383       Builder.restoreIP(InnerCodeGenIP);
1384       Call = createPrintfCall(Builder, "body i=%d j=%d\\n", {OuterLC, InnerLC});
1385     };
1386     InnerLoop = OMPBuilder.createCanonicalLoop(
1387         Builder.saveIP(), InnerLoopBodyGenCB, InnerTripCount, "inner");
1388 
1389     Builder.restoreIP(InnerLoop->getAfterIP());
1390     InbetweenTrail =
1391         createPrintfCall(Builder, "In-between trail i=%d\\n", {OuterLC});
1392   };
1393   CanonicalLoopInfo *OuterLoop = OMPBuilder.createCanonicalLoop(
1394       OuterLoc, OuterLoopBodyGenCB, OuterTripCount, "outer");
1395 
1396   // Finish the function.
1397   Builder.restoreIP(OuterLoop->getAfterIP());
1398   Builder.CreateRetVoid();
1399 
1400   CanonicalLoopInfo *Collapsed =
1401       OMPBuilder.collapseLoops(DL, {OuterLoop, InnerLoop}, ComputeIP);
1402 
1403   OMPBuilder.finalize();
1404   EXPECT_FALSE(verifyModule(*M, &errs()));
1405 
1406   // Verify control flow and BB order.
1407   BasicBlock *RefOrder[] = {
1408       Collapsed->getPreheader(),   Collapsed->getHeader(),
1409       Collapsed->getCond(),        Collapsed->getBody(),
1410       InbetweenLead->getParent(),  Call->getParent(),
1411       InbetweenTrail->getParent(), Collapsed->getLatch(),
1412       Collapsed->getExit(),        Collapsed->getAfter(),
1413   };
1414   EXPECT_TRUE(verifyDFSOrder(F, RefOrder));
1415   EXPECT_TRUE(verifyListOrder(F, RefOrder));
1416 
1417   // Verify the total trip count.
1418   auto *TripCount = cast<MulOperator>(Collapsed->getTripCount());
1419   EXPECT_EQ(TripCount->getOperand(0), OuterTripCount);
1420   EXPECT_EQ(TripCount->getOperand(1), InnerTripCount);
1421 
1422   // Verify the changed indvar.
1423   auto *OuterIV = cast<BinaryOperator>(Call->getOperand(1));
1424   EXPECT_EQ(OuterIV->getOpcode(), Instruction::UDiv);
1425   EXPECT_EQ(OuterIV->getParent(), Collapsed->getBody());
1426   EXPECT_EQ(OuterIV->getOperand(1), InnerTripCount);
1427   EXPECT_EQ(OuterIV->getOperand(0), Collapsed->getIndVar());
1428 
1429   auto *InnerIV = cast<BinaryOperator>(Call->getOperand(2));
1430   EXPECT_EQ(InnerIV->getOpcode(), Instruction::URem);
1431   EXPECT_EQ(InnerIV->getParent(), Collapsed->getBody());
1432   EXPECT_EQ(InnerIV->getOperand(0), Collapsed->getIndVar());
1433   EXPECT_EQ(InnerIV->getOperand(1), InnerTripCount);
1434 
1435   EXPECT_EQ(InbetweenLead->getOperand(1), OuterIV);
1436   EXPECT_EQ(InbetweenTrail->getOperand(1), OuterIV);
1437 }
1438 
1439 TEST_F(OpenMPIRBuilderTest, TileSingleLoop) {
1440   OpenMPIRBuilder OMPBuilder(*M);
1441   CallInst *Call;
1442   BasicBlock *BodyCode;
1443   CanonicalLoopInfo *Loop =
1444       buildSingleLoopFunction(DL, OMPBuilder, 32, &Call, &BodyCode);
1445 
1446   Instruction *OrigIndVar = Loop->getIndVar();
1447   EXPECT_EQ(Call->getOperand(1), OrigIndVar);
1448 
1449   // Tile the loop.
1450   Constant *TileSize = ConstantInt::get(Loop->getIndVarType(), APInt(32, 7));
1451   std::vector<CanonicalLoopInfo *> GenLoops =
1452       OMPBuilder.tileLoops(DL, {Loop}, {TileSize});
1453 
1454   OMPBuilder.finalize();
1455   EXPECT_FALSE(verifyModule(*M, &errs()));
1456 
1457   EXPECT_EQ(GenLoops.size(), 2u);
1458   CanonicalLoopInfo *Floor = GenLoops[0];
1459   CanonicalLoopInfo *Tile = GenLoops[1];
1460 
1461   BasicBlock *RefOrder[] = {
1462       Floor->getPreheader(), Floor->getHeader(),   Floor->getCond(),
1463       Floor->getBody(),      Tile->getPreheader(), Tile->getHeader(),
1464       Tile->getCond(),       Tile->getBody(),      BodyCode,
1465       Tile->getLatch(),      Tile->getExit(),      Tile->getAfter(),
1466       Floor->getLatch(),     Floor->getExit(),     Floor->getAfter(),
1467   };
1468   EXPECT_TRUE(verifyDFSOrder(F, RefOrder));
1469   EXPECT_TRUE(verifyListOrder(F, RefOrder));
1470 
1471   // Check the induction variable.
1472   EXPECT_EQ(Call->getParent(), BodyCode);
1473   auto *Shift = cast<AddOperator>(Call->getOperand(1));
1474   EXPECT_EQ(cast<Instruction>(Shift)->getParent(), Tile->getBody());
1475   EXPECT_EQ(Shift->getOperand(1), Tile->getIndVar());
1476   auto *Scale = cast<MulOperator>(Shift->getOperand(0));
1477   EXPECT_EQ(cast<Instruction>(Scale)->getParent(), Tile->getBody());
1478   EXPECT_EQ(Scale->getOperand(0), TileSize);
1479   EXPECT_EQ(Scale->getOperand(1), Floor->getIndVar());
1480 }
1481 
1482 TEST_F(OpenMPIRBuilderTest, TileNestedLoops) {
1483   using InsertPointTy = OpenMPIRBuilder::InsertPointTy;
1484   OpenMPIRBuilder OMPBuilder(*M);
1485   OMPBuilder.initialize();
1486   F->setName("func");
1487 
1488   IRBuilder<> Builder(BB);
1489   OpenMPIRBuilder::LocationDescription Loc({Builder.saveIP(), DL});
1490   Value *TripCount = F->getArg(0);
1491   Type *LCTy = TripCount->getType();
1492 
1493   BasicBlock *BodyCode = nullptr;
1494   CanonicalLoopInfo *InnerLoop = nullptr;
1495   auto OuterLoopBodyGenCB = [&](InsertPointTy OuterCodeGenIP,
1496                                 llvm::Value *OuterLC) {
1497     auto InnerLoopBodyGenCB = [&](InsertPointTy InnerCodeGenIP,
1498                                   llvm::Value *InnerLC) {
1499       Builder.restoreIP(InnerCodeGenIP);
1500       BodyCode = Builder.GetInsertBlock();
1501 
1502       // Add something that consumes the induction variables to the body.
1503       createPrintfCall(Builder, "i=%d j=%d\\n", {OuterLC, InnerLC});
1504     };
1505     InnerLoop = OMPBuilder.createCanonicalLoop(
1506         OuterCodeGenIP, InnerLoopBodyGenCB, TripCount, "inner");
1507   };
1508   CanonicalLoopInfo *OuterLoop = OMPBuilder.createCanonicalLoop(
1509       Loc, OuterLoopBodyGenCB, TripCount, "outer");
1510 
1511   // Finalize the function.
1512   Builder.restoreIP(OuterLoop->getAfterIP());
1513   Builder.CreateRetVoid();
1514 
1515   // Tile to loop nest.
1516   Constant *OuterTileSize = ConstantInt::get(LCTy, APInt(32, 11));
1517   Constant *InnerTileSize = ConstantInt::get(LCTy, APInt(32, 7));
1518   std::vector<CanonicalLoopInfo *> GenLoops = OMPBuilder.tileLoops(
1519       DL, {OuterLoop, InnerLoop}, {OuterTileSize, InnerTileSize});
1520 
1521   OMPBuilder.finalize();
1522   EXPECT_FALSE(verifyModule(*M, &errs()));
1523 
1524   EXPECT_EQ(GenLoops.size(), 4u);
1525   CanonicalLoopInfo *Floor1 = GenLoops[0];
1526   CanonicalLoopInfo *Floor2 = GenLoops[1];
1527   CanonicalLoopInfo *Tile1 = GenLoops[2];
1528   CanonicalLoopInfo *Tile2 = GenLoops[3];
1529 
1530   BasicBlock *RefOrder[] = {
1531       Floor1->getPreheader(),
1532       Floor1->getHeader(),
1533       Floor1->getCond(),
1534       Floor1->getBody(),
1535       Floor2->getPreheader(),
1536       Floor2->getHeader(),
1537       Floor2->getCond(),
1538       Floor2->getBody(),
1539       Tile1->getPreheader(),
1540       Tile1->getHeader(),
1541       Tile1->getCond(),
1542       Tile1->getBody(),
1543       Tile2->getPreheader(),
1544       Tile2->getHeader(),
1545       Tile2->getCond(),
1546       Tile2->getBody(),
1547       BodyCode,
1548       Tile2->getLatch(),
1549       Tile2->getExit(),
1550       Tile2->getAfter(),
1551       Tile1->getLatch(),
1552       Tile1->getExit(),
1553       Tile1->getAfter(),
1554       Floor2->getLatch(),
1555       Floor2->getExit(),
1556       Floor2->getAfter(),
1557       Floor1->getLatch(),
1558       Floor1->getExit(),
1559       Floor1->getAfter(),
1560   };
1561   EXPECT_TRUE(verifyDFSOrder(F, RefOrder));
1562   EXPECT_TRUE(verifyListOrder(F, RefOrder));
1563 }
1564 
1565 TEST_F(OpenMPIRBuilderTest, TileNestedLoopsWithBounds) {
1566   using InsertPointTy = OpenMPIRBuilder::InsertPointTy;
1567   OpenMPIRBuilder OMPBuilder(*M);
1568   OMPBuilder.initialize();
1569   F->setName("func");
1570 
1571   IRBuilder<> Builder(BB);
1572   Value *TripCount = F->getArg(0);
1573   Type *LCTy = TripCount->getType();
1574 
1575   Value *OuterStartVal = ConstantInt::get(LCTy, 2);
1576   Value *OuterStopVal = TripCount;
1577   Value *OuterStep = ConstantInt::get(LCTy, 5);
1578   Value *InnerStartVal = ConstantInt::get(LCTy, 13);
1579   Value *InnerStopVal = TripCount;
1580   Value *InnerStep = ConstantInt::get(LCTy, 3);
1581 
1582   // Fix an insertion point for ComputeIP.
1583   BasicBlock *LoopNextEnter =
1584       BasicBlock::Create(M->getContext(), "loopnest.enter", F,
1585                          Builder.GetInsertBlock()->getNextNode());
1586   BranchInst *EnterBr = Builder.CreateBr(LoopNextEnter);
1587   InsertPointTy ComputeIP{EnterBr->getParent(), EnterBr->getIterator()};
1588 
1589   InsertPointTy LoopIP{LoopNextEnter, LoopNextEnter->begin()};
1590   OpenMPIRBuilder::LocationDescription Loc({LoopIP, DL});
1591 
1592   BasicBlock *BodyCode = nullptr;
1593   CanonicalLoopInfo *InnerLoop = nullptr;
1594   CallInst *Call = nullptr;
1595   auto OuterLoopBodyGenCB = [&](InsertPointTy OuterCodeGenIP,
1596                                 llvm::Value *OuterLC) {
1597     auto InnerLoopBodyGenCB = [&](InsertPointTy InnerCodeGenIP,
1598                                   llvm::Value *InnerLC) {
1599       Builder.restoreIP(InnerCodeGenIP);
1600       BodyCode = Builder.GetInsertBlock();
1601 
1602       // Add something that consumes the induction variable to the body.
1603       Call = createPrintfCall(Builder, "i=%d j=%d\\n", {OuterLC, InnerLC});
1604     };
1605     InnerLoop = OMPBuilder.createCanonicalLoop(
1606         OuterCodeGenIP, InnerLoopBodyGenCB, InnerStartVal, InnerStopVal,
1607         InnerStep, false, false, ComputeIP, "inner");
1608   };
1609   CanonicalLoopInfo *OuterLoop = OMPBuilder.createCanonicalLoop(
1610       Loc, OuterLoopBodyGenCB, OuterStartVal, OuterStopVal, OuterStep, false,
1611       false, ComputeIP, "outer");
1612 
1613   // Finalize the function
1614   Builder.restoreIP(OuterLoop->getAfterIP());
1615   Builder.CreateRetVoid();
1616 
1617   // Tile the loop nest.
1618   Constant *TileSize0 = ConstantInt::get(LCTy, APInt(32, 11));
1619   Constant *TileSize1 = ConstantInt::get(LCTy, APInt(32, 7));
1620   std::vector<CanonicalLoopInfo *> GenLoops =
1621       OMPBuilder.tileLoops(DL, {OuterLoop, InnerLoop}, {TileSize0, TileSize1});
1622 
1623   OMPBuilder.finalize();
1624   EXPECT_FALSE(verifyModule(*M, &errs()));
1625 
1626   EXPECT_EQ(GenLoops.size(), 4u);
1627   CanonicalLoopInfo *Floor0 = GenLoops[0];
1628   CanonicalLoopInfo *Floor1 = GenLoops[1];
1629   CanonicalLoopInfo *Tile0 = GenLoops[2];
1630   CanonicalLoopInfo *Tile1 = GenLoops[3];
1631 
1632   BasicBlock *RefOrder[] = {
1633       Floor0->getPreheader(),
1634       Floor0->getHeader(),
1635       Floor0->getCond(),
1636       Floor0->getBody(),
1637       Floor1->getPreheader(),
1638       Floor1->getHeader(),
1639       Floor1->getCond(),
1640       Floor1->getBody(),
1641       Tile0->getPreheader(),
1642       Tile0->getHeader(),
1643       Tile0->getCond(),
1644       Tile0->getBody(),
1645       Tile1->getPreheader(),
1646       Tile1->getHeader(),
1647       Tile1->getCond(),
1648       Tile1->getBody(),
1649       BodyCode,
1650       Tile1->getLatch(),
1651       Tile1->getExit(),
1652       Tile1->getAfter(),
1653       Tile0->getLatch(),
1654       Tile0->getExit(),
1655       Tile0->getAfter(),
1656       Floor1->getLatch(),
1657       Floor1->getExit(),
1658       Floor1->getAfter(),
1659       Floor0->getLatch(),
1660       Floor0->getExit(),
1661       Floor0->getAfter(),
1662   };
1663   EXPECT_TRUE(verifyDFSOrder(F, RefOrder));
1664   EXPECT_TRUE(verifyListOrder(F, RefOrder));
1665 
1666   EXPECT_EQ(Call->getParent(), BodyCode);
1667 
1668   auto *RangeShift0 = cast<AddOperator>(Call->getOperand(1));
1669   EXPECT_EQ(RangeShift0->getOperand(1), OuterStartVal);
1670   auto *RangeScale0 = cast<MulOperator>(RangeShift0->getOperand(0));
1671   EXPECT_EQ(RangeScale0->getOperand(1), OuterStep);
1672   auto *TileShift0 = cast<AddOperator>(RangeScale0->getOperand(0));
1673   EXPECT_EQ(cast<Instruction>(TileShift0)->getParent(), Tile1->getBody());
1674   EXPECT_EQ(TileShift0->getOperand(1), Tile0->getIndVar());
1675   auto *TileScale0 = cast<MulOperator>(TileShift0->getOperand(0));
1676   EXPECT_EQ(cast<Instruction>(TileScale0)->getParent(), Tile1->getBody());
1677   EXPECT_EQ(TileScale0->getOperand(0), TileSize0);
1678   EXPECT_EQ(TileScale0->getOperand(1), Floor0->getIndVar());
1679 
1680   auto *RangeShift1 = cast<AddOperator>(Call->getOperand(2));
1681   EXPECT_EQ(cast<Instruction>(RangeShift1)->getParent(), BodyCode);
1682   EXPECT_EQ(RangeShift1->getOperand(1), InnerStartVal);
1683   auto *RangeScale1 = cast<MulOperator>(RangeShift1->getOperand(0));
1684   EXPECT_EQ(cast<Instruction>(RangeScale1)->getParent(), BodyCode);
1685   EXPECT_EQ(RangeScale1->getOperand(1), InnerStep);
1686   auto *TileShift1 = cast<AddOperator>(RangeScale1->getOperand(0));
1687   EXPECT_EQ(cast<Instruction>(TileShift1)->getParent(), Tile1->getBody());
1688   EXPECT_EQ(TileShift1->getOperand(1), Tile1->getIndVar());
1689   auto *TileScale1 = cast<MulOperator>(TileShift1->getOperand(0));
1690   EXPECT_EQ(cast<Instruction>(TileScale1)->getParent(), Tile1->getBody());
1691   EXPECT_EQ(TileScale1->getOperand(0), TileSize1);
1692   EXPECT_EQ(TileScale1->getOperand(1), Floor1->getIndVar());
1693 }
1694 
1695 TEST_F(OpenMPIRBuilderTest, TileSingleLoopCounts) {
1696   using InsertPointTy = OpenMPIRBuilder::InsertPointTy;
1697   OpenMPIRBuilder OMPBuilder(*M);
1698   OMPBuilder.initialize();
1699   IRBuilder<> Builder(BB);
1700 
1701   // Create a loop, tile it, and extract its trip count. All input values are
1702   // constant and IRBuilder evaluates all-constant arithmetic inplace, such that
1703   // the floor trip count itself will be a ConstantInt. Unfortunately we cannot
1704   // do the same for the tile loop.
1705   auto GetFloorCount = [&](int64_t Start, int64_t Stop, int64_t Step,
1706                            bool IsSigned, bool InclusiveStop,
1707                            int64_t TileSize) -> uint64_t {
1708     OpenMPIRBuilder::LocationDescription Loc(Builder.saveIP(), DL);
1709     Type *LCTy = Type::getInt16Ty(Ctx);
1710     Value *StartVal = ConstantInt::get(LCTy, Start);
1711     Value *StopVal = ConstantInt::get(LCTy, Stop);
1712     Value *StepVal = ConstantInt::get(LCTy, Step);
1713 
1714     // Generate a loop.
1715     auto LoopBodyGenCB = [&](InsertPointTy CodeGenIP, llvm::Value *LC) {};
1716     CanonicalLoopInfo *Loop =
1717         OMPBuilder.createCanonicalLoop(Loc, LoopBodyGenCB, StartVal, StopVal,
1718                                        StepVal, IsSigned, InclusiveStop);
1719     InsertPointTy AfterIP = Loop->getAfterIP();
1720 
1721     // Tile the loop.
1722     Value *TileSizeVal = ConstantInt::get(LCTy, TileSize);
1723     std::vector<CanonicalLoopInfo *> GenLoops =
1724         OMPBuilder.tileLoops(Loc.DL, {Loop}, {TileSizeVal});
1725 
1726     // Set the insertion pointer to after loop, where the next loop will be
1727     // emitted.
1728     Builder.restoreIP(AfterIP);
1729 
1730     // Extract the trip count.
1731     CanonicalLoopInfo *FloorLoop = GenLoops[0];
1732     Value *FloorTripCount = FloorLoop->getTripCount();
1733     return cast<ConstantInt>(FloorTripCount)->getValue().getZExtValue();
1734   };
1735 
1736   // Empty iteration domain.
1737   EXPECT_EQ(GetFloorCount(0, 0, 1, false, false, 7), 0u);
1738   EXPECT_EQ(GetFloorCount(0, -1, 1, false, true, 7), 0u);
1739   EXPECT_EQ(GetFloorCount(-1, -1, -1, true, false, 7), 0u);
1740   EXPECT_EQ(GetFloorCount(-1, 0, -1, true, true, 7), 0u);
1741   EXPECT_EQ(GetFloorCount(-1, -1, 3, true, false, 7), 0u);
1742 
1743   // Only complete tiles.
1744   EXPECT_EQ(GetFloorCount(0, 14, 1, false, false, 7), 2u);
1745   EXPECT_EQ(GetFloorCount(0, 14, 1, false, false, 7), 2u);
1746   EXPECT_EQ(GetFloorCount(1, 15, 1, false, false, 7), 2u);
1747   EXPECT_EQ(GetFloorCount(0, -14, -1, true, false, 7), 2u);
1748   EXPECT_EQ(GetFloorCount(-1, -14, -1, true, true, 7), 2u);
1749   EXPECT_EQ(GetFloorCount(0, 3 * 7 * 2, 3, false, false, 7), 2u);
1750 
1751   // Only a partial tile.
1752   EXPECT_EQ(GetFloorCount(0, 1, 1, false, false, 7), 1u);
1753   EXPECT_EQ(GetFloorCount(0, 6, 1, false, false, 7), 1u);
1754   EXPECT_EQ(GetFloorCount(-1, 1, 3, true, false, 7), 1u);
1755   EXPECT_EQ(GetFloorCount(-1, -2, -1, true, false, 7), 1u);
1756   EXPECT_EQ(GetFloorCount(0, 2, 3, false, false, 7), 1u);
1757 
1758   // Complete and partial tiles.
1759   EXPECT_EQ(GetFloorCount(0, 13, 1, false, false, 7), 2u);
1760   EXPECT_EQ(GetFloorCount(0, 15, 1, false, false, 7), 3u);
1761   EXPECT_EQ(GetFloorCount(-1, -14, -1, true, false, 7), 2u);
1762   EXPECT_EQ(GetFloorCount(0, 3 * 7 * 5 - 1, 3, false, false, 7), 5u);
1763   EXPECT_EQ(GetFloorCount(-1, -3 * 7 * 5, -3, true, false, 7), 5u);
1764 
1765   // Close to 16-bit integer range.
1766   EXPECT_EQ(GetFloorCount(0, 0xFFFF, 1, false, false, 1), 0xFFFFu);
1767   EXPECT_EQ(GetFloorCount(0, 0xFFFF, 1, false, false, 7), 0xFFFFu / 7 + 1);
1768   EXPECT_EQ(GetFloorCount(0, 0xFFFE, 1, false, true, 7), 0xFFFFu / 7 + 1);
1769   EXPECT_EQ(GetFloorCount(-0x8000, 0x7FFF, 1, true, false, 7), 0xFFFFu / 7 + 1);
1770   EXPECT_EQ(GetFloorCount(-0x7FFF, 0x7FFF, 1, true, true, 7), 0xFFFFu / 7 + 1);
1771   EXPECT_EQ(GetFloorCount(0, 0xFFFE, 1, false, false, 0xFFFF), 1u);
1772   EXPECT_EQ(GetFloorCount(-0x8000, 0x7FFF, 1, true, false, 0xFFFF), 1u);
1773 
1774   // Finalize the function.
1775   Builder.CreateRetVoid();
1776   OMPBuilder.finalize();
1777 
1778   EXPECT_FALSE(verifyModule(*M, &errs()));
1779 }
1780 
1781 TEST_F(OpenMPIRBuilderTest, ApplySimd) {
1782   OpenMPIRBuilder OMPBuilder(*M);
1783 
1784   CanonicalLoopInfo *CLI = buildSingleLoopFunction(DL, OMPBuilder, 32);
1785 
1786   // Simd-ize the loop.
1787   OMPBuilder.applySimd(DL, CLI);
1788 
1789   OMPBuilder.finalize();
1790   EXPECT_FALSE(verifyModule(*M, &errs()));
1791 
1792   PassBuilder PB;
1793   FunctionAnalysisManager FAM;
1794   PB.registerFunctionAnalyses(FAM);
1795   LoopInfo &LI = FAM.getResult<LoopAnalysis>(*F);
1796 
1797   const std::vector<Loop *> &TopLvl = LI.getTopLevelLoops();
1798   EXPECT_EQ(TopLvl.size(), 1u);
1799 
1800   Loop *L = TopLvl.front();
1801   EXPECT_TRUE(findStringMetadataForLoop(L, "llvm.loop.parallel_accesses"));
1802   EXPECT_TRUE(getBooleanLoopAttribute(L, "llvm.loop.vectorize.enable"));
1803 
1804   // Check for llvm.access.group metadata attached to the printf
1805   // function in the loop body.
1806   BasicBlock *LoopBody = CLI->getBody();
1807   EXPECT_TRUE(any_of(*LoopBody, [](Instruction &I) {
1808     return I.getMetadata("llvm.access.group") != nullptr;
1809   }));
1810 }
1811 
1812 TEST_F(OpenMPIRBuilderTest, UnrollLoopFull) {
1813   OpenMPIRBuilder OMPBuilder(*M);
1814 
1815   CanonicalLoopInfo *CLI = buildSingleLoopFunction(DL, OMPBuilder, 32);
1816 
1817   // Unroll the loop.
1818   OMPBuilder.unrollLoopFull(DL, CLI);
1819 
1820   OMPBuilder.finalize();
1821   EXPECT_FALSE(verifyModule(*M, &errs()));
1822 
1823   PassBuilder PB;
1824   FunctionAnalysisManager FAM;
1825   PB.registerFunctionAnalyses(FAM);
1826   LoopInfo &LI = FAM.getResult<LoopAnalysis>(*F);
1827 
1828   const std::vector<Loop *> &TopLvl = LI.getTopLevelLoops();
1829   EXPECT_EQ(TopLvl.size(), 1u);
1830 
1831   Loop *L = TopLvl.front();
1832   EXPECT_TRUE(getBooleanLoopAttribute(L, "llvm.loop.unroll.enable"));
1833   EXPECT_TRUE(getBooleanLoopAttribute(L, "llvm.loop.unroll.full"));
1834 }
1835 
1836 TEST_F(OpenMPIRBuilderTest, UnrollLoopPartial) {
1837   OpenMPIRBuilder OMPBuilder(*M);
1838   CanonicalLoopInfo *CLI = buildSingleLoopFunction(DL, OMPBuilder, 32);
1839 
1840   // Unroll the loop.
1841   CanonicalLoopInfo *UnrolledLoop = nullptr;
1842   OMPBuilder.unrollLoopPartial(DL, CLI, 5, &UnrolledLoop);
1843   ASSERT_NE(UnrolledLoop, nullptr);
1844 
1845   OMPBuilder.finalize();
1846   EXPECT_FALSE(verifyModule(*M, &errs()));
1847   UnrolledLoop->assertOK();
1848 
1849   PassBuilder PB;
1850   FunctionAnalysisManager FAM;
1851   PB.registerFunctionAnalyses(FAM);
1852   LoopInfo &LI = FAM.getResult<LoopAnalysis>(*F);
1853 
1854   const std::vector<Loop *> &TopLvl = LI.getTopLevelLoops();
1855   EXPECT_EQ(TopLvl.size(), 1u);
1856   Loop *Outer = TopLvl.front();
1857   EXPECT_EQ(Outer->getHeader(), UnrolledLoop->getHeader());
1858   EXPECT_EQ(Outer->getLoopLatch(), UnrolledLoop->getLatch());
1859   EXPECT_EQ(Outer->getExitingBlock(), UnrolledLoop->getCond());
1860   EXPECT_EQ(Outer->getExitBlock(), UnrolledLoop->getExit());
1861 
1862   EXPECT_EQ(Outer->getSubLoops().size(), 1u);
1863   Loop *Inner = Outer->getSubLoops().front();
1864 
1865   EXPECT_TRUE(getBooleanLoopAttribute(Inner, "llvm.loop.unroll.enable"));
1866   EXPECT_EQ(getIntLoopAttribute(Inner, "llvm.loop.unroll.count"), 5);
1867 }
1868 
1869 TEST_F(OpenMPIRBuilderTest, UnrollLoopHeuristic) {
1870   OpenMPIRBuilder OMPBuilder(*M);
1871 
1872   CanonicalLoopInfo *CLI = buildSingleLoopFunction(DL, OMPBuilder, 32);
1873 
1874   // Unroll the loop.
1875   OMPBuilder.unrollLoopHeuristic(DL, CLI);
1876 
1877   OMPBuilder.finalize();
1878   EXPECT_FALSE(verifyModule(*M, &errs()));
1879 
1880   PassBuilder PB;
1881   FunctionAnalysisManager FAM;
1882   PB.registerFunctionAnalyses(FAM);
1883   LoopInfo &LI = FAM.getResult<LoopAnalysis>(*F);
1884 
1885   const std::vector<Loop *> &TopLvl = LI.getTopLevelLoops();
1886   EXPECT_EQ(TopLvl.size(), 1u);
1887 
1888   Loop *L = TopLvl.front();
1889   EXPECT_TRUE(getBooleanLoopAttribute(L, "llvm.loop.unroll.enable"));
1890 }
1891 
1892 TEST_F(OpenMPIRBuilderTest, StaticWorkShareLoop) {
1893   using InsertPointTy = OpenMPIRBuilder::InsertPointTy;
1894   OpenMPIRBuilder OMPBuilder(*M);
1895   OMPBuilder.initialize();
1896   IRBuilder<> Builder(BB);
1897   OpenMPIRBuilder::LocationDescription Loc({Builder.saveIP(), DL});
1898 
1899   Type *LCTy = Type::getInt32Ty(Ctx);
1900   Value *StartVal = ConstantInt::get(LCTy, 10);
1901   Value *StopVal = ConstantInt::get(LCTy, 52);
1902   Value *StepVal = ConstantInt::get(LCTy, 2);
1903   auto LoopBodyGen = [&](InsertPointTy, llvm::Value *) {};
1904 
1905   CanonicalLoopInfo *CLI = OMPBuilder.createCanonicalLoop(
1906       Loc, LoopBodyGen, StartVal, StopVal, StepVal,
1907       /*IsSigned=*/false, /*InclusiveStop=*/false);
1908   BasicBlock *Preheader = CLI->getPreheader();
1909   BasicBlock *Body = CLI->getBody();
1910   Value *IV = CLI->getIndVar();
1911   BasicBlock *ExitBlock = CLI->getExit();
1912 
1913   Builder.SetInsertPoint(BB, BB->getFirstInsertionPt());
1914   InsertPointTy AllocaIP = Builder.saveIP();
1915 
1916   OMPBuilder.applyWorkshareLoop(DL, CLI, AllocaIP, /*NeedsBarrier=*/true,
1917                                 OMP_SCHEDULE_Static);
1918 
1919   BasicBlock *Cond = Body->getSinglePredecessor();
1920   Instruction *Cmp = &*Cond->begin();
1921   Value *TripCount = Cmp->getOperand(1);
1922 
1923   auto AllocaIter = BB->begin();
1924   ASSERT_GE(std::distance(BB->begin(), BB->end()), 4);
1925   AllocaInst *PLastIter = dyn_cast<AllocaInst>(&*(AllocaIter++));
1926   AllocaInst *PLowerBound = dyn_cast<AllocaInst>(&*(AllocaIter++));
1927   AllocaInst *PUpperBound = dyn_cast<AllocaInst>(&*(AllocaIter++));
1928   AllocaInst *PStride = dyn_cast<AllocaInst>(&*(AllocaIter++));
1929   EXPECT_NE(PLastIter, nullptr);
1930   EXPECT_NE(PLowerBound, nullptr);
1931   EXPECT_NE(PUpperBound, nullptr);
1932   EXPECT_NE(PStride, nullptr);
1933 
1934   auto PreheaderIter = Preheader->begin();
1935   ASSERT_GE(std::distance(Preheader->begin(), Preheader->end()), 7);
1936   StoreInst *LowerBoundStore = dyn_cast<StoreInst>(&*(PreheaderIter++));
1937   StoreInst *UpperBoundStore = dyn_cast<StoreInst>(&*(PreheaderIter++));
1938   StoreInst *StrideStore = dyn_cast<StoreInst>(&*(PreheaderIter++));
1939   ASSERT_NE(LowerBoundStore, nullptr);
1940   ASSERT_NE(UpperBoundStore, nullptr);
1941   ASSERT_NE(StrideStore, nullptr);
1942 
1943   auto *OrigLowerBound =
1944       dyn_cast<ConstantInt>(LowerBoundStore->getValueOperand());
1945   auto *OrigUpperBound =
1946       dyn_cast<ConstantInt>(UpperBoundStore->getValueOperand());
1947   auto *OrigStride = dyn_cast<ConstantInt>(StrideStore->getValueOperand());
1948   ASSERT_NE(OrigLowerBound, nullptr);
1949   ASSERT_NE(OrigUpperBound, nullptr);
1950   ASSERT_NE(OrigStride, nullptr);
1951   EXPECT_EQ(OrigLowerBound->getValue(), 0);
1952   EXPECT_EQ(OrigUpperBound->getValue(), 20);
1953   EXPECT_EQ(OrigStride->getValue(), 1);
1954 
1955   // Check that the loop IV is updated to account for the lower bound returned
1956   // by the OpenMP runtime call.
1957   BinaryOperator *Add = dyn_cast<BinaryOperator>(&Body->front());
1958   EXPECT_EQ(Add->getOperand(0), IV);
1959   auto *LoadedLowerBound = dyn_cast<LoadInst>(Add->getOperand(1));
1960   ASSERT_NE(LoadedLowerBound, nullptr);
1961   EXPECT_EQ(LoadedLowerBound->getPointerOperand(), PLowerBound);
1962 
1963   // Check that the trip count is updated to account for the lower and upper
1964   // bounds return by the OpenMP runtime call.
1965   auto *AddOne = dyn_cast<Instruction>(TripCount);
1966   ASSERT_NE(AddOne, nullptr);
1967   ASSERT_TRUE(AddOne->isBinaryOp());
1968   auto *One = dyn_cast<ConstantInt>(AddOne->getOperand(1));
1969   ASSERT_NE(One, nullptr);
1970   EXPECT_EQ(One->getValue(), 1);
1971   auto *Difference = dyn_cast<Instruction>(AddOne->getOperand(0));
1972   ASSERT_NE(Difference, nullptr);
1973   ASSERT_TRUE(Difference->isBinaryOp());
1974   EXPECT_EQ(Difference->getOperand(1), LoadedLowerBound);
1975   auto *LoadedUpperBound = dyn_cast<LoadInst>(Difference->getOperand(0));
1976   ASSERT_NE(LoadedUpperBound, nullptr);
1977   EXPECT_EQ(LoadedUpperBound->getPointerOperand(), PUpperBound);
1978 
1979   // The original loop iterator should only be used in the condition, in the
1980   // increment and in the statement that adds the lower bound to it.
1981   EXPECT_EQ(std::distance(IV->use_begin(), IV->use_end()), 3);
1982 
1983   // The exit block should contain the "fini" call and the barrier call,
1984   // plus the call to obtain the thread ID.
1985   size_t NumCallsInExitBlock =
1986       count_if(*ExitBlock, [](Instruction &I) { return isa<CallInst>(I); });
1987   EXPECT_EQ(NumCallsInExitBlock, 3u);
1988 }
1989 
1990 TEST_P(OpenMPIRBuilderTestWithIVBits, StaticChunkedWorkshareLoop) {
1991   unsigned IVBits = GetParam();
1992 
1993   using InsertPointTy = OpenMPIRBuilder::InsertPointTy;
1994   OpenMPIRBuilder OMPBuilder(*M);
1995 
1996   BasicBlock *Body;
1997   CallInst *Call;
1998   CanonicalLoopInfo *CLI =
1999       buildSingleLoopFunction(DL, OMPBuilder, IVBits, &Call, &Body);
2000 
2001   Instruction *OrigIndVar = CLI->getIndVar();
2002   EXPECT_EQ(Call->getOperand(1), OrigIndVar);
2003 
2004   Type *LCTy = Type::getInt32Ty(Ctx);
2005   Value *ChunkSize = ConstantInt::get(LCTy, 5);
2006   InsertPointTy AllocaIP{&F->getEntryBlock(),
2007                          F->getEntryBlock().getFirstInsertionPt()};
2008   OMPBuilder.applyWorkshareLoop(DL, CLI, AllocaIP, /*NeedsBarrier=*/true,
2009                                 OMP_SCHEDULE_Static, ChunkSize);
2010 
2011   OMPBuilder.finalize();
2012   EXPECT_FALSE(verifyModule(*M, &errs()));
2013 
2014   BasicBlock *Entry = &F->getEntryBlock();
2015   BasicBlock *Preheader = Entry->getSingleSuccessor();
2016 
2017   BasicBlock *DispatchPreheader = Preheader->getSingleSuccessor();
2018   BasicBlock *DispatchHeader = DispatchPreheader->getSingleSuccessor();
2019   BasicBlock *DispatchCond = DispatchHeader->getSingleSuccessor();
2020   BasicBlock *DispatchBody = succ_begin(DispatchCond)[0];
2021   BasicBlock *DispatchExit = succ_begin(DispatchCond)[1];
2022   BasicBlock *DispatchAfter = DispatchExit->getSingleSuccessor();
2023   BasicBlock *Return = DispatchAfter->getSingleSuccessor();
2024 
2025   BasicBlock *ChunkPreheader = DispatchBody->getSingleSuccessor();
2026   BasicBlock *ChunkHeader = ChunkPreheader->getSingleSuccessor();
2027   BasicBlock *ChunkCond = ChunkHeader->getSingleSuccessor();
2028   BasicBlock *ChunkBody = succ_begin(ChunkCond)[0];
2029   BasicBlock *ChunkExit = succ_begin(ChunkCond)[1];
2030   BasicBlock *ChunkInc = ChunkBody->getSingleSuccessor();
2031   BasicBlock *ChunkAfter = ChunkExit->getSingleSuccessor();
2032 
2033   BasicBlock *DispatchInc = ChunkAfter;
2034 
2035   EXPECT_EQ(ChunkBody, Body);
2036   EXPECT_EQ(ChunkInc->getSingleSuccessor(), ChunkHeader);
2037   EXPECT_EQ(DispatchInc->getSingleSuccessor(), DispatchHeader);
2038 
2039   EXPECT_TRUE(isa<ReturnInst>(Return->front()));
2040 
2041   Value *NewIV = Call->getOperand(1);
2042   EXPECT_EQ(NewIV->getType()->getScalarSizeInBits(), IVBits);
2043 
2044   CallInst *InitCall = findSingleCall(
2045       F,
2046       (IVBits > 32) ? omp::RuntimeFunction::OMPRTL___kmpc_for_static_init_8u
2047                     : omp::RuntimeFunction::OMPRTL___kmpc_for_static_init_4u,
2048       OMPBuilder);
2049   EXPECT_EQ(InitCall->getParent(), Preheader);
2050   EXPECT_EQ(cast<ConstantInt>(InitCall->getArgOperand(2))->getSExtValue(), 33);
2051   EXPECT_EQ(cast<ConstantInt>(InitCall->getArgOperand(7))->getSExtValue(), 1);
2052   EXPECT_EQ(cast<ConstantInt>(InitCall->getArgOperand(8))->getSExtValue(), 5);
2053 
2054   CallInst *FiniCall = findSingleCall(
2055       F, omp::RuntimeFunction::OMPRTL___kmpc_for_static_fini, OMPBuilder);
2056   EXPECT_EQ(FiniCall->getParent(), DispatchExit);
2057 
2058   CallInst *BarrierCall = findSingleCall(
2059       F, omp::RuntimeFunction::OMPRTL___kmpc_barrier, OMPBuilder);
2060   EXPECT_EQ(BarrierCall->getParent(), DispatchExit);
2061 }
2062 
2063 INSTANTIATE_TEST_SUITE_P(IVBits, OpenMPIRBuilderTestWithIVBits,
2064                          ::testing::Values(8, 16, 32, 64));
2065 
2066 TEST_P(OpenMPIRBuilderTestWithParams, DynamicWorkShareLoop) {
2067   using InsertPointTy = OpenMPIRBuilder::InsertPointTy;
2068   OpenMPIRBuilder OMPBuilder(*M);
2069   OMPBuilder.initialize();
2070   IRBuilder<> Builder(BB);
2071   OpenMPIRBuilder::LocationDescription Loc({Builder.saveIP(), DL});
2072 
2073   omp::OMPScheduleType SchedType = GetParam();
2074   uint32_t ChunkSize = 1;
2075   switch (SchedType & ~OMPScheduleType::ModifierMask) {
2076   case omp::OMPScheduleType::BaseDynamicChunked:
2077   case omp::OMPScheduleType::BaseGuidedChunked:
2078     ChunkSize = 7;
2079     break;
2080   case omp::OMPScheduleType::BaseAuto:
2081   case omp::OMPScheduleType::BaseRuntime:
2082     ChunkSize = 1;
2083     break;
2084   default:
2085     assert(0 && "unknown type for this test");
2086     break;
2087   }
2088 
2089   Type *LCTy = Type::getInt32Ty(Ctx);
2090   Value *StartVal = ConstantInt::get(LCTy, 10);
2091   Value *StopVal = ConstantInt::get(LCTy, 52);
2092   Value *StepVal = ConstantInt::get(LCTy, 2);
2093   Value *ChunkVal =
2094       (ChunkSize == 1) ? nullptr : ConstantInt::get(LCTy, ChunkSize);
2095   auto LoopBodyGen = [&](InsertPointTy, llvm::Value *) {};
2096 
2097   CanonicalLoopInfo *CLI = OMPBuilder.createCanonicalLoop(
2098       Loc, LoopBodyGen, StartVal, StopVal, StepVal,
2099       /*IsSigned=*/false, /*InclusiveStop=*/false);
2100 
2101   Builder.SetInsertPoint(BB, BB->getFirstInsertionPt());
2102   InsertPointTy AllocaIP = Builder.saveIP();
2103 
2104   // Collect all the info from CLI, as it isn't usable after the call to
2105   // createDynamicWorkshareLoop.
2106   InsertPointTy AfterIP = CLI->getAfterIP();
2107   BasicBlock *Preheader = CLI->getPreheader();
2108   BasicBlock *ExitBlock = CLI->getExit();
2109   BasicBlock *LatchBlock = CLI->getLatch();
2110   Value *IV = CLI->getIndVar();
2111 
2112   InsertPointTy EndIP = OMPBuilder.applyWorkshareLoop(
2113       DL, CLI, AllocaIP, /*NeedsBarrier=*/true, getSchedKind(SchedType),
2114       ChunkVal, /*Simd=*/false,
2115       (SchedType & omp::OMPScheduleType::ModifierMonotonic) ==
2116           omp::OMPScheduleType::ModifierMonotonic,
2117       (SchedType & omp::OMPScheduleType::ModifierNonmonotonic) ==
2118           omp::OMPScheduleType::ModifierNonmonotonic,
2119       /*Ordered=*/false);
2120 
2121   // The returned value should be the "after" point.
2122   ASSERT_EQ(EndIP.getBlock(), AfterIP.getBlock());
2123   ASSERT_EQ(EndIP.getPoint(), AfterIP.getPoint());
2124 
2125   auto AllocaIter = BB->begin();
2126   ASSERT_GE(std::distance(BB->begin(), BB->end()), 4);
2127   AllocaInst *PLastIter = dyn_cast<AllocaInst>(&*(AllocaIter++));
2128   AllocaInst *PLowerBound = dyn_cast<AllocaInst>(&*(AllocaIter++));
2129   AllocaInst *PUpperBound = dyn_cast<AllocaInst>(&*(AllocaIter++));
2130   AllocaInst *PStride = dyn_cast<AllocaInst>(&*(AllocaIter++));
2131   EXPECT_NE(PLastIter, nullptr);
2132   EXPECT_NE(PLowerBound, nullptr);
2133   EXPECT_NE(PUpperBound, nullptr);
2134   EXPECT_NE(PStride, nullptr);
2135 
2136   auto PreheaderIter = Preheader->begin();
2137   ASSERT_GE(std::distance(Preheader->begin(), Preheader->end()), 6);
2138   StoreInst *LowerBoundStore = dyn_cast<StoreInst>(&*(PreheaderIter++));
2139   StoreInst *UpperBoundStore = dyn_cast<StoreInst>(&*(PreheaderIter++));
2140   StoreInst *StrideStore = dyn_cast<StoreInst>(&*(PreheaderIter++));
2141   ASSERT_NE(LowerBoundStore, nullptr);
2142   ASSERT_NE(UpperBoundStore, nullptr);
2143   ASSERT_NE(StrideStore, nullptr);
2144 
2145   CallInst *ThreadIdCall = dyn_cast<CallInst>(&*(PreheaderIter++));
2146   ASSERT_NE(ThreadIdCall, nullptr);
2147   EXPECT_EQ(ThreadIdCall->getCalledFunction()->getName(),
2148             "__kmpc_global_thread_num");
2149 
2150   CallInst *InitCall = dyn_cast<CallInst>(&*PreheaderIter);
2151 
2152   ASSERT_NE(InitCall, nullptr);
2153   EXPECT_EQ(InitCall->getCalledFunction()->getName(),
2154             "__kmpc_dispatch_init_4u");
2155   EXPECT_EQ(InitCall->arg_size(), 7U);
2156   EXPECT_EQ(InitCall->getArgOperand(6), ConstantInt::get(LCTy, ChunkSize));
2157   ConstantInt *SchedVal = cast<ConstantInt>(InitCall->getArgOperand(2));
2158   if ((SchedType & OMPScheduleType::MonotonicityMask) ==
2159       OMPScheduleType::None) {
2160     // Implementation is allowed to add default nonmonotonicity flag
2161     EXPECT_EQ(
2162         static_cast<OMPScheduleType>(SchedVal->getValue().getZExtValue()) |
2163             OMPScheduleType::ModifierNonmonotonic,
2164         SchedType | OMPScheduleType::ModifierNonmonotonic);
2165   } else {
2166     EXPECT_EQ(static_cast<OMPScheduleType>(SchedVal->getValue().getZExtValue()),
2167               SchedType);
2168   }
2169 
2170   ConstantInt *OrigLowerBound =
2171       dyn_cast<ConstantInt>(LowerBoundStore->getValueOperand());
2172   ConstantInt *OrigUpperBound =
2173       dyn_cast<ConstantInt>(UpperBoundStore->getValueOperand());
2174   ConstantInt *OrigStride =
2175       dyn_cast<ConstantInt>(StrideStore->getValueOperand());
2176   ASSERT_NE(OrigLowerBound, nullptr);
2177   ASSERT_NE(OrigUpperBound, nullptr);
2178   ASSERT_NE(OrigStride, nullptr);
2179   EXPECT_EQ(OrigLowerBound->getValue(), 1);
2180   EXPECT_EQ(OrigUpperBound->getValue(), 21);
2181   EXPECT_EQ(OrigStride->getValue(), 1);
2182 
2183   CallInst *FiniCall = dyn_cast<CallInst>(
2184       &*(LatchBlock->getTerminator()->getPrevNonDebugInstruction(true)));
2185   EXPECT_EQ(FiniCall, nullptr);
2186 
2187   // The original loop iterator should only be used in the condition, in the
2188   // increment and in the statement that adds the lower bound to it.
2189   EXPECT_EQ(std::distance(IV->use_begin(), IV->use_end()), 3);
2190 
2191   // The exit block should contain the barrier call, plus the call to obtain
2192   // the thread ID.
2193   size_t NumCallsInExitBlock =
2194       count_if(*ExitBlock, [](Instruction &I) { return isa<CallInst>(I); });
2195   EXPECT_EQ(NumCallsInExitBlock, 2u);
2196 
2197   // Add a termination to our block and check that it is internally consistent.
2198   Builder.restoreIP(EndIP);
2199   Builder.CreateRetVoid();
2200   OMPBuilder.finalize();
2201   EXPECT_FALSE(verifyModule(*M, &errs()));
2202 }
2203 
2204 INSTANTIATE_TEST_SUITE_P(
2205     OpenMPWSLoopSchedulingTypes, OpenMPIRBuilderTestWithParams,
2206     ::testing::Values(omp::OMPScheduleType::UnorderedDynamicChunked,
2207                       omp::OMPScheduleType::UnorderedGuidedChunked,
2208                       omp::OMPScheduleType::UnorderedAuto,
2209                       omp::OMPScheduleType::UnorderedRuntime,
2210                       omp::OMPScheduleType::UnorderedDynamicChunked |
2211                           omp::OMPScheduleType::ModifierMonotonic,
2212                       omp::OMPScheduleType::UnorderedDynamicChunked |
2213                           omp::OMPScheduleType::ModifierNonmonotonic,
2214                       omp::OMPScheduleType::UnorderedGuidedChunked |
2215                           omp::OMPScheduleType::ModifierMonotonic,
2216                       omp::OMPScheduleType::UnorderedGuidedChunked |
2217                           omp::OMPScheduleType::ModifierNonmonotonic,
2218                       omp::OMPScheduleType::UnorderedAuto |
2219                           omp::OMPScheduleType::ModifierMonotonic,
2220                       omp::OMPScheduleType::UnorderedRuntime |
2221                           omp::OMPScheduleType::ModifierMonotonic));
2222 
2223 TEST_F(OpenMPIRBuilderTest, DynamicWorkShareLoopOrdered) {
2224   using InsertPointTy = OpenMPIRBuilder::InsertPointTy;
2225   OpenMPIRBuilder OMPBuilder(*M);
2226   OMPBuilder.initialize();
2227   IRBuilder<> Builder(BB);
2228   OpenMPIRBuilder::LocationDescription Loc({Builder.saveIP(), DL});
2229 
2230   uint32_t ChunkSize = 1;
2231   Type *LCTy = Type::getInt32Ty(Ctx);
2232   Value *StartVal = ConstantInt::get(LCTy, 10);
2233   Value *StopVal = ConstantInt::get(LCTy, 52);
2234   Value *StepVal = ConstantInt::get(LCTy, 2);
2235   Value *ChunkVal = ConstantInt::get(LCTy, ChunkSize);
2236   auto LoopBodyGen = [&](InsertPointTy, llvm::Value *) {};
2237 
2238   CanonicalLoopInfo *CLI = OMPBuilder.createCanonicalLoop(
2239       Loc, LoopBodyGen, StartVal, StopVal, StepVal,
2240       /*IsSigned=*/false, /*InclusiveStop=*/false);
2241 
2242   Builder.SetInsertPoint(BB, BB->getFirstInsertionPt());
2243   InsertPointTy AllocaIP = Builder.saveIP();
2244 
2245   // Collect all the info from CLI, as it isn't usable after the call to
2246   // createDynamicWorkshareLoop.
2247   BasicBlock *Preheader = CLI->getPreheader();
2248   BasicBlock *ExitBlock = CLI->getExit();
2249   BasicBlock *LatchBlock = CLI->getLatch();
2250   Value *IV = CLI->getIndVar();
2251 
2252   InsertPointTy EndIP = OMPBuilder.applyWorkshareLoop(
2253       DL, CLI, AllocaIP, /*NeedsBarrier=*/true, OMP_SCHEDULE_Static, ChunkVal,
2254       /*HasSimdModifier=*/false, /*HasMonotonicModifier=*/false,
2255       /*HasNonmonotonicModifier=*/false,
2256       /*HasOrderedClause=*/true);
2257 
2258   // Add a termination to our block and check that it is internally consistent.
2259   Builder.restoreIP(EndIP);
2260   Builder.CreateRetVoid();
2261   OMPBuilder.finalize();
2262   EXPECT_FALSE(verifyModule(*M, &errs()));
2263 
2264   CallInst *InitCall = nullptr;
2265   for (Instruction &EI : *Preheader) {
2266     Instruction *Cur = &EI;
2267     if (isa<CallInst>(Cur)) {
2268       InitCall = cast<CallInst>(Cur);
2269       if (InitCall->getCalledFunction()->getName() == "__kmpc_dispatch_init_4u")
2270         break;
2271       InitCall = nullptr;
2272     }
2273   }
2274   EXPECT_NE(InitCall, nullptr);
2275   EXPECT_EQ(InitCall->arg_size(), 7U);
2276   ConstantInt *SchedVal = cast<ConstantInt>(InitCall->getArgOperand(2));
2277   EXPECT_EQ(SchedVal->getValue(),
2278             static_cast<uint64_t>(OMPScheduleType::OrderedStaticChunked));
2279 
2280   CallInst *FiniCall = dyn_cast<CallInst>(
2281       &*(LatchBlock->getTerminator()->getPrevNonDebugInstruction(true)));
2282   ASSERT_NE(FiniCall, nullptr);
2283   EXPECT_EQ(FiniCall->getCalledFunction()->getName(),
2284             "__kmpc_dispatch_fini_4u");
2285   EXPECT_EQ(FiniCall->arg_size(), 2U);
2286   EXPECT_EQ(InitCall->getArgOperand(0), FiniCall->getArgOperand(0));
2287   EXPECT_EQ(InitCall->getArgOperand(1), FiniCall->getArgOperand(1));
2288 
2289   // The original loop iterator should only be used in the condition, in the
2290   // increment and in the statement that adds the lower bound to it.
2291   EXPECT_EQ(std::distance(IV->use_begin(), IV->use_end()), 3);
2292 
2293   // The exit block should contain the barrier call, plus the call to obtain
2294   // the thread ID.
2295   size_t NumCallsInExitBlock =
2296       count_if(*ExitBlock, [](Instruction &I) { return isa<CallInst>(I); });
2297   EXPECT_EQ(NumCallsInExitBlock, 2u);
2298 }
2299 
2300 TEST_F(OpenMPIRBuilderTest, MasterDirective) {
2301   using InsertPointTy = OpenMPIRBuilder::InsertPointTy;
2302   OpenMPIRBuilder OMPBuilder(*M);
2303   OMPBuilder.initialize();
2304   F->setName("func");
2305   IRBuilder<> Builder(BB);
2306 
2307   OpenMPIRBuilder::LocationDescription Loc({Builder.saveIP(), DL});
2308 
2309   AllocaInst *PrivAI = nullptr;
2310 
2311   BasicBlock *EntryBB = nullptr;
2312   BasicBlock *ExitBB = nullptr;
2313   BasicBlock *ThenBB = nullptr;
2314 
2315   auto BodyGenCB = [&](InsertPointTy AllocaIP, InsertPointTy CodeGenIP,
2316                        BasicBlock &FiniBB) {
2317     if (AllocaIP.isSet())
2318       Builder.restoreIP(AllocaIP);
2319     else
2320       Builder.SetInsertPoint(&*(F->getEntryBlock().getFirstInsertionPt()));
2321     PrivAI = Builder.CreateAlloca(F->arg_begin()->getType());
2322     Builder.CreateStore(F->arg_begin(), PrivAI);
2323 
2324     llvm::BasicBlock *CodeGenIPBB = CodeGenIP.getBlock();
2325     llvm::Instruction *CodeGenIPInst = &*CodeGenIP.getPoint();
2326     EXPECT_EQ(CodeGenIPBB->getTerminator(), CodeGenIPInst);
2327 
2328     Builder.restoreIP(CodeGenIP);
2329 
2330     // collect some info for checks later
2331     ExitBB = FiniBB.getUniqueSuccessor();
2332     ThenBB = Builder.GetInsertBlock();
2333     EntryBB = ThenBB->getUniquePredecessor();
2334 
2335     // simple instructions for body
2336     Value *PrivLoad =
2337         Builder.CreateLoad(PrivAI->getAllocatedType(), PrivAI, "local.use");
2338     Builder.CreateICmpNE(F->arg_begin(), PrivLoad);
2339   };
2340 
2341   auto FiniCB = [&](InsertPointTy IP) {
2342     BasicBlock *IPBB = IP.getBlock();
2343     EXPECT_NE(IPBB->end(), IP.getPoint());
2344   };
2345 
2346   Builder.restoreIP(OMPBuilder.createMaster(Builder, BodyGenCB, FiniCB));
2347   Value *EntryBBTI = EntryBB->getTerminator();
2348   EXPECT_NE(EntryBBTI, nullptr);
2349   EXPECT_TRUE(isa<BranchInst>(EntryBBTI));
2350   BranchInst *EntryBr = cast<BranchInst>(EntryBB->getTerminator());
2351   EXPECT_TRUE(EntryBr->isConditional());
2352   EXPECT_EQ(EntryBr->getSuccessor(0), ThenBB);
2353   EXPECT_EQ(ThenBB->getUniqueSuccessor(), ExitBB);
2354   EXPECT_EQ(EntryBr->getSuccessor(1), ExitBB);
2355 
2356   CmpInst *CondInst = cast<CmpInst>(EntryBr->getCondition());
2357   EXPECT_TRUE(isa<CallInst>(CondInst->getOperand(0)));
2358 
2359   CallInst *MasterEntryCI = cast<CallInst>(CondInst->getOperand(0));
2360   EXPECT_EQ(MasterEntryCI->arg_size(), 2U);
2361   EXPECT_EQ(MasterEntryCI->getCalledFunction()->getName(), "__kmpc_master");
2362   EXPECT_TRUE(isa<GlobalVariable>(MasterEntryCI->getArgOperand(0)));
2363 
2364   CallInst *MasterEndCI = nullptr;
2365   for (auto &FI : *ThenBB) {
2366     Instruction *cur = &FI;
2367     if (isa<CallInst>(cur)) {
2368       MasterEndCI = cast<CallInst>(cur);
2369       if (MasterEndCI->getCalledFunction()->getName() == "__kmpc_end_master")
2370         break;
2371       MasterEndCI = nullptr;
2372     }
2373   }
2374   EXPECT_NE(MasterEndCI, nullptr);
2375   EXPECT_EQ(MasterEndCI->arg_size(), 2U);
2376   EXPECT_TRUE(isa<GlobalVariable>(MasterEndCI->getArgOperand(0)));
2377   EXPECT_EQ(MasterEndCI->getArgOperand(1), MasterEntryCI->getArgOperand(1));
2378 }
2379 
2380 TEST_F(OpenMPIRBuilderTest, MaskedDirective) {
2381   using InsertPointTy = OpenMPIRBuilder::InsertPointTy;
2382   OpenMPIRBuilder OMPBuilder(*M);
2383   OMPBuilder.initialize();
2384   F->setName("func");
2385   IRBuilder<> Builder(BB);
2386 
2387   OpenMPIRBuilder::LocationDescription Loc({Builder.saveIP(), DL});
2388 
2389   AllocaInst *PrivAI = nullptr;
2390 
2391   BasicBlock *EntryBB = nullptr;
2392   BasicBlock *ExitBB = nullptr;
2393   BasicBlock *ThenBB = nullptr;
2394 
2395   auto BodyGenCB = [&](InsertPointTy AllocaIP, InsertPointTy CodeGenIP,
2396                        BasicBlock &FiniBB) {
2397     if (AllocaIP.isSet())
2398       Builder.restoreIP(AllocaIP);
2399     else
2400       Builder.SetInsertPoint(&*(F->getEntryBlock().getFirstInsertionPt()));
2401     PrivAI = Builder.CreateAlloca(F->arg_begin()->getType());
2402     Builder.CreateStore(F->arg_begin(), PrivAI);
2403 
2404     llvm::BasicBlock *CodeGenIPBB = CodeGenIP.getBlock();
2405     llvm::Instruction *CodeGenIPInst = &*CodeGenIP.getPoint();
2406     EXPECT_EQ(CodeGenIPBB->getTerminator(), CodeGenIPInst);
2407 
2408     Builder.restoreIP(CodeGenIP);
2409 
2410     // collect some info for checks later
2411     ExitBB = FiniBB.getUniqueSuccessor();
2412     ThenBB = Builder.GetInsertBlock();
2413     EntryBB = ThenBB->getUniquePredecessor();
2414 
2415     // simple instructions for body
2416     Value *PrivLoad =
2417         Builder.CreateLoad(PrivAI->getAllocatedType(), PrivAI, "local.use");
2418     Builder.CreateICmpNE(F->arg_begin(), PrivLoad);
2419   };
2420 
2421   auto FiniCB = [&](InsertPointTy IP) {
2422     BasicBlock *IPBB = IP.getBlock();
2423     EXPECT_NE(IPBB->end(), IP.getPoint());
2424   };
2425 
2426   Constant *Filter = ConstantInt::get(Type::getInt32Ty(M->getContext()), 0);
2427   Builder.restoreIP(
2428       OMPBuilder.createMasked(Builder, BodyGenCB, FiniCB, Filter));
2429   Value *EntryBBTI = EntryBB->getTerminator();
2430   EXPECT_NE(EntryBBTI, nullptr);
2431   EXPECT_TRUE(isa<BranchInst>(EntryBBTI));
2432   BranchInst *EntryBr = cast<BranchInst>(EntryBB->getTerminator());
2433   EXPECT_TRUE(EntryBr->isConditional());
2434   EXPECT_EQ(EntryBr->getSuccessor(0), ThenBB);
2435   EXPECT_EQ(ThenBB->getUniqueSuccessor(), ExitBB);
2436   EXPECT_EQ(EntryBr->getSuccessor(1), ExitBB);
2437 
2438   CmpInst *CondInst = cast<CmpInst>(EntryBr->getCondition());
2439   EXPECT_TRUE(isa<CallInst>(CondInst->getOperand(0)));
2440 
2441   CallInst *MaskedEntryCI = cast<CallInst>(CondInst->getOperand(0));
2442   EXPECT_EQ(MaskedEntryCI->arg_size(), 3U);
2443   EXPECT_EQ(MaskedEntryCI->getCalledFunction()->getName(), "__kmpc_masked");
2444   EXPECT_TRUE(isa<GlobalVariable>(MaskedEntryCI->getArgOperand(0)));
2445 
2446   CallInst *MaskedEndCI = nullptr;
2447   for (auto &FI : *ThenBB) {
2448     Instruction *cur = &FI;
2449     if (isa<CallInst>(cur)) {
2450       MaskedEndCI = cast<CallInst>(cur);
2451       if (MaskedEndCI->getCalledFunction()->getName() == "__kmpc_end_masked")
2452         break;
2453       MaskedEndCI = nullptr;
2454     }
2455   }
2456   EXPECT_NE(MaskedEndCI, nullptr);
2457   EXPECT_EQ(MaskedEndCI->arg_size(), 2U);
2458   EXPECT_TRUE(isa<GlobalVariable>(MaskedEndCI->getArgOperand(0)));
2459   EXPECT_EQ(MaskedEndCI->getArgOperand(1), MaskedEntryCI->getArgOperand(1));
2460 }
2461 
2462 TEST_F(OpenMPIRBuilderTest, CriticalDirective) {
2463   using InsertPointTy = OpenMPIRBuilder::InsertPointTy;
2464   OpenMPIRBuilder OMPBuilder(*M);
2465   OMPBuilder.initialize();
2466   F->setName("func");
2467   IRBuilder<> Builder(BB);
2468 
2469   OpenMPIRBuilder::LocationDescription Loc({Builder.saveIP(), DL});
2470 
2471   AllocaInst *PrivAI = Builder.CreateAlloca(F->arg_begin()->getType());
2472 
2473   BasicBlock *EntryBB = nullptr;
2474 
2475   auto BodyGenCB = [&](InsertPointTy AllocaIP, InsertPointTy CodeGenIP,
2476                        BasicBlock &FiniBB) {
2477     // collect some info for checks later
2478     EntryBB = FiniBB.getUniquePredecessor();
2479 
2480     // actual start for bodyCB
2481     llvm::BasicBlock *CodeGenIPBB = CodeGenIP.getBlock();
2482     llvm::Instruction *CodeGenIPInst = &*CodeGenIP.getPoint();
2483     EXPECT_EQ(CodeGenIPBB->getTerminator(), CodeGenIPInst);
2484     EXPECT_EQ(EntryBB, CodeGenIPBB);
2485 
2486     // body begin
2487     Builder.restoreIP(CodeGenIP);
2488     Builder.CreateStore(F->arg_begin(), PrivAI);
2489     Value *PrivLoad =
2490         Builder.CreateLoad(PrivAI->getAllocatedType(), PrivAI, "local.use");
2491     Builder.CreateICmpNE(F->arg_begin(), PrivLoad);
2492   };
2493 
2494   auto FiniCB = [&](InsertPointTy IP) {
2495     BasicBlock *IPBB = IP.getBlock();
2496     EXPECT_NE(IPBB->end(), IP.getPoint());
2497   };
2498 
2499   Builder.restoreIP(OMPBuilder.createCritical(Builder, BodyGenCB, FiniCB,
2500                                               "testCRT", nullptr));
2501 
2502   Value *EntryBBTI = EntryBB->getTerminator();
2503   EXPECT_EQ(EntryBBTI, nullptr);
2504 
2505   CallInst *CriticalEntryCI = nullptr;
2506   for (auto &EI : *EntryBB) {
2507     Instruction *cur = &EI;
2508     if (isa<CallInst>(cur)) {
2509       CriticalEntryCI = cast<CallInst>(cur);
2510       if (CriticalEntryCI->getCalledFunction()->getName() == "__kmpc_critical")
2511         break;
2512       CriticalEntryCI = nullptr;
2513     }
2514   }
2515   EXPECT_NE(CriticalEntryCI, nullptr);
2516   EXPECT_EQ(CriticalEntryCI->arg_size(), 3U);
2517   EXPECT_EQ(CriticalEntryCI->getCalledFunction()->getName(), "__kmpc_critical");
2518   EXPECT_TRUE(isa<GlobalVariable>(CriticalEntryCI->getArgOperand(0)));
2519 
2520   CallInst *CriticalEndCI = nullptr;
2521   for (auto &FI : *EntryBB) {
2522     Instruction *cur = &FI;
2523     if (isa<CallInst>(cur)) {
2524       CriticalEndCI = cast<CallInst>(cur);
2525       if (CriticalEndCI->getCalledFunction()->getName() ==
2526           "__kmpc_end_critical")
2527         break;
2528       CriticalEndCI = nullptr;
2529     }
2530   }
2531   EXPECT_NE(CriticalEndCI, nullptr);
2532   EXPECT_EQ(CriticalEndCI->arg_size(), 3U);
2533   EXPECT_TRUE(isa<GlobalVariable>(CriticalEndCI->getArgOperand(0)));
2534   EXPECT_EQ(CriticalEndCI->getArgOperand(1), CriticalEntryCI->getArgOperand(1));
2535   PointerType *CriticalNamePtrTy =
2536       PointerType::getUnqual(ArrayType::get(Type::getInt32Ty(Ctx), 8));
2537   EXPECT_EQ(CriticalEndCI->getArgOperand(2), CriticalEntryCI->getArgOperand(2));
2538   EXPECT_EQ(CriticalEndCI->getArgOperand(2)->getType(), CriticalNamePtrTy);
2539 }
2540 
2541 TEST_F(OpenMPIRBuilderTest, OrderedDirectiveDependSource) {
2542   using InsertPointTy = OpenMPIRBuilder::InsertPointTy;
2543   OpenMPIRBuilder OMPBuilder(*M);
2544   OMPBuilder.initialize();
2545   F->setName("func");
2546   IRBuilder<> Builder(BB);
2547   LLVMContext &Ctx = M->getContext();
2548 
2549   OpenMPIRBuilder::LocationDescription Loc({Builder.saveIP(), DL});
2550 
2551   InsertPointTy AllocaIP(&F->getEntryBlock(),
2552                          F->getEntryBlock().getFirstInsertionPt());
2553 
2554   unsigned NumLoops = 2;
2555   SmallVector<Value *, 2> StoreValues;
2556   Type *LCTy = Type::getInt64Ty(Ctx);
2557   StoreValues.emplace_back(ConstantInt::get(LCTy, 1));
2558   StoreValues.emplace_back(ConstantInt::get(LCTy, 2));
2559 
2560   // Test for "#omp ordered depend(source)"
2561   Builder.restoreIP(OMPBuilder.createOrderedDepend(Builder, AllocaIP, NumLoops,
2562                                                    StoreValues, ".cnt.addr",
2563                                                    /*IsDependSource=*/true));
2564 
2565   Builder.CreateRetVoid();
2566   OMPBuilder.finalize();
2567   EXPECT_FALSE(verifyModule(*M, &errs()));
2568 
2569   AllocaInst *AllocInst = dyn_cast<AllocaInst>(&BB->front());
2570   ASSERT_NE(AllocInst, nullptr);
2571   ArrayType *ArrType = dyn_cast<ArrayType>(AllocInst->getAllocatedType());
2572   EXPECT_EQ(ArrType->getNumElements(), NumLoops);
2573   EXPECT_TRUE(
2574       AllocInst->getAllocatedType()->getArrayElementType()->isIntegerTy(64));
2575 
2576   Instruction *IterInst = dyn_cast<Instruction>(AllocInst);
2577   for (unsigned Iter = 0; Iter < NumLoops; Iter++) {
2578     GetElementPtrInst *DependAddrGEPIter =
2579         dyn_cast<GetElementPtrInst>(IterInst->getNextNode());
2580     ASSERT_NE(DependAddrGEPIter, nullptr);
2581     EXPECT_EQ(DependAddrGEPIter->getPointerOperand(), AllocInst);
2582     EXPECT_EQ(DependAddrGEPIter->getNumIndices(), (unsigned)2);
2583     auto *FirstIdx = dyn_cast<ConstantInt>(DependAddrGEPIter->getOperand(1));
2584     auto *SecondIdx = dyn_cast<ConstantInt>(DependAddrGEPIter->getOperand(2));
2585     ASSERT_NE(FirstIdx, nullptr);
2586     ASSERT_NE(SecondIdx, nullptr);
2587     EXPECT_EQ(FirstIdx->getValue(), 0);
2588     EXPECT_EQ(SecondIdx->getValue(), Iter);
2589     StoreInst *StoreValue =
2590         dyn_cast<StoreInst>(DependAddrGEPIter->getNextNode());
2591     ASSERT_NE(StoreValue, nullptr);
2592     EXPECT_EQ(StoreValue->getValueOperand(), StoreValues[Iter]);
2593     EXPECT_EQ(StoreValue->getPointerOperand(), DependAddrGEPIter);
2594     EXPECT_EQ(StoreValue->getAlignment(), 8UL);
2595     IterInst = dyn_cast<Instruction>(StoreValue);
2596   }
2597 
2598   GetElementPtrInst *DependBaseAddrGEP =
2599       dyn_cast<GetElementPtrInst>(IterInst->getNextNode());
2600   ASSERT_NE(DependBaseAddrGEP, nullptr);
2601   EXPECT_EQ(DependBaseAddrGEP->getPointerOperand(), AllocInst);
2602   EXPECT_EQ(DependBaseAddrGEP->getNumIndices(), (unsigned)2);
2603   auto *FirstIdx = dyn_cast<ConstantInt>(DependBaseAddrGEP->getOperand(1));
2604   auto *SecondIdx = dyn_cast<ConstantInt>(DependBaseAddrGEP->getOperand(2));
2605   ASSERT_NE(FirstIdx, nullptr);
2606   ASSERT_NE(SecondIdx, nullptr);
2607   EXPECT_EQ(FirstIdx->getValue(), 0);
2608   EXPECT_EQ(SecondIdx->getValue(), 0);
2609 
2610   CallInst *GTID = dyn_cast<CallInst>(DependBaseAddrGEP->getNextNode());
2611   ASSERT_NE(GTID, nullptr);
2612   EXPECT_EQ(GTID->arg_size(), 1U);
2613   EXPECT_EQ(GTID->getCalledFunction()->getName(), "__kmpc_global_thread_num");
2614   EXPECT_FALSE(GTID->getCalledFunction()->doesNotAccessMemory());
2615   EXPECT_FALSE(GTID->getCalledFunction()->doesNotFreeMemory());
2616 
2617   CallInst *Depend = dyn_cast<CallInst>(GTID->getNextNode());
2618   ASSERT_NE(Depend, nullptr);
2619   EXPECT_EQ(Depend->arg_size(), 3U);
2620   EXPECT_EQ(Depend->getCalledFunction()->getName(), "__kmpc_doacross_post");
2621   EXPECT_TRUE(isa<GlobalVariable>(Depend->getArgOperand(0)));
2622   EXPECT_EQ(Depend->getArgOperand(1), GTID);
2623   EXPECT_EQ(Depend->getArgOperand(2), DependBaseAddrGEP);
2624 }
2625 
2626 TEST_F(OpenMPIRBuilderTest, OrderedDirectiveDependSink) {
2627   using InsertPointTy = OpenMPIRBuilder::InsertPointTy;
2628   OpenMPIRBuilder OMPBuilder(*M);
2629   OMPBuilder.initialize();
2630   F->setName("func");
2631   IRBuilder<> Builder(BB);
2632   LLVMContext &Ctx = M->getContext();
2633 
2634   OpenMPIRBuilder::LocationDescription Loc({Builder.saveIP(), DL});
2635 
2636   InsertPointTy AllocaIP(&F->getEntryBlock(),
2637                          F->getEntryBlock().getFirstInsertionPt());
2638 
2639   unsigned NumLoops = 2;
2640   SmallVector<Value *, 2> StoreValues;
2641   Type *LCTy = Type::getInt64Ty(Ctx);
2642   StoreValues.emplace_back(ConstantInt::get(LCTy, 1));
2643   StoreValues.emplace_back(ConstantInt::get(LCTy, 2));
2644 
2645   // Test for "#omp ordered depend(sink: vec)"
2646   Builder.restoreIP(OMPBuilder.createOrderedDepend(Builder, AllocaIP, NumLoops,
2647                                                    StoreValues, ".cnt.addr",
2648                                                    /*IsDependSource=*/false));
2649 
2650   Builder.CreateRetVoid();
2651   OMPBuilder.finalize();
2652   EXPECT_FALSE(verifyModule(*M, &errs()));
2653 
2654   AllocaInst *AllocInst = dyn_cast<AllocaInst>(&BB->front());
2655   ASSERT_NE(AllocInst, nullptr);
2656   ArrayType *ArrType = dyn_cast<ArrayType>(AllocInst->getAllocatedType());
2657   EXPECT_EQ(ArrType->getNumElements(), NumLoops);
2658   EXPECT_TRUE(
2659       AllocInst->getAllocatedType()->getArrayElementType()->isIntegerTy(64));
2660 
2661   Instruction *IterInst = dyn_cast<Instruction>(AllocInst);
2662   for (unsigned Iter = 0; Iter < NumLoops; Iter++) {
2663     GetElementPtrInst *DependAddrGEPIter =
2664         dyn_cast<GetElementPtrInst>(IterInst->getNextNode());
2665     ASSERT_NE(DependAddrGEPIter, nullptr);
2666     EXPECT_EQ(DependAddrGEPIter->getPointerOperand(), AllocInst);
2667     EXPECT_EQ(DependAddrGEPIter->getNumIndices(), (unsigned)2);
2668     auto *FirstIdx = dyn_cast<ConstantInt>(DependAddrGEPIter->getOperand(1));
2669     auto *SecondIdx = dyn_cast<ConstantInt>(DependAddrGEPIter->getOperand(2));
2670     ASSERT_NE(FirstIdx, nullptr);
2671     ASSERT_NE(SecondIdx, nullptr);
2672     EXPECT_EQ(FirstIdx->getValue(), 0);
2673     EXPECT_EQ(SecondIdx->getValue(), Iter);
2674     StoreInst *StoreValue =
2675         dyn_cast<StoreInst>(DependAddrGEPIter->getNextNode());
2676     ASSERT_NE(StoreValue, nullptr);
2677     EXPECT_EQ(StoreValue->getValueOperand(), StoreValues[Iter]);
2678     EXPECT_EQ(StoreValue->getPointerOperand(), DependAddrGEPIter);
2679     EXPECT_EQ(StoreValue->getAlignment(), 8UL);
2680     IterInst = dyn_cast<Instruction>(StoreValue);
2681   }
2682 
2683   GetElementPtrInst *DependBaseAddrGEP =
2684       dyn_cast<GetElementPtrInst>(IterInst->getNextNode());
2685   ASSERT_NE(DependBaseAddrGEP, nullptr);
2686   EXPECT_EQ(DependBaseAddrGEP->getPointerOperand(), AllocInst);
2687   EXPECT_EQ(DependBaseAddrGEP->getNumIndices(), (unsigned)2);
2688   auto *FirstIdx = dyn_cast<ConstantInt>(DependBaseAddrGEP->getOperand(1));
2689   auto *SecondIdx = dyn_cast<ConstantInt>(DependBaseAddrGEP->getOperand(2));
2690   ASSERT_NE(FirstIdx, nullptr);
2691   ASSERT_NE(SecondIdx, nullptr);
2692   EXPECT_EQ(FirstIdx->getValue(), 0);
2693   EXPECT_EQ(SecondIdx->getValue(), 0);
2694 
2695   CallInst *GTID = dyn_cast<CallInst>(DependBaseAddrGEP->getNextNode());
2696   ASSERT_NE(GTID, nullptr);
2697   EXPECT_EQ(GTID->arg_size(), 1U);
2698   EXPECT_EQ(GTID->getCalledFunction()->getName(), "__kmpc_global_thread_num");
2699   EXPECT_FALSE(GTID->getCalledFunction()->doesNotAccessMemory());
2700   EXPECT_FALSE(GTID->getCalledFunction()->doesNotFreeMemory());
2701 
2702   CallInst *Depend = dyn_cast<CallInst>(GTID->getNextNode());
2703   ASSERT_NE(Depend, nullptr);
2704   EXPECT_EQ(Depend->arg_size(), 3U);
2705   EXPECT_EQ(Depend->getCalledFunction()->getName(), "__kmpc_doacross_wait");
2706   EXPECT_TRUE(isa<GlobalVariable>(Depend->getArgOperand(0)));
2707   EXPECT_EQ(Depend->getArgOperand(1), GTID);
2708   EXPECT_EQ(Depend->getArgOperand(2), DependBaseAddrGEP);
2709 }
2710 
2711 TEST_F(OpenMPIRBuilderTest, OrderedDirectiveThreads) {
2712   using InsertPointTy = OpenMPIRBuilder::InsertPointTy;
2713   OpenMPIRBuilder OMPBuilder(*M);
2714   OMPBuilder.initialize();
2715   F->setName("func");
2716   IRBuilder<> Builder(BB);
2717 
2718   OpenMPIRBuilder::LocationDescription Loc({Builder.saveIP(), DL});
2719 
2720   AllocaInst *PrivAI =
2721       Builder.CreateAlloca(F->arg_begin()->getType(), nullptr, "priv.inst");
2722 
2723   BasicBlock *EntryBB = nullptr;
2724 
2725   auto BodyGenCB = [&](InsertPointTy AllocaIP, InsertPointTy CodeGenIP,
2726                        BasicBlock &FiniBB) {
2727     EntryBB = FiniBB.getUniquePredecessor();
2728 
2729     llvm::BasicBlock *CodeGenIPBB = CodeGenIP.getBlock();
2730     llvm::Instruction *CodeGenIPInst = &*CodeGenIP.getPoint();
2731     EXPECT_EQ(CodeGenIPBB->getTerminator(), CodeGenIPInst);
2732     EXPECT_EQ(EntryBB, CodeGenIPBB);
2733 
2734     Builder.restoreIP(CodeGenIP);
2735     Builder.CreateStore(F->arg_begin(), PrivAI);
2736     Value *PrivLoad =
2737         Builder.CreateLoad(PrivAI->getAllocatedType(), PrivAI, "local.use");
2738     Builder.CreateICmpNE(F->arg_begin(), PrivLoad);
2739   };
2740 
2741   auto FiniCB = [&](InsertPointTy IP) {
2742     BasicBlock *IPBB = IP.getBlock();
2743     EXPECT_NE(IPBB->end(), IP.getPoint());
2744   };
2745 
2746   // Test for "#omp ordered [threads]"
2747   Builder.restoreIP(
2748       OMPBuilder.createOrderedThreadsSimd(Builder, BodyGenCB, FiniCB, true));
2749 
2750   Builder.CreateRetVoid();
2751   OMPBuilder.finalize();
2752   EXPECT_FALSE(verifyModule(*M, &errs()));
2753 
2754   EXPECT_NE(EntryBB->getTerminator(), nullptr);
2755 
2756   CallInst *OrderedEntryCI = nullptr;
2757   for (auto &EI : *EntryBB) {
2758     Instruction *Cur = &EI;
2759     if (isa<CallInst>(Cur)) {
2760       OrderedEntryCI = cast<CallInst>(Cur);
2761       if (OrderedEntryCI->getCalledFunction()->getName() == "__kmpc_ordered")
2762         break;
2763       OrderedEntryCI = nullptr;
2764     }
2765   }
2766   EXPECT_NE(OrderedEntryCI, nullptr);
2767   EXPECT_EQ(OrderedEntryCI->arg_size(), 2U);
2768   EXPECT_EQ(OrderedEntryCI->getCalledFunction()->getName(), "__kmpc_ordered");
2769   EXPECT_TRUE(isa<GlobalVariable>(OrderedEntryCI->getArgOperand(0)));
2770 
2771   CallInst *OrderedEndCI = nullptr;
2772   for (auto &FI : *EntryBB) {
2773     Instruction *Cur = &FI;
2774     if (isa<CallInst>(Cur)) {
2775       OrderedEndCI = cast<CallInst>(Cur);
2776       if (OrderedEndCI->getCalledFunction()->getName() == "__kmpc_end_ordered")
2777         break;
2778       OrderedEndCI = nullptr;
2779     }
2780   }
2781   EXPECT_NE(OrderedEndCI, nullptr);
2782   EXPECT_EQ(OrderedEndCI->arg_size(), 2U);
2783   EXPECT_TRUE(isa<GlobalVariable>(OrderedEndCI->getArgOperand(0)));
2784   EXPECT_EQ(OrderedEndCI->getArgOperand(1), OrderedEntryCI->getArgOperand(1));
2785 }
2786 
2787 TEST_F(OpenMPIRBuilderTest, OrderedDirectiveSimd) {
2788   using InsertPointTy = OpenMPIRBuilder::InsertPointTy;
2789   OpenMPIRBuilder OMPBuilder(*M);
2790   OMPBuilder.initialize();
2791   F->setName("func");
2792   IRBuilder<> Builder(BB);
2793 
2794   OpenMPIRBuilder::LocationDescription Loc({Builder.saveIP(), DL});
2795 
2796   AllocaInst *PrivAI =
2797       Builder.CreateAlloca(F->arg_begin()->getType(), nullptr, "priv.inst");
2798 
2799   BasicBlock *EntryBB = nullptr;
2800 
2801   auto BodyGenCB = [&](InsertPointTy AllocaIP, InsertPointTy CodeGenIP,
2802                        BasicBlock &FiniBB) {
2803     EntryBB = FiniBB.getUniquePredecessor();
2804 
2805     llvm::BasicBlock *CodeGenIPBB = CodeGenIP.getBlock();
2806     llvm::Instruction *CodeGenIPInst = &*CodeGenIP.getPoint();
2807     EXPECT_EQ(CodeGenIPBB->getTerminator(), CodeGenIPInst);
2808     EXPECT_EQ(EntryBB, CodeGenIPBB);
2809 
2810     Builder.restoreIP(CodeGenIP);
2811     Builder.CreateStore(F->arg_begin(), PrivAI);
2812     Value *PrivLoad =
2813         Builder.CreateLoad(PrivAI->getAllocatedType(), PrivAI, "local.use");
2814     Builder.CreateICmpNE(F->arg_begin(), PrivLoad);
2815   };
2816 
2817   auto FiniCB = [&](InsertPointTy IP) {
2818     BasicBlock *IPBB = IP.getBlock();
2819     EXPECT_NE(IPBB->end(), IP.getPoint());
2820   };
2821 
2822   // Test for "#omp ordered simd"
2823   Builder.restoreIP(
2824       OMPBuilder.createOrderedThreadsSimd(Builder, BodyGenCB, FiniCB, false));
2825 
2826   Builder.CreateRetVoid();
2827   OMPBuilder.finalize();
2828   EXPECT_FALSE(verifyModule(*M, &errs()));
2829 
2830   EXPECT_NE(EntryBB->getTerminator(), nullptr);
2831 
2832   CallInst *OrderedEntryCI = nullptr;
2833   for (auto &EI : *EntryBB) {
2834     Instruction *Cur = &EI;
2835     if (isa<CallInst>(Cur)) {
2836       OrderedEntryCI = cast<CallInst>(Cur);
2837       if (OrderedEntryCI->getCalledFunction()->getName() == "__kmpc_ordered")
2838         break;
2839       OrderedEntryCI = nullptr;
2840     }
2841   }
2842   EXPECT_EQ(OrderedEntryCI, nullptr);
2843 
2844   CallInst *OrderedEndCI = nullptr;
2845   for (auto &FI : *EntryBB) {
2846     Instruction *Cur = &FI;
2847     if (isa<CallInst>(Cur)) {
2848       OrderedEndCI = cast<CallInst>(Cur);
2849       if (OrderedEndCI->getCalledFunction()->getName() == "__kmpc_end_ordered")
2850         break;
2851       OrderedEndCI = nullptr;
2852     }
2853   }
2854   EXPECT_EQ(OrderedEndCI, nullptr);
2855 }
2856 
2857 TEST_F(OpenMPIRBuilderTest, CopyinBlocks) {
2858   OpenMPIRBuilder OMPBuilder(*M);
2859   OMPBuilder.initialize();
2860   F->setName("func");
2861   IRBuilder<> Builder(BB);
2862 
2863   OpenMPIRBuilder::LocationDescription Loc({Builder.saveIP(), DL});
2864 
2865   IntegerType *Int32 = Type::getInt32Ty(M->getContext());
2866   AllocaInst *MasterAddress = Builder.CreateAlloca(Int32->getPointerTo());
2867   AllocaInst *PrivAddress = Builder.CreateAlloca(Int32->getPointerTo());
2868 
2869   BasicBlock *EntryBB = BB;
2870 
2871   OMPBuilder.createCopyinClauseBlocks(Builder.saveIP(), MasterAddress,
2872                                       PrivAddress, Int32, /*BranchtoEnd*/ true);
2873 
2874   BranchInst *EntryBr = dyn_cast_or_null<BranchInst>(EntryBB->getTerminator());
2875 
2876   EXPECT_NE(EntryBr, nullptr);
2877   EXPECT_TRUE(EntryBr->isConditional());
2878 
2879   BasicBlock *NotMasterBB = EntryBr->getSuccessor(0);
2880   BasicBlock *CopyinEnd = EntryBr->getSuccessor(1);
2881   CmpInst *CMP = dyn_cast_or_null<CmpInst>(EntryBr->getCondition());
2882 
2883   EXPECT_NE(CMP, nullptr);
2884   EXPECT_NE(NotMasterBB, nullptr);
2885   EXPECT_NE(CopyinEnd, nullptr);
2886 
2887   BranchInst *NotMasterBr =
2888       dyn_cast_or_null<BranchInst>(NotMasterBB->getTerminator());
2889   EXPECT_NE(NotMasterBr, nullptr);
2890   EXPECT_FALSE(NotMasterBr->isConditional());
2891   EXPECT_EQ(CopyinEnd, NotMasterBr->getSuccessor(0));
2892 }
2893 
2894 TEST_F(OpenMPIRBuilderTest, SingleDirective) {
2895   using InsertPointTy = OpenMPIRBuilder::InsertPointTy;
2896   OpenMPIRBuilder OMPBuilder(*M);
2897   OMPBuilder.initialize();
2898   F->setName("func");
2899   IRBuilder<> Builder(BB);
2900 
2901   OpenMPIRBuilder::LocationDescription Loc({Builder.saveIP(), DL});
2902 
2903   AllocaInst *PrivAI = nullptr;
2904 
2905   BasicBlock *EntryBB = nullptr;
2906   BasicBlock *ExitBB = nullptr;
2907   BasicBlock *ThenBB = nullptr;
2908 
2909   auto BodyGenCB = [&](InsertPointTy AllocaIP, InsertPointTy CodeGenIP,
2910                        BasicBlock &FiniBB) {
2911     if (AllocaIP.isSet())
2912       Builder.restoreIP(AllocaIP);
2913     else
2914       Builder.SetInsertPoint(&*(F->getEntryBlock().getFirstInsertionPt()));
2915     PrivAI = Builder.CreateAlloca(F->arg_begin()->getType());
2916     Builder.CreateStore(F->arg_begin(), PrivAI);
2917 
2918     llvm::BasicBlock *CodeGenIPBB = CodeGenIP.getBlock();
2919     llvm::Instruction *CodeGenIPInst = &*CodeGenIP.getPoint();
2920     EXPECT_EQ(CodeGenIPBB->getTerminator(), CodeGenIPInst);
2921 
2922     Builder.restoreIP(CodeGenIP);
2923 
2924     // collect some info for checks later
2925     ExitBB = FiniBB.getUniqueSuccessor();
2926     ThenBB = Builder.GetInsertBlock();
2927     EntryBB = ThenBB->getUniquePredecessor();
2928 
2929     // simple instructions for body
2930     Value *PrivLoad =
2931         Builder.CreateLoad(PrivAI->getAllocatedType(), PrivAI, "local.use");
2932     Builder.CreateICmpNE(F->arg_begin(), PrivLoad);
2933   };
2934 
2935   auto FiniCB = [&](InsertPointTy IP) {
2936     BasicBlock *IPBB = IP.getBlock();
2937     EXPECT_NE(IPBB->end(), IP.getPoint());
2938   };
2939 
2940   Builder.restoreIP(OMPBuilder.createSingle(
2941       Builder, BodyGenCB, FiniCB, /*IsNowait*/ false, /*DidIt*/ nullptr));
2942   Value *EntryBBTI = EntryBB->getTerminator();
2943   EXPECT_NE(EntryBBTI, nullptr);
2944   EXPECT_TRUE(isa<BranchInst>(EntryBBTI));
2945   BranchInst *EntryBr = cast<BranchInst>(EntryBB->getTerminator());
2946   EXPECT_TRUE(EntryBr->isConditional());
2947   EXPECT_EQ(EntryBr->getSuccessor(0), ThenBB);
2948   EXPECT_EQ(ThenBB->getUniqueSuccessor(), ExitBB);
2949   EXPECT_EQ(EntryBr->getSuccessor(1), ExitBB);
2950 
2951   CmpInst *CondInst = cast<CmpInst>(EntryBr->getCondition());
2952   EXPECT_TRUE(isa<CallInst>(CondInst->getOperand(0)));
2953 
2954   CallInst *SingleEntryCI = cast<CallInst>(CondInst->getOperand(0));
2955   EXPECT_EQ(SingleEntryCI->arg_size(), 2U);
2956   EXPECT_EQ(SingleEntryCI->getCalledFunction()->getName(), "__kmpc_single");
2957   EXPECT_TRUE(isa<GlobalVariable>(SingleEntryCI->getArgOperand(0)));
2958 
2959   CallInst *SingleEndCI = nullptr;
2960   for (auto &FI : *ThenBB) {
2961     Instruction *cur = &FI;
2962     if (isa<CallInst>(cur)) {
2963       SingleEndCI = cast<CallInst>(cur);
2964       if (SingleEndCI->getCalledFunction()->getName() == "__kmpc_end_single")
2965         break;
2966       SingleEndCI = nullptr;
2967     }
2968   }
2969   EXPECT_NE(SingleEndCI, nullptr);
2970   EXPECT_EQ(SingleEndCI->arg_size(), 2U);
2971   EXPECT_TRUE(isa<GlobalVariable>(SingleEndCI->getArgOperand(0)));
2972   EXPECT_EQ(SingleEndCI->getArgOperand(1), SingleEntryCI->getArgOperand(1));
2973 
2974   bool FoundBarrier = false;
2975   for (auto &FI : *ExitBB) {
2976     Instruction *cur = &FI;
2977     if (auto CI = dyn_cast<CallInst>(cur)) {
2978       if (CI->getCalledFunction()->getName() == "__kmpc_barrier") {
2979         FoundBarrier = true;
2980         break;
2981       }
2982     }
2983   }
2984   EXPECT_TRUE(FoundBarrier);
2985 }
2986 
2987 TEST_F(OpenMPIRBuilderTest, SingleDirectiveNowait) {
2988   using InsertPointTy = OpenMPIRBuilder::InsertPointTy;
2989   OpenMPIRBuilder OMPBuilder(*M);
2990   OMPBuilder.initialize();
2991   F->setName("func");
2992   IRBuilder<> Builder(BB);
2993 
2994   OpenMPIRBuilder::LocationDescription Loc({Builder.saveIP(), DL});
2995 
2996   AllocaInst *PrivAI = nullptr;
2997 
2998   BasicBlock *EntryBB = nullptr;
2999   BasicBlock *ExitBB = nullptr;
3000   BasicBlock *ThenBB = nullptr;
3001 
3002   auto BodyGenCB = [&](InsertPointTy AllocaIP, InsertPointTy CodeGenIP,
3003                        BasicBlock &FiniBB) {
3004     if (AllocaIP.isSet())
3005       Builder.restoreIP(AllocaIP);
3006     else
3007       Builder.SetInsertPoint(&*(F->getEntryBlock().getFirstInsertionPt()));
3008     PrivAI = Builder.CreateAlloca(F->arg_begin()->getType());
3009     Builder.CreateStore(F->arg_begin(), PrivAI);
3010 
3011     llvm::BasicBlock *CodeGenIPBB = CodeGenIP.getBlock();
3012     llvm::Instruction *CodeGenIPInst = &*CodeGenIP.getPoint();
3013     EXPECT_EQ(CodeGenIPBB->getTerminator(), CodeGenIPInst);
3014 
3015     Builder.restoreIP(CodeGenIP);
3016 
3017     // collect some info for checks later
3018     ExitBB = FiniBB.getUniqueSuccessor();
3019     ThenBB = Builder.GetInsertBlock();
3020     EntryBB = ThenBB->getUniquePredecessor();
3021 
3022     // simple instructions for body
3023     Value *PrivLoad =
3024         Builder.CreateLoad(PrivAI->getAllocatedType(), PrivAI, "local.use");
3025     Builder.CreateICmpNE(F->arg_begin(), PrivLoad);
3026   };
3027 
3028   auto FiniCB = [&](InsertPointTy IP) {
3029     BasicBlock *IPBB = IP.getBlock();
3030     EXPECT_NE(IPBB->end(), IP.getPoint());
3031   };
3032 
3033   Builder.restoreIP(OMPBuilder.createSingle(
3034       Builder, BodyGenCB, FiniCB, /*IsNowait*/ true, /*DidIt*/ nullptr));
3035   Value *EntryBBTI = EntryBB->getTerminator();
3036   EXPECT_NE(EntryBBTI, nullptr);
3037   EXPECT_TRUE(isa<BranchInst>(EntryBBTI));
3038   BranchInst *EntryBr = cast<BranchInst>(EntryBB->getTerminator());
3039   EXPECT_TRUE(EntryBr->isConditional());
3040   EXPECT_EQ(EntryBr->getSuccessor(0), ThenBB);
3041   EXPECT_EQ(ThenBB->getUniqueSuccessor(), ExitBB);
3042   EXPECT_EQ(EntryBr->getSuccessor(1), ExitBB);
3043 
3044   CmpInst *CondInst = cast<CmpInst>(EntryBr->getCondition());
3045   EXPECT_TRUE(isa<CallInst>(CondInst->getOperand(0)));
3046 
3047   CallInst *SingleEntryCI = cast<CallInst>(CondInst->getOperand(0));
3048   EXPECT_EQ(SingleEntryCI->arg_size(), 2U);
3049   EXPECT_EQ(SingleEntryCI->getCalledFunction()->getName(), "__kmpc_single");
3050   EXPECT_TRUE(isa<GlobalVariable>(SingleEntryCI->getArgOperand(0)));
3051 
3052   CallInst *SingleEndCI = nullptr;
3053   for (auto &FI : *ThenBB) {
3054     Instruction *cur = &FI;
3055     if (isa<CallInst>(cur)) {
3056       SingleEndCI = cast<CallInst>(cur);
3057       if (SingleEndCI->getCalledFunction()->getName() == "__kmpc_end_single")
3058         break;
3059       SingleEndCI = nullptr;
3060     }
3061   }
3062   EXPECT_NE(SingleEndCI, nullptr);
3063   EXPECT_EQ(SingleEndCI->arg_size(), 2U);
3064   EXPECT_TRUE(isa<GlobalVariable>(SingleEndCI->getArgOperand(0)));
3065   EXPECT_EQ(SingleEndCI->getArgOperand(1), SingleEntryCI->getArgOperand(1));
3066 
3067   CallInst *ExitBarrier = nullptr;
3068   for (auto &FI : *ExitBB) {
3069     Instruction *cur = &FI;
3070     if (auto CI = dyn_cast<CallInst>(cur)) {
3071       if (CI->getCalledFunction()->getName() == "__kmpc_barrier") {
3072         ExitBarrier = CI;
3073         break;
3074       }
3075     }
3076   }
3077   EXPECT_EQ(ExitBarrier, nullptr);
3078 }
3079 
3080 TEST_F(OpenMPIRBuilderTest, OMPAtomicReadFlt) {
3081   OpenMPIRBuilder OMPBuilder(*M);
3082   OMPBuilder.initialize();
3083   F->setName("func");
3084   IRBuilder<> Builder(BB);
3085 
3086   OpenMPIRBuilder::LocationDescription Loc({Builder.saveIP(), DL});
3087 
3088   Type *Float32 = Type::getFloatTy(M->getContext());
3089   AllocaInst *XVal = Builder.CreateAlloca(Float32);
3090   XVal->setName("AtomicVar");
3091   AllocaInst *VVal = Builder.CreateAlloca(Float32);
3092   VVal->setName("AtomicRead");
3093   AtomicOrdering AO = AtomicOrdering::Monotonic;
3094   OpenMPIRBuilder::AtomicOpValue X = {XVal, Float32, false, false};
3095   OpenMPIRBuilder::AtomicOpValue V = {VVal, Float32, false, false};
3096 
3097   Builder.restoreIP(OMPBuilder.createAtomicRead(Loc, X, V, AO));
3098 
3099   IntegerType *IntCastTy =
3100       IntegerType::get(M->getContext(), Float32->getScalarSizeInBits());
3101 
3102   BitCastInst *CastFrmFlt = cast<BitCastInst>(VVal->getNextNode());
3103   EXPECT_EQ(CastFrmFlt->getSrcTy(), Float32->getPointerTo());
3104   EXPECT_EQ(CastFrmFlt->getDestTy(), IntCastTy->getPointerTo());
3105   EXPECT_EQ(CastFrmFlt->getOperand(0), XVal);
3106 
3107   LoadInst *AtomicLoad = cast<LoadInst>(CastFrmFlt->getNextNode());
3108   EXPECT_TRUE(AtomicLoad->isAtomic());
3109   EXPECT_EQ(AtomicLoad->getPointerOperand(), CastFrmFlt);
3110 
3111   BitCastInst *CastToFlt = cast<BitCastInst>(AtomicLoad->getNextNode());
3112   EXPECT_EQ(CastToFlt->getSrcTy(), IntCastTy);
3113   EXPECT_EQ(CastToFlt->getDestTy(), Float32);
3114   EXPECT_EQ(CastToFlt->getOperand(0), AtomicLoad);
3115 
3116   StoreInst *StoreofAtomic = cast<StoreInst>(CastToFlt->getNextNode());
3117   EXPECT_EQ(StoreofAtomic->getValueOperand(), CastToFlt);
3118   EXPECT_EQ(StoreofAtomic->getPointerOperand(), VVal);
3119 
3120   Builder.CreateRetVoid();
3121   OMPBuilder.finalize();
3122   EXPECT_FALSE(verifyModule(*M, &errs()));
3123 }
3124 
3125 TEST_F(OpenMPIRBuilderTest, OMPAtomicReadInt) {
3126   OpenMPIRBuilder OMPBuilder(*M);
3127   OMPBuilder.initialize();
3128   F->setName("func");
3129   IRBuilder<> Builder(BB);
3130 
3131   OpenMPIRBuilder::LocationDescription Loc({Builder.saveIP(), DL});
3132 
3133   IntegerType *Int32 = Type::getInt32Ty(M->getContext());
3134   AllocaInst *XVal = Builder.CreateAlloca(Int32);
3135   XVal->setName("AtomicVar");
3136   AllocaInst *VVal = Builder.CreateAlloca(Int32);
3137   VVal->setName("AtomicRead");
3138   AtomicOrdering AO = AtomicOrdering::Monotonic;
3139   OpenMPIRBuilder::AtomicOpValue X = {XVal, Int32, false, false};
3140   OpenMPIRBuilder::AtomicOpValue V = {VVal, Int32, false, false};
3141 
3142   BasicBlock *EntryBB = BB;
3143 
3144   Builder.restoreIP(OMPBuilder.createAtomicRead(Loc, X, V, AO));
3145   LoadInst *AtomicLoad = nullptr;
3146   StoreInst *StoreofAtomic = nullptr;
3147 
3148   for (Instruction &Cur : *EntryBB) {
3149     if (isa<LoadInst>(Cur)) {
3150       AtomicLoad = cast<LoadInst>(&Cur);
3151       if (AtomicLoad->getPointerOperand() == XVal)
3152         continue;
3153       AtomicLoad = nullptr;
3154     } else if (isa<StoreInst>(Cur)) {
3155       StoreofAtomic = cast<StoreInst>(&Cur);
3156       if (StoreofAtomic->getPointerOperand() == VVal)
3157         continue;
3158       StoreofAtomic = nullptr;
3159     }
3160   }
3161 
3162   EXPECT_NE(AtomicLoad, nullptr);
3163   EXPECT_TRUE(AtomicLoad->isAtomic());
3164 
3165   EXPECT_NE(StoreofAtomic, nullptr);
3166   EXPECT_EQ(StoreofAtomic->getValueOperand(), AtomicLoad);
3167 
3168   Builder.CreateRetVoid();
3169   OMPBuilder.finalize();
3170 
3171   EXPECT_FALSE(verifyModule(*M, &errs()));
3172 }
3173 
3174 TEST_F(OpenMPIRBuilderTest, OMPAtomicWriteFlt) {
3175   OpenMPIRBuilder OMPBuilder(*M);
3176   OMPBuilder.initialize();
3177   F->setName("func");
3178   IRBuilder<> Builder(BB);
3179 
3180   OpenMPIRBuilder::LocationDescription Loc({Builder.saveIP(), DL});
3181 
3182   LLVMContext &Ctx = M->getContext();
3183   Type *Float32 = Type::getFloatTy(Ctx);
3184   AllocaInst *XVal = Builder.CreateAlloca(Float32);
3185   XVal->setName("AtomicVar");
3186   OpenMPIRBuilder::AtomicOpValue X = {XVal, Float32, false, false};
3187   AtomicOrdering AO = AtomicOrdering::Monotonic;
3188   Constant *ValToWrite = ConstantFP::get(Float32, 1.0);
3189 
3190   Builder.restoreIP(OMPBuilder.createAtomicWrite(Loc, X, ValToWrite, AO));
3191 
3192   IntegerType *IntCastTy =
3193       IntegerType::get(M->getContext(), Float32->getScalarSizeInBits());
3194 
3195   BitCastInst *CastFrmFlt = cast<BitCastInst>(XVal->getNextNode());
3196   EXPECT_EQ(CastFrmFlt->getSrcTy(), Float32->getPointerTo());
3197   EXPECT_EQ(CastFrmFlt->getDestTy(), IntCastTy->getPointerTo());
3198   EXPECT_EQ(CastFrmFlt->getOperand(0), XVal);
3199 
3200   Value *ExprCast = Builder.CreateBitCast(ValToWrite, IntCastTy);
3201 
3202   StoreInst *StoreofAtomic = cast<StoreInst>(CastFrmFlt->getNextNode());
3203   EXPECT_EQ(StoreofAtomic->getValueOperand(), ExprCast);
3204   EXPECT_EQ(StoreofAtomic->getPointerOperand(), CastFrmFlt);
3205   EXPECT_TRUE(StoreofAtomic->isAtomic());
3206 
3207   Builder.CreateRetVoid();
3208   OMPBuilder.finalize();
3209   EXPECT_FALSE(verifyModule(*M, &errs()));
3210 }
3211 
3212 TEST_F(OpenMPIRBuilderTest, OMPAtomicWriteInt) {
3213   OpenMPIRBuilder OMPBuilder(*M);
3214   OMPBuilder.initialize();
3215   F->setName("func");
3216   IRBuilder<> Builder(BB);
3217 
3218   OpenMPIRBuilder::LocationDescription Loc({Builder.saveIP(), DL});
3219 
3220   LLVMContext &Ctx = M->getContext();
3221   IntegerType *Int32 = Type::getInt32Ty(Ctx);
3222   AllocaInst *XVal = Builder.CreateAlloca(Int32);
3223   XVal->setName("AtomicVar");
3224   OpenMPIRBuilder::AtomicOpValue X = {XVal, Int32, false, false};
3225   AtomicOrdering AO = AtomicOrdering::Monotonic;
3226   ConstantInt *ValToWrite = ConstantInt::get(Type::getInt32Ty(Ctx), 1U);
3227 
3228   BasicBlock *EntryBB = BB;
3229 
3230   Builder.restoreIP(OMPBuilder.createAtomicWrite(Loc, X, ValToWrite, AO));
3231 
3232   StoreInst *StoreofAtomic = nullptr;
3233 
3234   for (Instruction &Cur : *EntryBB) {
3235     if (isa<StoreInst>(Cur)) {
3236       StoreofAtomic = cast<StoreInst>(&Cur);
3237       if (StoreofAtomic->getPointerOperand() == XVal)
3238         continue;
3239       StoreofAtomic = nullptr;
3240     }
3241   }
3242 
3243   EXPECT_NE(StoreofAtomic, nullptr);
3244   EXPECT_TRUE(StoreofAtomic->isAtomic());
3245   EXPECT_EQ(StoreofAtomic->getValueOperand(), ValToWrite);
3246 
3247   Builder.CreateRetVoid();
3248   OMPBuilder.finalize();
3249   EXPECT_FALSE(verifyModule(*M, &errs()));
3250 }
3251 
3252 TEST_F(OpenMPIRBuilderTest, OMPAtomicUpdate) {
3253   OpenMPIRBuilder OMPBuilder(*M);
3254   OMPBuilder.initialize();
3255   F->setName("func");
3256   IRBuilder<> Builder(BB);
3257 
3258   OpenMPIRBuilder::LocationDescription Loc({Builder.saveIP(), DL});
3259 
3260   IntegerType *Int32 = Type::getInt32Ty(M->getContext());
3261   AllocaInst *XVal = Builder.CreateAlloca(Int32);
3262   XVal->setName("AtomicVar");
3263   Builder.CreateStore(ConstantInt::get(Type::getInt32Ty(Ctx), 0U), XVal);
3264   OpenMPIRBuilder::AtomicOpValue X = {XVal, Int32, false, false};
3265   AtomicOrdering AO = AtomicOrdering::Monotonic;
3266   ConstantInt *ConstVal = ConstantInt::get(Type::getInt32Ty(Ctx), 1U);
3267   Value *Expr = nullptr;
3268   AtomicRMWInst::BinOp RMWOp = AtomicRMWInst::Sub;
3269   bool IsXLHSInRHSPart = false;
3270 
3271   BasicBlock *EntryBB = BB;
3272   OpenMPIRBuilder::InsertPointTy AllocaIP(EntryBB,
3273                                           EntryBB->getFirstInsertionPt());
3274   Value *Sub = nullptr;
3275 
3276   auto UpdateOp = [&](Value *Atomic, IRBuilder<> &IRB) {
3277     Sub = IRB.CreateSub(ConstVal, Atomic);
3278     return Sub;
3279   };
3280   Builder.restoreIP(OMPBuilder.createAtomicUpdate(
3281       Builder, AllocaIP, X, Expr, AO, RMWOp, UpdateOp, IsXLHSInRHSPart));
3282   BasicBlock *ContBB = EntryBB->getSingleSuccessor();
3283   BranchInst *ContTI = dyn_cast<BranchInst>(ContBB->getTerminator());
3284   EXPECT_NE(ContTI, nullptr);
3285   BasicBlock *EndBB = ContTI->getSuccessor(0);
3286   EXPECT_TRUE(ContTI->isConditional());
3287   EXPECT_EQ(ContTI->getSuccessor(1), ContBB);
3288   EXPECT_NE(EndBB, nullptr);
3289 
3290   PHINode *Phi = dyn_cast<PHINode>(&ContBB->front());
3291   EXPECT_NE(Phi, nullptr);
3292   EXPECT_EQ(Phi->getNumIncomingValues(), 2U);
3293   EXPECT_EQ(Phi->getIncomingBlock(0), EntryBB);
3294   EXPECT_EQ(Phi->getIncomingBlock(1), ContBB);
3295 
3296   EXPECT_EQ(Sub->getNumUses(), 1U);
3297   StoreInst *St = dyn_cast<StoreInst>(Sub->user_back());
3298   AllocaInst *UpdateTemp = dyn_cast<AllocaInst>(St->getPointerOperand());
3299 
3300   ExtractValueInst *ExVI1 =
3301       dyn_cast<ExtractValueInst>(Phi->getIncomingValueForBlock(ContBB));
3302   EXPECT_NE(ExVI1, nullptr);
3303   AtomicCmpXchgInst *CmpExchg =
3304       dyn_cast<AtomicCmpXchgInst>(ExVI1->getAggregateOperand());
3305   EXPECT_NE(CmpExchg, nullptr);
3306   EXPECT_EQ(CmpExchg->getPointerOperand(), XVal);
3307   EXPECT_EQ(CmpExchg->getCompareOperand(), Phi);
3308   EXPECT_EQ(CmpExchg->getSuccessOrdering(), AtomicOrdering::Monotonic);
3309 
3310   LoadInst *Ld = dyn_cast<LoadInst>(CmpExchg->getNewValOperand());
3311   EXPECT_NE(Ld, nullptr);
3312   EXPECT_EQ(UpdateTemp, Ld->getPointerOperand());
3313 
3314   Builder.CreateRetVoid();
3315   OMPBuilder.finalize();
3316   EXPECT_FALSE(verifyModule(*M, &errs()));
3317 }
3318 
3319 TEST_F(OpenMPIRBuilderTest, OMPAtomicUpdateFloat) {
3320   OpenMPIRBuilder OMPBuilder(*M);
3321   OMPBuilder.initialize();
3322   F->setName("func");
3323   IRBuilder<> Builder(BB);
3324 
3325   OpenMPIRBuilder::LocationDescription Loc({Builder.saveIP(), DL});
3326 
3327   Type *FloatTy = Type::getFloatTy(M->getContext());
3328   AllocaInst *XVal = Builder.CreateAlloca(FloatTy);
3329   XVal->setName("AtomicVar");
3330   Builder.CreateStore(ConstantFP::get(Type::getFloatTy(Ctx), 0.0), XVal);
3331   OpenMPIRBuilder::AtomicOpValue X = {XVal, FloatTy, false, false};
3332   AtomicOrdering AO = AtomicOrdering::Monotonic;
3333   Constant *ConstVal = ConstantFP::get(Type::getFloatTy(Ctx), 1.0);
3334   Value *Expr = nullptr;
3335   AtomicRMWInst::BinOp RMWOp = AtomicRMWInst::FSub;
3336   bool IsXLHSInRHSPart = false;
3337 
3338   BasicBlock *EntryBB = BB;
3339   OpenMPIRBuilder::InsertPointTy AllocaIP(EntryBB,
3340                                           EntryBB->getFirstInsertionPt());
3341   Value *Sub = nullptr;
3342 
3343   auto UpdateOp = [&](Value *Atomic, IRBuilder<> &IRB) {
3344     Sub = IRB.CreateFSub(ConstVal, Atomic);
3345     return Sub;
3346   };
3347   Builder.restoreIP(OMPBuilder.createAtomicUpdate(
3348       Builder, AllocaIP, X, Expr, AO, RMWOp, UpdateOp, IsXLHSInRHSPart));
3349   BasicBlock *ContBB = EntryBB->getSingleSuccessor();
3350   BranchInst *ContTI = dyn_cast<BranchInst>(ContBB->getTerminator());
3351   EXPECT_NE(ContTI, nullptr);
3352   BasicBlock *EndBB = ContTI->getSuccessor(0);
3353   EXPECT_TRUE(ContTI->isConditional());
3354   EXPECT_EQ(ContTI->getSuccessor(1), ContBB);
3355   EXPECT_NE(EndBB, nullptr);
3356 
3357   PHINode *Phi = dyn_cast<PHINode>(&ContBB->front());
3358   EXPECT_NE(Phi, nullptr);
3359   EXPECT_EQ(Phi->getNumIncomingValues(), 2U);
3360   EXPECT_EQ(Phi->getIncomingBlock(0), EntryBB);
3361   EXPECT_EQ(Phi->getIncomingBlock(1), ContBB);
3362 
3363   EXPECT_EQ(Sub->getNumUses(), 1U);
3364   StoreInst *St = dyn_cast<StoreInst>(Sub->user_back());
3365   AllocaInst *UpdateTemp = dyn_cast<AllocaInst>(St->getPointerOperand());
3366 
3367   ExtractValueInst *ExVI1 =
3368       dyn_cast<ExtractValueInst>(Phi->getIncomingValueForBlock(ContBB));
3369   EXPECT_NE(ExVI1, nullptr);
3370   AtomicCmpXchgInst *CmpExchg =
3371       dyn_cast<AtomicCmpXchgInst>(ExVI1->getAggregateOperand());
3372   EXPECT_NE(CmpExchg, nullptr);
3373   BitCastInst *BitCastNew =
3374       dyn_cast<BitCastInst>(CmpExchg->getPointerOperand());
3375   EXPECT_NE(BitCastNew, nullptr);
3376   EXPECT_EQ(BitCastNew->getOperand(0), XVal);
3377   EXPECT_EQ(CmpExchg->getCompareOperand(), Phi);
3378   EXPECT_EQ(CmpExchg->getSuccessOrdering(), AtomicOrdering::Monotonic);
3379 
3380   LoadInst *Ld = dyn_cast<LoadInst>(CmpExchg->getNewValOperand());
3381   EXPECT_NE(Ld, nullptr);
3382   BitCastInst *BitCastOld = dyn_cast<BitCastInst>(Ld->getPointerOperand());
3383   EXPECT_NE(BitCastOld, nullptr);
3384   EXPECT_EQ(UpdateTemp, BitCastOld->getOperand(0));
3385 
3386   Builder.CreateRetVoid();
3387   OMPBuilder.finalize();
3388   EXPECT_FALSE(verifyModule(*M, &errs()));
3389 }
3390 
3391 TEST_F(OpenMPIRBuilderTest, OMPAtomicUpdateIntr) {
3392   OpenMPIRBuilder OMPBuilder(*M);
3393   OMPBuilder.initialize();
3394   F->setName("func");
3395   IRBuilder<> Builder(BB);
3396 
3397   OpenMPIRBuilder::LocationDescription Loc({Builder.saveIP(), DL});
3398 
3399   Type *IntTy = Type::getInt32Ty(M->getContext());
3400   AllocaInst *XVal = Builder.CreateAlloca(IntTy);
3401   XVal->setName("AtomicVar");
3402   Builder.CreateStore(ConstantInt::get(Type::getInt32Ty(Ctx), 0), XVal);
3403   OpenMPIRBuilder::AtomicOpValue X = {XVal, IntTy, false, false};
3404   AtomicOrdering AO = AtomicOrdering::Monotonic;
3405   Constant *ConstVal = ConstantInt::get(Type::getInt32Ty(Ctx), 1);
3406   Value *Expr = ConstantInt::get(Type::getInt32Ty(Ctx), 1);
3407   AtomicRMWInst::BinOp RMWOp = AtomicRMWInst::UMax;
3408   bool IsXLHSInRHSPart = false;
3409 
3410   BasicBlock *EntryBB = BB;
3411   OpenMPIRBuilder::InsertPointTy AllocaIP(EntryBB,
3412                                           EntryBB->getFirstInsertionPt());
3413   Value *Sub = nullptr;
3414 
3415   auto UpdateOp = [&](Value *Atomic, IRBuilder<> &IRB) {
3416     Sub = IRB.CreateSub(ConstVal, Atomic);
3417     return Sub;
3418   };
3419   Builder.restoreIP(OMPBuilder.createAtomicUpdate(
3420       Builder, AllocaIP, X, Expr, AO, RMWOp, UpdateOp, IsXLHSInRHSPart));
3421   BasicBlock *ContBB = EntryBB->getSingleSuccessor();
3422   BranchInst *ContTI = dyn_cast<BranchInst>(ContBB->getTerminator());
3423   EXPECT_NE(ContTI, nullptr);
3424   BasicBlock *EndBB = ContTI->getSuccessor(0);
3425   EXPECT_TRUE(ContTI->isConditional());
3426   EXPECT_EQ(ContTI->getSuccessor(1), ContBB);
3427   EXPECT_NE(EndBB, nullptr);
3428 
3429   PHINode *Phi = dyn_cast<PHINode>(&ContBB->front());
3430   EXPECT_NE(Phi, nullptr);
3431   EXPECT_EQ(Phi->getNumIncomingValues(), 2U);
3432   EXPECT_EQ(Phi->getIncomingBlock(0), EntryBB);
3433   EXPECT_EQ(Phi->getIncomingBlock(1), ContBB);
3434 
3435   EXPECT_EQ(Sub->getNumUses(), 1U);
3436   StoreInst *St = dyn_cast<StoreInst>(Sub->user_back());
3437   AllocaInst *UpdateTemp = dyn_cast<AllocaInst>(St->getPointerOperand());
3438 
3439   ExtractValueInst *ExVI1 =
3440       dyn_cast<ExtractValueInst>(Phi->getIncomingValueForBlock(ContBB));
3441   EXPECT_NE(ExVI1, nullptr);
3442   AtomicCmpXchgInst *CmpExchg =
3443       dyn_cast<AtomicCmpXchgInst>(ExVI1->getAggregateOperand());
3444   EXPECT_NE(CmpExchg, nullptr);
3445   EXPECT_EQ(CmpExchg->getPointerOperand(), XVal);
3446   EXPECT_EQ(CmpExchg->getCompareOperand(), Phi);
3447   EXPECT_EQ(CmpExchg->getSuccessOrdering(), AtomicOrdering::Monotonic);
3448 
3449   LoadInst *Ld = dyn_cast<LoadInst>(CmpExchg->getNewValOperand());
3450   EXPECT_NE(Ld, nullptr);
3451   EXPECT_EQ(UpdateTemp, Ld->getPointerOperand());
3452 
3453   Builder.CreateRetVoid();
3454   OMPBuilder.finalize();
3455   EXPECT_FALSE(verifyModule(*M, &errs()));
3456 }
3457 
3458 TEST_F(OpenMPIRBuilderTest, OMPAtomicCapture) {
3459   OpenMPIRBuilder OMPBuilder(*M);
3460   OMPBuilder.initialize();
3461   F->setName("func");
3462   IRBuilder<> Builder(BB);
3463 
3464   OpenMPIRBuilder::LocationDescription Loc({Builder.saveIP(), DL});
3465 
3466   LLVMContext &Ctx = M->getContext();
3467   IntegerType *Int32 = Type::getInt32Ty(Ctx);
3468   AllocaInst *XVal = Builder.CreateAlloca(Int32);
3469   XVal->setName("AtomicVar");
3470   AllocaInst *VVal = Builder.CreateAlloca(Int32);
3471   VVal->setName("AtomicCapTar");
3472   StoreInst *Init =
3473       Builder.CreateStore(ConstantInt::get(Type::getInt32Ty(Ctx), 0U), XVal);
3474 
3475   OpenMPIRBuilder::AtomicOpValue X = {XVal, Int32, false, false};
3476   OpenMPIRBuilder::AtomicOpValue V = {VVal, Int32, false, false};
3477   AtomicOrdering AO = AtomicOrdering::Monotonic;
3478   ConstantInt *Expr = ConstantInt::get(Type::getInt32Ty(Ctx), 1U);
3479   AtomicRMWInst::BinOp RMWOp = AtomicRMWInst::Add;
3480   bool IsXLHSInRHSPart = true;
3481   bool IsPostfixUpdate = true;
3482   bool UpdateExpr = true;
3483 
3484   BasicBlock *EntryBB = BB;
3485   OpenMPIRBuilder::InsertPointTy AllocaIP(EntryBB,
3486                                           EntryBB->getFirstInsertionPt());
3487 
3488   // integer update - not used
3489   auto UpdateOp = [&](Value *Atomic, IRBuilder<> &IRB) { return nullptr; };
3490 
3491   Builder.restoreIP(OMPBuilder.createAtomicCapture(
3492       Builder, AllocaIP, X, V, Expr, AO, RMWOp, UpdateOp, UpdateExpr,
3493       IsPostfixUpdate, IsXLHSInRHSPart));
3494   EXPECT_EQ(EntryBB->getParent()->size(), 1U);
3495   AtomicRMWInst *ARWM = dyn_cast<AtomicRMWInst>(Init->getNextNode());
3496   EXPECT_NE(ARWM, nullptr);
3497   EXPECT_EQ(ARWM->getPointerOperand(), XVal);
3498   EXPECT_EQ(ARWM->getOperation(), RMWOp);
3499   StoreInst *St = dyn_cast<StoreInst>(ARWM->user_back());
3500   EXPECT_NE(St, nullptr);
3501   EXPECT_EQ(St->getPointerOperand(), VVal);
3502 
3503   Builder.CreateRetVoid();
3504   OMPBuilder.finalize();
3505   EXPECT_FALSE(verifyModule(*M, &errs()));
3506 }
3507 
3508 TEST_F(OpenMPIRBuilderTest, OMPAtomicCompare) {
3509   OpenMPIRBuilder OMPBuilder(*M);
3510   OMPBuilder.initialize();
3511   F->setName("func");
3512   IRBuilder<> Builder(BB);
3513 
3514   OpenMPIRBuilder::LocationDescription Loc({Builder.saveIP(), DL});
3515 
3516   LLVMContext &Ctx = M->getContext();
3517   IntegerType *Int32 = Type::getInt32Ty(Ctx);
3518   AllocaInst *XVal = Builder.CreateAlloca(Int32);
3519   XVal->setName("x");
3520   StoreInst *Init =
3521       Builder.CreateStore(ConstantInt::get(Type::getInt32Ty(Ctx), 0U), XVal);
3522 
3523   OpenMPIRBuilder::AtomicOpValue XSigned = {XVal, Int32, true, false};
3524   OpenMPIRBuilder::AtomicOpValue XUnsigned = {XVal, Int32, false, false};
3525   AtomicOrdering AO = AtomicOrdering::Monotonic;
3526   ConstantInt *Expr = ConstantInt::get(Type::getInt32Ty(Ctx), 1U);
3527   ConstantInt *D = ConstantInt::get(Type::getInt32Ty(Ctx), 1U);
3528   OMPAtomicCompareOp OpMax = OMPAtomicCompareOp::MAX;
3529   OMPAtomicCompareOp OpEQ = OMPAtomicCompareOp::EQ;
3530 
3531   Builder.restoreIP(OMPBuilder.createAtomicCompare(Builder, XSigned, Expr,
3532                                                    nullptr, AO, OpMax, true));
3533   Builder.restoreIP(OMPBuilder.createAtomicCompare(Builder, XUnsigned, Expr,
3534                                                    nullptr, AO, OpMax, false));
3535   Builder.restoreIP(OMPBuilder.createAtomicCompare(Builder, XSigned, Expr, D,
3536                                                    AO, OpEQ, true));
3537 
3538   BasicBlock *EntryBB = BB;
3539   EXPECT_EQ(EntryBB->getParent()->size(), 1U);
3540   EXPECT_EQ(EntryBB->size(), 5U);
3541 
3542   AtomicRMWInst *ARWM1 = dyn_cast<AtomicRMWInst>(Init->getNextNode());
3543   EXPECT_NE(ARWM1, nullptr);
3544   EXPECT_EQ(ARWM1->getPointerOperand(), XVal);
3545   EXPECT_EQ(ARWM1->getValOperand(), Expr);
3546   EXPECT_EQ(ARWM1->getOperation(), AtomicRMWInst::Min);
3547 
3548   AtomicRMWInst *ARWM2 = dyn_cast<AtomicRMWInst>(ARWM1->getNextNode());
3549   EXPECT_NE(ARWM2, nullptr);
3550   EXPECT_EQ(ARWM2->getPointerOperand(), XVal);
3551   EXPECT_EQ(ARWM2->getValOperand(), Expr);
3552   EXPECT_EQ(ARWM2->getOperation(), AtomicRMWInst::UMax);
3553 
3554   AtomicCmpXchgInst *AXCHG = dyn_cast<AtomicCmpXchgInst>(ARWM2->getNextNode());
3555   EXPECT_NE(AXCHG, nullptr);
3556   EXPECT_EQ(AXCHG->getPointerOperand(), XVal);
3557   EXPECT_EQ(AXCHG->getCompareOperand(), Expr);
3558   EXPECT_EQ(AXCHG->getNewValOperand(), D);
3559 
3560   Builder.CreateRetVoid();
3561   OMPBuilder.finalize();
3562   EXPECT_FALSE(verifyModule(*M, &errs()));
3563 }
3564 
3565 /// Returns the single instruction of InstTy type in BB that uses the value V.
3566 /// If there is more than one such instruction, returns null.
3567 template <typename InstTy>
3568 static InstTy *findSingleUserInBlock(Value *V, BasicBlock *BB) {
3569   InstTy *Result = nullptr;
3570   for (User *U : V->users()) {
3571     auto *Inst = dyn_cast<InstTy>(U);
3572     if (!Inst || Inst->getParent() != BB)
3573       continue;
3574     if (Result)
3575       return nullptr;
3576     Result = Inst;
3577   }
3578   return Result;
3579 }
3580 
3581 /// Returns true if BB contains a simple binary reduction that loads a value
3582 /// from Accum, performs some binary operation with it, and stores it back to
3583 /// Accum.
3584 static bool isSimpleBinaryReduction(Value *Accum, BasicBlock *BB,
3585                                     Instruction::BinaryOps *OpCode = nullptr) {
3586   StoreInst *Store = findSingleUserInBlock<StoreInst>(Accum, BB);
3587   if (!Store)
3588     return false;
3589   auto *Stored = dyn_cast<BinaryOperator>(Store->getOperand(0));
3590   if (!Stored)
3591     return false;
3592   if (OpCode && *OpCode != Stored->getOpcode())
3593     return false;
3594   auto *Load = dyn_cast<LoadInst>(Stored->getOperand(0));
3595   return Load && Load->getOperand(0) == Accum;
3596 }
3597 
3598 /// Returns true if BB contains a binary reduction that reduces V using a binary
3599 /// operator into an accumulator that is a function argument.
3600 static bool isValueReducedToFuncArg(Value *V, BasicBlock *BB) {
3601   auto *ReductionOp = findSingleUserInBlock<BinaryOperator>(V, BB);
3602   if (!ReductionOp)
3603     return false;
3604 
3605   auto *GlobalLoad = dyn_cast<LoadInst>(ReductionOp->getOperand(0));
3606   if (!GlobalLoad)
3607     return false;
3608 
3609   auto *Store = findSingleUserInBlock<StoreInst>(ReductionOp, BB);
3610   if (!Store)
3611     return false;
3612 
3613   return Store->getPointerOperand() == GlobalLoad->getPointerOperand() &&
3614          isa<Argument>(findAggregateFromValue(GlobalLoad->getPointerOperand()));
3615 }
3616 
3617 /// Finds among users of Ptr a pair of GEP instructions with indices [0, 0] and
3618 /// [0, 1], respectively, and assigns results of these instructions to Zero and
3619 /// One. Returns true on success, false on failure or if such instructions are
3620 /// not unique among the users of Ptr.
3621 static bool findGEPZeroOne(Value *Ptr, Value *&Zero, Value *&One) {
3622   Zero = nullptr;
3623   One = nullptr;
3624   for (User *U : Ptr->users()) {
3625     if (auto *GEP = dyn_cast<GetElementPtrInst>(U)) {
3626       if (GEP->getNumIndices() != 2)
3627         continue;
3628       auto *FirstIdx = dyn_cast<ConstantInt>(GEP->getOperand(1));
3629       auto *SecondIdx = dyn_cast<ConstantInt>(GEP->getOperand(2));
3630       EXPECT_NE(FirstIdx, nullptr);
3631       EXPECT_NE(SecondIdx, nullptr);
3632 
3633       EXPECT_TRUE(FirstIdx->isZero());
3634       if (SecondIdx->isZero()) {
3635         if (Zero)
3636           return false;
3637         Zero = GEP;
3638       } else if (SecondIdx->isOne()) {
3639         if (One)
3640           return false;
3641         One = GEP;
3642       } else {
3643         return false;
3644       }
3645     }
3646   }
3647   return Zero != nullptr && One != nullptr;
3648 }
3649 
3650 static OpenMPIRBuilder::InsertPointTy
3651 sumReduction(OpenMPIRBuilder::InsertPointTy IP, Value *LHS, Value *RHS,
3652              Value *&Result) {
3653   IRBuilder<> Builder(IP.getBlock(), IP.getPoint());
3654   Result = Builder.CreateFAdd(LHS, RHS, "red.add");
3655   return Builder.saveIP();
3656 }
3657 
3658 static OpenMPIRBuilder::InsertPointTy
3659 sumAtomicReduction(OpenMPIRBuilder::InsertPointTy IP, Type *Ty, Value *LHS,
3660                    Value *RHS) {
3661   IRBuilder<> Builder(IP.getBlock(), IP.getPoint());
3662   Value *Partial = Builder.CreateLoad(Ty, RHS, "red.partial");
3663   Builder.CreateAtomicRMW(AtomicRMWInst::FAdd, LHS, Partial, None,
3664                           AtomicOrdering::Monotonic);
3665   return Builder.saveIP();
3666 }
3667 
3668 static OpenMPIRBuilder::InsertPointTy
3669 xorReduction(OpenMPIRBuilder::InsertPointTy IP, Value *LHS, Value *RHS,
3670              Value *&Result) {
3671   IRBuilder<> Builder(IP.getBlock(), IP.getPoint());
3672   Result = Builder.CreateXor(LHS, RHS, "red.xor");
3673   return Builder.saveIP();
3674 }
3675 
3676 static OpenMPIRBuilder::InsertPointTy
3677 xorAtomicReduction(OpenMPIRBuilder::InsertPointTy IP, Type *Ty, Value *LHS,
3678                    Value *RHS) {
3679   IRBuilder<> Builder(IP.getBlock(), IP.getPoint());
3680   Value *Partial = Builder.CreateLoad(Ty, RHS, "red.partial");
3681   Builder.CreateAtomicRMW(AtomicRMWInst::Xor, LHS, Partial, None,
3682                           AtomicOrdering::Monotonic);
3683   return Builder.saveIP();
3684 }
3685 
3686 TEST_F(OpenMPIRBuilderTest, CreateReductions) {
3687   using InsertPointTy = OpenMPIRBuilder::InsertPointTy;
3688   OpenMPIRBuilder OMPBuilder(*M);
3689   OMPBuilder.initialize();
3690   F->setName("func");
3691   IRBuilder<> Builder(BB);
3692 
3693   BasicBlock *EnterBB = BasicBlock::Create(Ctx, "parallel.enter", F);
3694   Builder.CreateBr(EnterBB);
3695   Builder.SetInsertPoint(EnterBB);
3696   OpenMPIRBuilder::LocationDescription Loc({Builder.saveIP(), DL});
3697 
3698   // Create variables to be reduced.
3699   InsertPointTy OuterAllocaIP(&F->getEntryBlock(),
3700                               F->getEntryBlock().getFirstInsertionPt());
3701   Type *SumType = Builder.getFloatTy();
3702   Type *XorType = Builder.getInt32Ty();
3703   Value *SumReduced;
3704   Value *XorReduced;
3705   {
3706     IRBuilderBase::InsertPointGuard Guard(Builder);
3707     Builder.restoreIP(OuterAllocaIP);
3708     SumReduced = Builder.CreateAlloca(SumType);
3709     XorReduced = Builder.CreateAlloca(XorType);
3710   }
3711 
3712   // Store initial values of reductions into global variables.
3713   Builder.CreateStore(ConstantFP::get(Builder.getFloatTy(), 0.0), SumReduced);
3714   Builder.CreateStore(Builder.getInt32(1), XorReduced);
3715 
3716   // The loop body computes two reductions:
3717   //   sum of (float) thread-id;
3718   //   xor of thread-id;
3719   // and store the result in global variables.
3720   InsertPointTy BodyIP, BodyAllocaIP;
3721   auto BodyGenCB = [&](InsertPointTy InnerAllocaIP, InsertPointTy CodeGenIP,
3722                        BasicBlock &ContinuationBB) {
3723     IRBuilderBase::InsertPointGuard Guard(Builder);
3724     Builder.restoreIP(CodeGenIP);
3725 
3726     uint32_t StrSize;
3727     Constant *SrcLocStr = OMPBuilder.getOrCreateSrcLocStr(Loc, StrSize);
3728     Value *Ident = OMPBuilder.getOrCreateIdent(SrcLocStr, StrSize);
3729     Value *TID = OMPBuilder.getOrCreateThreadID(Ident);
3730     Value *SumLocal =
3731         Builder.CreateUIToFP(TID, Builder.getFloatTy(), "sum.local");
3732     Value *SumPartial = Builder.CreateLoad(SumType, SumReduced, "sum.partial");
3733     Value *XorPartial = Builder.CreateLoad(XorType, XorReduced, "xor.partial");
3734     Value *Sum = Builder.CreateFAdd(SumPartial, SumLocal, "sum");
3735     Value *Xor = Builder.CreateXor(XorPartial, TID, "xor");
3736     Builder.CreateStore(Sum, SumReduced);
3737     Builder.CreateStore(Xor, XorReduced);
3738 
3739     BodyIP = Builder.saveIP();
3740     BodyAllocaIP = InnerAllocaIP;
3741   };
3742 
3743   // Privatization for reduction creates local copies of reduction variables and
3744   // initializes them to reduction-neutral values.
3745   Value *SumPrivatized;
3746   Value *XorPrivatized;
3747   auto PrivCB = [&](InsertPointTy InnerAllocaIP, InsertPointTy CodeGenIP,
3748                     Value &Original, Value &Inner, Value *&ReplVal) {
3749     IRBuilderBase::InsertPointGuard Guard(Builder);
3750     Builder.restoreIP(InnerAllocaIP);
3751     if (&Original == SumReduced) {
3752       SumPrivatized = Builder.CreateAlloca(Builder.getFloatTy());
3753       ReplVal = SumPrivatized;
3754     } else if (&Original == XorReduced) {
3755       XorPrivatized = Builder.CreateAlloca(Builder.getInt32Ty());
3756       ReplVal = XorPrivatized;
3757     } else {
3758       ReplVal = &Inner;
3759       return CodeGenIP;
3760     }
3761 
3762     Builder.restoreIP(CodeGenIP);
3763     if (&Original == SumReduced)
3764       Builder.CreateStore(ConstantFP::get(Builder.getFloatTy(), 0.0),
3765                           SumPrivatized);
3766     else if (&Original == XorReduced)
3767       Builder.CreateStore(Builder.getInt32(0), XorPrivatized);
3768 
3769     return Builder.saveIP();
3770   };
3771 
3772   // Do nothing in finalization.
3773   auto FiniCB = [&](InsertPointTy CodeGenIP) { return CodeGenIP; };
3774 
3775   InsertPointTy AfterIP =
3776       OMPBuilder.createParallel(Loc, OuterAllocaIP, BodyGenCB, PrivCB, FiniCB,
3777                                 /* IfCondition */ nullptr,
3778                                 /* NumThreads */ nullptr, OMP_PROC_BIND_default,
3779                                 /* IsCancellable */ false);
3780   Builder.restoreIP(AfterIP);
3781 
3782   OpenMPIRBuilder::ReductionInfo ReductionInfos[] = {
3783       {SumType, SumReduced, SumPrivatized, sumReduction, sumAtomicReduction},
3784       {XorType, XorReduced, XorPrivatized, xorReduction, xorAtomicReduction}};
3785 
3786   OMPBuilder.createReductions(BodyIP, BodyAllocaIP, ReductionInfos);
3787 
3788   Builder.restoreIP(AfterIP);
3789   Builder.CreateRetVoid();
3790 
3791   OMPBuilder.finalize(F);
3792 
3793   // The IR must be valid.
3794   EXPECT_FALSE(verifyModule(*M));
3795 
3796   // Outlining must have happened.
3797   SmallVector<CallInst *> ForkCalls;
3798   findCalls(F, omp::RuntimeFunction::OMPRTL___kmpc_fork_call, OMPBuilder,
3799             ForkCalls);
3800   ASSERT_EQ(ForkCalls.size(), 1u);
3801   Value *CalleeVal = cast<Constant>(ForkCalls[0]->getOperand(2))->getOperand(0);
3802   Function *Outlined = dyn_cast<Function>(CalleeVal);
3803   EXPECT_NE(Outlined, nullptr);
3804 
3805   // Check that the lock variable was created with the expected name.
3806   GlobalVariable *LockVar =
3807       M->getGlobalVariable(".gomp_critical_user_.reduction.var");
3808   EXPECT_NE(LockVar, nullptr);
3809 
3810   // Find the allocation of a local array that will be used to call the runtime
3811   // reduciton function.
3812   BasicBlock &AllocBlock = Outlined->getEntryBlock();
3813   Value *LocalArray = nullptr;
3814   for (Instruction &I : AllocBlock) {
3815     if (AllocaInst *Alloc = dyn_cast<AllocaInst>(&I)) {
3816       if (!Alloc->getAllocatedType()->isArrayTy() ||
3817           !Alloc->getAllocatedType()->getArrayElementType()->isPointerTy())
3818         continue;
3819       LocalArray = Alloc;
3820       break;
3821     }
3822   }
3823   ASSERT_NE(LocalArray, nullptr);
3824 
3825   // Find the call to the runtime reduction function.
3826   BasicBlock *BB = AllocBlock.getUniqueSuccessor();
3827   Value *LocalArrayPtr = nullptr;
3828   Value *ReductionFnVal = nullptr;
3829   Value *SwitchArg = nullptr;
3830   for (Instruction &I : *BB) {
3831     if (CallInst *Call = dyn_cast<CallInst>(&I)) {
3832       if (Call->getCalledFunction() !=
3833           OMPBuilder.getOrCreateRuntimeFunctionPtr(
3834               RuntimeFunction::OMPRTL___kmpc_reduce))
3835         continue;
3836       LocalArrayPtr = Call->getOperand(4);
3837       ReductionFnVal = Call->getOperand(5);
3838       SwitchArg = Call;
3839       break;
3840     }
3841   }
3842 
3843   // Check that the local array is passed to the function.
3844   ASSERT_NE(LocalArrayPtr, nullptr);
3845   BitCastInst *BitCast = dyn_cast<BitCastInst>(LocalArrayPtr);
3846   ASSERT_NE(BitCast, nullptr);
3847   EXPECT_EQ(BitCast->getOperand(0), LocalArray);
3848 
3849   // Find the GEP instructions preceding stores to the local array.
3850   Value *FirstArrayElemPtr = nullptr;
3851   Value *SecondArrayElemPtr = nullptr;
3852   EXPECT_EQ(LocalArray->getNumUses(), 3u);
3853   ASSERT_TRUE(
3854       findGEPZeroOne(LocalArray, FirstArrayElemPtr, SecondArrayElemPtr));
3855 
3856   // Check that the values stored into the local array are privatized reduction
3857   // variables.
3858   auto *FirstStored = dyn_cast_or_null<BitCastInst>(
3859       findStoredValue<GetElementPtrInst>(FirstArrayElemPtr));
3860   auto *SecondStored = dyn_cast_or_null<BitCastInst>(
3861       findStoredValue<GetElementPtrInst>(SecondArrayElemPtr));
3862   ASSERT_NE(FirstStored, nullptr);
3863   ASSERT_NE(SecondStored, nullptr);
3864   Value *FirstPrivatized = FirstStored->getOperand(0);
3865   Value *SecondPrivatized = SecondStored->getOperand(0);
3866   EXPECT_TRUE(
3867       isSimpleBinaryReduction(FirstPrivatized, FirstStored->getParent()));
3868   EXPECT_TRUE(
3869       isSimpleBinaryReduction(SecondPrivatized, SecondStored->getParent()));
3870 
3871   // Check that the result of the runtime reduction call is used for further
3872   // dispatch.
3873   ASSERT_EQ(SwitchArg->getNumUses(), 1u);
3874   SwitchInst *Switch = dyn_cast<SwitchInst>(*SwitchArg->user_begin());
3875   ASSERT_NE(Switch, nullptr);
3876   EXPECT_EQ(Switch->getNumSuccessors(), 3u);
3877   BasicBlock *NonAtomicBB = Switch->case_begin()->getCaseSuccessor();
3878   BasicBlock *AtomicBB = std::next(Switch->case_begin())->getCaseSuccessor();
3879 
3880   // Non-atomic block contains reductions to the global reduction variable,
3881   // which is passed into the outlined function as an argument.
3882   Value *FirstLoad =
3883       findSingleUserInBlock<LoadInst>(FirstPrivatized, NonAtomicBB);
3884   Value *SecondLoad =
3885       findSingleUserInBlock<LoadInst>(SecondPrivatized, NonAtomicBB);
3886   EXPECT_TRUE(isValueReducedToFuncArg(FirstLoad, NonAtomicBB));
3887   EXPECT_TRUE(isValueReducedToFuncArg(SecondLoad, NonAtomicBB));
3888 
3889   // Atomic block also constains reductions to the global reduction variable.
3890   FirstLoad = findSingleUserInBlock<LoadInst>(FirstPrivatized, AtomicBB);
3891   SecondLoad = findSingleUserInBlock<LoadInst>(SecondPrivatized, AtomicBB);
3892   auto *FirstAtomic = findSingleUserInBlock<AtomicRMWInst>(FirstLoad, AtomicBB);
3893   auto *SecondAtomic =
3894       findSingleUserInBlock<AtomicRMWInst>(SecondLoad, AtomicBB);
3895   ASSERT_NE(FirstAtomic, nullptr);
3896   Value *AtomicStorePointer = FirstAtomic->getPointerOperand();
3897   EXPECT_TRUE(isa<Argument>(findAggregateFromValue(AtomicStorePointer)));
3898   ASSERT_NE(SecondAtomic, nullptr);
3899   AtomicStorePointer = SecondAtomic->getPointerOperand();
3900   EXPECT_TRUE(isa<Argument>(findAggregateFromValue(AtomicStorePointer)));
3901 
3902   // Check that the separate reduction function also performs (non-atomic)
3903   // reductions after extracting reduction variables from its arguments.
3904   Function *ReductionFn = cast<Function>(ReductionFnVal);
3905   BasicBlock *FnReductionBB = &ReductionFn->getEntryBlock();
3906   auto *Bitcast =
3907       findSingleUserInBlock<BitCastInst>(ReductionFn->getArg(0), FnReductionBB);
3908   Value *FirstLHSPtr;
3909   Value *SecondLHSPtr;
3910   ASSERT_TRUE(findGEPZeroOne(Bitcast, FirstLHSPtr, SecondLHSPtr));
3911   Value *Opaque = findSingleUserInBlock<LoadInst>(FirstLHSPtr, FnReductionBB);
3912   ASSERT_NE(Opaque, nullptr);
3913   Bitcast = findSingleUserInBlock<BitCastInst>(Opaque, FnReductionBB);
3914   ASSERT_NE(Bitcast, nullptr);
3915   EXPECT_TRUE(isSimpleBinaryReduction(Bitcast, FnReductionBB));
3916   Opaque = findSingleUserInBlock<LoadInst>(SecondLHSPtr, FnReductionBB);
3917   ASSERT_NE(Opaque, nullptr);
3918   Bitcast = findSingleUserInBlock<BitCastInst>(Opaque, FnReductionBB);
3919   ASSERT_NE(Bitcast, nullptr);
3920   EXPECT_TRUE(isSimpleBinaryReduction(Bitcast, FnReductionBB));
3921 
3922   Bitcast =
3923       findSingleUserInBlock<BitCastInst>(ReductionFn->getArg(1), FnReductionBB);
3924   Value *FirstRHS;
3925   Value *SecondRHS;
3926   EXPECT_TRUE(findGEPZeroOne(Bitcast, FirstRHS, SecondRHS));
3927 }
3928 
3929 TEST_F(OpenMPIRBuilderTest, CreateTwoReductions) {
3930   using InsertPointTy = OpenMPIRBuilder::InsertPointTy;
3931   OpenMPIRBuilder OMPBuilder(*M);
3932   OMPBuilder.initialize();
3933   F->setName("func");
3934   IRBuilder<> Builder(BB);
3935 
3936   BasicBlock *EnterBB = BasicBlock::Create(Ctx, "parallel.enter", F);
3937   Builder.CreateBr(EnterBB);
3938   Builder.SetInsertPoint(EnterBB);
3939   OpenMPIRBuilder::LocationDescription Loc({Builder.saveIP(), DL});
3940 
3941   // Create variables to be reduced.
3942   InsertPointTy OuterAllocaIP(&F->getEntryBlock(),
3943                               F->getEntryBlock().getFirstInsertionPt());
3944   Type *SumType = Builder.getFloatTy();
3945   Type *XorType = Builder.getInt32Ty();
3946   Value *SumReduced;
3947   Value *XorReduced;
3948   {
3949     IRBuilderBase::InsertPointGuard Guard(Builder);
3950     Builder.restoreIP(OuterAllocaIP);
3951     SumReduced = Builder.CreateAlloca(SumType);
3952     XorReduced = Builder.CreateAlloca(XorType);
3953   }
3954 
3955   // Store initial values of reductions into global variables.
3956   Builder.CreateStore(ConstantFP::get(Builder.getFloatTy(), 0.0), SumReduced);
3957   Builder.CreateStore(Builder.getInt32(1), XorReduced);
3958 
3959   InsertPointTy FirstBodyIP, FirstBodyAllocaIP;
3960   auto FirstBodyGenCB = [&](InsertPointTy InnerAllocaIP,
3961                             InsertPointTy CodeGenIP,
3962                             BasicBlock &ContinuationBB) {
3963     IRBuilderBase::InsertPointGuard Guard(Builder);
3964     Builder.restoreIP(CodeGenIP);
3965 
3966     uint32_t StrSize;
3967     Constant *SrcLocStr = OMPBuilder.getOrCreateSrcLocStr(Loc, StrSize);
3968     Value *Ident = OMPBuilder.getOrCreateIdent(SrcLocStr, StrSize);
3969     Value *TID = OMPBuilder.getOrCreateThreadID(Ident);
3970     Value *SumLocal =
3971         Builder.CreateUIToFP(TID, Builder.getFloatTy(), "sum.local");
3972     Value *SumPartial = Builder.CreateLoad(SumType, SumReduced, "sum.partial");
3973     Value *Sum = Builder.CreateFAdd(SumPartial, SumLocal, "sum");
3974     Builder.CreateStore(Sum, SumReduced);
3975 
3976     FirstBodyIP = Builder.saveIP();
3977     FirstBodyAllocaIP = InnerAllocaIP;
3978   };
3979 
3980   InsertPointTy SecondBodyIP, SecondBodyAllocaIP;
3981   auto SecondBodyGenCB = [&](InsertPointTy InnerAllocaIP,
3982                              InsertPointTy CodeGenIP,
3983                              BasicBlock &ContinuationBB) {
3984     IRBuilderBase::InsertPointGuard Guard(Builder);
3985     Builder.restoreIP(CodeGenIP);
3986 
3987     uint32_t StrSize;
3988     Constant *SrcLocStr = OMPBuilder.getOrCreateSrcLocStr(Loc, StrSize);
3989     Value *Ident = OMPBuilder.getOrCreateIdent(SrcLocStr, StrSize);
3990     Value *TID = OMPBuilder.getOrCreateThreadID(Ident);
3991     Value *XorPartial = Builder.CreateLoad(XorType, XorReduced, "xor.partial");
3992     Value *Xor = Builder.CreateXor(XorPartial, TID, "xor");
3993     Builder.CreateStore(Xor, XorReduced);
3994 
3995     SecondBodyIP = Builder.saveIP();
3996     SecondBodyAllocaIP = InnerAllocaIP;
3997   };
3998 
3999   // Privatization for reduction creates local copies of reduction variables and
4000   // initializes them to reduction-neutral values. The same privatization
4001   // callback is used for both loops, with dispatch based on the value being
4002   // privatized.
4003   Value *SumPrivatized;
4004   Value *XorPrivatized;
4005   auto PrivCB = [&](InsertPointTy InnerAllocaIP, InsertPointTy CodeGenIP,
4006                     Value &Original, Value &Inner, Value *&ReplVal) {
4007     IRBuilderBase::InsertPointGuard Guard(Builder);
4008     Builder.restoreIP(InnerAllocaIP);
4009     if (&Original == SumReduced) {
4010       SumPrivatized = Builder.CreateAlloca(Builder.getFloatTy());
4011       ReplVal = SumPrivatized;
4012     } else if (&Original == XorReduced) {
4013       XorPrivatized = Builder.CreateAlloca(Builder.getInt32Ty());
4014       ReplVal = XorPrivatized;
4015     } else {
4016       ReplVal = &Inner;
4017       return CodeGenIP;
4018     }
4019 
4020     Builder.restoreIP(CodeGenIP);
4021     if (&Original == SumReduced)
4022       Builder.CreateStore(ConstantFP::get(Builder.getFloatTy(), 0.0),
4023                           SumPrivatized);
4024     else if (&Original == XorReduced)
4025       Builder.CreateStore(Builder.getInt32(0), XorPrivatized);
4026 
4027     return Builder.saveIP();
4028   };
4029 
4030   // Do nothing in finalization.
4031   auto FiniCB = [&](InsertPointTy CodeGenIP) { return CodeGenIP; };
4032 
4033   Builder.restoreIP(
4034       OMPBuilder.createParallel(Loc, OuterAllocaIP, FirstBodyGenCB, PrivCB,
4035                                 FiniCB, /* IfCondition */ nullptr,
4036                                 /* NumThreads */ nullptr, OMP_PROC_BIND_default,
4037                                 /* IsCancellable */ false));
4038   InsertPointTy AfterIP = OMPBuilder.createParallel(
4039       {Builder.saveIP(), DL}, OuterAllocaIP, SecondBodyGenCB, PrivCB, FiniCB,
4040       /* IfCondition */ nullptr,
4041       /* NumThreads */ nullptr, OMP_PROC_BIND_default,
4042       /* IsCancellable */ false);
4043 
4044   OMPBuilder.createReductions(
4045       FirstBodyIP, FirstBodyAllocaIP,
4046       {{SumType, SumReduced, SumPrivatized, sumReduction, sumAtomicReduction}});
4047   OMPBuilder.createReductions(
4048       SecondBodyIP, SecondBodyAllocaIP,
4049       {{XorType, XorReduced, XorPrivatized, xorReduction, xorAtomicReduction}});
4050 
4051   Builder.restoreIP(AfterIP);
4052   Builder.CreateRetVoid();
4053 
4054   OMPBuilder.finalize(F);
4055 
4056   // The IR must be valid.
4057   EXPECT_FALSE(verifyModule(*M));
4058 
4059   // Two different outlined functions must have been created.
4060   SmallVector<CallInst *> ForkCalls;
4061   findCalls(F, omp::RuntimeFunction::OMPRTL___kmpc_fork_call, OMPBuilder,
4062             ForkCalls);
4063   ASSERT_EQ(ForkCalls.size(), 2u);
4064   Value *CalleeVal = cast<Constant>(ForkCalls[0]->getOperand(2))->getOperand(0);
4065   Function *FirstCallee = cast<Function>(CalleeVal);
4066   CalleeVal = cast<Constant>(ForkCalls[1]->getOperand(2))->getOperand(0);
4067   Function *SecondCallee = cast<Function>(CalleeVal);
4068   EXPECT_NE(FirstCallee, SecondCallee);
4069 
4070   // Two different reduction functions must have been created.
4071   SmallVector<CallInst *> ReduceCalls;
4072   findCalls(FirstCallee, omp::RuntimeFunction::OMPRTL___kmpc_reduce, OMPBuilder,
4073             ReduceCalls);
4074   ASSERT_EQ(ReduceCalls.size(), 1u);
4075   auto *AddReduction = cast<Function>(ReduceCalls[0]->getOperand(5));
4076   ReduceCalls.clear();
4077   findCalls(SecondCallee, omp::RuntimeFunction::OMPRTL___kmpc_reduce,
4078             OMPBuilder, ReduceCalls);
4079   auto *XorReduction = cast<Function>(ReduceCalls[0]->getOperand(5));
4080   EXPECT_NE(AddReduction, XorReduction);
4081 
4082   // Each reduction function does its own kind of reduction.
4083   BasicBlock *FnReductionBB = &AddReduction->getEntryBlock();
4084   auto *Bitcast = findSingleUserInBlock<BitCastInst>(AddReduction->getArg(0),
4085                                                      FnReductionBB);
4086   ASSERT_NE(Bitcast, nullptr);
4087   Value *FirstLHSPtr =
4088       findSingleUserInBlock<GetElementPtrInst>(Bitcast, FnReductionBB);
4089   ASSERT_NE(FirstLHSPtr, nullptr);
4090   Value *Opaque = findSingleUserInBlock<LoadInst>(FirstLHSPtr, FnReductionBB);
4091   ASSERT_NE(Opaque, nullptr);
4092   Bitcast = findSingleUserInBlock<BitCastInst>(Opaque, FnReductionBB);
4093   ASSERT_NE(Bitcast, nullptr);
4094   Instruction::BinaryOps Opcode = Instruction::FAdd;
4095   EXPECT_TRUE(isSimpleBinaryReduction(Bitcast, FnReductionBB, &Opcode));
4096 
4097   FnReductionBB = &XorReduction->getEntryBlock();
4098   Bitcast = findSingleUserInBlock<BitCastInst>(XorReduction->getArg(0),
4099                                                FnReductionBB);
4100   ASSERT_NE(Bitcast, nullptr);
4101   Value *SecondLHSPtr =
4102       findSingleUserInBlock<GetElementPtrInst>(Bitcast, FnReductionBB);
4103   ASSERT_NE(FirstLHSPtr, nullptr);
4104   Opaque = findSingleUserInBlock<LoadInst>(SecondLHSPtr, FnReductionBB);
4105   ASSERT_NE(Opaque, nullptr);
4106   Bitcast = findSingleUserInBlock<BitCastInst>(Opaque, FnReductionBB);
4107   ASSERT_NE(Bitcast, nullptr);
4108   Opcode = Instruction::Xor;
4109   EXPECT_TRUE(isSimpleBinaryReduction(Bitcast, FnReductionBB, &Opcode));
4110 }
4111 
4112 TEST_F(OpenMPIRBuilderTest, CreateSectionsSimple) {
4113   using InsertPointTy = OpenMPIRBuilder::InsertPointTy;
4114   using BodyGenCallbackTy = llvm::OpenMPIRBuilder::StorableBodyGenCallbackTy;
4115   OpenMPIRBuilder OMPBuilder(*M);
4116   OMPBuilder.initialize();
4117   F->setName("func");
4118   IRBuilder<> Builder(BB);
4119 
4120   BasicBlock *EnterBB = BasicBlock::Create(Ctx, "sections.enter", F);
4121   Builder.CreateBr(EnterBB);
4122   Builder.SetInsertPoint(EnterBB);
4123   OpenMPIRBuilder::LocationDescription Loc({Builder.saveIP(), DL});
4124 
4125   llvm::SmallVector<BodyGenCallbackTy, 4> SectionCBVector;
4126   llvm::SmallVector<BasicBlock *, 4> CaseBBs;
4127 
4128   auto FiniCB = [&](InsertPointTy IP) {};
4129   auto SectionCB = [&](InsertPointTy AllocaIP, InsertPointTy CodeGenIP,
4130                        BasicBlock &FiniBB) {
4131     Builder.restoreIP(CodeGenIP);
4132     Builder.CreateBr(&FiniBB);
4133   };
4134   SectionCBVector.push_back(SectionCB);
4135 
4136   auto PrivCB = [](InsertPointTy AllocaIP, InsertPointTy CodeGenIP,
4137                    llvm::Value &, llvm::Value &Val,
4138                    llvm::Value *&ReplVal) { return CodeGenIP; };
4139   IRBuilder<>::InsertPoint AllocaIP(&F->getEntryBlock(),
4140                                     F->getEntryBlock().getFirstInsertionPt());
4141   Builder.restoreIP(OMPBuilder.createSections(Loc, AllocaIP, SectionCBVector,
4142                                               PrivCB, FiniCB, false, false));
4143   Builder.CreateRetVoid(); // Required at the end of the function
4144   EXPECT_NE(F->getEntryBlock().getTerminator(), nullptr);
4145   EXPECT_FALSE(verifyModule(*M, &errs()));
4146 }
4147 
4148 TEST_F(OpenMPIRBuilderTest, CreateSections) {
4149   using InsertPointTy = OpenMPIRBuilder::InsertPointTy;
4150   using BodyGenCallbackTy = llvm::OpenMPIRBuilder::StorableBodyGenCallbackTy;
4151   OpenMPIRBuilder OMPBuilder(*M);
4152   OMPBuilder.initialize();
4153   F->setName("func");
4154   IRBuilder<> Builder(BB);
4155 
4156   OpenMPIRBuilder::LocationDescription Loc({Builder.saveIP(), DL});
4157   llvm::SmallVector<BodyGenCallbackTy, 4> SectionCBVector;
4158   llvm::SmallVector<BasicBlock *, 4> CaseBBs;
4159 
4160   BasicBlock *SwitchBB = nullptr;
4161   BasicBlock *ForExitBB = nullptr;
4162   BasicBlock *ForIncBB = nullptr;
4163   AllocaInst *PrivAI = nullptr;
4164   SwitchInst *Switch = nullptr;
4165 
4166   unsigned NumBodiesGenerated = 0;
4167   unsigned NumFiniCBCalls = 0;
4168   PrivAI = Builder.CreateAlloca(F->arg_begin()->getType());
4169 
4170   auto FiniCB = [&](InsertPointTy IP) {
4171     ++NumFiniCBCalls;
4172     BasicBlock *IPBB = IP.getBlock();
4173     EXPECT_NE(IPBB->end(), IP.getPoint());
4174   };
4175 
4176   auto SectionCB = [&](InsertPointTy AllocaIP, InsertPointTy CodeGenIP,
4177                        BasicBlock &FiniBB) {
4178     ++NumBodiesGenerated;
4179     CaseBBs.push_back(CodeGenIP.getBlock());
4180     SwitchBB = CodeGenIP.getBlock()->getSinglePredecessor();
4181     Builder.restoreIP(CodeGenIP);
4182     Builder.CreateStore(F->arg_begin(), PrivAI);
4183     Value *PrivLoad =
4184         Builder.CreateLoad(F->arg_begin()->getType(), PrivAI, "local.alloca");
4185     Builder.CreateICmpNE(F->arg_begin(), PrivLoad);
4186     Builder.CreateBr(&FiniBB);
4187     ForIncBB =
4188         CodeGenIP.getBlock()->getSinglePredecessor()->getSingleSuccessor();
4189   };
4190   auto PrivCB = [](InsertPointTy AllocaIP, InsertPointTy CodeGenIP,
4191                    llvm::Value &, llvm::Value &Val, llvm::Value *&ReplVal) {
4192     // TODO: Privatization not implemented yet
4193     return CodeGenIP;
4194   };
4195 
4196   SectionCBVector.push_back(SectionCB);
4197   SectionCBVector.push_back(SectionCB);
4198 
4199   IRBuilder<>::InsertPoint AllocaIP(&F->getEntryBlock(),
4200                                     F->getEntryBlock().getFirstInsertionPt());
4201   Builder.restoreIP(OMPBuilder.createSections(Loc, AllocaIP, SectionCBVector,
4202                                               PrivCB, FiniCB, false, false));
4203   Builder.CreateRetVoid(); // Required at the end of the function
4204 
4205   // Switch BB's predecessor is loop condition BB, whose successor at index 1 is
4206   // loop's exit BB
4207   ForExitBB =
4208       SwitchBB->getSinglePredecessor()->getTerminator()->getSuccessor(1);
4209   EXPECT_NE(ForExitBB, nullptr);
4210 
4211   EXPECT_NE(PrivAI, nullptr);
4212   Function *OutlinedFn = PrivAI->getFunction();
4213   EXPECT_EQ(F, OutlinedFn);
4214   EXPECT_FALSE(verifyModule(*M, &errs()));
4215   EXPECT_EQ(OutlinedFn->arg_size(), 1U);
4216   EXPECT_EQ(OutlinedFn->getBasicBlockList().size(), size_t(11));
4217 
4218   BasicBlock *LoopPreheaderBB =
4219       OutlinedFn->getEntryBlock().getSingleSuccessor();
4220   // loop variables are 5 - lower bound, upper bound, stride, islastiter, and
4221   // iterator/counter
4222   bool FoundForInit = false;
4223   for (Instruction &Inst : *LoopPreheaderBB) {
4224     if (isa<CallInst>(Inst)) {
4225       if (cast<CallInst>(&Inst)->getCalledFunction()->getName() ==
4226           "__kmpc_for_static_init_4u") {
4227         FoundForInit = true;
4228       }
4229     }
4230   }
4231   EXPECT_EQ(FoundForInit, true);
4232 
4233   bool FoundForExit = false;
4234   bool FoundBarrier = false;
4235   for (Instruction &Inst : *ForExitBB) {
4236     if (isa<CallInst>(Inst)) {
4237       if (cast<CallInst>(&Inst)->getCalledFunction()->getName() ==
4238           "__kmpc_for_static_fini") {
4239         FoundForExit = true;
4240       }
4241       if (cast<CallInst>(&Inst)->getCalledFunction()->getName() ==
4242           "__kmpc_barrier") {
4243         FoundBarrier = true;
4244       }
4245       if (FoundForExit && FoundBarrier)
4246         break;
4247     }
4248   }
4249   EXPECT_EQ(FoundForExit, true);
4250   EXPECT_EQ(FoundBarrier, true);
4251 
4252   EXPECT_NE(SwitchBB, nullptr);
4253   EXPECT_NE(SwitchBB->getTerminator(), nullptr);
4254   EXPECT_EQ(isa<SwitchInst>(SwitchBB->getTerminator()), true);
4255   Switch = cast<SwitchInst>(SwitchBB->getTerminator());
4256   EXPECT_EQ(Switch->getNumCases(), 2U);
4257   EXPECT_NE(ForIncBB, nullptr);
4258   EXPECT_EQ(Switch->getSuccessor(0), ForIncBB);
4259 
4260   EXPECT_EQ(CaseBBs.size(), 2U);
4261   for (auto *&CaseBB : CaseBBs) {
4262     EXPECT_EQ(CaseBB->getParent(), OutlinedFn);
4263     EXPECT_EQ(CaseBB->getSingleSuccessor(), ForExitBB);
4264   }
4265 
4266   ASSERT_EQ(NumBodiesGenerated, 2U);
4267   ASSERT_EQ(NumFiniCBCalls, 1U);
4268   EXPECT_FALSE(verifyModule(*M, &errs()));
4269 }
4270 
4271 TEST_F(OpenMPIRBuilderTest, CreateSectionsNoWait) {
4272   using InsertPointTy = OpenMPIRBuilder::InsertPointTy;
4273   using BodyGenCallbackTy = llvm::OpenMPIRBuilder::StorableBodyGenCallbackTy;
4274   OpenMPIRBuilder OMPBuilder(*M);
4275   OMPBuilder.initialize();
4276   F->setName("func");
4277   IRBuilder<> Builder(BB);
4278 
4279   BasicBlock *EnterBB = BasicBlock::Create(Ctx, "sections.enter", F);
4280   Builder.CreateBr(EnterBB);
4281   Builder.SetInsertPoint(EnterBB);
4282   OpenMPIRBuilder::LocationDescription Loc({Builder.saveIP(), DL});
4283 
4284   IRBuilder<>::InsertPoint AllocaIP(&F->getEntryBlock(),
4285                                     F->getEntryBlock().getFirstInsertionPt());
4286   llvm::SmallVector<BodyGenCallbackTy, 4> SectionCBVector;
4287   auto PrivCB = [](InsertPointTy AllocaIP, InsertPointTy CodeGenIP,
4288                    llvm::Value &, llvm::Value &Val,
4289                    llvm::Value *&ReplVal) { return CodeGenIP; };
4290   auto FiniCB = [&](InsertPointTy IP) {};
4291 
4292   Builder.restoreIP(OMPBuilder.createSections(Loc, AllocaIP, SectionCBVector,
4293                                               PrivCB, FiniCB, false, true));
4294   Builder.CreateRetVoid(); // Required at the end of the function
4295   for (auto &Inst : instructions(*F)) {
4296     EXPECT_FALSE(isa<CallInst>(Inst) &&
4297                  cast<CallInst>(&Inst)->getCalledFunction()->getName() ==
4298                      "__kmpc_barrier" &&
4299                  "call to function __kmpc_barrier found with nowait");
4300   }
4301 }
4302 
4303 TEST_F(OpenMPIRBuilderTest, CreateOffloadMaptypes) {
4304   OpenMPIRBuilder OMPBuilder(*M);
4305   OMPBuilder.initialize();
4306 
4307   IRBuilder<> Builder(BB);
4308 
4309   SmallVector<uint64_t> Mappings = {0, 1};
4310   GlobalVariable *OffloadMaptypesGlobal =
4311       OMPBuilder.createOffloadMaptypes(Mappings, "offload_maptypes");
4312   EXPECT_FALSE(M->global_empty());
4313   EXPECT_EQ(OffloadMaptypesGlobal->getName(), "offload_maptypes");
4314   EXPECT_TRUE(OffloadMaptypesGlobal->isConstant());
4315   EXPECT_TRUE(OffloadMaptypesGlobal->hasGlobalUnnamedAddr());
4316   EXPECT_TRUE(OffloadMaptypesGlobal->hasPrivateLinkage());
4317   EXPECT_TRUE(OffloadMaptypesGlobal->hasInitializer());
4318   Constant *Initializer = OffloadMaptypesGlobal->getInitializer();
4319   EXPECT_TRUE(isa<ConstantDataArray>(Initializer));
4320   ConstantDataArray *MappingInit = dyn_cast<ConstantDataArray>(Initializer);
4321   EXPECT_EQ(MappingInit->getNumElements(), Mappings.size());
4322   EXPECT_TRUE(MappingInit->getType()->getElementType()->isIntegerTy(64));
4323   Constant *CA = ConstantDataArray::get(Builder.getContext(), Mappings);
4324   EXPECT_EQ(MappingInit, CA);
4325 }
4326 
4327 TEST_F(OpenMPIRBuilderTest, CreateOffloadMapnames) {
4328   OpenMPIRBuilder OMPBuilder(*M);
4329   OMPBuilder.initialize();
4330 
4331   IRBuilder<> Builder(BB);
4332 
4333   uint32_t StrSize;
4334   Constant *Cst1 =
4335       OMPBuilder.getOrCreateSrcLocStr("array1", "file1", 2, 5, StrSize);
4336   Constant *Cst2 =
4337       OMPBuilder.getOrCreateSrcLocStr("array2", "file1", 3, 5, StrSize);
4338   SmallVector<llvm::Constant *> Names = {Cst1, Cst2};
4339 
4340   GlobalVariable *OffloadMaptypesGlobal =
4341       OMPBuilder.createOffloadMapnames(Names, "offload_mapnames");
4342   EXPECT_FALSE(M->global_empty());
4343   EXPECT_EQ(OffloadMaptypesGlobal->getName(), "offload_mapnames");
4344   EXPECT_TRUE(OffloadMaptypesGlobal->isConstant());
4345   EXPECT_FALSE(OffloadMaptypesGlobal->hasGlobalUnnamedAddr());
4346   EXPECT_TRUE(OffloadMaptypesGlobal->hasPrivateLinkage());
4347   EXPECT_TRUE(OffloadMaptypesGlobal->hasInitializer());
4348   Constant *Initializer = OffloadMaptypesGlobal->getInitializer();
4349   EXPECT_TRUE(isa<Constant>(Initializer->getOperand(0)->stripPointerCasts()));
4350   EXPECT_TRUE(isa<Constant>(Initializer->getOperand(1)->stripPointerCasts()));
4351 
4352   GlobalVariable *Name1Gbl =
4353       cast<GlobalVariable>(Initializer->getOperand(0)->stripPointerCasts());
4354   EXPECT_TRUE(isa<ConstantDataArray>(Name1Gbl->getInitializer()));
4355   ConstantDataArray *Name1GblCA =
4356       dyn_cast<ConstantDataArray>(Name1Gbl->getInitializer());
4357   EXPECT_EQ(Name1GblCA->getAsCString(), ";file1;array1;2;5;;");
4358 
4359   GlobalVariable *Name2Gbl =
4360       cast<GlobalVariable>(Initializer->getOperand(1)->stripPointerCasts());
4361   EXPECT_TRUE(isa<ConstantDataArray>(Name2Gbl->getInitializer()));
4362   ConstantDataArray *Name2GblCA =
4363       dyn_cast<ConstantDataArray>(Name2Gbl->getInitializer());
4364   EXPECT_EQ(Name2GblCA->getAsCString(), ";file1;array2;3;5;;");
4365 
4366   EXPECT_TRUE(Initializer->getType()->getArrayElementType()->isPointerTy());
4367   EXPECT_EQ(Initializer->getType()->getArrayNumElements(), Names.size());
4368 }
4369 
4370 TEST_F(OpenMPIRBuilderTest, CreateMapperAllocas) {
4371   OpenMPIRBuilder OMPBuilder(*M);
4372   OMPBuilder.initialize();
4373   F->setName("func");
4374   IRBuilder<> Builder(BB);
4375 
4376   OpenMPIRBuilder::LocationDescription Loc({Builder.saveIP(), DL});
4377 
4378   unsigned TotalNbOperand = 2;
4379 
4380   OpenMPIRBuilder::MapperAllocas MapperAllocas;
4381   IRBuilder<>::InsertPoint AllocaIP(&F->getEntryBlock(),
4382                                     F->getEntryBlock().getFirstInsertionPt());
4383   OMPBuilder.createMapperAllocas(Loc, AllocaIP, TotalNbOperand, MapperAllocas);
4384   EXPECT_NE(MapperAllocas.ArgsBase, nullptr);
4385   EXPECT_NE(MapperAllocas.Args, nullptr);
4386   EXPECT_NE(MapperAllocas.ArgSizes, nullptr);
4387   EXPECT_TRUE(MapperAllocas.ArgsBase->getAllocatedType()->isArrayTy());
4388   ArrayType *ArrType =
4389       dyn_cast<ArrayType>(MapperAllocas.ArgsBase->getAllocatedType());
4390   EXPECT_EQ(ArrType->getNumElements(), TotalNbOperand);
4391   EXPECT_TRUE(MapperAllocas.ArgsBase->getAllocatedType()
4392                   ->getArrayElementType()
4393                   ->isPointerTy());
4394   EXPECT_TRUE(
4395       cast<PointerType>(
4396           MapperAllocas.ArgsBase->getAllocatedType()->getArrayElementType())
4397           ->isOpaqueOrPointeeTypeMatches(Builder.getInt8Ty()));
4398 
4399   EXPECT_TRUE(MapperAllocas.Args->getAllocatedType()->isArrayTy());
4400   ArrType = dyn_cast<ArrayType>(MapperAllocas.Args->getAllocatedType());
4401   EXPECT_EQ(ArrType->getNumElements(), TotalNbOperand);
4402   EXPECT_TRUE(MapperAllocas.Args->getAllocatedType()
4403                   ->getArrayElementType()
4404                   ->isPointerTy());
4405   EXPECT_TRUE(cast<PointerType>(
4406                   MapperAllocas.Args->getAllocatedType()->getArrayElementType())
4407                   ->isOpaqueOrPointeeTypeMatches(Builder.getInt8Ty()));
4408 
4409   EXPECT_TRUE(MapperAllocas.ArgSizes->getAllocatedType()->isArrayTy());
4410   ArrType = dyn_cast<ArrayType>(MapperAllocas.ArgSizes->getAllocatedType());
4411   EXPECT_EQ(ArrType->getNumElements(), TotalNbOperand);
4412   EXPECT_TRUE(MapperAllocas.ArgSizes->getAllocatedType()
4413                   ->getArrayElementType()
4414                   ->isIntegerTy(64));
4415 }
4416 
4417 TEST_F(OpenMPIRBuilderTest, EmitMapperCall) {
4418   OpenMPIRBuilder OMPBuilder(*M);
4419   OMPBuilder.initialize();
4420   F->setName("func");
4421   IRBuilder<> Builder(BB);
4422   LLVMContext &Ctx = M->getContext();
4423 
4424   OpenMPIRBuilder::LocationDescription Loc({Builder.saveIP(), DL});
4425 
4426   unsigned TotalNbOperand = 2;
4427 
4428   OpenMPIRBuilder::MapperAllocas MapperAllocas;
4429   IRBuilder<>::InsertPoint AllocaIP(&F->getEntryBlock(),
4430                                     F->getEntryBlock().getFirstInsertionPt());
4431   OMPBuilder.createMapperAllocas(Loc, AllocaIP, TotalNbOperand, MapperAllocas);
4432 
4433   auto *BeginMapperFunc = OMPBuilder.getOrCreateRuntimeFunctionPtr(
4434       omp::OMPRTL___tgt_target_data_begin_mapper);
4435 
4436   SmallVector<uint64_t> Flags = {0, 2};
4437 
4438   uint32_t StrSize;
4439   Constant *SrcLocCst =
4440       OMPBuilder.getOrCreateSrcLocStr("", "file1", 2, 5, StrSize);
4441   Value *SrcLocInfo = OMPBuilder.getOrCreateIdent(SrcLocCst, StrSize);
4442 
4443   Constant *Cst1 =
4444       OMPBuilder.getOrCreateSrcLocStr("array1", "file1", 2, 5, StrSize);
4445   Constant *Cst2 =
4446       OMPBuilder.getOrCreateSrcLocStr("array2", "file1", 3, 5, StrSize);
4447   SmallVector<llvm::Constant *> Names = {Cst1, Cst2};
4448 
4449   GlobalVariable *Maptypes =
4450       OMPBuilder.createOffloadMaptypes(Flags, ".offload_maptypes");
4451   Value *MaptypesArg = Builder.CreateConstInBoundsGEP2_32(
4452       ArrayType::get(Type::getInt64Ty(Ctx), TotalNbOperand), Maptypes,
4453       /*Idx0=*/0, /*Idx1=*/0);
4454 
4455   GlobalVariable *Mapnames =
4456       OMPBuilder.createOffloadMapnames(Names, ".offload_mapnames");
4457   Value *MapnamesArg = Builder.CreateConstInBoundsGEP2_32(
4458       ArrayType::get(Type::getInt8PtrTy(Ctx), TotalNbOperand), Mapnames,
4459       /*Idx0=*/0, /*Idx1=*/0);
4460 
4461   OMPBuilder.emitMapperCall(Builder.saveIP(), BeginMapperFunc, SrcLocInfo,
4462                             MaptypesArg, MapnamesArg, MapperAllocas, -1,
4463                             TotalNbOperand);
4464 
4465   CallInst *MapperCall = dyn_cast<CallInst>(&BB->back());
4466   EXPECT_NE(MapperCall, nullptr);
4467   EXPECT_EQ(MapperCall->arg_size(), 9U);
4468   EXPECT_EQ(MapperCall->getCalledFunction()->getName(),
4469             "__tgt_target_data_begin_mapper");
4470   EXPECT_EQ(MapperCall->getOperand(0), SrcLocInfo);
4471   EXPECT_TRUE(MapperCall->getOperand(1)->getType()->isIntegerTy(64));
4472   EXPECT_TRUE(MapperCall->getOperand(2)->getType()->isIntegerTy(32));
4473 
4474   EXPECT_EQ(MapperCall->getOperand(6), MaptypesArg);
4475   EXPECT_EQ(MapperCall->getOperand(7), MapnamesArg);
4476   EXPECT_TRUE(MapperCall->getOperand(8)->getType()->isPointerTy());
4477 }
4478 
4479 } // namespace
4480