]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/CodeGen/CGStmtOpenMP.cpp
Merge llvm, clang, lld, lldb, compiler-rt and libc++ trunk r321545,
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / lib / CodeGen / CGStmtOpenMP.cpp
1 //===--- CGStmtOpenMP.cpp - Emit LLVM Code from Statements ----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This contains code to emit OpenMP nodes as LLVM code.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "CGCleanup.h"
15 #include "CGOpenMPRuntime.h"
16 #include "CodeGenFunction.h"
17 #include "CodeGenModule.h"
18 #include "TargetInfo.h"
19 #include "clang/AST/Stmt.h"
20 #include "clang/AST/StmtOpenMP.h"
21 #include "clang/AST/DeclOpenMP.h"
22 #include "llvm/IR/CallSite.h"
23 using namespace clang;
24 using namespace CodeGen;
25
26 namespace {
27 /// Lexical scope for OpenMP executable constructs, that handles correct codegen
28 /// for captured expressions.
29 class OMPLexicalScope : public CodeGenFunction::LexicalScope {
30   void emitPreInitStmt(CodeGenFunction &CGF, const OMPExecutableDirective &S) {
31     for (const auto *C : S.clauses()) {
32       if (auto *CPI = OMPClauseWithPreInit::get(C)) {
33         if (auto *PreInit = cast_or_null<DeclStmt>(CPI->getPreInitStmt())) {
34           for (const auto *I : PreInit->decls()) {
35             if (!I->hasAttr<OMPCaptureNoInitAttr>())
36               CGF.EmitVarDecl(cast<VarDecl>(*I));
37             else {
38               CodeGenFunction::AutoVarEmission Emission =
39                   CGF.EmitAutoVarAlloca(cast<VarDecl>(*I));
40               CGF.EmitAutoVarCleanups(Emission);
41             }
42           }
43         }
44       }
45     }
46   }
47   CodeGenFunction::OMPPrivateScope InlinedShareds;
48
49   static bool isCapturedVar(CodeGenFunction &CGF, const VarDecl *VD) {
50     return CGF.LambdaCaptureFields.lookup(VD) ||
51            (CGF.CapturedStmtInfo && CGF.CapturedStmtInfo->lookup(VD)) ||
52            (CGF.CurCodeDecl && isa<BlockDecl>(CGF.CurCodeDecl));
53   }
54
55 public:
56   OMPLexicalScope(CodeGenFunction &CGF, const OMPExecutableDirective &S,
57                   bool AsInlined = false, bool EmitPreInitStmt = true)
58       : CodeGenFunction::LexicalScope(CGF, S.getSourceRange()),
59         InlinedShareds(CGF) {
60     if (EmitPreInitStmt)
61       emitPreInitStmt(CGF, S);
62     if (AsInlined) {
63       if (S.hasAssociatedStmt()) {
64         auto *CS = cast<CapturedStmt>(S.getAssociatedStmt());
65         for (auto &C : CS->captures()) {
66           if (C.capturesVariable() || C.capturesVariableByCopy()) {
67             auto *VD = C.getCapturedVar();
68             assert(VD == VD->getCanonicalDecl() &&
69                         "Canonical decl must be captured.");
70             DeclRefExpr DRE(const_cast<VarDecl *>(VD),
71                             isCapturedVar(CGF, VD) ||
72                                 (CGF.CapturedStmtInfo &&
73                                  InlinedShareds.isGlobalVarCaptured(VD)),
74                             VD->getType().getNonReferenceType(), VK_LValue,
75                             SourceLocation());
76             InlinedShareds.addPrivate(VD, [&CGF, &DRE]() -> Address {
77               return CGF.EmitLValue(&DRE).getAddress();
78             });
79           }
80         }
81         (void)InlinedShareds.Privatize();
82       }
83     }
84   }
85 };
86
87 /// Lexical scope for OpenMP parallel construct, that handles correct codegen
88 /// for captured expressions.
89 class OMPParallelScope final : public OMPLexicalScope {
90   bool EmitPreInitStmt(const OMPExecutableDirective &S) {
91     OpenMPDirectiveKind Kind = S.getDirectiveKind();
92     return !(isOpenMPTargetExecutionDirective(Kind) ||
93              isOpenMPLoopBoundSharingDirective(Kind)) &&
94            isOpenMPParallelDirective(Kind);
95   }
96
97 public:
98   OMPParallelScope(CodeGenFunction &CGF, const OMPExecutableDirective &S)
99       : OMPLexicalScope(CGF, S,
100                         /*AsInlined=*/false,
101                         /*EmitPreInitStmt=*/EmitPreInitStmt(S)) {}
102 };
103
104 /// Lexical scope for OpenMP teams construct, that handles correct codegen
105 /// for captured expressions.
106 class OMPTeamsScope final : public OMPLexicalScope {
107   bool EmitPreInitStmt(const OMPExecutableDirective &S) {
108     OpenMPDirectiveKind Kind = S.getDirectiveKind();
109     return !isOpenMPTargetExecutionDirective(Kind) &&
110            isOpenMPTeamsDirective(Kind);
111   }
112
113 public:
114   OMPTeamsScope(CodeGenFunction &CGF, const OMPExecutableDirective &S)
115       : OMPLexicalScope(CGF, S,
116                         /*AsInlined=*/false,
117                         /*EmitPreInitStmt=*/EmitPreInitStmt(S)) {}
118 };
119
120 /// Private scope for OpenMP loop-based directives, that supports capturing
121 /// of used expression from loop statement.
122 class OMPLoopScope : public CodeGenFunction::RunCleanupsScope {
123   void emitPreInitStmt(CodeGenFunction &CGF, const OMPLoopDirective &S) {
124     CodeGenFunction::OMPPrivateScope PreCondScope(CGF);
125     for (auto *E : S.counters()) {
126       const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
127       (void)PreCondScope.addPrivate(VD, [&CGF, VD]() {
128         return CGF.CreateMemTemp(VD->getType().getNonReferenceType());
129       });
130     }
131     (void)PreCondScope.Privatize();
132     if (auto *LD = dyn_cast<OMPLoopDirective>(&S)) {
133       if (auto *PreInits = cast_or_null<DeclStmt>(LD->getPreInits())) {
134         for (const auto *I : PreInits->decls())
135           CGF.EmitVarDecl(cast<VarDecl>(*I));
136       }
137     }
138   }
139
140 public:
141   OMPLoopScope(CodeGenFunction &CGF, const OMPLoopDirective &S)
142       : CodeGenFunction::RunCleanupsScope(CGF) {
143     emitPreInitStmt(CGF, S);
144   }
145 };
146
147 } // namespace
148
149 static void emitCommonOMPTargetDirective(CodeGenFunction &CGF,
150                                          const OMPExecutableDirective &S,
151                                          const RegionCodeGenTy &CodeGen);
152
153 LValue CodeGenFunction::EmitOMPSharedLValue(const Expr *E) {
154   if (auto *OrigDRE = dyn_cast<DeclRefExpr>(E)) {
155     if (auto *OrigVD = dyn_cast<VarDecl>(OrigDRE->getDecl())) {
156       OrigVD = OrigVD->getCanonicalDecl();
157       bool IsCaptured =
158           LambdaCaptureFields.lookup(OrigVD) ||
159           (CapturedStmtInfo && CapturedStmtInfo->lookup(OrigVD)) ||
160           (CurCodeDecl && isa<BlockDecl>(CurCodeDecl));
161       DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD), IsCaptured,
162                       OrigDRE->getType(), VK_LValue, OrigDRE->getExprLoc());
163       return EmitLValue(&DRE);
164     }
165   }
166   return EmitLValue(E);
167 }
168
169 llvm::Value *CodeGenFunction::getTypeSize(QualType Ty) {
170   auto &C = getContext();
171   llvm::Value *Size = nullptr;
172   auto SizeInChars = C.getTypeSizeInChars(Ty);
173   if (SizeInChars.isZero()) {
174     // getTypeSizeInChars() returns 0 for a VLA.
175     while (auto *VAT = C.getAsVariableArrayType(Ty)) {
176       llvm::Value *ArraySize;
177       std::tie(ArraySize, Ty) = getVLASize(VAT);
178       Size = Size ? Builder.CreateNUWMul(Size, ArraySize) : ArraySize;
179     }
180     SizeInChars = C.getTypeSizeInChars(Ty);
181     if (SizeInChars.isZero())
182       return llvm::ConstantInt::get(SizeTy, /*V=*/0);
183     Size = Builder.CreateNUWMul(Size, CGM.getSize(SizeInChars));
184   } else
185     Size = CGM.getSize(SizeInChars);
186   return Size;
187 }
188
189 void CodeGenFunction::GenerateOpenMPCapturedVars(
190     const CapturedStmt &S, SmallVectorImpl<llvm::Value *> &CapturedVars) {
191   const RecordDecl *RD = S.getCapturedRecordDecl();
192   auto CurField = RD->field_begin();
193   auto CurCap = S.captures().begin();
194   for (CapturedStmt::const_capture_init_iterator I = S.capture_init_begin(),
195                                                  E = S.capture_init_end();
196        I != E; ++I, ++CurField, ++CurCap) {
197     if (CurField->hasCapturedVLAType()) {
198       auto VAT = CurField->getCapturedVLAType();
199       auto *Val = VLASizeMap[VAT->getSizeExpr()];
200       CapturedVars.push_back(Val);
201     } else if (CurCap->capturesThis())
202       CapturedVars.push_back(CXXThisValue);
203     else if (CurCap->capturesVariableByCopy()) {
204       llvm::Value *CV =
205           EmitLoadOfLValue(EmitLValue(*I), SourceLocation()).getScalarVal();
206
207       // If the field is not a pointer, we need to save the actual value
208       // and load it as a void pointer.
209       if (!CurField->getType()->isAnyPointerType()) {
210         auto &Ctx = getContext();
211         auto DstAddr = CreateMemTemp(
212             Ctx.getUIntPtrType(),
213             Twine(CurCap->getCapturedVar()->getName()) + ".casted");
214         LValue DstLV = MakeAddrLValue(DstAddr, Ctx.getUIntPtrType());
215
216         auto *SrcAddrVal = EmitScalarConversion(
217             DstAddr.getPointer(), Ctx.getPointerType(Ctx.getUIntPtrType()),
218             Ctx.getPointerType(CurField->getType()), SourceLocation());
219         LValue SrcLV =
220             MakeNaturalAlignAddrLValue(SrcAddrVal, CurField->getType());
221
222         // Store the value using the source type pointer.
223         EmitStoreThroughLValue(RValue::get(CV), SrcLV);
224
225         // Load the value using the destination type pointer.
226         CV = EmitLoadOfLValue(DstLV, SourceLocation()).getScalarVal();
227       }
228       CapturedVars.push_back(CV);
229     } else {
230       assert(CurCap->capturesVariable() && "Expected capture by reference.");
231       CapturedVars.push_back(EmitLValue(*I).getAddress().getPointer());
232     }
233   }
234 }
235
236 static Address castValueFromUintptr(CodeGenFunction &CGF, QualType DstType,
237                                     StringRef Name, LValue AddrLV,
238                                     bool isReferenceType = false) {
239   ASTContext &Ctx = CGF.getContext();
240
241   auto *CastedPtr = CGF.EmitScalarConversion(
242       AddrLV.getAddress().getPointer(), Ctx.getUIntPtrType(),
243       Ctx.getPointerType(DstType), SourceLocation());
244   auto TmpAddr =
245       CGF.MakeNaturalAlignAddrLValue(CastedPtr, Ctx.getPointerType(DstType))
246           .getAddress();
247
248   // If we are dealing with references we need to return the address of the
249   // reference instead of the reference of the value.
250   if (isReferenceType) {
251     QualType RefType = Ctx.getLValueReferenceType(DstType);
252     auto *RefVal = TmpAddr.getPointer();
253     TmpAddr = CGF.CreateMemTemp(RefType, Twine(Name) + ".ref");
254     auto TmpLVal = CGF.MakeAddrLValue(TmpAddr, RefType);
255     CGF.EmitStoreThroughLValue(RValue::get(RefVal), TmpLVal, /*isInit*/ true);
256   }
257
258   return TmpAddr;
259 }
260
261 static QualType getCanonicalParamType(ASTContext &C, QualType T) {
262   if (T->isLValueReferenceType()) {
263     return C.getLValueReferenceType(
264         getCanonicalParamType(C, T.getNonReferenceType()),
265         /*SpelledAsLValue=*/false);
266   }
267   if (T->isPointerType())
268     return C.getPointerType(getCanonicalParamType(C, T->getPointeeType()));
269   if (auto *A = T->getAsArrayTypeUnsafe()) {
270     if (auto *VLA = dyn_cast<VariableArrayType>(A))
271       return getCanonicalParamType(C, VLA->getElementType());
272     else if (!A->isVariablyModifiedType())
273       return C.getCanonicalType(T);
274   }
275   return C.getCanonicalParamType(T);
276 }
277
278 namespace {
279   /// Contains required data for proper outlined function codegen.
280   struct FunctionOptions {
281     /// Captured statement for which the function is generated.
282     const CapturedStmt *S = nullptr;
283     /// true if cast to/from  UIntPtr is required for variables captured by
284     /// value.
285     const bool UIntPtrCastRequired = true;
286     /// true if only casted arguments must be registered as local args or VLA
287     /// sizes.
288     const bool RegisterCastedArgsOnly = false;
289     /// Name of the generated function.
290     const StringRef FunctionName;
291     explicit FunctionOptions(const CapturedStmt *S, bool UIntPtrCastRequired,
292                              bool RegisterCastedArgsOnly,
293                              StringRef FunctionName)
294         : S(S), UIntPtrCastRequired(UIntPtrCastRequired),
295           RegisterCastedArgsOnly(UIntPtrCastRequired && RegisterCastedArgsOnly),
296           FunctionName(FunctionName) {}
297   };
298 }
299
300 static llvm::Function *emitOutlinedFunctionPrologue(
301     CodeGenFunction &CGF, FunctionArgList &Args,
302     llvm::MapVector<const Decl *, std::pair<const VarDecl *, Address>>
303         &LocalAddrs,
304     llvm::DenseMap<const Decl *, std::pair<const Expr *, llvm::Value *>>
305         &VLASizes,
306     llvm::Value *&CXXThisValue, const FunctionOptions &FO) {
307   const CapturedDecl *CD = FO.S->getCapturedDecl();
308   const RecordDecl *RD = FO.S->getCapturedRecordDecl();
309   assert(CD->hasBody() && "missing CapturedDecl body");
310
311   CXXThisValue = nullptr;
312   // Build the argument list.
313   CodeGenModule &CGM = CGF.CGM;
314   ASTContext &Ctx = CGM.getContext();
315   FunctionArgList TargetArgs;
316   Args.append(CD->param_begin(),
317               std::next(CD->param_begin(), CD->getContextParamPosition()));
318   TargetArgs.append(
319       CD->param_begin(),
320       std::next(CD->param_begin(), CD->getContextParamPosition()));
321   auto I = FO.S->captures().begin();
322   FunctionDecl *DebugFunctionDecl = nullptr;
323   if (!FO.UIntPtrCastRequired) {
324     FunctionProtoType::ExtProtoInfo EPI;
325     DebugFunctionDecl = FunctionDecl::Create(
326         Ctx, Ctx.getTranslationUnitDecl(), FO.S->getLocStart(),
327         SourceLocation(), DeclarationName(), Ctx.VoidTy,
328         Ctx.getTrivialTypeSourceInfo(
329             Ctx.getFunctionType(Ctx.VoidTy, llvm::None, EPI)),
330         SC_Static, /*isInlineSpecified=*/false, /*hasWrittenPrototype=*/false);
331   }
332   for (auto *FD : RD->fields()) {
333     QualType ArgType = FD->getType();
334     IdentifierInfo *II = nullptr;
335     VarDecl *CapVar = nullptr;
336
337     // If this is a capture by copy and the type is not a pointer, the outlined
338     // function argument type should be uintptr and the value properly casted to
339     // uintptr. This is necessary given that the runtime library is only able to
340     // deal with pointers. We can pass in the same way the VLA type sizes to the
341     // outlined function.
342     if ((I->capturesVariableByCopy() && !ArgType->isAnyPointerType()) ||
343         I->capturesVariableArrayType()) {
344       if (FO.UIntPtrCastRequired)
345         ArgType = Ctx.getUIntPtrType();
346     }
347
348     if (I->capturesVariable() || I->capturesVariableByCopy()) {
349       CapVar = I->getCapturedVar();
350       II = CapVar->getIdentifier();
351     } else if (I->capturesThis())
352       II = &Ctx.Idents.get("this");
353     else {
354       assert(I->capturesVariableArrayType());
355       II = &Ctx.Idents.get("vla");
356     }
357     if (ArgType->isVariablyModifiedType())
358       ArgType = getCanonicalParamType(Ctx, ArgType);
359     VarDecl *Arg;
360     if (DebugFunctionDecl && (CapVar || I->capturesThis())) {
361       Arg = ParmVarDecl::Create(
362           Ctx, DebugFunctionDecl,
363           CapVar ? CapVar->getLocStart() : FD->getLocStart(),
364           CapVar ? CapVar->getLocation() : FD->getLocation(), II, ArgType,
365           /*TInfo=*/nullptr, SC_None, /*DefArg=*/nullptr);
366     } else {
367       Arg = ImplicitParamDecl::Create(Ctx, /*DC=*/nullptr, FD->getLocation(),
368                                       II, ArgType, ImplicitParamDecl::Other);
369     }
370     Args.emplace_back(Arg);
371     // Do not cast arguments if we emit function with non-original types.
372     TargetArgs.emplace_back(
373         FO.UIntPtrCastRequired
374             ? Arg
375             : CGM.getOpenMPRuntime().translateParameter(FD, Arg));
376     ++I;
377   }
378   Args.append(
379       std::next(CD->param_begin(), CD->getContextParamPosition() + 1),
380       CD->param_end());
381   TargetArgs.append(
382       std::next(CD->param_begin(), CD->getContextParamPosition() + 1),
383       CD->param_end());
384
385   // Create the function declaration.
386   const CGFunctionInfo &FuncInfo =
387       CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, TargetArgs);
388   llvm::FunctionType *FuncLLVMTy = CGM.getTypes().GetFunctionType(FuncInfo);
389
390   llvm::Function *F =
391       llvm::Function::Create(FuncLLVMTy, llvm::GlobalValue::InternalLinkage,
392                              FO.FunctionName, &CGM.getModule());
393   CGM.SetInternalFunctionAttributes(CD, F, FuncInfo);
394   if (CD->isNothrow())
395     F->setDoesNotThrow();
396
397   // Generate the function.
398   CGF.StartFunction(CD, Ctx.VoidTy, F, FuncInfo, TargetArgs,
399                     FO.S->getLocStart(), CD->getBody()->getLocStart());
400   unsigned Cnt = CD->getContextParamPosition();
401   I = FO.S->captures().begin();
402   for (auto *FD : RD->fields()) {
403     // Do not map arguments if we emit function with non-original types.
404     Address LocalAddr(Address::invalid());
405     if (!FO.UIntPtrCastRequired && Args[Cnt] != TargetArgs[Cnt]) {
406       LocalAddr = CGM.getOpenMPRuntime().getParameterAddress(CGF, Args[Cnt],
407                                                              TargetArgs[Cnt]);
408     } else {
409       LocalAddr = CGF.GetAddrOfLocalVar(Args[Cnt]);
410     }
411     // If we are capturing a pointer by copy we don't need to do anything, just
412     // use the value that we get from the arguments.
413     if (I->capturesVariableByCopy() && FD->getType()->isAnyPointerType()) {
414       const VarDecl *CurVD = I->getCapturedVar();
415       // If the variable is a reference we need to materialize it here.
416       if (CurVD->getType()->isReferenceType()) {
417         Address RefAddr = CGF.CreateMemTemp(
418             CurVD->getType(), CGM.getPointerAlign(), ".materialized_ref");
419         CGF.EmitStoreOfScalar(LocalAddr.getPointer(), RefAddr,
420                               /*Volatile=*/false, CurVD->getType());
421         LocalAddr = RefAddr;
422       }
423       if (!FO.RegisterCastedArgsOnly)
424         LocalAddrs.insert({Args[Cnt], {CurVD, LocalAddr}});
425       ++Cnt;
426       ++I;
427       continue;
428     }
429
430     LValue ArgLVal = CGF.MakeAddrLValue(LocalAddr, Args[Cnt]->getType(),
431                                         AlignmentSource::Decl);
432     if (FD->hasCapturedVLAType()) {
433       if (FO.UIntPtrCastRequired) {
434         ArgLVal = CGF.MakeAddrLValue(castValueFromUintptr(CGF, FD->getType(),
435                                                           Args[Cnt]->getName(),
436                                                           ArgLVal),
437                                      FD->getType(), AlignmentSource::Decl);
438       }
439       auto *ExprArg =
440           CGF.EmitLoadOfLValue(ArgLVal, SourceLocation()).getScalarVal();
441       auto VAT = FD->getCapturedVLAType();
442       VLASizes.insert({Args[Cnt], {VAT->getSizeExpr(), ExprArg}});
443     } else if (I->capturesVariable()) {
444       auto *Var = I->getCapturedVar();
445       QualType VarTy = Var->getType();
446       Address ArgAddr = ArgLVal.getAddress();
447       if (!VarTy->isReferenceType()) {
448         if (ArgLVal.getType()->isLValueReferenceType()) {
449           ArgAddr = CGF.EmitLoadOfReference(ArgLVal);
450         } else if (!VarTy->isVariablyModifiedType() || !VarTy->isPointerType()) {
451           assert(ArgLVal.getType()->isPointerType());
452           ArgAddr = CGF.EmitLoadOfPointer(
453               ArgAddr, ArgLVal.getType()->castAs<PointerType>());
454         }
455       }
456       if (!FO.RegisterCastedArgsOnly) {
457         LocalAddrs.insert(
458             {Args[Cnt],
459              {Var, Address(ArgAddr.getPointer(), Ctx.getDeclAlign(Var))}});
460       }
461     } else if (I->capturesVariableByCopy()) {
462       assert(!FD->getType()->isAnyPointerType() &&
463              "Not expecting a captured pointer.");
464       auto *Var = I->getCapturedVar();
465       QualType VarTy = Var->getType();
466       LocalAddrs.insert(
467           {Args[Cnt],
468            {Var,
469             FO.UIntPtrCastRequired
470                 ? castValueFromUintptr(CGF, FD->getType(), Args[Cnt]->getName(),
471                                        ArgLVal, VarTy->isReferenceType())
472                 : ArgLVal.getAddress()}});
473     } else {
474       // If 'this' is captured, load it into CXXThisValue.
475       assert(I->capturesThis());
476       CXXThisValue = CGF.EmitLoadOfLValue(ArgLVal, Args[Cnt]->getLocation())
477                          .getScalarVal();
478       LocalAddrs.insert({Args[Cnt], {nullptr, ArgLVal.getAddress()}});
479     }
480     ++Cnt;
481     ++I;
482   }
483
484   return F;
485 }
486
487 llvm::Function *
488 CodeGenFunction::GenerateOpenMPCapturedStmtFunction(const CapturedStmt &S) {
489   assert(
490       CapturedStmtInfo &&
491       "CapturedStmtInfo should be set when generating the captured function");
492   const CapturedDecl *CD = S.getCapturedDecl();
493   // Build the argument list.
494   bool NeedWrapperFunction =
495       getDebugInfo() &&
496       CGM.getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo;
497   FunctionArgList Args;
498   llvm::MapVector<const Decl *, std::pair<const VarDecl *, Address>> LocalAddrs;
499   llvm::DenseMap<const Decl *, std::pair<const Expr *, llvm::Value *>> VLASizes;
500   SmallString<256> Buffer;
501   llvm::raw_svector_ostream Out(Buffer);
502   Out << CapturedStmtInfo->getHelperName();
503   if (NeedWrapperFunction)
504     Out << "_debug__";
505   FunctionOptions FO(&S, !NeedWrapperFunction, /*RegisterCastedArgsOnly=*/false,
506                      Out.str());
507   llvm::Function *F = emitOutlinedFunctionPrologue(*this, Args, LocalAddrs,
508                                                    VLASizes, CXXThisValue, FO);
509   for (const auto &LocalAddrPair : LocalAddrs) {
510     if (LocalAddrPair.second.first) {
511       setAddrOfLocalVar(LocalAddrPair.second.first,
512                         LocalAddrPair.second.second);
513     }
514   }
515   for (const auto &VLASizePair : VLASizes)
516     VLASizeMap[VLASizePair.second.first] = VLASizePair.second.second;
517   PGO.assignRegionCounters(GlobalDecl(CD), F);
518   CapturedStmtInfo->EmitBody(*this, CD->getBody());
519   FinishFunction(CD->getBodyRBrace());
520   if (!NeedWrapperFunction)
521     return F;
522
523   FunctionOptions WrapperFO(&S, /*UIntPtrCastRequired=*/true,
524                             /*RegisterCastedArgsOnly=*/true,
525                             CapturedStmtInfo->getHelperName());
526   CodeGenFunction WrapperCGF(CGM, /*suppressNewContext=*/true);
527   Args.clear();
528   LocalAddrs.clear();
529   VLASizes.clear();
530   llvm::Function *WrapperF =
531       emitOutlinedFunctionPrologue(WrapperCGF, Args, LocalAddrs, VLASizes,
532                                    WrapperCGF.CXXThisValue, WrapperFO);
533   llvm::SmallVector<llvm::Value *, 4> CallArgs;
534   for (const auto *Arg : Args) {
535     llvm::Value *CallArg;
536     auto I = LocalAddrs.find(Arg);
537     if (I != LocalAddrs.end()) {
538       LValue LV = WrapperCGF.MakeAddrLValue(
539           I->second.second,
540           I->second.first ? I->second.first->getType() : Arg->getType(),
541           AlignmentSource::Decl);
542       CallArg = WrapperCGF.EmitLoadOfScalar(LV, SourceLocation());
543     } else {
544       auto EI = VLASizes.find(Arg);
545       if (EI != VLASizes.end())
546         CallArg = EI->second.second;
547       else {
548         LValue LV = WrapperCGF.MakeAddrLValue(WrapperCGF.GetAddrOfLocalVar(Arg),
549                                               Arg->getType(),
550                                               AlignmentSource::Decl);
551         CallArg = WrapperCGF.EmitLoadOfScalar(LV, SourceLocation());
552       }
553     }
554     CallArgs.emplace_back(WrapperCGF.EmitFromMemory(CallArg, Arg->getType()));
555   }
556   CGM.getOpenMPRuntime().emitOutlinedFunctionCall(WrapperCGF, S.getLocStart(),
557                                                   F, CallArgs);
558   WrapperCGF.FinishFunction();
559   return WrapperF;
560 }
561
562 //===----------------------------------------------------------------------===//
563 //                              OpenMP Directive Emission
564 //===----------------------------------------------------------------------===//
565 void CodeGenFunction::EmitOMPAggregateAssign(
566     Address DestAddr, Address SrcAddr, QualType OriginalType,
567     const llvm::function_ref<void(Address, Address)> &CopyGen) {
568   // Perform element-by-element initialization.
569   QualType ElementTy;
570
571   // Drill down to the base element type on both arrays.
572   auto ArrayTy = OriginalType->getAsArrayTypeUnsafe();
573   auto NumElements = emitArrayLength(ArrayTy, ElementTy, DestAddr);
574   SrcAddr = Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
575
576   auto SrcBegin = SrcAddr.getPointer();
577   auto DestBegin = DestAddr.getPointer();
578   // Cast from pointer to array type to pointer to single element.
579   auto DestEnd = Builder.CreateGEP(DestBegin, NumElements);
580   // The basic structure here is a while-do loop.
581   auto BodyBB = createBasicBlock("omp.arraycpy.body");
582   auto DoneBB = createBasicBlock("omp.arraycpy.done");
583   auto IsEmpty =
584       Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arraycpy.isempty");
585   Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
586
587   // Enter the loop body, making that address the current address.
588   auto EntryBB = Builder.GetInsertBlock();
589   EmitBlock(BodyBB);
590
591   CharUnits ElementSize = getContext().getTypeSizeInChars(ElementTy);
592
593   llvm::PHINode *SrcElementPHI =
594     Builder.CreatePHI(SrcBegin->getType(), 2, "omp.arraycpy.srcElementPast");
595   SrcElementPHI->addIncoming(SrcBegin, EntryBB);
596   Address SrcElementCurrent =
597       Address(SrcElementPHI,
598               SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
599
600   llvm::PHINode *DestElementPHI =
601     Builder.CreatePHI(DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
602   DestElementPHI->addIncoming(DestBegin, EntryBB);
603   Address DestElementCurrent =
604     Address(DestElementPHI,
605             DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
606
607   // Emit copy.
608   CopyGen(DestElementCurrent, SrcElementCurrent);
609
610   // Shift the address forward by one element.
611   auto DestElementNext = Builder.CreateConstGEP1_32(
612       DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
613   auto SrcElementNext = Builder.CreateConstGEP1_32(
614       SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
615   // Check whether we've reached the end.
616   auto Done =
617       Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
618   Builder.CreateCondBr(Done, DoneBB, BodyBB);
619   DestElementPHI->addIncoming(DestElementNext, Builder.GetInsertBlock());
620   SrcElementPHI->addIncoming(SrcElementNext, Builder.GetInsertBlock());
621
622   // Done.
623   EmitBlock(DoneBB, /*IsFinished=*/true);
624 }
625
626 void CodeGenFunction::EmitOMPCopy(QualType OriginalType, Address DestAddr,
627                                   Address SrcAddr, const VarDecl *DestVD,
628                                   const VarDecl *SrcVD, const Expr *Copy) {
629   if (OriginalType->isArrayType()) {
630     auto *BO = dyn_cast<BinaryOperator>(Copy);
631     if (BO && BO->getOpcode() == BO_Assign) {
632       // Perform simple memcpy for simple copying.
633       EmitAggregateAssign(DestAddr, SrcAddr, OriginalType);
634     } else {
635       // For arrays with complex element types perform element by element
636       // copying.
637       EmitOMPAggregateAssign(
638           DestAddr, SrcAddr, OriginalType,
639           [this, Copy, SrcVD, DestVD](Address DestElement, Address SrcElement) {
640             // Working with the single array element, so have to remap
641             // destination and source variables to corresponding array
642             // elements.
643             CodeGenFunction::OMPPrivateScope Remap(*this);
644             Remap.addPrivate(DestVD, [DestElement]() -> Address {
645               return DestElement;
646             });
647             Remap.addPrivate(
648                 SrcVD, [SrcElement]() -> Address { return SrcElement; });
649             (void)Remap.Privatize();
650             EmitIgnoredExpr(Copy);
651           });
652     }
653   } else {
654     // Remap pseudo source variable to private copy.
655     CodeGenFunction::OMPPrivateScope Remap(*this);
656     Remap.addPrivate(SrcVD, [SrcAddr]() -> Address { return SrcAddr; });
657     Remap.addPrivate(DestVD, [DestAddr]() -> Address { return DestAddr; });
658     (void)Remap.Privatize();
659     // Emit copying of the whole variable.
660     EmitIgnoredExpr(Copy);
661   }
662 }
663
664 bool CodeGenFunction::EmitOMPFirstprivateClause(const OMPExecutableDirective &D,
665                                                 OMPPrivateScope &PrivateScope) {
666   if (!HaveInsertPoint())
667     return false;
668   bool FirstprivateIsLastprivate = false;
669   llvm::DenseSet<const VarDecl *> Lastprivates;
670   for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
671     for (const auto *D : C->varlists())
672       Lastprivates.insert(
673           cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
674   }
675   llvm::DenseSet<const VarDecl *> EmittedAsFirstprivate;
676   CGCapturedStmtInfo CapturesInfo(cast<CapturedStmt>(*D.getAssociatedStmt()));
677   for (const auto *C : D.getClausesOfKind<OMPFirstprivateClause>()) {
678     auto IRef = C->varlist_begin();
679     auto InitsRef = C->inits().begin();
680     for (auto IInit : C->private_copies()) {
681       auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
682       bool ThisFirstprivateIsLastprivate =
683           Lastprivates.count(OrigVD->getCanonicalDecl()) > 0;
684       auto *CapFD = CapturesInfo.lookup(OrigVD);
685       auto *FD = CapturedStmtInfo->lookup(OrigVD);
686       if (!ThisFirstprivateIsLastprivate && FD && (FD == CapFD) &&
687           !FD->getType()->isReferenceType()) {
688         EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl());
689         ++IRef;
690         ++InitsRef;
691         continue;
692       }
693       FirstprivateIsLastprivate =
694           FirstprivateIsLastprivate || ThisFirstprivateIsLastprivate;
695       if (EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl()).second) {
696         auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
697         auto *VDInit = cast<VarDecl>(cast<DeclRefExpr>(*InitsRef)->getDecl());
698         bool IsRegistered;
699         DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
700                         /*RefersToEnclosingVariableOrCapture=*/FD != nullptr,
701                         (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
702         Address OriginalAddr = EmitLValue(&DRE).getAddress();
703         QualType Type = VD->getType();
704         if (Type->isArrayType()) {
705           // Emit VarDecl with copy init for arrays.
706           // Get the address of the original variable captured in current
707           // captured region.
708           IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
709             auto Emission = EmitAutoVarAlloca(*VD);
710             auto *Init = VD->getInit();
711             if (!isa<CXXConstructExpr>(Init) || isTrivialInitializer(Init)) {
712               // Perform simple memcpy.
713               EmitAggregateAssign(Emission.getAllocatedAddress(), OriginalAddr,
714                                   Type);
715             } else {
716               EmitOMPAggregateAssign(
717                   Emission.getAllocatedAddress(), OriginalAddr, Type,
718                   [this, VDInit, Init](Address DestElement,
719                                        Address SrcElement) {
720                     // Clean up any temporaries needed by the initialization.
721                     RunCleanupsScope InitScope(*this);
722                     // Emit initialization for single element.
723                     setAddrOfLocalVar(VDInit, SrcElement);
724                     EmitAnyExprToMem(Init, DestElement,
725                                      Init->getType().getQualifiers(),
726                                      /*IsInitializer*/ false);
727                     LocalDeclMap.erase(VDInit);
728                   });
729             }
730             EmitAutoVarCleanups(Emission);
731             return Emission.getAllocatedAddress();
732           });
733         } else {
734           IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
735             // Emit private VarDecl with copy init.
736             // Remap temp VDInit variable to the address of the original
737             // variable
738             // (for proper handling of captured global variables).
739             setAddrOfLocalVar(VDInit, OriginalAddr);
740             EmitDecl(*VD);
741             LocalDeclMap.erase(VDInit);
742             return GetAddrOfLocalVar(VD);
743           });
744         }
745         assert(IsRegistered &&
746                "firstprivate var already registered as private");
747         // Silence the warning about unused variable.
748         (void)IsRegistered;
749       }
750       ++IRef;
751       ++InitsRef;
752     }
753   }
754   return FirstprivateIsLastprivate && !EmittedAsFirstprivate.empty();
755 }
756
757 void CodeGenFunction::EmitOMPPrivateClause(
758     const OMPExecutableDirective &D,
759     CodeGenFunction::OMPPrivateScope &PrivateScope) {
760   if (!HaveInsertPoint())
761     return;
762   llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
763   for (const auto *C : D.getClausesOfKind<OMPPrivateClause>()) {
764     auto IRef = C->varlist_begin();
765     for (auto IInit : C->private_copies()) {
766       auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
767       if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
768         auto VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
769         bool IsRegistered =
770             PrivateScope.addPrivate(OrigVD, [&]() -> Address {
771               // Emit private VarDecl with copy init.
772               EmitDecl(*VD);
773               return GetAddrOfLocalVar(VD);
774             });
775         assert(IsRegistered && "private var already registered as private");
776         // Silence the warning about unused variable.
777         (void)IsRegistered;
778       }
779       ++IRef;
780     }
781   }
782 }
783
784 bool CodeGenFunction::EmitOMPCopyinClause(const OMPExecutableDirective &D) {
785   if (!HaveInsertPoint())
786     return false;
787   // threadprivate_var1 = master_threadprivate_var1;
788   // operator=(threadprivate_var2, master_threadprivate_var2);
789   // ...
790   // __kmpc_barrier(&loc, global_tid);
791   llvm::DenseSet<const VarDecl *> CopiedVars;
792   llvm::BasicBlock *CopyBegin = nullptr, *CopyEnd = nullptr;
793   for (const auto *C : D.getClausesOfKind<OMPCopyinClause>()) {
794     auto IRef = C->varlist_begin();
795     auto ISrcRef = C->source_exprs().begin();
796     auto IDestRef = C->destination_exprs().begin();
797     for (auto *AssignOp : C->assignment_ops()) {
798       auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
799       QualType Type = VD->getType();
800       if (CopiedVars.insert(VD->getCanonicalDecl()).second) {
801         // Get the address of the master variable. If we are emitting code with
802         // TLS support, the address is passed from the master as field in the
803         // captured declaration.
804         Address MasterAddr = Address::invalid();
805         if (getLangOpts().OpenMPUseTLS &&
806             getContext().getTargetInfo().isTLSSupported()) {
807           assert(CapturedStmtInfo->lookup(VD) &&
808                  "Copyin threadprivates should have been captured!");
809           DeclRefExpr DRE(const_cast<VarDecl *>(VD), true, (*IRef)->getType(),
810                           VK_LValue, (*IRef)->getExprLoc());
811           MasterAddr = EmitLValue(&DRE).getAddress();
812           LocalDeclMap.erase(VD);
813         } else {
814           MasterAddr =
815             Address(VD->isStaticLocal() ? CGM.getStaticLocalDeclAddress(VD)
816                                         : CGM.GetAddrOfGlobal(VD),
817                     getContext().getDeclAlign(VD));
818         }
819         // Get the address of the threadprivate variable.
820         Address PrivateAddr = EmitLValue(*IRef).getAddress();
821         if (CopiedVars.size() == 1) {
822           // At first check if current thread is a master thread. If it is, no
823           // need to copy data.
824           CopyBegin = createBasicBlock("copyin.not.master");
825           CopyEnd = createBasicBlock("copyin.not.master.end");
826           Builder.CreateCondBr(
827               Builder.CreateICmpNE(
828                   Builder.CreatePtrToInt(MasterAddr.getPointer(), CGM.IntPtrTy),
829                   Builder.CreatePtrToInt(PrivateAddr.getPointer(), CGM.IntPtrTy)),
830               CopyBegin, CopyEnd);
831           EmitBlock(CopyBegin);
832         }
833         auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
834         auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
835         EmitOMPCopy(Type, PrivateAddr, MasterAddr, DestVD, SrcVD, AssignOp);
836       }
837       ++IRef;
838       ++ISrcRef;
839       ++IDestRef;
840     }
841   }
842   if (CopyEnd) {
843     // Exit out of copying procedure for non-master thread.
844     EmitBlock(CopyEnd, /*IsFinished=*/true);
845     return true;
846   }
847   return false;
848 }
849
850 bool CodeGenFunction::EmitOMPLastprivateClauseInit(
851     const OMPExecutableDirective &D, OMPPrivateScope &PrivateScope) {
852   if (!HaveInsertPoint())
853     return false;
854   bool HasAtLeastOneLastprivate = false;
855   llvm::DenseSet<const VarDecl *> SIMDLCVs;
856   if (isOpenMPSimdDirective(D.getDirectiveKind())) {
857     auto *LoopDirective = cast<OMPLoopDirective>(&D);
858     for (auto *C : LoopDirective->counters()) {
859       SIMDLCVs.insert(
860           cast<VarDecl>(cast<DeclRefExpr>(C)->getDecl())->getCanonicalDecl());
861     }
862   }
863   llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
864   for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
865     HasAtLeastOneLastprivate = true;
866     if (isOpenMPTaskLoopDirective(D.getDirectiveKind()))
867       break;
868     auto IRef = C->varlist_begin();
869     auto IDestRef = C->destination_exprs().begin();
870     for (auto *IInit : C->private_copies()) {
871       // Keep the address of the original variable for future update at the end
872       // of the loop.
873       auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
874       // Taskloops do not require additional initialization, it is done in
875       // runtime support library.
876       if (AlreadyEmittedVars.insert(OrigVD->getCanonicalDecl()).second) {
877         auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
878         PrivateScope.addPrivate(DestVD, [this, OrigVD, IRef]() -> Address {
879           DeclRefExpr DRE(
880               const_cast<VarDecl *>(OrigVD),
881               /*RefersToEnclosingVariableOrCapture=*/CapturedStmtInfo->lookup(
882                   OrigVD) != nullptr,
883               (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
884           return EmitLValue(&DRE).getAddress();
885         });
886         // Check if the variable is also a firstprivate: in this case IInit is
887         // not generated. Initialization of this variable will happen in codegen
888         // for 'firstprivate' clause.
889         if (IInit && !SIMDLCVs.count(OrigVD->getCanonicalDecl())) {
890           auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
891           bool IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
892             // Emit private VarDecl with copy init.
893             EmitDecl(*VD);
894             return GetAddrOfLocalVar(VD);
895           });
896           assert(IsRegistered &&
897                  "lastprivate var already registered as private");
898           (void)IsRegistered;
899         }
900       }
901       ++IRef;
902       ++IDestRef;
903     }
904   }
905   return HasAtLeastOneLastprivate;
906 }
907
908 void CodeGenFunction::EmitOMPLastprivateClauseFinal(
909     const OMPExecutableDirective &D, bool NoFinals,
910     llvm::Value *IsLastIterCond) {
911   if (!HaveInsertPoint())
912     return;
913   // Emit following code:
914   // if (<IsLastIterCond>) {
915   //   orig_var1 = private_orig_var1;
916   //   ...
917   //   orig_varn = private_orig_varn;
918   // }
919   llvm::BasicBlock *ThenBB = nullptr;
920   llvm::BasicBlock *DoneBB = nullptr;
921   if (IsLastIterCond) {
922     ThenBB = createBasicBlock(".omp.lastprivate.then");
923     DoneBB = createBasicBlock(".omp.lastprivate.done");
924     Builder.CreateCondBr(IsLastIterCond, ThenBB, DoneBB);
925     EmitBlock(ThenBB);
926   }
927   llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
928   llvm::DenseMap<const VarDecl *, const Expr *> LoopCountersAndUpdates;
929   if (auto *LoopDirective = dyn_cast<OMPLoopDirective>(&D)) {
930     auto IC = LoopDirective->counters().begin();
931     for (auto F : LoopDirective->finals()) {
932       auto *D =
933           cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl())->getCanonicalDecl();
934       if (NoFinals)
935         AlreadyEmittedVars.insert(D);
936       else
937         LoopCountersAndUpdates[D] = F;
938       ++IC;
939     }
940   }
941   for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
942     auto IRef = C->varlist_begin();
943     auto ISrcRef = C->source_exprs().begin();
944     auto IDestRef = C->destination_exprs().begin();
945     for (auto *AssignOp : C->assignment_ops()) {
946       auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
947       QualType Type = PrivateVD->getType();
948       auto *CanonicalVD = PrivateVD->getCanonicalDecl();
949       if (AlreadyEmittedVars.insert(CanonicalVD).second) {
950         // If lastprivate variable is a loop control variable for loop-based
951         // directive, update its value before copyin back to original
952         // variable.
953         if (auto *FinalExpr = LoopCountersAndUpdates.lookup(CanonicalVD))
954           EmitIgnoredExpr(FinalExpr);
955         auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
956         auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
957         // Get the address of the original variable.
958         Address OriginalAddr = GetAddrOfLocalVar(DestVD);
959         // Get the address of the private variable.
960         Address PrivateAddr = GetAddrOfLocalVar(PrivateVD);
961         if (auto RefTy = PrivateVD->getType()->getAs<ReferenceType>())
962           PrivateAddr =
963               Address(Builder.CreateLoad(PrivateAddr),
964                       getNaturalTypeAlignment(RefTy->getPointeeType()));
965         EmitOMPCopy(Type, OriginalAddr, PrivateAddr, DestVD, SrcVD, AssignOp);
966       }
967       ++IRef;
968       ++ISrcRef;
969       ++IDestRef;
970     }
971     if (auto *PostUpdate = C->getPostUpdateExpr())
972       EmitIgnoredExpr(PostUpdate);
973   }
974   if (IsLastIterCond)
975     EmitBlock(DoneBB, /*IsFinished=*/true);
976 }
977
978 void CodeGenFunction::EmitOMPReductionClauseInit(
979     const OMPExecutableDirective &D,
980     CodeGenFunction::OMPPrivateScope &PrivateScope) {
981   if (!HaveInsertPoint())
982     return;
983   SmallVector<const Expr *, 4> Shareds;
984   SmallVector<const Expr *, 4> Privates;
985   SmallVector<const Expr *, 4> ReductionOps;
986   SmallVector<const Expr *, 4> LHSs;
987   SmallVector<const Expr *, 4> RHSs;
988   for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
989     auto IPriv = C->privates().begin();
990     auto IRed = C->reduction_ops().begin();
991     auto ILHS = C->lhs_exprs().begin();
992     auto IRHS = C->rhs_exprs().begin();
993     for (const auto *Ref : C->varlists()) {
994       Shareds.emplace_back(Ref);
995       Privates.emplace_back(*IPriv);
996       ReductionOps.emplace_back(*IRed);
997       LHSs.emplace_back(*ILHS);
998       RHSs.emplace_back(*IRHS);
999       std::advance(IPriv, 1);
1000       std::advance(IRed, 1);
1001       std::advance(ILHS, 1);
1002       std::advance(IRHS, 1);
1003     }
1004   }
1005   ReductionCodeGen RedCG(Shareds, Privates, ReductionOps);
1006   unsigned Count = 0;
1007   auto ILHS = LHSs.begin();
1008   auto IRHS = RHSs.begin();
1009   auto IPriv = Privates.begin();
1010   for (const auto *IRef : Shareds) {
1011     auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IPriv)->getDecl());
1012     // Emit private VarDecl with reduction init.
1013     RedCG.emitSharedLValue(*this, Count);
1014     RedCG.emitAggregateType(*this, Count);
1015     auto Emission = EmitAutoVarAlloca(*PrivateVD);
1016     RedCG.emitInitialization(*this, Count, Emission.getAllocatedAddress(),
1017                              RedCG.getSharedLValue(Count),
1018                              [&Emission](CodeGenFunction &CGF) {
1019                                CGF.EmitAutoVarInit(Emission);
1020                                return true;
1021                              });
1022     EmitAutoVarCleanups(Emission);
1023     Address BaseAddr = RedCG.adjustPrivateAddress(
1024         *this, Count, Emission.getAllocatedAddress());
1025     bool IsRegistered = PrivateScope.addPrivate(
1026         RedCG.getBaseDecl(Count), [BaseAddr]() -> Address { return BaseAddr; });
1027     assert(IsRegistered && "private var already registered as private");
1028     // Silence the warning about unused variable.
1029     (void)IsRegistered;
1030
1031     auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
1032     auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
1033     QualType Type = PrivateVD->getType();
1034     bool isaOMPArraySectionExpr = isa<OMPArraySectionExpr>(IRef);
1035     if (isaOMPArraySectionExpr && Type->isVariablyModifiedType()) {
1036       // Store the address of the original variable associated with the LHS
1037       // implicit variable.
1038       PrivateScope.addPrivate(LHSVD, [&RedCG, Count]() -> Address {
1039         return RedCG.getSharedLValue(Count).getAddress();
1040       });
1041       PrivateScope.addPrivate(RHSVD, [this, PrivateVD]() -> Address {
1042         return GetAddrOfLocalVar(PrivateVD);
1043       });
1044     } else if ((isaOMPArraySectionExpr && Type->isScalarType()) ||
1045                isa<ArraySubscriptExpr>(IRef)) {
1046       // Store the address of the original variable associated with the LHS
1047       // implicit variable.
1048       PrivateScope.addPrivate(LHSVD, [&RedCG, Count]() -> Address {
1049         return RedCG.getSharedLValue(Count).getAddress();
1050       });
1051       PrivateScope.addPrivate(RHSVD, [this, PrivateVD, RHSVD]() -> Address {
1052         return Builder.CreateElementBitCast(GetAddrOfLocalVar(PrivateVD),
1053                                             ConvertTypeForMem(RHSVD->getType()),
1054                                             "rhs.begin");
1055       });
1056     } else {
1057       QualType Type = PrivateVD->getType();
1058       bool IsArray = getContext().getAsArrayType(Type) != nullptr;
1059       Address OriginalAddr = RedCG.getSharedLValue(Count).getAddress();
1060       // Store the address of the original variable associated with the LHS
1061       // implicit variable.
1062       if (IsArray) {
1063         OriginalAddr = Builder.CreateElementBitCast(
1064             OriginalAddr, ConvertTypeForMem(LHSVD->getType()), "lhs.begin");
1065       }
1066       PrivateScope.addPrivate(
1067           LHSVD, [OriginalAddr]() -> Address { return OriginalAddr; });
1068       PrivateScope.addPrivate(
1069           RHSVD, [this, PrivateVD, RHSVD, IsArray]() -> Address {
1070             return IsArray
1071                        ? Builder.CreateElementBitCast(
1072                              GetAddrOfLocalVar(PrivateVD),
1073                              ConvertTypeForMem(RHSVD->getType()), "rhs.begin")
1074                        : GetAddrOfLocalVar(PrivateVD);
1075           });
1076     }
1077     ++ILHS;
1078     ++IRHS;
1079     ++IPriv;
1080     ++Count;
1081   }
1082 }
1083
1084 void CodeGenFunction::EmitOMPReductionClauseFinal(
1085     const OMPExecutableDirective &D, const OpenMPDirectiveKind ReductionKind) {
1086   if (!HaveInsertPoint())
1087     return;
1088   llvm::SmallVector<const Expr *, 8> Privates;
1089   llvm::SmallVector<const Expr *, 8> LHSExprs;
1090   llvm::SmallVector<const Expr *, 8> RHSExprs;
1091   llvm::SmallVector<const Expr *, 8> ReductionOps;
1092   bool HasAtLeastOneReduction = false;
1093   for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
1094     HasAtLeastOneReduction = true;
1095     Privates.append(C->privates().begin(), C->privates().end());
1096     LHSExprs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
1097     RHSExprs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
1098     ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end());
1099   }
1100   if (HasAtLeastOneReduction) {
1101     bool WithNowait = D.getSingleClause<OMPNowaitClause>() ||
1102                       isOpenMPParallelDirective(D.getDirectiveKind()) ||
1103                       D.getDirectiveKind() == OMPD_simd;
1104     bool SimpleReduction = D.getDirectiveKind() == OMPD_simd ||
1105                            D.getDirectiveKind() == OMPD_distribute_simd;
1106     // Emit nowait reduction if nowait clause is present or directive is a
1107     // parallel directive (it always has implicit barrier).
1108     CGM.getOpenMPRuntime().emitReduction(
1109         *this, D.getLocEnd(), Privates, LHSExprs, RHSExprs, ReductionOps,
1110         {WithNowait, SimpleReduction, ReductionKind});
1111   }
1112 }
1113
1114 static void emitPostUpdateForReductionClause(
1115     CodeGenFunction &CGF, const OMPExecutableDirective &D,
1116     const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
1117   if (!CGF.HaveInsertPoint())
1118     return;
1119   llvm::BasicBlock *DoneBB = nullptr;
1120   for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
1121     if (auto *PostUpdate = C->getPostUpdateExpr()) {
1122       if (!DoneBB) {
1123         if (auto *Cond = CondGen(CGF)) {
1124           // If the first post-update expression is found, emit conditional
1125           // block if it was requested.
1126           auto *ThenBB = CGF.createBasicBlock(".omp.reduction.pu");
1127           DoneBB = CGF.createBasicBlock(".omp.reduction.pu.done");
1128           CGF.Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1129           CGF.EmitBlock(ThenBB);
1130         }
1131       }
1132       CGF.EmitIgnoredExpr(PostUpdate);
1133     }
1134   }
1135   if (DoneBB)
1136     CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
1137 }
1138
1139 namespace {
1140 /// Codegen lambda for appending distribute lower and upper bounds to outlined
1141 /// parallel function. This is necessary for combined constructs such as
1142 /// 'distribute parallel for'
1143 typedef llvm::function_ref<void(CodeGenFunction &,
1144                                 const OMPExecutableDirective &,
1145                                 llvm::SmallVectorImpl<llvm::Value *> &)>
1146     CodeGenBoundParametersTy;
1147 } // anonymous namespace
1148
1149 static void emitCommonOMPParallelDirective(
1150     CodeGenFunction &CGF, const OMPExecutableDirective &S,
1151     OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
1152     const CodeGenBoundParametersTy &CodeGenBoundParameters) {
1153   const CapturedStmt *CS = S.getCapturedStmt(OMPD_parallel);
1154   auto OutlinedFn = CGF.CGM.getOpenMPRuntime().emitParallelOutlinedFunction(
1155       S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
1156   if (const auto *NumThreadsClause = S.getSingleClause<OMPNumThreadsClause>()) {
1157     CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
1158     auto NumThreads = CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
1159                                          /*IgnoreResultAssign*/ true);
1160     CGF.CGM.getOpenMPRuntime().emitNumThreadsClause(
1161         CGF, NumThreads, NumThreadsClause->getLocStart());
1162   }
1163   if (const auto *ProcBindClause = S.getSingleClause<OMPProcBindClause>()) {
1164     CodeGenFunction::RunCleanupsScope ProcBindScope(CGF);
1165     CGF.CGM.getOpenMPRuntime().emitProcBindClause(
1166         CGF, ProcBindClause->getProcBindKind(), ProcBindClause->getLocStart());
1167   }
1168   const Expr *IfCond = nullptr;
1169   for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
1170     if (C->getNameModifier() == OMPD_unknown ||
1171         C->getNameModifier() == OMPD_parallel) {
1172       IfCond = C->getCondition();
1173       break;
1174     }
1175   }
1176
1177   OMPParallelScope Scope(CGF, S);
1178   llvm::SmallVector<llvm::Value *, 16> CapturedVars;
1179   // Combining 'distribute' with 'for' requires sharing each 'distribute' chunk
1180   // lower and upper bounds with the pragma 'for' chunking mechanism.
1181   // The following lambda takes care of appending the lower and upper bound
1182   // parameters when necessary
1183   CodeGenBoundParameters(CGF, S, CapturedVars);
1184   CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
1185   CGF.CGM.getOpenMPRuntime().emitParallelCall(CGF, S.getLocStart(), OutlinedFn,
1186                                               CapturedVars, IfCond);
1187 }
1188
1189 static void emitEmptyBoundParameters(CodeGenFunction &,
1190                                      const OMPExecutableDirective &,
1191                                      llvm::SmallVectorImpl<llvm::Value *> &) {}
1192
1193 void CodeGenFunction::EmitOMPParallelDirective(const OMPParallelDirective &S) {
1194   // Emit parallel region as a standalone region.
1195   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
1196     OMPPrivateScope PrivateScope(CGF);
1197     bool Copyins = CGF.EmitOMPCopyinClause(S);
1198     (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
1199     if (Copyins) {
1200       // Emit implicit barrier to synchronize threads and avoid data races on
1201       // propagation master's thread values of threadprivate variables to local
1202       // instances of that variables of all other implicit threads.
1203       CGF.CGM.getOpenMPRuntime().emitBarrierCall(
1204           CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
1205           /*ForceSimpleCall=*/true);
1206     }
1207     CGF.EmitOMPPrivateClause(S, PrivateScope);
1208     CGF.EmitOMPReductionClauseInit(S, PrivateScope);
1209     (void)PrivateScope.Privatize();
1210     CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1211     CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
1212   };
1213   emitCommonOMPParallelDirective(*this, S, OMPD_parallel, CodeGen,
1214                                  emitEmptyBoundParameters);
1215   emitPostUpdateForReductionClause(
1216       *this, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
1217 }
1218
1219 void CodeGenFunction::EmitOMPLoopBody(const OMPLoopDirective &D,
1220                                       JumpDest LoopExit) {
1221   RunCleanupsScope BodyScope(*this);
1222   // Update counters values on current iteration.
1223   for (auto I : D.updates()) {
1224     EmitIgnoredExpr(I);
1225   }
1226   // Update the linear variables.
1227   // In distribute directives only loop counters may be marked as linear, no
1228   // need to generate the code for them.
1229   if (!isOpenMPDistributeDirective(D.getDirectiveKind())) {
1230     for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
1231       for (auto *U : C->updates())
1232         EmitIgnoredExpr(U);
1233     }
1234   }
1235
1236   // On a continue in the body, jump to the end.
1237   auto Continue = getJumpDestInCurrentScope("omp.body.continue");
1238   BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1239   // Emit loop body.
1240   EmitStmt(D.getBody());
1241   // The end (updates/cleanups).
1242   EmitBlock(Continue.getBlock());
1243   BreakContinueStack.pop_back();
1244 }
1245
1246 void CodeGenFunction::EmitOMPInnerLoop(
1247     const Stmt &S, bool RequiresCleanup, const Expr *LoopCond,
1248     const Expr *IncExpr,
1249     const llvm::function_ref<void(CodeGenFunction &)> &BodyGen,
1250     const llvm::function_ref<void(CodeGenFunction &)> &PostIncGen) {
1251   auto LoopExit = getJumpDestInCurrentScope("omp.inner.for.end");
1252
1253   // Start the loop with a block that tests the condition.
1254   auto CondBlock = createBasicBlock("omp.inner.for.cond");
1255   EmitBlock(CondBlock);
1256   const SourceRange &R = S.getSourceRange();
1257   LoopStack.push(CondBlock, SourceLocToDebugLoc(R.getBegin()),
1258                  SourceLocToDebugLoc(R.getEnd()));
1259
1260   // If there are any cleanups between here and the loop-exit scope,
1261   // create a block to stage a loop exit along.
1262   auto ExitBlock = LoopExit.getBlock();
1263   if (RequiresCleanup)
1264     ExitBlock = createBasicBlock("omp.inner.for.cond.cleanup");
1265
1266   auto LoopBody = createBasicBlock("omp.inner.for.body");
1267
1268   // Emit condition.
1269   EmitBranchOnBoolExpr(LoopCond, LoopBody, ExitBlock, getProfileCount(&S));
1270   if (ExitBlock != LoopExit.getBlock()) {
1271     EmitBlock(ExitBlock);
1272     EmitBranchThroughCleanup(LoopExit);
1273   }
1274
1275   EmitBlock(LoopBody);
1276   incrementProfileCounter(&S);
1277
1278   // Create a block for the increment.
1279   auto Continue = getJumpDestInCurrentScope("omp.inner.for.inc");
1280   BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1281
1282   BodyGen(*this);
1283
1284   // Emit "IV = IV + 1" and a back-edge to the condition block.
1285   EmitBlock(Continue.getBlock());
1286   EmitIgnoredExpr(IncExpr);
1287   PostIncGen(*this);
1288   BreakContinueStack.pop_back();
1289   EmitBranch(CondBlock);
1290   LoopStack.pop();
1291   // Emit the fall-through block.
1292   EmitBlock(LoopExit.getBlock());
1293 }
1294
1295 bool CodeGenFunction::EmitOMPLinearClauseInit(const OMPLoopDirective &D) {
1296   if (!HaveInsertPoint())
1297     return false;
1298   // Emit inits for the linear variables.
1299   bool HasLinears = false;
1300   for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
1301     for (auto *Init : C->inits()) {
1302       HasLinears = true;
1303       auto *VD = cast<VarDecl>(cast<DeclRefExpr>(Init)->getDecl());
1304       if (auto *Ref = dyn_cast<DeclRefExpr>(VD->getInit()->IgnoreImpCasts())) {
1305         AutoVarEmission Emission = EmitAutoVarAlloca(*VD);
1306         auto *OrigVD = cast<VarDecl>(Ref->getDecl());
1307         DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
1308                         CapturedStmtInfo->lookup(OrigVD) != nullptr,
1309                         VD->getInit()->getType(), VK_LValue,
1310                         VD->getInit()->getExprLoc());
1311         EmitExprAsInit(&DRE, VD, MakeAddrLValue(Emission.getAllocatedAddress(),
1312                                                 VD->getType()),
1313                        /*capturedByInit=*/false);
1314         EmitAutoVarCleanups(Emission);
1315       } else
1316         EmitVarDecl(*VD);
1317     }
1318     // Emit the linear steps for the linear clauses.
1319     // If a step is not constant, it is pre-calculated before the loop.
1320     if (auto CS = cast_or_null<BinaryOperator>(C->getCalcStep()))
1321       if (auto SaveRef = cast<DeclRefExpr>(CS->getLHS())) {
1322         EmitVarDecl(*cast<VarDecl>(SaveRef->getDecl()));
1323         // Emit calculation of the linear step.
1324         EmitIgnoredExpr(CS);
1325       }
1326   }
1327   return HasLinears;
1328 }
1329
1330 void CodeGenFunction::EmitOMPLinearClauseFinal(
1331     const OMPLoopDirective &D,
1332     const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
1333   if (!HaveInsertPoint())
1334     return;
1335   llvm::BasicBlock *DoneBB = nullptr;
1336   // Emit the final values of the linear variables.
1337   for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
1338     auto IC = C->varlist_begin();
1339     for (auto *F : C->finals()) {
1340       if (!DoneBB) {
1341         if (auto *Cond = CondGen(*this)) {
1342           // If the first post-update expression is found, emit conditional
1343           // block if it was requested.
1344           auto *ThenBB = createBasicBlock(".omp.linear.pu");
1345           DoneBB = createBasicBlock(".omp.linear.pu.done");
1346           Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1347           EmitBlock(ThenBB);
1348         }
1349       }
1350       auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl());
1351       DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
1352                       CapturedStmtInfo->lookup(OrigVD) != nullptr,
1353                       (*IC)->getType(), VK_LValue, (*IC)->getExprLoc());
1354       Address OrigAddr = EmitLValue(&DRE).getAddress();
1355       CodeGenFunction::OMPPrivateScope VarScope(*this);
1356       VarScope.addPrivate(OrigVD, [OrigAddr]() -> Address { return OrigAddr; });
1357       (void)VarScope.Privatize();
1358       EmitIgnoredExpr(F);
1359       ++IC;
1360     }
1361     if (auto *PostUpdate = C->getPostUpdateExpr())
1362       EmitIgnoredExpr(PostUpdate);
1363   }
1364   if (DoneBB)
1365     EmitBlock(DoneBB, /*IsFinished=*/true);
1366 }
1367
1368 static void emitAlignedClause(CodeGenFunction &CGF,
1369                               const OMPExecutableDirective &D) {
1370   if (!CGF.HaveInsertPoint())
1371     return;
1372   for (const auto *Clause : D.getClausesOfKind<OMPAlignedClause>()) {
1373     unsigned ClauseAlignment = 0;
1374     if (auto AlignmentExpr = Clause->getAlignment()) {
1375       auto AlignmentCI =
1376           cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AlignmentExpr));
1377       ClauseAlignment = static_cast<unsigned>(AlignmentCI->getZExtValue());
1378     }
1379     for (auto E : Clause->varlists()) {
1380       unsigned Alignment = ClauseAlignment;
1381       if (Alignment == 0) {
1382         // OpenMP [2.8.1, Description]
1383         // If no optional parameter is specified, implementation-defined default
1384         // alignments for SIMD instructions on the target platforms are assumed.
1385         Alignment =
1386             CGF.getContext()
1387                 .toCharUnitsFromBits(CGF.getContext().getOpenMPDefaultSimdAlign(
1388                     E->getType()->getPointeeType()))
1389                 .getQuantity();
1390       }
1391       assert((Alignment == 0 || llvm::isPowerOf2_32(Alignment)) &&
1392              "alignment is not power of 2");
1393       if (Alignment != 0) {
1394         llvm::Value *PtrValue = CGF.EmitScalarExpr(E);
1395         CGF.EmitAlignmentAssumption(PtrValue, Alignment);
1396       }
1397     }
1398   }
1399 }
1400
1401 void CodeGenFunction::EmitOMPPrivateLoopCounters(
1402     const OMPLoopDirective &S, CodeGenFunction::OMPPrivateScope &LoopScope) {
1403   if (!HaveInsertPoint())
1404     return;
1405   auto I = S.private_counters().begin();
1406   for (auto *E : S.counters()) {
1407     auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1408     auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl());
1409     (void)LoopScope.addPrivate(VD, [&]() -> Address {
1410       // Emit var without initialization.
1411       if (!LocalDeclMap.count(PrivateVD)) {
1412         auto VarEmission = EmitAutoVarAlloca(*PrivateVD);
1413         EmitAutoVarCleanups(VarEmission);
1414       }
1415       DeclRefExpr DRE(const_cast<VarDecl *>(PrivateVD),
1416                       /*RefersToEnclosingVariableOrCapture=*/false,
1417                       (*I)->getType(), VK_LValue, (*I)->getExprLoc());
1418       return EmitLValue(&DRE).getAddress();
1419     });
1420     if (LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD) ||
1421         VD->hasGlobalStorage()) {
1422       (void)LoopScope.addPrivate(PrivateVD, [&]() -> Address {
1423         DeclRefExpr DRE(const_cast<VarDecl *>(VD),
1424                         LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD),
1425                         E->getType(), VK_LValue, E->getExprLoc());
1426         return EmitLValue(&DRE).getAddress();
1427       });
1428     }
1429     ++I;
1430   }
1431 }
1432
1433 static void emitPreCond(CodeGenFunction &CGF, const OMPLoopDirective &S,
1434                         const Expr *Cond, llvm::BasicBlock *TrueBlock,
1435                         llvm::BasicBlock *FalseBlock, uint64_t TrueCount) {
1436   if (!CGF.HaveInsertPoint())
1437     return;
1438   {
1439     CodeGenFunction::OMPPrivateScope PreCondScope(CGF);
1440     CGF.EmitOMPPrivateLoopCounters(S, PreCondScope);
1441     (void)PreCondScope.Privatize();
1442     // Get initial values of real counters.
1443     for (auto I : S.inits()) {
1444       CGF.EmitIgnoredExpr(I);
1445     }
1446   }
1447   // Check that loop is executed at least one time.
1448   CGF.EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount);
1449 }
1450
1451 void CodeGenFunction::EmitOMPLinearClause(
1452     const OMPLoopDirective &D, CodeGenFunction::OMPPrivateScope &PrivateScope) {
1453   if (!HaveInsertPoint())
1454     return;
1455   llvm::DenseSet<const VarDecl *> SIMDLCVs;
1456   if (isOpenMPSimdDirective(D.getDirectiveKind())) {
1457     auto *LoopDirective = cast<OMPLoopDirective>(&D);
1458     for (auto *C : LoopDirective->counters()) {
1459       SIMDLCVs.insert(
1460           cast<VarDecl>(cast<DeclRefExpr>(C)->getDecl())->getCanonicalDecl());
1461     }
1462   }
1463   for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
1464     auto CurPrivate = C->privates().begin();
1465     for (auto *E : C->varlists()) {
1466       auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1467       auto *PrivateVD =
1468           cast<VarDecl>(cast<DeclRefExpr>(*CurPrivate)->getDecl());
1469       if (!SIMDLCVs.count(VD->getCanonicalDecl())) {
1470         bool IsRegistered = PrivateScope.addPrivate(VD, [&]() -> Address {
1471           // Emit private VarDecl with copy init.
1472           EmitVarDecl(*PrivateVD);
1473           return GetAddrOfLocalVar(PrivateVD);
1474         });
1475         assert(IsRegistered && "linear var already registered as private");
1476         // Silence the warning about unused variable.
1477         (void)IsRegistered;
1478       } else
1479         EmitVarDecl(*PrivateVD);
1480       ++CurPrivate;
1481     }
1482   }
1483 }
1484
1485 static void emitSimdlenSafelenClause(CodeGenFunction &CGF,
1486                                      const OMPExecutableDirective &D,
1487                                      bool IsMonotonic) {
1488   if (!CGF.HaveInsertPoint())
1489     return;
1490   if (const auto *C = D.getSingleClause<OMPSimdlenClause>()) {
1491     RValue Len = CGF.EmitAnyExpr(C->getSimdlen(), AggValueSlot::ignored(),
1492                                  /*ignoreResult=*/true);
1493     llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
1494     CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
1495     // In presence of finite 'safelen', it may be unsafe to mark all
1496     // the memory instructions parallel, because loop-carried
1497     // dependences of 'safelen' iterations are possible.
1498     if (!IsMonotonic)
1499       CGF.LoopStack.setParallel(!D.getSingleClause<OMPSafelenClause>());
1500   } else if (const auto *C = D.getSingleClause<OMPSafelenClause>()) {
1501     RValue Len = CGF.EmitAnyExpr(C->getSafelen(), AggValueSlot::ignored(),
1502                                  /*ignoreResult=*/true);
1503     llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
1504     CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
1505     // In presence of finite 'safelen', it may be unsafe to mark all
1506     // the memory instructions parallel, because loop-carried
1507     // dependences of 'safelen' iterations are possible.
1508     CGF.LoopStack.setParallel(false);
1509   }
1510 }
1511
1512 void CodeGenFunction::EmitOMPSimdInit(const OMPLoopDirective &D,
1513                                       bool IsMonotonic) {
1514   // Walk clauses and process safelen/lastprivate.
1515   LoopStack.setParallel(!IsMonotonic);
1516   LoopStack.setVectorizeEnable(true);
1517   emitSimdlenSafelenClause(*this, D, IsMonotonic);
1518 }
1519
1520 void CodeGenFunction::EmitOMPSimdFinal(
1521     const OMPLoopDirective &D,
1522     const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
1523   if (!HaveInsertPoint())
1524     return;
1525   llvm::BasicBlock *DoneBB = nullptr;
1526   auto IC = D.counters().begin();
1527   auto IPC = D.private_counters().begin();
1528   for (auto F : D.finals()) {
1529     auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>((*IC))->getDecl());
1530     auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>((*IPC))->getDecl());
1531     auto *CED = dyn_cast<OMPCapturedExprDecl>(OrigVD);
1532     if (LocalDeclMap.count(OrigVD) || CapturedStmtInfo->lookup(OrigVD) ||
1533         OrigVD->hasGlobalStorage() || CED) {
1534       if (!DoneBB) {
1535         if (auto *Cond = CondGen(*this)) {
1536           // If the first post-update expression is found, emit conditional
1537           // block if it was requested.
1538           auto *ThenBB = createBasicBlock(".omp.final.then");
1539           DoneBB = createBasicBlock(".omp.final.done");
1540           Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1541           EmitBlock(ThenBB);
1542         }
1543       }
1544       Address OrigAddr = Address::invalid();
1545       if (CED)
1546         OrigAddr = EmitLValue(CED->getInit()->IgnoreImpCasts()).getAddress();
1547       else {
1548         DeclRefExpr DRE(const_cast<VarDecl *>(PrivateVD),
1549                         /*RefersToEnclosingVariableOrCapture=*/false,
1550                         (*IPC)->getType(), VK_LValue, (*IPC)->getExprLoc());
1551         OrigAddr = EmitLValue(&DRE).getAddress();
1552       }
1553       OMPPrivateScope VarScope(*this);
1554       VarScope.addPrivate(OrigVD,
1555                           [OrigAddr]() -> Address { return OrigAddr; });
1556       (void)VarScope.Privatize();
1557       EmitIgnoredExpr(F);
1558     }
1559     ++IC;
1560     ++IPC;
1561   }
1562   if (DoneBB)
1563     EmitBlock(DoneBB, /*IsFinished=*/true);
1564 }
1565
1566 static void emitOMPLoopBodyWithStopPoint(CodeGenFunction &CGF,
1567                                          const OMPLoopDirective &S,
1568                                          CodeGenFunction::JumpDest LoopExit) {
1569   CGF.EmitOMPLoopBody(S, LoopExit);
1570   CGF.EmitStopPoint(&S);
1571 }
1572
1573 static void emitOMPSimdRegion(CodeGenFunction &CGF, const OMPLoopDirective &S,
1574                               PrePostActionTy &Action) {
1575   Action.Enter(CGF);
1576   assert(isOpenMPSimdDirective(S.getDirectiveKind()) &&
1577          "Expected simd directive");
1578   OMPLoopScope PreInitScope(CGF, S);
1579   // if (PreCond) {
1580   //   for (IV in 0..LastIteration) BODY;
1581   //   <Final counter/linear vars updates>;
1582   // }
1583   //
1584
1585   // Emit: if (PreCond) - begin.
1586   // If the condition constant folds and can be elided, avoid emitting the
1587   // whole loop.
1588   bool CondConstant;
1589   llvm::BasicBlock *ContBlock = nullptr;
1590   if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
1591     if (!CondConstant)
1592       return;
1593   } else {
1594     auto *ThenBlock = CGF.createBasicBlock("simd.if.then");
1595     ContBlock = CGF.createBasicBlock("simd.if.end");
1596     emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
1597                 CGF.getProfileCount(&S));
1598     CGF.EmitBlock(ThenBlock);
1599     CGF.incrementProfileCounter(&S);
1600   }
1601
1602   // Emit the loop iteration variable.
1603   const Expr *IVExpr = S.getIterationVariable();
1604   const VarDecl *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
1605   CGF.EmitVarDecl(*IVDecl);
1606   CGF.EmitIgnoredExpr(S.getInit());
1607
1608   // Emit the iterations count variable.
1609   // If it is not a variable, Sema decided to calculate iterations count on
1610   // each iteration (e.g., it is foldable into a constant).
1611   if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
1612     CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
1613     // Emit calculation of the iterations count.
1614     CGF.EmitIgnoredExpr(S.getCalcLastIteration());
1615   }
1616
1617   CGF.EmitOMPSimdInit(S);
1618
1619   emitAlignedClause(CGF, S);
1620   (void)CGF.EmitOMPLinearClauseInit(S);
1621   {
1622     CodeGenFunction::OMPPrivateScope LoopScope(CGF);
1623     CGF.EmitOMPPrivateLoopCounters(S, LoopScope);
1624     CGF.EmitOMPLinearClause(S, LoopScope);
1625     CGF.EmitOMPPrivateClause(S, LoopScope);
1626     CGF.EmitOMPReductionClauseInit(S, LoopScope);
1627     bool HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
1628     (void)LoopScope.Privatize();
1629     CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
1630                          S.getInc(),
1631                          [&S](CodeGenFunction &CGF) {
1632                            CGF.EmitOMPLoopBody(S, CodeGenFunction::JumpDest());
1633                            CGF.EmitStopPoint(&S);
1634                          },
1635                          [](CodeGenFunction &) {});
1636     CGF.EmitOMPSimdFinal(
1637         S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
1638     // Emit final copy of the lastprivate variables at the end of loops.
1639     if (HasLastprivateClause)
1640       CGF.EmitOMPLastprivateClauseFinal(S, /*NoFinals=*/true);
1641     CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_simd);
1642     emitPostUpdateForReductionClause(
1643         CGF, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
1644   }
1645   CGF.EmitOMPLinearClauseFinal(
1646       S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
1647   // Emit: if (PreCond) - end.
1648   if (ContBlock) {
1649     CGF.EmitBranch(ContBlock);
1650     CGF.EmitBlock(ContBlock, true);
1651   }
1652 }
1653
1654 void CodeGenFunction::EmitOMPSimdDirective(const OMPSimdDirective &S) {
1655   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
1656     emitOMPSimdRegion(CGF, S, Action);
1657   };
1658   OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
1659   CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
1660 }
1661
1662 void CodeGenFunction::EmitOMPOuterLoop(
1663     bool DynamicOrOrdered, bool IsMonotonic, const OMPLoopDirective &S,
1664     CodeGenFunction::OMPPrivateScope &LoopScope,
1665     const CodeGenFunction::OMPLoopArguments &LoopArgs,
1666     const CodeGenFunction::CodeGenLoopTy &CodeGenLoop,
1667     const CodeGenFunction::CodeGenOrderedTy &CodeGenOrdered) {
1668   auto &RT = CGM.getOpenMPRuntime();
1669
1670   const Expr *IVExpr = S.getIterationVariable();
1671   const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1672   const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1673
1674   auto LoopExit = getJumpDestInCurrentScope("omp.dispatch.end");
1675
1676   // Start the loop with a block that tests the condition.
1677   auto CondBlock = createBasicBlock("omp.dispatch.cond");
1678   EmitBlock(CondBlock);
1679   const SourceRange &R = S.getSourceRange();
1680   LoopStack.push(CondBlock, SourceLocToDebugLoc(R.getBegin()),
1681                  SourceLocToDebugLoc(R.getEnd()));
1682
1683   llvm::Value *BoolCondVal = nullptr;
1684   if (!DynamicOrOrdered) {
1685     // UB = min(UB, GlobalUB) or
1686     // UB = min(UB, PrevUB) for combined loop sharing constructs (e.g.
1687     // 'distribute parallel for')
1688     EmitIgnoredExpr(LoopArgs.EUB);
1689     // IV = LB
1690     EmitIgnoredExpr(LoopArgs.Init);
1691     // IV < UB
1692     BoolCondVal = EvaluateExprAsBool(LoopArgs.Cond);
1693   } else {
1694     BoolCondVal =
1695         RT.emitForNext(*this, S.getLocStart(), IVSize, IVSigned, LoopArgs.IL,
1696                        LoopArgs.LB, LoopArgs.UB, LoopArgs.ST);
1697   }
1698
1699   // If there are any cleanups between here and the loop-exit scope,
1700   // create a block to stage a loop exit along.
1701   auto ExitBlock = LoopExit.getBlock();
1702   if (LoopScope.requiresCleanups())
1703     ExitBlock = createBasicBlock("omp.dispatch.cleanup");
1704
1705   auto LoopBody = createBasicBlock("omp.dispatch.body");
1706   Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
1707   if (ExitBlock != LoopExit.getBlock()) {
1708     EmitBlock(ExitBlock);
1709     EmitBranchThroughCleanup(LoopExit);
1710   }
1711   EmitBlock(LoopBody);
1712
1713   // Emit "IV = LB" (in case of static schedule, we have already calculated new
1714   // LB for loop condition and emitted it above).
1715   if (DynamicOrOrdered)
1716     EmitIgnoredExpr(LoopArgs.Init);
1717
1718   // Create a block for the increment.
1719   auto Continue = getJumpDestInCurrentScope("omp.dispatch.inc");
1720   BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1721
1722   // Generate !llvm.loop.parallel metadata for loads and stores for loops
1723   // with dynamic/guided scheduling and without ordered clause.
1724   if (!isOpenMPSimdDirective(S.getDirectiveKind()))
1725     LoopStack.setParallel(!IsMonotonic);
1726   else
1727     EmitOMPSimdInit(S, IsMonotonic);
1728
1729   SourceLocation Loc = S.getLocStart();
1730
1731   // when 'distribute' is not combined with a 'for':
1732   // while (idx <= UB) { BODY; ++idx; }
1733   // when 'distribute' is combined with a 'for'
1734   // (e.g. 'distribute parallel for')
1735   // while (idx <= UB) { <CodeGen rest of pragma>; idx += ST; }
1736   EmitOMPInnerLoop(
1737       S, LoopScope.requiresCleanups(), LoopArgs.Cond, LoopArgs.IncExpr,
1738       [&S, LoopExit, &CodeGenLoop](CodeGenFunction &CGF) {
1739         CodeGenLoop(CGF, S, LoopExit);
1740       },
1741       [IVSize, IVSigned, Loc, &CodeGenOrdered](CodeGenFunction &CGF) {
1742         CodeGenOrdered(CGF, Loc, IVSize, IVSigned);
1743       });
1744
1745   EmitBlock(Continue.getBlock());
1746   BreakContinueStack.pop_back();
1747   if (!DynamicOrOrdered) {
1748     // Emit "LB = LB + Stride", "UB = UB + Stride".
1749     EmitIgnoredExpr(LoopArgs.NextLB);
1750     EmitIgnoredExpr(LoopArgs.NextUB);
1751   }
1752
1753   EmitBranch(CondBlock);
1754   LoopStack.pop();
1755   // Emit the fall-through block.
1756   EmitBlock(LoopExit.getBlock());
1757
1758   // Tell the runtime we are done.
1759   auto &&CodeGen = [DynamicOrOrdered, &S](CodeGenFunction &CGF) {
1760     if (!DynamicOrOrdered)
1761       CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocEnd(),
1762                                                      S.getDirectiveKind());
1763   };
1764   OMPCancelStack.emitExit(*this, S.getDirectiveKind(), CodeGen);
1765 }
1766
1767 void CodeGenFunction::EmitOMPForOuterLoop(
1768     const OpenMPScheduleTy &ScheduleKind, bool IsMonotonic,
1769     const OMPLoopDirective &S, OMPPrivateScope &LoopScope, bool Ordered,
1770     const OMPLoopArguments &LoopArgs,
1771     const CodeGenDispatchBoundsTy &CGDispatchBounds) {
1772   auto &RT = CGM.getOpenMPRuntime();
1773
1774   // Dynamic scheduling of the outer loop (dynamic, guided, auto, runtime).
1775   const bool DynamicOrOrdered =
1776       Ordered || RT.isDynamic(ScheduleKind.Schedule);
1777
1778   assert((Ordered ||
1779           !RT.isStaticNonchunked(ScheduleKind.Schedule,
1780                                  LoopArgs.Chunk != nullptr)) &&
1781          "static non-chunked schedule does not need outer loop");
1782
1783   // Emit outer loop.
1784   //
1785   // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1786   // When schedule(dynamic,chunk_size) is specified, the iterations are
1787   // distributed to threads in the team in chunks as the threads request them.
1788   // Each thread executes a chunk of iterations, then requests another chunk,
1789   // until no chunks remain to be distributed. Each chunk contains chunk_size
1790   // iterations, except for the last chunk to be distributed, which may have
1791   // fewer iterations. When no chunk_size is specified, it defaults to 1.
1792   //
1793   // When schedule(guided,chunk_size) is specified, the iterations are assigned
1794   // to threads in the team in chunks as the executing threads request them.
1795   // Each thread executes a chunk of iterations, then requests another chunk,
1796   // until no chunks remain to be assigned. For a chunk_size of 1, the size of
1797   // each chunk is proportional to the number of unassigned iterations divided
1798   // by the number of threads in the team, decreasing to 1. For a chunk_size
1799   // with value k (greater than 1), the size of each chunk is determined in the
1800   // same way, with the restriction that the chunks do not contain fewer than k
1801   // iterations (except for the last chunk to be assigned, which may have fewer
1802   // than k iterations).
1803   //
1804   // When schedule(auto) is specified, the decision regarding scheduling is
1805   // delegated to the compiler and/or runtime system. The programmer gives the
1806   // implementation the freedom to choose any possible mapping of iterations to
1807   // threads in the team.
1808   //
1809   // When schedule(runtime) is specified, the decision regarding scheduling is
1810   // deferred until run time, and the schedule and chunk size are taken from the
1811   // run-sched-var ICV. If the ICV is set to auto, the schedule is
1812   // implementation defined
1813   //
1814   // while(__kmpc_dispatch_next(&LB, &UB)) {
1815   //   idx = LB;
1816   //   while (idx <= UB) { BODY; ++idx;
1817   //   __kmpc_dispatch_fini_(4|8)[u](); // For ordered loops only.
1818   //   } // inner loop
1819   // }
1820   //
1821   // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1822   // When schedule(static, chunk_size) is specified, iterations are divided into
1823   // chunks of size chunk_size, and the chunks are assigned to the threads in
1824   // the team in a round-robin fashion in the order of the thread number.
1825   //
1826   // while(UB = min(UB, GlobalUB), idx = LB, idx < UB) {
1827   //   while (idx <= UB) { BODY; ++idx; } // inner loop
1828   //   LB = LB + ST;
1829   //   UB = UB + ST;
1830   // }
1831   //
1832
1833   const Expr *IVExpr = S.getIterationVariable();
1834   const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1835   const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1836
1837   if (DynamicOrOrdered) {
1838     auto DispatchBounds = CGDispatchBounds(*this, S, LoopArgs.LB, LoopArgs.UB);
1839     llvm::Value *LBVal = DispatchBounds.first;
1840     llvm::Value *UBVal = DispatchBounds.second;
1841     CGOpenMPRuntime::DispatchRTInput DipatchRTInputValues = {LBVal, UBVal,
1842                                                              LoopArgs.Chunk};
1843     RT.emitForDispatchInit(*this, S.getLocStart(), ScheduleKind, IVSize,
1844                            IVSigned, Ordered, DipatchRTInputValues);
1845   } else {
1846     CGOpenMPRuntime::StaticRTInput StaticInit(
1847         IVSize, IVSigned, Ordered, LoopArgs.IL, LoopArgs.LB, LoopArgs.UB,
1848         LoopArgs.ST, LoopArgs.Chunk);
1849     RT.emitForStaticInit(*this, S.getLocStart(), S.getDirectiveKind(),
1850                          ScheduleKind, StaticInit);
1851   }
1852
1853   auto &&CodeGenOrdered = [Ordered](CodeGenFunction &CGF, SourceLocation Loc,
1854                                     const unsigned IVSize,
1855                                     const bool IVSigned) {
1856     if (Ordered) {
1857       CGF.CGM.getOpenMPRuntime().emitForOrderedIterationEnd(CGF, Loc, IVSize,
1858                                                             IVSigned);
1859     }
1860   };
1861
1862   OMPLoopArguments OuterLoopArgs(LoopArgs.LB, LoopArgs.UB, LoopArgs.ST,
1863                                  LoopArgs.IL, LoopArgs.Chunk, LoopArgs.EUB);
1864   OuterLoopArgs.IncExpr = S.getInc();
1865   OuterLoopArgs.Init = S.getInit();
1866   OuterLoopArgs.Cond = S.getCond();
1867   OuterLoopArgs.NextLB = S.getNextLowerBound();
1868   OuterLoopArgs.NextUB = S.getNextUpperBound();
1869   EmitOMPOuterLoop(DynamicOrOrdered, IsMonotonic, S, LoopScope, OuterLoopArgs,
1870                    emitOMPLoopBodyWithStopPoint, CodeGenOrdered);
1871 }
1872
1873 static void emitEmptyOrdered(CodeGenFunction &, SourceLocation Loc,
1874                              const unsigned IVSize, const bool IVSigned) {}
1875
1876 void CodeGenFunction::EmitOMPDistributeOuterLoop(
1877     OpenMPDistScheduleClauseKind ScheduleKind, const OMPLoopDirective &S,
1878     OMPPrivateScope &LoopScope, const OMPLoopArguments &LoopArgs,
1879     const CodeGenLoopTy &CodeGenLoopContent) {
1880
1881   auto &RT = CGM.getOpenMPRuntime();
1882
1883   // Emit outer loop.
1884   // Same behavior as a OMPForOuterLoop, except that schedule cannot be
1885   // dynamic
1886   //
1887
1888   const Expr *IVExpr = S.getIterationVariable();
1889   const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1890   const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1891
1892   CGOpenMPRuntime::StaticRTInput StaticInit(
1893       IVSize, IVSigned, /* Ordered = */ false, LoopArgs.IL, LoopArgs.LB,
1894       LoopArgs.UB, LoopArgs.ST, LoopArgs.Chunk);
1895   RT.emitDistributeStaticInit(*this, S.getLocStart(), ScheduleKind, StaticInit);
1896
1897   // for combined 'distribute' and 'for' the increment expression of distribute
1898   // is store in DistInc. For 'distribute' alone, it is in Inc.
1899   Expr *IncExpr;
1900   if (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()))
1901     IncExpr = S.getDistInc();
1902   else
1903     IncExpr = S.getInc();
1904
1905   // this routine is shared by 'omp distribute parallel for' and
1906   // 'omp distribute': select the right EUB expression depending on the
1907   // directive
1908   OMPLoopArguments OuterLoopArgs;
1909   OuterLoopArgs.LB = LoopArgs.LB;
1910   OuterLoopArgs.UB = LoopArgs.UB;
1911   OuterLoopArgs.ST = LoopArgs.ST;
1912   OuterLoopArgs.IL = LoopArgs.IL;
1913   OuterLoopArgs.Chunk = LoopArgs.Chunk;
1914   OuterLoopArgs.EUB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
1915                           ? S.getCombinedEnsureUpperBound()
1916                           : S.getEnsureUpperBound();
1917   OuterLoopArgs.IncExpr = IncExpr;
1918   OuterLoopArgs.Init = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
1919                            ? S.getCombinedInit()
1920                            : S.getInit();
1921   OuterLoopArgs.Cond = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
1922                            ? S.getCombinedCond()
1923                            : S.getCond();
1924   OuterLoopArgs.NextLB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
1925                              ? S.getCombinedNextLowerBound()
1926                              : S.getNextLowerBound();
1927   OuterLoopArgs.NextUB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
1928                              ? S.getCombinedNextUpperBound()
1929                              : S.getNextUpperBound();
1930
1931   EmitOMPOuterLoop(/* DynamicOrOrdered = */ false, /* IsMonotonic = */ false, S,
1932                    LoopScope, OuterLoopArgs, CodeGenLoopContent,
1933                    emitEmptyOrdered);
1934 }
1935
1936 /// Emit a helper variable and return corresponding lvalue.
1937 static LValue EmitOMPHelperVar(CodeGenFunction &CGF,
1938                                const DeclRefExpr *Helper) {
1939   auto VDecl = cast<VarDecl>(Helper->getDecl());
1940   CGF.EmitVarDecl(*VDecl);
1941   return CGF.EmitLValue(Helper);
1942 }
1943
1944 static std::pair<LValue, LValue>
1945 emitDistributeParallelForInnerBounds(CodeGenFunction &CGF,
1946                                      const OMPExecutableDirective &S) {
1947   const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
1948   LValue LB =
1949       EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getLowerBoundVariable()));
1950   LValue UB =
1951       EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getUpperBoundVariable()));
1952
1953   // When composing 'distribute' with 'for' (e.g. as in 'distribute
1954   // parallel for') we need to use the 'distribute'
1955   // chunk lower and upper bounds rather than the whole loop iteration
1956   // space. These are parameters to the outlined function for 'parallel'
1957   // and we copy the bounds of the previous schedule into the
1958   // the current ones.
1959   LValue PrevLB = CGF.EmitLValue(LS.getPrevLowerBoundVariable());
1960   LValue PrevUB = CGF.EmitLValue(LS.getPrevUpperBoundVariable());
1961   llvm::Value *PrevLBVal = CGF.EmitLoadOfScalar(PrevLB, SourceLocation());
1962   PrevLBVal = CGF.EmitScalarConversion(
1963       PrevLBVal, LS.getPrevLowerBoundVariable()->getType(),
1964       LS.getIterationVariable()->getType(), SourceLocation());
1965   llvm::Value *PrevUBVal = CGF.EmitLoadOfScalar(PrevUB, SourceLocation());
1966   PrevUBVal = CGF.EmitScalarConversion(
1967       PrevUBVal, LS.getPrevUpperBoundVariable()->getType(),
1968       LS.getIterationVariable()->getType(), SourceLocation());
1969
1970   CGF.EmitStoreOfScalar(PrevLBVal, LB);
1971   CGF.EmitStoreOfScalar(PrevUBVal, UB);
1972
1973   return {LB, UB};
1974 }
1975
1976 /// if the 'for' loop has a dispatch schedule (e.g. dynamic, guided) then
1977 /// we need to use the LB and UB expressions generated by the worksharing
1978 /// code generation support, whereas in non combined situations we would
1979 /// just emit 0 and the LastIteration expression
1980 /// This function is necessary due to the difference of the LB and UB
1981 /// types for the RT emission routines for 'for_static_init' and
1982 /// 'for_dispatch_init'
1983 static std::pair<llvm::Value *, llvm::Value *>
1984 emitDistributeParallelForDispatchBounds(CodeGenFunction &CGF,
1985                                         const OMPExecutableDirective &S,
1986                                         Address LB, Address UB) {
1987   const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
1988   const Expr *IVExpr = LS.getIterationVariable();
1989   // when implementing a dynamic schedule for a 'for' combined with a
1990   // 'distribute' (e.g. 'distribute parallel for'), the 'for' loop
1991   // is not normalized as each team only executes its own assigned
1992   // distribute chunk
1993   QualType IteratorTy = IVExpr->getType();
1994   llvm::Value *LBVal = CGF.EmitLoadOfScalar(LB, /*Volatile=*/false, IteratorTy,
1995                                             SourceLocation());
1996   llvm::Value *UBVal = CGF.EmitLoadOfScalar(UB, /*Volatile=*/false, IteratorTy,
1997                                             SourceLocation());
1998   return {LBVal, UBVal};
1999 }
2000
2001 static void emitDistributeParallelForDistributeInnerBoundParams(
2002     CodeGenFunction &CGF, const OMPExecutableDirective &S,
2003     llvm::SmallVectorImpl<llvm::Value *> &CapturedVars) {
2004   const auto &Dir = cast<OMPLoopDirective>(S);
2005   LValue LB =
2006       CGF.EmitLValue(cast<DeclRefExpr>(Dir.getCombinedLowerBoundVariable()));
2007   auto LBCast = CGF.Builder.CreateIntCast(
2008       CGF.Builder.CreateLoad(LB.getAddress()), CGF.SizeTy, /*isSigned=*/false);
2009   CapturedVars.push_back(LBCast);
2010   LValue UB =
2011       CGF.EmitLValue(cast<DeclRefExpr>(Dir.getCombinedUpperBoundVariable()));
2012
2013   auto UBCast = CGF.Builder.CreateIntCast(
2014       CGF.Builder.CreateLoad(UB.getAddress()), CGF.SizeTy, /*isSigned=*/false);
2015   CapturedVars.push_back(UBCast);
2016 }
2017
2018 static void
2019 emitInnerParallelForWhenCombined(CodeGenFunction &CGF,
2020                                  const OMPLoopDirective &S,
2021                                  CodeGenFunction::JumpDest LoopExit) {
2022   auto &&CGInlinedWorksharingLoop = [&S](CodeGenFunction &CGF,
2023                                          PrePostActionTy &) {
2024     bool HasCancel = false;
2025     if (!isOpenMPSimdDirective(S.getDirectiveKind())) {
2026       if (const auto *D = dyn_cast<OMPTeamsDistributeParallelForDirective>(&S))
2027         HasCancel = D->hasCancel();
2028       else if (const auto *D = dyn_cast<OMPDistributeParallelForDirective>(&S))
2029         HasCancel = D->hasCancel();
2030       else if (const auto *D =
2031                    dyn_cast<OMPTargetTeamsDistributeParallelForDirective>(&S))
2032         HasCancel = D->hasCancel();
2033     }
2034     CodeGenFunction::OMPCancelStackRAII CancelRegion(CGF, S.getDirectiveKind(),
2035                                                      HasCancel);
2036     CGF.EmitOMPWorksharingLoop(S, S.getPrevEnsureUpperBound(),
2037                                emitDistributeParallelForInnerBounds,
2038                                emitDistributeParallelForDispatchBounds);
2039   };
2040
2041   emitCommonOMPParallelDirective(
2042       CGF, S,
2043       isOpenMPSimdDirective(S.getDirectiveKind()) ? OMPD_for_simd : OMPD_for,
2044       CGInlinedWorksharingLoop,
2045       emitDistributeParallelForDistributeInnerBoundParams);
2046 }
2047
2048 void CodeGenFunction::EmitOMPDistributeParallelForDirective(
2049     const OMPDistributeParallelForDirective &S) {
2050   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2051     CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
2052                               S.getDistInc());
2053   };
2054   OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
2055   CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen);
2056 }
2057
2058 void CodeGenFunction::EmitOMPDistributeParallelForSimdDirective(
2059     const OMPDistributeParallelForSimdDirective &S) {
2060   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2061     CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
2062                               S.getDistInc());
2063   };
2064   OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
2065   CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen);
2066 }
2067
2068 void CodeGenFunction::EmitOMPDistributeSimdDirective(
2069     const OMPDistributeSimdDirective &S) {
2070   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2071     CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
2072   };
2073   OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
2074   CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
2075 }
2076
2077 void CodeGenFunction::EmitOMPTargetSimdDeviceFunction(
2078     CodeGenModule &CGM, StringRef ParentName, const OMPTargetSimdDirective &S) {
2079   // Emit SPMD target parallel for region as a standalone region.
2080   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2081     emitOMPSimdRegion(CGF, S, Action);
2082   };
2083   llvm::Function *Fn;
2084   llvm::Constant *Addr;
2085   // Emit target region as a standalone region.
2086   CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
2087       S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
2088   assert(Fn && Addr && "Target device function emission failed.");
2089 }
2090
2091 void CodeGenFunction::EmitOMPTargetSimdDirective(
2092     const OMPTargetSimdDirective &S) {
2093   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2094     emitOMPSimdRegion(CGF, S, Action);
2095   };
2096   emitCommonOMPTargetDirective(*this, S, CodeGen);
2097 }
2098
2099 void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDirective(
2100     const OMPTargetTeamsDistributeParallelForDirective &S) {
2101   OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
2102   CGM.getOpenMPRuntime().emitInlinedDirective(
2103       *this, OMPD_target_teams_distribute_parallel_for,
2104       [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2105         CGF.EmitStmt(
2106             cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2107       });
2108 }
2109
2110 void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForSimdDirective(
2111     const OMPTargetTeamsDistributeParallelForSimdDirective &S) {
2112   OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
2113   CGM.getOpenMPRuntime().emitInlinedDirective(
2114       *this, OMPD_target_teams_distribute_parallel_for_simd,
2115       [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2116         CGF.EmitStmt(
2117             cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2118       });
2119 }
2120
2121 namespace {
2122   struct ScheduleKindModifiersTy {
2123     OpenMPScheduleClauseKind Kind;
2124     OpenMPScheduleClauseModifier M1;
2125     OpenMPScheduleClauseModifier M2;
2126     ScheduleKindModifiersTy(OpenMPScheduleClauseKind Kind,
2127                             OpenMPScheduleClauseModifier M1,
2128                             OpenMPScheduleClauseModifier M2)
2129         : Kind(Kind), M1(M1), M2(M2) {}
2130   };
2131 } // namespace
2132
2133 bool CodeGenFunction::EmitOMPWorksharingLoop(
2134     const OMPLoopDirective &S, Expr *EUB,
2135     const CodeGenLoopBoundsTy &CodeGenLoopBounds,
2136     const CodeGenDispatchBoundsTy &CGDispatchBounds) {
2137   // Emit the loop iteration variable.
2138   auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
2139   auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
2140   EmitVarDecl(*IVDecl);
2141
2142   // Emit the iterations count variable.
2143   // If it is not a variable, Sema decided to calculate iterations count on each
2144   // iteration (e.g., it is foldable into a constant).
2145   if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
2146     EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
2147     // Emit calculation of the iterations count.
2148     EmitIgnoredExpr(S.getCalcLastIteration());
2149   }
2150
2151   auto &RT = CGM.getOpenMPRuntime();
2152
2153   bool HasLastprivateClause;
2154   // Check pre-condition.
2155   {
2156     OMPLoopScope PreInitScope(*this, S);
2157     // Skip the entire loop if we don't meet the precondition.
2158     // If the condition constant folds and can be elided, avoid emitting the
2159     // whole loop.
2160     bool CondConstant;
2161     llvm::BasicBlock *ContBlock = nullptr;
2162     if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
2163       if (!CondConstant)
2164         return false;
2165     } else {
2166       auto *ThenBlock = createBasicBlock("omp.precond.then");
2167       ContBlock = createBasicBlock("omp.precond.end");
2168       emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
2169                   getProfileCount(&S));
2170       EmitBlock(ThenBlock);
2171       incrementProfileCounter(&S);
2172     }
2173
2174     bool Ordered = false;
2175     if (auto *OrderedClause = S.getSingleClause<OMPOrderedClause>()) {
2176       if (OrderedClause->getNumForLoops())
2177         RT.emitDoacrossInit(*this, S);
2178       else
2179         Ordered = true;
2180     }
2181
2182     llvm::DenseSet<const Expr *> EmittedFinals;
2183     emitAlignedClause(*this, S);
2184     bool HasLinears = EmitOMPLinearClauseInit(S);
2185     // Emit helper vars inits.
2186
2187     std::pair<LValue, LValue> Bounds = CodeGenLoopBounds(*this, S);
2188     LValue LB = Bounds.first;
2189     LValue UB = Bounds.second;
2190     LValue ST =
2191         EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
2192     LValue IL =
2193         EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
2194
2195     // Emit 'then' code.
2196     {
2197       OMPPrivateScope LoopScope(*this);
2198       if (EmitOMPFirstprivateClause(S, LoopScope) || HasLinears) {
2199         // Emit implicit barrier to synchronize threads and avoid data races on
2200         // initialization of firstprivate variables and post-update of
2201         // lastprivate variables.
2202         CGM.getOpenMPRuntime().emitBarrierCall(
2203             *this, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
2204             /*ForceSimpleCall=*/true);
2205       }
2206       EmitOMPPrivateClause(S, LoopScope);
2207       HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
2208       EmitOMPReductionClauseInit(S, LoopScope);
2209       EmitOMPPrivateLoopCounters(S, LoopScope);
2210       EmitOMPLinearClause(S, LoopScope);
2211       (void)LoopScope.Privatize();
2212
2213       // Detect the loop schedule kind and chunk.
2214       llvm::Value *Chunk = nullptr;
2215       OpenMPScheduleTy ScheduleKind;
2216       if (auto *C = S.getSingleClause<OMPScheduleClause>()) {
2217         ScheduleKind.Schedule = C->getScheduleKind();
2218         ScheduleKind.M1 = C->getFirstScheduleModifier();
2219         ScheduleKind.M2 = C->getSecondScheduleModifier();
2220         if (const auto *Ch = C->getChunkSize()) {
2221           Chunk = EmitScalarExpr(Ch);
2222           Chunk = EmitScalarConversion(Chunk, Ch->getType(),
2223                                        S.getIterationVariable()->getType(),
2224                                        S.getLocStart());
2225         }
2226       }
2227       const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
2228       const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
2229       // OpenMP 4.5, 2.7.1 Loop Construct, Description.
2230       // If the static schedule kind is specified or if the ordered clause is
2231       // specified, and if no monotonic modifier is specified, the effect will
2232       // be as if the monotonic modifier was specified.
2233       if (RT.isStaticNonchunked(ScheduleKind.Schedule,
2234                                 /* Chunked */ Chunk != nullptr) &&
2235           !Ordered) {
2236         if (isOpenMPSimdDirective(S.getDirectiveKind()))
2237           EmitOMPSimdInit(S, /*IsMonotonic=*/true);
2238         // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
2239         // When no chunk_size is specified, the iteration space is divided into
2240         // chunks that are approximately equal in size, and at most one chunk is
2241         // distributed to each thread. Note that the size of the chunks is
2242         // unspecified in this case.
2243         CGOpenMPRuntime::StaticRTInput StaticInit(
2244             IVSize, IVSigned, Ordered, IL.getAddress(), LB.getAddress(),
2245             UB.getAddress(), ST.getAddress());
2246         RT.emitForStaticInit(*this, S.getLocStart(), S.getDirectiveKind(),
2247                              ScheduleKind, StaticInit);
2248         auto LoopExit =
2249             getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
2250         // UB = min(UB, GlobalUB);
2251         EmitIgnoredExpr(S.getEnsureUpperBound());
2252         // IV = LB;
2253         EmitIgnoredExpr(S.getInit());
2254         // while (idx <= UB) { BODY; ++idx; }
2255         EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
2256                          S.getInc(),
2257                          [&S, LoopExit](CodeGenFunction &CGF) {
2258                            CGF.EmitOMPLoopBody(S, LoopExit);
2259                            CGF.EmitStopPoint(&S);
2260                          },
2261                          [](CodeGenFunction &) {});
2262         EmitBlock(LoopExit.getBlock());
2263         // Tell the runtime we are done.
2264         auto &&CodeGen = [&S](CodeGenFunction &CGF) {
2265           CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocEnd(),
2266                                                          S.getDirectiveKind());
2267         };
2268         OMPCancelStack.emitExit(*this, S.getDirectiveKind(), CodeGen);
2269       } else {
2270         const bool IsMonotonic =
2271             Ordered || ScheduleKind.Schedule == OMPC_SCHEDULE_static ||
2272             ScheduleKind.Schedule == OMPC_SCHEDULE_unknown ||
2273             ScheduleKind.M1 == OMPC_SCHEDULE_MODIFIER_monotonic ||
2274             ScheduleKind.M2 == OMPC_SCHEDULE_MODIFIER_monotonic;
2275         // Emit the outer loop, which requests its work chunk [LB..UB] from
2276         // runtime and runs the inner loop to process it.
2277         const OMPLoopArguments LoopArguments(LB.getAddress(), UB.getAddress(),
2278                                              ST.getAddress(), IL.getAddress(),
2279                                              Chunk, EUB);
2280         EmitOMPForOuterLoop(ScheduleKind, IsMonotonic, S, LoopScope, Ordered,
2281                             LoopArguments, CGDispatchBounds);
2282       }
2283       if (isOpenMPSimdDirective(S.getDirectiveKind())) {
2284         EmitOMPSimdFinal(S,
2285                          [&](CodeGenFunction &CGF) -> llvm::Value * {
2286                            return CGF.Builder.CreateIsNotNull(
2287                                CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2288                          });
2289       }
2290       EmitOMPReductionClauseFinal(
2291           S, /*ReductionKind=*/isOpenMPSimdDirective(S.getDirectiveKind())
2292                  ? /*Parallel and Simd*/ OMPD_parallel_for_simd
2293                  : /*Parallel only*/ OMPD_parallel);
2294       // Emit post-update of the reduction variables if IsLastIter != 0.
2295       emitPostUpdateForReductionClause(
2296           *this, S, [&](CodeGenFunction &CGF) -> llvm::Value * {
2297             return CGF.Builder.CreateIsNotNull(
2298                 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2299           });
2300       // Emit final copy of the lastprivate variables if IsLastIter != 0.
2301       if (HasLastprivateClause)
2302         EmitOMPLastprivateClauseFinal(
2303             S, isOpenMPSimdDirective(S.getDirectiveKind()),
2304             Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getLocStart())));
2305     }
2306     EmitOMPLinearClauseFinal(S, [&](CodeGenFunction &CGF) -> llvm::Value * {
2307       return CGF.Builder.CreateIsNotNull(
2308           CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2309     });
2310     // We're now done with the loop, so jump to the continuation block.
2311     if (ContBlock) {
2312       EmitBranch(ContBlock);
2313       EmitBlock(ContBlock, true);
2314     }
2315   }
2316   return HasLastprivateClause;
2317 }
2318
2319 /// The following two functions generate expressions for the loop lower
2320 /// and upper bounds in case of static and dynamic (dispatch) schedule
2321 /// of the associated 'for' or 'distribute' loop.
2322 static std::pair<LValue, LValue>
2323 emitForLoopBounds(CodeGenFunction &CGF, const OMPExecutableDirective &S) {
2324   const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
2325   LValue LB =
2326       EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getLowerBoundVariable()));
2327   LValue UB =
2328       EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getUpperBoundVariable()));
2329   return {LB, UB};
2330 }
2331
2332 /// When dealing with dispatch schedules (e.g. dynamic, guided) we do not
2333 /// consider the lower and upper bound expressions generated by the
2334 /// worksharing loop support, but we use 0 and the iteration space size as
2335 /// constants
2336 static std::pair<llvm::Value *, llvm::Value *>
2337 emitDispatchForLoopBounds(CodeGenFunction &CGF, const OMPExecutableDirective &S,
2338                           Address LB, Address UB) {
2339   const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
2340   const Expr *IVExpr = LS.getIterationVariable();
2341   const unsigned IVSize = CGF.getContext().getTypeSize(IVExpr->getType());
2342   llvm::Value *LBVal = CGF.Builder.getIntN(IVSize, 0);
2343   llvm::Value *UBVal = CGF.EmitScalarExpr(LS.getLastIteration());
2344   return {LBVal, UBVal};
2345 }
2346
2347 void CodeGenFunction::EmitOMPForDirective(const OMPForDirective &S) {
2348   bool HasLastprivates = false;
2349   auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF,
2350                                           PrePostActionTy &) {
2351     OMPCancelStackRAII CancelRegion(CGF, OMPD_for, S.hasCancel());
2352     HasLastprivates = CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(),
2353                                                  emitForLoopBounds,
2354                                                  emitDispatchForLoopBounds);
2355   };
2356   {
2357     OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
2358     CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_for, CodeGen,
2359                                                 S.hasCancel());
2360   }
2361
2362   // Emit an implicit barrier at the end.
2363   if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
2364     CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
2365   }
2366 }
2367
2368 void CodeGenFunction::EmitOMPForSimdDirective(const OMPForSimdDirective &S) {
2369   bool HasLastprivates = false;
2370   auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF,
2371                                           PrePostActionTy &) {
2372     HasLastprivates = CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(),
2373                                                  emitForLoopBounds,
2374                                                  emitDispatchForLoopBounds);
2375   };
2376   {
2377     OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
2378     CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
2379   }
2380
2381   // Emit an implicit barrier at the end.
2382   if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
2383     CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
2384   }
2385 }
2386
2387 static LValue createSectionLVal(CodeGenFunction &CGF, QualType Ty,
2388                                 const Twine &Name,
2389                                 llvm::Value *Init = nullptr) {
2390   auto LVal = CGF.MakeAddrLValue(CGF.CreateMemTemp(Ty, Name), Ty);
2391   if (Init)
2392     CGF.EmitStoreThroughLValue(RValue::get(Init), LVal, /*isInit*/ true);
2393   return LVal;
2394 }
2395
2396 void CodeGenFunction::EmitSections(const OMPExecutableDirective &S) {
2397   auto *Stmt = cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt();
2398   auto *CS = dyn_cast<CompoundStmt>(Stmt);
2399   bool HasLastprivates = false;
2400   auto &&CodeGen = [&S, Stmt, CS, &HasLastprivates](CodeGenFunction &CGF,
2401                                                     PrePostActionTy &) {
2402     auto &C = CGF.CGM.getContext();
2403     auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
2404     // Emit helper vars inits.
2405     LValue LB = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.lb.",
2406                                   CGF.Builder.getInt32(0));
2407     auto *GlobalUBVal = CS != nullptr ? CGF.Builder.getInt32(CS->size() - 1)
2408                                       : CGF.Builder.getInt32(0);
2409     LValue UB =
2410         createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.ub.", GlobalUBVal);
2411     LValue ST = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.st.",
2412                                   CGF.Builder.getInt32(1));
2413     LValue IL = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.il.",
2414                                   CGF.Builder.getInt32(0));
2415     // Loop counter.
2416     LValue IV = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.iv.");
2417     OpaqueValueExpr IVRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
2418     CodeGenFunction::OpaqueValueMapping OpaqueIV(CGF, &IVRefExpr, IV);
2419     OpaqueValueExpr UBRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
2420     CodeGenFunction::OpaqueValueMapping OpaqueUB(CGF, &UBRefExpr, UB);
2421     // Generate condition for loop.
2422     BinaryOperator Cond(&IVRefExpr, &UBRefExpr, BO_LE, C.BoolTy, VK_RValue,
2423                         OK_Ordinary, S.getLocStart(), FPOptions());
2424     // Increment for loop counter.
2425     UnaryOperator Inc(&IVRefExpr, UO_PreInc, KmpInt32Ty, VK_RValue, OK_Ordinary,
2426                       S.getLocStart());
2427     auto BodyGen = [Stmt, CS, &S, &IV](CodeGenFunction &CGF) {
2428       // Iterate through all sections and emit a switch construct:
2429       // switch (IV) {
2430       //   case 0:
2431       //     <SectionStmt[0]>;
2432       //     break;
2433       // ...
2434       //   case <NumSection> - 1:
2435       //     <SectionStmt[<NumSection> - 1]>;
2436       //     break;
2437       // }
2438       // .omp.sections.exit:
2439       auto *ExitBB = CGF.createBasicBlock(".omp.sections.exit");
2440       auto *SwitchStmt = CGF.Builder.CreateSwitch(
2441           CGF.EmitLoadOfLValue(IV, S.getLocStart()).getScalarVal(), ExitBB,
2442           CS == nullptr ? 1 : CS->size());
2443       if (CS) {
2444         unsigned CaseNumber = 0;
2445         for (auto *SubStmt : CS->children()) {
2446           auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
2447           CGF.EmitBlock(CaseBB);
2448           SwitchStmt->addCase(CGF.Builder.getInt32(CaseNumber), CaseBB);
2449           CGF.EmitStmt(SubStmt);
2450           CGF.EmitBranch(ExitBB);
2451           ++CaseNumber;
2452         }
2453       } else {
2454         auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
2455         CGF.EmitBlock(CaseBB);
2456         SwitchStmt->addCase(CGF.Builder.getInt32(0), CaseBB);
2457         CGF.EmitStmt(Stmt);
2458         CGF.EmitBranch(ExitBB);
2459       }
2460       CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
2461     };
2462
2463     CodeGenFunction::OMPPrivateScope LoopScope(CGF);
2464     if (CGF.EmitOMPFirstprivateClause(S, LoopScope)) {
2465       // Emit implicit barrier to synchronize threads and avoid data races on
2466       // initialization of firstprivate variables and post-update of lastprivate
2467       // variables.
2468       CGF.CGM.getOpenMPRuntime().emitBarrierCall(
2469           CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
2470           /*ForceSimpleCall=*/true);
2471     }
2472     CGF.EmitOMPPrivateClause(S, LoopScope);
2473     HasLastprivates = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
2474     CGF.EmitOMPReductionClauseInit(S, LoopScope);
2475     (void)LoopScope.Privatize();
2476
2477     // Emit static non-chunked loop.
2478     OpenMPScheduleTy ScheduleKind;
2479     ScheduleKind.Schedule = OMPC_SCHEDULE_static;
2480     CGOpenMPRuntime::StaticRTInput StaticInit(
2481         /*IVSize=*/32, /*IVSigned=*/true, /*Ordered=*/false, IL.getAddress(),
2482         LB.getAddress(), UB.getAddress(), ST.getAddress());
2483     CGF.CGM.getOpenMPRuntime().emitForStaticInit(
2484         CGF, S.getLocStart(), S.getDirectiveKind(), ScheduleKind, StaticInit);
2485     // UB = min(UB, GlobalUB);
2486     auto *UBVal = CGF.EmitLoadOfScalar(UB, S.getLocStart());
2487     auto *MinUBGlobalUB = CGF.Builder.CreateSelect(
2488         CGF.Builder.CreateICmpSLT(UBVal, GlobalUBVal), UBVal, GlobalUBVal);
2489     CGF.EmitStoreOfScalar(MinUBGlobalUB, UB);
2490     // IV = LB;
2491     CGF.EmitStoreOfScalar(CGF.EmitLoadOfScalar(LB, S.getLocStart()), IV);
2492     // while (idx <= UB) { BODY; ++idx; }
2493     CGF.EmitOMPInnerLoop(S, /*RequiresCleanup=*/false, &Cond, &Inc, BodyGen,
2494                          [](CodeGenFunction &) {});
2495     // Tell the runtime we are done.
2496     auto &&CodeGen = [&S](CodeGenFunction &CGF) {
2497       CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocEnd(),
2498                                                      S.getDirectiveKind());
2499     };
2500     CGF.OMPCancelStack.emitExit(CGF, S.getDirectiveKind(), CodeGen);
2501     CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
2502     // Emit post-update of the reduction variables if IsLastIter != 0.
2503     emitPostUpdateForReductionClause(
2504         CGF, S, [&](CodeGenFunction &CGF) -> llvm::Value * {
2505           return CGF.Builder.CreateIsNotNull(
2506               CGF.EmitLoadOfScalar(IL, S.getLocStart()));
2507         });
2508
2509     // Emit final copy of the lastprivate variables if IsLastIter != 0.
2510     if (HasLastprivates)
2511       CGF.EmitOMPLastprivateClauseFinal(
2512           S, /*NoFinals=*/false,
2513           CGF.Builder.CreateIsNotNull(
2514               CGF.EmitLoadOfScalar(IL, S.getLocStart())));
2515   };
2516
2517   bool HasCancel = false;
2518   if (auto *OSD = dyn_cast<OMPSectionsDirective>(&S))
2519     HasCancel = OSD->hasCancel();
2520   else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&S))
2521     HasCancel = OPSD->hasCancel();
2522   OMPCancelStackRAII CancelRegion(*this, S.getDirectiveKind(), HasCancel);
2523   CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_sections, CodeGen,
2524                                               HasCancel);
2525   // Emit barrier for lastprivates only if 'sections' directive has 'nowait'
2526   // clause. Otherwise the barrier will be generated by the codegen for the
2527   // directive.
2528   if (HasLastprivates && S.getSingleClause<OMPNowaitClause>()) {
2529     // Emit implicit barrier to synchronize threads and avoid data races on
2530     // initialization of firstprivate variables.
2531     CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
2532                                            OMPD_unknown);
2533   }
2534 }
2535
2536 void CodeGenFunction::EmitOMPSectionsDirective(const OMPSectionsDirective &S) {
2537   {
2538     OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
2539     EmitSections(S);
2540   }
2541   // Emit an implicit barrier at the end.
2542   if (!S.getSingleClause<OMPNowaitClause>()) {
2543     CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
2544                                            OMPD_sections);
2545   }
2546 }
2547
2548 void CodeGenFunction::EmitOMPSectionDirective(const OMPSectionDirective &S) {
2549   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2550     CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2551   };
2552   OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
2553   CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_section, CodeGen,
2554                                               S.hasCancel());
2555 }
2556
2557 void CodeGenFunction::EmitOMPSingleDirective(const OMPSingleDirective &S) {
2558   llvm::SmallVector<const Expr *, 8> CopyprivateVars;
2559   llvm::SmallVector<const Expr *, 8> DestExprs;
2560   llvm::SmallVector<const Expr *, 8> SrcExprs;
2561   llvm::SmallVector<const Expr *, 8> AssignmentOps;
2562   // Check if there are any 'copyprivate' clauses associated with this
2563   // 'single' construct.
2564   // Build a list of copyprivate variables along with helper expressions
2565   // (<source>, <destination>, <destination>=<source> expressions)
2566   for (const auto *C : S.getClausesOfKind<OMPCopyprivateClause>()) {
2567     CopyprivateVars.append(C->varlists().begin(), C->varlists().end());
2568     DestExprs.append(C->destination_exprs().begin(),
2569                      C->destination_exprs().end());
2570     SrcExprs.append(C->source_exprs().begin(), C->source_exprs().end());
2571     AssignmentOps.append(C->assignment_ops().begin(),
2572                          C->assignment_ops().end());
2573   }
2574   // Emit code for 'single' region along with 'copyprivate' clauses
2575   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2576     Action.Enter(CGF);
2577     OMPPrivateScope SingleScope(CGF);
2578     (void)CGF.EmitOMPFirstprivateClause(S, SingleScope);
2579     CGF.EmitOMPPrivateClause(S, SingleScope);
2580     (void)SingleScope.Privatize();
2581     CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2582   };
2583   {
2584     OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
2585     CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getLocStart(),
2586                                             CopyprivateVars, DestExprs,
2587                                             SrcExprs, AssignmentOps);
2588   }
2589   // Emit an implicit barrier at the end (to avoid data race on firstprivate
2590   // init or if no 'nowait' clause was specified and no 'copyprivate' clause).
2591   if (!S.getSingleClause<OMPNowaitClause>() && CopyprivateVars.empty()) {
2592     CGM.getOpenMPRuntime().emitBarrierCall(
2593         *this, S.getLocStart(),
2594         S.getSingleClause<OMPNowaitClause>() ? OMPD_unknown : OMPD_single);
2595   }
2596 }
2597
2598 void CodeGenFunction::EmitOMPMasterDirective(const OMPMasterDirective &S) {
2599   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2600     Action.Enter(CGF);
2601     CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2602   };
2603   OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
2604   CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getLocStart());
2605 }
2606
2607 void CodeGenFunction::EmitOMPCriticalDirective(const OMPCriticalDirective &S) {
2608   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2609     Action.Enter(CGF);
2610     CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2611   };
2612   Expr *Hint = nullptr;
2613   if (auto *HintClause = S.getSingleClause<OMPHintClause>())
2614     Hint = HintClause->getHint();
2615   OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
2616   CGM.getOpenMPRuntime().emitCriticalRegion(*this,
2617                                             S.getDirectiveName().getAsString(),
2618                                             CodeGen, S.getLocStart(), Hint);
2619 }
2620
2621 void CodeGenFunction::EmitOMPParallelForDirective(
2622     const OMPParallelForDirective &S) {
2623   // Emit directive as a combined directive that consists of two implicit
2624   // directives: 'parallel' with 'for' directive.
2625   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2626     OMPCancelStackRAII CancelRegion(CGF, OMPD_parallel_for, S.hasCancel());
2627     CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
2628                                emitDispatchForLoopBounds);
2629   };
2630   emitCommonOMPParallelDirective(*this, S, OMPD_for, CodeGen,
2631                                  emitEmptyBoundParameters);
2632 }
2633
2634 void CodeGenFunction::EmitOMPParallelForSimdDirective(
2635     const OMPParallelForSimdDirective &S) {
2636   // Emit directive as a combined directive that consists of two implicit
2637   // directives: 'parallel' with 'for' directive.
2638   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2639     CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
2640                                emitDispatchForLoopBounds);
2641   };
2642   emitCommonOMPParallelDirective(*this, S, OMPD_simd, CodeGen,
2643                                  emitEmptyBoundParameters);
2644 }
2645
2646 void CodeGenFunction::EmitOMPParallelSectionsDirective(
2647     const OMPParallelSectionsDirective &S) {
2648   // Emit directive as a combined directive that consists of two implicit
2649   // directives: 'parallel' with 'sections' directive.
2650   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2651     CGF.EmitSections(S);
2652   };
2653   emitCommonOMPParallelDirective(*this, S, OMPD_sections, CodeGen,
2654                                  emitEmptyBoundParameters);
2655 }
2656
2657 void CodeGenFunction::EmitOMPTaskBasedDirective(const OMPExecutableDirective &S,
2658                                                 const RegionCodeGenTy &BodyGen,
2659                                                 const TaskGenTy &TaskGen,
2660                                                 OMPTaskDataTy &Data) {
2661   // Emit outlined function for task construct.
2662   auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
2663   auto *I = CS->getCapturedDecl()->param_begin();
2664   auto *PartId = std::next(I);
2665   auto *TaskT = std::next(I, 4);
2666   // Check if the task is final
2667   if (const auto *Clause = S.getSingleClause<OMPFinalClause>()) {
2668     // If the condition constant folds and can be elided, try to avoid emitting
2669     // the condition and the dead arm of the if/else.
2670     auto *Cond = Clause->getCondition();
2671     bool CondConstant;
2672     if (ConstantFoldsToSimpleInteger(Cond, CondConstant))
2673       Data.Final.setInt(CondConstant);
2674     else
2675       Data.Final.setPointer(EvaluateExprAsBool(Cond));
2676   } else {
2677     // By default the task is not final.
2678     Data.Final.setInt(/*IntVal=*/false);
2679   }
2680   // Check if the task has 'priority' clause.
2681   if (const auto *Clause = S.getSingleClause<OMPPriorityClause>()) {
2682     auto *Prio = Clause->getPriority();
2683     Data.Priority.setInt(/*IntVal=*/true);
2684     Data.Priority.setPointer(EmitScalarConversion(
2685         EmitScalarExpr(Prio), Prio->getType(),
2686         getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
2687         Prio->getExprLoc()));
2688   }
2689   // The first function argument for tasks is a thread id, the second one is a
2690   // part id (0 for tied tasks, >=0 for untied task).
2691   llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
2692   // Get list of private variables.
2693   for (const auto *C : S.getClausesOfKind<OMPPrivateClause>()) {
2694     auto IRef = C->varlist_begin();
2695     for (auto *IInit : C->private_copies()) {
2696       auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2697       if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
2698         Data.PrivateVars.push_back(*IRef);
2699         Data.PrivateCopies.push_back(IInit);
2700       }
2701       ++IRef;
2702     }
2703   }
2704   EmittedAsPrivate.clear();
2705   // Get list of firstprivate variables.
2706   for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
2707     auto IRef = C->varlist_begin();
2708     auto IElemInitRef = C->inits().begin();
2709     for (auto *IInit : C->private_copies()) {
2710       auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2711       if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
2712         Data.FirstprivateVars.push_back(*IRef);
2713         Data.FirstprivateCopies.push_back(IInit);
2714         Data.FirstprivateInits.push_back(*IElemInitRef);
2715       }
2716       ++IRef;
2717       ++IElemInitRef;
2718     }
2719   }
2720   // Get list of lastprivate variables (for taskloops).
2721   llvm::DenseMap<const VarDecl *, const DeclRefExpr *> LastprivateDstsOrigs;
2722   for (const auto *C : S.getClausesOfKind<OMPLastprivateClause>()) {
2723     auto IRef = C->varlist_begin();
2724     auto ID = C->destination_exprs().begin();
2725     for (auto *IInit : C->private_copies()) {
2726       auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2727       if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
2728         Data.LastprivateVars.push_back(*IRef);
2729         Data.LastprivateCopies.push_back(IInit);
2730       }
2731       LastprivateDstsOrigs.insert(
2732           {cast<VarDecl>(cast<DeclRefExpr>(*ID)->getDecl()),
2733            cast<DeclRefExpr>(*IRef)});
2734       ++IRef;
2735       ++ID;
2736     }
2737   }
2738   SmallVector<const Expr *, 4> LHSs;
2739   SmallVector<const Expr *, 4> RHSs;
2740   for (const auto *C : S.getClausesOfKind<OMPReductionClause>()) {
2741     auto IPriv = C->privates().begin();
2742     auto IRed = C->reduction_ops().begin();
2743     auto ILHS = C->lhs_exprs().begin();
2744     auto IRHS = C->rhs_exprs().begin();
2745     for (const auto *Ref : C->varlists()) {
2746       Data.ReductionVars.emplace_back(Ref);
2747       Data.ReductionCopies.emplace_back(*IPriv);
2748       Data.ReductionOps.emplace_back(*IRed);
2749       LHSs.emplace_back(*ILHS);
2750       RHSs.emplace_back(*IRHS);
2751       std::advance(IPriv, 1);
2752       std::advance(IRed, 1);
2753       std::advance(ILHS, 1);
2754       std::advance(IRHS, 1);
2755     }
2756   }
2757   Data.Reductions = CGM.getOpenMPRuntime().emitTaskReductionInit(
2758       *this, S.getLocStart(), LHSs, RHSs, Data);
2759   // Build list of dependences.
2760   for (const auto *C : S.getClausesOfKind<OMPDependClause>())
2761     for (auto *IRef : C->varlists())
2762       Data.Dependences.push_back(std::make_pair(C->getDependencyKind(), IRef));
2763   auto &&CodeGen = [&Data, &S, CS, &BodyGen, &LastprivateDstsOrigs](
2764       CodeGenFunction &CGF, PrePostActionTy &Action) {
2765     // Set proper addresses for generated private copies.
2766     OMPPrivateScope Scope(CGF);
2767     if (!Data.PrivateVars.empty() || !Data.FirstprivateVars.empty() ||
2768         !Data.LastprivateVars.empty()) {
2769       enum { PrivatesParam = 2, CopyFnParam = 3 };
2770       auto *CopyFn = CGF.Builder.CreateLoad(
2771           CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(3)));
2772       auto *PrivatesPtr = CGF.Builder.CreateLoad(
2773           CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(2)));
2774       // Map privates.
2775       llvm::SmallVector<std::pair<const VarDecl *, Address>, 16> PrivatePtrs;
2776       llvm::SmallVector<llvm::Value *, 16> CallArgs;
2777       CallArgs.push_back(PrivatesPtr);
2778       for (auto *E : Data.PrivateVars) {
2779         auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2780         Address PrivatePtr = CGF.CreateMemTemp(
2781             CGF.getContext().getPointerType(E->getType()), ".priv.ptr.addr");
2782         PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
2783         CallArgs.push_back(PrivatePtr.getPointer());
2784       }
2785       for (auto *E : Data.FirstprivateVars) {
2786         auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2787         Address PrivatePtr =
2788             CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
2789                               ".firstpriv.ptr.addr");
2790         PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
2791         CallArgs.push_back(PrivatePtr.getPointer());
2792       }
2793       for (auto *E : Data.LastprivateVars) {
2794         auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2795         Address PrivatePtr =
2796             CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
2797                               ".lastpriv.ptr.addr");
2798         PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
2799         CallArgs.push_back(PrivatePtr.getPointer());
2800       }
2801       CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, S.getLocStart(),
2802                                                           CopyFn, CallArgs);
2803       for (auto &&Pair : LastprivateDstsOrigs) {
2804         auto *OrigVD = cast<VarDecl>(Pair.second->getDecl());
2805         DeclRefExpr DRE(
2806             const_cast<VarDecl *>(OrigVD),
2807             /*RefersToEnclosingVariableOrCapture=*/CGF.CapturedStmtInfo->lookup(
2808                 OrigVD) != nullptr,
2809             Pair.second->getType(), VK_LValue, Pair.second->getExprLoc());
2810         Scope.addPrivate(Pair.first, [&CGF, &DRE]() {
2811           return CGF.EmitLValue(&DRE).getAddress();
2812         });
2813       }
2814       for (auto &&Pair : PrivatePtrs) {
2815         Address Replacement(CGF.Builder.CreateLoad(Pair.second),
2816                             CGF.getContext().getDeclAlign(Pair.first));
2817         Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; });
2818       }
2819     }
2820     if (Data.Reductions) {
2821       OMPLexicalScope LexScope(CGF, S, /*AsInlined=*/true);
2822       ReductionCodeGen RedCG(Data.ReductionVars, Data.ReductionCopies,
2823                              Data.ReductionOps);
2824       llvm::Value *ReductionsPtr = CGF.Builder.CreateLoad(
2825           CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(9)));
2826       for (unsigned Cnt = 0, E = Data.ReductionVars.size(); Cnt < E; ++Cnt) {
2827         RedCG.emitSharedLValue(CGF, Cnt);
2828         RedCG.emitAggregateType(CGF, Cnt);
2829         Address Replacement = CGF.CGM.getOpenMPRuntime().getTaskReductionItem(
2830             CGF, S.getLocStart(), ReductionsPtr, RedCG.getSharedLValue(Cnt));
2831         Replacement =
2832             Address(CGF.EmitScalarConversion(
2833                         Replacement.getPointer(), CGF.getContext().VoidPtrTy,
2834                         CGF.getContext().getPointerType(
2835                             Data.ReductionCopies[Cnt]->getType()),
2836                         SourceLocation()),
2837                     Replacement.getAlignment());
2838         Replacement = RedCG.adjustPrivateAddress(CGF, Cnt, Replacement);
2839         Scope.addPrivate(RedCG.getBaseDecl(Cnt),
2840                          [Replacement]() { return Replacement; });
2841         // FIXME: This must removed once the runtime library is fixed.
2842         // Emit required threadprivate variables for
2843         // initilizer/combiner/finalizer.
2844         CGF.CGM.getOpenMPRuntime().emitTaskReductionFixups(CGF, S.getLocStart(),
2845                                                            RedCG, Cnt);
2846       }
2847     }
2848     // Privatize all private variables except for in_reduction items.
2849     (void)Scope.Privatize();
2850     SmallVector<const Expr *, 4> InRedVars;
2851     SmallVector<const Expr *, 4> InRedPrivs;
2852     SmallVector<const Expr *, 4> InRedOps;
2853     SmallVector<const Expr *, 4> TaskgroupDescriptors;
2854     for (const auto *C : S.getClausesOfKind<OMPInReductionClause>()) {
2855       auto IPriv = C->privates().begin();
2856       auto IRed = C->reduction_ops().begin();
2857       auto ITD = C->taskgroup_descriptors().begin();
2858       for (const auto *Ref : C->varlists()) {
2859         InRedVars.emplace_back(Ref);
2860         InRedPrivs.emplace_back(*IPriv);
2861         InRedOps.emplace_back(*IRed);
2862         TaskgroupDescriptors.emplace_back(*ITD);
2863         std::advance(IPriv, 1);
2864         std::advance(IRed, 1);
2865         std::advance(ITD, 1);
2866       }
2867     }
2868     // Privatize in_reduction items here, because taskgroup descriptors must be
2869     // privatized earlier.
2870     OMPPrivateScope InRedScope(CGF);
2871     if (!InRedVars.empty()) {
2872       ReductionCodeGen RedCG(InRedVars, InRedPrivs, InRedOps);
2873       for (unsigned Cnt = 0, E = InRedVars.size(); Cnt < E; ++Cnt) {
2874         RedCG.emitSharedLValue(CGF, Cnt);
2875         RedCG.emitAggregateType(CGF, Cnt);
2876         // The taskgroup descriptor variable is always implicit firstprivate and
2877         // privatized already during procoessing of the firstprivates.
2878         llvm::Value *ReductionsPtr = CGF.EmitLoadOfScalar(
2879             CGF.EmitLValue(TaskgroupDescriptors[Cnt]), SourceLocation());
2880         Address Replacement = CGF.CGM.getOpenMPRuntime().getTaskReductionItem(
2881             CGF, S.getLocStart(), ReductionsPtr, RedCG.getSharedLValue(Cnt));
2882         Replacement = Address(
2883             CGF.EmitScalarConversion(
2884                 Replacement.getPointer(), CGF.getContext().VoidPtrTy,
2885                 CGF.getContext().getPointerType(InRedPrivs[Cnt]->getType()),
2886                 SourceLocation()),
2887             Replacement.getAlignment());
2888         Replacement = RedCG.adjustPrivateAddress(CGF, Cnt, Replacement);
2889         InRedScope.addPrivate(RedCG.getBaseDecl(Cnt),
2890                               [Replacement]() { return Replacement; });
2891         // FIXME: This must removed once the runtime library is fixed.
2892         // Emit required threadprivate variables for
2893         // initilizer/combiner/finalizer.
2894         CGF.CGM.getOpenMPRuntime().emitTaskReductionFixups(CGF, S.getLocStart(),
2895                                                            RedCG, Cnt);
2896       }
2897     }
2898     (void)InRedScope.Privatize();
2899
2900     Action.Enter(CGF);
2901     BodyGen(CGF);
2902   };
2903   auto *OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction(
2904       S, *I, *PartId, *TaskT, S.getDirectiveKind(), CodeGen, Data.Tied,
2905       Data.NumberOfParts);
2906   OMPLexicalScope Scope(*this, S);
2907   TaskGen(*this, OutlinedFn, Data);
2908 }
2909
2910 static ImplicitParamDecl *
2911 createImplicitFirstprivateForType(ASTContext &C, OMPTaskDataTy &Data,
2912                                   QualType Ty, CapturedDecl *CD) {
2913   auto *OrigVD = ImplicitParamDecl::Create(
2914       C, CD, SourceLocation(), /*Id=*/nullptr, Ty, ImplicitParamDecl::Other);
2915   auto *OrigRef =
2916       DeclRefExpr::Create(C, NestedNameSpecifierLoc(), SourceLocation(), OrigVD,
2917                           /*RefersToEnclosingVariableOrCapture=*/false,
2918                           SourceLocation(), Ty, VK_LValue);
2919   auto *PrivateVD = ImplicitParamDecl::Create(
2920       C, CD, SourceLocation(), /*Id=*/nullptr, Ty, ImplicitParamDecl::Other);
2921   auto *PrivateRef = DeclRefExpr::Create(
2922       C, NestedNameSpecifierLoc(), SourceLocation(), PrivateVD,
2923       /*RefersToEnclosingVariableOrCapture=*/false, SourceLocation(), Ty,
2924       VK_LValue);
2925   QualType ElemType = C.getBaseElementType(Ty);
2926   auto *InitVD =
2927       ImplicitParamDecl::Create(C, CD, SourceLocation(), /*Id=*/nullptr,
2928                                 ElemType, ImplicitParamDecl::Other);
2929   auto *InitRef =
2930       DeclRefExpr::Create(C, NestedNameSpecifierLoc(), SourceLocation(), InitVD,
2931                           /*RefersToEnclosingVariableOrCapture=*/false,
2932                           SourceLocation(), ElemType, VK_LValue);
2933   PrivateVD->setInitStyle(VarDecl::CInit);
2934   PrivateVD->setInit(ImplicitCastExpr::Create(C, ElemType, CK_LValueToRValue,
2935                                               InitRef, /*BasePath=*/nullptr,
2936                                               VK_RValue));
2937   Data.FirstprivateVars.emplace_back(OrigRef);
2938   Data.FirstprivateCopies.emplace_back(PrivateRef);
2939   Data.FirstprivateInits.emplace_back(InitRef);
2940   return OrigVD;
2941 }
2942
2943 void CodeGenFunction::EmitOMPTargetTaskBasedDirective(
2944     const OMPExecutableDirective &S, const RegionCodeGenTy &BodyGen,
2945     OMPTargetDataInfo &InputInfo) {
2946   // Emit outlined function for task construct.
2947   auto CS = S.getCapturedStmt(OMPD_task);
2948   auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
2949   auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
2950   auto *I = CS->getCapturedDecl()->param_begin();
2951   auto *PartId = std::next(I);
2952   auto *TaskT = std::next(I, 4);
2953   OMPTaskDataTy Data;
2954   // The task is not final.
2955   Data.Final.setInt(/*IntVal=*/false);
2956   // Get list of firstprivate variables.
2957   for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
2958     auto IRef = C->varlist_begin();
2959     auto IElemInitRef = C->inits().begin();
2960     for (auto *IInit : C->private_copies()) {
2961       Data.FirstprivateVars.push_back(*IRef);
2962       Data.FirstprivateCopies.push_back(IInit);
2963       Data.FirstprivateInits.push_back(*IElemInitRef);
2964       ++IRef;
2965       ++IElemInitRef;
2966     }
2967   }
2968   OMPPrivateScope TargetScope(*this);
2969   VarDecl *BPVD = nullptr;
2970   VarDecl *PVD = nullptr;
2971   VarDecl *SVD = nullptr;
2972   if (InputInfo.NumberOfTargetItems > 0) {
2973     auto *CD = CapturedDecl::Create(
2974         getContext(), getContext().getTranslationUnitDecl(), /*NumParams=*/0);
2975     llvm::APInt ArrSize(/*numBits=*/32, InputInfo.NumberOfTargetItems);
2976     QualType BaseAndPointersType = getContext().getConstantArrayType(
2977         getContext().VoidPtrTy, ArrSize, ArrayType::Normal,
2978         /*IndexTypeQuals=*/0);
2979     BPVD = createImplicitFirstprivateForType(getContext(), Data,
2980                                              BaseAndPointersType, CD);
2981     PVD = createImplicitFirstprivateForType(getContext(), Data,
2982                                             BaseAndPointersType, CD);
2983     QualType SizesType = getContext().getConstantArrayType(
2984         getContext().getSizeType(), ArrSize, ArrayType::Normal,
2985         /*IndexTypeQuals=*/0);
2986     SVD = createImplicitFirstprivateForType(getContext(), Data, SizesType, CD);
2987     TargetScope.addPrivate(
2988         BPVD, [&InputInfo]() { return InputInfo.BasePointersArray; });
2989     TargetScope.addPrivate(PVD,
2990                            [&InputInfo]() { return InputInfo.PointersArray; });
2991     TargetScope.addPrivate(SVD,
2992                            [&InputInfo]() { return InputInfo.SizesArray; });
2993   }
2994   (void)TargetScope.Privatize();
2995   // Build list of dependences.
2996   for (const auto *C : S.getClausesOfKind<OMPDependClause>())
2997     for (auto *IRef : C->varlists())
2998       Data.Dependences.push_back(std::make_pair(C->getDependencyKind(), IRef));
2999   auto &&CodeGen = [&Data, &S, CS, &BodyGen, BPVD, PVD, SVD,
3000                     &InputInfo](CodeGenFunction &CGF, PrePostActionTy &Action) {
3001     // Set proper addresses for generated private copies.
3002     OMPPrivateScope Scope(CGF);
3003     if (!Data.FirstprivateVars.empty()) {
3004       enum { PrivatesParam = 2, CopyFnParam = 3 };
3005       auto *CopyFn = CGF.Builder.CreateLoad(
3006           CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(3)));
3007       auto *PrivatesPtr = CGF.Builder.CreateLoad(
3008           CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(2)));
3009       // Map privates.
3010       llvm::SmallVector<std::pair<const VarDecl *, Address>, 16> PrivatePtrs;
3011       llvm::SmallVector<llvm::Value *, 16> CallArgs;
3012       CallArgs.push_back(PrivatesPtr);
3013       for (auto *E : Data.FirstprivateVars) {
3014         auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3015         Address PrivatePtr =
3016             CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
3017                               ".firstpriv.ptr.addr");
3018         PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
3019         CallArgs.push_back(PrivatePtr.getPointer());
3020       }
3021       CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, S.getLocStart(),
3022                                                           CopyFn, CallArgs);
3023       for (auto &&Pair : PrivatePtrs) {
3024         Address Replacement(CGF.Builder.CreateLoad(Pair.second),
3025                             CGF.getContext().getDeclAlign(Pair.first));
3026         Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; });
3027       }
3028     }
3029     // Privatize all private variables except for in_reduction items.
3030     (void)Scope.Privatize();
3031     InputInfo.BasePointersArray = CGF.Builder.CreateConstArrayGEP(
3032         CGF.GetAddrOfLocalVar(BPVD), /*Index=*/0, CGF.getPointerSize());
3033     InputInfo.PointersArray = CGF.Builder.CreateConstArrayGEP(
3034         CGF.GetAddrOfLocalVar(PVD), /*Index=*/0, CGF.getPointerSize());
3035     InputInfo.SizesArray = CGF.Builder.CreateConstArrayGEP(
3036         CGF.GetAddrOfLocalVar(SVD), /*Index=*/0, CGF.getSizeSize());
3037
3038     Action.Enter(CGF);
3039     OMPLexicalScope LexScope(CGF, S, /*AsInlined=*/true,
3040                              /*EmitPreInitStmt=*/false);
3041     BodyGen(CGF);
3042   };
3043   auto *OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction(
3044       S, *I, *PartId, *TaskT, S.getDirectiveKind(), CodeGen, /*Tied=*/true,
3045       Data.NumberOfParts);
3046   llvm::APInt TrueOrFalse(32, S.hasClausesOfKind<OMPNowaitClause>() ? 1 : 0);
3047   IntegerLiteral IfCond(getContext(), TrueOrFalse,
3048                         getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
3049                         SourceLocation());
3050
3051   CGM.getOpenMPRuntime().emitTaskCall(*this, S.getLocStart(), S, OutlinedFn,
3052                                       SharedsTy, CapturedStruct, &IfCond, Data);
3053 }
3054
3055 void CodeGenFunction::EmitOMPTaskDirective(const OMPTaskDirective &S) {
3056   // Emit outlined function for task construct.
3057   auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
3058   auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
3059   auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
3060   const Expr *IfCond = nullptr;
3061   for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
3062     if (C->getNameModifier() == OMPD_unknown ||
3063         C->getNameModifier() == OMPD_task) {
3064       IfCond = C->getCondition();
3065       break;
3066     }
3067   }
3068
3069   OMPTaskDataTy Data;
3070   // Check if we should emit tied or untied task.
3071   Data.Tied = !S.getSingleClause<OMPUntiedClause>();
3072   auto &&BodyGen = [CS](CodeGenFunction &CGF, PrePostActionTy &) {
3073     CGF.EmitStmt(CS->getCapturedStmt());
3074   };
3075   auto &&TaskGen = [&S, SharedsTy, CapturedStruct,
3076                     IfCond](CodeGenFunction &CGF, llvm::Value *OutlinedFn,
3077                             const OMPTaskDataTy &Data) {
3078     CGF.CGM.getOpenMPRuntime().emitTaskCall(CGF, S.getLocStart(), S, OutlinedFn,
3079                                             SharedsTy, CapturedStruct, IfCond,
3080                                             Data);
3081   };
3082   EmitOMPTaskBasedDirective(S, BodyGen, TaskGen, Data);
3083 }
3084
3085 void CodeGenFunction::EmitOMPTaskyieldDirective(
3086     const OMPTaskyieldDirective &S) {
3087   CGM.getOpenMPRuntime().emitTaskyieldCall(*this, S.getLocStart());
3088 }
3089
3090 void CodeGenFunction::EmitOMPBarrierDirective(const OMPBarrierDirective &S) {
3091   CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_barrier);
3092 }
3093
3094 void CodeGenFunction::EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S) {
3095   CGM.getOpenMPRuntime().emitTaskwaitCall(*this, S.getLocStart());
3096 }
3097
3098 void CodeGenFunction::EmitOMPTaskgroupDirective(
3099     const OMPTaskgroupDirective &S) {
3100   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3101     Action.Enter(CGF);
3102     if (const Expr *E = S.getReductionRef()) {
3103       SmallVector<const Expr *, 4> LHSs;
3104       SmallVector<const Expr *, 4> RHSs;
3105       OMPTaskDataTy Data;
3106       for (const auto *C : S.getClausesOfKind<OMPTaskReductionClause>()) {
3107         auto IPriv = C->privates().begin();
3108         auto IRed = C->reduction_ops().begin();
3109         auto ILHS = C->lhs_exprs().begin();
3110         auto IRHS = C->rhs_exprs().begin();
3111         for (const auto *Ref : C->varlists()) {
3112           Data.ReductionVars.emplace_back(Ref);
3113           Data.ReductionCopies.emplace_back(*IPriv);
3114           Data.ReductionOps.emplace_back(*IRed);
3115           LHSs.emplace_back(*ILHS);
3116           RHSs.emplace_back(*IRHS);
3117           std::advance(IPriv, 1);
3118           std::advance(IRed, 1);
3119           std::advance(ILHS, 1);
3120           std::advance(IRHS, 1);
3121         }
3122       }
3123       llvm::Value *ReductionDesc =
3124           CGF.CGM.getOpenMPRuntime().emitTaskReductionInit(CGF, S.getLocStart(),
3125                                                            LHSs, RHSs, Data);
3126       const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3127       CGF.EmitVarDecl(*VD);
3128       CGF.EmitStoreOfScalar(ReductionDesc, CGF.GetAddrOfLocalVar(VD),
3129                             /*Volatile=*/false, E->getType());
3130     }
3131     CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
3132   };
3133   OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
3134   CGM.getOpenMPRuntime().emitTaskgroupRegion(*this, CodeGen, S.getLocStart());
3135 }
3136
3137 void CodeGenFunction::EmitOMPFlushDirective(const OMPFlushDirective &S) {
3138   CGM.getOpenMPRuntime().emitFlush(*this, [&]() -> ArrayRef<const Expr *> {
3139     if (const auto *FlushClause = S.getSingleClause<OMPFlushClause>()) {
3140       return llvm::makeArrayRef(FlushClause->varlist_begin(),
3141                                 FlushClause->varlist_end());
3142     }
3143     return llvm::None;
3144   }(), S.getLocStart());
3145 }
3146
3147 void CodeGenFunction::EmitOMPDistributeLoop(const OMPLoopDirective &S,
3148                                             const CodeGenLoopTy &CodeGenLoop,
3149                                             Expr *IncExpr) {
3150   // Emit the loop iteration variable.
3151   auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
3152   auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
3153   EmitVarDecl(*IVDecl);
3154
3155   // Emit the iterations count variable.
3156   // If it is not a variable, Sema decided to calculate iterations count on each
3157   // iteration (e.g., it is foldable into a constant).
3158   if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
3159     EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
3160     // Emit calculation of the iterations count.
3161     EmitIgnoredExpr(S.getCalcLastIteration());
3162   }
3163
3164   auto &RT = CGM.getOpenMPRuntime();
3165
3166   bool HasLastprivateClause = false;
3167   // Check pre-condition.
3168   {
3169     OMPLoopScope PreInitScope(*this, S);
3170     // Skip the entire loop if we don't meet the precondition.
3171     // If the condition constant folds and can be elided, avoid emitting the
3172     // whole loop.
3173     bool CondConstant;
3174     llvm::BasicBlock *ContBlock = nullptr;
3175     if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
3176       if (!CondConstant)
3177         return;
3178     } else {
3179       auto *ThenBlock = createBasicBlock("omp.precond.then");
3180       ContBlock = createBasicBlock("omp.precond.end");
3181       emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
3182                   getProfileCount(&S));
3183       EmitBlock(ThenBlock);
3184       incrementProfileCounter(&S);
3185     }
3186
3187     emitAlignedClause(*this, S);
3188     // Emit 'then' code.
3189     {
3190       // Emit helper vars inits.
3191
3192       LValue LB = EmitOMPHelperVar(
3193           *this, cast<DeclRefExpr>(
3194                      (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3195                           ? S.getCombinedLowerBoundVariable()
3196                           : S.getLowerBoundVariable())));
3197       LValue UB = EmitOMPHelperVar(
3198           *this, cast<DeclRefExpr>(
3199                      (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3200                           ? S.getCombinedUpperBoundVariable()
3201                           : S.getUpperBoundVariable())));
3202       LValue ST =
3203           EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
3204       LValue IL =
3205           EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
3206
3207       OMPPrivateScope LoopScope(*this);
3208       if (EmitOMPFirstprivateClause(S, LoopScope)) {
3209         // Emit implicit barrier to synchronize threads and avoid data races
3210         // on initialization of firstprivate variables and post-update of
3211         // lastprivate variables.
3212         CGM.getOpenMPRuntime().emitBarrierCall(
3213             *this, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
3214             /*ForceSimpleCall=*/true);
3215       }
3216       EmitOMPPrivateClause(S, LoopScope);
3217       if (isOpenMPSimdDirective(S.getDirectiveKind()) &&
3218           !isOpenMPParallelDirective(S.getDirectiveKind()) &&
3219           !isOpenMPTeamsDirective(S.getDirectiveKind()))
3220         EmitOMPReductionClauseInit(S, LoopScope);
3221       HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
3222       EmitOMPPrivateLoopCounters(S, LoopScope);
3223       (void)LoopScope.Privatize();
3224
3225       // Detect the distribute schedule kind and chunk.
3226       llvm::Value *Chunk = nullptr;
3227       OpenMPDistScheduleClauseKind ScheduleKind = OMPC_DIST_SCHEDULE_unknown;
3228       if (auto *C = S.getSingleClause<OMPDistScheduleClause>()) {
3229         ScheduleKind = C->getDistScheduleKind();
3230         if (const auto *Ch = C->getChunkSize()) {
3231           Chunk = EmitScalarExpr(Ch);
3232           Chunk = EmitScalarConversion(Chunk, Ch->getType(),
3233                                        S.getIterationVariable()->getType(),
3234                                        S.getLocStart());
3235         }
3236       }
3237       const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
3238       const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
3239
3240       // OpenMP [2.10.8, distribute Construct, Description]
3241       // If dist_schedule is specified, kind must be static. If specified,
3242       // iterations are divided into chunks of size chunk_size, chunks are
3243       // assigned to the teams of the league in a round-robin fashion in the
3244       // order of the team number. When no chunk_size is specified, the
3245       // iteration space is divided into chunks that are approximately equal
3246       // in size, and at most one chunk is distributed to each team of the
3247       // league. The size of the chunks is unspecified in this case.
3248       if (RT.isStaticNonchunked(ScheduleKind,
3249                                 /* Chunked */ Chunk != nullptr)) {
3250         if (isOpenMPSimdDirective(S.getDirectiveKind()))
3251           EmitOMPSimdInit(S, /*IsMonotonic=*/true);
3252         CGOpenMPRuntime::StaticRTInput StaticInit(
3253             IVSize, IVSigned, /* Ordered = */ false, IL.getAddress(),
3254             LB.getAddress(), UB.getAddress(), ST.getAddress());
3255         RT.emitDistributeStaticInit(*this, S.getLocStart(), ScheduleKind,
3256                                     StaticInit);
3257         auto LoopExit =
3258             getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
3259         // UB = min(UB, GlobalUB);
3260         EmitIgnoredExpr(isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3261                             ? S.getCombinedEnsureUpperBound()
3262                             : S.getEnsureUpperBound());
3263         // IV = LB;
3264         EmitIgnoredExpr(isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3265                             ? S.getCombinedInit()
3266                             : S.getInit());
3267
3268         Expr *Cond = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3269                          ? S.getCombinedCond()
3270                          : S.getCond();
3271
3272         // for distribute alone,  codegen
3273         // while (idx <= UB) { BODY; ++idx; }
3274         // when combined with 'for' (e.g. as in 'distribute parallel for')
3275         // while (idx <= UB) { <CodeGen rest of pragma>; idx += ST; }
3276         EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), Cond, IncExpr,
3277                          [&S, LoopExit, &CodeGenLoop](CodeGenFunction &CGF) {
3278                            CodeGenLoop(CGF, S, LoopExit);
3279                          },
3280                          [](CodeGenFunction &) {});
3281         EmitBlock(LoopExit.getBlock());
3282         // Tell the runtime we are done.
3283         RT.emitForStaticFinish(*this, S.getLocStart(), S.getDirectiveKind());
3284       } else {
3285         // Emit the outer loop, which requests its work chunk [LB..UB] from
3286         // runtime and runs the inner loop to process it.
3287         const OMPLoopArguments LoopArguments = {
3288             LB.getAddress(), UB.getAddress(), ST.getAddress(), IL.getAddress(),
3289             Chunk};
3290         EmitOMPDistributeOuterLoop(ScheduleKind, S, LoopScope, LoopArguments,
3291                                    CodeGenLoop);
3292       }
3293       if (isOpenMPSimdDirective(S.getDirectiveKind())) {
3294         EmitOMPSimdFinal(S, [&](CodeGenFunction &CGF) -> llvm::Value * {
3295           return CGF.Builder.CreateIsNotNull(
3296               CGF.EmitLoadOfScalar(IL, S.getLocStart()));
3297         });
3298       }
3299       OpenMPDirectiveKind ReductionKind = OMPD_unknown;
3300       if (isOpenMPParallelDirective(S.getDirectiveKind()) &&
3301           isOpenMPSimdDirective(S.getDirectiveKind())) {
3302         ReductionKind = OMPD_parallel_for_simd;
3303       } else if (isOpenMPParallelDirective(S.getDirectiveKind())) {
3304         ReductionKind = OMPD_parallel_for;
3305       } else if (isOpenMPSimdDirective(S.getDirectiveKind())) {
3306         ReductionKind = OMPD_simd;
3307       } else if (!isOpenMPTeamsDirective(S.getDirectiveKind()) &&
3308                  S.hasClausesOfKind<OMPReductionClause>()) {
3309         llvm_unreachable(
3310             "No reduction clauses is allowed in distribute directive.");
3311       }
3312       EmitOMPReductionClauseFinal(S, ReductionKind);
3313       // Emit post-update of the reduction variables if IsLastIter != 0.
3314       emitPostUpdateForReductionClause(
3315           *this, S, [&](CodeGenFunction &CGF) -> llvm::Value * {
3316             return CGF.Builder.CreateIsNotNull(
3317                 CGF.EmitLoadOfScalar(IL, S.getLocStart()));
3318           });
3319       // Emit final copy of the lastprivate variables if IsLastIter != 0.
3320       if (HasLastprivateClause) {
3321         EmitOMPLastprivateClauseFinal(
3322             S, /*NoFinals=*/false,
3323             Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getLocStart())));
3324       }
3325     }
3326
3327     // We're now done with the loop, so jump to the continuation block.
3328     if (ContBlock) {
3329       EmitBranch(ContBlock);
3330       EmitBlock(ContBlock, true);
3331     }
3332   }
3333 }
3334
3335 void CodeGenFunction::EmitOMPDistributeDirective(
3336     const OMPDistributeDirective &S) {
3337   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
3338
3339     CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
3340   };
3341   OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
3342   CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen);
3343 }
3344
3345 static llvm::Function *emitOutlinedOrderedFunction(CodeGenModule &CGM,
3346                                                    const CapturedStmt *S) {
3347   CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
3348   CodeGenFunction::CGCapturedStmtInfo CapStmtInfo;
3349   CGF.CapturedStmtInfo = &CapStmtInfo;
3350   auto *Fn = CGF.GenerateOpenMPCapturedStmtFunction(*S);
3351   Fn->addFnAttr(llvm::Attribute::NoInline);
3352   return Fn;
3353 }
3354
3355 void CodeGenFunction::EmitOMPOrderedDirective(const OMPOrderedDirective &S) {
3356   if (!S.getAssociatedStmt()) {
3357     for (const auto *DC : S.getClausesOfKind<OMPDependClause>())
3358       CGM.getOpenMPRuntime().emitDoacrossOrdered(*this, DC);
3359     return;
3360   }
3361   auto *C = S.getSingleClause<OMPSIMDClause>();
3362   auto &&CodeGen = [&S, C, this](CodeGenFunction &CGF,
3363                                  PrePostActionTy &Action) {
3364     if (C) {
3365       auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
3366       llvm::SmallVector<llvm::Value *, 16> CapturedVars;
3367       CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
3368       auto *OutlinedFn = emitOutlinedOrderedFunction(CGM, CS);
3369       CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, S.getLocStart(),
3370                                                       OutlinedFn, CapturedVars);
3371     } else {
3372       Action.Enter(CGF);
3373       CGF.EmitStmt(
3374           cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
3375     }
3376   };
3377   OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
3378   CGM.getOpenMPRuntime().emitOrderedRegion(*this, CodeGen, S.getLocStart(), !C);
3379 }
3380
3381 static llvm::Value *convertToScalarValue(CodeGenFunction &CGF, RValue Val,
3382                                          QualType SrcType, QualType DestType,
3383                                          SourceLocation Loc) {
3384   assert(CGF.hasScalarEvaluationKind(DestType) &&
3385          "DestType must have scalar evaluation kind.");
3386   assert(!Val.isAggregate() && "Must be a scalar or complex.");
3387   return Val.isScalar()
3388              ? CGF.EmitScalarConversion(Val.getScalarVal(), SrcType, DestType,
3389                                         Loc)
3390              : CGF.EmitComplexToScalarConversion(Val.getComplexVal(), SrcType,
3391                                                  DestType, Loc);
3392 }
3393
3394 static CodeGenFunction::ComplexPairTy
3395 convertToComplexValue(CodeGenFunction &CGF, RValue Val, QualType SrcType,
3396                       QualType DestType, SourceLocation Loc) {
3397   assert(CGF.getEvaluationKind(DestType) == TEK_Complex &&
3398          "DestType must have complex evaluation kind.");
3399   CodeGenFunction::ComplexPairTy ComplexVal;
3400   if (Val.isScalar()) {
3401     // Convert the input element to the element type of the complex.
3402     auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
3403     auto ScalarVal = CGF.EmitScalarConversion(Val.getScalarVal(), SrcType,
3404                                               DestElementType, Loc);
3405     ComplexVal = CodeGenFunction::ComplexPairTy(
3406         ScalarVal, llvm::Constant::getNullValue(ScalarVal->getType()));
3407   } else {
3408     assert(Val.isComplex() && "Must be a scalar or complex.");
3409     auto SrcElementType = SrcType->castAs<ComplexType>()->getElementType();
3410     auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
3411     ComplexVal.first = CGF.EmitScalarConversion(
3412         Val.getComplexVal().first, SrcElementType, DestElementType, Loc);
3413     ComplexVal.second = CGF.EmitScalarConversion(
3414         Val.getComplexVal().second, SrcElementType, DestElementType, Loc);
3415   }
3416   return ComplexVal;
3417 }
3418
3419 static void emitSimpleAtomicStore(CodeGenFunction &CGF, bool IsSeqCst,
3420                                   LValue LVal, RValue RVal) {
3421   if (LVal.isGlobalReg()) {
3422     CGF.EmitStoreThroughGlobalRegLValue(RVal, LVal);
3423   } else {
3424     CGF.EmitAtomicStore(RVal, LVal,
3425                         IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3426                                  : llvm::AtomicOrdering::Monotonic,
3427                         LVal.isVolatile(), /*IsInit=*/false);
3428   }
3429 }
3430
3431 void CodeGenFunction::emitOMPSimpleStore(LValue LVal, RValue RVal,
3432                                          QualType RValTy, SourceLocation Loc) {
3433   switch (getEvaluationKind(LVal.getType())) {
3434   case TEK_Scalar:
3435     EmitStoreThroughLValue(RValue::get(convertToScalarValue(
3436                                *this, RVal, RValTy, LVal.getType(), Loc)),
3437                            LVal);
3438     break;
3439   case TEK_Complex:
3440     EmitStoreOfComplex(
3441         convertToComplexValue(*this, RVal, RValTy, LVal.getType(), Loc), LVal,
3442         /*isInit=*/false);
3443     break;
3444   case TEK_Aggregate:
3445     llvm_unreachable("Must be a scalar or complex.");
3446   }
3447 }
3448
3449 static void EmitOMPAtomicReadExpr(CodeGenFunction &CGF, bool IsSeqCst,
3450                                   const Expr *X, const Expr *V,
3451                                   SourceLocation Loc) {
3452   // v = x;
3453   assert(V->isLValue() && "V of 'omp atomic read' is not lvalue");
3454   assert(X->isLValue() && "X of 'omp atomic read' is not lvalue");
3455   LValue XLValue = CGF.EmitLValue(X);
3456   LValue VLValue = CGF.EmitLValue(V);
3457   RValue Res = XLValue.isGlobalReg()
3458                    ? CGF.EmitLoadOfLValue(XLValue, Loc)
3459                    : CGF.EmitAtomicLoad(
3460                          XLValue, Loc,
3461                          IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3462                                   : llvm::AtomicOrdering::Monotonic,
3463                          XLValue.isVolatile());
3464   // OpenMP, 2.12.6, atomic Construct
3465   // Any atomic construct with a seq_cst clause forces the atomically
3466   // performed operation to include an implicit flush operation without a
3467   // list.
3468   if (IsSeqCst)
3469     CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3470   CGF.emitOMPSimpleStore(VLValue, Res, X->getType().getNonReferenceType(), Loc);
3471 }
3472
3473 static void EmitOMPAtomicWriteExpr(CodeGenFunction &CGF, bool IsSeqCst,
3474                                    const Expr *X, const Expr *E,
3475                                    SourceLocation Loc) {
3476   // x = expr;
3477   assert(X->isLValue() && "X of 'omp atomic write' is not lvalue");
3478   emitSimpleAtomicStore(CGF, IsSeqCst, CGF.EmitLValue(X), CGF.EmitAnyExpr(E));
3479   // OpenMP, 2.12.6, atomic Construct
3480   // Any atomic construct with a seq_cst clause forces the atomically
3481   // performed operation to include an implicit flush operation without a
3482   // list.
3483   if (IsSeqCst)
3484     CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3485 }
3486
3487 static std::pair<bool, RValue> emitOMPAtomicRMW(CodeGenFunction &CGF, LValue X,
3488                                                 RValue Update,
3489                                                 BinaryOperatorKind BO,
3490                                                 llvm::AtomicOrdering AO,
3491                                                 bool IsXLHSInRHSPart) {
3492   auto &Context = CGF.CGM.getContext();
3493   // Allow atomicrmw only if 'x' and 'update' are integer values, lvalue for 'x'
3494   // expression is simple and atomic is allowed for the given type for the
3495   // target platform.
3496   if (BO == BO_Comma || !Update.isScalar() ||
3497       !Update.getScalarVal()->getType()->isIntegerTy() ||
3498       !X.isSimple() || (!isa<llvm::ConstantInt>(Update.getScalarVal()) &&
3499                         (Update.getScalarVal()->getType() !=
3500                          X.getAddress().getElementType())) ||
3501       !X.getAddress().getElementType()->isIntegerTy() ||
3502       !Context.getTargetInfo().hasBuiltinAtomic(
3503           Context.getTypeSize(X.getType()), Context.toBits(X.getAlignment())))
3504     return std::make_pair(false, RValue::get(nullptr));
3505
3506   llvm::AtomicRMWInst::BinOp RMWOp;
3507   switch (BO) {
3508   case BO_Add:
3509     RMWOp = llvm::AtomicRMWInst::Add;
3510     break;
3511   case BO_Sub:
3512     if (!IsXLHSInRHSPart)
3513       return std::make_pair(false, RValue::get(nullptr));
3514     RMWOp = llvm::AtomicRMWInst::Sub;
3515     break;
3516   case BO_And:
3517     RMWOp = llvm::AtomicRMWInst::And;
3518     break;
3519   case BO_Or:
3520     RMWOp = llvm::AtomicRMWInst::Or;
3521     break;
3522   case BO_Xor:
3523     RMWOp = llvm::AtomicRMWInst::Xor;
3524     break;
3525   case BO_LT:
3526     RMWOp = X.getType()->hasSignedIntegerRepresentation()
3527                 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Min
3528                                    : llvm::AtomicRMWInst::Max)
3529                 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMin
3530                                    : llvm::AtomicRMWInst::UMax);
3531     break;
3532   case BO_GT:
3533     RMWOp = X.getType()->hasSignedIntegerRepresentation()
3534                 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Max
3535                                    : llvm::AtomicRMWInst::Min)
3536                 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMax
3537                                    : llvm::AtomicRMWInst::UMin);
3538     break;
3539   case BO_Assign:
3540     RMWOp = llvm::AtomicRMWInst::Xchg;
3541     break;
3542   case BO_Mul:
3543   case BO_Div:
3544   case BO_Rem:
3545   case BO_Shl:
3546   case BO_Shr:
3547   case BO_LAnd:
3548   case BO_LOr:
3549     return std::make_pair(false, RValue::get(nullptr));
3550   case BO_PtrMemD:
3551   case BO_PtrMemI:
3552   case BO_LE:
3553   case BO_GE:
3554   case BO_EQ:
3555   case BO_NE:
3556   case BO_Cmp:
3557   case BO_AddAssign:
3558   case BO_SubAssign:
3559   case BO_AndAssign:
3560   case BO_OrAssign:
3561   case BO_XorAssign:
3562   case BO_MulAssign:
3563   case BO_DivAssign:
3564   case BO_RemAssign:
3565   case BO_ShlAssign:
3566   case BO_ShrAssign:
3567   case BO_Comma:
3568     llvm_unreachable("Unsupported atomic update operation");
3569   }
3570   auto *UpdateVal = Update.getScalarVal();
3571   if (auto *IC = dyn_cast<llvm::ConstantInt>(UpdateVal)) {
3572     UpdateVal = CGF.Builder.CreateIntCast(
3573         IC, X.getAddress().getElementType(),
3574         X.getType()->hasSignedIntegerRepresentation());
3575   }
3576   auto *Res = CGF.Builder.CreateAtomicRMW(RMWOp, X.getPointer(), UpdateVal, AO);
3577   return std::make_pair(true, RValue::get(Res));
3578 }
3579
3580 std::pair<bool, RValue> CodeGenFunction::EmitOMPAtomicSimpleUpdateExpr(
3581     LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
3582     llvm::AtomicOrdering AO, SourceLocation Loc,
3583     const llvm::function_ref<RValue(RValue)> &CommonGen) {
3584   // Update expressions are allowed to have the following forms:
3585   // x binop= expr; -> xrval + expr;
3586   // x++, ++x -> xrval + 1;
3587   // x--, --x -> xrval - 1;
3588   // x = x binop expr; -> xrval binop expr
3589   // x = expr Op x; - > expr binop xrval;
3590   auto Res = emitOMPAtomicRMW(*this, X, E, BO, AO, IsXLHSInRHSPart);
3591   if (!Res.first) {
3592     if (X.isGlobalReg()) {
3593       // Emit an update expression: 'xrval' binop 'expr' or 'expr' binop
3594       // 'xrval'.
3595       EmitStoreThroughLValue(CommonGen(EmitLoadOfLValue(X, Loc)), X);
3596     } else {
3597       // Perform compare-and-swap procedure.
3598       EmitAtomicUpdate(X, AO, CommonGen, X.getType().isVolatileQualified());
3599     }
3600   }
3601   return Res;
3602 }
3603
3604 static void EmitOMPAtomicUpdateExpr(CodeGenFunction &CGF, bool IsSeqCst,
3605                                     const Expr *X, const Expr *E,
3606                                     const Expr *UE, bool IsXLHSInRHSPart,
3607                                     SourceLocation Loc) {
3608   assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
3609          "Update expr in 'atomic update' must be a binary operator.");
3610   auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
3611   // Update expressions are allowed to have the following forms:
3612   // x binop= expr; -> xrval + expr;
3613   // x++, ++x -> xrval + 1;
3614   // x--, --x -> xrval - 1;
3615   // x = x binop expr; -> xrval binop expr
3616   // x = expr Op x; - > expr binop xrval;
3617   assert(X->isLValue() && "X of 'omp atomic update' is not lvalue");
3618   LValue XLValue = CGF.EmitLValue(X);
3619   RValue ExprRValue = CGF.EmitAnyExpr(E);
3620   auto AO = IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3621                      : llvm::AtomicOrdering::Monotonic;
3622   auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
3623   auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
3624   auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
3625   auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
3626   auto Gen =
3627       [&CGF, UE, ExprRValue, XRValExpr, ERValExpr](RValue XRValue) -> RValue {
3628         CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3629         CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
3630         return CGF.EmitAnyExpr(UE);
3631       };
3632   (void)CGF.EmitOMPAtomicSimpleUpdateExpr(
3633       XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
3634   // OpenMP, 2.12.6, atomic Construct
3635   // Any atomic construct with a seq_cst clause forces the atomically
3636   // performed operation to include an implicit flush operation without a
3637   // list.
3638   if (IsSeqCst)
3639     CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3640 }
3641
3642 static RValue convertToType(CodeGenFunction &CGF, RValue Value,
3643                             QualType SourceType, QualType ResType,
3644                             SourceLocation Loc) {
3645   switch (CGF.getEvaluationKind(ResType)) {
3646   case TEK_Scalar:
3647     return RValue::get(
3648         convertToScalarValue(CGF, Value, SourceType, ResType, Loc));
3649   case TEK_Complex: {
3650     auto Res = convertToComplexValue(CGF, Value, SourceType, ResType, Loc);
3651     return RValue::getComplex(Res.first, Res.second);
3652   }
3653   case TEK_Aggregate:
3654     break;
3655   }
3656   llvm_unreachable("Must be a scalar or complex.");
3657 }
3658
3659 static void EmitOMPAtomicCaptureExpr(CodeGenFunction &CGF, bool IsSeqCst,
3660                                      bool IsPostfixUpdate, const Expr *V,
3661                                      const Expr *X, const Expr *E,
3662                                      const Expr *UE, bool IsXLHSInRHSPart,
3663                                      SourceLocation Loc) {
3664   assert(X->isLValue() && "X of 'omp atomic capture' is not lvalue");
3665   assert(V->isLValue() && "V of 'omp atomic capture' is not lvalue");
3666   RValue NewVVal;
3667   LValue VLValue = CGF.EmitLValue(V);
3668   LValue XLValue = CGF.EmitLValue(X);
3669   RValue ExprRValue = CGF.EmitAnyExpr(E);
3670   auto AO = IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3671                      : llvm::AtomicOrdering::Monotonic;
3672   QualType NewVValType;
3673   if (UE) {
3674     // 'x' is updated with some additional value.
3675     assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
3676            "Update expr in 'atomic capture' must be a binary operator.");
3677     auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
3678     // Update expressions are allowed to have the following forms:
3679     // x binop= expr; -> xrval + expr;
3680     // x++, ++x -> xrval + 1;
3681     // x--, --x -> xrval - 1;
3682     // x = x binop expr; -> xrval binop expr
3683     // x = expr Op x; - > expr binop xrval;
3684     auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
3685     auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
3686     auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
3687     NewVValType = XRValExpr->getType();
3688     auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
3689     auto &&Gen = [&CGF, &NewVVal, UE, ExprRValue, XRValExpr, ERValExpr,
3690                   IsPostfixUpdate](RValue XRValue) -> RValue {
3691       CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3692       CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
3693       RValue Res = CGF.EmitAnyExpr(UE);
3694       NewVVal = IsPostfixUpdate ? XRValue : Res;
3695       return Res;
3696     };
3697     auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
3698         XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
3699     if (Res.first) {
3700       // 'atomicrmw' instruction was generated.
3701       if (IsPostfixUpdate) {
3702         // Use old value from 'atomicrmw'.
3703         NewVVal = Res.second;
3704       } else {
3705         // 'atomicrmw' does not provide new value, so evaluate it using old
3706         // value of 'x'.
3707         CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3708         CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, Res.second);
3709         NewVVal = CGF.EmitAnyExpr(UE);
3710       }
3711     }
3712   } else {
3713     // 'x' is simply rewritten with some 'expr'.
3714     NewVValType = X->getType().getNonReferenceType();
3715     ExprRValue = convertToType(CGF, ExprRValue, E->getType(),
3716                                X->getType().getNonReferenceType(), Loc);
3717     auto &&Gen = [&NewVVal, ExprRValue](RValue XRValue) -> RValue {
3718       NewVVal = XRValue;
3719       return ExprRValue;
3720     };
3721     // Try to perform atomicrmw xchg, otherwise simple exchange.
3722     auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
3723         XLValue, ExprRValue, /*BO=*/BO_Assign, /*IsXLHSInRHSPart=*/false, AO,
3724         Loc, Gen);
3725     if (Res.first) {
3726       // 'atomicrmw' instruction was generated.
3727       NewVVal = IsPostfixUpdate ? Res.second : ExprRValue;
3728     }
3729   }
3730   // Emit post-update store to 'v' of old/new 'x' value.
3731   CGF.emitOMPSimpleStore(VLValue, NewVVal, NewVValType, Loc);
3732   // OpenMP, 2.12.6, atomic Construct
3733   // Any atomic construct with a seq_cst clause forces the atomically
3734   // performed operation to include an implicit flush operation without a
3735   // list.
3736   if (IsSeqCst)
3737     CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3738 }
3739
3740 static void EmitOMPAtomicExpr(CodeGenFunction &CGF, OpenMPClauseKind Kind,
3741                               bool IsSeqCst, bool IsPostfixUpdate,
3742                               const Expr *X, const Expr *V, const Expr *E,
3743                               const Expr *UE, bool IsXLHSInRHSPart,
3744                               SourceLocation Loc) {
3745   switch (Kind) {
3746   case OMPC_read:
3747     EmitOMPAtomicReadExpr(CGF, IsSeqCst, X, V, Loc);
3748     break;
3749   case OMPC_write:
3750     EmitOMPAtomicWriteExpr(CGF, IsSeqCst, X, E, Loc);
3751     break;
3752   case OMPC_unknown:
3753   case OMPC_update:
3754     EmitOMPAtomicUpdateExpr(CGF, IsSeqCst, X, E, UE, IsXLHSInRHSPart, Loc);
3755     break;
3756   case OMPC_capture:
3757     EmitOMPAtomicCaptureExpr(CGF, IsSeqCst, IsPostfixUpdate, V, X, E, UE,
3758                              IsXLHSInRHSPart, Loc);
3759     break;
3760   case OMPC_if:
3761   case OMPC_final:
3762   case OMPC_num_threads:
3763   case OMPC_private:
3764   case OMPC_firstprivate:
3765   case OMPC_lastprivate:
3766   case OMPC_reduction:
3767   case OMPC_task_reduction:
3768   case OMPC_in_reduction:
3769   case OMPC_safelen:
3770   case OMPC_simdlen:
3771   case OMPC_collapse:
3772   case OMPC_default:
3773   case OMPC_seq_cst:
3774   case OMPC_shared:
3775   case OMPC_linear:
3776   case OMPC_aligned:
3777   case OMPC_copyin:
3778   case OMPC_copyprivate:
3779   case OMPC_flush:
3780   case OMPC_proc_bind:
3781   case OMPC_schedule:
3782   case OMPC_ordered:
3783   case OMPC_nowait:
3784   case OMPC_untied:
3785   case OMPC_threadprivate:
3786   case OMPC_depend:
3787   case OMPC_mergeable:
3788   case OMPC_device:
3789   case OMPC_threads:
3790   case OMPC_simd:
3791   case OMPC_map:
3792   case OMPC_num_teams:
3793   case OMPC_thread_limit:
3794   case OMPC_priority:
3795   case OMPC_grainsize:
3796   case OMPC_nogroup:
3797   case OMPC_num_tasks:
3798   case OMPC_hint:
3799   case OMPC_dist_schedule:
3800   case OMPC_defaultmap:
3801   case OMPC_uniform:
3802   case OMPC_to:
3803   case OMPC_from:
3804   case OMPC_use_device_ptr:
3805   case OMPC_is_device_ptr:
3806     llvm_unreachable("Clause is not allowed in 'omp atomic'.");
3807   }
3808 }
3809
3810 void CodeGenFunction::EmitOMPAtomicDirective(const OMPAtomicDirective &S) {
3811   bool IsSeqCst = S.getSingleClause<OMPSeqCstClause>();
3812   OpenMPClauseKind Kind = OMPC_unknown;
3813   for (auto *C : S.clauses()) {
3814     // Find first clause (skip seq_cst clause, if it is first).
3815     if (C->getClauseKind() != OMPC_seq_cst) {
3816       Kind = C->getClauseKind();
3817       break;
3818     }
3819   }
3820
3821   const auto *CS =
3822       S.getAssociatedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
3823   if (const auto *EWC = dyn_cast<ExprWithCleanups>(CS)) {
3824     enterFullExpression(EWC);
3825   }
3826   // Processing for statements under 'atomic capture'.
3827   if (const auto *Compound = dyn_cast<CompoundStmt>(CS)) {
3828     for (const auto *C : Compound->body()) {
3829       if (const auto *EWC = dyn_cast<ExprWithCleanups>(C)) {
3830         enterFullExpression(EWC);
3831       }
3832     }
3833   }
3834
3835   auto &&CodeGen = [&S, Kind, IsSeqCst, CS](CodeGenFunction &CGF,
3836                                             PrePostActionTy &) {
3837     CGF.EmitStopPoint(CS);
3838     EmitOMPAtomicExpr(CGF, Kind, IsSeqCst, S.isPostfixUpdate(), S.getX(),
3839                       S.getV(), S.getExpr(), S.getUpdateExpr(),
3840                       S.isXLHSInRHSPart(), S.getLocStart());
3841   };
3842   OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
3843   CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_atomic, CodeGen);
3844 }
3845
3846 static void emitCommonOMPTargetDirective(CodeGenFunction &CGF,
3847                                          const OMPExecutableDirective &S,
3848                                          const RegionCodeGenTy &CodeGen) {
3849   assert(isOpenMPTargetExecutionDirective(S.getDirectiveKind()));
3850   CodeGenModule &CGM = CGF.CGM;
3851   const CapturedStmt &CS = *S.getCapturedStmt(OMPD_target);
3852
3853   llvm::Function *Fn = nullptr;
3854   llvm::Constant *FnID = nullptr;
3855
3856   const Expr *IfCond = nullptr;
3857   // Check for the at most one if clause associated with the target region.
3858   for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
3859     if (C->getNameModifier() == OMPD_unknown ||
3860         C->getNameModifier() == OMPD_target) {
3861       IfCond = C->getCondition();
3862       break;
3863     }
3864   }
3865
3866   // Check if we have any device clause associated with the directive.
3867   const Expr *Device = nullptr;
3868   if (auto *C = S.getSingleClause<OMPDeviceClause>()) {
3869     Device = C->getDevice();
3870   }
3871
3872   // Check if we have an if clause whose conditional always evaluates to false
3873   // or if we do not have any targets specified. If so the target region is not
3874   // an offload entry point.
3875   bool IsOffloadEntry = true;
3876   if (IfCond) {
3877     bool Val;
3878     if (CGF.ConstantFoldsToSimpleInteger(IfCond, Val) && !Val)
3879       IsOffloadEntry = false;
3880   }
3881   if (CGM.getLangOpts().OMPTargetTriples.empty())
3882     IsOffloadEntry = false;
3883
3884   assert(CGF.CurFuncDecl && "No parent declaration for target region!");
3885   StringRef ParentName;
3886   // In case we have Ctors/Dtors we use the complete type variant to produce
3887   // the mangling of the device outlined kernel.
3888   if (auto *D = dyn_cast<CXXConstructorDecl>(CGF.CurFuncDecl))
3889     ParentName = CGM.getMangledName(GlobalDecl(D, Ctor_Complete));
3890   else if (auto *D = dyn_cast<CXXDestructorDecl>(CGF.CurFuncDecl))
3891     ParentName = CGM.getMangledName(GlobalDecl(D, Dtor_Complete));
3892   else
3893     ParentName =
3894         CGM.getMangledName(GlobalDecl(cast<FunctionDecl>(CGF.CurFuncDecl)));
3895
3896   // Emit target region as a standalone region.
3897   CGM.getOpenMPRuntime().emitTargetOutlinedFunction(S, ParentName, Fn, FnID,
3898                                                     IsOffloadEntry, CodeGen);
3899   OMPLexicalScope Scope(CGF, S);
3900   llvm::SmallVector<llvm::Value *, 16> CapturedVars;
3901   CGF.GenerateOpenMPCapturedVars(CS, CapturedVars);
3902   CGM.getOpenMPRuntime().emitTargetCall(CGF, S, Fn, FnID, IfCond, Device,
3903                                         CapturedVars);
3904 }
3905
3906 static void emitTargetRegion(CodeGenFunction &CGF, const OMPTargetDirective &S,
3907                              PrePostActionTy &Action) {
3908   CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
3909   (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
3910   CGF.EmitOMPPrivateClause(S, PrivateScope);
3911   (void)PrivateScope.Privatize();
3912
3913   Action.Enter(CGF);
3914   CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
3915 }
3916
3917 void CodeGenFunction::EmitOMPTargetDeviceFunction(CodeGenModule &CGM,
3918                                                   StringRef ParentName,
3919                                                   const OMPTargetDirective &S) {
3920   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3921     emitTargetRegion(CGF, S, Action);
3922   };
3923   llvm::Function *Fn;
3924   llvm::Constant *Addr;
3925   // Emit target region as a standalone region.
3926   CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
3927       S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
3928   assert(Fn && Addr && "Target device function emission failed.");
3929 }
3930
3931 void CodeGenFunction::EmitOMPTargetDirective(const OMPTargetDirective &S) {
3932   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3933     emitTargetRegion(CGF, S, Action);
3934   };
3935   emitCommonOMPTargetDirective(*this, S, CodeGen);
3936 }
3937
3938 static void emitCommonOMPTeamsDirective(CodeGenFunction &CGF,
3939                                         const OMPExecutableDirective &S,
3940                                         OpenMPDirectiveKind InnermostKind,
3941                                         const RegionCodeGenTy &CodeGen) {
3942   const CapturedStmt *CS = S.getCapturedStmt(OMPD_teams);
3943   auto OutlinedFn = CGF.CGM.getOpenMPRuntime().emitTeamsOutlinedFunction(
3944       S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
3945
3946   const OMPNumTeamsClause *NT = S.getSingleClause<OMPNumTeamsClause>();
3947   const OMPThreadLimitClause *TL = S.getSingleClause<OMPThreadLimitClause>();
3948   if (NT || TL) {
3949     Expr *NumTeams = (NT) ? NT->getNumTeams() : nullptr;
3950     Expr *ThreadLimit = (TL) ? TL->getThreadLimit() : nullptr;
3951
3952     CGF.CGM.getOpenMPRuntime().emitNumTeamsClause(CGF, NumTeams, ThreadLimit,
3953                                                   S.getLocStart());
3954   }
3955
3956   OMPTeamsScope Scope(CGF, S);
3957   llvm::SmallVector<llvm::Value *, 16> CapturedVars;
3958   CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
3959   CGF.CGM.getOpenMPRuntime().emitTeamsCall(CGF, S, S.getLocStart(), OutlinedFn,
3960                                            CapturedVars);
3961 }
3962
3963 void CodeGenFunction::EmitOMPTeamsDirective(const OMPTeamsDirective &S) {
3964   // Emit teams region as a standalone region.
3965   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
3966     OMPPrivateScope PrivateScope(CGF);
3967     (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
3968     CGF.EmitOMPPrivateClause(S, PrivateScope);
3969     CGF.EmitOMPReductionClauseInit(S, PrivateScope);
3970     (void)PrivateScope.Privatize();
3971     CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
3972     CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
3973   };
3974   emitCommonOMPTeamsDirective(*this, S, OMPD_distribute, CodeGen);
3975   emitPostUpdateForReductionClause(
3976       *this, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
3977 }
3978
3979 static void emitTargetTeamsRegion(CodeGenFunction &CGF, PrePostActionTy &Action,
3980                                   const OMPTargetTeamsDirective &S) {
3981   auto *CS = S.getCapturedStmt(OMPD_teams);
3982   Action.Enter(CGF);
3983   // Emit teams region as a standalone region.
3984   auto &&CodeGen = [&S, CS](CodeGenFunction &CGF, PrePostActionTy &Action) {
3985     CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
3986     (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
3987     CGF.EmitOMPPrivateClause(S, PrivateScope);
3988     CGF.EmitOMPReductionClauseInit(S, PrivateScope);
3989     (void)PrivateScope.Privatize();
3990     Action.Enter(CGF);
3991     CGF.EmitStmt(CS->getCapturedStmt());
3992     CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
3993   };
3994   emitCommonOMPTeamsDirective(CGF, S, OMPD_teams, CodeGen);
3995   emitPostUpdateForReductionClause(
3996       CGF, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
3997 }
3998
3999 void CodeGenFunction::EmitOMPTargetTeamsDeviceFunction(
4000     CodeGenModule &CGM, StringRef ParentName,
4001     const OMPTargetTeamsDirective &S) {
4002   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4003     emitTargetTeamsRegion(CGF, Action, S);
4004   };
4005   llvm::Function *Fn;
4006   llvm::Constant *Addr;
4007   // Emit target region as a standalone region.
4008   CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4009       S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4010   assert(Fn && Addr && "Target device function emission failed.");
4011 }
4012
4013 void CodeGenFunction::EmitOMPTargetTeamsDirective(
4014     const OMPTargetTeamsDirective &S) {
4015   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4016     emitTargetTeamsRegion(CGF, Action, S);
4017   };
4018   emitCommonOMPTargetDirective(*this, S, CodeGen);
4019 }
4020
4021 static void
4022 emitTargetTeamsDistributeRegion(CodeGenFunction &CGF, PrePostActionTy &Action,
4023                                 const OMPTargetTeamsDistributeDirective &S) {
4024   Action.Enter(CGF);
4025   auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4026     CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
4027   };
4028
4029   // Emit teams region as a standalone region.
4030   auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4031                                             PrePostActionTy &) {
4032     CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4033     CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4034     (void)PrivateScope.Privatize();
4035     CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
4036                                                     CodeGenDistribute);
4037     CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4038   };
4039   emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute, CodeGen);
4040   emitPostUpdateForReductionClause(CGF, S,
4041                                    [](CodeGenFunction &) { return nullptr; });
4042 }
4043
4044 void CodeGenFunction::EmitOMPTargetTeamsDistributeDeviceFunction(
4045     CodeGenModule &CGM, StringRef ParentName,
4046     const OMPTargetTeamsDistributeDirective &S) {
4047   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4048     emitTargetTeamsDistributeRegion(CGF, Action, S);
4049   };
4050   llvm::Function *Fn;
4051   llvm::Constant *Addr;
4052   // Emit target region as a standalone region.
4053   CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4054       S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4055   assert(Fn && Addr && "Target device function emission failed.");
4056 }
4057
4058 void CodeGenFunction::EmitOMPTargetTeamsDistributeDirective(
4059     const OMPTargetTeamsDistributeDirective &S) {
4060   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4061     emitTargetTeamsDistributeRegion(CGF, Action, S);
4062   };
4063   emitCommonOMPTargetDirective(*this, S, CodeGen);
4064 }
4065
4066 static void emitTargetTeamsDistributeSimdRegion(
4067     CodeGenFunction &CGF, PrePostActionTy &Action,
4068     const OMPTargetTeamsDistributeSimdDirective &S) {
4069   Action.Enter(CGF);
4070   auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4071     CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
4072   };
4073
4074   // Emit teams region as a standalone region.
4075   auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4076                                             PrePostActionTy &) {
4077     CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4078     CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4079     (void)PrivateScope.Privatize();
4080     CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
4081                                                     CodeGenDistribute);
4082     CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4083   };
4084   emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute_simd, CodeGen);
4085   emitPostUpdateForReductionClause(CGF, S,
4086                                    [](CodeGenFunction &) { return nullptr; });
4087 }
4088
4089 void CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDeviceFunction(
4090     CodeGenModule &CGM, StringRef ParentName,
4091     const OMPTargetTeamsDistributeSimdDirective &S) {
4092   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4093     emitTargetTeamsDistributeSimdRegion(CGF, Action, S);
4094   };
4095   llvm::Function *Fn;
4096   llvm::Constant *Addr;
4097   // Emit target region as a standalone region.
4098   CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4099       S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4100   assert(Fn && Addr && "Target device function emission failed.");
4101 }
4102
4103 void CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDirective(
4104     const OMPTargetTeamsDistributeSimdDirective &S) {
4105   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4106     emitTargetTeamsDistributeSimdRegion(CGF, Action, S);
4107   };
4108   emitCommonOMPTargetDirective(*this, S, CodeGen);
4109 }
4110
4111 void CodeGenFunction::EmitOMPTeamsDistributeDirective(
4112     const OMPTeamsDistributeDirective &S) {
4113
4114   auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4115     CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
4116   };
4117
4118   // Emit teams region as a standalone region.
4119   auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4120                                             PrePostActionTy &) {
4121     OMPPrivateScope PrivateScope(CGF);
4122     CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4123     (void)PrivateScope.Privatize();
4124     CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
4125                                                     CodeGenDistribute);
4126     CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4127   };
4128   emitCommonOMPTeamsDirective(*this, S, OMPD_distribute, CodeGen);
4129   emitPostUpdateForReductionClause(*this, S,
4130                                    [](CodeGenFunction &) { return nullptr; });
4131 }
4132
4133 void CodeGenFunction::EmitOMPTeamsDistributeSimdDirective(
4134     const OMPTeamsDistributeSimdDirective &S) {
4135   auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4136     CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
4137   };
4138
4139   // Emit teams region as a standalone region.
4140   auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4141                                             PrePostActionTy &) {
4142     OMPPrivateScope PrivateScope(CGF);
4143     CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4144     (void)PrivateScope.Privatize();
4145     CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_simd,
4146                                                     CodeGenDistribute);
4147     CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4148   };
4149   emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_simd, CodeGen);
4150   emitPostUpdateForReductionClause(*this, S,
4151                                    [](CodeGenFunction &) { return nullptr; });
4152 }
4153
4154 void CodeGenFunction::EmitOMPTeamsDistributeParallelForDirective(
4155     const OMPTeamsDistributeParallelForDirective &S) {
4156   auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4157     CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
4158                               S.getDistInc());
4159   };
4160
4161   // Emit teams region as a standalone region.
4162   auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4163                                             PrePostActionTy &) {
4164     OMPPrivateScope PrivateScope(CGF);
4165     CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4166     (void)PrivateScope.Privatize();
4167     CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
4168                                                     CodeGenDistribute);
4169     CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4170   };
4171   emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_parallel_for, CodeGen);
4172   emitPostUpdateForReductionClause(*this, S,
4173                                    [](CodeGenFunction &) { return nullptr; });
4174 }
4175
4176 void CodeGenFunction::EmitOMPTeamsDistributeParallelForSimdDirective(
4177     const OMPTeamsDistributeParallelForSimdDirective &S) {
4178   auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4179     CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
4180                               S.getDistInc());
4181   };
4182
4183   // Emit teams region as a standalone region.
4184   auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4185                                             PrePostActionTy &) {
4186     OMPPrivateScope PrivateScope(CGF);
4187     CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4188     (void)PrivateScope.Privatize();
4189     CGF.CGM.getOpenMPRuntime().emitInlinedDirective(
4190         CGF, OMPD_distribute, CodeGenDistribute, /*HasCancel=*/false);
4191     CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4192   };
4193   emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_parallel_for, CodeGen);
4194   emitPostUpdateForReductionClause(*this, S,
4195                                    [](CodeGenFunction &) { return nullptr; });
4196 }
4197
4198 void CodeGenFunction::EmitOMPCancellationPointDirective(
4199     const OMPCancellationPointDirective &S) {
4200   CGM.getOpenMPRuntime().emitCancellationPointCall(*this, S.getLocStart(),
4201                                                    S.getCancelRegion());
4202 }
4203
4204 void CodeGenFunction::EmitOMPCancelDirective(const OMPCancelDirective &S) {
4205   const Expr *IfCond = nullptr;
4206   for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
4207     if (C->getNameModifier() == OMPD_unknown ||
4208         C->getNameModifier() == OMPD_cancel) {
4209       IfCond = C->getCondition();
4210       break;
4211     }
4212   }
4213   CGM.getOpenMPRuntime().emitCancelCall(*this, S.getLocStart(), IfCond,
4214                                         S.getCancelRegion());
4215 }
4216
4217 CodeGenFunction::JumpDest
4218 CodeGenFunction::getOMPCancelDestination(OpenMPDirectiveKind Kind) {
4219   if (Kind == OMPD_parallel || Kind == OMPD_task ||
4220       Kind == OMPD_target_parallel)
4221     return ReturnBlock;
4222   assert(Kind == OMPD_for || Kind == OMPD_section || Kind == OMPD_sections ||
4223          Kind == OMPD_parallel_sections || Kind == OMPD_parallel_for ||
4224          Kind == OMPD_distribute_parallel_for ||
4225          Kind == OMPD_target_parallel_for ||
4226          Kind == OMPD_teams_distribute_parallel_for ||
4227          Kind == OMPD_target_teams_distribute_parallel_for);
4228   return OMPCancelStack.getExitBlock();
4229 }
4230
4231 void CodeGenFunction::EmitOMPUseDevicePtrClause(
4232     const OMPClause &NC, OMPPrivateScope &PrivateScope,
4233     const llvm::DenseMap<const ValueDecl *, Address> &CaptureDeviceAddrMap) {
4234   const auto &C = cast<OMPUseDevicePtrClause>(NC);
4235   auto OrigVarIt = C.varlist_begin();
4236   auto InitIt = C.inits().begin();
4237   for (auto PvtVarIt : C.private_copies()) {
4238     auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*OrigVarIt)->getDecl());
4239     auto *InitVD = cast<VarDecl>(cast<DeclRefExpr>(*InitIt)->getDecl());
4240     auto *PvtVD = cast<VarDecl>(cast<DeclRefExpr>(PvtVarIt)->getDecl());
4241
4242     // In order to identify the right initializer we need to match the
4243     // declaration used by the mapping logic. In some cases we may get
4244     // OMPCapturedExprDecl that refers to the original declaration.
4245     const ValueDecl *MatchingVD = OrigVD;
4246     if (auto *OED = dyn_cast<OMPCapturedExprDecl>(MatchingVD)) {
4247       // OMPCapturedExprDecl are used to privative fields of the current
4248       // structure.
4249       auto *ME = cast<MemberExpr>(OED->getInit());
4250       assert(isa<CXXThisExpr>(ME->getBase()) &&
4251              "Base should be the current struct!");
4252       MatchingVD = ME->getMemberDecl();
4253     }
4254
4255     // If we don't have information about the current list item, move on to
4256     // the next one.
4257     auto InitAddrIt = CaptureDeviceAddrMap.find(MatchingVD);
4258     if (InitAddrIt == CaptureDeviceAddrMap.end())
4259       continue;
4260
4261     bool IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
4262       // Initialize the temporary initialization variable with the address we
4263       // get from the runtime library. We have to cast the source address
4264       // because it is always a void *. References are materialized in the
4265       // privatization scope, so the initialization here disregards the fact
4266       // the original variable is a reference.
4267       QualType AddrQTy =
4268           getContext().getPointerType(OrigVD->getType().getNonReferenceType());
4269       llvm::Type *AddrTy = ConvertTypeForMem(AddrQTy);
4270       Address InitAddr = Builder.CreateBitCast(InitAddrIt->second, AddrTy);
4271       setAddrOfLocalVar(InitVD, InitAddr);
4272
4273       // Emit private declaration, it will be initialized by the value we
4274       // declaration we just added to the local declarations map.
4275       EmitDecl(*PvtVD);
4276
4277       // The initialization variables reached its purpose in the emission
4278       // ofthe previous declaration, so we don't need it anymore.
4279       LocalDeclMap.erase(InitVD);
4280
4281       // Return the address of the private variable.
4282       return GetAddrOfLocalVar(PvtVD);
4283     });
4284     assert(IsRegistered && "firstprivate var already registered as private");
4285     // Silence the warning about unused variable.
4286     (void)IsRegistered;
4287
4288     ++OrigVarIt;
4289     ++InitIt;
4290   }
4291 }
4292
4293 // Generate the instructions for '#pragma omp target data' directive.
4294 void CodeGenFunction::EmitOMPTargetDataDirective(
4295     const OMPTargetDataDirective &S) {
4296   CGOpenMPRuntime::TargetDataInfo Info(/*RequiresDevicePointerInfo=*/true);
4297
4298   // Create a pre/post action to signal the privatization of the device pointer.
4299   // This action can be replaced by the OpenMP runtime code generation to
4300   // deactivate privatization.
4301   bool PrivatizeDevicePointers = false;
4302   class DevicePointerPrivActionTy : public PrePostActionTy {
4303     bool &PrivatizeDevicePointers;
4304
4305   public:
4306     explicit DevicePointerPrivActionTy(bool &PrivatizeDevicePointers)
4307         : PrePostActionTy(), PrivatizeDevicePointers(PrivatizeDevicePointers) {}
4308     void Enter(CodeGenFunction &CGF) override {
4309       PrivatizeDevicePointers = true;
4310     }
4311   };
4312   DevicePointerPrivActionTy PrivAction(PrivatizeDevicePointers);
4313
4314   auto &&CodeGen = [&S, &Info, &PrivatizeDevicePointers](
4315       CodeGenFunction &CGF, PrePostActionTy &Action) {
4316     auto &&InnermostCodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4317       CGF.EmitStmt(
4318           cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
4319     };
4320
4321     // Codegen that selects wheather to generate the privatization code or not.
4322     auto &&PrivCodeGen = [&S, &Info, &PrivatizeDevicePointers,
4323                           &InnermostCodeGen](CodeGenFunction &CGF,
4324                                              PrePostActionTy &Action) {
4325       RegionCodeGenTy RCG(InnermostCodeGen);
4326       PrivatizeDevicePointers = false;
4327
4328       // Call the pre-action to change the status of PrivatizeDevicePointers if
4329       // needed.
4330       Action.Enter(CGF);
4331
4332       if (PrivatizeDevicePointers) {
4333         OMPPrivateScope PrivateScope(CGF);
4334         // Emit all instances of the use_device_ptr clause.
4335         for (const auto *C : S.getClausesOfKind<OMPUseDevicePtrClause>())
4336           CGF.EmitOMPUseDevicePtrClause(*C, PrivateScope,
4337                                         Info.CaptureDeviceAddrMap);
4338         (void)PrivateScope.Privatize();
4339         RCG(CGF);
4340       } else
4341         RCG(CGF);
4342     };
4343
4344     // Forward the provided action to the privatization codegen.
4345     RegionCodeGenTy PrivRCG(PrivCodeGen);
4346     PrivRCG.setAction(Action);
4347
4348     // Notwithstanding the body of the region is emitted as inlined directive,
4349     // we don't use an inline scope as changes in the references inside the
4350     // region are expected to be visible outside, so we do not privative them.
4351     OMPLexicalScope Scope(CGF, S);
4352     CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_target_data,
4353                                                     PrivRCG);
4354   };
4355
4356   RegionCodeGenTy RCG(CodeGen);
4357
4358   // If we don't have target devices, don't bother emitting the data mapping
4359   // code.
4360   if (CGM.getLangOpts().OMPTargetTriples.empty()) {
4361     RCG(*this);
4362     return;
4363   }
4364
4365   // Check if we have any if clause associated with the directive.
4366   const Expr *IfCond = nullptr;
4367   if (auto *C = S.getSingleClause<OMPIfClause>())
4368     IfCond = C->getCondition();
4369
4370   // Check if we have any device clause associated with the directive.
4371   const Expr *Device = nullptr;
4372   if (auto *C = S.getSingleClause<OMPDeviceClause>())
4373     Device = C->getDevice();
4374
4375   // Set the action to signal privatization of device pointers.
4376   RCG.setAction(PrivAction);
4377
4378   // Emit region code.
4379   CGM.getOpenMPRuntime().emitTargetDataCalls(*this, S, IfCond, Device, RCG,
4380                                              Info);
4381 }
4382
4383 void CodeGenFunction::EmitOMPTargetEnterDataDirective(
4384     const OMPTargetEnterDataDirective &S) {
4385   // If we don't have target devices, don't bother emitting the data mapping
4386   // code.
4387   if (CGM.getLangOpts().OMPTargetTriples.empty())
4388     return;
4389
4390   // Check if we have any if clause associated with the directive.
4391   const Expr *IfCond = nullptr;
4392   if (auto *C = S.getSingleClause<OMPIfClause>())
4393     IfCond = C->getCondition();
4394
4395   // Check if we have any device clause associated with the directive.
4396   const Expr *Device = nullptr;
4397   if (auto *C = S.getSingleClause<OMPDeviceClause>())
4398     Device = C->getDevice();
4399
4400   OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
4401   CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
4402 }
4403
4404 void CodeGenFunction::EmitOMPTargetExitDataDirective(
4405     const OMPTargetExitDataDirective &S) {
4406   // If we don't have target devices, don't bother emitting the data mapping
4407   // code.
4408   if (CGM.getLangOpts().OMPTargetTriples.empty())
4409     return;
4410
4411   // Check if we have any if clause associated with the directive.
4412   const Expr *IfCond = nullptr;
4413   if (auto *C = S.getSingleClause<OMPIfClause>())
4414     IfCond = C->getCondition();
4415
4416   // Check if we have any device clause associated with the directive.
4417   const Expr *Device = nullptr;
4418   if (auto *C = S.getSingleClause<OMPDeviceClause>())
4419     Device = C->getDevice();
4420
4421   OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
4422   CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
4423 }
4424
4425 static void emitTargetParallelRegion(CodeGenFunction &CGF,
4426                                      const OMPTargetParallelDirective &S,
4427                                      PrePostActionTy &Action) {
4428   // Get the captured statement associated with the 'parallel' region.
4429   auto *CS = S.getCapturedStmt(OMPD_parallel);
4430   Action.Enter(CGF);
4431   auto &&CodeGen = [&S, CS](CodeGenFunction &CGF, PrePostActionTy &) {
4432     CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4433     (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
4434     CGF.EmitOMPPrivateClause(S, PrivateScope);
4435     CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4436     (void)PrivateScope.Privatize();
4437     // TODO: Add support for clauses.
4438     CGF.EmitStmt(CS->getCapturedStmt());
4439     CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
4440   };
4441   emitCommonOMPParallelDirective(CGF, S, OMPD_parallel, CodeGen,
4442                                  emitEmptyBoundParameters);
4443   emitPostUpdateForReductionClause(
4444       CGF, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
4445 }
4446
4447 void CodeGenFunction::EmitOMPTargetParallelDeviceFunction(
4448     CodeGenModule &CGM, StringRef ParentName,
4449     const OMPTargetParallelDirective &S) {
4450   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4451     emitTargetParallelRegion(CGF, S, Action);
4452   };
4453   llvm::Function *Fn;
4454   llvm::Constant *Addr;
4455   // Emit target region as a standalone region.
4456   CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4457       S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4458   assert(Fn && Addr && "Target device function emission failed.");
4459 }
4460
4461 void CodeGenFunction::EmitOMPTargetParallelDirective(
4462     const OMPTargetParallelDirective &S) {
4463   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4464     emitTargetParallelRegion(CGF, S, Action);
4465   };
4466   emitCommonOMPTargetDirective(*this, S, CodeGen);
4467 }
4468
4469 static void emitTargetParallelForRegion(CodeGenFunction &CGF,
4470                                         const OMPTargetParallelForDirective &S,
4471                                         PrePostActionTy &Action) {
4472   Action.Enter(CGF);
4473   // Emit directive as a combined directive that consists of two implicit
4474   // directives: 'parallel' with 'for' directive.
4475   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4476     CodeGenFunction::OMPCancelStackRAII CancelRegion(
4477         CGF, OMPD_target_parallel_for, S.hasCancel());
4478     CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
4479                                emitDispatchForLoopBounds);
4480   };
4481   emitCommonOMPParallelDirective(CGF, S, OMPD_for, CodeGen,
4482                                  emitEmptyBoundParameters);
4483 }
4484
4485 void CodeGenFunction::EmitOMPTargetParallelForDeviceFunction(
4486     CodeGenModule &CGM, StringRef ParentName,
4487     const OMPTargetParallelForDirective &S) {
4488   // Emit SPMD target parallel for region as a standalone region.
4489   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4490     emitTargetParallelForRegion(CGF, S, Action);
4491   };
4492   llvm::Function *Fn;
4493   llvm::Constant *Addr;
4494   // Emit target region as a standalone region.
4495   CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4496       S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4497   assert(Fn && Addr && "Target device function emission failed.");
4498 }
4499
4500 void CodeGenFunction::EmitOMPTargetParallelForDirective(
4501     const OMPTargetParallelForDirective &S) {
4502   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4503     emitTargetParallelForRegion(CGF, S, Action);
4504   };
4505   emitCommonOMPTargetDirective(*this, S, CodeGen);
4506 }
4507
4508 static void
4509 emitTargetParallelForSimdRegion(CodeGenFunction &CGF,
4510                                 const OMPTargetParallelForSimdDirective &S,
4511                                 PrePostActionTy &Action) {
4512   Action.Enter(CGF);
4513   // Emit directive as a combined directive that consists of two implicit
4514   // directives: 'parallel' with 'for' directive.
4515   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4516     CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
4517                                emitDispatchForLoopBounds);
4518   };
4519   emitCommonOMPParallelDirective(CGF, S, OMPD_simd, CodeGen,
4520                                  emitEmptyBoundParameters);
4521 }
4522
4523 void CodeGenFunction::EmitOMPTargetParallelForSimdDeviceFunction(
4524     CodeGenModule &CGM, StringRef ParentName,
4525     const OMPTargetParallelForSimdDirective &S) {
4526   // Emit SPMD target parallel for region as a standalone region.
4527   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4528     emitTargetParallelForSimdRegion(CGF, S, Action);
4529   };
4530   llvm::Function *Fn;
4531   llvm::Constant *Addr;
4532   // Emit target region as a standalone region.
4533   CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4534       S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4535   assert(Fn && Addr && "Target device function emission failed.");
4536 }
4537
4538 void CodeGenFunction::EmitOMPTargetParallelForSimdDirective(
4539     const OMPTargetParallelForSimdDirective &S) {
4540   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4541     emitTargetParallelForSimdRegion(CGF, S, Action);
4542   };
4543   emitCommonOMPTargetDirective(*this, S, CodeGen);
4544 }
4545
4546 /// Emit a helper variable and return corresponding lvalue.
4547 static void mapParam(CodeGenFunction &CGF, const DeclRefExpr *Helper,
4548                      const ImplicitParamDecl *PVD,
4549                      CodeGenFunction::OMPPrivateScope &Privates) {
4550   auto *VDecl = cast<VarDecl>(Helper->getDecl());
4551   Privates.addPrivate(
4552       VDecl, [&CGF, PVD]() -> Address { return CGF.GetAddrOfLocalVar(PVD); });
4553 }
4554
4555 void CodeGenFunction::EmitOMPTaskLoopBasedDirective(const OMPLoopDirective &S) {
4556   assert(isOpenMPTaskLoopDirective(S.getDirectiveKind()));
4557   // Emit outlined function for task construct.
4558   auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
4559   auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
4560   auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
4561   const Expr *IfCond = nullptr;
4562   for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
4563     if (C->getNameModifier() == OMPD_unknown ||
4564         C->getNameModifier() == OMPD_taskloop) {
4565       IfCond = C->getCondition();
4566       break;
4567     }
4568   }
4569
4570   OMPTaskDataTy Data;
4571   // Check if taskloop must be emitted without taskgroup.
4572   Data.Nogroup = S.getSingleClause<OMPNogroupClause>();
4573   // TODO: Check if we should emit tied or untied task.
4574   Data.Tied = true;
4575   // Set scheduling for taskloop
4576   if (const auto* Clause = S.getSingleClause<OMPGrainsizeClause>()) {
4577     // grainsize clause
4578     Data.Schedule.setInt(/*IntVal=*/false);
4579     Data.Schedule.setPointer(EmitScalarExpr(Clause->getGrainsize()));
4580   } else if (const auto* Clause = S.getSingleClause<OMPNumTasksClause>()) {
4581     // num_tasks clause
4582     Data.Schedule.setInt(/*IntVal=*/true);
4583     Data.Schedule.setPointer(EmitScalarExpr(Clause->getNumTasks()));
4584   }
4585
4586   auto &&BodyGen = [CS, &S](CodeGenFunction &CGF, PrePostActionTy &) {
4587     // if (PreCond) {
4588     //   for (IV in 0..LastIteration) BODY;
4589     //   <Final counter/linear vars updates>;
4590     // }
4591     //
4592
4593     // Emit: if (PreCond) - begin.
4594     // If the condition constant folds and can be elided, avoid emitting the
4595     // whole loop.
4596     bool CondConstant;
4597     llvm::BasicBlock *ContBlock = nullptr;
4598     OMPLoopScope PreInitScope(CGF, S);
4599     if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
4600       if (!CondConstant)
4601         return;
4602     } else {
4603       auto *ThenBlock = CGF.createBasicBlock("taskloop.if.then");
4604       ContBlock = CGF.createBasicBlock("taskloop.if.end");
4605       emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
4606                   CGF.getProfileCount(&S));
4607       CGF.EmitBlock(ThenBlock);
4608       CGF.incrementProfileCounter(&S);
4609     }
4610
4611     if (isOpenMPSimdDirective(S.getDirectiveKind()))
4612       CGF.EmitOMPSimdInit(S);
4613
4614     OMPPrivateScope LoopScope(CGF);
4615     // Emit helper vars inits.
4616     enum { LowerBound = 5, UpperBound, Stride, LastIter };
4617     auto *I = CS->getCapturedDecl()->param_begin();
4618     auto *LBP = std::next(I, LowerBound);
4619     auto *UBP = std::next(I, UpperBound);
4620     auto *STP = std::next(I, Stride);
4621     auto *LIP = std::next(I, LastIter);
4622     mapParam(CGF, cast<DeclRefExpr>(S.getLowerBoundVariable()), *LBP,
4623              LoopScope);
4624     mapParam(CGF, cast<DeclRefExpr>(S.getUpperBoundVariable()), *UBP,
4625              LoopScope);
4626     mapParam(CGF, cast<DeclRefExpr>(S.getStrideVariable()), *STP, LoopScope);
4627     mapParam(CGF, cast<DeclRefExpr>(S.getIsLastIterVariable()), *LIP,
4628              LoopScope);
4629     CGF.EmitOMPPrivateLoopCounters(S, LoopScope);
4630     bool HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
4631     (void)LoopScope.Privatize();
4632     // Emit the loop iteration variable.
4633     const Expr *IVExpr = S.getIterationVariable();
4634     const VarDecl *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
4635     CGF.EmitVarDecl(*IVDecl);
4636     CGF.EmitIgnoredExpr(S.getInit());
4637
4638     // Emit the iterations count variable.
4639     // If it is not a variable, Sema decided to calculate iterations count on
4640     // each iteration (e.g., it is foldable into a constant).
4641     if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
4642       CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
4643       // Emit calculation of the iterations count.
4644       CGF.EmitIgnoredExpr(S.getCalcLastIteration());
4645     }
4646
4647     CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
4648                          S.getInc(),
4649                          [&S](CodeGenFunction &CGF) {
4650                            CGF.EmitOMPLoopBody(S, JumpDest());
4651                            CGF.EmitStopPoint(&S);
4652                          },
4653                          [](CodeGenFunction &) {});
4654     // Emit: if (PreCond) - end.
4655     if (ContBlock) {
4656       CGF.EmitBranch(ContBlock);
4657       CGF.EmitBlock(ContBlock, true);
4658     }
4659     // Emit final copy of the lastprivate variables if IsLastIter != 0.
4660     if (HasLastprivateClause) {
4661       CGF.EmitOMPLastprivateClauseFinal(
4662           S, isOpenMPSimdDirective(S.getDirectiveKind()),
4663           CGF.Builder.CreateIsNotNull(CGF.EmitLoadOfScalar(
4664               CGF.GetAddrOfLocalVar(*LIP), /*Volatile=*/false,
4665               (*LIP)->getType(), S.getLocStart())));
4666     }
4667   };
4668   auto &&TaskGen = [&S, SharedsTy, CapturedStruct,
4669                     IfCond](CodeGenFunction &CGF, llvm::Value *OutlinedFn,
4670                             const OMPTaskDataTy &Data) {
4671     auto &&CodeGen = [&](CodeGenFunction &CGF, PrePostActionTy &) {
4672       OMPLoopScope PreInitScope(CGF, S);
4673       CGF.CGM.getOpenMPRuntime().emitTaskLoopCall(CGF, S.getLocStart(), S,
4674                                                   OutlinedFn, SharedsTy,
4675                                                   CapturedStruct, IfCond, Data);
4676     };
4677     CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_taskloop,
4678                                                     CodeGen);
4679   };
4680   if (Data.Nogroup)
4681     EmitOMPTaskBasedDirective(S, BodyGen, TaskGen, Data);
4682   else {
4683     CGM.getOpenMPRuntime().emitTaskgroupRegion(
4684         *this,
4685         [&S, &BodyGen, &TaskGen, &Data](CodeGenFunction &CGF,
4686                                         PrePostActionTy &Action) {
4687           Action.Enter(CGF);
4688           CGF.EmitOMPTaskBasedDirective(S, BodyGen, TaskGen, Data);
4689         },
4690         S.getLocStart());
4691   }
4692 }
4693
4694 void CodeGenFunction::EmitOMPTaskLoopDirective(const OMPTaskLoopDirective &S) {
4695   EmitOMPTaskLoopBasedDirective(S);
4696 }
4697
4698 void CodeGenFunction::EmitOMPTaskLoopSimdDirective(
4699     const OMPTaskLoopSimdDirective &S) {
4700   EmitOMPTaskLoopBasedDirective(S);
4701 }
4702
4703 // Generate the instructions for '#pragma omp target update' directive.
4704 void CodeGenFunction::EmitOMPTargetUpdateDirective(
4705     const OMPTargetUpdateDirective &S) {
4706   // If we don't have target devices, don't bother emitting the data mapping
4707   // code.
4708   if (CGM.getLangOpts().OMPTargetTriples.empty())
4709     return;
4710
4711   // Check if we have any if clause associated with the directive.
4712   const Expr *IfCond = nullptr;
4713   if (auto *C = S.getSingleClause<OMPIfClause>())
4714     IfCond = C->getCondition();
4715
4716   // Check if we have any device clause associated with the directive.
4717   const Expr *Device = nullptr;
4718   if (auto *C = S.getSingleClause<OMPDeviceClause>())
4719     Device = C->getDevice();
4720
4721   OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
4722   CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
4723 }