1 //===--- SemaOpenMP.cpp - Semantic Analysis for OpenMP constructs ---------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 /// \file
9 /// This file implements semantic analysis for OpenMP directives and
10 /// clauses.
11 ///
12 //===----------------------------------------------------------------------===//
13 
14 #include "TreeTransform.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTMutationListener.h"
17 #include "clang/AST/CXXInheritance.h"
18 #include "clang/AST/Decl.h"
19 #include "clang/AST/DeclCXX.h"
20 #include "clang/AST/DeclOpenMP.h"
21 #include "clang/AST/StmtCXX.h"
22 #include "clang/AST/StmtOpenMP.h"
23 #include "clang/AST/StmtVisitor.h"
24 #include "clang/AST/TypeOrdering.h"
25 #include "clang/Basic/OpenMPKinds.h"
26 #include "clang/Sema/Initialization.h"
27 #include "clang/Sema/Lookup.h"
28 #include "clang/Sema/Scope.h"
29 #include "clang/Sema/ScopeInfo.h"
30 #include "clang/Sema/SemaInternal.h"
31 #include "llvm/ADT/PointerEmbeddedInt.h"
32 using namespace clang;
33 
34 //===----------------------------------------------------------------------===//
35 // Stack of data-sharing attributes for variables
36 //===----------------------------------------------------------------------===//
37 
38 static const Expr *checkMapClauseExpressionBase(
39     Sema &SemaRef, Expr *E,
40     OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
41     OpenMPClauseKind CKind, bool NoDiagnose);
42 
43 namespace {
44 /// Default data sharing attributes, which can be applied to directive.
45 enum DefaultDataSharingAttributes {
46   DSA_unspecified = 0, /// Data sharing attribute not specified.
47   DSA_none = 1 << 0,   /// Default data sharing attribute 'none'.
48   DSA_shared = 1 << 1, /// Default data sharing attribute 'shared'.
49 };
50 
51 /// Attributes of the defaultmap clause.
52 enum DefaultMapAttributes {
53   DMA_unspecified,   /// Default mapping is not specified.
54   DMA_tofrom_scalar, /// Default mapping is 'tofrom:scalar'.
55 };
56 
57 /// Stack for tracking declarations used in OpenMP directives and
58 /// clauses and their data-sharing attributes.
59 class DSAStackTy {
60 public:
61   struct DSAVarData {
62     OpenMPDirectiveKind DKind = OMPD_unknown;
63     OpenMPClauseKind CKind = OMPC_unknown;
64     const Expr *RefExpr = nullptr;
65     DeclRefExpr *PrivateCopy = nullptr;
66     SourceLocation ImplicitDSALoc;
67     DSAVarData() = default;
68     DSAVarData(OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
69                const Expr *RefExpr, DeclRefExpr *PrivateCopy,
70                SourceLocation ImplicitDSALoc)
71         : DKind(DKind), CKind(CKind), RefExpr(RefExpr),
72           PrivateCopy(PrivateCopy), ImplicitDSALoc(ImplicitDSALoc) {}
73   };
74   using OperatorOffsetTy =
75       llvm::SmallVector<std::pair<Expr *, OverloadedOperatorKind>, 4>;
76   using DoacrossDependMapTy =
77       llvm::DenseMap<OMPDependClause *, OperatorOffsetTy>;
78 
79 private:
80   struct DSAInfo {
81     OpenMPClauseKind Attributes = OMPC_unknown;
82     /// Pointer to a reference expression and a flag which shows that the
83     /// variable is marked as lastprivate(true) or not (false).
84     llvm::PointerIntPair<const Expr *, 1, bool> RefExpr;
85     DeclRefExpr *PrivateCopy = nullptr;
86   };
87   using DeclSAMapTy = llvm::SmallDenseMap<const ValueDecl *, DSAInfo, 8>;
88   using AlignedMapTy = llvm::SmallDenseMap<const ValueDecl *, const Expr *, 8>;
89   using LCDeclInfo = std::pair<unsigned, VarDecl *>;
90   using LoopControlVariablesMapTy =
91       llvm::SmallDenseMap<const ValueDecl *, LCDeclInfo, 8>;
92   /// Struct that associates a component with the clause kind where they are
93   /// found.
94   struct MappedExprComponentTy {
95     OMPClauseMappableExprCommon::MappableExprComponentLists Components;
96     OpenMPClauseKind Kind = OMPC_unknown;
97   };
98   using MappedExprComponentsTy =
99       llvm::DenseMap<const ValueDecl *, MappedExprComponentTy>;
100   using CriticalsWithHintsTy =
101       llvm::StringMap<std::pair<const OMPCriticalDirective *, llvm::APSInt>>;
102   struct ReductionData {
103     using BOKPtrType = llvm::PointerEmbeddedInt<BinaryOperatorKind, 16>;
104     SourceRange ReductionRange;
105     llvm::PointerUnion<const Expr *, BOKPtrType> ReductionOp;
106     ReductionData() = default;
107     void set(BinaryOperatorKind BO, SourceRange RR) {
108       ReductionRange = RR;
109       ReductionOp = BO;
110     }
111     void set(const Expr *RefExpr, SourceRange RR) {
112       ReductionRange = RR;
113       ReductionOp = RefExpr;
114     }
115   };
116   using DeclReductionMapTy =
117       llvm::SmallDenseMap<const ValueDecl *, ReductionData, 4>;
118 
119   struct SharingMapTy {
120     DeclSAMapTy SharingMap;
121     DeclReductionMapTy ReductionMap;
122     AlignedMapTy AlignedMap;
123     MappedExprComponentsTy MappedExprComponents;
124     LoopControlVariablesMapTy LCVMap;
125     DefaultDataSharingAttributes DefaultAttr = DSA_unspecified;
126     SourceLocation DefaultAttrLoc;
127     DefaultMapAttributes DefaultMapAttr = DMA_unspecified;
128     SourceLocation DefaultMapAttrLoc;
129     OpenMPDirectiveKind Directive = OMPD_unknown;
130     DeclarationNameInfo DirectiveName;
131     Scope *CurScope = nullptr;
132     SourceLocation ConstructLoc;
133     /// Set of 'depend' clauses with 'sink|source' dependence kind. Required to
134     /// get the data (loop counters etc.) about enclosing loop-based construct.
135     /// This data is required during codegen.
136     DoacrossDependMapTy DoacrossDepends;
137     /// First argument (Expr *) contains optional argument of the
138     /// 'ordered' clause, the second one is true if the regions has 'ordered'
139     /// clause, false otherwise.
140     llvm::Optional<std::pair<const Expr *, OMPOrderedClause *>> OrderedRegion;
141     unsigned AssociatedLoops = 1;
142     const Decl *PossiblyLoopCounter = nullptr;
143     bool NowaitRegion = false;
144     bool CancelRegion = false;
145     bool LoopStart = false;
146     SourceLocation InnerTeamsRegionLoc;
147     /// Reference to the taskgroup task_reduction reference expression.
148     Expr *TaskgroupReductionRef = nullptr;
149     llvm::DenseSet<QualType> MappedClassesQualTypes;
150     /// List of globals marked as declare target link in this target region
151     /// (isOpenMPTargetExecutionDirective(Directive) == true).
152     llvm::SmallVector<DeclRefExpr *, 4> DeclareTargetLinkVarDecls;
153     SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
154                  Scope *CurScope, SourceLocation Loc)
155         : Directive(DKind), DirectiveName(Name), CurScope(CurScope),
156           ConstructLoc(Loc) {}
157     SharingMapTy() = default;
158   };
159 
160   using StackTy = SmallVector<SharingMapTy, 4>;
161 
162   /// Stack of used declaration and their data-sharing attributes.
163   DeclSAMapTy Threadprivates;
164   const FunctionScopeInfo *CurrentNonCapturingFunctionScope = nullptr;
165   SmallVector<std::pair<StackTy, const FunctionScopeInfo *>, 4> Stack;
166   /// true, if check for DSA must be from parent directive, false, if
167   /// from current directive.
168   OpenMPClauseKind ClauseKindMode = OMPC_unknown;
169   Sema &SemaRef;
170   bool ForceCapturing = false;
171   /// true if all the vaiables in the target executable directives must be
172   /// captured by reference.
173   bool ForceCaptureByReferenceInTargetExecutable = false;
174   CriticalsWithHintsTy Criticals;
175 
176   using iterator = StackTy::const_reverse_iterator;
177 
178   DSAVarData getDSA(iterator &Iter, ValueDecl *D) const;
179 
180   /// Checks if the variable is a local for OpenMP region.
181   bool isOpenMPLocal(VarDecl *D, iterator Iter) const;
182 
183   bool isStackEmpty() const {
184     return Stack.empty() ||
185            Stack.back().second != CurrentNonCapturingFunctionScope ||
186            Stack.back().first.empty();
187   }
188 
189   /// Vector of previously declared requires directives
190   SmallVector<const OMPRequiresDecl *, 2> RequiresDecls;
191   /// omp_allocator_handle_t type.
192   QualType OMPAllocatorHandleT;
193   /// Expression for the predefined allocators.
194   Expr *OMPPredefinedAllocators[OMPAllocateDeclAttr::OMPUserDefinedMemAlloc] = {
195       nullptr};
196 
197 public:
198   explicit DSAStackTy(Sema &S) : SemaRef(S) {}
199 
200   /// Sets omp_allocator_handle_t type.
201   void setOMPAllocatorHandleT(QualType Ty) { OMPAllocatorHandleT = Ty; }
202   /// Gets omp_allocator_handle_t type.
203   QualType getOMPAllocatorHandleT() const { return OMPAllocatorHandleT; }
204   /// Sets the given default allocator.
205   void setAllocator(OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind,
206                     Expr *Allocator) {
207     OMPPredefinedAllocators[AllocatorKind] = Allocator;
208   }
209   /// Returns the specified default allocator.
210   Expr *getAllocator(OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind) const {
211     return OMPPredefinedAllocators[AllocatorKind];
212   }
213 
214   bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
215   OpenMPClauseKind getClauseParsingMode() const {
216     assert(isClauseParsingMode() && "Must be in clause parsing mode.");
217     return ClauseKindMode;
218   }
219   void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
220 
221   bool isForceVarCapturing() const { return ForceCapturing; }
222   void setForceVarCapturing(bool V) { ForceCapturing = V; }
223 
224   void setForceCaptureByReferenceInTargetExecutable(bool V) {
225     ForceCaptureByReferenceInTargetExecutable = V;
226   }
227   bool isForceCaptureByReferenceInTargetExecutable() const {
228     return ForceCaptureByReferenceInTargetExecutable;
229   }
230 
231   void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
232             Scope *CurScope, SourceLocation Loc) {
233     if (Stack.empty() ||
234         Stack.back().second != CurrentNonCapturingFunctionScope)
235       Stack.emplace_back(StackTy(), CurrentNonCapturingFunctionScope);
236     Stack.back().first.emplace_back(DKind, DirName, CurScope, Loc);
237     Stack.back().first.back().DefaultAttrLoc = Loc;
238   }
239 
240   void pop() {
241     assert(!Stack.back().first.empty() &&
242            "Data-sharing attributes stack is empty!");
243     Stack.back().first.pop_back();
244   }
245 
246   /// Marks that we're started loop parsing.
247   void loopInit() {
248     assert(isOpenMPLoopDirective(getCurrentDirective()) &&
249            "Expected loop-based directive.");
250     Stack.back().first.back().LoopStart = true;
251   }
252   /// Start capturing of the variables in the loop context.
253   void loopStart() {
254     assert(isOpenMPLoopDirective(getCurrentDirective()) &&
255            "Expected loop-based directive.");
256     Stack.back().first.back().LoopStart = false;
257   }
258   /// true, if variables are captured, false otherwise.
259   bool isLoopStarted() const {
260     assert(isOpenMPLoopDirective(getCurrentDirective()) &&
261            "Expected loop-based directive.");
262     return !Stack.back().first.back().LoopStart;
263   }
264   /// Marks (or clears) declaration as possibly loop counter.
265   void resetPossibleLoopCounter(const Decl *D = nullptr) {
266     Stack.back().first.back().PossiblyLoopCounter =
267         D ? D->getCanonicalDecl() : D;
268   }
269   /// Gets the possible loop counter decl.
270   const Decl *getPossiblyLoopCunter() const {
271     return Stack.back().first.back().PossiblyLoopCounter;
272   }
273   /// Start new OpenMP region stack in new non-capturing function.
274   void pushFunction() {
275     const FunctionScopeInfo *CurFnScope = SemaRef.getCurFunction();
276     assert(!isa<CapturingScopeInfo>(CurFnScope));
277     CurrentNonCapturingFunctionScope = CurFnScope;
278   }
279   /// Pop region stack for non-capturing function.
280   void popFunction(const FunctionScopeInfo *OldFSI) {
281     if (!Stack.empty() && Stack.back().second == OldFSI) {
282       assert(Stack.back().first.empty());
283       Stack.pop_back();
284     }
285     CurrentNonCapturingFunctionScope = nullptr;
286     for (const FunctionScopeInfo *FSI : llvm::reverse(SemaRef.FunctionScopes)) {
287       if (!isa<CapturingScopeInfo>(FSI)) {
288         CurrentNonCapturingFunctionScope = FSI;
289         break;
290       }
291     }
292   }
293 
294   void addCriticalWithHint(const OMPCriticalDirective *D, llvm::APSInt Hint) {
295     Criticals.try_emplace(D->getDirectiveName().getAsString(), D, Hint);
296   }
297   const std::pair<const OMPCriticalDirective *, llvm::APSInt>
298   getCriticalWithHint(const DeclarationNameInfo &Name) const {
299     auto I = Criticals.find(Name.getAsString());
300     if (I != Criticals.end())
301       return I->second;
302     return std::make_pair(nullptr, llvm::APSInt());
303   }
304   /// If 'aligned' declaration for given variable \a D was not seen yet,
305   /// add it and return NULL; otherwise return previous occurrence's expression
306   /// for diagnostics.
307   const Expr *addUniqueAligned(const ValueDecl *D, const Expr *NewDE);
308 
309   /// Register specified variable as loop control variable.
310   void addLoopControlVariable(const ValueDecl *D, VarDecl *Capture);
311   /// Check if the specified variable is a loop control variable for
312   /// current region.
313   /// \return The index of the loop control variable in the list of associated
314   /// for-loops (from outer to inner).
315   const LCDeclInfo isLoopControlVariable(const ValueDecl *D) const;
316   /// Check if the specified variable is a loop control variable for
317   /// parent region.
318   /// \return The index of the loop control variable in the list of associated
319   /// for-loops (from outer to inner).
320   const LCDeclInfo isParentLoopControlVariable(const ValueDecl *D) const;
321   /// Get the loop control variable for the I-th loop (or nullptr) in
322   /// parent directive.
323   const ValueDecl *getParentLoopControlVariable(unsigned I) const;
324 
325   /// Adds explicit data sharing attribute to the specified declaration.
326   void addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
327               DeclRefExpr *PrivateCopy = nullptr);
328 
329   /// Adds additional information for the reduction items with the reduction id
330   /// represented as an operator.
331   void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
332                                  BinaryOperatorKind BOK);
333   /// Adds additional information for the reduction items with the reduction id
334   /// represented as reduction identifier.
335   void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
336                                  const Expr *ReductionRef);
337   /// Returns the location and reduction operation from the innermost parent
338   /// region for the given \p D.
339   const DSAVarData
340   getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
341                                    BinaryOperatorKind &BOK,
342                                    Expr *&TaskgroupDescriptor) const;
343   /// Returns the location and reduction operation from the innermost parent
344   /// region for the given \p D.
345   const DSAVarData
346   getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
347                                    const Expr *&ReductionRef,
348                                    Expr *&TaskgroupDescriptor) const;
349   /// Return reduction reference expression for the current taskgroup.
350   Expr *getTaskgroupReductionRef() const {
351     assert(Stack.back().first.back().Directive == OMPD_taskgroup &&
352            "taskgroup reference expression requested for non taskgroup "
353            "directive.");
354     return Stack.back().first.back().TaskgroupReductionRef;
355   }
356   /// Checks if the given \p VD declaration is actually a taskgroup reduction
357   /// descriptor variable at the \p Level of OpenMP regions.
358   bool isTaskgroupReductionRef(const ValueDecl *VD, unsigned Level) const {
359     return Stack.back().first[Level].TaskgroupReductionRef &&
360            cast<DeclRefExpr>(Stack.back().first[Level].TaskgroupReductionRef)
361                    ->getDecl() == VD;
362   }
363 
364   /// Returns data sharing attributes from top of the stack for the
365   /// specified declaration.
366   const DSAVarData getTopDSA(ValueDecl *D, bool FromParent);
367   /// Returns data-sharing attributes for the specified declaration.
368   const DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent) const;
369   /// Checks if the specified variables has data-sharing attributes which
370   /// match specified \a CPred predicate in any directive which matches \a DPred
371   /// predicate.
372   const DSAVarData
373   hasDSA(ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
374          const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
375          bool FromParent) const;
376   /// Checks if the specified variables has data-sharing attributes which
377   /// match specified \a CPred predicate in any innermost directive which
378   /// matches \a DPred predicate.
379   const DSAVarData
380   hasInnermostDSA(ValueDecl *D,
381                   const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
382                   const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
383                   bool FromParent) const;
384   /// Checks if the specified variables has explicit data-sharing
385   /// attributes which match specified \a CPred predicate at the specified
386   /// OpenMP region.
387   bool hasExplicitDSA(const ValueDecl *D,
388                       const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
389                       unsigned Level, bool NotLastprivate = false) const;
390 
391   /// Returns true if the directive at level \Level matches in the
392   /// specified \a DPred predicate.
393   bool hasExplicitDirective(
394       const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
395       unsigned Level) const;
396 
397   /// Finds a directive which matches specified \a DPred predicate.
398   bool hasDirective(
399       const llvm::function_ref<bool(
400           OpenMPDirectiveKind, const DeclarationNameInfo &, SourceLocation)>
401           DPred,
402       bool FromParent) const;
403 
404   /// Returns currently analyzed directive.
405   OpenMPDirectiveKind getCurrentDirective() const {
406     return isStackEmpty() ? OMPD_unknown : Stack.back().first.back().Directive;
407   }
408   /// Returns directive kind at specified level.
409   OpenMPDirectiveKind getDirective(unsigned Level) const {
410     assert(!isStackEmpty() && "No directive at specified level.");
411     return Stack.back().first[Level].Directive;
412   }
413   /// Returns parent directive.
414   OpenMPDirectiveKind getParentDirective() const {
415     if (isStackEmpty() || Stack.back().first.size() == 1)
416       return OMPD_unknown;
417     return std::next(Stack.back().first.rbegin())->Directive;
418   }
419 
420   /// Add requires decl to internal vector
421   void addRequiresDecl(OMPRequiresDecl *RD) {
422     RequiresDecls.push_back(RD);
423   }
424 
425   /// Checks if the defined 'requires' directive has specified type of clause.
426   template <typename ClauseType>
427   bool hasRequiresDeclWithClause() {
428     return llvm::any_of(RequiresDecls, [](const OMPRequiresDecl *D) {
429       return llvm::any_of(D->clauselists(), [](const OMPClause *C) {
430         return isa<ClauseType>(C);
431       });
432     });
433   }
434 
435   /// Checks for a duplicate clause amongst previously declared requires
436   /// directives
437   bool hasDuplicateRequiresClause(ArrayRef<OMPClause *> ClauseList) const {
438     bool IsDuplicate = false;
439     for (OMPClause *CNew : ClauseList) {
440       for (const OMPRequiresDecl *D : RequiresDecls) {
441         for (const OMPClause *CPrev : D->clauselists()) {
442           if (CNew->getClauseKind() == CPrev->getClauseKind()) {
443             SemaRef.Diag(CNew->getBeginLoc(),
444                          diag::err_omp_requires_clause_redeclaration)
445                 << getOpenMPClauseName(CNew->getClauseKind());
446             SemaRef.Diag(CPrev->getBeginLoc(),
447                          diag::note_omp_requires_previous_clause)
448                 << getOpenMPClauseName(CPrev->getClauseKind());
449             IsDuplicate = true;
450           }
451         }
452       }
453     }
454     return IsDuplicate;
455   }
456 
457   /// Set default data sharing attribute to none.
458   void setDefaultDSANone(SourceLocation Loc) {
459     assert(!isStackEmpty());
460     Stack.back().first.back().DefaultAttr = DSA_none;
461     Stack.back().first.back().DefaultAttrLoc = Loc;
462   }
463   /// Set default data sharing attribute to shared.
464   void setDefaultDSAShared(SourceLocation Loc) {
465     assert(!isStackEmpty());
466     Stack.back().first.back().DefaultAttr = DSA_shared;
467     Stack.back().first.back().DefaultAttrLoc = Loc;
468   }
469   /// Set default data mapping attribute to 'tofrom:scalar'.
470   void setDefaultDMAToFromScalar(SourceLocation Loc) {
471     assert(!isStackEmpty());
472     Stack.back().first.back().DefaultMapAttr = DMA_tofrom_scalar;
473     Stack.back().first.back().DefaultMapAttrLoc = Loc;
474   }
475 
476   DefaultDataSharingAttributes getDefaultDSA() const {
477     return isStackEmpty() ? DSA_unspecified
478                           : Stack.back().first.back().DefaultAttr;
479   }
480   SourceLocation getDefaultDSALocation() const {
481     return isStackEmpty() ? SourceLocation()
482                           : Stack.back().first.back().DefaultAttrLoc;
483   }
484   DefaultMapAttributes getDefaultDMA() const {
485     return isStackEmpty() ? DMA_unspecified
486                           : Stack.back().first.back().DefaultMapAttr;
487   }
488   DefaultMapAttributes getDefaultDMAAtLevel(unsigned Level) const {
489     return Stack.back().first[Level].DefaultMapAttr;
490   }
491   SourceLocation getDefaultDMALocation() const {
492     return isStackEmpty() ? SourceLocation()
493                           : Stack.back().first.back().DefaultMapAttrLoc;
494   }
495 
496   /// Checks if the specified variable is a threadprivate.
497   bool isThreadPrivate(VarDecl *D) {
498     const DSAVarData DVar = getTopDSA(D, false);
499     return isOpenMPThreadPrivate(DVar.CKind);
500   }
501 
502   /// Marks current region as ordered (it has an 'ordered' clause).
503   void setOrderedRegion(bool IsOrdered, const Expr *Param,
504                         OMPOrderedClause *Clause) {
505     assert(!isStackEmpty());
506     if (IsOrdered)
507       Stack.back().first.back().OrderedRegion.emplace(Param, Clause);
508     else
509       Stack.back().first.back().OrderedRegion.reset();
510   }
511   /// Returns true, if region is ordered (has associated 'ordered' clause),
512   /// false - otherwise.
513   bool isOrderedRegion() const {
514     if (isStackEmpty())
515       return false;
516     return Stack.back().first.rbegin()->OrderedRegion.hasValue();
517   }
518   /// Returns optional parameter for the ordered region.
519   std::pair<const Expr *, OMPOrderedClause *> getOrderedRegionParam() const {
520     if (isStackEmpty() ||
521         !Stack.back().first.rbegin()->OrderedRegion.hasValue())
522       return std::make_pair(nullptr, nullptr);
523     return Stack.back().first.rbegin()->OrderedRegion.getValue();
524   }
525   /// Returns true, if parent region is ordered (has associated
526   /// 'ordered' clause), false - otherwise.
527   bool isParentOrderedRegion() const {
528     if (isStackEmpty() || Stack.back().first.size() == 1)
529       return false;
530     return std::next(Stack.back().first.rbegin())->OrderedRegion.hasValue();
531   }
532   /// Returns optional parameter for the ordered region.
533   std::pair<const Expr *, OMPOrderedClause *>
534   getParentOrderedRegionParam() const {
535     if (isStackEmpty() || Stack.back().first.size() == 1 ||
536         !std::next(Stack.back().first.rbegin())->OrderedRegion.hasValue())
537       return std::make_pair(nullptr, nullptr);
538     return std::next(Stack.back().first.rbegin())->OrderedRegion.getValue();
539   }
540   /// Marks current region as nowait (it has a 'nowait' clause).
541   void setNowaitRegion(bool IsNowait = true) {
542     assert(!isStackEmpty());
543     Stack.back().first.back().NowaitRegion = IsNowait;
544   }
545   /// Returns true, if parent region is nowait (has associated
546   /// 'nowait' clause), false - otherwise.
547   bool isParentNowaitRegion() const {
548     if (isStackEmpty() || Stack.back().first.size() == 1)
549       return false;
550     return std::next(Stack.back().first.rbegin())->NowaitRegion;
551   }
552   /// Marks parent region as cancel region.
553   void setParentCancelRegion(bool Cancel = true) {
554     if (!isStackEmpty() && Stack.back().first.size() > 1) {
555       auto &StackElemRef = *std::next(Stack.back().first.rbegin());
556       StackElemRef.CancelRegion |= StackElemRef.CancelRegion || Cancel;
557     }
558   }
559   /// Return true if current region has inner cancel construct.
560   bool isCancelRegion() const {
561     return isStackEmpty() ? false : Stack.back().first.back().CancelRegion;
562   }
563 
564   /// Set collapse value for the region.
565   void setAssociatedLoops(unsigned Val) {
566     assert(!isStackEmpty());
567     Stack.back().first.back().AssociatedLoops = Val;
568   }
569   /// Return collapse value for region.
570   unsigned getAssociatedLoops() const {
571     return isStackEmpty() ? 0 : Stack.back().first.back().AssociatedLoops;
572   }
573 
574   /// Marks current target region as one with closely nested teams
575   /// region.
576   void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
577     if (!isStackEmpty() && Stack.back().first.size() > 1) {
578       std::next(Stack.back().first.rbegin())->InnerTeamsRegionLoc =
579           TeamsRegionLoc;
580     }
581   }
582   /// Returns true, if current region has closely nested teams region.
583   bool hasInnerTeamsRegion() const {
584     return getInnerTeamsRegionLoc().isValid();
585   }
586   /// Returns location of the nested teams region (if any).
587   SourceLocation getInnerTeamsRegionLoc() const {
588     return isStackEmpty() ? SourceLocation()
589                           : Stack.back().first.back().InnerTeamsRegionLoc;
590   }
591 
592   Scope *getCurScope() const {
593     return isStackEmpty() ? nullptr : Stack.back().first.back().CurScope;
594   }
595   SourceLocation getConstructLoc() const {
596     return isStackEmpty() ? SourceLocation()
597                           : Stack.back().first.back().ConstructLoc;
598   }
599 
600   /// Do the check specified in \a Check to all component lists and return true
601   /// if any issue is found.
602   bool checkMappableExprComponentListsForDecl(
603       const ValueDecl *VD, bool CurrentRegionOnly,
604       const llvm::function_ref<
605           bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
606                OpenMPClauseKind)>
607           Check) const {
608     if (isStackEmpty())
609       return false;
610     auto SI = Stack.back().first.rbegin();
611     auto SE = Stack.back().first.rend();
612 
613     if (SI == SE)
614       return false;
615 
616     if (CurrentRegionOnly)
617       SE = std::next(SI);
618     else
619       std::advance(SI, 1);
620 
621     for (; SI != SE; ++SI) {
622       auto MI = SI->MappedExprComponents.find(VD);
623       if (MI != SI->MappedExprComponents.end())
624         for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
625              MI->second.Components)
626           if (Check(L, MI->second.Kind))
627             return true;
628     }
629     return false;
630   }
631 
632   /// Do the check specified in \a Check to all component lists at a given level
633   /// and return true if any issue is found.
634   bool checkMappableExprComponentListsForDeclAtLevel(
635       const ValueDecl *VD, unsigned Level,
636       const llvm::function_ref<
637           bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
638                OpenMPClauseKind)>
639           Check) const {
640     if (isStackEmpty())
641       return false;
642 
643     auto StartI = Stack.back().first.begin();
644     auto EndI = Stack.back().first.end();
645     if (std::distance(StartI, EndI) <= (int)Level)
646       return false;
647     std::advance(StartI, Level);
648 
649     auto MI = StartI->MappedExprComponents.find(VD);
650     if (MI != StartI->MappedExprComponents.end())
651       for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
652            MI->second.Components)
653         if (Check(L, MI->second.Kind))
654           return true;
655     return false;
656   }
657 
658   /// Create a new mappable expression component list associated with a given
659   /// declaration and initialize it with the provided list of components.
660   void addMappableExpressionComponents(
661       const ValueDecl *VD,
662       OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
663       OpenMPClauseKind WhereFoundClauseKind) {
664     assert(!isStackEmpty() &&
665            "Not expecting to retrieve components from a empty stack!");
666     MappedExprComponentTy &MEC =
667         Stack.back().first.back().MappedExprComponents[VD];
668     // Create new entry and append the new components there.
669     MEC.Components.resize(MEC.Components.size() + 1);
670     MEC.Components.back().append(Components.begin(), Components.end());
671     MEC.Kind = WhereFoundClauseKind;
672   }
673 
674   unsigned getNestingLevel() const {
675     assert(!isStackEmpty());
676     return Stack.back().first.size() - 1;
677   }
678   void addDoacrossDependClause(OMPDependClause *C,
679                                const OperatorOffsetTy &OpsOffs) {
680     assert(!isStackEmpty() && Stack.back().first.size() > 1);
681     SharingMapTy &StackElem = *std::next(Stack.back().first.rbegin());
682     assert(isOpenMPWorksharingDirective(StackElem.Directive));
683     StackElem.DoacrossDepends.try_emplace(C, OpsOffs);
684   }
685   llvm::iterator_range<DoacrossDependMapTy::const_iterator>
686   getDoacrossDependClauses() const {
687     assert(!isStackEmpty());
688     const SharingMapTy &StackElem = Stack.back().first.back();
689     if (isOpenMPWorksharingDirective(StackElem.Directive)) {
690       const DoacrossDependMapTy &Ref = StackElem.DoacrossDepends;
691       return llvm::make_range(Ref.begin(), Ref.end());
692     }
693     return llvm::make_range(StackElem.DoacrossDepends.end(),
694                             StackElem.DoacrossDepends.end());
695   }
696 
697   // Store types of classes which have been explicitly mapped
698   void addMappedClassesQualTypes(QualType QT) {
699     SharingMapTy &StackElem = Stack.back().first.back();
700     StackElem.MappedClassesQualTypes.insert(QT);
701   }
702 
703   // Return set of mapped classes types
704   bool isClassPreviouslyMapped(QualType QT) const {
705     const SharingMapTy &StackElem = Stack.back().first.back();
706     return StackElem.MappedClassesQualTypes.count(QT) != 0;
707   }
708 
709   /// Adds global declare target to the parent target region.
710   void addToParentTargetRegionLinkGlobals(DeclRefExpr *E) {
711     assert(*OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
712                E->getDecl()) == OMPDeclareTargetDeclAttr::MT_Link &&
713            "Expected declare target link global.");
714     if (isStackEmpty())
715       return;
716     auto It = Stack.back().first.rbegin();
717     while (It != Stack.back().first.rend() &&
718            !isOpenMPTargetExecutionDirective(It->Directive))
719       ++It;
720     if (It != Stack.back().first.rend()) {
721       assert(isOpenMPTargetExecutionDirective(It->Directive) &&
722              "Expected target executable directive.");
723       It->DeclareTargetLinkVarDecls.push_back(E);
724     }
725   }
726 
727   /// Returns the list of globals with declare target link if current directive
728   /// is target.
729   ArrayRef<DeclRefExpr *> getLinkGlobals() const {
730     assert(isOpenMPTargetExecutionDirective(getCurrentDirective()) &&
731            "Expected target executable directive.");
732     return Stack.back().first.back().DeclareTargetLinkVarDecls;
733   }
734 };
735 
736 bool isImplicitTaskingRegion(OpenMPDirectiveKind DKind) {
737   return isOpenMPParallelDirective(DKind) || isOpenMPTeamsDirective(DKind);
738 }
739 
740 bool isImplicitOrExplicitTaskingRegion(OpenMPDirectiveKind DKind) {
741   return isImplicitTaskingRegion(DKind) || isOpenMPTaskingDirective(DKind) || DKind == OMPD_unknown;
742 }
743 
744 } // namespace
745 
746 static const Expr *getExprAsWritten(const Expr *E) {
747   if (const auto *FE = dyn_cast<FullExpr>(E))
748     E = FE->getSubExpr();
749 
750   if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
751     E = MTE->GetTemporaryExpr();
752 
753   while (const auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
754     E = Binder->getSubExpr();
755 
756   if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
757     E = ICE->getSubExprAsWritten();
758   return E->IgnoreParens();
759 }
760 
761 static Expr *getExprAsWritten(Expr *E) {
762   return const_cast<Expr *>(getExprAsWritten(const_cast<const Expr *>(E)));
763 }
764 
765 static const ValueDecl *getCanonicalDecl(const ValueDecl *D) {
766   if (const auto *CED = dyn_cast<OMPCapturedExprDecl>(D))
767     if (const auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
768       D = ME->getMemberDecl();
769   const auto *VD = dyn_cast<VarDecl>(D);
770   const auto *FD = dyn_cast<FieldDecl>(D);
771   if (VD != nullptr) {
772     VD = VD->getCanonicalDecl();
773     D = VD;
774   } else {
775     assert(FD);
776     FD = FD->getCanonicalDecl();
777     D = FD;
778   }
779   return D;
780 }
781 
782 static ValueDecl *getCanonicalDecl(ValueDecl *D) {
783   return const_cast<ValueDecl *>(
784       getCanonicalDecl(const_cast<const ValueDecl *>(D)));
785 }
786 
787 DSAStackTy::DSAVarData DSAStackTy::getDSA(iterator &Iter,
788                                           ValueDecl *D) const {
789   D = getCanonicalDecl(D);
790   auto *VD = dyn_cast<VarDecl>(D);
791   const auto *FD = dyn_cast<FieldDecl>(D);
792   DSAVarData DVar;
793   if (isStackEmpty() || Iter == Stack.back().first.rend()) {
794     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
795     // in a region but not in construct]
796     //  File-scope or namespace-scope variables referenced in called routines
797     //  in the region are shared unless they appear in a threadprivate
798     //  directive.
799     if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(VD))
800       DVar.CKind = OMPC_shared;
801 
802     // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
803     // in a region but not in construct]
804     //  Variables with static storage duration that are declared in called
805     //  routines in the region are shared.
806     if (VD && VD->hasGlobalStorage())
807       DVar.CKind = OMPC_shared;
808 
809     // Non-static data members are shared by default.
810     if (FD)
811       DVar.CKind = OMPC_shared;
812 
813     return DVar;
814   }
815 
816   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
817   // in a Construct, C/C++, predetermined, p.1]
818   // Variables with automatic storage duration that are declared in a scope
819   // inside the construct are private.
820   if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() &&
821       (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) {
822     DVar.CKind = OMPC_private;
823     return DVar;
824   }
825 
826   DVar.DKind = Iter->Directive;
827   // Explicitly specified attributes and local variables with predetermined
828   // attributes.
829   if (Iter->SharingMap.count(D)) {
830     const DSAInfo &Data = Iter->SharingMap.lookup(D);
831     DVar.RefExpr = Data.RefExpr.getPointer();
832     DVar.PrivateCopy = Data.PrivateCopy;
833     DVar.CKind = Data.Attributes;
834     DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
835     return DVar;
836   }
837 
838   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
839   // in a Construct, C/C++, implicitly determined, p.1]
840   //  In a parallel or task construct, the data-sharing attributes of these
841   //  variables are determined by the default clause, if present.
842   switch (Iter->DefaultAttr) {
843   case DSA_shared:
844     DVar.CKind = OMPC_shared;
845     DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
846     return DVar;
847   case DSA_none:
848     return DVar;
849   case DSA_unspecified:
850     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
851     // in a Construct, implicitly determined, p.2]
852     //  In a parallel construct, if no default clause is present, these
853     //  variables are shared.
854     DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
855     if (isOpenMPParallelDirective(DVar.DKind) ||
856         isOpenMPTeamsDirective(DVar.DKind)) {
857       DVar.CKind = OMPC_shared;
858       return DVar;
859     }
860 
861     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
862     // in a Construct, implicitly determined, p.4]
863     //  In a task construct, if no default clause is present, a variable that in
864     //  the enclosing context is determined to be shared by all implicit tasks
865     //  bound to the current team is shared.
866     if (isOpenMPTaskingDirective(DVar.DKind)) {
867       DSAVarData DVarTemp;
868       iterator I = Iter, E = Stack.back().first.rend();
869       do {
870         ++I;
871         // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
872         // Referenced in a Construct, implicitly determined, p.6]
873         //  In a task construct, if no default clause is present, a variable
874         //  whose data-sharing attribute is not determined by the rules above is
875         //  firstprivate.
876         DVarTemp = getDSA(I, D);
877         if (DVarTemp.CKind != OMPC_shared) {
878           DVar.RefExpr = nullptr;
879           DVar.CKind = OMPC_firstprivate;
880           return DVar;
881         }
882       } while (I != E && !isImplicitTaskingRegion(I->Directive));
883       DVar.CKind =
884           (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
885       return DVar;
886     }
887   }
888   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
889   // in a Construct, implicitly determined, p.3]
890   //  For constructs other than task, if no default clause is present, these
891   //  variables inherit their data-sharing attributes from the enclosing
892   //  context.
893   return getDSA(++Iter, D);
894 }
895 
896 const Expr *DSAStackTy::addUniqueAligned(const ValueDecl *D,
897                                          const Expr *NewDE) {
898   assert(!isStackEmpty() && "Data sharing attributes stack is empty");
899   D = getCanonicalDecl(D);
900   SharingMapTy &StackElem = Stack.back().first.back();
901   auto It = StackElem.AlignedMap.find(D);
902   if (It == StackElem.AlignedMap.end()) {
903     assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
904     StackElem.AlignedMap[D] = NewDE;
905     return nullptr;
906   }
907   assert(It->second && "Unexpected nullptr expr in the aligned map");
908   return It->second;
909 }
910 
911 void DSAStackTy::addLoopControlVariable(const ValueDecl *D, VarDecl *Capture) {
912   assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
913   D = getCanonicalDecl(D);
914   SharingMapTy &StackElem = Stack.back().first.back();
915   StackElem.LCVMap.try_emplace(
916       D, LCDeclInfo(StackElem.LCVMap.size() + 1, Capture));
917 }
918 
919 const DSAStackTy::LCDeclInfo
920 DSAStackTy::isLoopControlVariable(const ValueDecl *D) const {
921   assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
922   D = getCanonicalDecl(D);
923   const SharingMapTy &StackElem = Stack.back().first.back();
924   auto It = StackElem.LCVMap.find(D);
925   if (It != StackElem.LCVMap.end())
926     return It->second;
927   return {0, nullptr};
928 }
929 
930 const DSAStackTy::LCDeclInfo
931 DSAStackTy::isParentLoopControlVariable(const ValueDecl *D) const {
932   assert(!isStackEmpty() && Stack.back().first.size() > 1 &&
933          "Data-sharing attributes stack is empty");
934   D = getCanonicalDecl(D);
935   const SharingMapTy &StackElem = *std::next(Stack.back().first.rbegin());
936   auto It = StackElem.LCVMap.find(D);
937   if (It != StackElem.LCVMap.end())
938     return It->second;
939   return {0, nullptr};
940 }
941 
942 const ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) const {
943   assert(!isStackEmpty() && Stack.back().first.size() > 1 &&
944          "Data-sharing attributes stack is empty");
945   const SharingMapTy &StackElem = *std::next(Stack.back().first.rbegin());
946   if (StackElem.LCVMap.size() < I)
947     return nullptr;
948   for (const auto &Pair : StackElem.LCVMap)
949     if (Pair.second.first == I)
950       return Pair.first;
951   return nullptr;
952 }
953 
954 void DSAStackTy::addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
955                         DeclRefExpr *PrivateCopy) {
956   D = getCanonicalDecl(D);
957   if (A == OMPC_threadprivate) {
958     DSAInfo &Data = Threadprivates[D];
959     Data.Attributes = A;
960     Data.RefExpr.setPointer(E);
961     Data.PrivateCopy = nullptr;
962   } else {
963     assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
964     DSAInfo &Data = Stack.back().first.back().SharingMap[D];
965     assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
966            (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) ||
967            (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) ||
968            (isLoopControlVariable(D).first && A == OMPC_private));
969     if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) {
970       Data.RefExpr.setInt(/*IntVal=*/true);
971       return;
972     }
973     const bool IsLastprivate =
974         A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate;
975     Data.Attributes = A;
976     Data.RefExpr.setPointerAndInt(E, IsLastprivate);
977     Data.PrivateCopy = PrivateCopy;
978     if (PrivateCopy) {
979       DSAInfo &Data =
980           Stack.back().first.back().SharingMap[PrivateCopy->getDecl()];
981       Data.Attributes = A;
982       Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate);
983       Data.PrivateCopy = nullptr;
984     }
985   }
986 }
987 
988 /// Build a variable declaration for OpenMP loop iteration variable.
989 static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
990                              StringRef Name, const AttrVec *Attrs = nullptr,
991                              DeclRefExpr *OrigRef = nullptr) {
992   DeclContext *DC = SemaRef.CurContext;
993   IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
994   TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
995   auto *Decl =
996       VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
997   if (Attrs) {
998     for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
999          I != E; ++I)
1000       Decl->addAttr(*I);
1001   }
1002   Decl->setImplicit();
1003   if (OrigRef) {
1004     Decl->addAttr(
1005         OMPReferencedVarAttr::CreateImplicit(SemaRef.Context, OrigRef));
1006   }
1007   return Decl;
1008 }
1009 
1010 static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
1011                                      SourceLocation Loc,
1012                                      bool RefersToCapture = false) {
1013   D->setReferenced();
1014   D->markUsed(S.Context);
1015   return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
1016                              SourceLocation(), D, RefersToCapture, Loc, Ty,
1017                              VK_LValue);
1018 }
1019 
1020 void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
1021                                            BinaryOperatorKind BOK) {
1022   D = getCanonicalDecl(D);
1023   assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
1024   assert(
1025       Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction &&
1026       "Additional reduction info may be specified only for reduction items.");
1027   ReductionData &ReductionData = Stack.back().first.back().ReductionMap[D];
1028   assert(ReductionData.ReductionRange.isInvalid() &&
1029          Stack.back().first.back().Directive == OMPD_taskgroup &&
1030          "Additional reduction info may be specified only once for reduction "
1031          "items.");
1032   ReductionData.set(BOK, SR);
1033   Expr *&TaskgroupReductionRef =
1034       Stack.back().first.back().TaskgroupReductionRef;
1035   if (!TaskgroupReductionRef) {
1036     VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
1037                                SemaRef.Context.VoidPtrTy, ".task_red.");
1038     TaskgroupReductionRef =
1039         buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
1040   }
1041 }
1042 
1043 void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
1044                                            const Expr *ReductionRef) {
1045   D = getCanonicalDecl(D);
1046   assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
1047   assert(
1048       Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction &&
1049       "Additional reduction info may be specified only for reduction items.");
1050   ReductionData &ReductionData = Stack.back().first.back().ReductionMap[D];
1051   assert(ReductionData.ReductionRange.isInvalid() &&
1052          Stack.back().first.back().Directive == OMPD_taskgroup &&
1053          "Additional reduction info may be specified only once for reduction "
1054          "items.");
1055   ReductionData.set(ReductionRef, SR);
1056   Expr *&TaskgroupReductionRef =
1057       Stack.back().first.back().TaskgroupReductionRef;
1058   if (!TaskgroupReductionRef) {
1059     VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
1060                                SemaRef.Context.VoidPtrTy, ".task_red.");
1061     TaskgroupReductionRef =
1062         buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
1063   }
1064 }
1065 
1066 const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
1067     const ValueDecl *D, SourceRange &SR, BinaryOperatorKind &BOK,
1068     Expr *&TaskgroupDescriptor) const {
1069   D = getCanonicalDecl(D);
1070   assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
1071   if (Stack.back().first.empty())
1072       return DSAVarData();
1073   for (iterator I = std::next(Stack.back().first.rbegin(), 1),
1074                 E = Stack.back().first.rend();
1075        I != E; std::advance(I, 1)) {
1076     const DSAInfo &Data = I->SharingMap.lookup(D);
1077     if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
1078       continue;
1079     const ReductionData &ReductionData = I->ReductionMap.lookup(D);
1080     if (!ReductionData.ReductionOp ||
1081         ReductionData.ReductionOp.is<const Expr *>())
1082       return DSAVarData();
1083     SR = ReductionData.ReductionRange;
1084     BOK = ReductionData.ReductionOp.get<ReductionData::BOKPtrType>();
1085     assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
1086                                        "expression for the descriptor is not "
1087                                        "set.");
1088     TaskgroupDescriptor = I->TaskgroupReductionRef;
1089     return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
1090                       Data.PrivateCopy, I->DefaultAttrLoc);
1091   }
1092   return DSAVarData();
1093 }
1094 
1095 const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
1096     const ValueDecl *D, SourceRange &SR, const Expr *&ReductionRef,
1097     Expr *&TaskgroupDescriptor) const {
1098   D = getCanonicalDecl(D);
1099   assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
1100   if (Stack.back().first.empty())
1101       return DSAVarData();
1102   for (iterator I = std::next(Stack.back().first.rbegin(), 1),
1103                 E = Stack.back().first.rend();
1104        I != E; std::advance(I, 1)) {
1105     const DSAInfo &Data = I->SharingMap.lookup(D);
1106     if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
1107       continue;
1108     const ReductionData &ReductionData = I->ReductionMap.lookup(D);
1109     if (!ReductionData.ReductionOp ||
1110         !ReductionData.ReductionOp.is<const Expr *>())
1111       return DSAVarData();
1112     SR = ReductionData.ReductionRange;
1113     ReductionRef = ReductionData.ReductionOp.get<const Expr *>();
1114     assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
1115                                        "expression for the descriptor is not "
1116                                        "set.");
1117     TaskgroupDescriptor = I->TaskgroupReductionRef;
1118     return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
1119                       Data.PrivateCopy, I->DefaultAttrLoc);
1120   }
1121   return DSAVarData();
1122 }
1123 
1124 bool DSAStackTy::isOpenMPLocal(VarDecl *D, iterator Iter) const {
1125   D = D->getCanonicalDecl();
1126   if (!isStackEmpty()) {
1127     iterator I = Iter, E = Stack.back().first.rend();
1128     Scope *TopScope = nullptr;
1129     while (I != E && !isImplicitOrExplicitTaskingRegion(I->Directive) &&
1130            !isOpenMPTargetExecutionDirective(I->Directive))
1131       ++I;
1132     if (I == E)
1133       return false;
1134     TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
1135     Scope *CurScope = getCurScope();
1136     while (CurScope != TopScope && !CurScope->isDeclScope(D))
1137       CurScope = CurScope->getParent();
1138     return CurScope != TopScope;
1139   }
1140   return false;
1141 }
1142 
1143 static bool isConstNotMutableType(Sema &SemaRef, QualType Type,
1144                                   bool AcceptIfMutable = true,
1145                                   bool *IsClassType = nullptr) {
1146   ASTContext &Context = SemaRef.getASTContext();
1147   Type = Type.getNonReferenceType().getCanonicalType();
1148   bool IsConstant = Type.isConstant(Context);
1149   Type = Context.getBaseElementType(Type);
1150   const CXXRecordDecl *RD = AcceptIfMutable && SemaRef.getLangOpts().CPlusPlus
1151                                 ? Type->getAsCXXRecordDecl()
1152                                 : nullptr;
1153   if (const auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
1154     if (const ClassTemplateDecl *CTD = CTSD->getSpecializedTemplate())
1155       RD = CTD->getTemplatedDecl();
1156   if (IsClassType)
1157     *IsClassType = RD;
1158   return IsConstant && !(SemaRef.getLangOpts().CPlusPlus && RD &&
1159                          RD->hasDefinition() && RD->hasMutableFields());
1160 }
1161 
1162 static bool rejectConstNotMutableType(Sema &SemaRef, const ValueDecl *D,
1163                                       QualType Type, OpenMPClauseKind CKind,
1164                                       SourceLocation ELoc,
1165                                       bool AcceptIfMutable = true,
1166                                       bool ListItemNotVar = false) {
1167   ASTContext &Context = SemaRef.getASTContext();
1168   bool IsClassType;
1169   if (isConstNotMutableType(SemaRef, Type, AcceptIfMutable, &IsClassType)) {
1170     unsigned Diag = ListItemNotVar
1171                         ? diag::err_omp_const_list_item
1172                         : IsClassType ? diag::err_omp_const_not_mutable_variable
1173                                       : diag::err_omp_const_variable;
1174     SemaRef.Diag(ELoc, Diag) << getOpenMPClauseName(CKind);
1175     if (!ListItemNotVar && D) {
1176       const VarDecl *VD = dyn_cast<VarDecl>(D);
1177       bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
1178                                VarDecl::DeclarationOnly;
1179       SemaRef.Diag(D->getLocation(),
1180                    IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1181           << D;
1182     }
1183     return true;
1184   }
1185   return false;
1186 }
1187 
1188 const DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D,
1189                                                    bool FromParent) {
1190   D = getCanonicalDecl(D);
1191   DSAVarData DVar;
1192 
1193   auto *VD = dyn_cast<VarDecl>(D);
1194   auto TI = Threadprivates.find(D);
1195   if (TI != Threadprivates.end()) {
1196     DVar.RefExpr = TI->getSecond().RefExpr.getPointer();
1197     DVar.CKind = OMPC_threadprivate;
1198     return DVar;
1199   }
1200   if (VD && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
1201     DVar.RefExpr = buildDeclRefExpr(
1202         SemaRef, VD, D->getType().getNonReferenceType(),
1203         VD->getAttr<OMPThreadPrivateDeclAttr>()->getLocation());
1204     DVar.CKind = OMPC_threadprivate;
1205     addDSA(D, DVar.RefExpr, OMPC_threadprivate);
1206     return DVar;
1207   }
1208   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1209   // in a Construct, C/C++, predetermined, p.1]
1210   //  Variables appearing in threadprivate directives are threadprivate.
1211   if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
1212        !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
1213          SemaRef.getLangOpts().OpenMPUseTLS &&
1214          SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
1215       (VD && VD->getStorageClass() == SC_Register &&
1216        VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
1217     DVar.RefExpr = buildDeclRefExpr(
1218         SemaRef, VD, D->getType().getNonReferenceType(), D->getLocation());
1219     DVar.CKind = OMPC_threadprivate;
1220     addDSA(D, DVar.RefExpr, OMPC_threadprivate);
1221     return DVar;
1222   }
1223   if (SemaRef.getLangOpts().OpenMPCUDAMode && VD &&
1224       VD->isLocalVarDeclOrParm() && !isStackEmpty() &&
1225       !isLoopControlVariable(D).first) {
1226     iterator IterTarget =
1227         std::find_if(Stack.back().first.rbegin(), Stack.back().first.rend(),
1228                      [](const SharingMapTy &Data) {
1229                        return isOpenMPTargetExecutionDirective(Data.Directive);
1230                      });
1231     if (IterTarget != Stack.back().first.rend()) {
1232       iterator ParentIterTarget = std::next(IterTarget, 1);
1233       for (iterator Iter = Stack.back().first.rbegin();
1234            Iter != ParentIterTarget; std::advance(Iter, 1)) {
1235         if (isOpenMPLocal(VD, Iter)) {
1236           DVar.RefExpr =
1237               buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
1238                                D->getLocation());
1239           DVar.CKind = OMPC_threadprivate;
1240           return DVar;
1241         }
1242       }
1243       if (!isClauseParsingMode() || IterTarget != Stack.back().first.rbegin()) {
1244         auto DSAIter = IterTarget->SharingMap.find(D);
1245         if (DSAIter != IterTarget->SharingMap.end() &&
1246             isOpenMPPrivate(DSAIter->getSecond().Attributes)) {
1247           DVar.RefExpr = DSAIter->getSecond().RefExpr.getPointer();
1248           DVar.CKind = OMPC_threadprivate;
1249           return DVar;
1250         }
1251         iterator End = Stack.back().first.rend();
1252         if (!SemaRef.isOpenMPCapturedByRef(
1253                 D, std::distance(ParentIterTarget, End))) {
1254           DVar.RefExpr =
1255               buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
1256                                IterTarget->ConstructLoc);
1257           DVar.CKind = OMPC_threadprivate;
1258           return DVar;
1259         }
1260       }
1261     }
1262   }
1263 
1264   if (isStackEmpty())
1265     // Not in OpenMP execution region and top scope was already checked.
1266     return DVar;
1267 
1268   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1269   // in a Construct, C/C++, predetermined, p.4]
1270   //  Static data members are shared.
1271   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1272   // in a Construct, C/C++, predetermined, p.7]
1273   //  Variables with static storage duration that are declared in a scope
1274   //  inside the construct are shared.
1275   auto &&MatchesAlways = [](OpenMPDirectiveKind) { return true; };
1276   if (VD && VD->isStaticDataMember()) {
1277     DSAVarData DVarTemp = hasDSA(D, isOpenMPPrivate, MatchesAlways, FromParent);
1278     if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
1279       return DVar;
1280 
1281     DVar.CKind = OMPC_shared;
1282     return DVar;
1283   }
1284 
1285   // The predetermined shared attribute for const-qualified types having no
1286   // mutable members was removed after OpenMP 3.1.
1287   if (SemaRef.LangOpts.OpenMP <= 31) {
1288     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1289     // in a Construct, C/C++, predetermined, p.6]
1290     //  Variables with const qualified type having no mutable member are
1291     //  shared.
1292     if (isConstNotMutableType(SemaRef, D->getType())) {
1293       // Variables with const-qualified type having no mutable member may be
1294       // listed in a firstprivate clause, even if they are static data members.
1295       DSAVarData DVarTemp = hasInnermostDSA(
1296           D,
1297           [](OpenMPClauseKind C) {
1298             return C == OMPC_firstprivate || C == OMPC_shared;
1299           },
1300           MatchesAlways, FromParent);
1301       if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
1302         return DVarTemp;
1303 
1304       DVar.CKind = OMPC_shared;
1305       return DVar;
1306     }
1307   }
1308 
1309   // Explicitly specified attributes and local variables with predetermined
1310   // attributes.
1311   iterator I = Stack.back().first.rbegin();
1312   iterator EndI = Stack.back().first.rend();
1313   if (FromParent && I != EndI)
1314     std::advance(I, 1);
1315   auto It = I->SharingMap.find(D);
1316   if (It != I->SharingMap.end()) {
1317     const DSAInfo &Data = It->getSecond();
1318     DVar.RefExpr = Data.RefExpr.getPointer();
1319     DVar.PrivateCopy = Data.PrivateCopy;
1320     DVar.CKind = Data.Attributes;
1321     DVar.ImplicitDSALoc = I->DefaultAttrLoc;
1322     DVar.DKind = I->Directive;
1323   }
1324 
1325   return DVar;
1326 }
1327 
1328 const DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
1329                                                         bool FromParent) const {
1330   if (isStackEmpty()) {
1331     iterator I;
1332     return getDSA(I, D);
1333   }
1334   D = getCanonicalDecl(D);
1335   iterator StartI = Stack.back().first.rbegin();
1336   iterator EndI = Stack.back().first.rend();
1337   if (FromParent && StartI != EndI)
1338     std::advance(StartI, 1);
1339   return getDSA(StartI, D);
1340 }
1341 
1342 const DSAStackTy::DSAVarData
1343 DSAStackTy::hasDSA(ValueDecl *D,
1344                    const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
1345                    const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
1346                    bool FromParent) const {
1347   if (isStackEmpty())
1348     return {};
1349   D = getCanonicalDecl(D);
1350   iterator I = Stack.back().first.rbegin();
1351   iterator EndI = Stack.back().first.rend();
1352   if (FromParent && I != EndI)
1353     std::advance(I, 1);
1354   for (; I != EndI; std::advance(I, 1)) {
1355     if (!DPred(I->Directive) && !isImplicitOrExplicitTaskingRegion(I->Directive))
1356       continue;
1357     iterator NewI = I;
1358     DSAVarData DVar = getDSA(NewI, D);
1359     if (I == NewI && CPred(DVar.CKind))
1360       return DVar;
1361   }
1362   return {};
1363 }
1364 
1365 const DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
1366     ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
1367     const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
1368     bool FromParent) const {
1369   if (isStackEmpty())
1370     return {};
1371   D = getCanonicalDecl(D);
1372   iterator StartI = Stack.back().first.rbegin();
1373   iterator EndI = Stack.back().first.rend();
1374   if (FromParent && StartI != EndI)
1375     std::advance(StartI, 1);
1376   if (StartI == EndI || !DPred(StartI->Directive))
1377     return {};
1378   iterator NewI = StartI;
1379   DSAVarData DVar = getDSA(NewI, D);
1380   return (NewI == StartI && CPred(DVar.CKind)) ? DVar : DSAVarData();
1381 }
1382 
1383 bool DSAStackTy::hasExplicitDSA(
1384     const ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
1385     unsigned Level, bool NotLastprivate) const {
1386   if (isStackEmpty())
1387     return false;
1388   D = getCanonicalDecl(D);
1389   auto StartI = Stack.back().first.begin();
1390   auto EndI = Stack.back().first.end();
1391   if (std::distance(StartI, EndI) <= (int)Level)
1392     return false;
1393   std::advance(StartI, Level);
1394   auto I = StartI->SharingMap.find(D);
1395   if ((I != StartI->SharingMap.end()) &&
1396          I->getSecond().RefExpr.getPointer() &&
1397          CPred(I->getSecond().Attributes) &&
1398          (!NotLastprivate || !I->getSecond().RefExpr.getInt()))
1399     return true;
1400   // Check predetermined rules for the loop control variables.
1401   auto LI = StartI->LCVMap.find(D);
1402   if (LI != StartI->LCVMap.end())
1403     return CPred(OMPC_private);
1404   return false;
1405 }
1406 
1407 bool DSAStackTy::hasExplicitDirective(
1408     const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
1409     unsigned Level) const {
1410   if (isStackEmpty())
1411     return false;
1412   auto StartI = Stack.back().first.begin();
1413   auto EndI = Stack.back().first.end();
1414   if (std::distance(StartI, EndI) <= (int)Level)
1415     return false;
1416   std::advance(StartI, Level);
1417   return DPred(StartI->Directive);
1418 }
1419 
1420 bool DSAStackTy::hasDirective(
1421     const llvm::function_ref<bool(OpenMPDirectiveKind,
1422                                   const DeclarationNameInfo &, SourceLocation)>
1423         DPred,
1424     bool FromParent) const {
1425   // We look only in the enclosing region.
1426   if (isStackEmpty())
1427     return false;
1428   auto StartI = std::next(Stack.back().first.rbegin());
1429   auto EndI = Stack.back().first.rend();
1430   if (FromParent && StartI != EndI)
1431     StartI = std::next(StartI);
1432   for (auto I = StartI, EE = EndI; I != EE; ++I) {
1433     if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
1434       return true;
1435   }
1436   return false;
1437 }
1438 
1439 void Sema::InitDataSharingAttributesStack() {
1440   VarDataSharingAttributesStack = new DSAStackTy(*this);
1441 }
1442 
1443 #define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
1444 
1445 void Sema::pushOpenMPFunctionRegion() {
1446   DSAStack->pushFunction();
1447 }
1448 
1449 void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) {
1450   DSAStack->popFunction(OldFSI);
1451 }
1452 
1453 static bool isOpenMPDeviceDelayedContext(Sema &S) {
1454   assert(S.LangOpts.OpenMP && S.LangOpts.OpenMPIsDevice &&
1455          "Expected OpenMP device compilation.");
1456   return !S.isInOpenMPTargetExecutionDirective() &&
1457          !S.isInOpenMPDeclareTargetContext();
1458 }
1459 
1460 /// Do we know that we will eventually codegen the given function?
1461 static bool isKnownEmitted(Sema &S, FunctionDecl *FD) {
1462   assert(S.LangOpts.OpenMP && S.LangOpts.OpenMPIsDevice &&
1463          "Expected OpenMP device compilation.");
1464   // Templates are emitted when they're instantiated.
1465   if (FD->isDependentContext())
1466     return false;
1467 
1468   if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
1469           FD->getCanonicalDecl()))
1470     return true;
1471 
1472   // Otherwise, the function is known-emitted if it's in our set of
1473   // known-emitted functions.
1474   return S.DeviceKnownEmittedFns.count(FD) > 0;
1475 }
1476 
1477 Sema::DeviceDiagBuilder Sema::diagIfOpenMPDeviceCode(SourceLocation Loc,
1478                                                      unsigned DiagID) {
1479   assert(LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
1480          "Expected OpenMP device compilation.");
1481   return DeviceDiagBuilder((isOpenMPDeviceDelayedContext(*this) &&
1482                             !isKnownEmitted(*this, getCurFunctionDecl()))
1483                                ? DeviceDiagBuilder::K_Deferred
1484                                : DeviceDiagBuilder::K_Immediate,
1485                            Loc, DiagID, getCurFunctionDecl(), *this);
1486 }
1487 
1488 void Sema::checkOpenMPDeviceFunction(SourceLocation Loc, FunctionDecl *Callee) {
1489   assert(LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
1490          "Expected OpenMP device compilation.");
1491   assert(Callee && "Callee may not be null.");
1492   FunctionDecl *Caller = getCurFunctionDecl();
1493 
1494   // If the caller is known-emitted, mark the callee as known-emitted.
1495   // Otherwise, mark the call in our call graph so we can traverse it later.
1496   if (!isOpenMPDeviceDelayedContext(*this) ||
1497       (Caller && isKnownEmitted(*this, Caller)))
1498     markKnownEmitted(*this, Caller, Callee, Loc, isKnownEmitted);
1499   else if (Caller)
1500     DeviceCallGraph[Caller].insert({Callee, Loc});
1501 }
1502 
1503 void Sema::checkOpenMPDeviceExpr(const Expr *E) {
1504   assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
1505          "OpenMP device compilation mode is expected.");
1506   QualType Ty = E->getType();
1507   if ((Ty->isFloat16Type() && !Context.getTargetInfo().hasFloat16Type()) ||
1508       (Ty->isFloat128Type() && !Context.getTargetInfo().hasFloat128Type()) ||
1509       (Ty->isIntegerType() && Context.getTypeSize(Ty) == 128 &&
1510        !Context.getTargetInfo().hasInt128Type()))
1511     targetDiag(E->getExprLoc(), diag::err_type_unsupported)
1512         << Ty << E->getSourceRange();
1513 }
1514 
1515 bool Sema::isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level) const {
1516   assert(LangOpts.OpenMP && "OpenMP is not allowed");
1517 
1518   ASTContext &Ctx = getASTContext();
1519   bool IsByRef = true;
1520 
1521   // Find the directive that is associated with the provided scope.
1522   D = cast<ValueDecl>(D->getCanonicalDecl());
1523   QualType Ty = D->getType();
1524 
1525   if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
1526     // This table summarizes how a given variable should be passed to the device
1527     // given its type and the clauses where it appears. This table is based on
1528     // the description in OpenMP 4.5 [2.10.4, target Construct] and
1529     // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
1530     //
1531     // =========================================================================
1532     // | type |  defaultmap   | pvt | first | is_device_ptr |    map   | res.  |
1533     // |      |(tofrom:scalar)|     |  pvt  |               |          |       |
1534     // =========================================================================
1535     // | scl  |               |     |       |       -       |          | bycopy|
1536     // | scl  |               |  -  |   x   |       -       |     -    | bycopy|
1537     // | scl  |               |  x  |   -   |       -       |     -    | null  |
1538     // | scl  |       x       |     |       |       -       |          | byref |
1539     // | scl  |       x       |  -  |   x   |       -       |     -    | bycopy|
1540     // | scl  |       x       |  x  |   -   |       -       |     -    | null  |
1541     // | scl  |               |  -  |   -   |       -       |     x    | byref |
1542     // | scl  |       x       |  -  |   -   |       -       |     x    | byref |
1543     //
1544     // | agg  |      n.a.     |     |       |       -       |          | byref |
1545     // | agg  |      n.a.     |  -  |   x   |       -       |     -    | byref |
1546     // | agg  |      n.a.     |  x  |   -   |       -       |     -    | null  |
1547     // | agg  |      n.a.     |  -  |   -   |       -       |     x    | byref |
1548     // | agg  |      n.a.     |  -  |   -   |       -       |    x[]   | byref |
1549     //
1550     // | ptr  |      n.a.     |     |       |       -       |          | bycopy|
1551     // | ptr  |      n.a.     |  -  |   x   |       -       |     -    | bycopy|
1552     // | ptr  |      n.a.     |  x  |   -   |       -       |     -    | null  |
1553     // | ptr  |      n.a.     |  -  |   -   |       -       |     x    | byref |
1554     // | ptr  |      n.a.     |  -  |   -   |       -       |    x[]   | bycopy|
1555     // | ptr  |      n.a.     |  -  |   -   |       x       |          | bycopy|
1556     // | ptr  |      n.a.     |  -  |   -   |       x       |     x    | bycopy|
1557     // | ptr  |      n.a.     |  -  |   -   |       x       |    x[]   | bycopy|
1558     // =========================================================================
1559     // Legend:
1560     //  scl - scalar
1561     //  ptr - pointer
1562     //  agg - aggregate
1563     //  x - applies
1564     //  - - invalid in this combination
1565     //  [] - mapped with an array section
1566     //  byref - should be mapped by reference
1567     //  byval - should be mapped by value
1568     //  null - initialize a local variable to null on the device
1569     //
1570     // Observations:
1571     //  - All scalar declarations that show up in a map clause have to be passed
1572     //    by reference, because they may have been mapped in the enclosing data
1573     //    environment.
1574     //  - If the scalar value does not fit the size of uintptr, it has to be
1575     //    passed by reference, regardless the result in the table above.
1576     //  - For pointers mapped by value that have either an implicit map or an
1577     //    array section, the runtime library may pass the NULL value to the
1578     //    device instead of the value passed to it by the compiler.
1579 
1580     if (Ty->isReferenceType())
1581       Ty = Ty->castAs<ReferenceType>()->getPointeeType();
1582 
1583     // Locate map clauses and see if the variable being captured is referred to
1584     // in any of those clauses. Here we only care about variables, not fields,
1585     // because fields are part of aggregates.
1586     bool IsVariableUsedInMapClause = false;
1587     bool IsVariableAssociatedWithSection = false;
1588 
1589     DSAStack->checkMappableExprComponentListsForDeclAtLevel(
1590         D, Level,
1591         [&IsVariableUsedInMapClause, &IsVariableAssociatedWithSection, D](
1592             OMPClauseMappableExprCommon::MappableExprComponentListRef
1593                 MapExprComponents,
1594             OpenMPClauseKind WhereFoundClauseKind) {
1595           // Only the map clause information influences how a variable is
1596           // captured. E.g. is_device_ptr does not require changing the default
1597           // behavior.
1598           if (WhereFoundClauseKind != OMPC_map)
1599             return false;
1600 
1601           auto EI = MapExprComponents.rbegin();
1602           auto EE = MapExprComponents.rend();
1603 
1604           assert(EI != EE && "Invalid map expression!");
1605 
1606           if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
1607             IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
1608 
1609           ++EI;
1610           if (EI == EE)
1611             return false;
1612 
1613           if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
1614               isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
1615               isa<MemberExpr>(EI->getAssociatedExpression())) {
1616             IsVariableAssociatedWithSection = true;
1617             // There is nothing more we need to know about this variable.
1618             return true;
1619           }
1620 
1621           // Keep looking for more map info.
1622           return false;
1623         });
1624 
1625     if (IsVariableUsedInMapClause) {
1626       // If variable is identified in a map clause it is always captured by
1627       // reference except if it is a pointer that is dereferenced somehow.
1628       IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
1629     } else {
1630       // By default, all the data that has a scalar type is mapped by copy
1631       // (except for reduction variables).
1632       IsByRef =
1633           (DSAStack->isForceCaptureByReferenceInTargetExecutable() &&
1634            !Ty->isAnyPointerType()) ||
1635           !Ty->isScalarType() ||
1636           DSAStack->getDefaultDMAAtLevel(Level) == DMA_tofrom_scalar ||
1637           DSAStack->hasExplicitDSA(
1638               D, [](OpenMPClauseKind K) { return K == OMPC_reduction; }, Level);
1639     }
1640   }
1641 
1642   if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
1643     IsByRef =
1644         ((DSAStack->isForceCaptureByReferenceInTargetExecutable() &&
1645           !Ty->isAnyPointerType()) ||
1646          !DSAStack->hasExplicitDSA(
1647              D,
1648              [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; },
1649              Level, /*NotLastprivate=*/true)) &&
1650         // If the variable is artificial and must be captured by value - try to
1651         // capture by value.
1652         !(isa<OMPCapturedExprDecl>(D) && !D->hasAttr<OMPCaptureNoInitAttr>() &&
1653           !cast<OMPCapturedExprDecl>(D)->getInit()->isGLValue());
1654   }
1655 
1656   // When passing data by copy, we need to make sure it fits the uintptr size
1657   // and alignment, because the runtime library only deals with uintptr types.
1658   // If it does not fit the uintptr size, we need to pass the data by reference
1659   // instead.
1660   if (!IsByRef &&
1661       (Ctx.getTypeSizeInChars(Ty) >
1662            Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
1663        Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
1664     IsByRef = true;
1665   }
1666 
1667   return IsByRef;
1668 }
1669 
1670 unsigned Sema::getOpenMPNestingLevel() const {
1671   assert(getLangOpts().OpenMP);
1672   return DSAStack->getNestingLevel();
1673 }
1674 
1675 bool Sema::isInOpenMPTargetExecutionDirective() const {
1676   return (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) &&
1677           !DSAStack->isClauseParsingMode()) ||
1678          DSAStack->hasDirective(
1679              [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
1680                 SourceLocation) -> bool {
1681                return isOpenMPTargetExecutionDirective(K);
1682              },
1683              false);
1684 }
1685 
1686 VarDecl *Sema::isOpenMPCapturedDecl(ValueDecl *D) {
1687   assert(LangOpts.OpenMP && "OpenMP is not allowed");
1688   D = getCanonicalDecl(D);
1689 
1690   // If we are attempting to capture a global variable in a directive with
1691   // 'target' we return true so that this global is also mapped to the device.
1692   //
1693   auto *VD = dyn_cast<VarDecl>(D);
1694   if (VD && !VD->hasLocalStorage()) {
1695     if (isInOpenMPDeclareTargetContext() &&
1696         (getCurCapturedRegion() || getCurBlock() || getCurLambda())) {
1697       // Try to mark variable as declare target if it is used in capturing
1698       // regions.
1699       if (!OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
1700         checkDeclIsAllowedInOpenMPTarget(nullptr, VD);
1701       return nullptr;
1702     } else if (isInOpenMPTargetExecutionDirective()) {
1703       // If the declaration is enclosed in a 'declare target' directive,
1704       // then it should not be captured.
1705       //
1706       if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
1707         return nullptr;
1708       return VD;
1709     }
1710   }
1711   // Capture variables captured by reference in lambdas for target-based
1712   // directives.
1713   if (VD && !DSAStack->isClauseParsingMode()) {
1714     if (const auto *RD = VD->getType()
1715                              .getCanonicalType()
1716                              .getNonReferenceType()
1717                              ->getAsCXXRecordDecl()) {
1718       bool SavedForceCaptureByReferenceInTargetExecutable =
1719           DSAStack->isForceCaptureByReferenceInTargetExecutable();
1720       DSAStack->setForceCaptureByReferenceInTargetExecutable(/*V=*/true);
1721       if (RD->isLambda()) {
1722         llvm::DenseMap<const VarDecl *, FieldDecl *> Captures;
1723         FieldDecl *ThisCapture;
1724         RD->getCaptureFields(Captures, ThisCapture);
1725         for (const LambdaCapture &LC : RD->captures()) {
1726           if (LC.getCaptureKind() == LCK_ByRef) {
1727             VarDecl *VD = LC.getCapturedVar();
1728             DeclContext *VDC = VD->getDeclContext();
1729             if (!VDC->Encloses(CurContext))
1730               continue;
1731             DSAStackTy::DSAVarData DVarPrivate =
1732                 DSAStack->getTopDSA(VD, /*FromParent=*/false);
1733             // Do not capture already captured variables.
1734             if (!OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD) &&
1735                 DVarPrivate.CKind == OMPC_unknown &&
1736                 !DSAStack->checkMappableExprComponentListsForDecl(
1737                     D, /*CurrentRegionOnly=*/true,
1738                     [](OMPClauseMappableExprCommon::
1739                            MappableExprComponentListRef,
1740                        OpenMPClauseKind) { return true; }))
1741               MarkVariableReferenced(LC.getLocation(), LC.getCapturedVar());
1742           } else if (LC.getCaptureKind() == LCK_This) {
1743             QualType ThisTy = getCurrentThisType();
1744             if (!ThisTy.isNull() &&
1745                 Context.typesAreCompatible(ThisTy, ThisCapture->getType()))
1746               CheckCXXThisCapture(LC.getLocation());
1747           }
1748         }
1749       }
1750       DSAStack->setForceCaptureByReferenceInTargetExecutable(
1751           SavedForceCaptureByReferenceInTargetExecutable);
1752     }
1753   }
1754 
1755   if (DSAStack->getCurrentDirective() != OMPD_unknown &&
1756       (!DSAStack->isClauseParsingMode() ||
1757        DSAStack->getParentDirective() != OMPD_unknown)) {
1758     auto &&Info = DSAStack->isLoopControlVariable(D);
1759     if (Info.first ||
1760         (VD && VD->hasLocalStorage() &&
1761          isImplicitOrExplicitTaskingRegion(DSAStack->getCurrentDirective())) ||
1762         (VD && DSAStack->isForceVarCapturing()))
1763       return VD ? VD : Info.second;
1764     DSAStackTy::DSAVarData DVarPrivate =
1765         DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
1766     if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
1767       return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
1768     DVarPrivate = DSAStack->hasDSA(D, isOpenMPPrivate,
1769                                    [](OpenMPDirectiveKind) { return true; },
1770                                    DSAStack->isClauseParsingMode());
1771     if (DVarPrivate.CKind != OMPC_unknown)
1772       return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
1773   }
1774   return nullptr;
1775 }
1776 
1777 void Sema::adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex,
1778                                         unsigned Level) const {
1779   SmallVector<OpenMPDirectiveKind, 4> Regions;
1780   getOpenMPCaptureRegions(Regions, DSAStack->getDirective(Level));
1781   FunctionScopesIndex -= Regions.size();
1782 }
1783 
1784 void Sema::startOpenMPLoop() {
1785   assert(LangOpts.OpenMP && "OpenMP must be enabled.");
1786   if (isOpenMPLoopDirective(DSAStack->getCurrentDirective()))
1787     DSAStack->loopInit();
1788 }
1789 
1790 bool Sema::isOpenMPPrivateDecl(const ValueDecl *D, unsigned Level) const {
1791   assert(LangOpts.OpenMP && "OpenMP is not allowed");
1792   if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
1793     if (DSAStack->getAssociatedLoops() > 0 &&
1794         !DSAStack->isLoopStarted()) {
1795       DSAStack->resetPossibleLoopCounter(D);
1796       DSAStack->loopStart();
1797       return true;
1798     }
1799     if ((DSAStack->getPossiblyLoopCunter() == D->getCanonicalDecl() ||
1800          DSAStack->isLoopControlVariable(D).first) &&
1801         !DSAStack->hasExplicitDSA(
1802             D, [](OpenMPClauseKind K) { return K != OMPC_private; }, Level) &&
1803         !isOpenMPSimdDirective(DSAStack->getCurrentDirective()))
1804       return true;
1805   }
1806   return DSAStack->hasExplicitDSA(
1807              D, [](OpenMPClauseKind K) { return K == OMPC_private; }, Level) ||
1808          (DSAStack->isClauseParsingMode() &&
1809           DSAStack->getClauseParsingMode() == OMPC_private) ||
1810          // Consider taskgroup reduction descriptor variable a private to avoid
1811          // possible capture in the region.
1812          (DSAStack->hasExplicitDirective(
1813               [](OpenMPDirectiveKind K) { return K == OMPD_taskgroup; },
1814               Level) &&
1815           DSAStack->isTaskgroupReductionRef(D, Level));
1816 }
1817 
1818 void Sema::setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D,
1819                                 unsigned Level) {
1820   assert(LangOpts.OpenMP && "OpenMP is not allowed");
1821   D = getCanonicalDecl(D);
1822   OpenMPClauseKind OMPC = OMPC_unknown;
1823   for (unsigned I = DSAStack->getNestingLevel() + 1; I > Level; --I) {
1824     const unsigned NewLevel = I - 1;
1825     if (DSAStack->hasExplicitDSA(D,
1826                                  [&OMPC](const OpenMPClauseKind K) {
1827                                    if (isOpenMPPrivate(K)) {
1828                                      OMPC = K;
1829                                      return true;
1830                                    }
1831                                    return false;
1832                                  },
1833                                  NewLevel))
1834       break;
1835     if (DSAStack->checkMappableExprComponentListsForDeclAtLevel(
1836             D, NewLevel,
1837             [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
1838                OpenMPClauseKind) { return true; })) {
1839       OMPC = OMPC_map;
1840       break;
1841     }
1842     if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
1843                                        NewLevel)) {
1844       OMPC = OMPC_map;
1845       if (D->getType()->isScalarType() &&
1846           DSAStack->getDefaultDMAAtLevel(NewLevel) !=
1847               DefaultMapAttributes::DMA_tofrom_scalar)
1848         OMPC = OMPC_firstprivate;
1849       break;
1850     }
1851   }
1852   if (OMPC != OMPC_unknown)
1853     FD->addAttr(OMPCaptureKindAttr::CreateImplicit(Context, OMPC));
1854 }
1855 
1856 bool Sema::isOpenMPTargetCapturedDecl(const ValueDecl *D,
1857                                       unsigned Level) const {
1858   assert(LangOpts.OpenMP && "OpenMP is not allowed");
1859   // Return true if the current level is no longer enclosed in a target region.
1860 
1861   const auto *VD = dyn_cast<VarDecl>(D);
1862   return VD && !VD->hasLocalStorage() &&
1863          DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
1864                                         Level);
1865 }
1866 
1867 void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
1868 
1869 void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
1870                                const DeclarationNameInfo &DirName,
1871                                Scope *CurScope, SourceLocation Loc) {
1872   DSAStack->push(DKind, DirName, CurScope, Loc);
1873   PushExpressionEvaluationContext(
1874       ExpressionEvaluationContext::PotentiallyEvaluated);
1875 }
1876 
1877 void Sema::StartOpenMPClause(OpenMPClauseKind K) {
1878   DSAStack->setClauseParsingMode(K);
1879 }
1880 
1881 void Sema::EndOpenMPClause() {
1882   DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
1883 }
1884 
1885 void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
1886   // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
1887   //  A variable of class type (or array thereof) that appears in a lastprivate
1888   //  clause requires an accessible, unambiguous default constructor for the
1889   //  class type, unless the list item is also specified in a firstprivate
1890   //  clause.
1891   if (const auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
1892     for (OMPClause *C : D->clauses()) {
1893       if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
1894         SmallVector<Expr *, 8> PrivateCopies;
1895         for (Expr *DE : Clause->varlists()) {
1896           if (DE->isValueDependent() || DE->isTypeDependent()) {
1897             PrivateCopies.push_back(nullptr);
1898             continue;
1899           }
1900           auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
1901           auto *VD = cast<VarDecl>(DRE->getDecl());
1902           QualType Type = VD->getType().getNonReferenceType();
1903           const DSAStackTy::DSAVarData DVar =
1904               DSAStack->getTopDSA(VD, /*FromParent=*/false);
1905           if (DVar.CKind == OMPC_lastprivate) {
1906             // Generate helper private variable and initialize it with the
1907             // default value. The address of the original variable is replaced
1908             // by the address of the new private variable in CodeGen. This new
1909             // variable is not added to IdResolver, so the code in the OpenMP
1910             // region uses original variable for proper diagnostics.
1911             VarDecl *VDPrivate = buildVarDecl(
1912                 *this, DE->getExprLoc(), Type.getUnqualifiedType(),
1913                 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr, DRE);
1914             ActOnUninitializedDecl(VDPrivate);
1915             if (VDPrivate->isInvalidDecl())
1916               continue;
1917             PrivateCopies.push_back(buildDeclRefExpr(
1918                 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
1919           } else {
1920             // The variable is also a firstprivate, so initialization sequence
1921             // for private copy is generated already.
1922             PrivateCopies.push_back(nullptr);
1923           }
1924         }
1925         // Set initializers to private copies if no errors were found.
1926         if (PrivateCopies.size() == Clause->varlist_size())
1927           Clause->setPrivateCopies(PrivateCopies);
1928       }
1929     }
1930   }
1931 
1932   DSAStack->pop();
1933   DiscardCleanupsInEvaluationContext();
1934   PopExpressionEvaluationContext();
1935 }
1936 
1937 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
1938                                      Expr *NumIterations, Sema &SemaRef,
1939                                      Scope *S, DSAStackTy *Stack);
1940 
1941 namespace {
1942 
1943 class VarDeclFilterCCC final : public CorrectionCandidateCallback {
1944 private:
1945   Sema &SemaRef;
1946 
1947 public:
1948   explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
1949   bool ValidateCandidate(const TypoCorrection &Candidate) override {
1950     NamedDecl *ND = Candidate.getCorrectionDecl();
1951     if (const auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
1952       return VD->hasGlobalStorage() &&
1953              SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1954                                    SemaRef.getCurScope());
1955     }
1956     return false;
1957   }
1958 
1959   std::unique_ptr<CorrectionCandidateCallback> clone() override {
1960     return llvm::make_unique<VarDeclFilterCCC>(*this);
1961   }
1962 
1963 };
1964 
1965 class VarOrFuncDeclFilterCCC final : public CorrectionCandidateCallback {
1966 private:
1967   Sema &SemaRef;
1968 
1969 public:
1970   explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
1971   bool ValidateCandidate(const TypoCorrection &Candidate) override {
1972     NamedDecl *ND = Candidate.getCorrectionDecl();
1973     if (ND && ((isa<VarDecl>(ND) && ND->getKind() == Decl::Var) ||
1974                isa<FunctionDecl>(ND))) {
1975       return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1976                                    SemaRef.getCurScope());
1977     }
1978     return false;
1979   }
1980 
1981   std::unique_ptr<CorrectionCandidateCallback> clone() override {
1982     return llvm::make_unique<VarOrFuncDeclFilterCCC>(*this);
1983   }
1984 };
1985 
1986 } // namespace
1987 
1988 ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
1989                                          CXXScopeSpec &ScopeSpec,
1990                                          const DeclarationNameInfo &Id,
1991                                          OpenMPDirectiveKind Kind) {
1992   LookupResult Lookup(*this, Id, LookupOrdinaryName);
1993   LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
1994 
1995   if (Lookup.isAmbiguous())
1996     return ExprError();
1997 
1998   VarDecl *VD;
1999   if (!Lookup.isSingleResult()) {
2000     VarDeclFilterCCC CCC(*this);
2001     if (TypoCorrection Corrected =
2002             CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC,
2003                         CTK_ErrorRecovery)) {
2004       diagnoseTypo(Corrected,
2005                    PDiag(Lookup.empty()
2006                              ? diag::err_undeclared_var_use_suggest
2007                              : diag::err_omp_expected_var_arg_suggest)
2008                        << Id.getName());
2009       VD = Corrected.getCorrectionDeclAs<VarDecl>();
2010     } else {
2011       Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
2012                                        : diag::err_omp_expected_var_arg)
2013           << Id.getName();
2014       return ExprError();
2015     }
2016   } else if (!(VD = Lookup.getAsSingle<VarDecl>())) {
2017     Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
2018     Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
2019     return ExprError();
2020   }
2021   Lookup.suppressDiagnostics();
2022 
2023   // OpenMP [2.9.2, Syntax, C/C++]
2024   //   Variables must be file-scope, namespace-scope, or static block-scope.
2025   if (Kind == OMPD_threadprivate && !VD->hasGlobalStorage()) {
2026     Diag(Id.getLoc(), diag::err_omp_global_var_arg)
2027         << getOpenMPDirectiveName(Kind) << !VD->isStaticLocal();
2028     bool IsDecl =
2029         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2030     Diag(VD->getLocation(),
2031          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2032         << VD;
2033     return ExprError();
2034   }
2035 
2036   VarDecl *CanonicalVD = VD->getCanonicalDecl();
2037   NamedDecl *ND = CanonicalVD;
2038   // OpenMP [2.9.2, Restrictions, C/C++, p.2]
2039   //   A threadprivate directive for file-scope variables must appear outside
2040   //   any definition or declaration.
2041   if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
2042       !getCurLexicalContext()->isTranslationUnit()) {
2043     Diag(Id.getLoc(), diag::err_omp_var_scope)
2044         << getOpenMPDirectiveName(Kind) << VD;
2045     bool IsDecl =
2046         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2047     Diag(VD->getLocation(),
2048          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2049         << VD;
2050     return ExprError();
2051   }
2052   // OpenMP [2.9.2, Restrictions, C/C++, p.3]
2053   //   A threadprivate directive for static class member variables must appear
2054   //   in the class definition, in the same scope in which the member
2055   //   variables are declared.
2056   if (CanonicalVD->isStaticDataMember() &&
2057       !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
2058     Diag(Id.getLoc(), diag::err_omp_var_scope)
2059         << getOpenMPDirectiveName(Kind) << VD;
2060     bool IsDecl =
2061         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2062     Diag(VD->getLocation(),
2063          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2064         << VD;
2065     return ExprError();
2066   }
2067   // OpenMP [2.9.2, Restrictions, C/C++, p.4]
2068   //   A threadprivate directive for namespace-scope variables must appear
2069   //   outside any definition or declaration other than the namespace
2070   //   definition itself.
2071   if (CanonicalVD->getDeclContext()->isNamespace() &&
2072       (!getCurLexicalContext()->isFileContext() ||
2073        !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
2074     Diag(Id.getLoc(), diag::err_omp_var_scope)
2075         << getOpenMPDirectiveName(Kind) << VD;
2076     bool IsDecl =
2077         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2078     Diag(VD->getLocation(),
2079          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2080         << VD;
2081     return ExprError();
2082   }
2083   // OpenMP [2.9.2, Restrictions, C/C++, p.6]
2084   //   A threadprivate directive for static block-scope variables must appear
2085   //   in the scope of the variable and not in a nested scope.
2086   if (CanonicalVD->isLocalVarDecl() && CurScope &&
2087       !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
2088     Diag(Id.getLoc(), diag::err_omp_var_scope)
2089         << getOpenMPDirectiveName(Kind) << VD;
2090     bool IsDecl =
2091         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2092     Diag(VD->getLocation(),
2093          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2094         << VD;
2095     return ExprError();
2096   }
2097 
2098   // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
2099   //   A threadprivate directive must lexically precede all references to any
2100   //   of the variables in its list.
2101   if (Kind == OMPD_threadprivate && VD->isUsed() &&
2102       !DSAStack->isThreadPrivate(VD)) {
2103     Diag(Id.getLoc(), diag::err_omp_var_used)
2104         << getOpenMPDirectiveName(Kind) << VD;
2105     return ExprError();
2106   }
2107 
2108   QualType ExprType = VD->getType().getNonReferenceType();
2109   return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
2110                              SourceLocation(), VD,
2111                              /*RefersToEnclosingVariableOrCapture=*/false,
2112                              Id.getLoc(), ExprType, VK_LValue);
2113 }
2114 
2115 Sema::DeclGroupPtrTy
2116 Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
2117                                         ArrayRef<Expr *> VarList) {
2118   if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
2119     CurContext->addDecl(D);
2120     return DeclGroupPtrTy::make(DeclGroupRef(D));
2121   }
2122   return nullptr;
2123 }
2124 
2125 namespace {
2126 class LocalVarRefChecker final
2127     : public ConstStmtVisitor<LocalVarRefChecker, bool> {
2128   Sema &SemaRef;
2129 
2130 public:
2131   bool VisitDeclRefExpr(const DeclRefExpr *E) {
2132     if (const auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
2133       if (VD->hasLocalStorage()) {
2134         SemaRef.Diag(E->getBeginLoc(),
2135                      diag::err_omp_local_var_in_threadprivate_init)
2136             << E->getSourceRange();
2137         SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
2138             << VD << VD->getSourceRange();
2139         return true;
2140       }
2141     }
2142     return false;
2143   }
2144   bool VisitStmt(const Stmt *S) {
2145     for (const Stmt *Child : S->children()) {
2146       if (Child && Visit(Child))
2147         return true;
2148     }
2149     return false;
2150   }
2151   explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
2152 };
2153 } // namespace
2154 
2155 OMPThreadPrivateDecl *
2156 Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
2157   SmallVector<Expr *, 8> Vars;
2158   for (Expr *RefExpr : VarList) {
2159     auto *DE = cast<DeclRefExpr>(RefExpr);
2160     auto *VD = cast<VarDecl>(DE->getDecl());
2161     SourceLocation ILoc = DE->getExprLoc();
2162 
2163     // Mark variable as used.
2164     VD->setReferenced();
2165     VD->markUsed(Context);
2166 
2167     QualType QType = VD->getType();
2168     if (QType->isDependentType() || QType->isInstantiationDependentType()) {
2169       // It will be analyzed later.
2170       Vars.push_back(DE);
2171       continue;
2172     }
2173 
2174     // OpenMP [2.9.2, Restrictions, C/C++, p.10]
2175     //   A threadprivate variable must not have an incomplete type.
2176     if (RequireCompleteType(ILoc, VD->getType(),
2177                             diag::err_omp_threadprivate_incomplete_type)) {
2178       continue;
2179     }
2180 
2181     // OpenMP [2.9.2, Restrictions, C/C++, p.10]
2182     //   A threadprivate variable must not have a reference type.
2183     if (VD->getType()->isReferenceType()) {
2184       Diag(ILoc, diag::err_omp_ref_type_arg)
2185           << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
2186       bool IsDecl =
2187           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2188       Diag(VD->getLocation(),
2189            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2190           << VD;
2191       continue;
2192     }
2193 
2194     // Check if this is a TLS variable. If TLS is not being supported, produce
2195     // the corresponding diagnostic.
2196     if ((VD->getTLSKind() != VarDecl::TLS_None &&
2197          !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
2198            getLangOpts().OpenMPUseTLS &&
2199            getASTContext().getTargetInfo().isTLSSupported())) ||
2200         (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
2201          !VD->isLocalVarDecl())) {
2202       Diag(ILoc, diag::err_omp_var_thread_local)
2203           << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
2204       bool IsDecl =
2205           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2206       Diag(VD->getLocation(),
2207            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2208           << VD;
2209       continue;
2210     }
2211 
2212     // Check if initial value of threadprivate variable reference variable with
2213     // local storage (it is not supported by runtime).
2214     if (const Expr *Init = VD->getAnyInitializer()) {
2215       LocalVarRefChecker Checker(*this);
2216       if (Checker.Visit(Init))
2217         continue;
2218     }
2219 
2220     Vars.push_back(RefExpr);
2221     DSAStack->addDSA(VD, DE, OMPC_threadprivate);
2222     VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
2223         Context, SourceRange(Loc, Loc)));
2224     if (ASTMutationListener *ML = Context.getASTMutationListener())
2225       ML->DeclarationMarkedOpenMPThreadPrivate(VD);
2226   }
2227   OMPThreadPrivateDecl *D = nullptr;
2228   if (!Vars.empty()) {
2229     D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
2230                                      Vars);
2231     D->setAccess(AS_public);
2232   }
2233   return D;
2234 }
2235 
2236 static OMPAllocateDeclAttr::AllocatorTypeTy
2237 getAllocatorKind(Sema &S, DSAStackTy *Stack, Expr *Allocator) {
2238   if (!Allocator)
2239     return OMPAllocateDeclAttr::OMPDefaultMemAlloc;
2240   if (Allocator->isTypeDependent() || Allocator->isValueDependent() ||
2241       Allocator->isInstantiationDependent() ||
2242       Allocator->containsUnexpandedParameterPack())
2243     return OMPAllocateDeclAttr::OMPUserDefinedMemAlloc;
2244   auto AllocatorKindRes = OMPAllocateDeclAttr::OMPUserDefinedMemAlloc;
2245   for (int I = OMPAllocateDeclAttr::OMPDefaultMemAlloc;
2246        I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
2247     auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
2248     Expr *DefAllocator = Stack->getAllocator(AllocatorKind);
2249     const Expr *AE = Allocator->IgnoreParenImpCasts();
2250     llvm::FoldingSetNodeID AEId, DAEId;
2251     AE->Profile(AEId, S.getASTContext(), /*Canonical=*/true);
2252     DefAllocator->Profile(DAEId, S.getASTContext(), /*Canonical=*/true);
2253     if (AEId == DAEId) {
2254       AllocatorKindRes = AllocatorKind;
2255       break;
2256     }
2257   }
2258   return AllocatorKindRes;
2259 }
2260 
2261 Sema::DeclGroupPtrTy Sema::ActOnOpenMPAllocateDirective(
2262     SourceLocation Loc, ArrayRef<Expr *> VarList,
2263     ArrayRef<OMPClause *> Clauses, DeclContext *Owner) {
2264   assert(Clauses.size() <= 1 && "Expected at most one clause.");
2265   Expr *Allocator = nullptr;
2266   if (Clauses.empty()) {
2267     // OpenMP 5.0, 2.11.3 allocate Directive, Restrictions.
2268     // allocate directives that appear in a target region must specify an
2269     // allocator clause unless a requires directive with the dynamic_allocators
2270     // clause is present in the same compilation unit.
2271     if (LangOpts.OpenMPIsDevice &&
2272         !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())
2273       targetDiag(Loc, diag::err_expected_allocator_clause);
2274   } else {
2275     Allocator = cast<OMPAllocatorClause>(Clauses.back())->getAllocator();
2276   }
2277   OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind =
2278       getAllocatorKind(*this, DSAStack, Allocator);
2279   SmallVector<Expr *, 8> Vars;
2280   for (Expr *RefExpr : VarList) {
2281     auto *DE = cast<DeclRefExpr>(RefExpr);
2282     auto *VD = cast<VarDecl>(DE->getDecl());
2283 
2284     // Check if this is a TLS variable or global register.
2285     if (VD->getTLSKind() != VarDecl::TLS_None ||
2286         VD->hasAttr<OMPThreadPrivateDeclAttr>() ||
2287         (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
2288          !VD->isLocalVarDecl()))
2289       continue;
2290     // Do not apply for parameters.
2291     if (isa<ParmVarDecl>(VD))
2292       continue;
2293 
2294     // If the used several times in the allocate directive, the same allocator
2295     // must be used.
2296     if (VD->hasAttr<OMPAllocateDeclAttr>()) {
2297       const auto *A = VD->getAttr<OMPAllocateDeclAttr>();
2298       Expr *PrevAllocator = A->getAllocator();
2299       OMPAllocateDeclAttr::AllocatorTypeTy PrevAllocatorKind =
2300           getAllocatorKind(*this, DSAStack, PrevAllocator);
2301       bool AllocatorsMatch = AllocatorKind == PrevAllocatorKind;
2302       if (AllocatorsMatch && Allocator && PrevAllocator) {
2303         const Expr *AE = Allocator->IgnoreParenImpCasts();
2304         const Expr *PAE = PrevAllocator->IgnoreParenImpCasts();
2305         llvm::FoldingSetNodeID AEId, PAEId;
2306         AE->Profile(AEId, Context, /*Canonical=*/true);
2307         PAE->Profile(PAEId, Context, /*Canonical=*/true);
2308         AllocatorsMatch = AEId == PAEId;
2309       }
2310       if (!AllocatorsMatch) {
2311         SmallString<256> AllocatorBuffer;
2312         llvm::raw_svector_ostream AllocatorStream(AllocatorBuffer);
2313         if (Allocator)
2314           Allocator->printPretty(AllocatorStream, nullptr, getPrintingPolicy());
2315         SmallString<256> PrevAllocatorBuffer;
2316         llvm::raw_svector_ostream PrevAllocatorStream(PrevAllocatorBuffer);
2317         if (PrevAllocator)
2318           PrevAllocator->printPretty(PrevAllocatorStream, nullptr,
2319                                      getPrintingPolicy());
2320 
2321         SourceLocation AllocatorLoc =
2322             Allocator ? Allocator->getExprLoc() : RefExpr->getExprLoc();
2323         SourceRange AllocatorRange =
2324             Allocator ? Allocator->getSourceRange() : RefExpr->getSourceRange();
2325         SourceLocation PrevAllocatorLoc =
2326             PrevAllocator ? PrevAllocator->getExprLoc() : A->getLocation();
2327         SourceRange PrevAllocatorRange =
2328             PrevAllocator ? PrevAllocator->getSourceRange() : A->getRange();
2329         Diag(AllocatorLoc, diag::warn_omp_used_different_allocator)
2330             << (Allocator ? 1 : 0) << AllocatorStream.str()
2331             << (PrevAllocator ? 1 : 0) << PrevAllocatorStream.str()
2332             << AllocatorRange;
2333         Diag(PrevAllocatorLoc, diag::note_omp_previous_allocator)
2334             << PrevAllocatorRange;
2335         continue;
2336       }
2337     }
2338 
2339     // OpenMP, 2.11.3 allocate Directive, Restrictions, C / C++
2340     // If a list item has a static storage type, the allocator expression in the
2341     // allocator clause must be a constant expression that evaluates to one of
2342     // the predefined memory allocator values.
2343     if (Allocator && VD->hasGlobalStorage()) {
2344       if (AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc) {
2345         Diag(Allocator->getExprLoc(),
2346              diag::err_omp_expected_predefined_allocator)
2347             << Allocator->getSourceRange();
2348         bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
2349                       VarDecl::DeclarationOnly;
2350         Diag(VD->getLocation(),
2351              IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2352             << VD;
2353         continue;
2354       }
2355     }
2356 
2357     Vars.push_back(RefExpr);
2358     if ((!Allocator || (Allocator && !Allocator->isTypeDependent() &&
2359                         !Allocator->isValueDependent() &&
2360                         !Allocator->isInstantiationDependent() &&
2361                         !Allocator->containsUnexpandedParameterPack())) &&
2362         !VD->hasAttr<OMPAllocateDeclAttr>()) {
2363       Attr *A = OMPAllocateDeclAttr::CreateImplicit(
2364           Context, AllocatorKind, Allocator, DE->getSourceRange());
2365       VD->addAttr(A);
2366       if (ASTMutationListener *ML = Context.getASTMutationListener())
2367         ML->DeclarationMarkedOpenMPAllocate(VD, A);
2368     }
2369   }
2370   if (Vars.empty())
2371     return nullptr;
2372   if (!Owner)
2373     Owner = getCurLexicalContext();
2374   OMPAllocateDecl *D =
2375       OMPAllocateDecl::Create(Context, Owner, Loc, Vars, Clauses);
2376   D->setAccess(AS_public);
2377   Owner->addDecl(D);
2378   return DeclGroupPtrTy::make(DeclGroupRef(D));
2379 }
2380 
2381 Sema::DeclGroupPtrTy
2382 Sema::ActOnOpenMPRequiresDirective(SourceLocation Loc,
2383                                    ArrayRef<OMPClause *> ClauseList) {
2384   OMPRequiresDecl *D = nullptr;
2385   if (!CurContext->isFileContext()) {
2386     Diag(Loc, diag::err_omp_invalid_scope) << "requires";
2387   } else {
2388     D = CheckOMPRequiresDecl(Loc, ClauseList);
2389     if (D) {
2390       CurContext->addDecl(D);
2391       DSAStack->addRequiresDecl(D);
2392     }
2393   }
2394   return DeclGroupPtrTy::make(DeclGroupRef(D));
2395 }
2396 
2397 OMPRequiresDecl *Sema::CheckOMPRequiresDecl(SourceLocation Loc,
2398                                             ArrayRef<OMPClause *> ClauseList) {
2399   if (!DSAStack->hasDuplicateRequiresClause(ClauseList))
2400     return OMPRequiresDecl::Create(Context, getCurLexicalContext(), Loc,
2401                                    ClauseList);
2402   return nullptr;
2403 }
2404 
2405 static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack,
2406                               const ValueDecl *D,
2407                               const DSAStackTy::DSAVarData &DVar,
2408                               bool IsLoopIterVar = false) {
2409   if (DVar.RefExpr) {
2410     SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
2411         << getOpenMPClauseName(DVar.CKind);
2412     return;
2413   }
2414   enum {
2415     PDSA_StaticMemberShared,
2416     PDSA_StaticLocalVarShared,
2417     PDSA_LoopIterVarPrivate,
2418     PDSA_LoopIterVarLinear,
2419     PDSA_LoopIterVarLastprivate,
2420     PDSA_ConstVarShared,
2421     PDSA_GlobalVarShared,
2422     PDSA_TaskVarFirstprivate,
2423     PDSA_LocalVarPrivate,
2424     PDSA_Implicit
2425   } Reason = PDSA_Implicit;
2426   bool ReportHint = false;
2427   auto ReportLoc = D->getLocation();
2428   auto *VD = dyn_cast<VarDecl>(D);
2429   if (IsLoopIterVar) {
2430     if (DVar.CKind == OMPC_private)
2431       Reason = PDSA_LoopIterVarPrivate;
2432     else if (DVar.CKind == OMPC_lastprivate)
2433       Reason = PDSA_LoopIterVarLastprivate;
2434     else
2435       Reason = PDSA_LoopIterVarLinear;
2436   } else if (isOpenMPTaskingDirective(DVar.DKind) &&
2437              DVar.CKind == OMPC_firstprivate) {
2438     Reason = PDSA_TaskVarFirstprivate;
2439     ReportLoc = DVar.ImplicitDSALoc;
2440   } else if (VD && VD->isStaticLocal())
2441     Reason = PDSA_StaticLocalVarShared;
2442   else if (VD && VD->isStaticDataMember())
2443     Reason = PDSA_StaticMemberShared;
2444   else if (VD && VD->isFileVarDecl())
2445     Reason = PDSA_GlobalVarShared;
2446   else if (D->getType().isConstant(SemaRef.getASTContext()))
2447     Reason = PDSA_ConstVarShared;
2448   else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
2449     ReportHint = true;
2450     Reason = PDSA_LocalVarPrivate;
2451   }
2452   if (Reason != PDSA_Implicit) {
2453     SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
2454         << Reason << ReportHint
2455         << getOpenMPDirectiveName(Stack->getCurrentDirective());
2456   } else if (DVar.ImplicitDSALoc.isValid()) {
2457     SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
2458         << getOpenMPClauseName(DVar.CKind);
2459   }
2460 }
2461 
2462 namespace {
2463 class DSAAttrChecker final : public StmtVisitor<DSAAttrChecker, void> {
2464   DSAStackTy *Stack;
2465   Sema &SemaRef;
2466   bool ErrorFound = false;
2467   CapturedStmt *CS = nullptr;
2468   llvm::SmallVector<Expr *, 4> ImplicitFirstprivate;
2469   llvm::SmallVector<Expr *, 4> ImplicitMap;
2470   Sema::VarsWithInheritedDSAType VarsWithInheritedDSA;
2471   llvm::SmallDenseSet<const ValueDecl *, 4> ImplicitDeclarations;
2472 
2473   void VisitSubCaptures(OMPExecutableDirective *S) {
2474     // Check implicitly captured variables.
2475     if (!S->hasAssociatedStmt() || !S->getAssociatedStmt())
2476       return;
2477     for (const CapturedStmt::Capture &Cap :
2478          S->getInnermostCapturedStmt()->captures()) {
2479       if (!Cap.capturesVariable())
2480         continue;
2481       VarDecl *VD = Cap.getCapturedVar();
2482       // Do not try to map the variable if it or its sub-component was mapped
2483       // already.
2484       if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
2485           Stack->checkMappableExprComponentListsForDecl(
2486               VD, /*CurrentRegionOnly=*/true,
2487               [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
2488                  OpenMPClauseKind) { return true; }))
2489         continue;
2490       DeclRefExpr *DRE = buildDeclRefExpr(
2491           SemaRef, VD, VD->getType().getNonLValueExprType(SemaRef.Context),
2492           Cap.getLocation(), /*RefersToCapture=*/true);
2493       Visit(DRE);
2494     }
2495   }
2496 
2497 public:
2498   void VisitDeclRefExpr(DeclRefExpr *E) {
2499     if (E->isTypeDependent() || E->isValueDependent() ||
2500         E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
2501       return;
2502     if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
2503       VD = VD->getCanonicalDecl();
2504       // Skip internally declared variables.
2505       if (VD->hasLocalStorage() && !CS->capturesVariable(VD))
2506         return;
2507 
2508       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
2509       // Check if the variable has explicit DSA set and stop analysis if it so.
2510       if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second)
2511         return;
2512 
2513       // Skip internally declared static variables.
2514       llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
2515           OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
2516       if (VD->hasGlobalStorage() && !CS->capturesVariable(VD) &&
2517           (!Res || *Res != OMPDeclareTargetDeclAttr::MT_Link))
2518         return;
2519 
2520       SourceLocation ELoc = E->getExprLoc();
2521       OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
2522       // The default(none) clause requires that each variable that is referenced
2523       // in the construct, and does not have a predetermined data-sharing
2524       // attribute, must have its data-sharing attribute explicitly determined
2525       // by being listed in a data-sharing attribute clause.
2526       if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
2527           isImplicitOrExplicitTaskingRegion(DKind) &&
2528           VarsWithInheritedDSA.count(VD) == 0) {
2529         VarsWithInheritedDSA[VD] = E;
2530         return;
2531       }
2532 
2533       if (isOpenMPTargetExecutionDirective(DKind) &&
2534           !Stack->isLoopControlVariable(VD).first) {
2535         if (!Stack->checkMappableExprComponentListsForDecl(
2536                 VD, /*CurrentRegionOnly=*/true,
2537                 [](OMPClauseMappableExprCommon::MappableExprComponentListRef
2538                        StackComponents,
2539                    OpenMPClauseKind) {
2540                   // Variable is used if it has been marked as an array, array
2541                   // section or the variable iself.
2542                   return StackComponents.size() == 1 ||
2543                          std::all_of(
2544                              std::next(StackComponents.rbegin()),
2545                              StackComponents.rend(),
2546                              [](const OMPClauseMappableExprCommon::
2547                                     MappableComponent &MC) {
2548                                return MC.getAssociatedDeclaration() ==
2549                                           nullptr &&
2550                                       (isa<OMPArraySectionExpr>(
2551                                            MC.getAssociatedExpression()) ||
2552                                        isa<ArraySubscriptExpr>(
2553                                            MC.getAssociatedExpression()));
2554                              });
2555                 })) {
2556           bool IsFirstprivate = false;
2557           // By default lambdas are captured as firstprivates.
2558           if (const auto *RD =
2559                   VD->getType().getNonReferenceType()->getAsCXXRecordDecl())
2560             IsFirstprivate = RD->isLambda();
2561           IsFirstprivate =
2562               IsFirstprivate ||
2563               (VD->getType().getNonReferenceType()->isScalarType() &&
2564                Stack->getDefaultDMA() != DMA_tofrom_scalar && !Res);
2565           if (IsFirstprivate)
2566             ImplicitFirstprivate.emplace_back(E);
2567           else
2568             ImplicitMap.emplace_back(E);
2569           return;
2570         }
2571       }
2572 
2573       // OpenMP [2.9.3.6, Restrictions, p.2]
2574       //  A list item that appears in a reduction clause of the innermost
2575       //  enclosing worksharing or parallel construct may not be accessed in an
2576       //  explicit task.
2577       DVar = Stack->hasInnermostDSA(
2578           VD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
2579           [](OpenMPDirectiveKind K) {
2580             return isOpenMPParallelDirective(K) ||
2581                    isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
2582           },
2583           /*FromParent=*/true);
2584       if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
2585         ErrorFound = true;
2586         SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
2587         reportOriginalDsa(SemaRef, Stack, VD, DVar);
2588         return;
2589       }
2590 
2591       // Define implicit data-sharing attributes for task.
2592       DVar = Stack->getImplicitDSA(VD, /*FromParent=*/false);
2593       if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
2594           !Stack->isLoopControlVariable(VD).first) {
2595         ImplicitFirstprivate.push_back(E);
2596         return;
2597       }
2598 
2599       // Store implicitly used globals with declare target link for parent
2600       // target.
2601       if (!isOpenMPTargetExecutionDirective(DKind) && Res &&
2602           *Res == OMPDeclareTargetDeclAttr::MT_Link) {
2603         Stack->addToParentTargetRegionLinkGlobals(E);
2604         return;
2605       }
2606     }
2607   }
2608   void VisitMemberExpr(MemberExpr *E) {
2609     if (E->isTypeDependent() || E->isValueDependent() ||
2610         E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
2611       return;
2612     auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
2613     OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
2614     if (auto *TE = dyn_cast<CXXThisExpr>(E->getBase()->IgnoreParens())) {
2615       if (!FD)
2616         return;
2617       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(FD, /*FromParent=*/false);
2618       // Check if the variable has explicit DSA set and stop analysis if it
2619       // so.
2620       if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second)
2621         return;
2622 
2623       if (isOpenMPTargetExecutionDirective(DKind) &&
2624           !Stack->isLoopControlVariable(FD).first &&
2625           !Stack->checkMappableExprComponentListsForDecl(
2626               FD, /*CurrentRegionOnly=*/true,
2627               [](OMPClauseMappableExprCommon::MappableExprComponentListRef
2628                      StackComponents,
2629                  OpenMPClauseKind) {
2630                 return isa<CXXThisExpr>(
2631                     cast<MemberExpr>(
2632                         StackComponents.back().getAssociatedExpression())
2633                         ->getBase()
2634                         ->IgnoreParens());
2635               })) {
2636         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
2637         //  A bit-field cannot appear in a map clause.
2638         //
2639         if (FD->isBitField())
2640           return;
2641 
2642         // Check to see if the member expression is referencing a class that
2643         // has already been explicitly mapped
2644         if (Stack->isClassPreviouslyMapped(TE->getType()))
2645           return;
2646 
2647         ImplicitMap.emplace_back(E);
2648         return;
2649       }
2650 
2651       SourceLocation ELoc = E->getExprLoc();
2652       // OpenMP [2.9.3.6, Restrictions, p.2]
2653       //  A list item that appears in a reduction clause of the innermost
2654       //  enclosing worksharing or parallel construct may not be accessed in
2655       //  an  explicit task.
2656       DVar = Stack->hasInnermostDSA(
2657           FD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
2658           [](OpenMPDirectiveKind K) {
2659             return isOpenMPParallelDirective(K) ||
2660                    isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
2661           },
2662           /*FromParent=*/true);
2663       if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
2664         ErrorFound = true;
2665         SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
2666         reportOriginalDsa(SemaRef, Stack, FD, DVar);
2667         return;
2668       }
2669 
2670       // Define implicit data-sharing attributes for task.
2671       DVar = Stack->getImplicitDSA(FD, /*FromParent=*/false);
2672       if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
2673           !Stack->isLoopControlVariable(FD).first) {
2674         // Check if there is a captured expression for the current field in the
2675         // region. Do not mark it as firstprivate unless there is no captured
2676         // expression.
2677         // TODO: try to make it firstprivate.
2678         if (DVar.CKind != OMPC_unknown)
2679           ImplicitFirstprivate.push_back(E);
2680       }
2681       return;
2682     }
2683     if (isOpenMPTargetExecutionDirective(DKind)) {
2684       OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
2685       if (!checkMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map,
2686                                         /*NoDiagnose=*/true))
2687         return;
2688       const auto *VD = cast<ValueDecl>(
2689           CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl());
2690       if (!Stack->checkMappableExprComponentListsForDecl(
2691               VD, /*CurrentRegionOnly=*/true,
2692               [&CurComponents](
2693                   OMPClauseMappableExprCommon::MappableExprComponentListRef
2694                       StackComponents,
2695                   OpenMPClauseKind) {
2696                 auto CCI = CurComponents.rbegin();
2697                 auto CCE = CurComponents.rend();
2698                 for (const auto &SC : llvm::reverse(StackComponents)) {
2699                   // Do both expressions have the same kind?
2700                   if (CCI->getAssociatedExpression()->getStmtClass() !=
2701                       SC.getAssociatedExpression()->getStmtClass())
2702                     if (!(isa<OMPArraySectionExpr>(
2703                               SC.getAssociatedExpression()) &&
2704                           isa<ArraySubscriptExpr>(
2705                               CCI->getAssociatedExpression())))
2706                       return false;
2707 
2708                   const Decl *CCD = CCI->getAssociatedDeclaration();
2709                   const Decl *SCD = SC.getAssociatedDeclaration();
2710                   CCD = CCD ? CCD->getCanonicalDecl() : nullptr;
2711                   SCD = SCD ? SCD->getCanonicalDecl() : nullptr;
2712                   if (SCD != CCD)
2713                     return false;
2714                   std::advance(CCI, 1);
2715                   if (CCI == CCE)
2716                     break;
2717                 }
2718                 return true;
2719               })) {
2720         Visit(E->getBase());
2721       }
2722     } else {
2723       Visit(E->getBase());
2724     }
2725   }
2726   void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
2727     for (OMPClause *C : S->clauses()) {
2728       // Skip analysis of arguments of implicitly defined firstprivate clause
2729       // for task|target directives.
2730       // Skip analysis of arguments of implicitly defined map clause for target
2731       // directives.
2732       if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) &&
2733                  C->isImplicit())) {
2734         for (Stmt *CC : C->children()) {
2735           if (CC)
2736             Visit(CC);
2737         }
2738       }
2739     }
2740     // Check implicitly captured variables.
2741     VisitSubCaptures(S);
2742   }
2743   void VisitStmt(Stmt *S) {
2744     for (Stmt *C : S->children()) {
2745       if (C) {
2746         // Check implicitly captured variables in the task-based directives to
2747         // check if they must be firstprivatized.
2748         Visit(C);
2749       }
2750     }
2751   }
2752 
2753   bool isErrorFound() const { return ErrorFound; }
2754   ArrayRef<Expr *> getImplicitFirstprivate() const {
2755     return ImplicitFirstprivate;
2756   }
2757   ArrayRef<Expr *> getImplicitMap() const { return ImplicitMap; }
2758   const Sema::VarsWithInheritedDSAType &getVarsWithInheritedDSA() const {
2759     return VarsWithInheritedDSA;
2760   }
2761 
2762   DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
2763       : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {
2764     // Process declare target link variables for the target directives.
2765     if (isOpenMPTargetExecutionDirective(S->getCurrentDirective())) {
2766       for (DeclRefExpr *E : Stack->getLinkGlobals())
2767         Visit(E);
2768     }
2769   }
2770 };
2771 } // namespace
2772 
2773 void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
2774   switch (DKind) {
2775   case OMPD_parallel:
2776   case OMPD_parallel_for:
2777   case OMPD_parallel_for_simd:
2778   case OMPD_parallel_sections:
2779   case OMPD_teams:
2780   case OMPD_teams_distribute:
2781   case OMPD_teams_distribute_simd: {
2782     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2783     QualType KmpInt32PtrTy =
2784         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2785     Sema::CapturedParamNameType Params[] = {
2786         std::make_pair(".global_tid.", KmpInt32PtrTy),
2787         std::make_pair(".bound_tid.", KmpInt32PtrTy),
2788         std::make_pair(StringRef(), QualType()) // __context with shared vars
2789     };
2790     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2791                              Params);
2792     break;
2793   }
2794   case OMPD_target_teams:
2795   case OMPD_target_parallel:
2796   case OMPD_target_parallel_for:
2797   case OMPD_target_parallel_for_simd:
2798   case OMPD_target_teams_distribute:
2799   case OMPD_target_teams_distribute_simd: {
2800     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2801     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2802     QualType KmpInt32PtrTy =
2803         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2804     QualType Args[] = {VoidPtrTy};
2805     FunctionProtoType::ExtProtoInfo EPI;
2806     EPI.Variadic = true;
2807     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2808     Sema::CapturedParamNameType Params[] = {
2809         std::make_pair(".global_tid.", KmpInt32Ty),
2810         std::make_pair(".part_id.", KmpInt32PtrTy),
2811         std::make_pair(".privates.", VoidPtrTy),
2812         std::make_pair(
2813             ".copy_fn.",
2814             Context.getPointerType(CopyFnType).withConst().withRestrict()),
2815         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2816         std::make_pair(StringRef(), QualType()) // __context with shared vars
2817     };
2818     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2819                              Params);
2820     // Mark this captured region as inlined, because we don't use outlined
2821     // function directly.
2822     getCurCapturedRegion()->TheCapturedDecl->addAttr(
2823         AlwaysInlineAttr::CreateImplicit(
2824             Context, AlwaysInlineAttr::Keyword_forceinline));
2825     Sema::CapturedParamNameType ParamsTarget[] = {
2826         std::make_pair(StringRef(), QualType()) // __context with shared vars
2827     };
2828     // Start a captured region for 'target' with no implicit parameters.
2829     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2830                              ParamsTarget);
2831     Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
2832         std::make_pair(".global_tid.", KmpInt32PtrTy),
2833         std::make_pair(".bound_tid.", KmpInt32PtrTy),
2834         std::make_pair(StringRef(), QualType()) // __context with shared vars
2835     };
2836     // Start a captured region for 'teams' or 'parallel'.  Both regions have
2837     // the same implicit parameters.
2838     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2839                              ParamsTeamsOrParallel);
2840     break;
2841   }
2842   case OMPD_target:
2843   case OMPD_target_simd: {
2844     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2845     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2846     QualType KmpInt32PtrTy =
2847         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2848     QualType Args[] = {VoidPtrTy};
2849     FunctionProtoType::ExtProtoInfo EPI;
2850     EPI.Variadic = true;
2851     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2852     Sema::CapturedParamNameType Params[] = {
2853         std::make_pair(".global_tid.", KmpInt32Ty),
2854         std::make_pair(".part_id.", KmpInt32PtrTy),
2855         std::make_pair(".privates.", VoidPtrTy),
2856         std::make_pair(
2857             ".copy_fn.",
2858             Context.getPointerType(CopyFnType).withConst().withRestrict()),
2859         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2860         std::make_pair(StringRef(), QualType()) // __context with shared vars
2861     };
2862     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2863                              Params);
2864     // Mark this captured region as inlined, because we don't use outlined
2865     // function directly.
2866     getCurCapturedRegion()->TheCapturedDecl->addAttr(
2867         AlwaysInlineAttr::CreateImplicit(
2868             Context, AlwaysInlineAttr::Keyword_forceinline));
2869     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2870                              std::make_pair(StringRef(), QualType()));
2871     break;
2872   }
2873   case OMPD_simd:
2874   case OMPD_for:
2875   case OMPD_for_simd:
2876   case OMPD_sections:
2877   case OMPD_section:
2878   case OMPD_single:
2879   case OMPD_master:
2880   case OMPD_critical:
2881   case OMPD_taskgroup:
2882   case OMPD_distribute:
2883   case OMPD_distribute_simd:
2884   case OMPD_ordered:
2885   case OMPD_atomic:
2886   case OMPD_target_data: {
2887     Sema::CapturedParamNameType Params[] = {
2888         std::make_pair(StringRef(), QualType()) // __context with shared vars
2889     };
2890     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2891                              Params);
2892     break;
2893   }
2894   case OMPD_task: {
2895     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2896     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2897     QualType KmpInt32PtrTy =
2898         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2899     QualType Args[] = {VoidPtrTy};
2900     FunctionProtoType::ExtProtoInfo EPI;
2901     EPI.Variadic = true;
2902     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2903     Sema::CapturedParamNameType Params[] = {
2904         std::make_pair(".global_tid.", KmpInt32Ty),
2905         std::make_pair(".part_id.", KmpInt32PtrTy),
2906         std::make_pair(".privates.", VoidPtrTy),
2907         std::make_pair(
2908             ".copy_fn.",
2909             Context.getPointerType(CopyFnType).withConst().withRestrict()),
2910         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2911         std::make_pair(StringRef(), QualType()) // __context with shared vars
2912     };
2913     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2914                              Params);
2915     // Mark this captured region as inlined, because we don't use outlined
2916     // function directly.
2917     getCurCapturedRegion()->TheCapturedDecl->addAttr(
2918         AlwaysInlineAttr::CreateImplicit(
2919             Context, AlwaysInlineAttr::Keyword_forceinline));
2920     break;
2921   }
2922   case OMPD_taskloop:
2923   case OMPD_taskloop_simd: {
2924     QualType KmpInt32Ty =
2925         Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1)
2926             .withConst();
2927     QualType KmpUInt64Ty =
2928         Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0)
2929             .withConst();
2930     QualType KmpInt64Ty =
2931         Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1)
2932             .withConst();
2933     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2934     QualType KmpInt32PtrTy =
2935         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2936     QualType Args[] = {VoidPtrTy};
2937     FunctionProtoType::ExtProtoInfo EPI;
2938     EPI.Variadic = true;
2939     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2940     Sema::CapturedParamNameType Params[] = {
2941         std::make_pair(".global_tid.", KmpInt32Ty),
2942         std::make_pair(".part_id.", KmpInt32PtrTy),
2943         std::make_pair(".privates.", VoidPtrTy),
2944         std::make_pair(
2945             ".copy_fn.",
2946             Context.getPointerType(CopyFnType).withConst().withRestrict()),
2947         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2948         std::make_pair(".lb.", KmpUInt64Ty),
2949         std::make_pair(".ub.", KmpUInt64Ty),
2950         std::make_pair(".st.", KmpInt64Ty),
2951         std::make_pair(".liter.", KmpInt32Ty),
2952         std::make_pair(".reductions.", VoidPtrTy),
2953         std::make_pair(StringRef(), QualType()) // __context with shared vars
2954     };
2955     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2956                              Params);
2957     // Mark this captured region as inlined, because we don't use outlined
2958     // function directly.
2959     getCurCapturedRegion()->TheCapturedDecl->addAttr(
2960         AlwaysInlineAttr::CreateImplicit(
2961             Context, AlwaysInlineAttr::Keyword_forceinline));
2962     break;
2963   }
2964   case OMPD_distribute_parallel_for_simd:
2965   case OMPD_distribute_parallel_for: {
2966     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2967     QualType KmpInt32PtrTy =
2968         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2969     Sema::CapturedParamNameType Params[] = {
2970         std::make_pair(".global_tid.", KmpInt32PtrTy),
2971         std::make_pair(".bound_tid.", KmpInt32PtrTy),
2972         std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
2973         std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
2974         std::make_pair(StringRef(), QualType()) // __context with shared vars
2975     };
2976     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2977                              Params);
2978     break;
2979   }
2980   case OMPD_target_teams_distribute_parallel_for:
2981   case OMPD_target_teams_distribute_parallel_for_simd: {
2982     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2983     QualType KmpInt32PtrTy =
2984         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2985     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2986 
2987     QualType Args[] = {VoidPtrTy};
2988     FunctionProtoType::ExtProtoInfo EPI;
2989     EPI.Variadic = true;
2990     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2991     Sema::CapturedParamNameType Params[] = {
2992         std::make_pair(".global_tid.", KmpInt32Ty),
2993         std::make_pair(".part_id.", KmpInt32PtrTy),
2994         std::make_pair(".privates.", VoidPtrTy),
2995         std::make_pair(
2996             ".copy_fn.",
2997             Context.getPointerType(CopyFnType).withConst().withRestrict()),
2998         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2999         std::make_pair(StringRef(), QualType()) // __context with shared vars
3000     };
3001     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3002                              Params);
3003     // Mark this captured region as inlined, because we don't use outlined
3004     // function directly.
3005     getCurCapturedRegion()->TheCapturedDecl->addAttr(
3006         AlwaysInlineAttr::CreateImplicit(
3007             Context, AlwaysInlineAttr::Keyword_forceinline));
3008     Sema::CapturedParamNameType ParamsTarget[] = {
3009         std::make_pair(StringRef(), QualType()) // __context with shared vars
3010     };
3011     // Start a captured region for 'target' with no implicit parameters.
3012     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3013                              ParamsTarget);
3014 
3015     Sema::CapturedParamNameType ParamsTeams[] = {
3016         std::make_pair(".global_tid.", KmpInt32PtrTy),
3017         std::make_pair(".bound_tid.", KmpInt32PtrTy),
3018         std::make_pair(StringRef(), QualType()) // __context with shared vars
3019     };
3020     // Start a captured region for 'target' with no implicit parameters.
3021     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3022                              ParamsTeams);
3023 
3024     Sema::CapturedParamNameType ParamsParallel[] = {
3025         std::make_pair(".global_tid.", KmpInt32PtrTy),
3026         std::make_pair(".bound_tid.", KmpInt32PtrTy),
3027         std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
3028         std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
3029         std::make_pair(StringRef(), QualType()) // __context with shared vars
3030     };
3031     // Start a captured region for 'teams' or 'parallel'.  Both regions have
3032     // the same implicit parameters.
3033     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3034                              ParamsParallel);
3035     break;
3036   }
3037 
3038   case OMPD_teams_distribute_parallel_for:
3039   case OMPD_teams_distribute_parallel_for_simd: {
3040     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3041     QualType KmpInt32PtrTy =
3042         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3043 
3044     Sema::CapturedParamNameType ParamsTeams[] = {
3045         std::make_pair(".global_tid.", KmpInt32PtrTy),
3046         std::make_pair(".bound_tid.", KmpInt32PtrTy),
3047         std::make_pair(StringRef(), QualType()) // __context with shared vars
3048     };
3049     // Start a captured region for 'target' with no implicit parameters.
3050     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3051                              ParamsTeams);
3052 
3053     Sema::CapturedParamNameType ParamsParallel[] = {
3054         std::make_pair(".global_tid.", KmpInt32PtrTy),
3055         std::make_pair(".bound_tid.", KmpInt32PtrTy),
3056         std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
3057         std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
3058         std::make_pair(StringRef(), QualType()) // __context with shared vars
3059     };
3060     // Start a captured region for 'teams' or 'parallel'.  Both regions have
3061     // the same implicit parameters.
3062     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3063                              ParamsParallel);
3064     break;
3065   }
3066   case OMPD_target_update:
3067   case OMPD_target_enter_data:
3068   case OMPD_target_exit_data: {
3069     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3070     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3071     QualType KmpInt32PtrTy =
3072         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3073     QualType Args[] = {VoidPtrTy};
3074     FunctionProtoType::ExtProtoInfo EPI;
3075     EPI.Variadic = true;
3076     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3077     Sema::CapturedParamNameType Params[] = {
3078         std::make_pair(".global_tid.", KmpInt32Ty),
3079         std::make_pair(".part_id.", KmpInt32PtrTy),
3080         std::make_pair(".privates.", VoidPtrTy),
3081         std::make_pair(
3082             ".copy_fn.",
3083             Context.getPointerType(CopyFnType).withConst().withRestrict()),
3084         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3085         std::make_pair(StringRef(), QualType()) // __context with shared vars
3086     };
3087     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3088                              Params);
3089     // Mark this captured region as inlined, because we don't use outlined
3090     // function directly.
3091     getCurCapturedRegion()->TheCapturedDecl->addAttr(
3092         AlwaysInlineAttr::CreateImplicit(
3093             Context, AlwaysInlineAttr::Keyword_forceinline));
3094     break;
3095   }
3096   case OMPD_threadprivate:
3097   case OMPD_allocate:
3098   case OMPD_taskyield:
3099   case OMPD_barrier:
3100   case OMPD_taskwait:
3101   case OMPD_cancellation_point:
3102   case OMPD_cancel:
3103   case OMPD_flush:
3104   case OMPD_declare_reduction:
3105   case OMPD_declare_mapper:
3106   case OMPD_declare_simd:
3107   case OMPD_declare_target:
3108   case OMPD_end_declare_target:
3109   case OMPD_requires:
3110     llvm_unreachable("OpenMP Directive is not allowed");
3111   case OMPD_unknown:
3112     llvm_unreachable("Unknown OpenMP directive");
3113   }
3114 }
3115 
3116 int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
3117   SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
3118   getOpenMPCaptureRegions(CaptureRegions, DKind);
3119   return CaptureRegions.size();
3120 }
3121 
3122 static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
3123                                              Expr *CaptureExpr, bool WithInit,
3124                                              bool AsExpression) {
3125   assert(CaptureExpr);
3126   ASTContext &C = S.getASTContext();
3127   Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
3128   QualType Ty = Init->getType();
3129   if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
3130     if (S.getLangOpts().CPlusPlus) {
3131       Ty = C.getLValueReferenceType(Ty);
3132     } else {
3133       Ty = C.getPointerType(Ty);
3134       ExprResult Res =
3135           S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
3136       if (!Res.isUsable())
3137         return nullptr;
3138       Init = Res.get();
3139     }
3140     WithInit = true;
3141   }
3142   auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
3143                                           CaptureExpr->getBeginLoc());
3144   if (!WithInit)
3145     CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C));
3146   S.CurContext->addHiddenDecl(CED);
3147   S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
3148   return CED;
3149 }
3150 
3151 static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
3152                                  bool WithInit) {
3153   OMPCapturedExprDecl *CD;
3154   if (VarDecl *VD = S.isOpenMPCapturedDecl(D))
3155     CD = cast<OMPCapturedExprDecl>(VD);
3156   else
3157     CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
3158                           /*AsExpression=*/false);
3159   return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
3160                           CaptureExpr->getExprLoc());
3161 }
3162 
3163 static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
3164   CaptureExpr = S.DefaultLvalueConversion(CaptureExpr).get();
3165   if (!Ref) {
3166     OMPCapturedExprDecl *CD = buildCaptureDecl(
3167         S, &S.getASTContext().Idents.get(".capture_expr."), CaptureExpr,
3168         /*WithInit=*/true, /*AsExpression=*/true);
3169     Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
3170                            CaptureExpr->getExprLoc());
3171   }
3172   ExprResult Res = Ref;
3173   if (!S.getLangOpts().CPlusPlus &&
3174       CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
3175       Ref->getType()->isPointerType()) {
3176     Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
3177     if (!Res.isUsable())
3178       return ExprError();
3179   }
3180   return S.DefaultLvalueConversion(Res.get());
3181 }
3182 
3183 namespace {
3184 // OpenMP directives parsed in this section are represented as a
3185 // CapturedStatement with an associated statement.  If a syntax error
3186 // is detected during the parsing of the associated statement, the
3187 // compiler must abort processing and close the CapturedStatement.
3188 //
3189 // Combined directives such as 'target parallel' have more than one
3190 // nested CapturedStatements.  This RAII ensures that we unwind out
3191 // of all the nested CapturedStatements when an error is found.
3192 class CaptureRegionUnwinderRAII {
3193 private:
3194   Sema &S;
3195   bool &ErrorFound;
3196   OpenMPDirectiveKind DKind = OMPD_unknown;
3197 
3198 public:
3199   CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
3200                             OpenMPDirectiveKind DKind)
3201       : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
3202   ~CaptureRegionUnwinderRAII() {
3203     if (ErrorFound) {
3204       int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
3205       while (--ThisCaptureLevel >= 0)
3206         S.ActOnCapturedRegionError();
3207     }
3208   }
3209 };
3210 } // namespace
3211 
3212 StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
3213                                       ArrayRef<OMPClause *> Clauses) {
3214   bool ErrorFound = false;
3215   CaptureRegionUnwinderRAII CaptureRegionUnwinder(
3216       *this, ErrorFound, DSAStack->getCurrentDirective());
3217   if (!S.isUsable()) {
3218     ErrorFound = true;
3219     return StmtError();
3220   }
3221 
3222   SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
3223   getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
3224   OMPOrderedClause *OC = nullptr;
3225   OMPScheduleClause *SC = nullptr;
3226   SmallVector<const OMPLinearClause *, 4> LCs;
3227   SmallVector<const OMPClauseWithPreInit *, 4> PICs;
3228   // This is required for proper codegen.
3229   for (OMPClause *Clause : Clauses) {
3230     if (isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) &&
3231         Clause->getClauseKind() == OMPC_in_reduction) {
3232       // Capture taskgroup task_reduction descriptors inside the tasking regions
3233       // with the corresponding in_reduction items.
3234       auto *IRC = cast<OMPInReductionClause>(Clause);
3235       for (Expr *E : IRC->taskgroup_descriptors())
3236         if (E)
3237           MarkDeclarationsReferencedInExpr(E);
3238     }
3239     if (isOpenMPPrivate(Clause->getClauseKind()) ||
3240         Clause->getClauseKind() == OMPC_copyprivate ||
3241         (getLangOpts().OpenMPUseTLS &&
3242          getASTContext().getTargetInfo().isTLSSupported() &&
3243          Clause->getClauseKind() == OMPC_copyin)) {
3244       DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
3245       // Mark all variables in private list clauses as used in inner region.
3246       for (Stmt *VarRef : Clause->children()) {
3247         if (auto *E = cast_or_null<Expr>(VarRef)) {
3248           MarkDeclarationsReferencedInExpr(E);
3249         }
3250       }
3251       DSAStack->setForceVarCapturing(/*V=*/false);
3252     } else if (CaptureRegions.size() > 1 ||
3253                CaptureRegions.back() != OMPD_unknown) {
3254       if (auto *C = OMPClauseWithPreInit::get(Clause))
3255         PICs.push_back(C);
3256       if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
3257         if (Expr *E = C->getPostUpdateExpr())
3258           MarkDeclarationsReferencedInExpr(E);
3259       }
3260     }
3261     if (Clause->getClauseKind() == OMPC_schedule)
3262       SC = cast<OMPScheduleClause>(Clause);
3263     else if (Clause->getClauseKind() == OMPC_ordered)
3264       OC = cast<OMPOrderedClause>(Clause);
3265     else if (Clause->getClauseKind() == OMPC_linear)
3266       LCs.push_back(cast<OMPLinearClause>(Clause));
3267   }
3268   // OpenMP, 2.7.1 Loop Construct, Restrictions
3269   // The nonmonotonic modifier cannot be specified if an ordered clause is
3270   // specified.
3271   if (SC &&
3272       (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
3273        SC->getSecondScheduleModifier() ==
3274            OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
3275       OC) {
3276     Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
3277              ? SC->getFirstScheduleModifierLoc()
3278              : SC->getSecondScheduleModifierLoc(),
3279          diag::err_omp_schedule_nonmonotonic_ordered)
3280         << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
3281     ErrorFound = true;
3282   }
3283   if (!LCs.empty() && OC && OC->getNumForLoops()) {
3284     for (const OMPLinearClause *C : LCs) {
3285       Diag(C->getBeginLoc(), diag::err_omp_linear_ordered)
3286           << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
3287     }
3288     ErrorFound = true;
3289   }
3290   if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
3291       isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
3292       OC->getNumForLoops()) {
3293     Diag(OC->getBeginLoc(), diag::err_omp_ordered_simd)
3294         << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
3295     ErrorFound = true;
3296   }
3297   if (ErrorFound) {
3298     return StmtError();
3299   }
3300   StmtResult SR = S;
3301   for (OpenMPDirectiveKind ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
3302     // Mark all variables in private list clauses as used in inner region.
3303     // Required for proper codegen of combined directives.
3304     // TODO: add processing for other clauses.
3305     if (ThisCaptureRegion != OMPD_unknown) {
3306       for (const clang::OMPClauseWithPreInit *C : PICs) {
3307         OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
3308         // Find the particular capture region for the clause if the
3309         // directive is a combined one with multiple capture regions.
3310         // If the directive is not a combined one, the capture region
3311         // associated with the clause is OMPD_unknown and is generated
3312         // only once.
3313         if (CaptureRegion == ThisCaptureRegion ||
3314             CaptureRegion == OMPD_unknown) {
3315           if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
3316             for (Decl *D : DS->decls())
3317               MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
3318           }
3319         }
3320       }
3321     }
3322     SR = ActOnCapturedRegionEnd(SR.get());
3323   }
3324   return SR;
3325 }
3326 
3327 static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
3328                               OpenMPDirectiveKind CancelRegion,
3329                               SourceLocation StartLoc) {
3330   // CancelRegion is only needed for cancel and cancellation_point.
3331   if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
3332     return false;
3333 
3334   if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
3335       CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
3336     return false;
3337 
3338   SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
3339       << getOpenMPDirectiveName(CancelRegion);
3340   return true;
3341 }
3342 
3343 static bool checkNestingOfRegions(Sema &SemaRef, const DSAStackTy *Stack,
3344                                   OpenMPDirectiveKind CurrentRegion,
3345                                   const DeclarationNameInfo &CurrentName,
3346                                   OpenMPDirectiveKind CancelRegion,
3347                                   SourceLocation StartLoc) {
3348   if (Stack->getCurScope()) {
3349     OpenMPDirectiveKind ParentRegion = Stack->getParentDirective();
3350     OpenMPDirectiveKind OffendingRegion = ParentRegion;
3351     bool NestingProhibited = false;
3352     bool CloseNesting = true;
3353     bool OrphanSeen = false;
3354     enum {
3355       NoRecommend,
3356       ShouldBeInParallelRegion,
3357       ShouldBeInOrderedRegion,
3358       ShouldBeInTargetRegion,
3359       ShouldBeInTeamsRegion
3360     } Recommend = NoRecommend;
3361     if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
3362       // OpenMP [2.16, Nesting of Regions]
3363       // OpenMP constructs may not be nested inside a simd region.
3364       // OpenMP [2.8.1,simd Construct, Restrictions]
3365       // An ordered construct with the simd clause is the only OpenMP
3366       // construct that can appear in the simd region.
3367       // Allowing a SIMD construct nested in another SIMD construct is an
3368       // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
3369       // message.
3370       SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
3371                                  ? diag::err_omp_prohibited_region_simd
3372                                  : diag::warn_omp_nesting_simd);
3373       return CurrentRegion != OMPD_simd;
3374     }
3375     if (ParentRegion == OMPD_atomic) {
3376       // OpenMP [2.16, Nesting of Regions]
3377       // OpenMP constructs may not be nested inside an atomic region.
3378       SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
3379       return true;
3380     }
3381     if (CurrentRegion == OMPD_section) {
3382       // OpenMP [2.7.2, sections Construct, Restrictions]
3383       // Orphaned section directives are prohibited. That is, the section
3384       // directives must appear within the sections construct and must not be
3385       // encountered elsewhere in the sections region.
3386       if (ParentRegion != OMPD_sections &&
3387           ParentRegion != OMPD_parallel_sections) {
3388         SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
3389             << (ParentRegion != OMPD_unknown)
3390             << getOpenMPDirectiveName(ParentRegion);
3391         return true;
3392       }
3393       return false;
3394     }
3395     // Allow some constructs (except teams and cancellation constructs) to be
3396     // orphaned (they could be used in functions, called from OpenMP regions
3397     // with the required preconditions).
3398     if (ParentRegion == OMPD_unknown &&
3399         !isOpenMPNestingTeamsDirective(CurrentRegion) &&
3400         CurrentRegion != OMPD_cancellation_point &&
3401         CurrentRegion != OMPD_cancel)
3402       return false;
3403     if (CurrentRegion == OMPD_cancellation_point ||
3404         CurrentRegion == OMPD_cancel) {
3405       // OpenMP [2.16, Nesting of Regions]
3406       // A cancellation point construct for which construct-type-clause is
3407       // taskgroup must be nested inside a task construct. A cancellation
3408       // point construct for which construct-type-clause is not taskgroup must
3409       // be closely nested inside an OpenMP construct that matches the type
3410       // specified in construct-type-clause.
3411       // A cancel construct for which construct-type-clause is taskgroup must be
3412       // nested inside a task construct. A cancel construct for which
3413       // construct-type-clause is not taskgroup must be closely nested inside an
3414       // OpenMP construct that matches the type specified in
3415       // construct-type-clause.
3416       NestingProhibited =
3417           !((CancelRegion == OMPD_parallel &&
3418              (ParentRegion == OMPD_parallel ||
3419               ParentRegion == OMPD_target_parallel)) ||
3420             (CancelRegion == OMPD_for &&
3421              (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
3422               ParentRegion == OMPD_target_parallel_for ||
3423               ParentRegion == OMPD_distribute_parallel_for ||
3424               ParentRegion == OMPD_teams_distribute_parallel_for ||
3425               ParentRegion == OMPD_target_teams_distribute_parallel_for)) ||
3426             (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
3427             (CancelRegion == OMPD_sections &&
3428              (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
3429               ParentRegion == OMPD_parallel_sections)));
3430       OrphanSeen = ParentRegion == OMPD_unknown;
3431     } else if (CurrentRegion == OMPD_master) {
3432       // OpenMP [2.16, Nesting of Regions]
3433       // A master region may not be closely nested inside a worksharing,
3434       // atomic, or explicit task region.
3435       NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
3436                           isOpenMPTaskingDirective(ParentRegion);
3437     } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
3438       // OpenMP [2.16, Nesting of Regions]
3439       // A critical region may not be nested (closely or otherwise) inside a
3440       // critical region with the same name. Note that this restriction is not
3441       // sufficient to prevent deadlock.
3442       SourceLocation PreviousCriticalLoc;
3443       bool DeadLock = Stack->hasDirective(
3444           [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
3445                                               const DeclarationNameInfo &DNI,
3446                                               SourceLocation Loc) {
3447             if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
3448               PreviousCriticalLoc = Loc;
3449               return true;
3450             }
3451             return false;
3452           },
3453           false /* skip top directive */);
3454       if (DeadLock) {
3455         SemaRef.Diag(StartLoc,
3456                      diag::err_omp_prohibited_region_critical_same_name)
3457             << CurrentName.getName();
3458         if (PreviousCriticalLoc.isValid())
3459           SemaRef.Diag(PreviousCriticalLoc,
3460                        diag::note_omp_previous_critical_region);
3461         return true;
3462       }
3463     } else if (CurrentRegion == OMPD_barrier) {
3464       // OpenMP [2.16, Nesting of Regions]
3465       // A barrier region may not be closely nested inside a worksharing,
3466       // explicit task, critical, ordered, atomic, or master region.
3467       NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
3468                           isOpenMPTaskingDirective(ParentRegion) ||
3469                           ParentRegion == OMPD_master ||
3470                           ParentRegion == OMPD_critical ||
3471                           ParentRegion == OMPD_ordered;
3472     } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
3473                !isOpenMPParallelDirective(CurrentRegion) &&
3474                !isOpenMPTeamsDirective(CurrentRegion)) {
3475       // OpenMP [2.16, Nesting of Regions]
3476       // A worksharing region may not be closely nested inside a worksharing,
3477       // explicit task, critical, ordered, atomic, or master region.
3478       NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
3479                           isOpenMPTaskingDirective(ParentRegion) ||
3480                           ParentRegion == OMPD_master ||
3481                           ParentRegion == OMPD_critical ||
3482                           ParentRegion == OMPD_ordered;
3483       Recommend = ShouldBeInParallelRegion;
3484     } else if (CurrentRegion == OMPD_ordered) {
3485       // OpenMP [2.16, Nesting of Regions]
3486       // An ordered region may not be closely nested inside a critical,
3487       // atomic, or explicit task region.
3488       // An ordered region must be closely nested inside a loop region (or
3489       // parallel loop region) with an ordered clause.
3490       // OpenMP [2.8.1,simd Construct, Restrictions]
3491       // An ordered construct with the simd clause is the only OpenMP construct
3492       // that can appear in the simd region.
3493       NestingProhibited = ParentRegion == OMPD_critical ||
3494                           isOpenMPTaskingDirective(ParentRegion) ||
3495                           !(isOpenMPSimdDirective(ParentRegion) ||
3496                             Stack->isParentOrderedRegion());
3497       Recommend = ShouldBeInOrderedRegion;
3498     } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
3499       // OpenMP [2.16, Nesting of Regions]
3500       // If specified, a teams construct must be contained within a target
3501       // construct.
3502       NestingProhibited = ParentRegion != OMPD_target;
3503       OrphanSeen = ParentRegion == OMPD_unknown;
3504       Recommend = ShouldBeInTargetRegion;
3505     }
3506     if (!NestingProhibited &&
3507         !isOpenMPTargetExecutionDirective(CurrentRegion) &&
3508         !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
3509         (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
3510       // OpenMP [2.16, Nesting of Regions]
3511       // distribute, parallel, parallel sections, parallel workshare, and the
3512       // parallel loop and parallel loop SIMD constructs are the only OpenMP
3513       // constructs that can be closely nested in the teams region.
3514       NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
3515                           !isOpenMPDistributeDirective(CurrentRegion);
3516       Recommend = ShouldBeInParallelRegion;
3517     }
3518     if (!NestingProhibited &&
3519         isOpenMPNestingDistributeDirective(CurrentRegion)) {
3520       // OpenMP 4.5 [2.17 Nesting of Regions]
3521       // The region associated with the distribute construct must be strictly
3522       // nested inside a teams region
3523       NestingProhibited =
3524           (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
3525       Recommend = ShouldBeInTeamsRegion;
3526     }
3527     if (!NestingProhibited &&
3528         (isOpenMPTargetExecutionDirective(CurrentRegion) ||
3529          isOpenMPTargetDataManagementDirective(CurrentRegion))) {
3530       // OpenMP 4.5 [2.17 Nesting of Regions]
3531       // If a target, target update, target data, target enter data, or
3532       // target exit data construct is encountered during execution of a
3533       // target region, the behavior is unspecified.
3534       NestingProhibited = Stack->hasDirective(
3535           [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
3536                              SourceLocation) {
3537             if (isOpenMPTargetExecutionDirective(K)) {
3538               OffendingRegion = K;
3539               return true;
3540             }
3541             return false;
3542           },
3543           false /* don't skip top directive */);
3544       CloseNesting = false;
3545     }
3546     if (NestingProhibited) {
3547       if (OrphanSeen) {
3548         SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
3549             << getOpenMPDirectiveName(CurrentRegion) << Recommend;
3550       } else {
3551         SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
3552             << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
3553             << Recommend << getOpenMPDirectiveName(CurrentRegion);
3554       }
3555       return true;
3556     }
3557   }
3558   return false;
3559 }
3560 
3561 static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
3562                            ArrayRef<OMPClause *> Clauses,
3563                            ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
3564   bool ErrorFound = false;
3565   unsigned NamedModifiersNumber = 0;
3566   SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
3567       OMPD_unknown + 1);
3568   SmallVector<SourceLocation, 4> NameModifierLoc;
3569   for (const OMPClause *C : Clauses) {
3570     if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
3571       // At most one if clause without a directive-name-modifier can appear on
3572       // the directive.
3573       OpenMPDirectiveKind CurNM = IC->getNameModifier();
3574       if (FoundNameModifiers[CurNM]) {
3575         S.Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
3576             << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
3577             << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
3578         ErrorFound = true;
3579       } else if (CurNM != OMPD_unknown) {
3580         NameModifierLoc.push_back(IC->getNameModifierLoc());
3581         ++NamedModifiersNumber;
3582       }
3583       FoundNameModifiers[CurNM] = IC;
3584       if (CurNM == OMPD_unknown)
3585         continue;
3586       // Check if the specified name modifier is allowed for the current
3587       // directive.
3588       // At most one if clause with the particular directive-name-modifier can
3589       // appear on the directive.
3590       bool MatchFound = false;
3591       for (auto NM : AllowedNameModifiers) {
3592         if (CurNM == NM) {
3593           MatchFound = true;
3594           break;
3595         }
3596       }
3597       if (!MatchFound) {
3598         S.Diag(IC->getNameModifierLoc(),
3599                diag::err_omp_wrong_if_directive_name_modifier)
3600             << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
3601         ErrorFound = true;
3602       }
3603     }
3604   }
3605   // If any if clause on the directive includes a directive-name-modifier then
3606   // all if clauses on the directive must include a directive-name-modifier.
3607   if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
3608     if (NamedModifiersNumber == AllowedNameModifiers.size()) {
3609       S.Diag(FoundNameModifiers[OMPD_unknown]->getBeginLoc(),
3610              diag::err_omp_no_more_if_clause);
3611     } else {
3612       std::string Values;
3613       std::string Sep(", ");
3614       unsigned AllowedCnt = 0;
3615       unsigned TotalAllowedNum =
3616           AllowedNameModifiers.size() - NamedModifiersNumber;
3617       for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
3618            ++Cnt) {
3619         OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
3620         if (!FoundNameModifiers[NM]) {
3621           Values += "'";
3622           Values += getOpenMPDirectiveName(NM);
3623           Values += "'";
3624           if (AllowedCnt + 2 == TotalAllowedNum)
3625             Values += " or ";
3626           else if (AllowedCnt + 1 != TotalAllowedNum)
3627             Values += Sep;
3628           ++AllowedCnt;
3629         }
3630       }
3631       S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getBeginLoc(),
3632              diag::err_omp_unnamed_if_clause)
3633           << (TotalAllowedNum > 1) << Values;
3634     }
3635     for (SourceLocation Loc : NameModifierLoc) {
3636       S.Diag(Loc, diag::note_omp_previous_named_if_clause);
3637     }
3638     ErrorFound = true;
3639   }
3640   return ErrorFound;
3641 }
3642 
3643 StmtResult Sema::ActOnOpenMPExecutableDirective(
3644     OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
3645     OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
3646     Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
3647   StmtResult Res = StmtError();
3648   // First check CancelRegion which is then used in checkNestingOfRegions.
3649   if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
3650       checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
3651                             StartLoc))
3652     return StmtError();
3653 
3654   llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
3655   VarsWithInheritedDSAType VarsWithInheritedDSA;
3656   bool ErrorFound = false;
3657   ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
3658   if (AStmt && !CurContext->isDependentContext()) {
3659     assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
3660 
3661     // Check default data sharing attributes for referenced variables.
3662     DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
3663     int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
3664     Stmt *S = AStmt;
3665     while (--ThisCaptureLevel >= 0)
3666       S = cast<CapturedStmt>(S)->getCapturedStmt();
3667     DSAChecker.Visit(S);
3668     if (DSAChecker.isErrorFound())
3669       return StmtError();
3670     // Generate list of implicitly defined firstprivate variables.
3671     VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
3672 
3673     SmallVector<Expr *, 4> ImplicitFirstprivates(
3674         DSAChecker.getImplicitFirstprivate().begin(),
3675         DSAChecker.getImplicitFirstprivate().end());
3676     SmallVector<Expr *, 4> ImplicitMaps(DSAChecker.getImplicitMap().begin(),
3677                                         DSAChecker.getImplicitMap().end());
3678     // Mark taskgroup task_reduction descriptors as implicitly firstprivate.
3679     for (OMPClause *C : Clauses) {
3680       if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) {
3681         for (Expr *E : IRC->taskgroup_descriptors())
3682           if (E)
3683             ImplicitFirstprivates.emplace_back(E);
3684       }
3685     }
3686     if (!ImplicitFirstprivates.empty()) {
3687       if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
3688               ImplicitFirstprivates, SourceLocation(), SourceLocation(),
3689               SourceLocation())) {
3690         ClausesWithImplicit.push_back(Implicit);
3691         ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
3692                      ImplicitFirstprivates.size();
3693       } else {
3694         ErrorFound = true;
3695       }
3696     }
3697     if (!ImplicitMaps.empty()) {
3698       CXXScopeSpec MapperIdScopeSpec;
3699       DeclarationNameInfo MapperId;
3700       if (OMPClause *Implicit = ActOnOpenMPMapClause(
3701               llvm::None, llvm::None, MapperIdScopeSpec, MapperId,
3702               OMPC_MAP_tofrom, /*IsMapTypeImplicit=*/true, SourceLocation(),
3703               SourceLocation(), ImplicitMaps, OMPVarListLocTy())) {
3704         ClausesWithImplicit.emplace_back(Implicit);
3705         ErrorFound |=
3706             cast<OMPMapClause>(Implicit)->varlist_size() != ImplicitMaps.size();
3707       } else {
3708         ErrorFound = true;
3709       }
3710     }
3711   }
3712 
3713   llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
3714   switch (Kind) {
3715   case OMPD_parallel:
3716     Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
3717                                        EndLoc);
3718     AllowedNameModifiers.push_back(OMPD_parallel);
3719     break;
3720   case OMPD_simd:
3721     Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
3722                                    VarsWithInheritedDSA);
3723     break;
3724   case OMPD_for:
3725     Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
3726                                   VarsWithInheritedDSA);
3727     break;
3728   case OMPD_for_simd:
3729     Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3730                                       EndLoc, VarsWithInheritedDSA);
3731     break;
3732   case OMPD_sections:
3733     Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
3734                                        EndLoc);
3735     break;
3736   case OMPD_section:
3737     assert(ClausesWithImplicit.empty() &&
3738            "No clauses are allowed for 'omp section' directive");
3739     Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
3740     break;
3741   case OMPD_single:
3742     Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
3743                                      EndLoc);
3744     break;
3745   case OMPD_master:
3746     assert(ClausesWithImplicit.empty() &&
3747            "No clauses are allowed for 'omp master' directive");
3748     Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
3749     break;
3750   case OMPD_critical:
3751     Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
3752                                        StartLoc, EndLoc);
3753     break;
3754   case OMPD_parallel_for:
3755     Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
3756                                           EndLoc, VarsWithInheritedDSA);
3757     AllowedNameModifiers.push_back(OMPD_parallel);
3758     break;
3759   case OMPD_parallel_for_simd:
3760     Res = ActOnOpenMPParallelForSimdDirective(
3761         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3762     AllowedNameModifiers.push_back(OMPD_parallel);
3763     break;
3764   case OMPD_parallel_sections:
3765     Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
3766                                                StartLoc, EndLoc);
3767     AllowedNameModifiers.push_back(OMPD_parallel);
3768     break;
3769   case OMPD_task:
3770     Res =
3771         ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
3772     AllowedNameModifiers.push_back(OMPD_task);
3773     break;
3774   case OMPD_taskyield:
3775     assert(ClausesWithImplicit.empty() &&
3776            "No clauses are allowed for 'omp taskyield' directive");
3777     assert(AStmt == nullptr &&
3778            "No associated statement allowed for 'omp taskyield' directive");
3779     Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
3780     break;
3781   case OMPD_barrier:
3782     assert(ClausesWithImplicit.empty() &&
3783            "No clauses are allowed for 'omp barrier' directive");
3784     assert(AStmt == nullptr &&
3785            "No associated statement allowed for 'omp barrier' directive");
3786     Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
3787     break;
3788   case OMPD_taskwait:
3789     assert(ClausesWithImplicit.empty() &&
3790            "No clauses are allowed for 'omp taskwait' directive");
3791     assert(AStmt == nullptr &&
3792            "No associated statement allowed for 'omp taskwait' directive");
3793     Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
3794     break;
3795   case OMPD_taskgroup:
3796     Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc,
3797                                         EndLoc);
3798     break;
3799   case OMPD_flush:
3800     assert(AStmt == nullptr &&
3801            "No associated statement allowed for 'omp flush' directive");
3802     Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
3803     break;
3804   case OMPD_ordered:
3805     Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
3806                                       EndLoc);
3807     break;
3808   case OMPD_atomic:
3809     Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
3810                                      EndLoc);
3811     break;
3812   case OMPD_teams:
3813     Res =
3814         ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
3815     break;
3816   case OMPD_target:
3817     Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
3818                                      EndLoc);
3819     AllowedNameModifiers.push_back(OMPD_target);
3820     break;
3821   case OMPD_target_parallel:
3822     Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
3823                                              StartLoc, EndLoc);
3824     AllowedNameModifiers.push_back(OMPD_target);
3825     AllowedNameModifiers.push_back(OMPD_parallel);
3826     break;
3827   case OMPD_target_parallel_for:
3828     Res = ActOnOpenMPTargetParallelForDirective(
3829         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3830     AllowedNameModifiers.push_back(OMPD_target);
3831     AllowedNameModifiers.push_back(OMPD_parallel);
3832     break;
3833   case OMPD_cancellation_point:
3834     assert(ClausesWithImplicit.empty() &&
3835            "No clauses are allowed for 'omp cancellation point' directive");
3836     assert(AStmt == nullptr && "No associated statement allowed for 'omp "
3837                                "cancellation point' directive");
3838     Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
3839     break;
3840   case OMPD_cancel:
3841     assert(AStmt == nullptr &&
3842            "No associated statement allowed for 'omp cancel' directive");
3843     Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
3844                                      CancelRegion);
3845     AllowedNameModifiers.push_back(OMPD_cancel);
3846     break;
3847   case OMPD_target_data:
3848     Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
3849                                          EndLoc);
3850     AllowedNameModifiers.push_back(OMPD_target_data);
3851     break;
3852   case OMPD_target_enter_data:
3853     Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
3854                                               EndLoc, AStmt);
3855     AllowedNameModifiers.push_back(OMPD_target_enter_data);
3856     break;
3857   case OMPD_target_exit_data:
3858     Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
3859                                              EndLoc, AStmt);
3860     AllowedNameModifiers.push_back(OMPD_target_exit_data);
3861     break;
3862   case OMPD_taskloop:
3863     Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
3864                                        EndLoc, VarsWithInheritedDSA);
3865     AllowedNameModifiers.push_back(OMPD_taskloop);
3866     break;
3867   case OMPD_taskloop_simd:
3868     Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3869                                            EndLoc, VarsWithInheritedDSA);
3870     AllowedNameModifiers.push_back(OMPD_taskloop);
3871     break;
3872   case OMPD_distribute:
3873     Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
3874                                          EndLoc, VarsWithInheritedDSA);
3875     break;
3876   case OMPD_target_update:
3877     Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc,
3878                                            EndLoc, AStmt);
3879     AllowedNameModifiers.push_back(OMPD_target_update);
3880     break;
3881   case OMPD_distribute_parallel_for:
3882     Res = ActOnOpenMPDistributeParallelForDirective(
3883         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3884     AllowedNameModifiers.push_back(OMPD_parallel);
3885     break;
3886   case OMPD_distribute_parallel_for_simd:
3887     Res = ActOnOpenMPDistributeParallelForSimdDirective(
3888         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3889     AllowedNameModifiers.push_back(OMPD_parallel);
3890     break;
3891   case OMPD_distribute_simd:
3892     Res = ActOnOpenMPDistributeSimdDirective(
3893         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3894     break;
3895   case OMPD_target_parallel_for_simd:
3896     Res = ActOnOpenMPTargetParallelForSimdDirective(
3897         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3898     AllowedNameModifiers.push_back(OMPD_target);
3899     AllowedNameModifiers.push_back(OMPD_parallel);
3900     break;
3901   case OMPD_target_simd:
3902     Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3903                                          EndLoc, VarsWithInheritedDSA);
3904     AllowedNameModifiers.push_back(OMPD_target);
3905     break;
3906   case OMPD_teams_distribute:
3907     Res = ActOnOpenMPTeamsDistributeDirective(
3908         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3909     break;
3910   case OMPD_teams_distribute_simd:
3911     Res = ActOnOpenMPTeamsDistributeSimdDirective(
3912         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3913     break;
3914   case OMPD_teams_distribute_parallel_for_simd:
3915     Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
3916         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3917     AllowedNameModifiers.push_back(OMPD_parallel);
3918     break;
3919   case OMPD_teams_distribute_parallel_for:
3920     Res = ActOnOpenMPTeamsDistributeParallelForDirective(
3921         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3922     AllowedNameModifiers.push_back(OMPD_parallel);
3923     break;
3924   case OMPD_target_teams:
3925     Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
3926                                           EndLoc);
3927     AllowedNameModifiers.push_back(OMPD_target);
3928     break;
3929   case OMPD_target_teams_distribute:
3930     Res = ActOnOpenMPTargetTeamsDistributeDirective(
3931         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3932     AllowedNameModifiers.push_back(OMPD_target);
3933     break;
3934   case OMPD_target_teams_distribute_parallel_for:
3935     Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
3936         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3937     AllowedNameModifiers.push_back(OMPD_target);
3938     AllowedNameModifiers.push_back(OMPD_parallel);
3939     break;
3940   case OMPD_target_teams_distribute_parallel_for_simd:
3941     Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
3942         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3943     AllowedNameModifiers.push_back(OMPD_target);
3944     AllowedNameModifiers.push_back(OMPD_parallel);
3945     break;
3946   case OMPD_target_teams_distribute_simd:
3947     Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
3948         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3949     AllowedNameModifiers.push_back(OMPD_target);
3950     break;
3951   case OMPD_declare_target:
3952   case OMPD_end_declare_target:
3953   case OMPD_threadprivate:
3954   case OMPD_allocate:
3955   case OMPD_declare_reduction:
3956   case OMPD_declare_mapper:
3957   case OMPD_declare_simd:
3958   case OMPD_requires:
3959     llvm_unreachable("OpenMP Directive is not allowed");
3960   case OMPD_unknown:
3961     llvm_unreachable("Unknown OpenMP directive");
3962   }
3963 
3964   ErrorFound = Res.isInvalid() || ErrorFound;
3965 
3966   for (const auto &P : VarsWithInheritedDSA) {
3967     Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
3968         << P.first << P.second->getSourceRange();
3969   }
3970   ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound;
3971 
3972   if (!AllowedNameModifiers.empty())
3973     ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
3974                  ErrorFound;
3975 
3976   if (ErrorFound)
3977     return StmtError();
3978 
3979   if (!(Res.getAs<OMPExecutableDirective>()->isStandaloneDirective())) {
3980     Res.getAs<OMPExecutableDirective>()
3981         ->getStructuredBlock()
3982         ->setIsOMPStructuredBlock(true);
3983   }
3984 
3985   return Res;
3986 }
3987 
3988 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
3989     DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
3990     ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
3991     ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
3992     ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
3993   assert(Aligneds.size() == Alignments.size());
3994   assert(Linears.size() == LinModifiers.size());
3995   assert(Linears.size() == Steps.size());
3996   if (!DG || DG.get().isNull())
3997     return DeclGroupPtrTy();
3998 
3999   if (!DG.get().isSingleDecl()) {
4000     Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd);
4001     return DG;
4002   }
4003   Decl *ADecl = DG.get().getSingleDecl();
4004   if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
4005     ADecl = FTD->getTemplatedDecl();
4006 
4007   auto *FD = dyn_cast<FunctionDecl>(ADecl);
4008   if (!FD) {
4009     Diag(ADecl->getLocation(), diag::err_omp_function_expected);
4010     return DeclGroupPtrTy();
4011   }
4012 
4013   // OpenMP [2.8.2, declare simd construct, Description]
4014   // The parameter of the simdlen clause must be a constant positive integer
4015   // expression.
4016   ExprResult SL;
4017   if (Simdlen)
4018     SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
4019   // OpenMP [2.8.2, declare simd construct, Description]
4020   // The special this pointer can be used as if was one of the arguments to the
4021   // function in any of the linear, aligned, or uniform clauses.
4022   // The uniform clause declares one or more arguments to have an invariant
4023   // value for all concurrent invocations of the function in the execution of a
4024   // single SIMD loop.
4025   llvm::DenseMap<const Decl *, const Expr *> UniformedArgs;
4026   const Expr *UniformedLinearThis = nullptr;
4027   for (const Expr *E : Uniforms) {
4028     E = E->IgnoreParenImpCasts();
4029     if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
4030       if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
4031         if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
4032             FD->getParamDecl(PVD->getFunctionScopeIndex())
4033                     ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
4034           UniformedArgs.try_emplace(PVD->getCanonicalDecl(), E);
4035           continue;
4036         }
4037     if (isa<CXXThisExpr>(E)) {
4038       UniformedLinearThis = E;
4039       continue;
4040     }
4041     Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
4042         << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
4043   }
4044   // OpenMP [2.8.2, declare simd construct, Description]
4045   // The aligned clause declares that the object to which each list item points
4046   // is aligned to the number of bytes expressed in the optional parameter of
4047   // the aligned clause.
4048   // The special this pointer can be used as if was one of the arguments to the
4049   // function in any of the linear, aligned, or uniform clauses.
4050   // The type of list items appearing in the aligned clause must be array,
4051   // pointer, reference to array, or reference to pointer.
4052   llvm::DenseMap<const Decl *, const Expr *> AlignedArgs;
4053   const Expr *AlignedThis = nullptr;
4054   for (const Expr *E : Aligneds) {
4055     E = E->IgnoreParenImpCasts();
4056     if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
4057       if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
4058         const VarDecl *CanonPVD = PVD->getCanonicalDecl();
4059         if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
4060             FD->getParamDecl(PVD->getFunctionScopeIndex())
4061                     ->getCanonicalDecl() == CanonPVD) {
4062           // OpenMP  [2.8.1, simd construct, Restrictions]
4063           // A list-item cannot appear in more than one aligned clause.
4064           if (AlignedArgs.count(CanonPVD) > 0) {
4065             Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
4066                 << 1 << E->getSourceRange();
4067             Diag(AlignedArgs[CanonPVD]->getExprLoc(),
4068                  diag::note_omp_explicit_dsa)
4069                 << getOpenMPClauseName(OMPC_aligned);
4070             continue;
4071           }
4072           AlignedArgs[CanonPVD] = E;
4073           QualType QTy = PVD->getType()
4074                              .getNonReferenceType()
4075                              .getUnqualifiedType()
4076                              .getCanonicalType();
4077           const Type *Ty = QTy.getTypePtrOrNull();
4078           if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
4079             Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
4080                 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
4081             Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
4082           }
4083           continue;
4084         }
4085       }
4086     if (isa<CXXThisExpr>(E)) {
4087       if (AlignedThis) {
4088         Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
4089             << 2 << E->getSourceRange();
4090         Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
4091             << getOpenMPClauseName(OMPC_aligned);
4092       }
4093       AlignedThis = E;
4094       continue;
4095     }
4096     Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
4097         << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
4098   }
4099   // The optional parameter of the aligned clause, alignment, must be a constant
4100   // positive integer expression. If no optional parameter is specified,
4101   // implementation-defined default alignments for SIMD instructions on the
4102   // target platforms are assumed.
4103   SmallVector<const Expr *, 4> NewAligns;
4104   for (Expr *E : Alignments) {
4105     ExprResult Align;
4106     if (E)
4107       Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
4108     NewAligns.push_back(Align.get());
4109   }
4110   // OpenMP [2.8.2, declare simd construct, Description]
4111   // The linear clause declares one or more list items to be private to a SIMD
4112   // lane and to have a linear relationship with respect to the iteration space
4113   // of a loop.
4114   // The special this pointer can be used as if was one of the arguments to the
4115   // function in any of the linear, aligned, or uniform clauses.
4116   // When a linear-step expression is specified in a linear clause it must be
4117   // either a constant integer expression or an integer-typed parameter that is
4118   // specified in a uniform clause on the directive.
4119   llvm::DenseMap<const Decl *, const Expr *> LinearArgs;
4120   const bool IsUniformedThis = UniformedLinearThis != nullptr;
4121   auto MI = LinModifiers.begin();
4122   for (const Expr *E : Linears) {
4123     auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
4124     ++MI;
4125     E = E->IgnoreParenImpCasts();
4126     if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
4127       if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
4128         const VarDecl *CanonPVD = PVD->getCanonicalDecl();
4129         if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
4130             FD->getParamDecl(PVD->getFunctionScopeIndex())
4131                     ->getCanonicalDecl() == CanonPVD) {
4132           // OpenMP  [2.15.3.7, linear Clause, Restrictions]
4133           // A list-item cannot appear in more than one linear clause.
4134           if (LinearArgs.count(CanonPVD) > 0) {
4135             Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
4136                 << getOpenMPClauseName(OMPC_linear)
4137                 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
4138             Diag(LinearArgs[CanonPVD]->getExprLoc(),
4139                  diag::note_omp_explicit_dsa)
4140                 << getOpenMPClauseName(OMPC_linear);
4141             continue;
4142           }
4143           // Each argument can appear in at most one uniform or linear clause.
4144           if (UniformedArgs.count(CanonPVD) > 0) {
4145             Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
4146                 << getOpenMPClauseName(OMPC_linear)
4147                 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
4148             Diag(UniformedArgs[CanonPVD]->getExprLoc(),
4149                  diag::note_omp_explicit_dsa)
4150                 << getOpenMPClauseName(OMPC_uniform);
4151             continue;
4152           }
4153           LinearArgs[CanonPVD] = E;
4154           if (E->isValueDependent() || E->isTypeDependent() ||
4155               E->isInstantiationDependent() ||
4156               E->containsUnexpandedParameterPack())
4157             continue;
4158           (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
4159                                       PVD->getOriginalType());
4160           continue;
4161         }
4162       }
4163     if (isa<CXXThisExpr>(E)) {
4164       if (UniformedLinearThis) {
4165         Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
4166             << getOpenMPClauseName(OMPC_linear)
4167             << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
4168             << E->getSourceRange();
4169         Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
4170             << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
4171                                                    : OMPC_linear);
4172         continue;
4173       }
4174       UniformedLinearThis = E;
4175       if (E->isValueDependent() || E->isTypeDependent() ||
4176           E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
4177         continue;
4178       (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
4179                                   E->getType());
4180       continue;
4181     }
4182     Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
4183         << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
4184   }
4185   Expr *Step = nullptr;
4186   Expr *NewStep = nullptr;
4187   SmallVector<Expr *, 4> NewSteps;
4188   for (Expr *E : Steps) {
4189     // Skip the same step expression, it was checked already.
4190     if (Step == E || !E) {
4191       NewSteps.push_back(E ? NewStep : nullptr);
4192       continue;
4193     }
4194     Step = E;
4195     if (const auto *DRE = dyn_cast<DeclRefExpr>(Step))
4196       if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
4197         const VarDecl *CanonPVD = PVD->getCanonicalDecl();
4198         if (UniformedArgs.count(CanonPVD) == 0) {
4199           Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
4200               << Step->getSourceRange();
4201         } else if (E->isValueDependent() || E->isTypeDependent() ||
4202                    E->isInstantiationDependent() ||
4203                    E->containsUnexpandedParameterPack() ||
4204                    CanonPVD->getType()->hasIntegerRepresentation()) {
4205           NewSteps.push_back(Step);
4206         } else {
4207           Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
4208               << Step->getSourceRange();
4209         }
4210         continue;
4211       }
4212     NewStep = Step;
4213     if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
4214         !Step->isInstantiationDependent() &&
4215         !Step->containsUnexpandedParameterPack()) {
4216       NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
4217                     .get();
4218       if (NewStep)
4219         NewStep = VerifyIntegerConstantExpression(NewStep).get();
4220     }
4221     NewSteps.push_back(NewStep);
4222   }
4223   auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
4224       Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
4225       Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
4226       const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
4227       const_cast<Expr **>(Linears.data()), Linears.size(),
4228       const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
4229       NewSteps.data(), NewSteps.size(), SR);
4230   ADecl->addAttr(NewAttr);
4231   return ConvertDeclToDeclGroup(ADecl);
4232 }
4233 
4234 StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
4235                                               Stmt *AStmt,
4236                                               SourceLocation StartLoc,
4237                                               SourceLocation EndLoc) {
4238   if (!AStmt)
4239     return StmtError();
4240 
4241   auto *CS = cast<CapturedStmt>(AStmt);
4242   // 1.2.2 OpenMP Language Terminology
4243   // Structured block - An executable statement with a single entry at the
4244   // top and a single exit at the bottom.
4245   // The point of exit cannot be a branch out of the structured block.
4246   // longjmp() and throw() must not violate the entry/exit criteria.
4247   CS->getCapturedDecl()->setNothrow();
4248 
4249   setFunctionHasBranchProtectedScope();
4250 
4251   return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
4252                                       DSAStack->isCancelRegion());
4253 }
4254 
4255 namespace {
4256 /// Helper class for checking canonical form of the OpenMP loops and
4257 /// extracting iteration space of each loop in the loop nest, that will be used
4258 /// for IR generation.
4259 class OpenMPIterationSpaceChecker {
4260   /// Reference to Sema.
4261   Sema &SemaRef;
4262   /// A location for diagnostics (when there is no some better location).
4263   SourceLocation DefaultLoc;
4264   /// A location for diagnostics (when increment is not compatible).
4265   SourceLocation ConditionLoc;
4266   /// A source location for referring to loop init later.
4267   SourceRange InitSrcRange;
4268   /// A source location for referring to condition later.
4269   SourceRange ConditionSrcRange;
4270   /// A source location for referring to increment later.
4271   SourceRange IncrementSrcRange;
4272   /// Loop variable.
4273   ValueDecl *LCDecl = nullptr;
4274   /// Reference to loop variable.
4275   Expr *LCRef = nullptr;
4276   /// Lower bound (initializer for the var).
4277   Expr *LB = nullptr;
4278   /// Upper bound.
4279   Expr *UB = nullptr;
4280   /// Loop step (increment).
4281   Expr *Step = nullptr;
4282   /// This flag is true when condition is one of:
4283   ///   Var <  UB
4284   ///   Var <= UB
4285   ///   UB  >  Var
4286   ///   UB  >= Var
4287   /// This will have no value when the condition is !=
4288   llvm::Optional<bool> TestIsLessOp;
4289   /// This flag is true when condition is strict ( < or > ).
4290   bool TestIsStrictOp = false;
4291   /// This flag is true when step is subtracted on each iteration.
4292   bool SubtractStep = false;
4293 
4294 public:
4295   OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
4296       : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {}
4297   /// Check init-expr for canonical loop form and save loop counter
4298   /// variable - #Var and its initialization value - #LB.
4299   bool checkAndSetInit(Stmt *S, bool EmitDiags = true);
4300   /// Check test-expr for canonical form, save upper-bound (#UB), flags
4301   /// for less/greater and for strict/non-strict comparison.
4302   bool checkAndSetCond(Expr *S);
4303   /// Check incr-expr for canonical loop form and return true if it
4304   /// does not conform, otherwise save loop step (#Step).
4305   bool checkAndSetInc(Expr *S);
4306   /// Return the loop counter variable.
4307   ValueDecl *getLoopDecl() const { return LCDecl; }
4308   /// Return the reference expression to loop counter variable.
4309   Expr *getLoopDeclRefExpr() const { return LCRef; }
4310   /// Source range of the loop init.
4311   SourceRange getInitSrcRange() const { return InitSrcRange; }
4312   /// Source range of the loop condition.
4313   SourceRange getConditionSrcRange() const { return ConditionSrcRange; }
4314   /// Source range of the loop increment.
4315   SourceRange getIncrementSrcRange() const { return IncrementSrcRange; }
4316   /// True if the step should be subtracted.
4317   bool shouldSubtractStep() const { return SubtractStep; }
4318   /// True, if the compare operator is strict (<, > or !=).
4319   bool isStrictTestOp() const { return TestIsStrictOp; }
4320   /// Build the expression to calculate the number of iterations.
4321   Expr *buildNumIterations(
4322       Scope *S, const bool LimitedType,
4323       llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
4324   /// Build the precondition expression for the loops.
4325   Expr *
4326   buildPreCond(Scope *S, Expr *Cond,
4327                llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
4328   /// Build reference expression to the counter be used for codegen.
4329   DeclRefExpr *
4330   buildCounterVar(llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
4331                   DSAStackTy &DSA) const;
4332   /// Build reference expression to the private counter be used for
4333   /// codegen.
4334   Expr *buildPrivateCounterVar() const;
4335   /// Build initialization of the counter be used for codegen.
4336   Expr *buildCounterInit() const;
4337   /// Build step of the counter be used for codegen.
4338   Expr *buildCounterStep() const;
4339   /// Build loop data with counter value for depend clauses in ordered
4340   /// directives.
4341   Expr *
4342   buildOrderedLoopData(Scope *S, Expr *Counter,
4343                        llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
4344                        SourceLocation Loc, Expr *Inc = nullptr,
4345                        OverloadedOperatorKind OOK = OO_Amp);
4346   /// Return true if any expression is dependent.
4347   bool dependent() const;
4348 
4349 private:
4350   /// Check the right-hand side of an assignment in the increment
4351   /// expression.
4352   bool checkAndSetIncRHS(Expr *RHS);
4353   /// Helper to set loop counter variable and its initializer.
4354   bool setLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB);
4355   /// Helper to set upper bound.
4356   bool setUB(Expr *NewUB, llvm::Optional<bool> LessOp, bool StrictOp,
4357              SourceRange SR, SourceLocation SL);
4358   /// Helper to set loop increment.
4359   bool setStep(Expr *NewStep, bool Subtract);
4360 };
4361 
4362 bool OpenMPIterationSpaceChecker::dependent() const {
4363   if (!LCDecl) {
4364     assert(!LB && !UB && !Step);
4365     return false;
4366   }
4367   return LCDecl->getType()->isDependentType() ||
4368          (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
4369          (Step && Step->isValueDependent());
4370 }
4371 
4372 bool OpenMPIterationSpaceChecker::setLCDeclAndLB(ValueDecl *NewLCDecl,
4373                                                  Expr *NewLCRefExpr,
4374                                                  Expr *NewLB) {
4375   // State consistency checking to ensure correct usage.
4376   assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
4377          UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
4378   if (!NewLCDecl || !NewLB)
4379     return true;
4380   LCDecl = getCanonicalDecl(NewLCDecl);
4381   LCRef = NewLCRefExpr;
4382   if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
4383     if (const CXXConstructorDecl *Ctor = CE->getConstructor())
4384       if ((Ctor->isCopyOrMoveConstructor() ||
4385            Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
4386           CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
4387         NewLB = CE->getArg(0)->IgnoreParenImpCasts();
4388   LB = NewLB;
4389   return false;
4390 }
4391 
4392 bool OpenMPIterationSpaceChecker::setUB(Expr *NewUB,
4393                                         llvm::Optional<bool> LessOp,
4394                                         bool StrictOp, SourceRange SR,
4395                                         SourceLocation SL) {
4396   // State consistency checking to ensure correct usage.
4397   assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
4398          Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
4399   if (!NewUB)
4400     return true;
4401   UB = NewUB;
4402   if (LessOp)
4403     TestIsLessOp = LessOp;
4404   TestIsStrictOp = StrictOp;
4405   ConditionSrcRange = SR;
4406   ConditionLoc = SL;
4407   return false;
4408 }
4409 
4410 bool OpenMPIterationSpaceChecker::setStep(Expr *NewStep, bool Subtract) {
4411   // State consistency checking to ensure correct usage.
4412   assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
4413   if (!NewStep)
4414     return true;
4415   if (!NewStep->isValueDependent()) {
4416     // Check that the step is integer expression.
4417     SourceLocation StepLoc = NewStep->getBeginLoc();
4418     ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion(
4419         StepLoc, getExprAsWritten(NewStep));
4420     if (Val.isInvalid())
4421       return true;
4422     NewStep = Val.get();
4423 
4424     // OpenMP [2.6, Canonical Loop Form, Restrictions]
4425     //  If test-expr is of form var relational-op b and relational-op is < or
4426     //  <= then incr-expr must cause var to increase on each iteration of the
4427     //  loop. If test-expr is of form var relational-op b and relational-op is
4428     //  > or >= then incr-expr must cause var to decrease on each iteration of
4429     //  the loop.
4430     //  If test-expr is of form b relational-op var and relational-op is < or
4431     //  <= then incr-expr must cause var to decrease on each iteration of the
4432     //  loop. If test-expr is of form b relational-op var and relational-op is
4433     //  > or >= then incr-expr must cause var to increase on each iteration of
4434     //  the loop.
4435     llvm::APSInt Result;
4436     bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
4437     bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
4438     bool IsConstNeg =
4439         IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
4440     bool IsConstPos =
4441         IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
4442     bool IsConstZero = IsConstant && !Result.getBoolValue();
4443 
4444     // != with increment is treated as <; != with decrement is treated as >
4445     if (!TestIsLessOp.hasValue())
4446       TestIsLessOp = IsConstPos || (IsUnsigned && !Subtract);
4447     if (UB && (IsConstZero ||
4448                (TestIsLessOp.getValue() ?
4449                   (IsConstNeg || (IsUnsigned && Subtract)) :
4450                   (IsConstPos || (IsUnsigned && !Subtract))))) {
4451       SemaRef.Diag(NewStep->getExprLoc(),
4452                    diag::err_omp_loop_incr_not_compatible)
4453           << LCDecl << TestIsLessOp.getValue() << NewStep->getSourceRange();
4454       SemaRef.Diag(ConditionLoc,
4455                    diag::note_omp_loop_cond_requres_compatible_incr)
4456           << TestIsLessOp.getValue() << ConditionSrcRange;
4457       return true;
4458     }
4459     if (TestIsLessOp.getValue() == Subtract) {
4460       NewStep =
4461           SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
4462               .get();
4463       Subtract = !Subtract;
4464     }
4465   }
4466 
4467   Step = NewStep;
4468   SubtractStep = Subtract;
4469   return false;
4470 }
4471 
4472 bool OpenMPIterationSpaceChecker::checkAndSetInit(Stmt *S, bool EmitDiags) {
4473   // Check init-expr for canonical loop form and save loop counter
4474   // variable - #Var and its initialization value - #LB.
4475   // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
4476   //   var = lb
4477   //   integer-type var = lb
4478   //   random-access-iterator-type var = lb
4479   //   pointer-type var = lb
4480   //
4481   if (!S) {
4482     if (EmitDiags) {
4483       SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
4484     }
4485     return true;
4486   }
4487   if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
4488     if (!ExprTemp->cleanupsHaveSideEffects())
4489       S = ExprTemp->getSubExpr();
4490 
4491   InitSrcRange = S->getSourceRange();
4492   if (Expr *E = dyn_cast<Expr>(S))
4493     S = E->IgnoreParens();
4494   if (auto *BO = dyn_cast<BinaryOperator>(S)) {
4495     if (BO->getOpcode() == BO_Assign) {
4496       Expr *LHS = BO->getLHS()->IgnoreParens();
4497       if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
4498         if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
4499           if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
4500             return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
4501         return setLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS());
4502       }
4503       if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
4504         if (ME->isArrow() &&
4505             isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
4506           return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
4507       }
4508     }
4509   } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
4510     if (DS->isSingleDecl()) {
4511       if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
4512         if (Var->hasInit() && !Var->getType()->isReferenceType()) {
4513           // Accept non-canonical init form here but emit ext. warning.
4514           if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
4515             SemaRef.Diag(S->getBeginLoc(),
4516                          diag::ext_omp_loop_not_canonical_init)
4517                 << S->getSourceRange();
4518           return setLCDeclAndLB(
4519               Var,
4520               buildDeclRefExpr(SemaRef, Var,
4521                                Var->getType().getNonReferenceType(),
4522                                DS->getBeginLoc()),
4523               Var->getInit());
4524         }
4525       }
4526     }
4527   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
4528     if (CE->getOperator() == OO_Equal) {
4529       Expr *LHS = CE->getArg(0);
4530       if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
4531         if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
4532           if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
4533             return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
4534         return setLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1));
4535       }
4536       if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
4537         if (ME->isArrow() &&
4538             isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
4539           return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
4540       }
4541     }
4542   }
4543 
4544   if (dependent() || SemaRef.CurContext->isDependentContext())
4545     return false;
4546   if (EmitDiags) {
4547     SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_init)
4548         << S->getSourceRange();
4549   }
4550   return true;
4551 }
4552 
4553 /// Ignore parenthesizes, implicit casts, copy constructor and return the
4554 /// variable (which may be the loop variable) if possible.
4555 static const ValueDecl *getInitLCDecl(const Expr *E) {
4556   if (!E)
4557     return nullptr;
4558   E = getExprAsWritten(E);
4559   if (const auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
4560     if (const CXXConstructorDecl *Ctor = CE->getConstructor())
4561       if ((Ctor->isCopyOrMoveConstructor() ||
4562            Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
4563           CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
4564         E = CE->getArg(0)->IgnoreParenImpCasts();
4565   if (const auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
4566     if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
4567       return getCanonicalDecl(VD);
4568   }
4569   if (const auto *ME = dyn_cast_or_null<MemberExpr>(E))
4570     if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
4571       return getCanonicalDecl(ME->getMemberDecl());
4572   return nullptr;
4573 }
4574 
4575 bool OpenMPIterationSpaceChecker::checkAndSetCond(Expr *S) {
4576   // Check test-expr for canonical form, save upper-bound UB, flags for
4577   // less/greater and for strict/non-strict comparison.
4578   // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
4579   //   var relational-op b
4580   //   b relational-op var
4581   //
4582   if (!S) {
4583     SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl;
4584     return true;
4585   }
4586   S = getExprAsWritten(S);
4587   SourceLocation CondLoc = S->getBeginLoc();
4588   if (auto *BO = dyn_cast<BinaryOperator>(S)) {
4589     if (BO->isRelationalOp()) {
4590       if (getInitLCDecl(BO->getLHS()) == LCDecl)
4591         return setUB(BO->getRHS(),
4592                      (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
4593                      (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
4594                      BO->getSourceRange(), BO->getOperatorLoc());
4595       if (getInitLCDecl(BO->getRHS()) == LCDecl)
4596         return setUB(BO->getLHS(),
4597                      (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
4598                      (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
4599                      BO->getSourceRange(), BO->getOperatorLoc());
4600     } else if (BO->getOpcode() == BO_NE)
4601         return setUB(getInitLCDecl(BO->getLHS()) == LCDecl ?
4602                        BO->getRHS() : BO->getLHS(),
4603                      /*LessOp=*/llvm::None,
4604                      /*StrictOp=*/true,
4605                      BO->getSourceRange(), BO->getOperatorLoc());
4606   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
4607     if (CE->getNumArgs() == 2) {
4608       auto Op = CE->getOperator();
4609       switch (Op) {
4610       case OO_Greater:
4611       case OO_GreaterEqual:
4612       case OO_Less:
4613       case OO_LessEqual:
4614         if (getInitLCDecl(CE->getArg(0)) == LCDecl)
4615           return setUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
4616                        Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
4617                        CE->getOperatorLoc());
4618         if (getInitLCDecl(CE->getArg(1)) == LCDecl)
4619           return setUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
4620                        Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
4621                        CE->getOperatorLoc());
4622         break;
4623       case OO_ExclaimEqual:
4624         return setUB(getInitLCDecl(CE->getArg(0)) == LCDecl ?
4625                      CE->getArg(1) : CE->getArg(0),
4626                      /*LessOp=*/llvm::None,
4627                      /*StrictOp=*/true,
4628                      CE->getSourceRange(),
4629                      CE->getOperatorLoc());
4630         break;
4631       default:
4632         break;
4633       }
4634     }
4635   }
4636   if (dependent() || SemaRef.CurContext->isDependentContext())
4637     return false;
4638   SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
4639       << S->getSourceRange() << LCDecl;
4640   return true;
4641 }
4642 
4643 bool OpenMPIterationSpaceChecker::checkAndSetIncRHS(Expr *RHS) {
4644   // RHS of canonical loop form increment can be:
4645   //   var + incr
4646   //   incr + var
4647   //   var - incr
4648   //
4649   RHS = RHS->IgnoreParenImpCasts();
4650   if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
4651     if (BO->isAdditiveOp()) {
4652       bool IsAdd = BO->getOpcode() == BO_Add;
4653       if (getInitLCDecl(BO->getLHS()) == LCDecl)
4654         return setStep(BO->getRHS(), !IsAdd);
4655       if (IsAdd && getInitLCDecl(BO->getRHS()) == LCDecl)
4656         return setStep(BO->getLHS(), /*Subtract=*/false);
4657     }
4658   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
4659     bool IsAdd = CE->getOperator() == OO_Plus;
4660     if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
4661       if (getInitLCDecl(CE->getArg(0)) == LCDecl)
4662         return setStep(CE->getArg(1), !IsAdd);
4663       if (IsAdd && getInitLCDecl(CE->getArg(1)) == LCDecl)
4664         return setStep(CE->getArg(0), /*Subtract=*/false);
4665     }
4666   }
4667   if (dependent() || SemaRef.CurContext->isDependentContext())
4668     return false;
4669   SemaRef.Diag(RHS->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
4670       << RHS->getSourceRange() << LCDecl;
4671   return true;
4672 }
4673 
4674 bool OpenMPIterationSpaceChecker::checkAndSetInc(Expr *S) {
4675   // Check incr-expr for canonical loop form and return true if it
4676   // does not conform.
4677   // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
4678   //   ++var
4679   //   var++
4680   //   --var
4681   //   var--
4682   //   var += incr
4683   //   var -= incr
4684   //   var = var + incr
4685   //   var = incr + var
4686   //   var = var - incr
4687   //
4688   if (!S) {
4689     SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
4690     return true;
4691   }
4692   if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
4693     if (!ExprTemp->cleanupsHaveSideEffects())
4694       S = ExprTemp->getSubExpr();
4695 
4696   IncrementSrcRange = S->getSourceRange();
4697   S = S->IgnoreParens();
4698   if (auto *UO = dyn_cast<UnaryOperator>(S)) {
4699     if (UO->isIncrementDecrementOp() &&
4700         getInitLCDecl(UO->getSubExpr()) == LCDecl)
4701       return setStep(SemaRef
4702                          .ActOnIntegerConstant(UO->getBeginLoc(),
4703                                                (UO->isDecrementOp() ? -1 : 1))
4704                          .get(),
4705                      /*Subtract=*/false);
4706   } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
4707     switch (BO->getOpcode()) {
4708     case BO_AddAssign:
4709     case BO_SubAssign:
4710       if (getInitLCDecl(BO->getLHS()) == LCDecl)
4711         return setStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
4712       break;
4713     case BO_Assign:
4714       if (getInitLCDecl(BO->getLHS()) == LCDecl)
4715         return checkAndSetIncRHS(BO->getRHS());
4716       break;
4717     default:
4718       break;
4719     }
4720   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
4721     switch (CE->getOperator()) {
4722     case OO_PlusPlus:
4723     case OO_MinusMinus:
4724       if (getInitLCDecl(CE->getArg(0)) == LCDecl)
4725         return setStep(SemaRef
4726                            .ActOnIntegerConstant(
4727                                CE->getBeginLoc(),
4728                                ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
4729                            .get(),
4730                        /*Subtract=*/false);
4731       break;
4732     case OO_PlusEqual:
4733     case OO_MinusEqual:
4734       if (getInitLCDecl(CE->getArg(0)) == LCDecl)
4735         return setStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
4736       break;
4737     case OO_Equal:
4738       if (getInitLCDecl(CE->getArg(0)) == LCDecl)
4739         return checkAndSetIncRHS(CE->getArg(1));
4740       break;
4741     default:
4742       break;
4743     }
4744   }
4745   if (dependent() || SemaRef.CurContext->isDependentContext())
4746     return false;
4747   SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
4748       << S->getSourceRange() << LCDecl;
4749   return true;
4750 }
4751 
4752 static ExprResult
4753 tryBuildCapture(Sema &SemaRef, Expr *Capture,
4754                 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
4755   if (SemaRef.CurContext->isDependentContext())
4756     return ExprResult(Capture);
4757   if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
4758     return SemaRef.PerformImplicitConversion(
4759         Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
4760         /*AllowExplicit=*/true);
4761   auto I = Captures.find(Capture);
4762   if (I != Captures.end())
4763     return buildCapture(SemaRef, Capture, I->second);
4764   DeclRefExpr *Ref = nullptr;
4765   ExprResult Res = buildCapture(SemaRef, Capture, Ref);
4766   Captures[Capture] = Ref;
4767   return Res;
4768 }
4769 
4770 /// Build the expression to calculate the number of iterations.
4771 Expr *OpenMPIterationSpaceChecker::buildNumIterations(
4772     Scope *S, const bool LimitedType,
4773     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
4774   ExprResult Diff;
4775   QualType VarType = LCDecl->getType().getNonReferenceType();
4776   if (VarType->isIntegerType() || VarType->isPointerType() ||
4777       SemaRef.getLangOpts().CPlusPlus) {
4778     // Upper - Lower
4779     Expr *UBExpr = TestIsLessOp.getValue() ? UB : LB;
4780     Expr *LBExpr = TestIsLessOp.getValue() ? LB : UB;
4781     Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
4782     Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
4783     if (!Upper || !Lower)
4784       return nullptr;
4785 
4786     Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
4787 
4788     if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
4789       // BuildBinOp already emitted error, this one is to point user to upper
4790       // and lower bound, and to tell what is passed to 'operator-'.
4791       SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
4792           << Upper->getSourceRange() << Lower->getSourceRange();
4793       return nullptr;
4794     }
4795   }
4796 
4797   if (!Diff.isUsable())
4798     return nullptr;
4799 
4800   // Upper - Lower [- 1]
4801   if (TestIsStrictOp)
4802     Diff = SemaRef.BuildBinOp(
4803         S, DefaultLoc, BO_Sub, Diff.get(),
4804         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4805   if (!Diff.isUsable())
4806     return nullptr;
4807 
4808   // Upper - Lower [- 1] + Step
4809   ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
4810   if (!NewStep.isUsable())
4811     return nullptr;
4812   Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
4813   if (!Diff.isUsable())
4814     return nullptr;
4815 
4816   // Parentheses (for dumping/debugging purposes only).
4817   Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
4818   if (!Diff.isUsable())
4819     return nullptr;
4820 
4821   // (Upper - Lower [- 1] + Step) / Step
4822   Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
4823   if (!Diff.isUsable())
4824     return nullptr;
4825 
4826   // OpenMP runtime requires 32-bit or 64-bit loop variables.
4827   QualType Type = Diff.get()->getType();
4828   ASTContext &C = SemaRef.Context;
4829   bool UseVarType = VarType->hasIntegerRepresentation() &&
4830                     C.getTypeSize(Type) > C.getTypeSize(VarType);
4831   if (!Type->isIntegerType() || UseVarType) {
4832     unsigned NewSize =
4833         UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
4834     bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
4835                                : Type->hasSignedIntegerRepresentation();
4836     Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
4837     if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
4838       Diff = SemaRef.PerformImplicitConversion(
4839           Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
4840       if (!Diff.isUsable())
4841         return nullptr;
4842     }
4843   }
4844   if (LimitedType) {
4845     unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
4846     if (NewSize != C.getTypeSize(Type)) {
4847       if (NewSize < C.getTypeSize(Type)) {
4848         assert(NewSize == 64 && "incorrect loop var size");
4849         SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
4850             << InitSrcRange << ConditionSrcRange;
4851       }
4852       QualType NewType = C.getIntTypeForBitwidth(
4853           NewSize, Type->hasSignedIntegerRepresentation() ||
4854                        C.getTypeSize(Type) < NewSize);
4855       if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
4856         Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
4857                                                  Sema::AA_Converting, true);
4858         if (!Diff.isUsable())
4859           return nullptr;
4860       }
4861     }
4862   }
4863 
4864   return Diff.get();
4865 }
4866 
4867 Expr *OpenMPIterationSpaceChecker::buildPreCond(
4868     Scope *S, Expr *Cond,
4869     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
4870   // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
4871   bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
4872   SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
4873 
4874   ExprResult NewLB = tryBuildCapture(SemaRef, LB, Captures);
4875   ExprResult NewUB = tryBuildCapture(SemaRef, UB, Captures);
4876   if (!NewLB.isUsable() || !NewUB.isUsable())
4877     return nullptr;
4878 
4879   ExprResult CondExpr =
4880       SemaRef.BuildBinOp(S, DefaultLoc,
4881                          TestIsLessOp.getValue() ?
4882                            (TestIsStrictOp ? BO_LT : BO_LE) :
4883                            (TestIsStrictOp ? BO_GT : BO_GE),
4884                          NewLB.get(), NewUB.get());
4885   if (CondExpr.isUsable()) {
4886     if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
4887                                                 SemaRef.Context.BoolTy))
4888       CondExpr = SemaRef.PerformImplicitConversion(
4889           CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
4890           /*AllowExplicit=*/true);
4891   }
4892   SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
4893   // Otherwise use original loop condition and evaluate it in runtime.
4894   return CondExpr.isUsable() ? CondExpr.get() : Cond;
4895 }
4896 
4897 /// Build reference expression to the counter be used for codegen.
4898 DeclRefExpr *OpenMPIterationSpaceChecker::buildCounterVar(
4899     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
4900     DSAStackTy &DSA) const {
4901   auto *VD = dyn_cast<VarDecl>(LCDecl);
4902   if (!VD) {
4903     VD = SemaRef.isOpenMPCapturedDecl(LCDecl);
4904     DeclRefExpr *Ref = buildDeclRefExpr(
4905         SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
4906     const DSAStackTy::DSAVarData Data =
4907         DSA.getTopDSA(LCDecl, /*FromParent=*/false);
4908     // If the loop control decl is explicitly marked as private, do not mark it
4909     // as captured again.
4910     if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
4911       Captures.insert(std::make_pair(LCRef, Ref));
4912     return Ref;
4913   }
4914   return cast<DeclRefExpr>(LCRef);
4915 }
4916 
4917 Expr *OpenMPIterationSpaceChecker::buildPrivateCounterVar() const {
4918   if (LCDecl && !LCDecl->isInvalidDecl()) {
4919     QualType Type = LCDecl->getType().getNonReferenceType();
4920     VarDecl *PrivateVar = buildVarDecl(
4921         SemaRef, DefaultLoc, Type, LCDecl->getName(),
4922         LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr,
4923         isa<VarDecl>(LCDecl)
4924             ? buildDeclRefExpr(SemaRef, cast<VarDecl>(LCDecl), Type, DefaultLoc)
4925             : nullptr);
4926     if (PrivateVar->isInvalidDecl())
4927       return nullptr;
4928     return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
4929   }
4930   return nullptr;
4931 }
4932 
4933 /// Build initialization of the counter to be used for codegen.
4934 Expr *OpenMPIterationSpaceChecker::buildCounterInit() const { return LB; }
4935 
4936 /// Build step of the counter be used for codegen.
4937 Expr *OpenMPIterationSpaceChecker::buildCounterStep() const { return Step; }
4938 
4939 Expr *OpenMPIterationSpaceChecker::buildOrderedLoopData(
4940     Scope *S, Expr *Counter,
4941     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, SourceLocation Loc,
4942     Expr *Inc, OverloadedOperatorKind OOK) {
4943   Expr *Cnt = SemaRef.DefaultLvalueConversion(Counter).get();
4944   if (!Cnt)
4945     return nullptr;
4946   if (Inc) {
4947     assert((OOK == OO_Plus || OOK == OO_Minus) &&
4948            "Expected only + or - operations for depend clauses.");
4949     BinaryOperatorKind BOK = (OOK == OO_Plus) ? BO_Add : BO_Sub;
4950     Cnt = SemaRef.BuildBinOp(S, Loc, BOK, Cnt, Inc).get();
4951     if (!Cnt)
4952       return nullptr;
4953   }
4954   ExprResult Diff;
4955   QualType VarType = LCDecl->getType().getNonReferenceType();
4956   if (VarType->isIntegerType() || VarType->isPointerType() ||
4957       SemaRef.getLangOpts().CPlusPlus) {
4958     // Upper - Lower
4959     Expr *Upper = TestIsLessOp.getValue()
4960                       ? Cnt
4961                       : tryBuildCapture(SemaRef, UB, Captures).get();
4962     Expr *Lower = TestIsLessOp.getValue()
4963                       ? tryBuildCapture(SemaRef, LB, Captures).get()
4964                       : Cnt;
4965     if (!Upper || !Lower)
4966       return nullptr;
4967 
4968     Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
4969 
4970     if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
4971       // BuildBinOp already emitted error, this one is to point user to upper
4972       // and lower bound, and to tell what is passed to 'operator-'.
4973       SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
4974           << Upper->getSourceRange() << Lower->getSourceRange();
4975       return nullptr;
4976     }
4977   }
4978 
4979   if (!Diff.isUsable())
4980     return nullptr;
4981 
4982   // Parentheses (for dumping/debugging purposes only).
4983   Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
4984   if (!Diff.isUsable())
4985     return nullptr;
4986 
4987   ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
4988   if (!NewStep.isUsable())
4989     return nullptr;
4990   // (Upper - Lower) / Step
4991   Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
4992   if (!Diff.isUsable())
4993     return nullptr;
4994 
4995   return Diff.get();
4996 }
4997 
4998 /// Iteration space of a single for loop.
4999 struct LoopIterationSpace final {
5000   /// True if the condition operator is the strict compare operator (<, > or
5001   /// !=).
5002   bool IsStrictCompare = false;
5003   /// Condition of the loop.
5004   Expr *PreCond = nullptr;
5005   /// This expression calculates the number of iterations in the loop.
5006   /// It is always possible to calculate it before starting the loop.
5007   Expr *NumIterations = nullptr;
5008   /// The loop counter variable.
5009   Expr *CounterVar = nullptr;
5010   /// Private loop counter variable.
5011   Expr *PrivateCounterVar = nullptr;
5012   /// This is initializer for the initial value of #CounterVar.
5013   Expr *CounterInit = nullptr;
5014   /// This is step for the #CounterVar used to generate its update:
5015   /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
5016   Expr *CounterStep = nullptr;
5017   /// Should step be subtracted?
5018   bool Subtract = false;
5019   /// Source range of the loop init.
5020   SourceRange InitSrcRange;
5021   /// Source range of the loop condition.
5022   SourceRange CondSrcRange;
5023   /// Source range of the loop increment.
5024   SourceRange IncSrcRange;
5025 };
5026 
5027 } // namespace
5028 
5029 void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
5030   assert(getLangOpts().OpenMP && "OpenMP is not active.");
5031   assert(Init && "Expected loop in canonical form.");
5032   unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
5033   if (AssociatedLoops > 0 &&
5034       isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
5035     DSAStack->loopStart();
5036     OpenMPIterationSpaceChecker ISC(*this, ForLoc);
5037     if (!ISC.checkAndSetInit(Init, /*EmitDiags=*/false)) {
5038       if (ValueDecl *D = ISC.getLoopDecl()) {
5039         auto *VD = dyn_cast<VarDecl>(D);
5040         if (!VD) {
5041           if (VarDecl *Private = isOpenMPCapturedDecl(D)) {
5042             VD = Private;
5043           } else {
5044             DeclRefExpr *Ref = buildCapture(*this, D, ISC.getLoopDeclRefExpr(),
5045                                             /*WithInit=*/false);
5046             VD = cast<VarDecl>(Ref->getDecl());
5047           }
5048         }
5049         DSAStack->addLoopControlVariable(D, VD);
5050         const Decl *LD = DSAStack->getPossiblyLoopCunter();
5051         if (LD != D->getCanonicalDecl()) {
5052           DSAStack->resetPossibleLoopCounter();
5053           if (auto *Var = dyn_cast_or_null<VarDecl>(LD))
5054             MarkDeclarationsReferencedInExpr(
5055                 buildDeclRefExpr(*this, const_cast<VarDecl *>(Var),
5056                                  Var->getType().getNonLValueExprType(Context),
5057                                  ForLoc, /*RefersToCapture=*/true));
5058         }
5059       }
5060     }
5061     DSAStack->setAssociatedLoops(AssociatedLoops - 1);
5062   }
5063 }
5064 
5065 /// Called on a for stmt to check and extract its iteration space
5066 /// for further processing (such as collapsing).
5067 static bool checkOpenMPIterationSpace(
5068     OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
5069     unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
5070     unsigned TotalNestedLoopCount, Expr *CollapseLoopCountExpr,
5071     Expr *OrderedLoopCountExpr,
5072     Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
5073     LoopIterationSpace &ResultIterSpace,
5074     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
5075   // OpenMP [2.6, Canonical Loop Form]
5076   //   for (init-expr; test-expr; incr-expr) structured-block
5077   auto *For = dyn_cast_or_null<ForStmt>(S);
5078   if (!For) {
5079     SemaRef.Diag(S->getBeginLoc(), diag::err_omp_not_for)
5080         << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
5081         << getOpenMPDirectiveName(DKind) << TotalNestedLoopCount
5082         << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
5083     if (TotalNestedLoopCount > 1) {
5084       if (CollapseLoopCountExpr && OrderedLoopCountExpr)
5085         SemaRef.Diag(DSA.getConstructLoc(),
5086                      diag::note_omp_collapse_ordered_expr)
5087             << 2 << CollapseLoopCountExpr->getSourceRange()
5088             << OrderedLoopCountExpr->getSourceRange();
5089       else if (CollapseLoopCountExpr)
5090         SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
5091                      diag::note_omp_collapse_ordered_expr)
5092             << 0 << CollapseLoopCountExpr->getSourceRange();
5093       else
5094         SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
5095                      diag::note_omp_collapse_ordered_expr)
5096             << 1 << OrderedLoopCountExpr->getSourceRange();
5097     }
5098     return true;
5099   }
5100   assert(For->getBody());
5101 
5102   OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
5103 
5104   // Check init.
5105   Stmt *Init = For->getInit();
5106   if (ISC.checkAndSetInit(Init))
5107     return true;
5108 
5109   bool HasErrors = false;
5110 
5111   // Check loop variable's type.
5112   if (ValueDecl *LCDecl = ISC.getLoopDecl()) {
5113     Expr *LoopDeclRefExpr = ISC.getLoopDeclRefExpr();
5114 
5115     // OpenMP [2.6, Canonical Loop Form]
5116     // Var is one of the following:
5117     //   A variable of signed or unsigned integer type.
5118     //   For C++, a variable of a random access iterator type.
5119     //   For C, a variable of a pointer type.
5120     QualType VarType = LCDecl->getType().getNonReferenceType();
5121     if (!VarType->isDependentType() && !VarType->isIntegerType() &&
5122         !VarType->isPointerType() &&
5123         !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
5124       SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_variable_type)
5125           << SemaRef.getLangOpts().CPlusPlus;
5126       HasErrors = true;
5127     }
5128 
5129     // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
5130     // a Construct
5131     // The loop iteration variable(s) in the associated for-loop(s) of a for or
5132     // parallel for construct is (are) private.
5133     // The loop iteration variable in the associated for-loop of a simd
5134     // construct with just one associated for-loop is linear with a
5135     // constant-linear-step that is the increment of the associated for-loop.
5136     // Exclude loop var from the list of variables with implicitly defined data
5137     // sharing attributes.
5138     VarsWithImplicitDSA.erase(LCDecl);
5139 
5140     // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
5141     // in a Construct, C/C++].
5142     // The loop iteration variable in the associated for-loop of a simd
5143     // construct with just one associated for-loop may be listed in a linear
5144     // clause with a constant-linear-step that is the increment of the
5145     // associated for-loop.
5146     // The loop iteration variable(s) in the associated for-loop(s) of a for or
5147     // parallel for construct may be listed in a private or lastprivate clause.
5148     DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false);
5149     // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
5150     // declared in the loop and it is predetermined as a private.
5151     OpenMPClauseKind PredeterminedCKind =
5152         isOpenMPSimdDirective(DKind)
5153             ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
5154             : OMPC_private;
5155     if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
5156           DVar.CKind != PredeterminedCKind) ||
5157          ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
5158            isOpenMPDistributeDirective(DKind)) &&
5159           !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
5160           DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
5161         (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
5162       SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_var_dsa)
5163           << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
5164           << getOpenMPClauseName(PredeterminedCKind);
5165       if (DVar.RefExpr == nullptr)
5166         DVar.CKind = PredeterminedCKind;
5167       reportOriginalDsa(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true);
5168       HasErrors = true;
5169     } else if (LoopDeclRefExpr != nullptr) {
5170       // Make the loop iteration variable private (for worksharing constructs),
5171       // linear (for simd directives with the only one associated loop) or
5172       // lastprivate (for simd directives with several collapsed or ordered
5173       // loops).
5174       if (DVar.CKind == OMPC_unknown)
5175         DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind);
5176     }
5177 
5178     assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
5179 
5180     // Check test-expr.
5181     HasErrors |= ISC.checkAndSetCond(For->getCond());
5182 
5183     // Check incr-expr.
5184     HasErrors |= ISC.checkAndSetInc(For->getInc());
5185   }
5186 
5187   if (ISC.dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
5188     return HasErrors;
5189 
5190   // Build the loop's iteration space representation.
5191   ResultIterSpace.PreCond =
5192       ISC.buildPreCond(DSA.getCurScope(), For->getCond(), Captures);
5193   ResultIterSpace.NumIterations = ISC.buildNumIterations(
5194       DSA.getCurScope(),
5195       (isOpenMPWorksharingDirective(DKind) ||
5196        isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)),
5197       Captures);
5198   ResultIterSpace.CounterVar = ISC.buildCounterVar(Captures, DSA);
5199   ResultIterSpace.PrivateCounterVar = ISC.buildPrivateCounterVar();
5200   ResultIterSpace.CounterInit = ISC.buildCounterInit();
5201   ResultIterSpace.CounterStep = ISC.buildCounterStep();
5202   ResultIterSpace.InitSrcRange = ISC.getInitSrcRange();
5203   ResultIterSpace.CondSrcRange = ISC.getConditionSrcRange();
5204   ResultIterSpace.IncSrcRange = ISC.getIncrementSrcRange();
5205   ResultIterSpace.Subtract = ISC.shouldSubtractStep();
5206   ResultIterSpace.IsStrictCompare = ISC.isStrictTestOp();
5207 
5208   HasErrors |= (ResultIterSpace.PreCond == nullptr ||
5209                 ResultIterSpace.NumIterations == nullptr ||
5210                 ResultIterSpace.CounterVar == nullptr ||
5211                 ResultIterSpace.PrivateCounterVar == nullptr ||
5212                 ResultIterSpace.CounterInit == nullptr ||
5213                 ResultIterSpace.CounterStep == nullptr);
5214   if (!HasErrors && DSA.isOrderedRegion()) {
5215     if (DSA.getOrderedRegionParam().second->getNumForLoops()) {
5216       if (CurrentNestedLoopCount <
5217           DSA.getOrderedRegionParam().second->getLoopNumIterations().size()) {
5218         DSA.getOrderedRegionParam().second->setLoopNumIterations(
5219             CurrentNestedLoopCount, ResultIterSpace.NumIterations);
5220         DSA.getOrderedRegionParam().second->setLoopCounter(
5221             CurrentNestedLoopCount, ResultIterSpace.CounterVar);
5222       }
5223     }
5224     for (auto &Pair : DSA.getDoacrossDependClauses()) {
5225       if (CurrentNestedLoopCount >= Pair.first->getNumLoops()) {
5226         // Erroneous case - clause has some problems.
5227         continue;
5228       }
5229       if (Pair.first->getDependencyKind() == OMPC_DEPEND_sink &&
5230           Pair.second.size() <= CurrentNestedLoopCount) {
5231         // Erroneous case - clause has some problems.
5232         Pair.first->setLoopData(CurrentNestedLoopCount, nullptr);
5233         continue;
5234       }
5235       Expr *CntValue;
5236       if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
5237         CntValue = ISC.buildOrderedLoopData(
5238             DSA.getCurScope(), ResultIterSpace.CounterVar, Captures,
5239             Pair.first->getDependencyLoc());
5240       else
5241         CntValue = ISC.buildOrderedLoopData(
5242             DSA.getCurScope(), ResultIterSpace.CounterVar, Captures,
5243             Pair.first->getDependencyLoc(),
5244             Pair.second[CurrentNestedLoopCount].first,
5245             Pair.second[CurrentNestedLoopCount].second);
5246       Pair.first->setLoopData(CurrentNestedLoopCount, CntValue);
5247     }
5248   }
5249 
5250   return HasErrors;
5251 }
5252 
5253 /// Build 'VarRef = Start.
5254 static ExprResult
5255 buildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
5256                  ExprResult Start,
5257                  llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
5258   // Build 'VarRef = Start.
5259   ExprResult NewStart = tryBuildCapture(SemaRef, Start.get(), Captures);
5260   if (!NewStart.isUsable())
5261     return ExprError();
5262   if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
5263                                    VarRef.get()->getType())) {
5264     NewStart = SemaRef.PerformImplicitConversion(
5265         NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
5266         /*AllowExplicit=*/true);
5267     if (!NewStart.isUsable())
5268       return ExprError();
5269   }
5270 
5271   ExprResult Init =
5272       SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
5273   return Init;
5274 }
5275 
5276 /// Build 'VarRef = Start + Iter * Step'.
5277 static ExprResult buildCounterUpdate(
5278     Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
5279     ExprResult Start, ExprResult Iter, ExprResult Step, bool Subtract,
5280     llvm::MapVector<const Expr *, DeclRefExpr *> *Captures = nullptr) {
5281   // Add parentheses (for debugging purposes only).
5282   Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
5283   if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
5284       !Step.isUsable())
5285     return ExprError();
5286 
5287   ExprResult NewStep = Step;
5288   if (Captures)
5289     NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
5290   if (NewStep.isInvalid())
5291     return ExprError();
5292   ExprResult Update =
5293       SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
5294   if (!Update.isUsable())
5295     return ExprError();
5296 
5297   // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
5298   // 'VarRef = Start (+|-) Iter * Step'.
5299   ExprResult NewStart = Start;
5300   if (Captures)
5301     NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
5302   if (NewStart.isInvalid())
5303     return ExprError();
5304 
5305   // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
5306   ExprResult SavedUpdate = Update;
5307   ExprResult UpdateVal;
5308   if (VarRef.get()->getType()->isOverloadableType() ||
5309       NewStart.get()->getType()->isOverloadableType() ||
5310       Update.get()->getType()->isOverloadableType()) {
5311     bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
5312     SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
5313     Update =
5314         SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
5315     if (Update.isUsable()) {
5316       UpdateVal =
5317           SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
5318                              VarRef.get(), SavedUpdate.get());
5319       if (UpdateVal.isUsable()) {
5320         Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
5321                                             UpdateVal.get());
5322       }
5323     }
5324     SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
5325   }
5326 
5327   // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
5328   if (!Update.isUsable() || !UpdateVal.isUsable()) {
5329     Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
5330                                 NewStart.get(), SavedUpdate.get());
5331     if (!Update.isUsable())
5332       return ExprError();
5333 
5334     if (!SemaRef.Context.hasSameType(Update.get()->getType(),
5335                                      VarRef.get()->getType())) {
5336       Update = SemaRef.PerformImplicitConversion(
5337           Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
5338       if (!Update.isUsable())
5339         return ExprError();
5340     }
5341 
5342     Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
5343   }
5344   return Update;
5345 }
5346 
5347 /// Convert integer expression \a E to make it have at least \a Bits
5348 /// bits.
5349 static ExprResult widenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
5350   if (E == nullptr)
5351     return ExprError();
5352   ASTContext &C = SemaRef.Context;
5353   QualType OldType = E->getType();
5354   unsigned HasBits = C.getTypeSize(OldType);
5355   if (HasBits >= Bits)
5356     return ExprResult(E);
5357   // OK to convert to signed, because new type has more bits than old.
5358   QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
5359   return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
5360                                            true);
5361 }
5362 
5363 /// Check if the given expression \a E is a constant integer that fits
5364 /// into \a Bits bits.
5365 static bool fitsInto(unsigned Bits, bool Signed, const Expr *E, Sema &SemaRef) {
5366   if (E == nullptr)
5367     return false;
5368   llvm::APSInt Result;
5369   if (E->isIntegerConstantExpr(Result, SemaRef.Context))
5370     return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
5371   return false;
5372 }
5373 
5374 /// Build preinits statement for the given declarations.
5375 static Stmt *buildPreInits(ASTContext &Context,
5376                            MutableArrayRef<Decl *> PreInits) {
5377   if (!PreInits.empty()) {
5378     return new (Context) DeclStmt(
5379         DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
5380         SourceLocation(), SourceLocation());
5381   }
5382   return nullptr;
5383 }
5384 
5385 /// Build preinits statement for the given declarations.
5386 static Stmt *
5387 buildPreInits(ASTContext &Context,
5388               const llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
5389   if (!Captures.empty()) {
5390     SmallVector<Decl *, 16> PreInits;
5391     for (const auto &Pair : Captures)
5392       PreInits.push_back(Pair.second->getDecl());
5393     return buildPreInits(Context, PreInits);
5394   }
5395   return nullptr;
5396 }
5397 
5398 /// Build postupdate expression for the given list of postupdates expressions.
5399 static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
5400   Expr *PostUpdate = nullptr;
5401   if (!PostUpdates.empty()) {
5402     for (Expr *E : PostUpdates) {
5403       Expr *ConvE = S.BuildCStyleCastExpr(
5404                          E->getExprLoc(),
5405                          S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
5406                          E->getExprLoc(), E)
5407                         .get();
5408       PostUpdate = PostUpdate
5409                        ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
5410                                               PostUpdate, ConvE)
5411                              .get()
5412                        : ConvE;
5413     }
5414   }
5415   return PostUpdate;
5416 }
5417 
5418 /// Called on a for stmt to check itself and nested loops (if any).
5419 /// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
5420 /// number of collapsed loops otherwise.
5421 static unsigned
5422 checkOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
5423                 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
5424                 DSAStackTy &DSA,
5425                 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
5426                 OMPLoopDirective::HelperExprs &Built) {
5427   unsigned NestedLoopCount = 1;
5428   if (CollapseLoopCountExpr) {
5429     // Found 'collapse' clause - calculate collapse number.
5430     Expr::EvalResult Result;
5431     if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
5432       NestedLoopCount = Result.Val.getInt().getLimitedValue();
5433   }
5434   unsigned OrderedLoopCount = 1;
5435   if (OrderedLoopCountExpr) {
5436     // Found 'ordered' clause - calculate collapse number.
5437     Expr::EvalResult EVResult;
5438     if (OrderedLoopCountExpr->EvaluateAsInt(EVResult, SemaRef.getASTContext())) {
5439       llvm::APSInt Result = EVResult.Val.getInt();
5440       if (Result.getLimitedValue() < NestedLoopCount) {
5441         SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
5442                      diag::err_omp_wrong_ordered_loop_count)
5443             << OrderedLoopCountExpr->getSourceRange();
5444         SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
5445                      diag::note_collapse_loop_count)
5446             << CollapseLoopCountExpr->getSourceRange();
5447       }
5448       OrderedLoopCount = Result.getLimitedValue();
5449     }
5450   }
5451   // This is helper routine for loop directives (e.g., 'for', 'simd',
5452   // 'for simd', etc.).
5453   llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
5454   SmallVector<LoopIterationSpace, 4> IterSpaces(
5455       std::max(OrderedLoopCount, NestedLoopCount));
5456   Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
5457   for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
5458     if (checkOpenMPIterationSpace(
5459             DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
5460             std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
5461             OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces[Cnt],
5462             Captures))
5463       return 0;
5464     // Move on to the next nested for loop, or to the loop body.
5465     // OpenMP [2.8.1, simd construct, Restrictions]
5466     // All loops associated with the construct must be perfectly nested; that
5467     // is, there must be no intervening code nor any OpenMP directive between
5468     // any two loops.
5469     CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
5470   }
5471   for (unsigned Cnt = NestedLoopCount; Cnt < OrderedLoopCount; ++Cnt) {
5472     if (checkOpenMPIterationSpace(
5473             DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
5474             std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
5475             OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces[Cnt],
5476             Captures))
5477       return 0;
5478     if (Cnt > 0 && IterSpaces[Cnt].CounterVar) {
5479       // Handle initialization of captured loop iterator variables.
5480       auto *DRE = cast<DeclRefExpr>(IterSpaces[Cnt].CounterVar);
5481       if (isa<OMPCapturedExprDecl>(DRE->getDecl())) {
5482         Captures[DRE] = DRE;
5483       }
5484     }
5485     // Move on to the next nested for loop, or to the loop body.
5486     // OpenMP [2.8.1, simd construct, Restrictions]
5487     // All loops associated with the construct must be perfectly nested; that
5488     // is, there must be no intervening code nor any OpenMP directive between
5489     // any two loops.
5490     CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
5491   }
5492 
5493   Built.clear(/* size */ NestedLoopCount);
5494 
5495   if (SemaRef.CurContext->isDependentContext())
5496     return NestedLoopCount;
5497 
5498   // An example of what is generated for the following code:
5499   //
5500   //   #pragma omp simd collapse(2) ordered(2)
5501   //   for (i = 0; i < NI; ++i)
5502   //     for (k = 0; k < NK; ++k)
5503   //       for (j = J0; j < NJ; j+=2) {
5504   //         <loop body>
5505   //       }
5506   //
5507   // We generate the code below.
5508   // Note: the loop body may be outlined in CodeGen.
5509   // Note: some counters may be C++ classes, operator- is used to find number of
5510   // iterations and operator+= to calculate counter value.
5511   // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
5512   // or i64 is currently supported).
5513   //
5514   //   #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
5515   //   for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
5516   //     .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
5517   //     .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
5518   //     // similar updates for vars in clauses (e.g. 'linear')
5519   //     <loop body (using local i and j)>
5520   //   }
5521   //   i = NI; // assign final values of counters
5522   //   j = NJ;
5523   //
5524 
5525   // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
5526   // the iteration counts of the collapsed for loops.
5527   // Precondition tests if there is at least one iteration (all conditions are
5528   // true).
5529   auto PreCond = ExprResult(IterSpaces[0].PreCond);
5530   Expr *N0 = IterSpaces[0].NumIterations;
5531   ExprResult LastIteration32 =
5532       widenIterationCount(/*Bits=*/32,
5533                           SemaRef
5534                               .PerformImplicitConversion(
5535                                   N0->IgnoreImpCasts(), N0->getType(),
5536                                   Sema::AA_Converting, /*AllowExplicit=*/true)
5537                               .get(),
5538                           SemaRef);
5539   ExprResult LastIteration64 = widenIterationCount(
5540       /*Bits=*/64,
5541       SemaRef
5542           .PerformImplicitConversion(N0->IgnoreImpCasts(), N0->getType(),
5543                                      Sema::AA_Converting,
5544                                      /*AllowExplicit=*/true)
5545           .get(),
5546       SemaRef);
5547 
5548   if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
5549     return NestedLoopCount;
5550 
5551   ASTContext &C = SemaRef.Context;
5552   bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
5553 
5554   Scope *CurScope = DSA.getCurScope();
5555   for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
5556     if (PreCond.isUsable()) {
5557       PreCond =
5558           SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
5559                              PreCond.get(), IterSpaces[Cnt].PreCond);
5560     }
5561     Expr *N = IterSpaces[Cnt].NumIterations;
5562     SourceLocation Loc = N->getExprLoc();
5563     AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
5564     if (LastIteration32.isUsable())
5565       LastIteration32 = SemaRef.BuildBinOp(
5566           CurScope, Loc, BO_Mul, LastIteration32.get(),
5567           SemaRef
5568               .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
5569                                          Sema::AA_Converting,
5570                                          /*AllowExplicit=*/true)
5571               .get());
5572     if (LastIteration64.isUsable())
5573       LastIteration64 = SemaRef.BuildBinOp(
5574           CurScope, Loc, BO_Mul, LastIteration64.get(),
5575           SemaRef
5576               .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
5577                                          Sema::AA_Converting,
5578                                          /*AllowExplicit=*/true)
5579               .get());
5580   }
5581 
5582   // Choose either the 32-bit or 64-bit version.
5583   ExprResult LastIteration = LastIteration64;
5584   if (SemaRef.getLangOpts().OpenMPOptimisticCollapse ||
5585       (LastIteration32.isUsable() &&
5586        C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
5587        (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
5588         fitsInto(
5589             /*Bits=*/32,
5590             LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
5591             LastIteration64.get(), SemaRef))))
5592     LastIteration = LastIteration32;
5593   QualType VType = LastIteration.get()->getType();
5594   QualType RealVType = VType;
5595   QualType StrideVType = VType;
5596   if (isOpenMPTaskLoopDirective(DKind)) {
5597     VType =
5598         SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
5599     StrideVType =
5600         SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
5601   }
5602 
5603   if (!LastIteration.isUsable())
5604     return 0;
5605 
5606   // Save the number of iterations.
5607   ExprResult NumIterations = LastIteration;
5608   {
5609     LastIteration = SemaRef.BuildBinOp(
5610         CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
5611         LastIteration.get(),
5612         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
5613     if (!LastIteration.isUsable())
5614       return 0;
5615   }
5616 
5617   // Calculate the last iteration number beforehand instead of doing this on
5618   // each iteration. Do not do this if the number of iterations may be kfold-ed.
5619   llvm::APSInt Result;
5620   bool IsConstant =
5621       LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
5622   ExprResult CalcLastIteration;
5623   if (!IsConstant) {
5624     ExprResult SaveRef =
5625         tryBuildCapture(SemaRef, LastIteration.get(), Captures);
5626     LastIteration = SaveRef;
5627 
5628     // Prepare SaveRef + 1.
5629     NumIterations = SemaRef.BuildBinOp(
5630         CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
5631         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
5632     if (!NumIterations.isUsable())
5633       return 0;
5634   }
5635 
5636   SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
5637 
5638   // Build variables passed into runtime, necessary for worksharing directives.
5639   ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
5640   if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
5641       isOpenMPDistributeDirective(DKind)) {
5642     // Lower bound variable, initialized with zero.
5643     VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
5644     LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
5645     SemaRef.AddInitializerToDecl(LBDecl,
5646                                  SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
5647                                  /*DirectInit*/ false);
5648 
5649     // Upper bound variable, initialized with last iteration number.
5650     VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
5651     UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
5652     SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
5653                                  /*DirectInit*/ false);
5654 
5655     // A 32-bit variable-flag where runtime returns 1 for the last iteration.
5656     // This will be used to implement clause 'lastprivate'.
5657     QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
5658     VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
5659     IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
5660     SemaRef.AddInitializerToDecl(ILDecl,
5661                                  SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
5662                                  /*DirectInit*/ false);
5663 
5664     // Stride variable returned by runtime (we initialize it to 1 by default).
5665     VarDecl *STDecl =
5666         buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
5667     ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
5668     SemaRef.AddInitializerToDecl(STDecl,
5669                                  SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
5670                                  /*DirectInit*/ false);
5671 
5672     // Build expression: UB = min(UB, LastIteration)
5673     // It is necessary for CodeGen of directives with static scheduling.
5674     ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
5675                                                 UB.get(), LastIteration.get());
5676     ExprResult CondOp = SemaRef.ActOnConditionalOp(
5677         LastIteration.get()->getExprLoc(), InitLoc, IsUBGreater.get(),
5678         LastIteration.get(), UB.get());
5679     EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
5680                              CondOp.get());
5681     EUB = SemaRef.ActOnFinishFullExpr(EUB.get(), /*DiscardedValue*/ false);
5682 
5683     // If we have a combined directive that combines 'distribute', 'for' or
5684     // 'simd' we need to be able to access the bounds of the schedule of the
5685     // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
5686     // by scheduling 'distribute' have to be passed to the schedule of 'for'.
5687     if (isOpenMPLoopBoundSharingDirective(DKind)) {
5688       // Lower bound variable, initialized with zero.
5689       VarDecl *CombLBDecl =
5690           buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
5691       CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
5692       SemaRef.AddInitializerToDecl(
5693           CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
5694           /*DirectInit*/ false);
5695 
5696       // Upper bound variable, initialized with last iteration number.
5697       VarDecl *CombUBDecl =
5698           buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
5699       CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
5700       SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
5701                                    /*DirectInit*/ false);
5702 
5703       ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
5704           CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
5705       ExprResult CombCondOp =
5706           SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
5707                                      LastIteration.get(), CombUB.get());
5708       CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
5709                                    CombCondOp.get());
5710       CombEUB =
5711           SemaRef.ActOnFinishFullExpr(CombEUB.get(), /*DiscardedValue*/ false);
5712 
5713       const CapturedDecl *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
5714       // We expect to have at least 2 more parameters than the 'parallel'
5715       // directive does - the lower and upper bounds of the previous schedule.
5716       assert(CD->getNumParams() >= 4 &&
5717              "Unexpected number of parameters in loop combined directive");
5718 
5719       // Set the proper type for the bounds given what we learned from the
5720       // enclosed loops.
5721       ImplicitParamDecl *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
5722       ImplicitParamDecl *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
5723 
5724       // Previous lower and upper bounds are obtained from the region
5725       // parameters.
5726       PrevLB =
5727           buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
5728       PrevUB =
5729           buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
5730     }
5731   }
5732 
5733   // Build the iteration variable and its initialization before loop.
5734   ExprResult IV;
5735   ExprResult Init, CombInit;
5736   {
5737     VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
5738     IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
5739     Expr *RHS =
5740         (isOpenMPWorksharingDirective(DKind) ||
5741          isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
5742             ? LB.get()
5743             : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
5744     Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
5745     Init = SemaRef.ActOnFinishFullExpr(Init.get(), /*DiscardedValue*/ false);
5746 
5747     if (isOpenMPLoopBoundSharingDirective(DKind)) {
5748       Expr *CombRHS =
5749           (isOpenMPWorksharingDirective(DKind) ||
5750            isOpenMPTaskLoopDirective(DKind) ||
5751            isOpenMPDistributeDirective(DKind))
5752               ? CombLB.get()
5753               : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
5754       CombInit =
5755           SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
5756       CombInit =
5757           SemaRef.ActOnFinishFullExpr(CombInit.get(), /*DiscardedValue*/ false);
5758     }
5759   }
5760 
5761   bool UseStrictCompare =
5762       RealVType->hasUnsignedIntegerRepresentation() &&
5763       llvm::all_of(IterSpaces, [](const LoopIterationSpace &LIS) {
5764         return LIS.IsStrictCompare;
5765       });
5766   // Loop condition (IV < NumIterations) or (IV <= UB or IV < UB + 1 (for
5767   // unsigned IV)) for worksharing loops.
5768   SourceLocation CondLoc = AStmt->getBeginLoc();
5769   Expr *BoundUB = UB.get();
5770   if (UseStrictCompare) {
5771     BoundUB =
5772         SemaRef
5773             .BuildBinOp(CurScope, CondLoc, BO_Add, BoundUB,
5774                         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
5775             .get();
5776     BoundUB =
5777         SemaRef.ActOnFinishFullExpr(BoundUB, /*DiscardedValue*/ false).get();
5778   }
5779   ExprResult Cond =
5780       (isOpenMPWorksharingDirective(DKind) ||
5781        isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
5782           ? SemaRef.BuildBinOp(CurScope, CondLoc,
5783                                UseStrictCompare ? BO_LT : BO_LE, IV.get(),
5784                                BoundUB)
5785           : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
5786                                NumIterations.get());
5787   ExprResult CombDistCond;
5788   if (isOpenMPLoopBoundSharingDirective(DKind)) {
5789     CombDistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
5790                                       NumIterations.get());
5791   }
5792 
5793   ExprResult CombCond;
5794   if (isOpenMPLoopBoundSharingDirective(DKind)) {
5795     Expr *BoundCombUB = CombUB.get();
5796     if (UseStrictCompare) {
5797       BoundCombUB =
5798           SemaRef
5799               .BuildBinOp(
5800                   CurScope, CondLoc, BO_Add, BoundCombUB,
5801                   SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
5802               .get();
5803       BoundCombUB =
5804           SemaRef.ActOnFinishFullExpr(BoundCombUB, /*DiscardedValue*/ false)
5805               .get();
5806     }
5807     CombCond =
5808         SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
5809                            IV.get(), BoundCombUB);
5810   }
5811   // Loop increment (IV = IV + 1)
5812   SourceLocation IncLoc = AStmt->getBeginLoc();
5813   ExprResult Inc =
5814       SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
5815                          SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
5816   if (!Inc.isUsable())
5817     return 0;
5818   Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
5819   Inc = SemaRef.ActOnFinishFullExpr(Inc.get(), /*DiscardedValue*/ false);
5820   if (!Inc.isUsable())
5821     return 0;
5822 
5823   // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
5824   // Used for directives with static scheduling.
5825   // In combined construct, add combined version that use CombLB and CombUB
5826   // base variables for the update
5827   ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
5828   if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
5829       isOpenMPDistributeDirective(DKind)) {
5830     // LB + ST
5831     NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
5832     if (!NextLB.isUsable())
5833       return 0;
5834     // LB = LB + ST
5835     NextLB =
5836         SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
5837     NextLB =
5838         SemaRef.ActOnFinishFullExpr(NextLB.get(), /*DiscardedValue*/ false);
5839     if (!NextLB.isUsable())
5840       return 0;
5841     // UB + ST
5842     NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
5843     if (!NextUB.isUsable())
5844       return 0;
5845     // UB = UB + ST
5846     NextUB =
5847         SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
5848     NextUB =
5849         SemaRef.ActOnFinishFullExpr(NextUB.get(), /*DiscardedValue*/ false);
5850     if (!NextUB.isUsable())
5851       return 0;
5852     if (isOpenMPLoopBoundSharingDirective(DKind)) {
5853       CombNextLB =
5854           SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
5855       if (!NextLB.isUsable())
5856         return 0;
5857       // LB = LB + ST
5858       CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
5859                                       CombNextLB.get());
5860       CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get(),
5861                                                /*DiscardedValue*/ false);
5862       if (!CombNextLB.isUsable())
5863         return 0;
5864       // UB + ST
5865       CombNextUB =
5866           SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
5867       if (!CombNextUB.isUsable())
5868         return 0;
5869       // UB = UB + ST
5870       CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
5871                                       CombNextUB.get());
5872       CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get(),
5873                                                /*DiscardedValue*/ false);
5874       if (!CombNextUB.isUsable())
5875         return 0;
5876     }
5877   }
5878 
5879   // Create increment expression for distribute loop when combined in a same
5880   // directive with for as IV = IV + ST; ensure upper bound expression based
5881   // on PrevUB instead of NumIterations - used to implement 'for' when found
5882   // in combination with 'distribute', like in 'distribute parallel for'
5883   SourceLocation DistIncLoc = AStmt->getBeginLoc();
5884   ExprResult DistCond, DistInc, PrevEUB, ParForInDistCond;
5885   if (isOpenMPLoopBoundSharingDirective(DKind)) {
5886     DistCond = SemaRef.BuildBinOp(
5887         CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE, IV.get(), BoundUB);
5888     assert(DistCond.isUsable() && "distribute cond expr was not built");
5889 
5890     DistInc =
5891         SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
5892     assert(DistInc.isUsable() && "distribute inc expr was not built");
5893     DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
5894                                  DistInc.get());
5895     DistInc =
5896         SemaRef.ActOnFinishFullExpr(DistInc.get(), /*DiscardedValue*/ false);
5897     assert(DistInc.isUsable() && "distribute inc expr was not built");
5898 
5899     // Build expression: UB = min(UB, prevUB) for #for in composite or combined
5900     // construct
5901     SourceLocation DistEUBLoc = AStmt->getBeginLoc();
5902     ExprResult IsUBGreater =
5903         SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get());
5904     ExprResult CondOp = SemaRef.ActOnConditionalOp(
5905         DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get());
5906     PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
5907                                  CondOp.get());
5908     PrevEUB =
5909         SemaRef.ActOnFinishFullExpr(PrevEUB.get(), /*DiscardedValue*/ false);
5910 
5911     // Build IV <= PrevUB or IV < PrevUB + 1 for unsigned IV to be used in
5912     // parallel for is in combination with a distribute directive with
5913     // schedule(static, 1)
5914     Expr *BoundPrevUB = PrevUB.get();
5915     if (UseStrictCompare) {
5916       BoundPrevUB =
5917           SemaRef
5918               .BuildBinOp(
5919                   CurScope, CondLoc, BO_Add, BoundPrevUB,
5920                   SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
5921               .get();
5922       BoundPrevUB =
5923           SemaRef.ActOnFinishFullExpr(BoundPrevUB, /*DiscardedValue*/ false)
5924               .get();
5925     }
5926     ParForInDistCond =
5927         SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
5928                            IV.get(), BoundPrevUB);
5929   }
5930 
5931   // Build updates and final values of the loop counters.
5932   bool HasErrors = false;
5933   Built.Counters.resize(NestedLoopCount);
5934   Built.Inits.resize(NestedLoopCount);
5935   Built.Updates.resize(NestedLoopCount);
5936   Built.Finals.resize(NestedLoopCount);
5937   {
5938     // We implement the following algorithm for obtaining the
5939     // original loop iteration variable values based on the
5940     // value of the collapsed loop iteration variable IV.
5941     //
5942     // Let n+1 be the number of collapsed loops in the nest.
5943     // Iteration variables (I0, I1, .... In)
5944     // Iteration counts (N0, N1, ... Nn)
5945     //
5946     // Acc = IV;
5947     //
5948     // To compute Ik for loop k, 0 <= k <= n, generate:
5949     //    Prod = N(k+1) * N(k+2) * ... * Nn;
5950     //    Ik = Acc / Prod;
5951     //    Acc -= Ik * Prod;
5952     //
5953     ExprResult Acc = IV;
5954     for (unsigned int Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
5955       LoopIterationSpace &IS = IterSpaces[Cnt];
5956       SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
5957       ExprResult Iter;
5958 
5959       // Compute prod
5960       ExprResult Prod =
5961           SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
5962       for (unsigned int K = Cnt+1; K < NestedLoopCount; ++K)
5963         Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Prod.get(),
5964                                   IterSpaces[K].NumIterations);
5965 
5966       // Iter = Acc / Prod
5967       // If there is at least one more inner loop to avoid
5968       // multiplication by 1.
5969       if (Cnt + 1 < NestedLoopCount)
5970         Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div,
5971                                   Acc.get(), Prod.get());
5972       else
5973         Iter = Acc;
5974       if (!Iter.isUsable()) {
5975         HasErrors = true;
5976         break;
5977       }
5978 
5979       // Update Acc:
5980       // Acc -= Iter * Prod
5981       // Check if there is at least one more inner loop to avoid
5982       // multiplication by 1.
5983       if (Cnt + 1 < NestedLoopCount)
5984         Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul,
5985                                   Iter.get(), Prod.get());
5986       else
5987         Prod = Iter;
5988       Acc = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Sub,
5989                                Acc.get(), Prod.get());
5990 
5991       // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
5992       auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
5993       DeclRefExpr *CounterVar = buildDeclRefExpr(
5994           SemaRef, VD, IS.CounterVar->getType(), IS.CounterVar->getExprLoc(),
5995           /*RefersToCapture=*/true);
5996       ExprResult Init = buildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
5997                                          IS.CounterInit, Captures);
5998       if (!Init.isUsable()) {
5999         HasErrors = true;
6000         break;
6001       }
6002       ExprResult Update = buildCounterUpdate(
6003           SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
6004           IS.CounterStep, IS.Subtract, &Captures);
6005       if (!Update.isUsable()) {
6006         HasErrors = true;
6007         break;
6008       }
6009 
6010       // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
6011       ExprResult Final = buildCounterUpdate(
6012           SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
6013           IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures);
6014       if (!Final.isUsable()) {
6015         HasErrors = true;
6016         break;
6017       }
6018 
6019       if (!Update.isUsable() || !Final.isUsable()) {
6020         HasErrors = true;
6021         break;
6022       }
6023       // Save results
6024       Built.Counters[Cnt] = IS.CounterVar;
6025       Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
6026       Built.Inits[Cnt] = Init.get();
6027       Built.Updates[Cnt] = Update.get();
6028       Built.Finals[Cnt] = Final.get();
6029     }
6030   }
6031 
6032   if (HasErrors)
6033     return 0;
6034 
6035   // Save results
6036   Built.IterationVarRef = IV.get();
6037   Built.LastIteration = LastIteration.get();
6038   Built.NumIterations = NumIterations.get();
6039   Built.CalcLastIteration = SemaRef
6040                                 .ActOnFinishFullExpr(CalcLastIteration.get(),
6041                                                      /*DiscardedValue*/ false)
6042                                 .get();
6043   Built.PreCond = PreCond.get();
6044   Built.PreInits = buildPreInits(C, Captures);
6045   Built.Cond = Cond.get();
6046   Built.Init = Init.get();
6047   Built.Inc = Inc.get();
6048   Built.LB = LB.get();
6049   Built.UB = UB.get();
6050   Built.IL = IL.get();
6051   Built.ST = ST.get();
6052   Built.EUB = EUB.get();
6053   Built.NLB = NextLB.get();
6054   Built.NUB = NextUB.get();
6055   Built.PrevLB = PrevLB.get();
6056   Built.PrevUB = PrevUB.get();
6057   Built.DistInc = DistInc.get();
6058   Built.PrevEUB = PrevEUB.get();
6059   Built.DistCombinedFields.LB = CombLB.get();
6060   Built.DistCombinedFields.UB = CombUB.get();
6061   Built.DistCombinedFields.EUB = CombEUB.get();
6062   Built.DistCombinedFields.Init = CombInit.get();
6063   Built.DistCombinedFields.Cond = CombCond.get();
6064   Built.DistCombinedFields.NLB = CombNextLB.get();
6065   Built.DistCombinedFields.NUB = CombNextUB.get();
6066   Built.DistCombinedFields.DistCond = CombDistCond.get();
6067   Built.DistCombinedFields.ParForInDistCond = ParForInDistCond.get();
6068 
6069   return NestedLoopCount;
6070 }
6071 
6072 static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
6073   auto CollapseClauses =
6074       OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
6075   if (CollapseClauses.begin() != CollapseClauses.end())
6076     return (*CollapseClauses.begin())->getNumForLoops();
6077   return nullptr;
6078 }
6079 
6080 static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
6081   auto OrderedClauses =
6082       OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
6083   if (OrderedClauses.begin() != OrderedClauses.end())
6084     return (*OrderedClauses.begin())->getNumForLoops();
6085   return nullptr;
6086 }
6087 
6088 static bool checkSimdlenSafelenSpecified(Sema &S,
6089                                          const ArrayRef<OMPClause *> Clauses) {
6090   const OMPSafelenClause *Safelen = nullptr;
6091   const OMPSimdlenClause *Simdlen = nullptr;
6092 
6093   for (const OMPClause *Clause : Clauses) {
6094     if (Clause->getClauseKind() == OMPC_safelen)
6095       Safelen = cast<OMPSafelenClause>(Clause);
6096     else if (Clause->getClauseKind() == OMPC_simdlen)
6097       Simdlen = cast<OMPSimdlenClause>(Clause);
6098     if (Safelen && Simdlen)
6099       break;
6100   }
6101 
6102   if (Simdlen && Safelen) {
6103     const Expr *SimdlenLength = Simdlen->getSimdlen();
6104     const Expr *SafelenLength = Safelen->getSafelen();
6105     if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
6106         SimdlenLength->isInstantiationDependent() ||
6107         SimdlenLength->containsUnexpandedParameterPack())
6108       return false;
6109     if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
6110         SafelenLength->isInstantiationDependent() ||
6111         SafelenLength->containsUnexpandedParameterPack())
6112       return false;
6113     Expr::EvalResult SimdlenResult, SafelenResult;
6114     SimdlenLength->EvaluateAsInt(SimdlenResult, S.Context);
6115     SafelenLength->EvaluateAsInt(SafelenResult, S.Context);
6116     llvm::APSInt SimdlenRes = SimdlenResult.Val.getInt();
6117     llvm::APSInt SafelenRes = SafelenResult.Val.getInt();
6118     // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
6119     // If both simdlen and safelen clauses are specified, the value of the
6120     // simdlen parameter must be less than or equal to the value of the safelen
6121     // parameter.
6122     if (SimdlenRes > SafelenRes) {
6123       S.Diag(SimdlenLength->getExprLoc(),
6124              diag::err_omp_wrong_simdlen_safelen_values)
6125           << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
6126       return true;
6127     }
6128   }
6129   return false;
6130 }
6131 
6132 StmtResult
6133 Sema::ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
6134                                SourceLocation StartLoc, SourceLocation EndLoc,
6135                                VarsWithInheritedDSAType &VarsWithImplicitDSA) {
6136   if (!AStmt)
6137     return StmtError();
6138 
6139   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6140   OMPLoopDirective::HelperExprs B;
6141   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6142   // define the nested loops number.
6143   unsigned NestedLoopCount = checkOpenMPLoop(
6144       OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
6145       AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
6146   if (NestedLoopCount == 0)
6147     return StmtError();
6148 
6149   assert((CurContext->isDependentContext() || B.builtAll()) &&
6150          "omp simd loop exprs were not built");
6151 
6152   if (!CurContext->isDependentContext()) {
6153     // Finalize the clauses that need pre-built expressions for CodeGen.
6154     for (OMPClause *C : Clauses) {
6155       if (auto *LC = dyn_cast<OMPLinearClause>(C))
6156         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6157                                      B.NumIterations, *this, CurScope,
6158                                      DSAStack))
6159           return StmtError();
6160     }
6161   }
6162 
6163   if (checkSimdlenSafelenSpecified(*this, Clauses))
6164     return StmtError();
6165 
6166   setFunctionHasBranchProtectedScope();
6167   return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
6168                                   Clauses, AStmt, B);
6169 }
6170 
6171 StmtResult
6172 Sema::ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
6173                               SourceLocation StartLoc, SourceLocation EndLoc,
6174                               VarsWithInheritedDSAType &VarsWithImplicitDSA) {
6175   if (!AStmt)
6176     return StmtError();
6177 
6178   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6179   OMPLoopDirective::HelperExprs B;
6180   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6181   // define the nested loops number.
6182   unsigned NestedLoopCount = checkOpenMPLoop(
6183       OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
6184       AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
6185   if (NestedLoopCount == 0)
6186     return StmtError();
6187 
6188   assert((CurContext->isDependentContext() || B.builtAll()) &&
6189          "omp for loop exprs were not built");
6190 
6191   if (!CurContext->isDependentContext()) {
6192     // Finalize the clauses that need pre-built expressions for CodeGen.
6193     for (OMPClause *C : Clauses) {
6194       if (auto *LC = dyn_cast<OMPLinearClause>(C))
6195         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6196                                      B.NumIterations, *this, CurScope,
6197                                      DSAStack))
6198           return StmtError();
6199     }
6200   }
6201 
6202   setFunctionHasBranchProtectedScope();
6203   return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
6204                                  Clauses, AStmt, B, DSAStack->isCancelRegion());
6205 }
6206 
6207 StmtResult Sema::ActOnOpenMPForSimdDirective(
6208     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6209     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
6210   if (!AStmt)
6211     return StmtError();
6212 
6213   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6214   OMPLoopDirective::HelperExprs B;
6215   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6216   // define the nested loops number.
6217   unsigned NestedLoopCount =
6218       checkOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
6219                       getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6220                       VarsWithImplicitDSA, B);
6221   if (NestedLoopCount == 0)
6222     return StmtError();
6223 
6224   assert((CurContext->isDependentContext() || B.builtAll()) &&
6225          "omp for simd loop exprs were not built");
6226 
6227   if (!CurContext->isDependentContext()) {
6228     // Finalize the clauses that need pre-built expressions for CodeGen.
6229     for (OMPClause *C : Clauses) {
6230       if (auto *LC = dyn_cast<OMPLinearClause>(C))
6231         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6232                                      B.NumIterations, *this, CurScope,
6233                                      DSAStack))
6234           return StmtError();
6235     }
6236   }
6237 
6238   if (checkSimdlenSafelenSpecified(*this, Clauses))
6239     return StmtError();
6240 
6241   setFunctionHasBranchProtectedScope();
6242   return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
6243                                      Clauses, AStmt, B);
6244 }
6245 
6246 StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
6247                                               Stmt *AStmt,
6248                                               SourceLocation StartLoc,
6249                                               SourceLocation EndLoc) {
6250   if (!AStmt)
6251     return StmtError();
6252 
6253   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6254   auto BaseStmt = AStmt;
6255   while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
6256     BaseStmt = CS->getCapturedStmt();
6257   if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
6258     auto S = C->children();
6259     if (S.begin() == S.end())
6260       return StmtError();
6261     // All associated statements must be '#pragma omp section' except for
6262     // the first one.
6263     for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
6264       if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
6265         if (SectionStmt)
6266           Diag(SectionStmt->getBeginLoc(),
6267                diag::err_omp_sections_substmt_not_section);
6268         return StmtError();
6269       }
6270       cast<OMPSectionDirective>(SectionStmt)
6271           ->setHasCancel(DSAStack->isCancelRegion());
6272     }
6273   } else {
6274     Diag(AStmt->getBeginLoc(), diag::err_omp_sections_not_compound_stmt);
6275     return StmtError();
6276   }
6277 
6278   setFunctionHasBranchProtectedScope();
6279 
6280   return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
6281                                       DSAStack->isCancelRegion());
6282 }
6283 
6284 StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
6285                                              SourceLocation StartLoc,
6286                                              SourceLocation EndLoc) {
6287   if (!AStmt)
6288     return StmtError();
6289 
6290   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6291 
6292   setFunctionHasBranchProtectedScope();
6293   DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
6294 
6295   return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
6296                                      DSAStack->isCancelRegion());
6297 }
6298 
6299 StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
6300                                             Stmt *AStmt,
6301                                             SourceLocation StartLoc,
6302                                             SourceLocation EndLoc) {
6303   if (!AStmt)
6304     return StmtError();
6305 
6306   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6307 
6308   setFunctionHasBranchProtectedScope();
6309 
6310   // OpenMP [2.7.3, single Construct, Restrictions]
6311   // The copyprivate clause must not be used with the nowait clause.
6312   const OMPClause *Nowait = nullptr;
6313   const OMPClause *Copyprivate = nullptr;
6314   for (const OMPClause *Clause : Clauses) {
6315     if (Clause->getClauseKind() == OMPC_nowait)
6316       Nowait = Clause;
6317     else if (Clause->getClauseKind() == OMPC_copyprivate)
6318       Copyprivate = Clause;
6319     if (Copyprivate && Nowait) {
6320       Diag(Copyprivate->getBeginLoc(),
6321            diag::err_omp_single_copyprivate_with_nowait);
6322       Diag(Nowait->getBeginLoc(), diag::note_omp_nowait_clause_here);
6323       return StmtError();
6324     }
6325   }
6326 
6327   return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
6328 }
6329 
6330 StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
6331                                             SourceLocation StartLoc,
6332                                             SourceLocation EndLoc) {
6333   if (!AStmt)
6334     return StmtError();
6335 
6336   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6337 
6338   setFunctionHasBranchProtectedScope();
6339 
6340   return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
6341 }
6342 
6343 StmtResult Sema::ActOnOpenMPCriticalDirective(
6344     const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
6345     Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
6346   if (!AStmt)
6347     return StmtError();
6348 
6349   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6350 
6351   bool ErrorFound = false;
6352   llvm::APSInt Hint;
6353   SourceLocation HintLoc;
6354   bool DependentHint = false;
6355   for (const OMPClause *C : Clauses) {
6356     if (C->getClauseKind() == OMPC_hint) {
6357       if (!DirName.getName()) {
6358         Diag(C->getBeginLoc(), diag::err_omp_hint_clause_no_name);
6359         ErrorFound = true;
6360       }
6361       Expr *E = cast<OMPHintClause>(C)->getHint();
6362       if (E->isTypeDependent() || E->isValueDependent() ||
6363           E->isInstantiationDependent()) {
6364         DependentHint = true;
6365       } else {
6366         Hint = E->EvaluateKnownConstInt(Context);
6367         HintLoc = C->getBeginLoc();
6368       }
6369     }
6370   }
6371   if (ErrorFound)
6372     return StmtError();
6373   const auto Pair = DSAStack->getCriticalWithHint(DirName);
6374   if (Pair.first && DirName.getName() && !DependentHint) {
6375     if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
6376       Diag(StartLoc, diag::err_omp_critical_with_hint);
6377       if (HintLoc.isValid())
6378         Diag(HintLoc, diag::note_omp_critical_hint_here)
6379             << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
6380       else
6381         Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
6382       if (const auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
6383         Diag(C->getBeginLoc(), diag::note_omp_critical_hint_here)
6384             << 1
6385             << C->getHint()->EvaluateKnownConstInt(Context).toString(
6386                    /*Radix=*/10, /*Signed=*/false);
6387       } else {
6388         Diag(Pair.first->getBeginLoc(), diag::note_omp_critical_no_hint) << 1;
6389       }
6390     }
6391   }
6392 
6393   setFunctionHasBranchProtectedScope();
6394 
6395   auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
6396                                            Clauses, AStmt);
6397   if (!Pair.first && DirName.getName() && !DependentHint)
6398     DSAStack->addCriticalWithHint(Dir, Hint);
6399   return Dir;
6400 }
6401 
6402 StmtResult Sema::ActOnOpenMPParallelForDirective(
6403     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6404     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
6405   if (!AStmt)
6406     return StmtError();
6407 
6408   auto *CS = cast<CapturedStmt>(AStmt);
6409   // 1.2.2 OpenMP Language Terminology
6410   // Structured block - An executable statement with a single entry at the
6411   // top and a single exit at the bottom.
6412   // The point of exit cannot be a branch out of the structured block.
6413   // longjmp() and throw() must not violate the entry/exit criteria.
6414   CS->getCapturedDecl()->setNothrow();
6415 
6416   OMPLoopDirective::HelperExprs B;
6417   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6418   // define the nested loops number.
6419   unsigned NestedLoopCount =
6420       checkOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
6421                       getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6422                       VarsWithImplicitDSA, B);
6423   if (NestedLoopCount == 0)
6424     return StmtError();
6425 
6426   assert((CurContext->isDependentContext() || B.builtAll()) &&
6427          "omp parallel for loop exprs were not built");
6428 
6429   if (!CurContext->isDependentContext()) {
6430     // Finalize the clauses that need pre-built expressions for CodeGen.
6431     for (OMPClause *C : Clauses) {
6432       if (auto *LC = dyn_cast<OMPLinearClause>(C))
6433         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6434                                      B.NumIterations, *this, CurScope,
6435                                      DSAStack))
6436           return StmtError();
6437     }
6438   }
6439 
6440   setFunctionHasBranchProtectedScope();
6441   return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
6442                                          NestedLoopCount, Clauses, AStmt, B,
6443                                          DSAStack->isCancelRegion());
6444 }
6445 
6446 StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
6447     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6448     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
6449   if (!AStmt)
6450     return StmtError();
6451 
6452   auto *CS = cast<CapturedStmt>(AStmt);
6453   // 1.2.2 OpenMP Language Terminology
6454   // Structured block - An executable statement with a single entry at the
6455   // top and a single exit at the bottom.
6456   // The point of exit cannot be a branch out of the structured block.
6457   // longjmp() and throw() must not violate the entry/exit criteria.
6458   CS->getCapturedDecl()->setNothrow();
6459 
6460   OMPLoopDirective::HelperExprs B;
6461   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6462   // define the nested loops number.
6463   unsigned NestedLoopCount =
6464       checkOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
6465                       getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6466                       VarsWithImplicitDSA, B);
6467   if (NestedLoopCount == 0)
6468     return StmtError();
6469 
6470   if (!CurContext->isDependentContext()) {
6471     // Finalize the clauses that need pre-built expressions for CodeGen.
6472     for (OMPClause *C : Clauses) {
6473       if (auto *LC = dyn_cast<OMPLinearClause>(C))
6474         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6475                                      B.NumIterations, *this, CurScope,
6476                                      DSAStack))
6477           return StmtError();
6478     }
6479   }
6480 
6481   if (checkSimdlenSafelenSpecified(*this, Clauses))
6482     return StmtError();
6483 
6484   setFunctionHasBranchProtectedScope();
6485   return OMPParallelForSimdDirective::Create(
6486       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6487 }
6488 
6489 StmtResult
6490 Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
6491                                            Stmt *AStmt, SourceLocation StartLoc,
6492                                            SourceLocation EndLoc) {
6493   if (!AStmt)
6494     return StmtError();
6495 
6496   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6497   auto BaseStmt = AStmt;
6498   while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
6499     BaseStmt = CS->getCapturedStmt();
6500   if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
6501     auto S = C->children();
6502     if (S.begin() == S.end())
6503       return StmtError();
6504     // All associated statements must be '#pragma omp section' except for
6505     // the first one.
6506     for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
6507       if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
6508         if (SectionStmt)
6509           Diag(SectionStmt->getBeginLoc(),
6510                diag::err_omp_parallel_sections_substmt_not_section);
6511         return StmtError();
6512       }
6513       cast<OMPSectionDirective>(SectionStmt)
6514           ->setHasCancel(DSAStack->isCancelRegion());
6515     }
6516   } else {
6517     Diag(AStmt->getBeginLoc(),
6518          diag::err_omp_parallel_sections_not_compound_stmt);
6519     return StmtError();
6520   }
6521 
6522   setFunctionHasBranchProtectedScope();
6523 
6524   return OMPParallelSectionsDirective::Create(
6525       Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
6526 }
6527 
6528 StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
6529                                           Stmt *AStmt, SourceLocation StartLoc,
6530                                           SourceLocation EndLoc) {
6531   if (!AStmt)
6532     return StmtError();
6533 
6534   auto *CS = cast<CapturedStmt>(AStmt);
6535   // 1.2.2 OpenMP Language Terminology
6536   // Structured block - An executable statement with a single entry at the
6537   // top and a single exit at the bottom.
6538   // The point of exit cannot be a branch out of the structured block.
6539   // longjmp() and throw() must not violate the entry/exit criteria.
6540   CS->getCapturedDecl()->setNothrow();
6541 
6542   setFunctionHasBranchProtectedScope();
6543 
6544   return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
6545                                   DSAStack->isCancelRegion());
6546 }
6547 
6548 StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
6549                                                SourceLocation EndLoc) {
6550   return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
6551 }
6552 
6553 StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
6554                                              SourceLocation EndLoc) {
6555   return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
6556 }
6557 
6558 StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
6559                                               SourceLocation EndLoc) {
6560   return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
6561 }
6562 
6563 StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
6564                                                Stmt *AStmt,
6565                                                SourceLocation StartLoc,
6566                                                SourceLocation EndLoc) {
6567   if (!AStmt)
6568     return StmtError();
6569 
6570   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6571 
6572   setFunctionHasBranchProtectedScope();
6573 
6574   return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses,
6575                                        AStmt,
6576                                        DSAStack->getTaskgroupReductionRef());
6577 }
6578 
6579 StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
6580                                            SourceLocation StartLoc,
6581                                            SourceLocation EndLoc) {
6582   assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
6583   return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
6584 }
6585 
6586 StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
6587                                              Stmt *AStmt,
6588                                              SourceLocation StartLoc,
6589                                              SourceLocation EndLoc) {
6590   const OMPClause *DependFound = nullptr;
6591   const OMPClause *DependSourceClause = nullptr;
6592   const OMPClause *DependSinkClause = nullptr;
6593   bool ErrorFound = false;
6594   const OMPThreadsClause *TC = nullptr;
6595   const OMPSIMDClause *SC = nullptr;
6596   for (const OMPClause *C : Clauses) {
6597     if (auto *DC = dyn_cast<OMPDependClause>(C)) {
6598       DependFound = C;
6599       if (DC->getDependencyKind() == OMPC_DEPEND_source) {
6600         if (DependSourceClause) {
6601           Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
6602               << getOpenMPDirectiveName(OMPD_ordered)
6603               << getOpenMPClauseName(OMPC_depend) << 2;
6604           ErrorFound = true;
6605         } else {
6606           DependSourceClause = C;
6607         }
6608         if (DependSinkClause) {
6609           Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
6610               << 0;
6611           ErrorFound = true;
6612         }
6613       } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
6614         if (DependSourceClause) {
6615           Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
6616               << 1;
6617           ErrorFound = true;
6618         }
6619         DependSinkClause = C;
6620       }
6621     } else if (C->getClauseKind() == OMPC_threads) {
6622       TC = cast<OMPThreadsClause>(C);
6623     } else if (C->getClauseKind() == OMPC_simd) {
6624       SC = cast<OMPSIMDClause>(C);
6625     }
6626   }
6627   if (!ErrorFound && !SC &&
6628       isOpenMPSimdDirective(DSAStack->getParentDirective())) {
6629     // OpenMP [2.8.1,simd Construct, Restrictions]
6630     // An ordered construct with the simd clause is the only OpenMP construct
6631     // that can appear in the simd region.
6632     Diag(StartLoc, diag::err_omp_prohibited_region_simd);
6633     ErrorFound = true;
6634   } else if (DependFound && (TC || SC)) {
6635     Diag(DependFound->getBeginLoc(), diag::err_omp_depend_clause_thread_simd)
6636         << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
6637     ErrorFound = true;
6638   } else if (DependFound && !DSAStack->getParentOrderedRegionParam().first) {
6639     Diag(DependFound->getBeginLoc(),
6640          diag::err_omp_ordered_directive_without_param);
6641     ErrorFound = true;
6642   } else if (TC || Clauses.empty()) {
6643     if (const Expr *Param = DSAStack->getParentOrderedRegionParam().first) {
6644       SourceLocation ErrLoc = TC ? TC->getBeginLoc() : StartLoc;
6645       Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
6646           << (TC != nullptr);
6647       Diag(Param->getBeginLoc(), diag::note_omp_ordered_param);
6648       ErrorFound = true;
6649     }
6650   }
6651   if ((!AStmt && !DependFound) || ErrorFound)
6652     return StmtError();
6653 
6654   if (AStmt) {
6655     assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6656 
6657     setFunctionHasBranchProtectedScope();
6658   }
6659 
6660   return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
6661 }
6662 
6663 namespace {
6664 /// Helper class for checking expression in 'omp atomic [update]'
6665 /// construct.
6666 class OpenMPAtomicUpdateChecker {
6667   /// Error results for atomic update expressions.
6668   enum ExprAnalysisErrorCode {
6669     /// A statement is not an expression statement.
6670     NotAnExpression,
6671     /// Expression is not builtin binary or unary operation.
6672     NotABinaryOrUnaryExpression,
6673     /// Unary operation is not post-/pre- increment/decrement operation.
6674     NotAnUnaryIncDecExpression,
6675     /// An expression is not of scalar type.
6676     NotAScalarType,
6677     /// A binary operation is not an assignment operation.
6678     NotAnAssignmentOp,
6679     /// RHS part of the binary operation is not a binary expression.
6680     NotABinaryExpression,
6681     /// RHS part is not additive/multiplicative/shift/biwise binary
6682     /// expression.
6683     NotABinaryOperator,
6684     /// RHS binary operation does not have reference to the updated LHS
6685     /// part.
6686     NotAnUpdateExpression,
6687     /// No errors is found.
6688     NoError
6689   };
6690   /// Reference to Sema.
6691   Sema &SemaRef;
6692   /// A location for note diagnostics (when error is found).
6693   SourceLocation NoteLoc;
6694   /// 'x' lvalue part of the source atomic expression.
6695   Expr *X;
6696   /// 'expr' rvalue part of the source atomic expression.
6697   Expr *E;
6698   /// Helper expression of the form
6699   /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
6700   /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
6701   Expr *UpdateExpr;
6702   /// Is 'x' a LHS in a RHS part of full update expression. It is
6703   /// important for non-associative operations.
6704   bool IsXLHSInRHSPart;
6705   BinaryOperatorKind Op;
6706   SourceLocation OpLoc;
6707   /// true if the source expression is a postfix unary operation, false
6708   /// if it is a prefix unary operation.
6709   bool IsPostfixUpdate;
6710 
6711 public:
6712   OpenMPAtomicUpdateChecker(Sema &SemaRef)
6713       : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
6714         IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
6715   /// Check specified statement that it is suitable for 'atomic update'
6716   /// constructs and extract 'x', 'expr' and Operation from the original
6717   /// expression. If DiagId and NoteId == 0, then only check is performed
6718   /// without error notification.
6719   /// \param DiagId Diagnostic which should be emitted if error is found.
6720   /// \param NoteId Diagnostic note for the main error message.
6721   /// \return true if statement is not an update expression, false otherwise.
6722   bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
6723   /// Return the 'x' lvalue part of the source atomic expression.
6724   Expr *getX() const { return X; }
6725   /// Return the 'expr' rvalue part of the source atomic expression.
6726   Expr *getExpr() const { return E; }
6727   /// Return the update expression used in calculation of the updated
6728   /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
6729   /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
6730   Expr *getUpdateExpr() const { return UpdateExpr; }
6731   /// Return true if 'x' is LHS in RHS part of full update expression,
6732   /// false otherwise.
6733   bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
6734 
6735   /// true if the source expression is a postfix unary operation, false
6736   /// if it is a prefix unary operation.
6737   bool isPostfixUpdate() const { return IsPostfixUpdate; }
6738 
6739 private:
6740   bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
6741                             unsigned NoteId = 0);
6742 };
6743 } // namespace
6744 
6745 bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
6746     BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
6747   ExprAnalysisErrorCode ErrorFound = NoError;
6748   SourceLocation ErrorLoc, NoteLoc;
6749   SourceRange ErrorRange, NoteRange;
6750   // Allowed constructs are:
6751   //  x = x binop expr;
6752   //  x = expr binop x;
6753   if (AtomicBinOp->getOpcode() == BO_Assign) {
6754     X = AtomicBinOp->getLHS();
6755     if (const auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
6756             AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
6757       if (AtomicInnerBinOp->isMultiplicativeOp() ||
6758           AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
6759           AtomicInnerBinOp->isBitwiseOp()) {
6760         Op = AtomicInnerBinOp->getOpcode();
6761         OpLoc = AtomicInnerBinOp->getOperatorLoc();
6762         Expr *LHS = AtomicInnerBinOp->getLHS();
6763         Expr *RHS = AtomicInnerBinOp->getRHS();
6764         llvm::FoldingSetNodeID XId, LHSId, RHSId;
6765         X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
6766                                           /*Canonical=*/true);
6767         LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
6768                                             /*Canonical=*/true);
6769         RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
6770                                             /*Canonical=*/true);
6771         if (XId == LHSId) {
6772           E = RHS;
6773           IsXLHSInRHSPart = true;
6774         } else if (XId == RHSId) {
6775           E = LHS;
6776           IsXLHSInRHSPart = false;
6777         } else {
6778           ErrorLoc = AtomicInnerBinOp->getExprLoc();
6779           ErrorRange = AtomicInnerBinOp->getSourceRange();
6780           NoteLoc = X->getExprLoc();
6781           NoteRange = X->getSourceRange();
6782           ErrorFound = NotAnUpdateExpression;
6783         }
6784       } else {
6785         ErrorLoc = AtomicInnerBinOp->getExprLoc();
6786         ErrorRange = AtomicInnerBinOp->getSourceRange();
6787         NoteLoc = AtomicInnerBinOp->getOperatorLoc();
6788         NoteRange = SourceRange(NoteLoc, NoteLoc);
6789         ErrorFound = NotABinaryOperator;
6790       }
6791     } else {
6792       NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
6793       NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
6794       ErrorFound = NotABinaryExpression;
6795     }
6796   } else {
6797     ErrorLoc = AtomicBinOp->getExprLoc();
6798     ErrorRange = AtomicBinOp->getSourceRange();
6799     NoteLoc = AtomicBinOp->getOperatorLoc();
6800     NoteRange = SourceRange(NoteLoc, NoteLoc);
6801     ErrorFound = NotAnAssignmentOp;
6802   }
6803   if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
6804     SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
6805     SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
6806     return true;
6807   }
6808   if (SemaRef.CurContext->isDependentContext())
6809     E = X = UpdateExpr = nullptr;
6810   return ErrorFound != NoError;
6811 }
6812 
6813 bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
6814                                                unsigned NoteId) {
6815   ExprAnalysisErrorCode ErrorFound = NoError;
6816   SourceLocation ErrorLoc, NoteLoc;
6817   SourceRange ErrorRange, NoteRange;
6818   // Allowed constructs are:
6819   //  x++;
6820   //  x--;
6821   //  ++x;
6822   //  --x;
6823   //  x binop= expr;
6824   //  x = x binop expr;
6825   //  x = expr binop x;
6826   if (auto *AtomicBody = dyn_cast<Expr>(S)) {
6827     AtomicBody = AtomicBody->IgnoreParenImpCasts();
6828     if (AtomicBody->getType()->isScalarType() ||
6829         AtomicBody->isInstantiationDependent()) {
6830       if (const auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
6831               AtomicBody->IgnoreParenImpCasts())) {
6832         // Check for Compound Assignment Operation
6833         Op = BinaryOperator::getOpForCompoundAssignment(
6834             AtomicCompAssignOp->getOpcode());
6835         OpLoc = AtomicCompAssignOp->getOperatorLoc();
6836         E = AtomicCompAssignOp->getRHS();
6837         X = AtomicCompAssignOp->getLHS()->IgnoreParens();
6838         IsXLHSInRHSPart = true;
6839       } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
6840                      AtomicBody->IgnoreParenImpCasts())) {
6841         // Check for Binary Operation
6842         if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
6843           return true;
6844       } else if (const auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
6845                      AtomicBody->IgnoreParenImpCasts())) {
6846         // Check for Unary Operation
6847         if (AtomicUnaryOp->isIncrementDecrementOp()) {
6848           IsPostfixUpdate = AtomicUnaryOp->isPostfix();
6849           Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
6850           OpLoc = AtomicUnaryOp->getOperatorLoc();
6851           X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
6852           E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
6853           IsXLHSInRHSPart = true;
6854         } else {
6855           ErrorFound = NotAnUnaryIncDecExpression;
6856           ErrorLoc = AtomicUnaryOp->getExprLoc();
6857           ErrorRange = AtomicUnaryOp->getSourceRange();
6858           NoteLoc = AtomicUnaryOp->getOperatorLoc();
6859           NoteRange = SourceRange(NoteLoc, NoteLoc);
6860         }
6861       } else if (!AtomicBody->isInstantiationDependent()) {
6862         ErrorFound = NotABinaryOrUnaryExpression;
6863         NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
6864         NoteRange = ErrorRange = AtomicBody->getSourceRange();
6865       }
6866     } else {
6867       ErrorFound = NotAScalarType;
6868       NoteLoc = ErrorLoc = AtomicBody->getBeginLoc();
6869       NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
6870     }
6871   } else {
6872     ErrorFound = NotAnExpression;
6873     NoteLoc = ErrorLoc = S->getBeginLoc();
6874     NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
6875   }
6876   if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
6877     SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
6878     SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
6879     return true;
6880   }
6881   if (SemaRef.CurContext->isDependentContext())
6882     E = X = UpdateExpr = nullptr;
6883   if (ErrorFound == NoError && E && X) {
6884     // Build an update expression of form 'OpaqueValueExpr(x) binop
6885     // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
6886     // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
6887     auto *OVEX = new (SemaRef.getASTContext())
6888         OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
6889     auto *OVEExpr = new (SemaRef.getASTContext())
6890         OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
6891     ExprResult Update =
6892         SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
6893                                    IsXLHSInRHSPart ? OVEExpr : OVEX);
6894     if (Update.isInvalid())
6895       return true;
6896     Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
6897                                                Sema::AA_Casting);
6898     if (Update.isInvalid())
6899       return true;
6900     UpdateExpr = Update.get();
6901   }
6902   return ErrorFound != NoError;
6903 }
6904 
6905 StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
6906                                             Stmt *AStmt,
6907                                             SourceLocation StartLoc,
6908                                             SourceLocation EndLoc) {
6909   if (!AStmt)
6910     return StmtError();
6911 
6912   auto *CS = cast<CapturedStmt>(AStmt);
6913   // 1.2.2 OpenMP Language Terminology
6914   // Structured block - An executable statement with a single entry at the
6915   // top and a single exit at the bottom.
6916   // The point of exit cannot be a branch out of the structured block.
6917   // longjmp() and throw() must not violate the entry/exit criteria.
6918   OpenMPClauseKind AtomicKind = OMPC_unknown;
6919   SourceLocation AtomicKindLoc;
6920   for (const OMPClause *C : Clauses) {
6921     if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
6922         C->getClauseKind() == OMPC_update ||
6923         C->getClauseKind() == OMPC_capture) {
6924       if (AtomicKind != OMPC_unknown) {
6925         Diag(C->getBeginLoc(), diag::err_omp_atomic_several_clauses)
6926             << SourceRange(C->getBeginLoc(), C->getEndLoc());
6927         Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
6928             << getOpenMPClauseName(AtomicKind);
6929       } else {
6930         AtomicKind = C->getClauseKind();
6931         AtomicKindLoc = C->getBeginLoc();
6932       }
6933     }
6934   }
6935 
6936   Stmt *Body = CS->getCapturedStmt();
6937   if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
6938     Body = EWC->getSubExpr();
6939 
6940   Expr *X = nullptr;
6941   Expr *V = nullptr;
6942   Expr *E = nullptr;
6943   Expr *UE = nullptr;
6944   bool IsXLHSInRHSPart = false;
6945   bool IsPostfixUpdate = false;
6946   // OpenMP [2.12.6, atomic Construct]
6947   // In the next expressions:
6948   // * x and v (as applicable) are both l-value expressions with scalar type.
6949   // * During the execution of an atomic region, multiple syntactic
6950   // occurrences of x must designate the same storage location.
6951   // * Neither of v and expr (as applicable) may access the storage location
6952   // designated by x.
6953   // * Neither of x and expr (as applicable) may access the storage location
6954   // designated by v.
6955   // * expr is an expression with scalar type.
6956   // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
6957   // * binop, binop=, ++, and -- are not overloaded operators.
6958   // * The expression x binop expr must be numerically equivalent to x binop
6959   // (expr). This requirement is satisfied if the operators in expr have
6960   // precedence greater than binop, or by using parentheses around expr or
6961   // subexpressions of expr.
6962   // * The expression expr binop x must be numerically equivalent to (expr)
6963   // binop x. This requirement is satisfied if the operators in expr have
6964   // precedence equal to or greater than binop, or by using parentheses around
6965   // expr or subexpressions of expr.
6966   // * For forms that allow multiple occurrences of x, the number of times
6967   // that x is evaluated is unspecified.
6968   if (AtomicKind == OMPC_read) {
6969     enum {
6970       NotAnExpression,
6971       NotAnAssignmentOp,
6972       NotAScalarType,
6973       NotAnLValue,
6974       NoError
6975     } ErrorFound = NoError;
6976     SourceLocation ErrorLoc, NoteLoc;
6977     SourceRange ErrorRange, NoteRange;
6978     // If clause is read:
6979     //  v = x;
6980     if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
6981       const auto *AtomicBinOp =
6982           dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
6983       if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
6984         X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
6985         V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
6986         if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
6987             (V->isInstantiationDependent() || V->getType()->isScalarType())) {
6988           if (!X->isLValue() || !V->isLValue()) {
6989             const Expr *NotLValueExpr = X->isLValue() ? V : X;
6990             ErrorFound = NotAnLValue;
6991             ErrorLoc = AtomicBinOp->getExprLoc();
6992             ErrorRange = AtomicBinOp->getSourceRange();
6993             NoteLoc = NotLValueExpr->getExprLoc();
6994             NoteRange = NotLValueExpr->getSourceRange();
6995           }
6996         } else if (!X->isInstantiationDependent() ||
6997                    !V->isInstantiationDependent()) {
6998           const Expr *NotScalarExpr =
6999               (X->isInstantiationDependent() || X->getType()->isScalarType())
7000                   ? V
7001                   : X;
7002           ErrorFound = NotAScalarType;
7003           ErrorLoc = AtomicBinOp->getExprLoc();
7004           ErrorRange = AtomicBinOp->getSourceRange();
7005           NoteLoc = NotScalarExpr->getExprLoc();
7006           NoteRange = NotScalarExpr->getSourceRange();
7007         }
7008       } else if (!AtomicBody->isInstantiationDependent()) {
7009         ErrorFound = NotAnAssignmentOp;
7010         ErrorLoc = AtomicBody->getExprLoc();
7011         ErrorRange = AtomicBody->getSourceRange();
7012         NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
7013                               : AtomicBody->getExprLoc();
7014         NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
7015                                 : AtomicBody->getSourceRange();
7016       }
7017     } else {
7018       ErrorFound = NotAnExpression;
7019       NoteLoc = ErrorLoc = Body->getBeginLoc();
7020       NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
7021     }
7022     if (ErrorFound != NoError) {
7023       Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
7024           << ErrorRange;
7025       Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
7026                                                       << NoteRange;
7027       return StmtError();
7028     }
7029     if (CurContext->isDependentContext())
7030       V = X = nullptr;
7031   } else if (AtomicKind == OMPC_write) {
7032     enum {
7033       NotAnExpression,
7034       NotAnAssignmentOp,
7035       NotAScalarType,
7036       NotAnLValue,
7037       NoError
7038     } ErrorFound = NoError;
7039     SourceLocation ErrorLoc, NoteLoc;
7040     SourceRange ErrorRange, NoteRange;
7041     // If clause is write:
7042     //  x = expr;
7043     if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
7044       const auto *AtomicBinOp =
7045           dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
7046       if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
7047         X = AtomicBinOp->getLHS();
7048         E = AtomicBinOp->getRHS();
7049         if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
7050             (E->isInstantiationDependent() || E->getType()->isScalarType())) {
7051           if (!X->isLValue()) {
7052             ErrorFound = NotAnLValue;
7053             ErrorLoc = AtomicBinOp->getExprLoc();
7054             ErrorRange = AtomicBinOp->getSourceRange();
7055             NoteLoc = X->getExprLoc();
7056             NoteRange = X->getSourceRange();
7057           }
7058         } else if (!X->isInstantiationDependent() ||
7059                    !E->isInstantiationDependent()) {
7060           const Expr *NotScalarExpr =
7061               (X->isInstantiationDependent() || X->getType()->isScalarType())
7062                   ? E
7063                   : X;
7064           ErrorFound = NotAScalarType;
7065           ErrorLoc = AtomicBinOp->getExprLoc();
7066           ErrorRange = AtomicBinOp->getSourceRange();
7067           NoteLoc = NotScalarExpr->getExprLoc();
7068           NoteRange = NotScalarExpr->getSourceRange();
7069         }
7070       } else if (!AtomicBody->isInstantiationDependent()) {
7071         ErrorFound = NotAnAssignmentOp;
7072         ErrorLoc = AtomicBody->getExprLoc();
7073         ErrorRange = AtomicBody->getSourceRange();
7074         NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
7075                               : AtomicBody->getExprLoc();
7076         NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
7077                                 : AtomicBody->getSourceRange();
7078       }
7079     } else {
7080       ErrorFound = NotAnExpression;
7081       NoteLoc = ErrorLoc = Body->getBeginLoc();
7082       NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
7083     }
7084     if (ErrorFound != NoError) {
7085       Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
7086           << ErrorRange;
7087       Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
7088                                                       << NoteRange;
7089       return StmtError();
7090     }
7091     if (CurContext->isDependentContext())
7092       E = X = nullptr;
7093   } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
7094     // If clause is update:
7095     //  x++;
7096     //  x--;
7097     //  ++x;
7098     //  --x;
7099     //  x binop= expr;
7100     //  x = x binop expr;
7101     //  x = expr binop x;
7102     OpenMPAtomicUpdateChecker Checker(*this);
7103     if (Checker.checkStatement(
7104             Body, (AtomicKind == OMPC_update)
7105                       ? diag::err_omp_atomic_update_not_expression_statement
7106                       : diag::err_omp_atomic_not_expression_statement,
7107             diag::note_omp_atomic_update))
7108       return StmtError();
7109     if (!CurContext->isDependentContext()) {
7110       E = Checker.getExpr();
7111       X = Checker.getX();
7112       UE = Checker.getUpdateExpr();
7113       IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
7114     }
7115   } else if (AtomicKind == OMPC_capture) {
7116     enum {
7117       NotAnAssignmentOp,
7118       NotACompoundStatement,
7119       NotTwoSubstatements,
7120       NotASpecificExpression,
7121       NoError
7122     } ErrorFound = NoError;
7123     SourceLocation ErrorLoc, NoteLoc;
7124     SourceRange ErrorRange, NoteRange;
7125     if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
7126       // If clause is a capture:
7127       //  v = x++;
7128       //  v = x--;
7129       //  v = ++x;
7130       //  v = --x;
7131       //  v = x binop= expr;
7132       //  v = x = x binop expr;
7133       //  v = x = expr binop x;
7134       const auto *AtomicBinOp =
7135           dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
7136       if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
7137         V = AtomicBinOp->getLHS();
7138         Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
7139         OpenMPAtomicUpdateChecker Checker(*this);
7140         if (Checker.checkStatement(
7141                 Body, diag::err_omp_atomic_capture_not_expression_statement,
7142                 diag::note_omp_atomic_update))
7143           return StmtError();
7144         E = Checker.getExpr();
7145         X = Checker.getX();
7146         UE = Checker.getUpdateExpr();
7147         IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
7148         IsPostfixUpdate = Checker.isPostfixUpdate();
7149       } else if (!AtomicBody->isInstantiationDependent()) {
7150         ErrorLoc = AtomicBody->getExprLoc();
7151         ErrorRange = AtomicBody->getSourceRange();
7152         NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
7153                               : AtomicBody->getExprLoc();
7154         NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
7155                                 : AtomicBody->getSourceRange();
7156         ErrorFound = NotAnAssignmentOp;
7157       }
7158       if (ErrorFound != NoError) {
7159         Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
7160             << ErrorRange;
7161         Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
7162         return StmtError();
7163       }
7164       if (CurContext->isDependentContext())
7165         UE = V = E = X = nullptr;
7166     } else {
7167       // If clause is a capture:
7168       //  { v = x; x = expr; }
7169       //  { v = x; x++; }
7170       //  { v = x; x--; }
7171       //  { v = x; ++x; }
7172       //  { v = x; --x; }
7173       //  { v = x; x binop= expr; }
7174       //  { v = x; x = x binop expr; }
7175       //  { v = x; x = expr binop x; }
7176       //  { x++; v = x; }
7177       //  { x--; v = x; }
7178       //  { ++x; v = x; }
7179       //  { --x; v = x; }
7180       //  { x binop= expr; v = x; }
7181       //  { x = x binop expr; v = x; }
7182       //  { x = expr binop x; v = x; }
7183       if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
7184         // Check that this is { expr1; expr2; }
7185         if (CS->size() == 2) {
7186           Stmt *First = CS->body_front();
7187           Stmt *Second = CS->body_back();
7188           if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
7189             First = EWC->getSubExpr()->IgnoreParenImpCasts();
7190           if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
7191             Second = EWC->getSubExpr()->IgnoreParenImpCasts();
7192           // Need to find what subexpression is 'v' and what is 'x'.
7193           OpenMPAtomicUpdateChecker Checker(*this);
7194           bool IsUpdateExprFound = !Checker.checkStatement(Second);
7195           BinaryOperator *BinOp = nullptr;
7196           if (IsUpdateExprFound) {
7197             BinOp = dyn_cast<BinaryOperator>(First);
7198             IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
7199           }
7200           if (IsUpdateExprFound && !CurContext->isDependentContext()) {
7201             //  { v = x; x++; }
7202             //  { v = x; x--; }
7203             //  { v = x; ++x; }
7204             //  { v = x; --x; }
7205             //  { v = x; x binop= expr; }
7206             //  { v = x; x = x binop expr; }
7207             //  { v = x; x = expr binop x; }
7208             // Check that the first expression has form v = x.
7209             Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
7210             llvm::FoldingSetNodeID XId, PossibleXId;
7211             Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
7212             PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
7213             IsUpdateExprFound = XId == PossibleXId;
7214             if (IsUpdateExprFound) {
7215               V = BinOp->getLHS();
7216               X = Checker.getX();
7217               E = Checker.getExpr();
7218               UE = Checker.getUpdateExpr();
7219               IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
7220               IsPostfixUpdate = true;
7221             }
7222           }
7223           if (!IsUpdateExprFound) {
7224             IsUpdateExprFound = !Checker.checkStatement(First);
7225             BinOp = nullptr;
7226             if (IsUpdateExprFound) {
7227               BinOp = dyn_cast<BinaryOperator>(Second);
7228               IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
7229             }
7230             if (IsUpdateExprFound && !CurContext->isDependentContext()) {
7231               //  { x++; v = x; }
7232               //  { x--; v = x; }
7233               //  { ++x; v = x; }
7234               //  { --x; v = x; }
7235               //  { x binop= expr; v = x; }
7236               //  { x = x binop expr; v = x; }
7237               //  { x = expr binop x; v = x; }
7238               // Check that the second expression has form v = x.
7239               Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
7240               llvm::FoldingSetNodeID XId, PossibleXId;
7241               Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
7242               PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
7243               IsUpdateExprFound = XId == PossibleXId;
7244               if (IsUpdateExprFound) {
7245                 V = BinOp->getLHS();
7246                 X = Checker.getX();
7247                 E = Checker.getExpr();
7248                 UE = Checker.getUpdateExpr();
7249                 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
7250                 IsPostfixUpdate = false;
7251               }
7252             }
7253           }
7254           if (!IsUpdateExprFound) {
7255             //  { v = x; x = expr; }
7256             auto *FirstExpr = dyn_cast<Expr>(First);
7257             auto *SecondExpr = dyn_cast<Expr>(Second);
7258             if (!FirstExpr || !SecondExpr ||
7259                 !(FirstExpr->isInstantiationDependent() ||
7260                   SecondExpr->isInstantiationDependent())) {
7261               auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
7262               if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
7263                 ErrorFound = NotAnAssignmentOp;
7264                 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
7265                                                 : First->getBeginLoc();
7266                 NoteRange = ErrorRange = FirstBinOp
7267                                              ? FirstBinOp->getSourceRange()
7268                                              : SourceRange(ErrorLoc, ErrorLoc);
7269               } else {
7270                 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
7271                 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
7272                   ErrorFound = NotAnAssignmentOp;
7273                   NoteLoc = ErrorLoc = SecondBinOp
7274                                            ? SecondBinOp->getOperatorLoc()
7275                                            : Second->getBeginLoc();
7276                   NoteRange = ErrorRange =
7277                       SecondBinOp ? SecondBinOp->getSourceRange()
7278                                   : SourceRange(ErrorLoc, ErrorLoc);
7279                 } else {
7280                   Expr *PossibleXRHSInFirst =
7281                       FirstBinOp->getRHS()->IgnoreParenImpCasts();
7282                   Expr *PossibleXLHSInSecond =
7283                       SecondBinOp->getLHS()->IgnoreParenImpCasts();
7284                   llvm::FoldingSetNodeID X1Id, X2Id;
7285                   PossibleXRHSInFirst->Profile(X1Id, Context,
7286                                                /*Canonical=*/true);
7287                   PossibleXLHSInSecond->Profile(X2Id, Context,
7288                                                 /*Canonical=*/true);
7289                   IsUpdateExprFound = X1Id == X2Id;
7290                   if (IsUpdateExprFound) {
7291                     V = FirstBinOp->getLHS();
7292                     X = SecondBinOp->getLHS();
7293                     E = SecondBinOp->getRHS();
7294                     UE = nullptr;
7295                     IsXLHSInRHSPart = false;
7296                     IsPostfixUpdate = true;
7297                   } else {
7298                     ErrorFound = NotASpecificExpression;
7299                     ErrorLoc = FirstBinOp->getExprLoc();
7300                     ErrorRange = FirstBinOp->getSourceRange();
7301                     NoteLoc = SecondBinOp->getLHS()->getExprLoc();
7302                     NoteRange = SecondBinOp->getRHS()->getSourceRange();
7303                   }
7304                 }
7305               }
7306             }
7307           }
7308         } else {
7309           NoteLoc = ErrorLoc = Body->getBeginLoc();
7310           NoteRange = ErrorRange =
7311               SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
7312           ErrorFound = NotTwoSubstatements;
7313         }
7314       } else {
7315         NoteLoc = ErrorLoc = Body->getBeginLoc();
7316         NoteRange = ErrorRange =
7317             SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
7318         ErrorFound = NotACompoundStatement;
7319       }
7320       if (ErrorFound != NoError) {
7321         Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
7322             << ErrorRange;
7323         Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
7324         return StmtError();
7325       }
7326       if (CurContext->isDependentContext())
7327         UE = V = E = X = nullptr;
7328     }
7329   }
7330 
7331   setFunctionHasBranchProtectedScope();
7332 
7333   return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
7334                                     X, V, E, UE, IsXLHSInRHSPart,
7335                                     IsPostfixUpdate);
7336 }
7337 
7338 StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
7339                                             Stmt *AStmt,
7340                                             SourceLocation StartLoc,
7341                                             SourceLocation EndLoc) {
7342   if (!AStmt)
7343     return StmtError();
7344 
7345   auto *CS = cast<CapturedStmt>(AStmt);
7346   // 1.2.2 OpenMP Language Terminology
7347   // Structured block - An executable statement with a single entry at the
7348   // top and a single exit at the bottom.
7349   // The point of exit cannot be a branch out of the structured block.
7350   // longjmp() and throw() must not violate the entry/exit criteria.
7351   CS->getCapturedDecl()->setNothrow();
7352   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target);
7353        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7354     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7355     // 1.2.2 OpenMP Language Terminology
7356     // Structured block - An executable statement with a single entry at the
7357     // top and a single exit at the bottom.
7358     // The point of exit cannot be a branch out of the structured block.
7359     // longjmp() and throw() must not violate the entry/exit criteria.
7360     CS->getCapturedDecl()->setNothrow();
7361   }
7362 
7363   // OpenMP [2.16, Nesting of Regions]
7364   // If specified, a teams construct must be contained within a target
7365   // construct. That target construct must contain no statements or directives
7366   // outside of the teams construct.
7367   if (DSAStack->hasInnerTeamsRegion()) {
7368     const Stmt *S = CS->IgnoreContainers(/*IgnoreCaptured=*/true);
7369     bool OMPTeamsFound = true;
7370     if (const auto *CS = dyn_cast<CompoundStmt>(S)) {
7371       auto I = CS->body_begin();
7372       while (I != CS->body_end()) {
7373         const auto *OED = dyn_cast<OMPExecutableDirective>(*I);
7374         if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind()) ||
7375             OMPTeamsFound) {
7376 
7377           OMPTeamsFound = false;
7378           break;
7379         }
7380         ++I;
7381       }
7382       assert(I != CS->body_end() && "Not found statement");
7383       S = *I;
7384     } else {
7385       const auto *OED = dyn_cast<OMPExecutableDirective>(S);
7386       OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
7387     }
7388     if (!OMPTeamsFound) {
7389       Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
7390       Diag(DSAStack->getInnerTeamsRegionLoc(),
7391            diag::note_omp_nested_teams_construct_here);
7392       Diag(S->getBeginLoc(), diag::note_omp_nested_statement_here)
7393           << isa<OMPExecutableDirective>(S);
7394       return StmtError();
7395     }
7396   }
7397 
7398   setFunctionHasBranchProtectedScope();
7399 
7400   return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
7401 }
7402 
7403 StmtResult
7404 Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
7405                                          Stmt *AStmt, SourceLocation StartLoc,
7406                                          SourceLocation EndLoc) {
7407   if (!AStmt)
7408     return StmtError();
7409 
7410   auto *CS = cast<CapturedStmt>(AStmt);
7411   // 1.2.2 OpenMP Language Terminology
7412   // Structured block - An executable statement with a single entry at the
7413   // top and a single exit at the bottom.
7414   // The point of exit cannot be a branch out of the structured block.
7415   // longjmp() and throw() must not violate the entry/exit criteria.
7416   CS->getCapturedDecl()->setNothrow();
7417   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel);
7418        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7419     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7420     // 1.2.2 OpenMP Language Terminology
7421     // Structured block - An executable statement with a single entry at the
7422     // top and a single exit at the bottom.
7423     // The point of exit cannot be a branch out of the structured block.
7424     // longjmp() and throw() must not violate the entry/exit criteria.
7425     CS->getCapturedDecl()->setNothrow();
7426   }
7427 
7428   setFunctionHasBranchProtectedScope();
7429 
7430   return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
7431                                             AStmt);
7432 }
7433 
7434 StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
7435     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7436     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
7437   if (!AStmt)
7438     return StmtError();
7439 
7440   auto *CS = cast<CapturedStmt>(AStmt);
7441   // 1.2.2 OpenMP Language Terminology
7442   // Structured block - An executable statement with a single entry at the
7443   // top and a single exit at the bottom.
7444   // The point of exit cannot be a branch out of the structured block.
7445   // longjmp() and throw() must not violate the entry/exit criteria.
7446   CS->getCapturedDecl()->setNothrow();
7447   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
7448        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7449     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7450     // 1.2.2 OpenMP Language Terminology
7451     // Structured block - An executable statement with a single entry at the
7452     // top and a single exit at the bottom.
7453     // The point of exit cannot be a branch out of the structured block.
7454     // longjmp() and throw() must not violate the entry/exit criteria.
7455     CS->getCapturedDecl()->setNothrow();
7456   }
7457 
7458   OMPLoopDirective::HelperExprs B;
7459   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7460   // define the nested loops number.
7461   unsigned NestedLoopCount =
7462       checkOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
7463                       getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
7464                       VarsWithImplicitDSA, B);
7465   if (NestedLoopCount == 0)
7466     return StmtError();
7467 
7468   assert((CurContext->isDependentContext() || B.builtAll()) &&
7469          "omp target parallel for loop exprs were not built");
7470 
7471   if (!CurContext->isDependentContext()) {
7472     // Finalize the clauses that need pre-built expressions for CodeGen.
7473     for (OMPClause *C : Clauses) {
7474       if (auto *LC = dyn_cast<OMPLinearClause>(C))
7475         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7476                                      B.NumIterations, *this, CurScope,
7477                                      DSAStack))
7478           return StmtError();
7479     }
7480   }
7481 
7482   setFunctionHasBranchProtectedScope();
7483   return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
7484                                                NestedLoopCount, Clauses, AStmt,
7485                                                B, DSAStack->isCancelRegion());
7486 }
7487 
7488 /// Check for existence of a map clause in the list of clauses.
7489 static bool hasClauses(ArrayRef<OMPClause *> Clauses,
7490                        const OpenMPClauseKind K) {
7491   return llvm::any_of(
7492       Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; });
7493 }
7494 
7495 template <typename... Params>
7496 static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K,
7497                        const Params... ClauseTypes) {
7498   return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...);
7499 }
7500 
7501 StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
7502                                                 Stmt *AStmt,
7503                                                 SourceLocation StartLoc,
7504                                                 SourceLocation EndLoc) {
7505   if (!AStmt)
7506     return StmtError();
7507 
7508   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
7509 
7510   // OpenMP [2.10.1, Restrictions, p. 97]
7511   // At least one map clause must appear on the directive.
7512   if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr)) {
7513     Diag(StartLoc, diag::err_omp_no_clause_for_directive)
7514         << "'map' or 'use_device_ptr'"
7515         << getOpenMPDirectiveName(OMPD_target_data);
7516     return StmtError();
7517   }
7518 
7519   setFunctionHasBranchProtectedScope();
7520 
7521   return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
7522                                         AStmt);
7523 }
7524 
7525 StmtResult
7526 Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
7527                                           SourceLocation StartLoc,
7528                                           SourceLocation EndLoc, Stmt *AStmt) {
7529   if (!AStmt)
7530     return StmtError();
7531 
7532   auto *CS = cast<CapturedStmt>(AStmt);
7533   // 1.2.2 OpenMP Language Terminology
7534   // Structured block - An executable statement with a single entry at the
7535   // top and a single exit at the bottom.
7536   // The point of exit cannot be a branch out of the structured block.
7537   // longjmp() and throw() must not violate the entry/exit criteria.
7538   CS->getCapturedDecl()->setNothrow();
7539   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_enter_data);
7540        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7541     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7542     // 1.2.2 OpenMP Language Terminology
7543     // Structured block - An executable statement with a single entry at the
7544     // top and a single exit at the bottom.
7545     // The point of exit cannot be a branch out of the structured block.
7546     // longjmp() and throw() must not violate the entry/exit criteria.
7547     CS->getCapturedDecl()->setNothrow();
7548   }
7549 
7550   // OpenMP [2.10.2, Restrictions, p. 99]
7551   // At least one map clause must appear on the directive.
7552   if (!hasClauses(Clauses, OMPC_map)) {
7553     Diag(StartLoc, diag::err_omp_no_clause_for_directive)
7554         << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data);
7555     return StmtError();
7556   }
7557 
7558   return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
7559                                              AStmt);
7560 }
7561 
7562 StmtResult
7563 Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
7564                                          SourceLocation StartLoc,
7565                                          SourceLocation EndLoc, Stmt *AStmt) {
7566   if (!AStmt)
7567     return StmtError();
7568 
7569   auto *CS = cast<CapturedStmt>(AStmt);
7570   // 1.2.2 OpenMP Language Terminology
7571   // Structured block - An executable statement with a single entry at the
7572   // top and a single exit at the bottom.
7573   // The point of exit cannot be a branch out of the structured block.
7574   // longjmp() and throw() must not violate the entry/exit criteria.
7575   CS->getCapturedDecl()->setNothrow();
7576   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_exit_data);
7577        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7578     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7579     // 1.2.2 OpenMP Language Terminology
7580     // Structured block - An executable statement with a single entry at the
7581     // top and a single exit at the bottom.
7582     // The point of exit cannot be a branch out of the structured block.
7583     // longjmp() and throw() must not violate the entry/exit criteria.
7584     CS->getCapturedDecl()->setNothrow();
7585   }
7586 
7587   // OpenMP [2.10.3, Restrictions, p. 102]
7588   // At least one map clause must appear on the directive.
7589   if (!hasClauses(Clauses, OMPC_map)) {
7590     Diag(StartLoc, diag::err_omp_no_clause_for_directive)
7591         << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data);
7592     return StmtError();
7593   }
7594 
7595   return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
7596                                             AStmt);
7597 }
7598 
7599 StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
7600                                                   SourceLocation StartLoc,
7601                                                   SourceLocation EndLoc,
7602                                                   Stmt *AStmt) {
7603   if (!AStmt)
7604     return StmtError();
7605 
7606   auto *CS = cast<CapturedStmt>(AStmt);
7607   // 1.2.2 OpenMP Language Terminology
7608   // Structured block - An executable statement with a single entry at the
7609   // top and a single exit at the bottom.
7610   // The point of exit cannot be a branch out of the structured block.
7611   // longjmp() and throw() must not violate the entry/exit criteria.
7612   CS->getCapturedDecl()->setNothrow();
7613   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_update);
7614        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7615     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7616     // 1.2.2 OpenMP Language Terminology
7617     // Structured block - An executable statement with a single entry at the
7618     // top and a single exit at the bottom.
7619     // The point of exit cannot be a branch out of the structured block.
7620     // longjmp() and throw() must not violate the entry/exit criteria.
7621     CS->getCapturedDecl()->setNothrow();
7622   }
7623 
7624   if (!hasClauses(Clauses, OMPC_to, OMPC_from)) {
7625     Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
7626     return StmtError();
7627   }
7628   return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses,
7629                                           AStmt);
7630 }
7631 
7632 StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
7633                                            Stmt *AStmt, SourceLocation StartLoc,
7634                                            SourceLocation EndLoc) {
7635   if (!AStmt)
7636     return StmtError();
7637 
7638   auto *CS = cast<CapturedStmt>(AStmt);
7639   // 1.2.2 OpenMP Language Terminology
7640   // Structured block - An executable statement with a single entry at the
7641   // top and a single exit at the bottom.
7642   // The point of exit cannot be a branch out of the structured block.
7643   // longjmp() and throw() must not violate the entry/exit criteria.
7644   CS->getCapturedDecl()->setNothrow();
7645 
7646   setFunctionHasBranchProtectedScope();
7647 
7648   DSAStack->setParentTeamsRegionLoc(StartLoc);
7649 
7650   return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
7651 }
7652 
7653 StmtResult
7654 Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
7655                                             SourceLocation EndLoc,
7656                                             OpenMPDirectiveKind CancelRegion) {
7657   if (DSAStack->isParentNowaitRegion()) {
7658     Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
7659     return StmtError();
7660   }
7661   if (DSAStack->isParentOrderedRegion()) {
7662     Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
7663     return StmtError();
7664   }
7665   return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
7666                                                CancelRegion);
7667 }
7668 
7669 StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
7670                                             SourceLocation StartLoc,
7671                                             SourceLocation EndLoc,
7672                                             OpenMPDirectiveKind CancelRegion) {
7673   if (DSAStack->isParentNowaitRegion()) {
7674     Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
7675     return StmtError();
7676   }
7677   if (DSAStack->isParentOrderedRegion()) {
7678     Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
7679     return StmtError();
7680   }
7681   DSAStack->setParentCancelRegion(/*Cancel=*/true);
7682   return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
7683                                     CancelRegion);
7684 }
7685 
7686 static bool checkGrainsizeNumTasksClauses(Sema &S,
7687                                           ArrayRef<OMPClause *> Clauses) {
7688   const OMPClause *PrevClause = nullptr;
7689   bool ErrorFound = false;
7690   for (const OMPClause *C : Clauses) {
7691     if (C->getClauseKind() == OMPC_grainsize ||
7692         C->getClauseKind() == OMPC_num_tasks) {
7693       if (!PrevClause)
7694         PrevClause = C;
7695       else if (PrevClause->getClauseKind() != C->getClauseKind()) {
7696         S.Diag(C->getBeginLoc(),
7697                diag::err_omp_grainsize_num_tasks_mutually_exclusive)
7698             << getOpenMPClauseName(C->getClauseKind())
7699             << getOpenMPClauseName(PrevClause->getClauseKind());
7700         S.Diag(PrevClause->getBeginLoc(),
7701                diag::note_omp_previous_grainsize_num_tasks)
7702             << getOpenMPClauseName(PrevClause->getClauseKind());
7703         ErrorFound = true;
7704       }
7705     }
7706   }
7707   return ErrorFound;
7708 }
7709 
7710 static bool checkReductionClauseWithNogroup(Sema &S,
7711                                             ArrayRef<OMPClause *> Clauses) {
7712   const OMPClause *ReductionClause = nullptr;
7713   const OMPClause *NogroupClause = nullptr;
7714   for (const OMPClause *C : Clauses) {
7715     if (C->getClauseKind() == OMPC_reduction) {
7716       ReductionClause = C;
7717       if (NogroupClause)
7718         break;
7719       continue;
7720     }
7721     if (C->getClauseKind() == OMPC_nogroup) {
7722       NogroupClause = C;
7723       if (ReductionClause)
7724         break;
7725       continue;
7726     }
7727   }
7728   if (ReductionClause && NogroupClause) {
7729     S.Diag(ReductionClause->getBeginLoc(), diag::err_omp_reduction_with_nogroup)
7730         << SourceRange(NogroupClause->getBeginLoc(),
7731                        NogroupClause->getEndLoc());
7732     return true;
7733   }
7734   return false;
7735 }
7736 
7737 StmtResult Sema::ActOnOpenMPTaskLoopDirective(
7738     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7739     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
7740   if (!AStmt)
7741     return StmtError();
7742 
7743   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
7744   OMPLoopDirective::HelperExprs B;
7745   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7746   // define the nested loops number.
7747   unsigned NestedLoopCount =
7748       checkOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
7749                       /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
7750                       VarsWithImplicitDSA, B);
7751   if (NestedLoopCount == 0)
7752     return StmtError();
7753 
7754   assert((CurContext->isDependentContext() || B.builtAll()) &&
7755          "omp for loop exprs were not built");
7756 
7757   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
7758   // The grainsize clause and num_tasks clause are mutually exclusive and may
7759   // not appear on the same taskloop directive.
7760   if (checkGrainsizeNumTasksClauses(*this, Clauses))
7761     return StmtError();
7762   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
7763   // If a reduction clause is present on the taskloop directive, the nogroup
7764   // clause must not be specified.
7765   if (checkReductionClauseWithNogroup(*this, Clauses))
7766     return StmtError();
7767 
7768   setFunctionHasBranchProtectedScope();
7769   return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
7770                                       NestedLoopCount, Clauses, AStmt, B);
7771 }
7772 
7773 StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
7774     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7775     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
7776   if (!AStmt)
7777     return StmtError();
7778 
7779   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
7780   OMPLoopDirective::HelperExprs B;
7781   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7782   // define the nested loops number.
7783   unsigned NestedLoopCount =
7784       checkOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
7785                       /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
7786                       VarsWithImplicitDSA, B);
7787   if (NestedLoopCount == 0)
7788     return StmtError();
7789 
7790   assert((CurContext->isDependentContext() || B.builtAll()) &&
7791          "omp for loop exprs were not built");
7792 
7793   if (!CurContext->isDependentContext()) {
7794     // Finalize the clauses that need pre-built expressions for CodeGen.
7795     for (OMPClause *C : Clauses) {
7796       if (auto *LC = dyn_cast<OMPLinearClause>(C))
7797         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7798                                      B.NumIterations, *this, CurScope,
7799                                      DSAStack))
7800           return StmtError();
7801     }
7802   }
7803 
7804   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
7805   // The grainsize clause and num_tasks clause are mutually exclusive and may
7806   // not appear on the same taskloop directive.
7807   if (checkGrainsizeNumTasksClauses(*this, Clauses))
7808     return StmtError();
7809   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
7810   // If a reduction clause is present on the taskloop directive, the nogroup
7811   // clause must not be specified.
7812   if (checkReductionClauseWithNogroup(*this, Clauses))
7813     return StmtError();
7814   if (checkSimdlenSafelenSpecified(*this, Clauses))
7815     return StmtError();
7816 
7817   setFunctionHasBranchProtectedScope();
7818   return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
7819                                           NestedLoopCount, Clauses, AStmt, B);
7820 }
7821 
7822 StmtResult Sema::ActOnOpenMPDistributeDirective(
7823     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7824     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
7825   if (!AStmt)
7826     return StmtError();
7827 
7828   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
7829   OMPLoopDirective::HelperExprs B;
7830   // In presence of clause 'collapse' with number of loops, it will
7831   // define the nested loops number.
7832   unsigned NestedLoopCount =
7833       checkOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
7834                       nullptr /*ordered not a clause on distribute*/, AStmt,
7835                       *this, *DSAStack, VarsWithImplicitDSA, B);
7836   if (NestedLoopCount == 0)
7837     return StmtError();
7838 
7839   assert((CurContext->isDependentContext() || B.builtAll()) &&
7840          "omp for loop exprs were not built");
7841 
7842   setFunctionHasBranchProtectedScope();
7843   return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
7844                                         NestedLoopCount, Clauses, AStmt, B);
7845 }
7846 
7847 StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
7848     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7849     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
7850   if (!AStmt)
7851     return StmtError();
7852 
7853   auto *CS = cast<CapturedStmt>(AStmt);
7854   // 1.2.2 OpenMP Language Terminology
7855   // Structured block - An executable statement with a single entry at the
7856   // top and a single exit at the bottom.
7857   // The point of exit cannot be a branch out of the structured block.
7858   // longjmp() and throw() must not violate the entry/exit criteria.
7859   CS->getCapturedDecl()->setNothrow();
7860   for (int ThisCaptureLevel =
7861            getOpenMPCaptureLevels(OMPD_distribute_parallel_for);
7862        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7863     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7864     // 1.2.2 OpenMP Language Terminology
7865     // Structured block - An executable statement with a single entry at the
7866     // top and a single exit at the bottom.
7867     // The point of exit cannot be a branch out of the structured block.
7868     // longjmp() and throw() must not violate the entry/exit criteria.
7869     CS->getCapturedDecl()->setNothrow();
7870   }
7871 
7872   OMPLoopDirective::HelperExprs B;
7873   // In presence of clause 'collapse' with number of loops, it will
7874   // define the nested loops number.
7875   unsigned NestedLoopCount = checkOpenMPLoop(
7876       OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
7877       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
7878       VarsWithImplicitDSA, B);
7879   if (NestedLoopCount == 0)
7880     return StmtError();
7881 
7882   assert((CurContext->isDependentContext() || B.builtAll()) &&
7883          "omp for loop exprs were not built");
7884 
7885   setFunctionHasBranchProtectedScope();
7886   return OMPDistributeParallelForDirective::Create(
7887       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
7888       DSAStack->isCancelRegion());
7889 }
7890 
7891 StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
7892     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7893     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
7894   if (!AStmt)
7895     return StmtError();
7896 
7897   auto *CS = cast<CapturedStmt>(AStmt);
7898   // 1.2.2 OpenMP Language Terminology
7899   // Structured block - An executable statement with a single entry at the
7900   // top and a single exit at the bottom.
7901   // The point of exit cannot be a branch out of the structured block.
7902   // longjmp() and throw() must not violate the entry/exit criteria.
7903   CS->getCapturedDecl()->setNothrow();
7904   for (int ThisCaptureLevel =
7905            getOpenMPCaptureLevels(OMPD_distribute_parallel_for_simd);
7906        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7907     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7908     // 1.2.2 OpenMP Language Terminology
7909     // Structured block - An executable statement with a single entry at the
7910     // top and a single exit at the bottom.
7911     // The point of exit cannot be a branch out of the structured block.
7912     // longjmp() and throw() must not violate the entry/exit criteria.
7913     CS->getCapturedDecl()->setNothrow();
7914   }
7915 
7916   OMPLoopDirective::HelperExprs B;
7917   // In presence of clause 'collapse' with number of loops, it will
7918   // define the nested loops number.
7919   unsigned NestedLoopCount = checkOpenMPLoop(
7920       OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
7921       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
7922       VarsWithImplicitDSA, B);
7923   if (NestedLoopCount == 0)
7924     return StmtError();
7925 
7926   assert((CurContext->isDependentContext() || B.builtAll()) &&
7927          "omp for loop exprs were not built");
7928 
7929   if (!CurContext->isDependentContext()) {
7930     // Finalize the clauses that need pre-built expressions for CodeGen.
7931     for (OMPClause *C : Clauses) {
7932       if (auto *LC = dyn_cast<OMPLinearClause>(C))
7933         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7934                                      B.NumIterations, *this, CurScope,
7935                                      DSAStack))
7936           return StmtError();
7937     }
7938   }
7939 
7940   if (checkSimdlenSafelenSpecified(*this, Clauses))
7941     return StmtError();
7942 
7943   setFunctionHasBranchProtectedScope();
7944   return OMPDistributeParallelForSimdDirective::Create(
7945       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7946 }
7947 
7948 StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
7949     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7950     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
7951   if (!AStmt)
7952     return StmtError();
7953 
7954   auto *CS = cast<CapturedStmt>(AStmt);
7955   // 1.2.2 OpenMP Language Terminology
7956   // Structured block - An executable statement with a single entry at the
7957   // top and a single exit at the bottom.
7958   // The point of exit cannot be a branch out of the structured block.
7959   // longjmp() and throw() must not violate the entry/exit criteria.
7960   CS->getCapturedDecl()->setNothrow();
7961   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_distribute_simd);
7962        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7963     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7964     // 1.2.2 OpenMP Language Terminology
7965     // Structured block - An executable statement with a single entry at the
7966     // top and a single exit at the bottom.
7967     // The point of exit cannot be a branch out of the structured block.
7968     // longjmp() and throw() must not violate the entry/exit criteria.
7969     CS->getCapturedDecl()->setNothrow();
7970   }
7971 
7972   OMPLoopDirective::HelperExprs B;
7973   // In presence of clause 'collapse' with number of loops, it will
7974   // define the nested loops number.
7975   unsigned NestedLoopCount =
7976       checkOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
7977                       nullptr /*ordered not a clause on distribute*/, CS, *this,
7978                       *DSAStack, VarsWithImplicitDSA, B);
7979   if (NestedLoopCount == 0)
7980     return StmtError();
7981 
7982   assert((CurContext->isDependentContext() || B.builtAll()) &&
7983          "omp for loop exprs were not built");
7984 
7985   if (!CurContext->isDependentContext()) {
7986     // Finalize the clauses that need pre-built expressions for CodeGen.
7987     for (OMPClause *C : Clauses) {
7988       if (auto *LC = dyn_cast<OMPLinearClause>(C))
7989         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7990                                      B.NumIterations, *this, CurScope,
7991                                      DSAStack))
7992           return StmtError();
7993     }
7994   }
7995 
7996   if (checkSimdlenSafelenSpecified(*this, Clauses))
7997     return StmtError();
7998 
7999   setFunctionHasBranchProtectedScope();
8000   return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
8001                                             NestedLoopCount, Clauses, AStmt, B);
8002 }
8003 
8004 StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
8005     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8006     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
8007   if (!AStmt)
8008     return StmtError();
8009 
8010   auto *CS = cast<CapturedStmt>(AStmt);
8011   // 1.2.2 OpenMP Language Terminology
8012   // Structured block - An executable statement with a single entry at the
8013   // top and a single exit at the bottom.
8014   // The point of exit cannot be a branch out of the structured block.
8015   // longjmp() and throw() must not violate the entry/exit criteria.
8016   CS->getCapturedDecl()->setNothrow();
8017   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
8018        ThisCaptureLevel > 1; --ThisCaptureLevel) {
8019     CS = cast<CapturedStmt>(CS->getCapturedStmt());
8020     // 1.2.2 OpenMP Language Terminology
8021     // Structured block - An executable statement with a single entry at the
8022     // top and a single exit at the bottom.
8023     // The point of exit cannot be a branch out of the structured block.
8024     // longjmp() and throw() must not violate the entry/exit criteria.
8025     CS->getCapturedDecl()->setNothrow();
8026   }
8027 
8028   OMPLoopDirective::HelperExprs B;
8029   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
8030   // define the nested loops number.
8031   unsigned NestedLoopCount = checkOpenMPLoop(
8032       OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
8033       getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
8034       VarsWithImplicitDSA, B);
8035   if (NestedLoopCount == 0)
8036     return StmtError();
8037 
8038   assert((CurContext->isDependentContext() || B.builtAll()) &&
8039          "omp target parallel for simd loop exprs were not built");
8040 
8041   if (!CurContext->isDependentContext()) {
8042     // Finalize the clauses that need pre-built expressions for CodeGen.
8043     for (OMPClause *C : Clauses) {
8044       if (auto *LC = dyn_cast<OMPLinearClause>(C))
8045         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8046                                      B.NumIterations, *this, CurScope,
8047                                      DSAStack))
8048           return StmtError();
8049     }
8050   }
8051   if (checkSimdlenSafelenSpecified(*this, Clauses))
8052     return StmtError();
8053 
8054   setFunctionHasBranchProtectedScope();
8055   return OMPTargetParallelForSimdDirective::Create(
8056       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8057 }
8058 
8059 StmtResult Sema::ActOnOpenMPTargetSimdDirective(
8060     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8061     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
8062   if (!AStmt)
8063     return StmtError();
8064 
8065   auto *CS = cast<CapturedStmt>(AStmt);
8066   // 1.2.2 OpenMP Language Terminology
8067   // Structured block - An executable statement with a single entry at the
8068   // top and a single exit at the bottom.
8069   // The point of exit cannot be a branch out of the structured block.
8070   // longjmp() and throw() must not violate the entry/exit criteria.
8071   CS->getCapturedDecl()->setNothrow();
8072   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_simd);
8073        ThisCaptureLevel > 1; --ThisCaptureLevel) {
8074     CS = cast<CapturedStmt>(CS->getCapturedStmt());
8075     // 1.2.2 OpenMP Language Terminology
8076     // Structured block - An executable statement with a single entry at the
8077     // top and a single exit at the bottom.
8078     // The point of exit cannot be a branch out of the structured block.
8079     // longjmp() and throw() must not violate the entry/exit criteria.
8080     CS->getCapturedDecl()->setNothrow();
8081   }
8082 
8083   OMPLoopDirective::HelperExprs B;
8084   // In presence of clause 'collapse' with number of loops, it will define the
8085   // nested loops number.
8086   unsigned NestedLoopCount =
8087       checkOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
8088                       getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
8089                       VarsWithImplicitDSA, B);
8090   if (NestedLoopCount == 0)
8091     return StmtError();
8092 
8093   assert((CurContext->isDependentContext() || B.builtAll()) &&
8094          "omp target simd loop exprs were not built");
8095 
8096   if (!CurContext->isDependentContext()) {
8097     // Finalize the clauses that need pre-built expressions for CodeGen.
8098     for (OMPClause *C : Clauses) {
8099       if (auto *LC = dyn_cast<OMPLinearClause>(C))
8100         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8101                                      B.NumIterations, *this, CurScope,
8102                                      DSAStack))
8103           return StmtError();
8104     }
8105   }
8106 
8107   if (checkSimdlenSafelenSpecified(*this, Clauses))
8108     return StmtError();
8109 
8110   setFunctionHasBranchProtectedScope();
8111   return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
8112                                         NestedLoopCount, Clauses, AStmt, B);
8113 }
8114 
8115 StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
8116     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8117     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
8118   if (!AStmt)
8119     return StmtError();
8120 
8121   auto *CS = cast<CapturedStmt>(AStmt);
8122   // 1.2.2 OpenMP Language Terminology
8123   // Structured block - An executable statement with a single entry at the
8124   // top and a single exit at the bottom.
8125   // The point of exit cannot be a branch out of the structured block.
8126   // longjmp() and throw() must not violate the entry/exit criteria.
8127   CS->getCapturedDecl()->setNothrow();
8128   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_teams_distribute);
8129        ThisCaptureLevel > 1; --ThisCaptureLevel) {
8130     CS = cast<CapturedStmt>(CS->getCapturedStmt());
8131     // 1.2.2 OpenMP Language Terminology
8132     // Structured block - An executable statement with a single entry at the
8133     // top and a single exit at the bottom.
8134     // The point of exit cannot be a branch out of the structured block.
8135     // longjmp() and throw() must not violate the entry/exit criteria.
8136     CS->getCapturedDecl()->setNothrow();
8137   }
8138 
8139   OMPLoopDirective::HelperExprs B;
8140   // In presence of clause 'collapse' with number of loops, it will
8141   // define the nested loops number.
8142   unsigned NestedLoopCount =
8143       checkOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
8144                       nullptr /*ordered not a clause on distribute*/, CS, *this,
8145                       *DSAStack, VarsWithImplicitDSA, B);
8146   if (NestedLoopCount == 0)
8147     return StmtError();
8148 
8149   assert((CurContext->isDependentContext() || B.builtAll()) &&
8150          "omp teams distribute loop exprs were not built");
8151 
8152   setFunctionHasBranchProtectedScope();
8153 
8154   DSAStack->setParentTeamsRegionLoc(StartLoc);
8155 
8156   return OMPTeamsDistributeDirective::Create(
8157       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8158 }
8159 
8160 StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
8161     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8162     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
8163   if (!AStmt)
8164     return StmtError();
8165 
8166   auto *CS = cast<CapturedStmt>(AStmt);
8167   // 1.2.2 OpenMP Language Terminology
8168   // Structured block - An executable statement with a single entry at the
8169   // top and a single exit at the bottom.
8170   // The point of exit cannot be a branch out of the structured block.
8171   // longjmp() and throw() must not violate the entry/exit criteria.
8172   CS->getCapturedDecl()->setNothrow();
8173   for (int ThisCaptureLevel =
8174            getOpenMPCaptureLevels(OMPD_teams_distribute_simd);
8175        ThisCaptureLevel > 1; --ThisCaptureLevel) {
8176     CS = cast<CapturedStmt>(CS->getCapturedStmt());
8177     // 1.2.2 OpenMP Language Terminology
8178     // Structured block - An executable statement with a single entry at the
8179     // top and a single exit at the bottom.
8180     // The point of exit cannot be a branch out of the structured block.
8181     // longjmp() and throw() must not violate the entry/exit criteria.
8182     CS->getCapturedDecl()->setNothrow();
8183   }
8184 
8185 
8186   OMPLoopDirective::HelperExprs B;
8187   // In presence of clause 'collapse' with number of loops, it will
8188   // define the nested loops number.
8189   unsigned NestedLoopCount = checkOpenMPLoop(
8190       OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
8191       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
8192       VarsWithImplicitDSA, B);
8193 
8194   if (NestedLoopCount == 0)
8195     return StmtError();
8196 
8197   assert((CurContext->isDependentContext() || B.builtAll()) &&
8198          "omp teams distribute simd loop exprs were not built");
8199 
8200   if (!CurContext->isDependentContext()) {
8201     // Finalize the clauses that need pre-built expressions for CodeGen.
8202     for (OMPClause *C : Clauses) {
8203       if (auto *LC = dyn_cast<OMPLinearClause>(C))
8204         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8205                                      B.NumIterations, *this, CurScope,
8206                                      DSAStack))
8207           return StmtError();
8208     }
8209   }
8210 
8211   if (checkSimdlenSafelenSpecified(*this, Clauses))
8212     return StmtError();
8213 
8214   setFunctionHasBranchProtectedScope();
8215 
8216   DSAStack->setParentTeamsRegionLoc(StartLoc);
8217 
8218   return OMPTeamsDistributeSimdDirective::Create(
8219       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8220 }
8221 
8222 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
8223     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8224     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
8225   if (!AStmt)
8226     return StmtError();
8227 
8228   auto *CS = cast<CapturedStmt>(AStmt);
8229   // 1.2.2 OpenMP Language Terminology
8230   // Structured block - An executable statement with a single entry at the
8231   // top and a single exit at the bottom.
8232   // The point of exit cannot be a branch out of the structured block.
8233   // longjmp() and throw() must not violate the entry/exit criteria.
8234   CS->getCapturedDecl()->setNothrow();
8235 
8236   for (int ThisCaptureLevel =
8237            getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for_simd);
8238        ThisCaptureLevel > 1; --ThisCaptureLevel) {
8239     CS = cast<CapturedStmt>(CS->getCapturedStmt());
8240     // 1.2.2 OpenMP Language Terminology
8241     // Structured block - An executable statement with a single entry at the
8242     // top and a single exit at the bottom.
8243     // The point of exit cannot be a branch out of the structured block.
8244     // longjmp() and throw() must not violate the entry/exit criteria.
8245     CS->getCapturedDecl()->setNothrow();
8246   }
8247 
8248   OMPLoopDirective::HelperExprs B;
8249   // In presence of clause 'collapse' with number of loops, it will
8250   // define the nested loops number.
8251   unsigned NestedLoopCount = checkOpenMPLoop(
8252       OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
8253       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
8254       VarsWithImplicitDSA, B);
8255 
8256   if (NestedLoopCount == 0)
8257     return StmtError();
8258 
8259   assert((CurContext->isDependentContext() || B.builtAll()) &&
8260          "omp for loop exprs were not built");
8261 
8262   if (!CurContext->isDependentContext()) {
8263     // Finalize the clauses that need pre-built expressions for CodeGen.
8264     for (OMPClause *C : Clauses) {
8265       if (auto *LC = dyn_cast<OMPLinearClause>(C))
8266         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8267                                      B.NumIterations, *this, CurScope,
8268                                      DSAStack))
8269           return StmtError();
8270     }
8271   }
8272 
8273   if (checkSimdlenSafelenSpecified(*this, Clauses))
8274     return StmtError();
8275 
8276   setFunctionHasBranchProtectedScope();
8277 
8278   DSAStack->setParentTeamsRegionLoc(StartLoc);
8279 
8280   return OMPTeamsDistributeParallelForSimdDirective::Create(
8281       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8282 }
8283 
8284 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
8285     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8286     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
8287   if (!AStmt)
8288     return StmtError();
8289 
8290   auto *CS = cast<CapturedStmt>(AStmt);
8291   // 1.2.2 OpenMP Language Terminology
8292   // Structured block - An executable statement with a single entry at the
8293   // top and a single exit at the bottom.
8294   // The point of exit cannot be a branch out of the structured block.
8295   // longjmp() and throw() must not violate the entry/exit criteria.
8296   CS->getCapturedDecl()->setNothrow();
8297 
8298   for (int ThisCaptureLevel =
8299            getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for);
8300        ThisCaptureLevel > 1; --ThisCaptureLevel) {
8301     CS = cast<CapturedStmt>(CS->getCapturedStmt());
8302     // 1.2.2 OpenMP Language Terminology
8303     // Structured block - An executable statement with a single entry at the
8304     // top and a single exit at the bottom.
8305     // The point of exit cannot be a branch out of the structured block.
8306     // longjmp() and throw() must not violate the entry/exit criteria.
8307     CS->getCapturedDecl()->setNothrow();
8308   }
8309 
8310   OMPLoopDirective::HelperExprs B;
8311   // In presence of clause 'collapse' with number of loops, it will
8312   // define the nested loops number.
8313   unsigned NestedLoopCount = checkOpenMPLoop(
8314       OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
8315       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
8316       VarsWithImplicitDSA, B);
8317 
8318   if (NestedLoopCount == 0)
8319     return StmtError();
8320 
8321   assert((CurContext->isDependentContext() || B.builtAll()) &&
8322          "omp for loop exprs were not built");
8323 
8324   setFunctionHasBranchProtectedScope();
8325 
8326   DSAStack->setParentTeamsRegionLoc(StartLoc);
8327 
8328   return OMPTeamsDistributeParallelForDirective::Create(
8329       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
8330       DSAStack->isCancelRegion());
8331 }
8332 
8333 StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
8334                                                  Stmt *AStmt,
8335                                                  SourceLocation StartLoc,
8336                                                  SourceLocation EndLoc) {
8337   if (!AStmt)
8338     return StmtError();
8339 
8340   auto *CS = cast<CapturedStmt>(AStmt);
8341   // 1.2.2 OpenMP Language Terminology
8342   // Structured block - An executable statement with a single entry at the
8343   // top and a single exit at the bottom.
8344   // The point of exit cannot be a branch out of the structured block.
8345   // longjmp() and throw() must not violate the entry/exit criteria.
8346   CS->getCapturedDecl()->setNothrow();
8347 
8348   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams);
8349        ThisCaptureLevel > 1; --ThisCaptureLevel) {
8350     CS = cast<CapturedStmt>(CS->getCapturedStmt());
8351     // 1.2.2 OpenMP Language Terminology
8352     // Structured block - An executable statement with a single entry at the
8353     // top and a single exit at the bottom.
8354     // The point of exit cannot be a branch out of the structured block.
8355     // longjmp() and throw() must not violate the entry/exit criteria.
8356     CS->getCapturedDecl()->setNothrow();
8357   }
8358   setFunctionHasBranchProtectedScope();
8359 
8360   return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
8361                                          AStmt);
8362 }
8363 
8364 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
8365     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8366     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
8367   if (!AStmt)
8368     return StmtError();
8369 
8370   auto *CS = cast<CapturedStmt>(AStmt);
8371   // 1.2.2 OpenMP Language Terminology
8372   // Structured block - An executable statement with a single entry at the
8373   // top and a single exit at the bottom.
8374   // The point of exit cannot be a branch out of the structured block.
8375   // longjmp() and throw() must not violate the entry/exit criteria.
8376   CS->getCapturedDecl()->setNothrow();
8377   for (int ThisCaptureLevel =
8378            getOpenMPCaptureLevels(OMPD_target_teams_distribute);
8379        ThisCaptureLevel > 1; --ThisCaptureLevel) {
8380     CS = cast<CapturedStmt>(CS->getCapturedStmt());
8381     // 1.2.2 OpenMP Language Terminology
8382     // Structured block - An executable statement with a single entry at the
8383     // top and a single exit at the bottom.
8384     // The point of exit cannot be a branch out of the structured block.
8385     // longjmp() and throw() must not violate the entry/exit criteria.
8386     CS->getCapturedDecl()->setNothrow();
8387   }
8388 
8389   OMPLoopDirective::HelperExprs B;
8390   // In presence of clause 'collapse' with number of loops, it will
8391   // define the nested loops number.
8392   unsigned NestedLoopCount = checkOpenMPLoop(
8393       OMPD_target_teams_distribute, getCollapseNumberExpr(Clauses),
8394       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
8395       VarsWithImplicitDSA, B);
8396   if (NestedLoopCount == 0)
8397     return StmtError();
8398 
8399   assert((CurContext->isDependentContext() || B.builtAll()) &&
8400          "omp target teams distribute loop exprs were not built");
8401 
8402   setFunctionHasBranchProtectedScope();
8403   return OMPTargetTeamsDistributeDirective::Create(
8404       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8405 }
8406 
8407 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
8408     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8409     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
8410   if (!AStmt)
8411     return StmtError();
8412 
8413   auto *CS = cast<CapturedStmt>(AStmt);
8414   // 1.2.2 OpenMP Language Terminology
8415   // Structured block - An executable statement with a single entry at the
8416   // top and a single exit at the bottom.
8417   // The point of exit cannot be a branch out of the structured block.
8418   // longjmp() and throw() must not violate the entry/exit criteria.
8419   CS->getCapturedDecl()->setNothrow();
8420   for (int ThisCaptureLevel =
8421            getOpenMPCaptureLevels(OMPD_target_teams_distribute_parallel_for);
8422        ThisCaptureLevel > 1; --ThisCaptureLevel) {
8423     CS = cast<CapturedStmt>(CS->getCapturedStmt());
8424     // 1.2.2 OpenMP Language Terminology
8425     // Structured block - An executable statement with a single entry at the
8426     // top and a single exit at the bottom.
8427     // The point of exit cannot be a branch out of the structured block.
8428     // longjmp() and throw() must not violate the entry/exit criteria.
8429     CS->getCapturedDecl()->setNothrow();
8430   }
8431 
8432   OMPLoopDirective::HelperExprs B;
8433   // In presence of clause 'collapse' with number of loops, it will
8434   // define the nested loops number.
8435   unsigned NestedLoopCount = checkOpenMPLoop(
8436       OMPD_target_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
8437       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
8438       VarsWithImplicitDSA, B);
8439   if (NestedLoopCount == 0)
8440     return StmtError();
8441 
8442   assert((CurContext->isDependentContext() || B.builtAll()) &&
8443          "omp target teams distribute parallel for loop exprs were not built");
8444 
8445   if (!CurContext->isDependentContext()) {
8446     // Finalize the clauses that need pre-built expressions for CodeGen.
8447     for (OMPClause *C : Clauses) {
8448       if (auto *LC = dyn_cast<OMPLinearClause>(C))
8449         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8450                                      B.NumIterations, *this, CurScope,
8451                                      DSAStack))
8452           return StmtError();
8453     }
8454   }
8455 
8456   setFunctionHasBranchProtectedScope();
8457   return OMPTargetTeamsDistributeParallelForDirective::Create(
8458       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
8459       DSAStack->isCancelRegion());
8460 }
8461 
8462 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
8463     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8464     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
8465   if (!AStmt)
8466     return StmtError();
8467 
8468   auto *CS = cast<CapturedStmt>(AStmt);
8469   // 1.2.2 OpenMP Language Terminology
8470   // Structured block - An executable statement with a single entry at the
8471   // top and a single exit at the bottom.
8472   // The point of exit cannot be a branch out of the structured block.
8473   // longjmp() and throw() must not violate the entry/exit criteria.
8474   CS->getCapturedDecl()->setNothrow();
8475   for (int ThisCaptureLevel = getOpenMPCaptureLevels(
8476            OMPD_target_teams_distribute_parallel_for_simd);
8477        ThisCaptureLevel > 1; --ThisCaptureLevel) {
8478     CS = cast<CapturedStmt>(CS->getCapturedStmt());
8479     // 1.2.2 OpenMP Language Terminology
8480     // Structured block - An executable statement with a single entry at the
8481     // top and a single exit at the bottom.
8482     // The point of exit cannot be a branch out of the structured block.
8483     // longjmp() and throw() must not violate the entry/exit criteria.
8484     CS->getCapturedDecl()->setNothrow();
8485   }
8486 
8487   OMPLoopDirective::HelperExprs B;
8488   // In presence of clause 'collapse' with number of loops, it will
8489   // define the nested loops number.
8490   unsigned NestedLoopCount =
8491       checkOpenMPLoop(OMPD_target_teams_distribute_parallel_for_simd,
8492                       getCollapseNumberExpr(Clauses),
8493                       nullptr /*ordered not a clause on distribute*/, CS, *this,
8494                       *DSAStack, VarsWithImplicitDSA, B);
8495   if (NestedLoopCount == 0)
8496     return StmtError();
8497 
8498   assert((CurContext->isDependentContext() || B.builtAll()) &&
8499          "omp target teams distribute parallel for simd loop exprs were not "
8500          "built");
8501 
8502   if (!CurContext->isDependentContext()) {
8503     // Finalize the clauses that need pre-built expressions for CodeGen.
8504     for (OMPClause *C : Clauses) {
8505       if (auto *LC = dyn_cast<OMPLinearClause>(C))
8506         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8507                                      B.NumIterations, *this, CurScope,
8508                                      DSAStack))
8509           return StmtError();
8510     }
8511   }
8512 
8513   if (checkSimdlenSafelenSpecified(*this, Clauses))
8514     return StmtError();
8515 
8516   setFunctionHasBranchProtectedScope();
8517   return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
8518       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8519 }
8520 
8521 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
8522     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8523     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
8524   if (!AStmt)
8525     return StmtError();
8526 
8527   auto *CS = cast<CapturedStmt>(AStmt);
8528   // 1.2.2 OpenMP Language Terminology
8529   // Structured block - An executable statement with a single entry at the
8530   // top and a single exit at the bottom.
8531   // The point of exit cannot be a branch out of the structured block.
8532   // longjmp() and throw() must not violate the entry/exit criteria.
8533   CS->getCapturedDecl()->setNothrow();
8534   for (int ThisCaptureLevel =
8535            getOpenMPCaptureLevels(OMPD_target_teams_distribute_simd);
8536        ThisCaptureLevel > 1; --ThisCaptureLevel) {
8537     CS = cast<CapturedStmt>(CS->getCapturedStmt());
8538     // 1.2.2 OpenMP Language Terminology
8539     // Structured block - An executable statement with a single entry at the
8540     // top and a single exit at the bottom.
8541     // The point of exit cannot be a branch out of the structured block.
8542     // longjmp() and throw() must not violate the entry/exit criteria.
8543     CS->getCapturedDecl()->setNothrow();
8544   }
8545 
8546   OMPLoopDirective::HelperExprs B;
8547   // In presence of clause 'collapse' with number of loops, it will
8548   // define the nested loops number.
8549   unsigned NestedLoopCount = checkOpenMPLoop(
8550       OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
8551       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
8552       VarsWithImplicitDSA, B);
8553   if (NestedLoopCount == 0)
8554     return StmtError();
8555 
8556   assert((CurContext->isDependentContext() || B.builtAll()) &&
8557          "omp target teams distribute simd loop exprs were not built");
8558 
8559   if (!CurContext->isDependentContext()) {
8560     // Finalize the clauses that need pre-built expressions for CodeGen.
8561     for (OMPClause *C : Clauses) {
8562       if (auto *LC = dyn_cast<OMPLinearClause>(C))
8563         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8564                                      B.NumIterations, *this, CurScope,
8565                                      DSAStack))
8566           return StmtError();
8567     }
8568   }
8569 
8570   if (checkSimdlenSafelenSpecified(*this, Clauses))
8571     return StmtError();
8572 
8573   setFunctionHasBranchProtectedScope();
8574   return OMPTargetTeamsDistributeSimdDirective::Create(
8575       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8576 }
8577 
8578 OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
8579                                              SourceLocation StartLoc,
8580                                              SourceLocation LParenLoc,
8581                                              SourceLocation EndLoc) {
8582   OMPClause *Res = nullptr;
8583   switch (Kind) {
8584   case OMPC_final:
8585     Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
8586     break;
8587   case OMPC_num_threads:
8588     Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
8589     break;
8590   case OMPC_safelen:
8591     Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
8592     break;
8593   case OMPC_simdlen:
8594     Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
8595     break;
8596   case OMPC_allocator:
8597     Res = ActOnOpenMPAllocatorClause(Expr, StartLoc, LParenLoc, EndLoc);
8598     break;
8599   case OMPC_collapse:
8600     Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
8601     break;
8602   case OMPC_ordered:
8603     Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
8604     break;
8605   case OMPC_device:
8606     Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
8607     break;
8608   case OMPC_num_teams:
8609     Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
8610     break;
8611   case OMPC_thread_limit:
8612     Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
8613     break;
8614   case OMPC_priority:
8615     Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
8616     break;
8617   case OMPC_grainsize:
8618     Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
8619     break;
8620   case OMPC_num_tasks:
8621     Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
8622     break;
8623   case OMPC_hint:
8624     Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
8625     break;
8626   case OMPC_if:
8627   case OMPC_default:
8628   case OMPC_proc_bind:
8629   case OMPC_schedule:
8630   case OMPC_private:
8631   case OMPC_firstprivate:
8632   case OMPC_lastprivate:
8633   case OMPC_shared:
8634   case OMPC_reduction:
8635   case OMPC_task_reduction:
8636   case OMPC_in_reduction:
8637   case OMPC_linear:
8638   case OMPC_aligned:
8639   case OMPC_copyin:
8640   case OMPC_copyprivate:
8641   case OMPC_nowait:
8642   case OMPC_untied:
8643   case OMPC_mergeable:
8644   case OMPC_threadprivate:
8645   case OMPC_allocate:
8646   case OMPC_flush:
8647   case OMPC_read:
8648   case OMPC_write:
8649   case OMPC_update:
8650   case OMPC_capture:
8651   case OMPC_seq_cst:
8652   case OMPC_depend:
8653   case OMPC_threads:
8654   case OMPC_simd:
8655   case OMPC_map:
8656   case OMPC_nogroup:
8657   case OMPC_dist_schedule:
8658   case OMPC_defaultmap:
8659   case OMPC_unknown:
8660   case OMPC_uniform:
8661   case OMPC_to:
8662   case OMPC_from:
8663   case OMPC_use_device_ptr:
8664   case OMPC_is_device_ptr:
8665   case OMPC_unified_address:
8666   case OMPC_unified_shared_memory:
8667   case OMPC_reverse_offload:
8668   case OMPC_dynamic_allocators:
8669   case OMPC_atomic_default_mem_order:
8670     llvm_unreachable("Clause is not allowed.");
8671   }
8672   return Res;
8673 }
8674 
8675 // An OpenMP directive such as 'target parallel' has two captured regions:
8676 // for the 'target' and 'parallel' respectively.  This function returns
8677 // the region in which to capture expressions associated with a clause.
8678 // A return value of OMPD_unknown signifies that the expression should not
8679 // be captured.
8680 static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
8681     OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
8682     OpenMPDirectiveKind NameModifier = OMPD_unknown) {
8683   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
8684   switch (CKind) {
8685   case OMPC_if:
8686     switch (DKind) {
8687     case OMPD_target_parallel:
8688     case OMPD_target_parallel_for:
8689     case OMPD_target_parallel_for_simd:
8690       // If this clause applies to the nested 'parallel' region, capture within
8691       // the 'target' region, otherwise do not capture.
8692       if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
8693         CaptureRegion = OMPD_target;
8694       break;
8695     case OMPD_target_teams_distribute_parallel_for:
8696     case OMPD_target_teams_distribute_parallel_for_simd:
8697       // If this clause applies to the nested 'parallel' region, capture within
8698       // the 'teams' region, otherwise do not capture.
8699       if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
8700         CaptureRegion = OMPD_teams;
8701       break;
8702     case OMPD_teams_distribute_parallel_for:
8703     case OMPD_teams_distribute_parallel_for_simd:
8704       CaptureRegion = OMPD_teams;
8705       break;
8706     case OMPD_target_update:
8707     case OMPD_target_enter_data:
8708     case OMPD_target_exit_data:
8709       CaptureRegion = OMPD_task;
8710       break;
8711     case OMPD_cancel:
8712     case OMPD_parallel:
8713     case OMPD_parallel_sections:
8714     case OMPD_parallel_for:
8715     case OMPD_parallel_for_simd:
8716     case OMPD_target:
8717     case OMPD_target_simd:
8718     case OMPD_target_teams:
8719     case OMPD_target_teams_distribute:
8720     case OMPD_target_teams_distribute_simd:
8721     case OMPD_distribute_parallel_for:
8722     case OMPD_distribute_parallel_for_simd:
8723     case OMPD_task:
8724     case OMPD_taskloop:
8725     case OMPD_taskloop_simd:
8726     case OMPD_target_data:
8727       // Do not capture if-clause expressions.
8728       break;
8729     case OMPD_threadprivate:
8730     case OMPD_allocate:
8731     case OMPD_taskyield:
8732     case OMPD_barrier:
8733     case OMPD_taskwait:
8734     case OMPD_cancellation_point:
8735     case OMPD_flush:
8736     case OMPD_declare_reduction:
8737     case OMPD_declare_mapper:
8738     case OMPD_declare_simd:
8739     case OMPD_declare_target:
8740     case OMPD_end_declare_target:
8741     case OMPD_teams:
8742     case OMPD_simd:
8743     case OMPD_for:
8744     case OMPD_for_simd:
8745     case OMPD_sections:
8746     case OMPD_section:
8747     case OMPD_single:
8748     case OMPD_master:
8749     case OMPD_critical:
8750     case OMPD_taskgroup:
8751     case OMPD_distribute:
8752     case OMPD_ordered:
8753     case OMPD_atomic:
8754     case OMPD_distribute_simd:
8755     case OMPD_teams_distribute:
8756     case OMPD_teams_distribute_simd:
8757     case OMPD_requires:
8758       llvm_unreachable("Unexpected OpenMP directive with if-clause");
8759     case OMPD_unknown:
8760       llvm_unreachable("Unknown OpenMP directive");
8761     }
8762     break;
8763   case OMPC_num_threads:
8764     switch (DKind) {
8765     case OMPD_target_parallel:
8766     case OMPD_target_parallel_for:
8767     case OMPD_target_parallel_for_simd:
8768       CaptureRegion = OMPD_target;
8769       break;
8770     case OMPD_teams_distribute_parallel_for:
8771     case OMPD_teams_distribute_parallel_for_simd:
8772     case OMPD_target_teams_distribute_parallel_for:
8773     case OMPD_target_teams_distribute_parallel_for_simd:
8774       CaptureRegion = OMPD_teams;
8775       break;
8776     case OMPD_parallel:
8777     case OMPD_parallel_sections:
8778     case OMPD_parallel_for:
8779     case OMPD_parallel_for_simd:
8780     case OMPD_distribute_parallel_for:
8781     case OMPD_distribute_parallel_for_simd:
8782       // Do not capture num_threads-clause expressions.
8783       break;
8784     case OMPD_target_data:
8785     case OMPD_target_enter_data:
8786     case OMPD_target_exit_data:
8787     case OMPD_target_update:
8788     case OMPD_target:
8789     case OMPD_target_simd:
8790     case OMPD_target_teams:
8791     case OMPD_target_teams_distribute:
8792     case OMPD_target_teams_distribute_simd:
8793     case OMPD_cancel:
8794     case OMPD_task:
8795     case OMPD_taskloop:
8796     case OMPD_taskloop_simd:
8797     case OMPD_threadprivate:
8798     case OMPD_allocate:
8799     case OMPD_taskyield:
8800     case OMPD_barrier:
8801     case OMPD_taskwait:
8802     case OMPD_cancellation_point:
8803     case OMPD_flush:
8804     case OMPD_declare_reduction:
8805     case OMPD_declare_mapper:
8806     case OMPD_declare_simd:
8807     case OMPD_declare_target:
8808     case OMPD_end_declare_target:
8809     case OMPD_teams:
8810     case OMPD_simd:
8811     case OMPD_for:
8812     case OMPD_for_simd:
8813     case OMPD_sections:
8814     case OMPD_section:
8815     case OMPD_single:
8816     case OMPD_master:
8817     case OMPD_critical:
8818     case OMPD_taskgroup:
8819     case OMPD_distribute:
8820     case OMPD_ordered:
8821     case OMPD_atomic:
8822     case OMPD_distribute_simd:
8823     case OMPD_teams_distribute:
8824     case OMPD_teams_distribute_simd:
8825     case OMPD_requires:
8826       llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
8827     case OMPD_unknown:
8828       llvm_unreachable("Unknown OpenMP directive");
8829     }
8830     break;
8831   case OMPC_num_teams:
8832     switch (DKind) {
8833     case OMPD_target_teams:
8834     case OMPD_target_teams_distribute:
8835     case OMPD_target_teams_distribute_simd:
8836     case OMPD_target_teams_distribute_parallel_for:
8837     case OMPD_target_teams_distribute_parallel_for_simd:
8838       CaptureRegion = OMPD_target;
8839       break;
8840     case OMPD_teams_distribute_parallel_for:
8841     case OMPD_teams_distribute_parallel_for_simd:
8842     case OMPD_teams:
8843     case OMPD_teams_distribute:
8844     case OMPD_teams_distribute_simd:
8845       // Do not capture num_teams-clause expressions.
8846       break;
8847     case OMPD_distribute_parallel_for:
8848     case OMPD_distribute_parallel_for_simd:
8849     case OMPD_task:
8850     case OMPD_taskloop:
8851     case OMPD_taskloop_simd:
8852     case OMPD_target_data:
8853     case OMPD_target_enter_data:
8854     case OMPD_target_exit_data:
8855     case OMPD_target_update:
8856     case OMPD_cancel:
8857     case OMPD_parallel:
8858     case OMPD_parallel_sections:
8859     case OMPD_parallel_for:
8860     case OMPD_parallel_for_simd:
8861     case OMPD_target:
8862     case OMPD_target_simd:
8863     case OMPD_target_parallel:
8864     case OMPD_target_parallel_for:
8865     case OMPD_target_parallel_for_simd:
8866     case OMPD_threadprivate:
8867     case OMPD_allocate:
8868     case OMPD_taskyield:
8869     case OMPD_barrier:
8870     case OMPD_taskwait:
8871     case OMPD_cancellation_point:
8872     case OMPD_flush:
8873     case OMPD_declare_reduction:
8874     case OMPD_declare_mapper:
8875     case OMPD_declare_simd:
8876     case OMPD_declare_target:
8877     case OMPD_end_declare_target:
8878     case OMPD_simd:
8879     case OMPD_for:
8880     case OMPD_for_simd:
8881     case OMPD_sections:
8882     case OMPD_section:
8883     case OMPD_single:
8884     case OMPD_master:
8885     case OMPD_critical:
8886     case OMPD_taskgroup:
8887     case OMPD_distribute:
8888     case OMPD_ordered:
8889     case OMPD_atomic:
8890     case OMPD_distribute_simd:
8891     case OMPD_requires:
8892       llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
8893     case OMPD_unknown:
8894       llvm_unreachable("Unknown OpenMP directive");
8895     }
8896     break;
8897   case OMPC_thread_limit:
8898     switch (DKind) {
8899     case OMPD_target_teams:
8900     case OMPD_target_teams_distribute:
8901     case OMPD_target_teams_distribute_simd:
8902     case OMPD_target_teams_distribute_parallel_for:
8903     case OMPD_target_teams_distribute_parallel_for_simd:
8904       CaptureRegion = OMPD_target;
8905       break;
8906     case OMPD_teams_distribute_parallel_for:
8907     case OMPD_teams_distribute_parallel_for_simd:
8908     case OMPD_teams:
8909     case OMPD_teams_distribute:
8910     case OMPD_teams_distribute_simd:
8911       // Do not capture thread_limit-clause expressions.
8912       break;
8913     case OMPD_distribute_parallel_for:
8914     case OMPD_distribute_parallel_for_simd:
8915     case OMPD_task:
8916     case OMPD_taskloop:
8917     case OMPD_taskloop_simd:
8918     case OMPD_target_data:
8919     case OMPD_target_enter_data:
8920     case OMPD_target_exit_data:
8921     case OMPD_target_update:
8922     case OMPD_cancel:
8923     case OMPD_parallel:
8924     case OMPD_parallel_sections:
8925     case OMPD_parallel_for:
8926     case OMPD_parallel_for_simd:
8927     case OMPD_target:
8928     case OMPD_target_simd:
8929     case OMPD_target_parallel:
8930     case OMPD_target_parallel_for:
8931     case OMPD_target_parallel_for_simd:
8932     case OMPD_threadprivate:
8933     case OMPD_allocate:
8934     case OMPD_taskyield:
8935     case OMPD_barrier:
8936     case OMPD_taskwait:
8937     case OMPD_cancellation_point:
8938     case OMPD_flush:
8939     case OMPD_declare_reduction:
8940     case OMPD_declare_mapper:
8941     case OMPD_declare_simd:
8942     case OMPD_declare_target:
8943     case OMPD_end_declare_target:
8944     case OMPD_simd:
8945     case OMPD_for:
8946     case OMPD_for_simd:
8947     case OMPD_sections:
8948     case OMPD_section:
8949     case OMPD_single:
8950     case OMPD_master:
8951     case OMPD_critical:
8952     case OMPD_taskgroup:
8953     case OMPD_distribute:
8954     case OMPD_ordered:
8955     case OMPD_atomic:
8956     case OMPD_distribute_simd:
8957     case OMPD_requires:
8958       llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
8959     case OMPD_unknown:
8960       llvm_unreachable("Unknown OpenMP directive");
8961     }
8962     break;
8963   case OMPC_schedule:
8964     switch (DKind) {
8965     case OMPD_parallel_for:
8966     case OMPD_parallel_for_simd:
8967     case OMPD_distribute_parallel_for:
8968     case OMPD_distribute_parallel_for_simd:
8969     case OMPD_teams_distribute_parallel_for:
8970     case OMPD_teams_distribute_parallel_for_simd:
8971     case OMPD_target_parallel_for:
8972     case OMPD_target_parallel_for_simd:
8973     case OMPD_target_teams_distribute_parallel_for:
8974     case OMPD_target_teams_distribute_parallel_for_simd:
8975       CaptureRegion = OMPD_parallel;
8976       break;
8977     case OMPD_for:
8978     case OMPD_for_simd:
8979       // Do not capture schedule-clause expressions.
8980       break;
8981     case OMPD_task:
8982     case OMPD_taskloop:
8983     case OMPD_taskloop_simd:
8984     case OMPD_target_data:
8985     case OMPD_target_enter_data:
8986     case OMPD_target_exit_data:
8987     case OMPD_target_update:
8988     case OMPD_teams:
8989     case OMPD_teams_distribute:
8990     case OMPD_teams_distribute_simd:
8991     case OMPD_target_teams_distribute:
8992     case OMPD_target_teams_distribute_simd:
8993     case OMPD_target:
8994     case OMPD_target_simd:
8995     case OMPD_target_parallel:
8996     case OMPD_cancel:
8997     case OMPD_parallel:
8998     case OMPD_parallel_sections:
8999     case OMPD_threadprivate:
9000     case OMPD_allocate:
9001     case OMPD_taskyield:
9002     case OMPD_barrier:
9003     case OMPD_taskwait:
9004     case OMPD_cancellation_point:
9005     case OMPD_flush:
9006     case OMPD_declare_reduction:
9007     case OMPD_declare_mapper:
9008     case OMPD_declare_simd:
9009     case OMPD_declare_target:
9010     case OMPD_end_declare_target:
9011     case OMPD_simd:
9012     case OMPD_sections:
9013     case OMPD_section:
9014     case OMPD_single:
9015     case OMPD_master:
9016     case OMPD_critical:
9017     case OMPD_taskgroup:
9018     case OMPD_distribute:
9019     case OMPD_ordered:
9020     case OMPD_atomic:
9021     case OMPD_distribute_simd:
9022     case OMPD_target_teams:
9023     case OMPD_requires:
9024       llvm_unreachable("Unexpected OpenMP directive with schedule clause");
9025     case OMPD_unknown:
9026       llvm_unreachable("Unknown OpenMP directive");
9027     }
9028     break;
9029   case OMPC_dist_schedule:
9030     switch (DKind) {
9031     case OMPD_teams_distribute_parallel_for:
9032     case OMPD_teams_distribute_parallel_for_simd:
9033     case OMPD_teams_distribute:
9034     case OMPD_teams_distribute_simd:
9035     case OMPD_target_teams_distribute_parallel_for:
9036     case OMPD_target_teams_distribute_parallel_for_simd:
9037     case OMPD_target_teams_distribute:
9038     case OMPD_target_teams_distribute_simd:
9039       CaptureRegion = OMPD_teams;
9040       break;
9041     case OMPD_distribute_parallel_for:
9042     case OMPD_distribute_parallel_for_simd:
9043     case OMPD_distribute:
9044     case OMPD_distribute_simd:
9045       // Do not capture thread_limit-clause expressions.
9046       break;
9047     case OMPD_parallel_for:
9048     case OMPD_parallel_for_simd:
9049     case OMPD_target_parallel_for_simd:
9050     case OMPD_target_parallel_for:
9051     case OMPD_task:
9052     case OMPD_taskloop:
9053     case OMPD_taskloop_simd:
9054     case OMPD_target_data:
9055     case OMPD_target_enter_data:
9056     case OMPD_target_exit_data:
9057     case OMPD_target_update:
9058     case OMPD_teams:
9059     case OMPD_target:
9060     case OMPD_target_simd:
9061     case OMPD_target_parallel:
9062     case OMPD_cancel:
9063     case OMPD_parallel:
9064     case OMPD_parallel_sections:
9065     case OMPD_threadprivate:
9066     case OMPD_allocate:
9067     case OMPD_taskyield:
9068     case OMPD_barrier:
9069     case OMPD_taskwait:
9070     case OMPD_cancellation_point:
9071     case OMPD_flush:
9072     case OMPD_declare_reduction:
9073     case OMPD_declare_mapper:
9074     case OMPD_declare_simd:
9075     case OMPD_declare_target:
9076     case OMPD_end_declare_target:
9077     case OMPD_simd:
9078     case OMPD_for:
9079     case OMPD_for_simd:
9080     case OMPD_sections:
9081     case OMPD_section:
9082     case OMPD_single:
9083     case OMPD_master:
9084     case OMPD_critical:
9085     case OMPD_taskgroup:
9086     case OMPD_ordered:
9087     case OMPD_atomic:
9088     case OMPD_target_teams:
9089     case OMPD_requires:
9090       llvm_unreachable("Unexpected OpenMP directive with schedule clause");
9091     case OMPD_unknown:
9092       llvm_unreachable("Unknown OpenMP directive");
9093     }
9094     break;
9095   case OMPC_device:
9096     switch (DKind) {
9097     case OMPD_target_update:
9098     case OMPD_target_enter_data:
9099     case OMPD_target_exit_data:
9100     case OMPD_target:
9101     case OMPD_target_simd:
9102     case OMPD_target_teams:
9103     case OMPD_target_parallel:
9104     case OMPD_target_teams_distribute:
9105     case OMPD_target_teams_distribute_simd:
9106     case OMPD_target_parallel_for:
9107     case OMPD_target_parallel_for_simd:
9108     case OMPD_target_teams_distribute_parallel_for:
9109     case OMPD_target_teams_distribute_parallel_for_simd:
9110       CaptureRegion = OMPD_task;
9111       break;
9112     case OMPD_target_data:
9113       // Do not capture device-clause expressions.
9114       break;
9115     case OMPD_teams_distribute_parallel_for:
9116     case OMPD_teams_distribute_parallel_for_simd:
9117     case OMPD_teams:
9118     case OMPD_teams_distribute:
9119     case OMPD_teams_distribute_simd:
9120     case OMPD_distribute_parallel_for:
9121     case OMPD_distribute_parallel_for_simd:
9122     case OMPD_task:
9123     case OMPD_taskloop:
9124     case OMPD_taskloop_simd:
9125     case OMPD_cancel:
9126     case OMPD_parallel:
9127     case OMPD_parallel_sections:
9128     case OMPD_parallel_for:
9129     case OMPD_parallel_for_simd:
9130     case OMPD_threadprivate:
9131     case OMPD_allocate:
9132     case OMPD_taskyield:
9133     case OMPD_barrier:
9134     case OMPD_taskwait:
9135     case OMPD_cancellation_point:
9136     case OMPD_flush:
9137     case OMPD_declare_reduction:
9138     case OMPD_declare_mapper:
9139     case OMPD_declare_simd:
9140     case OMPD_declare_target:
9141     case OMPD_end_declare_target:
9142     case OMPD_simd:
9143     case OMPD_for:
9144     case OMPD_for_simd:
9145     case OMPD_sections:
9146     case OMPD_section:
9147     case OMPD_single:
9148     case OMPD_master:
9149     case OMPD_critical:
9150     case OMPD_taskgroup:
9151     case OMPD_distribute:
9152     case OMPD_ordered:
9153     case OMPD_atomic:
9154     case OMPD_distribute_simd:
9155     case OMPD_requires:
9156       llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
9157     case OMPD_unknown:
9158       llvm_unreachable("Unknown OpenMP directive");
9159     }
9160     break;
9161   case OMPC_firstprivate:
9162   case OMPC_lastprivate:
9163   case OMPC_reduction:
9164   case OMPC_task_reduction:
9165   case OMPC_in_reduction:
9166   case OMPC_linear:
9167   case OMPC_default:
9168   case OMPC_proc_bind:
9169   case OMPC_final:
9170   case OMPC_safelen:
9171   case OMPC_simdlen:
9172   case OMPC_allocator:
9173   case OMPC_collapse:
9174   case OMPC_private:
9175   case OMPC_shared:
9176   case OMPC_aligned:
9177   case OMPC_copyin:
9178   case OMPC_copyprivate:
9179   case OMPC_ordered:
9180   case OMPC_nowait:
9181   case OMPC_untied:
9182   case OMPC_mergeable:
9183   case OMPC_threadprivate:
9184   case OMPC_allocate:
9185   case OMPC_flush:
9186   case OMPC_read:
9187   case OMPC_write:
9188   case OMPC_update:
9189   case OMPC_capture:
9190   case OMPC_seq_cst:
9191   case OMPC_depend:
9192   case OMPC_threads:
9193   case OMPC_simd:
9194   case OMPC_map:
9195   case OMPC_priority:
9196   case OMPC_grainsize:
9197   case OMPC_nogroup:
9198   case OMPC_num_tasks:
9199   case OMPC_hint:
9200   case OMPC_defaultmap:
9201   case OMPC_unknown:
9202   case OMPC_uniform:
9203   case OMPC_to:
9204   case OMPC_from:
9205   case OMPC_use_device_ptr:
9206   case OMPC_is_device_ptr:
9207   case OMPC_unified_address:
9208   case OMPC_unified_shared_memory:
9209   case OMPC_reverse_offload:
9210   case OMPC_dynamic_allocators:
9211   case OMPC_atomic_default_mem_order:
9212     llvm_unreachable("Unexpected OpenMP clause.");
9213   }
9214   return CaptureRegion;
9215 }
9216 
9217 OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
9218                                      Expr *Condition, SourceLocation StartLoc,
9219                                      SourceLocation LParenLoc,
9220                                      SourceLocation NameModifierLoc,
9221                                      SourceLocation ColonLoc,
9222                                      SourceLocation EndLoc) {
9223   Expr *ValExpr = Condition;
9224   Stmt *HelperValStmt = nullptr;
9225   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
9226   if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
9227       !Condition->isInstantiationDependent() &&
9228       !Condition->containsUnexpandedParameterPack()) {
9229     ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
9230     if (Val.isInvalid())
9231       return nullptr;
9232 
9233     ValExpr = Val.get();
9234 
9235     OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
9236     CaptureRegion =
9237         getOpenMPCaptureRegionForClause(DKind, OMPC_if, NameModifier);
9238     if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
9239       ValExpr = MakeFullExpr(ValExpr).get();
9240       llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
9241       ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
9242       HelperValStmt = buildPreInits(Context, Captures);
9243     }
9244   }
9245 
9246   return new (Context)
9247       OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
9248                   LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
9249 }
9250 
9251 OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
9252                                         SourceLocation StartLoc,
9253                                         SourceLocation LParenLoc,
9254                                         SourceLocation EndLoc) {
9255   Expr *ValExpr = Condition;
9256   if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
9257       !Condition->isInstantiationDependent() &&
9258       !Condition->containsUnexpandedParameterPack()) {
9259     ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
9260     if (Val.isInvalid())
9261       return nullptr;
9262 
9263     ValExpr = MakeFullExpr(Val.get()).get();
9264   }
9265 
9266   return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
9267 }
9268 ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
9269                                                         Expr *Op) {
9270   if (!Op)
9271     return ExprError();
9272 
9273   class IntConvertDiagnoser : public ICEConvertDiagnoser {
9274   public:
9275     IntConvertDiagnoser()
9276         : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
9277     SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
9278                                          QualType T) override {
9279       return S.Diag(Loc, diag::err_omp_not_integral) << T;
9280     }
9281     SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
9282                                              QualType T) override {
9283       return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
9284     }
9285     SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
9286                                                QualType T,
9287                                                QualType ConvTy) override {
9288       return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
9289     }
9290     SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
9291                                            QualType ConvTy) override {
9292       return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
9293              << ConvTy->isEnumeralType() << ConvTy;
9294     }
9295     SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
9296                                             QualType T) override {
9297       return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
9298     }
9299     SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
9300                                         QualType ConvTy) override {
9301       return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
9302              << ConvTy->isEnumeralType() << ConvTy;
9303     }
9304     SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
9305                                              QualType) override {
9306       llvm_unreachable("conversion functions are permitted");
9307     }
9308   } ConvertDiagnoser;
9309   return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
9310 }
9311 
9312 static bool isNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
9313                                       OpenMPClauseKind CKind,
9314                                       bool StrictlyPositive) {
9315   if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
9316       !ValExpr->isInstantiationDependent()) {
9317     SourceLocation Loc = ValExpr->getExprLoc();
9318     ExprResult Value =
9319         SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
9320     if (Value.isInvalid())
9321       return false;
9322 
9323     ValExpr = Value.get();
9324     // The expression must evaluate to a non-negative integer value.
9325     llvm::APSInt Result;
9326     if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
9327         Result.isSigned() &&
9328         !((!StrictlyPositive && Result.isNonNegative()) ||
9329           (StrictlyPositive && Result.isStrictlyPositive()))) {
9330       SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
9331           << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
9332           << ValExpr->getSourceRange();
9333       return false;
9334     }
9335   }
9336   return true;
9337 }
9338 
9339 OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
9340                                              SourceLocation StartLoc,
9341                                              SourceLocation LParenLoc,
9342                                              SourceLocation EndLoc) {
9343   Expr *ValExpr = NumThreads;
9344   Stmt *HelperValStmt = nullptr;
9345 
9346   // OpenMP [2.5, Restrictions]
9347   //  The num_threads expression must evaluate to a positive integer value.
9348   if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
9349                                  /*StrictlyPositive=*/true))
9350     return nullptr;
9351 
9352   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
9353   OpenMPDirectiveKind CaptureRegion =
9354       getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads);
9355   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
9356     ValExpr = MakeFullExpr(ValExpr).get();
9357     llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
9358     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
9359     HelperValStmt = buildPreInits(Context, Captures);
9360   }
9361 
9362   return new (Context) OMPNumThreadsClause(
9363       ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
9364 }
9365 
9366 ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
9367                                                        OpenMPClauseKind CKind,
9368                                                        bool StrictlyPositive) {
9369   if (!E)
9370     return ExprError();
9371   if (E->isValueDependent() || E->isTypeDependent() ||
9372       E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
9373     return E;
9374   llvm::APSInt Result;
9375   ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
9376   if (ICE.isInvalid())
9377     return ExprError();
9378   if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
9379       (!StrictlyPositive && !Result.isNonNegative())) {
9380     Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
9381         << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
9382         << E->getSourceRange();
9383     return ExprError();
9384   }
9385   if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
9386     Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
9387         << E->getSourceRange();
9388     return ExprError();
9389   }
9390   if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
9391     DSAStack->setAssociatedLoops(Result.getExtValue());
9392   else if (CKind == OMPC_ordered)
9393     DSAStack->setAssociatedLoops(Result.getExtValue());
9394   return ICE;
9395 }
9396 
9397 OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
9398                                           SourceLocation LParenLoc,
9399                                           SourceLocation EndLoc) {
9400   // OpenMP [2.8.1, simd construct, Description]
9401   // The parameter of the safelen clause must be a constant
9402   // positive integer expression.
9403   ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
9404   if (Safelen.isInvalid())
9405     return nullptr;
9406   return new (Context)
9407       OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
9408 }
9409 
9410 OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
9411                                           SourceLocation LParenLoc,
9412                                           SourceLocation EndLoc) {
9413   // OpenMP [2.8.1, simd construct, Description]
9414   // The parameter of the simdlen clause must be a constant
9415   // positive integer expression.
9416   ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
9417   if (Simdlen.isInvalid())
9418     return nullptr;
9419   return new (Context)
9420       OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
9421 }
9422 
9423 /// Tries to find omp_allocator_handle_t type.
9424 static bool findOMPAllocatorHandleT(Sema &S, SourceLocation Loc,
9425                                     DSAStackTy *Stack) {
9426   QualType OMPAllocatorHandleT = Stack->getOMPAllocatorHandleT();
9427   if (!OMPAllocatorHandleT.isNull())
9428     return true;
9429   // Build the predefined allocator expressions.
9430   bool ErrorFound = false;
9431   for (int I = OMPAllocateDeclAttr::OMPDefaultMemAlloc;
9432        I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
9433     auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
9434     StringRef Allocator =
9435         OMPAllocateDeclAttr::ConvertAllocatorTypeTyToStr(AllocatorKind);
9436     DeclarationName AllocatorName = &S.getASTContext().Idents.get(Allocator);
9437     auto *VD = dyn_cast_or_null<ValueDecl>(
9438         S.LookupSingleName(S.TUScope, AllocatorName, Loc, Sema::LookupAnyName));
9439     if (!VD) {
9440       ErrorFound = true;
9441       break;
9442     }
9443     QualType AllocatorType =
9444         VD->getType().getNonLValueExprType(S.getASTContext());
9445     ExprResult Res = S.BuildDeclRefExpr(VD, AllocatorType, VK_LValue, Loc);
9446     if (!Res.isUsable()) {
9447       ErrorFound = true;
9448       break;
9449     }
9450     if (OMPAllocatorHandleT.isNull())
9451       OMPAllocatorHandleT = AllocatorType;
9452     if (!S.getASTContext().hasSameType(OMPAllocatorHandleT, AllocatorType)) {
9453       ErrorFound = true;
9454       break;
9455     }
9456     Stack->setAllocator(AllocatorKind, Res.get());
9457   }
9458   if (ErrorFound) {
9459     S.Diag(Loc, diag::err_implied_omp_allocator_handle_t_not_found);
9460     return false;
9461   }
9462   OMPAllocatorHandleT.addConst();
9463   Stack->setOMPAllocatorHandleT(OMPAllocatorHandleT);
9464   return true;
9465 }
9466 
9467 OMPClause *Sema::ActOnOpenMPAllocatorClause(Expr *A, SourceLocation StartLoc,
9468                                             SourceLocation LParenLoc,
9469                                             SourceLocation EndLoc) {
9470   // OpenMP [2.11.3, allocate Directive, Description]
9471   // allocator is an expression of omp_allocator_handle_t type.
9472   if (!findOMPAllocatorHandleT(*this, A->getExprLoc(), DSAStack))
9473     return nullptr;
9474 
9475   ExprResult Allocator = DefaultLvalueConversion(A);
9476   if (Allocator.isInvalid())
9477     return nullptr;
9478   Allocator = PerformImplicitConversion(Allocator.get(),
9479                                         DSAStack->getOMPAllocatorHandleT(),
9480                                         Sema::AA_Initializing,
9481                                         /*AllowExplicit=*/true);
9482   if (Allocator.isInvalid())
9483     return nullptr;
9484   return new (Context)
9485       OMPAllocatorClause(Allocator.get(), StartLoc, LParenLoc, EndLoc);
9486 }
9487 
9488 OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
9489                                            SourceLocation StartLoc,
9490                                            SourceLocation LParenLoc,
9491                                            SourceLocation EndLoc) {
9492   // OpenMP [2.7.1, loop construct, Description]
9493   // OpenMP [2.8.1, simd construct, Description]
9494   // OpenMP [2.9.6, distribute construct, Description]
9495   // The parameter of the collapse clause must be a constant
9496   // positive integer expression.
9497   ExprResult NumForLoopsResult =
9498       VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
9499   if (NumForLoopsResult.isInvalid())
9500     return nullptr;
9501   return new (Context)
9502       OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
9503 }
9504 
9505 OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
9506                                           SourceLocation EndLoc,
9507                                           SourceLocation LParenLoc,
9508                                           Expr *NumForLoops) {
9509   // OpenMP [2.7.1, loop construct, Description]
9510   // OpenMP [2.8.1, simd construct, Description]
9511   // OpenMP [2.9.6, distribute construct, Description]
9512   // The parameter of the ordered clause must be a constant
9513   // positive integer expression if any.
9514   if (NumForLoops && LParenLoc.isValid()) {
9515     ExprResult NumForLoopsResult =
9516         VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
9517     if (NumForLoopsResult.isInvalid())
9518       return nullptr;
9519     NumForLoops = NumForLoopsResult.get();
9520   } else {
9521     NumForLoops = nullptr;
9522   }
9523   auto *Clause = OMPOrderedClause::Create(
9524       Context, NumForLoops, NumForLoops ? DSAStack->getAssociatedLoops() : 0,
9525       StartLoc, LParenLoc, EndLoc);
9526   DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops, Clause);
9527   return Clause;
9528 }
9529 
9530 OMPClause *Sema::ActOnOpenMPSimpleClause(
9531     OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
9532     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
9533   OMPClause *Res = nullptr;
9534   switch (Kind) {
9535   case OMPC_default:
9536     Res =
9537         ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
9538                                  ArgumentLoc, StartLoc, LParenLoc, EndLoc);
9539     break;
9540   case OMPC_proc_bind:
9541     Res = ActOnOpenMPProcBindClause(
9542         static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
9543         LParenLoc, EndLoc);
9544     break;
9545   case OMPC_atomic_default_mem_order:
9546     Res = ActOnOpenMPAtomicDefaultMemOrderClause(
9547         static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Argument),
9548         ArgumentLoc, StartLoc, LParenLoc, EndLoc);
9549     break;
9550   case OMPC_if:
9551   case OMPC_final:
9552   case OMPC_num_threads:
9553   case OMPC_safelen:
9554   case OMPC_simdlen:
9555   case OMPC_allocator:
9556   case OMPC_collapse:
9557   case OMPC_schedule:
9558   case OMPC_private:
9559   case OMPC_firstprivate:
9560   case OMPC_lastprivate:
9561   case OMPC_shared:
9562   case OMPC_reduction:
9563   case OMPC_task_reduction:
9564   case OMPC_in_reduction:
9565   case OMPC_linear:
9566   case OMPC_aligned:
9567   case OMPC_copyin:
9568   case OMPC_copyprivate:
9569   case OMPC_ordered:
9570   case OMPC_nowait:
9571   case OMPC_untied:
9572   case OMPC_mergeable:
9573   case OMPC_threadprivate:
9574   case OMPC_allocate:
9575   case OMPC_flush:
9576   case OMPC_read:
9577   case OMPC_write:
9578   case OMPC_update:
9579   case OMPC_capture:
9580   case OMPC_seq_cst:
9581   case OMPC_depend:
9582   case OMPC_device:
9583   case OMPC_threads:
9584   case OMPC_simd:
9585   case OMPC_map:
9586   case OMPC_num_teams:
9587   case OMPC_thread_limit:
9588   case OMPC_priority:
9589   case OMPC_grainsize:
9590   case OMPC_nogroup:
9591   case OMPC_num_tasks:
9592   case OMPC_hint:
9593   case OMPC_dist_schedule:
9594   case OMPC_defaultmap:
9595   case OMPC_unknown:
9596   case OMPC_uniform:
9597   case OMPC_to:
9598   case OMPC_from:
9599   case OMPC_use_device_ptr:
9600   case OMPC_is_device_ptr:
9601   case OMPC_unified_address:
9602   case OMPC_unified_shared_memory:
9603   case OMPC_reverse_offload:
9604   case OMPC_dynamic_allocators:
9605     llvm_unreachable("Clause is not allowed.");
9606   }
9607   return Res;
9608 }
9609 
9610 static std::string
9611 getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
9612                         ArrayRef<unsigned> Exclude = llvm::None) {
9613   SmallString<256> Buffer;
9614   llvm::raw_svector_ostream Out(Buffer);
9615   unsigned Bound = Last >= 2 ? Last - 2 : 0;
9616   unsigned Skipped = Exclude.size();
9617   auto S = Exclude.begin(), E = Exclude.end();
9618   for (unsigned I = First; I < Last; ++I) {
9619     if (std::find(S, E, I) != E) {
9620       --Skipped;
9621       continue;
9622     }
9623     Out << "'" << getOpenMPSimpleClauseTypeName(K, I) << "'";
9624     if (I == Bound - Skipped)
9625       Out << " or ";
9626     else if (I != Bound + 1 - Skipped)
9627       Out << ", ";
9628   }
9629   return Out.str();
9630 }
9631 
9632 OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
9633                                           SourceLocation KindKwLoc,
9634                                           SourceLocation StartLoc,
9635                                           SourceLocation LParenLoc,
9636                                           SourceLocation EndLoc) {
9637   if (Kind == OMPC_DEFAULT_unknown) {
9638     static_assert(OMPC_DEFAULT_unknown > 0,
9639                   "OMPC_DEFAULT_unknown not greater than 0");
9640     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
9641         << getListOfPossibleValues(OMPC_default, /*First=*/0,
9642                                    /*Last=*/OMPC_DEFAULT_unknown)
9643         << getOpenMPClauseName(OMPC_default);
9644     return nullptr;
9645   }
9646   switch (Kind) {
9647   case OMPC_DEFAULT_none:
9648     DSAStack->setDefaultDSANone(KindKwLoc);
9649     break;
9650   case OMPC_DEFAULT_shared:
9651     DSAStack->setDefaultDSAShared(KindKwLoc);
9652     break;
9653   case OMPC_DEFAULT_unknown:
9654     llvm_unreachable("Clause kind is not allowed.");
9655     break;
9656   }
9657   return new (Context)
9658       OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
9659 }
9660 
9661 OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
9662                                            SourceLocation KindKwLoc,
9663                                            SourceLocation StartLoc,
9664                                            SourceLocation LParenLoc,
9665                                            SourceLocation EndLoc) {
9666   if (Kind == OMPC_PROC_BIND_unknown) {
9667     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
9668         << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
9669                                    /*Last=*/OMPC_PROC_BIND_unknown)
9670         << getOpenMPClauseName(OMPC_proc_bind);
9671     return nullptr;
9672   }
9673   return new (Context)
9674       OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
9675 }
9676 
9677 OMPClause *Sema::ActOnOpenMPAtomicDefaultMemOrderClause(
9678     OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindKwLoc,
9679     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
9680   if (Kind == OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown) {
9681     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
9682         << getListOfPossibleValues(
9683                OMPC_atomic_default_mem_order, /*First=*/0,
9684                /*Last=*/OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown)
9685         << getOpenMPClauseName(OMPC_atomic_default_mem_order);
9686     return nullptr;
9687   }
9688   return new (Context) OMPAtomicDefaultMemOrderClause(Kind, KindKwLoc, StartLoc,
9689                                                       LParenLoc, EndLoc);
9690 }
9691 
9692 OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
9693     OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
9694     SourceLocation StartLoc, SourceLocation LParenLoc,
9695     ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
9696     SourceLocation EndLoc) {
9697   OMPClause *Res = nullptr;
9698   switch (Kind) {
9699   case OMPC_schedule:
9700     enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
9701     assert(Argument.size() == NumberOfElements &&
9702            ArgumentLoc.size() == NumberOfElements);
9703     Res = ActOnOpenMPScheduleClause(
9704         static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
9705         static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
9706         static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
9707         StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
9708         ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
9709     break;
9710   case OMPC_if:
9711     assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
9712     Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
9713                               Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
9714                               DelimLoc, EndLoc);
9715     break;
9716   case OMPC_dist_schedule:
9717     Res = ActOnOpenMPDistScheduleClause(
9718         static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
9719         StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
9720     break;
9721   case OMPC_defaultmap:
9722     enum { Modifier, DefaultmapKind };
9723     Res = ActOnOpenMPDefaultmapClause(
9724         static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
9725         static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
9726         StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
9727         EndLoc);
9728     break;
9729   case OMPC_final:
9730   case OMPC_num_threads:
9731   case OMPC_safelen:
9732   case OMPC_simdlen:
9733   case OMPC_allocator:
9734   case OMPC_collapse:
9735   case OMPC_default:
9736   case OMPC_proc_bind:
9737   case OMPC_private:
9738   case OMPC_firstprivate:
9739   case OMPC_lastprivate:
9740   case OMPC_shared:
9741   case OMPC_reduction:
9742   case OMPC_task_reduction:
9743   case OMPC_in_reduction:
9744   case OMPC_linear:
9745   case OMPC_aligned:
9746   case OMPC_copyin:
9747   case OMPC_copyprivate:
9748   case OMPC_ordered:
9749   case OMPC_nowait:
9750   case OMPC_untied:
9751   case OMPC_mergeable:
9752   case OMPC_threadprivate:
9753   case OMPC_allocate:
9754   case OMPC_flush:
9755   case OMPC_read:
9756   case OMPC_write:
9757   case OMPC_update:
9758   case OMPC_capture:
9759   case OMPC_seq_cst:
9760   case OMPC_depend:
9761   case OMPC_device:
9762   case OMPC_threads:
9763   case OMPC_simd:
9764   case OMPC_map:
9765   case OMPC_num_teams:
9766   case OMPC_thread_limit:
9767   case OMPC_priority:
9768   case OMPC_grainsize:
9769   case OMPC_nogroup:
9770   case OMPC_num_tasks:
9771   case OMPC_hint:
9772   case OMPC_unknown:
9773   case OMPC_uniform:
9774   case OMPC_to:
9775   case OMPC_from:
9776   case OMPC_use_device_ptr:
9777   case OMPC_is_device_ptr:
9778   case OMPC_unified_address:
9779   case OMPC_unified_shared_memory:
9780   case OMPC_reverse_offload:
9781   case OMPC_dynamic_allocators:
9782   case OMPC_atomic_default_mem_order:
9783     llvm_unreachable("Clause is not allowed.");
9784   }
9785   return Res;
9786 }
9787 
9788 static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
9789                                    OpenMPScheduleClauseModifier M2,
9790                                    SourceLocation M1Loc, SourceLocation M2Loc) {
9791   if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
9792     SmallVector<unsigned, 2> Excluded;
9793     if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
9794       Excluded.push_back(M2);
9795     if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
9796       Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
9797     if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
9798       Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
9799     S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
9800         << getListOfPossibleValues(OMPC_schedule,
9801                                    /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
9802                                    /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
9803                                    Excluded)
9804         << getOpenMPClauseName(OMPC_schedule);
9805     return true;
9806   }
9807   return false;
9808 }
9809 
9810 OMPClause *Sema::ActOnOpenMPScheduleClause(
9811     OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
9812     OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
9813     SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
9814     SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
9815   if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
9816       checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
9817     return nullptr;
9818   // OpenMP, 2.7.1, Loop Construct, Restrictions
9819   // Either the monotonic modifier or the nonmonotonic modifier can be specified
9820   // but not both.
9821   if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
9822       (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
9823        M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
9824       (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
9825        M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
9826     Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
9827         << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
9828         << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
9829     return nullptr;
9830   }
9831   if (Kind == OMPC_SCHEDULE_unknown) {
9832     std::string Values;
9833     if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
9834       unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
9835       Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
9836                                        /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
9837                                        Exclude);
9838     } else {
9839       Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
9840                                        /*Last=*/OMPC_SCHEDULE_unknown);
9841     }
9842     Diag(KindLoc, diag::err_omp_unexpected_clause_value)
9843         << Values << getOpenMPClauseName(OMPC_schedule);
9844     return nullptr;
9845   }
9846   // OpenMP, 2.7.1, Loop Construct, Restrictions
9847   // The nonmonotonic modifier can only be specified with schedule(dynamic) or
9848   // schedule(guided).
9849   if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
9850        M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
9851       Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
9852     Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
9853          diag::err_omp_schedule_nonmonotonic_static);
9854     return nullptr;
9855   }
9856   Expr *ValExpr = ChunkSize;
9857   Stmt *HelperValStmt = nullptr;
9858   if (ChunkSize) {
9859     if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
9860         !ChunkSize->isInstantiationDependent() &&
9861         !ChunkSize->containsUnexpandedParameterPack()) {
9862       SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
9863       ExprResult Val =
9864           PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
9865       if (Val.isInvalid())
9866         return nullptr;
9867 
9868       ValExpr = Val.get();
9869 
9870       // OpenMP [2.7.1, Restrictions]
9871       //  chunk_size must be a loop invariant integer expression with a positive
9872       //  value.
9873       llvm::APSInt Result;
9874       if (ValExpr->isIntegerConstantExpr(Result, Context)) {
9875         if (Result.isSigned() && !Result.isStrictlyPositive()) {
9876           Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
9877               << "schedule" << 1 << ChunkSize->getSourceRange();
9878           return nullptr;
9879         }
9880       } else if (getOpenMPCaptureRegionForClause(
9881                      DSAStack->getCurrentDirective(), OMPC_schedule) !=
9882                      OMPD_unknown &&
9883                  !CurContext->isDependentContext()) {
9884         ValExpr = MakeFullExpr(ValExpr).get();
9885         llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
9886         ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
9887         HelperValStmt = buildPreInits(Context, Captures);
9888       }
9889     }
9890   }
9891 
9892   return new (Context)
9893       OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
9894                         ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
9895 }
9896 
9897 OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
9898                                    SourceLocation StartLoc,
9899                                    SourceLocation EndLoc) {
9900   OMPClause *Res = nullptr;
9901   switch (Kind) {
9902   case OMPC_ordered:
9903     Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
9904     break;
9905   case OMPC_nowait:
9906     Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
9907     break;
9908   case OMPC_untied:
9909     Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
9910     break;
9911   case OMPC_mergeable:
9912     Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
9913     break;
9914   case OMPC_read:
9915     Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
9916     break;
9917   case OMPC_write:
9918     Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
9919     break;
9920   case OMPC_update:
9921     Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
9922     break;
9923   case OMPC_capture:
9924     Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
9925     break;
9926   case OMPC_seq_cst:
9927     Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
9928     break;
9929   case OMPC_threads:
9930     Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
9931     break;
9932   case OMPC_simd:
9933     Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
9934     break;
9935   case OMPC_nogroup:
9936     Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
9937     break;
9938   case OMPC_unified_address:
9939     Res = ActOnOpenMPUnifiedAddressClause(StartLoc, EndLoc);
9940     break;
9941   case OMPC_unified_shared_memory:
9942     Res = ActOnOpenMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
9943     break;
9944   case OMPC_reverse_offload:
9945     Res = ActOnOpenMPReverseOffloadClause(StartLoc, EndLoc);
9946     break;
9947   case OMPC_dynamic_allocators:
9948     Res = ActOnOpenMPDynamicAllocatorsClause(StartLoc, EndLoc);
9949     break;
9950   case OMPC_if:
9951   case OMPC_final:
9952   case OMPC_num_threads:
9953   case OMPC_safelen:
9954   case OMPC_simdlen:
9955   case OMPC_allocator:
9956   case OMPC_collapse:
9957   case OMPC_schedule:
9958   case OMPC_private:
9959   case OMPC_firstprivate:
9960   case OMPC_lastprivate:
9961   case OMPC_shared:
9962   case OMPC_reduction:
9963   case OMPC_task_reduction:
9964   case OMPC_in_reduction:
9965   case OMPC_linear:
9966   case OMPC_aligned:
9967   case OMPC_copyin:
9968   case OMPC_copyprivate:
9969   case OMPC_default:
9970   case OMPC_proc_bind:
9971   case OMPC_threadprivate:
9972   case OMPC_allocate:
9973   case OMPC_flush:
9974   case OMPC_depend:
9975   case OMPC_device:
9976   case OMPC_map:
9977   case OMPC_num_teams:
9978   case OMPC_thread_limit:
9979   case OMPC_priority:
9980   case OMPC_grainsize:
9981   case OMPC_num_tasks:
9982   case OMPC_hint:
9983   case OMPC_dist_schedule:
9984   case OMPC_defaultmap:
9985   case OMPC_unknown:
9986   case OMPC_uniform:
9987   case OMPC_to:
9988   case OMPC_from:
9989   case OMPC_use_device_ptr:
9990   case OMPC_is_device_ptr:
9991   case OMPC_atomic_default_mem_order:
9992     llvm_unreachable("Clause is not allowed.");
9993   }
9994   return Res;
9995 }
9996 
9997 OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
9998                                          SourceLocation EndLoc) {
9999   DSAStack->setNowaitRegion();
10000   return new (Context) OMPNowaitClause(StartLoc, EndLoc);
10001 }
10002 
10003 OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
10004                                          SourceLocation EndLoc) {
10005   return new (Context) OMPUntiedClause(StartLoc, EndLoc);
10006 }
10007 
10008 OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
10009                                             SourceLocation EndLoc) {
10010   return new (Context) OMPMergeableClause(StartLoc, EndLoc);
10011 }
10012 
10013 OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
10014                                        SourceLocation EndLoc) {
10015   return new (Context) OMPReadClause(StartLoc, EndLoc);
10016 }
10017 
10018 OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
10019                                         SourceLocation EndLoc) {
10020   return new (Context) OMPWriteClause(StartLoc, EndLoc);
10021 }
10022 
10023 OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
10024                                          SourceLocation EndLoc) {
10025   return new (Context) OMPUpdateClause(StartLoc, EndLoc);
10026 }
10027 
10028 OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
10029                                           SourceLocation EndLoc) {
10030   return new (Context) OMPCaptureClause(StartLoc, EndLoc);
10031 }
10032 
10033 OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
10034                                          SourceLocation EndLoc) {
10035   return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
10036 }
10037 
10038 OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
10039                                           SourceLocation EndLoc) {
10040   return new (Context) OMPThreadsClause(StartLoc, EndLoc);
10041 }
10042 
10043 OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
10044                                        SourceLocation EndLoc) {
10045   return new (Context) OMPSIMDClause(StartLoc, EndLoc);
10046 }
10047 
10048 OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
10049                                           SourceLocation EndLoc) {
10050   return new (Context) OMPNogroupClause(StartLoc, EndLoc);
10051 }
10052 
10053 OMPClause *Sema::ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc,
10054                                                  SourceLocation EndLoc) {
10055   return new (Context) OMPUnifiedAddressClause(StartLoc, EndLoc);
10056 }
10057 
10058 OMPClause *Sema::ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc,
10059                                                       SourceLocation EndLoc) {
10060   return new (Context) OMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
10061 }
10062 
10063 OMPClause *Sema::ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc,
10064                                                  SourceLocation EndLoc) {
10065   return new (Context) OMPReverseOffloadClause(StartLoc, EndLoc);
10066 }
10067 
10068 OMPClause *Sema::ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc,
10069                                                     SourceLocation EndLoc) {
10070   return new (Context) OMPDynamicAllocatorsClause(StartLoc, EndLoc);
10071 }
10072 
10073 OMPClause *Sema::ActOnOpenMPVarListClause(
10074     OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
10075     const OMPVarListLocTy &Locs, SourceLocation ColonLoc,
10076     CXXScopeSpec &ReductionOrMapperIdScopeSpec,
10077     DeclarationNameInfo &ReductionOrMapperId, OpenMPDependClauseKind DepKind,
10078     OpenMPLinearClauseKind LinKind,
10079     ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
10080     ArrayRef<SourceLocation> MapTypeModifiersLoc, OpenMPMapClauseKind MapType,
10081     bool IsMapTypeImplicit, SourceLocation DepLinMapLoc) {
10082   SourceLocation StartLoc = Locs.StartLoc;
10083   SourceLocation LParenLoc = Locs.LParenLoc;
10084   SourceLocation EndLoc = Locs.EndLoc;
10085   OMPClause *Res = nullptr;
10086   switch (Kind) {
10087   case OMPC_private:
10088     Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
10089     break;
10090   case OMPC_firstprivate:
10091     Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
10092     break;
10093   case OMPC_lastprivate:
10094     Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
10095     break;
10096   case OMPC_shared:
10097     Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
10098     break;
10099   case OMPC_reduction:
10100     Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
10101                                      EndLoc, ReductionOrMapperIdScopeSpec,
10102                                      ReductionOrMapperId);
10103     break;
10104   case OMPC_task_reduction:
10105     Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
10106                                          EndLoc, ReductionOrMapperIdScopeSpec,
10107                                          ReductionOrMapperId);
10108     break;
10109   case OMPC_in_reduction:
10110     Res = ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
10111                                        EndLoc, ReductionOrMapperIdScopeSpec,
10112                                        ReductionOrMapperId);
10113     break;
10114   case OMPC_linear:
10115     Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
10116                                   LinKind, DepLinMapLoc, ColonLoc, EndLoc);
10117     break;
10118   case OMPC_aligned:
10119     Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
10120                                    ColonLoc, EndLoc);
10121     break;
10122   case OMPC_copyin:
10123     Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
10124     break;
10125   case OMPC_copyprivate:
10126     Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
10127     break;
10128   case OMPC_flush:
10129     Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
10130     break;
10131   case OMPC_depend:
10132     Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
10133                                   StartLoc, LParenLoc, EndLoc);
10134     break;
10135   case OMPC_map:
10136     Res = ActOnOpenMPMapClause(MapTypeModifiers, MapTypeModifiersLoc,
10137                                ReductionOrMapperIdScopeSpec,
10138                                ReductionOrMapperId, MapType, IsMapTypeImplicit,
10139                                DepLinMapLoc, ColonLoc, VarList, Locs);
10140     break;
10141   case OMPC_to:
10142     Res = ActOnOpenMPToClause(VarList, ReductionOrMapperIdScopeSpec,
10143                               ReductionOrMapperId, Locs);
10144     break;
10145   case OMPC_from:
10146     Res = ActOnOpenMPFromClause(VarList, ReductionOrMapperIdScopeSpec,
10147                                 ReductionOrMapperId, Locs);
10148     break;
10149   case OMPC_use_device_ptr:
10150     Res = ActOnOpenMPUseDevicePtrClause(VarList, Locs);
10151     break;
10152   case OMPC_is_device_ptr:
10153     Res = ActOnOpenMPIsDevicePtrClause(VarList, Locs);
10154     break;
10155   case OMPC_allocate:
10156     Res = ActOnOpenMPAllocateClause(TailExpr, VarList, StartLoc, LParenLoc,
10157                                     ColonLoc, EndLoc);
10158     break;
10159   case OMPC_if:
10160   case OMPC_final:
10161   case OMPC_num_threads:
10162   case OMPC_safelen:
10163   case OMPC_simdlen:
10164   case OMPC_allocator:
10165   case OMPC_collapse:
10166   case OMPC_default:
10167   case OMPC_proc_bind:
10168   case OMPC_schedule:
10169   case OMPC_ordered:
10170   case OMPC_nowait:
10171   case OMPC_untied:
10172   case OMPC_mergeable:
10173   case OMPC_threadprivate:
10174   case OMPC_read:
10175   case OMPC_write:
10176   case OMPC_update:
10177   case OMPC_capture:
10178   case OMPC_seq_cst:
10179   case OMPC_device:
10180   case OMPC_threads:
10181   case OMPC_simd:
10182   case OMPC_num_teams:
10183   case OMPC_thread_limit:
10184   case OMPC_priority:
10185   case OMPC_grainsize:
10186   case OMPC_nogroup:
10187   case OMPC_num_tasks:
10188   case OMPC_hint:
10189   case OMPC_dist_schedule:
10190   case OMPC_defaultmap:
10191   case OMPC_unknown:
10192   case OMPC_uniform:
10193   case OMPC_unified_address:
10194   case OMPC_unified_shared_memory:
10195   case OMPC_reverse_offload:
10196   case OMPC_dynamic_allocators:
10197   case OMPC_atomic_default_mem_order:
10198     llvm_unreachable("Clause is not allowed.");
10199   }
10200   return Res;
10201 }
10202 
10203 ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
10204                                        ExprObjectKind OK, SourceLocation Loc) {
10205   ExprResult Res = BuildDeclRefExpr(
10206       Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
10207   if (!Res.isUsable())
10208     return ExprError();
10209   if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
10210     Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
10211     if (!Res.isUsable())
10212       return ExprError();
10213   }
10214   if (VK != VK_LValue && Res.get()->isGLValue()) {
10215     Res = DefaultLvalueConversion(Res.get());
10216     if (!Res.isUsable())
10217       return ExprError();
10218   }
10219   return Res;
10220 }
10221 
10222 static std::pair<ValueDecl *, bool>
10223 getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
10224                SourceRange &ERange, bool AllowArraySection = false) {
10225   if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
10226       RefExpr->containsUnexpandedParameterPack())
10227     return std::make_pair(nullptr, true);
10228 
10229   // OpenMP [3.1, C/C++]
10230   //  A list item is a variable name.
10231   // OpenMP  [2.9.3.3, Restrictions, p.1]
10232   //  A variable that is part of another variable (as an array or
10233   //  structure element) cannot appear in a private clause.
10234   RefExpr = RefExpr->IgnoreParens();
10235   enum {
10236     NoArrayExpr = -1,
10237     ArraySubscript = 0,
10238     OMPArraySection = 1
10239   } IsArrayExpr = NoArrayExpr;
10240   if (AllowArraySection) {
10241     if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
10242       Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
10243       while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
10244         Base = TempASE->getBase()->IgnoreParenImpCasts();
10245       RefExpr = Base;
10246       IsArrayExpr = ArraySubscript;
10247     } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
10248       Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
10249       while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
10250         Base = TempOASE->getBase()->IgnoreParenImpCasts();
10251       while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
10252         Base = TempASE->getBase()->IgnoreParenImpCasts();
10253       RefExpr = Base;
10254       IsArrayExpr = OMPArraySection;
10255     }
10256   }
10257   ELoc = RefExpr->getExprLoc();
10258   ERange = RefExpr->getSourceRange();
10259   RefExpr = RefExpr->IgnoreParenImpCasts();
10260   auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
10261   auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
10262   if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
10263       (S.getCurrentThisType().isNull() || !ME ||
10264        !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
10265        !isa<FieldDecl>(ME->getMemberDecl()))) {
10266     if (IsArrayExpr != NoArrayExpr) {
10267       S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
10268                                                          << ERange;
10269     } else {
10270       S.Diag(ELoc,
10271              AllowArraySection
10272                  ? diag::err_omp_expected_var_name_member_expr_or_array_item
10273                  : diag::err_omp_expected_var_name_member_expr)
10274           << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
10275     }
10276     return std::make_pair(nullptr, false);
10277   }
10278   return std::make_pair(
10279       getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false);
10280 }
10281 
10282 OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
10283                                           SourceLocation StartLoc,
10284                                           SourceLocation LParenLoc,
10285                                           SourceLocation EndLoc) {
10286   SmallVector<Expr *, 8> Vars;
10287   SmallVector<Expr *, 8> PrivateCopies;
10288   for (Expr *RefExpr : VarList) {
10289     assert(RefExpr && "NULL expr in OpenMP private clause.");
10290     SourceLocation ELoc;
10291     SourceRange ERange;
10292     Expr *SimpleRefExpr = RefExpr;
10293     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
10294     if (Res.second) {
10295       // It will be analyzed later.
10296       Vars.push_back(RefExpr);
10297       PrivateCopies.push_back(nullptr);
10298     }
10299     ValueDecl *D = Res.first;
10300     if (!D)
10301       continue;
10302 
10303     QualType Type = D->getType();
10304     auto *VD = dyn_cast<VarDecl>(D);
10305 
10306     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
10307     //  A variable that appears in a private clause must not have an incomplete
10308     //  type or a reference type.
10309     if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
10310       continue;
10311     Type = Type.getNonReferenceType();
10312 
10313     // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
10314     // A variable that is privatized must not have a const-qualified type
10315     // unless it is of class type with a mutable member. This restriction does
10316     // not apply to the firstprivate clause.
10317     //
10318     // OpenMP 3.1 [2.9.3.3, private clause, Restrictions]
10319     // A variable that appears in a private clause must not have a
10320     // const-qualified type unless it is of class type with a mutable member.
10321     if (rejectConstNotMutableType(*this, D, Type, OMPC_private, ELoc))
10322       continue;
10323 
10324     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
10325     // in a Construct]
10326     //  Variables with the predetermined data-sharing attributes may not be
10327     //  listed in data-sharing attributes clauses, except for the cases
10328     //  listed below. For these exceptions only, listing a predetermined
10329     //  variable in a data-sharing attribute clause is allowed and overrides
10330     //  the variable's predetermined data-sharing attributes.
10331     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
10332     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
10333       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
10334                                           << getOpenMPClauseName(OMPC_private);
10335       reportOriginalDsa(*this, DSAStack, D, DVar);
10336       continue;
10337     }
10338 
10339     OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
10340     // Variably modified types are not supported for tasks.
10341     if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
10342         isOpenMPTaskingDirective(CurrDir)) {
10343       Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
10344           << getOpenMPClauseName(OMPC_private) << Type
10345           << getOpenMPDirectiveName(CurrDir);
10346       bool IsDecl =
10347           !VD ||
10348           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
10349       Diag(D->getLocation(),
10350            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
10351           << D;
10352       continue;
10353     }
10354 
10355     // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
10356     // A list item cannot appear in both a map clause and a data-sharing
10357     // attribute clause on the same construct
10358     if (isOpenMPTargetExecutionDirective(CurrDir)) {
10359       OpenMPClauseKind ConflictKind;
10360       if (DSAStack->checkMappableExprComponentListsForDecl(
10361               VD, /*CurrentRegionOnly=*/true,
10362               [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
10363                   OpenMPClauseKind WhereFoundClauseKind) -> bool {
10364                 ConflictKind = WhereFoundClauseKind;
10365                 return true;
10366               })) {
10367         Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
10368             << getOpenMPClauseName(OMPC_private)
10369             << getOpenMPClauseName(ConflictKind)
10370             << getOpenMPDirectiveName(CurrDir);
10371         reportOriginalDsa(*this, DSAStack, D, DVar);
10372         continue;
10373       }
10374     }
10375 
10376     // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
10377     //  A variable of class type (or array thereof) that appears in a private
10378     //  clause requires an accessible, unambiguous default constructor for the
10379     //  class type.
10380     // Generate helper private variable and initialize it with the default
10381     // value. The address of the original variable is replaced by the address of
10382     // the new private variable in CodeGen. This new variable is not added to
10383     // IdResolver, so the code in the OpenMP region uses original variable for
10384     // proper diagnostics.
10385     Type = Type.getUnqualifiedType();
10386     VarDecl *VDPrivate =
10387         buildVarDecl(*this, ELoc, Type, D->getName(),
10388                      D->hasAttrs() ? &D->getAttrs() : nullptr,
10389                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
10390     ActOnUninitializedDecl(VDPrivate);
10391     if (VDPrivate->isInvalidDecl())
10392       continue;
10393     DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
10394         *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
10395 
10396     DeclRefExpr *Ref = nullptr;
10397     if (!VD && !CurContext->isDependentContext())
10398       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
10399     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
10400     Vars.push_back((VD || CurContext->isDependentContext())
10401                        ? RefExpr->IgnoreParens()
10402                        : Ref);
10403     PrivateCopies.push_back(VDPrivateRefExpr);
10404   }
10405 
10406   if (Vars.empty())
10407     return nullptr;
10408 
10409   return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
10410                                   PrivateCopies);
10411 }
10412 
10413 namespace {
10414 class DiagsUninitializedSeveretyRAII {
10415 private:
10416   DiagnosticsEngine &Diags;
10417   SourceLocation SavedLoc;
10418   bool IsIgnored = false;
10419 
10420 public:
10421   DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
10422                                  bool IsIgnored)
10423       : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
10424     if (!IsIgnored) {
10425       Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
10426                         /*Map*/ diag::Severity::Ignored, Loc);
10427     }
10428   }
10429   ~DiagsUninitializedSeveretyRAII() {
10430     if (!IsIgnored)
10431       Diags.popMappings(SavedLoc);
10432   }
10433 };
10434 }
10435 
10436 OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
10437                                                SourceLocation StartLoc,
10438                                                SourceLocation LParenLoc,
10439                                                SourceLocation EndLoc) {
10440   SmallVector<Expr *, 8> Vars;
10441   SmallVector<Expr *, 8> PrivateCopies;
10442   SmallVector<Expr *, 8> Inits;
10443   SmallVector<Decl *, 4> ExprCaptures;
10444   bool IsImplicitClause =
10445       StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
10446   SourceLocation ImplicitClauseLoc = DSAStack->getConstructLoc();
10447 
10448   for (Expr *RefExpr : VarList) {
10449     assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
10450     SourceLocation ELoc;
10451     SourceRange ERange;
10452     Expr *SimpleRefExpr = RefExpr;
10453     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
10454     if (Res.second) {
10455       // It will be analyzed later.
10456       Vars.push_back(RefExpr);
10457       PrivateCopies.push_back(nullptr);
10458       Inits.push_back(nullptr);
10459     }
10460     ValueDecl *D = Res.first;
10461     if (!D)
10462       continue;
10463 
10464     ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
10465     QualType Type = D->getType();
10466     auto *VD = dyn_cast<VarDecl>(D);
10467 
10468     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
10469     //  A variable that appears in a private clause must not have an incomplete
10470     //  type or a reference type.
10471     if (RequireCompleteType(ELoc, Type,
10472                             diag::err_omp_firstprivate_incomplete_type))
10473       continue;
10474     Type = Type.getNonReferenceType();
10475 
10476     // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
10477     //  A variable of class type (or array thereof) that appears in a private
10478     //  clause requires an accessible, unambiguous copy constructor for the
10479     //  class type.
10480     QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
10481 
10482     // If an implicit firstprivate variable found it was checked already.
10483     DSAStackTy::DSAVarData TopDVar;
10484     if (!IsImplicitClause) {
10485       DSAStackTy::DSAVarData DVar =
10486           DSAStack->getTopDSA(D, /*FromParent=*/false);
10487       TopDVar = DVar;
10488       OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
10489       bool IsConstant = ElemType.isConstant(Context);
10490       // OpenMP [2.4.13, Data-sharing Attribute Clauses]
10491       //  A list item that specifies a given variable may not appear in more
10492       // than one clause on the same directive, except that a variable may be
10493       //  specified in both firstprivate and lastprivate clauses.
10494       // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
10495       // A list item may appear in a firstprivate or lastprivate clause but not
10496       // both.
10497       if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
10498           (isOpenMPDistributeDirective(CurrDir) ||
10499            DVar.CKind != OMPC_lastprivate) &&
10500           DVar.RefExpr) {
10501         Diag(ELoc, diag::err_omp_wrong_dsa)
10502             << getOpenMPClauseName(DVar.CKind)
10503             << getOpenMPClauseName(OMPC_firstprivate);
10504         reportOriginalDsa(*this, DSAStack, D, DVar);
10505         continue;
10506       }
10507 
10508       // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
10509       // in a Construct]
10510       //  Variables with the predetermined data-sharing attributes may not be
10511       //  listed in data-sharing attributes clauses, except for the cases
10512       //  listed below. For these exceptions only, listing a predetermined
10513       //  variable in a data-sharing attribute clause is allowed and overrides
10514       //  the variable's predetermined data-sharing attributes.
10515       // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
10516       // in a Construct, C/C++, p.2]
10517       //  Variables with const-qualified type having no mutable member may be
10518       //  listed in a firstprivate clause, even if they are static data members.
10519       if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
10520           DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
10521         Diag(ELoc, diag::err_omp_wrong_dsa)
10522             << getOpenMPClauseName(DVar.CKind)
10523             << getOpenMPClauseName(OMPC_firstprivate);
10524         reportOriginalDsa(*this, DSAStack, D, DVar);
10525         continue;
10526       }
10527 
10528       // OpenMP [2.9.3.4, Restrictions, p.2]
10529       //  A list item that is private within a parallel region must not appear
10530       //  in a firstprivate clause on a worksharing construct if any of the
10531       //  worksharing regions arising from the worksharing construct ever bind
10532       //  to any of the parallel regions arising from the parallel construct.
10533       // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
10534       // A list item that is private within a teams region must not appear in a
10535       // firstprivate clause on a distribute construct if any of the distribute
10536       // regions arising from the distribute construct ever bind to any of the
10537       // teams regions arising from the teams construct.
10538       // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
10539       // A list item that appears in a reduction clause of a teams construct
10540       // must not appear in a firstprivate clause on a distribute construct if
10541       // any of the distribute regions arising from the distribute construct
10542       // ever bind to any of the teams regions arising from the teams construct.
10543       if ((isOpenMPWorksharingDirective(CurrDir) ||
10544            isOpenMPDistributeDirective(CurrDir)) &&
10545           !isOpenMPParallelDirective(CurrDir) &&
10546           !isOpenMPTeamsDirective(CurrDir)) {
10547         DVar = DSAStack->getImplicitDSA(D, true);
10548         if (DVar.CKind != OMPC_shared &&
10549             (isOpenMPParallelDirective(DVar.DKind) ||
10550              isOpenMPTeamsDirective(DVar.DKind) ||
10551              DVar.DKind == OMPD_unknown)) {
10552           Diag(ELoc, diag::err_omp_required_access)
10553               << getOpenMPClauseName(OMPC_firstprivate)
10554               << getOpenMPClauseName(OMPC_shared);
10555           reportOriginalDsa(*this, DSAStack, D, DVar);
10556           continue;
10557         }
10558       }
10559       // OpenMP [2.9.3.4, Restrictions, p.3]
10560       //  A list item that appears in a reduction clause of a parallel construct
10561       //  must not appear in a firstprivate clause on a worksharing or task
10562       //  construct if any of the worksharing or task regions arising from the
10563       //  worksharing or task construct ever bind to any of the parallel regions
10564       //  arising from the parallel construct.
10565       // OpenMP [2.9.3.4, Restrictions, p.4]
10566       //  A list item that appears in a reduction clause in worksharing
10567       //  construct must not appear in a firstprivate clause in a task construct
10568       //  encountered during execution of any of the worksharing regions arising
10569       //  from the worksharing construct.
10570       if (isOpenMPTaskingDirective(CurrDir)) {
10571         DVar = DSAStack->hasInnermostDSA(
10572             D, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
10573             [](OpenMPDirectiveKind K) {
10574               return isOpenMPParallelDirective(K) ||
10575                      isOpenMPWorksharingDirective(K) ||
10576                      isOpenMPTeamsDirective(K);
10577             },
10578             /*FromParent=*/true);
10579         if (DVar.CKind == OMPC_reduction &&
10580             (isOpenMPParallelDirective(DVar.DKind) ||
10581              isOpenMPWorksharingDirective(DVar.DKind) ||
10582              isOpenMPTeamsDirective(DVar.DKind))) {
10583           Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
10584               << getOpenMPDirectiveName(DVar.DKind);
10585           reportOriginalDsa(*this, DSAStack, D, DVar);
10586           continue;
10587         }
10588       }
10589 
10590       // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
10591       // A list item cannot appear in both a map clause and a data-sharing
10592       // attribute clause on the same construct
10593       if (isOpenMPTargetExecutionDirective(CurrDir)) {
10594         OpenMPClauseKind ConflictKind;
10595         if (DSAStack->checkMappableExprComponentListsForDecl(
10596                 VD, /*CurrentRegionOnly=*/true,
10597                 [&ConflictKind](
10598                     OMPClauseMappableExprCommon::MappableExprComponentListRef,
10599                     OpenMPClauseKind WhereFoundClauseKind) {
10600                   ConflictKind = WhereFoundClauseKind;
10601                   return true;
10602                 })) {
10603           Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
10604               << getOpenMPClauseName(OMPC_firstprivate)
10605               << getOpenMPClauseName(ConflictKind)
10606               << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
10607           reportOriginalDsa(*this, DSAStack, D, DVar);
10608           continue;
10609         }
10610       }
10611     }
10612 
10613     // Variably modified types are not supported for tasks.
10614     if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
10615         isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
10616       Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
10617           << getOpenMPClauseName(OMPC_firstprivate) << Type
10618           << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
10619       bool IsDecl =
10620           !VD ||
10621           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
10622       Diag(D->getLocation(),
10623            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
10624           << D;
10625       continue;
10626     }
10627 
10628     Type = Type.getUnqualifiedType();
10629     VarDecl *VDPrivate =
10630         buildVarDecl(*this, ELoc, Type, D->getName(),
10631                      D->hasAttrs() ? &D->getAttrs() : nullptr,
10632                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
10633     // Generate helper private variable and initialize it with the value of the
10634     // original variable. The address of the original variable is replaced by
10635     // the address of the new private variable in the CodeGen. This new variable
10636     // is not added to IdResolver, so the code in the OpenMP region uses
10637     // original variable for proper diagnostics and variable capturing.
10638     Expr *VDInitRefExpr = nullptr;
10639     // For arrays generate initializer for single element and replace it by the
10640     // original array element in CodeGen.
10641     if (Type->isArrayType()) {
10642       VarDecl *VDInit =
10643           buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
10644       VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
10645       Expr *Init = DefaultLvalueConversion(VDInitRefExpr).get();
10646       ElemType = ElemType.getUnqualifiedType();
10647       VarDecl *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
10648                                          ".firstprivate.temp");
10649       InitializedEntity Entity =
10650           InitializedEntity::InitializeVariable(VDInitTemp);
10651       InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
10652 
10653       InitializationSequence InitSeq(*this, Entity, Kind, Init);
10654       ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
10655       if (Result.isInvalid())
10656         VDPrivate->setInvalidDecl();
10657       else
10658         VDPrivate->setInit(Result.getAs<Expr>());
10659       // Remove temp variable declaration.
10660       Context.Deallocate(VDInitTemp);
10661     } else {
10662       VarDecl *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
10663                                      ".firstprivate.temp");
10664       VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
10665                                        RefExpr->getExprLoc());
10666       AddInitializerToDecl(VDPrivate,
10667                            DefaultLvalueConversion(VDInitRefExpr).get(),
10668                            /*DirectInit=*/false);
10669     }
10670     if (VDPrivate->isInvalidDecl()) {
10671       if (IsImplicitClause) {
10672         Diag(RefExpr->getExprLoc(),
10673              diag::note_omp_task_predetermined_firstprivate_here);
10674       }
10675       continue;
10676     }
10677     CurContext->addDecl(VDPrivate);
10678     DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
10679         *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
10680         RefExpr->getExprLoc());
10681     DeclRefExpr *Ref = nullptr;
10682     if (!VD && !CurContext->isDependentContext()) {
10683       if (TopDVar.CKind == OMPC_lastprivate) {
10684         Ref = TopDVar.PrivateCopy;
10685       } else {
10686         Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
10687         if (!isOpenMPCapturedDecl(D))
10688           ExprCaptures.push_back(Ref->getDecl());
10689       }
10690     }
10691     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
10692     Vars.push_back((VD || CurContext->isDependentContext())
10693                        ? RefExpr->IgnoreParens()
10694                        : Ref);
10695     PrivateCopies.push_back(VDPrivateRefExpr);
10696     Inits.push_back(VDInitRefExpr);
10697   }
10698 
10699   if (Vars.empty())
10700     return nullptr;
10701 
10702   return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
10703                                        Vars, PrivateCopies, Inits,
10704                                        buildPreInits(Context, ExprCaptures));
10705 }
10706 
10707 OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
10708                                               SourceLocation StartLoc,
10709                                               SourceLocation LParenLoc,
10710                                               SourceLocation EndLoc) {
10711   SmallVector<Expr *, 8> Vars;
10712   SmallVector<Expr *, 8> SrcExprs;
10713   SmallVector<Expr *, 8> DstExprs;
10714   SmallVector<Expr *, 8> AssignmentOps;
10715   SmallVector<Decl *, 4> ExprCaptures;
10716   SmallVector<Expr *, 4> ExprPostUpdates;
10717   for (Expr *RefExpr : VarList) {
10718     assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
10719     SourceLocation ELoc;
10720     SourceRange ERange;
10721     Expr *SimpleRefExpr = RefExpr;
10722     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
10723     if (Res.second) {
10724       // It will be analyzed later.
10725       Vars.push_back(RefExpr);
10726       SrcExprs.push_back(nullptr);
10727       DstExprs.push_back(nullptr);
10728       AssignmentOps.push_back(nullptr);
10729     }
10730     ValueDecl *D = Res.first;
10731     if (!D)
10732       continue;
10733 
10734     QualType Type = D->getType();
10735     auto *VD = dyn_cast<VarDecl>(D);
10736 
10737     // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
10738     //  A variable that appears in a lastprivate clause must not have an
10739     //  incomplete type or a reference type.
10740     if (RequireCompleteType(ELoc, Type,
10741                             diag::err_omp_lastprivate_incomplete_type))
10742       continue;
10743     Type = Type.getNonReferenceType();
10744 
10745     // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
10746     // A variable that is privatized must not have a const-qualified type
10747     // unless it is of class type with a mutable member. This restriction does
10748     // not apply to the firstprivate clause.
10749     //
10750     // OpenMP 3.1 [2.9.3.5, lastprivate clause, Restrictions]
10751     // A variable that appears in a lastprivate clause must not have a
10752     // const-qualified type unless it is of class type with a mutable member.
10753     if (rejectConstNotMutableType(*this, D, Type, OMPC_lastprivate, ELoc))
10754       continue;
10755 
10756     OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
10757     // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
10758     // in a Construct]
10759     //  Variables with the predetermined data-sharing attributes may not be
10760     //  listed in data-sharing attributes clauses, except for the cases
10761     //  listed below.
10762     // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
10763     // A list item may appear in a firstprivate or lastprivate clause but not
10764     // both.
10765     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
10766     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
10767         (isOpenMPDistributeDirective(CurrDir) ||
10768          DVar.CKind != OMPC_firstprivate) &&
10769         (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
10770       Diag(ELoc, diag::err_omp_wrong_dsa)
10771           << getOpenMPClauseName(DVar.CKind)
10772           << getOpenMPClauseName(OMPC_lastprivate);
10773       reportOriginalDsa(*this, DSAStack, D, DVar);
10774       continue;
10775     }
10776 
10777     // OpenMP [2.14.3.5, Restrictions, p.2]
10778     // A list item that is private within a parallel region, or that appears in
10779     // the reduction clause of a parallel construct, must not appear in a
10780     // lastprivate clause on a worksharing construct if any of the corresponding
10781     // worksharing regions ever binds to any of the corresponding parallel
10782     // regions.
10783     DSAStackTy::DSAVarData TopDVar = DVar;
10784     if (isOpenMPWorksharingDirective(CurrDir) &&
10785         !isOpenMPParallelDirective(CurrDir) &&
10786         !isOpenMPTeamsDirective(CurrDir)) {
10787       DVar = DSAStack->getImplicitDSA(D, true);
10788       if (DVar.CKind != OMPC_shared) {
10789         Diag(ELoc, diag::err_omp_required_access)
10790             << getOpenMPClauseName(OMPC_lastprivate)
10791             << getOpenMPClauseName(OMPC_shared);
10792         reportOriginalDsa(*this, DSAStack, D, DVar);
10793         continue;
10794       }
10795     }
10796 
10797     // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
10798     //  A variable of class type (or array thereof) that appears in a
10799     //  lastprivate clause requires an accessible, unambiguous default
10800     //  constructor for the class type, unless the list item is also specified
10801     //  in a firstprivate clause.
10802     //  A variable of class type (or array thereof) that appears in a
10803     //  lastprivate clause requires an accessible, unambiguous copy assignment
10804     //  operator for the class type.
10805     Type = Context.getBaseElementType(Type).getNonReferenceType();
10806     VarDecl *SrcVD = buildVarDecl(*this, ERange.getBegin(),
10807                                   Type.getUnqualifiedType(), ".lastprivate.src",
10808                                   D->hasAttrs() ? &D->getAttrs() : nullptr);
10809     DeclRefExpr *PseudoSrcExpr =
10810         buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
10811     VarDecl *DstVD =
10812         buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
10813                      D->hasAttrs() ? &D->getAttrs() : nullptr);
10814     DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
10815     // For arrays generate assignment operation for single element and replace
10816     // it by the original array element in CodeGen.
10817     ExprResult AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
10818                                          PseudoDstExpr, PseudoSrcExpr);
10819     if (AssignmentOp.isInvalid())
10820       continue;
10821     AssignmentOp =
10822         ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
10823     if (AssignmentOp.isInvalid())
10824       continue;
10825 
10826     DeclRefExpr *Ref = nullptr;
10827     if (!VD && !CurContext->isDependentContext()) {
10828       if (TopDVar.CKind == OMPC_firstprivate) {
10829         Ref = TopDVar.PrivateCopy;
10830       } else {
10831         Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
10832         if (!isOpenMPCapturedDecl(D))
10833           ExprCaptures.push_back(Ref->getDecl());
10834       }
10835       if (TopDVar.CKind == OMPC_firstprivate ||
10836           (!isOpenMPCapturedDecl(D) &&
10837            Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
10838         ExprResult RefRes = DefaultLvalueConversion(Ref);
10839         if (!RefRes.isUsable())
10840           continue;
10841         ExprResult PostUpdateRes =
10842             BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
10843                        RefRes.get());
10844         if (!PostUpdateRes.isUsable())
10845           continue;
10846         ExprPostUpdates.push_back(
10847             IgnoredValueConversions(PostUpdateRes.get()).get());
10848       }
10849     }
10850     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
10851     Vars.push_back((VD || CurContext->isDependentContext())
10852                        ? RefExpr->IgnoreParens()
10853                        : Ref);
10854     SrcExprs.push_back(PseudoSrcExpr);
10855     DstExprs.push_back(PseudoDstExpr);
10856     AssignmentOps.push_back(AssignmentOp.get());
10857   }
10858 
10859   if (Vars.empty())
10860     return nullptr;
10861 
10862   return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
10863                                       Vars, SrcExprs, DstExprs, AssignmentOps,
10864                                       buildPreInits(Context, ExprCaptures),
10865                                       buildPostUpdate(*this, ExprPostUpdates));
10866 }
10867 
10868 OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
10869                                          SourceLocation StartLoc,
10870                                          SourceLocation LParenLoc,
10871                                          SourceLocation EndLoc) {
10872   SmallVector<Expr *, 8> Vars;
10873   for (Expr *RefExpr : VarList) {
10874     assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
10875     SourceLocation ELoc;
10876     SourceRange ERange;
10877     Expr *SimpleRefExpr = RefExpr;
10878     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
10879     if (Res.second) {
10880       // It will be analyzed later.
10881       Vars.push_back(RefExpr);
10882     }
10883     ValueDecl *D = Res.first;
10884     if (!D)
10885       continue;
10886 
10887     auto *VD = dyn_cast<VarDecl>(D);
10888     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
10889     // in a Construct]
10890     //  Variables with the predetermined data-sharing attributes may not be
10891     //  listed in data-sharing attributes clauses, except for the cases
10892     //  listed below. For these exceptions only, listing a predetermined
10893     //  variable in a data-sharing attribute clause is allowed and overrides
10894     //  the variable's predetermined data-sharing attributes.
10895     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
10896     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
10897         DVar.RefExpr) {
10898       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
10899                                           << getOpenMPClauseName(OMPC_shared);
10900       reportOriginalDsa(*this, DSAStack, D, DVar);
10901       continue;
10902     }
10903 
10904     DeclRefExpr *Ref = nullptr;
10905     if (!VD && isOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
10906       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
10907     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
10908     Vars.push_back((VD || !Ref || CurContext->isDependentContext())
10909                        ? RefExpr->IgnoreParens()
10910                        : Ref);
10911   }
10912 
10913   if (Vars.empty())
10914     return nullptr;
10915 
10916   return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
10917 }
10918 
10919 namespace {
10920 class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
10921   DSAStackTy *Stack;
10922 
10923 public:
10924   bool VisitDeclRefExpr(DeclRefExpr *E) {
10925     if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
10926       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
10927       if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
10928         return false;
10929       if (DVar.CKind != OMPC_unknown)
10930         return true;
10931       DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
10932           VD, isOpenMPPrivate, [](OpenMPDirectiveKind) { return true; },
10933           /*FromParent=*/true);
10934       return DVarPrivate.CKind != OMPC_unknown;
10935     }
10936     return false;
10937   }
10938   bool VisitStmt(Stmt *S) {
10939     for (Stmt *Child : S->children()) {
10940       if (Child && Visit(Child))
10941         return true;
10942     }
10943     return false;
10944   }
10945   explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
10946 };
10947 } // namespace
10948 
10949 namespace {
10950 // Transform MemberExpression for specified FieldDecl of current class to
10951 // DeclRefExpr to specified OMPCapturedExprDecl.
10952 class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
10953   typedef TreeTransform<TransformExprToCaptures> BaseTransform;
10954   ValueDecl *Field = nullptr;
10955   DeclRefExpr *CapturedExpr = nullptr;
10956 
10957 public:
10958   TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
10959       : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
10960 
10961   ExprResult TransformMemberExpr(MemberExpr *E) {
10962     if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
10963         E->getMemberDecl() == Field) {
10964       CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
10965       return CapturedExpr;
10966     }
10967     return BaseTransform::TransformMemberExpr(E);
10968   }
10969   DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
10970 };
10971 } // namespace
10972 
10973 template <typename T, typename U>
10974 static T filterLookupForUDReductionAndMapper(
10975     SmallVectorImpl<U> &Lookups, const llvm::function_ref<T(ValueDecl *)> Gen) {
10976   for (U &Set : Lookups) {
10977     for (auto *D : Set) {
10978       if (T Res = Gen(cast<ValueDecl>(D)))
10979         return Res;
10980     }
10981   }
10982   return T();
10983 }
10984 
10985 static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) {
10986   assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case");
10987 
10988   for (auto RD : D->redecls()) {
10989     // Don't bother with extra checks if we already know this one isn't visible.
10990     if (RD == D)
10991       continue;
10992 
10993     auto ND = cast<NamedDecl>(RD);
10994     if (LookupResult::isVisible(SemaRef, ND))
10995       return ND;
10996   }
10997 
10998   return nullptr;
10999 }
11000 
11001 static void
11002 argumentDependentLookup(Sema &SemaRef, const DeclarationNameInfo &Id,
11003                         SourceLocation Loc, QualType Ty,
11004                         SmallVectorImpl<UnresolvedSet<8>> &Lookups) {
11005   // Find all of the associated namespaces and classes based on the
11006   // arguments we have.
11007   Sema::AssociatedNamespaceSet AssociatedNamespaces;
11008   Sema::AssociatedClassSet AssociatedClasses;
11009   OpaqueValueExpr OVE(Loc, Ty, VK_LValue);
11010   SemaRef.FindAssociatedClassesAndNamespaces(Loc, &OVE, AssociatedNamespaces,
11011                                              AssociatedClasses);
11012 
11013   // C++ [basic.lookup.argdep]p3:
11014   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
11015   //   and let Y be the lookup set produced by argument dependent
11016   //   lookup (defined as follows). If X contains [...] then Y is
11017   //   empty. Otherwise Y is the set of declarations found in the
11018   //   namespaces associated with the argument types as described
11019   //   below. The set of declarations found by the lookup of the name
11020   //   is the union of X and Y.
11021   //
11022   // Here, we compute Y and add its members to the overloaded
11023   // candidate set.
11024   for (auto *NS : AssociatedNamespaces) {
11025     //   When considering an associated namespace, the lookup is the
11026     //   same as the lookup performed when the associated namespace is
11027     //   used as a qualifier (3.4.3.2) except that:
11028     //
11029     //     -- Any using-directives in the associated namespace are
11030     //        ignored.
11031     //
11032     //     -- Any namespace-scope friend functions declared in
11033     //        associated classes are visible within their respective
11034     //        namespaces even if they are not visible during an ordinary
11035     //        lookup (11.4).
11036     DeclContext::lookup_result R = NS->lookup(Id.getName());
11037     for (auto *D : R) {
11038       auto *Underlying = D;
11039       if (auto *USD = dyn_cast<UsingShadowDecl>(D))
11040         Underlying = USD->getTargetDecl();
11041 
11042       if (!isa<OMPDeclareReductionDecl>(Underlying) &&
11043           !isa<OMPDeclareMapperDecl>(Underlying))
11044         continue;
11045 
11046       if (!SemaRef.isVisible(D)) {
11047         D = findAcceptableDecl(SemaRef, D);
11048         if (!D)
11049           continue;
11050         if (auto *USD = dyn_cast<UsingShadowDecl>(D))
11051           Underlying = USD->getTargetDecl();
11052       }
11053       Lookups.emplace_back();
11054       Lookups.back().addDecl(Underlying);
11055     }
11056   }
11057 }
11058 
11059 static ExprResult
11060 buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
11061                          Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
11062                          const DeclarationNameInfo &ReductionId, QualType Ty,
11063                          CXXCastPath &BasePath, Expr *UnresolvedReduction) {
11064   if (ReductionIdScopeSpec.isInvalid())
11065     return ExprError();
11066   SmallVector<UnresolvedSet<8>, 4> Lookups;
11067   if (S) {
11068     LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
11069     Lookup.suppressDiagnostics();
11070     while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
11071       NamedDecl *D = Lookup.getRepresentativeDecl();
11072       do {
11073         S = S->getParent();
11074       } while (S && !S->isDeclScope(D));
11075       if (S)
11076         S = S->getParent();
11077       Lookups.emplace_back();
11078       Lookups.back().append(Lookup.begin(), Lookup.end());
11079       Lookup.clear();
11080     }
11081   } else if (auto *ULE =
11082                  cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
11083     Lookups.push_back(UnresolvedSet<8>());
11084     Decl *PrevD = nullptr;
11085     for (NamedDecl *D : ULE->decls()) {
11086       if (D == PrevD)
11087         Lookups.push_back(UnresolvedSet<8>());
11088       else if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(D))
11089         Lookups.back().addDecl(DRD);
11090       PrevD = D;
11091     }
11092   }
11093   if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() ||
11094       Ty->isInstantiationDependentType() ||
11095       Ty->containsUnexpandedParameterPack() ||
11096       filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
11097         return !D->isInvalidDecl() &&
11098                (D->getType()->isDependentType() ||
11099                 D->getType()->isInstantiationDependentType() ||
11100                 D->getType()->containsUnexpandedParameterPack());
11101       })) {
11102     UnresolvedSet<8> ResSet;
11103     for (const UnresolvedSet<8> &Set : Lookups) {
11104       if (Set.empty())
11105         continue;
11106       ResSet.append(Set.begin(), Set.end());
11107       // The last item marks the end of all declarations at the specified scope.
11108       ResSet.addDecl(Set[Set.size() - 1]);
11109     }
11110     return UnresolvedLookupExpr::Create(
11111         SemaRef.Context, /*NamingClass=*/nullptr,
11112         ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
11113         /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
11114   }
11115   // Lookup inside the classes.
11116   // C++ [over.match.oper]p3:
11117   //   For a unary operator @ with an operand of a type whose
11118   //   cv-unqualified version is T1, and for a binary operator @ with
11119   //   a left operand of a type whose cv-unqualified version is T1 and
11120   //   a right operand of a type whose cv-unqualified version is T2,
11121   //   three sets of candidate functions, designated member
11122   //   candidates, non-member candidates and built-in candidates, are
11123   //   constructed as follows:
11124   //     -- If T1 is a complete class type or a class currently being
11125   //        defined, the set of member candidates is the result of the
11126   //        qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
11127   //        the set of member candidates is empty.
11128   LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
11129   Lookup.suppressDiagnostics();
11130   if (const auto *TyRec = Ty->getAs<RecordType>()) {
11131     // Complete the type if it can be completed.
11132     // If the type is neither complete nor being defined, bail out now.
11133     if (SemaRef.isCompleteType(Loc, Ty) || TyRec->isBeingDefined() ||
11134         TyRec->getDecl()->getDefinition()) {
11135       Lookup.clear();
11136       SemaRef.LookupQualifiedName(Lookup, TyRec->getDecl());
11137       if (Lookup.empty()) {
11138         Lookups.emplace_back();
11139         Lookups.back().append(Lookup.begin(), Lookup.end());
11140       }
11141     }
11142   }
11143   // Perform ADL.
11144   if (SemaRef.getLangOpts().CPlusPlus) {
11145     argumentDependentLookup(SemaRef, ReductionId, Loc, Ty, Lookups);
11146     if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
11147             Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
11148               if (!D->isInvalidDecl() &&
11149                   SemaRef.Context.hasSameType(D->getType(), Ty))
11150                 return D;
11151               return nullptr;
11152             }))
11153       return SemaRef.BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(),
11154                                       VK_LValue, Loc);
11155     if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
11156             Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
11157               if (!D->isInvalidDecl() &&
11158                   SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
11159                   !Ty.isMoreQualifiedThan(D->getType()))
11160                 return D;
11161               return nullptr;
11162             })) {
11163       CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
11164                          /*DetectVirtual=*/false);
11165       if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
11166         if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
11167                 VD->getType().getUnqualifiedType()))) {
11168           if (SemaRef.CheckBaseClassAccess(
11169                   Loc, VD->getType(), Ty, Paths.front(),
11170                   /*DiagID=*/0) != Sema::AR_inaccessible) {
11171             SemaRef.BuildBasePathArray(Paths, BasePath);
11172             return SemaRef.BuildDeclRefExpr(
11173                 VD, VD->getType().getNonReferenceType(), VK_LValue, Loc);
11174           }
11175         }
11176       }
11177     }
11178   }
11179   if (ReductionIdScopeSpec.isSet()) {
11180     SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
11181     return ExprError();
11182   }
11183   return ExprEmpty();
11184 }
11185 
11186 namespace {
11187 /// Data for the reduction-based clauses.
11188 struct ReductionData {
11189   /// List of original reduction items.
11190   SmallVector<Expr *, 8> Vars;
11191   /// List of private copies of the reduction items.
11192   SmallVector<Expr *, 8> Privates;
11193   /// LHS expressions for the reduction_op expressions.
11194   SmallVector<Expr *, 8> LHSs;
11195   /// RHS expressions for the reduction_op expressions.
11196   SmallVector<Expr *, 8> RHSs;
11197   /// Reduction operation expression.
11198   SmallVector<Expr *, 8> ReductionOps;
11199   /// Taskgroup descriptors for the corresponding reduction items in
11200   /// in_reduction clauses.
11201   SmallVector<Expr *, 8> TaskgroupDescriptors;
11202   /// List of captures for clause.
11203   SmallVector<Decl *, 4> ExprCaptures;
11204   /// List of postupdate expressions.
11205   SmallVector<Expr *, 4> ExprPostUpdates;
11206   ReductionData() = delete;
11207   /// Reserves required memory for the reduction data.
11208   ReductionData(unsigned Size) {
11209     Vars.reserve(Size);
11210     Privates.reserve(Size);
11211     LHSs.reserve(Size);
11212     RHSs.reserve(Size);
11213     ReductionOps.reserve(Size);
11214     TaskgroupDescriptors.reserve(Size);
11215     ExprCaptures.reserve(Size);
11216     ExprPostUpdates.reserve(Size);
11217   }
11218   /// Stores reduction item and reduction operation only (required for dependent
11219   /// reduction item).
11220   void push(Expr *Item, Expr *ReductionOp) {
11221     Vars.emplace_back(Item);
11222     Privates.emplace_back(nullptr);
11223     LHSs.emplace_back(nullptr);
11224     RHSs.emplace_back(nullptr);
11225     ReductionOps.emplace_back(ReductionOp);
11226     TaskgroupDescriptors.emplace_back(nullptr);
11227   }
11228   /// Stores reduction data.
11229   void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp,
11230             Expr *TaskgroupDescriptor) {
11231     Vars.emplace_back(Item);
11232     Privates.emplace_back(Private);
11233     LHSs.emplace_back(LHS);
11234     RHSs.emplace_back(RHS);
11235     ReductionOps.emplace_back(ReductionOp);
11236     TaskgroupDescriptors.emplace_back(TaskgroupDescriptor);
11237   }
11238 };
11239 } // namespace
11240 
11241 static bool checkOMPArraySectionConstantForReduction(
11242     ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement,
11243     SmallVectorImpl<llvm::APSInt> &ArraySizes) {
11244   const Expr *Length = OASE->getLength();
11245   if (Length == nullptr) {
11246     // For array sections of the form [1:] or [:], we would need to analyze
11247     // the lower bound...
11248     if (OASE->getColonLoc().isValid())
11249       return false;
11250 
11251     // This is an array subscript which has implicit length 1!
11252     SingleElement = true;
11253     ArraySizes.push_back(llvm::APSInt::get(1));
11254   } else {
11255     Expr::EvalResult Result;
11256     if (!Length->EvaluateAsInt(Result, Context))
11257       return false;
11258 
11259     llvm::APSInt ConstantLengthValue = Result.Val.getInt();
11260     SingleElement = (ConstantLengthValue.getSExtValue() == 1);
11261     ArraySizes.push_back(ConstantLengthValue);
11262   }
11263 
11264   // Get the base of this array section and walk up from there.
11265   const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
11266 
11267   // We require length = 1 for all array sections except the right-most to
11268   // guarantee that the memory region is contiguous and has no holes in it.
11269   while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) {
11270     Length = TempOASE->getLength();
11271     if (Length == nullptr) {
11272       // For array sections of the form [1:] or [:], we would need to analyze
11273       // the lower bound...
11274       if (OASE->getColonLoc().isValid())
11275         return false;
11276 
11277       // This is an array subscript which has implicit length 1!
11278       ArraySizes.push_back(llvm::APSInt::get(1));
11279     } else {
11280       Expr::EvalResult Result;
11281       if (!Length->EvaluateAsInt(Result, Context))
11282         return false;
11283 
11284       llvm::APSInt ConstantLengthValue = Result.Val.getInt();
11285       if (ConstantLengthValue.getSExtValue() != 1)
11286         return false;
11287 
11288       ArraySizes.push_back(ConstantLengthValue);
11289     }
11290     Base = TempOASE->getBase()->IgnoreParenImpCasts();
11291   }
11292 
11293   // If we have a single element, we don't need to add the implicit lengths.
11294   if (!SingleElement) {
11295     while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) {
11296       // Has implicit length 1!
11297       ArraySizes.push_back(llvm::APSInt::get(1));
11298       Base = TempASE->getBase()->IgnoreParenImpCasts();
11299     }
11300   }
11301 
11302   // This array section can be privatized as a single value or as a constant
11303   // sized array.
11304   return true;
11305 }
11306 
11307 static bool actOnOMPReductionKindClause(
11308     Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind,
11309     ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
11310     SourceLocation ColonLoc, SourceLocation EndLoc,
11311     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
11312     ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) {
11313   DeclarationName DN = ReductionId.getName();
11314   OverloadedOperatorKind OOK = DN.getCXXOverloadedOperator();
11315   BinaryOperatorKind BOK = BO_Comma;
11316 
11317   ASTContext &Context = S.Context;
11318   // OpenMP [2.14.3.6, reduction clause]
11319   // C
11320   // reduction-identifier is either an identifier or one of the following
11321   // operators: +, -, *,  &, |, ^, && and ||
11322   // C++
11323   // reduction-identifier is either an id-expression or one of the following
11324   // operators: +, -, *, &, |, ^, && and ||
11325   switch (OOK) {
11326   case OO_Plus:
11327   case OO_Minus:
11328     BOK = BO_Add;
11329     break;
11330   case OO_Star:
11331     BOK = BO_Mul;
11332     break;
11333   case OO_Amp:
11334     BOK = BO_And;
11335     break;
11336   case OO_Pipe:
11337     BOK = BO_Or;
11338     break;
11339   case OO_Caret:
11340     BOK = BO_Xor;
11341     break;
11342   case OO_AmpAmp:
11343     BOK = BO_LAnd;
11344     break;
11345   case OO_PipePipe:
11346     BOK = BO_LOr;
11347     break;
11348   case OO_New:
11349   case OO_Delete:
11350   case OO_Array_New:
11351   case OO_Array_Delete:
11352   case OO_Slash:
11353   case OO_Percent:
11354   case OO_Tilde:
11355   case OO_Exclaim:
11356   case OO_Equal:
11357   case OO_Less:
11358   case OO_Greater:
11359   case OO_LessEqual:
11360   case OO_GreaterEqual:
11361   case OO_PlusEqual:
11362   case OO_MinusEqual:
11363   case OO_StarEqual:
11364   case OO_SlashEqual:
11365   case OO_PercentEqual:
11366   case OO_CaretEqual:
11367   case OO_AmpEqual:
11368   case OO_PipeEqual:
11369   case OO_LessLess:
11370   case OO_GreaterGreater:
11371   case OO_LessLessEqual:
11372   case OO_GreaterGreaterEqual:
11373   case OO_EqualEqual:
11374   case OO_ExclaimEqual:
11375   case OO_Spaceship:
11376   case OO_PlusPlus:
11377   case OO_MinusMinus:
11378   case OO_Comma:
11379   case OO_ArrowStar:
11380   case OO_Arrow:
11381   case OO_Call:
11382   case OO_Subscript:
11383   case OO_Conditional:
11384   case OO_Coawait:
11385   case NUM_OVERLOADED_OPERATORS:
11386     llvm_unreachable("Unexpected reduction identifier");
11387   case OO_None:
11388     if (IdentifierInfo *II = DN.getAsIdentifierInfo()) {
11389       if (II->isStr("max"))
11390         BOK = BO_GT;
11391       else if (II->isStr("min"))
11392         BOK = BO_LT;
11393     }
11394     break;
11395   }
11396   SourceRange ReductionIdRange;
11397   if (ReductionIdScopeSpec.isValid())
11398     ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
11399   else
11400     ReductionIdRange.setBegin(ReductionId.getBeginLoc());
11401   ReductionIdRange.setEnd(ReductionId.getEndLoc());
11402 
11403   auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
11404   bool FirstIter = true;
11405   for (Expr *RefExpr : VarList) {
11406     assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
11407     // OpenMP [2.1, C/C++]
11408     //  A list item is a variable or array section, subject to the restrictions
11409     //  specified in Section 2.4 on page 42 and in each of the sections
11410     // describing clauses and directives for which a list appears.
11411     // OpenMP  [2.14.3.3, Restrictions, p.1]
11412     //  A variable that is part of another variable (as an array or
11413     //  structure element) cannot appear in a private clause.
11414     if (!FirstIter && IR != ER)
11415       ++IR;
11416     FirstIter = false;
11417     SourceLocation ELoc;
11418     SourceRange ERange;
11419     Expr *SimpleRefExpr = RefExpr;
11420     auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
11421                               /*AllowArraySection=*/true);
11422     if (Res.second) {
11423       // Try to find 'declare reduction' corresponding construct before using
11424       // builtin/overloaded operators.
11425       QualType Type = Context.DependentTy;
11426       CXXCastPath BasePath;
11427       ExprResult DeclareReductionRef = buildDeclareReductionRef(
11428           S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
11429           ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
11430       Expr *ReductionOp = nullptr;
11431       if (S.CurContext->isDependentContext() &&
11432           (DeclareReductionRef.isUnset() ||
11433            isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
11434         ReductionOp = DeclareReductionRef.get();
11435       // It will be analyzed later.
11436       RD.push(RefExpr, ReductionOp);
11437     }
11438     ValueDecl *D = Res.first;
11439     if (!D)
11440       continue;
11441 
11442     Expr *TaskgroupDescriptor = nullptr;
11443     QualType Type;
11444     auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
11445     auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
11446     if (ASE) {
11447       Type = ASE->getType().getNonReferenceType();
11448     } else if (OASE) {
11449       QualType BaseType =
11450           OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
11451       if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
11452         Type = ATy->getElementType();
11453       else
11454         Type = BaseType->getPointeeType();
11455       Type = Type.getNonReferenceType();
11456     } else {
11457       Type = Context.getBaseElementType(D->getType().getNonReferenceType());
11458     }
11459     auto *VD = dyn_cast<VarDecl>(D);
11460 
11461     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
11462     //  A variable that appears in a private clause must not have an incomplete
11463     //  type or a reference type.
11464     if (S.RequireCompleteType(ELoc, D->getType(),
11465                               diag::err_omp_reduction_incomplete_type))
11466       continue;
11467     // OpenMP [2.14.3.6, reduction clause, Restrictions]
11468     // A list item that appears in a reduction clause must not be
11469     // const-qualified.
11470     if (rejectConstNotMutableType(S, D, Type, ClauseKind, ELoc,
11471                                   /*AcceptIfMutable*/ false, ASE || OASE))
11472       continue;
11473 
11474     OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective();
11475     // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
11476     //  If a list-item is a reference type then it must bind to the same object
11477     //  for all threads of the team.
11478     if (!ASE && !OASE) {
11479       if (VD) {
11480         VarDecl *VDDef = VD->getDefinition();
11481         if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
11482           DSARefChecker Check(Stack);
11483           if (Check.Visit(VDDef->getInit())) {
11484             S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg)
11485                 << getOpenMPClauseName(ClauseKind) << ERange;
11486             S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
11487             continue;
11488           }
11489         }
11490       }
11491 
11492       // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
11493       // in a Construct]
11494       //  Variables with the predetermined data-sharing attributes may not be
11495       //  listed in data-sharing attributes clauses, except for the cases
11496       //  listed below. For these exceptions only, listing a predetermined
11497       //  variable in a data-sharing attribute clause is allowed and overrides
11498       //  the variable's predetermined data-sharing attributes.
11499       // OpenMP [2.14.3.6, Restrictions, p.3]
11500       //  Any number of reduction clauses can be specified on the directive,
11501       //  but a list item can appear only once in the reduction clauses for that
11502       //  directive.
11503       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false);
11504       if (DVar.CKind == OMPC_reduction) {
11505         S.Diag(ELoc, diag::err_omp_once_referenced)
11506             << getOpenMPClauseName(ClauseKind);
11507         if (DVar.RefExpr)
11508           S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
11509         continue;
11510       }
11511       if (DVar.CKind != OMPC_unknown) {
11512         S.Diag(ELoc, diag::err_omp_wrong_dsa)
11513             << getOpenMPClauseName(DVar.CKind)
11514             << getOpenMPClauseName(OMPC_reduction);
11515         reportOriginalDsa(S, Stack, D, DVar);
11516         continue;
11517       }
11518 
11519       // OpenMP [2.14.3.6, Restrictions, p.1]
11520       //  A list item that appears in a reduction clause of a worksharing
11521       //  construct must be shared in the parallel regions to which any of the
11522       //  worksharing regions arising from the worksharing construct bind.
11523       if (isOpenMPWorksharingDirective(CurrDir) &&
11524           !isOpenMPParallelDirective(CurrDir) &&
11525           !isOpenMPTeamsDirective(CurrDir)) {
11526         DVar = Stack->getImplicitDSA(D, true);
11527         if (DVar.CKind != OMPC_shared) {
11528           S.Diag(ELoc, diag::err_omp_required_access)
11529               << getOpenMPClauseName(OMPC_reduction)
11530               << getOpenMPClauseName(OMPC_shared);
11531           reportOriginalDsa(S, Stack, D, DVar);
11532           continue;
11533         }
11534       }
11535     }
11536 
11537     // Try to find 'declare reduction' corresponding construct before using
11538     // builtin/overloaded operators.
11539     CXXCastPath BasePath;
11540     ExprResult DeclareReductionRef = buildDeclareReductionRef(
11541         S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
11542         ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
11543     if (DeclareReductionRef.isInvalid())
11544       continue;
11545     if (S.CurContext->isDependentContext() &&
11546         (DeclareReductionRef.isUnset() ||
11547          isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
11548       RD.push(RefExpr, DeclareReductionRef.get());
11549       continue;
11550     }
11551     if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
11552       // Not allowed reduction identifier is found.
11553       S.Diag(ReductionId.getBeginLoc(),
11554              diag::err_omp_unknown_reduction_identifier)
11555           << Type << ReductionIdRange;
11556       continue;
11557     }
11558 
11559     // OpenMP [2.14.3.6, reduction clause, Restrictions]
11560     // The type of a list item that appears in a reduction clause must be valid
11561     // for the reduction-identifier. For a max or min reduction in C, the type
11562     // of the list item must be an allowed arithmetic data type: char, int,
11563     // float, double, or _Bool, possibly modified with long, short, signed, or
11564     // unsigned. For a max or min reduction in C++, the type of the list item
11565     // must be an allowed arithmetic data type: char, wchar_t, int, float,
11566     // double, or bool, possibly modified with long, short, signed, or unsigned.
11567     if (DeclareReductionRef.isUnset()) {
11568       if ((BOK == BO_GT || BOK == BO_LT) &&
11569           !(Type->isScalarType() ||
11570             (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
11571         S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
11572             << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus;
11573         if (!ASE && !OASE) {
11574           bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
11575                                    VarDecl::DeclarationOnly;
11576           S.Diag(D->getLocation(),
11577                  IsDecl ? diag::note_previous_decl : diag::note_defined_here)
11578               << D;
11579         }
11580         continue;
11581       }
11582       if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
11583           !S.getLangOpts().CPlusPlus && Type->isFloatingType()) {
11584         S.Diag(ELoc, diag::err_omp_clause_floating_type_arg)
11585             << getOpenMPClauseName(ClauseKind);
11586         if (!ASE && !OASE) {
11587           bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
11588                                    VarDecl::DeclarationOnly;
11589           S.Diag(D->getLocation(),
11590                  IsDecl ? diag::note_previous_decl : diag::note_defined_here)
11591               << D;
11592         }
11593         continue;
11594       }
11595     }
11596 
11597     Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
11598     VarDecl *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs",
11599                                   D->hasAttrs() ? &D->getAttrs() : nullptr);
11600     VarDecl *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(),
11601                                   D->hasAttrs() ? &D->getAttrs() : nullptr);
11602     QualType PrivateTy = Type;
11603 
11604     // Try if we can determine constant lengths for all array sections and avoid
11605     // the VLA.
11606     bool ConstantLengthOASE = false;
11607     if (OASE) {
11608       bool SingleElement;
11609       llvm::SmallVector<llvm::APSInt, 4> ArraySizes;
11610       ConstantLengthOASE = checkOMPArraySectionConstantForReduction(
11611           Context, OASE, SingleElement, ArraySizes);
11612 
11613       // If we don't have a single element, we must emit a constant array type.
11614       if (ConstantLengthOASE && !SingleElement) {
11615         for (llvm::APSInt &Size : ArraySizes)
11616           PrivateTy = Context.getConstantArrayType(
11617               PrivateTy, Size, ArrayType::Normal, /*IndexTypeQuals=*/0);
11618       }
11619     }
11620 
11621     if ((OASE && !ConstantLengthOASE) ||
11622         (!OASE && !ASE &&
11623          D->getType().getNonReferenceType()->isVariablyModifiedType())) {
11624       if (!Context.getTargetInfo().isVLASupported() &&
11625           S.shouldDiagnoseTargetSupportFromOpenMP()) {
11626         S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
11627         S.Diag(ELoc, diag::note_vla_unsupported);
11628         continue;
11629       }
11630       // For arrays/array sections only:
11631       // Create pseudo array type for private copy. The size for this array will
11632       // be generated during codegen.
11633       // For array subscripts or single variables Private Ty is the same as Type
11634       // (type of the variable or single array element).
11635       PrivateTy = Context.getVariableArrayType(
11636           Type,
11637           new (Context) OpaqueValueExpr(ELoc, Context.getSizeType(), VK_RValue),
11638           ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
11639     } else if (!ASE && !OASE &&
11640                Context.getAsArrayType(D->getType().getNonReferenceType())) {
11641       PrivateTy = D->getType().getNonReferenceType();
11642     }
11643     // Private copy.
11644     VarDecl *PrivateVD =
11645         buildVarDecl(S, ELoc, PrivateTy, D->getName(),
11646                      D->hasAttrs() ? &D->getAttrs() : nullptr,
11647                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
11648     // Add initializer for private variable.
11649     Expr *Init = nullptr;
11650     DeclRefExpr *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc);
11651     DeclRefExpr *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc);
11652     if (DeclareReductionRef.isUsable()) {
11653       auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
11654       auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
11655       if (DRD->getInitializer()) {
11656         Init = DRDRef;
11657         RHSVD->setInit(DRDRef);
11658         RHSVD->setInitStyle(VarDecl::CallInit);
11659       }
11660     } else {
11661       switch (BOK) {
11662       case BO_Add:
11663       case BO_Xor:
11664       case BO_Or:
11665       case BO_LOr:
11666         // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
11667         if (Type->isScalarType() || Type->isAnyComplexType())
11668           Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get();
11669         break;
11670       case BO_Mul:
11671       case BO_LAnd:
11672         if (Type->isScalarType() || Type->isAnyComplexType()) {
11673           // '*' and '&&' reduction ops - initializer is '1'.
11674           Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get();
11675         }
11676         break;
11677       case BO_And: {
11678         // '&' reduction op - initializer is '~0'.
11679         QualType OrigType = Type;
11680         if (auto *ComplexTy = OrigType->getAs<ComplexType>())
11681           Type = ComplexTy->getElementType();
11682         if (Type->isRealFloatingType()) {
11683           llvm::APFloat InitValue =
11684               llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
11685                                              /*isIEEE=*/true);
11686           Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
11687                                          Type, ELoc);
11688         } else if (Type->isScalarType()) {
11689           uint64_t Size = Context.getTypeSize(Type);
11690           QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
11691           llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
11692           Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
11693         }
11694         if (Init && OrigType->isAnyComplexType()) {
11695           // Init = 0xFFFF + 0xFFFFi;
11696           auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
11697           Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
11698         }
11699         Type = OrigType;
11700         break;
11701       }
11702       case BO_LT:
11703       case BO_GT: {
11704         // 'min' reduction op - initializer is 'Largest representable number in
11705         // the reduction list item type'.
11706         // 'max' reduction op - initializer is 'Least representable number in
11707         // the reduction list item type'.
11708         if (Type->isIntegerType() || Type->isPointerType()) {
11709           bool IsSigned = Type->hasSignedIntegerRepresentation();
11710           uint64_t Size = Context.getTypeSize(Type);
11711           QualType IntTy =
11712               Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
11713           llvm::APInt InitValue =
11714               (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
11715                                         : llvm::APInt::getMinValue(Size)
11716                              : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
11717                                         : llvm::APInt::getMaxValue(Size);
11718           Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
11719           if (Type->isPointerType()) {
11720             // Cast to pointer type.
11721             ExprResult CastExpr = S.BuildCStyleCastExpr(
11722                 ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init);
11723             if (CastExpr.isInvalid())
11724               continue;
11725             Init = CastExpr.get();
11726           }
11727         } else if (Type->isRealFloatingType()) {
11728           llvm::APFloat InitValue = llvm::APFloat::getLargest(
11729               Context.getFloatTypeSemantics(Type), BOK != BO_LT);
11730           Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
11731                                          Type, ELoc);
11732         }
11733         break;
11734       }
11735       case BO_PtrMemD:
11736       case BO_PtrMemI:
11737       case BO_MulAssign:
11738       case BO_Div:
11739       case BO_Rem:
11740       case BO_Sub:
11741       case BO_Shl:
11742       case BO_Shr:
11743       case BO_LE:
11744       case BO_GE:
11745       case BO_EQ:
11746       case BO_NE:
11747       case BO_Cmp:
11748       case BO_AndAssign:
11749       case BO_XorAssign:
11750       case BO_OrAssign:
11751       case BO_Assign:
11752       case BO_AddAssign:
11753       case BO_SubAssign:
11754       case BO_DivAssign:
11755       case BO_RemAssign:
11756       case BO_ShlAssign:
11757       case BO_ShrAssign:
11758       case BO_Comma:
11759         llvm_unreachable("Unexpected reduction operation");
11760       }
11761     }
11762     if (Init && DeclareReductionRef.isUnset())
11763       S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
11764     else if (!Init)
11765       S.ActOnUninitializedDecl(RHSVD);
11766     if (RHSVD->isInvalidDecl())
11767       continue;
11768     if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) {
11769       S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible)
11770           << Type << ReductionIdRange;
11771       bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
11772                                VarDecl::DeclarationOnly;
11773       S.Diag(D->getLocation(),
11774              IsDecl ? diag::note_previous_decl : diag::note_defined_here)
11775           << D;
11776       continue;
11777     }
11778     // Store initializer for single element in private copy. Will be used during
11779     // codegen.
11780     PrivateVD->setInit(RHSVD->getInit());
11781     PrivateVD->setInitStyle(RHSVD->getInitStyle());
11782     DeclRefExpr *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc);
11783     ExprResult ReductionOp;
11784     if (DeclareReductionRef.isUsable()) {
11785       QualType RedTy = DeclareReductionRef.get()->getType();
11786       QualType PtrRedTy = Context.getPointerType(RedTy);
11787       ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
11788       ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
11789       if (!BasePath.empty()) {
11790         LHS = S.DefaultLvalueConversion(LHS.get());
11791         RHS = S.DefaultLvalueConversion(RHS.get());
11792         LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
11793                                        CK_UncheckedDerivedToBase, LHS.get(),
11794                                        &BasePath, LHS.get()->getValueKind());
11795         RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
11796                                        CK_UncheckedDerivedToBase, RHS.get(),
11797                                        &BasePath, RHS.get()->getValueKind());
11798       }
11799       FunctionProtoType::ExtProtoInfo EPI;
11800       QualType Params[] = {PtrRedTy, PtrRedTy};
11801       QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
11802       auto *OVE = new (Context) OpaqueValueExpr(
11803           ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
11804           S.DefaultLvalueConversion(DeclareReductionRef.get()).get());
11805       Expr *Args[] = {LHS.get(), RHS.get()};
11806       ReductionOp =
11807           CallExpr::Create(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
11808     } else {
11809       ReductionOp = S.BuildBinOp(
11810           Stack->getCurScope(), ReductionId.getBeginLoc(), BOK, LHSDRE, RHSDRE);
11811       if (ReductionOp.isUsable()) {
11812         if (BOK != BO_LT && BOK != BO_GT) {
11813           ReductionOp =
11814               S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
11815                            BO_Assign, LHSDRE, ReductionOp.get());
11816         } else {
11817           auto *ConditionalOp = new (Context)
11818               ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc, RHSDRE,
11819                                   Type, VK_LValue, OK_Ordinary);
11820           ReductionOp =
11821               S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
11822                            BO_Assign, LHSDRE, ConditionalOp);
11823         }
11824         if (ReductionOp.isUsable())
11825           ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get(),
11826                                               /*DiscardedValue*/ false);
11827       }
11828       if (!ReductionOp.isUsable())
11829         continue;
11830     }
11831 
11832     // OpenMP [2.15.4.6, Restrictions, p.2]
11833     // A list item that appears in an in_reduction clause of a task construct
11834     // must appear in a task_reduction clause of a construct associated with a
11835     // taskgroup region that includes the participating task in its taskgroup
11836     // set. The construct associated with the innermost region that meets this
11837     // condition must specify the same reduction-identifier as the in_reduction
11838     // clause.
11839     if (ClauseKind == OMPC_in_reduction) {
11840       SourceRange ParentSR;
11841       BinaryOperatorKind ParentBOK;
11842       const Expr *ParentReductionOp;
11843       Expr *ParentBOKTD, *ParentReductionOpTD;
11844       DSAStackTy::DSAVarData ParentBOKDSA =
11845           Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK,
11846                                                   ParentBOKTD);
11847       DSAStackTy::DSAVarData ParentReductionOpDSA =
11848           Stack->getTopMostTaskgroupReductionData(
11849               D, ParentSR, ParentReductionOp, ParentReductionOpTD);
11850       bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown;
11851       bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown;
11852       if (!IsParentBOK && !IsParentReductionOp) {
11853         S.Diag(ELoc, diag::err_omp_in_reduction_not_task_reduction);
11854         continue;
11855       }
11856       if ((DeclareReductionRef.isUnset() && IsParentReductionOp) ||
11857           (DeclareReductionRef.isUsable() && IsParentBOK) || BOK != ParentBOK ||
11858           IsParentReductionOp) {
11859         bool EmitError = true;
11860         if (IsParentReductionOp && DeclareReductionRef.isUsable()) {
11861           llvm::FoldingSetNodeID RedId, ParentRedId;
11862           ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true);
11863           DeclareReductionRef.get()->Profile(RedId, Context,
11864                                              /*Canonical=*/true);
11865           EmitError = RedId != ParentRedId;
11866         }
11867         if (EmitError) {
11868           S.Diag(ReductionId.getBeginLoc(),
11869                  diag::err_omp_reduction_identifier_mismatch)
11870               << ReductionIdRange << RefExpr->getSourceRange();
11871           S.Diag(ParentSR.getBegin(),
11872                  diag::note_omp_previous_reduction_identifier)
11873               << ParentSR
11874               << (IsParentBOK ? ParentBOKDSA.RefExpr
11875                               : ParentReductionOpDSA.RefExpr)
11876                      ->getSourceRange();
11877           continue;
11878         }
11879       }
11880       TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD;
11881       assert(TaskgroupDescriptor && "Taskgroup descriptor must be defined.");
11882     }
11883 
11884     DeclRefExpr *Ref = nullptr;
11885     Expr *VarsExpr = RefExpr->IgnoreParens();
11886     if (!VD && !S.CurContext->isDependentContext()) {
11887       if (ASE || OASE) {
11888         TransformExprToCaptures RebuildToCapture(S, D);
11889         VarsExpr =
11890             RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
11891         Ref = RebuildToCapture.getCapturedExpr();
11892       } else {
11893         VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false);
11894       }
11895       if (!S.isOpenMPCapturedDecl(D)) {
11896         RD.ExprCaptures.emplace_back(Ref->getDecl());
11897         if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
11898           ExprResult RefRes = S.DefaultLvalueConversion(Ref);
11899           if (!RefRes.isUsable())
11900             continue;
11901           ExprResult PostUpdateRes =
11902               S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
11903                            RefRes.get());
11904           if (!PostUpdateRes.isUsable())
11905             continue;
11906           if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
11907               Stack->getCurrentDirective() == OMPD_taskgroup) {
11908             S.Diag(RefExpr->getExprLoc(),
11909                    diag::err_omp_reduction_non_addressable_expression)
11910                 << RefExpr->getSourceRange();
11911             continue;
11912           }
11913           RD.ExprPostUpdates.emplace_back(
11914               S.IgnoredValueConversions(PostUpdateRes.get()).get());
11915         }
11916       }
11917     }
11918     // All reduction items are still marked as reduction (to do not increase
11919     // code base size).
11920     Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
11921     if (CurrDir == OMPD_taskgroup) {
11922       if (DeclareReductionRef.isUsable())
11923         Stack->addTaskgroupReductionData(D, ReductionIdRange,
11924                                          DeclareReductionRef.get());
11925       else
11926         Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK);
11927     }
11928     RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(),
11929             TaskgroupDescriptor);
11930   }
11931   return RD.Vars.empty();
11932 }
11933 
11934 OMPClause *Sema::ActOnOpenMPReductionClause(
11935     ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
11936     SourceLocation ColonLoc, SourceLocation EndLoc,
11937     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
11938     ArrayRef<Expr *> UnresolvedReductions) {
11939   ReductionData RD(VarList.size());
11940   if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList,
11941                                   StartLoc, LParenLoc, ColonLoc, EndLoc,
11942                                   ReductionIdScopeSpec, ReductionId,
11943                                   UnresolvedReductions, RD))
11944     return nullptr;
11945 
11946   return OMPReductionClause::Create(
11947       Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
11948       ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
11949       RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
11950       buildPreInits(Context, RD.ExprCaptures),
11951       buildPostUpdate(*this, RD.ExprPostUpdates));
11952 }
11953 
11954 OMPClause *Sema::ActOnOpenMPTaskReductionClause(
11955     ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
11956     SourceLocation ColonLoc, SourceLocation EndLoc,
11957     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
11958     ArrayRef<Expr *> UnresolvedReductions) {
11959   ReductionData RD(VarList.size());
11960   if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction, VarList,
11961                                   StartLoc, LParenLoc, ColonLoc, EndLoc,
11962                                   ReductionIdScopeSpec, ReductionId,
11963                                   UnresolvedReductions, RD))
11964     return nullptr;
11965 
11966   return OMPTaskReductionClause::Create(
11967       Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
11968       ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
11969       RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
11970       buildPreInits(Context, RD.ExprCaptures),
11971       buildPostUpdate(*this, RD.ExprPostUpdates));
11972 }
11973 
11974 OMPClause *Sema::ActOnOpenMPInReductionClause(
11975     ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
11976     SourceLocation ColonLoc, SourceLocation EndLoc,
11977     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
11978     ArrayRef<Expr *> UnresolvedReductions) {
11979   ReductionData RD(VarList.size());
11980   if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList,
11981                                   StartLoc, LParenLoc, ColonLoc, EndLoc,
11982                                   ReductionIdScopeSpec, ReductionId,
11983                                   UnresolvedReductions, RD))
11984     return nullptr;
11985 
11986   return OMPInReductionClause::Create(
11987       Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
11988       ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
11989       RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors,
11990       buildPreInits(Context, RD.ExprCaptures),
11991       buildPostUpdate(*this, RD.ExprPostUpdates));
11992 }
11993 
11994 bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
11995                                      SourceLocation LinLoc) {
11996   if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
11997       LinKind == OMPC_LINEAR_unknown) {
11998     Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
11999     return true;
12000   }
12001   return false;
12002 }
12003 
12004 bool Sema::CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc,
12005                                  OpenMPLinearClauseKind LinKind,
12006                                  QualType Type) {
12007   const auto *VD = dyn_cast_or_null<VarDecl>(D);
12008   // A variable must not have an incomplete type or a reference type.
12009   if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
12010     return true;
12011   if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
12012       !Type->isReferenceType()) {
12013     Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
12014         << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
12015     return true;
12016   }
12017   Type = Type.getNonReferenceType();
12018 
12019   // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
12020   // A variable that is privatized must not have a const-qualified type
12021   // unless it is of class type with a mutable member. This restriction does
12022   // not apply to the firstprivate clause.
12023   if (rejectConstNotMutableType(*this, D, Type, OMPC_linear, ELoc))
12024     return true;
12025 
12026   // A list item must be of integral or pointer type.
12027   Type = Type.getUnqualifiedType().getCanonicalType();
12028   const auto *Ty = Type.getTypePtrOrNull();
12029   if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
12030               !Ty->isPointerType())) {
12031     Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
12032     if (D) {
12033       bool IsDecl =
12034           !VD ||
12035           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
12036       Diag(D->getLocation(),
12037            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
12038           << D;
12039     }
12040     return true;
12041   }
12042   return false;
12043 }
12044 
12045 OMPClause *Sema::ActOnOpenMPLinearClause(
12046     ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
12047     SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
12048     SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
12049   SmallVector<Expr *, 8> Vars;
12050   SmallVector<Expr *, 8> Privates;
12051   SmallVector<Expr *, 8> Inits;
12052   SmallVector<Decl *, 4> ExprCaptures;
12053   SmallVector<Expr *, 4> ExprPostUpdates;
12054   if (CheckOpenMPLinearModifier(LinKind, LinLoc))
12055     LinKind = OMPC_LINEAR_val;
12056   for (Expr *RefExpr : VarList) {
12057     assert(RefExpr && "NULL expr in OpenMP linear clause.");
12058     SourceLocation ELoc;
12059     SourceRange ERange;
12060     Expr *SimpleRefExpr = RefExpr;
12061     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
12062     if (Res.second) {
12063       // It will be analyzed later.
12064       Vars.push_back(RefExpr);
12065       Privates.push_back(nullptr);
12066       Inits.push_back(nullptr);
12067     }
12068     ValueDecl *D = Res.first;
12069     if (!D)
12070       continue;
12071 
12072     QualType Type = D->getType();
12073     auto *VD = dyn_cast<VarDecl>(D);
12074 
12075     // OpenMP [2.14.3.7, linear clause]
12076     //  A list-item cannot appear in more than one linear clause.
12077     //  A list-item that appears in a linear clause cannot appear in any
12078     //  other data-sharing attribute clause.
12079     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
12080     if (DVar.RefExpr) {
12081       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
12082                                           << getOpenMPClauseName(OMPC_linear);
12083       reportOriginalDsa(*this, DSAStack, D, DVar);
12084       continue;
12085     }
12086 
12087     if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
12088       continue;
12089     Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
12090 
12091     // Build private copy of original var.
12092     VarDecl *Private =
12093         buildVarDecl(*this, ELoc, Type, D->getName(),
12094                      D->hasAttrs() ? &D->getAttrs() : nullptr,
12095                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
12096     DeclRefExpr *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
12097     // Build var to save initial value.
12098     VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
12099     Expr *InitExpr;
12100     DeclRefExpr *Ref = nullptr;
12101     if (!VD && !CurContext->isDependentContext()) {
12102       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
12103       if (!isOpenMPCapturedDecl(D)) {
12104         ExprCaptures.push_back(Ref->getDecl());
12105         if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
12106           ExprResult RefRes = DefaultLvalueConversion(Ref);
12107           if (!RefRes.isUsable())
12108             continue;
12109           ExprResult PostUpdateRes =
12110               BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
12111                          SimpleRefExpr, RefRes.get());
12112           if (!PostUpdateRes.isUsable())
12113             continue;
12114           ExprPostUpdates.push_back(
12115               IgnoredValueConversions(PostUpdateRes.get()).get());
12116         }
12117       }
12118     }
12119     if (LinKind == OMPC_LINEAR_uval)
12120       InitExpr = VD ? VD->getInit() : SimpleRefExpr;
12121     else
12122       InitExpr = VD ? SimpleRefExpr : Ref;
12123     AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
12124                          /*DirectInit=*/false);
12125     DeclRefExpr *InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
12126 
12127     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
12128     Vars.push_back((VD || CurContext->isDependentContext())
12129                        ? RefExpr->IgnoreParens()
12130                        : Ref);
12131     Privates.push_back(PrivateRef);
12132     Inits.push_back(InitRef);
12133   }
12134 
12135   if (Vars.empty())
12136     return nullptr;
12137 
12138   Expr *StepExpr = Step;
12139   Expr *CalcStepExpr = nullptr;
12140   if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
12141       !Step->isInstantiationDependent() &&
12142       !Step->containsUnexpandedParameterPack()) {
12143     SourceLocation StepLoc = Step->getBeginLoc();
12144     ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
12145     if (Val.isInvalid())
12146       return nullptr;
12147     StepExpr = Val.get();
12148 
12149     // Build var to save the step value.
12150     VarDecl *SaveVar =
12151         buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
12152     ExprResult SaveRef =
12153         buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
12154     ExprResult CalcStep =
12155         BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
12156     CalcStep = ActOnFinishFullExpr(CalcStep.get(), /*DiscardedValue*/ false);
12157 
12158     // Warn about zero linear step (it would be probably better specified as
12159     // making corresponding variables 'const').
12160     llvm::APSInt Result;
12161     bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
12162     if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
12163       Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
12164                                                      << (Vars.size() > 1);
12165     if (!IsConstant && CalcStep.isUsable()) {
12166       // Calculate the step beforehand instead of doing this on each iteration.
12167       // (This is not used if the number of iterations may be kfold-ed).
12168       CalcStepExpr = CalcStep.get();
12169     }
12170   }
12171 
12172   return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
12173                                  ColonLoc, EndLoc, Vars, Privates, Inits,
12174                                  StepExpr, CalcStepExpr,
12175                                  buildPreInits(Context, ExprCaptures),
12176                                  buildPostUpdate(*this, ExprPostUpdates));
12177 }
12178 
12179 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
12180                                      Expr *NumIterations, Sema &SemaRef,
12181                                      Scope *S, DSAStackTy *Stack) {
12182   // Walk the vars and build update/final expressions for the CodeGen.
12183   SmallVector<Expr *, 8> Updates;
12184   SmallVector<Expr *, 8> Finals;
12185   Expr *Step = Clause.getStep();
12186   Expr *CalcStep = Clause.getCalcStep();
12187   // OpenMP [2.14.3.7, linear clause]
12188   // If linear-step is not specified it is assumed to be 1.
12189   if (!Step)
12190     Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
12191   else if (CalcStep)
12192     Step = cast<BinaryOperator>(CalcStep)->getLHS();
12193   bool HasErrors = false;
12194   auto CurInit = Clause.inits().begin();
12195   auto CurPrivate = Clause.privates().begin();
12196   OpenMPLinearClauseKind LinKind = Clause.getModifier();
12197   for (Expr *RefExpr : Clause.varlists()) {
12198     SourceLocation ELoc;
12199     SourceRange ERange;
12200     Expr *SimpleRefExpr = RefExpr;
12201     auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange);
12202     ValueDecl *D = Res.first;
12203     if (Res.second || !D) {
12204       Updates.push_back(nullptr);
12205       Finals.push_back(nullptr);
12206       HasErrors = true;
12207       continue;
12208     }
12209     auto &&Info = Stack->isLoopControlVariable(D);
12210     // OpenMP [2.15.11, distribute simd Construct]
12211     // A list item may not appear in a linear clause, unless it is the loop
12212     // iteration variable.
12213     if (isOpenMPDistributeDirective(Stack->getCurrentDirective()) &&
12214         isOpenMPSimdDirective(Stack->getCurrentDirective()) && !Info.first) {
12215       SemaRef.Diag(ELoc,
12216                    diag::err_omp_linear_distribute_var_non_loop_iteration);
12217       Updates.push_back(nullptr);
12218       Finals.push_back(nullptr);
12219       HasErrors = true;
12220       continue;
12221     }
12222     Expr *InitExpr = *CurInit;
12223 
12224     // Build privatized reference to the current linear var.
12225     auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
12226     Expr *CapturedRef;
12227     if (LinKind == OMPC_LINEAR_uval)
12228       CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
12229     else
12230       CapturedRef =
12231           buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
12232                            DE->getType().getUnqualifiedType(), DE->getExprLoc(),
12233                            /*RefersToCapture=*/true);
12234 
12235     // Build update: Var = InitExpr + IV * Step
12236     ExprResult Update;
12237     if (!Info.first)
12238       Update =
12239           buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate,
12240                              InitExpr, IV, Step, /* Subtract */ false);
12241     else
12242       Update = *CurPrivate;
12243     Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getBeginLoc(),
12244                                          /*DiscardedValue*/ false);
12245 
12246     // Build final: Var = InitExpr + NumIterations * Step
12247     ExprResult Final;
12248     if (!Info.first)
12249       Final =
12250           buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
12251                              InitExpr, NumIterations, Step, /*Subtract=*/false);
12252     else
12253       Final = *CurPrivate;
12254     Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getBeginLoc(),
12255                                         /*DiscardedValue*/ false);
12256 
12257     if (!Update.isUsable() || !Final.isUsable()) {
12258       Updates.push_back(nullptr);
12259       Finals.push_back(nullptr);
12260       HasErrors = true;
12261     } else {
12262       Updates.push_back(Update.get());
12263       Finals.push_back(Final.get());
12264     }
12265     ++CurInit;
12266     ++CurPrivate;
12267   }
12268   Clause.setUpdates(Updates);
12269   Clause.setFinals(Finals);
12270   return HasErrors;
12271 }
12272 
12273 OMPClause *Sema::ActOnOpenMPAlignedClause(
12274     ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
12275     SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
12276   SmallVector<Expr *, 8> Vars;
12277   for (Expr *RefExpr : VarList) {
12278     assert(RefExpr && "NULL expr in OpenMP linear clause.");
12279     SourceLocation ELoc;
12280     SourceRange ERange;
12281     Expr *SimpleRefExpr = RefExpr;
12282     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
12283     if (Res.second) {
12284       // It will be analyzed later.
12285       Vars.push_back(RefExpr);
12286     }
12287     ValueDecl *D = Res.first;
12288     if (!D)
12289       continue;
12290 
12291     QualType QType = D->getType();
12292     auto *VD = dyn_cast<VarDecl>(D);
12293 
12294     // OpenMP  [2.8.1, simd construct, Restrictions]
12295     // The type of list items appearing in the aligned clause must be
12296     // array, pointer, reference to array, or reference to pointer.
12297     QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
12298     const Type *Ty = QType.getTypePtrOrNull();
12299     if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
12300       Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
12301           << QType << getLangOpts().CPlusPlus << ERange;
12302       bool IsDecl =
12303           !VD ||
12304           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
12305       Diag(D->getLocation(),
12306            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
12307           << D;
12308       continue;
12309     }
12310 
12311     // OpenMP  [2.8.1, simd construct, Restrictions]
12312     // A list-item cannot appear in more than one aligned clause.
12313     if (const Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
12314       Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
12315       Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
12316           << getOpenMPClauseName(OMPC_aligned);
12317       continue;
12318     }
12319 
12320     DeclRefExpr *Ref = nullptr;
12321     if (!VD && isOpenMPCapturedDecl(D))
12322       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
12323     Vars.push_back(DefaultFunctionArrayConversion(
12324                        (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
12325                        .get());
12326   }
12327 
12328   // OpenMP [2.8.1, simd construct, Description]
12329   // The parameter of the aligned clause, alignment, must be a constant
12330   // positive integer expression.
12331   // If no optional parameter is specified, implementation-defined default
12332   // alignments for SIMD instructions on the target platforms are assumed.
12333   if (Alignment != nullptr) {
12334     ExprResult AlignResult =
12335         VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
12336     if (AlignResult.isInvalid())
12337       return nullptr;
12338     Alignment = AlignResult.get();
12339   }
12340   if (Vars.empty())
12341     return nullptr;
12342 
12343   return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
12344                                   EndLoc, Vars, Alignment);
12345 }
12346 
12347 OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
12348                                          SourceLocation StartLoc,
12349                                          SourceLocation LParenLoc,
12350                                          SourceLocation EndLoc) {
12351   SmallVector<Expr *, 8> Vars;
12352   SmallVector<Expr *, 8> SrcExprs;
12353   SmallVector<Expr *, 8> DstExprs;
12354   SmallVector<Expr *, 8> AssignmentOps;
12355   for (Expr *RefExpr : VarList) {
12356     assert(RefExpr && "NULL expr in OpenMP copyin clause.");
12357     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
12358       // It will be analyzed later.
12359       Vars.push_back(RefExpr);
12360       SrcExprs.push_back(nullptr);
12361       DstExprs.push_back(nullptr);
12362       AssignmentOps.push_back(nullptr);
12363       continue;
12364     }
12365 
12366     SourceLocation ELoc = RefExpr->getExprLoc();
12367     // OpenMP [2.1, C/C++]
12368     //  A list item is a variable name.
12369     // OpenMP  [2.14.4.1, Restrictions, p.1]
12370     //  A list item that appears in a copyin clause must be threadprivate.
12371     auto *DE = dyn_cast<DeclRefExpr>(RefExpr);
12372     if (!DE || !isa<VarDecl>(DE->getDecl())) {
12373       Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
12374           << 0 << RefExpr->getSourceRange();
12375       continue;
12376     }
12377 
12378     Decl *D = DE->getDecl();
12379     auto *VD = cast<VarDecl>(D);
12380 
12381     QualType Type = VD->getType();
12382     if (Type->isDependentType() || Type->isInstantiationDependentType()) {
12383       // It will be analyzed later.
12384       Vars.push_back(DE);
12385       SrcExprs.push_back(nullptr);
12386       DstExprs.push_back(nullptr);
12387       AssignmentOps.push_back(nullptr);
12388       continue;
12389     }
12390 
12391     // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
12392     //  A list item that appears in a copyin clause must be threadprivate.
12393     if (!DSAStack->isThreadPrivate(VD)) {
12394       Diag(ELoc, diag::err_omp_required_access)
12395           << getOpenMPClauseName(OMPC_copyin)
12396           << getOpenMPDirectiveName(OMPD_threadprivate);
12397       continue;
12398     }
12399 
12400     // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
12401     //  A variable of class type (or array thereof) that appears in a
12402     //  copyin clause requires an accessible, unambiguous copy assignment
12403     //  operator for the class type.
12404     QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
12405     VarDecl *SrcVD =
12406         buildVarDecl(*this, DE->getBeginLoc(), ElemType.getUnqualifiedType(),
12407                      ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
12408     DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(
12409         *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
12410     VarDecl *DstVD =
12411         buildVarDecl(*this, DE->getBeginLoc(), ElemType, ".copyin.dst",
12412                      VD->hasAttrs() ? &VD->getAttrs() : nullptr);
12413     DeclRefExpr *PseudoDstExpr =
12414         buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
12415     // For arrays generate assignment operation for single element and replace
12416     // it by the original array element in CodeGen.
12417     ExprResult AssignmentOp =
12418         BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign, PseudoDstExpr,
12419                    PseudoSrcExpr);
12420     if (AssignmentOp.isInvalid())
12421       continue;
12422     AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
12423                                        /*DiscardedValue*/ false);
12424     if (AssignmentOp.isInvalid())
12425       continue;
12426 
12427     DSAStack->addDSA(VD, DE, OMPC_copyin);
12428     Vars.push_back(DE);
12429     SrcExprs.push_back(PseudoSrcExpr);
12430     DstExprs.push_back(PseudoDstExpr);
12431     AssignmentOps.push_back(AssignmentOp.get());
12432   }
12433 
12434   if (Vars.empty())
12435     return nullptr;
12436 
12437   return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
12438                                  SrcExprs, DstExprs, AssignmentOps);
12439 }
12440 
12441 OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
12442                                               SourceLocation StartLoc,
12443                                               SourceLocation LParenLoc,
12444                                               SourceLocation EndLoc) {
12445   SmallVector<Expr *, 8> Vars;
12446   SmallVector<Expr *, 8> SrcExprs;
12447   SmallVector<Expr *, 8> DstExprs;
12448   SmallVector<Expr *, 8> AssignmentOps;
12449   for (Expr *RefExpr : VarList) {
12450     assert(RefExpr && "NULL expr in OpenMP linear clause.");
12451     SourceLocation ELoc;
12452     SourceRange ERange;
12453     Expr *SimpleRefExpr = RefExpr;
12454     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
12455     if (Res.second) {
12456       // It will be analyzed later.
12457       Vars.push_back(RefExpr);
12458       SrcExprs.push_back(nullptr);
12459       DstExprs.push_back(nullptr);
12460       AssignmentOps.push_back(nullptr);
12461     }
12462     ValueDecl *D = Res.first;
12463     if (!D)
12464       continue;
12465 
12466     QualType Type = D->getType();
12467     auto *VD = dyn_cast<VarDecl>(D);
12468 
12469     // OpenMP [2.14.4.2, Restrictions, p.2]
12470     //  A list item that appears in a copyprivate clause may not appear in a
12471     //  private or firstprivate clause on the single construct.
12472     if (!VD || !DSAStack->isThreadPrivate(VD)) {
12473       DSAStackTy::DSAVarData DVar =
12474           DSAStack->getTopDSA(D, /*FromParent=*/false);
12475       if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
12476           DVar.RefExpr) {
12477         Diag(ELoc, diag::err_omp_wrong_dsa)
12478             << getOpenMPClauseName(DVar.CKind)
12479             << getOpenMPClauseName(OMPC_copyprivate);
12480         reportOriginalDsa(*this, DSAStack, D, DVar);
12481         continue;
12482       }
12483 
12484       // OpenMP [2.11.4.2, Restrictions, p.1]
12485       //  All list items that appear in a copyprivate clause must be either
12486       //  threadprivate or private in the enclosing context.
12487       if (DVar.CKind == OMPC_unknown) {
12488         DVar = DSAStack->getImplicitDSA(D, false);
12489         if (DVar.CKind == OMPC_shared) {
12490           Diag(ELoc, diag::err_omp_required_access)
12491               << getOpenMPClauseName(OMPC_copyprivate)
12492               << "threadprivate or private in the enclosing context";
12493           reportOriginalDsa(*this, DSAStack, D, DVar);
12494           continue;
12495         }
12496       }
12497     }
12498 
12499     // Variably modified types are not supported.
12500     if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
12501       Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
12502           << getOpenMPClauseName(OMPC_copyprivate) << Type
12503           << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
12504       bool IsDecl =
12505           !VD ||
12506           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
12507       Diag(D->getLocation(),
12508            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
12509           << D;
12510       continue;
12511     }
12512 
12513     // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
12514     //  A variable of class type (or array thereof) that appears in a
12515     //  copyin clause requires an accessible, unambiguous copy assignment
12516     //  operator for the class type.
12517     Type = Context.getBaseElementType(Type.getNonReferenceType())
12518                .getUnqualifiedType();
12519     VarDecl *SrcVD =
12520         buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.src",
12521                      D->hasAttrs() ? &D->getAttrs() : nullptr);
12522     DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
12523     VarDecl *DstVD =
12524         buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.dst",
12525                      D->hasAttrs() ? &D->getAttrs() : nullptr);
12526     DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
12527     ExprResult AssignmentOp = BuildBinOp(
12528         DSAStack->getCurScope(), ELoc, BO_Assign, PseudoDstExpr, PseudoSrcExpr);
12529     if (AssignmentOp.isInvalid())
12530       continue;
12531     AssignmentOp =
12532         ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
12533     if (AssignmentOp.isInvalid())
12534       continue;
12535 
12536     // No need to mark vars as copyprivate, they are already threadprivate or
12537     // implicitly private.
12538     assert(VD || isOpenMPCapturedDecl(D));
12539     Vars.push_back(
12540         VD ? RefExpr->IgnoreParens()
12541            : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
12542     SrcExprs.push_back(PseudoSrcExpr);
12543     DstExprs.push_back(PseudoDstExpr);
12544     AssignmentOps.push_back(AssignmentOp.get());
12545   }
12546 
12547   if (Vars.empty())
12548     return nullptr;
12549 
12550   return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
12551                                       Vars, SrcExprs, DstExprs, AssignmentOps);
12552 }
12553 
12554 OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
12555                                         SourceLocation StartLoc,
12556                                         SourceLocation LParenLoc,
12557                                         SourceLocation EndLoc) {
12558   if (VarList.empty())
12559     return nullptr;
12560 
12561   return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
12562 }
12563 
12564 OMPClause *
12565 Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
12566                               SourceLocation DepLoc, SourceLocation ColonLoc,
12567                               ArrayRef<Expr *> VarList, SourceLocation StartLoc,
12568                               SourceLocation LParenLoc, SourceLocation EndLoc) {
12569   if (DSAStack->getCurrentDirective() == OMPD_ordered &&
12570       DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
12571     Diag(DepLoc, diag::err_omp_unexpected_clause_value)
12572         << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
12573     return nullptr;
12574   }
12575   if (DSAStack->getCurrentDirective() != OMPD_ordered &&
12576       (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
12577        DepKind == OMPC_DEPEND_sink)) {
12578     unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
12579     Diag(DepLoc, diag::err_omp_unexpected_clause_value)
12580         << getListOfPossibleValues(OMPC_depend, /*First=*/0,
12581                                    /*Last=*/OMPC_DEPEND_unknown, Except)
12582         << getOpenMPClauseName(OMPC_depend);
12583     return nullptr;
12584   }
12585   SmallVector<Expr *, 8> Vars;
12586   DSAStackTy::OperatorOffsetTy OpsOffs;
12587   llvm::APSInt DepCounter(/*BitWidth=*/32);
12588   llvm::APSInt TotalDepCount(/*BitWidth=*/32);
12589   if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) {
12590     if (const Expr *OrderedCountExpr =
12591             DSAStack->getParentOrderedRegionParam().first) {
12592       TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
12593       TotalDepCount.setIsUnsigned(/*Val=*/true);
12594     }
12595   }
12596   for (Expr *RefExpr : VarList) {
12597     assert(RefExpr && "NULL expr in OpenMP shared clause.");
12598     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
12599       // It will be analyzed later.
12600       Vars.push_back(RefExpr);
12601       continue;
12602     }
12603 
12604     SourceLocation ELoc = RefExpr->getExprLoc();
12605     Expr *SimpleExpr = RefExpr->IgnoreParenCasts();
12606     if (DepKind == OMPC_DEPEND_sink) {
12607       if (DSAStack->getParentOrderedRegionParam().first &&
12608           DepCounter >= TotalDepCount) {
12609         Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
12610         continue;
12611       }
12612       ++DepCounter;
12613       // OpenMP  [2.13.9, Summary]
12614       // depend(dependence-type : vec), where dependence-type is:
12615       // 'sink' and where vec is the iteration vector, which has the form:
12616       //  x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
12617       // where n is the value specified by the ordered clause in the loop
12618       // directive, xi denotes the loop iteration variable of the i-th nested
12619       // loop associated with the loop directive, and di is a constant
12620       // non-negative integer.
12621       if (CurContext->isDependentContext()) {
12622         // It will be analyzed later.
12623         Vars.push_back(RefExpr);
12624         continue;
12625       }
12626       SimpleExpr = SimpleExpr->IgnoreImplicit();
12627       OverloadedOperatorKind OOK = OO_None;
12628       SourceLocation OOLoc;
12629       Expr *LHS = SimpleExpr;
12630       Expr *RHS = nullptr;
12631       if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
12632         OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
12633         OOLoc = BO->getOperatorLoc();
12634         LHS = BO->getLHS()->IgnoreParenImpCasts();
12635         RHS = BO->getRHS()->IgnoreParenImpCasts();
12636       } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
12637         OOK = OCE->getOperator();
12638         OOLoc = OCE->getOperatorLoc();
12639         LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
12640         RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
12641       } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
12642         OOK = MCE->getMethodDecl()
12643                   ->getNameInfo()
12644                   .getName()
12645                   .getCXXOverloadedOperator();
12646         OOLoc = MCE->getCallee()->getExprLoc();
12647         LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
12648         RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
12649       }
12650       SourceLocation ELoc;
12651       SourceRange ERange;
12652       auto Res = getPrivateItem(*this, LHS, ELoc, ERange);
12653       if (Res.second) {
12654         // It will be analyzed later.
12655         Vars.push_back(RefExpr);
12656       }
12657       ValueDecl *D = Res.first;
12658       if (!D)
12659         continue;
12660 
12661       if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
12662         Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
12663         continue;
12664       }
12665       if (RHS) {
12666         ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
12667             RHS, OMPC_depend, /*StrictlyPositive=*/false);
12668         if (RHSRes.isInvalid())
12669           continue;
12670       }
12671       if (!CurContext->isDependentContext() &&
12672           DSAStack->getParentOrderedRegionParam().first &&
12673           DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
12674         const ValueDecl *VD =
12675             DSAStack->getParentLoopControlVariable(DepCounter.getZExtValue());
12676         if (VD)
12677           Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
12678               << 1 << VD;
12679         else
12680           Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0;
12681         continue;
12682       }
12683       OpsOffs.emplace_back(RHS, OOK);
12684     } else {
12685       auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
12686       if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
12687           (ASE &&
12688            !ASE->getBase()->getType().getNonReferenceType()->isPointerType() &&
12689            !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
12690         Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
12691             << RefExpr->getSourceRange();
12692         continue;
12693       }
12694       bool Suppress = getDiagnostics().getSuppressAllDiagnostics();
12695       getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
12696       ExprResult Res =
12697           CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RefExpr->IgnoreParenImpCasts());
12698       getDiagnostics().setSuppressAllDiagnostics(Suppress);
12699       if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr)) {
12700         Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
12701             << RefExpr->getSourceRange();
12702         continue;
12703       }
12704     }
12705     Vars.push_back(RefExpr->IgnoreParenImpCasts());
12706   }
12707 
12708   if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
12709       TotalDepCount > VarList.size() &&
12710       DSAStack->getParentOrderedRegionParam().first &&
12711       DSAStack->getParentLoopControlVariable(VarList.size() + 1)) {
12712     Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
12713         << 1 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
12714   }
12715   if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
12716       Vars.empty())
12717     return nullptr;
12718 
12719   auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
12720                                     DepKind, DepLoc, ColonLoc, Vars,
12721                                     TotalDepCount.getZExtValue());
12722   if ((DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) &&
12723       DSAStack->isParentOrderedRegion())
12724     DSAStack->addDoacrossDependClause(C, OpsOffs);
12725   return C;
12726 }
12727 
12728 OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
12729                                          SourceLocation LParenLoc,
12730                                          SourceLocation EndLoc) {
12731   Expr *ValExpr = Device;
12732   Stmt *HelperValStmt = nullptr;
12733 
12734   // OpenMP [2.9.1, Restrictions]
12735   // The device expression must evaluate to a non-negative integer value.
12736   if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
12737                                  /*StrictlyPositive=*/false))
12738     return nullptr;
12739 
12740   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
12741   OpenMPDirectiveKind CaptureRegion =
12742       getOpenMPCaptureRegionForClause(DKind, OMPC_device);
12743   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
12744     ValExpr = MakeFullExpr(ValExpr).get();
12745     llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
12746     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
12747     HelperValStmt = buildPreInits(Context, Captures);
12748   }
12749 
12750   return new (Context) OMPDeviceClause(ValExpr, HelperValStmt, CaptureRegion,
12751                                        StartLoc, LParenLoc, EndLoc);
12752 }
12753 
12754 static bool checkTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
12755                               DSAStackTy *Stack, QualType QTy,
12756                               bool FullCheck = true) {
12757   NamedDecl *ND;
12758   if (QTy->isIncompleteType(&ND)) {
12759     SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
12760     return false;
12761   }
12762   if (FullCheck && !SemaRef.CurContext->isDependentContext() &&
12763       !QTy.isTrivialType(SemaRef.Context))
12764     SemaRef.Diag(SL, diag::warn_omp_non_trivial_type_mapped) << QTy << SR;
12765   return true;
12766 }
12767 
12768 /// Return true if it can be proven that the provided array expression
12769 /// (array section or array subscript) does NOT specify the whole size of the
12770 /// array whose base type is \a BaseQTy.
12771 static bool checkArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
12772                                                         const Expr *E,
12773                                                         QualType BaseQTy) {
12774   const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
12775 
12776   // If this is an array subscript, it refers to the whole size if the size of
12777   // the dimension is constant and equals 1. Also, an array section assumes the
12778   // format of an array subscript if no colon is used.
12779   if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
12780     if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
12781       return ATy->getSize().getSExtValue() != 1;
12782     // Size can't be evaluated statically.
12783     return false;
12784   }
12785 
12786   assert(OASE && "Expecting array section if not an array subscript.");
12787   const Expr *LowerBound = OASE->getLowerBound();
12788   const Expr *Length = OASE->getLength();
12789 
12790   // If there is a lower bound that does not evaluates to zero, we are not
12791   // covering the whole dimension.
12792   if (LowerBound) {
12793     Expr::EvalResult Result;
12794     if (!LowerBound->EvaluateAsInt(Result, SemaRef.getASTContext()))
12795       return false; // Can't get the integer value as a constant.
12796 
12797     llvm::APSInt ConstLowerBound = Result.Val.getInt();
12798     if (ConstLowerBound.getSExtValue())
12799       return true;
12800   }
12801 
12802   // If we don't have a length we covering the whole dimension.
12803   if (!Length)
12804     return false;
12805 
12806   // If the base is a pointer, we don't have a way to get the size of the
12807   // pointee.
12808   if (BaseQTy->isPointerType())
12809     return false;
12810 
12811   // We can only check if the length is the same as the size of the dimension
12812   // if we have a constant array.
12813   const auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
12814   if (!CATy)
12815     return false;
12816 
12817   Expr::EvalResult Result;
12818   if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
12819     return false; // Can't get the integer value as a constant.
12820 
12821   llvm::APSInt ConstLength = Result.Val.getInt();
12822   return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
12823 }
12824 
12825 // Return true if it can be proven that the provided array expression (array
12826 // section or array subscript) does NOT specify a single element of the array
12827 // whose base type is \a BaseQTy.
12828 static bool checkArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
12829                                                         const Expr *E,
12830                                                         QualType BaseQTy) {
12831   const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
12832 
12833   // An array subscript always refer to a single element. Also, an array section
12834   // assumes the format of an array subscript if no colon is used.
12835   if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
12836     return false;
12837 
12838   assert(OASE && "Expecting array section if not an array subscript.");
12839   const Expr *Length = OASE->getLength();
12840 
12841   // If we don't have a length we have to check if the array has unitary size
12842   // for this dimension. Also, we should always expect a length if the base type
12843   // is pointer.
12844   if (!Length) {
12845     if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
12846       return ATy->getSize().getSExtValue() != 1;
12847     // We cannot assume anything.
12848     return false;
12849   }
12850 
12851   // Check if the length evaluates to 1.
12852   Expr::EvalResult Result;
12853   if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
12854     return false; // Can't get the integer value as a constant.
12855 
12856   llvm::APSInt ConstLength = Result.Val.getInt();
12857   return ConstLength.getSExtValue() != 1;
12858 }
12859 
12860 // Return the expression of the base of the mappable expression or null if it
12861 // cannot be determined and do all the necessary checks to see if the expression
12862 // is valid as a standalone mappable expression. In the process, record all the
12863 // components of the expression.
12864 static const Expr *checkMapClauseExpressionBase(
12865     Sema &SemaRef, Expr *E,
12866     OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
12867     OpenMPClauseKind CKind, bool NoDiagnose) {
12868   SourceLocation ELoc = E->getExprLoc();
12869   SourceRange ERange = E->getSourceRange();
12870 
12871   // The base of elements of list in a map clause have to be either:
12872   //  - a reference to variable or field.
12873   //  - a member expression.
12874   //  - an array expression.
12875   //
12876   // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
12877   // reference to 'r'.
12878   //
12879   // If we have:
12880   //
12881   // struct SS {
12882   //   Bla S;
12883   //   foo() {
12884   //     #pragma omp target map (S.Arr[:12]);
12885   //   }
12886   // }
12887   //
12888   // We want to retrieve the member expression 'this->S';
12889 
12890   const Expr *RelevantExpr = nullptr;
12891 
12892   // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
12893   //  If a list item is an array section, it must specify contiguous storage.
12894   //
12895   // For this restriction it is sufficient that we make sure only references
12896   // to variables or fields and array expressions, and that no array sections
12897   // exist except in the rightmost expression (unless they cover the whole
12898   // dimension of the array). E.g. these would be invalid:
12899   //
12900   //   r.ArrS[3:5].Arr[6:7]
12901   //
12902   //   r.ArrS[3:5].x
12903   //
12904   // but these would be valid:
12905   //   r.ArrS[3].Arr[6:7]
12906   //
12907   //   r.ArrS[3].x
12908 
12909   bool AllowUnitySizeArraySection = true;
12910   bool AllowWholeSizeArraySection = true;
12911 
12912   while (!RelevantExpr) {
12913     E = E->IgnoreParenImpCasts();
12914 
12915     if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
12916       if (!isa<VarDecl>(CurE->getDecl()))
12917         return nullptr;
12918 
12919       RelevantExpr = CurE;
12920 
12921       // If we got a reference to a declaration, we should not expect any array
12922       // section before that.
12923       AllowUnitySizeArraySection = false;
12924       AllowWholeSizeArraySection = false;
12925 
12926       // Record the component.
12927       CurComponents.emplace_back(CurE, CurE->getDecl());
12928     } else if (auto *CurE = dyn_cast<MemberExpr>(E)) {
12929       Expr *BaseE = CurE->getBase()->IgnoreParenImpCasts();
12930 
12931       if (isa<CXXThisExpr>(BaseE))
12932         // We found a base expression: this->Val.
12933         RelevantExpr = CurE;
12934       else
12935         E = BaseE;
12936 
12937       if (!isa<FieldDecl>(CurE->getMemberDecl())) {
12938         if (!NoDiagnose) {
12939           SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
12940               << CurE->getSourceRange();
12941           return nullptr;
12942         }
12943         if (RelevantExpr)
12944           return nullptr;
12945         continue;
12946       }
12947 
12948       auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
12949 
12950       // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
12951       //  A bit-field cannot appear in a map clause.
12952       //
12953       if (FD->isBitField()) {
12954         if (!NoDiagnose) {
12955           SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
12956               << CurE->getSourceRange() << getOpenMPClauseName(CKind);
12957           return nullptr;
12958         }
12959         if (RelevantExpr)
12960           return nullptr;
12961         continue;
12962       }
12963 
12964       // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
12965       //  If the type of a list item is a reference to a type T then the type
12966       //  will be considered to be T for all purposes of this clause.
12967       QualType CurType = BaseE->getType().getNonReferenceType();
12968 
12969       // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
12970       //  A list item cannot be a variable that is a member of a structure with
12971       //  a union type.
12972       //
12973       if (CurType->isUnionType()) {
12974         if (!NoDiagnose) {
12975           SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
12976               << CurE->getSourceRange();
12977           return nullptr;
12978         }
12979         continue;
12980       }
12981 
12982       // If we got a member expression, we should not expect any array section
12983       // before that:
12984       //
12985       // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
12986       //  If a list item is an element of a structure, only the rightmost symbol
12987       //  of the variable reference can be an array section.
12988       //
12989       AllowUnitySizeArraySection = false;
12990       AllowWholeSizeArraySection = false;
12991 
12992       // Record the component.
12993       CurComponents.emplace_back(CurE, FD);
12994     } else if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
12995       E = CurE->getBase()->IgnoreParenImpCasts();
12996 
12997       if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
12998         if (!NoDiagnose) {
12999           SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
13000               << 0 << CurE->getSourceRange();
13001           return nullptr;
13002         }
13003         continue;
13004       }
13005 
13006       // If we got an array subscript that express the whole dimension we
13007       // can have any array expressions before. If it only expressing part of
13008       // the dimension, we can only have unitary-size array expressions.
13009       if (checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
13010                                                       E->getType()))
13011         AllowWholeSizeArraySection = false;
13012 
13013       if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
13014         Expr::EvalResult Result;
13015         if (CurE->getIdx()->EvaluateAsInt(Result, SemaRef.getASTContext())) {
13016           if (!Result.Val.getInt().isNullValue()) {
13017             SemaRef.Diag(CurE->getIdx()->getExprLoc(),
13018                          diag::err_omp_invalid_map_this_expr);
13019             SemaRef.Diag(CurE->getIdx()->getExprLoc(),
13020                          diag::note_omp_invalid_subscript_on_this_ptr_map);
13021           }
13022         }
13023         RelevantExpr = TE;
13024       }
13025 
13026       // Record the component - we don't have any declaration associated.
13027       CurComponents.emplace_back(CurE, nullptr);
13028     } else if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
13029       assert(!NoDiagnose && "Array sections cannot be implicitly mapped.");
13030       E = CurE->getBase()->IgnoreParenImpCasts();
13031 
13032       QualType CurType =
13033           OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
13034 
13035       // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
13036       //  If the type of a list item is a reference to a type T then the type
13037       //  will be considered to be T for all purposes of this clause.
13038       if (CurType->isReferenceType())
13039         CurType = CurType->getPointeeType();
13040 
13041       bool IsPointer = CurType->isAnyPointerType();
13042 
13043       if (!IsPointer && !CurType->isArrayType()) {
13044         SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
13045             << 0 << CurE->getSourceRange();
13046         return nullptr;
13047       }
13048 
13049       bool NotWhole =
13050           checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
13051       bool NotUnity =
13052           checkArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
13053 
13054       if (AllowWholeSizeArraySection) {
13055         // Any array section is currently allowed. Allowing a whole size array
13056         // section implies allowing a unity array section as well.
13057         //
13058         // If this array section refers to the whole dimension we can still
13059         // accept other array sections before this one, except if the base is a
13060         // pointer. Otherwise, only unitary sections are accepted.
13061         if (NotWhole || IsPointer)
13062           AllowWholeSizeArraySection = false;
13063       } else if (AllowUnitySizeArraySection && NotUnity) {
13064         // A unity or whole array section is not allowed and that is not
13065         // compatible with the properties of the current array section.
13066         SemaRef.Diag(
13067             ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
13068             << CurE->getSourceRange();
13069         return nullptr;
13070       }
13071 
13072       if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
13073         Expr::EvalResult ResultR;
13074         Expr::EvalResult ResultL;
13075         if (CurE->getLength()->EvaluateAsInt(ResultR,
13076                                              SemaRef.getASTContext())) {
13077           if (!ResultR.Val.getInt().isOneValue()) {
13078             SemaRef.Diag(CurE->getLength()->getExprLoc(),
13079                          diag::err_omp_invalid_map_this_expr);
13080             SemaRef.Diag(CurE->getLength()->getExprLoc(),
13081                          diag::note_omp_invalid_length_on_this_ptr_mapping);
13082           }
13083         }
13084         if (CurE->getLowerBound() && CurE->getLowerBound()->EvaluateAsInt(
13085                                         ResultL, SemaRef.getASTContext())) {
13086           if (!ResultL.Val.getInt().isNullValue()) {
13087             SemaRef.Diag(CurE->getLowerBound()->getExprLoc(),
13088                          diag::err_omp_invalid_map_this_expr);
13089             SemaRef.Diag(CurE->getLowerBound()->getExprLoc(),
13090                          diag::note_omp_invalid_lower_bound_on_this_ptr_mapping);
13091           }
13092         }
13093         RelevantExpr = TE;
13094       }
13095 
13096       // Record the component - we don't have any declaration associated.
13097       CurComponents.emplace_back(CurE, nullptr);
13098     } else {
13099       if (!NoDiagnose) {
13100         // If nothing else worked, this is not a valid map clause expression.
13101         SemaRef.Diag(
13102             ELoc, diag::err_omp_expected_named_var_member_or_array_expression)
13103             << ERange;
13104       }
13105       return nullptr;
13106     }
13107   }
13108 
13109   return RelevantExpr;
13110 }
13111 
13112 // Return true if expression E associated with value VD has conflicts with other
13113 // map information.
13114 static bool checkMapConflicts(
13115     Sema &SemaRef, DSAStackTy *DSAS, const ValueDecl *VD, const Expr *E,
13116     bool CurrentRegionOnly,
13117     OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
13118     OpenMPClauseKind CKind) {
13119   assert(VD && E);
13120   SourceLocation ELoc = E->getExprLoc();
13121   SourceRange ERange = E->getSourceRange();
13122 
13123   // In order to easily check the conflicts we need to match each component of
13124   // the expression under test with the components of the expressions that are
13125   // already in the stack.
13126 
13127   assert(!CurComponents.empty() && "Map clause expression with no components!");
13128   assert(CurComponents.back().getAssociatedDeclaration() == VD &&
13129          "Map clause expression with unexpected base!");
13130 
13131   // Variables to help detecting enclosing problems in data environment nests.
13132   bool IsEnclosedByDataEnvironmentExpr = false;
13133   const Expr *EnclosingExpr = nullptr;
13134 
13135   bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
13136       VD, CurrentRegionOnly,
13137       [&IsEnclosedByDataEnvironmentExpr, &SemaRef, VD, CurrentRegionOnly, ELoc,
13138        ERange, CKind, &EnclosingExpr,
13139        CurComponents](OMPClauseMappableExprCommon::MappableExprComponentListRef
13140                           StackComponents,
13141                       OpenMPClauseKind) {
13142         assert(!StackComponents.empty() &&
13143                "Map clause expression with no components!");
13144         assert(StackComponents.back().getAssociatedDeclaration() == VD &&
13145                "Map clause expression with unexpected base!");
13146         (void)VD;
13147 
13148         // The whole expression in the stack.
13149         const Expr *RE = StackComponents.front().getAssociatedExpression();
13150 
13151         // Expressions must start from the same base. Here we detect at which
13152         // point both expressions diverge from each other and see if we can
13153         // detect if the memory referred to both expressions is contiguous and
13154         // do not overlap.
13155         auto CI = CurComponents.rbegin();
13156         auto CE = CurComponents.rend();
13157         auto SI = StackComponents.rbegin();
13158         auto SE = StackComponents.rend();
13159         for (; CI != CE && SI != SE; ++CI, ++SI) {
13160 
13161           // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
13162           //  At most one list item can be an array item derived from a given
13163           //  variable in map clauses of the same construct.
13164           if (CurrentRegionOnly &&
13165               (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
13166                isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
13167               (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
13168                isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
13169             SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
13170                          diag::err_omp_multiple_array_items_in_map_clause)
13171                 << CI->getAssociatedExpression()->getSourceRange();
13172             SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
13173                          diag::note_used_here)
13174                 << SI->getAssociatedExpression()->getSourceRange();
13175             return true;
13176           }
13177 
13178           // Do both expressions have the same kind?
13179           if (CI->getAssociatedExpression()->getStmtClass() !=
13180               SI->getAssociatedExpression()->getStmtClass())
13181             break;
13182 
13183           // Are we dealing with different variables/fields?
13184           if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
13185             break;
13186         }
13187         // Check if the extra components of the expressions in the enclosing
13188         // data environment are redundant for the current base declaration.
13189         // If they are, the maps completely overlap, which is legal.
13190         for (; SI != SE; ++SI) {
13191           QualType Type;
13192           if (const auto *ASE =
13193                   dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
13194             Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
13195           } else if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(
13196                          SI->getAssociatedExpression())) {
13197             const Expr *E = OASE->getBase()->IgnoreParenImpCasts();
13198             Type =
13199                 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
13200           }
13201           if (Type.isNull() || Type->isAnyPointerType() ||
13202               checkArrayExpressionDoesNotReferToWholeSize(
13203                   SemaRef, SI->getAssociatedExpression(), Type))
13204             break;
13205         }
13206 
13207         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
13208         //  List items of map clauses in the same construct must not share
13209         //  original storage.
13210         //
13211         // If the expressions are exactly the same or one is a subset of the
13212         // other, it means they are sharing storage.
13213         if (CI == CE && SI == SE) {
13214           if (CurrentRegionOnly) {
13215             if (CKind == OMPC_map) {
13216               SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
13217             } else {
13218               assert(CKind == OMPC_to || CKind == OMPC_from);
13219               SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
13220                   << ERange;
13221             }
13222             SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
13223                 << RE->getSourceRange();
13224             return true;
13225           }
13226           // If we find the same expression in the enclosing data environment,
13227           // that is legal.
13228           IsEnclosedByDataEnvironmentExpr = true;
13229           return false;
13230         }
13231 
13232         QualType DerivedType =
13233             std::prev(CI)->getAssociatedDeclaration()->getType();
13234         SourceLocation DerivedLoc =
13235             std::prev(CI)->getAssociatedExpression()->getExprLoc();
13236 
13237         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
13238         //  If the type of a list item is a reference to a type T then the type
13239         //  will be considered to be T for all purposes of this clause.
13240         DerivedType = DerivedType.getNonReferenceType();
13241 
13242         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
13243         //  A variable for which the type is pointer and an array section
13244         //  derived from that variable must not appear as list items of map
13245         //  clauses of the same construct.
13246         //
13247         // Also, cover one of the cases in:
13248         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
13249         //  If any part of the original storage of a list item has corresponding
13250         //  storage in the device data environment, all of the original storage
13251         //  must have corresponding storage in the device data environment.
13252         //
13253         if (DerivedType->isAnyPointerType()) {
13254           if (CI == CE || SI == SE) {
13255             SemaRef.Diag(
13256                 DerivedLoc,
13257                 diag::err_omp_pointer_mapped_along_with_derived_section)
13258                 << DerivedLoc;
13259             SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
13260                 << RE->getSourceRange();
13261             return true;
13262           }
13263           if (CI->getAssociatedExpression()->getStmtClass() !=
13264                          SI->getAssociatedExpression()->getStmtClass() ||
13265                      CI->getAssociatedDeclaration()->getCanonicalDecl() ==
13266                          SI->getAssociatedDeclaration()->getCanonicalDecl()) {
13267             assert(CI != CE && SI != SE);
13268             SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_dereferenced)
13269                 << DerivedLoc;
13270             SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
13271                 << RE->getSourceRange();
13272             return true;
13273           }
13274         }
13275 
13276         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
13277         //  List items of map clauses in the same construct must not share
13278         //  original storage.
13279         //
13280         // An expression is a subset of the other.
13281         if (CurrentRegionOnly && (CI == CE || SI == SE)) {
13282           if (CKind == OMPC_map) {
13283             if (CI != CE || SI != SE) {
13284               // Allow constructs like this: map(s, s.ptr[0:1]), where s.ptr is
13285               // a pointer.
13286               auto Begin =
13287                   CI != CE ? CurComponents.begin() : StackComponents.begin();
13288               auto End = CI != CE ? CurComponents.end() : StackComponents.end();
13289               auto It = Begin;
13290               while (It != End && !It->getAssociatedDeclaration())
13291                 std::advance(It, 1);
13292               assert(It != End &&
13293                      "Expected at least one component with the declaration.");
13294               if (It != Begin && It->getAssociatedDeclaration()
13295                                      ->getType()
13296                                      .getCanonicalType()
13297                                      ->isAnyPointerType()) {
13298                 IsEnclosedByDataEnvironmentExpr = false;
13299                 EnclosingExpr = nullptr;
13300                 return false;
13301               }
13302             }
13303             SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
13304           } else {
13305             assert(CKind == OMPC_to || CKind == OMPC_from);
13306             SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
13307                 << ERange;
13308           }
13309           SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
13310               << RE->getSourceRange();
13311           return true;
13312         }
13313 
13314         // The current expression uses the same base as other expression in the
13315         // data environment but does not contain it completely.
13316         if (!CurrentRegionOnly && SI != SE)
13317           EnclosingExpr = RE;
13318 
13319         // The current expression is a subset of the expression in the data
13320         // environment.
13321         IsEnclosedByDataEnvironmentExpr |=
13322             (!CurrentRegionOnly && CI != CE && SI == SE);
13323 
13324         return false;
13325       });
13326 
13327   if (CurrentRegionOnly)
13328     return FoundError;
13329 
13330   // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
13331   //  If any part of the original storage of a list item has corresponding
13332   //  storage in the device data environment, all of the original storage must
13333   //  have corresponding storage in the device data environment.
13334   // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
13335   //  If a list item is an element of a structure, and a different element of
13336   //  the structure has a corresponding list item in the device data environment
13337   //  prior to a task encountering the construct associated with the map clause,
13338   //  then the list item must also have a corresponding list item in the device
13339   //  data environment prior to the task encountering the construct.
13340   //
13341   if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
13342     SemaRef.Diag(ELoc,
13343                  diag::err_omp_original_storage_is_shared_and_does_not_contain)
13344         << ERange;
13345     SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
13346         << EnclosingExpr->getSourceRange();
13347     return true;
13348   }
13349 
13350   return FoundError;
13351 }
13352 
13353 // Look up the user-defined mapper given the mapper name and mapped type, and
13354 // build a reference to it.
13355 ExprResult buildUserDefinedMapperRef(Sema &SemaRef, Scope *S,
13356                                      CXXScopeSpec &MapperIdScopeSpec,
13357                                      const DeclarationNameInfo &MapperId,
13358                                      QualType Type, Expr *UnresolvedMapper) {
13359   if (MapperIdScopeSpec.isInvalid())
13360     return ExprError();
13361   // Find all user-defined mappers with the given MapperId.
13362   SmallVector<UnresolvedSet<8>, 4> Lookups;
13363   LookupResult Lookup(SemaRef, MapperId, Sema::LookupOMPMapperName);
13364   Lookup.suppressDiagnostics();
13365   if (S) {
13366     while (S && SemaRef.LookupParsedName(Lookup, S, &MapperIdScopeSpec)) {
13367       NamedDecl *D = Lookup.getRepresentativeDecl();
13368       while (S && !S->isDeclScope(D))
13369         S = S->getParent();
13370       if (S)
13371         S = S->getParent();
13372       Lookups.emplace_back();
13373       Lookups.back().append(Lookup.begin(), Lookup.end());
13374       Lookup.clear();
13375     }
13376   } else if (auto *ULE = cast_or_null<UnresolvedLookupExpr>(UnresolvedMapper)) {
13377     // Extract the user-defined mappers with the given MapperId.
13378     Lookups.push_back(UnresolvedSet<8>());
13379     for (NamedDecl *D : ULE->decls()) {
13380       auto *DMD = cast<OMPDeclareMapperDecl>(D);
13381       assert(DMD && "Expect valid OMPDeclareMapperDecl during instantiation.");
13382       Lookups.back().addDecl(DMD);
13383     }
13384   }
13385   // Defer the lookup for dependent types. The results will be passed through
13386   // UnresolvedMapper on instantiation.
13387   if (SemaRef.CurContext->isDependentContext() || Type->isDependentType() ||
13388       Type->isInstantiationDependentType() ||
13389       Type->containsUnexpandedParameterPack() ||
13390       filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
13391         return !D->isInvalidDecl() &&
13392                (D->getType()->isDependentType() ||
13393                 D->getType()->isInstantiationDependentType() ||
13394                 D->getType()->containsUnexpandedParameterPack());
13395       })) {
13396     UnresolvedSet<8> URS;
13397     for (const UnresolvedSet<8> &Set : Lookups) {
13398       if (Set.empty())
13399         continue;
13400       URS.append(Set.begin(), Set.end());
13401     }
13402     return UnresolvedLookupExpr::Create(
13403         SemaRef.Context, /*NamingClass=*/nullptr,
13404         MapperIdScopeSpec.getWithLocInContext(SemaRef.Context), MapperId,
13405         /*ADL=*/false, /*Overloaded=*/true, URS.begin(), URS.end());
13406   }
13407   // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
13408   //  The type must be of struct, union or class type in C and C++
13409   if (!Type->isStructureOrClassType() && !Type->isUnionType())
13410     return ExprEmpty();
13411   SourceLocation Loc = MapperId.getLoc();
13412   // Perform argument dependent lookup.
13413   if (SemaRef.getLangOpts().CPlusPlus && !MapperIdScopeSpec.isSet())
13414     argumentDependentLookup(SemaRef, MapperId, Loc, Type, Lookups);
13415   // Return the first user-defined mapper with the desired type.
13416   if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
13417           Lookups, [&SemaRef, Type](ValueDecl *D) -> ValueDecl * {
13418             if (!D->isInvalidDecl() &&
13419                 SemaRef.Context.hasSameType(D->getType(), Type))
13420               return D;
13421             return nullptr;
13422           }))
13423     return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
13424   // Find the first user-defined mapper with a type derived from the desired
13425   // type.
13426   if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
13427           Lookups, [&SemaRef, Type, Loc](ValueDecl *D) -> ValueDecl * {
13428             if (!D->isInvalidDecl() &&
13429                 SemaRef.IsDerivedFrom(Loc, Type, D->getType()) &&
13430                 !Type.isMoreQualifiedThan(D->getType()))
13431               return D;
13432             return nullptr;
13433           })) {
13434     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
13435                        /*DetectVirtual=*/false);
13436     if (SemaRef.IsDerivedFrom(Loc, Type, VD->getType(), Paths)) {
13437       if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
13438               VD->getType().getUnqualifiedType()))) {
13439         if (SemaRef.CheckBaseClassAccess(
13440                 Loc, VD->getType(), Type, Paths.front(),
13441                 /*DiagID=*/0) != Sema::AR_inaccessible) {
13442           return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
13443         }
13444       }
13445     }
13446   }
13447   // Report error if a mapper is specified, but cannot be found.
13448   if (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default") {
13449     SemaRef.Diag(Loc, diag::err_omp_invalid_mapper)
13450         << Type << MapperId.getName();
13451     return ExprError();
13452   }
13453   return ExprEmpty();
13454 }
13455 
13456 namespace {
13457 // Utility struct that gathers all the related lists associated with a mappable
13458 // expression.
13459 struct MappableVarListInfo {
13460   // The list of expressions.
13461   ArrayRef<Expr *> VarList;
13462   // The list of processed expressions.
13463   SmallVector<Expr *, 16> ProcessedVarList;
13464   // The mappble components for each expression.
13465   OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
13466   // The base declaration of the variable.
13467   SmallVector<ValueDecl *, 16> VarBaseDeclarations;
13468   // The reference to the user-defined mapper associated with every expression.
13469   SmallVector<Expr *, 16> UDMapperList;
13470 
13471   MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
13472     // We have a list of components and base declarations for each entry in the
13473     // variable list.
13474     VarComponents.reserve(VarList.size());
13475     VarBaseDeclarations.reserve(VarList.size());
13476   }
13477 };
13478 }
13479 
13480 // Check the validity of the provided variable list for the provided clause kind
13481 // \a CKind. In the check process the valid expressions, mappable expression
13482 // components, variables, and user-defined mappers are extracted and used to
13483 // fill \a ProcessedVarList, \a VarComponents, \a VarBaseDeclarations, and \a
13484 // UDMapperList in MVLI. \a MapType, \a IsMapTypeImplicit, \a MapperIdScopeSpec,
13485 // and \a MapperId are expected to be valid if the clause kind is 'map'.
13486 static void checkMappableExpressionList(
13487     Sema &SemaRef, DSAStackTy *DSAS, OpenMPClauseKind CKind,
13488     MappableVarListInfo &MVLI, SourceLocation StartLoc,
13489     CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo MapperId,
13490     ArrayRef<Expr *> UnresolvedMappers,
13491     OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
13492     bool IsMapTypeImplicit = false) {
13493   // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
13494   assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
13495          "Unexpected clause kind with mappable expressions!");
13496 
13497   // If the identifier of user-defined mapper is not specified, it is "default".
13498   // We do not change the actual name in this clause to distinguish whether a
13499   // mapper is specified explicitly, i.e., it is not explicitly specified when
13500   // MapperId.getName() is empty.
13501   if (!MapperId.getName() || MapperId.getName().isEmpty()) {
13502     auto &DeclNames = SemaRef.getASTContext().DeclarationNames;
13503     MapperId.setName(DeclNames.getIdentifier(
13504         &SemaRef.getASTContext().Idents.get("default")));
13505   }
13506 
13507   // Iterators to find the current unresolved mapper expression.
13508   auto UMIt = UnresolvedMappers.begin(), UMEnd = UnresolvedMappers.end();
13509   bool UpdateUMIt = false;
13510   Expr *UnresolvedMapper = nullptr;
13511 
13512   // Keep track of the mappable components and base declarations in this clause.
13513   // Each entry in the list is going to have a list of components associated. We
13514   // record each set of the components so that we can build the clause later on.
13515   // In the end we should have the same amount of declarations and component
13516   // lists.
13517 
13518   for (Expr *RE : MVLI.VarList) {
13519     assert(RE && "Null expr in omp to/from/map clause");
13520     SourceLocation ELoc = RE->getExprLoc();
13521 
13522     // Find the current unresolved mapper expression.
13523     if (UpdateUMIt && UMIt != UMEnd) {
13524       UMIt++;
13525       assert(
13526           UMIt != UMEnd &&
13527           "Expect the size of UnresolvedMappers to match with that of VarList");
13528     }
13529     UpdateUMIt = true;
13530     if (UMIt != UMEnd)
13531       UnresolvedMapper = *UMIt;
13532 
13533     const Expr *VE = RE->IgnoreParenLValueCasts();
13534 
13535     if (VE->isValueDependent() || VE->isTypeDependent() ||
13536         VE->isInstantiationDependent() ||
13537         VE->containsUnexpandedParameterPack()) {
13538       // Try to find the associated user-defined mapper.
13539       ExprResult ER = buildUserDefinedMapperRef(
13540           SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
13541           VE->getType().getCanonicalType(), UnresolvedMapper);
13542       if (ER.isInvalid())
13543         continue;
13544       MVLI.UDMapperList.push_back(ER.get());
13545       // We can only analyze this information once the missing information is
13546       // resolved.
13547       MVLI.ProcessedVarList.push_back(RE);
13548       continue;
13549     }
13550 
13551     Expr *SimpleExpr = RE->IgnoreParenCasts();
13552 
13553     if (!RE->IgnoreParenImpCasts()->isLValue()) {
13554       SemaRef.Diag(ELoc,
13555                    diag::err_omp_expected_named_var_member_or_array_expression)
13556           << RE->getSourceRange();
13557       continue;
13558     }
13559 
13560     OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
13561     ValueDecl *CurDeclaration = nullptr;
13562 
13563     // Obtain the array or member expression bases if required. Also, fill the
13564     // components array with all the components identified in the process.
13565     const Expr *BE = checkMapClauseExpressionBase(
13566         SemaRef, SimpleExpr, CurComponents, CKind, /*NoDiagnose=*/false);
13567     if (!BE)
13568       continue;
13569 
13570     assert(!CurComponents.empty() &&
13571            "Invalid mappable expression information.");
13572 
13573     if (const auto *TE = dyn_cast<CXXThisExpr>(BE)) {
13574       // Add store "this" pointer to class in DSAStackTy for future checking
13575       DSAS->addMappedClassesQualTypes(TE->getType());
13576       // Try to find the associated user-defined mapper.
13577       ExprResult ER = buildUserDefinedMapperRef(
13578           SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
13579           VE->getType().getCanonicalType(), UnresolvedMapper);
13580       if (ER.isInvalid())
13581         continue;
13582       MVLI.UDMapperList.push_back(ER.get());
13583       // Skip restriction checking for variable or field declarations
13584       MVLI.ProcessedVarList.push_back(RE);
13585       MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
13586       MVLI.VarComponents.back().append(CurComponents.begin(),
13587                                        CurComponents.end());
13588       MVLI.VarBaseDeclarations.push_back(nullptr);
13589       continue;
13590     }
13591 
13592     // For the following checks, we rely on the base declaration which is
13593     // expected to be associated with the last component. The declaration is
13594     // expected to be a variable or a field (if 'this' is being mapped).
13595     CurDeclaration = CurComponents.back().getAssociatedDeclaration();
13596     assert(CurDeclaration && "Null decl on map clause.");
13597     assert(
13598         CurDeclaration->isCanonicalDecl() &&
13599         "Expecting components to have associated only canonical declarations.");
13600 
13601     auto *VD = dyn_cast<VarDecl>(CurDeclaration);
13602     const auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
13603 
13604     assert((VD || FD) && "Only variables or fields are expected here!");
13605     (void)FD;
13606 
13607     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
13608     // threadprivate variables cannot appear in a map clause.
13609     // OpenMP 4.5 [2.10.5, target update Construct]
13610     // threadprivate variables cannot appear in a from clause.
13611     if (VD && DSAS->isThreadPrivate(VD)) {
13612       DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
13613       SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
13614           << getOpenMPClauseName(CKind);
13615       reportOriginalDsa(SemaRef, DSAS, VD, DVar);
13616       continue;
13617     }
13618 
13619     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
13620     //  A list item cannot appear in both a map clause and a data-sharing
13621     //  attribute clause on the same construct.
13622 
13623     // Check conflicts with other map clause expressions. We check the conflicts
13624     // with the current construct separately from the enclosing data
13625     // environment, because the restrictions are different. We only have to
13626     // check conflicts across regions for the map clauses.
13627     if (checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
13628                           /*CurrentRegionOnly=*/true, CurComponents, CKind))
13629       break;
13630     if (CKind == OMPC_map &&
13631         checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
13632                           /*CurrentRegionOnly=*/false, CurComponents, CKind))
13633       break;
13634 
13635     // OpenMP 4.5 [2.10.5, target update Construct]
13636     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
13637     //  If the type of a list item is a reference to a type T then the type will
13638     //  be considered to be T for all purposes of this clause.
13639     auto I = llvm::find_if(
13640         CurComponents,
13641         [](const OMPClauseMappableExprCommon::MappableComponent &MC) {
13642           return MC.getAssociatedDeclaration();
13643         });
13644     assert(I != CurComponents.end() && "Null decl on map clause.");
13645     QualType Type =
13646         I->getAssociatedDeclaration()->getType().getNonReferenceType();
13647 
13648     // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
13649     // A list item in a to or from clause must have a mappable type.
13650     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
13651     //  A list item must have a mappable type.
13652     if (!checkTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
13653                            DSAS, Type))
13654       continue;
13655 
13656     if (CKind == OMPC_map) {
13657       // target enter data
13658       // OpenMP [2.10.2, Restrictions, p. 99]
13659       // A map-type must be specified in all map clauses and must be either
13660       // to or alloc.
13661       OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
13662       if (DKind == OMPD_target_enter_data &&
13663           !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
13664         SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
13665             << (IsMapTypeImplicit ? 1 : 0)
13666             << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
13667             << getOpenMPDirectiveName(DKind);
13668         continue;
13669       }
13670 
13671       // target exit_data
13672       // OpenMP [2.10.3, Restrictions, p. 102]
13673       // A map-type must be specified in all map clauses and must be either
13674       // from, release, or delete.
13675       if (DKind == OMPD_target_exit_data &&
13676           !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
13677             MapType == OMPC_MAP_delete)) {
13678         SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
13679             << (IsMapTypeImplicit ? 1 : 0)
13680             << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
13681             << getOpenMPDirectiveName(DKind);
13682         continue;
13683       }
13684 
13685       // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
13686       // A list item cannot appear in both a map clause and a data-sharing
13687       // attribute clause on the same construct
13688       if (VD && isOpenMPTargetExecutionDirective(DKind)) {
13689         DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
13690         if (isOpenMPPrivate(DVar.CKind)) {
13691           SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
13692               << getOpenMPClauseName(DVar.CKind)
13693               << getOpenMPClauseName(OMPC_map)
13694               << getOpenMPDirectiveName(DSAS->getCurrentDirective());
13695           reportOriginalDsa(SemaRef, DSAS, CurDeclaration, DVar);
13696           continue;
13697         }
13698       }
13699     }
13700 
13701     // Try to find the associated user-defined mapper.
13702     ExprResult ER = buildUserDefinedMapperRef(
13703         SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
13704         Type.getCanonicalType(), UnresolvedMapper);
13705     if (ER.isInvalid())
13706       continue;
13707     MVLI.UDMapperList.push_back(ER.get());
13708 
13709     // Save the current expression.
13710     MVLI.ProcessedVarList.push_back(RE);
13711 
13712     // Store the components in the stack so that they can be used to check
13713     // against other clauses later on.
13714     DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
13715                                           /*WhereFoundClauseKind=*/OMPC_map);
13716 
13717     // Save the components and declaration to create the clause. For purposes of
13718     // the clause creation, any component list that has has base 'this' uses
13719     // null as base declaration.
13720     MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
13721     MVLI.VarComponents.back().append(CurComponents.begin(),
13722                                      CurComponents.end());
13723     MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
13724                                                            : CurDeclaration);
13725   }
13726 }
13727 
13728 OMPClause *Sema::ActOnOpenMPMapClause(
13729     ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
13730     ArrayRef<SourceLocation> MapTypeModifiersLoc,
13731     CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId,
13732     OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, SourceLocation MapLoc,
13733     SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
13734     const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) {
13735   OpenMPMapModifierKind Modifiers[] = {OMPC_MAP_MODIFIER_unknown,
13736                                        OMPC_MAP_MODIFIER_unknown,
13737                                        OMPC_MAP_MODIFIER_unknown};
13738   SourceLocation ModifiersLoc[OMPMapClause::NumberOfModifiers];
13739 
13740   // Process map-type-modifiers, flag errors for duplicate modifiers.
13741   unsigned Count = 0;
13742   for (unsigned I = 0, E = MapTypeModifiers.size(); I < E; ++I) {
13743     if (MapTypeModifiers[I] != OMPC_MAP_MODIFIER_unknown &&
13744         llvm::find(Modifiers, MapTypeModifiers[I]) != std::end(Modifiers)) {
13745       Diag(MapTypeModifiersLoc[I], diag::err_omp_duplicate_map_type_modifier);
13746       continue;
13747     }
13748     assert(Count < OMPMapClause::NumberOfModifiers &&
13749            "Modifiers exceed the allowed number of map type modifiers");
13750     Modifiers[Count] = MapTypeModifiers[I];
13751     ModifiersLoc[Count] = MapTypeModifiersLoc[I];
13752     ++Count;
13753   }
13754 
13755   MappableVarListInfo MVLI(VarList);
13756   checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, Locs.StartLoc,
13757                               MapperIdScopeSpec, MapperId, UnresolvedMappers,
13758                               MapType, IsMapTypeImplicit);
13759 
13760   // We need to produce a map clause even if we don't have variables so that
13761   // other diagnostics related with non-existing map clauses are accurate.
13762   return OMPMapClause::Create(Context, Locs, MVLI.ProcessedVarList,
13763                               MVLI.VarBaseDeclarations, MVLI.VarComponents,
13764                               MVLI.UDMapperList, Modifiers, ModifiersLoc,
13765                               MapperIdScopeSpec.getWithLocInContext(Context),
13766                               MapperId, MapType, IsMapTypeImplicit, MapLoc);
13767 }
13768 
13769 QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
13770                                                TypeResult ParsedType) {
13771   assert(ParsedType.isUsable());
13772 
13773   QualType ReductionType = GetTypeFromParser(ParsedType.get());
13774   if (ReductionType.isNull())
13775     return QualType();
13776 
13777   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
13778   // A type name in a declare reduction directive cannot be a function type, an
13779   // array type, a reference type, or a type qualified with const, volatile or
13780   // restrict.
13781   if (ReductionType.hasQualifiers()) {
13782     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
13783     return QualType();
13784   }
13785 
13786   if (ReductionType->isFunctionType()) {
13787     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
13788     return QualType();
13789   }
13790   if (ReductionType->isReferenceType()) {
13791     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
13792     return QualType();
13793   }
13794   if (ReductionType->isArrayType()) {
13795     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
13796     return QualType();
13797   }
13798   return ReductionType;
13799 }
13800 
13801 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
13802     Scope *S, DeclContext *DC, DeclarationName Name,
13803     ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
13804     AccessSpecifier AS, Decl *PrevDeclInScope) {
13805   SmallVector<Decl *, 8> Decls;
13806   Decls.reserve(ReductionTypes.size());
13807 
13808   LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
13809                       forRedeclarationInCurContext());
13810   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
13811   // A reduction-identifier may not be re-declared in the current scope for the
13812   // same type or for a type that is compatible according to the base language
13813   // rules.
13814   llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
13815   OMPDeclareReductionDecl *PrevDRD = nullptr;
13816   bool InCompoundScope = true;
13817   if (S != nullptr) {
13818     // Find previous declaration with the same name not referenced in other
13819     // declarations.
13820     FunctionScopeInfo *ParentFn = getEnclosingFunction();
13821     InCompoundScope =
13822         (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
13823     LookupName(Lookup, S);
13824     FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
13825                          /*AllowInlineNamespace=*/false);
13826     llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
13827     LookupResult::Filter Filter = Lookup.makeFilter();
13828     while (Filter.hasNext()) {
13829       auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
13830       if (InCompoundScope) {
13831         auto I = UsedAsPrevious.find(PrevDecl);
13832         if (I == UsedAsPrevious.end())
13833           UsedAsPrevious[PrevDecl] = false;
13834         if (OMPDeclareReductionDecl *D = PrevDecl->getPrevDeclInScope())
13835           UsedAsPrevious[D] = true;
13836       }
13837       PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
13838           PrevDecl->getLocation();
13839     }
13840     Filter.done();
13841     if (InCompoundScope) {
13842       for (const auto &PrevData : UsedAsPrevious) {
13843         if (!PrevData.second) {
13844           PrevDRD = PrevData.first;
13845           break;
13846         }
13847       }
13848     }
13849   } else if (PrevDeclInScope != nullptr) {
13850     auto *PrevDRDInScope = PrevDRD =
13851         cast<OMPDeclareReductionDecl>(PrevDeclInScope);
13852     do {
13853       PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
13854           PrevDRDInScope->getLocation();
13855       PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
13856     } while (PrevDRDInScope != nullptr);
13857   }
13858   for (const auto &TyData : ReductionTypes) {
13859     const auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
13860     bool Invalid = false;
13861     if (I != PreviousRedeclTypes.end()) {
13862       Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
13863           << TyData.first;
13864       Diag(I->second, diag::note_previous_definition);
13865       Invalid = true;
13866     }
13867     PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
13868     auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
13869                                                 Name, TyData.first, PrevDRD);
13870     DC->addDecl(DRD);
13871     DRD->setAccess(AS);
13872     Decls.push_back(DRD);
13873     if (Invalid)
13874       DRD->setInvalidDecl();
13875     else
13876       PrevDRD = DRD;
13877   }
13878 
13879   return DeclGroupPtrTy::make(
13880       DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
13881 }
13882 
13883 void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
13884   auto *DRD = cast<OMPDeclareReductionDecl>(D);
13885 
13886   // Enter new function scope.
13887   PushFunctionScope();
13888   setFunctionHasBranchProtectedScope();
13889   getCurFunction()->setHasOMPDeclareReductionCombiner();
13890 
13891   if (S != nullptr)
13892     PushDeclContext(S, DRD);
13893   else
13894     CurContext = DRD;
13895 
13896   PushExpressionEvaluationContext(
13897       ExpressionEvaluationContext::PotentiallyEvaluated);
13898 
13899   QualType ReductionType = DRD->getType();
13900   // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
13901   // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
13902   // uses semantics of argument handles by value, but it should be passed by
13903   // reference. C lang does not support references, so pass all parameters as
13904   // pointers.
13905   // Create 'T omp_in;' variable.
13906   VarDecl *OmpInParm =
13907       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
13908   // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
13909   // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
13910   // uses semantics of argument handles by value, but it should be passed by
13911   // reference. C lang does not support references, so pass all parameters as
13912   // pointers.
13913   // Create 'T omp_out;' variable.
13914   VarDecl *OmpOutParm =
13915       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
13916   if (S != nullptr) {
13917     PushOnScopeChains(OmpInParm, S);
13918     PushOnScopeChains(OmpOutParm, S);
13919   } else {
13920     DRD->addDecl(OmpInParm);
13921     DRD->addDecl(OmpOutParm);
13922   }
13923   Expr *InE =
13924       ::buildDeclRefExpr(*this, OmpInParm, ReductionType, D->getLocation());
13925   Expr *OutE =
13926       ::buildDeclRefExpr(*this, OmpOutParm, ReductionType, D->getLocation());
13927   DRD->setCombinerData(InE, OutE);
13928 }
13929 
13930 void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
13931   auto *DRD = cast<OMPDeclareReductionDecl>(D);
13932   DiscardCleanupsInEvaluationContext();
13933   PopExpressionEvaluationContext();
13934 
13935   PopDeclContext();
13936   PopFunctionScopeInfo();
13937 
13938   if (Combiner != nullptr)
13939     DRD->setCombiner(Combiner);
13940   else
13941     DRD->setInvalidDecl();
13942 }
13943 
13944 VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
13945   auto *DRD = cast<OMPDeclareReductionDecl>(D);
13946 
13947   // Enter new function scope.
13948   PushFunctionScope();
13949   setFunctionHasBranchProtectedScope();
13950 
13951   if (S != nullptr)
13952     PushDeclContext(S, DRD);
13953   else
13954     CurContext = DRD;
13955 
13956   PushExpressionEvaluationContext(
13957       ExpressionEvaluationContext::PotentiallyEvaluated);
13958 
13959   QualType ReductionType = DRD->getType();
13960   // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
13961   // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
13962   // uses semantics of argument handles by value, but it should be passed by
13963   // reference. C lang does not support references, so pass all parameters as
13964   // pointers.
13965   // Create 'T omp_priv;' variable.
13966   VarDecl *OmpPrivParm =
13967       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
13968   // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
13969   // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
13970   // uses semantics of argument handles by value, but it should be passed by
13971   // reference. C lang does not support references, so pass all parameters as
13972   // pointers.
13973   // Create 'T omp_orig;' variable.
13974   VarDecl *OmpOrigParm =
13975       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
13976   if (S != nullptr) {
13977     PushOnScopeChains(OmpPrivParm, S);
13978     PushOnScopeChains(OmpOrigParm, S);
13979   } else {
13980     DRD->addDecl(OmpPrivParm);
13981     DRD->addDecl(OmpOrigParm);
13982   }
13983   Expr *OrigE =
13984       ::buildDeclRefExpr(*this, OmpOrigParm, ReductionType, D->getLocation());
13985   Expr *PrivE =
13986       ::buildDeclRefExpr(*this, OmpPrivParm, ReductionType, D->getLocation());
13987   DRD->setInitializerData(OrigE, PrivE);
13988   return OmpPrivParm;
13989 }
13990 
13991 void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
13992                                                      VarDecl *OmpPrivParm) {
13993   auto *DRD = cast<OMPDeclareReductionDecl>(D);
13994   DiscardCleanupsInEvaluationContext();
13995   PopExpressionEvaluationContext();
13996 
13997   PopDeclContext();
13998   PopFunctionScopeInfo();
13999 
14000   if (Initializer != nullptr) {
14001     DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit);
14002   } else if (OmpPrivParm->hasInit()) {
14003     DRD->setInitializer(OmpPrivParm->getInit(),
14004                         OmpPrivParm->isDirectInit()
14005                             ? OMPDeclareReductionDecl::DirectInit
14006                             : OMPDeclareReductionDecl::CopyInit);
14007   } else {
14008     DRD->setInvalidDecl();
14009   }
14010 }
14011 
14012 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
14013     Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
14014   for (Decl *D : DeclReductions.get()) {
14015     if (IsValid) {
14016       if (S)
14017         PushOnScopeChains(cast<OMPDeclareReductionDecl>(D), S,
14018                           /*AddToContext=*/false);
14019     } else {
14020       D->setInvalidDecl();
14021     }
14022   }
14023   return DeclReductions;
14024 }
14025 
14026 TypeResult Sema::ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D) {
14027   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14028   QualType T = TInfo->getType();
14029   if (D.isInvalidType())
14030     return true;
14031 
14032   if (getLangOpts().CPlusPlus) {
14033     // Check that there are no default arguments (C++ only).
14034     CheckExtraCXXDefaultArguments(D);
14035   }
14036 
14037   return CreateParsedType(T, TInfo);
14038 }
14039 
14040 QualType Sema::ActOnOpenMPDeclareMapperType(SourceLocation TyLoc,
14041                                             TypeResult ParsedType) {
14042   assert(ParsedType.isUsable() && "Expect usable parsed mapper type");
14043 
14044   QualType MapperType = GetTypeFromParser(ParsedType.get());
14045   assert(!MapperType.isNull() && "Expect valid mapper type");
14046 
14047   // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
14048   //  The type must be of struct, union or class type in C and C++
14049   if (!MapperType->isStructureOrClassType() && !MapperType->isUnionType()) {
14050     Diag(TyLoc, diag::err_omp_mapper_wrong_type);
14051     return QualType();
14052   }
14053   return MapperType;
14054 }
14055 
14056 OMPDeclareMapperDecl *Sema::ActOnOpenMPDeclareMapperDirectiveStart(
14057     Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType,
14058     SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS,
14059     Decl *PrevDeclInScope) {
14060   LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPMapperName,
14061                       forRedeclarationInCurContext());
14062   // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
14063   //  A mapper-identifier may not be redeclared in the current scope for the
14064   //  same type or for a type that is compatible according to the base language
14065   //  rules.
14066   llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
14067   OMPDeclareMapperDecl *PrevDMD = nullptr;
14068   bool InCompoundScope = true;
14069   if (S != nullptr) {
14070     // Find previous declaration with the same name not referenced in other
14071     // declarations.
14072     FunctionScopeInfo *ParentFn = getEnclosingFunction();
14073     InCompoundScope =
14074         (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
14075     LookupName(Lookup, S);
14076     FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
14077                          /*AllowInlineNamespace=*/false);
14078     llvm::DenseMap<OMPDeclareMapperDecl *, bool> UsedAsPrevious;
14079     LookupResult::Filter Filter = Lookup.makeFilter();
14080     while (Filter.hasNext()) {
14081       auto *PrevDecl = cast<OMPDeclareMapperDecl>(Filter.next());
14082       if (InCompoundScope) {
14083         auto I = UsedAsPrevious.find(PrevDecl);
14084         if (I == UsedAsPrevious.end())
14085           UsedAsPrevious[PrevDecl] = false;
14086         if (OMPDeclareMapperDecl *D = PrevDecl->getPrevDeclInScope())
14087           UsedAsPrevious[D] = true;
14088       }
14089       PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
14090           PrevDecl->getLocation();
14091     }
14092     Filter.done();
14093     if (InCompoundScope) {
14094       for (const auto &PrevData : UsedAsPrevious) {
14095         if (!PrevData.second) {
14096           PrevDMD = PrevData.first;
14097           break;
14098         }
14099       }
14100     }
14101   } else if (PrevDeclInScope) {
14102     auto *PrevDMDInScope = PrevDMD =
14103         cast<OMPDeclareMapperDecl>(PrevDeclInScope);
14104     do {
14105       PreviousRedeclTypes[PrevDMDInScope->getType().getCanonicalType()] =
14106           PrevDMDInScope->getLocation();
14107       PrevDMDInScope = PrevDMDInScope->getPrevDeclInScope();
14108     } while (PrevDMDInScope != nullptr);
14109   }
14110   const auto I = PreviousRedeclTypes.find(MapperType.getCanonicalType());
14111   bool Invalid = false;
14112   if (I != PreviousRedeclTypes.end()) {
14113     Diag(StartLoc, diag::err_omp_declare_mapper_redefinition)
14114         << MapperType << Name;
14115     Diag(I->second, diag::note_previous_definition);
14116     Invalid = true;
14117   }
14118   auto *DMD = OMPDeclareMapperDecl::Create(Context, DC, StartLoc, Name,
14119                                            MapperType, VN, PrevDMD);
14120   DC->addDecl(DMD);
14121   DMD->setAccess(AS);
14122   if (Invalid)
14123     DMD->setInvalidDecl();
14124 
14125   // Enter new function scope.
14126   PushFunctionScope();
14127   setFunctionHasBranchProtectedScope();
14128 
14129   CurContext = DMD;
14130 
14131   return DMD;
14132 }
14133 
14134 void Sema::ActOnOpenMPDeclareMapperDirectiveVarDecl(OMPDeclareMapperDecl *DMD,
14135                                                     Scope *S,
14136                                                     QualType MapperType,
14137                                                     SourceLocation StartLoc,
14138                                                     DeclarationName VN) {
14139   VarDecl *VD = buildVarDecl(*this, StartLoc, MapperType, VN.getAsString());
14140   if (S)
14141     PushOnScopeChains(VD, S);
14142   else
14143     DMD->addDecl(VD);
14144   Expr *MapperVarRefExpr = buildDeclRefExpr(*this, VD, MapperType, StartLoc);
14145   DMD->setMapperVarRef(MapperVarRefExpr);
14146 }
14147 
14148 Sema::DeclGroupPtrTy
14149 Sema::ActOnOpenMPDeclareMapperDirectiveEnd(OMPDeclareMapperDecl *D, Scope *S,
14150                                            ArrayRef<OMPClause *> ClauseList) {
14151   PopDeclContext();
14152   PopFunctionScopeInfo();
14153 
14154   if (D) {
14155     if (S)
14156       PushOnScopeChains(D, S, /*AddToContext=*/false);
14157     D->CreateClauses(Context, ClauseList);
14158   }
14159 
14160   return DeclGroupPtrTy::make(DeclGroupRef(D));
14161 }
14162 
14163 OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
14164                                            SourceLocation StartLoc,
14165                                            SourceLocation LParenLoc,
14166                                            SourceLocation EndLoc) {
14167   Expr *ValExpr = NumTeams;
14168   Stmt *HelperValStmt = nullptr;
14169 
14170   // OpenMP [teams Constrcut, Restrictions]
14171   // The num_teams expression must evaluate to a positive integer value.
14172   if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
14173                                  /*StrictlyPositive=*/true))
14174     return nullptr;
14175 
14176   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
14177   OpenMPDirectiveKind CaptureRegion =
14178       getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams);
14179   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
14180     ValExpr = MakeFullExpr(ValExpr).get();
14181     llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
14182     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
14183     HelperValStmt = buildPreInits(Context, Captures);
14184   }
14185 
14186   return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
14187                                          StartLoc, LParenLoc, EndLoc);
14188 }
14189 
14190 OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
14191                                               SourceLocation StartLoc,
14192                                               SourceLocation LParenLoc,
14193                                               SourceLocation EndLoc) {
14194   Expr *ValExpr = ThreadLimit;
14195   Stmt *HelperValStmt = nullptr;
14196 
14197   // OpenMP [teams Constrcut, Restrictions]
14198   // The thread_limit expression must evaluate to a positive integer value.
14199   if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
14200                                  /*StrictlyPositive=*/true))
14201     return nullptr;
14202 
14203   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
14204   OpenMPDirectiveKind CaptureRegion =
14205       getOpenMPCaptureRegionForClause(DKind, OMPC_thread_limit);
14206   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
14207     ValExpr = MakeFullExpr(ValExpr).get();
14208     llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
14209     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
14210     HelperValStmt = buildPreInits(Context, Captures);
14211   }
14212 
14213   return new (Context) OMPThreadLimitClause(
14214       ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
14215 }
14216 
14217 OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
14218                                            SourceLocation StartLoc,
14219                                            SourceLocation LParenLoc,
14220                                            SourceLocation EndLoc) {
14221   Expr *ValExpr = Priority;
14222 
14223   // OpenMP [2.9.1, task Constrcut]
14224   // The priority-value is a non-negative numerical scalar expression.
14225   if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_priority,
14226                                  /*StrictlyPositive=*/false))
14227     return nullptr;
14228 
14229   return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc);
14230 }
14231 
14232 OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
14233                                             SourceLocation StartLoc,
14234                                             SourceLocation LParenLoc,
14235                                             SourceLocation EndLoc) {
14236   Expr *ValExpr = Grainsize;
14237 
14238   // OpenMP [2.9.2, taskloop Constrcut]
14239   // The parameter of the grainsize clause must be a positive integer
14240   // expression.
14241   if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize,
14242                                  /*StrictlyPositive=*/true))
14243     return nullptr;
14244 
14245   return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc);
14246 }
14247 
14248 OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
14249                                            SourceLocation StartLoc,
14250                                            SourceLocation LParenLoc,
14251                                            SourceLocation EndLoc) {
14252   Expr *ValExpr = NumTasks;
14253 
14254   // OpenMP [2.9.2, taskloop Constrcut]
14255   // The parameter of the num_tasks clause must be a positive integer
14256   // expression.
14257   if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks,
14258                                  /*StrictlyPositive=*/true))
14259     return nullptr;
14260 
14261   return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc);
14262 }
14263 
14264 OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
14265                                        SourceLocation LParenLoc,
14266                                        SourceLocation EndLoc) {
14267   // OpenMP [2.13.2, critical construct, Description]
14268   // ... where hint-expression is an integer constant expression that evaluates
14269   // to a valid lock hint.
14270   ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
14271   if (HintExpr.isInvalid())
14272     return nullptr;
14273   return new (Context)
14274       OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
14275 }
14276 
14277 OMPClause *Sema::ActOnOpenMPDistScheduleClause(
14278     OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
14279     SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
14280     SourceLocation EndLoc) {
14281   if (Kind == OMPC_DIST_SCHEDULE_unknown) {
14282     std::string Values;
14283     Values += "'";
14284     Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
14285     Values += "'";
14286     Diag(KindLoc, diag::err_omp_unexpected_clause_value)
14287         << Values << getOpenMPClauseName(OMPC_dist_schedule);
14288     return nullptr;
14289   }
14290   Expr *ValExpr = ChunkSize;
14291   Stmt *HelperValStmt = nullptr;
14292   if (ChunkSize) {
14293     if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
14294         !ChunkSize->isInstantiationDependent() &&
14295         !ChunkSize->containsUnexpandedParameterPack()) {
14296       SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
14297       ExprResult Val =
14298           PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
14299       if (Val.isInvalid())
14300         return nullptr;
14301 
14302       ValExpr = Val.get();
14303 
14304       // OpenMP [2.7.1, Restrictions]
14305       //  chunk_size must be a loop invariant integer expression with a positive
14306       //  value.
14307       llvm::APSInt Result;
14308       if (ValExpr->isIntegerConstantExpr(Result, Context)) {
14309         if (Result.isSigned() && !Result.isStrictlyPositive()) {
14310           Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
14311               << "dist_schedule" << ChunkSize->getSourceRange();
14312           return nullptr;
14313         }
14314       } else if (getOpenMPCaptureRegionForClause(
14315                      DSAStack->getCurrentDirective(), OMPC_dist_schedule) !=
14316                      OMPD_unknown &&
14317                  !CurContext->isDependentContext()) {
14318         ValExpr = MakeFullExpr(ValExpr).get();
14319         llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
14320         ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
14321         HelperValStmt = buildPreInits(Context, Captures);
14322       }
14323     }
14324   }
14325 
14326   return new (Context)
14327       OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
14328                             Kind, ValExpr, HelperValStmt);
14329 }
14330 
14331 OMPClause *Sema::ActOnOpenMPDefaultmapClause(
14332     OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
14333     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
14334     SourceLocation KindLoc, SourceLocation EndLoc) {
14335   // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)'
14336   if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) {
14337     std::string Value;
14338     SourceLocation Loc;
14339     Value += "'";
14340     if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
14341       Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
14342                                              OMPC_DEFAULTMAP_MODIFIER_tofrom);
14343       Loc = MLoc;
14344     } else {
14345       Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
14346                                              OMPC_DEFAULTMAP_scalar);
14347       Loc = KindLoc;
14348     }
14349     Value += "'";
14350     Diag(Loc, diag::err_omp_unexpected_clause_value)
14351         << Value << getOpenMPClauseName(OMPC_defaultmap);
14352     return nullptr;
14353   }
14354   DSAStack->setDefaultDMAToFromScalar(StartLoc);
14355 
14356   return new (Context)
14357       OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
14358 }
14359 
14360 bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
14361   DeclContext *CurLexicalContext = getCurLexicalContext();
14362   if (!CurLexicalContext->isFileContext() &&
14363       !CurLexicalContext->isExternCContext() &&
14364       !CurLexicalContext->isExternCXXContext() &&
14365       !isa<CXXRecordDecl>(CurLexicalContext) &&
14366       !isa<ClassTemplateDecl>(CurLexicalContext) &&
14367       !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) &&
14368       !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) {
14369     Diag(Loc, diag::err_omp_region_not_file_context);
14370     return false;
14371   }
14372   ++DeclareTargetNestingLevel;
14373   return true;
14374 }
14375 
14376 void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
14377   assert(DeclareTargetNestingLevel > 0 &&
14378          "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
14379   --DeclareTargetNestingLevel;
14380 }
14381 
14382 void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope,
14383                                         CXXScopeSpec &ScopeSpec,
14384                                         const DeclarationNameInfo &Id,
14385                                         OMPDeclareTargetDeclAttr::MapTypeTy MT,
14386                                         NamedDeclSetType &SameDirectiveDecls) {
14387   LookupResult Lookup(*this, Id, LookupOrdinaryName);
14388   LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
14389 
14390   if (Lookup.isAmbiguous())
14391     return;
14392   Lookup.suppressDiagnostics();
14393 
14394   if (!Lookup.isSingleResult()) {
14395     VarOrFuncDeclFilterCCC CCC(*this);
14396     if (TypoCorrection Corrected =
14397             CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC,
14398                         CTK_ErrorRecovery)) {
14399       diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
14400                                   << Id.getName());
14401       checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
14402       return;
14403     }
14404 
14405     Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
14406     return;
14407   }
14408 
14409   NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
14410   if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND) ||
14411       isa<FunctionTemplateDecl>(ND)) {
14412     if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
14413       Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
14414     llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
14415         OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
14416             cast<ValueDecl>(ND));
14417     if (!Res) {
14418       auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT);
14419       ND->addAttr(A);
14420       if (ASTMutationListener *ML = Context.getASTMutationListener())
14421         ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
14422       checkDeclIsAllowedInOpenMPTarget(nullptr, ND, Id.getLoc());
14423     } else if (*Res != MT) {
14424       Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link)
14425           << Id.getName();
14426     }
14427   } else {
14428     Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
14429   }
14430 }
14431 
14432 static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
14433                                      Sema &SemaRef, Decl *D) {
14434   if (!D || !isa<VarDecl>(D))
14435     return;
14436   auto *VD = cast<VarDecl>(D);
14437   if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
14438     return;
14439   SemaRef.Diag(VD->getLocation(), diag::warn_omp_not_in_target_context);
14440   SemaRef.Diag(SL, diag::note_used_here) << SR;
14441 }
14442 
14443 static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
14444                                    Sema &SemaRef, DSAStackTy *Stack,
14445                                    ValueDecl *VD) {
14446   return VD->hasAttr<OMPDeclareTargetDeclAttr>() ||
14447          checkTypeMappable(SL, SR, SemaRef, Stack, VD->getType(),
14448                            /*FullCheck=*/false);
14449 }
14450 
14451 void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
14452                                             SourceLocation IdLoc) {
14453   if (!D || D->isInvalidDecl())
14454     return;
14455   SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
14456   SourceLocation SL = E ? E->getBeginLoc() : D->getLocation();
14457   if (auto *VD = dyn_cast<VarDecl>(D)) {
14458     // Only global variables can be marked as declare target.
14459     if (!VD->isFileVarDecl() && !VD->isStaticLocal() &&
14460         !VD->isStaticDataMember())
14461       return;
14462     // 2.10.6: threadprivate variable cannot appear in a declare target
14463     // directive.
14464     if (DSAStack->isThreadPrivate(VD)) {
14465       Diag(SL, diag::err_omp_threadprivate_in_target);
14466       reportOriginalDsa(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
14467       return;
14468     }
14469   }
14470   if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(D))
14471     D = FTD->getTemplatedDecl();
14472   if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
14473     llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
14474         OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(FD);
14475     if (Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) {
14476       assert(IdLoc.isValid() && "Source location is expected");
14477       Diag(IdLoc, diag::err_omp_function_in_link_clause);
14478       Diag(FD->getLocation(), diag::note_defined_here) << FD;
14479       return;
14480     }
14481   }
14482   if (auto *VD = dyn_cast<ValueDecl>(D)) {
14483     // Problem if any with var declared with incomplete type will be reported
14484     // as normal, so no need to check it here.
14485     if ((E || !VD->getType()->isIncompleteType()) &&
14486         !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD))
14487       return;
14488     if (!E && !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
14489       // Checking declaration inside declare target region.
14490       if (isa<VarDecl>(D) || isa<FunctionDecl>(D) ||
14491           isa<FunctionTemplateDecl>(D)) {
14492         auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(
14493             Context, OMPDeclareTargetDeclAttr::MT_To);
14494         D->addAttr(A);
14495         if (ASTMutationListener *ML = Context.getASTMutationListener())
14496           ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
14497       }
14498       return;
14499     }
14500   }
14501   if (!E)
14502     return;
14503   checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
14504 }
14505 
14506 OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
14507                                      CXXScopeSpec &MapperIdScopeSpec,
14508                                      DeclarationNameInfo &MapperId,
14509                                      const OMPVarListLocTy &Locs,
14510                                      ArrayRef<Expr *> UnresolvedMappers) {
14511   MappableVarListInfo MVLI(VarList);
14512   checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, Locs.StartLoc,
14513                               MapperIdScopeSpec, MapperId, UnresolvedMappers);
14514   if (MVLI.ProcessedVarList.empty())
14515     return nullptr;
14516 
14517   return OMPToClause::Create(
14518       Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
14519       MVLI.VarComponents, MVLI.UDMapperList,
14520       MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
14521 }
14522 
14523 OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
14524                                        CXXScopeSpec &MapperIdScopeSpec,
14525                                        DeclarationNameInfo &MapperId,
14526                                        const OMPVarListLocTy &Locs,
14527                                        ArrayRef<Expr *> UnresolvedMappers) {
14528   MappableVarListInfo MVLI(VarList);
14529   checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, Locs.StartLoc,
14530                               MapperIdScopeSpec, MapperId, UnresolvedMappers);
14531   if (MVLI.ProcessedVarList.empty())
14532     return nullptr;
14533 
14534   return OMPFromClause::Create(
14535       Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
14536       MVLI.VarComponents, MVLI.UDMapperList,
14537       MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
14538 }
14539 
14540 OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
14541                                                const OMPVarListLocTy &Locs) {
14542   MappableVarListInfo MVLI(VarList);
14543   SmallVector<Expr *, 8> PrivateCopies;
14544   SmallVector<Expr *, 8> Inits;
14545 
14546   for (Expr *RefExpr : VarList) {
14547     assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
14548     SourceLocation ELoc;
14549     SourceRange ERange;
14550     Expr *SimpleRefExpr = RefExpr;
14551     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
14552     if (Res.second) {
14553       // It will be analyzed later.
14554       MVLI.ProcessedVarList.push_back(RefExpr);
14555       PrivateCopies.push_back(nullptr);
14556       Inits.push_back(nullptr);
14557     }
14558     ValueDecl *D = Res.first;
14559     if (!D)
14560       continue;
14561 
14562     QualType Type = D->getType();
14563     Type = Type.getNonReferenceType().getUnqualifiedType();
14564 
14565     auto *VD = dyn_cast<VarDecl>(D);
14566 
14567     // Item should be a pointer or reference to pointer.
14568     if (!Type->isPointerType()) {
14569       Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
14570           << 0 << RefExpr->getSourceRange();
14571       continue;
14572     }
14573 
14574     // Build the private variable and the expression that refers to it.
14575     auto VDPrivate =
14576         buildVarDecl(*this, ELoc, Type, D->getName(),
14577                      D->hasAttrs() ? &D->getAttrs() : nullptr,
14578                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
14579     if (VDPrivate->isInvalidDecl())
14580       continue;
14581 
14582     CurContext->addDecl(VDPrivate);
14583     DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
14584         *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
14585 
14586     // Add temporary variable to initialize the private copy of the pointer.
14587     VarDecl *VDInit =
14588         buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
14589     DeclRefExpr *VDInitRefExpr = buildDeclRefExpr(
14590         *this, VDInit, RefExpr->getType(), RefExpr->getExprLoc());
14591     AddInitializerToDecl(VDPrivate,
14592                          DefaultLvalueConversion(VDInitRefExpr).get(),
14593                          /*DirectInit=*/false);
14594 
14595     // If required, build a capture to implement the privatization initialized
14596     // with the current list item value.
14597     DeclRefExpr *Ref = nullptr;
14598     if (!VD)
14599       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
14600     MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
14601     PrivateCopies.push_back(VDPrivateRefExpr);
14602     Inits.push_back(VDInitRefExpr);
14603 
14604     // We need to add a data sharing attribute for this variable to make sure it
14605     // is correctly captured. A variable that shows up in a use_device_ptr has
14606     // similar properties of a first private variable.
14607     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
14608 
14609     // Create a mappable component for the list item. List items in this clause
14610     // only need a component.
14611     MVLI.VarBaseDeclarations.push_back(D);
14612     MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
14613     MVLI.VarComponents.back().push_back(
14614         OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
14615   }
14616 
14617   if (MVLI.ProcessedVarList.empty())
14618     return nullptr;
14619 
14620   return OMPUseDevicePtrClause::Create(
14621       Context, Locs, MVLI.ProcessedVarList, PrivateCopies, Inits,
14622       MVLI.VarBaseDeclarations, MVLI.VarComponents);
14623 }
14624 
14625 OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
14626                                               const OMPVarListLocTy &Locs) {
14627   MappableVarListInfo MVLI(VarList);
14628   for (Expr *RefExpr : VarList) {
14629     assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
14630     SourceLocation ELoc;
14631     SourceRange ERange;
14632     Expr *SimpleRefExpr = RefExpr;
14633     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
14634     if (Res.second) {
14635       // It will be analyzed later.
14636       MVLI.ProcessedVarList.push_back(RefExpr);
14637     }
14638     ValueDecl *D = Res.first;
14639     if (!D)
14640       continue;
14641 
14642     QualType Type = D->getType();
14643     // item should be a pointer or array or reference to pointer or array
14644     if (!Type.getNonReferenceType()->isPointerType() &&
14645         !Type.getNonReferenceType()->isArrayType()) {
14646       Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
14647           << 0 << RefExpr->getSourceRange();
14648       continue;
14649     }
14650 
14651     // Check if the declaration in the clause does not show up in any data
14652     // sharing attribute.
14653     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
14654     if (isOpenMPPrivate(DVar.CKind)) {
14655       Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
14656           << getOpenMPClauseName(DVar.CKind)
14657           << getOpenMPClauseName(OMPC_is_device_ptr)
14658           << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
14659       reportOriginalDsa(*this, DSAStack, D, DVar);
14660       continue;
14661     }
14662 
14663     const Expr *ConflictExpr;
14664     if (DSAStack->checkMappableExprComponentListsForDecl(
14665             D, /*CurrentRegionOnly=*/true,
14666             [&ConflictExpr](
14667                 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
14668                 OpenMPClauseKind) -> bool {
14669               ConflictExpr = R.front().getAssociatedExpression();
14670               return true;
14671             })) {
14672       Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
14673       Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
14674           << ConflictExpr->getSourceRange();
14675       continue;
14676     }
14677 
14678     // Store the components in the stack so that they can be used to check
14679     // against other clauses later on.
14680     OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
14681     DSAStack->addMappableExpressionComponents(
14682         D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
14683 
14684     // Record the expression we've just processed.
14685     MVLI.ProcessedVarList.push_back(SimpleRefExpr);
14686 
14687     // Create a mappable component for the list item. List items in this clause
14688     // only need a component. We use a null declaration to signal fields in
14689     // 'this'.
14690     assert((isa<DeclRefExpr>(SimpleRefExpr) ||
14691             isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
14692            "Unexpected device pointer expression!");
14693     MVLI.VarBaseDeclarations.push_back(
14694         isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
14695     MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
14696     MVLI.VarComponents.back().push_back(MC);
14697   }
14698 
14699   if (MVLI.ProcessedVarList.empty())
14700     return nullptr;
14701 
14702   return OMPIsDevicePtrClause::Create(Context, Locs, MVLI.ProcessedVarList,
14703                                       MVLI.VarBaseDeclarations,
14704                                       MVLI.VarComponents);
14705 }
14706 
14707 OMPClause *Sema::ActOnOpenMPAllocateClause(
14708     Expr *Allocator, ArrayRef<Expr *> VarList, SourceLocation StartLoc,
14709     SourceLocation ColonLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
14710   if (Allocator) {
14711     // OpenMP [2.11.4 allocate Clause, Description]
14712     // allocator is an expression of omp_allocator_handle_t type.
14713     if (!findOMPAllocatorHandleT(*this, Allocator->getExprLoc(), DSAStack))
14714       return nullptr;
14715 
14716     ExprResult AllocatorRes = DefaultLvalueConversion(Allocator);
14717     if (AllocatorRes.isInvalid())
14718       return nullptr;
14719     AllocatorRes = PerformImplicitConversion(AllocatorRes.get(),
14720                                              DSAStack->getOMPAllocatorHandleT(),
14721                                              Sema::AA_Initializing,
14722                                              /*AllowExplicit=*/true);
14723     if (AllocatorRes.isInvalid())
14724       return nullptr;
14725     Allocator = AllocatorRes.get();
14726   }
14727   // Analyze and build list of variables.
14728   SmallVector<Expr *, 8> Vars;
14729   for (Expr *RefExpr : VarList) {
14730     assert(RefExpr && "NULL expr in OpenMP private clause.");
14731     SourceLocation ELoc;
14732     SourceRange ERange;
14733     Expr *SimpleRefExpr = RefExpr;
14734     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
14735     if (Res.second) {
14736       // It will be analyzed later.
14737       Vars.push_back(RefExpr);
14738     }
14739     ValueDecl *D = Res.first;
14740     if (!D)
14741       continue;
14742 
14743     auto *VD = dyn_cast<VarDecl>(D);
14744     DeclRefExpr *Ref = nullptr;
14745     if (!VD && !CurContext->isDependentContext())
14746       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
14747     Vars.push_back((VD || CurContext->isDependentContext())
14748                        ? RefExpr->IgnoreParens()
14749                        : Ref);
14750   }
14751 
14752   if (Vars.empty())
14753     return nullptr;
14754 
14755   return OMPAllocateClause::Create(Context, StartLoc, LParenLoc, Allocator,
14756                                    ColonLoc, EndLoc, Vars);
14757 }
14758