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 static void checkAllocateClauses(Sema &S, DSAStackTy *Stack,
1886                                  ArrayRef<OMPClause *> Clauses);
1887 
1888 void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
1889   // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
1890   //  A variable of class type (or array thereof) that appears in a lastprivate
1891   //  clause requires an accessible, unambiguous default constructor for the
1892   //  class type, unless the list item is also specified in a firstprivate
1893   //  clause.
1894   if (const auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
1895     for (OMPClause *C : D->clauses()) {
1896       if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
1897         SmallVector<Expr *, 8> PrivateCopies;
1898         for (Expr *DE : Clause->varlists()) {
1899           if (DE->isValueDependent() || DE->isTypeDependent()) {
1900             PrivateCopies.push_back(nullptr);
1901             continue;
1902           }
1903           auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
1904           auto *VD = cast<VarDecl>(DRE->getDecl());
1905           QualType Type = VD->getType().getNonReferenceType();
1906           const DSAStackTy::DSAVarData DVar =
1907               DSAStack->getTopDSA(VD, /*FromParent=*/false);
1908           if (DVar.CKind == OMPC_lastprivate) {
1909             // Generate helper private variable and initialize it with the
1910             // default value. The address of the original variable is replaced
1911             // by the address of the new private variable in CodeGen. This new
1912             // variable is not added to IdResolver, so the code in the OpenMP
1913             // region uses original variable for proper diagnostics.
1914             VarDecl *VDPrivate = buildVarDecl(
1915                 *this, DE->getExprLoc(), Type.getUnqualifiedType(),
1916                 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr, DRE);
1917             ActOnUninitializedDecl(VDPrivate);
1918             if (VDPrivate->isInvalidDecl()) {
1919               PrivateCopies.push_back(nullptr);
1920               continue;
1921             }
1922             PrivateCopies.push_back(buildDeclRefExpr(
1923                 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
1924           } else {
1925             // The variable is also a firstprivate, so initialization sequence
1926             // for private copy is generated already.
1927             PrivateCopies.push_back(nullptr);
1928           }
1929         }
1930         Clause->setPrivateCopies(PrivateCopies);
1931       }
1932     }
1933     // Check allocate clauses.
1934     if (!CurContext->isDependentContext())
1935       checkAllocateClauses(*this, DSAStack, D->clauses());
1936   }
1937 
1938   DSAStack->pop();
1939   DiscardCleanupsInEvaluationContext();
1940   PopExpressionEvaluationContext();
1941 }
1942 
1943 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
1944                                      Expr *NumIterations, Sema &SemaRef,
1945                                      Scope *S, DSAStackTy *Stack);
1946 
1947 namespace {
1948 
1949 class VarDeclFilterCCC final : public CorrectionCandidateCallback {
1950 private:
1951   Sema &SemaRef;
1952 
1953 public:
1954   explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
1955   bool ValidateCandidate(const TypoCorrection &Candidate) override {
1956     NamedDecl *ND = Candidate.getCorrectionDecl();
1957     if (const auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
1958       return VD->hasGlobalStorage() &&
1959              SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1960                                    SemaRef.getCurScope());
1961     }
1962     return false;
1963   }
1964 
1965   std::unique_ptr<CorrectionCandidateCallback> clone() override {
1966     return llvm::make_unique<VarDeclFilterCCC>(*this);
1967   }
1968 
1969 };
1970 
1971 class VarOrFuncDeclFilterCCC final : public CorrectionCandidateCallback {
1972 private:
1973   Sema &SemaRef;
1974 
1975 public:
1976   explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
1977   bool ValidateCandidate(const TypoCorrection &Candidate) override {
1978     NamedDecl *ND = Candidate.getCorrectionDecl();
1979     if (ND && ((isa<VarDecl>(ND) && ND->getKind() == Decl::Var) ||
1980                isa<FunctionDecl>(ND))) {
1981       return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1982                                    SemaRef.getCurScope());
1983     }
1984     return false;
1985   }
1986 
1987   std::unique_ptr<CorrectionCandidateCallback> clone() override {
1988     return llvm::make_unique<VarOrFuncDeclFilterCCC>(*this);
1989   }
1990 };
1991 
1992 } // namespace
1993 
1994 ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
1995                                          CXXScopeSpec &ScopeSpec,
1996                                          const DeclarationNameInfo &Id,
1997                                          OpenMPDirectiveKind Kind) {
1998   LookupResult Lookup(*this, Id, LookupOrdinaryName);
1999   LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
2000 
2001   if (Lookup.isAmbiguous())
2002     return ExprError();
2003 
2004   VarDecl *VD;
2005   if (!Lookup.isSingleResult()) {
2006     VarDeclFilterCCC CCC(*this);
2007     if (TypoCorrection Corrected =
2008             CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC,
2009                         CTK_ErrorRecovery)) {
2010       diagnoseTypo(Corrected,
2011                    PDiag(Lookup.empty()
2012                              ? diag::err_undeclared_var_use_suggest
2013                              : diag::err_omp_expected_var_arg_suggest)
2014                        << Id.getName());
2015       VD = Corrected.getCorrectionDeclAs<VarDecl>();
2016     } else {
2017       Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
2018                                        : diag::err_omp_expected_var_arg)
2019           << Id.getName();
2020       return ExprError();
2021     }
2022   } else if (!(VD = Lookup.getAsSingle<VarDecl>())) {
2023     Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
2024     Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
2025     return ExprError();
2026   }
2027   Lookup.suppressDiagnostics();
2028 
2029   // OpenMP [2.9.2, Syntax, C/C++]
2030   //   Variables must be file-scope, namespace-scope, or static block-scope.
2031   if (Kind == OMPD_threadprivate && !VD->hasGlobalStorage()) {
2032     Diag(Id.getLoc(), diag::err_omp_global_var_arg)
2033         << getOpenMPDirectiveName(Kind) << !VD->isStaticLocal();
2034     bool IsDecl =
2035         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2036     Diag(VD->getLocation(),
2037          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2038         << VD;
2039     return ExprError();
2040   }
2041 
2042   VarDecl *CanonicalVD = VD->getCanonicalDecl();
2043   NamedDecl *ND = CanonicalVD;
2044   // OpenMP [2.9.2, Restrictions, C/C++, p.2]
2045   //   A threadprivate directive for file-scope variables must appear outside
2046   //   any definition or declaration.
2047   if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
2048       !getCurLexicalContext()->isTranslationUnit()) {
2049     Diag(Id.getLoc(), diag::err_omp_var_scope)
2050         << getOpenMPDirectiveName(Kind) << VD;
2051     bool IsDecl =
2052         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2053     Diag(VD->getLocation(),
2054          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2055         << VD;
2056     return ExprError();
2057   }
2058   // OpenMP [2.9.2, Restrictions, C/C++, p.3]
2059   //   A threadprivate directive for static class member variables must appear
2060   //   in the class definition, in the same scope in which the member
2061   //   variables are declared.
2062   if (CanonicalVD->isStaticDataMember() &&
2063       !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
2064     Diag(Id.getLoc(), diag::err_omp_var_scope)
2065         << getOpenMPDirectiveName(Kind) << VD;
2066     bool IsDecl =
2067         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2068     Diag(VD->getLocation(),
2069          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2070         << VD;
2071     return ExprError();
2072   }
2073   // OpenMP [2.9.2, Restrictions, C/C++, p.4]
2074   //   A threadprivate directive for namespace-scope variables must appear
2075   //   outside any definition or declaration other than the namespace
2076   //   definition itself.
2077   if (CanonicalVD->getDeclContext()->isNamespace() &&
2078       (!getCurLexicalContext()->isFileContext() ||
2079        !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
2080     Diag(Id.getLoc(), diag::err_omp_var_scope)
2081         << getOpenMPDirectiveName(Kind) << VD;
2082     bool IsDecl =
2083         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2084     Diag(VD->getLocation(),
2085          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2086         << VD;
2087     return ExprError();
2088   }
2089   // OpenMP [2.9.2, Restrictions, C/C++, p.6]
2090   //   A threadprivate directive for static block-scope variables must appear
2091   //   in the scope of the variable and not in a nested scope.
2092   if (CanonicalVD->isLocalVarDecl() && CurScope &&
2093       !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
2094     Diag(Id.getLoc(), diag::err_omp_var_scope)
2095         << getOpenMPDirectiveName(Kind) << VD;
2096     bool IsDecl =
2097         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2098     Diag(VD->getLocation(),
2099          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2100         << VD;
2101     return ExprError();
2102   }
2103 
2104   // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
2105   //   A threadprivate directive must lexically precede all references to any
2106   //   of the variables in its list.
2107   if (Kind == OMPD_threadprivate && VD->isUsed() &&
2108       !DSAStack->isThreadPrivate(VD)) {
2109     Diag(Id.getLoc(), diag::err_omp_var_used)
2110         << getOpenMPDirectiveName(Kind) << VD;
2111     return ExprError();
2112   }
2113 
2114   QualType ExprType = VD->getType().getNonReferenceType();
2115   return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
2116                              SourceLocation(), VD,
2117                              /*RefersToEnclosingVariableOrCapture=*/false,
2118                              Id.getLoc(), ExprType, VK_LValue);
2119 }
2120 
2121 Sema::DeclGroupPtrTy
2122 Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
2123                                         ArrayRef<Expr *> VarList) {
2124   if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
2125     CurContext->addDecl(D);
2126     return DeclGroupPtrTy::make(DeclGroupRef(D));
2127   }
2128   return nullptr;
2129 }
2130 
2131 namespace {
2132 class LocalVarRefChecker final
2133     : public ConstStmtVisitor<LocalVarRefChecker, bool> {
2134   Sema &SemaRef;
2135 
2136 public:
2137   bool VisitDeclRefExpr(const DeclRefExpr *E) {
2138     if (const auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
2139       if (VD->hasLocalStorage()) {
2140         SemaRef.Diag(E->getBeginLoc(),
2141                      diag::err_omp_local_var_in_threadprivate_init)
2142             << E->getSourceRange();
2143         SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
2144             << VD << VD->getSourceRange();
2145         return true;
2146       }
2147     }
2148     return false;
2149   }
2150   bool VisitStmt(const Stmt *S) {
2151     for (const Stmt *Child : S->children()) {
2152       if (Child && Visit(Child))
2153         return true;
2154     }
2155     return false;
2156   }
2157   explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
2158 };
2159 } // namespace
2160 
2161 OMPThreadPrivateDecl *
2162 Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
2163   SmallVector<Expr *, 8> Vars;
2164   for (Expr *RefExpr : VarList) {
2165     auto *DE = cast<DeclRefExpr>(RefExpr);
2166     auto *VD = cast<VarDecl>(DE->getDecl());
2167     SourceLocation ILoc = DE->getExprLoc();
2168 
2169     // Mark variable as used.
2170     VD->setReferenced();
2171     VD->markUsed(Context);
2172 
2173     QualType QType = VD->getType();
2174     if (QType->isDependentType() || QType->isInstantiationDependentType()) {
2175       // It will be analyzed later.
2176       Vars.push_back(DE);
2177       continue;
2178     }
2179 
2180     // OpenMP [2.9.2, Restrictions, C/C++, p.10]
2181     //   A threadprivate variable must not have an incomplete type.
2182     if (RequireCompleteType(ILoc, VD->getType(),
2183                             diag::err_omp_threadprivate_incomplete_type)) {
2184       continue;
2185     }
2186 
2187     // OpenMP [2.9.2, Restrictions, C/C++, p.10]
2188     //   A threadprivate variable must not have a reference type.
2189     if (VD->getType()->isReferenceType()) {
2190       Diag(ILoc, diag::err_omp_ref_type_arg)
2191           << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
2192       bool IsDecl =
2193           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2194       Diag(VD->getLocation(),
2195            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2196           << VD;
2197       continue;
2198     }
2199 
2200     // Check if this is a TLS variable. If TLS is not being supported, produce
2201     // the corresponding diagnostic.
2202     if ((VD->getTLSKind() != VarDecl::TLS_None &&
2203          !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
2204            getLangOpts().OpenMPUseTLS &&
2205            getASTContext().getTargetInfo().isTLSSupported())) ||
2206         (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
2207          !VD->isLocalVarDecl())) {
2208       Diag(ILoc, diag::err_omp_var_thread_local)
2209           << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
2210       bool IsDecl =
2211           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2212       Diag(VD->getLocation(),
2213            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2214           << VD;
2215       continue;
2216     }
2217 
2218     // Check if initial value of threadprivate variable reference variable with
2219     // local storage (it is not supported by runtime).
2220     if (const Expr *Init = VD->getAnyInitializer()) {
2221       LocalVarRefChecker Checker(*this);
2222       if (Checker.Visit(Init))
2223         continue;
2224     }
2225 
2226     Vars.push_back(RefExpr);
2227     DSAStack->addDSA(VD, DE, OMPC_threadprivate);
2228     VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
2229         Context, SourceRange(Loc, Loc)));
2230     if (ASTMutationListener *ML = Context.getASTMutationListener())
2231       ML->DeclarationMarkedOpenMPThreadPrivate(VD);
2232   }
2233   OMPThreadPrivateDecl *D = nullptr;
2234   if (!Vars.empty()) {
2235     D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
2236                                      Vars);
2237     D->setAccess(AS_public);
2238   }
2239   return D;
2240 }
2241 
2242 static OMPAllocateDeclAttr::AllocatorTypeTy
2243 getAllocatorKind(Sema &S, DSAStackTy *Stack, Expr *Allocator) {
2244   if (!Allocator)
2245     return OMPAllocateDeclAttr::OMPDefaultMemAlloc;
2246   if (Allocator->isTypeDependent() || Allocator->isValueDependent() ||
2247       Allocator->isInstantiationDependent() ||
2248       Allocator->containsUnexpandedParameterPack())
2249     return OMPAllocateDeclAttr::OMPUserDefinedMemAlloc;
2250   auto AllocatorKindRes = OMPAllocateDeclAttr::OMPUserDefinedMemAlloc;
2251   const Expr *AE = Allocator->IgnoreParenImpCasts();
2252   for (int I = OMPAllocateDeclAttr::OMPDefaultMemAlloc;
2253        I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
2254     auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
2255     const Expr *DefAllocator = Stack->getAllocator(AllocatorKind);
2256     llvm::FoldingSetNodeID AEId, DAEId;
2257     AE->Profile(AEId, S.getASTContext(), /*Canonical=*/true);
2258     DefAllocator->Profile(DAEId, S.getASTContext(), /*Canonical=*/true);
2259     if (AEId == DAEId) {
2260       AllocatorKindRes = AllocatorKind;
2261       break;
2262     }
2263   }
2264   return AllocatorKindRes;
2265 }
2266 
2267 static bool checkPreviousOMPAllocateAttribute(
2268     Sema &S, DSAStackTy *Stack, Expr *RefExpr, VarDecl *VD,
2269     OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind, Expr *Allocator) {
2270   if (!VD->hasAttr<OMPAllocateDeclAttr>())
2271     return false;
2272   const auto *A = VD->getAttr<OMPAllocateDeclAttr>();
2273   Expr *PrevAllocator = A->getAllocator();
2274   OMPAllocateDeclAttr::AllocatorTypeTy PrevAllocatorKind =
2275       getAllocatorKind(S, Stack, PrevAllocator);
2276   bool AllocatorsMatch = AllocatorKind == PrevAllocatorKind;
2277   if (AllocatorsMatch &&
2278       AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc &&
2279       Allocator && PrevAllocator) {
2280     const Expr *AE = Allocator->IgnoreParenImpCasts();
2281     const Expr *PAE = PrevAllocator->IgnoreParenImpCasts();
2282     llvm::FoldingSetNodeID AEId, PAEId;
2283     AE->Profile(AEId, S.Context, /*Canonical=*/true);
2284     PAE->Profile(PAEId, S.Context, /*Canonical=*/true);
2285     AllocatorsMatch = AEId == PAEId;
2286   }
2287   if (!AllocatorsMatch) {
2288     SmallString<256> AllocatorBuffer;
2289     llvm::raw_svector_ostream AllocatorStream(AllocatorBuffer);
2290     if (Allocator)
2291       Allocator->printPretty(AllocatorStream, nullptr, S.getPrintingPolicy());
2292     SmallString<256> PrevAllocatorBuffer;
2293     llvm::raw_svector_ostream PrevAllocatorStream(PrevAllocatorBuffer);
2294     if (PrevAllocator)
2295       PrevAllocator->printPretty(PrevAllocatorStream, nullptr,
2296                                  S.getPrintingPolicy());
2297 
2298     SourceLocation AllocatorLoc =
2299         Allocator ? Allocator->getExprLoc() : RefExpr->getExprLoc();
2300     SourceRange AllocatorRange =
2301         Allocator ? Allocator->getSourceRange() : RefExpr->getSourceRange();
2302     SourceLocation PrevAllocatorLoc =
2303         PrevAllocator ? PrevAllocator->getExprLoc() : A->getLocation();
2304     SourceRange PrevAllocatorRange =
2305         PrevAllocator ? PrevAllocator->getSourceRange() : A->getRange();
2306     S.Diag(AllocatorLoc, diag::warn_omp_used_different_allocator)
2307         << (Allocator ? 1 : 0) << AllocatorStream.str()
2308         << (PrevAllocator ? 1 : 0) << PrevAllocatorStream.str()
2309         << AllocatorRange;
2310     S.Diag(PrevAllocatorLoc, diag::note_omp_previous_allocator)
2311         << PrevAllocatorRange;
2312     return true;
2313   }
2314   return false;
2315 }
2316 
2317 static void
2318 applyOMPAllocateAttribute(Sema &S, VarDecl *VD,
2319                           OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind,
2320                           Expr *Allocator, SourceRange SR) {
2321   if (VD->hasAttr<OMPAllocateDeclAttr>())
2322     return;
2323   if (Allocator &&
2324       (Allocator->isTypeDependent() || Allocator->isValueDependent() ||
2325        Allocator->isInstantiationDependent() ||
2326        Allocator->containsUnexpandedParameterPack()))
2327     return;
2328   auto *A = OMPAllocateDeclAttr::CreateImplicit(S.Context, AllocatorKind,
2329                                                 Allocator, SR);
2330   VD->addAttr(A);
2331   if (ASTMutationListener *ML = S.Context.getASTMutationListener())
2332     ML->DeclarationMarkedOpenMPAllocate(VD, A);
2333 }
2334 
2335 Sema::DeclGroupPtrTy Sema::ActOnOpenMPAllocateDirective(
2336     SourceLocation Loc, ArrayRef<Expr *> VarList,
2337     ArrayRef<OMPClause *> Clauses, DeclContext *Owner) {
2338   assert(Clauses.size() <= 1 && "Expected at most one clause.");
2339   Expr *Allocator = nullptr;
2340   if (Clauses.empty()) {
2341     // OpenMP 5.0, 2.11.3 allocate Directive, Restrictions.
2342     // allocate directives that appear in a target region must specify an
2343     // allocator clause unless a requires directive with the dynamic_allocators
2344     // clause is present in the same compilation unit.
2345     if (LangOpts.OpenMPIsDevice &&
2346         !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())
2347       targetDiag(Loc, diag::err_expected_allocator_clause);
2348   } else {
2349     Allocator = cast<OMPAllocatorClause>(Clauses.back())->getAllocator();
2350   }
2351   OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind =
2352       getAllocatorKind(*this, DSAStack, Allocator);
2353   SmallVector<Expr *, 8> Vars;
2354   for (Expr *RefExpr : VarList) {
2355     auto *DE = cast<DeclRefExpr>(RefExpr);
2356     auto *VD = cast<VarDecl>(DE->getDecl());
2357 
2358     // Check if this is a TLS variable or global register.
2359     if (VD->getTLSKind() != VarDecl::TLS_None ||
2360         VD->hasAttr<OMPThreadPrivateDeclAttr>() ||
2361         (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
2362          !VD->isLocalVarDecl()))
2363       continue;
2364     // Do not apply for parameters.
2365     if (isa<ParmVarDecl>(VD))
2366       continue;
2367 
2368     // If the used several times in the allocate directive, the same allocator
2369     // must be used.
2370     if (checkPreviousOMPAllocateAttribute(*this, DSAStack, RefExpr, VD,
2371                                           AllocatorKind, Allocator))
2372       continue;
2373 
2374     // OpenMP, 2.11.3 allocate Directive, Restrictions, C / C++
2375     // If a list item has a static storage type, the allocator expression in the
2376     // allocator clause must be a constant expression that evaluates to one of
2377     // the predefined memory allocator values.
2378     if (Allocator && VD->hasGlobalStorage()) {
2379       if (AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc) {
2380         Diag(Allocator->getExprLoc(),
2381              diag::err_omp_expected_predefined_allocator)
2382             << Allocator->getSourceRange();
2383         bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
2384                       VarDecl::DeclarationOnly;
2385         Diag(VD->getLocation(),
2386              IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2387             << VD;
2388         continue;
2389       }
2390     }
2391 
2392     Vars.push_back(RefExpr);
2393     applyOMPAllocateAttribute(*this, VD, AllocatorKind, Allocator,
2394                               DE->getSourceRange());
2395   }
2396   if (Vars.empty())
2397     return nullptr;
2398   if (!Owner)
2399     Owner = getCurLexicalContext();
2400   auto *D = OMPAllocateDecl::Create(Context, Owner, Loc, Vars, Clauses);
2401   D->setAccess(AS_public);
2402   Owner->addDecl(D);
2403   return DeclGroupPtrTy::make(DeclGroupRef(D));
2404 }
2405 
2406 Sema::DeclGroupPtrTy
2407 Sema::ActOnOpenMPRequiresDirective(SourceLocation Loc,
2408                                    ArrayRef<OMPClause *> ClauseList) {
2409   OMPRequiresDecl *D = nullptr;
2410   if (!CurContext->isFileContext()) {
2411     Diag(Loc, diag::err_omp_invalid_scope) << "requires";
2412   } else {
2413     D = CheckOMPRequiresDecl(Loc, ClauseList);
2414     if (D) {
2415       CurContext->addDecl(D);
2416       DSAStack->addRequiresDecl(D);
2417     }
2418   }
2419   return DeclGroupPtrTy::make(DeclGroupRef(D));
2420 }
2421 
2422 OMPRequiresDecl *Sema::CheckOMPRequiresDecl(SourceLocation Loc,
2423                                             ArrayRef<OMPClause *> ClauseList) {
2424   if (!DSAStack->hasDuplicateRequiresClause(ClauseList))
2425     return OMPRequiresDecl::Create(Context, getCurLexicalContext(), Loc,
2426                                    ClauseList);
2427   return nullptr;
2428 }
2429 
2430 static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack,
2431                               const ValueDecl *D,
2432                               const DSAStackTy::DSAVarData &DVar,
2433                               bool IsLoopIterVar = false) {
2434   if (DVar.RefExpr) {
2435     SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
2436         << getOpenMPClauseName(DVar.CKind);
2437     return;
2438   }
2439   enum {
2440     PDSA_StaticMemberShared,
2441     PDSA_StaticLocalVarShared,
2442     PDSA_LoopIterVarPrivate,
2443     PDSA_LoopIterVarLinear,
2444     PDSA_LoopIterVarLastprivate,
2445     PDSA_ConstVarShared,
2446     PDSA_GlobalVarShared,
2447     PDSA_TaskVarFirstprivate,
2448     PDSA_LocalVarPrivate,
2449     PDSA_Implicit
2450   } Reason = PDSA_Implicit;
2451   bool ReportHint = false;
2452   auto ReportLoc = D->getLocation();
2453   auto *VD = dyn_cast<VarDecl>(D);
2454   if (IsLoopIterVar) {
2455     if (DVar.CKind == OMPC_private)
2456       Reason = PDSA_LoopIterVarPrivate;
2457     else if (DVar.CKind == OMPC_lastprivate)
2458       Reason = PDSA_LoopIterVarLastprivate;
2459     else
2460       Reason = PDSA_LoopIterVarLinear;
2461   } else if (isOpenMPTaskingDirective(DVar.DKind) &&
2462              DVar.CKind == OMPC_firstprivate) {
2463     Reason = PDSA_TaskVarFirstprivate;
2464     ReportLoc = DVar.ImplicitDSALoc;
2465   } else if (VD && VD->isStaticLocal())
2466     Reason = PDSA_StaticLocalVarShared;
2467   else if (VD && VD->isStaticDataMember())
2468     Reason = PDSA_StaticMemberShared;
2469   else if (VD && VD->isFileVarDecl())
2470     Reason = PDSA_GlobalVarShared;
2471   else if (D->getType().isConstant(SemaRef.getASTContext()))
2472     Reason = PDSA_ConstVarShared;
2473   else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
2474     ReportHint = true;
2475     Reason = PDSA_LocalVarPrivate;
2476   }
2477   if (Reason != PDSA_Implicit) {
2478     SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
2479         << Reason << ReportHint
2480         << getOpenMPDirectiveName(Stack->getCurrentDirective());
2481   } else if (DVar.ImplicitDSALoc.isValid()) {
2482     SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
2483         << getOpenMPClauseName(DVar.CKind);
2484   }
2485 }
2486 
2487 namespace {
2488 class DSAAttrChecker final : public StmtVisitor<DSAAttrChecker, void> {
2489   DSAStackTy *Stack;
2490   Sema &SemaRef;
2491   bool ErrorFound = false;
2492   CapturedStmt *CS = nullptr;
2493   llvm::SmallVector<Expr *, 4> ImplicitFirstprivate;
2494   llvm::SmallVector<Expr *, 4> ImplicitMap;
2495   Sema::VarsWithInheritedDSAType VarsWithInheritedDSA;
2496   llvm::SmallDenseSet<const ValueDecl *, 4> ImplicitDeclarations;
2497 
2498   void VisitSubCaptures(OMPExecutableDirective *S) {
2499     // Check implicitly captured variables.
2500     if (!S->hasAssociatedStmt() || !S->getAssociatedStmt())
2501       return;
2502     for (const CapturedStmt::Capture &Cap :
2503          S->getInnermostCapturedStmt()->captures()) {
2504       if (!Cap.capturesVariable())
2505         continue;
2506       VarDecl *VD = Cap.getCapturedVar();
2507       // Do not try to map the variable if it or its sub-component was mapped
2508       // already.
2509       if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
2510           Stack->checkMappableExprComponentListsForDecl(
2511               VD, /*CurrentRegionOnly=*/true,
2512               [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
2513                  OpenMPClauseKind) { return true; }))
2514         continue;
2515       DeclRefExpr *DRE = buildDeclRefExpr(
2516           SemaRef, VD, VD->getType().getNonLValueExprType(SemaRef.Context),
2517           Cap.getLocation(), /*RefersToCapture=*/true);
2518       Visit(DRE);
2519     }
2520   }
2521 
2522 public:
2523   void VisitDeclRefExpr(DeclRefExpr *E) {
2524     if (E->isTypeDependent() || E->isValueDependent() ||
2525         E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
2526       return;
2527     if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
2528       VD = VD->getCanonicalDecl();
2529       // Skip internally declared variables.
2530       if (VD->hasLocalStorage() && !CS->capturesVariable(VD))
2531         return;
2532 
2533       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
2534       // Check if the variable has explicit DSA set and stop analysis if it so.
2535       if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second)
2536         return;
2537 
2538       // Skip internally declared static variables.
2539       llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
2540           OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
2541       if (VD->hasGlobalStorage() && !CS->capturesVariable(VD) &&
2542           (!Res || *Res != OMPDeclareTargetDeclAttr::MT_Link))
2543         return;
2544 
2545       SourceLocation ELoc = E->getExprLoc();
2546       OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
2547       // The default(none) clause requires that each variable that is referenced
2548       // in the construct, and does not have a predetermined data-sharing
2549       // attribute, must have its data-sharing attribute explicitly determined
2550       // by being listed in a data-sharing attribute clause.
2551       if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
2552           isImplicitOrExplicitTaskingRegion(DKind) &&
2553           VarsWithInheritedDSA.count(VD) == 0) {
2554         VarsWithInheritedDSA[VD] = E;
2555         return;
2556       }
2557 
2558       if (isOpenMPTargetExecutionDirective(DKind) &&
2559           !Stack->isLoopControlVariable(VD).first) {
2560         if (!Stack->checkMappableExprComponentListsForDecl(
2561                 VD, /*CurrentRegionOnly=*/true,
2562                 [](OMPClauseMappableExprCommon::MappableExprComponentListRef
2563                        StackComponents,
2564                    OpenMPClauseKind) {
2565                   // Variable is used if it has been marked as an array, array
2566                   // section or the variable iself.
2567                   return StackComponents.size() == 1 ||
2568                          std::all_of(
2569                              std::next(StackComponents.rbegin()),
2570                              StackComponents.rend(),
2571                              [](const OMPClauseMappableExprCommon::
2572                                     MappableComponent &MC) {
2573                                return MC.getAssociatedDeclaration() ==
2574                                           nullptr &&
2575                                       (isa<OMPArraySectionExpr>(
2576                                            MC.getAssociatedExpression()) ||
2577                                        isa<ArraySubscriptExpr>(
2578                                            MC.getAssociatedExpression()));
2579                              });
2580                 })) {
2581           bool IsFirstprivate = false;
2582           // By default lambdas are captured as firstprivates.
2583           if (const auto *RD =
2584                   VD->getType().getNonReferenceType()->getAsCXXRecordDecl())
2585             IsFirstprivate = RD->isLambda();
2586           IsFirstprivate =
2587               IsFirstprivate ||
2588               (VD->getType().getNonReferenceType()->isScalarType() &&
2589                Stack->getDefaultDMA() != DMA_tofrom_scalar && !Res);
2590           if (IsFirstprivate)
2591             ImplicitFirstprivate.emplace_back(E);
2592           else
2593             ImplicitMap.emplace_back(E);
2594           return;
2595         }
2596       }
2597 
2598       // OpenMP [2.9.3.6, Restrictions, p.2]
2599       //  A list item that appears in a reduction clause of the innermost
2600       //  enclosing worksharing or parallel construct may not be accessed in an
2601       //  explicit task.
2602       DVar = Stack->hasInnermostDSA(
2603           VD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
2604           [](OpenMPDirectiveKind K) {
2605             return isOpenMPParallelDirective(K) ||
2606                    isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
2607           },
2608           /*FromParent=*/true);
2609       if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
2610         ErrorFound = true;
2611         SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
2612         reportOriginalDsa(SemaRef, Stack, VD, DVar);
2613         return;
2614       }
2615 
2616       // Define implicit data-sharing attributes for task.
2617       DVar = Stack->getImplicitDSA(VD, /*FromParent=*/false);
2618       if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
2619           !Stack->isLoopControlVariable(VD).first) {
2620         ImplicitFirstprivate.push_back(E);
2621         return;
2622       }
2623 
2624       // Store implicitly used globals with declare target link for parent
2625       // target.
2626       if (!isOpenMPTargetExecutionDirective(DKind) && Res &&
2627           *Res == OMPDeclareTargetDeclAttr::MT_Link) {
2628         Stack->addToParentTargetRegionLinkGlobals(E);
2629         return;
2630       }
2631     }
2632   }
2633   void VisitMemberExpr(MemberExpr *E) {
2634     if (E->isTypeDependent() || E->isValueDependent() ||
2635         E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
2636       return;
2637     auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
2638     OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
2639     if (auto *TE = dyn_cast<CXXThisExpr>(E->getBase()->IgnoreParens())) {
2640       if (!FD)
2641         return;
2642       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(FD, /*FromParent=*/false);
2643       // Check if the variable has explicit DSA set and stop analysis if it
2644       // so.
2645       if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second)
2646         return;
2647 
2648       if (isOpenMPTargetExecutionDirective(DKind) &&
2649           !Stack->isLoopControlVariable(FD).first &&
2650           !Stack->checkMappableExprComponentListsForDecl(
2651               FD, /*CurrentRegionOnly=*/true,
2652               [](OMPClauseMappableExprCommon::MappableExprComponentListRef
2653                      StackComponents,
2654                  OpenMPClauseKind) {
2655                 return isa<CXXThisExpr>(
2656                     cast<MemberExpr>(
2657                         StackComponents.back().getAssociatedExpression())
2658                         ->getBase()
2659                         ->IgnoreParens());
2660               })) {
2661         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
2662         //  A bit-field cannot appear in a map clause.
2663         //
2664         if (FD->isBitField())
2665           return;
2666 
2667         // Check to see if the member expression is referencing a class that
2668         // has already been explicitly mapped
2669         if (Stack->isClassPreviouslyMapped(TE->getType()))
2670           return;
2671 
2672         ImplicitMap.emplace_back(E);
2673         return;
2674       }
2675 
2676       SourceLocation ELoc = E->getExprLoc();
2677       // OpenMP [2.9.3.6, Restrictions, p.2]
2678       //  A list item that appears in a reduction clause of the innermost
2679       //  enclosing worksharing or parallel construct may not be accessed in
2680       //  an  explicit task.
2681       DVar = Stack->hasInnermostDSA(
2682           FD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
2683           [](OpenMPDirectiveKind K) {
2684             return isOpenMPParallelDirective(K) ||
2685                    isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
2686           },
2687           /*FromParent=*/true);
2688       if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
2689         ErrorFound = true;
2690         SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
2691         reportOriginalDsa(SemaRef, Stack, FD, DVar);
2692         return;
2693       }
2694 
2695       // Define implicit data-sharing attributes for task.
2696       DVar = Stack->getImplicitDSA(FD, /*FromParent=*/false);
2697       if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
2698           !Stack->isLoopControlVariable(FD).first) {
2699         // Check if there is a captured expression for the current field in the
2700         // region. Do not mark it as firstprivate unless there is no captured
2701         // expression.
2702         // TODO: try to make it firstprivate.
2703         if (DVar.CKind != OMPC_unknown)
2704           ImplicitFirstprivate.push_back(E);
2705       }
2706       return;
2707     }
2708     if (isOpenMPTargetExecutionDirective(DKind)) {
2709       OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
2710       if (!checkMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map,
2711                                         /*NoDiagnose=*/true))
2712         return;
2713       const auto *VD = cast<ValueDecl>(
2714           CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl());
2715       if (!Stack->checkMappableExprComponentListsForDecl(
2716               VD, /*CurrentRegionOnly=*/true,
2717               [&CurComponents](
2718                   OMPClauseMappableExprCommon::MappableExprComponentListRef
2719                       StackComponents,
2720                   OpenMPClauseKind) {
2721                 auto CCI = CurComponents.rbegin();
2722                 auto CCE = CurComponents.rend();
2723                 for (const auto &SC : llvm::reverse(StackComponents)) {
2724                   // Do both expressions have the same kind?
2725                   if (CCI->getAssociatedExpression()->getStmtClass() !=
2726                       SC.getAssociatedExpression()->getStmtClass())
2727                     if (!(isa<OMPArraySectionExpr>(
2728                               SC.getAssociatedExpression()) &&
2729                           isa<ArraySubscriptExpr>(
2730                               CCI->getAssociatedExpression())))
2731                       return false;
2732 
2733                   const Decl *CCD = CCI->getAssociatedDeclaration();
2734                   const Decl *SCD = SC.getAssociatedDeclaration();
2735                   CCD = CCD ? CCD->getCanonicalDecl() : nullptr;
2736                   SCD = SCD ? SCD->getCanonicalDecl() : nullptr;
2737                   if (SCD != CCD)
2738                     return false;
2739                   std::advance(CCI, 1);
2740                   if (CCI == CCE)
2741                     break;
2742                 }
2743                 return true;
2744               })) {
2745         Visit(E->getBase());
2746       }
2747     } else {
2748       Visit(E->getBase());
2749     }
2750   }
2751   void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
2752     for (OMPClause *C : S->clauses()) {
2753       // Skip analysis of arguments of implicitly defined firstprivate clause
2754       // for task|target directives.
2755       // Skip analysis of arguments of implicitly defined map clause for target
2756       // directives.
2757       if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) &&
2758                  C->isImplicit())) {
2759         for (Stmt *CC : C->children()) {
2760           if (CC)
2761             Visit(CC);
2762         }
2763       }
2764     }
2765     // Check implicitly captured variables.
2766     VisitSubCaptures(S);
2767   }
2768   void VisitStmt(Stmt *S) {
2769     for (Stmt *C : S->children()) {
2770       if (C) {
2771         // Check implicitly captured variables in the task-based directives to
2772         // check if they must be firstprivatized.
2773         Visit(C);
2774       }
2775     }
2776   }
2777 
2778   bool isErrorFound() const { return ErrorFound; }
2779   ArrayRef<Expr *> getImplicitFirstprivate() const {
2780     return ImplicitFirstprivate;
2781   }
2782   ArrayRef<Expr *> getImplicitMap() const { return ImplicitMap; }
2783   const Sema::VarsWithInheritedDSAType &getVarsWithInheritedDSA() const {
2784     return VarsWithInheritedDSA;
2785   }
2786 
2787   DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
2788       : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {
2789     // Process declare target link variables for the target directives.
2790     if (isOpenMPTargetExecutionDirective(S->getCurrentDirective())) {
2791       for (DeclRefExpr *E : Stack->getLinkGlobals())
2792         Visit(E);
2793     }
2794   }
2795 };
2796 } // namespace
2797 
2798 void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
2799   switch (DKind) {
2800   case OMPD_parallel:
2801   case OMPD_parallel_for:
2802   case OMPD_parallel_for_simd:
2803   case OMPD_parallel_sections:
2804   case OMPD_teams:
2805   case OMPD_teams_distribute:
2806   case OMPD_teams_distribute_simd: {
2807     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2808     QualType KmpInt32PtrTy =
2809         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2810     Sema::CapturedParamNameType Params[] = {
2811         std::make_pair(".global_tid.", KmpInt32PtrTy),
2812         std::make_pair(".bound_tid.", KmpInt32PtrTy),
2813         std::make_pair(StringRef(), QualType()) // __context with shared vars
2814     };
2815     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2816                              Params);
2817     break;
2818   }
2819   case OMPD_target_teams:
2820   case OMPD_target_parallel:
2821   case OMPD_target_parallel_for:
2822   case OMPD_target_parallel_for_simd:
2823   case OMPD_target_teams_distribute:
2824   case OMPD_target_teams_distribute_simd: {
2825     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2826     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2827     QualType KmpInt32PtrTy =
2828         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2829     QualType Args[] = {VoidPtrTy};
2830     FunctionProtoType::ExtProtoInfo EPI;
2831     EPI.Variadic = true;
2832     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2833     Sema::CapturedParamNameType Params[] = {
2834         std::make_pair(".global_tid.", KmpInt32Ty),
2835         std::make_pair(".part_id.", KmpInt32PtrTy),
2836         std::make_pair(".privates.", VoidPtrTy),
2837         std::make_pair(
2838             ".copy_fn.",
2839             Context.getPointerType(CopyFnType).withConst().withRestrict()),
2840         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2841         std::make_pair(StringRef(), QualType()) // __context with shared vars
2842     };
2843     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2844                              Params);
2845     // Mark this captured region as inlined, because we don't use outlined
2846     // function directly.
2847     getCurCapturedRegion()->TheCapturedDecl->addAttr(
2848         AlwaysInlineAttr::CreateImplicit(
2849             Context, AlwaysInlineAttr::Keyword_forceinline));
2850     Sema::CapturedParamNameType ParamsTarget[] = {
2851         std::make_pair(StringRef(), QualType()) // __context with shared vars
2852     };
2853     // Start a captured region for 'target' with no implicit parameters.
2854     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2855                              ParamsTarget);
2856     Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
2857         std::make_pair(".global_tid.", KmpInt32PtrTy),
2858         std::make_pair(".bound_tid.", KmpInt32PtrTy),
2859         std::make_pair(StringRef(), QualType()) // __context with shared vars
2860     };
2861     // Start a captured region for 'teams' or 'parallel'.  Both regions have
2862     // the same implicit parameters.
2863     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2864                              ParamsTeamsOrParallel);
2865     break;
2866   }
2867   case OMPD_target:
2868   case OMPD_target_simd: {
2869     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2870     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2871     QualType KmpInt32PtrTy =
2872         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2873     QualType Args[] = {VoidPtrTy};
2874     FunctionProtoType::ExtProtoInfo EPI;
2875     EPI.Variadic = true;
2876     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2877     Sema::CapturedParamNameType Params[] = {
2878         std::make_pair(".global_tid.", KmpInt32Ty),
2879         std::make_pair(".part_id.", KmpInt32PtrTy),
2880         std::make_pair(".privates.", VoidPtrTy),
2881         std::make_pair(
2882             ".copy_fn.",
2883             Context.getPointerType(CopyFnType).withConst().withRestrict()),
2884         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2885         std::make_pair(StringRef(), QualType()) // __context with shared vars
2886     };
2887     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2888                              Params);
2889     // Mark this captured region as inlined, because we don't use outlined
2890     // function directly.
2891     getCurCapturedRegion()->TheCapturedDecl->addAttr(
2892         AlwaysInlineAttr::CreateImplicit(
2893             Context, AlwaysInlineAttr::Keyword_forceinline));
2894     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2895                              std::make_pair(StringRef(), QualType()));
2896     break;
2897   }
2898   case OMPD_simd:
2899   case OMPD_for:
2900   case OMPD_for_simd:
2901   case OMPD_sections:
2902   case OMPD_section:
2903   case OMPD_single:
2904   case OMPD_master:
2905   case OMPD_critical:
2906   case OMPD_taskgroup:
2907   case OMPD_distribute:
2908   case OMPD_distribute_simd:
2909   case OMPD_ordered:
2910   case OMPD_atomic:
2911   case OMPD_target_data: {
2912     Sema::CapturedParamNameType Params[] = {
2913         std::make_pair(StringRef(), QualType()) // __context with shared vars
2914     };
2915     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2916                              Params);
2917     break;
2918   }
2919   case OMPD_task: {
2920     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2921     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2922     QualType KmpInt32PtrTy =
2923         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2924     QualType Args[] = {VoidPtrTy};
2925     FunctionProtoType::ExtProtoInfo EPI;
2926     EPI.Variadic = true;
2927     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2928     Sema::CapturedParamNameType Params[] = {
2929         std::make_pair(".global_tid.", KmpInt32Ty),
2930         std::make_pair(".part_id.", KmpInt32PtrTy),
2931         std::make_pair(".privates.", VoidPtrTy),
2932         std::make_pair(
2933             ".copy_fn.",
2934             Context.getPointerType(CopyFnType).withConst().withRestrict()),
2935         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2936         std::make_pair(StringRef(), QualType()) // __context with shared vars
2937     };
2938     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2939                              Params);
2940     // Mark this captured region as inlined, because we don't use outlined
2941     // function directly.
2942     getCurCapturedRegion()->TheCapturedDecl->addAttr(
2943         AlwaysInlineAttr::CreateImplicit(
2944             Context, AlwaysInlineAttr::Keyword_forceinline));
2945     break;
2946   }
2947   case OMPD_taskloop:
2948   case OMPD_taskloop_simd: {
2949     QualType KmpInt32Ty =
2950         Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1)
2951             .withConst();
2952     QualType KmpUInt64Ty =
2953         Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0)
2954             .withConst();
2955     QualType KmpInt64Ty =
2956         Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1)
2957             .withConst();
2958     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2959     QualType KmpInt32PtrTy =
2960         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2961     QualType Args[] = {VoidPtrTy};
2962     FunctionProtoType::ExtProtoInfo EPI;
2963     EPI.Variadic = true;
2964     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2965     Sema::CapturedParamNameType Params[] = {
2966         std::make_pair(".global_tid.", KmpInt32Ty),
2967         std::make_pair(".part_id.", KmpInt32PtrTy),
2968         std::make_pair(".privates.", VoidPtrTy),
2969         std::make_pair(
2970             ".copy_fn.",
2971             Context.getPointerType(CopyFnType).withConst().withRestrict()),
2972         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2973         std::make_pair(".lb.", KmpUInt64Ty),
2974         std::make_pair(".ub.", KmpUInt64Ty),
2975         std::make_pair(".st.", KmpInt64Ty),
2976         std::make_pair(".liter.", KmpInt32Ty),
2977         std::make_pair(".reductions.", VoidPtrTy),
2978         std::make_pair(StringRef(), QualType()) // __context with shared vars
2979     };
2980     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2981                              Params);
2982     // Mark this captured region as inlined, because we don't use outlined
2983     // function directly.
2984     getCurCapturedRegion()->TheCapturedDecl->addAttr(
2985         AlwaysInlineAttr::CreateImplicit(
2986             Context, AlwaysInlineAttr::Keyword_forceinline));
2987     break;
2988   }
2989   case OMPD_distribute_parallel_for_simd:
2990   case OMPD_distribute_parallel_for: {
2991     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2992     QualType KmpInt32PtrTy =
2993         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2994     Sema::CapturedParamNameType Params[] = {
2995         std::make_pair(".global_tid.", KmpInt32PtrTy),
2996         std::make_pair(".bound_tid.", KmpInt32PtrTy),
2997         std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
2998         std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
2999         std::make_pair(StringRef(), QualType()) // __context with shared vars
3000     };
3001     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3002                              Params);
3003     break;
3004   }
3005   case OMPD_target_teams_distribute_parallel_for:
3006   case OMPD_target_teams_distribute_parallel_for_simd: {
3007     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3008     QualType KmpInt32PtrTy =
3009         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3010     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3011 
3012     QualType Args[] = {VoidPtrTy};
3013     FunctionProtoType::ExtProtoInfo EPI;
3014     EPI.Variadic = true;
3015     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3016     Sema::CapturedParamNameType Params[] = {
3017         std::make_pair(".global_tid.", KmpInt32Ty),
3018         std::make_pair(".part_id.", KmpInt32PtrTy),
3019         std::make_pair(".privates.", VoidPtrTy),
3020         std::make_pair(
3021             ".copy_fn.",
3022             Context.getPointerType(CopyFnType).withConst().withRestrict()),
3023         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3024         std::make_pair(StringRef(), QualType()) // __context with shared vars
3025     };
3026     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3027                              Params);
3028     // Mark this captured region as inlined, because we don't use outlined
3029     // function directly.
3030     getCurCapturedRegion()->TheCapturedDecl->addAttr(
3031         AlwaysInlineAttr::CreateImplicit(
3032             Context, AlwaysInlineAttr::Keyword_forceinline));
3033     Sema::CapturedParamNameType ParamsTarget[] = {
3034         std::make_pair(StringRef(), QualType()) // __context with shared vars
3035     };
3036     // Start a captured region for 'target' with no implicit parameters.
3037     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3038                              ParamsTarget);
3039 
3040     Sema::CapturedParamNameType ParamsTeams[] = {
3041         std::make_pair(".global_tid.", KmpInt32PtrTy),
3042         std::make_pair(".bound_tid.", KmpInt32PtrTy),
3043         std::make_pair(StringRef(), QualType()) // __context with shared vars
3044     };
3045     // Start a captured region for 'target' with no implicit parameters.
3046     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3047                              ParamsTeams);
3048 
3049     Sema::CapturedParamNameType ParamsParallel[] = {
3050         std::make_pair(".global_tid.", KmpInt32PtrTy),
3051         std::make_pair(".bound_tid.", KmpInt32PtrTy),
3052         std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
3053         std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
3054         std::make_pair(StringRef(), QualType()) // __context with shared vars
3055     };
3056     // Start a captured region for 'teams' or 'parallel'.  Both regions have
3057     // the same implicit parameters.
3058     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3059                              ParamsParallel);
3060     break;
3061   }
3062 
3063   case OMPD_teams_distribute_parallel_for:
3064   case OMPD_teams_distribute_parallel_for_simd: {
3065     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3066     QualType KmpInt32PtrTy =
3067         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3068 
3069     Sema::CapturedParamNameType ParamsTeams[] = {
3070         std::make_pair(".global_tid.", KmpInt32PtrTy),
3071         std::make_pair(".bound_tid.", KmpInt32PtrTy),
3072         std::make_pair(StringRef(), QualType()) // __context with shared vars
3073     };
3074     // Start a captured region for 'target' with no implicit parameters.
3075     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3076                              ParamsTeams);
3077 
3078     Sema::CapturedParamNameType ParamsParallel[] = {
3079         std::make_pair(".global_tid.", KmpInt32PtrTy),
3080         std::make_pair(".bound_tid.", KmpInt32PtrTy),
3081         std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
3082         std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
3083         std::make_pair(StringRef(), QualType()) // __context with shared vars
3084     };
3085     // Start a captured region for 'teams' or 'parallel'.  Both regions have
3086     // the same implicit parameters.
3087     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3088                              ParamsParallel);
3089     break;
3090   }
3091   case OMPD_target_update:
3092   case OMPD_target_enter_data:
3093   case OMPD_target_exit_data: {
3094     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3095     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3096     QualType KmpInt32PtrTy =
3097         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3098     QualType Args[] = {VoidPtrTy};
3099     FunctionProtoType::ExtProtoInfo EPI;
3100     EPI.Variadic = true;
3101     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3102     Sema::CapturedParamNameType Params[] = {
3103         std::make_pair(".global_tid.", KmpInt32Ty),
3104         std::make_pair(".part_id.", KmpInt32PtrTy),
3105         std::make_pair(".privates.", VoidPtrTy),
3106         std::make_pair(
3107             ".copy_fn.",
3108             Context.getPointerType(CopyFnType).withConst().withRestrict()),
3109         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3110         std::make_pair(StringRef(), QualType()) // __context with shared vars
3111     };
3112     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3113                              Params);
3114     // Mark this captured region as inlined, because we don't use outlined
3115     // function directly.
3116     getCurCapturedRegion()->TheCapturedDecl->addAttr(
3117         AlwaysInlineAttr::CreateImplicit(
3118             Context, AlwaysInlineAttr::Keyword_forceinline));
3119     break;
3120   }
3121   case OMPD_threadprivate:
3122   case OMPD_allocate:
3123   case OMPD_taskyield:
3124   case OMPD_barrier:
3125   case OMPD_taskwait:
3126   case OMPD_cancellation_point:
3127   case OMPD_cancel:
3128   case OMPD_flush:
3129   case OMPD_declare_reduction:
3130   case OMPD_declare_mapper:
3131   case OMPD_declare_simd:
3132   case OMPD_declare_target:
3133   case OMPD_end_declare_target:
3134   case OMPD_requires:
3135     llvm_unreachable("OpenMP Directive is not allowed");
3136   case OMPD_unknown:
3137     llvm_unreachable("Unknown OpenMP directive");
3138   }
3139 }
3140 
3141 int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
3142   SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
3143   getOpenMPCaptureRegions(CaptureRegions, DKind);
3144   return CaptureRegions.size();
3145 }
3146 
3147 static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
3148                                              Expr *CaptureExpr, bool WithInit,
3149                                              bool AsExpression) {
3150   assert(CaptureExpr);
3151   ASTContext &C = S.getASTContext();
3152   Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
3153   QualType Ty = Init->getType();
3154   if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
3155     if (S.getLangOpts().CPlusPlus) {
3156       Ty = C.getLValueReferenceType(Ty);
3157     } else {
3158       Ty = C.getPointerType(Ty);
3159       ExprResult Res =
3160           S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
3161       if (!Res.isUsable())
3162         return nullptr;
3163       Init = Res.get();
3164     }
3165     WithInit = true;
3166   }
3167   auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
3168                                           CaptureExpr->getBeginLoc());
3169   if (!WithInit)
3170     CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C));
3171   S.CurContext->addHiddenDecl(CED);
3172   S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
3173   return CED;
3174 }
3175 
3176 static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
3177                                  bool WithInit) {
3178   OMPCapturedExprDecl *CD;
3179   if (VarDecl *VD = S.isOpenMPCapturedDecl(D))
3180     CD = cast<OMPCapturedExprDecl>(VD);
3181   else
3182     CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
3183                           /*AsExpression=*/false);
3184   return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
3185                           CaptureExpr->getExprLoc());
3186 }
3187 
3188 static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
3189   CaptureExpr = S.DefaultLvalueConversion(CaptureExpr).get();
3190   if (!Ref) {
3191     OMPCapturedExprDecl *CD = buildCaptureDecl(
3192         S, &S.getASTContext().Idents.get(".capture_expr."), CaptureExpr,
3193         /*WithInit=*/true, /*AsExpression=*/true);
3194     Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
3195                            CaptureExpr->getExprLoc());
3196   }
3197   ExprResult Res = Ref;
3198   if (!S.getLangOpts().CPlusPlus &&
3199       CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
3200       Ref->getType()->isPointerType()) {
3201     Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
3202     if (!Res.isUsable())
3203       return ExprError();
3204   }
3205   return S.DefaultLvalueConversion(Res.get());
3206 }
3207 
3208 namespace {
3209 // OpenMP directives parsed in this section are represented as a
3210 // CapturedStatement with an associated statement.  If a syntax error
3211 // is detected during the parsing of the associated statement, the
3212 // compiler must abort processing and close the CapturedStatement.
3213 //
3214 // Combined directives such as 'target parallel' have more than one
3215 // nested CapturedStatements.  This RAII ensures that we unwind out
3216 // of all the nested CapturedStatements when an error is found.
3217 class CaptureRegionUnwinderRAII {
3218 private:
3219   Sema &S;
3220   bool &ErrorFound;
3221   OpenMPDirectiveKind DKind = OMPD_unknown;
3222 
3223 public:
3224   CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
3225                             OpenMPDirectiveKind DKind)
3226       : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
3227   ~CaptureRegionUnwinderRAII() {
3228     if (ErrorFound) {
3229       int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
3230       while (--ThisCaptureLevel >= 0)
3231         S.ActOnCapturedRegionError();
3232     }
3233   }
3234 };
3235 } // namespace
3236 
3237 StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
3238                                       ArrayRef<OMPClause *> Clauses) {
3239   bool ErrorFound = false;
3240   CaptureRegionUnwinderRAII CaptureRegionUnwinder(
3241       *this, ErrorFound, DSAStack->getCurrentDirective());
3242   if (!S.isUsable()) {
3243     ErrorFound = true;
3244     return StmtError();
3245   }
3246 
3247   SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
3248   getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
3249   OMPOrderedClause *OC = nullptr;
3250   OMPScheduleClause *SC = nullptr;
3251   SmallVector<const OMPLinearClause *, 4> LCs;
3252   SmallVector<const OMPClauseWithPreInit *, 4> PICs;
3253   // This is required for proper codegen.
3254   for (OMPClause *Clause : Clauses) {
3255     if (isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) &&
3256         Clause->getClauseKind() == OMPC_in_reduction) {
3257       // Capture taskgroup task_reduction descriptors inside the tasking regions
3258       // with the corresponding in_reduction items.
3259       auto *IRC = cast<OMPInReductionClause>(Clause);
3260       for (Expr *E : IRC->taskgroup_descriptors())
3261         if (E)
3262           MarkDeclarationsReferencedInExpr(E);
3263     }
3264     if (isOpenMPPrivate(Clause->getClauseKind()) ||
3265         Clause->getClauseKind() == OMPC_copyprivate ||
3266         (getLangOpts().OpenMPUseTLS &&
3267          getASTContext().getTargetInfo().isTLSSupported() &&
3268          Clause->getClauseKind() == OMPC_copyin)) {
3269       DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
3270       // Mark all variables in private list clauses as used in inner region.
3271       for (Stmt *VarRef : Clause->children()) {
3272         if (auto *E = cast_or_null<Expr>(VarRef)) {
3273           MarkDeclarationsReferencedInExpr(E);
3274         }
3275       }
3276       DSAStack->setForceVarCapturing(/*V=*/false);
3277     } else if (CaptureRegions.size() > 1 ||
3278                CaptureRegions.back() != OMPD_unknown) {
3279       if (auto *C = OMPClauseWithPreInit::get(Clause))
3280         PICs.push_back(C);
3281       if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
3282         if (Expr *E = C->getPostUpdateExpr())
3283           MarkDeclarationsReferencedInExpr(E);
3284       }
3285     }
3286     if (Clause->getClauseKind() == OMPC_schedule)
3287       SC = cast<OMPScheduleClause>(Clause);
3288     else if (Clause->getClauseKind() == OMPC_ordered)
3289       OC = cast<OMPOrderedClause>(Clause);
3290     else if (Clause->getClauseKind() == OMPC_linear)
3291       LCs.push_back(cast<OMPLinearClause>(Clause));
3292   }
3293   // OpenMP, 2.7.1 Loop Construct, Restrictions
3294   // The nonmonotonic modifier cannot be specified if an ordered clause is
3295   // specified.
3296   if (SC &&
3297       (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
3298        SC->getSecondScheduleModifier() ==
3299            OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
3300       OC) {
3301     Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
3302              ? SC->getFirstScheduleModifierLoc()
3303              : SC->getSecondScheduleModifierLoc(),
3304          diag::err_omp_schedule_nonmonotonic_ordered)
3305         << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
3306     ErrorFound = true;
3307   }
3308   if (!LCs.empty() && OC && OC->getNumForLoops()) {
3309     for (const OMPLinearClause *C : LCs) {
3310       Diag(C->getBeginLoc(), diag::err_omp_linear_ordered)
3311           << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
3312     }
3313     ErrorFound = true;
3314   }
3315   if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
3316       isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
3317       OC->getNumForLoops()) {
3318     Diag(OC->getBeginLoc(), diag::err_omp_ordered_simd)
3319         << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
3320     ErrorFound = true;
3321   }
3322   if (ErrorFound) {
3323     return StmtError();
3324   }
3325   StmtResult SR = S;
3326   for (OpenMPDirectiveKind ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
3327     // Mark all variables in private list clauses as used in inner region.
3328     // Required for proper codegen of combined directives.
3329     // TODO: add processing for other clauses.
3330     if (ThisCaptureRegion != OMPD_unknown) {
3331       for (const clang::OMPClauseWithPreInit *C : PICs) {
3332         OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
3333         // Find the particular capture region for the clause if the
3334         // directive is a combined one with multiple capture regions.
3335         // If the directive is not a combined one, the capture region
3336         // associated with the clause is OMPD_unknown and is generated
3337         // only once.
3338         if (CaptureRegion == ThisCaptureRegion ||
3339             CaptureRegion == OMPD_unknown) {
3340           if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
3341             for (Decl *D : DS->decls())
3342               MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
3343           }
3344         }
3345       }
3346     }
3347     SR = ActOnCapturedRegionEnd(SR.get());
3348   }
3349   return SR;
3350 }
3351 
3352 static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
3353                               OpenMPDirectiveKind CancelRegion,
3354                               SourceLocation StartLoc) {
3355   // CancelRegion is only needed for cancel and cancellation_point.
3356   if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
3357     return false;
3358 
3359   if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
3360       CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
3361     return false;
3362 
3363   SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
3364       << getOpenMPDirectiveName(CancelRegion);
3365   return true;
3366 }
3367 
3368 static bool checkNestingOfRegions(Sema &SemaRef, const DSAStackTy *Stack,
3369                                   OpenMPDirectiveKind CurrentRegion,
3370                                   const DeclarationNameInfo &CurrentName,
3371                                   OpenMPDirectiveKind CancelRegion,
3372                                   SourceLocation StartLoc) {
3373   if (Stack->getCurScope()) {
3374     OpenMPDirectiveKind ParentRegion = Stack->getParentDirective();
3375     OpenMPDirectiveKind OffendingRegion = ParentRegion;
3376     bool NestingProhibited = false;
3377     bool CloseNesting = true;
3378     bool OrphanSeen = false;
3379     enum {
3380       NoRecommend,
3381       ShouldBeInParallelRegion,
3382       ShouldBeInOrderedRegion,
3383       ShouldBeInTargetRegion,
3384       ShouldBeInTeamsRegion
3385     } Recommend = NoRecommend;
3386     if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
3387       // OpenMP [2.16, Nesting of Regions]
3388       // OpenMP constructs may not be nested inside a simd region.
3389       // OpenMP [2.8.1,simd Construct, Restrictions]
3390       // An ordered construct with the simd clause is the only OpenMP
3391       // construct that can appear in the simd region.
3392       // Allowing a SIMD construct nested in another SIMD construct is an
3393       // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
3394       // message.
3395       SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
3396                                  ? diag::err_omp_prohibited_region_simd
3397                                  : diag::warn_omp_nesting_simd);
3398       return CurrentRegion != OMPD_simd;
3399     }
3400     if (ParentRegion == OMPD_atomic) {
3401       // OpenMP [2.16, Nesting of Regions]
3402       // OpenMP constructs may not be nested inside an atomic region.
3403       SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
3404       return true;
3405     }
3406     if (CurrentRegion == OMPD_section) {
3407       // OpenMP [2.7.2, sections Construct, Restrictions]
3408       // Orphaned section directives are prohibited. That is, the section
3409       // directives must appear within the sections construct and must not be
3410       // encountered elsewhere in the sections region.
3411       if (ParentRegion != OMPD_sections &&
3412           ParentRegion != OMPD_parallel_sections) {
3413         SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
3414             << (ParentRegion != OMPD_unknown)
3415             << getOpenMPDirectiveName(ParentRegion);
3416         return true;
3417       }
3418       return false;
3419     }
3420     // Allow some constructs (except teams and cancellation constructs) to be
3421     // orphaned (they could be used in functions, called from OpenMP regions
3422     // with the required preconditions).
3423     if (ParentRegion == OMPD_unknown &&
3424         !isOpenMPNestingTeamsDirective(CurrentRegion) &&
3425         CurrentRegion != OMPD_cancellation_point &&
3426         CurrentRegion != OMPD_cancel)
3427       return false;
3428     if (CurrentRegion == OMPD_cancellation_point ||
3429         CurrentRegion == OMPD_cancel) {
3430       // OpenMP [2.16, Nesting of Regions]
3431       // A cancellation point construct for which construct-type-clause is
3432       // taskgroup must be nested inside a task construct. A cancellation
3433       // point construct for which construct-type-clause is not taskgroup must
3434       // be closely nested inside an OpenMP construct that matches the type
3435       // specified in construct-type-clause.
3436       // A cancel construct for which construct-type-clause is taskgroup must be
3437       // nested inside a task construct. A cancel construct for which
3438       // construct-type-clause is not taskgroup must be closely nested inside an
3439       // OpenMP construct that matches the type specified in
3440       // construct-type-clause.
3441       NestingProhibited =
3442           !((CancelRegion == OMPD_parallel &&
3443              (ParentRegion == OMPD_parallel ||
3444               ParentRegion == OMPD_target_parallel)) ||
3445             (CancelRegion == OMPD_for &&
3446              (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
3447               ParentRegion == OMPD_target_parallel_for ||
3448               ParentRegion == OMPD_distribute_parallel_for ||
3449               ParentRegion == OMPD_teams_distribute_parallel_for ||
3450               ParentRegion == OMPD_target_teams_distribute_parallel_for)) ||
3451             (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
3452             (CancelRegion == OMPD_sections &&
3453              (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
3454               ParentRegion == OMPD_parallel_sections)));
3455       OrphanSeen = ParentRegion == OMPD_unknown;
3456     } else if (CurrentRegion == OMPD_master) {
3457       // OpenMP [2.16, Nesting of Regions]
3458       // A master region may not be closely nested inside a worksharing,
3459       // atomic, or explicit task region.
3460       NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
3461                           isOpenMPTaskingDirective(ParentRegion);
3462     } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
3463       // OpenMP [2.16, Nesting of Regions]
3464       // A critical region may not be nested (closely or otherwise) inside a
3465       // critical region with the same name. Note that this restriction is not
3466       // sufficient to prevent deadlock.
3467       SourceLocation PreviousCriticalLoc;
3468       bool DeadLock = Stack->hasDirective(
3469           [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
3470                                               const DeclarationNameInfo &DNI,
3471                                               SourceLocation Loc) {
3472             if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
3473               PreviousCriticalLoc = Loc;
3474               return true;
3475             }
3476             return false;
3477           },
3478           false /* skip top directive */);
3479       if (DeadLock) {
3480         SemaRef.Diag(StartLoc,
3481                      diag::err_omp_prohibited_region_critical_same_name)
3482             << CurrentName.getName();
3483         if (PreviousCriticalLoc.isValid())
3484           SemaRef.Diag(PreviousCriticalLoc,
3485                        diag::note_omp_previous_critical_region);
3486         return true;
3487       }
3488     } else if (CurrentRegion == OMPD_barrier) {
3489       // OpenMP [2.16, Nesting of Regions]
3490       // A barrier region may not be closely nested inside a worksharing,
3491       // explicit task, critical, ordered, atomic, or master region.
3492       NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
3493                           isOpenMPTaskingDirective(ParentRegion) ||
3494                           ParentRegion == OMPD_master ||
3495                           ParentRegion == OMPD_critical ||
3496                           ParentRegion == OMPD_ordered;
3497     } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
3498                !isOpenMPParallelDirective(CurrentRegion) &&
3499                !isOpenMPTeamsDirective(CurrentRegion)) {
3500       // OpenMP [2.16, Nesting of Regions]
3501       // A worksharing region may not be closely nested inside a worksharing,
3502       // explicit task, critical, ordered, atomic, or master region.
3503       NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
3504                           isOpenMPTaskingDirective(ParentRegion) ||
3505                           ParentRegion == OMPD_master ||
3506                           ParentRegion == OMPD_critical ||
3507                           ParentRegion == OMPD_ordered;
3508       Recommend = ShouldBeInParallelRegion;
3509     } else if (CurrentRegion == OMPD_ordered) {
3510       // OpenMP [2.16, Nesting of Regions]
3511       // An ordered region may not be closely nested inside a critical,
3512       // atomic, or explicit task region.
3513       // An ordered region must be closely nested inside a loop region (or
3514       // parallel loop region) with an ordered clause.
3515       // OpenMP [2.8.1,simd Construct, Restrictions]
3516       // An ordered construct with the simd clause is the only OpenMP construct
3517       // that can appear in the simd region.
3518       NestingProhibited = ParentRegion == OMPD_critical ||
3519                           isOpenMPTaskingDirective(ParentRegion) ||
3520                           !(isOpenMPSimdDirective(ParentRegion) ||
3521                             Stack->isParentOrderedRegion());
3522       Recommend = ShouldBeInOrderedRegion;
3523     } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
3524       // OpenMP [2.16, Nesting of Regions]
3525       // If specified, a teams construct must be contained within a target
3526       // construct.
3527       NestingProhibited = ParentRegion != OMPD_target;
3528       OrphanSeen = ParentRegion == OMPD_unknown;
3529       Recommend = ShouldBeInTargetRegion;
3530     }
3531     if (!NestingProhibited &&
3532         !isOpenMPTargetExecutionDirective(CurrentRegion) &&
3533         !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
3534         (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
3535       // OpenMP [2.16, Nesting of Regions]
3536       // distribute, parallel, parallel sections, parallel workshare, and the
3537       // parallel loop and parallel loop SIMD constructs are the only OpenMP
3538       // constructs that can be closely nested in the teams region.
3539       NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
3540                           !isOpenMPDistributeDirective(CurrentRegion);
3541       Recommend = ShouldBeInParallelRegion;
3542     }
3543     if (!NestingProhibited &&
3544         isOpenMPNestingDistributeDirective(CurrentRegion)) {
3545       // OpenMP 4.5 [2.17 Nesting of Regions]
3546       // The region associated with the distribute construct must be strictly
3547       // nested inside a teams region
3548       NestingProhibited =
3549           (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
3550       Recommend = ShouldBeInTeamsRegion;
3551     }
3552     if (!NestingProhibited &&
3553         (isOpenMPTargetExecutionDirective(CurrentRegion) ||
3554          isOpenMPTargetDataManagementDirective(CurrentRegion))) {
3555       // OpenMP 4.5 [2.17 Nesting of Regions]
3556       // If a target, target update, target data, target enter data, or
3557       // target exit data construct is encountered during execution of a
3558       // target region, the behavior is unspecified.
3559       NestingProhibited = Stack->hasDirective(
3560           [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
3561                              SourceLocation) {
3562             if (isOpenMPTargetExecutionDirective(K)) {
3563               OffendingRegion = K;
3564               return true;
3565             }
3566             return false;
3567           },
3568           false /* don't skip top directive */);
3569       CloseNesting = false;
3570     }
3571     if (NestingProhibited) {
3572       if (OrphanSeen) {
3573         SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
3574             << getOpenMPDirectiveName(CurrentRegion) << Recommend;
3575       } else {
3576         SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
3577             << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
3578             << Recommend << getOpenMPDirectiveName(CurrentRegion);
3579       }
3580       return true;
3581     }
3582   }
3583   return false;
3584 }
3585 
3586 static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
3587                            ArrayRef<OMPClause *> Clauses,
3588                            ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
3589   bool ErrorFound = false;
3590   unsigned NamedModifiersNumber = 0;
3591   SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
3592       OMPD_unknown + 1);
3593   SmallVector<SourceLocation, 4> NameModifierLoc;
3594   for (const OMPClause *C : Clauses) {
3595     if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
3596       // At most one if clause without a directive-name-modifier can appear on
3597       // the directive.
3598       OpenMPDirectiveKind CurNM = IC->getNameModifier();
3599       if (FoundNameModifiers[CurNM]) {
3600         S.Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
3601             << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
3602             << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
3603         ErrorFound = true;
3604       } else if (CurNM != OMPD_unknown) {
3605         NameModifierLoc.push_back(IC->getNameModifierLoc());
3606         ++NamedModifiersNumber;
3607       }
3608       FoundNameModifiers[CurNM] = IC;
3609       if (CurNM == OMPD_unknown)
3610         continue;
3611       // Check if the specified name modifier is allowed for the current
3612       // directive.
3613       // At most one if clause with the particular directive-name-modifier can
3614       // appear on the directive.
3615       bool MatchFound = false;
3616       for (auto NM : AllowedNameModifiers) {
3617         if (CurNM == NM) {
3618           MatchFound = true;
3619           break;
3620         }
3621       }
3622       if (!MatchFound) {
3623         S.Diag(IC->getNameModifierLoc(),
3624                diag::err_omp_wrong_if_directive_name_modifier)
3625             << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
3626         ErrorFound = true;
3627       }
3628     }
3629   }
3630   // If any if clause on the directive includes a directive-name-modifier then
3631   // all if clauses on the directive must include a directive-name-modifier.
3632   if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
3633     if (NamedModifiersNumber == AllowedNameModifiers.size()) {
3634       S.Diag(FoundNameModifiers[OMPD_unknown]->getBeginLoc(),
3635              diag::err_omp_no_more_if_clause);
3636     } else {
3637       std::string Values;
3638       std::string Sep(", ");
3639       unsigned AllowedCnt = 0;
3640       unsigned TotalAllowedNum =
3641           AllowedNameModifiers.size() - NamedModifiersNumber;
3642       for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
3643            ++Cnt) {
3644         OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
3645         if (!FoundNameModifiers[NM]) {
3646           Values += "'";
3647           Values += getOpenMPDirectiveName(NM);
3648           Values += "'";
3649           if (AllowedCnt + 2 == TotalAllowedNum)
3650             Values += " or ";
3651           else if (AllowedCnt + 1 != TotalAllowedNum)
3652             Values += Sep;
3653           ++AllowedCnt;
3654         }
3655       }
3656       S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getBeginLoc(),
3657              diag::err_omp_unnamed_if_clause)
3658           << (TotalAllowedNum > 1) << Values;
3659     }
3660     for (SourceLocation Loc : NameModifierLoc) {
3661       S.Diag(Loc, diag::note_omp_previous_named_if_clause);
3662     }
3663     ErrorFound = true;
3664   }
3665   return ErrorFound;
3666 }
3667 
3668 static std::pair<ValueDecl *, bool>
3669 getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
3670                SourceRange &ERange, bool AllowArraySection = false) {
3671   if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
3672       RefExpr->containsUnexpandedParameterPack())
3673     return std::make_pair(nullptr, true);
3674 
3675   // OpenMP [3.1, C/C++]
3676   //  A list item is a variable name.
3677   // OpenMP  [2.9.3.3, Restrictions, p.1]
3678   //  A variable that is part of another variable (as an array or
3679   //  structure element) cannot appear in a private clause.
3680   RefExpr = RefExpr->IgnoreParens();
3681   enum {
3682     NoArrayExpr = -1,
3683     ArraySubscript = 0,
3684     OMPArraySection = 1
3685   } IsArrayExpr = NoArrayExpr;
3686   if (AllowArraySection) {
3687     if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
3688       Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
3689       while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
3690         Base = TempASE->getBase()->IgnoreParenImpCasts();
3691       RefExpr = Base;
3692       IsArrayExpr = ArraySubscript;
3693     } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
3694       Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
3695       while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
3696         Base = TempOASE->getBase()->IgnoreParenImpCasts();
3697       while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
3698         Base = TempASE->getBase()->IgnoreParenImpCasts();
3699       RefExpr = Base;
3700       IsArrayExpr = OMPArraySection;
3701     }
3702   }
3703   ELoc = RefExpr->getExprLoc();
3704   ERange = RefExpr->getSourceRange();
3705   RefExpr = RefExpr->IgnoreParenImpCasts();
3706   auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
3707   auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
3708   if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
3709       (S.getCurrentThisType().isNull() || !ME ||
3710        !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
3711        !isa<FieldDecl>(ME->getMemberDecl()))) {
3712     if (IsArrayExpr != NoArrayExpr) {
3713       S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
3714                                                          << ERange;
3715     } else {
3716       S.Diag(ELoc,
3717              AllowArraySection
3718                  ? diag::err_omp_expected_var_name_member_expr_or_array_item
3719                  : diag::err_omp_expected_var_name_member_expr)
3720           << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
3721     }
3722     return std::make_pair(nullptr, false);
3723   }
3724   return std::make_pair(
3725       getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false);
3726 }
3727 
3728 static void checkAllocateClauses(Sema &S, DSAStackTy *Stack,
3729                                  ArrayRef<OMPClause *> Clauses) {
3730   assert(!S.CurContext->isDependentContext() &&
3731          "Expected non-dependent context.");
3732   auto AllocateRange =
3733       llvm::make_filter_range(Clauses, OMPAllocateClause::classof);
3734   llvm::DenseMap<CanonicalDeclPtr<Decl>, CanonicalDeclPtr<VarDecl>>
3735       DeclToCopy;
3736   auto PrivateRange = llvm::make_filter_range(Clauses, [](const OMPClause *C) {
3737     return isOpenMPPrivate(C->getClauseKind());
3738   });
3739   for (OMPClause *Cl : PrivateRange) {
3740     MutableArrayRef<Expr *>::iterator I, It, Et;
3741     if (Cl->getClauseKind() == OMPC_private) {
3742       auto *PC = cast<OMPPrivateClause>(Cl);
3743       I = PC->private_copies().begin();
3744       It = PC->varlist_begin();
3745       Et = PC->varlist_end();
3746     } else if (Cl->getClauseKind() == OMPC_firstprivate) {
3747       auto *PC = cast<OMPFirstprivateClause>(Cl);
3748       I = PC->private_copies().begin();
3749       It = PC->varlist_begin();
3750       Et = PC->varlist_end();
3751     } else if (Cl->getClauseKind() == OMPC_lastprivate) {
3752       auto *PC = cast<OMPLastprivateClause>(Cl);
3753       I = PC->private_copies().begin();
3754       It = PC->varlist_begin();
3755       Et = PC->varlist_end();
3756     } else if (Cl->getClauseKind() == OMPC_linear) {
3757       auto *PC = cast<OMPLinearClause>(Cl);
3758       I = PC->privates().begin();
3759       It = PC->varlist_begin();
3760       Et = PC->varlist_end();
3761     } else if (Cl->getClauseKind() == OMPC_reduction) {
3762       auto *PC = cast<OMPReductionClause>(Cl);
3763       I = PC->privates().begin();
3764       It = PC->varlist_begin();
3765       Et = PC->varlist_end();
3766     } else if (Cl->getClauseKind() == OMPC_task_reduction) {
3767       auto *PC = cast<OMPTaskReductionClause>(Cl);
3768       I = PC->privates().begin();
3769       It = PC->varlist_begin();
3770       Et = PC->varlist_end();
3771     } else if (Cl->getClauseKind() == OMPC_in_reduction) {
3772       auto *PC = cast<OMPInReductionClause>(Cl);
3773       I = PC->privates().begin();
3774       It = PC->varlist_begin();
3775       Et = PC->varlist_end();
3776     } else {
3777       llvm_unreachable("Expected private clause.");
3778     }
3779     for (Expr *E : llvm::make_range(It, Et)) {
3780       if (!*I) {
3781         ++I;
3782         continue;
3783       }
3784       SourceLocation ELoc;
3785       SourceRange ERange;
3786       Expr *SimpleRefExpr = E;
3787       auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
3788                                 /*AllowArraySection=*/true);
3789       DeclToCopy.try_emplace(Res.first,
3790                              cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()));
3791       ++I;
3792     }
3793   }
3794   for (OMPClause *C : AllocateRange) {
3795     auto *AC = cast<OMPAllocateClause>(C);
3796     OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind =
3797         getAllocatorKind(S, Stack, AC->getAllocator());
3798     // OpenMP, 2.11.4 allocate Clause, Restrictions.
3799     // For task, taskloop or target directives, allocation requests to memory
3800     // allocators with the trait access set to thread result in unspecified
3801     // behavior.
3802     if (AllocatorKind == OMPAllocateDeclAttr::OMPThreadMemAlloc &&
3803         (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
3804          isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()))) {
3805       S.Diag(AC->getAllocator()->getExprLoc(),
3806              diag::warn_omp_allocate_thread_on_task_target_directive)
3807           << getOpenMPDirectiveName(Stack->getCurrentDirective());
3808     }
3809     for (Expr *E : AC->varlists()) {
3810       SourceLocation ELoc;
3811       SourceRange ERange;
3812       Expr *SimpleRefExpr = E;
3813       auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange);
3814       ValueDecl *VD = Res.first;
3815       DSAStackTy::DSAVarData Data = Stack->getTopDSA(VD, /*FromParent=*/false);
3816       if (!isOpenMPPrivate(Data.CKind)) {
3817         S.Diag(E->getExprLoc(),
3818                diag::err_omp_expected_private_copy_for_allocate);
3819         continue;
3820       }
3821       VarDecl *PrivateVD = DeclToCopy[VD];
3822       if (checkPreviousOMPAllocateAttribute(S, Stack, E, PrivateVD,
3823                                             AllocatorKind, AC->getAllocator()))
3824         continue;
3825       applyOMPAllocateAttribute(S, PrivateVD, AllocatorKind, AC->getAllocator(),
3826                                 E->getSourceRange());
3827     }
3828   }
3829 }
3830 
3831 StmtResult Sema::ActOnOpenMPExecutableDirective(
3832     OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
3833     OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
3834     Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
3835   StmtResult Res = StmtError();
3836   // First check CancelRegion which is then used in checkNestingOfRegions.
3837   if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
3838       checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
3839                             StartLoc))
3840     return StmtError();
3841 
3842   llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
3843   VarsWithInheritedDSAType VarsWithInheritedDSA;
3844   bool ErrorFound = false;
3845   ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
3846   if (AStmt && !CurContext->isDependentContext()) {
3847     assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
3848 
3849     // Check default data sharing attributes for referenced variables.
3850     DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
3851     int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
3852     Stmt *S = AStmt;
3853     while (--ThisCaptureLevel >= 0)
3854       S = cast<CapturedStmt>(S)->getCapturedStmt();
3855     DSAChecker.Visit(S);
3856     if (DSAChecker.isErrorFound())
3857       return StmtError();
3858     // Generate list of implicitly defined firstprivate variables.
3859     VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
3860 
3861     SmallVector<Expr *, 4> ImplicitFirstprivates(
3862         DSAChecker.getImplicitFirstprivate().begin(),
3863         DSAChecker.getImplicitFirstprivate().end());
3864     SmallVector<Expr *, 4> ImplicitMaps(DSAChecker.getImplicitMap().begin(),
3865                                         DSAChecker.getImplicitMap().end());
3866     // Mark taskgroup task_reduction descriptors as implicitly firstprivate.
3867     for (OMPClause *C : Clauses) {
3868       if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) {
3869         for (Expr *E : IRC->taskgroup_descriptors())
3870           if (E)
3871             ImplicitFirstprivates.emplace_back(E);
3872       }
3873     }
3874     if (!ImplicitFirstprivates.empty()) {
3875       if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
3876               ImplicitFirstprivates, SourceLocation(), SourceLocation(),
3877               SourceLocation())) {
3878         ClausesWithImplicit.push_back(Implicit);
3879         ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
3880                      ImplicitFirstprivates.size();
3881       } else {
3882         ErrorFound = true;
3883       }
3884     }
3885     if (!ImplicitMaps.empty()) {
3886       CXXScopeSpec MapperIdScopeSpec;
3887       DeclarationNameInfo MapperId;
3888       if (OMPClause *Implicit = ActOnOpenMPMapClause(
3889               llvm::None, llvm::None, MapperIdScopeSpec, MapperId,
3890               OMPC_MAP_tofrom, /*IsMapTypeImplicit=*/true, SourceLocation(),
3891               SourceLocation(), ImplicitMaps, OMPVarListLocTy())) {
3892         ClausesWithImplicit.emplace_back(Implicit);
3893         ErrorFound |=
3894             cast<OMPMapClause>(Implicit)->varlist_size() != ImplicitMaps.size();
3895       } else {
3896         ErrorFound = true;
3897       }
3898     }
3899   }
3900 
3901   llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
3902   switch (Kind) {
3903   case OMPD_parallel:
3904     Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
3905                                        EndLoc);
3906     AllowedNameModifiers.push_back(OMPD_parallel);
3907     break;
3908   case OMPD_simd:
3909     Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
3910                                    VarsWithInheritedDSA);
3911     break;
3912   case OMPD_for:
3913     Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
3914                                   VarsWithInheritedDSA);
3915     break;
3916   case OMPD_for_simd:
3917     Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3918                                       EndLoc, VarsWithInheritedDSA);
3919     break;
3920   case OMPD_sections:
3921     Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
3922                                        EndLoc);
3923     break;
3924   case OMPD_section:
3925     assert(ClausesWithImplicit.empty() &&
3926            "No clauses are allowed for 'omp section' directive");
3927     Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
3928     break;
3929   case OMPD_single:
3930     Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
3931                                      EndLoc);
3932     break;
3933   case OMPD_master:
3934     assert(ClausesWithImplicit.empty() &&
3935            "No clauses are allowed for 'omp master' directive");
3936     Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
3937     break;
3938   case OMPD_critical:
3939     Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
3940                                        StartLoc, EndLoc);
3941     break;
3942   case OMPD_parallel_for:
3943     Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
3944                                           EndLoc, VarsWithInheritedDSA);
3945     AllowedNameModifiers.push_back(OMPD_parallel);
3946     break;
3947   case OMPD_parallel_for_simd:
3948     Res = ActOnOpenMPParallelForSimdDirective(
3949         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3950     AllowedNameModifiers.push_back(OMPD_parallel);
3951     break;
3952   case OMPD_parallel_sections:
3953     Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
3954                                                StartLoc, EndLoc);
3955     AllowedNameModifiers.push_back(OMPD_parallel);
3956     break;
3957   case OMPD_task:
3958     Res =
3959         ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
3960     AllowedNameModifiers.push_back(OMPD_task);
3961     break;
3962   case OMPD_taskyield:
3963     assert(ClausesWithImplicit.empty() &&
3964            "No clauses are allowed for 'omp taskyield' directive");
3965     assert(AStmt == nullptr &&
3966            "No associated statement allowed for 'omp taskyield' directive");
3967     Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
3968     break;
3969   case OMPD_barrier:
3970     assert(ClausesWithImplicit.empty() &&
3971            "No clauses are allowed for 'omp barrier' directive");
3972     assert(AStmt == nullptr &&
3973            "No associated statement allowed for 'omp barrier' directive");
3974     Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
3975     break;
3976   case OMPD_taskwait:
3977     assert(ClausesWithImplicit.empty() &&
3978            "No clauses are allowed for 'omp taskwait' directive");
3979     assert(AStmt == nullptr &&
3980            "No associated statement allowed for 'omp taskwait' directive");
3981     Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
3982     break;
3983   case OMPD_taskgroup:
3984     Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc,
3985                                         EndLoc);
3986     break;
3987   case OMPD_flush:
3988     assert(AStmt == nullptr &&
3989            "No associated statement allowed for 'omp flush' directive");
3990     Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
3991     break;
3992   case OMPD_ordered:
3993     Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
3994                                       EndLoc);
3995     break;
3996   case OMPD_atomic:
3997     Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
3998                                      EndLoc);
3999     break;
4000   case OMPD_teams:
4001     Res =
4002         ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
4003     break;
4004   case OMPD_target:
4005     Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
4006                                      EndLoc);
4007     AllowedNameModifiers.push_back(OMPD_target);
4008     break;
4009   case OMPD_target_parallel:
4010     Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
4011                                              StartLoc, EndLoc);
4012     AllowedNameModifiers.push_back(OMPD_target);
4013     AllowedNameModifiers.push_back(OMPD_parallel);
4014     break;
4015   case OMPD_target_parallel_for:
4016     Res = ActOnOpenMPTargetParallelForDirective(
4017         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4018     AllowedNameModifiers.push_back(OMPD_target);
4019     AllowedNameModifiers.push_back(OMPD_parallel);
4020     break;
4021   case OMPD_cancellation_point:
4022     assert(ClausesWithImplicit.empty() &&
4023            "No clauses are allowed for 'omp cancellation point' directive");
4024     assert(AStmt == nullptr && "No associated statement allowed for 'omp "
4025                                "cancellation point' directive");
4026     Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
4027     break;
4028   case OMPD_cancel:
4029     assert(AStmt == nullptr &&
4030            "No associated statement allowed for 'omp cancel' directive");
4031     Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
4032                                      CancelRegion);
4033     AllowedNameModifiers.push_back(OMPD_cancel);
4034     break;
4035   case OMPD_target_data:
4036     Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
4037                                          EndLoc);
4038     AllowedNameModifiers.push_back(OMPD_target_data);
4039     break;
4040   case OMPD_target_enter_data:
4041     Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
4042                                               EndLoc, AStmt);
4043     AllowedNameModifiers.push_back(OMPD_target_enter_data);
4044     break;
4045   case OMPD_target_exit_data:
4046     Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
4047                                              EndLoc, AStmt);
4048     AllowedNameModifiers.push_back(OMPD_target_exit_data);
4049     break;
4050   case OMPD_taskloop:
4051     Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
4052                                        EndLoc, VarsWithInheritedDSA);
4053     AllowedNameModifiers.push_back(OMPD_taskloop);
4054     break;
4055   case OMPD_taskloop_simd:
4056     Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
4057                                            EndLoc, VarsWithInheritedDSA);
4058     AllowedNameModifiers.push_back(OMPD_taskloop);
4059     break;
4060   case OMPD_distribute:
4061     Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
4062                                          EndLoc, VarsWithInheritedDSA);
4063     break;
4064   case OMPD_target_update:
4065     Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc,
4066                                            EndLoc, AStmt);
4067     AllowedNameModifiers.push_back(OMPD_target_update);
4068     break;
4069   case OMPD_distribute_parallel_for:
4070     Res = ActOnOpenMPDistributeParallelForDirective(
4071         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4072     AllowedNameModifiers.push_back(OMPD_parallel);
4073     break;
4074   case OMPD_distribute_parallel_for_simd:
4075     Res = ActOnOpenMPDistributeParallelForSimdDirective(
4076         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4077     AllowedNameModifiers.push_back(OMPD_parallel);
4078     break;
4079   case OMPD_distribute_simd:
4080     Res = ActOnOpenMPDistributeSimdDirective(
4081         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4082     break;
4083   case OMPD_target_parallel_for_simd:
4084     Res = ActOnOpenMPTargetParallelForSimdDirective(
4085         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4086     AllowedNameModifiers.push_back(OMPD_target);
4087     AllowedNameModifiers.push_back(OMPD_parallel);
4088     break;
4089   case OMPD_target_simd:
4090     Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
4091                                          EndLoc, VarsWithInheritedDSA);
4092     AllowedNameModifiers.push_back(OMPD_target);
4093     break;
4094   case OMPD_teams_distribute:
4095     Res = ActOnOpenMPTeamsDistributeDirective(
4096         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4097     break;
4098   case OMPD_teams_distribute_simd:
4099     Res = ActOnOpenMPTeamsDistributeSimdDirective(
4100         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4101     break;
4102   case OMPD_teams_distribute_parallel_for_simd:
4103     Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
4104         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4105     AllowedNameModifiers.push_back(OMPD_parallel);
4106     break;
4107   case OMPD_teams_distribute_parallel_for:
4108     Res = ActOnOpenMPTeamsDistributeParallelForDirective(
4109         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4110     AllowedNameModifiers.push_back(OMPD_parallel);
4111     break;
4112   case OMPD_target_teams:
4113     Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
4114                                           EndLoc);
4115     AllowedNameModifiers.push_back(OMPD_target);
4116     break;
4117   case OMPD_target_teams_distribute:
4118     Res = ActOnOpenMPTargetTeamsDistributeDirective(
4119         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4120     AllowedNameModifiers.push_back(OMPD_target);
4121     break;
4122   case OMPD_target_teams_distribute_parallel_for:
4123     Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
4124         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4125     AllowedNameModifiers.push_back(OMPD_target);
4126     AllowedNameModifiers.push_back(OMPD_parallel);
4127     break;
4128   case OMPD_target_teams_distribute_parallel_for_simd:
4129     Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
4130         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4131     AllowedNameModifiers.push_back(OMPD_target);
4132     AllowedNameModifiers.push_back(OMPD_parallel);
4133     break;
4134   case OMPD_target_teams_distribute_simd:
4135     Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
4136         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4137     AllowedNameModifiers.push_back(OMPD_target);
4138     break;
4139   case OMPD_declare_target:
4140   case OMPD_end_declare_target:
4141   case OMPD_threadprivate:
4142   case OMPD_allocate:
4143   case OMPD_declare_reduction:
4144   case OMPD_declare_mapper:
4145   case OMPD_declare_simd:
4146   case OMPD_requires:
4147     llvm_unreachable("OpenMP Directive is not allowed");
4148   case OMPD_unknown:
4149     llvm_unreachable("Unknown OpenMP directive");
4150   }
4151 
4152   ErrorFound = Res.isInvalid() || ErrorFound;
4153 
4154   for (const auto &P : VarsWithInheritedDSA) {
4155     Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
4156         << P.first << P.second->getSourceRange();
4157   }
4158   ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound;
4159 
4160   if (!AllowedNameModifiers.empty())
4161     ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
4162                  ErrorFound;
4163 
4164   if (ErrorFound)
4165     return StmtError();
4166 
4167   if (!(Res.getAs<OMPExecutableDirective>()->isStandaloneDirective())) {
4168     Res.getAs<OMPExecutableDirective>()
4169         ->getStructuredBlock()
4170         ->setIsOMPStructuredBlock(true);
4171   }
4172 
4173   return Res;
4174 }
4175 
4176 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
4177     DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
4178     ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
4179     ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
4180     ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
4181   assert(Aligneds.size() == Alignments.size());
4182   assert(Linears.size() == LinModifiers.size());
4183   assert(Linears.size() == Steps.size());
4184   if (!DG || DG.get().isNull())
4185     return DeclGroupPtrTy();
4186 
4187   if (!DG.get().isSingleDecl()) {
4188     Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd);
4189     return DG;
4190   }
4191   Decl *ADecl = DG.get().getSingleDecl();
4192   if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
4193     ADecl = FTD->getTemplatedDecl();
4194 
4195   auto *FD = dyn_cast<FunctionDecl>(ADecl);
4196   if (!FD) {
4197     Diag(ADecl->getLocation(), diag::err_omp_function_expected);
4198     return DeclGroupPtrTy();
4199   }
4200 
4201   // OpenMP [2.8.2, declare simd construct, Description]
4202   // The parameter of the simdlen clause must be a constant positive integer
4203   // expression.
4204   ExprResult SL;
4205   if (Simdlen)
4206     SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
4207   // OpenMP [2.8.2, declare simd construct, Description]
4208   // The special this pointer can be used as if was one of the arguments to the
4209   // function in any of the linear, aligned, or uniform clauses.
4210   // The uniform clause declares one or more arguments to have an invariant
4211   // value for all concurrent invocations of the function in the execution of a
4212   // single SIMD loop.
4213   llvm::DenseMap<const Decl *, const Expr *> UniformedArgs;
4214   const Expr *UniformedLinearThis = nullptr;
4215   for (const Expr *E : Uniforms) {
4216     E = E->IgnoreParenImpCasts();
4217     if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
4218       if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
4219         if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
4220             FD->getParamDecl(PVD->getFunctionScopeIndex())
4221                     ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
4222           UniformedArgs.try_emplace(PVD->getCanonicalDecl(), E);
4223           continue;
4224         }
4225     if (isa<CXXThisExpr>(E)) {
4226       UniformedLinearThis = E;
4227       continue;
4228     }
4229     Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
4230         << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
4231   }
4232   // OpenMP [2.8.2, declare simd construct, Description]
4233   // The aligned clause declares that the object to which each list item points
4234   // is aligned to the number of bytes expressed in the optional parameter of
4235   // the aligned clause.
4236   // The special this pointer can be used as if was one of the arguments to the
4237   // function in any of the linear, aligned, or uniform clauses.
4238   // The type of list items appearing in the aligned clause must be array,
4239   // pointer, reference to array, or reference to pointer.
4240   llvm::DenseMap<const Decl *, const Expr *> AlignedArgs;
4241   const Expr *AlignedThis = nullptr;
4242   for (const Expr *E : Aligneds) {
4243     E = E->IgnoreParenImpCasts();
4244     if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
4245       if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
4246         const VarDecl *CanonPVD = PVD->getCanonicalDecl();
4247         if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
4248             FD->getParamDecl(PVD->getFunctionScopeIndex())
4249                     ->getCanonicalDecl() == CanonPVD) {
4250           // OpenMP  [2.8.1, simd construct, Restrictions]
4251           // A list-item cannot appear in more than one aligned clause.
4252           if (AlignedArgs.count(CanonPVD) > 0) {
4253             Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
4254                 << 1 << E->getSourceRange();
4255             Diag(AlignedArgs[CanonPVD]->getExprLoc(),
4256                  diag::note_omp_explicit_dsa)
4257                 << getOpenMPClauseName(OMPC_aligned);
4258             continue;
4259           }
4260           AlignedArgs[CanonPVD] = E;
4261           QualType QTy = PVD->getType()
4262                              .getNonReferenceType()
4263                              .getUnqualifiedType()
4264                              .getCanonicalType();
4265           const Type *Ty = QTy.getTypePtrOrNull();
4266           if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
4267             Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
4268                 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
4269             Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
4270           }
4271           continue;
4272         }
4273       }
4274     if (isa<CXXThisExpr>(E)) {
4275       if (AlignedThis) {
4276         Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
4277             << 2 << E->getSourceRange();
4278         Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
4279             << getOpenMPClauseName(OMPC_aligned);
4280       }
4281       AlignedThis = E;
4282       continue;
4283     }
4284     Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
4285         << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
4286   }
4287   // The optional parameter of the aligned clause, alignment, must be a constant
4288   // positive integer expression. If no optional parameter is specified,
4289   // implementation-defined default alignments for SIMD instructions on the
4290   // target platforms are assumed.
4291   SmallVector<const Expr *, 4> NewAligns;
4292   for (Expr *E : Alignments) {
4293     ExprResult Align;
4294     if (E)
4295       Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
4296     NewAligns.push_back(Align.get());
4297   }
4298   // OpenMP [2.8.2, declare simd construct, Description]
4299   // The linear clause declares one or more list items to be private to a SIMD
4300   // lane and to have a linear relationship with respect to the iteration space
4301   // of a loop.
4302   // The special this pointer can be used as if was one of the arguments to the
4303   // function in any of the linear, aligned, or uniform clauses.
4304   // When a linear-step expression is specified in a linear clause it must be
4305   // either a constant integer expression or an integer-typed parameter that is
4306   // specified in a uniform clause on the directive.
4307   llvm::DenseMap<const Decl *, const Expr *> LinearArgs;
4308   const bool IsUniformedThis = UniformedLinearThis != nullptr;
4309   auto MI = LinModifiers.begin();
4310   for (const Expr *E : Linears) {
4311     auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
4312     ++MI;
4313     E = E->IgnoreParenImpCasts();
4314     if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
4315       if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
4316         const VarDecl *CanonPVD = PVD->getCanonicalDecl();
4317         if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
4318             FD->getParamDecl(PVD->getFunctionScopeIndex())
4319                     ->getCanonicalDecl() == CanonPVD) {
4320           // OpenMP  [2.15.3.7, linear Clause, Restrictions]
4321           // A list-item cannot appear in more than one linear clause.
4322           if (LinearArgs.count(CanonPVD) > 0) {
4323             Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
4324                 << getOpenMPClauseName(OMPC_linear)
4325                 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
4326             Diag(LinearArgs[CanonPVD]->getExprLoc(),
4327                  diag::note_omp_explicit_dsa)
4328                 << getOpenMPClauseName(OMPC_linear);
4329             continue;
4330           }
4331           // Each argument can appear in at most one uniform or linear clause.
4332           if (UniformedArgs.count(CanonPVD) > 0) {
4333             Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
4334                 << getOpenMPClauseName(OMPC_linear)
4335                 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
4336             Diag(UniformedArgs[CanonPVD]->getExprLoc(),
4337                  diag::note_omp_explicit_dsa)
4338                 << getOpenMPClauseName(OMPC_uniform);
4339             continue;
4340           }
4341           LinearArgs[CanonPVD] = E;
4342           if (E->isValueDependent() || E->isTypeDependent() ||
4343               E->isInstantiationDependent() ||
4344               E->containsUnexpandedParameterPack())
4345             continue;
4346           (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
4347                                       PVD->getOriginalType());
4348           continue;
4349         }
4350       }
4351     if (isa<CXXThisExpr>(E)) {
4352       if (UniformedLinearThis) {
4353         Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
4354             << getOpenMPClauseName(OMPC_linear)
4355             << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
4356             << E->getSourceRange();
4357         Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
4358             << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
4359                                                    : OMPC_linear);
4360         continue;
4361       }
4362       UniformedLinearThis = E;
4363       if (E->isValueDependent() || E->isTypeDependent() ||
4364           E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
4365         continue;
4366       (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
4367                                   E->getType());
4368       continue;
4369     }
4370     Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
4371         << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
4372   }
4373   Expr *Step = nullptr;
4374   Expr *NewStep = nullptr;
4375   SmallVector<Expr *, 4> NewSteps;
4376   for (Expr *E : Steps) {
4377     // Skip the same step expression, it was checked already.
4378     if (Step == E || !E) {
4379       NewSteps.push_back(E ? NewStep : nullptr);
4380       continue;
4381     }
4382     Step = E;
4383     if (const auto *DRE = dyn_cast<DeclRefExpr>(Step))
4384       if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
4385         const VarDecl *CanonPVD = PVD->getCanonicalDecl();
4386         if (UniformedArgs.count(CanonPVD) == 0) {
4387           Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
4388               << Step->getSourceRange();
4389         } else if (E->isValueDependent() || E->isTypeDependent() ||
4390                    E->isInstantiationDependent() ||
4391                    E->containsUnexpandedParameterPack() ||
4392                    CanonPVD->getType()->hasIntegerRepresentation()) {
4393           NewSteps.push_back(Step);
4394         } else {
4395           Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
4396               << Step->getSourceRange();
4397         }
4398         continue;
4399       }
4400     NewStep = Step;
4401     if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
4402         !Step->isInstantiationDependent() &&
4403         !Step->containsUnexpandedParameterPack()) {
4404       NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
4405                     .get();
4406       if (NewStep)
4407         NewStep = VerifyIntegerConstantExpression(NewStep).get();
4408     }
4409     NewSteps.push_back(NewStep);
4410   }
4411   auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
4412       Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
4413       Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
4414       const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
4415       const_cast<Expr **>(Linears.data()), Linears.size(),
4416       const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
4417       NewSteps.data(), NewSteps.size(), SR);
4418   ADecl->addAttr(NewAttr);
4419   return ConvertDeclToDeclGroup(ADecl);
4420 }
4421 
4422 StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
4423                                               Stmt *AStmt,
4424                                               SourceLocation StartLoc,
4425                                               SourceLocation EndLoc) {
4426   if (!AStmt)
4427     return StmtError();
4428 
4429   auto *CS = cast<CapturedStmt>(AStmt);
4430   // 1.2.2 OpenMP Language Terminology
4431   // Structured block - An executable statement with a single entry at the
4432   // top and a single exit at the bottom.
4433   // The point of exit cannot be a branch out of the structured block.
4434   // longjmp() and throw() must not violate the entry/exit criteria.
4435   CS->getCapturedDecl()->setNothrow();
4436 
4437   setFunctionHasBranchProtectedScope();
4438 
4439   return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
4440                                       DSAStack->isCancelRegion());
4441 }
4442 
4443 namespace {
4444 /// Helper class for checking canonical form of the OpenMP loops and
4445 /// extracting iteration space of each loop in the loop nest, that will be used
4446 /// for IR generation.
4447 class OpenMPIterationSpaceChecker {
4448   /// Reference to Sema.
4449   Sema &SemaRef;
4450   /// A location for diagnostics (when there is no some better location).
4451   SourceLocation DefaultLoc;
4452   /// A location for diagnostics (when increment is not compatible).
4453   SourceLocation ConditionLoc;
4454   /// A source location for referring to loop init later.
4455   SourceRange InitSrcRange;
4456   /// A source location for referring to condition later.
4457   SourceRange ConditionSrcRange;
4458   /// A source location for referring to increment later.
4459   SourceRange IncrementSrcRange;
4460   /// Loop variable.
4461   ValueDecl *LCDecl = nullptr;
4462   /// Reference to loop variable.
4463   Expr *LCRef = nullptr;
4464   /// Lower bound (initializer for the var).
4465   Expr *LB = nullptr;
4466   /// Upper bound.
4467   Expr *UB = nullptr;
4468   /// Loop step (increment).
4469   Expr *Step = nullptr;
4470   /// This flag is true when condition is one of:
4471   ///   Var <  UB
4472   ///   Var <= UB
4473   ///   UB  >  Var
4474   ///   UB  >= Var
4475   /// This will have no value when the condition is !=
4476   llvm::Optional<bool> TestIsLessOp;
4477   /// This flag is true when condition is strict ( < or > ).
4478   bool TestIsStrictOp = false;
4479   /// This flag is true when step is subtracted on each iteration.
4480   bool SubtractStep = false;
4481 
4482 public:
4483   OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
4484       : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {}
4485   /// Check init-expr for canonical loop form and save loop counter
4486   /// variable - #Var and its initialization value - #LB.
4487   bool checkAndSetInit(Stmt *S, bool EmitDiags = true);
4488   /// Check test-expr for canonical form, save upper-bound (#UB), flags
4489   /// for less/greater and for strict/non-strict comparison.
4490   bool checkAndSetCond(Expr *S);
4491   /// Check incr-expr for canonical loop form and return true if it
4492   /// does not conform, otherwise save loop step (#Step).
4493   bool checkAndSetInc(Expr *S);
4494   /// Return the loop counter variable.
4495   ValueDecl *getLoopDecl() const { return LCDecl; }
4496   /// Return the reference expression to loop counter variable.
4497   Expr *getLoopDeclRefExpr() const { return LCRef; }
4498   /// Source range of the loop init.
4499   SourceRange getInitSrcRange() const { return InitSrcRange; }
4500   /// Source range of the loop condition.
4501   SourceRange getConditionSrcRange() const { return ConditionSrcRange; }
4502   /// Source range of the loop increment.
4503   SourceRange getIncrementSrcRange() const { return IncrementSrcRange; }
4504   /// True if the step should be subtracted.
4505   bool shouldSubtractStep() const { return SubtractStep; }
4506   /// True, if the compare operator is strict (<, > or !=).
4507   bool isStrictTestOp() const { return TestIsStrictOp; }
4508   /// Build the expression to calculate the number of iterations.
4509   Expr *buildNumIterations(
4510       Scope *S, const bool LimitedType,
4511       llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
4512   /// Build the precondition expression for the loops.
4513   Expr *
4514   buildPreCond(Scope *S, Expr *Cond,
4515                llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
4516   /// Build reference expression to the counter be used for codegen.
4517   DeclRefExpr *
4518   buildCounterVar(llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
4519                   DSAStackTy &DSA) const;
4520   /// Build reference expression to the private counter be used for
4521   /// codegen.
4522   Expr *buildPrivateCounterVar() const;
4523   /// Build initialization of the counter be used for codegen.
4524   Expr *buildCounterInit() const;
4525   /// Build step of the counter be used for codegen.
4526   Expr *buildCounterStep() const;
4527   /// Build loop data with counter value for depend clauses in ordered
4528   /// directives.
4529   Expr *
4530   buildOrderedLoopData(Scope *S, Expr *Counter,
4531                        llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
4532                        SourceLocation Loc, Expr *Inc = nullptr,
4533                        OverloadedOperatorKind OOK = OO_Amp);
4534   /// Return true if any expression is dependent.
4535   bool dependent() const;
4536 
4537 private:
4538   /// Check the right-hand side of an assignment in the increment
4539   /// expression.
4540   bool checkAndSetIncRHS(Expr *RHS);
4541   /// Helper to set loop counter variable and its initializer.
4542   bool setLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB);
4543   /// Helper to set upper bound.
4544   bool setUB(Expr *NewUB, llvm::Optional<bool> LessOp, bool StrictOp,
4545              SourceRange SR, SourceLocation SL);
4546   /// Helper to set loop increment.
4547   bool setStep(Expr *NewStep, bool Subtract);
4548 };
4549 
4550 bool OpenMPIterationSpaceChecker::dependent() const {
4551   if (!LCDecl) {
4552     assert(!LB && !UB && !Step);
4553     return false;
4554   }
4555   return LCDecl->getType()->isDependentType() ||
4556          (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
4557          (Step && Step->isValueDependent());
4558 }
4559 
4560 bool OpenMPIterationSpaceChecker::setLCDeclAndLB(ValueDecl *NewLCDecl,
4561                                                  Expr *NewLCRefExpr,
4562                                                  Expr *NewLB) {
4563   // State consistency checking to ensure correct usage.
4564   assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
4565          UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
4566   if (!NewLCDecl || !NewLB)
4567     return true;
4568   LCDecl = getCanonicalDecl(NewLCDecl);
4569   LCRef = NewLCRefExpr;
4570   if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
4571     if (const CXXConstructorDecl *Ctor = CE->getConstructor())
4572       if ((Ctor->isCopyOrMoveConstructor() ||
4573            Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
4574           CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
4575         NewLB = CE->getArg(0)->IgnoreParenImpCasts();
4576   LB = NewLB;
4577   return false;
4578 }
4579 
4580 bool OpenMPIterationSpaceChecker::setUB(Expr *NewUB,
4581                                         llvm::Optional<bool> LessOp,
4582                                         bool StrictOp, SourceRange SR,
4583                                         SourceLocation SL) {
4584   // State consistency checking to ensure correct usage.
4585   assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
4586          Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
4587   if (!NewUB)
4588     return true;
4589   UB = NewUB;
4590   if (LessOp)
4591     TestIsLessOp = LessOp;
4592   TestIsStrictOp = StrictOp;
4593   ConditionSrcRange = SR;
4594   ConditionLoc = SL;
4595   return false;
4596 }
4597 
4598 bool OpenMPIterationSpaceChecker::setStep(Expr *NewStep, bool Subtract) {
4599   // State consistency checking to ensure correct usage.
4600   assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
4601   if (!NewStep)
4602     return true;
4603   if (!NewStep->isValueDependent()) {
4604     // Check that the step is integer expression.
4605     SourceLocation StepLoc = NewStep->getBeginLoc();
4606     ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion(
4607         StepLoc, getExprAsWritten(NewStep));
4608     if (Val.isInvalid())
4609       return true;
4610     NewStep = Val.get();
4611 
4612     // OpenMP [2.6, Canonical Loop Form, Restrictions]
4613     //  If test-expr is of form var relational-op b and relational-op is < or
4614     //  <= then incr-expr must cause var to increase on each iteration of the
4615     //  loop. If test-expr is of form var relational-op b and relational-op is
4616     //  > or >= then incr-expr must cause var to decrease on each iteration of
4617     //  the loop.
4618     //  If test-expr is of form b relational-op var and relational-op is < or
4619     //  <= then incr-expr must cause var to decrease on each iteration of the
4620     //  loop. If test-expr is of form b relational-op var and relational-op is
4621     //  > or >= then incr-expr must cause var to increase on each iteration of
4622     //  the loop.
4623     llvm::APSInt Result;
4624     bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
4625     bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
4626     bool IsConstNeg =
4627         IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
4628     bool IsConstPos =
4629         IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
4630     bool IsConstZero = IsConstant && !Result.getBoolValue();
4631 
4632     // != with increment is treated as <; != with decrement is treated as >
4633     if (!TestIsLessOp.hasValue())
4634       TestIsLessOp = IsConstPos || (IsUnsigned && !Subtract);
4635     if (UB && (IsConstZero ||
4636                (TestIsLessOp.getValue() ?
4637                   (IsConstNeg || (IsUnsigned && Subtract)) :
4638                   (IsConstPos || (IsUnsigned && !Subtract))))) {
4639       SemaRef.Diag(NewStep->getExprLoc(),
4640                    diag::err_omp_loop_incr_not_compatible)
4641           << LCDecl << TestIsLessOp.getValue() << NewStep->getSourceRange();
4642       SemaRef.Diag(ConditionLoc,
4643                    diag::note_omp_loop_cond_requres_compatible_incr)
4644           << TestIsLessOp.getValue() << ConditionSrcRange;
4645       return true;
4646     }
4647     if (TestIsLessOp.getValue() == Subtract) {
4648       NewStep =
4649           SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
4650               .get();
4651       Subtract = !Subtract;
4652     }
4653   }
4654 
4655   Step = NewStep;
4656   SubtractStep = Subtract;
4657   return false;
4658 }
4659 
4660 bool OpenMPIterationSpaceChecker::checkAndSetInit(Stmt *S, bool EmitDiags) {
4661   // Check init-expr for canonical loop form and save loop counter
4662   // variable - #Var and its initialization value - #LB.
4663   // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
4664   //   var = lb
4665   //   integer-type var = lb
4666   //   random-access-iterator-type var = lb
4667   //   pointer-type var = lb
4668   //
4669   if (!S) {
4670     if (EmitDiags) {
4671       SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
4672     }
4673     return true;
4674   }
4675   if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
4676     if (!ExprTemp->cleanupsHaveSideEffects())
4677       S = ExprTemp->getSubExpr();
4678 
4679   InitSrcRange = S->getSourceRange();
4680   if (Expr *E = dyn_cast<Expr>(S))
4681     S = E->IgnoreParens();
4682   if (auto *BO = dyn_cast<BinaryOperator>(S)) {
4683     if (BO->getOpcode() == BO_Assign) {
4684       Expr *LHS = BO->getLHS()->IgnoreParens();
4685       if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
4686         if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
4687           if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
4688             return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
4689         return setLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS());
4690       }
4691       if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
4692         if (ME->isArrow() &&
4693             isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
4694           return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
4695       }
4696     }
4697   } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
4698     if (DS->isSingleDecl()) {
4699       if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
4700         if (Var->hasInit() && !Var->getType()->isReferenceType()) {
4701           // Accept non-canonical init form here but emit ext. warning.
4702           if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
4703             SemaRef.Diag(S->getBeginLoc(),
4704                          diag::ext_omp_loop_not_canonical_init)
4705                 << S->getSourceRange();
4706           return setLCDeclAndLB(
4707               Var,
4708               buildDeclRefExpr(SemaRef, Var,
4709                                Var->getType().getNonReferenceType(),
4710                                DS->getBeginLoc()),
4711               Var->getInit());
4712         }
4713       }
4714     }
4715   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
4716     if (CE->getOperator() == OO_Equal) {
4717       Expr *LHS = CE->getArg(0);
4718       if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
4719         if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
4720           if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
4721             return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
4722         return setLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1));
4723       }
4724       if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
4725         if (ME->isArrow() &&
4726             isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
4727           return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
4728       }
4729     }
4730   }
4731 
4732   if (dependent() || SemaRef.CurContext->isDependentContext())
4733     return false;
4734   if (EmitDiags) {
4735     SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_init)
4736         << S->getSourceRange();
4737   }
4738   return true;
4739 }
4740 
4741 /// Ignore parenthesizes, implicit casts, copy constructor and return the
4742 /// variable (which may be the loop variable) if possible.
4743 static const ValueDecl *getInitLCDecl(const Expr *E) {
4744   if (!E)
4745     return nullptr;
4746   E = getExprAsWritten(E);
4747   if (const auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
4748     if (const CXXConstructorDecl *Ctor = CE->getConstructor())
4749       if ((Ctor->isCopyOrMoveConstructor() ||
4750            Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
4751           CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
4752         E = CE->getArg(0)->IgnoreParenImpCasts();
4753   if (const auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
4754     if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
4755       return getCanonicalDecl(VD);
4756   }
4757   if (const auto *ME = dyn_cast_or_null<MemberExpr>(E))
4758     if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
4759       return getCanonicalDecl(ME->getMemberDecl());
4760   return nullptr;
4761 }
4762 
4763 bool OpenMPIterationSpaceChecker::checkAndSetCond(Expr *S) {
4764   // Check test-expr for canonical form, save upper-bound UB, flags for
4765   // less/greater and for strict/non-strict comparison.
4766   // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
4767   //   var relational-op b
4768   //   b relational-op var
4769   //
4770   if (!S) {
4771     SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl;
4772     return true;
4773   }
4774   S = getExprAsWritten(S);
4775   SourceLocation CondLoc = S->getBeginLoc();
4776   if (auto *BO = dyn_cast<BinaryOperator>(S)) {
4777     if (BO->isRelationalOp()) {
4778       if (getInitLCDecl(BO->getLHS()) == LCDecl)
4779         return setUB(BO->getRHS(),
4780                      (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
4781                      (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
4782                      BO->getSourceRange(), BO->getOperatorLoc());
4783       if (getInitLCDecl(BO->getRHS()) == LCDecl)
4784         return setUB(BO->getLHS(),
4785                      (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
4786                      (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
4787                      BO->getSourceRange(), BO->getOperatorLoc());
4788     } else if (BO->getOpcode() == BO_NE)
4789         return setUB(getInitLCDecl(BO->getLHS()) == LCDecl ?
4790                        BO->getRHS() : BO->getLHS(),
4791                      /*LessOp=*/llvm::None,
4792                      /*StrictOp=*/true,
4793                      BO->getSourceRange(), BO->getOperatorLoc());
4794   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
4795     if (CE->getNumArgs() == 2) {
4796       auto Op = CE->getOperator();
4797       switch (Op) {
4798       case OO_Greater:
4799       case OO_GreaterEqual:
4800       case OO_Less:
4801       case OO_LessEqual:
4802         if (getInitLCDecl(CE->getArg(0)) == LCDecl)
4803           return setUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
4804                        Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
4805                        CE->getOperatorLoc());
4806         if (getInitLCDecl(CE->getArg(1)) == LCDecl)
4807           return setUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
4808                        Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
4809                        CE->getOperatorLoc());
4810         break;
4811       case OO_ExclaimEqual:
4812         return setUB(getInitLCDecl(CE->getArg(0)) == LCDecl ?
4813                      CE->getArg(1) : CE->getArg(0),
4814                      /*LessOp=*/llvm::None,
4815                      /*StrictOp=*/true,
4816                      CE->getSourceRange(),
4817                      CE->getOperatorLoc());
4818         break;
4819       default:
4820         break;
4821       }
4822     }
4823   }
4824   if (dependent() || SemaRef.CurContext->isDependentContext())
4825     return false;
4826   SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
4827       << S->getSourceRange() << LCDecl;
4828   return true;
4829 }
4830 
4831 bool OpenMPIterationSpaceChecker::checkAndSetIncRHS(Expr *RHS) {
4832   // RHS of canonical loop form increment can be:
4833   //   var + incr
4834   //   incr + var
4835   //   var - incr
4836   //
4837   RHS = RHS->IgnoreParenImpCasts();
4838   if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
4839     if (BO->isAdditiveOp()) {
4840       bool IsAdd = BO->getOpcode() == BO_Add;
4841       if (getInitLCDecl(BO->getLHS()) == LCDecl)
4842         return setStep(BO->getRHS(), !IsAdd);
4843       if (IsAdd && getInitLCDecl(BO->getRHS()) == LCDecl)
4844         return setStep(BO->getLHS(), /*Subtract=*/false);
4845     }
4846   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
4847     bool IsAdd = CE->getOperator() == OO_Plus;
4848     if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
4849       if (getInitLCDecl(CE->getArg(0)) == LCDecl)
4850         return setStep(CE->getArg(1), !IsAdd);
4851       if (IsAdd && getInitLCDecl(CE->getArg(1)) == LCDecl)
4852         return setStep(CE->getArg(0), /*Subtract=*/false);
4853     }
4854   }
4855   if (dependent() || SemaRef.CurContext->isDependentContext())
4856     return false;
4857   SemaRef.Diag(RHS->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
4858       << RHS->getSourceRange() << LCDecl;
4859   return true;
4860 }
4861 
4862 bool OpenMPIterationSpaceChecker::checkAndSetInc(Expr *S) {
4863   // Check incr-expr for canonical loop form and return true if it
4864   // does not conform.
4865   // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
4866   //   ++var
4867   //   var++
4868   //   --var
4869   //   var--
4870   //   var += incr
4871   //   var -= incr
4872   //   var = var + incr
4873   //   var = incr + var
4874   //   var = var - incr
4875   //
4876   if (!S) {
4877     SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
4878     return true;
4879   }
4880   if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
4881     if (!ExprTemp->cleanupsHaveSideEffects())
4882       S = ExprTemp->getSubExpr();
4883 
4884   IncrementSrcRange = S->getSourceRange();
4885   S = S->IgnoreParens();
4886   if (auto *UO = dyn_cast<UnaryOperator>(S)) {
4887     if (UO->isIncrementDecrementOp() &&
4888         getInitLCDecl(UO->getSubExpr()) == LCDecl)
4889       return setStep(SemaRef
4890                          .ActOnIntegerConstant(UO->getBeginLoc(),
4891                                                (UO->isDecrementOp() ? -1 : 1))
4892                          .get(),
4893                      /*Subtract=*/false);
4894   } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
4895     switch (BO->getOpcode()) {
4896     case BO_AddAssign:
4897     case BO_SubAssign:
4898       if (getInitLCDecl(BO->getLHS()) == LCDecl)
4899         return setStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
4900       break;
4901     case BO_Assign:
4902       if (getInitLCDecl(BO->getLHS()) == LCDecl)
4903         return checkAndSetIncRHS(BO->getRHS());
4904       break;
4905     default:
4906       break;
4907     }
4908   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
4909     switch (CE->getOperator()) {
4910     case OO_PlusPlus:
4911     case OO_MinusMinus:
4912       if (getInitLCDecl(CE->getArg(0)) == LCDecl)
4913         return setStep(SemaRef
4914                            .ActOnIntegerConstant(
4915                                CE->getBeginLoc(),
4916                                ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
4917                            .get(),
4918                        /*Subtract=*/false);
4919       break;
4920     case OO_PlusEqual:
4921     case OO_MinusEqual:
4922       if (getInitLCDecl(CE->getArg(0)) == LCDecl)
4923         return setStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
4924       break;
4925     case OO_Equal:
4926       if (getInitLCDecl(CE->getArg(0)) == LCDecl)
4927         return checkAndSetIncRHS(CE->getArg(1));
4928       break;
4929     default:
4930       break;
4931     }
4932   }
4933   if (dependent() || SemaRef.CurContext->isDependentContext())
4934     return false;
4935   SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
4936       << S->getSourceRange() << LCDecl;
4937   return true;
4938 }
4939 
4940 static ExprResult
4941 tryBuildCapture(Sema &SemaRef, Expr *Capture,
4942                 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
4943   if (SemaRef.CurContext->isDependentContext())
4944     return ExprResult(Capture);
4945   if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
4946     return SemaRef.PerformImplicitConversion(
4947         Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
4948         /*AllowExplicit=*/true);
4949   auto I = Captures.find(Capture);
4950   if (I != Captures.end())
4951     return buildCapture(SemaRef, Capture, I->second);
4952   DeclRefExpr *Ref = nullptr;
4953   ExprResult Res = buildCapture(SemaRef, Capture, Ref);
4954   Captures[Capture] = Ref;
4955   return Res;
4956 }
4957 
4958 /// Build the expression to calculate the number of iterations.
4959 Expr *OpenMPIterationSpaceChecker::buildNumIterations(
4960     Scope *S, const bool LimitedType,
4961     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
4962   ExprResult Diff;
4963   QualType VarType = LCDecl->getType().getNonReferenceType();
4964   if (VarType->isIntegerType() || VarType->isPointerType() ||
4965       SemaRef.getLangOpts().CPlusPlus) {
4966     // Upper - Lower
4967     Expr *UBExpr = TestIsLessOp.getValue() ? UB : LB;
4968     Expr *LBExpr = TestIsLessOp.getValue() ? LB : UB;
4969     Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
4970     Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
4971     if (!Upper || !Lower)
4972       return nullptr;
4973 
4974     Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
4975 
4976     if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
4977       // BuildBinOp already emitted error, this one is to point user to upper
4978       // and lower bound, and to tell what is passed to 'operator-'.
4979       SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
4980           << Upper->getSourceRange() << Lower->getSourceRange();
4981       return nullptr;
4982     }
4983   }
4984 
4985   if (!Diff.isUsable())
4986     return nullptr;
4987 
4988   // Upper - Lower [- 1]
4989   if (TestIsStrictOp)
4990     Diff = SemaRef.BuildBinOp(
4991         S, DefaultLoc, BO_Sub, Diff.get(),
4992         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4993   if (!Diff.isUsable())
4994     return nullptr;
4995 
4996   // Upper - Lower [- 1] + Step
4997   ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
4998   if (!NewStep.isUsable())
4999     return nullptr;
5000   Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
5001   if (!Diff.isUsable())
5002     return nullptr;
5003 
5004   // Parentheses (for dumping/debugging purposes only).
5005   Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
5006   if (!Diff.isUsable())
5007     return nullptr;
5008 
5009   // (Upper - Lower [- 1] + Step) / Step
5010   Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
5011   if (!Diff.isUsable())
5012     return nullptr;
5013 
5014   // OpenMP runtime requires 32-bit or 64-bit loop variables.
5015   QualType Type = Diff.get()->getType();
5016   ASTContext &C = SemaRef.Context;
5017   bool UseVarType = VarType->hasIntegerRepresentation() &&
5018                     C.getTypeSize(Type) > C.getTypeSize(VarType);
5019   if (!Type->isIntegerType() || UseVarType) {
5020     unsigned NewSize =
5021         UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
5022     bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
5023                                : Type->hasSignedIntegerRepresentation();
5024     Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
5025     if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
5026       Diff = SemaRef.PerformImplicitConversion(
5027           Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
5028       if (!Diff.isUsable())
5029         return nullptr;
5030     }
5031   }
5032   if (LimitedType) {
5033     unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
5034     if (NewSize != C.getTypeSize(Type)) {
5035       if (NewSize < C.getTypeSize(Type)) {
5036         assert(NewSize == 64 && "incorrect loop var size");
5037         SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
5038             << InitSrcRange << ConditionSrcRange;
5039       }
5040       QualType NewType = C.getIntTypeForBitwidth(
5041           NewSize, Type->hasSignedIntegerRepresentation() ||
5042                        C.getTypeSize(Type) < NewSize);
5043       if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
5044         Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
5045                                                  Sema::AA_Converting, true);
5046         if (!Diff.isUsable())
5047           return nullptr;
5048       }
5049     }
5050   }
5051 
5052   return Diff.get();
5053 }
5054 
5055 Expr *OpenMPIterationSpaceChecker::buildPreCond(
5056     Scope *S, Expr *Cond,
5057     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
5058   // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
5059   bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
5060   SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
5061 
5062   ExprResult NewLB = tryBuildCapture(SemaRef, LB, Captures);
5063   ExprResult NewUB = tryBuildCapture(SemaRef, UB, Captures);
5064   if (!NewLB.isUsable() || !NewUB.isUsable())
5065     return nullptr;
5066 
5067   ExprResult CondExpr =
5068       SemaRef.BuildBinOp(S, DefaultLoc,
5069                          TestIsLessOp.getValue() ?
5070                            (TestIsStrictOp ? BO_LT : BO_LE) :
5071                            (TestIsStrictOp ? BO_GT : BO_GE),
5072                          NewLB.get(), NewUB.get());
5073   if (CondExpr.isUsable()) {
5074     if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
5075                                                 SemaRef.Context.BoolTy))
5076       CondExpr = SemaRef.PerformImplicitConversion(
5077           CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
5078           /*AllowExplicit=*/true);
5079   }
5080   SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
5081   // Otherwise use original loop condition and evaluate it in runtime.
5082   return CondExpr.isUsable() ? CondExpr.get() : Cond;
5083 }
5084 
5085 /// Build reference expression to the counter be used for codegen.
5086 DeclRefExpr *OpenMPIterationSpaceChecker::buildCounterVar(
5087     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
5088     DSAStackTy &DSA) const {
5089   auto *VD = dyn_cast<VarDecl>(LCDecl);
5090   if (!VD) {
5091     VD = SemaRef.isOpenMPCapturedDecl(LCDecl);
5092     DeclRefExpr *Ref = buildDeclRefExpr(
5093         SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
5094     const DSAStackTy::DSAVarData Data =
5095         DSA.getTopDSA(LCDecl, /*FromParent=*/false);
5096     // If the loop control decl is explicitly marked as private, do not mark it
5097     // as captured again.
5098     if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
5099       Captures.insert(std::make_pair(LCRef, Ref));
5100     return Ref;
5101   }
5102   return cast<DeclRefExpr>(LCRef);
5103 }
5104 
5105 Expr *OpenMPIterationSpaceChecker::buildPrivateCounterVar() const {
5106   if (LCDecl && !LCDecl->isInvalidDecl()) {
5107     QualType Type = LCDecl->getType().getNonReferenceType();
5108     VarDecl *PrivateVar = buildVarDecl(
5109         SemaRef, DefaultLoc, Type, LCDecl->getName(),
5110         LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr,
5111         isa<VarDecl>(LCDecl)
5112             ? buildDeclRefExpr(SemaRef, cast<VarDecl>(LCDecl), Type, DefaultLoc)
5113             : nullptr);
5114     if (PrivateVar->isInvalidDecl())
5115       return nullptr;
5116     return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
5117   }
5118   return nullptr;
5119 }
5120 
5121 /// Build initialization of the counter to be used for codegen.
5122 Expr *OpenMPIterationSpaceChecker::buildCounterInit() const { return LB; }
5123 
5124 /// Build step of the counter be used for codegen.
5125 Expr *OpenMPIterationSpaceChecker::buildCounterStep() const { return Step; }
5126 
5127 Expr *OpenMPIterationSpaceChecker::buildOrderedLoopData(
5128     Scope *S, Expr *Counter,
5129     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, SourceLocation Loc,
5130     Expr *Inc, OverloadedOperatorKind OOK) {
5131   Expr *Cnt = SemaRef.DefaultLvalueConversion(Counter).get();
5132   if (!Cnt)
5133     return nullptr;
5134   if (Inc) {
5135     assert((OOK == OO_Plus || OOK == OO_Minus) &&
5136            "Expected only + or - operations for depend clauses.");
5137     BinaryOperatorKind BOK = (OOK == OO_Plus) ? BO_Add : BO_Sub;
5138     Cnt = SemaRef.BuildBinOp(S, Loc, BOK, Cnt, Inc).get();
5139     if (!Cnt)
5140       return nullptr;
5141   }
5142   ExprResult Diff;
5143   QualType VarType = LCDecl->getType().getNonReferenceType();
5144   if (VarType->isIntegerType() || VarType->isPointerType() ||
5145       SemaRef.getLangOpts().CPlusPlus) {
5146     // Upper - Lower
5147     Expr *Upper = TestIsLessOp.getValue()
5148                       ? Cnt
5149                       : tryBuildCapture(SemaRef, UB, Captures).get();
5150     Expr *Lower = TestIsLessOp.getValue()
5151                       ? tryBuildCapture(SemaRef, LB, Captures).get()
5152                       : Cnt;
5153     if (!Upper || !Lower)
5154       return nullptr;
5155 
5156     Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
5157 
5158     if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
5159       // BuildBinOp already emitted error, this one is to point user to upper
5160       // and lower bound, and to tell what is passed to 'operator-'.
5161       SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
5162           << Upper->getSourceRange() << Lower->getSourceRange();
5163       return nullptr;
5164     }
5165   }
5166 
5167   if (!Diff.isUsable())
5168     return nullptr;
5169 
5170   // Parentheses (for dumping/debugging purposes only).
5171   Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
5172   if (!Diff.isUsable())
5173     return nullptr;
5174 
5175   ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
5176   if (!NewStep.isUsable())
5177     return nullptr;
5178   // (Upper - Lower) / Step
5179   Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
5180   if (!Diff.isUsable())
5181     return nullptr;
5182 
5183   return Diff.get();
5184 }
5185 
5186 /// Iteration space of a single for loop.
5187 struct LoopIterationSpace final {
5188   /// True if the condition operator is the strict compare operator (<, > or
5189   /// !=).
5190   bool IsStrictCompare = false;
5191   /// Condition of the loop.
5192   Expr *PreCond = nullptr;
5193   /// This expression calculates the number of iterations in the loop.
5194   /// It is always possible to calculate it before starting the loop.
5195   Expr *NumIterations = nullptr;
5196   /// The loop counter variable.
5197   Expr *CounterVar = nullptr;
5198   /// Private loop counter variable.
5199   Expr *PrivateCounterVar = nullptr;
5200   /// This is initializer for the initial value of #CounterVar.
5201   Expr *CounterInit = nullptr;
5202   /// This is step for the #CounterVar used to generate its update:
5203   /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
5204   Expr *CounterStep = nullptr;
5205   /// Should step be subtracted?
5206   bool Subtract = false;
5207   /// Source range of the loop init.
5208   SourceRange InitSrcRange;
5209   /// Source range of the loop condition.
5210   SourceRange CondSrcRange;
5211   /// Source range of the loop increment.
5212   SourceRange IncSrcRange;
5213 };
5214 
5215 } // namespace
5216 
5217 void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
5218   assert(getLangOpts().OpenMP && "OpenMP is not active.");
5219   assert(Init && "Expected loop in canonical form.");
5220   unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
5221   if (AssociatedLoops > 0 &&
5222       isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
5223     DSAStack->loopStart();
5224     OpenMPIterationSpaceChecker ISC(*this, ForLoc);
5225     if (!ISC.checkAndSetInit(Init, /*EmitDiags=*/false)) {
5226       if (ValueDecl *D = ISC.getLoopDecl()) {
5227         auto *VD = dyn_cast<VarDecl>(D);
5228         if (!VD) {
5229           if (VarDecl *Private = isOpenMPCapturedDecl(D)) {
5230             VD = Private;
5231           } else {
5232             DeclRefExpr *Ref = buildCapture(*this, D, ISC.getLoopDeclRefExpr(),
5233                                             /*WithInit=*/false);
5234             VD = cast<VarDecl>(Ref->getDecl());
5235           }
5236         }
5237         DSAStack->addLoopControlVariable(D, VD);
5238         const Decl *LD = DSAStack->getPossiblyLoopCunter();
5239         if (LD != D->getCanonicalDecl()) {
5240           DSAStack->resetPossibleLoopCounter();
5241           if (auto *Var = dyn_cast_or_null<VarDecl>(LD))
5242             MarkDeclarationsReferencedInExpr(
5243                 buildDeclRefExpr(*this, const_cast<VarDecl *>(Var),
5244                                  Var->getType().getNonLValueExprType(Context),
5245                                  ForLoc, /*RefersToCapture=*/true));
5246         }
5247       }
5248     }
5249     DSAStack->setAssociatedLoops(AssociatedLoops - 1);
5250   }
5251 }
5252 
5253 /// Called on a for stmt to check and extract its iteration space
5254 /// for further processing (such as collapsing).
5255 static bool checkOpenMPIterationSpace(
5256     OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
5257     unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
5258     unsigned TotalNestedLoopCount, Expr *CollapseLoopCountExpr,
5259     Expr *OrderedLoopCountExpr,
5260     Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
5261     LoopIterationSpace &ResultIterSpace,
5262     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
5263   // OpenMP [2.6, Canonical Loop Form]
5264   //   for (init-expr; test-expr; incr-expr) structured-block
5265   auto *For = dyn_cast_or_null<ForStmt>(S);
5266   if (!For) {
5267     SemaRef.Diag(S->getBeginLoc(), diag::err_omp_not_for)
5268         << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
5269         << getOpenMPDirectiveName(DKind) << TotalNestedLoopCount
5270         << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
5271     if (TotalNestedLoopCount > 1) {
5272       if (CollapseLoopCountExpr && OrderedLoopCountExpr)
5273         SemaRef.Diag(DSA.getConstructLoc(),
5274                      diag::note_omp_collapse_ordered_expr)
5275             << 2 << CollapseLoopCountExpr->getSourceRange()
5276             << OrderedLoopCountExpr->getSourceRange();
5277       else if (CollapseLoopCountExpr)
5278         SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
5279                      diag::note_omp_collapse_ordered_expr)
5280             << 0 << CollapseLoopCountExpr->getSourceRange();
5281       else
5282         SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
5283                      diag::note_omp_collapse_ordered_expr)
5284             << 1 << OrderedLoopCountExpr->getSourceRange();
5285     }
5286     return true;
5287   }
5288   assert(For->getBody());
5289 
5290   OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
5291 
5292   // Check init.
5293   Stmt *Init = For->getInit();
5294   if (ISC.checkAndSetInit(Init))
5295     return true;
5296 
5297   bool HasErrors = false;
5298 
5299   // Check loop variable's type.
5300   if (ValueDecl *LCDecl = ISC.getLoopDecl()) {
5301     Expr *LoopDeclRefExpr = ISC.getLoopDeclRefExpr();
5302 
5303     // OpenMP [2.6, Canonical Loop Form]
5304     // Var is one of the following:
5305     //   A variable of signed or unsigned integer type.
5306     //   For C++, a variable of a random access iterator type.
5307     //   For C, a variable of a pointer type.
5308     QualType VarType = LCDecl->getType().getNonReferenceType();
5309     if (!VarType->isDependentType() && !VarType->isIntegerType() &&
5310         !VarType->isPointerType() &&
5311         !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
5312       SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_variable_type)
5313           << SemaRef.getLangOpts().CPlusPlus;
5314       HasErrors = true;
5315     }
5316 
5317     // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
5318     // a Construct
5319     // The loop iteration variable(s) in the associated for-loop(s) of a for or
5320     // parallel for construct is (are) private.
5321     // The loop iteration variable in the associated for-loop of a simd
5322     // construct with just one associated for-loop is linear with a
5323     // constant-linear-step that is the increment of the associated for-loop.
5324     // Exclude loop var from the list of variables with implicitly defined data
5325     // sharing attributes.
5326     VarsWithImplicitDSA.erase(LCDecl);
5327 
5328     // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
5329     // in a Construct, C/C++].
5330     // The loop iteration variable in the associated for-loop of a simd
5331     // construct with just one associated for-loop may be listed in a linear
5332     // clause with a constant-linear-step that is the increment of the
5333     // associated for-loop.
5334     // The loop iteration variable(s) in the associated for-loop(s) of a for or
5335     // parallel for construct may be listed in a private or lastprivate clause.
5336     DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false);
5337     // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
5338     // declared in the loop and it is predetermined as a private.
5339     OpenMPClauseKind PredeterminedCKind =
5340         isOpenMPSimdDirective(DKind)
5341             ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
5342             : OMPC_private;
5343     if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
5344           DVar.CKind != PredeterminedCKind) ||
5345          ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
5346            isOpenMPDistributeDirective(DKind)) &&
5347           !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
5348           DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
5349         (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
5350       SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_var_dsa)
5351           << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
5352           << getOpenMPClauseName(PredeterminedCKind);
5353       if (DVar.RefExpr == nullptr)
5354         DVar.CKind = PredeterminedCKind;
5355       reportOriginalDsa(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true);
5356       HasErrors = true;
5357     } else if (LoopDeclRefExpr != nullptr) {
5358       // Make the loop iteration variable private (for worksharing constructs),
5359       // linear (for simd directives with the only one associated loop) or
5360       // lastprivate (for simd directives with several collapsed or ordered
5361       // loops).
5362       if (DVar.CKind == OMPC_unknown)
5363         DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind);
5364     }
5365 
5366     assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
5367 
5368     // Check test-expr.
5369     HasErrors |= ISC.checkAndSetCond(For->getCond());
5370 
5371     // Check incr-expr.
5372     HasErrors |= ISC.checkAndSetInc(For->getInc());
5373   }
5374 
5375   if (ISC.dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
5376     return HasErrors;
5377 
5378   // Build the loop's iteration space representation.
5379   ResultIterSpace.PreCond =
5380       ISC.buildPreCond(DSA.getCurScope(), For->getCond(), Captures);
5381   ResultIterSpace.NumIterations = ISC.buildNumIterations(
5382       DSA.getCurScope(),
5383       (isOpenMPWorksharingDirective(DKind) ||
5384        isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)),
5385       Captures);
5386   ResultIterSpace.CounterVar = ISC.buildCounterVar(Captures, DSA);
5387   ResultIterSpace.PrivateCounterVar = ISC.buildPrivateCounterVar();
5388   ResultIterSpace.CounterInit = ISC.buildCounterInit();
5389   ResultIterSpace.CounterStep = ISC.buildCounterStep();
5390   ResultIterSpace.InitSrcRange = ISC.getInitSrcRange();
5391   ResultIterSpace.CondSrcRange = ISC.getConditionSrcRange();
5392   ResultIterSpace.IncSrcRange = ISC.getIncrementSrcRange();
5393   ResultIterSpace.Subtract = ISC.shouldSubtractStep();
5394   ResultIterSpace.IsStrictCompare = ISC.isStrictTestOp();
5395 
5396   HasErrors |= (ResultIterSpace.PreCond == nullptr ||
5397                 ResultIterSpace.NumIterations == nullptr ||
5398                 ResultIterSpace.CounterVar == nullptr ||
5399                 ResultIterSpace.PrivateCounterVar == nullptr ||
5400                 ResultIterSpace.CounterInit == nullptr ||
5401                 ResultIterSpace.CounterStep == nullptr);
5402   if (!HasErrors && DSA.isOrderedRegion()) {
5403     if (DSA.getOrderedRegionParam().second->getNumForLoops()) {
5404       if (CurrentNestedLoopCount <
5405           DSA.getOrderedRegionParam().second->getLoopNumIterations().size()) {
5406         DSA.getOrderedRegionParam().second->setLoopNumIterations(
5407             CurrentNestedLoopCount, ResultIterSpace.NumIterations);
5408         DSA.getOrderedRegionParam().second->setLoopCounter(
5409             CurrentNestedLoopCount, ResultIterSpace.CounterVar);
5410       }
5411     }
5412     for (auto &Pair : DSA.getDoacrossDependClauses()) {
5413       if (CurrentNestedLoopCount >= Pair.first->getNumLoops()) {
5414         // Erroneous case - clause has some problems.
5415         continue;
5416       }
5417       if (Pair.first->getDependencyKind() == OMPC_DEPEND_sink &&
5418           Pair.second.size() <= CurrentNestedLoopCount) {
5419         // Erroneous case - clause has some problems.
5420         Pair.first->setLoopData(CurrentNestedLoopCount, nullptr);
5421         continue;
5422       }
5423       Expr *CntValue;
5424       if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
5425         CntValue = ISC.buildOrderedLoopData(
5426             DSA.getCurScope(), ResultIterSpace.CounterVar, Captures,
5427             Pair.first->getDependencyLoc());
5428       else
5429         CntValue = ISC.buildOrderedLoopData(
5430             DSA.getCurScope(), ResultIterSpace.CounterVar, Captures,
5431             Pair.first->getDependencyLoc(),
5432             Pair.second[CurrentNestedLoopCount].first,
5433             Pair.second[CurrentNestedLoopCount].second);
5434       Pair.first->setLoopData(CurrentNestedLoopCount, CntValue);
5435     }
5436   }
5437 
5438   return HasErrors;
5439 }
5440 
5441 /// Build 'VarRef = Start.
5442 static ExprResult
5443 buildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
5444                  ExprResult Start,
5445                  llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
5446   // Build 'VarRef = Start.
5447   ExprResult NewStart = tryBuildCapture(SemaRef, Start.get(), Captures);
5448   if (!NewStart.isUsable())
5449     return ExprError();
5450   if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
5451                                    VarRef.get()->getType())) {
5452     NewStart = SemaRef.PerformImplicitConversion(
5453         NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
5454         /*AllowExplicit=*/true);
5455     if (!NewStart.isUsable())
5456       return ExprError();
5457   }
5458 
5459   ExprResult Init =
5460       SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
5461   return Init;
5462 }
5463 
5464 /// Build 'VarRef = Start + Iter * Step'.
5465 static ExprResult buildCounterUpdate(
5466     Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
5467     ExprResult Start, ExprResult Iter, ExprResult Step, bool Subtract,
5468     llvm::MapVector<const Expr *, DeclRefExpr *> *Captures = nullptr) {
5469   // Add parentheses (for debugging purposes only).
5470   Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
5471   if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
5472       !Step.isUsable())
5473     return ExprError();
5474 
5475   ExprResult NewStep = Step;
5476   if (Captures)
5477     NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
5478   if (NewStep.isInvalid())
5479     return ExprError();
5480   ExprResult Update =
5481       SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
5482   if (!Update.isUsable())
5483     return ExprError();
5484 
5485   // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
5486   // 'VarRef = Start (+|-) Iter * Step'.
5487   ExprResult NewStart = Start;
5488   if (Captures)
5489     NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
5490   if (NewStart.isInvalid())
5491     return ExprError();
5492 
5493   // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
5494   ExprResult SavedUpdate = Update;
5495   ExprResult UpdateVal;
5496   if (VarRef.get()->getType()->isOverloadableType() ||
5497       NewStart.get()->getType()->isOverloadableType() ||
5498       Update.get()->getType()->isOverloadableType()) {
5499     bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
5500     SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
5501     Update =
5502         SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
5503     if (Update.isUsable()) {
5504       UpdateVal =
5505           SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
5506                              VarRef.get(), SavedUpdate.get());
5507       if (UpdateVal.isUsable()) {
5508         Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
5509                                             UpdateVal.get());
5510       }
5511     }
5512     SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
5513   }
5514 
5515   // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
5516   if (!Update.isUsable() || !UpdateVal.isUsable()) {
5517     Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
5518                                 NewStart.get(), SavedUpdate.get());
5519     if (!Update.isUsable())
5520       return ExprError();
5521 
5522     if (!SemaRef.Context.hasSameType(Update.get()->getType(),
5523                                      VarRef.get()->getType())) {
5524       Update = SemaRef.PerformImplicitConversion(
5525           Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
5526       if (!Update.isUsable())
5527         return ExprError();
5528     }
5529 
5530     Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
5531   }
5532   return Update;
5533 }
5534 
5535 /// Convert integer expression \a E to make it have at least \a Bits
5536 /// bits.
5537 static ExprResult widenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
5538   if (E == nullptr)
5539     return ExprError();
5540   ASTContext &C = SemaRef.Context;
5541   QualType OldType = E->getType();
5542   unsigned HasBits = C.getTypeSize(OldType);
5543   if (HasBits >= Bits)
5544     return ExprResult(E);
5545   // OK to convert to signed, because new type has more bits than old.
5546   QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
5547   return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
5548                                            true);
5549 }
5550 
5551 /// Check if the given expression \a E is a constant integer that fits
5552 /// into \a Bits bits.
5553 static bool fitsInto(unsigned Bits, bool Signed, const Expr *E, Sema &SemaRef) {
5554   if (E == nullptr)
5555     return false;
5556   llvm::APSInt Result;
5557   if (E->isIntegerConstantExpr(Result, SemaRef.Context))
5558     return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
5559   return false;
5560 }
5561 
5562 /// Build preinits statement for the given declarations.
5563 static Stmt *buildPreInits(ASTContext &Context,
5564                            MutableArrayRef<Decl *> PreInits) {
5565   if (!PreInits.empty()) {
5566     return new (Context) DeclStmt(
5567         DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
5568         SourceLocation(), SourceLocation());
5569   }
5570   return nullptr;
5571 }
5572 
5573 /// Build preinits statement for the given declarations.
5574 static Stmt *
5575 buildPreInits(ASTContext &Context,
5576               const llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
5577   if (!Captures.empty()) {
5578     SmallVector<Decl *, 16> PreInits;
5579     for (const auto &Pair : Captures)
5580       PreInits.push_back(Pair.second->getDecl());
5581     return buildPreInits(Context, PreInits);
5582   }
5583   return nullptr;
5584 }
5585 
5586 /// Build postupdate expression for the given list of postupdates expressions.
5587 static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
5588   Expr *PostUpdate = nullptr;
5589   if (!PostUpdates.empty()) {
5590     for (Expr *E : PostUpdates) {
5591       Expr *ConvE = S.BuildCStyleCastExpr(
5592                          E->getExprLoc(),
5593                          S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
5594                          E->getExprLoc(), E)
5595                         .get();
5596       PostUpdate = PostUpdate
5597                        ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
5598                                               PostUpdate, ConvE)
5599                              .get()
5600                        : ConvE;
5601     }
5602   }
5603   return PostUpdate;
5604 }
5605 
5606 /// Called on a for stmt to check itself and nested loops (if any).
5607 /// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
5608 /// number of collapsed loops otherwise.
5609 static unsigned
5610 checkOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
5611                 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
5612                 DSAStackTy &DSA,
5613                 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
5614                 OMPLoopDirective::HelperExprs &Built) {
5615   unsigned NestedLoopCount = 1;
5616   if (CollapseLoopCountExpr) {
5617     // Found 'collapse' clause - calculate collapse number.
5618     Expr::EvalResult Result;
5619     if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
5620       NestedLoopCount = Result.Val.getInt().getLimitedValue();
5621   }
5622   unsigned OrderedLoopCount = 1;
5623   if (OrderedLoopCountExpr) {
5624     // Found 'ordered' clause - calculate collapse number.
5625     Expr::EvalResult EVResult;
5626     if (OrderedLoopCountExpr->EvaluateAsInt(EVResult, SemaRef.getASTContext())) {
5627       llvm::APSInt Result = EVResult.Val.getInt();
5628       if (Result.getLimitedValue() < NestedLoopCount) {
5629         SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
5630                      diag::err_omp_wrong_ordered_loop_count)
5631             << OrderedLoopCountExpr->getSourceRange();
5632         SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
5633                      diag::note_collapse_loop_count)
5634             << CollapseLoopCountExpr->getSourceRange();
5635       }
5636       OrderedLoopCount = Result.getLimitedValue();
5637     }
5638   }
5639   // This is helper routine for loop directives (e.g., 'for', 'simd',
5640   // 'for simd', etc.).
5641   llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
5642   SmallVector<LoopIterationSpace, 4> IterSpaces(
5643       std::max(OrderedLoopCount, NestedLoopCount));
5644   Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
5645   for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
5646     if (checkOpenMPIterationSpace(
5647             DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
5648             std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
5649             OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces[Cnt],
5650             Captures))
5651       return 0;
5652     // Move on to the next nested for loop, or to the loop body.
5653     // OpenMP [2.8.1, simd construct, Restrictions]
5654     // All loops associated with the construct must be perfectly nested; that
5655     // is, there must be no intervening code nor any OpenMP directive between
5656     // any two loops.
5657     CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
5658   }
5659   for (unsigned Cnt = NestedLoopCount; Cnt < OrderedLoopCount; ++Cnt) {
5660     if (checkOpenMPIterationSpace(
5661             DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
5662             std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
5663             OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces[Cnt],
5664             Captures))
5665       return 0;
5666     if (Cnt > 0 && IterSpaces[Cnt].CounterVar) {
5667       // Handle initialization of captured loop iterator variables.
5668       auto *DRE = cast<DeclRefExpr>(IterSpaces[Cnt].CounterVar);
5669       if (isa<OMPCapturedExprDecl>(DRE->getDecl())) {
5670         Captures[DRE] = DRE;
5671       }
5672     }
5673     // Move on to the next nested for loop, or to the loop body.
5674     // OpenMP [2.8.1, simd construct, Restrictions]
5675     // All loops associated with the construct must be perfectly nested; that
5676     // is, there must be no intervening code nor any OpenMP directive between
5677     // any two loops.
5678     CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
5679   }
5680 
5681   Built.clear(/* size */ NestedLoopCount);
5682 
5683   if (SemaRef.CurContext->isDependentContext())
5684     return NestedLoopCount;
5685 
5686   // An example of what is generated for the following code:
5687   //
5688   //   #pragma omp simd collapse(2) ordered(2)
5689   //   for (i = 0; i < NI; ++i)
5690   //     for (k = 0; k < NK; ++k)
5691   //       for (j = J0; j < NJ; j+=2) {
5692   //         <loop body>
5693   //       }
5694   //
5695   // We generate the code below.
5696   // Note: the loop body may be outlined in CodeGen.
5697   // Note: some counters may be C++ classes, operator- is used to find number of
5698   // iterations and operator+= to calculate counter value.
5699   // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
5700   // or i64 is currently supported).
5701   //
5702   //   #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
5703   //   for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
5704   //     .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
5705   //     .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
5706   //     // similar updates for vars in clauses (e.g. 'linear')
5707   //     <loop body (using local i and j)>
5708   //   }
5709   //   i = NI; // assign final values of counters
5710   //   j = NJ;
5711   //
5712 
5713   // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
5714   // the iteration counts of the collapsed for loops.
5715   // Precondition tests if there is at least one iteration (all conditions are
5716   // true).
5717   auto PreCond = ExprResult(IterSpaces[0].PreCond);
5718   Expr *N0 = IterSpaces[0].NumIterations;
5719   ExprResult LastIteration32 =
5720       widenIterationCount(/*Bits=*/32,
5721                           SemaRef
5722                               .PerformImplicitConversion(
5723                                   N0->IgnoreImpCasts(), N0->getType(),
5724                                   Sema::AA_Converting, /*AllowExplicit=*/true)
5725                               .get(),
5726                           SemaRef);
5727   ExprResult LastIteration64 = widenIterationCount(
5728       /*Bits=*/64,
5729       SemaRef
5730           .PerformImplicitConversion(N0->IgnoreImpCasts(), N0->getType(),
5731                                      Sema::AA_Converting,
5732                                      /*AllowExplicit=*/true)
5733           .get(),
5734       SemaRef);
5735 
5736   if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
5737     return NestedLoopCount;
5738 
5739   ASTContext &C = SemaRef.Context;
5740   bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
5741 
5742   Scope *CurScope = DSA.getCurScope();
5743   for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
5744     if (PreCond.isUsable()) {
5745       PreCond =
5746           SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
5747                              PreCond.get(), IterSpaces[Cnt].PreCond);
5748     }
5749     Expr *N = IterSpaces[Cnt].NumIterations;
5750     SourceLocation Loc = N->getExprLoc();
5751     AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
5752     if (LastIteration32.isUsable())
5753       LastIteration32 = SemaRef.BuildBinOp(
5754           CurScope, Loc, BO_Mul, LastIteration32.get(),
5755           SemaRef
5756               .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
5757                                          Sema::AA_Converting,
5758                                          /*AllowExplicit=*/true)
5759               .get());
5760     if (LastIteration64.isUsable())
5761       LastIteration64 = SemaRef.BuildBinOp(
5762           CurScope, Loc, BO_Mul, LastIteration64.get(),
5763           SemaRef
5764               .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
5765                                          Sema::AA_Converting,
5766                                          /*AllowExplicit=*/true)
5767               .get());
5768   }
5769 
5770   // Choose either the 32-bit or 64-bit version.
5771   ExprResult LastIteration = LastIteration64;
5772   if (SemaRef.getLangOpts().OpenMPOptimisticCollapse ||
5773       (LastIteration32.isUsable() &&
5774        C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
5775        (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
5776         fitsInto(
5777             /*Bits=*/32,
5778             LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
5779             LastIteration64.get(), SemaRef))))
5780     LastIteration = LastIteration32;
5781   QualType VType = LastIteration.get()->getType();
5782   QualType RealVType = VType;
5783   QualType StrideVType = VType;
5784   if (isOpenMPTaskLoopDirective(DKind)) {
5785     VType =
5786         SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
5787     StrideVType =
5788         SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
5789   }
5790 
5791   if (!LastIteration.isUsable())
5792     return 0;
5793 
5794   // Save the number of iterations.
5795   ExprResult NumIterations = LastIteration;
5796   {
5797     LastIteration = SemaRef.BuildBinOp(
5798         CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
5799         LastIteration.get(),
5800         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
5801     if (!LastIteration.isUsable())
5802       return 0;
5803   }
5804 
5805   // Calculate the last iteration number beforehand instead of doing this on
5806   // each iteration. Do not do this if the number of iterations may be kfold-ed.
5807   llvm::APSInt Result;
5808   bool IsConstant =
5809       LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
5810   ExprResult CalcLastIteration;
5811   if (!IsConstant) {
5812     ExprResult SaveRef =
5813         tryBuildCapture(SemaRef, LastIteration.get(), Captures);
5814     LastIteration = SaveRef;
5815 
5816     // Prepare SaveRef + 1.
5817     NumIterations = SemaRef.BuildBinOp(
5818         CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
5819         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
5820     if (!NumIterations.isUsable())
5821       return 0;
5822   }
5823 
5824   SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
5825 
5826   // Build variables passed into runtime, necessary for worksharing directives.
5827   ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
5828   if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
5829       isOpenMPDistributeDirective(DKind)) {
5830     // Lower bound variable, initialized with zero.
5831     VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
5832     LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
5833     SemaRef.AddInitializerToDecl(LBDecl,
5834                                  SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
5835                                  /*DirectInit*/ false);
5836 
5837     // Upper bound variable, initialized with last iteration number.
5838     VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
5839     UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
5840     SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
5841                                  /*DirectInit*/ false);
5842 
5843     // A 32-bit variable-flag where runtime returns 1 for the last iteration.
5844     // This will be used to implement clause 'lastprivate'.
5845     QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
5846     VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
5847     IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
5848     SemaRef.AddInitializerToDecl(ILDecl,
5849                                  SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
5850                                  /*DirectInit*/ false);
5851 
5852     // Stride variable returned by runtime (we initialize it to 1 by default).
5853     VarDecl *STDecl =
5854         buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
5855     ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
5856     SemaRef.AddInitializerToDecl(STDecl,
5857                                  SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
5858                                  /*DirectInit*/ false);
5859 
5860     // Build expression: UB = min(UB, LastIteration)
5861     // It is necessary for CodeGen of directives with static scheduling.
5862     ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
5863                                                 UB.get(), LastIteration.get());
5864     ExprResult CondOp = SemaRef.ActOnConditionalOp(
5865         LastIteration.get()->getExprLoc(), InitLoc, IsUBGreater.get(),
5866         LastIteration.get(), UB.get());
5867     EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
5868                              CondOp.get());
5869     EUB = SemaRef.ActOnFinishFullExpr(EUB.get(), /*DiscardedValue*/ false);
5870 
5871     // If we have a combined directive that combines 'distribute', 'for' or
5872     // 'simd' we need to be able to access the bounds of the schedule of the
5873     // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
5874     // by scheduling 'distribute' have to be passed to the schedule of 'for'.
5875     if (isOpenMPLoopBoundSharingDirective(DKind)) {
5876       // Lower bound variable, initialized with zero.
5877       VarDecl *CombLBDecl =
5878           buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
5879       CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
5880       SemaRef.AddInitializerToDecl(
5881           CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
5882           /*DirectInit*/ false);
5883 
5884       // Upper bound variable, initialized with last iteration number.
5885       VarDecl *CombUBDecl =
5886           buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
5887       CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
5888       SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
5889                                    /*DirectInit*/ false);
5890 
5891       ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
5892           CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
5893       ExprResult CombCondOp =
5894           SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
5895                                      LastIteration.get(), CombUB.get());
5896       CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
5897                                    CombCondOp.get());
5898       CombEUB =
5899           SemaRef.ActOnFinishFullExpr(CombEUB.get(), /*DiscardedValue*/ false);
5900 
5901       const CapturedDecl *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
5902       // We expect to have at least 2 more parameters than the 'parallel'
5903       // directive does - the lower and upper bounds of the previous schedule.
5904       assert(CD->getNumParams() >= 4 &&
5905              "Unexpected number of parameters in loop combined directive");
5906 
5907       // Set the proper type for the bounds given what we learned from the
5908       // enclosed loops.
5909       ImplicitParamDecl *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
5910       ImplicitParamDecl *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
5911 
5912       // Previous lower and upper bounds are obtained from the region
5913       // parameters.
5914       PrevLB =
5915           buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
5916       PrevUB =
5917           buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
5918     }
5919   }
5920 
5921   // Build the iteration variable and its initialization before loop.
5922   ExprResult IV;
5923   ExprResult Init, CombInit;
5924   {
5925     VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
5926     IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
5927     Expr *RHS =
5928         (isOpenMPWorksharingDirective(DKind) ||
5929          isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
5930             ? LB.get()
5931             : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
5932     Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
5933     Init = SemaRef.ActOnFinishFullExpr(Init.get(), /*DiscardedValue*/ false);
5934 
5935     if (isOpenMPLoopBoundSharingDirective(DKind)) {
5936       Expr *CombRHS =
5937           (isOpenMPWorksharingDirective(DKind) ||
5938            isOpenMPTaskLoopDirective(DKind) ||
5939            isOpenMPDistributeDirective(DKind))
5940               ? CombLB.get()
5941               : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
5942       CombInit =
5943           SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
5944       CombInit =
5945           SemaRef.ActOnFinishFullExpr(CombInit.get(), /*DiscardedValue*/ false);
5946     }
5947   }
5948 
5949   bool UseStrictCompare =
5950       RealVType->hasUnsignedIntegerRepresentation() &&
5951       llvm::all_of(IterSpaces, [](const LoopIterationSpace &LIS) {
5952         return LIS.IsStrictCompare;
5953       });
5954   // Loop condition (IV < NumIterations) or (IV <= UB or IV < UB + 1 (for
5955   // unsigned IV)) for worksharing loops.
5956   SourceLocation CondLoc = AStmt->getBeginLoc();
5957   Expr *BoundUB = UB.get();
5958   if (UseStrictCompare) {
5959     BoundUB =
5960         SemaRef
5961             .BuildBinOp(CurScope, CondLoc, BO_Add, BoundUB,
5962                         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
5963             .get();
5964     BoundUB =
5965         SemaRef.ActOnFinishFullExpr(BoundUB, /*DiscardedValue*/ false).get();
5966   }
5967   ExprResult Cond =
5968       (isOpenMPWorksharingDirective(DKind) ||
5969        isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
5970           ? SemaRef.BuildBinOp(CurScope, CondLoc,
5971                                UseStrictCompare ? BO_LT : BO_LE, IV.get(),
5972                                BoundUB)
5973           : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
5974                                NumIterations.get());
5975   ExprResult CombDistCond;
5976   if (isOpenMPLoopBoundSharingDirective(DKind)) {
5977     CombDistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
5978                                       NumIterations.get());
5979   }
5980 
5981   ExprResult CombCond;
5982   if (isOpenMPLoopBoundSharingDirective(DKind)) {
5983     Expr *BoundCombUB = CombUB.get();
5984     if (UseStrictCompare) {
5985       BoundCombUB =
5986           SemaRef
5987               .BuildBinOp(
5988                   CurScope, CondLoc, BO_Add, BoundCombUB,
5989                   SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
5990               .get();
5991       BoundCombUB =
5992           SemaRef.ActOnFinishFullExpr(BoundCombUB, /*DiscardedValue*/ false)
5993               .get();
5994     }
5995     CombCond =
5996         SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
5997                            IV.get(), BoundCombUB);
5998   }
5999   // Loop increment (IV = IV + 1)
6000   SourceLocation IncLoc = AStmt->getBeginLoc();
6001   ExprResult Inc =
6002       SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
6003                          SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
6004   if (!Inc.isUsable())
6005     return 0;
6006   Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
6007   Inc = SemaRef.ActOnFinishFullExpr(Inc.get(), /*DiscardedValue*/ false);
6008   if (!Inc.isUsable())
6009     return 0;
6010 
6011   // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
6012   // Used for directives with static scheduling.
6013   // In combined construct, add combined version that use CombLB and CombUB
6014   // base variables for the update
6015   ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
6016   if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
6017       isOpenMPDistributeDirective(DKind)) {
6018     // LB + ST
6019     NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
6020     if (!NextLB.isUsable())
6021       return 0;
6022     // LB = LB + ST
6023     NextLB =
6024         SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
6025     NextLB =
6026         SemaRef.ActOnFinishFullExpr(NextLB.get(), /*DiscardedValue*/ false);
6027     if (!NextLB.isUsable())
6028       return 0;
6029     // UB + ST
6030     NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
6031     if (!NextUB.isUsable())
6032       return 0;
6033     // UB = UB + ST
6034     NextUB =
6035         SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
6036     NextUB =
6037         SemaRef.ActOnFinishFullExpr(NextUB.get(), /*DiscardedValue*/ false);
6038     if (!NextUB.isUsable())
6039       return 0;
6040     if (isOpenMPLoopBoundSharingDirective(DKind)) {
6041       CombNextLB =
6042           SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
6043       if (!NextLB.isUsable())
6044         return 0;
6045       // LB = LB + ST
6046       CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
6047                                       CombNextLB.get());
6048       CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get(),
6049                                                /*DiscardedValue*/ false);
6050       if (!CombNextLB.isUsable())
6051         return 0;
6052       // UB + ST
6053       CombNextUB =
6054           SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
6055       if (!CombNextUB.isUsable())
6056         return 0;
6057       // UB = UB + ST
6058       CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
6059                                       CombNextUB.get());
6060       CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get(),
6061                                                /*DiscardedValue*/ false);
6062       if (!CombNextUB.isUsable())
6063         return 0;
6064     }
6065   }
6066 
6067   // Create increment expression for distribute loop when combined in a same
6068   // directive with for as IV = IV + ST; ensure upper bound expression based
6069   // on PrevUB instead of NumIterations - used to implement 'for' when found
6070   // in combination with 'distribute', like in 'distribute parallel for'
6071   SourceLocation DistIncLoc = AStmt->getBeginLoc();
6072   ExprResult DistCond, DistInc, PrevEUB, ParForInDistCond;
6073   if (isOpenMPLoopBoundSharingDirective(DKind)) {
6074     DistCond = SemaRef.BuildBinOp(
6075         CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE, IV.get(), BoundUB);
6076     assert(DistCond.isUsable() && "distribute cond expr was not built");
6077 
6078     DistInc =
6079         SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
6080     assert(DistInc.isUsable() && "distribute inc expr was not built");
6081     DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
6082                                  DistInc.get());
6083     DistInc =
6084         SemaRef.ActOnFinishFullExpr(DistInc.get(), /*DiscardedValue*/ false);
6085     assert(DistInc.isUsable() && "distribute inc expr was not built");
6086 
6087     // Build expression: UB = min(UB, prevUB) for #for in composite or combined
6088     // construct
6089     SourceLocation DistEUBLoc = AStmt->getBeginLoc();
6090     ExprResult IsUBGreater =
6091         SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get());
6092     ExprResult CondOp = SemaRef.ActOnConditionalOp(
6093         DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get());
6094     PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
6095                                  CondOp.get());
6096     PrevEUB =
6097         SemaRef.ActOnFinishFullExpr(PrevEUB.get(), /*DiscardedValue*/ false);
6098 
6099     // Build IV <= PrevUB or IV < PrevUB + 1 for unsigned IV to be used in
6100     // parallel for is in combination with a distribute directive with
6101     // schedule(static, 1)
6102     Expr *BoundPrevUB = PrevUB.get();
6103     if (UseStrictCompare) {
6104       BoundPrevUB =
6105           SemaRef
6106               .BuildBinOp(
6107                   CurScope, CondLoc, BO_Add, BoundPrevUB,
6108                   SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
6109               .get();
6110       BoundPrevUB =
6111           SemaRef.ActOnFinishFullExpr(BoundPrevUB, /*DiscardedValue*/ false)
6112               .get();
6113     }
6114     ParForInDistCond =
6115         SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
6116                            IV.get(), BoundPrevUB);
6117   }
6118 
6119   // Build updates and final values of the loop counters.
6120   bool HasErrors = false;
6121   Built.Counters.resize(NestedLoopCount);
6122   Built.Inits.resize(NestedLoopCount);
6123   Built.Updates.resize(NestedLoopCount);
6124   Built.Finals.resize(NestedLoopCount);
6125   {
6126     // We implement the following algorithm for obtaining the
6127     // original loop iteration variable values based on the
6128     // value of the collapsed loop iteration variable IV.
6129     //
6130     // Let n+1 be the number of collapsed loops in the nest.
6131     // Iteration variables (I0, I1, .... In)
6132     // Iteration counts (N0, N1, ... Nn)
6133     //
6134     // Acc = IV;
6135     //
6136     // To compute Ik for loop k, 0 <= k <= n, generate:
6137     //    Prod = N(k+1) * N(k+2) * ... * Nn;
6138     //    Ik = Acc / Prod;
6139     //    Acc -= Ik * Prod;
6140     //
6141     ExprResult Acc = IV;
6142     for (unsigned int Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
6143       LoopIterationSpace &IS = IterSpaces[Cnt];
6144       SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
6145       ExprResult Iter;
6146 
6147       // Compute prod
6148       ExprResult Prod =
6149           SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
6150       for (unsigned int K = Cnt+1; K < NestedLoopCount; ++K)
6151         Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Prod.get(),
6152                                   IterSpaces[K].NumIterations);
6153 
6154       // Iter = Acc / Prod
6155       // If there is at least one more inner loop to avoid
6156       // multiplication by 1.
6157       if (Cnt + 1 < NestedLoopCount)
6158         Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div,
6159                                   Acc.get(), Prod.get());
6160       else
6161         Iter = Acc;
6162       if (!Iter.isUsable()) {
6163         HasErrors = true;
6164         break;
6165       }
6166 
6167       // Update Acc:
6168       // Acc -= Iter * Prod
6169       // Check if there is at least one more inner loop to avoid
6170       // multiplication by 1.
6171       if (Cnt + 1 < NestedLoopCount)
6172         Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul,
6173                                   Iter.get(), Prod.get());
6174       else
6175         Prod = Iter;
6176       Acc = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Sub,
6177                                Acc.get(), Prod.get());
6178 
6179       // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
6180       auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
6181       DeclRefExpr *CounterVar = buildDeclRefExpr(
6182           SemaRef, VD, IS.CounterVar->getType(), IS.CounterVar->getExprLoc(),
6183           /*RefersToCapture=*/true);
6184       ExprResult Init = buildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
6185                                          IS.CounterInit, Captures);
6186       if (!Init.isUsable()) {
6187         HasErrors = true;
6188         break;
6189       }
6190       ExprResult Update = buildCounterUpdate(
6191           SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
6192           IS.CounterStep, IS.Subtract, &Captures);
6193       if (!Update.isUsable()) {
6194         HasErrors = true;
6195         break;
6196       }
6197 
6198       // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
6199       ExprResult Final = buildCounterUpdate(
6200           SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
6201           IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures);
6202       if (!Final.isUsable()) {
6203         HasErrors = true;
6204         break;
6205       }
6206 
6207       if (!Update.isUsable() || !Final.isUsable()) {
6208         HasErrors = true;
6209         break;
6210       }
6211       // Save results
6212       Built.Counters[Cnt] = IS.CounterVar;
6213       Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
6214       Built.Inits[Cnt] = Init.get();
6215       Built.Updates[Cnt] = Update.get();
6216       Built.Finals[Cnt] = Final.get();
6217     }
6218   }
6219 
6220   if (HasErrors)
6221     return 0;
6222 
6223   // Save results
6224   Built.IterationVarRef = IV.get();
6225   Built.LastIteration = LastIteration.get();
6226   Built.NumIterations = NumIterations.get();
6227   Built.CalcLastIteration = SemaRef
6228                                 .ActOnFinishFullExpr(CalcLastIteration.get(),
6229                                                      /*DiscardedValue*/ false)
6230                                 .get();
6231   Built.PreCond = PreCond.get();
6232   Built.PreInits = buildPreInits(C, Captures);
6233   Built.Cond = Cond.get();
6234   Built.Init = Init.get();
6235   Built.Inc = Inc.get();
6236   Built.LB = LB.get();
6237   Built.UB = UB.get();
6238   Built.IL = IL.get();
6239   Built.ST = ST.get();
6240   Built.EUB = EUB.get();
6241   Built.NLB = NextLB.get();
6242   Built.NUB = NextUB.get();
6243   Built.PrevLB = PrevLB.get();
6244   Built.PrevUB = PrevUB.get();
6245   Built.DistInc = DistInc.get();
6246   Built.PrevEUB = PrevEUB.get();
6247   Built.DistCombinedFields.LB = CombLB.get();
6248   Built.DistCombinedFields.UB = CombUB.get();
6249   Built.DistCombinedFields.EUB = CombEUB.get();
6250   Built.DistCombinedFields.Init = CombInit.get();
6251   Built.DistCombinedFields.Cond = CombCond.get();
6252   Built.DistCombinedFields.NLB = CombNextLB.get();
6253   Built.DistCombinedFields.NUB = CombNextUB.get();
6254   Built.DistCombinedFields.DistCond = CombDistCond.get();
6255   Built.DistCombinedFields.ParForInDistCond = ParForInDistCond.get();
6256 
6257   return NestedLoopCount;
6258 }
6259 
6260 static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
6261   auto CollapseClauses =
6262       OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
6263   if (CollapseClauses.begin() != CollapseClauses.end())
6264     return (*CollapseClauses.begin())->getNumForLoops();
6265   return nullptr;
6266 }
6267 
6268 static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
6269   auto OrderedClauses =
6270       OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
6271   if (OrderedClauses.begin() != OrderedClauses.end())
6272     return (*OrderedClauses.begin())->getNumForLoops();
6273   return nullptr;
6274 }
6275 
6276 static bool checkSimdlenSafelenSpecified(Sema &S,
6277                                          const ArrayRef<OMPClause *> Clauses) {
6278   const OMPSafelenClause *Safelen = nullptr;
6279   const OMPSimdlenClause *Simdlen = nullptr;
6280 
6281   for (const OMPClause *Clause : Clauses) {
6282     if (Clause->getClauseKind() == OMPC_safelen)
6283       Safelen = cast<OMPSafelenClause>(Clause);
6284     else if (Clause->getClauseKind() == OMPC_simdlen)
6285       Simdlen = cast<OMPSimdlenClause>(Clause);
6286     if (Safelen && Simdlen)
6287       break;
6288   }
6289 
6290   if (Simdlen && Safelen) {
6291     const Expr *SimdlenLength = Simdlen->getSimdlen();
6292     const Expr *SafelenLength = Safelen->getSafelen();
6293     if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
6294         SimdlenLength->isInstantiationDependent() ||
6295         SimdlenLength->containsUnexpandedParameterPack())
6296       return false;
6297     if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
6298         SafelenLength->isInstantiationDependent() ||
6299         SafelenLength->containsUnexpandedParameterPack())
6300       return false;
6301     Expr::EvalResult SimdlenResult, SafelenResult;
6302     SimdlenLength->EvaluateAsInt(SimdlenResult, S.Context);
6303     SafelenLength->EvaluateAsInt(SafelenResult, S.Context);
6304     llvm::APSInt SimdlenRes = SimdlenResult.Val.getInt();
6305     llvm::APSInt SafelenRes = SafelenResult.Val.getInt();
6306     // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
6307     // If both simdlen and safelen clauses are specified, the value of the
6308     // simdlen parameter must be less than or equal to the value of the safelen
6309     // parameter.
6310     if (SimdlenRes > SafelenRes) {
6311       S.Diag(SimdlenLength->getExprLoc(),
6312              diag::err_omp_wrong_simdlen_safelen_values)
6313           << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
6314       return true;
6315     }
6316   }
6317   return false;
6318 }
6319 
6320 StmtResult
6321 Sema::ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
6322                                SourceLocation StartLoc, SourceLocation EndLoc,
6323                                VarsWithInheritedDSAType &VarsWithImplicitDSA) {
6324   if (!AStmt)
6325     return StmtError();
6326 
6327   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6328   OMPLoopDirective::HelperExprs B;
6329   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6330   // define the nested loops number.
6331   unsigned NestedLoopCount = checkOpenMPLoop(
6332       OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
6333       AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
6334   if (NestedLoopCount == 0)
6335     return StmtError();
6336 
6337   assert((CurContext->isDependentContext() || B.builtAll()) &&
6338          "omp simd loop exprs were not built");
6339 
6340   if (!CurContext->isDependentContext()) {
6341     // Finalize the clauses that need pre-built expressions for CodeGen.
6342     for (OMPClause *C : Clauses) {
6343       if (auto *LC = dyn_cast<OMPLinearClause>(C))
6344         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6345                                      B.NumIterations, *this, CurScope,
6346                                      DSAStack))
6347           return StmtError();
6348     }
6349   }
6350 
6351   if (checkSimdlenSafelenSpecified(*this, Clauses))
6352     return StmtError();
6353 
6354   setFunctionHasBranchProtectedScope();
6355   return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
6356                                   Clauses, AStmt, B);
6357 }
6358 
6359 StmtResult
6360 Sema::ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
6361                               SourceLocation StartLoc, SourceLocation EndLoc,
6362                               VarsWithInheritedDSAType &VarsWithImplicitDSA) {
6363   if (!AStmt)
6364     return StmtError();
6365 
6366   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6367   OMPLoopDirective::HelperExprs B;
6368   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6369   // define the nested loops number.
6370   unsigned NestedLoopCount = checkOpenMPLoop(
6371       OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
6372       AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
6373   if (NestedLoopCount == 0)
6374     return StmtError();
6375 
6376   assert((CurContext->isDependentContext() || B.builtAll()) &&
6377          "omp for loop exprs were not built");
6378 
6379   if (!CurContext->isDependentContext()) {
6380     // Finalize the clauses that need pre-built expressions for CodeGen.
6381     for (OMPClause *C : Clauses) {
6382       if (auto *LC = dyn_cast<OMPLinearClause>(C))
6383         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6384                                      B.NumIterations, *this, CurScope,
6385                                      DSAStack))
6386           return StmtError();
6387     }
6388   }
6389 
6390   setFunctionHasBranchProtectedScope();
6391   return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
6392                                  Clauses, AStmt, B, DSAStack->isCancelRegion());
6393 }
6394 
6395 StmtResult Sema::ActOnOpenMPForSimdDirective(
6396     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6397     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
6398   if (!AStmt)
6399     return StmtError();
6400 
6401   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6402   OMPLoopDirective::HelperExprs B;
6403   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6404   // define the nested loops number.
6405   unsigned NestedLoopCount =
6406       checkOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
6407                       getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6408                       VarsWithImplicitDSA, B);
6409   if (NestedLoopCount == 0)
6410     return StmtError();
6411 
6412   assert((CurContext->isDependentContext() || B.builtAll()) &&
6413          "omp for simd loop exprs were not built");
6414 
6415   if (!CurContext->isDependentContext()) {
6416     // Finalize the clauses that need pre-built expressions for CodeGen.
6417     for (OMPClause *C : Clauses) {
6418       if (auto *LC = dyn_cast<OMPLinearClause>(C))
6419         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6420                                      B.NumIterations, *this, CurScope,
6421                                      DSAStack))
6422           return StmtError();
6423     }
6424   }
6425 
6426   if (checkSimdlenSafelenSpecified(*this, Clauses))
6427     return StmtError();
6428 
6429   setFunctionHasBranchProtectedScope();
6430   return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
6431                                      Clauses, AStmt, B);
6432 }
6433 
6434 StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
6435                                               Stmt *AStmt,
6436                                               SourceLocation StartLoc,
6437                                               SourceLocation EndLoc) {
6438   if (!AStmt)
6439     return StmtError();
6440 
6441   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6442   auto BaseStmt = AStmt;
6443   while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
6444     BaseStmt = CS->getCapturedStmt();
6445   if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
6446     auto S = C->children();
6447     if (S.begin() == S.end())
6448       return StmtError();
6449     // All associated statements must be '#pragma omp section' except for
6450     // the first one.
6451     for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
6452       if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
6453         if (SectionStmt)
6454           Diag(SectionStmt->getBeginLoc(),
6455                diag::err_omp_sections_substmt_not_section);
6456         return StmtError();
6457       }
6458       cast<OMPSectionDirective>(SectionStmt)
6459           ->setHasCancel(DSAStack->isCancelRegion());
6460     }
6461   } else {
6462     Diag(AStmt->getBeginLoc(), diag::err_omp_sections_not_compound_stmt);
6463     return StmtError();
6464   }
6465 
6466   setFunctionHasBranchProtectedScope();
6467 
6468   return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
6469                                       DSAStack->isCancelRegion());
6470 }
6471 
6472 StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
6473                                              SourceLocation StartLoc,
6474                                              SourceLocation EndLoc) {
6475   if (!AStmt)
6476     return StmtError();
6477 
6478   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6479 
6480   setFunctionHasBranchProtectedScope();
6481   DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
6482 
6483   return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
6484                                      DSAStack->isCancelRegion());
6485 }
6486 
6487 StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
6488                                             Stmt *AStmt,
6489                                             SourceLocation StartLoc,
6490                                             SourceLocation EndLoc) {
6491   if (!AStmt)
6492     return StmtError();
6493 
6494   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6495 
6496   setFunctionHasBranchProtectedScope();
6497 
6498   // OpenMP [2.7.3, single Construct, Restrictions]
6499   // The copyprivate clause must not be used with the nowait clause.
6500   const OMPClause *Nowait = nullptr;
6501   const OMPClause *Copyprivate = nullptr;
6502   for (const OMPClause *Clause : Clauses) {
6503     if (Clause->getClauseKind() == OMPC_nowait)
6504       Nowait = Clause;
6505     else if (Clause->getClauseKind() == OMPC_copyprivate)
6506       Copyprivate = Clause;
6507     if (Copyprivate && Nowait) {
6508       Diag(Copyprivate->getBeginLoc(),
6509            diag::err_omp_single_copyprivate_with_nowait);
6510       Diag(Nowait->getBeginLoc(), diag::note_omp_nowait_clause_here);
6511       return StmtError();
6512     }
6513   }
6514 
6515   return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
6516 }
6517 
6518 StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
6519                                             SourceLocation StartLoc,
6520                                             SourceLocation EndLoc) {
6521   if (!AStmt)
6522     return StmtError();
6523 
6524   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6525 
6526   setFunctionHasBranchProtectedScope();
6527 
6528   return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
6529 }
6530 
6531 StmtResult Sema::ActOnOpenMPCriticalDirective(
6532     const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
6533     Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
6534   if (!AStmt)
6535     return StmtError();
6536 
6537   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6538 
6539   bool ErrorFound = false;
6540   llvm::APSInt Hint;
6541   SourceLocation HintLoc;
6542   bool DependentHint = false;
6543   for (const OMPClause *C : Clauses) {
6544     if (C->getClauseKind() == OMPC_hint) {
6545       if (!DirName.getName()) {
6546         Diag(C->getBeginLoc(), diag::err_omp_hint_clause_no_name);
6547         ErrorFound = true;
6548       }
6549       Expr *E = cast<OMPHintClause>(C)->getHint();
6550       if (E->isTypeDependent() || E->isValueDependent() ||
6551           E->isInstantiationDependent()) {
6552         DependentHint = true;
6553       } else {
6554         Hint = E->EvaluateKnownConstInt(Context);
6555         HintLoc = C->getBeginLoc();
6556       }
6557     }
6558   }
6559   if (ErrorFound)
6560     return StmtError();
6561   const auto Pair = DSAStack->getCriticalWithHint(DirName);
6562   if (Pair.first && DirName.getName() && !DependentHint) {
6563     if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
6564       Diag(StartLoc, diag::err_omp_critical_with_hint);
6565       if (HintLoc.isValid())
6566         Diag(HintLoc, diag::note_omp_critical_hint_here)
6567             << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
6568       else
6569         Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
6570       if (const auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
6571         Diag(C->getBeginLoc(), diag::note_omp_critical_hint_here)
6572             << 1
6573             << C->getHint()->EvaluateKnownConstInt(Context).toString(
6574                    /*Radix=*/10, /*Signed=*/false);
6575       } else {
6576         Diag(Pair.first->getBeginLoc(), diag::note_omp_critical_no_hint) << 1;
6577       }
6578     }
6579   }
6580 
6581   setFunctionHasBranchProtectedScope();
6582 
6583   auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
6584                                            Clauses, AStmt);
6585   if (!Pair.first && DirName.getName() && !DependentHint)
6586     DSAStack->addCriticalWithHint(Dir, Hint);
6587   return Dir;
6588 }
6589 
6590 StmtResult Sema::ActOnOpenMPParallelForDirective(
6591     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6592     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
6593   if (!AStmt)
6594     return StmtError();
6595 
6596   auto *CS = cast<CapturedStmt>(AStmt);
6597   // 1.2.2 OpenMP Language Terminology
6598   // Structured block - An executable statement with a single entry at the
6599   // top and a single exit at the bottom.
6600   // The point of exit cannot be a branch out of the structured block.
6601   // longjmp() and throw() must not violate the entry/exit criteria.
6602   CS->getCapturedDecl()->setNothrow();
6603 
6604   OMPLoopDirective::HelperExprs B;
6605   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6606   // define the nested loops number.
6607   unsigned NestedLoopCount =
6608       checkOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
6609                       getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6610                       VarsWithImplicitDSA, B);
6611   if (NestedLoopCount == 0)
6612     return StmtError();
6613 
6614   assert((CurContext->isDependentContext() || B.builtAll()) &&
6615          "omp parallel for loop exprs were not built");
6616 
6617   if (!CurContext->isDependentContext()) {
6618     // Finalize the clauses that need pre-built expressions for CodeGen.
6619     for (OMPClause *C : Clauses) {
6620       if (auto *LC = dyn_cast<OMPLinearClause>(C))
6621         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6622                                      B.NumIterations, *this, CurScope,
6623                                      DSAStack))
6624           return StmtError();
6625     }
6626   }
6627 
6628   setFunctionHasBranchProtectedScope();
6629   return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
6630                                          NestedLoopCount, Clauses, AStmt, B,
6631                                          DSAStack->isCancelRegion());
6632 }
6633 
6634 StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
6635     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6636     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
6637   if (!AStmt)
6638     return StmtError();
6639 
6640   auto *CS = cast<CapturedStmt>(AStmt);
6641   // 1.2.2 OpenMP Language Terminology
6642   // Structured block - An executable statement with a single entry at the
6643   // top and a single exit at the bottom.
6644   // The point of exit cannot be a branch out of the structured block.
6645   // longjmp() and throw() must not violate the entry/exit criteria.
6646   CS->getCapturedDecl()->setNothrow();
6647 
6648   OMPLoopDirective::HelperExprs B;
6649   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6650   // define the nested loops number.
6651   unsigned NestedLoopCount =
6652       checkOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
6653                       getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6654                       VarsWithImplicitDSA, B);
6655   if (NestedLoopCount == 0)
6656     return StmtError();
6657 
6658   if (!CurContext->isDependentContext()) {
6659     // Finalize the clauses that need pre-built expressions for CodeGen.
6660     for (OMPClause *C : Clauses) {
6661       if (auto *LC = dyn_cast<OMPLinearClause>(C))
6662         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6663                                      B.NumIterations, *this, CurScope,
6664                                      DSAStack))
6665           return StmtError();
6666     }
6667   }
6668 
6669   if (checkSimdlenSafelenSpecified(*this, Clauses))
6670     return StmtError();
6671 
6672   setFunctionHasBranchProtectedScope();
6673   return OMPParallelForSimdDirective::Create(
6674       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6675 }
6676 
6677 StmtResult
6678 Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
6679                                            Stmt *AStmt, SourceLocation StartLoc,
6680                                            SourceLocation EndLoc) {
6681   if (!AStmt)
6682     return StmtError();
6683 
6684   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6685   auto BaseStmt = AStmt;
6686   while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
6687     BaseStmt = CS->getCapturedStmt();
6688   if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
6689     auto S = C->children();
6690     if (S.begin() == S.end())
6691       return StmtError();
6692     // All associated statements must be '#pragma omp section' except for
6693     // the first one.
6694     for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
6695       if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
6696         if (SectionStmt)
6697           Diag(SectionStmt->getBeginLoc(),
6698                diag::err_omp_parallel_sections_substmt_not_section);
6699         return StmtError();
6700       }
6701       cast<OMPSectionDirective>(SectionStmt)
6702           ->setHasCancel(DSAStack->isCancelRegion());
6703     }
6704   } else {
6705     Diag(AStmt->getBeginLoc(),
6706          diag::err_omp_parallel_sections_not_compound_stmt);
6707     return StmtError();
6708   }
6709 
6710   setFunctionHasBranchProtectedScope();
6711 
6712   return OMPParallelSectionsDirective::Create(
6713       Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
6714 }
6715 
6716 StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
6717                                           Stmt *AStmt, SourceLocation StartLoc,
6718                                           SourceLocation EndLoc) {
6719   if (!AStmt)
6720     return StmtError();
6721 
6722   auto *CS = cast<CapturedStmt>(AStmt);
6723   // 1.2.2 OpenMP Language Terminology
6724   // Structured block - An executable statement with a single entry at the
6725   // top and a single exit at the bottom.
6726   // The point of exit cannot be a branch out of the structured block.
6727   // longjmp() and throw() must not violate the entry/exit criteria.
6728   CS->getCapturedDecl()->setNothrow();
6729 
6730   setFunctionHasBranchProtectedScope();
6731 
6732   return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
6733                                   DSAStack->isCancelRegion());
6734 }
6735 
6736 StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
6737                                                SourceLocation EndLoc) {
6738   return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
6739 }
6740 
6741 StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
6742                                              SourceLocation EndLoc) {
6743   return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
6744 }
6745 
6746 StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
6747                                               SourceLocation EndLoc) {
6748   return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
6749 }
6750 
6751 StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
6752                                                Stmt *AStmt,
6753                                                SourceLocation StartLoc,
6754                                                SourceLocation EndLoc) {
6755   if (!AStmt)
6756     return StmtError();
6757 
6758   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6759 
6760   setFunctionHasBranchProtectedScope();
6761 
6762   return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses,
6763                                        AStmt,
6764                                        DSAStack->getTaskgroupReductionRef());
6765 }
6766 
6767 StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
6768                                            SourceLocation StartLoc,
6769                                            SourceLocation EndLoc) {
6770   assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
6771   return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
6772 }
6773 
6774 StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
6775                                              Stmt *AStmt,
6776                                              SourceLocation StartLoc,
6777                                              SourceLocation EndLoc) {
6778   const OMPClause *DependFound = nullptr;
6779   const OMPClause *DependSourceClause = nullptr;
6780   const OMPClause *DependSinkClause = nullptr;
6781   bool ErrorFound = false;
6782   const OMPThreadsClause *TC = nullptr;
6783   const OMPSIMDClause *SC = nullptr;
6784   for (const OMPClause *C : Clauses) {
6785     if (auto *DC = dyn_cast<OMPDependClause>(C)) {
6786       DependFound = C;
6787       if (DC->getDependencyKind() == OMPC_DEPEND_source) {
6788         if (DependSourceClause) {
6789           Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
6790               << getOpenMPDirectiveName(OMPD_ordered)
6791               << getOpenMPClauseName(OMPC_depend) << 2;
6792           ErrorFound = true;
6793         } else {
6794           DependSourceClause = C;
6795         }
6796         if (DependSinkClause) {
6797           Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
6798               << 0;
6799           ErrorFound = true;
6800         }
6801       } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
6802         if (DependSourceClause) {
6803           Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
6804               << 1;
6805           ErrorFound = true;
6806         }
6807         DependSinkClause = C;
6808       }
6809     } else if (C->getClauseKind() == OMPC_threads) {
6810       TC = cast<OMPThreadsClause>(C);
6811     } else if (C->getClauseKind() == OMPC_simd) {
6812       SC = cast<OMPSIMDClause>(C);
6813     }
6814   }
6815   if (!ErrorFound && !SC &&
6816       isOpenMPSimdDirective(DSAStack->getParentDirective())) {
6817     // OpenMP [2.8.1,simd Construct, Restrictions]
6818     // An ordered construct with the simd clause is the only OpenMP construct
6819     // that can appear in the simd region.
6820     Diag(StartLoc, diag::err_omp_prohibited_region_simd);
6821     ErrorFound = true;
6822   } else if (DependFound && (TC || SC)) {
6823     Diag(DependFound->getBeginLoc(), diag::err_omp_depend_clause_thread_simd)
6824         << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
6825     ErrorFound = true;
6826   } else if (DependFound && !DSAStack->getParentOrderedRegionParam().first) {
6827     Diag(DependFound->getBeginLoc(),
6828          diag::err_omp_ordered_directive_without_param);
6829     ErrorFound = true;
6830   } else if (TC || Clauses.empty()) {
6831     if (const Expr *Param = DSAStack->getParentOrderedRegionParam().first) {
6832       SourceLocation ErrLoc = TC ? TC->getBeginLoc() : StartLoc;
6833       Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
6834           << (TC != nullptr);
6835       Diag(Param->getBeginLoc(), diag::note_omp_ordered_param);
6836       ErrorFound = true;
6837     }
6838   }
6839   if ((!AStmt && !DependFound) || ErrorFound)
6840     return StmtError();
6841 
6842   if (AStmt) {
6843     assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6844 
6845     setFunctionHasBranchProtectedScope();
6846   }
6847 
6848   return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
6849 }
6850 
6851 namespace {
6852 /// Helper class for checking expression in 'omp atomic [update]'
6853 /// construct.
6854 class OpenMPAtomicUpdateChecker {
6855   /// Error results for atomic update expressions.
6856   enum ExprAnalysisErrorCode {
6857     /// A statement is not an expression statement.
6858     NotAnExpression,
6859     /// Expression is not builtin binary or unary operation.
6860     NotABinaryOrUnaryExpression,
6861     /// Unary operation is not post-/pre- increment/decrement operation.
6862     NotAnUnaryIncDecExpression,
6863     /// An expression is not of scalar type.
6864     NotAScalarType,
6865     /// A binary operation is not an assignment operation.
6866     NotAnAssignmentOp,
6867     /// RHS part of the binary operation is not a binary expression.
6868     NotABinaryExpression,
6869     /// RHS part is not additive/multiplicative/shift/biwise binary
6870     /// expression.
6871     NotABinaryOperator,
6872     /// RHS binary operation does not have reference to the updated LHS
6873     /// part.
6874     NotAnUpdateExpression,
6875     /// No errors is found.
6876     NoError
6877   };
6878   /// Reference to Sema.
6879   Sema &SemaRef;
6880   /// A location for note diagnostics (when error is found).
6881   SourceLocation NoteLoc;
6882   /// 'x' lvalue part of the source atomic expression.
6883   Expr *X;
6884   /// 'expr' rvalue part of the source atomic expression.
6885   Expr *E;
6886   /// Helper expression of the form
6887   /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
6888   /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
6889   Expr *UpdateExpr;
6890   /// Is 'x' a LHS in a RHS part of full update expression. It is
6891   /// important for non-associative operations.
6892   bool IsXLHSInRHSPart;
6893   BinaryOperatorKind Op;
6894   SourceLocation OpLoc;
6895   /// true if the source expression is a postfix unary operation, false
6896   /// if it is a prefix unary operation.
6897   bool IsPostfixUpdate;
6898 
6899 public:
6900   OpenMPAtomicUpdateChecker(Sema &SemaRef)
6901       : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
6902         IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
6903   /// Check specified statement that it is suitable for 'atomic update'
6904   /// constructs and extract 'x', 'expr' and Operation from the original
6905   /// expression. If DiagId and NoteId == 0, then only check is performed
6906   /// without error notification.
6907   /// \param DiagId Diagnostic which should be emitted if error is found.
6908   /// \param NoteId Diagnostic note for the main error message.
6909   /// \return true if statement is not an update expression, false otherwise.
6910   bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
6911   /// Return the 'x' lvalue part of the source atomic expression.
6912   Expr *getX() const { return X; }
6913   /// Return the 'expr' rvalue part of the source atomic expression.
6914   Expr *getExpr() const { return E; }
6915   /// Return the update expression used in calculation of the updated
6916   /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
6917   /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
6918   Expr *getUpdateExpr() const { return UpdateExpr; }
6919   /// Return true if 'x' is LHS in RHS part of full update expression,
6920   /// false otherwise.
6921   bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
6922 
6923   /// true if the source expression is a postfix unary operation, false
6924   /// if it is a prefix unary operation.
6925   bool isPostfixUpdate() const { return IsPostfixUpdate; }
6926 
6927 private:
6928   bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
6929                             unsigned NoteId = 0);
6930 };
6931 } // namespace
6932 
6933 bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
6934     BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
6935   ExprAnalysisErrorCode ErrorFound = NoError;
6936   SourceLocation ErrorLoc, NoteLoc;
6937   SourceRange ErrorRange, NoteRange;
6938   // Allowed constructs are:
6939   //  x = x binop expr;
6940   //  x = expr binop x;
6941   if (AtomicBinOp->getOpcode() == BO_Assign) {
6942     X = AtomicBinOp->getLHS();
6943     if (const auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
6944             AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
6945       if (AtomicInnerBinOp->isMultiplicativeOp() ||
6946           AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
6947           AtomicInnerBinOp->isBitwiseOp()) {
6948         Op = AtomicInnerBinOp->getOpcode();
6949         OpLoc = AtomicInnerBinOp->getOperatorLoc();
6950         Expr *LHS = AtomicInnerBinOp->getLHS();
6951         Expr *RHS = AtomicInnerBinOp->getRHS();
6952         llvm::FoldingSetNodeID XId, LHSId, RHSId;
6953         X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
6954                                           /*Canonical=*/true);
6955         LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
6956                                             /*Canonical=*/true);
6957         RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
6958                                             /*Canonical=*/true);
6959         if (XId == LHSId) {
6960           E = RHS;
6961           IsXLHSInRHSPart = true;
6962         } else if (XId == RHSId) {
6963           E = LHS;
6964           IsXLHSInRHSPart = false;
6965         } else {
6966           ErrorLoc = AtomicInnerBinOp->getExprLoc();
6967           ErrorRange = AtomicInnerBinOp->getSourceRange();
6968           NoteLoc = X->getExprLoc();
6969           NoteRange = X->getSourceRange();
6970           ErrorFound = NotAnUpdateExpression;
6971         }
6972       } else {
6973         ErrorLoc = AtomicInnerBinOp->getExprLoc();
6974         ErrorRange = AtomicInnerBinOp->getSourceRange();
6975         NoteLoc = AtomicInnerBinOp->getOperatorLoc();
6976         NoteRange = SourceRange(NoteLoc, NoteLoc);
6977         ErrorFound = NotABinaryOperator;
6978       }
6979     } else {
6980       NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
6981       NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
6982       ErrorFound = NotABinaryExpression;
6983     }
6984   } else {
6985     ErrorLoc = AtomicBinOp->getExprLoc();
6986     ErrorRange = AtomicBinOp->getSourceRange();
6987     NoteLoc = AtomicBinOp->getOperatorLoc();
6988     NoteRange = SourceRange(NoteLoc, NoteLoc);
6989     ErrorFound = NotAnAssignmentOp;
6990   }
6991   if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
6992     SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
6993     SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
6994     return true;
6995   }
6996   if (SemaRef.CurContext->isDependentContext())
6997     E = X = UpdateExpr = nullptr;
6998   return ErrorFound != NoError;
6999 }
7000 
7001 bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
7002                                                unsigned NoteId) {
7003   ExprAnalysisErrorCode ErrorFound = NoError;
7004   SourceLocation ErrorLoc, NoteLoc;
7005   SourceRange ErrorRange, NoteRange;
7006   // Allowed constructs are:
7007   //  x++;
7008   //  x--;
7009   //  ++x;
7010   //  --x;
7011   //  x binop= expr;
7012   //  x = x binop expr;
7013   //  x = expr binop x;
7014   if (auto *AtomicBody = dyn_cast<Expr>(S)) {
7015     AtomicBody = AtomicBody->IgnoreParenImpCasts();
7016     if (AtomicBody->getType()->isScalarType() ||
7017         AtomicBody->isInstantiationDependent()) {
7018       if (const auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
7019               AtomicBody->IgnoreParenImpCasts())) {
7020         // Check for Compound Assignment Operation
7021         Op = BinaryOperator::getOpForCompoundAssignment(
7022             AtomicCompAssignOp->getOpcode());
7023         OpLoc = AtomicCompAssignOp->getOperatorLoc();
7024         E = AtomicCompAssignOp->getRHS();
7025         X = AtomicCompAssignOp->getLHS()->IgnoreParens();
7026         IsXLHSInRHSPart = true;
7027       } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
7028                      AtomicBody->IgnoreParenImpCasts())) {
7029         // Check for Binary Operation
7030         if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
7031           return true;
7032       } else if (const auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
7033                      AtomicBody->IgnoreParenImpCasts())) {
7034         // Check for Unary Operation
7035         if (AtomicUnaryOp->isIncrementDecrementOp()) {
7036           IsPostfixUpdate = AtomicUnaryOp->isPostfix();
7037           Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
7038           OpLoc = AtomicUnaryOp->getOperatorLoc();
7039           X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
7040           E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
7041           IsXLHSInRHSPart = true;
7042         } else {
7043           ErrorFound = NotAnUnaryIncDecExpression;
7044           ErrorLoc = AtomicUnaryOp->getExprLoc();
7045           ErrorRange = AtomicUnaryOp->getSourceRange();
7046           NoteLoc = AtomicUnaryOp->getOperatorLoc();
7047           NoteRange = SourceRange(NoteLoc, NoteLoc);
7048         }
7049       } else if (!AtomicBody->isInstantiationDependent()) {
7050         ErrorFound = NotABinaryOrUnaryExpression;
7051         NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
7052         NoteRange = ErrorRange = AtomicBody->getSourceRange();
7053       }
7054     } else {
7055       ErrorFound = NotAScalarType;
7056       NoteLoc = ErrorLoc = AtomicBody->getBeginLoc();
7057       NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
7058     }
7059   } else {
7060     ErrorFound = NotAnExpression;
7061     NoteLoc = ErrorLoc = S->getBeginLoc();
7062     NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
7063   }
7064   if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
7065     SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
7066     SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
7067     return true;
7068   }
7069   if (SemaRef.CurContext->isDependentContext())
7070     E = X = UpdateExpr = nullptr;
7071   if (ErrorFound == NoError && E && X) {
7072     // Build an update expression of form 'OpaqueValueExpr(x) binop
7073     // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
7074     // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
7075     auto *OVEX = new (SemaRef.getASTContext())
7076         OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
7077     auto *OVEExpr = new (SemaRef.getASTContext())
7078         OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
7079     ExprResult Update =
7080         SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
7081                                    IsXLHSInRHSPart ? OVEExpr : OVEX);
7082     if (Update.isInvalid())
7083       return true;
7084     Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
7085                                                Sema::AA_Casting);
7086     if (Update.isInvalid())
7087       return true;
7088     UpdateExpr = Update.get();
7089   }
7090   return ErrorFound != NoError;
7091 }
7092 
7093 StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
7094                                             Stmt *AStmt,
7095                                             SourceLocation StartLoc,
7096                                             SourceLocation EndLoc) {
7097   if (!AStmt)
7098     return StmtError();
7099 
7100   auto *CS = cast<CapturedStmt>(AStmt);
7101   // 1.2.2 OpenMP Language Terminology
7102   // Structured block - An executable statement with a single entry at the
7103   // top and a single exit at the bottom.
7104   // The point of exit cannot be a branch out of the structured block.
7105   // longjmp() and throw() must not violate the entry/exit criteria.
7106   OpenMPClauseKind AtomicKind = OMPC_unknown;
7107   SourceLocation AtomicKindLoc;
7108   for (const OMPClause *C : Clauses) {
7109     if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
7110         C->getClauseKind() == OMPC_update ||
7111         C->getClauseKind() == OMPC_capture) {
7112       if (AtomicKind != OMPC_unknown) {
7113         Diag(C->getBeginLoc(), diag::err_omp_atomic_several_clauses)
7114             << SourceRange(C->getBeginLoc(), C->getEndLoc());
7115         Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
7116             << getOpenMPClauseName(AtomicKind);
7117       } else {
7118         AtomicKind = C->getClauseKind();
7119         AtomicKindLoc = C->getBeginLoc();
7120       }
7121     }
7122   }
7123 
7124   Stmt *Body = CS->getCapturedStmt();
7125   if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
7126     Body = EWC->getSubExpr();
7127 
7128   Expr *X = nullptr;
7129   Expr *V = nullptr;
7130   Expr *E = nullptr;
7131   Expr *UE = nullptr;
7132   bool IsXLHSInRHSPart = false;
7133   bool IsPostfixUpdate = false;
7134   // OpenMP [2.12.6, atomic Construct]
7135   // In the next expressions:
7136   // * x and v (as applicable) are both l-value expressions with scalar type.
7137   // * During the execution of an atomic region, multiple syntactic
7138   // occurrences of x must designate the same storage location.
7139   // * Neither of v and expr (as applicable) may access the storage location
7140   // designated by x.
7141   // * Neither of x and expr (as applicable) may access the storage location
7142   // designated by v.
7143   // * expr is an expression with scalar type.
7144   // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
7145   // * binop, binop=, ++, and -- are not overloaded operators.
7146   // * The expression x binop expr must be numerically equivalent to x binop
7147   // (expr). This requirement is satisfied if the operators in expr have
7148   // precedence greater than binop, or by using parentheses around expr or
7149   // subexpressions of expr.
7150   // * The expression expr binop x must be numerically equivalent to (expr)
7151   // binop x. This requirement is satisfied if the operators in expr have
7152   // precedence equal to or greater than binop, or by using parentheses around
7153   // expr or subexpressions of expr.
7154   // * For forms that allow multiple occurrences of x, the number of times
7155   // that x is evaluated is unspecified.
7156   if (AtomicKind == OMPC_read) {
7157     enum {
7158       NotAnExpression,
7159       NotAnAssignmentOp,
7160       NotAScalarType,
7161       NotAnLValue,
7162       NoError
7163     } ErrorFound = NoError;
7164     SourceLocation ErrorLoc, NoteLoc;
7165     SourceRange ErrorRange, NoteRange;
7166     // If clause is read:
7167     //  v = x;
7168     if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
7169       const auto *AtomicBinOp =
7170           dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
7171       if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
7172         X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
7173         V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
7174         if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
7175             (V->isInstantiationDependent() || V->getType()->isScalarType())) {
7176           if (!X->isLValue() || !V->isLValue()) {
7177             const Expr *NotLValueExpr = X->isLValue() ? V : X;
7178             ErrorFound = NotAnLValue;
7179             ErrorLoc = AtomicBinOp->getExprLoc();
7180             ErrorRange = AtomicBinOp->getSourceRange();
7181             NoteLoc = NotLValueExpr->getExprLoc();
7182             NoteRange = NotLValueExpr->getSourceRange();
7183           }
7184         } else if (!X->isInstantiationDependent() ||
7185                    !V->isInstantiationDependent()) {
7186           const Expr *NotScalarExpr =
7187               (X->isInstantiationDependent() || X->getType()->isScalarType())
7188                   ? V
7189                   : X;
7190           ErrorFound = NotAScalarType;
7191           ErrorLoc = AtomicBinOp->getExprLoc();
7192           ErrorRange = AtomicBinOp->getSourceRange();
7193           NoteLoc = NotScalarExpr->getExprLoc();
7194           NoteRange = NotScalarExpr->getSourceRange();
7195         }
7196       } else if (!AtomicBody->isInstantiationDependent()) {
7197         ErrorFound = NotAnAssignmentOp;
7198         ErrorLoc = AtomicBody->getExprLoc();
7199         ErrorRange = AtomicBody->getSourceRange();
7200         NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
7201                               : AtomicBody->getExprLoc();
7202         NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
7203                                 : AtomicBody->getSourceRange();
7204       }
7205     } else {
7206       ErrorFound = NotAnExpression;
7207       NoteLoc = ErrorLoc = Body->getBeginLoc();
7208       NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
7209     }
7210     if (ErrorFound != NoError) {
7211       Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
7212           << ErrorRange;
7213       Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
7214                                                       << NoteRange;
7215       return StmtError();
7216     }
7217     if (CurContext->isDependentContext())
7218       V = X = nullptr;
7219   } else if (AtomicKind == OMPC_write) {
7220     enum {
7221       NotAnExpression,
7222       NotAnAssignmentOp,
7223       NotAScalarType,
7224       NotAnLValue,
7225       NoError
7226     } ErrorFound = NoError;
7227     SourceLocation ErrorLoc, NoteLoc;
7228     SourceRange ErrorRange, NoteRange;
7229     // If clause is write:
7230     //  x = expr;
7231     if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
7232       const auto *AtomicBinOp =
7233           dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
7234       if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
7235         X = AtomicBinOp->getLHS();
7236         E = AtomicBinOp->getRHS();
7237         if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
7238             (E->isInstantiationDependent() || E->getType()->isScalarType())) {
7239           if (!X->isLValue()) {
7240             ErrorFound = NotAnLValue;
7241             ErrorLoc = AtomicBinOp->getExprLoc();
7242             ErrorRange = AtomicBinOp->getSourceRange();
7243             NoteLoc = X->getExprLoc();
7244             NoteRange = X->getSourceRange();
7245           }
7246         } else if (!X->isInstantiationDependent() ||
7247                    !E->isInstantiationDependent()) {
7248           const Expr *NotScalarExpr =
7249               (X->isInstantiationDependent() || X->getType()->isScalarType())
7250                   ? E
7251                   : X;
7252           ErrorFound = NotAScalarType;
7253           ErrorLoc = AtomicBinOp->getExprLoc();
7254           ErrorRange = AtomicBinOp->getSourceRange();
7255           NoteLoc = NotScalarExpr->getExprLoc();
7256           NoteRange = NotScalarExpr->getSourceRange();
7257         }
7258       } else if (!AtomicBody->isInstantiationDependent()) {
7259         ErrorFound = NotAnAssignmentOp;
7260         ErrorLoc = AtomicBody->getExprLoc();
7261         ErrorRange = AtomicBody->getSourceRange();
7262         NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
7263                               : AtomicBody->getExprLoc();
7264         NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
7265                                 : AtomicBody->getSourceRange();
7266       }
7267     } else {
7268       ErrorFound = NotAnExpression;
7269       NoteLoc = ErrorLoc = Body->getBeginLoc();
7270       NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
7271     }
7272     if (ErrorFound != NoError) {
7273       Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
7274           << ErrorRange;
7275       Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
7276                                                       << NoteRange;
7277       return StmtError();
7278     }
7279     if (CurContext->isDependentContext())
7280       E = X = nullptr;
7281   } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
7282     // If clause is update:
7283     //  x++;
7284     //  x--;
7285     //  ++x;
7286     //  --x;
7287     //  x binop= expr;
7288     //  x = x binop expr;
7289     //  x = expr binop x;
7290     OpenMPAtomicUpdateChecker Checker(*this);
7291     if (Checker.checkStatement(
7292             Body, (AtomicKind == OMPC_update)
7293                       ? diag::err_omp_atomic_update_not_expression_statement
7294                       : diag::err_omp_atomic_not_expression_statement,
7295             diag::note_omp_atomic_update))
7296       return StmtError();
7297     if (!CurContext->isDependentContext()) {
7298       E = Checker.getExpr();
7299       X = Checker.getX();
7300       UE = Checker.getUpdateExpr();
7301       IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
7302     }
7303   } else if (AtomicKind == OMPC_capture) {
7304     enum {
7305       NotAnAssignmentOp,
7306       NotACompoundStatement,
7307       NotTwoSubstatements,
7308       NotASpecificExpression,
7309       NoError
7310     } ErrorFound = NoError;
7311     SourceLocation ErrorLoc, NoteLoc;
7312     SourceRange ErrorRange, NoteRange;
7313     if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
7314       // If clause is a capture:
7315       //  v = x++;
7316       //  v = x--;
7317       //  v = ++x;
7318       //  v = --x;
7319       //  v = x binop= expr;
7320       //  v = x = x binop expr;
7321       //  v = x = expr binop x;
7322       const auto *AtomicBinOp =
7323           dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
7324       if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
7325         V = AtomicBinOp->getLHS();
7326         Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
7327         OpenMPAtomicUpdateChecker Checker(*this);
7328         if (Checker.checkStatement(
7329                 Body, diag::err_omp_atomic_capture_not_expression_statement,
7330                 diag::note_omp_atomic_update))
7331           return StmtError();
7332         E = Checker.getExpr();
7333         X = Checker.getX();
7334         UE = Checker.getUpdateExpr();
7335         IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
7336         IsPostfixUpdate = Checker.isPostfixUpdate();
7337       } else if (!AtomicBody->isInstantiationDependent()) {
7338         ErrorLoc = AtomicBody->getExprLoc();
7339         ErrorRange = AtomicBody->getSourceRange();
7340         NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
7341                               : AtomicBody->getExprLoc();
7342         NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
7343                                 : AtomicBody->getSourceRange();
7344         ErrorFound = NotAnAssignmentOp;
7345       }
7346       if (ErrorFound != NoError) {
7347         Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
7348             << ErrorRange;
7349         Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
7350         return StmtError();
7351       }
7352       if (CurContext->isDependentContext())
7353         UE = V = E = X = nullptr;
7354     } else {
7355       // If clause is a capture:
7356       //  { v = x; x = expr; }
7357       //  { v = x; x++; }
7358       //  { v = x; x--; }
7359       //  { v = x; ++x; }
7360       //  { v = x; --x; }
7361       //  { v = x; x binop= expr; }
7362       //  { v = x; x = x binop expr; }
7363       //  { v = x; x = expr binop x; }
7364       //  { x++; v = x; }
7365       //  { x--; v = x; }
7366       //  { ++x; v = x; }
7367       //  { --x; v = x; }
7368       //  { x binop= expr; v = x; }
7369       //  { x = x binop expr; v = x; }
7370       //  { x = expr binop x; v = x; }
7371       if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
7372         // Check that this is { expr1; expr2; }
7373         if (CS->size() == 2) {
7374           Stmt *First = CS->body_front();
7375           Stmt *Second = CS->body_back();
7376           if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
7377             First = EWC->getSubExpr()->IgnoreParenImpCasts();
7378           if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
7379             Second = EWC->getSubExpr()->IgnoreParenImpCasts();
7380           // Need to find what subexpression is 'v' and what is 'x'.
7381           OpenMPAtomicUpdateChecker Checker(*this);
7382           bool IsUpdateExprFound = !Checker.checkStatement(Second);
7383           BinaryOperator *BinOp = nullptr;
7384           if (IsUpdateExprFound) {
7385             BinOp = dyn_cast<BinaryOperator>(First);
7386             IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
7387           }
7388           if (IsUpdateExprFound && !CurContext->isDependentContext()) {
7389             //  { v = x; x++; }
7390             //  { v = x; x--; }
7391             //  { v = x; ++x; }
7392             //  { v = x; --x; }
7393             //  { v = x; x binop= expr; }
7394             //  { v = x; x = x binop expr; }
7395             //  { v = x; x = expr binop x; }
7396             // Check that the first expression has form v = x.
7397             Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
7398             llvm::FoldingSetNodeID XId, PossibleXId;
7399             Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
7400             PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
7401             IsUpdateExprFound = XId == PossibleXId;
7402             if (IsUpdateExprFound) {
7403               V = BinOp->getLHS();
7404               X = Checker.getX();
7405               E = Checker.getExpr();
7406               UE = Checker.getUpdateExpr();
7407               IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
7408               IsPostfixUpdate = true;
7409             }
7410           }
7411           if (!IsUpdateExprFound) {
7412             IsUpdateExprFound = !Checker.checkStatement(First);
7413             BinOp = nullptr;
7414             if (IsUpdateExprFound) {
7415               BinOp = dyn_cast<BinaryOperator>(Second);
7416               IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
7417             }
7418             if (IsUpdateExprFound && !CurContext->isDependentContext()) {
7419               //  { x++; v = x; }
7420               //  { x--; v = x; }
7421               //  { ++x; v = x; }
7422               //  { --x; v = x; }
7423               //  { x binop= expr; v = x; }
7424               //  { x = x binop expr; v = x; }
7425               //  { x = expr binop x; v = x; }
7426               // Check that the second expression has form v = x.
7427               Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
7428               llvm::FoldingSetNodeID XId, PossibleXId;
7429               Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
7430               PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
7431               IsUpdateExprFound = XId == PossibleXId;
7432               if (IsUpdateExprFound) {
7433                 V = BinOp->getLHS();
7434                 X = Checker.getX();
7435                 E = Checker.getExpr();
7436                 UE = Checker.getUpdateExpr();
7437                 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
7438                 IsPostfixUpdate = false;
7439               }
7440             }
7441           }
7442           if (!IsUpdateExprFound) {
7443             //  { v = x; x = expr; }
7444             auto *FirstExpr = dyn_cast<Expr>(First);
7445             auto *SecondExpr = dyn_cast<Expr>(Second);
7446             if (!FirstExpr || !SecondExpr ||
7447                 !(FirstExpr->isInstantiationDependent() ||
7448                   SecondExpr->isInstantiationDependent())) {
7449               auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
7450               if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
7451                 ErrorFound = NotAnAssignmentOp;
7452                 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
7453                                                 : First->getBeginLoc();
7454                 NoteRange = ErrorRange = FirstBinOp
7455                                              ? FirstBinOp->getSourceRange()
7456                                              : SourceRange(ErrorLoc, ErrorLoc);
7457               } else {
7458                 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
7459                 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
7460                   ErrorFound = NotAnAssignmentOp;
7461                   NoteLoc = ErrorLoc = SecondBinOp
7462                                            ? SecondBinOp->getOperatorLoc()
7463                                            : Second->getBeginLoc();
7464                   NoteRange = ErrorRange =
7465                       SecondBinOp ? SecondBinOp->getSourceRange()
7466                                   : SourceRange(ErrorLoc, ErrorLoc);
7467                 } else {
7468                   Expr *PossibleXRHSInFirst =
7469                       FirstBinOp->getRHS()->IgnoreParenImpCasts();
7470                   Expr *PossibleXLHSInSecond =
7471                       SecondBinOp->getLHS()->IgnoreParenImpCasts();
7472                   llvm::FoldingSetNodeID X1Id, X2Id;
7473                   PossibleXRHSInFirst->Profile(X1Id, Context,
7474                                                /*Canonical=*/true);
7475                   PossibleXLHSInSecond->Profile(X2Id, Context,
7476                                                 /*Canonical=*/true);
7477                   IsUpdateExprFound = X1Id == X2Id;
7478                   if (IsUpdateExprFound) {
7479                     V = FirstBinOp->getLHS();
7480                     X = SecondBinOp->getLHS();
7481                     E = SecondBinOp->getRHS();
7482                     UE = nullptr;
7483                     IsXLHSInRHSPart = false;
7484                     IsPostfixUpdate = true;
7485                   } else {
7486                     ErrorFound = NotASpecificExpression;
7487                     ErrorLoc = FirstBinOp->getExprLoc();
7488                     ErrorRange = FirstBinOp->getSourceRange();
7489                     NoteLoc = SecondBinOp->getLHS()->getExprLoc();
7490                     NoteRange = SecondBinOp->getRHS()->getSourceRange();
7491                   }
7492                 }
7493               }
7494             }
7495           }
7496         } else {
7497           NoteLoc = ErrorLoc = Body->getBeginLoc();
7498           NoteRange = ErrorRange =
7499               SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
7500           ErrorFound = NotTwoSubstatements;
7501         }
7502       } else {
7503         NoteLoc = ErrorLoc = Body->getBeginLoc();
7504         NoteRange = ErrorRange =
7505             SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
7506         ErrorFound = NotACompoundStatement;
7507       }
7508       if (ErrorFound != NoError) {
7509         Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
7510             << ErrorRange;
7511         Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
7512         return StmtError();
7513       }
7514       if (CurContext->isDependentContext())
7515         UE = V = E = X = nullptr;
7516     }
7517   }
7518 
7519   setFunctionHasBranchProtectedScope();
7520 
7521   return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
7522                                     X, V, E, UE, IsXLHSInRHSPart,
7523                                     IsPostfixUpdate);
7524 }
7525 
7526 StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
7527                                             Stmt *AStmt,
7528                                             SourceLocation StartLoc,
7529                                             SourceLocation EndLoc) {
7530   if (!AStmt)
7531     return StmtError();
7532 
7533   auto *CS = cast<CapturedStmt>(AStmt);
7534   // 1.2.2 OpenMP Language Terminology
7535   // Structured block - An executable statement with a single entry at the
7536   // top and a single exit at the bottom.
7537   // The point of exit cannot be a branch out of the structured block.
7538   // longjmp() and throw() must not violate the entry/exit criteria.
7539   CS->getCapturedDecl()->setNothrow();
7540   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target);
7541        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7542     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7543     // 1.2.2 OpenMP Language Terminology
7544     // Structured block - An executable statement with a single entry at the
7545     // top and a single exit at the bottom.
7546     // The point of exit cannot be a branch out of the structured block.
7547     // longjmp() and throw() must not violate the entry/exit criteria.
7548     CS->getCapturedDecl()->setNothrow();
7549   }
7550 
7551   // OpenMP [2.16, Nesting of Regions]
7552   // If specified, a teams construct must be contained within a target
7553   // construct. That target construct must contain no statements or directives
7554   // outside of the teams construct.
7555   if (DSAStack->hasInnerTeamsRegion()) {
7556     const Stmt *S = CS->IgnoreContainers(/*IgnoreCaptured=*/true);
7557     bool OMPTeamsFound = true;
7558     if (const auto *CS = dyn_cast<CompoundStmt>(S)) {
7559       auto I = CS->body_begin();
7560       while (I != CS->body_end()) {
7561         const auto *OED = dyn_cast<OMPExecutableDirective>(*I);
7562         if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind()) ||
7563             OMPTeamsFound) {
7564 
7565           OMPTeamsFound = false;
7566           break;
7567         }
7568         ++I;
7569       }
7570       assert(I != CS->body_end() && "Not found statement");
7571       S = *I;
7572     } else {
7573       const auto *OED = dyn_cast<OMPExecutableDirective>(S);
7574       OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
7575     }
7576     if (!OMPTeamsFound) {
7577       Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
7578       Diag(DSAStack->getInnerTeamsRegionLoc(),
7579            diag::note_omp_nested_teams_construct_here);
7580       Diag(S->getBeginLoc(), diag::note_omp_nested_statement_here)
7581           << isa<OMPExecutableDirective>(S);
7582       return StmtError();
7583     }
7584   }
7585 
7586   setFunctionHasBranchProtectedScope();
7587 
7588   return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
7589 }
7590 
7591 StmtResult
7592 Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
7593                                          Stmt *AStmt, SourceLocation StartLoc,
7594                                          SourceLocation EndLoc) {
7595   if (!AStmt)
7596     return StmtError();
7597 
7598   auto *CS = cast<CapturedStmt>(AStmt);
7599   // 1.2.2 OpenMP Language Terminology
7600   // Structured block - An executable statement with a single entry at the
7601   // top and a single exit at the bottom.
7602   // The point of exit cannot be a branch out of the structured block.
7603   // longjmp() and throw() must not violate the entry/exit criteria.
7604   CS->getCapturedDecl()->setNothrow();
7605   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel);
7606        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7607     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7608     // 1.2.2 OpenMP Language Terminology
7609     // Structured block - An executable statement with a single entry at the
7610     // top and a single exit at the bottom.
7611     // The point of exit cannot be a branch out of the structured block.
7612     // longjmp() and throw() must not violate the entry/exit criteria.
7613     CS->getCapturedDecl()->setNothrow();
7614   }
7615 
7616   setFunctionHasBranchProtectedScope();
7617 
7618   return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
7619                                             AStmt);
7620 }
7621 
7622 StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
7623     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7624     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
7625   if (!AStmt)
7626     return StmtError();
7627 
7628   auto *CS = cast<CapturedStmt>(AStmt);
7629   // 1.2.2 OpenMP Language Terminology
7630   // Structured block - An executable statement with a single entry at the
7631   // top and a single exit at the bottom.
7632   // The point of exit cannot be a branch out of the structured block.
7633   // longjmp() and throw() must not violate the entry/exit criteria.
7634   CS->getCapturedDecl()->setNothrow();
7635   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
7636        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7637     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7638     // 1.2.2 OpenMP Language Terminology
7639     // Structured block - An executable statement with a single entry at the
7640     // top and a single exit at the bottom.
7641     // The point of exit cannot be a branch out of the structured block.
7642     // longjmp() and throw() must not violate the entry/exit criteria.
7643     CS->getCapturedDecl()->setNothrow();
7644   }
7645 
7646   OMPLoopDirective::HelperExprs B;
7647   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7648   // define the nested loops number.
7649   unsigned NestedLoopCount =
7650       checkOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
7651                       getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
7652                       VarsWithImplicitDSA, B);
7653   if (NestedLoopCount == 0)
7654     return StmtError();
7655 
7656   assert((CurContext->isDependentContext() || B.builtAll()) &&
7657          "omp target parallel for loop exprs were not built");
7658 
7659   if (!CurContext->isDependentContext()) {
7660     // Finalize the clauses that need pre-built expressions for CodeGen.
7661     for (OMPClause *C : Clauses) {
7662       if (auto *LC = dyn_cast<OMPLinearClause>(C))
7663         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7664                                      B.NumIterations, *this, CurScope,
7665                                      DSAStack))
7666           return StmtError();
7667     }
7668   }
7669 
7670   setFunctionHasBranchProtectedScope();
7671   return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
7672                                                NestedLoopCount, Clauses, AStmt,
7673                                                B, DSAStack->isCancelRegion());
7674 }
7675 
7676 /// Check for existence of a map clause in the list of clauses.
7677 static bool hasClauses(ArrayRef<OMPClause *> Clauses,
7678                        const OpenMPClauseKind K) {
7679   return llvm::any_of(
7680       Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; });
7681 }
7682 
7683 template <typename... Params>
7684 static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K,
7685                        const Params... ClauseTypes) {
7686   return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...);
7687 }
7688 
7689 StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
7690                                                 Stmt *AStmt,
7691                                                 SourceLocation StartLoc,
7692                                                 SourceLocation EndLoc) {
7693   if (!AStmt)
7694     return StmtError();
7695 
7696   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
7697 
7698   // OpenMP [2.10.1, Restrictions, p. 97]
7699   // At least one map clause must appear on the directive.
7700   if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr)) {
7701     Diag(StartLoc, diag::err_omp_no_clause_for_directive)
7702         << "'map' or 'use_device_ptr'"
7703         << getOpenMPDirectiveName(OMPD_target_data);
7704     return StmtError();
7705   }
7706 
7707   setFunctionHasBranchProtectedScope();
7708 
7709   return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
7710                                         AStmt);
7711 }
7712 
7713 StmtResult
7714 Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
7715                                           SourceLocation StartLoc,
7716                                           SourceLocation EndLoc, Stmt *AStmt) {
7717   if (!AStmt)
7718     return StmtError();
7719 
7720   auto *CS = cast<CapturedStmt>(AStmt);
7721   // 1.2.2 OpenMP Language Terminology
7722   // Structured block - An executable statement with a single entry at the
7723   // top and a single exit at the bottom.
7724   // The point of exit cannot be a branch out of the structured block.
7725   // longjmp() and throw() must not violate the entry/exit criteria.
7726   CS->getCapturedDecl()->setNothrow();
7727   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_enter_data);
7728        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7729     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7730     // 1.2.2 OpenMP Language Terminology
7731     // Structured block - An executable statement with a single entry at the
7732     // top and a single exit at the bottom.
7733     // The point of exit cannot be a branch out of the structured block.
7734     // longjmp() and throw() must not violate the entry/exit criteria.
7735     CS->getCapturedDecl()->setNothrow();
7736   }
7737 
7738   // OpenMP [2.10.2, Restrictions, p. 99]
7739   // At least one map clause must appear on the directive.
7740   if (!hasClauses(Clauses, OMPC_map)) {
7741     Diag(StartLoc, diag::err_omp_no_clause_for_directive)
7742         << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data);
7743     return StmtError();
7744   }
7745 
7746   return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
7747                                              AStmt);
7748 }
7749 
7750 StmtResult
7751 Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
7752                                          SourceLocation StartLoc,
7753                                          SourceLocation EndLoc, Stmt *AStmt) {
7754   if (!AStmt)
7755     return StmtError();
7756 
7757   auto *CS = cast<CapturedStmt>(AStmt);
7758   // 1.2.2 OpenMP Language Terminology
7759   // Structured block - An executable statement with a single entry at the
7760   // top and a single exit at the bottom.
7761   // The point of exit cannot be a branch out of the structured block.
7762   // longjmp() and throw() must not violate the entry/exit criteria.
7763   CS->getCapturedDecl()->setNothrow();
7764   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_exit_data);
7765        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7766     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7767     // 1.2.2 OpenMP Language Terminology
7768     // Structured block - An executable statement with a single entry at the
7769     // top and a single exit at the bottom.
7770     // The point of exit cannot be a branch out of the structured block.
7771     // longjmp() and throw() must not violate the entry/exit criteria.
7772     CS->getCapturedDecl()->setNothrow();
7773   }
7774 
7775   // OpenMP [2.10.3, Restrictions, p. 102]
7776   // At least one map clause must appear on the directive.
7777   if (!hasClauses(Clauses, OMPC_map)) {
7778     Diag(StartLoc, diag::err_omp_no_clause_for_directive)
7779         << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data);
7780     return StmtError();
7781   }
7782 
7783   return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
7784                                             AStmt);
7785 }
7786 
7787 StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
7788                                                   SourceLocation StartLoc,
7789                                                   SourceLocation EndLoc,
7790                                                   Stmt *AStmt) {
7791   if (!AStmt)
7792     return StmtError();
7793 
7794   auto *CS = cast<CapturedStmt>(AStmt);
7795   // 1.2.2 OpenMP Language Terminology
7796   // Structured block - An executable statement with a single entry at the
7797   // top and a single exit at the bottom.
7798   // The point of exit cannot be a branch out of the structured block.
7799   // longjmp() and throw() must not violate the entry/exit criteria.
7800   CS->getCapturedDecl()->setNothrow();
7801   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_update);
7802        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7803     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7804     // 1.2.2 OpenMP Language Terminology
7805     // Structured block - An executable statement with a single entry at the
7806     // top and a single exit at the bottom.
7807     // The point of exit cannot be a branch out of the structured block.
7808     // longjmp() and throw() must not violate the entry/exit criteria.
7809     CS->getCapturedDecl()->setNothrow();
7810   }
7811 
7812   if (!hasClauses(Clauses, OMPC_to, OMPC_from)) {
7813     Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
7814     return StmtError();
7815   }
7816   return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses,
7817                                           AStmt);
7818 }
7819 
7820 StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
7821                                            Stmt *AStmt, SourceLocation StartLoc,
7822                                            SourceLocation EndLoc) {
7823   if (!AStmt)
7824     return StmtError();
7825 
7826   auto *CS = cast<CapturedStmt>(AStmt);
7827   // 1.2.2 OpenMP Language Terminology
7828   // Structured block - An executable statement with a single entry at the
7829   // top and a single exit at the bottom.
7830   // The point of exit cannot be a branch out of the structured block.
7831   // longjmp() and throw() must not violate the entry/exit criteria.
7832   CS->getCapturedDecl()->setNothrow();
7833 
7834   setFunctionHasBranchProtectedScope();
7835 
7836   DSAStack->setParentTeamsRegionLoc(StartLoc);
7837 
7838   return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
7839 }
7840 
7841 StmtResult
7842 Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
7843                                             SourceLocation EndLoc,
7844                                             OpenMPDirectiveKind CancelRegion) {
7845   if (DSAStack->isParentNowaitRegion()) {
7846     Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
7847     return StmtError();
7848   }
7849   if (DSAStack->isParentOrderedRegion()) {
7850     Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
7851     return StmtError();
7852   }
7853   return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
7854                                                CancelRegion);
7855 }
7856 
7857 StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
7858                                             SourceLocation StartLoc,
7859                                             SourceLocation EndLoc,
7860                                             OpenMPDirectiveKind CancelRegion) {
7861   if (DSAStack->isParentNowaitRegion()) {
7862     Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
7863     return StmtError();
7864   }
7865   if (DSAStack->isParentOrderedRegion()) {
7866     Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
7867     return StmtError();
7868   }
7869   DSAStack->setParentCancelRegion(/*Cancel=*/true);
7870   return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
7871                                     CancelRegion);
7872 }
7873 
7874 static bool checkGrainsizeNumTasksClauses(Sema &S,
7875                                           ArrayRef<OMPClause *> Clauses) {
7876   const OMPClause *PrevClause = nullptr;
7877   bool ErrorFound = false;
7878   for (const OMPClause *C : Clauses) {
7879     if (C->getClauseKind() == OMPC_grainsize ||
7880         C->getClauseKind() == OMPC_num_tasks) {
7881       if (!PrevClause)
7882         PrevClause = C;
7883       else if (PrevClause->getClauseKind() != C->getClauseKind()) {
7884         S.Diag(C->getBeginLoc(),
7885                diag::err_omp_grainsize_num_tasks_mutually_exclusive)
7886             << getOpenMPClauseName(C->getClauseKind())
7887             << getOpenMPClauseName(PrevClause->getClauseKind());
7888         S.Diag(PrevClause->getBeginLoc(),
7889                diag::note_omp_previous_grainsize_num_tasks)
7890             << getOpenMPClauseName(PrevClause->getClauseKind());
7891         ErrorFound = true;
7892       }
7893     }
7894   }
7895   return ErrorFound;
7896 }
7897 
7898 static bool checkReductionClauseWithNogroup(Sema &S,
7899                                             ArrayRef<OMPClause *> Clauses) {
7900   const OMPClause *ReductionClause = nullptr;
7901   const OMPClause *NogroupClause = nullptr;
7902   for (const OMPClause *C : Clauses) {
7903     if (C->getClauseKind() == OMPC_reduction) {
7904       ReductionClause = C;
7905       if (NogroupClause)
7906         break;
7907       continue;
7908     }
7909     if (C->getClauseKind() == OMPC_nogroup) {
7910       NogroupClause = C;
7911       if (ReductionClause)
7912         break;
7913       continue;
7914     }
7915   }
7916   if (ReductionClause && NogroupClause) {
7917     S.Diag(ReductionClause->getBeginLoc(), diag::err_omp_reduction_with_nogroup)
7918         << SourceRange(NogroupClause->getBeginLoc(),
7919                        NogroupClause->getEndLoc());
7920     return true;
7921   }
7922   return false;
7923 }
7924 
7925 StmtResult Sema::ActOnOpenMPTaskLoopDirective(
7926     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7927     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
7928   if (!AStmt)
7929     return StmtError();
7930 
7931   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
7932   OMPLoopDirective::HelperExprs B;
7933   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7934   // define the nested loops number.
7935   unsigned NestedLoopCount =
7936       checkOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
7937                       /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
7938                       VarsWithImplicitDSA, B);
7939   if (NestedLoopCount == 0)
7940     return StmtError();
7941 
7942   assert((CurContext->isDependentContext() || B.builtAll()) &&
7943          "omp for loop exprs were not built");
7944 
7945   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
7946   // The grainsize clause and num_tasks clause are mutually exclusive and may
7947   // not appear on the same taskloop directive.
7948   if (checkGrainsizeNumTasksClauses(*this, Clauses))
7949     return StmtError();
7950   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
7951   // If a reduction clause is present on the taskloop directive, the nogroup
7952   // clause must not be specified.
7953   if (checkReductionClauseWithNogroup(*this, Clauses))
7954     return StmtError();
7955 
7956   setFunctionHasBranchProtectedScope();
7957   return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
7958                                       NestedLoopCount, Clauses, AStmt, B);
7959 }
7960 
7961 StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
7962     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7963     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
7964   if (!AStmt)
7965     return StmtError();
7966 
7967   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
7968   OMPLoopDirective::HelperExprs B;
7969   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7970   // define the nested loops number.
7971   unsigned NestedLoopCount =
7972       checkOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
7973                       /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
7974                       VarsWithImplicitDSA, B);
7975   if (NestedLoopCount == 0)
7976     return StmtError();
7977 
7978   assert((CurContext->isDependentContext() || B.builtAll()) &&
7979          "omp for loop exprs were not built");
7980 
7981   if (!CurContext->isDependentContext()) {
7982     // Finalize the clauses that need pre-built expressions for CodeGen.
7983     for (OMPClause *C : Clauses) {
7984       if (auto *LC = dyn_cast<OMPLinearClause>(C))
7985         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7986                                      B.NumIterations, *this, CurScope,
7987                                      DSAStack))
7988           return StmtError();
7989     }
7990   }
7991 
7992   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
7993   // The grainsize clause and num_tasks clause are mutually exclusive and may
7994   // not appear on the same taskloop directive.
7995   if (checkGrainsizeNumTasksClauses(*this, Clauses))
7996     return StmtError();
7997   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
7998   // If a reduction clause is present on the taskloop directive, the nogroup
7999   // clause must not be specified.
8000   if (checkReductionClauseWithNogroup(*this, Clauses))
8001     return StmtError();
8002   if (checkSimdlenSafelenSpecified(*this, Clauses))
8003     return StmtError();
8004 
8005   setFunctionHasBranchProtectedScope();
8006   return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
8007                                           NestedLoopCount, Clauses, AStmt, B);
8008 }
8009 
8010 StmtResult Sema::ActOnOpenMPDistributeDirective(
8011     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8012     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
8013   if (!AStmt)
8014     return StmtError();
8015 
8016   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
8017   OMPLoopDirective::HelperExprs B;
8018   // In presence of clause 'collapse' with number of loops, it will
8019   // define the nested loops number.
8020   unsigned NestedLoopCount =
8021       checkOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
8022                       nullptr /*ordered not a clause on distribute*/, AStmt,
8023                       *this, *DSAStack, VarsWithImplicitDSA, B);
8024   if (NestedLoopCount == 0)
8025     return StmtError();
8026 
8027   assert((CurContext->isDependentContext() || B.builtAll()) &&
8028          "omp for loop exprs were not built");
8029 
8030   setFunctionHasBranchProtectedScope();
8031   return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
8032                                         NestedLoopCount, Clauses, AStmt, B);
8033 }
8034 
8035 StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
8036     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8037     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
8038   if (!AStmt)
8039     return StmtError();
8040 
8041   auto *CS = cast<CapturedStmt>(AStmt);
8042   // 1.2.2 OpenMP Language Terminology
8043   // Structured block - An executable statement with a single entry at the
8044   // top and a single exit at the bottom.
8045   // The point of exit cannot be a branch out of the structured block.
8046   // longjmp() and throw() must not violate the entry/exit criteria.
8047   CS->getCapturedDecl()->setNothrow();
8048   for (int ThisCaptureLevel =
8049            getOpenMPCaptureLevels(OMPD_distribute_parallel_for);
8050        ThisCaptureLevel > 1; --ThisCaptureLevel) {
8051     CS = cast<CapturedStmt>(CS->getCapturedStmt());
8052     // 1.2.2 OpenMP Language Terminology
8053     // Structured block - An executable statement with a single entry at the
8054     // top and a single exit at the bottom.
8055     // The point of exit cannot be a branch out of the structured block.
8056     // longjmp() and throw() must not violate the entry/exit criteria.
8057     CS->getCapturedDecl()->setNothrow();
8058   }
8059 
8060   OMPLoopDirective::HelperExprs B;
8061   // In presence of clause 'collapse' with number of loops, it will
8062   // define the nested loops number.
8063   unsigned NestedLoopCount = checkOpenMPLoop(
8064       OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
8065       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
8066       VarsWithImplicitDSA, B);
8067   if (NestedLoopCount == 0)
8068     return StmtError();
8069 
8070   assert((CurContext->isDependentContext() || B.builtAll()) &&
8071          "omp for loop exprs were not built");
8072 
8073   setFunctionHasBranchProtectedScope();
8074   return OMPDistributeParallelForDirective::Create(
8075       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
8076       DSAStack->isCancelRegion());
8077 }
8078 
8079 StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
8080     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8081     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
8082   if (!AStmt)
8083     return StmtError();
8084 
8085   auto *CS = cast<CapturedStmt>(AStmt);
8086   // 1.2.2 OpenMP Language Terminology
8087   // Structured block - An executable statement with a single entry at the
8088   // top and a single exit at the bottom.
8089   // The point of exit cannot be a branch out of the structured block.
8090   // longjmp() and throw() must not violate the entry/exit criteria.
8091   CS->getCapturedDecl()->setNothrow();
8092   for (int ThisCaptureLevel =
8093            getOpenMPCaptureLevels(OMPD_distribute_parallel_for_simd);
8094        ThisCaptureLevel > 1; --ThisCaptureLevel) {
8095     CS = cast<CapturedStmt>(CS->getCapturedStmt());
8096     // 1.2.2 OpenMP Language Terminology
8097     // Structured block - An executable statement with a single entry at the
8098     // top and a single exit at the bottom.
8099     // The point of exit cannot be a branch out of the structured block.
8100     // longjmp() and throw() must not violate the entry/exit criteria.
8101     CS->getCapturedDecl()->setNothrow();
8102   }
8103 
8104   OMPLoopDirective::HelperExprs B;
8105   // In presence of clause 'collapse' with number of loops, it will
8106   // define the nested loops number.
8107   unsigned NestedLoopCount = checkOpenMPLoop(
8108       OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
8109       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
8110       VarsWithImplicitDSA, B);
8111   if (NestedLoopCount == 0)
8112     return StmtError();
8113 
8114   assert((CurContext->isDependentContext() || B.builtAll()) &&
8115          "omp for loop exprs were not built");
8116 
8117   if (!CurContext->isDependentContext()) {
8118     // Finalize the clauses that need pre-built expressions for CodeGen.
8119     for (OMPClause *C : Clauses) {
8120       if (auto *LC = dyn_cast<OMPLinearClause>(C))
8121         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8122                                      B.NumIterations, *this, CurScope,
8123                                      DSAStack))
8124           return StmtError();
8125     }
8126   }
8127 
8128   if (checkSimdlenSafelenSpecified(*this, Clauses))
8129     return StmtError();
8130 
8131   setFunctionHasBranchProtectedScope();
8132   return OMPDistributeParallelForSimdDirective::Create(
8133       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8134 }
8135 
8136 StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
8137     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8138     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
8139   if (!AStmt)
8140     return StmtError();
8141 
8142   auto *CS = cast<CapturedStmt>(AStmt);
8143   // 1.2.2 OpenMP Language Terminology
8144   // Structured block - An executable statement with a single entry at the
8145   // top and a single exit at the bottom.
8146   // The point of exit cannot be a branch out of the structured block.
8147   // longjmp() and throw() must not violate the entry/exit criteria.
8148   CS->getCapturedDecl()->setNothrow();
8149   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_distribute_simd);
8150        ThisCaptureLevel > 1; --ThisCaptureLevel) {
8151     CS = cast<CapturedStmt>(CS->getCapturedStmt());
8152     // 1.2.2 OpenMP Language Terminology
8153     // Structured block - An executable statement with a single entry at the
8154     // top and a single exit at the bottom.
8155     // The point of exit cannot be a branch out of the structured block.
8156     // longjmp() and throw() must not violate the entry/exit criteria.
8157     CS->getCapturedDecl()->setNothrow();
8158   }
8159 
8160   OMPLoopDirective::HelperExprs B;
8161   // In presence of clause 'collapse' with number of loops, it will
8162   // define the nested loops number.
8163   unsigned NestedLoopCount =
8164       checkOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
8165                       nullptr /*ordered not a clause on distribute*/, CS, *this,
8166                       *DSAStack, VarsWithImplicitDSA, B);
8167   if (NestedLoopCount == 0)
8168     return StmtError();
8169 
8170   assert((CurContext->isDependentContext() || B.builtAll()) &&
8171          "omp for loop exprs were not built");
8172 
8173   if (!CurContext->isDependentContext()) {
8174     // Finalize the clauses that need pre-built expressions for CodeGen.
8175     for (OMPClause *C : Clauses) {
8176       if (auto *LC = dyn_cast<OMPLinearClause>(C))
8177         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8178                                      B.NumIterations, *this, CurScope,
8179                                      DSAStack))
8180           return StmtError();
8181     }
8182   }
8183 
8184   if (checkSimdlenSafelenSpecified(*this, Clauses))
8185     return StmtError();
8186 
8187   setFunctionHasBranchProtectedScope();
8188   return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
8189                                             NestedLoopCount, Clauses, AStmt, B);
8190 }
8191 
8192 StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
8193     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8194     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
8195   if (!AStmt)
8196     return StmtError();
8197 
8198   auto *CS = cast<CapturedStmt>(AStmt);
8199   // 1.2.2 OpenMP Language Terminology
8200   // Structured block - An executable statement with a single entry at the
8201   // top and a single exit at the bottom.
8202   // The point of exit cannot be a branch out of the structured block.
8203   // longjmp() and throw() must not violate the entry/exit criteria.
8204   CS->getCapturedDecl()->setNothrow();
8205   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
8206        ThisCaptureLevel > 1; --ThisCaptureLevel) {
8207     CS = cast<CapturedStmt>(CS->getCapturedStmt());
8208     // 1.2.2 OpenMP Language Terminology
8209     // Structured block - An executable statement with a single entry at the
8210     // top and a single exit at the bottom.
8211     // The point of exit cannot be a branch out of the structured block.
8212     // longjmp() and throw() must not violate the entry/exit criteria.
8213     CS->getCapturedDecl()->setNothrow();
8214   }
8215 
8216   OMPLoopDirective::HelperExprs B;
8217   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
8218   // define the nested loops number.
8219   unsigned NestedLoopCount = checkOpenMPLoop(
8220       OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
8221       getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
8222       VarsWithImplicitDSA, B);
8223   if (NestedLoopCount == 0)
8224     return StmtError();
8225 
8226   assert((CurContext->isDependentContext() || B.builtAll()) &&
8227          "omp target parallel for simd loop exprs were not built");
8228 
8229   if (!CurContext->isDependentContext()) {
8230     // Finalize the clauses that need pre-built expressions for CodeGen.
8231     for (OMPClause *C : Clauses) {
8232       if (auto *LC = dyn_cast<OMPLinearClause>(C))
8233         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8234                                      B.NumIterations, *this, CurScope,
8235                                      DSAStack))
8236           return StmtError();
8237     }
8238   }
8239   if (checkSimdlenSafelenSpecified(*this, Clauses))
8240     return StmtError();
8241 
8242   setFunctionHasBranchProtectedScope();
8243   return OMPTargetParallelForSimdDirective::Create(
8244       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8245 }
8246 
8247 StmtResult Sema::ActOnOpenMPTargetSimdDirective(
8248     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8249     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
8250   if (!AStmt)
8251     return StmtError();
8252 
8253   auto *CS = cast<CapturedStmt>(AStmt);
8254   // 1.2.2 OpenMP Language Terminology
8255   // Structured block - An executable statement with a single entry at the
8256   // top and a single exit at the bottom.
8257   // The point of exit cannot be a branch out of the structured block.
8258   // longjmp() and throw() must not violate the entry/exit criteria.
8259   CS->getCapturedDecl()->setNothrow();
8260   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_simd);
8261        ThisCaptureLevel > 1; --ThisCaptureLevel) {
8262     CS = cast<CapturedStmt>(CS->getCapturedStmt());
8263     // 1.2.2 OpenMP Language Terminology
8264     // Structured block - An executable statement with a single entry at the
8265     // top and a single exit at the bottom.
8266     // The point of exit cannot be a branch out of the structured block.
8267     // longjmp() and throw() must not violate the entry/exit criteria.
8268     CS->getCapturedDecl()->setNothrow();
8269   }
8270 
8271   OMPLoopDirective::HelperExprs B;
8272   // In presence of clause 'collapse' with number of loops, it will define the
8273   // nested loops number.
8274   unsigned NestedLoopCount =
8275       checkOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
8276                       getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
8277                       VarsWithImplicitDSA, B);
8278   if (NestedLoopCount == 0)
8279     return StmtError();
8280 
8281   assert((CurContext->isDependentContext() || B.builtAll()) &&
8282          "omp target simd loop exprs were not built");
8283 
8284   if (!CurContext->isDependentContext()) {
8285     // Finalize the clauses that need pre-built expressions for CodeGen.
8286     for (OMPClause *C : Clauses) {
8287       if (auto *LC = dyn_cast<OMPLinearClause>(C))
8288         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8289                                      B.NumIterations, *this, CurScope,
8290                                      DSAStack))
8291           return StmtError();
8292     }
8293   }
8294 
8295   if (checkSimdlenSafelenSpecified(*this, Clauses))
8296     return StmtError();
8297 
8298   setFunctionHasBranchProtectedScope();
8299   return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
8300                                         NestedLoopCount, Clauses, AStmt, B);
8301 }
8302 
8303 StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
8304     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8305     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
8306   if (!AStmt)
8307     return StmtError();
8308 
8309   auto *CS = cast<CapturedStmt>(AStmt);
8310   // 1.2.2 OpenMP Language Terminology
8311   // Structured block - An executable statement with a single entry at the
8312   // top and a single exit at the bottom.
8313   // The point of exit cannot be a branch out of the structured block.
8314   // longjmp() and throw() must not violate the entry/exit criteria.
8315   CS->getCapturedDecl()->setNothrow();
8316   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_teams_distribute);
8317        ThisCaptureLevel > 1; --ThisCaptureLevel) {
8318     CS = cast<CapturedStmt>(CS->getCapturedStmt());
8319     // 1.2.2 OpenMP Language Terminology
8320     // Structured block - An executable statement with a single entry at the
8321     // top and a single exit at the bottom.
8322     // The point of exit cannot be a branch out of the structured block.
8323     // longjmp() and throw() must not violate the entry/exit criteria.
8324     CS->getCapturedDecl()->setNothrow();
8325   }
8326 
8327   OMPLoopDirective::HelperExprs B;
8328   // In presence of clause 'collapse' with number of loops, it will
8329   // define the nested loops number.
8330   unsigned NestedLoopCount =
8331       checkOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
8332                       nullptr /*ordered not a clause on distribute*/, CS, *this,
8333                       *DSAStack, VarsWithImplicitDSA, B);
8334   if (NestedLoopCount == 0)
8335     return StmtError();
8336 
8337   assert((CurContext->isDependentContext() || B.builtAll()) &&
8338          "omp teams distribute loop exprs were not built");
8339 
8340   setFunctionHasBranchProtectedScope();
8341 
8342   DSAStack->setParentTeamsRegionLoc(StartLoc);
8343 
8344   return OMPTeamsDistributeDirective::Create(
8345       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8346 }
8347 
8348 StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
8349     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8350     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
8351   if (!AStmt)
8352     return StmtError();
8353 
8354   auto *CS = cast<CapturedStmt>(AStmt);
8355   // 1.2.2 OpenMP Language Terminology
8356   // Structured block - An executable statement with a single entry at the
8357   // top and a single exit at the bottom.
8358   // The point of exit cannot be a branch out of the structured block.
8359   // longjmp() and throw() must not violate the entry/exit criteria.
8360   CS->getCapturedDecl()->setNothrow();
8361   for (int ThisCaptureLevel =
8362            getOpenMPCaptureLevels(OMPD_teams_distribute_simd);
8363        ThisCaptureLevel > 1; --ThisCaptureLevel) {
8364     CS = cast<CapturedStmt>(CS->getCapturedStmt());
8365     // 1.2.2 OpenMP Language Terminology
8366     // Structured block - An executable statement with a single entry at the
8367     // top and a single exit at the bottom.
8368     // The point of exit cannot be a branch out of the structured block.
8369     // longjmp() and throw() must not violate the entry/exit criteria.
8370     CS->getCapturedDecl()->setNothrow();
8371   }
8372 
8373 
8374   OMPLoopDirective::HelperExprs B;
8375   // In presence of clause 'collapse' with number of loops, it will
8376   // define the nested loops number.
8377   unsigned NestedLoopCount = checkOpenMPLoop(
8378       OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
8379       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
8380       VarsWithImplicitDSA, B);
8381 
8382   if (NestedLoopCount == 0)
8383     return StmtError();
8384 
8385   assert((CurContext->isDependentContext() || B.builtAll()) &&
8386          "omp teams distribute simd loop exprs were not built");
8387 
8388   if (!CurContext->isDependentContext()) {
8389     // Finalize the clauses that need pre-built expressions for CodeGen.
8390     for (OMPClause *C : Clauses) {
8391       if (auto *LC = dyn_cast<OMPLinearClause>(C))
8392         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8393                                      B.NumIterations, *this, CurScope,
8394                                      DSAStack))
8395           return StmtError();
8396     }
8397   }
8398 
8399   if (checkSimdlenSafelenSpecified(*this, Clauses))
8400     return StmtError();
8401 
8402   setFunctionHasBranchProtectedScope();
8403 
8404   DSAStack->setParentTeamsRegionLoc(StartLoc);
8405 
8406   return OMPTeamsDistributeSimdDirective::Create(
8407       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8408 }
8409 
8410 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
8411     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8412     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
8413   if (!AStmt)
8414     return StmtError();
8415 
8416   auto *CS = cast<CapturedStmt>(AStmt);
8417   // 1.2.2 OpenMP Language Terminology
8418   // Structured block - An executable statement with a single entry at the
8419   // top and a single exit at the bottom.
8420   // The point of exit cannot be a branch out of the structured block.
8421   // longjmp() and throw() must not violate the entry/exit criteria.
8422   CS->getCapturedDecl()->setNothrow();
8423 
8424   for (int ThisCaptureLevel =
8425            getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for_simd);
8426        ThisCaptureLevel > 1; --ThisCaptureLevel) {
8427     CS = cast<CapturedStmt>(CS->getCapturedStmt());
8428     // 1.2.2 OpenMP Language Terminology
8429     // Structured block - An executable statement with a single entry at the
8430     // top and a single exit at the bottom.
8431     // The point of exit cannot be a branch out of the structured block.
8432     // longjmp() and throw() must not violate the entry/exit criteria.
8433     CS->getCapturedDecl()->setNothrow();
8434   }
8435 
8436   OMPLoopDirective::HelperExprs B;
8437   // In presence of clause 'collapse' with number of loops, it will
8438   // define the nested loops number.
8439   unsigned NestedLoopCount = checkOpenMPLoop(
8440       OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
8441       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
8442       VarsWithImplicitDSA, B);
8443 
8444   if (NestedLoopCount == 0)
8445     return StmtError();
8446 
8447   assert((CurContext->isDependentContext() || B.builtAll()) &&
8448          "omp for loop exprs were not built");
8449 
8450   if (!CurContext->isDependentContext()) {
8451     // Finalize the clauses that need pre-built expressions for CodeGen.
8452     for (OMPClause *C : Clauses) {
8453       if (auto *LC = dyn_cast<OMPLinearClause>(C))
8454         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8455                                      B.NumIterations, *this, CurScope,
8456                                      DSAStack))
8457           return StmtError();
8458     }
8459   }
8460 
8461   if (checkSimdlenSafelenSpecified(*this, Clauses))
8462     return StmtError();
8463 
8464   setFunctionHasBranchProtectedScope();
8465 
8466   DSAStack->setParentTeamsRegionLoc(StartLoc);
8467 
8468   return OMPTeamsDistributeParallelForSimdDirective::Create(
8469       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8470 }
8471 
8472 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
8473     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8474     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
8475   if (!AStmt)
8476     return StmtError();
8477 
8478   auto *CS = cast<CapturedStmt>(AStmt);
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   for (int ThisCaptureLevel =
8487            getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for);
8488        ThisCaptureLevel > 1; --ThisCaptureLevel) {
8489     CS = cast<CapturedStmt>(CS->getCapturedStmt());
8490     // 1.2.2 OpenMP Language Terminology
8491     // Structured block - An executable statement with a single entry at the
8492     // top and a single exit at the bottom.
8493     // The point of exit cannot be a branch out of the structured block.
8494     // longjmp() and throw() must not violate the entry/exit criteria.
8495     CS->getCapturedDecl()->setNothrow();
8496   }
8497 
8498   OMPLoopDirective::HelperExprs B;
8499   // In presence of clause 'collapse' with number of loops, it will
8500   // define the nested loops number.
8501   unsigned NestedLoopCount = checkOpenMPLoop(
8502       OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
8503       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
8504       VarsWithImplicitDSA, B);
8505 
8506   if (NestedLoopCount == 0)
8507     return StmtError();
8508 
8509   assert((CurContext->isDependentContext() || B.builtAll()) &&
8510          "omp for loop exprs were not built");
8511 
8512   setFunctionHasBranchProtectedScope();
8513 
8514   DSAStack->setParentTeamsRegionLoc(StartLoc);
8515 
8516   return OMPTeamsDistributeParallelForDirective::Create(
8517       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
8518       DSAStack->isCancelRegion());
8519 }
8520 
8521 StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
8522                                                  Stmt *AStmt,
8523                                                  SourceLocation StartLoc,
8524                                                  SourceLocation EndLoc) {
8525   if (!AStmt)
8526     return StmtError();
8527 
8528   auto *CS = cast<CapturedStmt>(AStmt);
8529   // 1.2.2 OpenMP Language Terminology
8530   // Structured block - An executable statement with a single entry at the
8531   // top and a single exit at the bottom.
8532   // The point of exit cannot be a branch out of the structured block.
8533   // longjmp() and throw() must not violate the entry/exit criteria.
8534   CS->getCapturedDecl()->setNothrow();
8535 
8536   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams);
8537        ThisCaptureLevel > 1; --ThisCaptureLevel) {
8538     CS = cast<CapturedStmt>(CS->getCapturedStmt());
8539     // 1.2.2 OpenMP Language Terminology
8540     // Structured block - An executable statement with a single entry at the
8541     // top and a single exit at the bottom.
8542     // The point of exit cannot be a branch out of the structured block.
8543     // longjmp() and throw() must not violate the entry/exit criteria.
8544     CS->getCapturedDecl()->setNothrow();
8545   }
8546   setFunctionHasBranchProtectedScope();
8547 
8548   return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
8549                                          AStmt);
8550 }
8551 
8552 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
8553     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8554     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
8555   if (!AStmt)
8556     return StmtError();
8557 
8558   auto *CS = cast<CapturedStmt>(AStmt);
8559   // 1.2.2 OpenMP Language Terminology
8560   // Structured block - An executable statement with a single entry at the
8561   // top and a single exit at the bottom.
8562   // The point of exit cannot be a branch out of the structured block.
8563   // longjmp() and throw() must not violate the entry/exit criteria.
8564   CS->getCapturedDecl()->setNothrow();
8565   for (int ThisCaptureLevel =
8566            getOpenMPCaptureLevels(OMPD_target_teams_distribute);
8567        ThisCaptureLevel > 1; --ThisCaptureLevel) {
8568     CS = cast<CapturedStmt>(CS->getCapturedStmt());
8569     // 1.2.2 OpenMP Language Terminology
8570     // Structured block - An executable statement with a single entry at the
8571     // top and a single exit at the bottom.
8572     // The point of exit cannot be a branch out of the structured block.
8573     // longjmp() and throw() must not violate the entry/exit criteria.
8574     CS->getCapturedDecl()->setNothrow();
8575   }
8576 
8577   OMPLoopDirective::HelperExprs B;
8578   // In presence of clause 'collapse' with number of loops, it will
8579   // define the nested loops number.
8580   unsigned NestedLoopCount = checkOpenMPLoop(
8581       OMPD_target_teams_distribute, getCollapseNumberExpr(Clauses),
8582       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
8583       VarsWithImplicitDSA, B);
8584   if (NestedLoopCount == 0)
8585     return StmtError();
8586 
8587   assert((CurContext->isDependentContext() || B.builtAll()) &&
8588          "omp target teams distribute loop exprs were not built");
8589 
8590   setFunctionHasBranchProtectedScope();
8591   return OMPTargetTeamsDistributeDirective::Create(
8592       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8593 }
8594 
8595 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
8596     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8597     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
8598   if (!AStmt)
8599     return StmtError();
8600 
8601   auto *CS = cast<CapturedStmt>(AStmt);
8602   // 1.2.2 OpenMP Language Terminology
8603   // Structured block - An executable statement with a single entry at the
8604   // top and a single exit at the bottom.
8605   // The point of exit cannot be a branch out of the structured block.
8606   // longjmp() and throw() must not violate the entry/exit criteria.
8607   CS->getCapturedDecl()->setNothrow();
8608   for (int ThisCaptureLevel =
8609            getOpenMPCaptureLevels(OMPD_target_teams_distribute_parallel_for);
8610        ThisCaptureLevel > 1; --ThisCaptureLevel) {
8611     CS = cast<CapturedStmt>(CS->getCapturedStmt());
8612     // 1.2.2 OpenMP Language Terminology
8613     // Structured block - An executable statement with a single entry at the
8614     // top and a single exit at the bottom.
8615     // The point of exit cannot be a branch out of the structured block.
8616     // longjmp() and throw() must not violate the entry/exit criteria.
8617     CS->getCapturedDecl()->setNothrow();
8618   }
8619 
8620   OMPLoopDirective::HelperExprs B;
8621   // In presence of clause 'collapse' with number of loops, it will
8622   // define the nested loops number.
8623   unsigned NestedLoopCount = checkOpenMPLoop(
8624       OMPD_target_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
8625       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
8626       VarsWithImplicitDSA, B);
8627   if (NestedLoopCount == 0)
8628     return StmtError();
8629 
8630   assert((CurContext->isDependentContext() || B.builtAll()) &&
8631          "omp target teams distribute parallel for loop exprs were not built");
8632 
8633   if (!CurContext->isDependentContext()) {
8634     // Finalize the clauses that need pre-built expressions for CodeGen.
8635     for (OMPClause *C : Clauses) {
8636       if (auto *LC = dyn_cast<OMPLinearClause>(C))
8637         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8638                                      B.NumIterations, *this, CurScope,
8639                                      DSAStack))
8640           return StmtError();
8641     }
8642   }
8643 
8644   setFunctionHasBranchProtectedScope();
8645   return OMPTargetTeamsDistributeParallelForDirective::Create(
8646       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
8647       DSAStack->isCancelRegion());
8648 }
8649 
8650 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
8651     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8652     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
8653   if (!AStmt)
8654     return StmtError();
8655 
8656   auto *CS = cast<CapturedStmt>(AStmt);
8657   // 1.2.2 OpenMP Language Terminology
8658   // Structured block - An executable statement with a single entry at the
8659   // top and a single exit at the bottom.
8660   // The point of exit cannot be a branch out of the structured block.
8661   // longjmp() and throw() must not violate the entry/exit criteria.
8662   CS->getCapturedDecl()->setNothrow();
8663   for (int ThisCaptureLevel = getOpenMPCaptureLevels(
8664            OMPD_target_teams_distribute_parallel_for_simd);
8665        ThisCaptureLevel > 1; --ThisCaptureLevel) {
8666     CS = cast<CapturedStmt>(CS->getCapturedStmt());
8667     // 1.2.2 OpenMP Language Terminology
8668     // Structured block - An executable statement with a single entry at the
8669     // top and a single exit at the bottom.
8670     // The point of exit cannot be a branch out of the structured block.
8671     // longjmp() and throw() must not violate the entry/exit criteria.
8672     CS->getCapturedDecl()->setNothrow();
8673   }
8674 
8675   OMPLoopDirective::HelperExprs B;
8676   // In presence of clause 'collapse' with number of loops, it will
8677   // define the nested loops number.
8678   unsigned NestedLoopCount =
8679       checkOpenMPLoop(OMPD_target_teams_distribute_parallel_for_simd,
8680                       getCollapseNumberExpr(Clauses),
8681                       nullptr /*ordered not a clause on distribute*/, CS, *this,
8682                       *DSAStack, VarsWithImplicitDSA, B);
8683   if (NestedLoopCount == 0)
8684     return StmtError();
8685 
8686   assert((CurContext->isDependentContext() || B.builtAll()) &&
8687          "omp target teams distribute parallel for simd loop exprs were not "
8688          "built");
8689 
8690   if (!CurContext->isDependentContext()) {
8691     // Finalize the clauses that need pre-built expressions for CodeGen.
8692     for (OMPClause *C : Clauses) {
8693       if (auto *LC = dyn_cast<OMPLinearClause>(C))
8694         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8695                                      B.NumIterations, *this, CurScope,
8696                                      DSAStack))
8697           return StmtError();
8698     }
8699   }
8700 
8701   if (checkSimdlenSafelenSpecified(*this, Clauses))
8702     return StmtError();
8703 
8704   setFunctionHasBranchProtectedScope();
8705   return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
8706       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8707 }
8708 
8709 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
8710     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8711     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
8712   if (!AStmt)
8713     return StmtError();
8714 
8715   auto *CS = cast<CapturedStmt>(AStmt);
8716   // 1.2.2 OpenMP Language Terminology
8717   // Structured block - An executable statement with a single entry at the
8718   // top and a single exit at the bottom.
8719   // The point of exit cannot be a branch out of the structured block.
8720   // longjmp() and throw() must not violate the entry/exit criteria.
8721   CS->getCapturedDecl()->setNothrow();
8722   for (int ThisCaptureLevel =
8723            getOpenMPCaptureLevels(OMPD_target_teams_distribute_simd);
8724        ThisCaptureLevel > 1; --ThisCaptureLevel) {
8725     CS = cast<CapturedStmt>(CS->getCapturedStmt());
8726     // 1.2.2 OpenMP Language Terminology
8727     // Structured block - An executable statement with a single entry at the
8728     // top and a single exit at the bottom.
8729     // The point of exit cannot be a branch out of the structured block.
8730     // longjmp() and throw() must not violate the entry/exit criteria.
8731     CS->getCapturedDecl()->setNothrow();
8732   }
8733 
8734   OMPLoopDirective::HelperExprs B;
8735   // In presence of clause 'collapse' with number of loops, it will
8736   // define the nested loops number.
8737   unsigned NestedLoopCount = checkOpenMPLoop(
8738       OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
8739       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
8740       VarsWithImplicitDSA, B);
8741   if (NestedLoopCount == 0)
8742     return StmtError();
8743 
8744   assert((CurContext->isDependentContext() || B.builtAll()) &&
8745          "omp target teams distribute simd loop exprs were not built");
8746 
8747   if (!CurContext->isDependentContext()) {
8748     // Finalize the clauses that need pre-built expressions for CodeGen.
8749     for (OMPClause *C : Clauses) {
8750       if (auto *LC = dyn_cast<OMPLinearClause>(C))
8751         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8752                                      B.NumIterations, *this, CurScope,
8753                                      DSAStack))
8754           return StmtError();
8755     }
8756   }
8757 
8758   if (checkSimdlenSafelenSpecified(*this, Clauses))
8759     return StmtError();
8760 
8761   setFunctionHasBranchProtectedScope();
8762   return OMPTargetTeamsDistributeSimdDirective::Create(
8763       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8764 }
8765 
8766 OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
8767                                              SourceLocation StartLoc,
8768                                              SourceLocation LParenLoc,
8769                                              SourceLocation EndLoc) {
8770   OMPClause *Res = nullptr;
8771   switch (Kind) {
8772   case OMPC_final:
8773     Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
8774     break;
8775   case OMPC_num_threads:
8776     Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
8777     break;
8778   case OMPC_safelen:
8779     Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
8780     break;
8781   case OMPC_simdlen:
8782     Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
8783     break;
8784   case OMPC_allocator:
8785     Res = ActOnOpenMPAllocatorClause(Expr, StartLoc, LParenLoc, EndLoc);
8786     break;
8787   case OMPC_collapse:
8788     Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
8789     break;
8790   case OMPC_ordered:
8791     Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
8792     break;
8793   case OMPC_device:
8794     Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
8795     break;
8796   case OMPC_num_teams:
8797     Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
8798     break;
8799   case OMPC_thread_limit:
8800     Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
8801     break;
8802   case OMPC_priority:
8803     Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
8804     break;
8805   case OMPC_grainsize:
8806     Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
8807     break;
8808   case OMPC_num_tasks:
8809     Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
8810     break;
8811   case OMPC_hint:
8812     Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
8813     break;
8814   case OMPC_if:
8815   case OMPC_default:
8816   case OMPC_proc_bind:
8817   case OMPC_schedule:
8818   case OMPC_private:
8819   case OMPC_firstprivate:
8820   case OMPC_lastprivate:
8821   case OMPC_shared:
8822   case OMPC_reduction:
8823   case OMPC_task_reduction:
8824   case OMPC_in_reduction:
8825   case OMPC_linear:
8826   case OMPC_aligned:
8827   case OMPC_copyin:
8828   case OMPC_copyprivate:
8829   case OMPC_nowait:
8830   case OMPC_untied:
8831   case OMPC_mergeable:
8832   case OMPC_threadprivate:
8833   case OMPC_allocate:
8834   case OMPC_flush:
8835   case OMPC_read:
8836   case OMPC_write:
8837   case OMPC_update:
8838   case OMPC_capture:
8839   case OMPC_seq_cst:
8840   case OMPC_depend:
8841   case OMPC_threads:
8842   case OMPC_simd:
8843   case OMPC_map:
8844   case OMPC_nogroup:
8845   case OMPC_dist_schedule:
8846   case OMPC_defaultmap:
8847   case OMPC_unknown:
8848   case OMPC_uniform:
8849   case OMPC_to:
8850   case OMPC_from:
8851   case OMPC_use_device_ptr:
8852   case OMPC_is_device_ptr:
8853   case OMPC_unified_address:
8854   case OMPC_unified_shared_memory:
8855   case OMPC_reverse_offload:
8856   case OMPC_dynamic_allocators:
8857   case OMPC_atomic_default_mem_order:
8858     llvm_unreachable("Clause is not allowed.");
8859   }
8860   return Res;
8861 }
8862 
8863 // An OpenMP directive such as 'target parallel' has two captured regions:
8864 // for the 'target' and 'parallel' respectively.  This function returns
8865 // the region in which to capture expressions associated with a clause.
8866 // A return value of OMPD_unknown signifies that the expression should not
8867 // be captured.
8868 static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
8869     OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
8870     OpenMPDirectiveKind NameModifier = OMPD_unknown) {
8871   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
8872   switch (CKind) {
8873   case OMPC_if:
8874     switch (DKind) {
8875     case OMPD_target_parallel:
8876     case OMPD_target_parallel_for:
8877     case OMPD_target_parallel_for_simd:
8878       // If this clause applies to the nested 'parallel' region, capture within
8879       // the 'target' region, otherwise do not capture.
8880       if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
8881         CaptureRegion = OMPD_target;
8882       break;
8883     case OMPD_target_teams_distribute_parallel_for:
8884     case OMPD_target_teams_distribute_parallel_for_simd:
8885       // If this clause applies to the nested 'parallel' region, capture within
8886       // the 'teams' region, otherwise do not capture.
8887       if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
8888         CaptureRegion = OMPD_teams;
8889       break;
8890     case OMPD_teams_distribute_parallel_for:
8891     case OMPD_teams_distribute_parallel_for_simd:
8892       CaptureRegion = OMPD_teams;
8893       break;
8894     case OMPD_target_update:
8895     case OMPD_target_enter_data:
8896     case OMPD_target_exit_data:
8897       CaptureRegion = OMPD_task;
8898       break;
8899     case OMPD_cancel:
8900     case OMPD_parallel:
8901     case OMPD_parallel_sections:
8902     case OMPD_parallel_for:
8903     case OMPD_parallel_for_simd:
8904     case OMPD_target:
8905     case OMPD_target_simd:
8906     case OMPD_target_teams:
8907     case OMPD_target_teams_distribute:
8908     case OMPD_target_teams_distribute_simd:
8909     case OMPD_distribute_parallel_for:
8910     case OMPD_distribute_parallel_for_simd:
8911     case OMPD_task:
8912     case OMPD_taskloop:
8913     case OMPD_taskloop_simd:
8914     case OMPD_target_data:
8915       // Do not capture if-clause expressions.
8916       break;
8917     case OMPD_threadprivate:
8918     case OMPD_allocate:
8919     case OMPD_taskyield:
8920     case OMPD_barrier:
8921     case OMPD_taskwait:
8922     case OMPD_cancellation_point:
8923     case OMPD_flush:
8924     case OMPD_declare_reduction:
8925     case OMPD_declare_mapper:
8926     case OMPD_declare_simd:
8927     case OMPD_declare_target:
8928     case OMPD_end_declare_target:
8929     case OMPD_teams:
8930     case OMPD_simd:
8931     case OMPD_for:
8932     case OMPD_for_simd:
8933     case OMPD_sections:
8934     case OMPD_section:
8935     case OMPD_single:
8936     case OMPD_master:
8937     case OMPD_critical:
8938     case OMPD_taskgroup:
8939     case OMPD_distribute:
8940     case OMPD_ordered:
8941     case OMPD_atomic:
8942     case OMPD_distribute_simd:
8943     case OMPD_teams_distribute:
8944     case OMPD_teams_distribute_simd:
8945     case OMPD_requires:
8946       llvm_unreachable("Unexpected OpenMP directive with if-clause");
8947     case OMPD_unknown:
8948       llvm_unreachable("Unknown OpenMP directive");
8949     }
8950     break;
8951   case OMPC_num_threads:
8952     switch (DKind) {
8953     case OMPD_target_parallel:
8954     case OMPD_target_parallel_for:
8955     case OMPD_target_parallel_for_simd:
8956       CaptureRegion = OMPD_target;
8957       break;
8958     case OMPD_teams_distribute_parallel_for:
8959     case OMPD_teams_distribute_parallel_for_simd:
8960     case OMPD_target_teams_distribute_parallel_for:
8961     case OMPD_target_teams_distribute_parallel_for_simd:
8962       CaptureRegion = OMPD_teams;
8963       break;
8964     case OMPD_parallel:
8965     case OMPD_parallel_sections:
8966     case OMPD_parallel_for:
8967     case OMPD_parallel_for_simd:
8968     case OMPD_distribute_parallel_for:
8969     case OMPD_distribute_parallel_for_simd:
8970       // Do not capture num_threads-clause expressions.
8971       break;
8972     case OMPD_target_data:
8973     case OMPD_target_enter_data:
8974     case OMPD_target_exit_data:
8975     case OMPD_target_update:
8976     case OMPD_target:
8977     case OMPD_target_simd:
8978     case OMPD_target_teams:
8979     case OMPD_target_teams_distribute:
8980     case OMPD_target_teams_distribute_simd:
8981     case OMPD_cancel:
8982     case OMPD_task:
8983     case OMPD_taskloop:
8984     case OMPD_taskloop_simd:
8985     case OMPD_threadprivate:
8986     case OMPD_allocate:
8987     case OMPD_taskyield:
8988     case OMPD_barrier:
8989     case OMPD_taskwait:
8990     case OMPD_cancellation_point:
8991     case OMPD_flush:
8992     case OMPD_declare_reduction:
8993     case OMPD_declare_mapper:
8994     case OMPD_declare_simd:
8995     case OMPD_declare_target:
8996     case OMPD_end_declare_target:
8997     case OMPD_teams:
8998     case OMPD_simd:
8999     case OMPD_for:
9000     case OMPD_for_simd:
9001     case OMPD_sections:
9002     case OMPD_section:
9003     case OMPD_single:
9004     case OMPD_master:
9005     case OMPD_critical:
9006     case OMPD_taskgroup:
9007     case OMPD_distribute:
9008     case OMPD_ordered:
9009     case OMPD_atomic:
9010     case OMPD_distribute_simd:
9011     case OMPD_teams_distribute:
9012     case OMPD_teams_distribute_simd:
9013     case OMPD_requires:
9014       llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
9015     case OMPD_unknown:
9016       llvm_unreachable("Unknown OpenMP directive");
9017     }
9018     break;
9019   case OMPC_num_teams:
9020     switch (DKind) {
9021     case OMPD_target_teams:
9022     case OMPD_target_teams_distribute:
9023     case OMPD_target_teams_distribute_simd:
9024     case OMPD_target_teams_distribute_parallel_for:
9025     case OMPD_target_teams_distribute_parallel_for_simd:
9026       CaptureRegion = OMPD_target;
9027       break;
9028     case OMPD_teams_distribute_parallel_for:
9029     case OMPD_teams_distribute_parallel_for_simd:
9030     case OMPD_teams:
9031     case OMPD_teams_distribute:
9032     case OMPD_teams_distribute_simd:
9033       // Do not capture num_teams-clause expressions.
9034       break;
9035     case OMPD_distribute_parallel_for:
9036     case OMPD_distribute_parallel_for_simd:
9037     case OMPD_task:
9038     case OMPD_taskloop:
9039     case OMPD_taskloop_simd:
9040     case OMPD_target_data:
9041     case OMPD_target_enter_data:
9042     case OMPD_target_exit_data:
9043     case OMPD_target_update:
9044     case OMPD_cancel:
9045     case OMPD_parallel:
9046     case OMPD_parallel_sections:
9047     case OMPD_parallel_for:
9048     case OMPD_parallel_for_simd:
9049     case OMPD_target:
9050     case OMPD_target_simd:
9051     case OMPD_target_parallel:
9052     case OMPD_target_parallel_for:
9053     case OMPD_target_parallel_for_simd:
9054     case OMPD_threadprivate:
9055     case OMPD_allocate:
9056     case OMPD_taskyield:
9057     case OMPD_barrier:
9058     case OMPD_taskwait:
9059     case OMPD_cancellation_point:
9060     case OMPD_flush:
9061     case OMPD_declare_reduction:
9062     case OMPD_declare_mapper:
9063     case OMPD_declare_simd:
9064     case OMPD_declare_target:
9065     case OMPD_end_declare_target:
9066     case OMPD_simd:
9067     case OMPD_for:
9068     case OMPD_for_simd:
9069     case OMPD_sections:
9070     case OMPD_section:
9071     case OMPD_single:
9072     case OMPD_master:
9073     case OMPD_critical:
9074     case OMPD_taskgroup:
9075     case OMPD_distribute:
9076     case OMPD_ordered:
9077     case OMPD_atomic:
9078     case OMPD_distribute_simd:
9079     case OMPD_requires:
9080       llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
9081     case OMPD_unknown:
9082       llvm_unreachable("Unknown OpenMP directive");
9083     }
9084     break;
9085   case OMPC_thread_limit:
9086     switch (DKind) {
9087     case OMPD_target_teams:
9088     case OMPD_target_teams_distribute:
9089     case OMPD_target_teams_distribute_simd:
9090     case OMPD_target_teams_distribute_parallel_for:
9091     case OMPD_target_teams_distribute_parallel_for_simd:
9092       CaptureRegion = OMPD_target;
9093       break;
9094     case OMPD_teams_distribute_parallel_for:
9095     case OMPD_teams_distribute_parallel_for_simd:
9096     case OMPD_teams:
9097     case OMPD_teams_distribute:
9098     case OMPD_teams_distribute_simd:
9099       // Do not capture thread_limit-clause expressions.
9100       break;
9101     case OMPD_distribute_parallel_for:
9102     case OMPD_distribute_parallel_for_simd:
9103     case OMPD_task:
9104     case OMPD_taskloop:
9105     case OMPD_taskloop_simd:
9106     case OMPD_target_data:
9107     case OMPD_target_enter_data:
9108     case OMPD_target_exit_data:
9109     case OMPD_target_update:
9110     case OMPD_cancel:
9111     case OMPD_parallel:
9112     case OMPD_parallel_sections:
9113     case OMPD_parallel_for:
9114     case OMPD_parallel_for_simd:
9115     case OMPD_target:
9116     case OMPD_target_simd:
9117     case OMPD_target_parallel:
9118     case OMPD_target_parallel_for:
9119     case OMPD_target_parallel_for_simd:
9120     case OMPD_threadprivate:
9121     case OMPD_allocate:
9122     case OMPD_taskyield:
9123     case OMPD_barrier:
9124     case OMPD_taskwait:
9125     case OMPD_cancellation_point:
9126     case OMPD_flush:
9127     case OMPD_declare_reduction:
9128     case OMPD_declare_mapper:
9129     case OMPD_declare_simd:
9130     case OMPD_declare_target:
9131     case OMPD_end_declare_target:
9132     case OMPD_simd:
9133     case OMPD_for:
9134     case OMPD_for_simd:
9135     case OMPD_sections:
9136     case OMPD_section:
9137     case OMPD_single:
9138     case OMPD_master:
9139     case OMPD_critical:
9140     case OMPD_taskgroup:
9141     case OMPD_distribute:
9142     case OMPD_ordered:
9143     case OMPD_atomic:
9144     case OMPD_distribute_simd:
9145     case OMPD_requires:
9146       llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
9147     case OMPD_unknown:
9148       llvm_unreachable("Unknown OpenMP directive");
9149     }
9150     break;
9151   case OMPC_schedule:
9152     switch (DKind) {
9153     case OMPD_parallel_for:
9154     case OMPD_parallel_for_simd:
9155     case OMPD_distribute_parallel_for:
9156     case OMPD_distribute_parallel_for_simd:
9157     case OMPD_teams_distribute_parallel_for:
9158     case OMPD_teams_distribute_parallel_for_simd:
9159     case OMPD_target_parallel_for:
9160     case OMPD_target_parallel_for_simd:
9161     case OMPD_target_teams_distribute_parallel_for:
9162     case OMPD_target_teams_distribute_parallel_for_simd:
9163       CaptureRegion = OMPD_parallel;
9164       break;
9165     case OMPD_for:
9166     case OMPD_for_simd:
9167       // Do not capture schedule-clause expressions.
9168       break;
9169     case OMPD_task:
9170     case OMPD_taskloop:
9171     case OMPD_taskloop_simd:
9172     case OMPD_target_data:
9173     case OMPD_target_enter_data:
9174     case OMPD_target_exit_data:
9175     case OMPD_target_update:
9176     case OMPD_teams:
9177     case OMPD_teams_distribute:
9178     case OMPD_teams_distribute_simd:
9179     case OMPD_target_teams_distribute:
9180     case OMPD_target_teams_distribute_simd:
9181     case OMPD_target:
9182     case OMPD_target_simd:
9183     case OMPD_target_parallel:
9184     case OMPD_cancel:
9185     case OMPD_parallel:
9186     case OMPD_parallel_sections:
9187     case OMPD_threadprivate:
9188     case OMPD_allocate:
9189     case OMPD_taskyield:
9190     case OMPD_barrier:
9191     case OMPD_taskwait:
9192     case OMPD_cancellation_point:
9193     case OMPD_flush:
9194     case OMPD_declare_reduction:
9195     case OMPD_declare_mapper:
9196     case OMPD_declare_simd:
9197     case OMPD_declare_target:
9198     case OMPD_end_declare_target:
9199     case OMPD_simd:
9200     case OMPD_sections:
9201     case OMPD_section:
9202     case OMPD_single:
9203     case OMPD_master:
9204     case OMPD_critical:
9205     case OMPD_taskgroup:
9206     case OMPD_distribute:
9207     case OMPD_ordered:
9208     case OMPD_atomic:
9209     case OMPD_distribute_simd:
9210     case OMPD_target_teams:
9211     case OMPD_requires:
9212       llvm_unreachable("Unexpected OpenMP directive with schedule clause");
9213     case OMPD_unknown:
9214       llvm_unreachable("Unknown OpenMP directive");
9215     }
9216     break;
9217   case OMPC_dist_schedule:
9218     switch (DKind) {
9219     case OMPD_teams_distribute_parallel_for:
9220     case OMPD_teams_distribute_parallel_for_simd:
9221     case OMPD_teams_distribute:
9222     case OMPD_teams_distribute_simd:
9223     case OMPD_target_teams_distribute_parallel_for:
9224     case OMPD_target_teams_distribute_parallel_for_simd:
9225     case OMPD_target_teams_distribute:
9226     case OMPD_target_teams_distribute_simd:
9227       CaptureRegion = OMPD_teams;
9228       break;
9229     case OMPD_distribute_parallel_for:
9230     case OMPD_distribute_parallel_for_simd:
9231     case OMPD_distribute:
9232     case OMPD_distribute_simd:
9233       // Do not capture thread_limit-clause expressions.
9234       break;
9235     case OMPD_parallel_for:
9236     case OMPD_parallel_for_simd:
9237     case OMPD_target_parallel_for_simd:
9238     case OMPD_target_parallel_for:
9239     case OMPD_task:
9240     case OMPD_taskloop:
9241     case OMPD_taskloop_simd:
9242     case OMPD_target_data:
9243     case OMPD_target_enter_data:
9244     case OMPD_target_exit_data:
9245     case OMPD_target_update:
9246     case OMPD_teams:
9247     case OMPD_target:
9248     case OMPD_target_simd:
9249     case OMPD_target_parallel:
9250     case OMPD_cancel:
9251     case OMPD_parallel:
9252     case OMPD_parallel_sections:
9253     case OMPD_threadprivate:
9254     case OMPD_allocate:
9255     case OMPD_taskyield:
9256     case OMPD_barrier:
9257     case OMPD_taskwait:
9258     case OMPD_cancellation_point:
9259     case OMPD_flush:
9260     case OMPD_declare_reduction:
9261     case OMPD_declare_mapper:
9262     case OMPD_declare_simd:
9263     case OMPD_declare_target:
9264     case OMPD_end_declare_target:
9265     case OMPD_simd:
9266     case OMPD_for:
9267     case OMPD_for_simd:
9268     case OMPD_sections:
9269     case OMPD_section:
9270     case OMPD_single:
9271     case OMPD_master:
9272     case OMPD_critical:
9273     case OMPD_taskgroup:
9274     case OMPD_ordered:
9275     case OMPD_atomic:
9276     case OMPD_target_teams:
9277     case OMPD_requires:
9278       llvm_unreachable("Unexpected OpenMP directive with schedule clause");
9279     case OMPD_unknown:
9280       llvm_unreachable("Unknown OpenMP directive");
9281     }
9282     break;
9283   case OMPC_device:
9284     switch (DKind) {
9285     case OMPD_target_update:
9286     case OMPD_target_enter_data:
9287     case OMPD_target_exit_data:
9288     case OMPD_target:
9289     case OMPD_target_simd:
9290     case OMPD_target_teams:
9291     case OMPD_target_parallel:
9292     case OMPD_target_teams_distribute:
9293     case OMPD_target_teams_distribute_simd:
9294     case OMPD_target_parallel_for:
9295     case OMPD_target_parallel_for_simd:
9296     case OMPD_target_teams_distribute_parallel_for:
9297     case OMPD_target_teams_distribute_parallel_for_simd:
9298       CaptureRegion = OMPD_task;
9299       break;
9300     case OMPD_target_data:
9301       // Do not capture device-clause expressions.
9302       break;
9303     case OMPD_teams_distribute_parallel_for:
9304     case OMPD_teams_distribute_parallel_for_simd:
9305     case OMPD_teams:
9306     case OMPD_teams_distribute:
9307     case OMPD_teams_distribute_simd:
9308     case OMPD_distribute_parallel_for:
9309     case OMPD_distribute_parallel_for_simd:
9310     case OMPD_task:
9311     case OMPD_taskloop:
9312     case OMPD_taskloop_simd:
9313     case OMPD_cancel:
9314     case OMPD_parallel:
9315     case OMPD_parallel_sections:
9316     case OMPD_parallel_for:
9317     case OMPD_parallel_for_simd:
9318     case OMPD_threadprivate:
9319     case OMPD_allocate:
9320     case OMPD_taskyield:
9321     case OMPD_barrier:
9322     case OMPD_taskwait:
9323     case OMPD_cancellation_point:
9324     case OMPD_flush:
9325     case OMPD_declare_reduction:
9326     case OMPD_declare_mapper:
9327     case OMPD_declare_simd:
9328     case OMPD_declare_target:
9329     case OMPD_end_declare_target:
9330     case OMPD_simd:
9331     case OMPD_for:
9332     case OMPD_for_simd:
9333     case OMPD_sections:
9334     case OMPD_section:
9335     case OMPD_single:
9336     case OMPD_master:
9337     case OMPD_critical:
9338     case OMPD_taskgroup:
9339     case OMPD_distribute:
9340     case OMPD_ordered:
9341     case OMPD_atomic:
9342     case OMPD_distribute_simd:
9343     case OMPD_requires:
9344       llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
9345     case OMPD_unknown:
9346       llvm_unreachable("Unknown OpenMP directive");
9347     }
9348     break;
9349   case OMPC_firstprivate:
9350   case OMPC_lastprivate:
9351   case OMPC_reduction:
9352   case OMPC_task_reduction:
9353   case OMPC_in_reduction:
9354   case OMPC_linear:
9355   case OMPC_default:
9356   case OMPC_proc_bind:
9357   case OMPC_final:
9358   case OMPC_safelen:
9359   case OMPC_simdlen:
9360   case OMPC_allocator:
9361   case OMPC_collapse:
9362   case OMPC_private:
9363   case OMPC_shared:
9364   case OMPC_aligned:
9365   case OMPC_copyin:
9366   case OMPC_copyprivate:
9367   case OMPC_ordered:
9368   case OMPC_nowait:
9369   case OMPC_untied:
9370   case OMPC_mergeable:
9371   case OMPC_threadprivate:
9372   case OMPC_allocate:
9373   case OMPC_flush:
9374   case OMPC_read:
9375   case OMPC_write:
9376   case OMPC_update:
9377   case OMPC_capture:
9378   case OMPC_seq_cst:
9379   case OMPC_depend:
9380   case OMPC_threads:
9381   case OMPC_simd:
9382   case OMPC_map:
9383   case OMPC_priority:
9384   case OMPC_grainsize:
9385   case OMPC_nogroup:
9386   case OMPC_num_tasks:
9387   case OMPC_hint:
9388   case OMPC_defaultmap:
9389   case OMPC_unknown:
9390   case OMPC_uniform:
9391   case OMPC_to:
9392   case OMPC_from:
9393   case OMPC_use_device_ptr:
9394   case OMPC_is_device_ptr:
9395   case OMPC_unified_address:
9396   case OMPC_unified_shared_memory:
9397   case OMPC_reverse_offload:
9398   case OMPC_dynamic_allocators:
9399   case OMPC_atomic_default_mem_order:
9400     llvm_unreachable("Unexpected OpenMP clause.");
9401   }
9402   return CaptureRegion;
9403 }
9404 
9405 OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
9406                                      Expr *Condition, SourceLocation StartLoc,
9407                                      SourceLocation LParenLoc,
9408                                      SourceLocation NameModifierLoc,
9409                                      SourceLocation ColonLoc,
9410                                      SourceLocation EndLoc) {
9411   Expr *ValExpr = Condition;
9412   Stmt *HelperValStmt = nullptr;
9413   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
9414   if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
9415       !Condition->isInstantiationDependent() &&
9416       !Condition->containsUnexpandedParameterPack()) {
9417     ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
9418     if (Val.isInvalid())
9419       return nullptr;
9420 
9421     ValExpr = Val.get();
9422 
9423     OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
9424     CaptureRegion =
9425         getOpenMPCaptureRegionForClause(DKind, OMPC_if, NameModifier);
9426     if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
9427       ValExpr = MakeFullExpr(ValExpr).get();
9428       llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
9429       ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
9430       HelperValStmt = buildPreInits(Context, Captures);
9431     }
9432   }
9433 
9434   return new (Context)
9435       OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
9436                   LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
9437 }
9438 
9439 OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
9440                                         SourceLocation StartLoc,
9441                                         SourceLocation LParenLoc,
9442                                         SourceLocation EndLoc) {
9443   Expr *ValExpr = Condition;
9444   if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
9445       !Condition->isInstantiationDependent() &&
9446       !Condition->containsUnexpandedParameterPack()) {
9447     ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
9448     if (Val.isInvalid())
9449       return nullptr;
9450 
9451     ValExpr = MakeFullExpr(Val.get()).get();
9452   }
9453 
9454   return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
9455 }
9456 ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
9457                                                         Expr *Op) {
9458   if (!Op)
9459     return ExprError();
9460 
9461   class IntConvertDiagnoser : public ICEConvertDiagnoser {
9462   public:
9463     IntConvertDiagnoser()
9464         : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
9465     SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
9466                                          QualType T) override {
9467       return S.Diag(Loc, diag::err_omp_not_integral) << T;
9468     }
9469     SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
9470                                              QualType T) override {
9471       return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
9472     }
9473     SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
9474                                                QualType T,
9475                                                QualType ConvTy) override {
9476       return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
9477     }
9478     SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
9479                                            QualType ConvTy) override {
9480       return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
9481              << ConvTy->isEnumeralType() << ConvTy;
9482     }
9483     SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
9484                                             QualType T) override {
9485       return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
9486     }
9487     SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
9488                                         QualType ConvTy) override {
9489       return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
9490              << ConvTy->isEnumeralType() << ConvTy;
9491     }
9492     SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
9493                                              QualType) override {
9494       llvm_unreachable("conversion functions are permitted");
9495     }
9496   } ConvertDiagnoser;
9497   return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
9498 }
9499 
9500 static bool isNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
9501                                       OpenMPClauseKind CKind,
9502                                       bool StrictlyPositive) {
9503   if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
9504       !ValExpr->isInstantiationDependent()) {
9505     SourceLocation Loc = ValExpr->getExprLoc();
9506     ExprResult Value =
9507         SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
9508     if (Value.isInvalid())
9509       return false;
9510 
9511     ValExpr = Value.get();
9512     // The expression must evaluate to a non-negative integer value.
9513     llvm::APSInt Result;
9514     if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
9515         Result.isSigned() &&
9516         !((!StrictlyPositive && Result.isNonNegative()) ||
9517           (StrictlyPositive && Result.isStrictlyPositive()))) {
9518       SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
9519           << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
9520           << ValExpr->getSourceRange();
9521       return false;
9522     }
9523   }
9524   return true;
9525 }
9526 
9527 OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
9528                                              SourceLocation StartLoc,
9529                                              SourceLocation LParenLoc,
9530                                              SourceLocation EndLoc) {
9531   Expr *ValExpr = NumThreads;
9532   Stmt *HelperValStmt = nullptr;
9533 
9534   // OpenMP [2.5, Restrictions]
9535   //  The num_threads expression must evaluate to a positive integer value.
9536   if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
9537                                  /*StrictlyPositive=*/true))
9538     return nullptr;
9539 
9540   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
9541   OpenMPDirectiveKind CaptureRegion =
9542       getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads);
9543   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
9544     ValExpr = MakeFullExpr(ValExpr).get();
9545     llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
9546     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
9547     HelperValStmt = buildPreInits(Context, Captures);
9548   }
9549 
9550   return new (Context) OMPNumThreadsClause(
9551       ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
9552 }
9553 
9554 ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
9555                                                        OpenMPClauseKind CKind,
9556                                                        bool StrictlyPositive) {
9557   if (!E)
9558     return ExprError();
9559   if (E->isValueDependent() || E->isTypeDependent() ||
9560       E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
9561     return E;
9562   llvm::APSInt Result;
9563   ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
9564   if (ICE.isInvalid())
9565     return ExprError();
9566   if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
9567       (!StrictlyPositive && !Result.isNonNegative())) {
9568     Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
9569         << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
9570         << E->getSourceRange();
9571     return ExprError();
9572   }
9573   if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
9574     Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
9575         << E->getSourceRange();
9576     return ExprError();
9577   }
9578   if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
9579     DSAStack->setAssociatedLoops(Result.getExtValue());
9580   else if (CKind == OMPC_ordered)
9581     DSAStack->setAssociatedLoops(Result.getExtValue());
9582   return ICE;
9583 }
9584 
9585 OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
9586                                           SourceLocation LParenLoc,
9587                                           SourceLocation EndLoc) {
9588   // OpenMP [2.8.1, simd construct, Description]
9589   // The parameter of the safelen clause must be a constant
9590   // positive integer expression.
9591   ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
9592   if (Safelen.isInvalid())
9593     return nullptr;
9594   return new (Context)
9595       OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
9596 }
9597 
9598 OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
9599                                           SourceLocation LParenLoc,
9600                                           SourceLocation EndLoc) {
9601   // OpenMP [2.8.1, simd construct, Description]
9602   // The parameter of the simdlen clause must be a constant
9603   // positive integer expression.
9604   ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
9605   if (Simdlen.isInvalid())
9606     return nullptr;
9607   return new (Context)
9608       OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
9609 }
9610 
9611 /// Tries to find omp_allocator_handle_t type.
9612 static bool findOMPAllocatorHandleT(Sema &S, SourceLocation Loc,
9613                                     DSAStackTy *Stack) {
9614   QualType OMPAllocatorHandleT = Stack->getOMPAllocatorHandleT();
9615   if (!OMPAllocatorHandleT.isNull())
9616     return true;
9617   // Build the predefined allocator expressions.
9618   bool ErrorFound = false;
9619   for (int I = OMPAllocateDeclAttr::OMPDefaultMemAlloc;
9620        I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
9621     auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
9622     StringRef Allocator =
9623         OMPAllocateDeclAttr::ConvertAllocatorTypeTyToStr(AllocatorKind);
9624     DeclarationName AllocatorName = &S.getASTContext().Idents.get(Allocator);
9625     auto *VD = dyn_cast_or_null<ValueDecl>(
9626         S.LookupSingleName(S.TUScope, AllocatorName, Loc, Sema::LookupAnyName));
9627     if (!VD) {
9628       ErrorFound = true;
9629       break;
9630     }
9631     QualType AllocatorType =
9632         VD->getType().getNonLValueExprType(S.getASTContext());
9633     ExprResult Res = S.BuildDeclRefExpr(VD, AllocatorType, VK_LValue, Loc);
9634     if (!Res.isUsable()) {
9635       ErrorFound = true;
9636       break;
9637     }
9638     if (OMPAllocatorHandleT.isNull())
9639       OMPAllocatorHandleT = AllocatorType;
9640     if (!S.getASTContext().hasSameType(OMPAllocatorHandleT, AllocatorType)) {
9641       ErrorFound = true;
9642       break;
9643     }
9644     Stack->setAllocator(AllocatorKind, Res.get());
9645   }
9646   if (ErrorFound) {
9647     S.Diag(Loc, diag::err_implied_omp_allocator_handle_t_not_found);
9648     return false;
9649   }
9650   OMPAllocatorHandleT.addConst();
9651   Stack->setOMPAllocatorHandleT(OMPAllocatorHandleT);
9652   return true;
9653 }
9654 
9655 OMPClause *Sema::ActOnOpenMPAllocatorClause(Expr *A, SourceLocation StartLoc,
9656                                             SourceLocation LParenLoc,
9657                                             SourceLocation EndLoc) {
9658   // OpenMP [2.11.3, allocate Directive, Description]
9659   // allocator is an expression of omp_allocator_handle_t type.
9660   if (!findOMPAllocatorHandleT(*this, A->getExprLoc(), DSAStack))
9661     return nullptr;
9662 
9663   ExprResult Allocator = DefaultLvalueConversion(A);
9664   if (Allocator.isInvalid())
9665     return nullptr;
9666   Allocator = PerformImplicitConversion(Allocator.get(),
9667                                         DSAStack->getOMPAllocatorHandleT(),
9668                                         Sema::AA_Initializing,
9669                                         /*AllowExplicit=*/true);
9670   if (Allocator.isInvalid())
9671     return nullptr;
9672   return new (Context)
9673       OMPAllocatorClause(Allocator.get(), StartLoc, LParenLoc, EndLoc);
9674 }
9675 
9676 OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
9677                                            SourceLocation StartLoc,
9678                                            SourceLocation LParenLoc,
9679                                            SourceLocation EndLoc) {
9680   // OpenMP [2.7.1, loop construct, Description]
9681   // OpenMP [2.8.1, simd construct, Description]
9682   // OpenMP [2.9.6, distribute construct, Description]
9683   // The parameter of the collapse clause must be a constant
9684   // positive integer expression.
9685   ExprResult NumForLoopsResult =
9686       VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
9687   if (NumForLoopsResult.isInvalid())
9688     return nullptr;
9689   return new (Context)
9690       OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
9691 }
9692 
9693 OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
9694                                           SourceLocation EndLoc,
9695                                           SourceLocation LParenLoc,
9696                                           Expr *NumForLoops) {
9697   // OpenMP [2.7.1, loop construct, Description]
9698   // OpenMP [2.8.1, simd construct, Description]
9699   // OpenMP [2.9.6, distribute construct, Description]
9700   // The parameter of the ordered clause must be a constant
9701   // positive integer expression if any.
9702   if (NumForLoops && LParenLoc.isValid()) {
9703     ExprResult NumForLoopsResult =
9704         VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
9705     if (NumForLoopsResult.isInvalid())
9706       return nullptr;
9707     NumForLoops = NumForLoopsResult.get();
9708   } else {
9709     NumForLoops = nullptr;
9710   }
9711   auto *Clause = OMPOrderedClause::Create(
9712       Context, NumForLoops, NumForLoops ? DSAStack->getAssociatedLoops() : 0,
9713       StartLoc, LParenLoc, EndLoc);
9714   DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops, Clause);
9715   return Clause;
9716 }
9717 
9718 OMPClause *Sema::ActOnOpenMPSimpleClause(
9719     OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
9720     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
9721   OMPClause *Res = nullptr;
9722   switch (Kind) {
9723   case OMPC_default:
9724     Res =
9725         ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
9726                                  ArgumentLoc, StartLoc, LParenLoc, EndLoc);
9727     break;
9728   case OMPC_proc_bind:
9729     Res = ActOnOpenMPProcBindClause(
9730         static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
9731         LParenLoc, EndLoc);
9732     break;
9733   case OMPC_atomic_default_mem_order:
9734     Res = ActOnOpenMPAtomicDefaultMemOrderClause(
9735         static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Argument),
9736         ArgumentLoc, StartLoc, LParenLoc, EndLoc);
9737     break;
9738   case OMPC_if:
9739   case OMPC_final:
9740   case OMPC_num_threads:
9741   case OMPC_safelen:
9742   case OMPC_simdlen:
9743   case OMPC_allocator:
9744   case OMPC_collapse:
9745   case OMPC_schedule:
9746   case OMPC_private:
9747   case OMPC_firstprivate:
9748   case OMPC_lastprivate:
9749   case OMPC_shared:
9750   case OMPC_reduction:
9751   case OMPC_task_reduction:
9752   case OMPC_in_reduction:
9753   case OMPC_linear:
9754   case OMPC_aligned:
9755   case OMPC_copyin:
9756   case OMPC_copyprivate:
9757   case OMPC_ordered:
9758   case OMPC_nowait:
9759   case OMPC_untied:
9760   case OMPC_mergeable:
9761   case OMPC_threadprivate:
9762   case OMPC_allocate:
9763   case OMPC_flush:
9764   case OMPC_read:
9765   case OMPC_write:
9766   case OMPC_update:
9767   case OMPC_capture:
9768   case OMPC_seq_cst:
9769   case OMPC_depend:
9770   case OMPC_device:
9771   case OMPC_threads:
9772   case OMPC_simd:
9773   case OMPC_map:
9774   case OMPC_num_teams:
9775   case OMPC_thread_limit:
9776   case OMPC_priority:
9777   case OMPC_grainsize:
9778   case OMPC_nogroup:
9779   case OMPC_num_tasks:
9780   case OMPC_hint:
9781   case OMPC_dist_schedule:
9782   case OMPC_defaultmap:
9783   case OMPC_unknown:
9784   case OMPC_uniform:
9785   case OMPC_to:
9786   case OMPC_from:
9787   case OMPC_use_device_ptr:
9788   case OMPC_is_device_ptr:
9789   case OMPC_unified_address:
9790   case OMPC_unified_shared_memory:
9791   case OMPC_reverse_offload:
9792   case OMPC_dynamic_allocators:
9793     llvm_unreachable("Clause is not allowed.");
9794   }
9795   return Res;
9796 }
9797 
9798 static std::string
9799 getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
9800                         ArrayRef<unsigned> Exclude = llvm::None) {
9801   SmallString<256> Buffer;
9802   llvm::raw_svector_ostream Out(Buffer);
9803   unsigned Bound = Last >= 2 ? Last - 2 : 0;
9804   unsigned Skipped = Exclude.size();
9805   auto S = Exclude.begin(), E = Exclude.end();
9806   for (unsigned I = First; I < Last; ++I) {
9807     if (std::find(S, E, I) != E) {
9808       --Skipped;
9809       continue;
9810     }
9811     Out << "'" << getOpenMPSimpleClauseTypeName(K, I) << "'";
9812     if (I == Bound - Skipped)
9813       Out << " or ";
9814     else if (I != Bound + 1 - Skipped)
9815       Out << ", ";
9816   }
9817   return Out.str();
9818 }
9819 
9820 OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
9821                                           SourceLocation KindKwLoc,
9822                                           SourceLocation StartLoc,
9823                                           SourceLocation LParenLoc,
9824                                           SourceLocation EndLoc) {
9825   if (Kind == OMPC_DEFAULT_unknown) {
9826     static_assert(OMPC_DEFAULT_unknown > 0,
9827                   "OMPC_DEFAULT_unknown not greater than 0");
9828     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
9829         << getListOfPossibleValues(OMPC_default, /*First=*/0,
9830                                    /*Last=*/OMPC_DEFAULT_unknown)
9831         << getOpenMPClauseName(OMPC_default);
9832     return nullptr;
9833   }
9834   switch (Kind) {
9835   case OMPC_DEFAULT_none:
9836     DSAStack->setDefaultDSANone(KindKwLoc);
9837     break;
9838   case OMPC_DEFAULT_shared:
9839     DSAStack->setDefaultDSAShared(KindKwLoc);
9840     break;
9841   case OMPC_DEFAULT_unknown:
9842     llvm_unreachable("Clause kind is not allowed.");
9843     break;
9844   }
9845   return new (Context)
9846       OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
9847 }
9848 
9849 OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
9850                                            SourceLocation KindKwLoc,
9851                                            SourceLocation StartLoc,
9852                                            SourceLocation LParenLoc,
9853                                            SourceLocation EndLoc) {
9854   if (Kind == OMPC_PROC_BIND_unknown) {
9855     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
9856         << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
9857                                    /*Last=*/OMPC_PROC_BIND_unknown)
9858         << getOpenMPClauseName(OMPC_proc_bind);
9859     return nullptr;
9860   }
9861   return new (Context)
9862       OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
9863 }
9864 
9865 OMPClause *Sema::ActOnOpenMPAtomicDefaultMemOrderClause(
9866     OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindKwLoc,
9867     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
9868   if (Kind == OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown) {
9869     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
9870         << getListOfPossibleValues(
9871                OMPC_atomic_default_mem_order, /*First=*/0,
9872                /*Last=*/OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown)
9873         << getOpenMPClauseName(OMPC_atomic_default_mem_order);
9874     return nullptr;
9875   }
9876   return new (Context) OMPAtomicDefaultMemOrderClause(Kind, KindKwLoc, StartLoc,
9877                                                       LParenLoc, EndLoc);
9878 }
9879 
9880 OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
9881     OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
9882     SourceLocation StartLoc, SourceLocation LParenLoc,
9883     ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
9884     SourceLocation EndLoc) {
9885   OMPClause *Res = nullptr;
9886   switch (Kind) {
9887   case OMPC_schedule:
9888     enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
9889     assert(Argument.size() == NumberOfElements &&
9890            ArgumentLoc.size() == NumberOfElements);
9891     Res = ActOnOpenMPScheduleClause(
9892         static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
9893         static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
9894         static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
9895         StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
9896         ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
9897     break;
9898   case OMPC_if:
9899     assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
9900     Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
9901                               Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
9902                               DelimLoc, EndLoc);
9903     break;
9904   case OMPC_dist_schedule:
9905     Res = ActOnOpenMPDistScheduleClause(
9906         static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
9907         StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
9908     break;
9909   case OMPC_defaultmap:
9910     enum { Modifier, DefaultmapKind };
9911     Res = ActOnOpenMPDefaultmapClause(
9912         static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
9913         static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
9914         StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
9915         EndLoc);
9916     break;
9917   case OMPC_final:
9918   case OMPC_num_threads:
9919   case OMPC_safelen:
9920   case OMPC_simdlen:
9921   case OMPC_allocator:
9922   case OMPC_collapse:
9923   case OMPC_default:
9924   case OMPC_proc_bind:
9925   case OMPC_private:
9926   case OMPC_firstprivate:
9927   case OMPC_lastprivate:
9928   case OMPC_shared:
9929   case OMPC_reduction:
9930   case OMPC_task_reduction:
9931   case OMPC_in_reduction:
9932   case OMPC_linear:
9933   case OMPC_aligned:
9934   case OMPC_copyin:
9935   case OMPC_copyprivate:
9936   case OMPC_ordered:
9937   case OMPC_nowait:
9938   case OMPC_untied:
9939   case OMPC_mergeable:
9940   case OMPC_threadprivate:
9941   case OMPC_allocate:
9942   case OMPC_flush:
9943   case OMPC_read:
9944   case OMPC_write:
9945   case OMPC_update:
9946   case OMPC_capture:
9947   case OMPC_seq_cst:
9948   case OMPC_depend:
9949   case OMPC_device:
9950   case OMPC_threads:
9951   case OMPC_simd:
9952   case OMPC_map:
9953   case OMPC_num_teams:
9954   case OMPC_thread_limit:
9955   case OMPC_priority:
9956   case OMPC_grainsize:
9957   case OMPC_nogroup:
9958   case OMPC_num_tasks:
9959   case OMPC_hint:
9960   case OMPC_unknown:
9961   case OMPC_uniform:
9962   case OMPC_to:
9963   case OMPC_from:
9964   case OMPC_use_device_ptr:
9965   case OMPC_is_device_ptr:
9966   case OMPC_unified_address:
9967   case OMPC_unified_shared_memory:
9968   case OMPC_reverse_offload:
9969   case OMPC_dynamic_allocators:
9970   case OMPC_atomic_default_mem_order:
9971     llvm_unreachable("Clause is not allowed.");
9972   }
9973   return Res;
9974 }
9975 
9976 static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
9977                                    OpenMPScheduleClauseModifier M2,
9978                                    SourceLocation M1Loc, SourceLocation M2Loc) {
9979   if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
9980     SmallVector<unsigned, 2> Excluded;
9981     if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
9982       Excluded.push_back(M2);
9983     if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
9984       Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
9985     if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
9986       Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
9987     S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
9988         << getListOfPossibleValues(OMPC_schedule,
9989                                    /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
9990                                    /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
9991                                    Excluded)
9992         << getOpenMPClauseName(OMPC_schedule);
9993     return true;
9994   }
9995   return false;
9996 }
9997 
9998 OMPClause *Sema::ActOnOpenMPScheduleClause(
9999     OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
10000     OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
10001     SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
10002     SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
10003   if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
10004       checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
10005     return nullptr;
10006   // OpenMP, 2.7.1, Loop Construct, Restrictions
10007   // Either the monotonic modifier or the nonmonotonic modifier can be specified
10008   // but not both.
10009   if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
10010       (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
10011        M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
10012       (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
10013        M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
10014     Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
10015         << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
10016         << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
10017     return nullptr;
10018   }
10019   if (Kind == OMPC_SCHEDULE_unknown) {
10020     std::string Values;
10021     if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
10022       unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
10023       Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
10024                                        /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
10025                                        Exclude);
10026     } else {
10027       Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
10028                                        /*Last=*/OMPC_SCHEDULE_unknown);
10029     }
10030     Diag(KindLoc, diag::err_omp_unexpected_clause_value)
10031         << Values << getOpenMPClauseName(OMPC_schedule);
10032     return nullptr;
10033   }
10034   // OpenMP, 2.7.1, Loop Construct, Restrictions
10035   // The nonmonotonic modifier can only be specified with schedule(dynamic) or
10036   // schedule(guided).
10037   if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
10038        M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
10039       Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
10040     Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
10041          diag::err_omp_schedule_nonmonotonic_static);
10042     return nullptr;
10043   }
10044   Expr *ValExpr = ChunkSize;
10045   Stmt *HelperValStmt = nullptr;
10046   if (ChunkSize) {
10047     if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
10048         !ChunkSize->isInstantiationDependent() &&
10049         !ChunkSize->containsUnexpandedParameterPack()) {
10050       SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
10051       ExprResult Val =
10052           PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
10053       if (Val.isInvalid())
10054         return nullptr;
10055 
10056       ValExpr = Val.get();
10057 
10058       // OpenMP [2.7.1, Restrictions]
10059       //  chunk_size must be a loop invariant integer expression with a positive
10060       //  value.
10061       llvm::APSInt Result;
10062       if (ValExpr->isIntegerConstantExpr(Result, Context)) {
10063         if (Result.isSigned() && !Result.isStrictlyPositive()) {
10064           Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
10065               << "schedule" << 1 << ChunkSize->getSourceRange();
10066           return nullptr;
10067         }
10068       } else if (getOpenMPCaptureRegionForClause(
10069                      DSAStack->getCurrentDirective(), OMPC_schedule) !=
10070                      OMPD_unknown &&
10071                  !CurContext->isDependentContext()) {
10072         ValExpr = MakeFullExpr(ValExpr).get();
10073         llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
10074         ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
10075         HelperValStmt = buildPreInits(Context, Captures);
10076       }
10077     }
10078   }
10079 
10080   return new (Context)
10081       OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
10082                         ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
10083 }
10084 
10085 OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
10086                                    SourceLocation StartLoc,
10087                                    SourceLocation EndLoc) {
10088   OMPClause *Res = nullptr;
10089   switch (Kind) {
10090   case OMPC_ordered:
10091     Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
10092     break;
10093   case OMPC_nowait:
10094     Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
10095     break;
10096   case OMPC_untied:
10097     Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
10098     break;
10099   case OMPC_mergeable:
10100     Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
10101     break;
10102   case OMPC_read:
10103     Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
10104     break;
10105   case OMPC_write:
10106     Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
10107     break;
10108   case OMPC_update:
10109     Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
10110     break;
10111   case OMPC_capture:
10112     Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
10113     break;
10114   case OMPC_seq_cst:
10115     Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
10116     break;
10117   case OMPC_threads:
10118     Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
10119     break;
10120   case OMPC_simd:
10121     Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
10122     break;
10123   case OMPC_nogroup:
10124     Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
10125     break;
10126   case OMPC_unified_address:
10127     Res = ActOnOpenMPUnifiedAddressClause(StartLoc, EndLoc);
10128     break;
10129   case OMPC_unified_shared_memory:
10130     Res = ActOnOpenMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
10131     break;
10132   case OMPC_reverse_offload:
10133     Res = ActOnOpenMPReverseOffloadClause(StartLoc, EndLoc);
10134     break;
10135   case OMPC_dynamic_allocators:
10136     Res = ActOnOpenMPDynamicAllocatorsClause(StartLoc, EndLoc);
10137     break;
10138   case OMPC_if:
10139   case OMPC_final:
10140   case OMPC_num_threads:
10141   case OMPC_safelen:
10142   case OMPC_simdlen:
10143   case OMPC_allocator:
10144   case OMPC_collapse:
10145   case OMPC_schedule:
10146   case OMPC_private:
10147   case OMPC_firstprivate:
10148   case OMPC_lastprivate:
10149   case OMPC_shared:
10150   case OMPC_reduction:
10151   case OMPC_task_reduction:
10152   case OMPC_in_reduction:
10153   case OMPC_linear:
10154   case OMPC_aligned:
10155   case OMPC_copyin:
10156   case OMPC_copyprivate:
10157   case OMPC_default:
10158   case OMPC_proc_bind:
10159   case OMPC_threadprivate:
10160   case OMPC_allocate:
10161   case OMPC_flush:
10162   case OMPC_depend:
10163   case OMPC_device:
10164   case OMPC_map:
10165   case OMPC_num_teams:
10166   case OMPC_thread_limit:
10167   case OMPC_priority:
10168   case OMPC_grainsize:
10169   case OMPC_num_tasks:
10170   case OMPC_hint:
10171   case OMPC_dist_schedule:
10172   case OMPC_defaultmap:
10173   case OMPC_unknown:
10174   case OMPC_uniform:
10175   case OMPC_to:
10176   case OMPC_from:
10177   case OMPC_use_device_ptr:
10178   case OMPC_is_device_ptr:
10179   case OMPC_atomic_default_mem_order:
10180     llvm_unreachable("Clause is not allowed.");
10181   }
10182   return Res;
10183 }
10184 
10185 OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
10186                                          SourceLocation EndLoc) {
10187   DSAStack->setNowaitRegion();
10188   return new (Context) OMPNowaitClause(StartLoc, EndLoc);
10189 }
10190 
10191 OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
10192                                          SourceLocation EndLoc) {
10193   return new (Context) OMPUntiedClause(StartLoc, EndLoc);
10194 }
10195 
10196 OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
10197                                             SourceLocation EndLoc) {
10198   return new (Context) OMPMergeableClause(StartLoc, EndLoc);
10199 }
10200 
10201 OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
10202                                        SourceLocation EndLoc) {
10203   return new (Context) OMPReadClause(StartLoc, EndLoc);
10204 }
10205 
10206 OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
10207                                         SourceLocation EndLoc) {
10208   return new (Context) OMPWriteClause(StartLoc, EndLoc);
10209 }
10210 
10211 OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
10212                                          SourceLocation EndLoc) {
10213   return new (Context) OMPUpdateClause(StartLoc, EndLoc);
10214 }
10215 
10216 OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
10217                                           SourceLocation EndLoc) {
10218   return new (Context) OMPCaptureClause(StartLoc, EndLoc);
10219 }
10220 
10221 OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
10222                                          SourceLocation EndLoc) {
10223   return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
10224 }
10225 
10226 OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
10227                                           SourceLocation EndLoc) {
10228   return new (Context) OMPThreadsClause(StartLoc, EndLoc);
10229 }
10230 
10231 OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
10232                                        SourceLocation EndLoc) {
10233   return new (Context) OMPSIMDClause(StartLoc, EndLoc);
10234 }
10235 
10236 OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
10237                                           SourceLocation EndLoc) {
10238   return new (Context) OMPNogroupClause(StartLoc, EndLoc);
10239 }
10240 
10241 OMPClause *Sema::ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc,
10242                                                  SourceLocation EndLoc) {
10243   return new (Context) OMPUnifiedAddressClause(StartLoc, EndLoc);
10244 }
10245 
10246 OMPClause *Sema::ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc,
10247                                                       SourceLocation EndLoc) {
10248   return new (Context) OMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
10249 }
10250 
10251 OMPClause *Sema::ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc,
10252                                                  SourceLocation EndLoc) {
10253   return new (Context) OMPReverseOffloadClause(StartLoc, EndLoc);
10254 }
10255 
10256 OMPClause *Sema::ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc,
10257                                                     SourceLocation EndLoc) {
10258   return new (Context) OMPDynamicAllocatorsClause(StartLoc, EndLoc);
10259 }
10260 
10261 OMPClause *Sema::ActOnOpenMPVarListClause(
10262     OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
10263     const OMPVarListLocTy &Locs, SourceLocation ColonLoc,
10264     CXXScopeSpec &ReductionOrMapperIdScopeSpec,
10265     DeclarationNameInfo &ReductionOrMapperId, OpenMPDependClauseKind DepKind,
10266     OpenMPLinearClauseKind LinKind,
10267     ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
10268     ArrayRef<SourceLocation> MapTypeModifiersLoc, OpenMPMapClauseKind MapType,
10269     bool IsMapTypeImplicit, SourceLocation DepLinMapLoc) {
10270   SourceLocation StartLoc = Locs.StartLoc;
10271   SourceLocation LParenLoc = Locs.LParenLoc;
10272   SourceLocation EndLoc = Locs.EndLoc;
10273   OMPClause *Res = nullptr;
10274   switch (Kind) {
10275   case OMPC_private:
10276     Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
10277     break;
10278   case OMPC_firstprivate:
10279     Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
10280     break;
10281   case OMPC_lastprivate:
10282     Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
10283     break;
10284   case OMPC_shared:
10285     Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
10286     break;
10287   case OMPC_reduction:
10288     Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
10289                                      EndLoc, ReductionOrMapperIdScopeSpec,
10290                                      ReductionOrMapperId);
10291     break;
10292   case OMPC_task_reduction:
10293     Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
10294                                          EndLoc, ReductionOrMapperIdScopeSpec,
10295                                          ReductionOrMapperId);
10296     break;
10297   case OMPC_in_reduction:
10298     Res = ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
10299                                        EndLoc, ReductionOrMapperIdScopeSpec,
10300                                        ReductionOrMapperId);
10301     break;
10302   case OMPC_linear:
10303     Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
10304                                   LinKind, DepLinMapLoc, ColonLoc, EndLoc);
10305     break;
10306   case OMPC_aligned:
10307     Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
10308                                    ColonLoc, EndLoc);
10309     break;
10310   case OMPC_copyin:
10311     Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
10312     break;
10313   case OMPC_copyprivate:
10314     Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
10315     break;
10316   case OMPC_flush:
10317     Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
10318     break;
10319   case OMPC_depend:
10320     Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
10321                                   StartLoc, LParenLoc, EndLoc);
10322     break;
10323   case OMPC_map:
10324     Res = ActOnOpenMPMapClause(MapTypeModifiers, MapTypeModifiersLoc,
10325                                ReductionOrMapperIdScopeSpec,
10326                                ReductionOrMapperId, MapType, IsMapTypeImplicit,
10327                                DepLinMapLoc, ColonLoc, VarList, Locs);
10328     break;
10329   case OMPC_to:
10330     Res = ActOnOpenMPToClause(VarList, ReductionOrMapperIdScopeSpec,
10331                               ReductionOrMapperId, Locs);
10332     break;
10333   case OMPC_from:
10334     Res = ActOnOpenMPFromClause(VarList, ReductionOrMapperIdScopeSpec,
10335                                 ReductionOrMapperId, Locs);
10336     break;
10337   case OMPC_use_device_ptr:
10338     Res = ActOnOpenMPUseDevicePtrClause(VarList, Locs);
10339     break;
10340   case OMPC_is_device_ptr:
10341     Res = ActOnOpenMPIsDevicePtrClause(VarList, Locs);
10342     break;
10343   case OMPC_allocate:
10344     Res = ActOnOpenMPAllocateClause(TailExpr, VarList, StartLoc, LParenLoc,
10345                                     ColonLoc, EndLoc);
10346     break;
10347   case OMPC_if:
10348   case OMPC_final:
10349   case OMPC_num_threads:
10350   case OMPC_safelen:
10351   case OMPC_simdlen:
10352   case OMPC_allocator:
10353   case OMPC_collapse:
10354   case OMPC_default:
10355   case OMPC_proc_bind:
10356   case OMPC_schedule:
10357   case OMPC_ordered:
10358   case OMPC_nowait:
10359   case OMPC_untied:
10360   case OMPC_mergeable:
10361   case OMPC_threadprivate:
10362   case OMPC_read:
10363   case OMPC_write:
10364   case OMPC_update:
10365   case OMPC_capture:
10366   case OMPC_seq_cst:
10367   case OMPC_device:
10368   case OMPC_threads:
10369   case OMPC_simd:
10370   case OMPC_num_teams:
10371   case OMPC_thread_limit:
10372   case OMPC_priority:
10373   case OMPC_grainsize:
10374   case OMPC_nogroup:
10375   case OMPC_num_tasks:
10376   case OMPC_hint:
10377   case OMPC_dist_schedule:
10378   case OMPC_defaultmap:
10379   case OMPC_unknown:
10380   case OMPC_uniform:
10381   case OMPC_unified_address:
10382   case OMPC_unified_shared_memory:
10383   case OMPC_reverse_offload:
10384   case OMPC_dynamic_allocators:
10385   case OMPC_atomic_default_mem_order:
10386     llvm_unreachable("Clause is not allowed.");
10387   }
10388   return Res;
10389 }
10390 
10391 ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
10392                                        ExprObjectKind OK, SourceLocation Loc) {
10393   ExprResult Res = BuildDeclRefExpr(
10394       Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
10395   if (!Res.isUsable())
10396     return ExprError();
10397   if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
10398     Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
10399     if (!Res.isUsable())
10400       return ExprError();
10401   }
10402   if (VK != VK_LValue && Res.get()->isGLValue()) {
10403     Res = DefaultLvalueConversion(Res.get());
10404     if (!Res.isUsable())
10405       return ExprError();
10406   }
10407   return Res;
10408 }
10409 
10410 OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
10411                                           SourceLocation StartLoc,
10412                                           SourceLocation LParenLoc,
10413                                           SourceLocation EndLoc) {
10414   SmallVector<Expr *, 8> Vars;
10415   SmallVector<Expr *, 8> PrivateCopies;
10416   for (Expr *RefExpr : VarList) {
10417     assert(RefExpr && "NULL expr in OpenMP private clause.");
10418     SourceLocation ELoc;
10419     SourceRange ERange;
10420     Expr *SimpleRefExpr = RefExpr;
10421     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
10422     if (Res.second) {
10423       // It will be analyzed later.
10424       Vars.push_back(RefExpr);
10425       PrivateCopies.push_back(nullptr);
10426     }
10427     ValueDecl *D = Res.first;
10428     if (!D)
10429       continue;
10430 
10431     QualType Type = D->getType();
10432     auto *VD = dyn_cast<VarDecl>(D);
10433 
10434     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
10435     //  A variable that appears in a private clause must not have an incomplete
10436     //  type or a reference type.
10437     if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
10438       continue;
10439     Type = Type.getNonReferenceType();
10440 
10441     // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
10442     // A variable that is privatized must not have a const-qualified type
10443     // unless it is of class type with a mutable member. This restriction does
10444     // not apply to the firstprivate clause.
10445     //
10446     // OpenMP 3.1 [2.9.3.3, private clause, Restrictions]
10447     // A variable that appears in a private clause must not have a
10448     // const-qualified type unless it is of class type with a mutable member.
10449     if (rejectConstNotMutableType(*this, D, Type, OMPC_private, ELoc))
10450       continue;
10451 
10452     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
10453     // in a Construct]
10454     //  Variables with the predetermined data-sharing attributes may not be
10455     //  listed in data-sharing attributes clauses, except for the cases
10456     //  listed below. For these exceptions only, listing a predetermined
10457     //  variable in a data-sharing attribute clause is allowed and overrides
10458     //  the variable's predetermined data-sharing attributes.
10459     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
10460     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
10461       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
10462                                           << getOpenMPClauseName(OMPC_private);
10463       reportOriginalDsa(*this, DSAStack, D, DVar);
10464       continue;
10465     }
10466 
10467     OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
10468     // Variably modified types are not supported for tasks.
10469     if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
10470         isOpenMPTaskingDirective(CurrDir)) {
10471       Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
10472           << getOpenMPClauseName(OMPC_private) << Type
10473           << getOpenMPDirectiveName(CurrDir);
10474       bool IsDecl =
10475           !VD ||
10476           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
10477       Diag(D->getLocation(),
10478            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
10479           << D;
10480       continue;
10481     }
10482 
10483     // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
10484     // A list item cannot appear in both a map clause and a data-sharing
10485     // attribute clause on the same construct
10486     if (isOpenMPTargetExecutionDirective(CurrDir)) {
10487       OpenMPClauseKind ConflictKind;
10488       if (DSAStack->checkMappableExprComponentListsForDecl(
10489               VD, /*CurrentRegionOnly=*/true,
10490               [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
10491                   OpenMPClauseKind WhereFoundClauseKind) -> bool {
10492                 ConflictKind = WhereFoundClauseKind;
10493                 return true;
10494               })) {
10495         Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
10496             << getOpenMPClauseName(OMPC_private)
10497             << getOpenMPClauseName(ConflictKind)
10498             << getOpenMPDirectiveName(CurrDir);
10499         reportOriginalDsa(*this, DSAStack, D, DVar);
10500         continue;
10501       }
10502     }
10503 
10504     // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
10505     //  A variable of class type (or array thereof) that appears in a private
10506     //  clause requires an accessible, unambiguous default constructor for the
10507     //  class type.
10508     // Generate helper private variable and initialize it with the default
10509     // value. The address of the original variable is replaced by the address of
10510     // the new private variable in CodeGen. This new variable is not added to
10511     // IdResolver, so the code in the OpenMP region uses original variable for
10512     // proper diagnostics.
10513     Type = Type.getUnqualifiedType();
10514     VarDecl *VDPrivate =
10515         buildVarDecl(*this, ELoc, Type, D->getName(),
10516                      D->hasAttrs() ? &D->getAttrs() : nullptr,
10517                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
10518     ActOnUninitializedDecl(VDPrivate);
10519     if (VDPrivate->isInvalidDecl())
10520       continue;
10521     DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
10522         *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
10523 
10524     DeclRefExpr *Ref = nullptr;
10525     if (!VD && !CurContext->isDependentContext())
10526       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
10527     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
10528     Vars.push_back((VD || CurContext->isDependentContext())
10529                        ? RefExpr->IgnoreParens()
10530                        : Ref);
10531     PrivateCopies.push_back(VDPrivateRefExpr);
10532   }
10533 
10534   if (Vars.empty())
10535     return nullptr;
10536 
10537   return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
10538                                   PrivateCopies);
10539 }
10540 
10541 namespace {
10542 class DiagsUninitializedSeveretyRAII {
10543 private:
10544   DiagnosticsEngine &Diags;
10545   SourceLocation SavedLoc;
10546   bool IsIgnored = false;
10547 
10548 public:
10549   DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
10550                                  bool IsIgnored)
10551       : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
10552     if (!IsIgnored) {
10553       Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
10554                         /*Map*/ diag::Severity::Ignored, Loc);
10555     }
10556   }
10557   ~DiagsUninitializedSeveretyRAII() {
10558     if (!IsIgnored)
10559       Diags.popMappings(SavedLoc);
10560   }
10561 };
10562 }
10563 
10564 OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
10565                                                SourceLocation StartLoc,
10566                                                SourceLocation LParenLoc,
10567                                                SourceLocation EndLoc) {
10568   SmallVector<Expr *, 8> Vars;
10569   SmallVector<Expr *, 8> PrivateCopies;
10570   SmallVector<Expr *, 8> Inits;
10571   SmallVector<Decl *, 4> ExprCaptures;
10572   bool IsImplicitClause =
10573       StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
10574   SourceLocation ImplicitClauseLoc = DSAStack->getConstructLoc();
10575 
10576   for (Expr *RefExpr : VarList) {
10577     assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
10578     SourceLocation ELoc;
10579     SourceRange ERange;
10580     Expr *SimpleRefExpr = RefExpr;
10581     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
10582     if (Res.second) {
10583       // It will be analyzed later.
10584       Vars.push_back(RefExpr);
10585       PrivateCopies.push_back(nullptr);
10586       Inits.push_back(nullptr);
10587     }
10588     ValueDecl *D = Res.first;
10589     if (!D)
10590       continue;
10591 
10592     ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
10593     QualType Type = D->getType();
10594     auto *VD = dyn_cast<VarDecl>(D);
10595 
10596     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
10597     //  A variable that appears in a private clause must not have an incomplete
10598     //  type or a reference type.
10599     if (RequireCompleteType(ELoc, Type,
10600                             diag::err_omp_firstprivate_incomplete_type))
10601       continue;
10602     Type = Type.getNonReferenceType();
10603 
10604     // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
10605     //  A variable of class type (or array thereof) that appears in a private
10606     //  clause requires an accessible, unambiguous copy constructor for the
10607     //  class type.
10608     QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
10609 
10610     // If an implicit firstprivate variable found it was checked already.
10611     DSAStackTy::DSAVarData TopDVar;
10612     if (!IsImplicitClause) {
10613       DSAStackTy::DSAVarData DVar =
10614           DSAStack->getTopDSA(D, /*FromParent=*/false);
10615       TopDVar = DVar;
10616       OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
10617       bool IsConstant = ElemType.isConstant(Context);
10618       // OpenMP [2.4.13, Data-sharing Attribute Clauses]
10619       //  A list item that specifies a given variable may not appear in more
10620       // than one clause on the same directive, except that a variable may be
10621       //  specified in both firstprivate and lastprivate clauses.
10622       // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
10623       // A list item may appear in a firstprivate or lastprivate clause but not
10624       // both.
10625       if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
10626           (isOpenMPDistributeDirective(CurrDir) ||
10627            DVar.CKind != OMPC_lastprivate) &&
10628           DVar.RefExpr) {
10629         Diag(ELoc, diag::err_omp_wrong_dsa)
10630             << getOpenMPClauseName(DVar.CKind)
10631             << getOpenMPClauseName(OMPC_firstprivate);
10632         reportOriginalDsa(*this, DSAStack, D, DVar);
10633         continue;
10634       }
10635 
10636       // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
10637       // in a Construct]
10638       //  Variables with the predetermined data-sharing attributes may not be
10639       //  listed in data-sharing attributes clauses, except for the cases
10640       //  listed below. For these exceptions only, listing a predetermined
10641       //  variable in a data-sharing attribute clause is allowed and overrides
10642       //  the variable's predetermined data-sharing attributes.
10643       // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
10644       // in a Construct, C/C++, p.2]
10645       //  Variables with const-qualified type having no mutable member may be
10646       //  listed in a firstprivate clause, even if they are static data members.
10647       if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
10648           DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
10649         Diag(ELoc, diag::err_omp_wrong_dsa)
10650             << getOpenMPClauseName(DVar.CKind)
10651             << getOpenMPClauseName(OMPC_firstprivate);
10652         reportOriginalDsa(*this, DSAStack, D, DVar);
10653         continue;
10654       }
10655 
10656       // OpenMP [2.9.3.4, Restrictions, p.2]
10657       //  A list item that is private within a parallel region must not appear
10658       //  in a firstprivate clause on a worksharing construct if any of the
10659       //  worksharing regions arising from the worksharing construct ever bind
10660       //  to any of the parallel regions arising from the parallel construct.
10661       // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
10662       // A list item that is private within a teams region must not appear in a
10663       // firstprivate clause on a distribute construct if any of the distribute
10664       // regions arising from the distribute construct ever bind to any of the
10665       // teams regions arising from the teams construct.
10666       // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
10667       // A list item that appears in a reduction clause of a teams construct
10668       // must not appear in a firstprivate clause on a distribute construct if
10669       // any of the distribute regions arising from the distribute construct
10670       // ever bind to any of the teams regions arising from the teams construct.
10671       if ((isOpenMPWorksharingDirective(CurrDir) ||
10672            isOpenMPDistributeDirective(CurrDir)) &&
10673           !isOpenMPParallelDirective(CurrDir) &&
10674           !isOpenMPTeamsDirective(CurrDir)) {
10675         DVar = DSAStack->getImplicitDSA(D, true);
10676         if (DVar.CKind != OMPC_shared &&
10677             (isOpenMPParallelDirective(DVar.DKind) ||
10678              isOpenMPTeamsDirective(DVar.DKind) ||
10679              DVar.DKind == OMPD_unknown)) {
10680           Diag(ELoc, diag::err_omp_required_access)
10681               << getOpenMPClauseName(OMPC_firstprivate)
10682               << getOpenMPClauseName(OMPC_shared);
10683           reportOriginalDsa(*this, DSAStack, D, DVar);
10684           continue;
10685         }
10686       }
10687       // OpenMP [2.9.3.4, Restrictions, p.3]
10688       //  A list item that appears in a reduction clause of a parallel construct
10689       //  must not appear in a firstprivate clause on a worksharing or task
10690       //  construct if any of the worksharing or task regions arising from the
10691       //  worksharing or task construct ever bind to any of the parallel regions
10692       //  arising from the parallel construct.
10693       // OpenMP [2.9.3.4, Restrictions, p.4]
10694       //  A list item that appears in a reduction clause in worksharing
10695       //  construct must not appear in a firstprivate clause in a task construct
10696       //  encountered during execution of any of the worksharing regions arising
10697       //  from the worksharing construct.
10698       if (isOpenMPTaskingDirective(CurrDir)) {
10699         DVar = DSAStack->hasInnermostDSA(
10700             D, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
10701             [](OpenMPDirectiveKind K) {
10702               return isOpenMPParallelDirective(K) ||
10703                      isOpenMPWorksharingDirective(K) ||
10704                      isOpenMPTeamsDirective(K);
10705             },
10706             /*FromParent=*/true);
10707         if (DVar.CKind == OMPC_reduction &&
10708             (isOpenMPParallelDirective(DVar.DKind) ||
10709              isOpenMPWorksharingDirective(DVar.DKind) ||
10710              isOpenMPTeamsDirective(DVar.DKind))) {
10711           Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
10712               << getOpenMPDirectiveName(DVar.DKind);
10713           reportOriginalDsa(*this, DSAStack, D, DVar);
10714           continue;
10715         }
10716       }
10717 
10718       // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
10719       // A list item cannot appear in both a map clause and a data-sharing
10720       // attribute clause on the same construct
10721       if (isOpenMPTargetExecutionDirective(CurrDir)) {
10722         OpenMPClauseKind ConflictKind;
10723         if (DSAStack->checkMappableExprComponentListsForDecl(
10724                 VD, /*CurrentRegionOnly=*/true,
10725                 [&ConflictKind](
10726                     OMPClauseMappableExprCommon::MappableExprComponentListRef,
10727                     OpenMPClauseKind WhereFoundClauseKind) {
10728                   ConflictKind = WhereFoundClauseKind;
10729                   return true;
10730                 })) {
10731           Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
10732               << getOpenMPClauseName(OMPC_firstprivate)
10733               << getOpenMPClauseName(ConflictKind)
10734               << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
10735           reportOriginalDsa(*this, DSAStack, D, DVar);
10736           continue;
10737         }
10738       }
10739     }
10740 
10741     // Variably modified types are not supported for tasks.
10742     if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
10743         isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
10744       Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
10745           << getOpenMPClauseName(OMPC_firstprivate) << Type
10746           << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
10747       bool IsDecl =
10748           !VD ||
10749           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
10750       Diag(D->getLocation(),
10751            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
10752           << D;
10753       continue;
10754     }
10755 
10756     Type = Type.getUnqualifiedType();
10757     VarDecl *VDPrivate =
10758         buildVarDecl(*this, ELoc, Type, D->getName(),
10759                      D->hasAttrs() ? &D->getAttrs() : nullptr,
10760                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
10761     // Generate helper private variable and initialize it with the value of the
10762     // original variable. The address of the original variable is replaced by
10763     // the address of the new private variable in the CodeGen. This new variable
10764     // is not added to IdResolver, so the code in the OpenMP region uses
10765     // original variable for proper diagnostics and variable capturing.
10766     Expr *VDInitRefExpr = nullptr;
10767     // For arrays generate initializer for single element and replace it by the
10768     // original array element in CodeGen.
10769     if (Type->isArrayType()) {
10770       VarDecl *VDInit =
10771           buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
10772       VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
10773       Expr *Init = DefaultLvalueConversion(VDInitRefExpr).get();
10774       ElemType = ElemType.getUnqualifiedType();
10775       VarDecl *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
10776                                          ".firstprivate.temp");
10777       InitializedEntity Entity =
10778           InitializedEntity::InitializeVariable(VDInitTemp);
10779       InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
10780 
10781       InitializationSequence InitSeq(*this, Entity, Kind, Init);
10782       ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
10783       if (Result.isInvalid())
10784         VDPrivate->setInvalidDecl();
10785       else
10786         VDPrivate->setInit(Result.getAs<Expr>());
10787       // Remove temp variable declaration.
10788       Context.Deallocate(VDInitTemp);
10789     } else {
10790       VarDecl *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
10791                                      ".firstprivate.temp");
10792       VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
10793                                        RefExpr->getExprLoc());
10794       AddInitializerToDecl(VDPrivate,
10795                            DefaultLvalueConversion(VDInitRefExpr).get(),
10796                            /*DirectInit=*/false);
10797     }
10798     if (VDPrivate->isInvalidDecl()) {
10799       if (IsImplicitClause) {
10800         Diag(RefExpr->getExprLoc(),
10801              diag::note_omp_task_predetermined_firstprivate_here);
10802       }
10803       continue;
10804     }
10805     CurContext->addDecl(VDPrivate);
10806     DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
10807         *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
10808         RefExpr->getExprLoc());
10809     DeclRefExpr *Ref = nullptr;
10810     if (!VD && !CurContext->isDependentContext()) {
10811       if (TopDVar.CKind == OMPC_lastprivate) {
10812         Ref = TopDVar.PrivateCopy;
10813       } else {
10814         Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
10815         if (!isOpenMPCapturedDecl(D))
10816           ExprCaptures.push_back(Ref->getDecl());
10817       }
10818     }
10819     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
10820     Vars.push_back((VD || CurContext->isDependentContext())
10821                        ? RefExpr->IgnoreParens()
10822                        : Ref);
10823     PrivateCopies.push_back(VDPrivateRefExpr);
10824     Inits.push_back(VDInitRefExpr);
10825   }
10826 
10827   if (Vars.empty())
10828     return nullptr;
10829 
10830   return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
10831                                        Vars, PrivateCopies, Inits,
10832                                        buildPreInits(Context, ExprCaptures));
10833 }
10834 
10835 OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
10836                                               SourceLocation StartLoc,
10837                                               SourceLocation LParenLoc,
10838                                               SourceLocation EndLoc) {
10839   SmallVector<Expr *, 8> Vars;
10840   SmallVector<Expr *, 8> SrcExprs;
10841   SmallVector<Expr *, 8> DstExprs;
10842   SmallVector<Expr *, 8> AssignmentOps;
10843   SmallVector<Decl *, 4> ExprCaptures;
10844   SmallVector<Expr *, 4> ExprPostUpdates;
10845   for (Expr *RefExpr : VarList) {
10846     assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
10847     SourceLocation ELoc;
10848     SourceRange ERange;
10849     Expr *SimpleRefExpr = RefExpr;
10850     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
10851     if (Res.second) {
10852       // It will be analyzed later.
10853       Vars.push_back(RefExpr);
10854       SrcExprs.push_back(nullptr);
10855       DstExprs.push_back(nullptr);
10856       AssignmentOps.push_back(nullptr);
10857     }
10858     ValueDecl *D = Res.first;
10859     if (!D)
10860       continue;
10861 
10862     QualType Type = D->getType();
10863     auto *VD = dyn_cast<VarDecl>(D);
10864 
10865     // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
10866     //  A variable that appears in a lastprivate clause must not have an
10867     //  incomplete type or a reference type.
10868     if (RequireCompleteType(ELoc, Type,
10869                             diag::err_omp_lastprivate_incomplete_type))
10870       continue;
10871     Type = Type.getNonReferenceType();
10872 
10873     // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
10874     // A variable that is privatized must not have a const-qualified type
10875     // unless it is of class type with a mutable member. This restriction does
10876     // not apply to the firstprivate clause.
10877     //
10878     // OpenMP 3.1 [2.9.3.5, lastprivate clause, Restrictions]
10879     // A variable that appears in a lastprivate clause must not have a
10880     // const-qualified type unless it is of class type with a mutable member.
10881     if (rejectConstNotMutableType(*this, D, Type, OMPC_lastprivate, ELoc))
10882       continue;
10883 
10884     OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
10885     // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
10886     // in a Construct]
10887     //  Variables with the predetermined data-sharing attributes may not be
10888     //  listed in data-sharing attributes clauses, except for the cases
10889     //  listed below.
10890     // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
10891     // A list item may appear in a firstprivate or lastprivate clause but not
10892     // both.
10893     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
10894     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
10895         (isOpenMPDistributeDirective(CurrDir) ||
10896          DVar.CKind != OMPC_firstprivate) &&
10897         (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
10898       Diag(ELoc, diag::err_omp_wrong_dsa)
10899           << getOpenMPClauseName(DVar.CKind)
10900           << getOpenMPClauseName(OMPC_lastprivate);
10901       reportOriginalDsa(*this, DSAStack, D, DVar);
10902       continue;
10903     }
10904 
10905     // OpenMP [2.14.3.5, Restrictions, p.2]
10906     // A list item that is private within a parallel region, or that appears in
10907     // the reduction clause of a parallel construct, must not appear in a
10908     // lastprivate clause on a worksharing construct if any of the corresponding
10909     // worksharing regions ever binds to any of the corresponding parallel
10910     // regions.
10911     DSAStackTy::DSAVarData TopDVar = DVar;
10912     if (isOpenMPWorksharingDirective(CurrDir) &&
10913         !isOpenMPParallelDirective(CurrDir) &&
10914         !isOpenMPTeamsDirective(CurrDir)) {
10915       DVar = DSAStack->getImplicitDSA(D, true);
10916       if (DVar.CKind != OMPC_shared) {
10917         Diag(ELoc, diag::err_omp_required_access)
10918             << getOpenMPClauseName(OMPC_lastprivate)
10919             << getOpenMPClauseName(OMPC_shared);
10920         reportOriginalDsa(*this, DSAStack, D, DVar);
10921         continue;
10922       }
10923     }
10924 
10925     // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
10926     //  A variable of class type (or array thereof) that appears in a
10927     //  lastprivate clause requires an accessible, unambiguous default
10928     //  constructor for the class type, unless the list item is also specified
10929     //  in a firstprivate clause.
10930     //  A variable of class type (or array thereof) that appears in a
10931     //  lastprivate clause requires an accessible, unambiguous copy assignment
10932     //  operator for the class type.
10933     Type = Context.getBaseElementType(Type).getNonReferenceType();
10934     VarDecl *SrcVD = buildVarDecl(*this, ERange.getBegin(),
10935                                   Type.getUnqualifiedType(), ".lastprivate.src",
10936                                   D->hasAttrs() ? &D->getAttrs() : nullptr);
10937     DeclRefExpr *PseudoSrcExpr =
10938         buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
10939     VarDecl *DstVD =
10940         buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
10941                      D->hasAttrs() ? &D->getAttrs() : nullptr);
10942     DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
10943     // For arrays generate assignment operation for single element and replace
10944     // it by the original array element in CodeGen.
10945     ExprResult AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
10946                                          PseudoDstExpr, PseudoSrcExpr);
10947     if (AssignmentOp.isInvalid())
10948       continue;
10949     AssignmentOp =
10950         ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
10951     if (AssignmentOp.isInvalid())
10952       continue;
10953 
10954     DeclRefExpr *Ref = nullptr;
10955     if (!VD && !CurContext->isDependentContext()) {
10956       if (TopDVar.CKind == OMPC_firstprivate) {
10957         Ref = TopDVar.PrivateCopy;
10958       } else {
10959         Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
10960         if (!isOpenMPCapturedDecl(D))
10961           ExprCaptures.push_back(Ref->getDecl());
10962       }
10963       if (TopDVar.CKind == OMPC_firstprivate ||
10964           (!isOpenMPCapturedDecl(D) &&
10965            Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
10966         ExprResult RefRes = DefaultLvalueConversion(Ref);
10967         if (!RefRes.isUsable())
10968           continue;
10969         ExprResult PostUpdateRes =
10970             BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
10971                        RefRes.get());
10972         if (!PostUpdateRes.isUsable())
10973           continue;
10974         ExprPostUpdates.push_back(
10975             IgnoredValueConversions(PostUpdateRes.get()).get());
10976       }
10977     }
10978     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
10979     Vars.push_back((VD || CurContext->isDependentContext())
10980                        ? RefExpr->IgnoreParens()
10981                        : Ref);
10982     SrcExprs.push_back(PseudoSrcExpr);
10983     DstExprs.push_back(PseudoDstExpr);
10984     AssignmentOps.push_back(AssignmentOp.get());
10985   }
10986 
10987   if (Vars.empty())
10988     return nullptr;
10989 
10990   return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
10991                                       Vars, SrcExprs, DstExprs, AssignmentOps,
10992                                       buildPreInits(Context, ExprCaptures),
10993                                       buildPostUpdate(*this, ExprPostUpdates));
10994 }
10995 
10996 OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
10997                                          SourceLocation StartLoc,
10998                                          SourceLocation LParenLoc,
10999                                          SourceLocation EndLoc) {
11000   SmallVector<Expr *, 8> Vars;
11001   for (Expr *RefExpr : VarList) {
11002     assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
11003     SourceLocation ELoc;
11004     SourceRange ERange;
11005     Expr *SimpleRefExpr = RefExpr;
11006     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
11007     if (Res.second) {
11008       // It will be analyzed later.
11009       Vars.push_back(RefExpr);
11010     }
11011     ValueDecl *D = Res.first;
11012     if (!D)
11013       continue;
11014 
11015     auto *VD = dyn_cast<VarDecl>(D);
11016     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
11017     // in a Construct]
11018     //  Variables with the predetermined data-sharing attributes may not be
11019     //  listed in data-sharing attributes clauses, except for the cases
11020     //  listed below. For these exceptions only, listing a predetermined
11021     //  variable in a data-sharing attribute clause is allowed and overrides
11022     //  the variable's predetermined data-sharing attributes.
11023     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
11024     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
11025         DVar.RefExpr) {
11026       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
11027                                           << getOpenMPClauseName(OMPC_shared);
11028       reportOriginalDsa(*this, DSAStack, D, DVar);
11029       continue;
11030     }
11031 
11032     DeclRefExpr *Ref = nullptr;
11033     if (!VD && isOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
11034       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
11035     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
11036     Vars.push_back((VD || !Ref || CurContext->isDependentContext())
11037                        ? RefExpr->IgnoreParens()
11038                        : Ref);
11039   }
11040 
11041   if (Vars.empty())
11042     return nullptr;
11043 
11044   return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
11045 }
11046 
11047 namespace {
11048 class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
11049   DSAStackTy *Stack;
11050 
11051 public:
11052   bool VisitDeclRefExpr(DeclRefExpr *E) {
11053     if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
11054       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
11055       if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
11056         return false;
11057       if (DVar.CKind != OMPC_unknown)
11058         return true;
11059       DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
11060           VD, isOpenMPPrivate, [](OpenMPDirectiveKind) { return true; },
11061           /*FromParent=*/true);
11062       return DVarPrivate.CKind != OMPC_unknown;
11063     }
11064     return false;
11065   }
11066   bool VisitStmt(Stmt *S) {
11067     for (Stmt *Child : S->children()) {
11068       if (Child && Visit(Child))
11069         return true;
11070     }
11071     return false;
11072   }
11073   explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
11074 };
11075 } // namespace
11076 
11077 namespace {
11078 // Transform MemberExpression for specified FieldDecl of current class to
11079 // DeclRefExpr to specified OMPCapturedExprDecl.
11080 class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
11081   typedef TreeTransform<TransformExprToCaptures> BaseTransform;
11082   ValueDecl *Field = nullptr;
11083   DeclRefExpr *CapturedExpr = nullptr;
11084 
11085 public:
11086   TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
11087       : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
11088 
11089   ExprResult TransformMemberExpr(MemberExpr *E) {
11090     if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
11091         E->getMemberDecl() == Field) {
11092       CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
11093       return CapturedExpr;
11094     }
11095     return BaseTransform::TransformMemberExpr(E);
11096   }
11097   DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
11098 };
11099 } // namespace
11100 
11101 template <typename T, typename U>
11102 static T filterLookupForUDReductionAndMapper(
11103     SmallVectorImpl<U> &Lookups, const llvm::function_ref<T(ValueDecl *)> Gen) {
11104   for (U &Set : Lookups) {
11105     for (auto *D : Set) {
11106       if (T Res = Gen(cast<ValueDecl>(D)))
11107         return Res;
11108     }
11109   }
11110   return T();
11111 }
11112 
11113 static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) {
11114   assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case");
11115 
11116   for (auto RD : D->redecls()) {
11117     // Don't bother with extra checks if we already know this one isn't visible.
11118     if (RD == D)
11119       continue;
11120 
11121     auto ND = cast<NamedDecl>(RD);
11122     if (LookupResult::isVisible(SemaRef, ND))
11123       return ND;
11124   }
11125 
11126   return nullptr;
11127 }
11128 
11129 static void
11130 argumentDependentLookup(Sema &SemaRef, const DeclarationNameInfo &Id,
11131                         SourceLocation Loc, QualType Ty,
11132                         SmallVectorImpl<UnresolvedSet<8>> &Lookups) {
11133   // Find all of the associated namespaces and classes based on the
11134   // arguments we have.
11135   Sema::AssociatedNamespaceSet AssociatedNamespaces;
11136   Sema::AssociatedClassSet AssociatedClasses;
11137   OpaqueValueExpr OVE(Loc, Ty, VK_LValue);
11138   SemaRef.FindAssociatedClassesAndNamespaces(Loc, &OVE, AssociatedNamespaces,
11139                                              AssociatedClasses);
11140 
11141   // C++ [basic.lookup.argdep]p3:
11142   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
11143   //   and let Y be the lookup set produced by argument dependent
11144   //   lookup (defined as follows). If X contains [...] then Y is
11145   //   empty. Otherwise Y is the set of declarations found in the
11146   //   namespaces associated with the argument types as described
11147   //   below. The set of declarations found by the lookup of the name
11148   //   is the union of X and Y.
11149   //
11150   // Here, we compute Y and add its members to the overloaded
11151   // candidate set.
11152   for (auto *NS : AssociatedNamespaces) {
11153     //   When considering an associated namespace, the lookup is the
11154     //   same as the lookup performed when the associated namespace is
11155     //   used as a qualifier (3.4.3.2) except that:
11156     //
11157     //     -- Any using-directives in the associated namespace are
11158     //        ignored.
11159     //
11160     //     -- Any namespace-scope friend functions declared in
11161     //        associated classes are visible within their respective
11162     //        namespaces even if they are not visible during an ordinary
11163     //        lookup (11.4).
11164     DeclContext::lookup_result R = NS->lookup(Id.getName());
11165     for (auto *D : R) {
11166       auto *Underlying = D;
11167       if (auto *USD = dyn_cast<UsingShadowDecl>(D))
11168         Underlying = USD->getTargetDecl();
11169 
11170       if (!isa<OMPDeclareReductionDecl>(Underlying) &&
11171           !isa<OMPDeclareMapperDecl>(Underlying))
11172         continue;
11173 
11174       if (!SemaRef.isVisible(D)) {
11175         D = findAcceptableDecl(SemaRef, D);
11176         if (!D)
11177           continue;
11178         if (auto *USD = dyn_cast<UsingShadowDecl>(D))
11179           Underlying = USD->getTargetDecl();
11180       }
11181       Lookups.emplace_back();
11182       Lookups.back().addDecl(Underlying);
11183     }
11184   }
11185 }
11186 
11187 static ExprResult
11188 buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
11189                          Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
11190                          const DeclarationNameInfo &ReductionId, QualType Ty,
11191                          CXXCastPath &BasePath, Expr *UnresolvedReduction) {
11192   if (ReductionIdScopeSpec.isInvalid())
11193     return ExprError();
11194   SmallVector<UnresolvedSet<8>, 4> Lookups;
11195   if (S) {
11196     LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
11197     Lookup.suppressDiagnostics();
11198     while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
11199       NamedDecl *D = Lookup.getRepresentativeDecl();
11200       do {
11201         S = S->getParent();
11202       } while (S && !S->isDeclScope(D));
11203       if (S)
11204         S = S->getParent();
11205       Lookups.emplace_back();
11206       Lookups.back().append(Lookup.begin(), Lookup.end());
11207       Lookup.clear();
11208     }
11209   } else if (auto *ULE =
11210                  cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
11211     Lookups.push_back(UnresolvedSet<8>());
11212     Decl *PrevD = nullptr;
11213     for (NamedDecl *D : ULE->decls()) {
11214       if (D == PrevD)
11215         Lookups.push_back(UnresolvedSet<8>());
11216       else if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(D))
11217         Lookups.back().addDecl(DRD);
11218       PrevD = D;
11219     }
11220   }
11221   if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() ||
11222       Ty->isInstantiationDependentType() ||
11223       Ty->containsUnexpandedParameterPack() ||
11224       filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
11225         return !D->isInvalidDecl() &&
11226                (D->getType()->isDependentType() ||
11227                 D->getType()->isInstantiationDependentType() ||
11228                 D->getType()->containsUnexpandedParameterPack());
11229       })) {
11230     UnresolvedSet<8> ResSet;
11231     for (const UnresolvedSet<8> &Set : Lookups) {
11232       if (Set.empty())
11233         continue;
11234       ResSet.append(Set.begin(), Set.end());
11235       // The last item marks the end of all declarations at the specified scope.
11236       ResSet.addDecl(Set[Set.size() - 1]);
11237     }
11238     return UnresolvedLookupExpr::Create(
11239         SemaRef.Context, /*NamingClass=*/nullptr,
11240         ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
11241         /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
11242   }
11243   // Lookup inside the classes.
11244   // C++ [over.match.oper]p3:
11245   //   For a unary operator @ with an operand of a type whose
11246   //   cv-unqualified version is T1, and for a binary operator @ with
11247   //   a left operand of a type whose cv-unqualified version is T1 and
11248   //   a right operand of a type whose cv-unqualified version is T2,
11249   //   three sets of candidate functions, designated member
11250   //   candidates, non-member candidates and built-in candidates, are
11251   //   constructed as follows:
11252   //     -- If T1 is a complete class type or a class currently being
11253   //        defined, the set of member candidates is the result of the
11254   //        qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
11255   //        the set of member candidates is empty.
11256   LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
11257   Lookup.suppressDiagnostics();
11258   if (const auto *TyRec = Ty->getAs<RecordType>()) {
11259     // Complete the type if it can be completed.
11260     // If the type is neither complete nor being defined, bail out now.
11261     if (SemaRef.isCompleteType(Loc, Ty) || TyRec->isBeingDefined() ||
11262         TyRec->getDecl()->getDefinition()) {
11263       Lookup.clear();
11264       SemaRef.LookupQualifiedName(Lookup, TyRec->getDecl());
11265       if (Lookup.empty()) {
11266         Lookups.emplace_back();
11267         Lookups.back().append(Lookup.begin(), Lookup.end());
11268       }
11269     }
11270   }
11271   // Perform ADL.
11272   if (SemaRef.getLangOpts().CPlusPlus) {
11273     argumentDependentLookup(SemaRef, ReductionId, Loc, Ty, Lookups);
11274     if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
11275             Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
11276               if (!D->isInvalidDecl() &&
11277                   SemaRef.Context.hasSameType(D->getType(), Ty))
11278                 return D;
11279               return nullptr;
11280             }))
11281       return SemaRef.BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(),
11282                                       VK_LValue, Loc);
11283     if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
11284             Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
11285               if (!D->isInvalidDecl() &&
11286                   SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
11287                   !Ty.isMoreQualifiedThan(D->getType()))
11288                 return D;
11289               return nullptr;
11290             })) {
11291       CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
11292                          /*DetectVirtual=*/false);
11293       if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
11294         if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
11295                 VD->getType().getUnqualifiedType()))) {
11296           if (SemaRef.CheckBaseClassAccess(
11297                   Loc, VD->getType(), Ty, Paths.front(),
11298                   /*DiagID=*/0) != Sema::AR_inaccessible) {
11299             SemaRef.BuildBasePathArray(Paths, BasePath);
11300             return SemaRef.BuildDeclRefExpr(
11301                 VD, VD->getType().getNonReferenceType(), VK_LValue, Loc);
11302           }
11303         }
11304       }
11305     }
11306   }
11307   if (ReductionIdScopeSpec.isSet()) {
11308     SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
11309     return ExprError();
11310   }
11311   return ExprEmpty();
11312 }
11313 
11314 namespace {
11315 /// Data for the reduction-based clauses.
11316 struct ReductionData {
11317   /// List of original reduction items.
11318   SmallVector<Expr *, 8> Vars;
11319   /// List of private copies of the reduction items.
11320   SmallVector<Expr *, 8> Privates;
11321   /// LHS expressions for the reduction_op expressions.
11322   SmallVector<Expr *, 8> LHSs;
11323   /// RHS expressions for the reduction_op expressions.
11324   SmallVector<Expr *, 8> RHSs;
11325   /// Reduction operation expression.
11326   SmallVector<Expr *, 8> ReductionOps;
11327   /// Taskgroup descriptors for the corresponding reduction items in
11328   /// in_reduction clauses.
11329   SmallVector<Expr *, 8> TaskgroupDescriptors;
11330   /// List of captures for clause.
11331   SmallVector<Decl *, 4> ExprCaptures;
11332   /// List of postupdate expressions.
11333   SmallVector<Expr *, 4> ExprPostUpdates;
11334   ReductionData() = delete;
11335   /// Reserves required memory for the reduction data.
11336   ReductionData(unsigned Size) {
11337     Vars.reserve(Size);
11338     Privates.reserve(Size);
11339     LHSs.reserve(Size);
11340     RHSs.reserve(Size);
11341     ReductionOps.reserve(Size);
11342     TaskgroupDescriptors.reserve(Size);
11343     ExprCaptures.reserve(Size);
11344     ExprPostUpdates.reserve(Size);
11345   }
11346   /// Stores reduction item and reduction operation only (required for dependent
11347   /// reduction item).
11348   void push(Expr *Item, Expr *ReductionOp) {
11349     Vars.emplace_back(Item);
11350     Privates.emplace_back(nullptr);
11351     LHSs.emplace_back(nullptr);
11352     RHSs.emplace_back(nullptr);
11353     ReductionOps.emplace_back(ReductionOp);
11354     TaskgroupDescriptors.emplace_back(nullptr);
11355   }
11356   /// Stores reduction data.
11357   void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp,
11358             Expr *TaskgroupDescriptor) {
11359     Vars.emplace_back(Item);
11360     Privates.emplace_back(Private);
11361     LHSs.emplace_back(LHS);
11362     RHSs.emplace_back(RHS);
11363     ReductionOps.emplace_back(ReductionOp);
11364     TaskgroupDescriptors.emplace_back(TaskgroupDescriptor);
11365   }
11366 };
11367 } // namespace
11368 
11369 static bool checkOMPArraySectionConstantForReduction(
11370     ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement,
11371     SmallVectorImpl<llvm::APSInt> &ArraySizes) {
11372   const Expr *Length = OASE->getLength();
11373   if (Length == nullptr) {
11374     // For array sections of the form [1:] or [:], we would need to analyze
11375     // the lower bound...
11376     if (OASE->getColonLoc().isValid())
11377       return false;
11378 
11379     // This is an array subscript which has implicit length 1!
11380     SingleElement = true;
11381     ArraySizes.push_back(llvm::APSInt::get(1));
11382   } else {
11383     Expr::EvalResult Result;
11384     if (!Length->EvaluateAsInt(Result, Context))
11385       return false;
11386 
11387     llvm::APSInt ConstantLengthValue = Result.Val.getInt();
11388     SingleElement = (ConstantLengthValue.getSExtValue() == 1);
11389     ArraySizes.push_back(ConstantLengthValue);
11390   }
11391 
11392   // Get the base of this array section and walk up from there.
11393   const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
11394 
11395   // We require length = 1 for all array sections except the right-most to
11396   // guarantee that the memory region is contiguous and has no holes in it.
11397   while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) {
11398     Length = TempOASE->getLength();
11399     if (Length == nullptr) {
11400       // For array sections of the form [1:] or [:], we would need to analyze
11401       // the lower bound...
11402       if (OASE->getColonLoc().isValid())
11403         return false;
11404 
11405       // This is an array subscript which has implicit length 1!
11406       ArraySizes.push_back(llvm::APSInt::get(1));
11407     } else {
11408       Expr::EvalResult Result;
11409       if (!Length->EvaluateAsInt(Result, Context))
11410         return false;
11411 
11412       llvm::APSInt ConstantLengthValue = Result.Val.getInt();
11413       if (ConstantLengthValue.getSExtValue() != 1)
11414         return false;
11415 
11416       ArraySizes.push_back(ConstantLengthValue);
11417     }
11418     Base = TempOASE->getBase()->IgnoreParenImpCasts();
11419   }
11420 
11421   // If we have a single element, we don't need to add the implicit lengths.
11422   if (!SingleElement) {
11423     while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) {
11424       // Has implicit length 1!
11425       ArraySizes.push_back(llvm::APSInt::get(1));
11426       Base = TempASE->getBase()->IgnoreParenImpCasts();
11427     }
11428   }
11429 
11430   // This array section can be privatized as a single value or as a constant
11431   // sized array.
11432   return true;
11433 }
11434 
11435 static bool actOnOMPReductionKindClause(
11436     Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind,
11437     ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
11438     SourceLocation ColonLoc, SourceLocation EndLoc,
11439     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
11440     ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) {
11441   DeclarationName DN = ReductionId.getName();
11442   OverloadedOperatorKind OOK = DN.getCXXOverloadedOperator();
11443   BinaryOperatorKind BOK = BO_Comma;
11444 
11445   ASTContext &Context = S.Context;
11446   // OpenMP [2.14.3.6, reduction clause]
11447   // C
11448   // reduction-identifier is either an identifier or one of the following
11449   // operators: +, -, *,  &, |, ^, && and ||
11450   // C++
11451   // reduction-identifier is either an id-expression or one of the following
11452   // operators: +, -, *, &, |, ^, && and ||
11453   switch (OOK) {
11454   case OO_Plus:
11455   case OO_Minus:
11456     BOK = BO_Add;
11457     break;
11458   case OO_Star:
11459     BOK = BO_Mul;
11460     break;
11461   case OO_Amp:
11462     BOK = BO_And;
11463     break;
11464   case OO_Pipe:
11465     BOK = BO_Or;
11466     break;
11467   case OO_Caret:
11468     BOK = BO_Xor;
11469     break;
11470   case OO_AmpAmp:
11471     BOK = BO_LAnd;
11472     break;
11473   case OO_PipePipe:
11474     BOK = BO_LOr;
11475     break;
11476   case OO_New:
11477   case OO_Delete:
11478   case OO_Array_New:
11479   case OO_Array_Delete:
11480   case OO_Slash:
11481   case OO_Percent:
11482   case OO_Tilde:
11483   case OO_Exclaim:
11484   case OO_Equal:
11485   case OO_Less:
11486   case OO_Greater:
11487   case OO_LessEqual:
11488   case OO_GreaterEqual:
11489   case OO_PlusEqual:
11490   case OO_MinusEqual:
11491   case OO_StarEqual:
11492   case OO_SlashEqual:
11493   case OO_PercentEqual:
11494   case OO_CaretEqual:
11495   case OO_AmpEqual:
11496   case OO_PipeEqual:
11497   case OO_LessLess:
11498   case OO_GreaterGreater:
11499   case OO_LessLessEqual:
11500   case OO_GreaterGreaterEqual:
11501   case OO_EqualEqual:
11502   case OO_ExclaimEqual:
11503   case OO_Spaceship:
11504   case OO_PlusPlus:
11505   case OO_MinusMinus:
11506   case OO_Comma:
11507   case OO_ArrowStar:
11508   case OO_Arrow:
11509   case OO_Call:
11510   case OO_Subscript:
11511   case OO_Conditional:
11512   case OO_Coawait:
11513   case NUM_OVERLOADED_OPERATORS:
11514     llvm_unreachable("Unexpected reduction identifier");
11515   case OO_None:
11516     if (IdentifierInfo *II = DN.getAsIdentifierInfo()) {
11517       if (II->isStr("max"))
11518         BOK = BO_GT;
11519       else if (II->isStr("min"))
11520         BOK = BO_LT;
11521     }
11522     break;
11523   }
11524   SourceRange ReductionIdRange;
11525   if (ReductionIdScopeSpec.isValid())
11526     ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
11527   else
11528     ReductionIdRange.setBegin(ReductionId.getBeginLoc());
11529   ReductionIdRange.setEnd(ReductionId.getEndLoc());
11530 
11531   auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
11532   bool FirstIter = true;
11533   for (Expr *RefExpr : VarList) {
11534     assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
11535     // OpenMP [2.1, C/C++]
11536     //  A list item is a variable or array section, subject to the restrictions
11537     //  specified in Section 2.4 on page 42 and in each of the sections
11538     // describing clauses and directives for which a list appears.
11539     // OpenMP  [2.14.3.3, Restrictions, p.1]
11540     //  A variable that is part of another variable (as an array or
11541     //  structure element) cannot appear in a private clause.
11542     if (!FirstIter && IR != ER)
11543       ++IR;
11544     FirstIter = false;
11545     SourceLocation ELoc;
11546     SourceRange ERange;
11547     Expr *SimpleRefExpr = RefExpr;
11548     auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
11549                               /*AllowArraySection=*/true);
11550     if (Res.second) {
11551       // Try to find 'declare reduction' corresponding construct before using
11552       // builtin/overloaded operators.
11553       QualType Type = Context.DependentTy;
11554       CXXCastPath BasePath;
11555       ExprResult DeclareReductionRef = buildDeclareReductionRef(
11556           S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
11557           ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
11558       Expr *ReductionOp = nullptr;
11559       if (S.CurContext->isDependentContext() &&
11560           (DeclareReductionRef.isUnset() ||
11561            isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
11562         ReductionOp = DeclareReductionRef.get();
11563       // It will be analyzed later.
11564       RD.push(RefExpr, ReductionOp);
11565     }
11566     ValueDecl *D = Res.first;
11567     if (!D)
11568       continue;
11569 
11570     Expr *TaskgroupDescriptor = nullptr;
11571     QualType Type;
11572     auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
11573     auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
11574     if (ASE) {
11575       Type = ASE->getType().getNonReferenceType();
11576     } else if (OASE) {
11577       QualType BaseType =
11578           OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
11579       if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
11580         Type = ATy->getElementType();
11581       else
11582         Type = BaseType->getPointeeType();
11583       Type = Type.getNonReferenceType();
11584     } else {
11585       Type = Context.getBaseElementType(D->getType().getNonReferenceType());
11586     }
11587     auto *VD = dyn_cast<VarDecl>(D);
11588 
11589     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
11590     //  A variable that appears in a private clause must not have an incomplete
11591     //  type or a reference type.
11592     if (S.RequireCompleteType(ELoc, D->getType(),
11593                               diag::err_omp_reduction_incomplete_type))
11594       continue;
11595     // OpenMP [2.14.3.6, reduction clause, Restrictions]
11596     // A list item that appears in a reduction clause must not be
11597     // const-qualified.
11598     if (rejectConstNotMutableType(S, D, Type, ClauseKind, ELoc,
11599                                   /*AcceptIfMutable*/ false, ASE || OASE))
11600       continue;
11601 
11602     OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective();
11603     // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
11604     //  If a list-item is a reference type then it must bind to the same object
11605     //  for all threads of the team.
11606     if (!ASE && !OASE) {
11607       if (VD) {
11608         VarDecl *VDDef = VD->getDefinition();
11609         if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
11610           DSARefChecker Check(Stack);
11611           if (Check.Visit(VDDef->getInit())) {
11612             S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg)
11613                 << getOpenMPClauseName(ClauseKind) << ERange;
11614             S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
11615             continue;
11616           }
11617         }
11618       }
11619 
11620       // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
11621       // in a Construct]
11622       //  Variables with the predetermined data-sharing attributes may not be
11623       //  listed in data-sharing attributes clauses, except for the cases
11624       //  listed below. For these exceptions only, listing a predetermined
11625       //  variable in a data-sharing attribute clause is allowed and overrides
11626       //  the variable's predetermined data-sharing attributes.
11627       // OpenMP [2.14.3.6, Restrictions, p.3]
11628       //  Any number of reduction clauses can be specified on the directive,
11629       //  but a list item can appear only once in the reduction clauses for that
11630       //  directive.
11631       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false);
11632       if (DVar.CKind == OMPC_reduction) {
11633         S.Diag(ELoc, diag::err_omp_once_referenced)
11634             << getOpenMPClauseName(ClauseKind);
11635         if (DVar.RefExpr)
11636           S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
11637         continue;
11638       }
11639       if (DVar.CKind != OMPC_unknown) {
11640         S.Diag(ELoc, diag::err_omp_wrong_dsa)
11641             << getOpenMPClauseName(DVar.CKind)
11642             << getOpenMPClauseName(OMPC_reduction);
11643         reportOriginalDsa(S, Stack, D, DVar);
11644         continue;
11645       }
11646 
11647       // OpenMP [2.14.3.6, Restrictions, p.1]
11648       //  A list item that appears in a reduction clause of a worksharing
11649       //  construct must be shared in the parallel regions to which any of the
11650       //  worksharing regions arising from the worksharing construct bind.
11651       if (isOpenMPWorksharingDirective(CurrDir) &&
11652           !isOpenMPParallelDirective(CurrDir) &&
11653           !isOpenMPTeamsDirective(CurrDir)) {
11654         DVar = Stack->getImplicitDSA(D, true);
11655         if (DVar.CKind != OMPC_shared) {
11656           S.Diag(ELoc, diag::err_omp_required_access)
11657               << getOpenMPClauseName(OMPC_reduction)
11658               << getOpenMPClauseName(OMPC_shared);
11659           reportOriginalDsa(S, Stack, D, DVar);
11660           continue;
11661         }
11662       }
11663     }
11664 
11665     // Try to find 'declare reduction' corresponding construct before using
11666     // builtin/overloaded operators.
11667     CXXCastPath BasePath;
11668     ExprResult DeclareReductionRef = buildDeclareReductionRef(
11669         S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
11670         ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
11671     if (DeclareReductionRef.isInvalid())
11672       continue;
11673     if (S.CurContext->isDependentContext() &&
11674         (DeclareReductionRef.isUnset() ||
11675          isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
11676       RD.push(RefExpr, DeclareReductionRef.get());
11677       continue;
11678     }
11679     if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
11680       // Not allowed reduction identifier is found.
11681       S.Diag(ReductionId.getBeginLoc(),
11682              diag::err_omp_unknown_reduction_identifier)
11683           << Type << ReductionIdRange;
11684       continue;
11685     }
11686 
11687     // OpenMP [2.14.3.6, reduction clause, Restrictions]
11688     // The type of a list item that appears in a reduction clause must be valid
11689     // for the reduction-identifier. For a max or min reduction in C, the type
11690     // of the list item must be an allowed arithmetic data type: char, int,
11691     // float, double, or _Bool, possibly modified with long, short, signed, or
11692     // unsigned. For a max or min reduction in C++, the type of the list item
11693     // must be an allowed arithmetic data type: char, wchar_t, int, float,
11694     // double, or bool, possibly modified with long, short, signed, or unsigned.
11695     if (DeclareReductionRef.isUnset()) {
11696       if ((BOK == BO_GT || BOK == BO_LT) &&
11697           !(Type->isScalarType() ||
11698             (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
11699         S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
11700             << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus;
11701         if (!ASE && !OASE) {
11702           bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
11703                                    VarDecl::DeclarationOnly;
11704           S.Diag(D->getLocation(),
11705                  IsDecl ? diag::note_previous_decl : diag::note_defined_here)
11706               << D;
11707         }
11708         continue;
11709       }
11710       if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
11711           !S.getLangOpts().CPlusPlus && Type->isFloatingType()) {
11712         S.Diag(ELoc, diag::err_omp_clause_floating_type_arg)
11713             << getOpenMPClauseName(ClauseKind);
11714         if (!ASE && !OASE) {
11715           bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
11716                                    VarDecl::DeclarationOnly;
11717           S.Diag(D->getLocation(),
11718                  IsDecl ? diag::note_previous_decl : diag::note_defined_here)
11719               << D;
11720         }
11721         continue;
11722       }
11723     }
11724 
11725     Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
11726     VarDecl *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs",
11727                                   D->hasAttrs() ? &D->getAttrs() : nullptr);
11728     VarDecl *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(),
11729                                   D->hasAttrs() ? &D->getAttrs() : nullptr);
11730     QualType PrivateTy = Type;
11731 
11732     // Try if we can determine constant lengths for all array sections and avoid
11733     // the VLA.
11734     bool ConstantLengthOASE = false;
11735     if (OASE) {
11736       bool SingleElement;
11737       llvm::SmallVector<llvm::APSInt, 4> ArraySizes;
11738       ConstantLengthOASE = checkOMPArraySectionConstantForReduction(
11739           Context, OASE, SingleElement, ArraySizes);
11740 
11741       // If we don't have a single element, we must emit a constant array type.
11742       if (ConstantLengthOASE && !SingleElement) {
11743         for (llvm::APSInt &Size : ArraySizes)
11744           PrivateTy = Context.getConstantArrayType(
11745               PrivateTy, Size, ArrayType::Normal, /*IndexTypeQuals=*/0);
11746       }
11747     }
11748 
11749     if ((OASE && !ConstantLengthOASE) ||
11750         (!OASE && !ASE &&
11751          D->getType().getNonReferenceType()->isVariablyModifiedType())) {
11752       if (!Context.getTargetInfo().isVLASupported() &&
11753           S.shouldDiagnoseTargetSupportFromOpenMP()) {
11754         S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
11755         S.Diag(ELoc, diag::note_vla_unsupported);
11756         continue;
11757       }
11758       // For arrays/array sections only:
11759       // Create pseudo array type for private copy. The size for this array will
11760       // be generated during codegen.
11761       // For array subscripts or single variables Private Ty is the same as Type
11762       // (type of the variable or single array element).
11763       PrivateTy = Context.getVariableArrayType(
11764           Type,
11765           new (Context) OpaqueValueExpr(ELoc, Context.getSizeType(), VK_RValue),
11766           ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
11767     } else if (!ASE && !OASE &&
11768                Context.getAsArrayType(D->getType().getNonReferenceType())) {
11769       PrivateTy = D->getType().getNonReferenceType();
11770     }
11771     // Private copy.
11772     VarDecl *PrivateVD =
11773         buildVarDecl(S, ELoc, PrivateTy, D->getName(),
11774                      D->hasAttrs() ? &D->getAttrs() : nullptr,
11775                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
11776     // Add initializer for private variable.
11777     Expr *Init = nullptr;
11778     DeclRefExpr *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc);
11779     DeclRefExpr *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc);
11780     if (DeclareReductionRef.isUsable()) {
11781       auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
11782       auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
11783       if (DRD->getInitializer()) {
11784         Init = DRDRef;
11785         RHSVD->setInit(DRDRef);
11786         RHSVD->setInitStyle(VarDecl::CallInit);
11787       }
11788     } else {
11789       switch (BOK) {
11790       case BO_Add:
11791       case BO_Xor:
11792       case BO_Or:
11793       case BO_LOr:
11794         // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
11795         if (Type->isScalarType() || Type->isAnyComplexType())
11796           Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get();
11797         break;
11798       case BO_Mul:
11799       case BO_LAnd:
11800         if (Type->isScalarType() || Type->isAnyComplexType()) {
11801           // '*' and '&&' reduction ops - initializer is '1'.
11802           Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get();
11803         }
11804         break;
11805       case BO_And: {
11806         // '&' reduction op - initializer is '~0'.
11807         QualType OrigType = Type;
11808         if (auto *ComplexTy = OrigType->getAs<ComplexType>())
11809           Type = ComplexTy->getElementType();
11810         if (Type->isRealFloatingType()) {
11811           llvm::APFloat InitValue =
11812               llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
11813                                              /*isIEEE=*/true);
11814           Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
11815                                          Type, ELoc);
11816         } else if (Type->isScalarType()) {
11817           uint64_t Size = Context.getTypeSize(Type);
11818           QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
11819           llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
11820           Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
11821         }
11822         if (Init && OrigType->isAnyComplexType()) {
11823           // Init = 0xFFFF + 0xFFFFi;
11824           auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
11825           Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
11826         }
11827         Type = OrigType;
11828         break;
11829       }
11830       case BO_LT:
11831       case BO_GT: {
11832         // 'min' reduction op - initializer is 'Largest representable number in
11833         // the reduction list item type'.
11834         // 'max' reduction op - initializer is 'Least representable number in
11835         // the reduction list item type'.
11836         if (Type->isIntegerType() || Type->isPointerType()) {
11837           bool IsSigned = Type->hasSignedIntegerRepresentation();
11838           uint64_t Size = Context.getTypeSize(Type);
11839           QualType IntTy =
11840               Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
11841           llvm::APInt InitValue =
11842               (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
11843                                         : llvm::APInt::getMinValue(Size)
11844                              : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
11845                                         : llvm::APInt::getMaxValue(Size);
11846           Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
11847           if (Type->isPointerType()) {
11848             // Cast to pointer type.
11849             ExprResult CastExpr = S.BuildCStyleCastExpr(
11850                 ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init);
11851             if (CastExpr.isInvalid())
11852               continue;
11853             Init = CastExpr.get();
11854           }
11855         } else if (Type->isRealFloatingType()) {
11856           llvm::APFloat InitValue = llvm::APFloat::getLargest(
11857               Context.getFloatTypeSemantics(Type), BOK != BO_LT);
11858           Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
11859                                          Type, ELoc);
11860         }
11861         break;
11862       }
11863       case BO_PtrMemD:
11864       case BO_PtrMemI:
11865       case BO_MulAssign:
11866       case BO_Div:
11867       case BO_Rem:
11868       case BO_Sub:
11869       case BO_Shl:
11870       case BO_Shr:
11871       case BO_LE:
11872       case BO_GE:
11873       case BO_EQ:
11874       case BO_NE:
11875       case BO_Cmp:
11876       case BO_AndAssign:
11877       case BO_XorAssign:
11878       case BO_OrAssign:
11879       case BO_Assign:
11880       case BO_AddAssign:
11881       case BO_SubAssign:
11882       case BO_DivAssign:
11883       case BO_RemAssign:
11884       case BO_ShlAssign:
11885       case BO_ShrAssign:
11886       case BO_Comma:
11887         llvm_unreachable("Unexpected reduction operation");
11888       }
11889     }
11890     if (Init && DeclareReductionRef.isUnset())
11891       S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
11892     else if (!Init)
11893       S.ActOnUninitializedDecl(RHSVD);
11894     if (RHSVD->isInvalidDecl())
11895       continue;
11896     if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) {
11897       S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible)
11898           << Type << ReductionIdRange;
11899       bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
11900                                VarDecl::DeclarationOnly;
11901       S.Diag(D->getLocation(),
11902              IsDecl ? diag::note_previous_decl : diag::note_defined_here)
11903           << D;
11904       continue;
11905     }
11906     // Store initializer for single element in private copy. Will be used during
11907     // codegen.
11908     PrivateVD->setInit(RHSVD->getInit());
11909     PrivateVD->setInitStyle(RHSVD->getInitStyle());
11910     DeclRefExpr *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc);
11911     ExprResult ReductionOp;
11912     if (DeclareReductionRef.isUsable()) {
11913       QualType RedTy = DeclareReductionRef.get()->getType();
11914       QualType PtrRedTy = Context.getPointerType(RedTy);
11915       ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
11916       ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
11917       if (!BasePath.empty()) {
11918         LHS = S.DefaultLvalueConversion(LHS.get());
11919         RHS = S.DefaultLvalueConversion(RHS.get());
11920         LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
11921                                        CK_UncheckedDerivedToBase, LHS.get(),
11922                                        &BasePath, LHS.get()->getValueKind());
11923         RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
11924                                        CK_UncheckedDerivedToBase, RHS.get(),
11925                                        &BasePath, RHS.get()->getValueKind());
11926       }
11927       FunctionProtoType::ExtProtoInfo EPI;
11928       QualType Params[] = {PtrRedTy, PtrRedTy};
11929       QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
11930       auto *OVE = new (Context) OpaqueValueExpr(
11931           ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
11932           S.DefaultLvalueConversion(DeclareReductionRef.get()).get());
11933       Expr *Args[] = {LHS.get(), RHS.get()};
11934       ReductionOp =
11935           CallExpr::Create(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
11936     } else {
11937       ReductionOp = S.BuildBinOp(
11938           Stack->getCurScope(), ReductionId.getBeginLoc(), BOK, LHSDRE, RHSDRE);
11939       if (ReductionOp.isUsable()) {
11940         if (BOK != BO_LT && BOK != BO_GT) {
11941           ReductionOp =
11942               S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
11943                            BO_Assign, LHSDRE, ReductionOp.get());
11944         } else {
11945           auto *ConditionalOp = new (Context)
11946               ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc, RHSDRE,
11947                                   Type, VK_LValue, OK_Ordinary);
11948           ReductionOp =
11949               S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
11950                            BO_Assign, LHSDRE, ConditionalOp);
11951         }
11952         if (ReductionOp.isUsable())
11953           ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get(),
11954                                               /*DiscardedValue*/ false);
11955       }
11956       if (!ReductionOp.isUsable())
11957         continue;
11958     }
11959 
11960     // OpenMP [2.15.4.6, Restrictions, p.2]
11961     // A list item that appears in an in_reduction clause of a task construct
11962     // must appear in a task_reduction clause of a construct associated with a
11963     // taskgroup region that includes the participating task in its taskgroup
11964     // set. The construct associated with the innermost region that meets this
11965     // condition must specify the same reduction-identifier as the in_reduction
11966     // clause.
11967     if (ClauseKind == OMPC_in_reduction) {
11968       SourceRange ParentSR;
11969       BinaryOperatorKind ParentBOK;
11970       const Expr *ParentReductionOp;
11971       Expr *ParentBOKTD, *ParentReductionOpTD;
11972       DSAStackTy::DSAVarData ParentBOKDSA =
11973           Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK,
11974                                                   ParentBOKTD);
11975       DSAStackTy::DSAVarData ParentReductionOpDSA =
11976           Stack->getTopMostTaskgroupReductionData(
11977               D, ParentSR, ParentReductionOp, ParentReductionOpTD);
11978       bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown;
11979       bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown;
11980       if (!IsParentBOK && !IsParentReductionOp) {
11981         S.Diag(ELoc, diag::err_omp_in_reduction_not_task_reduction);
11982         continue;
11983       }
11984       if ((DeclareReductionRef.isUnset() && IsParentReductionOp) ||
11985           (DeclareReductionRef.isUsable() && IsParentBOK) || BOK != ParentBOK ||
11986           IsParentReductionOp) {
11987         bool EmitError = true;
11988         if (IsParentReductionOp && DeclareReductionRef.isUsable()) {
11989           llvm::FoldingSetNodeID RedId, ParentRedId;
11990           ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true);
11991           DeclareReductionRef.get()->Profile(RedId, Context,
11992                                              /*Canonical=*/true);
11993           EmitError = RedId != ParentRedId;
11994         }
11995         if (EmitError) {
11996           S.Diag(ReductionId.getBeginLoc(),
11997                  diag::err_omp_reduction_identifier_mismatch)
11998               << ReductionIdRange << RefExpr->getSourceRange();
11999           S.Diag(ParentSR.getBegin(),
12000                  diag::note_omp_previous_reduction_identifier)
12001               << ParentSR
12002               << (IsParentBOK ? ParentBOKDSA.RefExpr
12003                               : ParentReductionOpDSA.RefExpr)
12004                      ->getSourceRange();
12005           continue;
12006         }
12007       }
12008       TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD;
12009       assert(TaskgroupDescriptor && "Taskgroup descriptor must be defined.");
12010     }
12011 
12012     DeclRefExpr *Ref = nullptr;
12013     Expr *VarsExpr = RefExpr->IgnoreParens();
12014     if (!VD && !S.CurContext->isDependentContext()) {
12015       if (ASE || OASE) {
12016         TransformExprToCaptures RebuildToCapture(S, D);
12017         VarsExpr =
12018             RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
12019         Ref = RebuildToCapture.getCapturedExpr();
12020       } else {
12021         VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false);
12022       }
12023       if (!S.isOpenMPCapturedDecl(D)) {
12024         RD.ExprCaptures.emplace_back(Ref->getDecl());
12025         if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
12026           ExprResult RefRes = S.DefaultLvalueConversion(Ref);
12027           if (!RefRes.isUsable())
12028             continue;
12029           ExprResult PostUpdateRes =
12030               S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
12031                            RefRes.get());
12032           if (!PostUpdateRes.isUsable())
12033             continue;
12034           if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
12035               Stack->getCurrentDirective() == OMPD_taskgroup) {
12036             S.Diag(RefExpr->getExprLoc(),
12037                    diag::err_omp_reduction_non_addressable_expression)
12038                 << RefExpr->getSourceRange();
12039             continue;
12040           }
12041           RD.ExprPostUpdates.emplace_back(
12042               S.IgnoredValueConversions(PostUpdateRes.get()).get());
12043         }
12044       }
12045     }
12046     // All reduction items are still marked as reduction (to do not increase
12047     // code base size).
12048     Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
12049     if (CurrDir == OMPD_taskgroup) {
12050       if (DeclareReductionRef.isUsable())
12051         Stack->addTaskgroupReductionData(D, ReductionIdRange,
12052                                          DeclareReductionRef.get());
12053       else
12054         Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK);
12055     }
12056     RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(),
12057             TaskgroupDescriptor);
12058   }
12059   return RD.Vars.empty();
12060 }
12061 
12062 OMPClause *Sema::ActOnOpenMPReductionClause(
12063     ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
12064     SourceLocation ColonLoc, SourceLocation EndLoc,
12065     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
12066     ArrayRef<Expr *> UnresolvedReductions) {
12067   ReductionData RD(VarList.size());
12068   if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList,
12069                                   StartLoc, LParenLoc, ColonLoc, EndLoc,
12070                                   ReductionIdScopeSpec, ReductionId,
12071                                   UnresolvedReductions, RD))
12072     return nullptr;
12073 
12074   return OMPReductionClause::Create(
12075       Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
12076       ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
12077       RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
12078       buildPreInits(Context, RD.ExprCaptures),
12079       buildPostUpdate(*this, RD.ExprPostUpdates));
12080 }
12081 
12082 OMPClause *Sema::ActOnOpenMPTaskReductionClause(
12083     ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
12084     SourceLocation ColonLoc, SourceLocation EndLoc,
12085     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
12086     ArrayRef<Expr *> UnresolvedReductions) {
12087   ReductionData RD(VarList.size());
12088   if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction, VarList,
12089                                   StartLoc, LParenLoc, ColonLoc, EndLoc,
12090                                   ReductionIdScopeSpec, ReductionId,
12091                                   UnresolvedReductions, RD))
12092     return nullptr;
12093 
12094   return OMPTaskReductionClause::Create(
12095       Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
12096       ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
12097       RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
12098       buildPreInits(Context, RD.ExprCaptures),
12099       buildPostUpdate(*this, RD.ExprPostUpdates));
12100 }
12101 
12102 OMPClause *Sema::ActOnOpenMPInReductionClause(
12103     ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
12104     SourceLocation ColonLoc, SourceLocation EndLoc,
12105     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
12106     ArrayRef<Expr *> UnresolvedReductions) {
12107   ReductionData RD(VarList.size());
12108   if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList,
12109                                   StartLoc, LParenLoc, ColonLoc, EndLoc,
12110                                   ReductionIdScopeSpec, ReductionId,
12111                                   UnresolvedReductions, RD))
12112     return nullptr;
12113 
12114   return OMPInReductionClause::Create(
12115       Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
12116       ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
12117       RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors,
12118       buildPreInits(Context, RD.ExprCaptures),
12119       buildPostUpdate(*this, RD.ExprPostUpdates));
12120 }
12121 
12122 bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
12123                                      SourceLocation LinLoc) {
12124   if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
12125       LinKind == OMPC_LINEAR_unknown) {
12126     Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
12127     return true;
12128   }
12129   return false;
12130 }
12131 
12132 bool Sema::CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc,
12133                                  OpenMPLinearClauseKind LinKind,
12134                                  QualType Type) {
12135   const auto *VD = dyn_cast_or_null<VarDecl>(D);
12136   // A variable must not have an incomplete type or a reference type.
12137   if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
12138     return true;
12139   if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
12140       !Type->isReferenceType()) {
12141     Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
12142         << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
12143     return true;
12144   }
12145   Type = Type.getNonReferenceType();
12146 
12147   // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
12148   // A variable that is privatized must not have a const-qualified type
12149   // unless it is of class type with a mutable member. This restriction does
12150   // not apply to the firstprivate clause.
12151   if (rejectConstNotMutableType(*this, D, Type, OMPC_linear, ELoc))
12152     return true;
12153 
12154   // A list item must be of integral or pointer type.
12155   Type = Type.getUnqualifiedType().getCanonicalType();
12156   const auto *Ty = Type.getTypePtrOrNull();
12157   if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
12158               !Ty->isPointerType())) {
12159     Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
12160     if (D) {
12161       bool IsDecl =
12162           !VD ||
12163           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
12164       Diag(D->getLocation(),
12165            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
12166           << D;
12167     }
12168     return true;
12169   }
12170   return false;
12171 }
12172 
12173 OMPClause *Sema::ActOnOpenMPLinearClause(
12174     ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
12175     SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
12176     SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
12177   SmallVector<Expr *, 8> Vars;
12178   SmallVector<Expr *, 8> Privates;
12179   SmallVector<Expr *, 8> Inits;
12180   SmallVector<Decl *, 4> ExprCaptures;
12181   SmallVector<Expr *, 4> ExprPostUpdates;
12182   if (CheckOpenMPLinearModifier(LinKind, LinLoc))
12183     LinKind = OMPC_LINEAR_val;
12184   for (Expr *RefExpr : VarList) {
12185     assert(RefExpr && "NULL expr in OpenMP linear clause.");
12186     SourceLocation ELoc;
12187     SourceRange ERange;
12188     Expr *SimpleRefExpr = RefExpr;
12189     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
12190     if (Res.second) {
12191       // It will be analyzed later.
12192       Vars.push_back(RefExpr);
12193       Privates.push_back(nullptr);
12194       Inits.push_back(nullptr);
12195     }
12196     ValueDecl *D = Res.first;
12197     if (!D)
12198       continue;
12199 
12200     QualType Type = D->getType();
12201     auto *VD = dyn_cast<VarDecl>(D);
12202 
12203     // OpenMP [2.14.3.7, linear clause]
12204     //  A list-item cannot appear in more than one linear clause.
12205     //  A list-item that appears in a linear clause cannot appear in any
12206     //  other data-sharing attribute clause.
12207     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
12208     if (DVar.RefExpr) {
12209       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
12210                                           << getOpenMPClauseName(OMPC_linear);
12211       reportOriginalDsa(*this, DSAStack, D, DVar);
12212       continue;
12213     }
12214 
12215     if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
12216       continue;
12217     Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
12218 
12219     // Build private copy of original var.
12220     VarDecl *Private =
12221         buildVarDecl(*this, ELoc, Type, D->getName(),
12222                      D->hasAttrs() ? &D->getAttrs() : nullptr,
12223                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
12224     DeclRefExpr *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
12225     // Build var to save initial value.
12226     VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
12227     Expr *InitExpr;
12228     DeclRefExpr *Ref = nullptr;
12229     if (!VD && !CurContext->isDependentContext()) {
12230       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
12231       if (!isOpenMPCapturedDecl(D)) {
12232         ExprCaptures.push_back(Ref->getDecl());
12233         if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
12234           ExprResult RefRes = DefaultLvalueConversion(Ref);
12235           if (!RefRes.isUsable())
12236             continue;
12237           ExprResult PostUpdateRes =
12238               BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
12239                          SimpleRefExpr, RefRes.get());
12240           if (!PostUpdateRes.isUsable())
12241             continue;
12242           ExprPostUpdates.push_back(
12243               IgnoredValueConversions(PostUpdateRes.get()).get());
12244         }
12245       }
12246     }
12247     if (LinKind == OMPC_LINEAR_uval)
12248       InitExpr = VD ? VD->getInit() : SimpleRefExpr;
12249     else
12250       InitExpr = VD ? SimpleRefExpr : Ref;
12251     AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
12252                          /*DirectInit=*/false);
12253     DeclRefExpr *InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
12254 
12255     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
12256     Vars.push_back((VD || CurContext->isDependentContext())
12257                        ? RefExpr->IgnoreParens()
12258                        : Ref);
12259     Privates.push_back(PrivateRef);
12260     Inits.push_back(InitRef);
12261   }
12262 
12263   if (Vars.empty())
12264     return nullptr;
12265 
12266   Expr *StepExpr = Step;
12267   Expr *CalcStepExpr = nullptr;
12268   if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
12269       !Step->isInstantiationDependent() &&
12270       !Step->containsUnexpandedParameterPack()) {
12271     SourceLocation StepLoc = Step->getBeginLoc();
12272     ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
12273     if (Val.isInvalid())
12274       return nullptr;
12275     StepExpr = Val.get();
12276 
12277     // Build var to save the step value.
12278     VarDecl *SaveVar =
12279         buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
12280     ExprResult SaveRef =
12281         buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
12282     ExprResult CalcStep =
12283         BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
12284     CalcStep = ActOnFinishFullExpr(CalcStep.get(), /*DiscardedValue*/ false);
12285 
12286     // Warn about zero linear step (it would be probably better specified as
12287     // making corresponding variables 'const').
12288     llvm::APSInt Result;
12289     bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
12290     if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
12291       Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
12292                                                      << (Vars.size() > 1);
12293     if (!IsConstant && CalcStep.isUsable()) {
12294       // Calculate the step beforehand instead of doing this on each iteration.
12295       // (This is not used if the number of iterations may be kfold-ed).
12296       CalcStepExpr = CalcStep.get();
12297     }
12298   }
12299 
12300   return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
12301                                  ColonLoc, EndLoc, Vars, Privates, Inits,
12302                                  StepExpr, CalcStepExpr,
12303                                  buildPreInits(Context, ExprCaptures),
12304                                  buildPostUpdate(*this, ExprPostUpdates));
12305 }
12306 
12307 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
12308                                      Expr *NumIterations, Sema &SemaRef,
12309                                      Scope *S, DSAStackTy *Stack) {
12310   // Walk the vars and build update/final expressions for the CodeGen.
12311   SmallVector<Expr *, 8> Updates;
12312   SmallVector<Expr *, 8> Finals;
12313   Expr *Step = Clause.getStep();
12314   Expr *CalcStep = Clause.getCalcStep();
12315   // OpenMP [2.14.3.7, linear clause]
12316   // If linear-step is not specified it is assumed to be 1.
12317   if (!Step)
12318     Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
12319   else if (CalcStep)
12320     Step = cast<BinaryOperator>(CalcStep)->getLHS();
12321   bool HasErrors = false;
12322   auto CurInit = Clause.inits().begin();
12323   auto CurPrivate = Clause.privates().begin();
12324   OpenMPLinearClauseKind LinKind = Clause.getModifier();
12325   for (Expr *RefExpr : Clause.varlists()) {
12326     SourceLocation ELoc;
12327     SourceRange ERange;
12328     Expr *SimpleRefExpr = RefExpr;
12329     auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange);
12330     ValueDecl *D = Res.first;
12331     if (Res.second || !D) {
12332       Updates.push_back(nullptr);
12333       Finals.push_back(nullptr);
12334       HasErrors = true;
12335       continue;
12336     }
12337     auto &&Info = Stack->isLoopControlVariable(D);
12338     // OpenMP [2.15.11, distribute simd Construct]
12339     // A list item may not appear in a linear clause, unless it is the loop
12340     // iteration variable.
12341     if (isOpenMPDistributeDirective(Stack->getCurrentDirective()) &&
12342         isOpenMPSimdDirective(Stack->getCurrentDirective()) && !Info.first) {
12343       SemaRef.Diag(ELoc,
12344                    diag::err_omp_linear_distribute_var_non_loop_iteration);
12345       Updates.push_back(nullptr);
12346       Finals.push_back(nullptr);
12347       HasErrors = true;
12348       continue;
12349     }
12350     Expr *InitExpr = *CurInit;
12351 
12352     // Build privatized reference to the current linear var.
12353     auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
12354     Expr *CapturedRef;
12355     if (LinKind == OMPC_LINEAR_uval)
12356       CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
12357     else
12358       CapturedRef =
12359           buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
12360                            DE->getType().getUnqualifiedType(), DE->getExprLoc(),
12361                            /*RefersToCapture=*/true);
12362 
12363     // Build update: Var = InitExpr + IV * Step
12364     ExprResult Update;
12365     if (!Info.first)
12366       Update =
12367           buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate,
12368                              InitExpr, IV, Step, /* Subtract */ false);
12369     else
12370       Update = *CurPrivate;
12371     Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getBeginLoc(),
12372                                          /*DiscardedValue*/ false);
12373 
12374     // Build final: Var = InitExpr + NumIterations * Step
12375     ExprResult Final;
12376     if (!Info.first)
12377       Final =
12378           buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
12379                              InitExpr, NumIterations, Step, /*Subtract=*/false);
12380     else
12381       Final = *CurPrivate;
12382     Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getBeginLoc(),
12383                                         /*DiscardedValue*/ false);
12384 
12385     if (!Update.isUsable() || !Final.isUsable()) {
12386       Updates.push_back(nullptr);
12387       Finals.push_back(nullptr);
12388       HasErrors = true;
12389     } else {
12390       Updates.push_back(Update.get());
12391       Finals.push_back(Final.get());
12392     }
12393     ++CurInit;
12394     ++CurPrivate;
12395   }
12396   Clause.setUpdates(Updates);
12397   Clause.setFinals(Finals);
12398   return HasErrors;
12399 }
12400 
12401 OMPClause *Sema::ActOnOpenMPAlignedClause(
12402     ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
12403     SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
12404   SmallVector<Expr *, 8> Vars;
12405   for (Expr *RefExpr : VarList) {
12406     assert(RefExpr && "NULL expr in OpenMP linear clause.");
12407     SourceLocation ELoc;
12408     SourceRange ERange;
12409     Expr *SimpleRefExpr = RefExpr;
12410     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
12411     if (Res.second) {
12412       // It will be analyzed later.
12413       Vars.push_back(RefExpr);
12414     }
12415     ValueDecl *D = Res.first;
12416     if (!D)
12417       continue;
12418 
12419     QualType QType = D->getType();
12420     auto *VD = dyn_cast<VarDecl>(D);
12421 
12422     // OpenMP  [2.8.1, simd construct, Restrictions]
12423     // The type of list items appearing in the aligned clause must be
12424     // array, pointer, reference to array, or reference to pointer.
12425     QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
12426     const Type *Ty = QType.getTypePtrOrNull();
12427     if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
12428       Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
12429           << QType << getLangOpts().CPlusPlus << ERange;
12430       bool IsDecl =
12431           !VD ||
12432           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
12433       Diag(D->getLocation(),
12434            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
12435           << D;
12436       continue;
12437     }
12438 
12439     // OpenMP  [2.8.1, simd construct, Restrictions]
12440     // A list-item cannot appear in more than one aligned clause.
12441     if (const Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
12442       Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
12443       Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
12444           << getOpenMPClauseName(OMPC_aligned);
12445       continue;
12446     }
12447 
12448     DeclRefExpr *Ref = nullptr;
12449     if (!VD && isOpenMPCapturedDecl(D))
12450       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
12451     Vars.push_back(DefaultFunctionArrayConversion(
12452                        (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
12453                        .get());
12454   }
12455 
12456   // OpenMP [2.8.1, simd construct, Description]
12457   // The parameter of the aligned clause, alignment, must be a constant
12458   // positive integer expression.
12459   // If no optional parameter is specified, implementation-defined default
12460   // alignments for SIMD instructions on the target platforms are assumed.
12461   if (Alignment != nullptr) {
12462     ExprResult AlignResult =
12463         VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
12464     if (AlignResult.isInvalid())
12465       return nullptr;
12466     Alignment = AlignResult.get();
12467   }
12468   if (Vars.empty())
12469     return nullptr;
12470 
12471   return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
12472                                   EndLoc, Vars, Alignment);
12473 }
12474 
12475 OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
12476                                          SourceLocation StartLoc,
12477                                          SourceLocation LParenLoc,
12478                                          SourceLocation EndLoc) {
12479   SmallVector<Expr *, 8> Vars;
12480   SmallVector<Expr *, 8> SrcExprs;
12481   SmallVector<Expr *, 8> DstExprs;
12482   SmallVector<Expr *, 8> AssignmentOps;
12483   for (Expr *RefExpr : VarList) {
12484     assert(RefExpr && "NULL expr in OpenMP copyin clause.");
12485     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
12486       // It will be analyzed later.
12487       Vars.push_back(RefExpr);
12488       SrcExprs.push_back(nullptr);
12489       DstExprs.push_back(nullptr);
12490       AssignmentOps.push_back(nullptr);
12491       continue;
12492     }
12493 
12494     SourceLocation ELoc = RefExpr->getExprLoc();
12495     // OpenMP [2.1, C/C++]
12496     //  A list item is a variable name.
12497     // OpenMP  [2.14.4.1, Restrictions, p.1]
12498     //  A list item that appears in a copyin clause must be threadprivate.
12499     auto *DE = dyn_cast<DeclRefExpr>(RefExpr);
12500     if (!DE || !isa<VarDecl>(DE->getDecl())) {
12501       Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
12502           << 0 << RefExpr->getSourceRange();
12503       continue;
12504     }
12505 
12506     Decl *D = DE->getDecl();
12507     auto *VD = cast<VarDecl>(D);
12508 
12509     QualType Type = VD->getType();
12510     if (Type->isDependentType() || Type->isInstantiationDependentType()) {
12511       // It will be analyzed later.
12512       Vars.push_back(DE);
12513       SrcExprs.push_back(nullptr);
12514       DstExprs.push_back(nullptr);
12515       AssignmentOps.push_back(nullptr);
12516       continue;
12517     }
12518 
12519     // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
12520     //  A list item that appears in a copyin clause must be threadprivate.
12521     if (!DSAStack->isThreadPrivate(VD)) {
12522       Diag(ELoc, diag::err_omp_required_access)
12523           << getOpenMPClauseName(OMPC_copyin)
12524           << getOpenMPDirectiveName(OMPD_threadprivate);
12525       continue;
12526     }
12527 
12528     // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
12529     //  A variable of class type (or array thereof) that appears in a
12530     //  copyin clause requires an accessible, unambiguous copy assignment
12531     //  operator for the class type.
12532     QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
12533     VarDecl *SrcVD =
12534         buildVarDecl(*this, DE->getBeginLoc(), ElemType.getUnqualifiedType(),
12535                      ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
12536     DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(
12537         *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
12538     VarDecl *DstVD =
12539         buildVarDecl(*this, DE->getBeginLoc(), ElemType, ".copyin.dst",
12540                      VD->hasAttrs() ? &VD->getAttrs() : nullptr);
12541     DeclRefExpr *PseudoDstExpr =
12542         buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
12543     // For arrays generate assignment operation for single element and replace
12544     // it by the original array element in CodeGen.
12545     ExprResult AssignmentOp =
12546         BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign, PseudoDstExpr,
12547                    PseudoSrcExpr);
12548     if (AssignmentOp.isInvalid())
12549       continue;
12550     AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
12551                                        /*DiscardedValue*/ false);
12552     if (AssignmentOp.isInvalid())
12553       continue;
12554 
12555     DSAStack->addDSA(VD, DE, OMPC_copyin);
12556     Vars.push_back(DE);
12557     SrcExprs.push_back(PseudoSrcExpr);
12558     DstExprs.push_back(PseudoDstExpr);
12559     AssignmentOps.push_back(AssignmentOp.get());
12560   }
12561 
12562   if (Vars.empty())
12563     return nullptr;
12564 
12565   return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
12566                                  SrcExprs, DstExprs, AssignmentOps);
12567 }
12568 
12569 OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
12570                                               SourceLocation StartLoc,
12571                                               SourceLocation LParenLoc,
12572                                               SourceLocation EndLoc) {
12573   SmallVector<Expr *, 8> Vars;
12574   SmallVector<Expr *, 8> SrcExprs;
12575   SmallVector<Expr *, 8> DstExprs;
12576   SmallVector<Expr *, 8> AssignmentOps;
12577   for (Expr *RefExpr : VarList) {
12578     assert(RefExpr && "NULL expr in OpenMP linear clause.");
12579     SourceLocation ELoc;
12580     SourceRange ERange;
12581     Expr *SimpleRefExpr = RefExpr;
12582     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
12583     if (Res.second) {
12584       // It will be analyzed later.
12585       Vars.push_back(RefExpr);
12586       SrcExprs.push_back(nullptr);
12587       DstExprs.push_back(nullptr);
12588       AssignmentOps.push_back(nullptr);
12589     }
12590     ValueDecl *D = Res.first;
12591     if (!D)
12592       continue;
12593 
12594     QualType Type = D->getType();
12595     auto *VD = dyn_cast<VarDecl>(D);
12596 
12597     // OpenMP [2.14.4.2, Restrictions, p.2]
12598     //  A list item that appears in a copyprivate clause may not appear in a
12599     //  private or firstprivate clause on the single construct.
12600     if (!VD || !DSAStack->isThreadPrivate(VD)) {
12601       DSAStackTy::DSAVarData DVar =
12602           DSAStack->getTopDSA(D, /*FromParent=*/false);
12603       if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
12604           DVar.RefExpr) {
12605         Diag(ELoc, diag::err_omp_wrong_dsa)
12606             << getOpenMPClauseName(DVar.CKind)
12607             << getOpenMPClauseName(OMPC_copyprivate);
12608         reportOriginalDsa(*this, DSAStack, D, DVar);
12609         continue;
12610       }
12611 
12612       // OpenMP [2.11.4.2, Restrictions, p.1]
12613       //  All list items that appear in a copyprivate clause must be either
12614       //  threadprivate or private in the enclosing context.
12615       if (DVar.CKind == OMPC_unknown) {
12616         DVar = DSAStack->getImplicitDSA(D, false);
12617         if (DVar.CKind == OMPC_shared) {
12618           Diag(ELoc, diag::err_omp_required_access)
12619               << getOpenMPClauseName(OMPC_copyprivate)
12620               << "threadprivate or private in the enclosing context";
12621           reportOriginalDsa(*this, DSAStack, D, DVar);
12622           continue;
12623         }
12624       }
12625     }
12626 
12627     // Variably modified types are not supported.
12628     if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
12629       Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
12630           << getOpenMPClauseName(OMPC_copyprivate) << Type
12631           << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
12632       bool IsDecl =
12633           !VD ||
12634           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
12635       Diag(D->getLocation(),
12636            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
12637           << D;
12638       continue;
12639     }
12640 
12641     // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
12642     //  A variable of class type (or array thereof) that appears in a
12643     //  copyin clause requires an accessible, unambiguous copy assignment
12644     //  operator for the class type.
12645     Type = Context.getBaseElementType(Type.getNonReferenceType())
12646                .getUnqualifiedType();
12647     VarDecl *SrcVD =
12648         buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.src",
12649                      D->hasAttrs() ? &D->getAttrs() : nullptr);
12650     DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
12651     VarDecl *DstVD =
12652         buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.dst",
12653                      D->hasAttrs() ? &D->getAttrs() : nullptr);
12654     DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
12655     ExprResult AssignmentOp = BuildBinOp(
12656         DSAStack->getCurScope(), ELoc, BO_Assign, PseudoDstExpr, PseudoSrcExpr);
12657     if (AssignmentOp.isInvalid())
12658       continue;
12659     AssignmentOp =
12660         ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
12661     if (AssignmentOp.isInvalid())
12662       continue;
12663 
12664     // No need to mark vars as copyprivate, they are already threadprivate or
12665     // implicitly private.
12666     assert(VD || isOpenMPCapturedDecl(D));
12667     Vars.push_back(
12668         VD ? RefExpr->IgnoreParens()
12669            : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
12670     SrcExprs.push_back(PseudoSrcExpr);
12671     DstExprs.push_back(PseudoDstExpr);
12672     AssignmentOps.push_back(AssignmentOp.get());
12673   }
12674 
12675   if (Vars.empty())
12676     return nullptr;
12677 
12678   return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
12679                                       Vars, SrcExprs, DstExprs, AssignmentOps);
12680 }
12681 
12682 OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
12683                                         SourceLocation StartLoc,
12684                                         SourceLocation LParenLoc,
12685                                         SourceLocation EndLoc) {
12686   if (VarList.empty())
12687     return nullptr;
12688 
12689   return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
12690 }
12691 
12692 OMPClause *
12693 Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
12694                               SourceLocation DepLoc, SourceLocation ColonLoc,
12695                               ArrayRef<Expr *> VarList, SourceLocation StartLoc,
12696                               SourceLocation LParenLoc, SourceLocation EndLoc) {
12697   if (DSAStack->getCurrentDirective() == OMPD_ordered &&
12698       DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
12699     Diag(DepLoc, diag::err_omp_unexpected_clause_value)
12700         << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
12701     return nullptr;
12702   }
12703   if (DSAStack->getCurrentDirective() != OMPD_ordered &&
12704       (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
12705        DepKind == OMPC_DEPEND_sink)) {
12706     unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
12707     Diag(DepLoc, diag::err_omp_unexpected_clause_value)
12708         << getListOfPossibleValues(OMPC_depend, /*First=*/0,
12709                                    /*Last=*/OMPC_DEPEND_unknown, Except)
12710         << getOpenMPClauseName(OMPC_depend);
12711     return nullptr;
12712   }
12713   SmallVector<Expr *, 8> Vars;
12714   DSAStackTy::OperatorOffsetTy OpsOffs;
12715   llvm::APSInt DepCounter(/*BitWidth=*/32);
12716   llvm::APSInt TotalDepCount(/*BitWidth=*/32);
12717   if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) {
12718     if (const Expr *OrderedCountExpr =
12719             DSAStack->getParentOrderedRegionParam().first) {
12720       TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
12721       TotalDepCount.setIsUnsigned(/*Val=*/true);
12722     }
12723   }
12724   for (Expr *RefExpr : VarList) {
12725     assert(RefExpr && "NULL expr in OpenMP shared clause.");
12726     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
12727       // It will be analyzed later.
12728       Vars.push_back(RefExpr);
12729       continue;
12730     }
12731 
12732     SourceLocation ELoc = RefExpr->getExprLoc();
12733     Expr *SimpleExpr = RefExpr->IgnoreParenCasts();
12734     if (DepKind == OMPC_DEPEND_sink) {
12735       if (DSAStack->getParentOrderedRegionParam().first &&
12736           DepCounter >= TotalDepCount) {
12737         Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
12738         continue;
12739       }
12740       ++DepCounter;
12741       // OpenMP  [2.13.9, Summary]
12742       // depend(dependence-type : vec), where dependence-type is:
12743       // 'sink' and where vec is the iteration vector, which has the form:
12744       //  x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
12745       // where n is the value specified by the ordered clause in the loop
12746       // directive, xi denotes the loop iteration variable of the i-th nested
12747       // loop associated with the loop directive, and di is a constant
12748       // non-negative integer.
12749       if (CurContext->isDependentContext()) {
12750         // It will be analyzed later.
12751         Vars.push_back(RefExpr);
12752         continue;
12753       }
12754       SimpleExpr = SimpleExpr->IgnoreImplicit();
12755       OverloadedOperatorKind OOK = OO_None;
12756       SourceLocation OOLoc;
12757       Expr *LHS = SimpleExpr;
12758       Expr *RHS = nullptr;
12759       if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
12760         OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
12761         OOLoc = BO->getOperatorLoc();
12762         LHS = BO->getLHS()->IgnoreParenImpCasts();
12763         RHS = BO->getRHS()->IgnoreParenImpCasts();
12764       } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
12765         OOK = OCE->getOperator();
12766         OOLoc = OCE->getOperatorLoc();
12767         LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
12768         RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
12769       } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
12770         OOK = MCE->getMethodDecl()
12771                   ->getNameInfo()
12772                   .getName()
12773                   .getCXXOverloadedOperator();
12774         OOLoc = MCE->getCallee()->getExprLoc();
12775         LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
12776         RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
12777       }
12778       SourceLocation ELoc;
12779       SourceRange ERange;
12780       auto Res = getPrivateItem(*this, LHS, ELoc, ERange);
12781       if (Res.second) {
12782         // It will be analyzed later.
12783         Vars.push_back(RefExpr);
12784       }
12785       ValueDecl *D = Res.first;
12786       if (!D)
12787         continue;
12788 
12789       if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
12790         Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
12791         continue;
12792       }
12793       if (RHS) {
12794         ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
12795             RHS, OMPC_depend, /*StrictlyPositive=*/false);
12796         if (RHSRes.isInvalid())
12797           continue;
12798       }
12799       if (!CurContext->isDependentContext() &&
12800           DSAStack->getParentOrderedRegionParam().first &&
12801           DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
12802         const ValueDecl *VD =
12803             DSAStack->getParentLoopControlVariable(DepCounter.getZExtValue());
12804         if (VD)
12805           Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
12806               << 1 << VD;
12807         else
12808           Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0;
12809         continue;
12810       }
12811       OpsOffs.emplace_back(RHS, OOK);
12812     } else {
12813       auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
12814       if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
12815           (ASE &&
12816            !ASE->getBase()->getType().getNonReferenceType()->isPointerType() &&
12817            !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
12818         Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
12819             << RefExpr->getSourceRange();
12820         continue;
12821       }
12822       bool Suppress = getDiagnostics().getSuppressAllDiagnostics();
12823       getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
12824       ExprResult Res =
12825           CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RefExpr->IgnoreParenImpCasts());
12826       getDiagnostics().setSuppressAllDiagnostics(Suppress);
12827       if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr)) {
12828         Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
12829             << RefExpr->getSourceRange();
12830         continue;
12831       }
12832     }
12833     Vars.push_back(RefExpr->IgnoreParenImpCasts());
12834   }
12835 
12836   if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
12837       TotalDepCount > VarList.size() &&
12838       DSAStack->getParentOrderedRegionParam().first &&
12839       DSAStack->getParentLoopControlVariable(VarList.size() + 1)) {
12840     Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
12841         << 1 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
12842   }
12843   if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
12844       Vars.empty())
12845     return nullptr;
12846 
12847   auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
12848                                     DepKind, DepLoc, ColonLoc, Vars,
12849                                     TotalDepCount.getZExtValue());
12850   if ((DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) &&
12851       DSAStack->isParentOrderedRegion())
12852     DSAStack->addDoacrossDependClause(C, OpsOffs);
12853   return C;
12854 }
12855 
12856 OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
12857                                          SourceLocation LParenLoc,
12858                                          SourceLocation EndLoc) {
12859   Expr *ValExpr = Device;
12860   Stmt *HelperValStmt = nullptr;
12861 
12862   // OpenMP [2.9.1, Restrictions]
12863   // The device expression must evaluate to a non-negative integer value.
12864   if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
12865                                  /*StrictlyPositive=*/false))
12866     return nullptr;
12867 
12868   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
12869   OpenMPDirectiveKind CaptureRegion =
12870       getOpenMPCaptureRegionForClause(DKind, OMPC_device);
12871   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
12872     ValExpr = MakeFullExpr(ValExpr).get();
12873     llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
12874     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
12875     HelperValStmt = buildPreInits(Context, Captures);
12876   }
12877 
12878   return new (Context) OMPDeviceClause(ValExpr, HelperValStmt, CaptureRegion,
12879                                        StartLoc, LParenLoc, EndLoc);
12880 }
12881 
12882 static bool checkTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
12883                               DSAStackTy *Stack, QualType QTy,
12884                               bool FullCheck = true) {
12885   NamedDecl *ND;
12886   if (QTy->isIncompleteType(&ND)) {
12887     SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
12888     return false;
12889   }
12890   if (FullCheck && !SemaRef.CurContext->isDependentContext() &&
12891       !QTy.isTrivialType(SemaRef.Context))
12892     SemaRef.Diag(SL, diag::warn_omp_non_trivial_type_mapped) << QTy << SR;
12893   return true;
12894 }
12895 
12896 /// Return true if it can be proven that the provided array expression
12897 /// (array section or array subscript) does NOT specify the whole size of the
12898 /// array whose base type is \a BaseQTy.
12899 static bool checkArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
12900                                                         const Expr *E,
12901                                                         QualType BaseQTy) {
12902   const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
12903 
12904   // If this is an array subscript, it refers to the whole size if the size of
12905   // the dimension is constant and equals 1. Also, an array section assumes the
12906   // format of an array subscript if no colon is used.
12907   if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
12908     if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
12909       return ATy->getSize().getSExtValue() != 1;
12910     // Size can't be evaluated statically.
12911     return false;
12912   }
12913 
12914   assert(OASE && "Expecting array section if not an array subscript.");
12915   const Expr *LowerBound = OASE->getLowerBound();
12916   const Expr *Length = OASE->getLength();
12917 
12918   // If there is a lower bound that does not evaluates to zero, we are not
12919   // covering the whole dimension.
12920   if (LowerBound) {
12921     Expr::EvalResult Result;
12922     if (!LowerBound->EvaluateAsInt(Result, SemaRef.getASTContext()))
12923       return false; // Can't get the integer value as a constant.
12924 
12925     llvm::APSInt ConstLowerBound = Result.Val.getInt();
12926     if (ConstLowerBound.getSExtValue())
12927       return true;
12928   }
12929 
12930   // If we don't have a length we covering the whole dimension.
12931   if (!Length)
12932     return false;
12933 
12934   // If the base is a pointer, we don't have a way to get the size of the
12935   // pointee.
12936   if (BaseQTy->isPointerType())
12937     return false;
12938 
12939   // We can only check if the length is the same as the size of the dimension
12940   // if we have a constant array.
12941   const auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
12942   if (!CATy)
12943     return false;
12944 
12945   Expr::EvalResult Result;
12946   if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
12947     return false; // Can't get the integer value as a constant.
12948 
12949   llvm::APSInt ConstLength = Result.Val.getInt();
12950   return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
12951 }
12952 
12953 // Return true if it can be proven that the provided array expression (array
12954 // section or array subscript) does NOT specify a single element of the array
12955 // whose base type is \a BaseQTy.
12956 static bool checkArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
12957                                                         const Expr *E,
12958                                                         QualType BaseQTy) {
12959   const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
12960 
12961   // An array subscript always refer to a single element. Also, an array section
12962   // assumes the format of an array subscript if no colon is used.
12963   if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
12964     return false;
12965 
12966   assert(OASE && "Expecting array section if not an array subscript.");
12967   const Expr *Length = OASE->getLength();
12968 
12969   // If we don't have a length we have to check if the array has unitary size
12970   // for this dimension. Also, we should always expect a length if the base type
12971   // is pointer.
12972   if (!Length) {
12973     if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
12974       return ATy->getSize().getSExtValue() != 1;
12975     // We cannot assume anything.
12976     return false;
12977   }
12978 
12979   // Check if the length evaluates to 1.
12980   Expr::EvalResult Result;
12981   if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
12982     return false; // Can't get the integer value as a constant.
12983 
12984   llvm::APSInt ConstLength = Result.Val.getInt();
12985   return ConstLength.getSExtValue() != 1;
12986 }
12987 
12988 // Return the expression of the base of the mappable expression or null if it
12989 // cannot be determined and do all the necessary checks to see if the expression
12990 // is valid as a standalone mappable expression. In the process, record all the
12991 // components of the expression.
12992 static const Expr *checkMapClauseExpressionBase(
12993     Sema &SemaRef, Expr *E,
12994     OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
12995     OpenMPClauseKind CKind, bool NoDiagnose) {
12996   SourceLocation ELoc = E->getExprLoc();
12997   SourceRange ERange = E->getSourceRange();
12998 
12999   // The base of elements of list in a map clause have to be either:
13000   //  - a reference to variable or field.
13001   //  - a member expression.
13002   //  - an array expression.
13003   //
13004   // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
13005   // reference to 'r'.
13006   //
13007   // If we have:
13008   //
13009   // struct SS {
13010   //   Bla S;
13011   //   foo() {
13012   //     #pragma omp target map (S.Arr[:12]);
13013   //   }
13014   // }
13015   //
13016   // We want to retrieve the member expression 'this->S';
13017 
13018   const Expr *RelevantExpr = nullptr;
13019 
13020   // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
13021   //  If a list item is an array section, it must specify contiguous storage.
13022   //
13023   // For this restriction it is sufficient that we make sure only references
13024   // to variables or fields and array expressions, and that no array sections
13025   // exist except in the rightmost expression (unless they cover the whole
13026   // dimension of the array). E.g. these would be invalid:
13027   //
13028   //   r.ArrS[3:5].Arr[6:7]
13029   //
13030   //   r.ArrS[3:5].x
13031   //
13032   // but these would be valid:
13033   //   r.ArrS[3].Arr[6:7]
13034   //
13035   //   r.ArrS[3].x
13036 
13037   bool AllowUnitySizeArraySection = true;
13038   bool AllowWholeSizeArraySection = true;
13039 
13040   while (!RelevantExpr) {
13041     E = E->IgnoreParenImpCasts();
13042 
13043     if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
13044       if (!isa<VarDecl>(CurE->getDecl()))
13045         return nullptr;
13046 
13047       RelevantExpr = CurE;
13048 
13049       // If we got a reference to a declaration, we should not expect any array
13050       // section before that.
13051       AllowUnitySizeArraySection = false;
13052       AllowWholeSizeArraySection = false;
13053 
13054       // Record the component.
13055       CurComponents.emplace_back(CurE, CurE->getDecl());
13056     } else if (auto *CurE = dyn_cast<MemberExpr>(E)) {
13057       Expr *BaseE = CurE->getBase()->IgnoreParenImpCasts();
13058 
13059       if (isa<CXXThisExpr>(BaseE))
13060         // We found a base expression: this->Val.
13061         RelevantExpr = CurE;
13062       else
13063         E = BaseE;
13064 
13065       if (!isa<FieldDecl>(CurE->getMemberDecl())) {
13066         if (!NoDiagnose) {
13067           SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
13068               << CurE->getSourceRange();
13069           return nullptr;
13070         }
13071         if (RelevantExpr)
13072           return nullptr;
13073         continue;
13074       }
13075 
13076       auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
13077 
13078       // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
13079       //  A bit-field cannot appear in a map clause.
13080       //
13081       if (FD->isBitField()) {
13082         if (!NoDiagnose) {
13083           SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
13084               << CurE->getSourceRange() << getOpenMPClauseName(CKind);
13085           return nullptr;
13086         }
13087         if (RelevantExpr)
13088           return nullptr;
13089         continue;
13090       }
13091 
13092       // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
13093       //  If the type of a list item is a reference to a type T then the type
13094       //  will be considered to be T for all purposes of this clause.
13095       QualType CurType = BaseE->getType().getNonReferenceType();
13096 
13097       // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
13098       //  A list item cannot be a variable that is a member of a structure with
13099       //  a union type.
13100       //
13101       if (CurType->isUnionType()) {
13102         if (!NoDiagnose) {
13103           SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
13104               << CurE->getSourceRange();
13105           return nullptr;
13106         }
13107         continue;
13108       }
13109 
13110       // If we got a member expression, we should not expect any array section
13111       // before that:
13112       //
13113       // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
13114       //  If a list item is an element of a structure, only the rightmost symbol
13115       //  of the variable reference can be an array section.
13116       //
13117       AllowUnitySizeArraySection = false;
13118       AllowWholeSizeArraySection = false;
13119 
13120       // Record the component.
13121       CurComponents.emplace_back(CurE, FD);
13122     } else if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
13123       E = CurE->getBase()->IgnoreParenImpCasts();
13124 
13125       if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
13126         if (!NoDiagnose) {
13127           SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
13128               << 0 << CurE->getSourceRange();
13129           return nullptr;
13130         }
13131         continue;
13132       }
13133 
13134       // If we got an array subscript that express the whole dimension we
13135       // can have any array expressions before. If it only expressing part of
13136       // the dimension, we can only have unitary-size array expressions.
13137       if (checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
13138                                                       E->getType()))
13139         AllowWholeSizeArraySection = false;
13140 
13141       if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
13142         Expr::EvalResult Result;
13143         if (CurE->getIdx()->EvaluateAsInt(Result, SemaRef.getASTContext())) {
13144           if (!Result.Val.getInt().isNullValue()) {
13145             SemaRef.Diag(CurE->getIdx()->getExprLoc(),
13146                          diag::err_omp_invalid_map_this_expr);
13147             SemaRef.Diag(CurE->getIdx()->getExprLoc(),
13148                          diag::note_omp_invalid_subscript_on_this_ptr_map);
13149           }
13150         }
13151         RelevantExpr = TE;
13152       }
13153 
13154       // Record the component - we don't have any declaration associated.
13155       CurComponents.emplace_back(CurE, nullptr);
13156     } else if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
13157       assert(!NoDiagnose && "Array sections cannot be implicitly mapped.");
13158       E = CurE->getBase()->IgnoreParenImpCasts();
13159 
13160       QualType CurType =
13161           OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
13162 
13163       // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
13164       //  If the type of a list item is a reference to a type T then the type
13165       //  will be considered to be T for all purposes of this clause.
13166       if (CurType->isReferenceType())
13167         CurType = CurType->getPointeeType();
13168 
13169       bool IsPointer = CurType->isAnyPointerType();
13170 
13171       if (!IsPointer && !CurType->isArrayType()) {
13172         SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
13173             << 0 << CurE->getSourceRange();
13174         return nullptr;
13175       }
13176 
13177       bool NotWhole =
13178           checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
13179       bool NotUnity =
13180           checkArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
13181 
13182       if (AllowWholeSizeArraySection) {
13183         // Any array section is currently allowed. Allowing a whole size array
13184         // section implies allowing a unity array section as well.
13185         //
13186         // If this array section refers to the whole dimension we can still
13187         // accept other array sections before this one, except if the base is a
13188         // pointer. Otherwise, only unitary sections are accepted.
13189         if (NotWhole || IsPointer)
13190           AllowWholeSizeArraySection = false;
13191       } else if (AllowUnitySizeArraySection && NotUnity) {
13192         // A unity or whole array section is not allowed and that is not
13193         // compatible with the properties of the current array section.
13194         SemaRef.Diag(
13195             ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
13196             << CurE->getSourceRange();
13197         return nullptr;
13198       }
13199 
13200       if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
13201         Expr::EvalResult ResultR;
13202         Expr::EvalResult ResultL;
13203         if (CurE->getLength()->EvaluateAsInt(ResultR,
13204                                              SemaRef.getASTContext())) {
13205           if (!ResultR.Val.getInt().isOneValue()) {
13206             SemaRef.Diag(CurE->getLength()->getExprLoc(),
13207                          diag::err_omp_invalid_map_this_expr);
13208             SemaRef.Diag(CurE->getLength()->getExprLoc(),
13209                          diag::note_omp_invalid_length_on_this_ptr_mapping);
13210           }
13211         }
13212         if (CurE->getLowerBound() && CurE->getLowerBound()->EvaluateAsInt(
13213                                         ResultL, SemaRef.getASTContext())) {
13214           if (!ResultL.Val.getInt().isNullValue()) {
13215             SemaRef.Diag(CurE->getLowerBound()->getExprLoc(),
13216                          diag::err_omp_invalid_map_this_expr);
13217             SemaRef.Diag(CurE->getLowerBound()->getExprLoc(),
13218                          diag::note_omp_invalid_lower_bound_on_this_ptr_mapping);
13219           }
13220         }
13221         RelevantExpr = TE;
13222       }
13223 
13224       // Record the component - we don't have any declaration associated.
13225       CurComponents.emplace_back(CurE, nullptr);
13226     } else {
13227       if (!NoDiagnose) {
13228         // If nothing else worked, this is not a valid map clause expression.
13229         SemaRef.Diag(
13230             ELoc, diag::err_omp_expected_named_var_member_or_array_expression)
13231             << ERange;
13232       }
13233       return nullptr;
13234     }
13235   }
13236 
13237   return RelevantExpr;
13238 }
13239 
13240 // Return true if expression E associated with value VD has conflicts with other
13241 // map information.
13242 static bool checkMapConflicts(
13243     Sema &SemaRef, DSAStackTy *DSAS, const ValueDecl *VD, const Expr *E,
13244     bool CurrentRegionOnly,
13245     OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
13246     OpenMPClauseKind CKind) {
13247   assert(VD && E);
13248   SourceLocation ELoc = E->getExprLoc();
13249   SourceRange ERange = E->getSourceRange();
13250 
13251   // In order to easily check the conflicts we need to match each component of
13252   // the expression under test with the components of the expressions that are
13253   // already in the stack.
13254 
13255   assert(!CurComponents.empty() && "Map clause expression with no components!");
13256   assert(CurComponents.back().getAssociatedDeclaration() == VD &&
13257          "Map clause expression with unexpected base!");
13258 
13259   // Variables to help detecting enclosing problems in data environment nests.
13260   bool IsEnclosedByDataEnvironmentExpr = false;
13261   const Expr *EnclosingExpr = nullptr;
13262 
13263   bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
13264       VD, CurrentRegionOnly,
13265       [&IsEnclosedByDataEnvironmentExpr, &SemaRef, VD, CurrentRegionOnly, ELoc,
13266        ERange, CKind, &EnclosingExpr,
13267        CurComponents](OMPClauseMappableExprCommon::MappableExprComponentListRef
13268                           StackComponents,
13269                       OpenMPClauseKind) {
13270         assert(!StackComponents.empty() &&
13271                "Map clause expression with no components!");
13272         assert(StackComponents.back().getAssociatedDeclaration() == VD &&
13273                "Map clause expression with unexpected base!");
13274         (void)VD;
13275 
13276         // The whole expression in the stack.
13277         const Expr *RE = StackComponents.front().getAssociatedExpression();
13278 
13279         // Expressions must start from the same base. Here we detect at which
13280         // point both expressions diverge from each other and see if we can
13281         // detect if the memory referred to both expressions is contiguous and
13282         // do not overlap.
13283         auto CI = CurComponents.rbegin();
13284         auto CE = CurComponents.rend();
13285         auto SI = StackComponents.rbegin();
13286         auto SE = StackComponents.rend();
13287         for (; CI != CE && SI != SE; ++CI, ++SI) {
13288 
13289           // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
13290           //  At most one list item can be an array item derived from a given
13291           //  variable in map clauses of the same construct.
13292           if (CurrentRegionOnly &&
13293               (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
13294                isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
13295               (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
13296                isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
13297             SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
13298                          diag::err_omp_multiple_array_items_in_map_clause)
13299                 << CI->getAssociatedExpression()->getSourceRange();
13300             SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
13301                          diag::note_used_here)
13302                 << SI->getAssociatedExpression()->getSourceRange();
13303             return true;
13304           }
13305 
13306           // Do both expressions have the same kind?
13307           if (CI->getAssociatedExpression()->getStmtClass() !=
13308               SI->getAssociatedExpression()->getStmtClass())
13309             break;
13310 
13311           // Are we dealing with different variables/fields?
13312           if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
13313             break;
13314         }
13315         // Check if the extra components of the expressions in the enclosing
13316         // data environment are redundant for the current base declaration.
13317         // If they are, the maps completely overlap, which is legal.
13318         for (; SI != SE; ++SI) {
13319           QualType Type;
13320           if (const auto *ASE =
13321                   dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
13322             Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
13323           } else if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(
13324                          SI->getAssociatedExpression())) {
13325             const Expr *E = OASE->getBase()->IgnoreParenImpCasts();
13326             Type =
13327                 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
13328           }
13329           if (Type.isNull() || Type->isAnyPointerType() ||
13330               checkArrayExpressionDoesNotReferToWholeSize(
13331                   SemaRef, SI->getAssociatedExpression(), Type))
13332             break;
13333         }
13334 
13335         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
13336         //  List items of map clauses in the same construct must not share
13337         //  original storage.
13338         //
13339         // If the expressions are exactly the same or one is a subset of the
13340         // other, it means they are sharing storage.
13341         if (CI == CE && SI == SE) {
13342           if (CurrentRegionOnly) {
13343             if (CKind == OMPC_map) {
13344               SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
13345             } else {
13346               assert(CKind == OMPC_to || CKind == OMPC_from);
13347               SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
13348                   << ERange;
13349             }
13350             SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
13351                 << RE->getSourceRange();
13352             return true;
13353           }
13354           // If we find the same expression in the enclosing data environment,
13355           // that is legal.
13356           IsEnclosedByDataEnvironmentExpr = true;
13357           return false;
13358         }
13359 
13360         QualType DerivedType =
13361             std::prev(CI)->getAssociatedDeclaration()->getType();
13362         SourceLocation DerivedLoc =
13363             std::prev(CI)->getAssociatedExpression()->getExprLoc();
13364 
13365         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
13366         //  If the type of a list item is a reference to a type T then the type
13367         //  will be considered to be T for all purposes of this clause.
13368         DerivedType = DerivedType.getNonReferenceType();
13369 
13370         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
13371         //  A variable for which the type is pointer and an array section
13372         //  derived from that variable must not appear as list items of map
13373         //  clauses of the same construct.
13374         //
13375         // Also, cover one of the cases in:
13376         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
13377         //  If any part of the original storage of a list item has corresponding
13378         //  storage in the device data environment, all of the original storage
13379         //  must have corresponding storage in the device data environment.
13380         //
13381         if (DerivedType->isAnyPointerType()) {
13382           if (CI == CE || SI == SE) {
13383             SemaRef.Diag(
13384                 DerivedLoc,
13385                 diag::err_omp_pointer_mapped_along_with_derived_section)
13386                 << DerivedLoc;
13387             SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
13388                 << RE->getSourceRange();
13389             return true;
13390           }
13391           if (CI->getAssociatedExpression()->getStmtClass() !=
13392                          SI->getAssociatedExpression()->getStmtClass() ||
13393                      CI->getAssociatedDeclaration()->getCanonicalDecl() ==
13394                          SI->getAssociatedDeclaration()->getCanonicalDecl()) {
13395             assert(CI != CE && SI != SE);
13396             SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_dereferenced)
13397                 << DerivedLoc;
13398             SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
13399                 << RE->getSourceRange();
13400             return true;
13401           }
13402         }
13403 
13404         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
13405         //  List items of map clauses in the same construct must not share
13406         //  original storage.
13407         //
13408         // An expression is a subset of the other.
13409         if (CurrentRegionOnly && (CI == CE || SI == SE)) {
13410           if (CKind == OMPC_map) {
13411             if (CI != CE || SI != SE) {
13412               // Allow constructs like this: map(s, s.ptr[0:1]), where s.ptr is
13413               // a pointer.
13414               auto Begin =
13415                   CI != CE ? CurComponents.begin() : StackComponents.begin();
13416               auto End = CI != CE ? CurComponents.end() : StackComponents.end();
13417               auto It = Begin;
13418               while (It != End && !It->getAssociatedDeclaration())
13419                 std::advance(It, 1);
13420               assert(It != End &&
13421                      "Expected at least one component with the declaration.");
13422               if (It != Begin && It->getAssociatedDeclaration()
13423                                      ->getType()
13424                                      .getCanonicalType()
13425                                      ->isAnyPointerType()) {
13426                 IsEnclosedByDataEnvironmentExpr = false;
13427                 EnclosingExpr = nullptr;
13428                 return false;
13429               }
13430             }
13431             SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
13432           } else {
13433             assert(CKind == OMPC_to || CKind == OMPC_from);
13434             SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
13435                 << ERange;
13436           }
13437           SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
13438               << RE->getSourceRange();
13439           return true;
13440         }
13441 
13442         // The current expression uses the same base as other expression in the
13443         // data environment but does not contain it completely.
13444         if (!CurrentRegionOnly && SI != SE)
13445           EnclosingExpr = RE;
13446 
13447         // The current expression is a subset of the expression in the data
13448         // environment.
13449         IsEnclosedByDataEnvironmentExpr |=
13450             (!CurrentRegionOnly && CI != CE && SI == SE);
13451 
13452         return false;
13453       });
13454 
13455   if (CurrentRegionOnly)
13456     return FoundError;
13457 
13458   // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
13459   //  If any part of the original storage of a list item has corresponding
13460   //  storage in the device data environment, all of the original storage must
13461   //  have corresponding storage in the device data environment.
13462   // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
13463   //  If a list item is an element of a structure, and a different element of
13464   //  the structure has a corresponding list item in the device data environment
13465   //  prior to a task encountering the construct associated with the map clause,
13466   //  then the list item must also have a corresponding list item in the device
13467   //  data environment prior to the task encountering the construct.
13468   //
13469   if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
13470     SemaRef.Diag(ELoc,
13471                  diag::err_omp_original_storage_is_shared_and_does_not_contain)
13472         << ERange;
13473     SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
13474         << EnclosingExpr->getSourceRange();
13475     return true;
13476   }
13477 
13478   return FoundError;
13479 }
13480 
13481 // Look up the user-defined mapper given the mapper name and mapped type, and
13482 // build a reference to it.
13483 static ExprResult buildUserDefinedMapperRef(Sema &SemaRef, Scope *S,
13484                                             CXXScopeSpec &MapperIdScopeSpec,
13485                                             const DeclarationNameInfo &MapperId,
13486                                             QualType Type,
13487                                             Expr *UnresolvedMapper) {
13488   if (MapperIdScopeSpec.isInvalid())
13489     return ExprError();
13490   // Find all user-defined mappers with the given MapperId.
13491   SmallVector<UnresolvedSet<8>, 4> Lookups;
13492   LookupResult Lookup(SemaRef, MapperId, Sema::LookupOMPMapperName);
13493   Lookup.suppressDiagnostics();
13494   if (S) {
13495     while (S && SemaRef.LookupParsedName(Lookup, S, &MapperIdScopeSpec)) {
13496       NamedDecl *D = Lookup.getRepresentativeDecl();
13497       while (S && !S->isDeclScope(D))
13498         S = S->getParent();
13499       if (S)
13500         S = S->getParent();
13501       Lookups.emplace_back();
13502       Lookups.back().append(Lookup.begin(), Lookup.end());
13503       Lookup.clear();
13504     }
13505   } else if (auto *ULE = cast_or_null<UnresolvedLookupExpr>(UnresolvedMapper)) {
13506     // Extract the user-defined mappers with the given MapperId.
13507     Lookups.push_back(UnresolvedSet<8>());
13508     for (NamedDecl *D : ULE->decls()) {
13509       auto *DMD = cast<OMPDeclareMapperDecl>(D);
13510       assert(DMD && "Expect valid OMPDeclareMapperDecl during instantiation.");
13511       Lookups.back().addDecl(DMD);
13512     }
13513   }
13514   // Defer the lookup for dependent types. The results will be passed through
13515   // UnresolvedMapper on instantiation.
13516   if (SemaRef.CurContext->isDependentContext() || Type->isDependentType() ||
13517       Type->isInstantiationDependentType() ||
13518       Type->containsUnexpandedParameterPack() ||
13519       filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
13520         return !D->isInvalidDecl() &&
13521                (D->getType()->isDependentType() ||
13522                 D->getType()->isInstantiationDependentType() ||
13523                 D->getType()->containsUnexpandedParameterPack());
13524       })) {
13525     UnresolvedSet<8> URS;
13526     for (const UnresolvedSet<8> &Set : Lookups) {
13527       if (Set.empty())
13528         continue;
13529       URS.append(Set.begin(), Set.end());
13530     }
13531     return UnresolvedLookupExpr::Create(
13532         SemaRef.Context, /*NamingClass=*/nullptr,
13533         MapperIdScopeSpec.getWithLocInContext(SemaRef.Context), MapperId,
13534         /*ADL=*/false, /*Overloaded=*/true, URS.begin(), URS.end());
13535   }
13536   // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
13537   //  The type must be of struct, union or class type in C and C++
13538   if (!Type->isStructureOrClassType() && !Type->isUnionType())
13539     return ExprEmpty();
13540   SourceLocation Loc = MapperId.getLoc();
13541   // Perform argument dependent lookup.
13542   if (SemaRef.getLangOpts().CPlusPlus && !MapperIdScopeSpec.isSet())
13543     argumentDependentLookup(SemaRef, MapperId, Loc, Type, Lookups);
13544   // Return the first user-defined mapper with the desired type.
13545   if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
13546           Lookups, [&SemaRef, Type](ValueDecl *D) -> ValueDecl * {
13547             if (!D->isInvalidDecl() &&
13548                 SemaRef.Context.hasSameType(D->getType(), Type))
13549               return D;
13550             return nullptr;
13551           }))
13552     return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
13553   // Find the first user-defined mapper with a type derived from the desired
13554   // type.
13555   if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
13556           Lookups, [&SemaRef, Type, Loc](ValueDecl *D) -> ValueDecl * {
13557             if (!D->isInvalidDecl() &&
13558                 SemaRef.IsDerivedFrom(Loc, Type, D->getType()) &&
13559                 !Type.isMoreQualifiedThan(D->getType()))
13560               return D;
13561             return nullptr;
13562           })) {
13563     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
13564                        /*DetectVirtual=*/false);
13565     if (SemaRef.IsDerivedFrom(Loc, Type, VD->getType(), Paths)) {
13566       if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
13567               VD->getType().getUnqualifiedType()))) {
13568         if (SemaRef.CheckBaseClassAccess(
13569                 Loc, VD->getType(), Type, Paths.front(),
13570                 /*DiagID=*/0) != Sema::AR_inaccessible) {
13571           return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
13572         }
13573       }
13574     }
13575   }
13576   // Report error if a mapper is specified, but cannot be found.
13577   if (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default") {
13578     SemaRef.Diag(Loc, diag::err_omp_invalid_mapper)
13579         << Type << MapperId.getName();
13580     return ExprError();
13581   }
13582   return ExprEmpty();
13583 }
13584 
13585 namespace {
13586 // Utility struct that gathers all the related lists associated with a mappable
13587 // expression.
13588 struct MappableVarListInfo {
13589   // The list of expressions.
13590   ArrayRef<Expr *> VarList;
13591   // The list of processed expressions.
13592   SmallVector<Expr *, 16> ProcessedVarList;
13593   // The mappble components for each expression.
13594   OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
13595   // The base declaration of the variable.
13596   SmallVector<ValueDecl *, 16> VarBaseDeclarations;
13597   // The reference to the user-defined mapper associated with every expression.
13598   SmallVector<Expr *, 16> UDMapperList;
13599 
13600   MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
13601     // We have a list of components and base declarations for each entry in the
13602     // variable list.
13603     VarComponents.reserve(VarList.size());
13604     VarBaseDeclarations.reserve(VarList.size());
13605   }
13606 };
13607 }
13608 
13609 // Check the validity of the provided variable list for the provided clause kind
13610 // \a CKind. In the check process the valid expressions, mappable expression
13611 // components, variables, and user-defined mappers are extracted and used to
13612 // fill \a ProcessedVarList, \a VarComponents, \a VarBaseDeclarations, and \a
13613 // UDMapperList in MVLI. \a MapType, \a IsMapTypeImplicit, \a MapperIdScopeSpec,
13614 // and \a MapperId are expected to be valid if the clause kind is 'map'.
13615 static void checkMappableExpressionList(
13616     Sema &SemaRef, DSAStackTy *DSAS, OpenMPClauseKind CKind,
13617     MappableVarListInfo &MVLI, SourceLocation StartLoc,
13618     CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo MapperId,
13619     ArrayRef<Expr *> UnresolvedMappers,
13620     OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
13621     bool IsMapTypeImplicit = false) {
13622   // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
13623   assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
13624          "Unexpected clause kind with mappable expressions!");
13625 
13626   // If the identifier of user-defined mapper is not specified, it is "default".
13627   // We do not change the actual name in this clause to distinguish whether a
13628   // mapper is specified explicitly, i.e., it is not explicitly specified when
13629   // MapperId.getName() is empty.
13630   if (!MapperId.getName() || MapperId.getName().isEmpty()) {
13631     auto &DeclNames = SemaRef.getASTContext().DeclarationNames;
13632     MapperId.setName(DeclNames.getIdentifier(
13633         &SemaRef.getASTContext().Idents.get("default")));
13634   }
13635 
13636   // Iterators to find the current unresolved mapper expression.
13637   auto UMIt = UnresolvedMappers.begin(), UMEnd = UnresolvedMappers.end();
13638   bool UpdateUMIt = false;
13639   Expr *UnresolvedMapper = nullptr;
13640 
13641   // Keep track of the mappable components and base declarations in this clause.
13642   // Each entry in the list is going to have a list of components associated. We
13643   // record each set of the components so that we can build the clause later on.
13644   // In the end we should have the same amount of declarations and component
13645   // lists.
13646 
13647   for (Expr *RE : MVLI.VarList) {
13648     assert(RE && "Null expr in omp to/from/map clause");
13649     SourceLocation ELoc = RE->getExprLoc();
13650 
13651     // Find the current unresolved mapper expression.
13652     if (UpdateUMIt && UMIt != UMEnd) {
13653       UMIt++;
13654       assert(
13655           UMIt != UMEnd &&
13656           "Expect the size of UnresolvedMappers to match with that of VarList");
13657     }
13658     UpdateUMIt = true;
13659     if (UMIt != UMEnd)
13660       UnresolvedMapper = *UMIt;
13661 
13662     const Expr *VE = RE->IgnoreParenLValueCasts();
13663 
13664     if (VE->isValueDependent() || VE->isTypeDependent() ||
13665         VE->isInstantiationDependent() ||
13666         VE->containsUnexpandedParameterPack()) {
13667       // Try to find the associated user-defined mapper.
13668       ExprResult ER = buildUserDefinedMapperRef(
13669           SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
13670           VE->getType().getCanonicalType(), UnresolvedMapper);
13671       if (ER.isInvalid())
13672         continue;
13673       MVLI.UDMapperList.push_back(ER.get());
13674       // We can only analyze this information once the missing information is
13675       // resolved.
13676       MVLI.ProcessedVarList.push_back(RE);
13677       continue;
13678     }
13679 
13680     Expr *SimpleExpr = RE->IgnoreParenCasts();
13681 
13682     if (!RE->IgnoreParenImpCasts()->isLValue()) {
13683       SemaRef.Diag(ELoc,
13684                    diag::err_omp_expected_named_var_member_or_array_expression)
13685           << RE->getSourceRange();
13686       continue;
13687     }
13688 
13689     OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
13690     ValueDecl *CurDeclaration = nullptr;
13691 
13692     // Obtain the array or member expression bases if required. Also, fill the
13693     // components array with all the components identified in the process.
13694     const Expr *BE = checkMapClauseExpressionBase(
13695         SemaRef, SimpleExpr, CurComponents, CKind, /*NoDiagnose=*/false);
13696     if (!BE)
13697       continue;
13698 
13699     assert(!CurComponents.empty() &&
13700            "Invalid mappable expression information.");
13701 
13702     if (const auto *TE = dyn_cast<CXXThisExpr>(BE)) {
13703       // Add store "this" pointer to class in DSAStackTy for future checking
13704       DSAS->addMappedClassesQualTypes(TE->getType());
13705       // Try to find the associated user-defined mapper.
13706       ExprResult ER = buildUserDefinedMapperRef(
13707           SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
13708           VE->getType().getCanonicalType(), UnresolvedMapper);
13709       if (ER.isInvalid())
13710         continue;
13711       MVLI.UDMapperList.push_back(ER.get());
13712       // Skip restriction checking for variable or field declarations
13713       MVLI.ProcessedVarList.push_back(RE);
13714       MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
13715       MVLI.VarComponents.back().append(CurComponents.begin(),
13716                                        CurComponents.end());
13717       MVLI.VarBaseDeclarations.push_back(nullptr);
13718       continue;
13719     }
13720 
13721     // For the following checks, we rely on the base declaration which is
13722     // expected to be associated with the last component. The declaration is
13723     // expected to be a variable or a field (if 'this' is being mapped).
13724     CurDeclaration = CurComponents.back().getAssociatedDeclaration();
13725     assert(CurDeclaration && "Null decl on map clause.");
13726     assert(
13727         CurDeclaration->isCanonicalDecl() &&
13728         "Expecting components to have associated only canonical declarations.");
13729 
13730     auto *VD = dyn_cast<VarDecl>(CurDeclaration);
13731     const auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
13732 
13733     assert((VD || FD) && "Only variables or fields are expected here!");
13734     (void)FD;
13735 
13736     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
13737     // threadprivate variables cannot appear in a map clause.
13738     // OpenMP 4.5 [2.10.5, target update Construct]
13739     // threadprivate variables cannot appear in a from clause.
13740     if (VD && DSAS->isThreadPrivate(VD)) {
13741       DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
13742       SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
13743           << getOpenMPClauseName(CKind);
13744       reportOriginalDsa(SemaRef, DSAS, VD, DVar);
13745       continue;
13746     }
13747 
13748     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
13749     //  A list item cannot appear in both a map clause and a data-sharing
13750     //  attribute clause on the same construct.
13751 
13752     // Check conflicts with other map clause expressions. We check the conflicts
13753     // with the current construct separately from the enclosing data
13754     // environment, because the restrictions are different. We only have to
13755     // check conflicts across regions for the map clauses.
13756     if (checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
13757                           /*CurrentRegionOnly=*/true, CurComponents, CKind))
13758       break;
13759     if (CKind == OMPC_map &&
13760         checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
13761                           /*CurrentRegionOnly=*/false, CurComponents, CKind))
13762       break;
13763 
13764     // OpenMP 4.5 [2.10.5, target update Construct]
13765     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
13766     //  If the type of a list item is a reference to a type T then the type will
13767     //  be considered to be T for all purposes of this clause.
13768     auto I = llvm::find_if(
13769         CurComponents,
13770         [](const OMPClauseMappableExprCommon::MappableComponent &MC) {
13771           return MC.getAssociatedDeclaration();
13772         });
13773     assert(I != CurComponents.end() && "Null decl on map clause.");
13774     QualType Type =
13775         I->getAssociatedDeclaration()->getType().getNonReferenceType();
13776 
13777     // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
13778     // A list item in a to or from clause must have a mappable type.
13779     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
13780     //  A list item must have a mappable type.
13781     if (!checkTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
13782                            DSAS, Type))
13783       continue;
13784 
13785     if (CKind == OMPC_map) {
13786       // target enter data
13787       // OpenMP [2.10.2, Restrictions, p. 99]
13788       // A map-type must be specified in all map clauses and must be either
13789       // to or alloc.
13790       OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
13791       if (DKind == OMPD_target_enter_data &&
13792           !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
13793         SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
13794             << (IsMapTypeImplicit ? 1 : 0)
13795             << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
13796             << getOpenMPDirectiveName(DKind);
13797         continue;
13798       }
13799 
13800       // target exit_data
13801       // OpenMP [2.10.3, Restrictions, p. 102]
13802       // A map-type must be specified in all map clauses and must be either
13803       // from, release, or delete.
13804       if (DKind == OMPD_target_exit_data &&
13805           !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
13806             MapType == OMPC_MAP_delete)) {
13807         SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
13808             << (IsMapTypeImplicit ? 1 : 0)
13809             << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
13810             << getOpenMPDirectiveName(DKind);
13811         continue;
13812       }
13813 
13814       // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
13815       // A list item cannot appear in both a map clause and a data-sharing
13816       // attribute clause on the same construct
13817       if (VD && isOpenMPTargetExecutionDirective(DKind)) {
13818         DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
13819         if (isOpenMPPrivate(DVar.CKind)) {
13820           SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
13821               << getOpenMPClauseName(DVar.CKind)
13822               << getOpenMPClauseName(OMPC_map)
13823               << getOpenMPDirectiveName(DSAS->getCurrentDirective());
13824           reportOriginalDsa(SemaRef, DSAS, CurDeclaration, DVar);
13825           continue;
13826         }
13827       }
13828     }
13829 
13830     // Try to find the associated user-defined mapper.
13831     ExprResult ER = buildUserDefinedMapperRef(
13832         SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
13833         Type.getCanonicalType(), UnresolvedMapper);
13834     if (ER.isInvalid())
13835       continue;
13836     MVLI.UDMapperList.push_back(ER.get());
13837 
13838     // Save the current expression.
13839     MVLI.ProcessedVarList.push_back(RE);
13840 
13841     // Store the components in the stack so that they can be used to check
13842     // against other clauses later on.
13843     DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
13844                                           /*WhereFoundClauseKind=*/OMPC_map);
13845 
13846     // Save the components and declaration to create the clause. For purposes of
13847     // the clause creation, any component list that has has base 'this' uses
13848     // null as base declaration.
13849     MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
13850     MVLI.VarComponents.back().append(CurComponents.begin(),
13851                                      CurComponents.end());
13852     MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
13853                                                            : CurDeclaration);
13854   }
13855 }
13856 
13857 OMPClause *Sema::ActOnOpenMPMapClause(
13858     ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
13859     ArrayRef<SourceLocation> MapTypeModifiersLoc,
13860     CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId,
13861     OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, SourceLocation MapLoc,
13862     SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
13863     const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) {
13864   OpenMPMapModifierKind Modifiers[] = {OMPC_MAP_MODIFIER_unknown,
13865                                        OMPC_MAP_MODIFIER_unknown,
13866                                        OMPC_MAP_MODIFIER_unknown};
13867   SourceLocation ModifiersLoc[OMPMapClause::NumberOfModifiers];
13868 
13869   // Process map-type-modifiers, flag errors for duplicate modifiers.
13870   unsigned Count = 0;
13871   for (unsigned I = 0, E = MapTypeModifiers.size(); I < E; ++I) {
13872     if (MapTypeModifiers[I] != OMPC_MAP_MODIFIER_unknown &&
13873         llvm::find(Modifiers, MapTypeModifiers[I]) != std::end(Modifiers)) {
13874       Diag(MapTypeModifiersLoc[I], diag::err_omp_duplicate_map_type_modifier);
13875       continue;
13876     }
13877     assert(Count < OMPMapClause::NumberOfModifiers &&
13878            "Modifiers exceed the allowed number of map type modifiers");
13879     Modifiers[Count] = MapTypeModifiers[I];
13880     ModifiersLoc[Count] = MapTypeModifiersLoc[I];
13881     ++Count;
13882   }
13883 
13884   MappableVarListInfo MVLI(VarList);
13885   checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, Locs.StartLoc,
13886                               MapperIdScopeSpec, MapperId, UnresolvedMappers,
13887                               MapType, IsMapTypeImplicit);
13888 
13889   // We need to produce a map clause even if we don't have variables so that
13890   // other diagnostics related with non-existing map clauses are accurate.
13891   return OMPMapClause::Create(Context, Locs, MVLI.ProcessedVarList,
13892                               MVLI.VarBaseDeclarations, MVLI.VarComponents,
13893                               MVLI.UDMapperList, Modifiers, ModifiersLoc,
13894                               MapperIdScopeSpec.getWithLocInContext(Context),
13895                               MapperId, MapType, IsMapTypeImplicit, MapLoc);
13896 }
13897 
13898 QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
13899                                                TypeResult ParsedType) {
13900   assert(ParsedType.isUsable());
13901 
13902   QualType ReductionType = GetTypeFromParser(ParsedType.get());
13903   if (ReductionType.isNull())
13904     return QualType();
13905 
13906   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
13907   // A type name in a declare reduction directive cannot be a function type, an
13908   // array type, a reference type, or a type qualified with const, volatile or
13909   // restrict.
13910   if (ReductionType.hasQualifiers()) {
13911     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
13912     return QualType();
13913   }
13914 
13915   if (ReductionType->isFunctionType()) {
13916     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
13917     return QualType();
13918   }
13919   if (ReductionType->isReferenceType()) {
13920     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
13921     return QualType();
13922   }
13923   if (ReductionType->isArrayType()) {
13924     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
13925     return QualType();
13926   }
13927   return ReductionType;
13928 }
13929 
13930 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
13931     Scope *S, DeclContext *DC, DeclarationName Name,
13932     ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
13933     AccessSpecifier AS, Decl *PrevDeclInScope) {
13934   SmallVector<Decl *, 8> Decls;
13935   Decls.reserve(ReductionTypes.size());
13936 
13937   LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
13938                       forRedeclarationInCurContext());
13939   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
13940   // A reduction-identifier may not be re-declared in the current scope for the
13941   // same type or for a type that is compatible according to the base language
13942   // rules.
13943   llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
13944   OMPDeclareReductionDecl *PrevDRD = nullptr;
13945   bool InCompoundScope = true;
13946   if (S != nullptr) {
13947     // Find previous declaration with the same name not referenced in other
13948     // declarations.
13949     FunctionScopeInfo *ParentFn = getEnclosingFunction();
13950     InCompoundScope =
13951         (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
13952     LookupName(Lookup, S);
13953     FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
13954                          /*AllowInlineNamespace=*/false);
13955     llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
13956     LookupResult::Filter Filter = Lookup.makeFilter();
13957     while (Filter.hasNext()) {
13958       auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
13959       if (InCompoundScope) {
13960         auto I = UsedAsPrevious.find(PrevDecl);
13961         if (I == UsedAsPrevious.end())
13962           UsedAsPrevious[PrevDecl] = false;
13963         if (OMPDeclareReductionDecl *D = PrevDecl->getPrevDeclInScope())
13964           UsedAsPrevious[D] = true;
13965       }
13966       PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
13967           PrevDecl->getLocation();
13968     }
13969     Filter.done();
13970     if (InCompoundScope) {
13971       for (const auto &PrevData : UsedAsPrevious) {
13972         if (!PrevData.second) {
13973           PrevDRD = PrevData.first;
13974           break;
13975         }
13976       }
13977     }
13978   } else if (PrevDeclInScope != nullptr) {
13979     auto *PrevDRDInScope = PrevDRD =
13980         cast<OMPDeclareReductionDecl>(PrevDeclInScope);
13981     do {
13982       PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
13983           PrevDRDInScope->getLocation();
13984       PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
13985     } while (PrevDRDInScope != nullptr);
13986   }
13987   for (const auto &TyData : ReductionTypes) {
13988     const auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
13989     bool Invalid = false;
13990     if (I != PreviousRedeclTypes.end()) {
13991       Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
13992           << TyData.first;
13993       Diag(I->second, diag::note_previous_definition);
13994       Invalid = true;
13995     }
13996     PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
13997     auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
13998                                                 Name, TyData.first, PrevDRD);
13999     DC->addDecl(DRD);
14000     DRD->setAccess(AS);
14001     Decls.push_back(DRD);
14002     if (Invalid)
14003       DRD->setInvalidDecl();
14004     else
14005       PrevDRD = DRD;
14006   }
14007 
14008   return DeclGroupPtrTy::make(
14009       DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
14010 }
14011 
14012 void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
14013   auto *DRD = cast<OMPDeclareReductionDecl>(D);
14014 
14015   // Enter new function scope.
14016   PushFunctionScope();
14017   setFunctionHasBranchProtectedScope();
14018   getCurFunction()->setHasOMPDeclareReductionCombiner();
14019 
14020   if (S != nullptr)
14021     PushDeclContext(S, DRD);
14022   else
14023     CurContext = DRD;
14024 
14025   PushExpressionEvaluationContext(
14026       ExpressionEvaluationContext::PotentiallyEvaluated);
14027 
14028   QualType ReductionType = DRD->getType();
14029   // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
14030   // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
14031   // uses semantics of argument handles by value, but it should be passed by
14032   // reference. C lang does not support references, so pass all parameters as
14033   // pointers.
14034   // Create 'T omp_in;' variable.
14035   VarDecl *OmpInParm =
14036       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
14037   // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
14038   // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
14039   // uses semantics of argument handles by value, but it should be passed by
14040   // reference. C lang does not support references, so pass all parameters as
14041   // pointers.
14042   // Create 'T omp_out;' variable.
14043   VarDecl *OmpOutParm =
14044       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
14045   if (S != nullptr) {
14046     PushOnScopeChains(OmpInParm, S);
14047     PushOnScopeChains(OmpOutParm, S);
14048   } else {
14049     DRD->addDecl(OmpInParm);
14050     DRD->addDecl(OmpOutParm);
14051   }
14052   Expr *InE =
14053       ::buildDeclRefExpr(*this, OmpInParm, ReductionType, D->getLocation());
14054   Expr *OutE =
14055       ::buildDeclRefExpr(*this, OmpOutParm, ReductionType, D->getLocation());
14056   DRD->setCombinerData(InE, OutE);
14057 }
14058 
14059 void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
14060   auto *DRD = cast<OMPDeclareReductionDecl>(D);
14061   DiscardCleanupsInEvaluationContext();
14062   PopExpressionEvaluationContext();
14063 
14064   PopDeclContext();
14065   PopFunctionScopeInfo();
14066 
14067   if (Combiner != nullptr)
14068     DRD->setCombiner(Combiner);
14069   else
14070     DRD->setInvalidDecl();
14071 }
14072 
14073 VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
14074   auto *DRD = cast<OMPDeclareReductionDecl>(D);
14075 
14076   // Enter new function scope.
14077   PushFunctionScope();
14078   setFunctionHasBranchProtectedScope();
14079 
14080   if (S != nullptr)
14081     PushDeclContext(S, DRD);
14082   else
14083     CurContext = DRD;
14084 
14085   PushExpressionEvaluationContext(
14086       ExpressionEvaluationContext::PotentiallyEvaluated);
14087 
14088   QualType ReductionType = DRD->getType();
14089   // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
14090   // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
14091   // uses semantics of argument handles by value, but it should be passed by
14092   // reference. C lang does not support references, so pass all parameters as
14093   // pointers.
14094   // Create 'T omp_priv;' variable.
14095   VarDecl *OmpPrivParm =
14096       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
14097   // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
14098   // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
14099   // uses semantics of argument handles by value, but it should be passed by
14100   // reference. C lang does not support references, so pass all parameters as
14101   // pointers.
14102   // Create 'T omp_orig;' variable.
14103   VarDecl *OmpOrigParm =
14104       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
14105   if (S != nullptr) {
14106     PushOnScopeChains(OmpPrivParm, S);
14107     PushOnScopeChains(OmpOrigParm, S);
14108   } else {
14109     DRD->addDecl(OmpPrivParm);
14110     DRD->addDecl(OmpOrigParm);
14111   }
14112   Expr *OrigE =
14113       ::buildDeclRefExpr(*this, OmpOrigParm, ReductionType, D->getLocation());
14114   Expr *PrivE =
14115       ::buildDeclRefExpr(*this, OmpPrivParm, ReductionType, D->getLocation());
14116   DRD->setInitializerData(OrigE, PrivE);
14117   return OmpPrivParm;
14118 }
14119 
14120 void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
14121                                                      VarDecl *OmpPrivParm) {
14122   auto *DRD = cast<OMPDeclareReductionDecl>(D);
14123   DiscardCleanupsInEvaluationContext();
14124   PopExpressionEvaluationContext();
14125 
14126   PopDeclContext();
14127   PopFunctionScopeInfo();
14128 
14129   if (Initializer != nullptr) {
14130     DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit);
14131   } else if (OmpPrivParm->hasInit()) {
14132     DRD->setInitializer(OmpPrivParm->getInit(),
14133                         OmpPrivParm->isDirectInit()
14134                             ? OMPDeclareReductionDecl::DirectInit
14135                             : OMPDeclareReductionDecl::CopyInit);
14136   } else {
14137     DRD->setInvalidDecl();
14138   }
14139 }
14140 
14141 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
14142     Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
14143   for (Decl *D : DeclReductions.get()) {
14144     if (IsValid) {
14145       if (S)
14146         PushOnScopeChains(cast<OMPDeclareReductionDecl>(D), S,
14147                           /*AddToContext=*/false);
14148     } else {
14149       D->setInvalidDecl();
14150     }
14151   }
14152   return DeclReductions;
14153 }
14154 
14155 TypeResult Sema::ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D) {
14156   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14157   QualType T = TInfo->getType();
14158   if (D.isInvalidType())
14159     return true;
14160 
14161   if (getLangOpts().CPlusPlus) {
14162     // Check that there are no default arguments (C++ only).
14163     CheckExtraCXXDefaultArguments(D);
14164   }
14165 
14166   return CreateParsedType(T, TInfo);
14167 }
14168 
14169 QualType Sema::ActOnOpenMPDeclareMapperType(SourceLocation TyLoc,
14170                                             TypeResult ParsedType) {
14171   assert(ParsedType.isUsable() && "Expect usable parsed mapper type");
14172 
14173   QualType MapperType = GetTypeFromParser(ParsedType.get());
14174   assert(!MapperType.isNull() && "Expect valid mapper type");
14175 
14176   // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
14177   //  The type must be of struct, union or class type in C and C++
14178   if (!MapperType->isStructureOrClassType() && !MapperType->isUnionType()) {
14179     Diag(TyLoc, diag::err_omp_mapper_wrong_type);
14180     return QualType();
14181   }
14182   return MapperType;
14183 }
14184 
14185 OMPDeclareMapperDecl *Sema::ActOnOpenMPDeclareMapperDirectiveStart(
14186     Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType,
14187     SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS,
14188     Decl *PrevDeclInScope) {
14189   LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPMapperName,
14190                       forRedeclarationInCurContext());
14191   // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
14192   //  A mapper-identifier may not be redeclared in the current scope for the
14193   //  same type or for a type that is compatible according to the base language
14194   //  rules.
14195   llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
14196   OMPDeclareMapperDecl *PrevDMD = nullptr;
14197   bool InCompoundScope = true;
14198   if (S != nullptr) {
14199     // Find previous declaration with the same name not referenced in other
14200     // declarations.
14201     FunctionScopeInfo *ParentFn = getEnclosingFunction();
14202     InCompoundScope =
14203         (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
14204     LookupName(Lookup, S);
14205     FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
14206                          /*AllowInlineNamespace=*/false);
14207     llvm::DenseMap<OMPDeclareMapperDecl *, bool> UsedAsPrevious;
14208     LookupResult::Filter Filter = Lookup.makeFilter();
14209     while (Filter.hasNext()) {
14210       auto *PrevDecl = cast<OMPDeclareMapperDecl>(Filter.next());
14211       if (InCompoundScope) {
14212         auto I = UsedAsPrevious.find(PrevDecl);
14213         if (I == UsedAsPrevious.end())
14214           UsedAsPrevious[PrevDecl] = false;
14215         if (OMPDeclareMapperDecl *D = PrevDecl->getPrevDeclInScope())
14216           UsedAsPrevious[D] = true;
14217       }
14218       PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
14219           PrevDecl->getLocation();
14220     }
14221     Filter.done();
14222     if (InCompoundScope) {
14223       for (const auto &PrevData : UsedAsPrevious) {
14224         if (!PrevData.second) {
14225           PrevDMD = PrevData.first;
14226           break;
14227         }
14228       }
14229     }
14230   } else if (PrevDeclInScope) {
14231     auto *PrevDMDInScope = PrevDMD =
14232         cast<OMPDeclareMapperDecl>(PrevDeclInScope);
14233     do {
14234       PreviousRedeclTypes[PrevDMDInScope->getType().getCanonicalType()] =
14235           PrevDMDInScope->getLocation();
14236       PrevDMDInScope = PrevDMDInScope->getPrevDeclInScope();
14237     } while (PrevDMDInScope != nullptr);
14238   }
14239   const auto I = PreviousRedeclTypes.find(MapperType.getCanonicalType());
14240   bool Invalid = false;
14241   if (I != PreviousRedeclTypes.end()) {
14242     Diag(StartLoc, diag::err_omp_declare_mapper_redefinition)
14243         << MapperType << Name;
14244     Diag(I->second, diag::note_previous_definition);
14245     Invalid = true;
14246   }
14247   auto *DMD = OMPDeclareMapperDecl::Create(Context, DC, StartLoc, Name,
14248                                            MapperType, VN, PrevDMD);
14249   DC->addDecl(DMD);
14250   DMD->setAccess(AS);
14251   if (Invalid)
14252     DMD->setInvalidDecl();
14253 
14254   // Enter new function scope.
14255   PushFunctionScope();
14256   setFunctionHasBranchProtectedScope();
14257 
14258   CurContext = DMD;
14259 
14260   return DMD;
14261 }
14262 
14263 void Sema::ActOnOpenMPDeclareMapperDirectiveVarDecl(OMPDeclareMapperDecl *DMD,
14264                                                     Scope *S,
14265                                                     QualType MapperType,
14266                                                     SourceLocation StartLoc,
14267                                                     DeclarationName VN) {
14268   VarDecl *VD = buildVarDecl(*this, StartLoc, MapperType, VN.getAsString());
14269   if (S)
14270     PushOnScopeChains(VD, S);
14271   else
14272     DMD->addDecl(VD);
14273   Expr *MapperVarRefExpr = buildDeclRefExpr(*this, VD, MapperType, StartLoc);
14274   DMD->setMapperVarRef(MapperVarRefExpr);
14275 }
14276 
14277 Sema::DeclGroupPtrTy
14278 Sema::ActOnOpenMPDeclareMapperDirectiveEnd(OMPDeclareMapperDecl *D, Scope *S,
14279                                            ArrayRef<OMPClause *> ClauseList) {
14280   PopDeclContext();
14281   PopFunctionScopeInfo();
14282 
14283   if (D) {
14284     if (S)
14285       PushOnScopeChains(D, S, /*AddToContext=*/false);
14286     D->CreateClauses(Context, ClauseList);
14287   }
14288 
14289   return DeclGroupPtrTy::make(DeclGroupRef(D));
14290 }
14291 
14292 OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
14293                                            SourceLocation StartLoc,
14294                                            SourceLocation LParenLoc,
14295                                            SourceLocation EndLoc) {
14296   Expr *ValExpr = NumTeams;
14297   Stmt *HelperValStmt = nullptr;
14298 
14299   // OpenMP [teams Constrcut, Restrictions]
14300   // The num_teams expression must evaluate to a positive integer value.
14301   if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
14302                                  /*StrictlyPositive=*/true))
14303     return nullptr;
14304 
14305   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
14306   OpenMPDirectiveKind CaptureRegion =
14307       getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams);
14308   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
14309     ValExpr = MakeFullExpr(ValExpr).get();
14310     llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
14311     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
14312     HelperValStmt = buildPreInits(Context, Captures);
14313   }
14314 
14315   return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
14316                                          StartLoc, LParenLoc, EndLoc);
14317 }
14318 
14319 OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
14320                                               SourceLocation StartLoc,
14321                                               SourceLocation LParenLoc,
14322                                               SourceLocation EndLoc) {
14323   Expr *ValExpr = ThreadLimit;
14324   Stmt *HelperValStmt = nullptr;
14325 
14326   // OpenMP [teams Constrcut, Restrictions]
14327   // The thread_limit expression must evaluate to a positive integer value.
14328   if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
14329                                  /*StrictlyPositive=*/true))
14330     return nullptr;
14331 
14332   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
14333   OpenMPDirectiveKind CaptureRegion =
14334       getOpenMPCaptureRegionForClause(DKind, OMPC_thread_limit);
14335   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
14336     ValExpr = MakeFullExpr(ValExpr).get();
14337     llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
14338     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
14339     HelperValStmt = buildPreInits(Context, Captures);
14340   }
14341 
14342   return new (Context) OMPThreadLimitClause(
14343       ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
14344 }
14345 
14346 OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
14347                                            SourceLocation StartLoc,
14348                                            SourceLocation LParenLoc,
14349                                            SourceLocation EndLoc) {
14350   Expr *ValExpr = Priority;
14351 
14352   // OpenMP [2.9.1, task Constrcut]
14353   // The priority-value is a non-negative numerical scalar expression.
14354   if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_priority,
14355                                  /*StrictlyPositive=*/false))
14356     return nullptr;
14357 
14358   return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc);
14359 }
14360 
14361 OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
14362                                             SourceLocation StartLoc,
14363                                             SourceLocation LParenLoc,
14364                                             SourceLocation EndLoc) {
14365   Expr *ValExpr = Grainsize;
14366 
14367   // OpenMP [2.9.2, taskloop Constrcut]
14368   // The parameter of the grainsize clause must be a positive integer
14369   // expression.
14370   if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize,
14371                                  /*StrictlyPositive=*/true))
14372     return nullptr;
14373 
14374   return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc);
14375 }
14376 
14377 OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
14378                                            SourceLocation StartLoc,
14379                                            SourceLocation LParenLoc,
14380                                            SourceLocation EndLoc) {
14381   Expr *ValExpr = NumTasks;
14382 
14383   // OpenMP [2.9.2, taskloop Constrcut]
14384   // The parameter of the num_tasks clause must be a positive integer
14385   // expression.
14386   if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks,
14387                                  /*StrictlyPositive=*/true))
14388     return nullptr;
14389 
14390   return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc);
14391 }
14392 
14393 OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
14394                                        SourceLocation LParenLoc,
14395                                        SourceLocation EndLoc) {
14396   // OpenMP [2.13.2, critical construct, Description]
14397   // ... where hint-expression is an integer constant expression that evaluates
14398   // to a valid lock hint.
14399   ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
14400   if (HintExpr.isInvalid())
14401     return nullptr;
14402   return new (Context)
14403       OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
14404 }
14405 
14406 OMPClause *Sema::ActOnOpenMPDistScheduleClause(
14407     OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
14408     SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
14409     SourceLocation EndLoc) {
14410   if (Kind == OMPC_DIST_SCHEDULE_unknown) {
14411     std::string Values;
14412     Values += "'";
14413     Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
14414     Values += "'";
14415     Diag(KindLoc, diag::err_omp_unexpected_clause_value)
14416         << Values << getOpenMPClauseName(OMPC_dist_schedule);
14417     return nullptr;
14418   }
14419   Expr *ValExpr = ChunkSize;
14420   Stmt *HelperValStmt = nullptr;
14421   if (ChunkSize) {
14422     if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
14423         !ChunkSize->isInstantiationDependent() &&
14424         !ChunkSize->containsUnexpandedParameterPack()) {
14425       SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
14426       ExprResult Val =
14427           PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
14428       if (Val.isInvalid())
14429         return nullptr;
14430 
14431       ValExpr = Val.get();
14432 
14433       // OpenMP [2.7.1, Restrictions]
14434       //  chunk_size must be a loop invariant integer expression with a positive
14435       //  value.
14436       llvm::APSInt Result;
14437       if (ValExpr->isIntegerConstantExpr(Result, Context)) {
14438         if (Result.isSigned() && !Result.isStrictlyPositive()) {
14439           Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
14440               << "dist_schedule" << ChunkSize->getSourceRange();
14441           return nullptr;
14442         }
14443       } else if (getOpenMPCaptureRegionForClause(
14444                      DSAStack->getCurrentDirective(), OMPC_dist_schedule) !=
14445                      OMPD_unknown &&
14446                  !CurContext->isDependentContext()) {
14447         ValExpr = MakeFullExpr(ValExpr).get();
14448         llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
14449         ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
14450         HelperValStmt = buildPreInits(Context, Captures);
14451       }
14452     }
14453   }
14454 
14455   return new (Context)
14456       OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
14457                             Kind, ValExpr, HelperValStmt);
14458 }
14459 
14460 OMPClause *Sema::ActOnOpenMPDefaultmapClause(
14461     OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
14462     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
14463     SourceLocation KindLoc, SourceLocation EndLoc) {
14464   // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)'
14465   if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) {
14466     std::string Value;
14467     SourceLocation Loc;
14468     Value += "'";
14469     if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
14470       Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
14471                                              OMPC_DEFAULTMAP_MODIFIER_tofrom);
14472       Loc = MLoc;
14473     } else {
14474       Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
14475                                              OMPC_DEFAULTMAP_scalar);
14476       Loc = KindLoc;
14477     }
14478     Value += "'";
14479     Diag(Loc, diag::err_omp_unexpected_clause_value)
14480         << Value << getOpenMPClauseName(OMPC_defaultmap);
14481     return nullptr;
14482   }
14483   DSAStack->setDefaultDMAToFromScalar(StartLoc);
14484 
14485   return new (Context)
14486       OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
14487 }
14488 
14489 bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
14490   DeclContext *CurLexicalContext = getCurLexicalContext();
14491   if (!CurLexicalContext->isFileContext() &&
14492       !CurLexicalContext->isExternCContext() &&
14493       !CurLexicalContext->isExternCXXContext() &&
14494       !isa<CXXRecordDecl>(CurLexicalContext) &&
14495       !isa<ClassTemplateDecl>(CurLexicalContext) &&
14496       !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) &&
14497       !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) {
14498     Diag(Loc, diag::err_omp_region_not_file_context);
14499     return false;
14500   }
14501   ++DeclareTargetNestingLevel;
14502   return true;
14503 }
14504 
14505 void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
14506   assert(DeclareTargetNestingLevel > 0 &&
14507          "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
14508   --DeclareTargetNestingLevel;
14509 }
14510 
14511 void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope,
14512                                         CXXScopeSpec &ScopeSpec,
14513                                         const DeclarationNameInfo &Id,
14514                                         OMPDeclareTargetDeclAttr::MapTypeTy MT,
14515                                         NamedDeclSetType &SameDirectiveDecls) {
14516   LookupResult Lookup(*this, Id, LookupOrdinaryName);
14517   LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
14518 
14519   if (Lookup.isAmbiguous())
14520     return;
14521   Lookup.suppressDiagnostics();
14522 
14523   if (!Lookup.isSingleResult()) {
14524     VarOrFuncDeclFilterCCC CCC(*this);
14525     if (TypoCorrection Corrected =
14526             CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC,
14527                         CTK_ErrorRecovery)) {
14528       diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
14529                                   << Id.getName());
14530       checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
14531       return;
14532     }
14533 
14534     Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
14535     return;
14536   }
14537 
14538   NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
14539   if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND) ||
14540       isa<FunctionTemplateDecl>(ND)) {
14541     if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
14542       Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
14543     llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
14544         OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
14545             cast<ValueDecl>(ND));
14546     if (!Res) {
14547       auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT);
14548       ND->addAttr(A);
14549       if (ASTMutationListener *ML = Context.getASTMutationListener())
14550         ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
14551       checkDeclIsAllowedInOpenMPTarget(nullptr, ND, Id.getLoc());
14552     } else if (*Res != MT) {
14553       Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link)
14554           << Id.getName();
14555     }
14556   } else {
14557     Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
14558   }
14559 }
14560 
14561 static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
14562                                      Sema &SemaRef, Decl *D) {
14563   if (!D || !isa<VarDecl>(D))
14564     return;
14565   auto *VD = cast<VarDecl>(D);
14566   if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
14567     return;
14568   SemaRef.Diag(VD->getLocation(), diag::warn_omp_not_in_target_context);
14569   SemaRef.Diag(SL, diag::note_used_here) << SR;
14570 }
14571 
14572 static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
14573                                    Sema &SemaRef, DSAStackTy *Stack,
14574                                    ValueDecl *VD) {
14575   return VD->hasAttr<OMPDeclareTargetDeclAttr>() ||
14576          checkTypeMappable(SL, SR, SemaRef, Stack, VD->getType(),
14577                            /*FullCheck=*/false);
14578 }
14579 
14580 void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
14581                                             SourceLocation IdLoc) {
14582   if (!D || D->isInvalidDecl())
14583     return;
14584   SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
14585   SourceLocation SL = E ? E->getBeginLoc() : D->getLocation();
14586   if (auto *VD = dyn_cast<VarDecl>(D)) {
14587     // Only global variables can be marked as declare target.
14588     if (!VD->isFileVarDecl() && !VD->isStaticLocal() &&
14589         !VD->isStaticDataMember())
14590       return;
14591     // 2.10.6: threadprivate variable cannot appear in a declare target
14592     // directive.
14593     if (DSAStack->isThreadPrivate(VD)) {
14594       Diag(SL, diag::err_omp_threadprivate_in_target);
14595       reportOriginalDsa(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
14596       return;
14597     }
14598   }
14599   if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(D))
14600     D = FTD->getTemplatedDecl();
14601   if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
14602     llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
14603         OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(FD);
14604     if (Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) {
14605       assert(IdLoc.isValid() && "Source location is expected");
14606       Diag(IdLoc, diag::err_omp_function_in_link_clause);
14607       Diag(FD->getLocation(), diag::note_defined_here) << FD;
14608       return;
14609     }
14610   }
14611   if (auto *VD = dyn_cast<ValueDecl>(D)) {
14612     // Problem if any with var declared with incomplete type will be reported
14613     // as normal, so no need to check it here.
14614     if ((E || !VD->getType()->isIncompleteType()) &&
14615         !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD))
14616       return;
14617     if (!E && !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
14618       // Checking declaration inside declare target region.
14619       if (isa<VarDecl>(D) || isa<FunctionDecl>(D) ||
14620           isa<FunctionTemplateDecl>(D)) {
14621         auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(
14622             Context, OMPDeclareTargetDeclAttr::MT_To);
14623         D->addAttr(A);
14624         if (ASTMutationListener *ML = Context.getASTMutationListener())
14625           ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
14626       }
14627       return;
14628     }
14629   }
14630   if (!E)
14631     return;
14632   checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
14633 }
14634 
14635 OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
14636                                      CXXScopeSpec &MapperIdScopeSpec,
14637                                      DeclarationNameInfo &MapperId,
14638                                      const OMPVarListLocTy &Locs,
14639                                      ArrayRef<Expr *> UnresolvedMappers) {
14640   MappableVarListInfo MVLI(VarList);
14641   checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, Locs.StartLoc,
14642                               MapperIdScopeSpec, MapperId, UnresolvedMappers);
14643   if (MVLI.ProcessedVarList.empty())
14644     return nullptr;
14645 
14646   return OMPToClause::Create(
14647       Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
14648       MVLI.VarComponents, MVLI.UDMapperList,
14649       MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
14650 }
14651 
14652 OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
14653                                        CXXScopeSpec &MapperIdScopeSpec,
14654                                        DeclarationNameInfo &MapperId,
14655                                        const OMPVarListLocTy &Locs,
14656                                        ArrayRef<Expr *> UnresolvedMappers) {
14657   MappableVarListInfo MVLI(VarList);
14658   checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, Locs.StartLoc,
14659                               MapperIdScopeSpec, MapperId, UnresolvedMappers);
14660   if (MVLI.ProcessedVarList.empty())
14661     return nullptr;
14662 
14663   return OMPFromClause::Create(
14664       Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
14665       MVLI.VarComponents, MVLI.UDMapperList,
14666       MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
14667 }
14668 
14669 OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
14670                                                const OMPVarListLocTy &Locs) {
14671   MappableVarListInfo MVLI(VarList);
14672   SmallVector<Expr *, 8> PrivateCopies;
14673   SmallVector<Expr *, 8> Inits;
14674 
14675   for (Expr *RefExpr : VarList) {
14676     assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
14677     SourceLocation ELoc;
14678     SourceRange ERange;
14679     Expr *SimpleRefExpr = RefExpr;
14680     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
14681     if (Res.second) {
14682       // It will be analyzed later.
14683       MVLI.ProcessedVarList.push_back(RefExpr);
14684       PrivateCopies.push_back(nullptr);
14685       Inits.push_back(nullptr);
14686     }
14687     ValueDecl *D = Res.first;
14688     if (!D)
14689       continue;
14690 
14691     QualType Type = D->getType();
14692     Type = Type.getNonReferenceType().getUnqualifiedType();
14693 
14694     auto *VD = dyn_cast<VarDecl>(D);
14695 
14696     // Item should be a pointer or reference to pointer.
14697     if (!Type->isPointerType()) {
14698       Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
14699           << 0 << RefExpr->getSourceRange();
14700       continue;
14701     }
14702 
14703     // Build the private variable and the expression that refers to it.
14704     auto VDPrivate =
14705         buildVarDecl(*this, ELoc, Type, D->getName(),
14706                      D->hasAttrs() ? &D->getAttrs() : nullptr,
14707                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
14708     if (VDPrivate->isInvalidDecl())
14709       continue;
14710 
14711     CurContext->addDecl(VDPrivate);
14712     DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
14713         *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
14714 
14715     // Add temporary variable to initialize the private copy of the pointer.
14716     VarDecl *VDInit =
14717         buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
14718     DeclRefExpr *VDInitRefExpr = buildDeclRefExpr(
14719         *this, VDInit, RefExpr->getType(), RefExpr->getExprLoc());
14720     AddInitializerToDecl(VDPrivate,
14721                          DefaultLvalueConversion(VDInitRefExpr).get(),
14722                          /*DirectInit=*/false);
14723 
14724     // If required, build a capture to implement the privatization initialized
14725     // with the current list item value.
14726     DeclRefExpr *Ref = nullptr;
14727     if (!VD)
14728       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
14729     MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
14730     PrivateCopies.push_back(VDPrivateRefExpr);
14731     Inits.push_back(VDInitRefExpr);
14732 
14733     // We need to add a data sharing attribute for this variable to make sure it
14734     // is correctly captured. A variable that shows up in a use_device_ptr has
14735     // similar properties of a first private variable.
14736     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
14737 
14738     // Create a mappable component for the list item. List items in this clause
14739     // only need a component.
14740     MVLI.VarBaseDeclarations.push_back(D);
14741     MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
14742     MVLI.VarComponents.back().push_back(
14743         OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
14744   }
14745 
14746   if (MVLI.ProcessedVarList.empty())
14747     return nullptr;
14748 
14749   return OMPUseDevicePtrClause::Create(
14750       Context, Locs, MVLI.ProcessedVarList, PrivateCopies, Inits,
14751       MVLI.VarBaseDeclarations, MVLI.VarComponents);
14752 }
14753 
14754 OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
14755                                               const OMPVarListLocTy &Locs) {
14756   MappableVarListInfo MVLI(VarList);
14757   for (Expr *RefExpr : VarList) {
14758     assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
14759     SourceLocation ELoc;
14760     SourceRange ERange;
14761     Expr *SimpleRefExpr = RefExpr;
14762     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
14763     if (Res.second) {
14764       // It will be analyzed later.
14765       MVLI.ProcessedVarList.push_back(RefExpr);
14766     }
14767     ValueDecl *D = Res.first;
14768     if (!D)
14769       continue;
14770 
14771     QualType Type = D->getType();
14772     // item should be a pointer or array or reference to pointer or array
14773     if (!Type.getNonReferenceType()->isPointerType() &&
14774         !Type.getNonReferenceType()->isArrayType()) {
14775       Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
14776           << 0 << RefExpr->getSourceRange();
14777       continue;
14778     }
14779 
14780     // Check if the declaration in the clause does not show up in any data
14781     // sharing attribute.
14782     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
14783     if (isOpenMPPrivate(DVar.CKind)) {
14784       Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
14785           << getOpenMPClauseName(DVar.CKind)
14786           << getOpenMPClauseName(OMPC_is_device_ptr)
14787           << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
14788       reportOriginalDsa(*this, DSAStack, D, DVar);
14789       continue;
14790     }
14791 
14792     const Expr *ConflictExpr;
14793     if (DSAStack->checkMappableExprComponentListsForDecl(
14794             D, /*CurrentRegionOnly=*/true,
14795             [&ConflictExpr](
14796                 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
14797                 OpenMPClauseKind) -> bool {
14798               ConflictExpr = R.front().getAssociatedExpression();
14799               return true;
14800             })) {
14801       Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
14802       Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
14803           << ConflictExpr->getSourceRange();
14804       continue;
14805     }
14806 
14807     // Store the components in the stack so that they can be used to check
14808     // against other clauses later on.
14809     OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
14810     DSAStack->addMappableExpressionComponents(
14811         D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
14812 
14813     // Record the expression we've just processed.
14814     MVLI.ProcessedVarList.push_back(SimpleRefExpr);
14815 
14816     // Create a mappable component for the list item. List items in this clause
14817     // only need a component. We use a null declaration to signal fields in
14818     // 'this'.
14819     assert((isa<DeclRefExpr>(SimpleRefExpr) ||
14820             isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
14821            "Unexpected device pointer expression!");
14822     MVLI.VarBaseDeclarations.push_back(
14823         isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
14824     MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
14825     MVLI.VarComponents.back().push_back(MC);
14826   }
14827 
14828   if (MVLI.ProcessedVarList.empty())
14829     return nullptr;
14830 
14831   return OMPIsDevicePtrClause::Create(Context, Locs, MVLI.ProcessedVarList,
14832                                       MVLI.VarBaseDeclarations,
14833                                       MVLI.VarComponents);
14834 }
14835 
14836 OMPClause *Sema::ActOnOpenMPAllocateClause(
14837     Expr *Allocator, ArrayRef<Expr *> VarList, SourceLocation StartLoc,
14838     SourceLocation ColonLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
14839   if (Allocator) {
14840     // OpenMP [2.11.4 allocate Clause, Description]
14841     // allocator is an expression of omp_allocator_handle_t type.
14842     if (!findOMPAllocatorHandleT(*this, Allocator->getExprLoc(), DSAStack))
14843       return nullptr;
14844 
14845     ExprResult AllocatorRes = DefaultLvalueConversion(Allocator);
14846     if (AllocatorRes.isInvalid())
14847       return nullptr;
14848     AllocatorRes = PerformImplicitConversion(AllocatorRes.get(),
14849                                              DSAStack->getOMPAllocatorHandleT(),
14850                                              Sema::AA_Initializing,
14851                                              /*AllowExplicit=*/true);
14852     if (AllocatorRes.isInvalid())
14853       return nullptr;
14854     Allocator = AllocatorRes.get();
14855   } else {
14856     // OpenMP 5.0, 2.11.4 allocate Clause, Restrictions.
14857     // allocate clauses that appear on a target construct or on constructs in a
14858     // target region must specify an allocator expression unless a requires
14859     // directive with the dynamic_allocators clause is present in the same
14860     // compilation unit.
14861     if (LangOpts.OpenMPIsDevice &&
14862         !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())
14863       targetDiag(StartLoc, diag::err_expected_allocator_expression);
14864   }
14865   // Analyze and build list of variables.
14866   SmallVector<Expr *, 8> Vars;
14867   for (Expr *RefExpr : VarList) {
14868     assert(RefExpr && "NULL expr in OpenMP private clause.");
14869     SourceLocation ELoc;
14870     SourceRange ERange;
14871     Expr *SimpleRefExpr = RefExpr;
14872     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
14873     if (Res.second) {
14874       // It will be analyzed later.
14875       Vars.push_back(RefExpr);
14876     }
14877     ValueDecl *D = Res.first;
14878     if (!D)
14879       continue;
14880 
14881     auto *VD = dyn_cast<VarDecl>(D);
14882     DeclRefExpr *Ref = nullptr;
14883     if (!VD && !CurContext->isDependentContext())
14884       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
14885     Vars.push_back((VD || CurContext->isDependentContext())
14886                        ? RefExpr->IgnoreParens()
14887                        : Ref);
14888   }
14889 
14890   if (Vars.empty())
14891     return nullptr;
14892 
14893   return OMPAllocateClause::Create(Context, StartLoc, LParenLoc, Allocator,
14894                                    ColonLoc, EndLoc, Vars);
14895 }
14896