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/OpenMPClause.h"
22 #include "clang/AST/StmtCXX.h"
23 #include "clang/AST/StmtOpenMP.h"
24 #include "clang/AST/StmtVisitor.h"
25 #include "clang/AST/TypeOrdering.h"
26 #include "clang/Basic/DiagnosticSema.h"
27 #include "clang/Basic/OpenMPKinds.h"
28 #include "clang/Basic/PartialDiagnostic.h"
29 #include "clang/Basic/TargetInfo.h"
30 #include "clang/Sema/Initialization.h"
31 #include "clang/Sema/Lookup.h"
32 #include "clang/Sema/Scope.h"
33 #include "clang/Sema/ScopeInfo.h"
34 #include "clang/Sema/SemaInternal.h"
35 #include "llvm/ADT/IndexedMap.h"
36 #include "llvm/ADT/PointerEmbeddedInt.h"
37 #include "llvm/ADT/STLExtras.h"
38 #include "llvm/ADT/StringExtras.h"
39 #include "llvm/Frontend/OpenMP/OMPConstants.h"
40 #include <set>
41 
42 using namespace clang;
43 using namespace llvm::omp;
44 
45 //===----------------------------------------------------------------------===//
46 // Stack of data-sharing attributes for variables
47 //===----------------------------------------------------------------------===//
48 
49 static const Expr *checkMapClauseExpressionBase(
50     Sema &SemaRef, Expr *E,
51     OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
52     OpenMPClauseKind CKind, OpenMPDirectiveKind DKind, bool NoDiagnose);
53 
54 namespace {
55 /// Default data sharing attributes, which can be applied to directive.
56 enum DefaultDataSharingAttributes {
57   DSA_unspecified = 0,       /// Data sharing attribute not specified.
58   DSA_none = 1 << 0,         /// Default data sharing attribute 'none'.
59   DSA_shared = 1 << 1,       /// Default data sharing attribute 'shared'.
60   DSA_firstprivate = 1 << 2, /// Default data sharing attribute 'firstprivate'.
61 };
62 
63 /// Stack for tracking declarations used in OpenMP directives and
64 /// clauses and their data-sharing attributes.
65 class DSAStackTy {
66 public:
67   struct DSAVarData {
68     OpenMPDirectiveKind DKind = OMPD_unknown;
69     OpenMPClauseKind CKind = OMPC_unknown;
70     unsigned Modifier = 0;
71     const Expr *RefExpr = nullptr;
72     DeclRefExpr *PrivateCopy = nullptr;
73     SourceLocation ImplicitDSALoc;
74     bool AppliedToPointee = false;
75     DSAVarData() = default;
76     DSAVarData(OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
77                const Expr *RefExpr, DeclRefExpr *PrivateCopy,
78                SourceLocation ImplicitDSALoc, unsigned Modifier,
79                bool AppliedToPointee)
80         : DKind(DKind), CKind(CKind), Modifier(Modifier), RefExpr(RefExpr),
81           PrivateCopy(PrivateCopy), ImplicitDSALoc(ImplicitDSALoc),
82           AppliedToPointee(AppliedToPointee) {}
83   };
84   using OperatorOffsetTy =
85       llvm::SmallVector<std::pair<Expr *, OverloadedOperatorKind>, 4>;
86   using DoacrossDependMapTy =
87       llvm::DenseMap<OMPDependClause *, OperatorOffsetTy>;
88   /// Kind of the declaration used in the uses_allocators clauses.
89   enum class UsesAllocatorsDeclKind {
90     /// Predefined allocator
91     PredefinedAllocator,
92     /// User-defined allocator
93     UserDefinedAllocator,
94     /// The declaration that represent allocator trait
95     AllocatorTrait,
96   };
97 
98 private:
99   struct DSAInfo {
100     OpenMPClauseKind Attributes = OMPC_unknown;
101     unsigned Modifier = 0;
102     /// Pointer to a reference expression and a flag which shows that the
103     /// variable is marked as lastprivate(true) or not (false).
104     llvm::PointerIntPair<const Expr *, 1, bool> RefExpr;
105     DeclRefExpr *PrivateCopy = nullptr;
106     /// true if the attribute is applied to the pointee, not the variable
107     /// itself.
108     bool AppliedToPointee = false;
109   };
110   using DeclSAMapTy = llvm::SmallDenseMap<const ValueDecl *, DSAInfo, 8>;
111   using UsedRefMapTy = llvm::SmallDenseMap<const ValueDecl *, const Expr *, 8>;
112   using LCDeclInfo = std::pair<unsigned, VarDecl *>;
113   using LoopControlVariablesMapTy =
114       llvm::SmallDenseMap<const ValueDecl *, LCDeclInfo, 8>;
115   /// Struct that associates a component with the clause kind where they are
116   /// found.
117   struct MappedExprComponentTy {
118     OMPClauseMappableExprCommon::MappableExprComponentLists Components;
119     OpenMPClauseKind Kind = OMPC_unknown;
120   };
121   using MappedExprComponentsTy =
122       llvm::DenseMap<const ValueDecl *, MappedExprComponentTy>;
123   using CriticalsWithHintsTy =
124       llvm::StringMap<std::pair<const OMPCriticalDirective *, llvm::APSInt>>;
125   struct ReductionData {
126     using BOKPtrType = llvm::PointerEmbeddedInt<BinaryOperatorKind, 16>;
127     SourceRange ReductionRange;
128     llvm::PointerUnion<const Expr *, BOKPtrType> ReductionOp;
129     ReductionData() = default;
130     void set(BinaryOperatorKind BO, SourceRange RR) {
131       ReductionRange = RR;
132       ReductionOp = BO;
133     }
134     void set(const Expr *RefExpr, SourceRange RR) {
135       ReductionRange = RR;
136       ReductionOp = RefExpr;
137     }
138   };
139   using DeclReductionMapTy =
140       llvm::SmallDenseMap<const ValueDecl *, ReductionData, 4>;
141   struct DefaultmapInfo {
142     OpenMPDefaultmapClauseModifier ImplicitBehavior =
143         OMPC_DEFAULTMAP_MODIFIER_unknown;
144     SourceLocation SLoc;
145     DefaultmapInfo() = default;
146     DefaultmapInfo(OpenMPDefaultmapClauseModifier M, SourceLocation Loc)
147         : ImplicitBehavior(M), SLoc(Loc) {}
148   };
149 
150   struct SharingMapTy {
151     DeclSAMapTy SharingMap;
152     DeclReductionMapTy ReductionMap;
153     UsedRefMapTy AlignedMap;
154     UsedRefMapTy NontemporalMap;
155     MappedExprComponentsTy MappedExprComponents;
156     LoopControlVariablesMapTy LCVMap;
157     DefaultDataSharingAttributes DefaultAttr = DSA_unspecified;
158     SourceLocation DefaultAttrLoc;
159     DefaultmapInfo DefaultmapMap[OMPC_DEFAULTMAP_unknown];
160     OpenMPDirectiveKind Directive = OMPD_unknown;
161     DeclarationNameInfo DirectiveName;
162     Scope *CurScope = nullptr;
163     DeclContext *Context = nullptr;
164     SourceLocation ConstructLoc;
165     /// Set of 'depend' clauses with 'sink|source' dependence kind. Required to
166     /// get the data (loop counters etc.) about enclosing loop-based construct.
167     /// This data is required during codegen.
168     DoacrossDependMapTy DoacrossDepends;
169     /// First argument (Expr *) contains optional argument of the
170     /// 'ordered' clause, the second one is true if the regions has 'ordered'
171     /// clause, false otherwise.
172     llvm::Optional<std::pair<const Expr *, OMPOrderedClause *>> OrderedRegion;
173     unsigned AssociatedLoops = 1;
174     bool HasMutipleLoops = false;
175     const Decl *PossiblyLoopCounter = nullptr;
176     bool NowaitRegion = false;
177     bool CancelRegion = false;
178     bool LoopStart = false;
179     bool BodyComplete = false;
180     SourceLocation PrevScanLocation;
181     SourceLocation PrevOrderedLocation;
182     SourceLocation InnerTeamsRegionLoc;
183     /// Reference to the taskgroup task_reduction reference expression.
184     Expr *TaskgroupReductionRef = nullptr;
185     llvm::DenseSet<QualType> MappedClassesQualTypes;
186     SmallVector<Expr *, 4> InnerUsedAllocators;
187     llvm::DenseSet<CanonicalDeclPtr<Decl>> ImplicitTaskFirstprivates;
188     /// List of globals marked as declare target link in this target region
189     /// (isOpenMPTargetExecutionDirective(Directive) == true).
190     llvm::SmallVector<DeclRefExpr *, 4> DeclareTargetLinkVarDecls;
191     /// List of decls used in inclusive/exclusive clauses of the scan directive.
192     llvm::DenseSet<CanonicalDeclPtr<Decl>> UsedInScanDirective;
193     llvm::DenseMap<CanonicalDeclPtr<const Decl>, UsesAllocatorsDeclKind>
194         UsesAllocatorsDecls;
195     Expr *DeclareMapperVar = nullptr;
196     SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
197                  Scope *CurScope, SourceLocation Loc)
198         : Directive(DKind), DirectiveName(Name), CurScope(CurScope),
199           ConstructLoc(Loc) {}
200     SharingMapTy() = default;
201   };
202 
203   using StackTy = SmallVector<SharingMapTy, 4>;
204 
205   /// Stack of used declaration and their data-sharing attributes.
206   DeclSAMapTy Threadprivates;
207   const FunctionScopeInfo *CurrentNonCapturingFunctionScope = nullptr;
208   SmallVector<std::pair<StackTy, const FunctionScopeInfo *>, 4> Stack;
209   /// true, if check for DSA must be from parent directive, false, if
210   /// from current directive.
211   OpenMPClauseKind ClauseKindMode = OMPC_unknown;
212   Sema &SemaRef;
213   bool ForceCapturing = false;
214   /// true if all the variables in the target executable directives must be
215   /// captured by reference.
216   bool ForceCaptureByReferenceInTargetExecutable = false;
217   CriticalsWithHintsTy Criticals;
218   unsigned IgnoredStackElements = 0;
219 
220   /// Iterators over the stack iterate in order from innermost to outermost
221   /// directive.
222   using const_iterator = StackTy::const_reverse_iterator;
223   const_iterator begin() const {
224     return Stack.empty() ? const_iterator()
225                          : Stack.back().first.rbegin() + IgnoredStackElements;
226   }
227   const_iterator end() const {
228     return Stack.empty() ? const_iterator() : Stack.back().first.rend();
229   }
230   using iterator = StackTy::reverse_iterator;
231   iterator begin() {
232     return Stack.empty() ? iterator()
233                          : Stack.back().first.rbegin() + IgnoredStackElements;
234   }
235   iterator end() {
236     return Stack.empty() ? iterator() : Stack.back().first.rend();
237   }
238 
239   // Convenience operations to get at the elements of the stack.
240 
241   bool isStackEmpty() const {
242     return Stack.empty() ||
243            Stack.back().second != CurrentNonCapturingFunctionScope ||
244            Stack.back().first.size() <= IgnoredStackElements;
245   }
246   size_t getStackSize() const {
247     return isStackEmpty() ? 0
248                           : Stack.back().first.size() - IgnoredStackElements;
249   }
250 
251   SharingMapTy *getTopOfStackOrNull() {
252     size_t Size = getStackSize();
253     if (Size == 0)
254       return nullptr;
255     return &Stack.back().first[Size - 1];
256   }
257   const SharingMapTy *getTopOfStackOrNull() const {
258     return const_cast<DSAStackTy &>(*this).getTopOfStackOrNull();
259   }
260   SharingMapTy &getTopOfStack() {
261     assert(!isStackEmpty() && "no current directive");
262     return *getTopOfStackOrNull();
263   }
264   const SharingMapTy &getTopOfStack() const {
265     return const_cast<DSAStackTy &>(*this).getTopOfStack();
266   }
267 
268   SharingMapTy *getSecondOnStackOrNull() {
269     size_t Size = getStackSize();
270     if (Size <= 1)
271       return nullptr;
272     return &Stack.back().first[Size - 2];
273   }
274   const SharingMapTy *getSecondOnStackOrNull() const {
275     return const_cast<DSAStackTy &>(*this).getSecondOnStackOrNull();
276   }
277 
278   /// Get the stack element at a certain level (previously returned by
279   /// \c getNestingLevel).
280   ///
281   /// Note that nesting levels count from outermost to innermost, and this is
282   /// the reverse of our iteration order where new inner levels are pushed at
283   /// the front of the stack.
284   SharingMapTy &getStackElemAtLevel(unsigned Level) {
285     assert(Level < getStackSize() && "no such stack element");
286     return Stack.back().first[Level];
287   }
288   const SharingMapTy &getStackElemAtLevel(unsigned Level) const {
289     return const_cast<DSAStackTy &>(*this).getStackElemAtLevel(Level);
290   }
291 
292   DSAVarData getDSA(const_iterator &Iter, ValueDecl *D) const;
293 
294   /// Checks if the variable is a local for OpenMP region.
295   bool isOpenMPLocal(VarDecl *D, const_iterator Iter) const;
296 
297   /// Vector of previously declared requires directives
298   SmallVector<const OMPRequiresDecl *, 2> RequiresDecls;
299   /// omp_allocator_handle_t type.
300   QualType OMPAllocatorHandleT;
301   /// omp_depend_t type.
302   QualType OMPDependT;
303   /// omp_event_handle_t type.
304   QualType OMPEventHandleT;
305   /// omp_alloctrait_t type.
306   QualType OMPAlloctraitT;
307   /// Expression for the predefined allocators.
308   Expr *OMPPredefinedAllocators[OMPAllocateDeclAttr::OMPUserDefinedMemAlloc] = {
309       nullptr};
310   /// Vector of previously encountered target directives
311   SmallVector<SourceLocation, 2> TargetLocations;
312   SourceLocation AtomicLocation;
313   /// Vector of declare variant construct traits.
314   SmallVector<llvm::omp::TraitProperty, 8> ConstructTraits;
315 
316 public:
317   explicit DSAStackTy(Sema &S) : SemaRef(S) {}
318 
319   /// Sets omp_allocator_handle_t type.
320   void setOMPAllocatorHandleT(QualType Ty) { OMPAllocatorHandleT = Ty; }
321   /// Gets omp_allocator_handle_t type.
322   QualType getOMPAllocatorHandleT() const { return OMPAllocatorHandleT; }
323   /// Sets omp_alloctrait_t type.
324   void setOMPAlloctraitT(QualType Ty) { OMPAlloctraitT = Ty; }
325   /// Gets omp_alloctrait_t type.
326   QualType getOMPAlloctraitT() const { return OMPAlloctraitT; }
327   /// Sets the given default allocator.
328   void setAllocator(OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind,
329                     Expr *Allocator) {
330     OMPPredefinedAllocators[AllocatorKind] = Allocator;
331   }
332   /// Returns the specified default allocator.
333   Expr *getAllocator(OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind) const {
334     return OMPPredefinedAllocators[AllocatorKind];
335   }
336   /// Sets omp_depend_t type.
337   void setOMPDependT(QualType Ty) { OMPDependT = Ty; }
338   /// Gets omp_depend_t type.
339   QualType getOMPDependT() const { return OMPDependT; }
340 
341   /// Sets omp_event_handle_t type.
342   void setOMPEventHandleT(QualType Ty) { OMPEventHandleT = Ty; }
343   /// Gets omp_event_handle_t type.
344   QualType getOMPEventHandleT() const { return OMPEventHandleT; }
345 
346   bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
347   OpenMPClauseKind getClauseParsingMode() const {
348     assert(isClauseParsingMode() && "Must be in clause parsing mode.");
349     return ClauseKindMode;
350   }
351   void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
352 
353   bool isBodyComplete() const {
354     const SharingMapTy *Top = getTopOfStackOrNull();
355     return Top && Top->BodyComplete;
356   }
357   void setBodyComplete() { getTopOfStack().BodyComplete = true; }
358 
359   bool isForceVarCapturing() const { return ForceCapturing; }
360   void setForceVarCapturing(bool V) { ForceCapturing = V; }
361 
362   void setForceCaptureByReferenceInTargetExecutable(bool V) {
363     ForceCaptureByReferenceInTargetExecutable = V;
364   }
365   bool isForceCaptureByReferenceInTargetExecutable() const {
366     return ForceCaptureByReferenceInTargetExecutable;
367   }
368 
369   void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
370             Scope *CurScope, SourceLocation Loc) {
371     assert(!IgnoredStackElements &&
372            "cannot change stack while ignoring elements");
373     if (Stack.empty() ||
374         Stack.back().second != CurrentNonCapturingFunctionScope)
375       Stack.emplace_back(StackTy(), CurrentNonCapturingFunctionScope);
376     Stack.back().first.emplace_back(DKind, DirName, CurScope, Loc);
377     Stack.back().first.back().DefaultAttrLoc = Loc;
378   }
379 
380   void pop() {
381     assert(!IgnoredStackElements &&
382            "cannot change stack while ignoring elements");
383     assert(!Stack.back().first.empty() &&
384            "Data-sharing attributes stack is empty!");
385     Stack.back().first.pop_back();
386   }
387 
388   /// RAII object to temporarily leave the scope of a directive when we want to
389   /// logically operate in its parent.
390   class ParentDirectiveScope {
391     DSAStackTy &Self;
392     bool Active;
393 
394   public:
395     ParentDirectiveScope(DSAStackTy &Self, bool Activate)
396         : Self(Self), Active(false) {
397       if (Activate)
398         enable();
399     }
400     ~ParentDirectiveScope() { disable(); }
401     void disable() {
402       if (Active) {
403         --Self.IgnoredStackElements;
404         Active = false;
405       }
406     }
407     void enable() {
408       if (!Active) {
409         ++Self.IgnoredStackElements;
410         Active = true;
411       }
412     }
413   };
414 
415   /// Marks that we're started loop parsing.
416   void loopInit() {
417     assert(isOpenMPLoopDirective(getCurrentDirective()) &&
418            "Expected loop-based directive.");
419     getTopOfStack().LoopStart = true;
420   }
421   /// Start capturing of the variables in the loop context.
422   void loopStart() {
423     assert(isOpenMPLoopDirective(getCurrentDirective()) &&
424            "Expected loop-based directive.");
425     getTopOfStack().LoopStart = false;
426   }
427   /// true, if variables are captured, false otherwise.
428   bool isLoopStarted() const {
429     assert(isOpenMPLoopDirective(getCurrentDirective()) &&
430            "Expected loop-based directive.");
431     return !getTopOfStack().LoopStart;
432   }
433   /// Marks (or clears) declaration as possibly loop counter.
434   void resetPossibleLoopCounter(const Decl *D = nullptr) {
435     getTopOfStack().PossiblyLoopCounter = D ? D->getCanonicalDecl() : D;
436   }
437   /// Gets the possible loop counter decl.
438   const Decl *getPossiblyLoopCunter() const {
439     return getTopOfStack().PossiblyLoopCounter;
440   }
441   /// Start new OpenMP region stack in new non-capturing function.
442   void pushFunction() {
443     assert(!IgnoredStackElements &&
444            "cannot change stack while ignoring elements");
445     const FunctionScopeInfo *CurFnScope = SemaRef.getCurFunction();
446     assert(!isa<CapturingScopeInfo>(CurFnScope));
447     CurrentNonCapturingFunctionScope = CurFnScope;
448   }
449   /// Pop region stack for non-capturing function.
450   void popFunction(const FunctionScopeInfo *OldFSI) {
451     assert(!IgnoredStackElements &&
452            "cannot change stack while ignoring elements");
453     if (!Stack.empty() && Stack.back().second == OldFSI) {
454       assert(Stack.back().first.empty());
455       Stack.pop_back();
456     }
457     CurrentNonCapturingFunctionScope = nullptr;
458     for (const FunctionScopeInfo *FSI : llvm::reverse(SemaRef.FunctionScopes)) {
459       if (!isa<CapturingScopeInfo>(FSI)) {
460         CurrentNonCapturingFunctionScope = FSI;
461         break;
462       }
463     }
464   }
465 
466   void addCriticalWithHint(const OMPCriticalDirective *D, llvm::APSInt Hint) {
467     Criticals.try_emplace(D->getDirectiveName().getAsString(), D, Hint);
468   }
469   const std::pair<const OMPCriticalDirective *, llvm::APSInt>
470   getCriticalWithHint(const DeclarationNameInfo &Name) const {
471     auto I = Criticals.find(Name.getAsString());
472     if (I != Criticals.end())
473       return I->second;
474     return std::make_pair(nullptr, llvm::APSInt());
475   }
476   /// If 'aligned' declaration for given variable \a D was not seen yet,
477   /// add it and return NULL; otherwise return previous occurrence's expression
478   /// for diagnostics.
479   const Expr *addUniqueAligned(const ValueDecl *D, const Expr *NewDE);
480   /// If 'nontemporal' declaration for given variable \a D was not seen yet,
481   /// add it and return NULL; otherwise return previous occurrence's expression
482   /// for diagnostics.
483   const Expr *addUniqueNontemporal(const ValueDecl *D, const Expr *NewDE);
484 
485   /// Register specified variable as loop control variable.
486   void addLoopControlVariable(const ValueDecl *D, VarDecl *Capture);
487   /// Check if the specified variable is a loop control variable for
488   /// current region.
489   /// \return The index of the loop control variable in the list of associated
490   /// for-loops (from outer to inner).
491   const LCDeclInfo isLoopControlVariable(const ValueDecl *D) const;
492   /// Check if the specified variable is a loop control variable for
493   /// parent region.
494   /// \return The index of the loop control variable in the list of associated
495   /// for-loops (from outer to inner).
496   const LCDeclInfo isParentLoopControlVariable(const ValueDecl *D) const;
497   /// Check if the specified variable is a loop control variable for
498   /// current region.
499   /// \return The index of the loop control variable in the list of associated
500   /// for-loops (from outer to inner).
501   const LCDeclInfo isLoopControlVariable(const ValueDecl *D,
502                                          unsigned Level) const;
503   /// Get the loop control variable for the I-th loop (or nullptr) in
504   /// parent directive.
505   const ValueDecl *getParentLoopControlVariable(unsigned I) const;
506 
507   /// Marks the specified decl \p D as used in scan directive.
508   void markDeclAsUsedInScanDirective(ValueDecl *D) {
509     if (SharingMapTy *Stack = getSecondOnStackOrNull())
510       Stack->UsedInScanDirective.insert(D);
511   }
512 
513   /// Checks if the specified declaration was used in the inner scan directive.
514   bool isUsedInScanDirective(ValueDecl *D) const {
515     if (const SharingMapTy *Stack = getTopOfStackOrNull())
516       return Stack->UsedInScanDirective.contains(D);
517     return false;
518   }
519 
520   /// Adds explicit data sharing attribute to the specified declaration.
521   void addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
522               DeclRefExpr *PrivateCopy = nullptr, unsigned Modifier = 0,
523               bool AppliedToPointee = false);
524 
525   /// Adds additional information for the reduction items with the reduction id
526   /// represented as an operator.
527   void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
528                                  BinaryOperatorKind BOK);
529   /// Adds additional information for the reduction items with the reduction id
530   /// represented as reduction identifier.
531   void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
532                                  const Expr *ReductionRef);
533   /// Returns the location and reduction operation from the innermost parent
534   /// region for the given \p D.
535   const DSAVarData
536   getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
537                                    BinaryOperatorKind &BOK,
538                                    Expr *&TaskgroupDescriptor) const;
539   /// Returns the location and reduction operation from the innermost parent
540   /// region for the given \p D.
541   const DSAVarData
542   getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
543                                    const Expr *&ReductionRef,
544                                    Expr *&TaskgroupDescriptor) const;
545   /// Return reduction reference expression for the current taskgroup or
546   /// parallel/worksharing directives with task reductions.
547   Expr *getTaskgroupReductionRef() const {
548     assert((getTopOfStack().Directive == OMPD_taskgroup ||
549             ((isOpenMPParallelDirective(getTopOfStack().Directive) ||
550               isOpenMPWorksharingDirective(getTopOfStack().Directive)) &&
551              !isOpenMPSimdDirective(getTopOfStack().Directive))) &&
552            "taskgroup reference expression requested for non taskgroup or "
553            "parallel/worksharing directive.");
554     return getTopOfStack().TaskgroupReductionRef;
555   }
556   /// Checks if the given \p VD declaration is actually a taskgroup reduction
557   /// descriptor variable at the \p Level of OpenMP regions.
558   bool isTaskgroupReductionRef(const ValueDecl *VD, unsigned Level) const {
559     return getStackElemAtLevel(Level).TaskgroupReductionRef &&
560            cast<DeclRefExpr>(getStackElemAtLevel(Level).TaskgroupReductionRef)
561                    ->getDecl() == VD;
562   }
563 
564   /// Returns data sharing attributes from top of the stack for the
565   /// specified declaration.
566   const DSAVarData getTopDSA(ValueDecl *D, bool FromParent);
567   /// Returns data-sharing attributes for the specified declaration.
568   const DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent) const;
569   /// Returns data-sharing attributes for the specified declaration.
570   const DSAVarData getImplicitDSA(ValueDecl *D, unsigned Level) const;
571   /// Checks if the specified variables has data-sharing attributes which
572   /// match specified \a CPred predicate in any directive which matches \a DPred
573   /// predicate.
574   const DSAVarData
575   hasDSA(ValueDecl *D,
576          const llvm::function_ref<bool(OpenMPClauseKind, bool)> CPred,
577          const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
578          bool FromParent) const;
579   /// Checks if the specified variables has data-sharing attributes which
580   /// match specified \a CPred predicate in any innermost directive which
581   /// matches \a DPred predicate.
582   const DSAVarData
583   hasInnermostDSA(ValueDecl *D,
584                   const llvm::function_ref<bool(OpenMPClauseKind, bool)> CPred,
585                   const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
586                   bool FromParent) const;
587   /// Checks if the specified variables has explicit data-sharing
588   /// attributes which match specified \a CPred predicate at the specified
589   /// OpenMP region.
590   bool
591   hasExplicitDSA(const ValueDecl *D,
592                  const llvm::function_ref<bool(OpenMPClauseKind, bool)> CPred,
593                  unsigned Level, bool NotLastprivate = false) const;
594 
595   /// Returns true if the directive at level \Level matches in the
596   /// specified \a DPred predicate.
597   bool hasExplicitDirective(
598       const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
599       unsigned Level) const;
600 
601   /// Finds a directive which matches specified \a DPred predicate.
602   bool hasDirective(
603       const llvm::function_ref<bool(
604           OpenMPDirectiveKind, const DeclarationNameInfo &, SourceLocation)>
605           DPred,
606       bool FromParent) const;
607 
608   /// Returns currently analyzed directive.
609   OpenMPDirectiveKind getCurrentDirective() const {
610     const SharingMapTy *Top = getTopOfStackOrNull();
611     return Top ? Top->Directive : OMPD_unknown;
612   }
613   /// Returns directive kind at specified level.
614   OpenMPDirectiveKind getDirective(unsigned Level) const {
615     assert(!isStackEmpty() && "No directive at specified level.");
616     return getStackElemAtLevel(Level).Directive;
617   }
618   /// Returns the capture region at the specified level.
619   OpenMPDirectiveKind getCaptureRegion(unsigned Level,
620                                        unsigned OpenMPCaptureLevel) const {
621     SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
622     getOpenMPCaptureRegions(CaptureRegions, getDirective(Level));
623     return CaptureRegions[OpenMPCaptureLevel];
624   }
625   /// Returns parent directive.
626   OpenMPDirectiveKind getParentDirective() const {
627     const SharingMapTy *Parent = getSecondOnStackOrNull();
628     return Parent ? Parent->Directive : OMPD_unknown;
629   }
630 
631   /// Add requires decl to internal vector
632   void addRequiresDecl(OMPRequiresDecl *RD) { RequiresDecls.push_back(RD); }
633 
634   /// Checks if the defined 'requires' directive has specified type of clause.
635   template <typename ClauseType> bool hasRequiresDeclWithClause() const {
636     return llvm::any_of(RequiresDecls, [](const OMPRequiresDecl *D) {
637       return llvm::any_of(D->clauselists(), [](const OMPClause *C) {
638         return isa<ClauseType>(C);
639       });
640     });
641   }
642 
643   /// Checks for a duplicate clause amongst previously declared requires
644   /// directives
645   bool hasDuplicateRequiresClause(ArrayRef<OMPClause *> ClauseList) const {
646     bool IsDuplicate = false;
647     for (OMPClause *CNew : ClauseList) {
648       for (const OMPRequiresDecl *D : RequiresDecls) {
649         for (const OMPClause *CPrev : D->clauselists()) {
650           if (CNew->getClauseKind() == CPrev->getClauseKind()) {
651             SemaRef.Diag(CNew->getBeginLoc(),
652                          diag::err_omp_requires_clause_redeclaration)
653                 << getOpenMPClauseName(CNew->getClauseKind());
654             SemaRef.Diag(CPrev->getBeginLoc(),
655                          diag::note_omp_requires_previous_clause)
656                 << getOpenMPClauseName(CPrev->getClauseKind());
657             IsDuplicate = true;
658           }
659         }
660       }
661     }
662     return IsDuplicate;
663   }
664 
665   /// Add location of previously encountered target to internal vector
666   void addTargetDirLocation(SourceLocation LocStart) {
667     TargetLocations.push_back(LocStart);
668   }
669 
670   /// Add location for the first encountered atomicc directive.
671   void addAtomicDirectiveLoc(SourceLocation Loc) {
672     if (AtomicLocation.isInvalid())
673       AtomicLocation = Loc;
674   }
675 
676   /// Returns the location of the first encountered atomic directive in the
677   /// module.
678   SourceLocation getAtomicDirectiveLoc() const { return AtomicLocation; }
679 
680   // Return previously encountered target region locations.
681   ArrayRef<SourceLocation> getEncounteredTargetLocs() const {
682     return TargetLocations;
683   }
684 
685   /// Set default data sharing attribute to none.
686   void setDefaultDSANone(SourceLocation Loc) {
687     getTopOfStack().DefaultAttr = DSA_none;
688     getTopOfStack().DefaultAttrLoc = Loc;
689   }
690   /// Set default data sharing attribute to shared.
691   void setDefaultDSAShared(SourceLocation Loc) {
692     getTopOfStack().DefaultAttr = DSA_shared;
693     getTopOfStack().DefaultAttrLoc = Loc;
694   }
695   /// Set default data sharing attribute to firstprivate.
696   void setDefaultDSAFirstPrivate(SourceLocation Loc) {
697     getTopOfStack().DefaultAttr = DSA_firstprivate;
698     getTopOfStack().DefaultAttrLoc = Loc;
699   }
700   /// Set default data mapping attribute to Modifier:Kind
701   void setDefaultDMAAttr(OpenMPDefaultmapClauseModifier M,
702                          OpenMPDefaultmapClauseKind Kind, SourceLocation Loc) {
703     DefaultmapInfo &DMI = getTopOfStack().DefaultmapMap[Kind];
704     DMI.ImplicitBehavior = M;
705     DMI.SLoc = Loc;
706   }
707   /// Check whether the implicit-behavior has been set in defaultmap
708   bool checkDefaultmapCategory(OpenMPDefaultmapClauseKind VariableCategory) {
709     if (VariableCategory == OMPC_DEFAULTMAP_unknown)
710       return getTopOfStack()
711                      .DefaultmapMap[OMPC_DEFAULTMAP_aggregate]
712                      .ImplicitBehavior != OMPC_DEFAULTMAP_MODIFIER_unknown ||
713              getTopOfStack()
714                      .DefaultmapMap[OMPC_DEFAULTMAP_scalar]
715                      .ImplicitBehavior != OMPC_DEFAULTMAP_MODIFIER_unknown ||
716              getTopOfStack()
717                      .DefaultmapMap[OMPC_DEFAULTMAP_pointer]
718                      .ImplicitBehavior != OMPC_DEFAULTMAP_MODIFIER_unknown;
719     return getTopOfStack().DefaultmapMap[VariableCategory].ImplicitBehavior !=
720            OMPC_DEFAULTMAP_MODIFIER_unknown;
721   }
722 
723   ArrayRef<llvm::omp::TraitProperty> getConstructTraits() {
724     return ConstructTraits;
725   }
726   void handleConstructTrait(ArrayRef<llvm::omp::TraitProperty> Traits,
727                             bool ScopeEntry) {
728     if (ScopeEntry)
729       ConstructTraits.append(Traits.begin(), Traits.end());
730     else
731       for (llvm::omp::TraitProperty Trait : llvm::reverse(Traits)) {
732         llvm::omp::TraitProperty Top = ConstructTraits.pop_back_val();
733         assert(Top == Trait && "Something left a trait on the stack!");
734         (void)Trait;
735         (void)Top;
736       }
737   }
738 
739   DefaultDataSharingAttributes getDefaultDSA(unsigned Level) const {
740     return getStackSize() <= Level ? DSA_unspecified
741                                    : getStackElemAtLevel(Level).DefaultAttr;
742   }
743   DefaultDataSharingAttributes getDefaultDSA() const {
744     return isStackEmpty() ? DSA_unspecified : getTopOfStack().DefaultAttr;
745   }
746   SourceLocation getDefaultDSALocation() const {
747     return isStackEmpty() ? SourceLocation() : getTopOfStack().DefaultAttrLoc;
748   }
749   OpenMPDefaultmapClauseModifier
750   getDefaultmapModifier(OpenMPDefaultmapClauseKind Kind) const {
751     return isStackEmpty()
752                ? OMPC_DEFAULTMAP_MODIFIER_unknown
753                : getTopOfStack().DefaultmapMap[Kind].ImplicitBehavior;
754   }
755   OpenMPDefaultmapClauseModifier
756   getDefaultmapModifierAtLevel(unsigned Level,
757                                OpenMPDefaultmapClauseKind Kind) const {
758     return getStackElemAtLevel(Level).DefaultmapMap[Kind].ImplicitBehavior;
759   }
760   bool isDefaultmapCapturedByRef(unsigned Level,
761                                  OpenMPDefaultmapClauseKind Kind) const {
762     OpenMPDefaultmapClauseModifier M =
763         getDefaultmapModifierAtLevel(Level, Kind);
764     if (Kind == OMPC_DEFAULTMAP_scalar || Kind == OMPC_DEFAULTMAP_pointer) {
765       return (M == OMPC_DEFAULTMAP_MODIFIER_alloc) ||
766              (M == OMPC_DEFAULTMAP_MODIFIER_to) ||
767              (M == OMPC_DEFAULTMAP_MODIFIER_from) ||
768              (M == OMPC_DEFAULTMAP_MODIFIER_tofrom);
769     }
770     return true;
771   }
772   static bool mustBeFirstprivateBase(OpenMPDefaultmapClauseModifier M,
773                                      OpenMPDefaultmapClauseKind Kind) {
774     switch (Kind) {
775     case OMPC_DEFAULTMAP_scalar:
776     case OMPC_DEFAULTMAP_pointer:
777       return (M == OMPC_DEFAULTMAP_MODIFIER_unknown) ||
778              (M == OMPC_DEFAULTMAP_MODIFIER_firstprivate) ||
779              (M == OMPC_DEFAULTMAP_MODIFIER_default);
780     case OMPC_DEFAULTMAP_aggregate:
781       return M == OMPC_DEFAULTMAP_MODIFIER_firstprivate;
782     default:
783       break;
784     }
785     llvm_unreachable("Unexpected OpenMPDefaultmapClauseKind enum");
786   }
787   bool mustBeFirstprivateAtLevel(unsigned Level,
788                                  OpenMPDefaultmapClauseKind Kind) const {
789     OpenMPDefaultmapClauseModifier M =
790         getDefaultmapModifierAtLevel(Level, Kind);
791     return mustBeFirstprivateBase(M, Kind);
792   }
793   bool mustBeFirstprivate(OpenMPDefaultmapClauseKind Kind) const {
794     OpenMPDefaultmapClauseModifier M = getDefaultmapModifier(Kind);
795     return mustBeFirstprivateBase(M, Kind);
796   }
797 
798   /// Checks if the specified variable is a threadprivate.
799   bool isThreadPrivate(VarDecl *D) {
800     const DSAVarData DVar = getTopDSA(D, false);
801     return isOpenMPThreadPrivate(DVar.CKind);
802   }
803 
804   /// Marks current region as ordered (it has an 'ordered' clause).
805   void setOrderedRegion(bool IsOrdered, const Expr *Param,
806                         OMPOrderedClause *Clause) {
807     if (IsOrdered)
808       getTopOfStack().OrderedRegion.emplace(Param, Clause);
809     else
810       getTopOfStack().OrderedRegion.reset();
811   }
812   /// Returns true, if region is ordered (has associated 'ordered' clause),
813   /// false - otherwise.
814   bool isOrderedRegion() const {
815     if (const SharingMapTy *Top = getTopOfStackOrNull())
816       return Top->OrderedRegion.hasValue();
817     return false;
818   }
819   /// Returns optional parameter for the ordered region.
820   std::pair<const Expr *, OMPOrderedClause *> getOrderedRegionParam() const {
821     if (const SharingMapTy *Top = getTopOfStackOrNull())
822       if (Top->OrderedRegion.hasValue())
823         return Top->OrderedRegion.getValue();
824     return std::make_pair(nullptr, nullptr);
825   }
826   /// Returns true, if parent region is ordered (has associated
827   /// 'ordered' clause), false - otherwise.
828   bool isParentOrderedRegion() const {
829     if (const SharingMapTy *Parent = getSecondOnStackOrNull())
830       return Parent->OrderedRegion.hasValue();
831     return false;
832   }
833   /// Returns optional parameter for the ordered region.
834   std::pair<const Expr *, OMPOrderedClause *>
835   getParentOrderedRegionParam() const {
836     if (const SharingMapTy *Parent = getSecondOnStackOrNull())
837       if (Parent->OrderedRegion.hasValue())
838         return Parent->OrderedRegion.getValue();
839     return std::make_pair(nullptr, nullptr);
840   }
841   /// Marks current region as nowait (it has a 'nowait' clause).
842   void setNowaitRegion(bool IsNowait = true) {
843     getTopOfStack().NowaitRegion = IsNowait;
844   }
845   /// Returns true, if parent region is nowait (has associated
846   /// 'nowait' clause), false - otherwise.
847   bool isParentNowaitRegion() const {
848     if (const SharingMapTy *Parent = getSecondOnStackOrNull())
849       return Parent->NowaitRegion;
850     return false;
851   }
852   /// Marks parent region as cancel region.
853   void setParentCancelRegion(bool Cancel = true) {
854     if (SharingMapTy *Parent = getSecondOnStackOrNull())
855       Parent->CancelRegion |= Cancel;
856   }
857   /// Return true if current region has inner cancel construct.
858   bool isCancelRegion() const {
859     const SharingMapTy *Top = getTopOfStackOrNull();
860     return Top ? Top->CancelRegion : false;
861   }
862 
863   /// Mark that parent region already has scan directive.
864   void setParentHasScanDirective(SourceLocation Loc) {
865     if (SharingMapTy *Parent = getSecondOnStackOrNull())
866       Parent->PrevScanLocation = Loc;
867   }
868   /// Return true if current region has inner cancel construct.
869   bool doesParentHasScanDirective() const {
870     const SharingMapTy *Top = getSecondOnStackOrNull();
871     return Top ? Top->PrevScanLocation.isValid() : false;
872   }
873   /// Return true if current region has inner cancel construct.
874   SourceLocation getParentScanDirectiveLoc() const {
875     const SharingMapTy *Top = getSecondOnStackOrNull();
876     return Top ? Top->PrevScanLocation : SourceLocation();
877   }
878   /// Mark that parent region already has ordered directive.
879   void setParentHasOrderedDirective(SourceLocation Loc) {
880     if (SharingMapTy *Parent = getSecondOnStackOrNull())
881       Parent->PrevOrderedLocation = Loc;
882   }
883   /// Return true if current region has inner ordered construct.
884   bool doesParentHasOrderedDirective() const {
885     const SharingMapTy *Top = getSecondOnStackOrNull();
886     return Top ? Top->PrevOrderedLocation.isValid() : false;
887   }
888   /// Returns the location of the previously specified ordered directive.
889   SourceLocation getParentOrderedDirectiveLoc() const {
890     const SharingMapTy *Top = getSecondOnStackOrNull();
891     return Top ? Top->PrevOrderedLocation : SourceLocation();
892   }
893 
894   /// Set collapse value for the region.
895   void setAssociatedLoops(unsigned Val) {
896     getTopOfStack().AssociatedLoops = Val;
897     if (Val > 1)
898       getTopOfStack().HasMutipleLoops = true;
899   }
900   /// Return collapse value for region.
901   unsigned getAssociatedLoops() const {
902     const SharingMapTy *Top = getTopOfStackOrNull();
903     return Top ? Top->AssociatedLoops : 0;
904   }
905   /// Returns true if the construct is associated with multiple loops.
906   bool hasMutipleLoops() const {
907     const SharingMapTy *Top = getTopOfStackOrNull();
908     return Top ? Top->HasMutipleLoops : false;
909   }
910 
911   /// Marks current target region as one with closely nested teams
912   /// region.
913   void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
914     if (SharingMapTy *Parent = getSecondOnStackOrNull())
915       Parent->InnerTeamsRegionLoc = TeamsRegionLoc;
916   }
917   /// Returns true, if current region has closely nested teams region.
918   bool hasInnerTeamsRegion() const {
919     return getInnerTeamsRegionLoc().isValid();
920   }
921   /// Returns location of the nested teams region (if any).
922   SourceLocation getInnerTeamsRegionLoc() const {
923     const SharingMapTy *Top = getTopOfStackOrNull();
924     return Top ? Top->InnerTeamsRegionLoc : SourceLocation();
925   }
926 
927   Scope *getCurScope() const {
928     const SharingMapTy *Top = getTopOfStackOrNull();
929     return Top ? Top->CurScope : nullptr;
930   }
931   void setContext(DeclContext *DC) { getTopOfStack().Context = DC; }
932   SourceLocation getConstructLoc() const {
933     const SharingMapTy *Top = getTopOfStackOrNull();
934     return Top ? Top->ConstructLoc : SourceLocation();
935   }
936 
937   /// Do the check specified in \a Check to all component lists and return true
938   /// if any issue is found.
939   bool checkMappableExprComponentListsForDecl(
940       const ValueDecl *VD, bool CurrentRegionOnly,
941       const llvm::function_ref<
942           bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
943                OpenMPClauseKind)>
944           Check) const {
945     if (isStackEmpty())
946       return false;
947     auto SI = begin();
948     auto SE = end();
949 
950     if (SI == SE)
951       return false;
952 
953     if (CurrentRegionOnly)
954       SE = std::next(SI);
955     else
956       std::advance(SI, 1);
957 
958     for (; SI != SE; ++SI) {
959       auto MI = SI->MappedExprComponents.find(VD);
960       if (MI != SI->MappedExprComponents.end())
961         for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
962              MI->second.Components)
963           if (Check(L, MI->second.Kind))
964             return true;
965     }
966     return false;
967   }
968 
969   /// Do the check specified in \a Check to all component lists at a given level
970   /// and return true if any issue is found.
971   bool checkMappableExprComponentListsForDeclAtLevel(
972       const ValueDecl *VD, unsigned Level,
973       const llvm::function_ref<
974           bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
975                OpenMPClauseKind)>
976           Check) const {
977     if (getStackSize() <= Level)
978       return false;
979 
980     const SharingMapTy &StackElem = getStackElemAtLevel(Level);
981     auto MI = StackElem.MappedExprComponents.find(VD);
982     if (MI != StackElem.MappedExprComponents.end())
983       for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
984            MI->second.Components)
985         if (Check(L, MI->second.Kind))
986           return true;
987     return false;
988   }
989 
990   /// Create a new mappable expression component list associated with a given
991   /// declaration and initialize it with the provided list of components.
992   void addMappableExpressionComponents(
993       const ValueDecl *VD,
994       OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
995       OpenMPClauseKind WhereFoundClauseKind) {
996     MappedExprComponentTy &MEC = getTopOfStack().MappedExprComponents[VD];
997     // Create new entry and append the new components there.
998     MEC.Components.resize(MEC.Components.size() + 1);
999     MEC.Components.back().append(Components.begin(), Components.end());
1000     MEC.Kind = WhereFoundClauseKind;
1001   }
1002 
1003   unsigned getNestingLevel() const {
1004     assert(!isStackEmpty());
1005     return getStackSize() - 1;
1006   }
1007   void addDoacrossDependClause(OMPDependClause *C,
1008                                const OperatorOffsetTy &OpsOffs) {
1009     SharingMapTy *Parent = getSecondOnStackOrNull();
1010     assert(Parent && isOpenMPWorksharingDirective(Parent->Directive));
1011     Parent->DoacrossDepends.try_emplace(C, OpsOffs);
1012   }
1013   llvm::iterator_range<DoacrossDependMapTy::const_iterator>
1014   getDoacrossDependClauses() const {
1015     const SharingMapTy &StackElem = getTopOfStack();
1016     if (isOpenMPWorksharingDirective(StackElem.Directive)) {
1017       const DoacrossDependMapTy &Ref = StackElem.DoacrossDepends;
1018       return llvm::make_range(Ref.begin(), Ref.end());
1019     }
1020     return llvm::make_range(StackElem.DoacrossDepends.end(),
1021                             StackElem.DoacrossDepends.end());
1022   }
1023 
1024   // Store types of classes which have been explicitly mapped
1025   void addMappedClassesQualTypes(QualType QT) {
1026     SharingMapTy &StackElem = getTopOfStack();
1027     StackElem.MappedClassesQualTypes.insert(QT);
1028   }
1029 
1030   // Return set of mapped classes types
1031   bool isClassPreviouslyMapped(QualType QT) const {
1032     const SharingMapTy &StackElem = getTopOfStack();
1033     return StackElem.MappedClassesQualTypes.contains(QT);
1034   }
1035 
1036   /// Adds global declare target to the parent target region.
1037   void addToParentTargetRegionLinkGlobals(DeclRefExpr *E) {
1038     assert(*OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
1039                E->getDecl()) == OMPDeclareTargetDeclAttr::MT_Link &&
1040            "Expected declare target link global.");
1041     for (auto &Elem : *this) {
1042       if (isOpenMPTargetExecutionDirective(Elem.Directive)) {
1043         Elem.DeclareTargetLinkVarDecls.push_back(E);
1044         return;
1045       }
1046     }
1047   }
1048 
1049   /// Returns the list of globals with declare target link if current directive
1050   /// is target.
1051   ArrayRef<DeclRefExpr *> getLinkGlobals() const {
1052     assert(isOpenMPTargetExecutionDirective(getCurrentDirective()) &&
1053            "Expected target executable directive.");
1054     return getTopOfStack().DeclareTargetLinkVarDecls;
1055   }
1056 
1057   /// Adds list of allocators expressions.
1058   void addInnerAllocatorExpr(Expr *E) {
1059     getTopOfStack().InnerUsedAllocators.push_back(E);
1060   }
1061   /// Return list of used allocators.
1062   ArrayRef<Expr *> getInnerAllocators() const {
1063     return getTopOfStack().InnerUsedAllocators;
1064   }
1065   /// Marks the declaration as implicitly firstprivate nin the task-based
1066   /// regions.
1067   void addImplicitTaskFirstprivate(unsigned Level, Decl *D) {
1068     getStackElemAtLevel(Level).ImplicitTaskFirstprivates.insert(D);
1069   }
1070   /// Checks if the decl is implicitly firstprivate in the task-based region.
1071   bool isImplicitTaskFirstprivate(Decl *D) const {
1072     return getTopOfStack().ImplicitTaskFirstprivates.contains(D);
1073   }
1074 
1075   /// Marks decl as used in uses_allocators clause as the allocator.
1076   void addUsesAllocatorsDecl(const Decl *D, UsesAllocatorsDeclKind Kind) {
1077     getTopOfStack().UsesAllocatorsDecls.try_emplace(D, Kind);
1078   }
1079   /// Checks if specified decl is used in uses allocator clause as the
1080   /// allocator.
1081   Optional<UsesAllocatorsDeclKind> isUsesAllocatorsDecl(unsigned Level,
1082                                                         const Decl *D) const {
1083     const SharingMapTy &StackElem = getTopOfStack();
1084     auto I = StackElem.UsesAllocatorsDecls.find(D);
1085     if (I == StackElem.UsesAllocatorsDecls.end())
1086       return None;
1087     return I->getSecond();
1088   }
1089   Optional<UsesAllocatorsDeclKind> isUsesAllocatorsDecl(const Decl *D) const {
1090     const SharingMapTy &StackElem = getTopOfStack();
1091     auto I = StackElem.UsesAllocatorsDecls.find(D);
1092     if (I == StackElem.UsesAllocatorsDecls.end())
1093       return None;
1094     return I->getSecond();
1095   }
1096 
1097   void addDeclareMapperVarRef(Expr *Ref) {
1098     SharingMapTy &StackElem = getTopOfStack();
1099     StackElem.DeclareMapperVar = Ref;
1100   }
1101   const Expr *getDeclareMapperVarRef() const {
1102     const SharingMapTy *Top = getTopOfStackOrNull();
1103     return Top ? Top->DeclareMapperVar : nullptr;
1104   }
1105 };
1106 
1107 bool isImplicitTaskingRegion(OpenMPDirectiveKind DKind) {
1108   return isOpenMPParallelDirective(DKind) || isOpenMPTeamsDirective(DKind);
1109 }
1110 
1111 bool isImplicitOrExplicitTaskingRegion(OpenMPDirectiveKind DKind) {
1112   return isImplicitTaskingRegion(DKind) || isOpenMPTaskingDirective(DKind) ||
1113          DKind == OMPD_unknown;
1114 }
1115 
1116 } // namespace
1117 
1118 static const Expr *getExprAsWritten(const Expr *E) {
1119   if (const auto *FE = dyn_cast<FullExpr>(E))
1120     E = FE->getSubExpr();
1121 
1122   if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
1123     E = MTE->getSubExpr();
1124 
1125   while (const auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
1126     E = Binder->getSubExpr();
1127 
1128   if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
1129     E = ICE->getSubExprAsWritten();
1130   return E->IgnoreParens();
1131 }
1132 
1133 static Expr *getExprAsWritten(Expr *E) {
1134   return const_cast<Expr *>(getExprAsWritten(const_cast<const Expr *>(E)));
1135 }
1136 
1137 static const ValueDecl *getCanonicalDecl(const ValueDecl *D) {
1138   if (const auto *CED = dyn_cast<OMPCapturedExprDecl>(D))
1139     if (const auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
1140       D = ME->getMemberDecl();
1141   const auto *VD = dyn_cast<VarDecl>(D);
1142   const auto *FD = dyn_cast<FieldDecl>(D);
1143   if (VD != nullptr) {
1144     VD = VD->getCanonicalDecl();
1145     D = VD;
1146   } else {
1147     assert(FD);
1148     FD = FD->getCanonicalDecl();
1149     D = FD;
1150   }
1151   return D;
1152 }
1153 
1154 static ValueDecl *getCanonicalDecl(ValueDecl *D) {
1155   return const_cast<ValueDecl *>(
1156       getCanonicalDecl(const_cast<const ValueDecl *>(D)));
1157 }
1158 
1159 DSAStackTy::DSAVarData DSAStackTy::getDSA(const_iterator &Iter,
1160                                           ValueDecl *D) const {
1161   D = getCanonicalDecl(D);
1162   auto *VD = dyn_cast<VarDecl>(D);
1163   const auto *FD = dyn_cast<FieldDecl>(D);
1164   DSAVarData DVar;
1165   if (Iter == end()) {
1166     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1167     // in a region but not in construct]
1168     //  File-scope or namespace-scope variables referenced in called routines
1169     //  in the region are shared unless they appear in a threadprivate
1170     //  directive.
1171     if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(VD))
1172       DVar.CKind = OMPC_shared;
1173 
1174     // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
1175     // in a region but not in construct]
1176     //  Variables with static storage duration that are declared in called
1177     //  routines in the region are shared.
1178     if (VD && VD->hasGlobalStorage())
1179       DVar.CKind = OMPC_shared;
1180 
1181     // Non-static data members are shared by default.
1182     if (FD)
1183       DVar.CKind = OMPC_shared;
1184 
1185     return DVar;
1186   }
1187 
1188   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1189   // in a Construct, C/C++, predetermined, p.1]
1190   // Variables with automatic storage duration that are declared in a scope
1191   // inside the construct are private.
1192   if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() &&
1193       (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) {
1194     DVar.CKind = OMPC_private;
1195     return DVar;
1196   }
1197 
1198   DVar.DKind = Iter->Directive;
1199   // Explicitly specified attributes and local variables with predetermined
1200   // attributes.
1201   if (Iter->SharingMap.count(D)) {
1202     const DSAInfo &Data = Iter->SharingMap.lookup(D);
1203     DVar.RefExpr = Data.RefExpr.getPointer();
1204     DVar.PrivateCopy = Data.PrivateCopy;
1205     DVar.CKind = Data.Attributes;
1206     DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
1207     DVar.Modifier = Data.Modifier;
1208     DVar.AppliedToPointee = Data.AppliedToPointee;
1209     return DVar;
1210   }
1211 
1212   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1213   // in a Construct, C/C++, implicitly determined, p.1]
1214   //  In a parallel or task construct, the data-sharing attributes of these
1215   //  variables are determined by the default clause, if present.
1216   switch (Iter->DefaultAttr) {
1217   case DSA_shared:
1218     DVar.CKind = OMPC_shared;
1219     DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
1220     return DVar;
1221   case DSA_none:
1222     return DVar;
1223   case DSA_firstprivate:
1224     if (VD->getStorageDuration() == SD_Static &&
1225         VD->getDeclContext()->isFileContext()) {
1226       DVar.CKind = OMPC_unknown;
1227     } else {
1228       DVar.CKind = OMPC_firstprivate;
1229     }
1230     DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
1231     return DVar;
1232   case DSA_unspecified:
1233     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1234     // in a Construct, implicitly determined, p.2]
1235     //  In a parallel construct, if no default clause is present, these
1236     //  variables are shared.
1237     DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
1238     if ((isOpenMPParallelDirective(DVar.DKind) &&
1239          !isOpenMPTaskLoopDirective(DVar.DKind)) ||
1240         isOpenMPTeamsDirective(DVar.DKind)) {
1241       DVar.CKind = OMPC_shared;
1242       return DVar;
1243     }
1244 
1245     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1246     // in a Construct, implicitly determined, p.4]
1247     //  In a task construct, if no default clause is present, a variable that in
1248     //  the enclosing context is determined to be shared by all implicit tasks
1249     //  bound to the current team is shared.
1250     if (isOpenMPTaskingDirective(DVar.DKind)) {
1251       DSAVarData DVarTemp;
1252       const_iterator I = Iter, E = end();
1253       do {
1254         ++I;
1255         // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
1256         // Referenced in a Construct, implicitly determined, p.6]
1257         //  In a task construct, if no default clause is present, a variable
1258         //  whose data-sharing attribute is not determined by the rules above is
1259         //  firstprivate.
1260         DVarTemp = getDSA(I, D);
1261         if (DVarTemp.CKind != OMPC_shared) {
1262           DVar.RefExpr = nullptr;
1263           DVar.CKind = OMPC_firstprivate;
1264           return DVar;
1265         }
1266       } while (I != E && !isImplicitTaskingRegion(I->Directive));
1267       DVar.CKind =
1268           (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
1269       return DVar;
1270     }
1271   }
1272   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1273   // in a Construct, implicitly determined, p.3]
1274   //  For constructs other than task, if no default clause is present, these
1275   //  variables inherit their data-sharing attributes from the enclosing
1276   //  context.
1277   return getDSA(++Iter, D);
1278 }
1279 
1280 const Expr *DSAStackTy::addUniqueAligned(const ValueDecl *D,
1281                                          const Expr *NewDE) {
1282   assert(!isStackEmpty() && "Data sharing attributes stack is empty");
1283   D = getCanonicalDecl(D);
1284   SharingMapTy &StackElem = getTopOfStack();
1285   auto It = StackElem.AlignedMap.find(D);
1286   if (It == StackElem.AlignedMap.end()) {
1287     assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
1288     StackElem.AlignedMap[D] = NewDE;
1289     return nullptr;
1290   }
1291   assert(It->second && "Unexpected nullptr expr in the aligned map");
1292   return It->second;
1293 }
1294 
1295 const Expr *DSAStackTy::addUniqueNontemporal(const ValueDecl *D,
1296                                              const Expr *NewDE) {
1297   assert(!isStackEmpty() && "Data sharing attributes stack is empty");
1298   D = getCanonicalDecl(D);
1299   SharingMapTy &StackElem = getTopOfStack();
1300   auto It = StackElem.NontemporalMap.find(D);
1301   if (It == StackElem.NontemporalMap.end()) {
1302     assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
1303     StackElem.NontemporalMap[D] = NewDE;
1304     return nullptr;
1305   }
1306   assert(It->second && "Unexpected nullptr expr in the aligned map");
1307   return It->second;
1308 }
1309 
1310 void DSAStackTy::addLoopControlVariable(const ValueDecl *D, VarDecl *Capture) {
1311   assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
1312   D = getCanonicalDecl(D);
1313   SharingMapTy &StackElem = getTopOfStack();
1314   StackElem.LCVMap.try_emplace(
1315       D, LCDeclInfo(StackElem.LCVMap.size() + 1, Capture));
1316 }
1317 
1318 const DSAStackTy::LCDeclInfo
1319 DSAStackTy::isLoopControlVariable(const ValueDecl *D) const {
1320   assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
1321   D = getCanonicalDecl(D);
1322   const SharingMapTy &StackElem = getTopOfStack();
1323   auto It = StackElem.LCVMap.find(D);
1324   if (It != StackElem.LCVMap.end())
1325     return It->second;
1326   return {0, nullptr};
1327 }
1328 
1329 const DSAStackTy::LCDeclInfo
1330 DSAStackTy::isLoopControlVariable(const ValueDecl *D, unsigned Level) const {
1331   assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
1332   D = getCanonicalDecl(D);
1333   for (unsigned I = Level + 1; I > 0; --I) {
1334     const SharingMapTy &StackElem = getStackElemAtLevel(I - 1);
1335     auto It = StackElem.LCVMap.find(D);
1336     if (It != StackElem.LCVMap.end())
1337       return It->second;
1338   }
1339   return {0, nullptr};
1340 }
1341 
1342 const DSAStackTy::LCDeclInfo
1343 DSAStackTy::isParentLoopControlVariable(const ValueDecl *D) const {
1344   const SharingMapTy *Parent = getSecondOnStackOrNull();
1345   assert(Parent && "Data-sharing attributes stack is empty");
1346   D = getCanonicalDecl(D);
1347   auto It = Parent->LCVMap.find(D);
1348   if (It != Parent->LCVMap.end())
1349     return It->second;
1350   return {0, nullptr};
1351 }
1352 
1353 const ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) const {
1354   const SharingMapTy *Parent = getSecondOnStackOrNull();
1355   assert(Parent && "Data-sharing attributes stack is empty");
1356   if (Parent->LCVMap.size() < I)
1357     return nullptr;
1358   for (const auto &Pair : Parent->LCVMap)
1359     if (Pair.second.first == I)
1360       return Pair.first;
1361   return nullptr;
1362 }
1363 
1364 void DSAStackTy::addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
1365                         DeclRefExpr *PrivateCopy, unsigned Modifier,
1366                         bool AppliedToPointee) {
1367   D = getCanonicalDecl(D);
1368   if (A == OMPC_threadprivate) {
1369     DSAInfo &Data = Threadprivates[D];
1370     Data.Attributes = A;
1371     Data.RefExpr.setPointer(E);
1372     Data.PrivateCopy = nullptr;
1373     Data.Modifier = Modifier;
1374   } else {
1375     DSAInfo &Data = getTopOfStack().SharingMap[D];
1376     assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
1377            (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) ||
1378            (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) ||
1379            (isLoopControlVariable(D).first && A == OMPC_private));
1380     Data.Modifier = Modifier;
1381     if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) {
1382       Data.RefExpr.setInt(/*IntVal=*/true);
1383       return;
1384     }
1385     const bool IsLastprivate =
1386         A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate;
1387     Data.Attributes = A;
1388     Data.RefExpr.setPointerAndInt(E, IsLastprivate);
1389     Data.PrivateCopy = PrivateCopy;
1390     Data.AppliedToPointee = AppliedToPointee;
1391     if (PrivateCopy) {
1392       DSAInfo &Data = getTopOfStack().SharingMap[PrivateCopy->getDecl()];
1393       Data.Modifier = Modifier;
1394       Data.Attributes = A;
1395       Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate);
1396       Data.PrivateCopy = nullptr;
1397       Data.AppliedToPointee = AppliedToPointee;
1398     }
1399   }
1400 }
1401 
1402 /// Build a variable declaration for OpenMP loop iteration variable.
1403 static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
1404                              StringRef Name, const AttrVec *Attrs = nullptr,
1405                              DeclRefExpr *OrigRef = nullptr) {
1406   DeclContext *DC = SemaRef.CurContext;
1407   IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
1408   TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
1409   auto *Decl =
1410       VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
1411   if (Attrs) {
1412     for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
1413          I != E; ++I)
1414       Decl->addAttr(*I);
1415   }
1416   Decl->setImplicit();
1417   if (OrigRef) {
1418     Decl->addAttr(
1419         OMPReferencedVarAttr::CreateImplicit(SemaRef.Context, OrigRef));
1420   }
1421   return Decl;
1422 }
1423 
1424 static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
1425                                      SourceLocation Loc,
1426                                      bool RefersToCapture = false) {
1427   D->setReferenced();
1428   D->markUsed(S.Context);
1429   return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
1430                              SourceLocation(), D, RefersToCapture, Loc, Ty,
1431                              VK_LValue);
1432 }
1433 
1434 void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
1435                                            BinaryOperatorKind BOK) {
1436   D = getCanonicalDecl(D);
1437   assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
1438   assert(
1439       getTopOfStack().SharingMap[D].Attributes == OMPC_reduction &&
1440       "Additional reduction info may be specified only for reduction items.");
1441   ReductionData &ReductionData = getTopOfStack().ReductionMap[D];
1442   assert(ReductionData.ReductionRange.isInvalid() &&
1443          (getTopOfStack().Directive == OMPD_taskgroup ||
1444           ((isOpenMPParallelDirective(getTopOfStack().Directive) ||
1445             isOpenMPWorksharingDirective(getTopOfStack().Directive)) &&
1446            !isOpenMPSimdDirective(getTopOfStack().Directive))) &&
1447          "Additional reduction info may be specified only once for reduction "
1448          "items.");
1449   ReductionData.set(BOK, SR);
1450   Expr *&TaskgroupReductionRef = getTopOfStack().TaskgroupReductionRef;
1451   if (!TaskgroupReductionRef) {
1452     VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
1453                                SemaRef.Context.VoidPtrTy, ".task_red.");
1454     TaskgroupReductionRef =
1455         buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
1456   }
1457 }
1458 
1459 void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
1460                                            const Expr *ReductionRef) {
1461   D = getCanonicalDecl(D);
1462   assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
1463   assert(
1464       getTopOfStack().SharingMap[D].Attributes == OMPC_reduction &&
1465       "Additional reduction info may be specified only for reduction items.");
1466   ReductionData &ReductionData = getTopOfStack().ReductionMap[D];
1467   assert(ReductionData.ReductionRange.isInvalid() &&
1468          (getTopOfStack().Directive == OMPD_taskgroup ||
1469           ((isOpenMPParallelDirective(getTopOfStack().Directive) ||
1470             isOpenMPWorksharingDirective(getTopOfStack().Directive)) &&
1471            !isOpenMPSimdDirective(getTopOfStack().Directive))) &&
1472          "Additional reduction info may be specified only once for reduction "
1473          "items.");
1474   ReductionData.set(ReductionRef, SR);
1475   Expr *&TaskgroupReductionRef = getTopOfStack().TaskgroupReductionRef;
1476   if (!TaskgroupReductionRef) {
1477     VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
1478                                SemaRef.Context.VoidPtrTy, ".task_red.");
1479     TaskgroupReductionRef =
1480         buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
1481   }
1482 }
1483 
1484 const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
1485     const ValueDecl *D, SourceRange &SR, BinaryOperatorKind &BOK,
1486     Expr *&TaskgroupDescriptor) const {
1487   D = getCanonicalDecl(D);
1488   assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
1489   for (const_iterator I = begin() + 1, E = end(); I != E; ++I) {
1490     const DSAInfo &Data = I->SharingMap.lookup(D);
1491     if (Data.Attributes != OMPC_reduction ||
1492         Data.Modifier != OMPC_REDUCTION_task)
1493       continue;
1494     const ReductionData &ReductionData = I->ReductionMap.lookup(D);
1495     if (!ReductionData.ReductionOp ||
1496         ReductionData.ReductionOp.is<const Expr *>())
1497       return DSAVarData();
1498     SR = ReductionData.ReductionRange;
1499     BOK = ReductionData.ReductionOp.get<ReductionData::BOKPtrType>();
1500     assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
1501                                        "expression for the descriptor is not "
1502                                        "set.");
1503     TaskgroupDescriptor = I->TaskgroupReductionRef;
1504     return DSAVarData(I->Directive, OMPC_reduction, Data.RefExpr.getPointer(),
1505                       Data.PrivateCopy, I->DefaultAttrLoc, OMPC_REDUCTION_task,
1506                       /*AppliedToPointee=*/false);
1507   }
1508   return DSAVarData();
1509 }
1510 
1511 const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
1512     const ValueDecl *D, SourceRange &SR, const Expr *&ReductionRef,
1513     Expr *&TaskgroupDescriptor) const {
1514   D = getCanonicalDecl(D);
1515   assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
1516   for (const_iterator I = begin() + 1, E = end(); I != E; ++I) {
1517     const DSAInfo &Data = I->SharingMap.lookup(D);
1518     if (Data.Attributes != OMPC_reduction ||
1519         Data.Modifier != OMPC_REDUCTION_task)
1520       continue;
1521     const ReductionData &ReductionData = I->ReductionMap.lookup(D);
1522     if (!ReductionData.ReductionOp ||
1523         !ReductionData.ReductionOp.is<const Expr *>())
1524       return DSAVarData();
1525     SR = ReductionData.ReductionRange;
1526     ReductionRef = ReductionData.ReductionOp.get<const Expr *>();
1527     assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
1528                                        "expression for the descriptor is not "
1529                                        "set.");
1530     TaskgroupDescriptor = I->TaskgroupReductionRef;
1531     return DSAVarData(I->Directive, OMPC_reduction, Data.RefExpr.getPointer(),
1532                       Data.PrivateCopy, I->DefaultAttrLoc, OMPC_REDUCTION_task,
1533                       /*AppliedToPointee=*/false);
1534   }
1535   return DSAVarData();
1536 }
1537 
1538 bool DSAStackTy::isOpenMPLocal(VarDecl *D, const_iterator I) const {
1539   D = D->getCanonicalDecl();
1540   for (const_iterator E = end(); I != E; ++I) {
1541     if (isImplicitOrExplicitTaskingRegion(I->Directive) ||
1542         isOpenMPTargetExecutionDirective(I->Directive)) {
1543       if (I->CurScope) {
1544         Scope *TopScope = I->CurScope->getParent();
1545         Scope *CurScope = getCurScope();
1546         while (CurScope && CurScope != TopScope && !CurScope->isDeclScope(D))
1547           CurScope = CurScope->getParent();
1548         return CurScope != TopScope;
1549       }
1550       for (DeclContext *DC = D->getDeclContext(); DC; DC = DC->getParent())
1551         if (I->Context == DC)
1552           return true;
1553       return false;
1554     }
1555   }
1556   return false;
1557 }
1558 
1559 static bool isConstNotMutableType(Sema &SemaRef, QualType Type,
1560                                   bool AcceptIfMutable = true,
1561                                   bool *IsClassType = nullptr) {
1562   ASTContext &Context = SemaRef.getASTContext();
1563   Type = Type.getNonReferenceType().getCanonicalType();
1564   bool IsConstant = Type.isConstant(Context);
1565   Type = Context.getBaseElementType(Type);
1566   const CXXRecordDecl *RD = AcceptIfMutable && SemaRef.getLangOpts().CPlusPlus
1567                                 ? Type->getAsCXXRecordDecl()
1568                                 : nullptr;
1569   if (const auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
1570     if (const ClassTemplateDecl *CTD = CTSD->getSpecializedTemplate())
1571       RD = CTD->getTemplatedDecl();
1572   if (IsClassType)
1573     *IsClassType = RD;
1574   return IsConstant && !(SemaRef.getLangOpts().CPlusPlus && RD &&
1575                          RD->hasDefinition() && RD->hasMutableFields());
1576 }
1577 
1578 static bool rejectConstNotMutableType(Sema &SemaRef, const ValueDecl *D,
1579                                       QualType Type, OpenMPClauseKind CKind,
1580                                       SourceLocation ELoc,
1581                                       bool AcceptIfMutable = true,
1582                                       bool ListItemNotVar = false) {
1583   ASTContext &Context = SemaRef.getASTContext();
1584   bool IsClassType;
1585   if (isConstNotMutableType(SemaRef, Type, AcceptIfMutable, &IsClassType)) {
1586     unsigned Diag = ListItemNotVar ? diag::err_omp_const_list_item
1587                     : IsClassType  ? diag::err_omp_const_not_mutable_variable
1588                                    : diag::err_omp_const_variable;
1589     SemaRef.Diag(ELoc, Diag) << getOpenMPClauseName(CKind);
1590     if (!ListItemNotVar && D) {
1591       const VarDecl *VD = dyn_cast<VarDecl>(D);
1592       bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
1593                                VarDecl::DeclarationOnly;
1594       SemaRef.Diag(D->getLocation(),
1595                    IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1596           << D;
1597     }
1598     return true;
1599   }
1600   return false;
1601 }
1602 
1603 const DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D,
1604                                                    bool FromParent) {
1605   D = getCanonicalDecl(D);
1606   DSAVarData DVar;
1607 
1608   auto *VD = dyn_cast<VarDecl>(D);
1609   auto TI = Threadprivates.find(D);
1610   if (TI != Threadprivates.end()) {
1611     DVar.RefExpr = TI->getSecond().RefExpr.getPointer();
1612     DVar.CKind = OMPC_threadprivate;
1613     DVar.Modifier = TI->getSecond().Modifier;
1614     return DVar;
1615   }
1616   if (VD && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
1617     DVar.RefExpr = buildDeclRefExpr(
1618         SemaRef, VD, D->getType().getNonReferenceType(),
1619         VD->getAttr<OMPThreadPrivateDeclAttr>()->getLocation());
1620     DVar.CKind = OMPC_threadprivate;
1621     addDSA(D, DVar.RefExpr, OMPC_threadprivate);
1622     return DVar;
1623   }
1624   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1625   // in a Construct, C/C++, predetermined, p.1]
1626   //  Variables appearing in threadprivate directives are threadprivate.
1627   if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
1628        !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
1629          SemaRef.getLangOpts().OpenMPUseTLS &&
1630          SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
1631       (VD && VD->getStorageClass() == SC_Register &&
1632        VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
1633     DVar.RefExpr = buildDeclRefExpr(
1634         SemaRef, VD, D->getType().getNonReferenceType(), D->getLocation());
1635     DVar.CKind = OMPC_threadprivate;
1636     addDSA(D, DVar.RefExpr, OMPC_threadprivate);
1637     return DVar;
1638   }
1639   if (SemaRef.getLangOpts().OpenMPCUDAMode && VD &&
1640       VD->isLocalVarDeclOrParm() && !isStackEmpty() &&
1641       !isLoopControlVariable(D).first) {
1642     const_iterator IterTarget =
1643         std::find_if(begin(), end(), [](const SharingMapTy &Data) {
1644           return isOpenMPTargetExecutionDirective(Data.Directive);
1645         });
1646     if (IterTarget != end()) {
1647       const_iterator ParentIterTarget = IterTarget + 1;
1648       for (const_iterator Iter = begin(); Iter != ParentIterTarget; ++Iter) {
1649         if (isOpenMPLocal(VD, Iter)) {
1650           DVar.RefExpr =
1651               buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
1652                                D->getLocation());
1653           DVar.CKind = OMPC_threadprivate;
1654           return DVar;
1655         }
1656       }
1657       if (!isClauseParsingMode() || IterTarget != begin()) {
1658         auto DSAIter = IterTarget->SharingMap.find(D);
1659         if (DSAIter != IterTarget->SharingMap.end() &&
1660             isOpenMPPrivate(DSAIter->getSecond().Attributes)) {
1661           DVar.RefExpr = DSAIter->getSecond().RefExpr.getPointer();
1662           DVar.CKind = OMPC_threadprivate;
1663           return DVar;
1664         }
1665         const_iterator End = end();
1666         if (!SemaRef.isOpenMPCapturedByRef(D,
1667                                            std::distance(ParentIterTarget, End),
1668                                            /*OpenMPCaptureLevel=*/0)) {
1669           DVar.RefExpr =
1670               buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
1671                                IterTarget->ConstructLoc);
1672           DVar.CKind = OMPC_threadprivate;
1673           return DVar;
1674         }
1675       }
1676     }
1677   }
1678 
1679   if (isStackEmpty())
1680     // Not in OpenMP execution region and top scope was already checked.
1681     return DVar;
1682 
1683   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1684   // in a Construct, C/C++, predetermined, p.4]
1685   //  Static data members are shared.
1686   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1687   // in a Construct, C/C++, predetermined, p.7]
1688   //  Variables with static storage duration that are declared in a scope
1689   //  inside the construct are shared.
1690   if (VD && VD->isStaticDataMember()) {
1691     // Check for explicitly specified attributes.
1692     const_iterator I = begin();
1693     const_iterator EndI = end();
1694     if (FromParent && I != EndI)
1695       ++I;
1696     if (I != EndI) {
1697       auto It = I->SharingMap.find(D);
1698       if (It != I->SharingMap.end()) {
1699         const DSAInfo &Data = It->getSecond();
1700         DVar.RefExpr = Data.RefExpr.getPointer();
1701         DVar.PrivateCopy = Data.PrivateCopy;
1702         DVar.CKind = Data.Attributes;
1703         DVar.ImplicitDSALoc = I->DefaultAttrLoc;
1704         DVar.DKind = I->Directive;
1705         DVar.Modifier = Data.Modifier;
1706         DVar.AppliedToPointee = Data.AppliedToPointee;
1707         return DVar;
1708       }
1709     }
1710 
1711     DVar.CKind = OMPC_shared;
1712     return DVar;
1713   }
1714 
1715   auto &&MatchesAlways = [](OpenMPDirectiveKind) { return true; };
1716   // The predetermined shared attribute for const-qualified types having no
1717   // mutable members was removed after OpenMP 3.1.
1718   if (SemaRef.LangOpts.OpenMP <= 31) {
1719     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1720     // in a Construct, C/C++, predetermined, p.6]
1721     //  Variables with const qualified type having no mutable member are
1722     //  shared.
1723     if (isConstNotMutableType(SemaRef, D->getType())) {
1724       // Variables with const-qualified type having no mutable member may be
1725       // listed in a firstprivate clause, even if they are static data members.
1726       DSAVarData DVarTemp = hasInnermostDSA(
1727           D,
1728           [](OpenMPClauseKind C, bool) {
1729             return C == OMPC_firstprivate || C == OMPC_shared;
1730           },
1731           MatchesAlways, FromParent);
1732       if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
1733         return DVarTemp;
1734 
1735       DVar.CKind = OMPC_shared;
1736       return DVar;
1737     }
1738   }
1739 
1740   // Explicitly specified attributes and local variables with predetermined
1741   // attributes.
1742   const_iterator I = begin();
1743   const_iterator EndI = end();
1744   if (FromParent && I != EndI)
1745     ++I;
1746   if (I == EndI)
1747     return DVar;
1748   auto It = I->SharingMap.find(D);
1749   if (It != I->SharingMap.end()) {
1750     const DSAInfo &Data = It->getSecond();
1751     DVar.RefExpr = Data.RefExpr.getPointer();
1752     DVar.PrivateCopy = Data.PrivateCopy;
1753     DVar.CKind = Data.Attributes;
1754     DVar.ImplicitDSALoc = I->DefaultAttrLoc;
1755     DVar.DKind = I->Directive;
1756     DVar.Modifier = Data.Modifier;
1757     DVar.AppliedToPointee = Data.AppliedToPointee;
1758   }
1759 
1760   return DVar;
1761 }
1762 
1763 const DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
1764                                                         bool FromParent) const {
1765   if (isStackEmpty()) {
1766     const_iterator I;
1767     return getDSA(I, D);
1768   }
1769   D = getCanonicalDecl(D);
1770   const_iterator StartI = begin();
1771   const_iterator EndI = end();
1772   if (FromParent && StartI != EndI)
1773     ++StartI;
1774   return getDSA(StartI, D);
1775 }
1776 
1777 const DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
1778                                                         unsigned Level) const {
1779   if (getStackSize() <= Level)
1780     return DSAVarData();
1781   D = getCanonicalDecl(D);
1782   const_iterator StartI = std::next(begin(), getStackSize() - 1 - Level);
1783   return getDSA(StartI, D);
1784 }
1785 
1786 const DSAStackTy::DSAVarData
1787 DSAStackTy::hasDSA(ValueDecl *D,
1788                    const llvm::function_ref<bool(OpenMPClauseKind, bool)> CPred,
1789                    const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
1790                    bool FromParent) const {
1791   if (isStackEmpty())
1792     return {};
1793   D = getCanonicalDecl(D);
1794   const_iterator I = begin();
1795   const_iterator EndI = end();
1796   if (FromParent && I != EndI)
1797     ++I;
1798   for (; I != EndI; ++I) {
1799     if (!DPred(I->Directive) &&
1800         !isImplicitOrExplicitTaskingRegion(I->Directive))
1801       continue;
1802     const_iterator NewI = I;
1803     DSAVarData DVar = getDSA(NewI, D);
1804     if (I == NewI && CPred(DVar.CKind, DVar.AppliedToPointee))
1805       return DVar;
1806   }
1807   return {};
1808 }
1809 
1810 const DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
1811     ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind, bool)> CPred,
1812     const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
1813     bool FromParent) const {
1814   if (isStackEmpty())
1815     return {};
1816   D = getCanonicalDecl(D);
1817   const_iterator StartI = begin();
1818   const_iterator EndI = end();
1819   if (FromParent && StartI != EndI)
1820     ++StartI;
1821   if (StartI == EndI || !DPred(StartI->Directive))
1822     return {};
1823   const_iterator NewI = StartI;
1824   DSAVarData DVar = getDSA(NewI, D);
1825   return (NewI == StartI && CPred(DVar.CKind, DVar.AppliedToPointee))
1826              ? DVar
1827              : DSAVarData();
1828 }
1829 
1830 bool DSAStackTy::hasExplicitDSA(
1831     const ValueDecl *D,
1832     const llvm::function_ref<bool(OpenMPClauseKind, bool)> CPred,
1833     unsigned Level, bool NotLastprivate) const {
1834   if (getStackSize() <= Level)
1835     return false;
1836   D = getCanonicalDecl(D);
1837   const SharingMapTy &StackElem = getStackElemAtLevel(Level);
1838   auto I = StackElem.SharingMap.find(D);
1839   if (I != StackElem.SharingMap.end() && I->getSecond().RefExpr.getPointer() &&
1840       CPred(I->getSecond().Attributes, I->getSecond().AppliedToPointee) &&
1841       (!NotLastprivate || !I->getSecond().RefExpr.getInt()))
1842     return true;
1843   // Check predetermined rules for the loop control variables.
1844   auto LI = StackElem.LCVMap.find(D);
1845   if (LI != StackElem.LCVMap.end())
1846     return CPred(OMPC_private, /*AppliedToPointee=*/false);
1847   return false;
1848 }
1849 
1850 bool DSAStackTy::hasExplicitDirective(
1851     const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
1852     unsigned Level) const {
1853   if (getStackSize() <= Level)
1854     return false;
1855   const SharingMapTy &StackElem = getStackElemAtLevel(Level);
1856   return DPred(StackElem.Directive);
1857 }
1858 
1859 bool DSAStackTy::hasDirective(
1860     const llvm::function_ref<bool(OpenMPDirectiveKind,
1861                                   const DeclarationNameInfo &, SourceLocation)>
1862         DPred,
1863     bool FromParent) const {
1864   // We look only in the enclosing region.
1865   size_t Skip = FromParent ? 2 : 1;
1866   for (const_iterator I = begin() + std::min(Skip, getStackSize()), E = end();
1867        I != E; ++I) {
1868     if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
1869       return true;
1870   }
1871   return false;
1872 }
1873 
1874 void Sema::InitDataSharingAttributesStack() {
1875   VarDataSharingAttributesStack = new DSAStackTy(*this);
1876 }
1877 
1878 #define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
1879 
1880 void Sema::pushOpenMPFunctionRegion() { DSAStack->pushFunction(); }
1881 
1882 void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) {
1883   DSAStack->popFunction(OldFSI);
1884 }
1885 
1886 static bool isOpenMPDeviceDelayedContext(Sema &S) {
1887   assert(S.LangOpts.OpenMP && S.LangOpts.OpenMPIsDevice &&
1888          "Expected OpenMP device compilation.");
1889   return !S.isInOpenMPTargetExecutionDirective();
1890 }
1891 
1892 namespace {
1893 /// Status of the function emission on the host/device.
1894 enum class FunctionEmissionStatus {
1895   Emitted,
1896   Discarded,
1897   Unknown,
1898 };
1899 } // anonymous namespace
1900 
1901 Sema::SemaDiagnosticBuilder Sema::diagIfOpenMPDeviceCode(SourceLocation Loc,
1902                                                          unsigned DiagID,
1903                                                          FunctionDecl *FD) {
1904   assert(LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
1905          "Expected OpenMP device compilation.");
1906 
1907   SemaDiagnosticBuilder::Kind Kind = SemaDiagnosticBuilder::K_Nop;
1908   if (FD) {
1909     FunctionEmissionStatus FES = getEmissionStatus(FD);
1910     switch (FES) {
1911     case FunctionEmissionStatus::Emitted:
1912       Kind = SemaDiagnosticBuilder::K_Immediate;
1913       break;
1914     case FunctionEmissionStatus::Unknown:
1915       // TODO: We should always delay diagnostics here in case a target
1916       //       region is in a function we do not emit. However, as the
1917       //       current diagnostics are associated with the function containing
1918       //       the target region and we do not emit that one, we would miss out
1919       //       on diagnostics for the target region itself. We need to anchor
1920       //       the diagnostics with the new generated function *or* ensure we
1921       //       emit diagnostics associated with the surrounding function.
1922       Kind = isOpenMPDeviceDelayedContext(*this)
1923                  ? SemaDiagnosticBuilder::K_Deferred
1924                  : SemaDiagnosticBuilder::K_Immediate;
1925       break;
1926     case FunctionEmissionStatus::TemplateDiscarded:
1927     case FunctionEmissionStatus::OMPDiscarded:
1928       Kind = SemaDiagnosticBuilder::K_Nop;
1929       break;
1930     case FunctionEmissionStatus::CUDADiscarded:
1931       llvm_unreachable("CUDADiscarded unexpected in OpenMP device compilation");
1932       break;
1933     }
1934   }
1935 
1936   return SemaDiagnosticBuilder(Kind, Loc, DiagID, FD, *this);
1937 }
1938 
1939 Sema::SemaDiagnosticBuilder Sema::diagIfOpenMPHostCode(SourceLocation Loc,
1940                                                        unsigned DiagID,
1941                                                        FunctionDecl *FD) {
1942   assert(LangOpts.OpenMP && !LangOpts.OpenMPIsDevice &&
1943          "Expected OpenMP host compilation.");
1944 
1945   SemaDiagnosticBuilder::Kind Kind = SemaDiagnosticBuilder::K_Nop;
1946   if (FD) {
1947     FunctionEmissionStatus FES = getEmissionStatus(FD);
1948     switch (FES) {
1949     case FunctionEmissionStatus::Emitted:
1950       Kind = SemaDiagnosticBuilder::K_Immediate;
1951       break;
1952     case FunctionEmissionStatus::Unknown:
1953       Kind = SemaDiagnosticBuilder::K_Deferred;
1954       break;
1955     case FunctionEmissionStatus::TemplateDiscarded:
1956     case FunctionEmissionStatus::OMPDiscarded:
1957     case FunctionEmissionStatus::CUDADiscarded:
1958       Kind = SemaDiagnosticBuilder::K_Nop;
1959       break;
1960     }
1961   }
1962 
1963   return SemaDiagnosticBuilder(Kind, Loc, DiagID, FD, *this);
1964 }
1965 
1966 static OpenMPDefaultmapClauseKind
1967 getVariableCategoryFromDecl(const LangOptions &LO, const ValueDecl *VD) {
1968   if (LO.OpenMP <= 45) {
1969     if (VD->getType().getNonReferenceType()->isScalarType())
1970       return OMPC_DEFAULTMAP_scalar;
1971     return OMPC_DEFAULTMAP_aggregate;
1972   }
1973   if (VD->getType().getNonReferenceType()->isAnyPointerType())
1974     return OMPC_DEFAULTMAP_pointer;
1975   if (VD->getType().getNonReferenceType()->isScalarType())
1976     return OMPC_DEFAULTMAP_scalar;
1977   return OMPC_DEFAULTMAP_aggregate;
1978 }
1979 
1980 bool Sema::isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level,
1981                                  unsigned OpenMPCaptureLevel) const {
1982   assert(LangOpts.OpenMP && "OpenMP is not allowed");
1983 
1984   ASTContext &Ctx = getASTContext();
1985   bool IsByRef = true;
1986 
1987   // Find the directive that is associated with the provided scope.
1988   D = cast<ValueDecl>(D->getCanonicalDecl());
1989   QualType Ty = D->getType();
1990 
1991   bool IsVariableUsedInMapClause = false;
1992   if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
1993     // This table summarizes how a given variable should be passed to the device
1994     // given its type and the clauses where it appears. This table is based on
1995     // the description in OpenMP 4.5 [2.10.4, target Construct] and
1996     // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
1997     //
1998     // =========================================================================
1999     // | type |  defaultmap   | pvt | first | is_device_ptr |    map   | res.  |
2000     // |      |(tofrom:scalar)|     |  pvt  |               |          |       |
2001     // =========================================================================
2002     // | scl  |               |     |       |       -       |          | bycopy|
2003     // | scl  |               |  -  |   x   |       -       |     -    | bycopy|
2004     // | scl  |               |  x  |   -   |       -       |     -    | null  |
2005     // | scl  |       x       |     |       |       -       |          | byref |
2006     // | scl  |       x       |  -  |   x   |       -       |     -    | bycopy|
2007     // | scl  |       x       |  x  |   -   |       -       |     -    | null  |
2008     // | scl  |               |  -  |   -   |       -       |     x    | byref |
2009     // | scl  |       x       |  -  |   -   |       -       |     x    | byref |
2010     //
2011     // | agg  |      n.a.     |     |       |       -       |          | byref |
2012     // | agg  |      n.a.     |  -  |   x   |       -       |     -    | byref |
2013     // | agg  |      n.a.     |  x  |   -   |       -       |     -    | null  |
2014     // | agg  |      n.a.     |  -  |   -   |       -       |     x    | byref |
2015     // | agg  |      n.a.     |  -  |   -   |       -       |    x[]   | byref |
2016     //
2017     // | ptr  |      n.a.     |     |       |       -       |          | bycopy|
2018     // | ptr  |      n.a.     |  -  |   x   |       -       |     -    | bycopy|
2019     // | ptr  |      n.a.     |  x  |   -   |       -       |     -    | null  |
2020     // | ptr  |      n.a.     |  -  |   -   |       -       |     x    | byref |
2021     // | ptr  |      n.a.     |  -  |   -   |       -       |    x[]   | bycopy|
2022     // | ptr  |      n.a.     |  -  |   -   |       x       |          | bycopy|
2023     // | ptr  |      n.a.     |  -  |   -   |       x       |     x    | bycopy|
2024     // | ptr  |      n.a.     |  -  |   -   |       x       |    x[]   | bycopy|
2025     // =========================================================================
2026     // Legend:
2027     //  scl - scalar
2028     //  ptr - pointer
2029     //  agg - aggregate
2030     //  x - applies
2031     //  - - invalid in this combination
2032     //  [] - mapped with an array section
2033     //  byref - should be mapped by reference
2034     //  byval - should be mapped by value
2035     //  null - initialize a local variable to null on the device
2036     //
2037     // Observations:
2038     //  - All scalar declarations that show up in a map clause have to be passed
2039     //    by reference, because they may have been mapped in the enclosing data
2040     //    environment.
2041     //  - If the scalar value does not fit the size of uintptr, it has to be
2042     //    passed by reference, regardless the result in the table above.
2043     //  - For pointers mapped by value that have either an implicit map or an
2044     //    array section, the runtime library may pass the NULL value to the
2045     //    device instead of the value passed to it by the compiler.
2046 
2047     if (Ty->isReferenceType())
2048       Ty = Ty->castAs<ReferenceType>()->getPointeeType();
2049 
2050     // Locate map clauses and see if the variable being captured is referred to
2051     // in any of those clauses. Here we only care about variables, not fields,
2052     // because fields are part of aggregates.
2053     bool IsVariableAssociatedWithSection = false;
2054 
2055     DSAStack->checkMappableExprComponentListsForDeclAtLevel(
2056         D, Level,
2057         [&IsVariableUsedInMapClause, &IsVariableAssociatedWithSection,
2058          D](OMPClauseMappableExprCommon::MappableExprComponentListRef
2059                 MapExprComponents,
2060             OpenMPClauseKind WhereFoundClauseKind) {
2061           // Only the map clause information influences how a variable is
2062           // captured. E.g. is_device_ptr does not require changing the default
2063           // behavior.
2064           if (WhereFoundClauseKind != OMPC_map)
2065             return false;
2066 
2067           auto EI = MapExprComponents.rbegin();
2068           auto EE = MapExprComponents.rend();
2069 
2070           assert(EI != EE && "Invalid map expression!");
2071 
2072           if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
2073             IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
2074 
2075           ++EI;
2076           if (EI == EE)
2077             return false;
2078 
2079           if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
2080               isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
2081               isa<MemberExpr>(EI->getAssociatedExpression()) ||
2082               isa<OMPArrayShapingExpr>(EI->getAssociatedExpression())) {
2083             IsVariableAssociatedWithSection = true;
2084             // There is nothing more we need to know about this variable.
2085             return true;
2086           }
2087 
2088           // Keep looking for more map info.
2089           return false;
2090         });
2091 
2092     if (IsVariableUsedInMapClause) {
2093       // If variable is identified in a map clause it is always captured by
2094       // reference except if it is a pointer that is dereferenced somehow.
2095       IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
2096     } else {
2097       // By default, all the data that has a scalar type is mapped by copy
2098       // (except for reduction variables).
2099       // Defaultmap scalar is mutual exclusive to defaultmap pointer
2100       IsByRef = (DSAStack->isForceCaptureByReferenceInTargetExecutable() &&
2101                  !Ty->isAnyPointerType()) ||
2102                 !Ty->isScalarType() ||
2103                 DSAStack->isDefaultmapCapturedByRef(
2104                     Level, getVariableCategoryFromDecl(LangOpts, D)) ||
2105                 DSAStack->hasExplicitDSA(
2106                     D,
2107                     [](OpenMPClauseKind K, bool AppliedToPointee) {
2108                       return K == OMPC_reduction && !AppliedToPointee;
2109                     },
2110                     Level);
2111     }
2112   }
2113 
2114   if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
2115     IsByRef =
2116         ((IsVariableUsedInMapClause &&
2117           DSAStack->getCaptureRegion(Level, OpenMPCaptureLevel) ==
2118               OMPD_target) ||
2119          !(DSAStack->hasExplicitDSA(
2120                D,
2121                [](OpenMPClauseKind K, bool AppliedToPointee) -> bool {
2122                  return K == OMPC_firstprivate ||
2123                         (K == OMPC_reduction && AppliedToPointee);
2124                },
2125                Level, /*NotLastprivate=*/true) ||
2126            DSAStack->isUsesAllocatorsDecl(Level, D))) &&
2127         // If the variable is artificial and must be captured by value - try to
2128         // capture by value.
2129         !(isa<OMPCapturedExprDecl>(D) && !D->hasAttr<OMPCaptureNoInitAttr>() &&
2130           !cast<OMPCapturedExprDecl>(D)->getInit()->isGLValue()) &&
2131         // If the variable is implicitly firstprivate and scalar - capture by
2132         // copy
2133         !(DSAStack->getDefaultDSA() == DSA_firstprivate &&
2134           !DSAStack->hasExplicitDSA(
2135               D, [](OpenMPClauseKind K, bool) { return K != OMPC_unknown; },
2136               Level) &&
2137           !DSAStack->isLoopControlVariable(D, Level).first);
2138   }
2139 
2140   // When passing data by copy, we need to make sure it fits the uintptr size
2141   // and alignment, because the runtime library only deals with uintptr types.
2142   // If it does not fit the uintptr size, we need to pass the data by reference
2143   // instead.
2144   if (!IsByRef &&
2145       (Ctx.getTypeSizeInChars(Ty) >
2146            Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
2147        Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
2148     IsByRef = true;
2149   }
2150 
2151   return IsByRef;
2152 }
2153 
2154 unsigned Sema::getOpenMPNestingLevel() const {
2155   assert(getLangOpts().OpenMP);
2156   return DSAStack->getNestingLevel();
2157 }
2158 
2159 bool Sema::isInOpenMPTargetExecutionDirective() const {
2160   return (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) &&
2161           !DSAStack->isClauseParsingMode()) ||
2162          DSAStack->hasDirective(
2163              [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
2164                 SourceLocation) -> bool {
2165                return isOpenMPTargetExecutionDirective(K);
2166              },
2167              false);
2168 }
2169 
2170 VarDecl *Sema::isOpenMPCapturedDecl(ValueDecl *D, bool CheckScopeInfo,
2171                                     unsigned StopAt) {
2172   assert(LangOpts.OpenMP && "OpenMP is not allowed");
2173   D = getCanonicalDecl(D);
2174 
2175   auto *VD = dyn_cast<VarDecl>(D);
2176   // Do not capture constexpr variables.
2177   if (VD && VD->isConstexpr())
2178     return nullptr;
2179 
2180   // If we want to determine whether the variable should be captured from the
2181   // perspective of the current capturing scope, and we've already left all the
2182   // capturing scopes of the top directive on the stack, check from the
2183   // perspective of its parent directive (if any) instead.
2184   DSAStackTy::ParentDirectiveScope InParentDirectiveRAII(
2185       *DSAStack, CheckScopeInfo && DSAStack->isBodyComplete());
2186 
2187   // If we are attempting to capture a global variable in a directive with
2188   // 'target' we return true so that this global is also mapped to the device.
2189   //
2190   if (VD && !VD->hasLocalStorage() &&
2191       (getCurCapturedRegion() || getCurBlock() || getCurLambda())) {
2192     if (isInOpenMPTargetExecutionDirective()) {
2193       DSAStackTy::DSAVarData DVarTop =
2194           DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
2195       if (DVarTop.CKind != OMPC_unknown && DVarTop.RefExpr)
2196         return VD;
2197       // If the declaration is enclosed in a 'declare target' directive,
2198       // then it should not be captured.
2199       //
2200       if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
2201         return nullptr;
2202       CapturedRegionScopeInfo *CSI = nullptr;
2203       for (FunctionScopeInfo *FSI : llvm::drop_begin(
2204                llvm::reverse(FunctionScopes),
2205                CheckScopeInfo ? (FunctionScopes.size() - (StopAt + 1)) : 0)) {
2206         if (!isa<CapturingScopeInfo>(FSI))
2207           return nullptr;
2208         if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(FSI))
2209           if (RSI->CapRegionKind == CR_OpenMP) {
2210             CSI = RSI;
2211             break;
2212           }
2213       }
2214       assert(CSI && "Failed to find CapturedRegionScopeInfo");
2215       SmallVector<OpenMPDirectiveKind, 4> Regions;
2216       getOpenMPCaptureRegions(Regions,
2217                               DSAStack->getDirective(CSI->OpenMPLevel));
2218       if (Regions[CSI->OpenMPCaptureLevel] != OMPD_task)
2219         return VD;
2220     }
2221     if (isInOpenMPDeclareTargetContext()) {
2222       // Try to mark variable as declare target if it is used in capturing
2223       // regions.
2224       if (LangOpts.OpenMP <= 45 &&
2225           !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
2226         checkDeclIsAllowedInOpenMPTarget(nullptr, VD);
2227       return nullptr;
2228     }
2229   }
2230 
2231   if (CheckScopeInfo) {
2232     bool OpenMPFound = false;
2233     for (unsigned I = StopAt + 1; I > 0; --I) {
2234       FunctionScopeInfo *FSI = FunctionScopes[I - 1];
2235       if (!isa<CapturingScopeInfo>(FSI))
2236         return nullptr;
2237       if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(FSI))
2238         if (RSI->CapRegionKind == CR_OpenMP) {
2239           OpenMPFound = true;
2240           break;
2241         }
2242     }
2243     if (!OpenMPFound)
2244       return nullptr;
2245   }
2246 
2247   if (DSAStack->getCurrentDirective() != OMPD_unknown &&
2248       (!DSAStack->isClauseParsingMode() ||
2249        DSAStack->getParentDirective() != OMPD_unknown)) {
2250     auto &&Info = DSAStack->isLoopControlVariable(D);
2251     if (Info.first ||
2252         (VD && VD->hasLocalStorage() &&
2253          isImplicitOrExplicitTaskingRegion(DSAStack->getCurrentDirective())) ||
2254         (VD && DSAStack->isForceVarCapturing()))
2255       return VD ? VD : Info.second;
2256     DSAStackTy::DSAVarData DVarTop =
2257         DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
2258     if (DVarTop.CKind != OMPC_unknown && isOpenMPPrivate(DVarTop.CKind) &&
2259         (!VD || VD->hasLocalStorage() || !DVarTop.AppliedToPointee))
2260       return VD ? VD : cast<VarDecl>(DVarTop.PrivateCopy->getDecl());
2261     // Threadprivate variables must not be captured.
2262     if (isOpenMPThreadPrivate(DVarTop.CKind))
2263       return nullptr;
2264     // The variable is not private or it is the variable in the directive with
2265     // default(none) clause and not used in any clause.
2266     DSAStackTy::DSAVarData DVarPrivate = DSAStack->hasDSA(
2267         D,
2268         [](OpenMPClauseKind C, bool AppliedToPointee) {
2269           return isOpenMPPrivate(C) && !AppliedToPointee;
2270         },
2271         [](OpenMPDirectiveKind) { return true; },
2272         DSAStack->isClauseParsingMode());
2273     // Global shared must not be captured.
2274     if (VD && !VD->hasLocalStorage() && DVarPrivate.CKind == OMPC_unknown &&
2275         ((DSAStack->getDefaultDSA() != DSA_none &&
2276           DSAStack->getDefaultDSA() != DSA_firstprivate) ||
2277          DVarTop.CKind == OMPC_shared))
2278       return nullptr;
2279     if (DVarPrivate.CKind != OMPC_unknown ||
2280         (VD && (DSAStack->getDefaultDSA() == DSA_none ||
2281                 DSAStack->getDefaultDSA() == DSA_firstprivate)))
2282       return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
2283   }
2284   return nullptr;
2285 }
2286 
2287 void Sema::adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex,
2288                                         unsigned Level) const {
2289   FunctionScopesIndex -= getOpenMPCaptureLevels(DSAStack->getDirective(Level));
2290 }
2291 
2292 void Sema::startOpenMPLoop() {
2293   assert(LangOpts.OpenMP && "OpenMP must be enabled.");
2294   if (isOpenMPLoopDirective(DSAStack->getCurrentDirective()))
2295     DSAStack->loopInit();
2296 }
2297 
2298 void Sema::startOpenMPCXXRangeFor() {
2299   assert(LangOpts.OpenMP && "OpenMP must be enabled.");
2300   if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
2301     DSAStack->resetPossibleLoopCounter();
2302     DSAStack->loopStart();
2303   }
2304 }
2305 
2306 OpenMPClauseKind Sema::isOpenMPPrivateDecl(ValueDecl *D, unsigned Level,
2307                                            unsigned CapLevel) const {
2308   assert(LangOpts.OpenMP && "OpenMP is not allowed");
2309   if (DSAStack->hasExplicitDirective(
2310           [](OpenMPDirectiveKind K) { return isOpenMPTaskingDirective(K); },
2311           Level)) {
2312     bool IsTriviallyCopyable =
2313         D->getType().getNonReferenceType().isTriviallyCopyableType(Context) &&
2314         !D->getType()
2315              .getNonReferenceType()
2316              .getCanonicalType()
2317              ->getAsCXXRecordDecl();
2318     OpenMPDirectiveKind DKind = DSAStack->getDirective(Level);
2319     SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
2320     getOpenMPCaptureRegions(CaptureRegions, DKind);
2321     if (isOpenMPTaskingDirective(CaptureRegions[CapLevel]) &&
2322         (IsTriviallyCopyable ||
2323          !isOpenMPTaskLoopDirective(CaptureRegions[CapLevel]))) {
2324       if (DSAStack->hasExplicitDSA(
2325               D,
2326               [](OpenMPClauseKind K, bool) { return K == OMPC_firstprivate; },
2327               Level, /*NotLastprivate=*/true))
2328         return OMPC_firstprivate;
2329       DSAStackTy::DSAVarData DVar = DSAStack->getImplicitDSA(D, Level);
2330       if (DVar.CKind != OMPC_shared &&
2331           !DSAStack->isLoopControlVariable(D, Level).first && !DVar.RefExpr) {
2332         DSAStack->addImplicitTaskFirstprivate(Level, D);
2333         return OMPC_firstprivate;
2334       }
2335     }
2336   }
2337   if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
2338     if (DSAStack->getAssociatedLoops() > 0 && !DSAStack->isLoopStarted()) {
2339       DSAStack->resetPossibleLoopCounter(D);
2340       DSAStack->loopStart();
2341       return OMPC_private;
2342     }
2343     if ((DSAStack->getPossiblyLoopCunter() == D->getCanonicalDecl() ||
2344          DSAStack->isLoopControlVariable(D).first) &&
2345         !DSAStack->hasExplicitDSA(
2346             D, [](OpenMPClauseKind K, bool) { return K != OMPC_private; },
2347             Level) &&
2348         !isOpenMPSimdDirective(DSAStack->getCurrentDirective()))
2349       return OMPC_private;
2350   }
2351   if (const auto *VD = dyn_cast<VarDecl>(D)) {
2352     if (DSAStack->isThreadPrivate(const_cast<VarDecl *>(VD)) &&
2353         DSAStack->isForceVarCapturing() &&
2354         !DSAStack->hasExplicitDSA(
2355             D, [](OpenMPClauseKind K, bool) { return K == OMPC_copyin; },
2356             Level))
2357       return OMPC_private;
2358   }
2359   // User-defined allocators are private since they must be defined in the
2360   // context of target region.
2361   if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level) &&
2362       DSAStack->isUsesAllocatorsDecl(Level, D).getValueOr(
2363           DSAStackTy::UsesAllocatorsDeclKind::AllocatorTrait) ==
2364           DSAStackTy::UsesAllocatorsDeclKind::UserDefinedAllocator)
2365     return OMPC_private;
2366   return (DSAStack->hasExplicitDSA(
2367               D, [](OpenMPClauseKind K, bool) { return K == OMPC_private; },
2368               Level) ||
2369           (DSAStack->isClauseParsingMode() &&
2370            DSAStack->getClauseParsingMode() == OMPC_private) ||
2371           // Consider taskgroup reduction descriptor variable a private
2372           // to avoid possible capture in the region.
2373           (DSAStack->hasExplicitDirective(
2374                [](OpenMPDirectiveKind K) {
2375                  return K == OMPD_taskgroup ||
2376                         ((isOpenMPParallelDirective(K) ||
2377                           isOpenMPWorksharingDirective(K)) &&
2378                          !isOpenMPSimdDirective(K));
2379                },
2380                Level) &&
2381            DSAStack->isTaskgroupReductionRef(D, Level)))
2382              ? OMPC_private
2383              : OMPC_unknown;
2384 }
2385 
2386 void Sema::setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D,
2387                                 unsigned Level) {
2388   assert(LangOpts.OpenMP && "OpenMP is not allowed");
2389   D = getCanonicalDecl(D);
2390   OpenMPClauseKind OMPC = OMPC_unknown;
2391   for (unsigned I = DSAStack->getNestingLevel() + 1; I > Level; --I) {
2392     const unsigned NewLevel = I - 1;
2393     if (DSAStack->hasExplicitDSA(
2394             D,
2395             [&OMPC](const OpenMPClauseKind K, bool AppliedToPointee) {
2396               if (isOpenMPPrivate(K) && !AppliedToPointee) {
2397                 OMPC = K;
2398                 return true;
2399               }
2400               return false;
2401             },
2402             NewLevel))
2403       break;
2404     if (DSAStack->checkMappableExprComponentListsForDeclAtLevel(
2405             D, NewLevel,
2406             [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
2407                OpenMPClauseKind) { return true; })) {
2408       OMPC = OMPC_map;
2409       break;
2410     }
2411     if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
2412                                        NewLevel)) {
2413       OMPC = OMPC_map;
2414       if (DSAStack->mustBeFirstprivateAtLevel(
2415               NewLevel, getVariableCategoryFromDecl(LangOpts, D)))
2416         OMPC = OMPC_firstprivate;
2417       break;
2418     }
2419   }
2420   if (OMPC != OMPC_unknown)
2421     FD->addAttr(OMPCaptureKindAttr::CreateImplicit(Context, unsigned(OMPC)));
2422 }
2423 
2424 bool Sema::isOpenMPTargetCapturedDecl(const ValueDecl *D, unsigned Level,
2425                                       unsigned CaptureLevel) const {
2426   assert(LangOpts.OpenMP && "OpenMP is not allowed");
2427   // Return true if the current level is no longer enclosed in a target region.
2428 
2429   SmallVector<OpenMPDirectiveKind, 4> Regions;
2430   getOpenMPCaptureRegions(Regions, DSAStack->getDirective(Level));
2431   const auto *VD = dyn_cast<VarDecl>(D);
2432   return VD && !VD->hasLocalStorage() &&
2433          DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
2434                                         Level) &&
2435          Regions[CaptureLevel] != OMPD_task;
2436 }
2437 
2438 bool Sema::isOpenMPGlobalCapturedDecl(ValueDecl *D, unsigned Level,
2439                                       unsigned CaptureLevel) const {
2440   assert(LangOpts.OpenMP && "OpenMP is not allowed");
2441   // Return true if the current level is no longer enclosed in a target region.
2442 
2443   if (const auto *VD = dyn_cast<VarDecl>(D)) {
2444     if (!VD->hasLocalStorage()) {
2445       if (isInOpenMPTargetExecutionDirective())
2446         return true;
2447       DSAStackTy::DSAVarData TopDVar =
2448           DSAStack->getTopDSA(D, /*FromParent=*/false);
2449       unsigned NumLevels =
2450           getOpenMPCaptureLevels(DSAStack->getDirective(Level));
2451       if (Level == 0)
2452         return (NumLevels == CaptureLevel + 1) && TopDVar.CKind != OMPC_shared;
2453       do {
2454         --Level;
2455         DSAStackTy::DSAVarData DVar = DSAStack->getImplicitDSA(D, Level);
2456         if (DVar.CKind != OMPC_shared)
2457           return true;
2458       } while (Level > 0);
2459     }
2460   }
2461   return true;
2462 }
2463 
2464 void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
2465 
2466 void Sema::ActOnOpenMPBeginDeclareVariant(SourceLocation Loc,
2467                                           OMPTraitInfo &TI) {
2468   OMPDeclareVariantScopes.push_back(OMPDeclareVariantScope(TI));
2469 }
2470 
2471 void Sema::ActOnOpenMPEndDeclareVariant() {
2472   assert(isInOpenMPDeclareVariantScope() &&
2473          "Not in OpenMP declare variant scope!");
2474 
2475   OMPDeclareVariantScopes.pop_back();
2476 }
2477 
2478 void Sema::finalizeOpenMPDelayedAnalysis(const FunctionDecl *Caller,
2479                                          const FunctionDecl *Callee,
2480                                          SourceLocation Loc) {
2481   assert(LangOpts.OpenMP && "Expected OpenMP compilation mode.");
2482   Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
2483       OMPDeclareTargetDeclAttr::getDeviceType(Caller->getMostRecentDecl());
2484   // Ignore host functions during device analyzis.
2485   if (LangOpts.OpenMPIsDevice &&
2486       (!DevTy || *DevTy == OMPDeclareTargetDeclAttr::DT_Host))
2487     return;
2488   // Ignore nohost functions during host analyzis.
2489   if (!LangOpts.OpenMPIsDevice && DevTy &&
2490       *DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
2491     return;
2492   const FunctionDecl *FD = Callee->getMostRecentDecl();
2493   DevTy = OMPDeclareTargetDeclAttr::getDeviceType(FD);
2494   if (LangOpts.OpenMPIsDevice && DevTy &&
2495       *DevTy == OMPDeclareTargetDeclAttr::DT_Host) {
2496     // Diagnose host function called during device codegen.
2497     StringRef HostDevTy =
2498         getOpenMPSimpleClauseTypeName(OMPC_device_type, OMPC_DEVICE_TYPE_host);
2499     Diag(Loc, diag::err_omp_wrong_device_function_call) << HostDevTy << 0;
2500     Diag(*OMPDeclareTargetDeclAttr::getLocation(FD),
2501          diag::note_omp_marked_device_type_here)
2502         << HostDevTy;
2503     return;
2504   }
2505   if (!LangOpts.OpenMPIsDevice && DevTy &&
2506       *DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) {
2507     // Diagnose nohost function called during host codegen.
2508     StringRef NoHostDevTy = getOpenMPSimpleClauseTypeName(
2509         OMPC_device_type, OMPC_DEVICE_TYPE_nohost);
2510     Diag(Loc, diag::err_omp_wrong_device_function_call) << NoHostDevTy << 1;
2511     Diag(*OMPDeclareTargetDeclAttr::getLocation(FD),
2512          diag::note_omp_marked_device_type_here)
2513         << NoHostDevTy;
2514   }
2515 }
2516 
2517 void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
2518                                const DeclarationNameInfo &DirName,
2519                                Scope *CurScope, SourceLocation Loc) {
2520   DSAStack->push(DKind, DirName, CurScope, Loc);
2521   PushExpressionEvaluationContext(
2522       ExpressionEvaluationContext::PotentiallyEvaluated);
2523 }
2524 
2525 void Sema::StartOpenMPClause(OpenMPClauseKind K) {
2526   DSAStack->setClauseParsingMode(K);
2527 }
2528 
2529 void Sema::EndOpenMPClause() {
2530   DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
2531   CleanupVarDeclMarking();
2532 }
2533 
2534 static std::pair<ValueDecl *, bool>
2535 getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
2536                SourceRange &ERange, bool AllowArraySection = false);
2537 
2538 /// Check consistency of the reduction clauses.
2539 static void checkReductionClauses(Sema &S, DSAStackTy *Stack,
2540                                   ArrayRef<OMPClause *> Clauses) {
2541   bool InscanFound = false;
2542   SourceLocation InscanLoc;
2543   // OpenMP 5.0, 2.19.5.4 reduction Clause, Restrictions.
2544   // A reduction clause without the inscan reduction-modifier may not appear on
2545   // a construct on which a reduction clause with the inscan reduction-modifier
2546   // appears.
2547   for (OMPClause *C : Clauses) {
2548     if (C->getClauseKind() != OMPC_reduction)
2549       continue;
2550     auto *RC = cast<OMPReductionClause>(C);
2551     if (RC->getModifier() == OMPC_REDUCTION_inscan) {
2552       InscanFound = true;
2553       InscanLoc = RC->getModifierLoc();
2554       continue;
2555     }
2556     if (RC->getModifier() == OMPC_REDUCTION_task) {
2557       // OpenMP 5.0, 2.19.5.4 reduction Clause.
2558       // A reduction clause with the task reduction-modifier may only appear on
2559       // a parallel construct, a worksharing construct or a combined or
2560       // composite construct for which any of the aforementioned constructs is a
2561       // constituent construct and simd or loop are not constituent constructs.
2562       OpenMPDirectiveKind CurDir = Stack->getCurrentDirective();
2563       if (!(isOpenMPParallelDirective(CurDir) ||
2564             isOpenMPWorksharingDirective(CurDir)) ||
2565           isOpenMPSimdDirective(CurDir))
2566         S.Diag(RC->getModifierLoc(),
2567                diag::err_omp_reduction_task_not_parallel_or_worksharing);
2568       continue;
2569     }
2570   }
2571   if (InscanFound) {
2572     for (OMPClause *C : Clauses) {
2573       if (C->getClauseKind() != OMPC_reduction)
2574         continue;
2575       auto *RC = cast<OMPReductionClause>(C);
2576       if (RC->getModifier() != OMPC_REDUCTION_inscan) {
2577         S.Diag(RC->getModifier() == OMPC_REDUCTION_unknown
2578                    ? RC->getBeginLoc()
2579                    : RC->getModifierLoc(),
2580                diag::err_omp_inscan_reduction_expected);
2581         S.Diag(InscanLoc, diag::note_omp_previous_inscan_reduction);
2582         continue;
2583       }
2584       for (Expr *Ref : RC->varlists()) {
2585         assert(Ref && "NULL expr in OpenMP nontemporal clause.");
2586         SourceLocation ELoc;
2587         SourceRange ERange;
2588         Expr *SimpleRefExpr = Ref;
2589         auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
2590                                   /*AllowArraySection=*/true);
2591         ValueDecl *D = Res.first;
2592         if (!D)
2593           continue;
2594         if (!Stack->isUsedInScanDirective(getCanonicalDecl(D))) {
2595           S.Diag(Ref->getExprLoc(),
2596                  diag::err_omp_reduction_not_inclusive_exclusive)
2597               << Ref->getSourceRange();
2598         }
2599       }
2600     }
2601   }
2602 }
2603 
2604 static void checkAllocateClauses(Sema &S, DSAStackTy *Stack,
2605                                  ArrayRef<OMPClause *> Clauses);
2606 static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
2607                                  bool WithInit);
2608 
2609 static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack,
2610                               const ValueDecl *D,
2611                               const DSAStackTy::DSAVarData &DVar,
2612                               bool IsLoopIterVar = false);
2613 
2614 void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
2615   // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
2616   //  A variable of class type (or array thereof) that appears in a lastprivate
2617   //  clause requires an accessible, unambiguous default constructor for the
2618   //  class type, unless the list item is also specified in a firstprivate
2619   //  clause.
2620   if (const auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
2621     for (OMPClause *C : D->clauses()) {
2622       if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
2623         SmallVector<Expr *, 8> PrivateCopies;
2624         for (Expr *DE : Clause->varlists()) {
2625           if (DE->isValueDependent() || DE->isTypeDependent()) {
2626             PrivateCopies.push_back(nullptr);
2627             continue;
2628           }
2629           auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
2630           auto *VD = cast<VarDecl>(DRE->getDecl());
2631           QualType Type = VD->getType().getNonReferenceType();
2632           const DSAStackTy::DSAVarData DVar =
2633               DSAStack->getTopDSA(VD, /*FromParent=*/false);
2634           if (DVar.CKind == OMPC_lastprivate) {
2635             // Generate helper private variable and initialize it with the
2636             // default value. The address of the original variable is replaced
2637             // by the address of the new private variable in CodeGen. This new
2638             // variable is not added to IdResolver, so the code in the OpenMP
2639             // region uses original variable for proper diagnostics.
2640             VarDecl *VDPrivate = buildVarDecl(
2641                 *this, DE->getExprLoc(), Type.getUnqualifiedType(),
2642                 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr, DRE);
2643             ActOnUninitializedDecl(VDPrivate);
2644             if (VDPrivate->isInvalidDecl()) {
2645               PrivateCopies.push_back(nullptr);
2646               continue;
2647             }
2648             PrivateCopies.push_back(buildDeclRefExpr(
2649                 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
2650           } else {
2651             // The variable is also a firstprivate, so initialization sequence
2652             // for private copy is generated already.
2653             PrivateCopies.push_back(nullptr);
2654           }
2655         }
2656         Clause->setPrivateCopies(PrivateCopies);
2657         continue;
2658       }
2659       // Finalize nontemporal clause by handling private copies, if any.
2660       if (auto *Clause = dyn_cast<OMPNontemporalClause>(C)) {
2661         SmallVector<Expr *, 8> PrivateRefs;
2662         for (Expr *RefExpr : Clause->varlists()) {
2663           assert(RefExpr && "NULL expr in OpenMP nontemporal clause.");
2664           SourceLocation ELoc;
2665           SourceRange ERange;
2666           Expr *SimpleRefExpr = RefExpr;
2667           auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
2668           if (Res.second)
2669             // It will be analyzed later.
2670             PrivateRefs.push_back(RefExpr);
2671           ValueDecl *D = Res.first;
2672           if (!D)
2673             continue;
2674 
2675           const DSAStackTy::DSAVarData DVar =
2676               DSAStack->getTopDSA(D, /*FromParent=*/false);
2677           PrivateRefs.push_back(DVar.PrivateCopy ? DVar.PrivateCopy
2678                                                  : SimpleRefExpr);
2679         }
2680         Clause->setPrivateRefs(PrivateRefs);
2681         continue;
2682       }
2683       if (auto *Clause = dyn_cast<OMPUsesAllocatorsClause>(C)) {
2684         for (unsigned I = 0, E = Clause->getNumberOfAllocators(); I < E; ++I) {
2685           OMPUsesAllocatorsClause::Data D = Clause->getAllocatorData(I);
2686           auto *DRE = dyn_cast<DeclRefExpr>(D.Allocator->IgnoreParenImpCasts());
2687           if (!DRE)
2688             continue;
2689           ValueDecl *VD = DRE->getDecl();
2690           if (!VD || !isa<VarDecl>(VD))
2691             continue;
2692           DSAStackTy::DSAVarData DVar =
2693               DSAStack->getTopDSA(VD, /*FromParent=*/false);
2694           // OpenMP [2.12.5, target Construct]
2695           // Memory allocators that appear in a uses_allocators clause cannot
2696           // appear in other data-sharing attribute clauses or data-mapping
2697           // attribute clauses in the same construct.
2698           Expr *MapExpr = nullptr;
2699           if (DVar.RefExpr ||
2700               DSAStack->checkMappableExprComponentListsForDecl(
2701                   VD, /*CurrentRegionOnly=*/true,
2702                   [VD, &MapExpr](
2703                       OMPClauseMappableExprCommon::MappableExprComponentListRef
2704                           MapExprComponents,
2705                       OpenMPClauseKind C) {
2706                     auto MI = MapExprComponents.rbegin();
2707                     auto ME = MapExprComponents.rend();
2708                     if (MI != ME &&
2709                         MI->getAssociatedDeclaration()->getCanonicalDecl() ==
2710                             VD->getCanonicalDecl()) {
2711                       MapExpr = MI->getAssociatedExpression();
2712                       return true;
2713                     }
2714                     return false;
2715                   })) {
2716             Diag(D.Allocator->getExprLoc(),
2717                  diag::err_omp_allocator_used_in_clauses)
2718                 << D.Allocator->getSourceRange();
2719             if (DVar.RefExpr)
2720               reportOriginalDsa(*this, DSAStack, VD, DVar);
2721             else
2722               Diag(MapExpr->getExprLoc(), diag::note_used_here)
2723                   << MapExpr->getSourceRange();
2724           }
2725         }
2726         continue;
2727       }
2728     }
2729     // Check allocate clauses.
2730     if (!CurContext->isDependentContext())
2731       checkAllocateClauses(*this, DSAStack, D->clauses());
2732     checkReductionClauses(*this, DSAStack, D->clauses());
2733   }
2734 
2735   DSAStack->pop();
2736   DiscardCleanupsInEvaluationContext();
2737   PopExpressionEvaluationContext();
2738 }
2739 
2740 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
2741                                      Expr *NumIterations, Sema &SemaRef,
2742                                      Scope *S, DSAStackTy *Stack);
2743 
2744 namespace {
2745 
2746 class VarDeclFilterCCC final : public CorrectionCandidateCallback {
2747 private:
2748   Sema &SemaRef;
2749 
2750 public:
2751   explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
2752   bool ValidateCandidate(const TypoCorrection &Candidate) override {
2753     NamedDecl *ND = Candidate.getCorrectionDecl();
2754     if (const auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
2755       return VD->hasGlobalStorage() &&
2756              SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
2757                                    SemaRef.getCurScope());
2758     }
2759     return false;
2760   }
2761 
2762   std::unique_ptr<CorrectionCandidateCallback> clone() override {
2763     return std::make_unique<VarDeclFilterCCC>(*this);
2764   }
2765 };
2766 
2767 class VarOrFuncDeclFilterCCC final : public CorrectionCandidateCallback {
2768 private:
2769   Sema &SemaRef;
2770 
2771 public:
2772   explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
2773   bool ValidateCandidate(const TypoCorrection &Candidate) override {
2774     NamedDecl *ND = Candidate.getCorrectionDecl();
2775     if (ND && ((isa<VarDecl>(ND) && ND->getKind() == Decl::Var) ||
2776                isa<FunctionDecl>(ND))) {
2777       return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
2778                                    SemaRef.getCurScope());
2779     }
2780     return false;
2781   }
2782 
2783   std::unique_ptr<CorrectionCandidateCallback> clone() override {
2784     return std::make_unique<VarOrFuncDeclFilterCCC>(*this);
2785   }
2786 };
2787 
2788 } // namespace
2789 
2790 ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
2791                                          CXXScopeSpec &ScopeSpec,
2792                                          const DeclarationNameInfo &Id,
2793                                          OpenMPDirectiveKind Kind) {
2794   LookupResult Lookup(*this, Id, LookupOrdinaryName);
2795   LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
2796 
2797   if (Lookup.isAmbiguous())
2798     return ExprError();
2799 
2800   VarDecl *VD;
2801   if (!Lookup.isSingleResult()) {
2802     VarDeclFilterCCC CCC(*this);
2803     if (TypoCorrection Corrected =
2804             CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC,
2805                         CTK_ErrorRecovery)) {
2806       diagnoseTypo(Corrected,
2807                    PDiag(Lookup.empty()
2808                              ? diag::err_undeclared_var_use_suggest
2809                              : diag::err_omp_expected_var_arg_suggest)
2810                        << Id.getName());
2811       VD = Corrected.getCorrectionDeclAs<VarDecl>();
2812     } else {
2813       Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
2814                                        : diag::err_omp_expected_var_arg)
2815           << Id.getName();
2816       return ExprError();
2817     }
2818   } else if (!(VD = Lookup.getAsSingle<VarDecl>())) {
2819     Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
2820     Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
2821     return ExprError();
2822   }
2823   Lookup.suppressDiagnostics();
2824 
2825   // OpenMP [2.9.2, Syntax, C/C++]
2826   //   Variables must be file-scope, namespace-scope, or static block-scope.
2827   if (Kind == OMPD_threadprivate && !VD->hasGlobalStorage()) {
2828     Diag(Id.getLoc(), diag::err_omp_global_var_arg)
2829         << getOpenMPDirectiveName(Kind) << !VD->isStaticLocal();
2830     bool IsDecl =
2831         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2832     Diag(VD->getLocation(),
2833          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2834         << VD;
2835     return ExprError();
2836   }
2837 
2838   VarDecl *CanonicalVD = VD->getCanonicalDecl();
2839   NamedDecl *ND = CanonicalVD;
2840   // OpenMP [2.9.2, Restrictions, C/C++, p.2]
2841   //   A threadprivate directive for file-scope variables must appear outside
2842   //   any definition or declaration.
2843   if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
2844       !getCurLexicalContext()->isTranslationUnit()) {
2845     Diag(Id.getLoc(), diag::err_omp_var_scope)
2846         << getOpenMPDirectiveName(Kind) << VD;
2847     bool IsDecl =
2848         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2849     Diag(VD->getLocation(),
2850          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2851         << VD;
2852     return ExprError();
2853   }
2854   // OpenMP [2.9.2, Restrictions, C/C++, p.3]
2855   //   A threadprivate directive for static class member variables must appear
2856   //   in the class definition, in the same scope in which the member
2857   //   variables are declared.
2858   if (CanonicalVD->isStaticDataMember() &&
2859       !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
2860     Diag(Id.getLoc(), diag::err_omp_var_scope)
2861         << getOpenMPDirectiveName(Kind) << VD;
2862     bool IsDecl =
2863         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2864     Diag(VD->getLocation(),
2865          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2866         << VD;
2867     return ExprError();
2868   }
2869   // OpenMP [2.9.2, Restrictions, C/C++, p.4]
2870   //   A threadprivate directive for namespace-scope variables must appear
2871   //   outside any definition or declaration other than the namespace
2872   //   definition itself.
2873   if (CanonicalVD->getDeclContext()->isNamespace() &&
2874       (!getCurLexicalContext()->isFileContext() ||
2875        !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
2876     Diag(Id.getLoc(), diag::err_omp_var_scope)
2877         << getOpenMPDirectiveName(Kind) << VD;
2878     bool IsDecl =
2879         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2880     Diag(VD->getLocation(),
2881          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2882         << VD;
2883     return ExprError();
2884   }
2885   // OpenMP [2.9.2, Restrictions, C/C++, p.6]
2886   //   A threadprivate directive for static block-scope variables must appear
2887   //   in the scope of the variable and not in a nested scope.
2888   if (CanonicalVD->isLocalVarDecl() && CurScope &&
2889       !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
2890     Diag(Id.getLoc(), diag::err_omp_var_scope)
2891         << getOpenMPDirectiveName(Kind) << VD;
2892     bool IsDecl =
2893         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2894     Diag(VD->getLocation(),
2895          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2896         << VD;
2897     return ExprError();
2898   }
2899 
2900   // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
2901   //   A threadprivate directive must lexically precede all references to any
2902   //   of the variables in its list.
2903   if (Kind == OMPD_threadprivate && VD->isUsed() &&
2904       !DSAStack->isThreadPrivate(VD)) {
2905     Diag(Id.getLoc(), diag::err_omp_var_used)
2906         << getOpenMPDirectiveName(Kind) << VD;
2907     return ExprError();
2908   }
2909 
2910   QualType ExprType = VD->getType().getNonReferenceType();
2911   return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
2912                              SourceLocation(), VD,
2913                              /*RefersToEnclosingVariableOrCapture=*/false,
2914                              Id.getLoc(), ExprType, VK_LValue);
2915 }
2916 
2917 Sema::DeclGroupPtrTy
2918 Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
2919                                         ArrayRef<Expr *> VarList) {
2920   if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
2921     CurContext->addDecl(D);
2922     return DeclGroupPtrTy::make(DeclGroupRef(D));
2923   }
2924   return nullptr;
2925 }
2926 
2927 namespace {
2928 class LocalVarRefChecker final
2929     : public ConstStmtVisitor<LocalVarRefChecker, bool> {
2930   Sema &SemaRef;
2931 
2932 public:
2933   bool VisitDeclRefExpr(const DeclRefExpr *E) {
2934     if (const auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
2935       if (VD->hasLocalStorage()) {
2936         SemaRef.Diag(E->getBeginLoc(),
2937                      diag::err_omp_local_var_in_threadprivate_init)
2938             << E->getSourceRange();
2939         SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
2940             << VD << VD->getSourceRange();
2941         return true;
2942       }
2943     }
2944     return false;
2945   }
2946   bool VisitStmt(const Stmt *S) {
2947     for (const Stmt *Child : S->children()) {
2948       if (Child && Visit(Child))
2949         return true;
2950     }
2951     return false;
2952   }
2953   explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
2954 };
2955 } // namespace
2956 
2957 OMPThreadPrivateDecl *
2958 Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
2959   SmallVector<Expr *, 8> Vars;
2960   for (Expr *RefExpr : VarList) {
2961     auto *DE = cast<DeclRefExpr>(RefExpr);
2962     auto *VD = cast<VarDecl>(DE->getDecl());
2963     SourceLocation ILoc = DE->getExprLoc();
2964 
2965     // Mark variable as used.
2966     VD->setReferenced();
2967     VD->markUsed(Context);
2968 
2969     QualType QType = VD->getType();
2970     if (QType->isDependentType() || QType->isInstantiationDependentType()) {
2971       // It will be analyzed later.
2972       Vars.push_back(DE);
2973       continue;
2974     }
2975 
2976     // OpenMP [2.9.2, Restrictions, C/C++, p.10]
2977     //   A threadprivate variable must not have an incomplete type.
2978     if (RequireCompleteType(ILoc, VD->getType(),
2979                             diag::err_omp_threadprivate_incomplete_type)) {
2980       continue;
2981     }
2982 
2983     // OpenMP [2.9.2, Restrictions, C/C++, p.10]
2984     //   A threadprivate variable must not have a reference type.
2985     if (VD->getType()->isReferenceType()) {
2986       Diag(ILoc, diag::err_omp_ref_type_arg)
2987           << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
2988       bool IsDecl =
2989           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2990       Diag(VD->getLocation(),
2991            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2992           << VD;
2993       continue;
2994     }
2995 
2996     // Check if this is a TLS variable. If TLS is not being supported, produce
2997     // the corresponding diagnostic.
2998     if ((VD->getTLSKind() != VarDecl::TLS_None &&
2999          !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
3000            getLangOpts().OpenMPUseTLS &&
3001            getASTContext().getTargetInfo().isTLSSupported())) ||
3002         (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
3003          !VD->isLocalVarDecl())) {
3004       Diag(ILoc, diag::err_omp_var_thread_local)
3005           << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
3006       bool IsDecl =
3007           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
3008       Diag(VD->getLocation(),
3009            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
3010           << VD;
3011       continue;
3012     }
3013 
3014     // Check if initial value of threadprivate variable reference variable with
3015     // local storage (it is not supported by runtime).
3016     if (const Expr *Init = VD->getAnyInitializer()) {
3017       LocalVarRefChecker Checker(*this);
3018       if (Checker.Visit(Init))
3019         continue;
3020     }
3021 
3022     Vars.push_back(RefExpr);
3023     DSAStack->addDSA(VD, DE, OMPC_threadprivate);
3024     VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
3025         Context, SourceRange(Loc, Loc)));
3026     if (ASTMutationListener *ML = Context.getASTMutationListener())
3027       ML->DeclarationMarkedOpenMPThreadPrivate(VD);
3028   }
3029   OMPThreadPrivateDecl *D = nullptr;
3030   if (!Vars.empty()) {
3031     D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
3032                                      Vars);
3033     D->setAccess(AS_public);
3034   }
3035   return D;
3036 }
3037 
3038 static OMPAllocateDeclAttr::AllocatorTypeTy
3039 getAllocatorKind(Sema &S, DSAStackTy *Stack, Expr *Allocator) {
3040   if (!Allocator)
3041     return OMPAllocateDeclAttr::OMPNullMemAlloc;
3042   if (Allocator->isTypeDependent() || Allocator->isValueDependent() ||
3043       Allocator->isInstantiationDependent() ||
3044       Allocator->containsUnexpandedParameterPack())
3045     return OMPAllocateDeclAttr::OMPUserDefinedMemAlloc;
3046   auto AllocatorKindRes = OMPAllocateDeclAttr::OMPUserDefinedMemAlloc;
3047   const Expr *AE = Allocator->IgnoreParenImpCasts();
3048   for (int I = 0; I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
3049     auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
3050     const Expr *DefAllocator = Stack->getAllocator(AllocatorKind);
3051     llvm::FoldingSetNodeID AEId, DAEId;
3052     AE->Profile(AEId, S.getASTContext(), /*Canonical=*/true);
3053     DefAllocator->Profile(DAEId, S.getASTContext(), /*Canonical=*/true);
3054     if (AEId == DAEId) {
3055       AllocatorKindRes = AllocatorKind;
3056       break;
3057     }
3058   }
3059   return AllocatorKindRes;
3060 }
3061 
3062 static bool checkPreviousOMPAllocateAttribute(
3063     Sema &S, DSAStackTy *Stack, Expr *RefExpr, VarDecl *VD,
3064     OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind, Expr *Allocator) {
3065   if (!VD->hasAttr<OMPAllocateDeclAttr>())
3066     return false;
3067   const auto *A = VD->getAttr<OMPAllocateDeclAttr>();
3068   Expr *PrevAllocator = A->getAllocator();
3069   OMPAllocateDeclAttr::AllocatorTypeTy PrevAllocatorKind =
3070       getAllocatorKind(S, Stack, PrevAllocator);
3071   bool AllocatorsMatch = AllocatorKind == PrevAllocatorKind;
3072   if (AllocatorsMatch &&
3073       AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc &&
3074       Allocator && PrevAllocator) {
3075     const Expr *AE = Allocator->IgnoreParenImpCasts();
3076     const Expr *PAE = PrevAllocator->IgnoreParenImpCasts();
3077     llvm::FoldingSetNodeID AEId, PAEId;
3078     AE->Profile(AEId, S.Context, /*Canonical=*/true);
3079     PAE->Profile(PAEId, S.Context, /*Canonical=*/true);
3080     AllocatorsMatch = AEId == PAEId;
3081   }
3082   if (!AllocatorsMatch) {
3083     SmallString<256> AllocatorBuffer;
3084     llvm::raw_svector_ostream AllocatorStream(AllocatorBuffer);
3085     if (Allocator)
3086       Allocator->printPretty(AllocatorStream, nullptr, S.getPrintingPolicy());
3087     SmallString<256> PrevAllocatorBuffer;
3088     llvm::raw_svector_ostream PrevAllocatorStream(PrevAllocatorBuffer);
3089     if (PrevAllocator)
3090       PrevAllocator->printPretty(PrevAllocatorStream, nullptr,
3091                                  S.getPrintingPolicy());
3092 
3093     SourceLocation AllocatorLoc =
3094         Allocator ? Allocator->getExprLoc() : RefExpr->getExprLoc();
3095     SourceRange AllocatorRange =
3096         Allocator ? Allocator->getSourceRange() : RefExpr->getSourceRange();
3097     SourceLocation PrevAllocatorLoc =
3098         PrevAllocator ? PrevAllocator->getExprLoc() : A->getLocation();
3099     SourceRange PrevAllocatorRange =
3100         PrevAllocator ? PrevAllocator->getSourceRange() : A->getRange();
3101     S.Diag(AllocatorLoc, diag::warn_omp_used_different_allocator)
3102         << (Allocator ? 1 : 0) << AllocatorStream.str()
3103         << (PrevAllocator ? 1 : 0) << PrevAllocatorStream.str()
3104         << AllocatorRange;
3105     S.Diag(PrevAllocatorLoc, diag::note_omp_previous_allocator)
3106         << PrevAllocatorRange;
3107     return true;
3108   }
3109   return false;
3110 }
3111 
3112 static void
3113 applyOMPAllocateAttribute(Sema &S, VarDecl *VD,
3114                           OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind,
3115                           Expr *Allocator, Expr *Alignment, SourceRange SR) {
3116   if (VD->hasAttr<OMPAllocateDeclAttr>())
3117     return;
3118   if (Alignment &&
3119       (Alignment->isTypeDependent() || Alignment->isValueDependent() ||
3120        Alignment->isInstantiationDependent() ||
3121        Alignment->containsUnexpandedParameterPack()))
3122     // Apply later when we have a usable value.
3123     return;
3124   if (Allocator &&
3125       (Allocator->isTypeDependent() || Allocator->isValueDependent() ||
3126        Allocator->isInstantiationDependent() ||
3127        Allocator->containsUnexpandedParameterPack()))
3128     return;
3129   auto *A = OMPAllocateDeclAttr::CreateImplicit(S.Context, AllocatorKind,
3130                                                 Allocator, Alignment, SR);
3131   VD->addAttr(A);
3132   if (ASTMutationListener *ML = S.Context.getASTMutationListener())
3133     ML->DeclarationMarkedOpenMPAllocate(VD, A);
3134 }
3135 
3136 Sema::DeclGroupPtrTy
3137 Sema::ActOnOpenMPAllocateDirective(SourceLocation Loc, ArrayRef<Expr *> VarList,
3138                                    ArrayRef<OMPClause *> Clauses,
3139                                    DeclContext *Owner) {
3140   assert(Clauses.size() <= 2 && "Expected at most two clauses.");
3141   Expr *Alignment = nullptr;
3142   Expr *Allocator = nullptr;
3143   if (Clauses.empty()) {
3144     // OpenMP 5.0, 2.11.3 allocate Directive, Restrictions.
3145     // allocate directives that appear in a target region must specify an
3146     // allocator clause unless a requires directive with the dynamic_allocators
3147     // clause is present in the same compilation unit.
3148     if (LangOpts.OpenMPIsDevice &&
3149         !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())
3150       targetDiag(Loc, diag::err_expected_allocator_clause);
3151   } else {
3152     for (const OMPClause *C : Clauses)
3153       if (const auto *AC = dyn_cast<OMPAllocatorClause>(C))
3154         Allocator = AC->getAllocator();
3155       else if (const auto *AC = dyn_cast<OMPAlignClause>(C))
3156         Alignment = AC->getAlignment();
3157       else
3158         llvm_unreachable("Unexpected clause on allocate directive");
3159   }
3160   OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind =
3161       getAllocatorKind(*this, DSAStack, Allocator);
3162   SmallVector<Expr *, 8> Vars;
3163   for (Expr *RefExpr : VarList) {
3164     auto *DE = cast<DeclRefExpr>(RefExpr);
3165     auto *VD = cast<VarDecl>(DE->getDecl());
3166 
3167     // Check if this is a TLS variable or global register.
3168     if (VD->getTLSKind() != VarDecl::TLS_None ||
3169         VD->hasAttr<OMPThreadPrivateDeclAttr>() ||
3170         (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
3171          !VD->isLocalVarDecl()))
3172       continue;
3173 
3174     // If the used several times in the allocate directive, the same allocator
3175     // must be used.
3176     if (checkPreviousOMPAllocateAttribute(*this, DSAStack, RefExpr, VD,
3177                                           AllocatorKind, Allocator))
3178       continue;
3179 
3180     // OpenMP, 2.11.3 allocate Directive, Restrictions, C / C++
3181     // If a list item has a static storage type, the allocator expression in the
3182     // allocator clause must be a constant expression that evaluates to one of
3183     // the predefined memory allocator values.
3184     if (Allocator && VD->hasGlobalStorage()) {
3185       if (AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc) {
3186         Diag(Allocator->getExprLoc(),
3187              diag::err_omp_expected_predefined_allocator)
3188             << Allocator->getSourceRange();
3189         bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
3190                       VarDecl::DeclarationOnly;
3191         Diag(VD->getLocation(),
3192              IsDecl ? diag::note_previous_decl : diag::note_defined_here)
3193             << VD;
3194         continue;
3195       }
3196     }
3197 
3198     Vars.push_back(RefExpr);
3199     applyOMPAllocateAttribute(*this, VD, AllocatorKind, Allocator, Alignment,
3200                               DE->getSourceRange());
3201   }
3202   if (Vars.empty())
3203     return nullptr;
3204   if (!Owner)
3205     Owner = getCurLexicalContext();
3206   auto *D = OMPAllocateDecl::Create(Context, Owner, Loc, Vars, Clauses);
3207   D->setAccess(AS_public);
3208   Owner->addDecl(D);
3209   return DeclGroupPtrTy::make(DeclGroupRef(D));
3210 }
3211 
3212 Sema::DeclGroupPtrTy
3213 Sema::ActOnOpenMPRequiresDirective(SourceLocation Loc,
3214                                    ArrayRef<OMPClause *> ClauseList) {
3215   OMPRequiresDecl *D = nullptr;
3216   if (!CurContext->isFileContext()) {
3217     Diag(Loc, diag::err_omp_invalid_scope) << "requires";
3218   } else {
3219     D = CheckOMPRequiresDecl(Loc, ClauseList);
3220     if (D) {
3221       CurContext->addDecl(D);
3222       DSAStack->addRequiresDecl(D);
3223     }
3224   }
3225   return DeclGroupPtrTy::make(DeclGroupRef(D));
3226 }
3227 
3228 void Sema::ActOnOpenMPAssumesDirective(SourceLocation Loc,
3229                                        OpenMPDirectiveKind DKind,
3230                                        ArrayRef<std::string> Assumptions,
3231                                        bool SkippedClauses) {
3232   if (!SkippedClauses && Assumptions.empty())
3233     Diag(Loc, diag::err_omp_no_clause_for_directive)
3234         << llvm::omp::getAllAssumeClauseOptions()
3235         << llvm::omp::getOpenMPDirectiveName(DKind);
3236 
3237   auto *AA = AssumptionAttr::Create(Context, llvm::join(Assumptions, ","), Loc);
3238   if (DKind == llvm::omp::Directive::OMPD_begin_assumes) {
3239     OMPAssumeScoped.push_back(AA);
3240     return;
3241   }
3242 
3243   // Global assumes without assumption clauses are ignored.
3244   if (Assumptions.empty())
3245     return;
3246 
3247   assert(DKind == llvm::omp::Directive::OMPD_assumes &&
3248          "Unexpected omp assumption directive!");
3249   OMPAssumeGlobal.push_back(AA);
3250 
3251   // The OMPAssumeGlobal scope above will take care of new declarations but
3252   // we also want to apply the assumption to existing ones, e.g., to
3253   // declarations in included headers. To this end, we traverse all existing
3254   // declaration contexts and annotate function declarations here.
3255   SmallVector<DeclContext *, 8> DeclContexts;
3256   auto *Ctx = CurContext;
3257   while (Ctx->getLexicalParent())
3258     Ctx = Ctx->getLexicalParent();
3259   DeclContexts.push_back(Ctx);
3260   while (!DeclContexts.empty()) {
3261     DeclContext *DC = DeclContexts.pop_back_val();
3262     for (auto *SubDC : DC->decls()) {
3263       if (SubDC->isInvalidDecl())
3264         continue;
3265       if (auto *CTD = dyn_cast<ClassTemplateDecl>(SubDC)) {
3266         DeclContexts.push_back(CTD->getTemplatedDecl());
3267         for (auto *S : CTD->specializations())
3268           DeclContexts.push_back(S);
3269         continue;
3270       }
3271       if (auto *DC = dyn_cast<DeclContext>(SubDC))
3272         DeclContexts.push_back(DC);
3273       if (auto *F = dyn_cast<FunctionDecl>(SubDC)) {
3274         F->addAttr(AA);
3275         continue;
3276       }
3277     }
3278   }
3279 }
3280 
3281 void Sema::ActOnOpenMPEndAssumesDirective() {
3282   assert(isInOpenMPAssumeScope() && "Not in OpenMP assumes scope!");
3283   OMPAssumeScoped.pop_back();
3284 }
3285 
3286 OMPRequiresDecl *Sema::CheckOMPRequiresDecl(SourceLocation Loc,
3287                                             ArrayRef<OMPClause *> ClauseList) {
3288   /// For target specific clauses, the requires directive cannot be
3289   /// specified after the handling of any of the target regions in the
3290   /// current compilation unit.
3291   ArrayRef<SourceLocation> TargetLocations =
3292       DSAStack->getEncounteredTargetLocs();
3293   SourceLocation AtomicLoc = DSAStack->getAtomicDirectiveLoc();
3294   if (!TargetLocations.empty() || !AtomicLoc.isInvalid()) {
3295     for (const OMPClause *CNew : ClauseList) {
3296       // Check if any of the requires clauses affect target regions.
3297       if (isa<OMPUnifiedSharedMemoryClause>(CNew) ||
3298           isa<OMPUnifiedAddressClause>(CNew) ||
3299           isa<OMPReverseOffloadClause>(CNew) ||
3300           isa<OMPDynamicAllocatorsClause>(CNew)) {
3301         Diag(Loc, diag::err_omp_directive_before_requires)
3302             << "target" << getOpenMPClauseName(CNew->getClauseKind());
3303         for (SourceLocation TargetLoc : TargetLocations) {
3304           Diag(TargetLoc, diag::note_omp_requires_encountered_directive)
3305               << "target";
3306         }
3307       } else if (!AtomicLoc.isInvalid() &&
3308                  isa<OMPAtomicDefaultMemOrderClause>(CNew)) {
3309         Diag(Loc, diag::err_omp_directive_before_requires)
3310             << "atomic" << getOpenMPClauseName(CNew->getClauseKind());
3311         Diag(AtomicLoc, diag::note_omp_requires_encountered_directive)
3312             << "atomic";
3313       }
3314     }
3315   }
3316 
3317   if (!DSAStack->hasDuplicateRequiresClause(ClauseList))
3318     return OMPRequiresDecl::Create(Context, getCurLexicalContext(), Loc,
3319                                    ClauseList);
3320   return nullptr;
3321 }
3322 
3323 static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack,
3324                               const ValueDecl *D,
3325                               const DSAStackTy::DSAVarData &DVar,
3326                               bool IsLoopIterVar) {
3327   if (DVar.RefExpr) {
3328     SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
3329         << getOpenMPClauseName(DVar.CKind);
3330     return;
3331   }
3332   enum {
3333     PDSA_StaticMemberShared,
3334     PDSA_StaticLocalVarShared,
3335     PDSA_LoopIterVarPrivate,
3336     PDSA_LoopIterVarLinear,
3337     PDSA_LoopIterVarLastprivate,
3338     PDSA_ConstVarShared,
3339     PDSA_GlobalVarShared,
3340     PDSA_TaskVarFirstprivate,
3341     PDSA_LocalVarPrivate,
3342     PDSA_Implicit
3343   } Reason = PDSA_Implicit;
3344   bool ReportHint = false;
3345   auto ReportLoc = D->getLocation();
3346   auto *VD = dyn_cast<VarDecl>(D);
3347   if (IsLoopIterVar) {
3348     if (DVar.CKind == OMPC_private)
3349       Reason = PDSA_LoopIterVarPrivate;
3350     else if (DVar.CKind == OMPC_lastprivate)
3351       Reason = PDSA_LoopIterVarLastprivate;
3352     else
3353       Reason = PDSA_LoopIterVarLinear;
3354   } else if (isOpenMPTaskingDirective(DVar.DKind) &&
3355              DVar.CKind == OMPC_firstprivate) {
3356     Reason = PDSA_TaskVarFirstprivate;
3357     ReportLoc = DVar.ImplicitDSALoc;
3358   } else if (VD && VD->isStaticLocal())
3359     Reason = PDSA_StaticLocalVarShared;
3360   else if (VD && VD->isStaticDataMember())
3361     Reason = PDSA_StaticMemberShared;
3362   else if (VD && VD->isFileVarDecl())
3363     Reason = PDSA_GlobalVarShared;
3364   else if (D->getType().isConstant(SemaRef.getASTContext()))
3365     Reason = PDSA_ConstVarShared;
3366   else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
3367     ReportHint = true;
3368     Reason = PDSA_LocalVarPrivate;
3369   }
3370   if (Reason != PDSA_Implicit) {
3371     SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
3372         << Reason << ReportHint
3373         << getOpenMPDirectiveName(Stack->getCurrentDirective());
3374   } else if (DVar.ImplicitDSALoc.isValid()) {
3375     SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
3376         << getOpenMPClauseName(DVar.CKind);
3377   }
3378 }
3379 
3380 static OpenMPMapClauseKind
3381 getMapClauseKindFromModifier(OpenMPDefaultmapClauseModifier M,
3382                              bool IsAggregateOrDeclareTarget) {
3383   OpenMPMapClauseKind Kind = OMPC_MAP_unknown;
3384   switch (M) {
3385   case OMPC_DEFAULTMAP_MODIFIER_alloc:
3386     Kind = OMPC_MAP_alloc;
3387     break;
3388   case OMPC_DEFAULTMAP_MODIFIER_to:
3389     Kind = OMPC_MAP_to;
3390     break;
3391   case OMPC_DEFAULTMAP_MODIFIER_from:
3392     Kind = OMPC_MAP_from;
3393     break;
3394   case OMPC_DEFAULTMAP_MODIFIER_tofrom:
3395     Kind = OMPC_MAP_tofrom;
3396     break;
3397   case OMPC_DEFAULTMAP_MODIFIER_present:
3398     // OpenMP 5.1 [2.21.7.3] defaultmap clause, Description]
3399     // If implicit-behavior is present, each variable referenced in the
3400     // construct in the category specified by variable-category is treated as if
3401     // it had been listed in a map clause with the map-type of alloc and
3402     // map-type-modifier of present.
3403     Kind = OMPC_MAP_alloc;
3404     break;
3405   case OMPC_DEFAULTMAP_MODIFIER_firstprivate:
3406   case OMPC_DEFAULTMAP_MODIFIER_last:
3407     llvm_unreachable("Unexpected defaultmap implicit behavior");
3408   case OMPC_DEFAULTMAP_MODIFIER_none:
3409   case OMPC_DEFAULTMAP_MODIFIER_default:
3410   case OMPC_DEFAULTMAP_MODIFIER_unknown:
3411     // IsAggregateOrDeclareTarget could be true if:
3412     // 1. the implicit behavior for aggregate is tofrom
3413     // 2. it's a declare target link
3414     if (IsAggregateOrDeclareTarget) {
3415       Kind = OMPC_MAP_tofrom;
3416       break;
3417     }
3418     llvm_unreachable("Unexpected defaultmap implicit behavior");
3419   }
3420   assert(Kind != OMPC_MAP_unknown && "Expect map kind to be known");
3421   return Kind;
3422 }
3423 
3424 namespace {
3425 class DSAAttrChecker final : public StmtVisitor<DSAAttrChecker, void> {
3426   DSAStackTy *Stack;
3427   Sema &SemaRef;
3428   bool ErrorFound = false;
3429   bool TryCaptureCXXThisMembers = false;
3430   CapturedStmt *CS = nullptr;
3431   const static unsigned DefaultmapKindNum = OMPC_DEFAULTMAP_pointer + 1;
3432   llvm::SmallVector<Expr *, 4> ImplicitFirstprivate;
3433   llvm::SmallVector<Expr *, 4> ImplicitMap[DefaultmapKindNum][OMPC_MAP_delete];
3434   llvm::SmallVector<OpenMPMapModifierKind, NumberOfOMPMapClauseModifiers>
3435       ImplicitMapModifier[DefaultmapKindNum];
3436   Sema::VarsWithInheritedDSAType VarsWithInheritedDSA;
3437   llvm::SmallDenseSet<const ValueDecl *, 4> ImplicitDeclarations;
3438 
3439   void VisitSubCaptures(OMPExecutableDirective *S) {
3440     // Check implicitly captured variables.
3441     if (!S->hasAssociatedStmt() || !S->getAssociatedStmt())
3442       return;
3443     if (S->getDirectiveKind() == OMPD_atomic ||
3444         S->getDirectiveKind() == OMPD_critical ||
3445         S->getDirectiveKind() == OMPD_section ||
3446         S->getDirectiveKind() == OMPD_master ||
3447         S->getDirectiveKind() == OMPD_masked ||
3448         isOpenMPLoopTransformationDirective(S->getDirectiveKind())) {
3449       Visit(S->getAssociatedStmt());
3450       return;
3451     }
3452     visitSubCaptures(S->getInnermostCapturedStmt());
3453     // Try to capture inner this->member references to generate correct mappings
3454     // and diagnostics.
3455     if (TryCaptureCXXThisMembers ||
3456         (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
3457          llvm::any_of(S->getInnermostCapturedStmt()->captures(),
3458                       [](const CapturedStmt::Capture &C) {
3459                         return C.capturesThis();
3460                       }))) {
3461       bool SavedTryCaptureCXXThisMembers = TryCaptureCXXThisMembers;
3462       TryCaptureCXXThisMembers = true;
3463       Visit(S->getInnermostCapturedStmt()->getCapturedStmt());
3464       TryCaptureCXXThisMembers = SavedTryCaptureCXXThisMembers;
3465     }
3466     // In tasks firstprivates are not captured anymore, need to analyze them
3467     // explicitly.
3468     if (isOpenMPTaskingDirective(S->getDirectiveKind()) &&
3469         !isOpenMPTaskLoopDirective(S->getDirectiveKind())) {
3470       for (OMPClause *C : S->clauses())
3471         if (auto *FC = dyn_cast<OMPFirstprivateClause>(C)) {
3472           for (Expr *Ref : FC->varlists())
3473             Visit(Ref);
3474         }
3475     }
3476   }
3477 
3478 public:
3479   void VisitDeclRefExpr(DeclRefExpr *E) {
3480     if (TryCaptureCXXThisMembers || E->isTypeDependent() ||
3481         E->isValueDependent() || E->containsUnexpandedParameterPack() ||
3482         E->isInstantiationDependent())
3483       return;
3484     if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
3485       // Check the datasharing rules for the expressions in the clauses.
3486       if (!CS || (isa<OMPCapturedExprDecl>(VD) && !CS->capturesVariable(VD) &&
3487                   !Stack->getTopDSA(VD, /*FromParent=*/false).RefExpr)) {
3488         if (auto *CED = dyn_cast<OMPCapturedExprDecl>(VD))
3489           if (!CED->hasAttr<OMPCaptureNoInitAttr>()) {
3490             Visit(CED->getInit());
3491             return;
3492           }
3493       } else if (VD->isImplicit() || isa<OMPCapturedExprDecl>(VD))
3494         // Do not analyze internal variables and do not enclose them into
3495         // implicit clauses.
3496         return;
3497       VD = VD->getCanonicalDecl();
3498       // Skip internally declared variables.
3499       if (VD->hasLocalStorage() && CS && !CS->capturesVariable(VD) &&
3500           !Stack->isImplicitTaskFirstprivate(VD))
3501         return;
3502       // Skip allocators in uses_allocators clauses.
3503       if (Stack->isUsesAllocatorsDecl(VD).hasValue())
3504         return;
3505 
3506       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
3507       // Check if the variable has explicit DSA set and stop analysis if it so.
3508       if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second)
3509         return;
3510 
3511       // Skip internally declared static variables.
3512       llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
3513           OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
3514       if (VD->hasGlobalStorage() && CS && !CS->capturesVariable(VD) &&
3515           (Stack->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() ||
3516            !Res || *Res != OMPDeclareTargetDeclAttr::MT_Link) &&
3517           !Stack->isImplicitTaskFirstprivate(VD))
3518         return;
3519 
3520       SourceLocation ELoc = E->getExprLoc();
3521       OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
3522       // The default(none) clause requires that each variable that is referenced
3523       // in the construct, and does not have a predetermined data-sharing
3524       // attribute, must have its data-sharing attribute explicitly determined
3525       // by being listed in a data-sharing attribute clause.
3526       if (DVar.CKind == OMPC_unknown &&
3527           (Stack->getDefaultDSA() == DSA_none ||
3528            Stack->getDefaultDSA() == DSA_firstprivate) &&
3529           isImplicitOrExplicitTaskingRegion(DKind) &&
3530           VarsWithInheritedDSA.count(VD) == 0) {
3531         bool InheritedDSA = Stack->getDefaultDSA() == DSA_none;
3532         if (!InheritedDSA && Stack->getDefaultDSA() == DSA_firstprivate) {
3533           DSAStackTy::DSAVarData DVar =
3534               Stack->getImplicitDSA(VD, /*FromParent=*/false);
3535           InheritedDSA = DVar.CKind == OMPC_unknown;
3536         }
3537         if (InheritedDSA)
3538           VarsWithInheritedDSA[VD] = E;
3539         return;
3540       }
3541 
3542       // OpenMP 5.0 [2.19.7.2, defaultmap clause, Description]
3543       // If implicit-behavior is none, each variable referenced in the
3544       // construct that does not have a predetermined data-sharing attribute
3545       // and does not appear in a to or link clause on a declare target
3546       // directive must be listed in a data-mapping attribute clause, a
3547       // data-haring attribute clause (including a data-sharing attribute
3548       // clause on a combined construct where target. is one of the
3549       // constituent constructs), or an is_device_ptr clause.
3550       OpenMPDefaultmapClauseKind ClauseKind =
3551           getVariableCategoryFromDecl(SemaRef.getLangOpts(), VD);
3552       if (SemaRef.getLangOpts().OpenMP >= 50) {
3553         bool IsModifierNone = Stack->getDefaultmapModifier(ClauseKind) ==
3554                               OMPC_DEFAULTMAP_MODIFIER_none;
3555         if (DVar.CKind == OMPC_unknown && IsModifierNone &&
3556             VarsWithInheritedDSA.count(VD) == 0 && !Res) {
3557           // Only check for data-mapping attribute and is_device_ptr here
3558           // since we have already make sure that the declaration does not
3559           // have a data-sharing attribute above
3560           if (!Stack->checkMappableExprComponentListsForDecl(
3561                   VD, /*CurrentRegionOnly=*/true,
3562                   [VD](OMPClauseMappableExprCommon::MappableExprComponentListRef
3563                            MapExprComponents,
3564                        OpenMPClauseKind) {
3565                     auto MI = MapExprComponents.rbegin();
3566                     auto ME = MapExprComponents.rend();
3567                     return MI != ME && MI->getAssociatedDeclaration() == VD;
3568                   })) {
3569             VarsWithInheritedDSA[VD] = E;
3570             return;
3571           }
3572         }
3573       }
3574       if (SemaRef.getLangOpts().OpenMP > 50) {
3575         bool IsModifierPresent = Stack->getDefaultmapModifier(ClauseKind) ==
3576                                  OMPC_DEFAULTMAP_MODIFIER_present;
3577         if (IsModifierPresent) {
3578           if (llvm::find(ImplicitMapModifier[ClauseKind],
3579                          OMPC_MAP_MODIFIER_present) ==
3580               std::end(ImplicitMapModifier[ClauseKind])) {
3581             ImplicitMapModifier[ClauseKind].push_back(
3582                 OMPC_MAP_MODIFIER_present);
3583           }
3584         }
3585       }
3586 
3587       if (isOpenMPTargetExecutionDirective(DKind) &&
3588           !Stack->isLoopControlVariable(VD).first) {
3589         if (!Stack->checkMappableExprComponentListsForDecl(
3590                 VD, /*CurrentRegionOnly=*/true,
3591                 [this](OMPClauseMappableExprCommon::MappableExprComponentListRef
3592                            StackComponents,
3593                        OpenMPClauseKind) {
3594                   if (SemaRef.LangOpts.OpenMP >= 50)
3595                     return !StackComponents.empty();
3596                   // Variable is used if it has been marked as an array, array
3597                   // section, array shaping or the variable iself.
3598                   return StackComponents.size() == 1 ||
3599                          std::all_of(
3600                              std::next(StackComponents.rbegin()),
3601                              StackComponents.rend(),
3602                              [](const OMPClauseMappableExprCommon::
3603                                     MappableComponent &MC) {
3604                                return MC.getAssociatedDeclaration() ==
3605                                           nullptr &&
3606                                       (isa<OMPArraySectionExpr>(
3607                                            MC.getAssociatedExpression()) ||
3608                                        isa<OMPArrayShapingExpr>(
3609                                            MC.getAssociatedExpression()) ||
3610                                        isa<ArraySubscriptExpr>(
3611                                            MC.getAssociatedExpression()));
3612                              });
3613                 })) {
3614           bool IsFirstprivate = false;
3615           // By default lambdas are captured as firstprivates.
3616           if (const auto *RD =
3617                   VD->getType().getNonReferenceType()->getAsCXXRecordDecl())
3618             IsFirstprivate = RD->isLambda();
3619           IsFirstprivate =
3620               IsFirstprivate || (Stack->mustBeFirstprivate(ClauseKind) && !Res);
3621           if (IsFirstprivate) {
3622             ImplicitFirstprivate.emplace_back(E);
3623           } else {
3624             OpenMPDefaultmapClauseModifier M =
3625                 Stack->getDefaultmapModifier(ClauseKind);
3626             OpenMPMapClauseKind Kind = getMapClauseKindFromModifier(
3627                 M, ClauseKind == OMPC_DEFAULTMAP_aggregate || Res);
3628             ImplicitMap[ClauseKind][Kind].emplace_back(E);
3629           }
3630           return;
3631         }
3632       }
3633 
3634       // OpenMP [2.9.3.6, Restrictions, p.2]
3635       //  A list item that appears in a reduction clause of the innermost
3636       //  enclosing worksharing or parallel construct may not be accessed in an
3637       //  explicit task.
3638       DVar = Stack->hasInnermostDSA(
3639           VD,
3640           [](OpenMPClauseKind C, bool AppliedToPointee) {
3641             return C == OMPC_reduction && !AppliedToPointee;
3642           },
3643           [](OpenMPDirectiveKind K) {
3644             return isOpenMPParallelDirective(K) ||
3645                    isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
3646           },
3647           /*FromParent=*/true);
3648       if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
3649         ErrorFound = true;
3650         SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
3651         reportOriginalDsa(SemaRef, Stack, VD, DVar);
3652         return;
3653       }
3654 
3655       // Define implicit data-sharing attributes for task.
3656       DVar = Stack->getImplicitDSA(VD, /*FromParent=*/false);
3657       if (((isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared) ||
3658            (Stack->getDefaultDSA() == DSA_firstprivate &&
3659             DVar.CKind == OMPC_firstprivate && !DVar.RefExpr)) &&
3660           !Stack->isLoopControlVariable(VD).first) {
3661         ImplicitFirstprivate.push_back(E);
3662         return;
3663       }
3664 
3665       // Store implicitly used globals with declare target link for parent
3666       // target.
3667       if (!isOpenMPTargetExecutionDirective(DKind) && Res &&
3668           *Res == OMPDeclareTargetDeclAttr::MT_Link) {
3669         Stack->addToParentTargetRegionLinkGlobals(E);
3670         return;
3671       }
3672     }
3673   }
3674   void VisitMemberExpr(MemberExpr *E) {
3675     if (E->isTypeDependent() || E->isValueDependent() ||
3676         E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
3677       return;
3678     auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
3679     OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
3680     if (auto *TE = dyn_cast<CXXThisExpr>(E->getBase()->IgnoreParenCasts())) {
3681       if (!FD)
3682         return;
3683       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(FD, /*FromParent=*/false);
3684       // Check if the variable has explicit DSA set and stop analysis if it
3685       // so.
3686       if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second)
3687         return;
3688 
3689       if (isOpenMPTargetExecutionDirective(DKind) &&
3690           !Stack->isLoopControlVariable(FD).first &&
3691           !Stack->checkMappableExprComponentListsForDecl(
3692               FD, /*CurrentRegionOnly=*/true,
3693               [](OMPClauseMappableExprCommon::MappableExprComponentListRef
3694                      StackComponents,
3695                  OpenMPClauseKind) {
3696                 return isa<CXXThisExpr>(
3697                     cast<MemberExpr>(
3698                         StackComponents.back().getAssociatedExpression())
3699                         ->getBase()
3700                         ->IgnoreParens());
3701               })) {
3702         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
3703         //  A bit-field cannot appear in a map clause.
3704         //
3705         if (FD->isBitField())
3706           return;
3707 
3708         // Check to see if the member expression is referencing a class that
3709         // has already been explicitly mapped
3710         if (Stack->isClassPreviouslyMapped(TE->getType()))
3711           return;
3712 
3713         OpenMPDefaultmapClauseModifier Modifier =
3714             Stack->getDefaultmapModifier(OMPC_DEFAULTMAP_aggregate);
3715         OpenMPDefaultmapClauseKind ClauseKind =
3716             getVariableCategoryFromDecl(SemaRef.getLangOpts(), FD);
3717         OpenMPMapClauseKind Kind = getMapClauseKindFromModifier(
3718             Modifier, /*IsAggregateOrDeclareTarget*/ true);
3719         ImplicitMap[ClauseKind][Kind].emplace_back(E);
3720         return;
3721       }
3722 
3723       SourceLocation ELoc = E->getExprLoc();
3724       // OpenMP [2.9.3.6, Restrictions, p.2]
3725       //  A list item that appears in a reduction clause of the innermost
3726       //  enclosing worksharing or parallel construct may not be accessed in
3727       //  an  explicit task.
3728       DVar = Stack->hasInnermostDSA(
3729           FD,
3730           [](OpenMPClauseKind C, bool AppliedToPointee) {
3731             return C == OMPC_reduction && !AppliedToPointee;
3732           },
3733           [](OpenMPDirectiveKind K) {
3734             return isOpenMPParallelDirective(K) ||
3735                    isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
3736           },
3737           /*FromParent=*/true);
3738       if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
3739         ErrorFound = true;
3740         SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
3741         reportOriginalDsa(SemaRef, Stack, FD, DVar);
3742         return;
3743       }
3744 
3745       // Define implicit data-sharing attributes for task.
3746       DVar = Stack->getImplicitDSA(FD, /*FromParent=*/false);
3747       if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
3748           !Stack->isLoopControlVariable(FD).first) {
3749         // Check if there is a captured expression for the current field in the
3750         // region. Do not mark it as firstprivate unless there is no captured
3751         // expression.
3752         // TODO: try to make it firstprivate.
3753         if (DVar.CKind != OMPC_unknown)
3754           ImplicitFirstprivate.push_back(E);
3755       }
3756       return;
3757     }
3758     if (isOpenMPTargetExecutionDirective(DKind)) {
3759       OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
3760       if (!checkMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map,
3761                                         Stack->getCurrentDirective(),
3762                                         /*NoDiagnose=*/true))
3763         return;
3764       const auto *VD = cast<ValueDecl>(
3765           CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl());
3766       if (!Stack->checkMappableExprComponentListsForDecl(
3767               VD, /*CurrentRegionOnly=*/true,
3768               [&CurComponents](
3769                   OMPClauseMappableExprCommon::MappableExprComponentListRef
3770                       StackComponents,
3771                   OpenMPClauseKind) {
3772                 auto CCI = CurComponents.rbegin();
3773                 auto CCE = CurComponents.rend();
3774                 for (const auto &SC : llvm::reverse(StackComponents)) {
3775                   // Do both expressions have the same kind?
3776                   if (CCI->getAssociatedExpression()->getStmtClass() !=
3777                       SC.getAssociatedExpression()->getStmtClass())
3778                     if (!((isa<OMPArraySectionExpr>(
3779                                SC.getAssociatedExpression()) ||
3780                            isa<OMPArrayShapingExpr>(
3781                                SC.getAssociatedExpression())) &&
3782                           isa<ArraySubscriptExpr>(
3783                               CCI->getAssociatedExpression())))
3784                       return false;
3785 
3786                   const Decl *CCD = CCI->getAssociatedDeclaration();
3787                   const Decl *SCD = SC.getAssociatedDeclaration();
3788                   CCD = CCD ? CCD->getCanonicalDecl() : nullptr;
3789                   SCD = SCD ? SCD->getCanonicalDecl() : nullptr;
3790                   if (SCD != CCD)
3791                     return false;
3792                   std::advance(CCI, 1);
3793                   if (CCI == CCE)
3794                     break;
3795                 }
3796                 return true;
3797               })) {
3798         Visit(E->getBase());
3799       }
3800     } else if (!TryCaptureCXXThisMembers) {
3801       Visit(E->getBase());
3802     }
3803   }
3804   void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
3805     for (OMPClause *C : S->clauses()) {
3806       // Skip analysis of arguments of private clauses for task|target
3807       // directives.
3808       if (isa_and_nonnull<OMPPrivateClause>(C))
3809         continue;
3810       // Skip analysis of arguments of implicitly defined firstprivate clause
3811       // for task|target directives.
3812       // Skip analysis of arguments of implicitly defined map clause for target
3813       // directives.
3814       if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) &&
3815                  C->isImplicit() &&
3816                  !isOpenMPTaskingDirective(Stack->getCurrentDirective()))) {
3817         for (Stmt *CC : C->children()) {
3818           if (CC)
3819             Visit(CC);
3820         }
3821       }
3822     }
3823     // Check implicitly captured variables.
3824     VisitSubCaptures(S);
3825   }
3826 
3827   void VisitOMPLoopTransformationDirective(OMPLoopTransformationDirective *S) {
3828     // Loop transformation directives do not introduce data sharing
3829     VisitStmt(S);
3830   }
3831 
3832   void VisitCallExpr(CallExpr *S) {
3833     for (Stmt *C : S->arguments()) {
3834       if (C) {
3835         // Check implicitly captured variables in the task-based directives to
3836         // check if they must be firstprivatized.
3837         Visit(C);
3838       }
3839     }
3840   }
3841   void VisitStmt(Stmt *S) {
3842     for (Stmt *C : S->children()) {
3843       if (C) {
3844         // Check implicitly captured variables in the task-based directives to
3845         // check if they must be firstprivatized.
3846         Visit(C);
3847       }
3848     }
3849   }
3850 
3851   void visitSubCaptures(CapturedStmt *S) {
3852     for (const CapturedStmt::Capture &Cap : S->captures()) {
3853       if (!Cap.capturesVariable() && !Cap.capturesVariableByCopy())
3854         continue;
3855       VarDecl *VD = Cap.getCapturedVar();
3856       // Do not try to map the variable if it or its sub-component was mapped
3857       // already.
3858       if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
3859           Stack->checkMappableExprComponentListsForDecl(
3860               VD, /*CurrentRegionOnly=*/true,
3861               [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
3862                  OpenMPClauseKind) { return true; }))
3863         continue;
3864       DeclRefExpr *DRE = buildDeclRefExpr(
3865           SemaRef, VD, VD->getType().getNonLValueExprType(SemaRef.Context),
3866           Cap.getLocation(), /*RefersToCapture=*/true);
3867       Visit(DRE);
3868     }
3869   }
3870   bool isErrorFound() const { return ErrorFound; }
3871   ArrayRef<Expr *> getImplicitFirstprivate() const {
3872     return ImplicitFirstprivate;
3873   }
3874   ArrayRef<Expr *> getImplicitMap(OpenMPDefaultmapClauseKind DK,
3875                                   OpenMPMapClauseKind MK) const {
3876     return ImplicitMap[DK][MK];
3877   }
3878   ArrayRef<OpenMPMapModifierKind>
3879   getImplicitMapModifier(OpenMPDefaultmapClauseKind Kind) const {
3880     return ImplicitMapModifier[Kind];
3881   }
3882   const Sema::VarsWithInheritedDSAType &getVarsWithInheritedDSA() const {
3883     return VarsWithInheritedDSA;
3884   }
3885 
3886   DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
3887       : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {
3888     // Process declare target link variables for the target directives.
3889     if (isOpenMPTargetExecutionDirective(S->getCurrentDirective())) {
3890       for (DeclRefExpr *E : Stack->getLinkGlobals())
3891         Visit(E);
3892     }
3893   }
3894 };
3895 } // namespace
3896 
3897 static void handleDeclareVariantConstructTrait(DSAStackTy *Stack,
3898                                                OpenMPDirectiveKind DKind,
3899                                                bool ScopeEntry) {
3900   SmallVector<llvm::omp::TraitProperty, 8> Traits;
3901   if (isOpenMPTargetExecutionDirective(DKind))
3902     Traits.emplace_back(llvm::omp::TraitProperty::construct_target_target);
3903   if (isOpenMPTeamsDirective(DKind))
3904     Traits.emplace_back(llvm::omp::TraitProperty::construct_teams_teams);
3905   if (isOpenMPParallelDirective(DKind))
3906     Traits.emplace_back(llvm::omp::TraitProperty::construct_parallel_parallel);
3907   if (isOpenMPWorksharingDirective(DKind))
3908     Traits.emplace_back(llvm::omp::TraitProperty::construct_for_for);
3909   if (isOpenMPSimdDirective(DKind))
3910     Traits.emplace_back(llvm::omp::TraitProperty::construct_simd_simd);
3911   Stack->handleConstructTrait(Traits, ScopeEntry);
3912 }
3913 
3914 void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
3915   switch (DKind) {
3916   case OMPD_parallel:
3917   case OMPD_parallel_for:
3918   case OMPD_parallel_for_simd:
3919   case OMPD_parallel_sections:
3920   case OMPD_parallel_master:
3921   case OMPD_teams:
3922   case OMPD_teams_distribute:
3923   case OMPD_teams_distribute_simd: {
3924     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3925     QualType KmpInt32PtrTy =
3926         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3927     Sema::CapturedParamNameType Params[] = {
3928         std::make_pair(".global_tid.", KmpInt32PtrTy),
3929         std::make_pair(".bound_tid.", KmpInt32PtrTy),
3930         std::make_pair(StringRef(), QualType()) // __context with shared vars
3931     };
3932     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3933                              Params);
3934     break;
3935   }
3936   case OMPD_target_teams:
3937   case OMPD_target_parallel:
3938   case OMPD_target_parallel_for:
3939   case OMPD_target_parallel_for_simd:
3940   case OMPD_target_teams_distribute:
3941   case OMPD_target_teams_distribute_simd: {
3942     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3943     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3944     QualType KmpInt32PtrTy =
3945         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3946     QualType Args[] = {VoidPtrTy};
3947     FunctionProtoType::ExtProtoInfo EPI;
3948     EPI.Variadic = true;
3949     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3950     Sema::CapturedParamNameType Params[] = {
3951         std::make_pair(".global_tid.", KmpInt32Ty),
3952         std::make_pair(".part_id.", KmpInt32PtrTy),
3953         std::make_pair(".privates.", VoidPtrTy),
3954         std::make_pair(
3955             ".copy_fn.",
3956             Context.getPointerType(CopyFnType).withConst().withRestrict()),
3957         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3958         std::make_pair(StringRef(), QualType()) // __context with shared vars
3959     };
3960     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3961                              Params, /*OpenMPCaptureLevel=*/0);
3962     // Mark this captured region as inlined, because we don't use outlined
3963     // function directly.
3964     getCurCapturedRegion()->TheCapturedDecl->addAttr(
3965         AlwaysInlineAttr::CreateImplicit(
3966             Context, {}, AttributeCommonInfo::AS_Keyword,
3967             AlwaysInlineAttr::Keyword_forceinline));
3968     Sema::CapturedParamNameType ParamsTarget[] = {
3969         std::make_pair(StringRef(), QualType()) // __context with shared vars
3970     };
3971     // Start a captured region for 'target' with no implicit parameters.
3972     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3973                              ParamsTarget, /*OpenMPCaptureLevel=*/1);
3974     Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
3975         std::make_pair(".global_tid.", KmpInt32PtrTy),
3976         std::make_pair(".bound_tid.", KmpInt32PtrTy),
3977         std::make_pair(StringRef(), QualType()) // __context with shared vars
3978     };
3979     // Start a captured region for 'teams' or 'parallel'.  Both regions have
3980     // the same implicit parameters.
3981     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3982                              ParamsTeamsOrParallel, /*OpenMPCaptureLevel=*/2);
3983     break;
3984   }
3985   case OMPD_target:
3986   case OMPD_target_simd: {
3987     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3988     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3989     QualType KmpInt32PtrTy =
3990         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3991     QualType Args[] = {VoidPtrTy};
3992     FunctionProtoType::ExtProtoInfo EPI;
3993     EPI.Variadic = true;
3994     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3995     Sema::CapturedParamNameType Params[] = {
3996         std::make_pair(".global_tid.", KmpInt32Ty),
3997         std::make_pair(".part_id.", KmpInt32PtrTy),
3998         std::make_pair(".privates.", VoidPtrTy),
3999         std::make_pair(
4000             ".copy_fn.",
4001             Context.getPointerType(CopyFnType).withConst().withRestrict()),
4002         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
4003         std::make_pair(StringRef(), QualType()) // __context with shared vars
4004     };
4005     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4006                              Params, /*OpenMPCaptureLevel=*/0);
4007     // Mark this captured region as inlined, because we don't use outlined
4008     // function directly.
4009     getCurCapturedRegion()->TheCapturedDecl->addAttr(
4010         AlwaysInlineAttr::CreateImplicit(
4011             Context, {}, AttributeCommonInfo::AS_Keyword,
4012             AlwaysInlineAttr::Keyword_forceinline));
4013     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4014                              std::make_pair(StringRef(), QualType()),
4015                              /*OpenMPCaptureLevel=*/1);
4016     break;
4017   }
4018   case OMPD_atomic:
4019   case OMPD_critical:
4020   case OMPD_section:
4021   case OMPD_master:
4022   case OMPD_masked:
4023   case OMPD_tile:
4024   case OMPD_unroll:
4025     break;
4026   case OMPD_loop:
4027     // TODO: 'loop' may require additional parameters depending on the binding.
4028     // Treat similar to OMPD_simd/OMPD_for for now.
4029   case OMPD_simd:
4030   case OMPD_for:
4031   case OMPD_for_simd:
4032   case OMPD_sections:
4033   case OMPD_single:
4034   case OMPD_taskgroup:
4035   case OMPD_distribute:
4036   case OMPD_distribute_simd:
4037   case OMPD_ordered:
4038   case OMPD_target_data:
4039   case OMPD_dispatch: {
4040     Sema::CapturedParamNameType Params[] = {
4041         std::make_pair(StringRef(), QualType()) // __context with shared vars
4042     };
4043     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4044                              Params);
4045     break;
4046   }
4047   case OMPD_task: {
4048     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
4049     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
4050     QualType KmpInt32PtrTy =
4051         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
4052     QualType Args[] = {VoidPtrTy};
4053     FunctionProtoType::ExtProtoInfo EPI;
4054     EPI.Variadic = true;
4055     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
4056     Sema::CapturedParamNameType Params[] = {
4057         std::make_pair(".global_tid.", KmpInt32Ty),
4058         std::make_pair(".part_id.", KmpInt32PtrTy),
4059         std::make_pair(".privates.", VoidPtrTy),
4060         std::make_pair(
4061             ".copy_fn.",
4062             Context.getPointerType(CopyFnType).withConst().withRestrict()),
4063         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
4064         std::make_pair(StringRef(), QualType()) // __context with shared vars
4065     };
4066     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4067                              Params);
4068     // Mark this captured region as inlined, because we don't use outlined
4069     // function directly.
4070     getCurCapturedRegion()->TheCapturedDecl->addAttr(
4071         AlwaysInlineAttr::CreateImplicit(
4072             Context, {}, AttributeCommonInfo::AS_Keyword,
4073             AlwaysInlineAttr::Keyword_forceinline));
4074     break;
4075   }
4076   case OMPD_taskloop:
4077   case OMPD_taskloop_simd:
4078   case OMPD_master_taskloop:
4079   case OMPD_master_taskloop_simd: {
4080     QualType KmpInt32Ty =
4081         Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1)
4082             .withConst();
4083     QualType KmpUInt64Ty =
4084         Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0)
4085             .withConst();
4086     QualType KmpInt64Ty =
4087         Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1)
4088             .withConst();
4089     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
4090     QualType KmpInt32PtrTy =
4091         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
4092     QualType Args[] = {VoidPtrTy};
4093     FunctionProtoType::ExtProtoInfo EPI;
4094     EPI.Variadic = true;
4095     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
4096     Sema::CapturedParamNameType Params[] = {
4097         std::make_pair(".global_tid.", KmpInt32Ty),
4098         std::make_pair(".part_id.", KmpInt32PtrTy),
4099         std::make_pair(".privates.", VoidPtrTy),
4100         std::make_pair(
4101             ".copy_fn.",
4102             Context.getPointerType(CopyFnType).withConst().withRestrict()),
4103         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
4104         std::make_pair(".lb.", KmpUInt64Ty),
4105         std::make_pair(".ub.", KmpUInt64Ty),
4106         std::make_pair(".st.", KmpInt64Ty),
4107         std::make_pair(".liter.", KmpInt32Ty),
4108         std::make_pair(".reductions.", VoidPtrTy),
4109         std::make_pair(StringRef(), QualType()) // __context with shared vars
4110     };
4111     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4112                              Params);
4113     // Mark this captured region as inlined, because we don't use outlined
4114     // function directly.
4115     getCurCapturedRegion()->TheCapturedDecl->addAttr(
4116         AlwaysInlineAttr::CreateImplicit(
4117             Context, {}, AttributeCommonInfo::AS_Keyword,
4118             AlwaysInlineAttr::Keyword_forceinline));
4119     break;
4120   }
4121   case OMPD_parallel_master_taskloop:
4122   case OMPD_parallel_master_taskloop_simd: {
4123     QualType KmpInt32Ty =
4124         Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1)
4125             .withConst();
4126     QualType KmpUInt64Ty =
4127         Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0)
4128             .withConst();
4129     QualType KmpInt64Ty =
4130         Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1)
4131             .withConst();
4132     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
4133     QualType KmpInt32PtrTy =
4134         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
4135     Sema::CapturedParamNameType ParamsParallel[] = {
4136         std::make_pair(".global_tid.", KmpInt32PtrTy),
4137         std::make_pair(".bound_tid.", KmpInt32PtrTy),
4138         std::make_pair(StringRef(), QualType()) // __context with shared vars
4139     };
4140     // Start a captured region for 'parallel'.
4141     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4142                              ParamsParallel, /*OpenMPCaptureLevel=*/0);
4143     QualType Args[] = {VoidPtrTy};
4144     FunctionProtoType::ExtProtoInfo EPI;
4145     EPI.Variadic = true;
4146     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
4147     Sema::CapturedParamNameType Params[] = {
4148         std::make_pair(".global_tid.", KmpInt32Ty),
4149         std::make_pair(".part_id.", KmpInt32PtrTy),
4150         std::make_pair(".privates.", VoidPtrTy),
4151         std::make_pair(
4152             ".copy_fn.",
4153             Context.getPointerType(CopyFnType).withConst().withRestrict()),
4154         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
4155         std::make_pair(".lb.", KmpUInt64Ty),
4156         std::make_pair(".ub.", KmpUInt64Ty),
4157         std::make_pair(".st.", KmpInt64Ty),
4158         std::make_pair(".liter.", KmpInt32Ty),
4159         std::make_pair(".reductions.", VoidPtrTy),
4160         std::make_pair(StringRef(), QualType()) // __context with shared vars
4161     };
4162     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4163                              Params, /*OpenMPCaptureLevel=*/1);
4164     // Mark this captured region as inlined, because we don't use outlined
4165     // function directly.
4166     getCurCapturedRegion()->TheCapturedDecl->addAttr(
4167         AlwaysInlineAttr::CreateImplicit(
4168             Context, {}, AttributeCommonInfo::AS_Keyword,
4169             AlwaysInlineAttr::Keyword_forceinline));
4170     break;
4171   }
4172   case OMPD_distribute_parallel_for_simd:
4173   case OMPD_distribute_parallel_for: {
4174     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
4175     QualType KmpInt32PtrTy =
4176         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
4177     Sema::CapturedParamNameType Params[] = {
4178         std::make_pair(".global_tid.", KmpInt32PtrTy),
4179         std::make_pair(".bound_tid.", KmpInt32PtrTy),
4180         std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
4181         std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
4182         std::make_pair(StringRef(), QualType()) // __context with shared vars
4183     };
4184     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4185                              Params);
4186     break;
4187   }
4188   case OMPD_target_teams_distribute_parallel_for:
4189   case OMPD_target_teams_distribute_parallel_for_simd: {
4190     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
4191     QualType KmpInt32PtrTy =
4192         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
4193     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
4194 
4195     QualType Args[] = {VoidPtrTy};
4196     FunctionProtoType::ExtProtoInfo EPI;
4197     EPI.Variadic = true;
4198     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
4199     Sema::CapturedParamNameType Params[] = {
4200         std::make_pair(".global_tid.", KmpInt32Ty),
4201         std::make_pair(".part_id.", KmpInt32PtrTy),
4202         std::make_pair(".privates.", VoidPtrTy),
4203         std::make_pair(
4204             ".copy_fn.",
4205             Context.getPointerType(CopyFnType).withConst().withRestrict()),
4206         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
4207         std::make_pair(StringRef(), QualType()) // __context with shared vars
4208     };
4209     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4210                              Params, /*OpenMPCaptureLevel=*/0);
4211     // Mark this captured region as inlined, because we don't use outlined
4212     // function directly.
4213     getCurCapturedRegion()->TheCapturedDecl->addAttr(
4214         AlwaysInlineAttr::CreateImplicit(
4215             Context, {}, AttributeCommonInfo::AS_Keyword,
4216             AlwaysInlineAttr::Keyword_forceinline));
4217     Sema::CapturedParamNameType ParamsTarget[] = {
4218         std::make_pair(StringRef(), QualType()) // __context with shared vars
4219     };
4220     // Start a captured region for 'target' with no implicit parameters.
4221     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4222                              ParamsTarget, /*OpenMPCaptureLevel=*/1);
4223 
4224     Sema::CapturedParamNameType ParamsTeams[] = {
4225         std::make_pair(".global_tid.", KmpInt32PtrTy),
4226         std::make_pair(".bound_tid.", KmpInt32PtrTy),
4227         std::make_pair(StringRef(), QualType()) // __context with shared vars
4228     };
4229     // Start a captured region for 'target' with no implicit parameters.
4230     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4231                              ParamsTeams, /*OpenMPCaptureLevel=*/2);
4232 
4233     Sema::CapturedParamNameType ParamsParallel[] = {
4234         std::make_pair(".global_tid.", KmpInt32PtrTy),
4235         std::make_pair(".bound_tid.", KmpInt32PtrTy),
4236         std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
4237         std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
4238         std::make_pair(StringRef(), QualType()) // __context with shared vars
4239     };
4240     // Start a captured region for 'teams' or 'parallel'.  Both regions have
4241     // the same implicit parameters.
4242     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4243                              ParamsParallel, /*OpenMPCaptureLevel=*/3);
4244     break;
4245   }
4246 
4247   case OMPD_teams_distribute_parallel_for:
4248   case OMPD_teams_distribute_parallel_for_simd: {
4249     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
4250     QualType KmpInt32PtrTy =
4251         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
4252 
4253     Sema::CapturedParamNameType ParamsTeams[] = {
4254         std::make_pair(".global_tid.", KmpInt32PtrTy),
4255         std::make_pair(".bound_tid.", KmpInt32PtrTy),
4256         std::make_pair(StringRef(), QualType()) // __context with shared vars
4257     };
4258     // Start a captured region for 'target' with no implicit parameters.
4259     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4260                              ParamsTeams, /*OpenMPCaptureLevel=*/0);
4261 
4262     Sema::CapturedParamNameType ParamsParallel[] = {
4263         std::make_pair(".global_tid.", KmpInt32PtrTy),
4264         std::make_pair(".bound_tid.", KmpInt32PtrTy),
4265         std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
4266         std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
4267         std::make_pair(StringRef(), QualType()) // __context with shared vars
4268     };
4269     // Start a captured region for 'teams' or 'parallel'.  Both regions have
4270     // the same implicit parameters.
4271     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4272                              ParamsParallel, /*OpenMPCaptureLevel=*/1);
4273     break;
4274   }
4275   case OMPD_target_update:
4276   case OMPD_target_enter_data:
4277   case OMPD_target_exit_data: {
4278     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
4279     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
4280     QualType KmpInt32PtrTy =
4281         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
4282     QualType Args[] = {VoidPtrTy};
4283     FunctionProtoType::ExtProtoInfo EPI;
4284     EPI.Variadic = true;
4285     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
4286     Sema::CapturedParamNameType Params[] = {
4287         std::make_pair(".global_tid.", KmpInt32Ty),
4288         std::make_pair(".part_id.", KmpInt32PtrTy),
4289         std::make_pair(".privates.", VoidPtrTy),
4290         std::make_pair(
4291             ".copy_fn.",
4292             Context.getPointerType(CopyFnType).withConst().withRestrict()),
4293         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
4294         std::make_pair(StringRef(), QualType()) // __context with shared vars
4295     };
4296     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4297                              Params);
4298     // Mark this captured region as inlined, because we don't use outlined
4299     // function directly.
4300     getCurCapturedRegion()->TheCapturedDecl->addAttr(
4301         AlwaysInlineAttr::CreateImplicit(
4302             Context, {}, AttributeCommonInfo::AS_Keyword,
4303             AlwaysInlineAttr::Keyword_forceinline));
4304     break;
4305   }
4306   case OMPD_threadprivate:
4307   case OMPD_allocate:
4308   case OMPD_taskyield:
4309   case OMPD_barrier:
4310   case OMPD_taskwait:
4311   case OMPD_cancellation_point:
4312   case OMPD_cancel:
4313   case OMPD_flush:
4314   case OMPD_depobj:
4315   case OMPD_scan:
4316   case OMPD_declare_reduction:
4317   case OMPD_declare_mapper:
4318   case OMPD_declare_simd:
4319   case OMPD_declare_target:
4320   case OMPD_end_declare_target:
4321   case OMPD_requires:
4322   case OMPD_declare_variant:
4323   case OMPD_begin_declare_variant:
4324   case OMPD_end_declare_variant:
4325   case OMPD_metadirective:
4326     llvm_unreachable("OpenMP Directive is not allowed");
4327   case OMPD_unknown:
4328   default:
4329     llvm_unreachable("Unknown OpenMP directive");
4330   }
4331   DSAStack->setContext(CurContext);
4332   handleDeclareVariantConstructTrait(DSAStack, DKind, /* ScopeEntry */ true);
4333 }
4334 
4335 int Sema::getNumberOfConstructScopes(unsigned Level) const {
4336   return getOpenMPCaptureLevels(DSAStack->getDirective(Level));
4337 }
4338 
4339 int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
4340   SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
4341   getOpenMPCaptureRegions(CaptureRegions, DKind);
4342   return CaptureRegions.size();
4343 }
4344 
4345 static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
4346                                              Expr *CaptureExpr, bool WithInit,
4347                                              bool AsExpression) {
4348   assert(CaptureExpr);
4349   ASTContext &C = S.getASTContext();
4350   Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
4351   QualType Ty = Init->getType();
4352   if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
4353     if (S.getLangOpts().CPlusPlus) {
4354       Ty = C.getLValueReferenceType(Ty);
4355     } else {
4356       Ty = C.getPointerType(Ty);
4357       ExprResult Res =
4358           S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
4359       if (!Res.isUsable())
4360         return nullptr;
4361       Init = Res.get();
4362     }
4363     WithInit = true;
4364   }
4365   auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
4366                                           CaptureExpr->getBeginLoc());
4367   if (!WithInit)
4368     CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C));
4369   S.CurContext->addHiddenDecl(CED);
4370   Sema::TentativeAnalysisScope Trap(S);
4371   S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
4372   return CED;
4373 }
4374 
4375 static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
4376                                  bool WithInit) {
4377   OMPCapturedExprDecl *CD;
4378   if (VarDecl *VD = S.isOpenMPCapturedDecl(D))
4379     CD = cast<OMPCapturedExprDecl>(VD);
4380   else
4381     CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
4382                           /*AsExpression=*/false);
4383   return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
4384                           CaptureExpr->getExprLoc());
4385 }
4386 
4387 static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
4388   CaptureExpr = S.DefaultLvalueConversion(CaptureExpr).get();
4389   if (!Ref) {
4390     OMPCapturedExprDecl *CD = buildCaptureDecl(
4391         S, &S.getASTContext().Idents.get(".capture_expr."), CaptureExpr,
4392         /*WithInit=*/true, /*AsExpression=*/true);
4393     Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
4394                            CaptureExpr->getExprLoc());
4395   }
4396   ExprResult Res = Ref;
4397   if (!S.getLangOpts().CPlusPlus &&
4398       CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
4399       Ref->getType()->isPointerType()) {
4400     Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
4401     if (!Res.isUsable())
4402       return ExprError();
4403   }
4404   return S.DefaultLvalueConversion(Res.get());
4405 }
4406 
4407 namespace {
4408 // OpenMP directives parsed in this section are represented as a
4409 // CapturedStatement with an associated statement.  If a syntax error
4410 // is detected during the parsing of the associated statement, the
4411 // compiler must abort processing and close the CapturedStatement.
4412 //
4413 // Combined directives such as 'target parallel' have more than one
4414 // nested CapturedStatements.  This RAII ensures that we unwind out
4415 // of all the nested CapturedStatements when an error is found.
4416 class CaptureRegionUnwinderRAII {
4417 private:
4418   Sema &S;
4419   bool &ErrorFound;
4420   OpenMPDirectiveKind DKind = OMPD_unknown;
4421 
4422 public:
4423   CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
4424                             OpenMPDirectiveKind DKind)
4425       : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
4426   ~CaptureRegionUnwinderRAII() {
4427     if (ErrorFound) {
4428       int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
4429       while (--ThisCaptureLevel >= 0)
4430         S.ActOnCapturedRegionError();
4431     }
4432   }
4433 };
4434 } // namespace
4435 
4436 void Sema::tryCaptureOpenMPLambdas(ValueDecl *V) {
4437   // Capture variables captured by reference in lambdas for target-based
4438   // directives.
4439   if (!CurContext->isDependentContext() &&
4440       (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) ||
4441        isOpenMPTargetDataManagementDirective(
4442            DSAStack->getCurrentDirective()))) {
4443     QualType Type = V->getType();
4444     if (const auto *RD = Type.getCanonicalType()
4445                              .getNonReferenceType()
4446                              ->getAsCXXRecordDecl()) {
4447       bool SavedForceCaptureByReferenceInTargetExecutable =
4448           DSAStack->isForceCaptureByReferenceInTargetExecutable();
4449       DSAStack->setForceCaptureByReferenceInTargetExecutable(
4450           /*V=*/true);
4451       if (RD->isLambda()) {
4452         llvm::DenseMap<const VarDecl *, FieldDecl *> Captures;
4453         FieldDecl *ThisCapture;
4454         RD->getCaptureFields(Captures, ThisCapture);
4455         for (const LambdaCapture &LC : RD->captures()) {
4456           if (LC.getCaptureKind() == LCK_ByRef) {
4457             VarDecl *VD = LC.getCapturedVar();
4458             DeclContext *VDC = VD->getDeclContext();
4459             if (!VDC->Encloses(CurContext))
4460               continue;
4461             MarkVariableReferenced(LC.getLocation(), VD);
4462           } else if (LC.getCaptureKind() == LCK_This) {
4463             QualType ThisTy = getCurrentThisType();
4464             if (!ThisTy.isNull() &&
4465                 Context.typesAreCompatible(ThisTy, ThisCapture->getType()))
4466               CheckCXXThisCapture(LC.getLocation());
4467           }
4468         }
4469       }
4470       DSAStack->setForceCaptureByReferenceInTargetExecutable(
4471           SavedForceCaptureByReferenceInTargetExecutable);
4472     }
4473   }
4474 }
4475 
4476 static bool checkOrderedOrderSpecified(Sema &S,
4477                                        const ArrayRef<OMPClause *> Clauses) {
4478   const OMPOrderedClause *Ordered = nullptr;
4479   const OMPOrderClause *Order = nullptr;
4480 
4481   for (const OMPClause *Clause : Clauses) {
4482     if (Clause->getClauseKind() == OMPC_ordered)
4483       Ordered = cast<OMPOrderedClause>(Clause);
4484     else if (Clause->getClauseKind() == OMPC_order) {
4485       Order = cast<OMPOrderClause>(Clause);
4486       if (Order->getKind() != OMPC_ORDER_concurrent)
4487         Order = nullptr;
4488     }
4489     if (Ordered && Order)
4490       break;
4491   }
4492 
4493   if (Ordered && Order) {
4494     S.Diag(Order->getKindKwLoc(),
4495            diag::err_omp_simple_clause_incompatible_with_ordered)
4496         << getOpenMPClauseName(OMPC_order)
4497         << getOpenMPSimpleClauseTypeName(OMPC_order, OMPC_ORDER_concurrent)
4498         << SourceRange(Order->getBeginLoc(), Order->getEndLoc());
4499     S.Diag(Ordered->getBeginLoc(), diag::note_omp_ordered_param)
4500         << 0 << SourceRange(Ordered->getBeginLoc(), Ordered->getEndLoc());
4501     return true;
4502   }
4503   return false;
4504 }
4505 
4506 StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
4507                                       ArrayRef<OMPClause *> Clauses) {
4508   handleDeclareVariantConstructTrait(DSAStack, DSAStack->getCurrentDirective(),
4509                                      /* ScopeEntry */ false);
4510   if (DSAStack->getCurrentDirective() == OMPD_atomic ||
4511       DSAStack->getCurrentDirective() == OMPD_critical ||
4512       DSAStack->getCurrentDirective() == OMPD_section ||
4513       DSAStack->getCurrentDirective() == OMPD_master ||
4514       DSAStack->getCurrentDirective() == OMPD_masked)
4515     return S;
4516 
4517   bool ErrorFound = false;
4518   CaptureRegionUnwinderRAII CaptureRegionUnwinder(
4519       *this, ErrorFound, DSAStack->getCurrentDirective());
4520   if (!S.isUsable()) {
4521     ErrorFound = true;
4522     return StmtError();
4523   }
4524 
4525   SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
4526   getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
4527   OMPOrderedClause *OC = nullptr;
4528   OMPScheduleClause *SC = nullptr;
4529   SmallVector<const OMPLinearClause *, 4> LCs;
4530   SmallVector<const OMPClauseWithPreInit *, 4> PICs;
4531   // This is required for proper codegen.
4532   for (OMPClause *Clause : Clauses) {
4533     if (!LangOpts.OpenMPSimd &&
4534         isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) &&
4535         Clause->getClauseKind() == OMPC_in_reduction) {
4536       // Capture taskgroup task_reduction descriptors inside the tasking regions
4537       // with the corresponding in_reduction items.
4538       auto *IRC = cast<OMPInReductionClause>(Clause);
4539       for (Expr *E : IRC->taskgroup_descriptors())
4540         if (E)
4541           MarkDeclarationsReferencedInExpr(E);
4542     }
4543     if (isOpenMPPrivate(Clause->getClauseKind()) ||
4544         Clause->getClauseKind() == OMPC_copyprivate ||
4545         (getLangOpts().OpenMPUseTLS &&
4546          getASTContext().getTargetInfo().isTLSSupported() &&
4547          Clause->getClauseKind() == OMPC_copyin)) {
4548       DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
4549       // Mark all variables in private list clauses as used in inner region.
4550       for (Stmt *VarRef : Clause->children()) {
4551         if (auto *E = cast_or_null<Expr>(VarRef)) {
4552           MarkDeclarationsReferencedInExpr(E);
4553         }
4554       }
4555       DSAStack->setForceVarCapturing(/*V=*/false);
4556     } else if (isOpenMPLoopTransformationDirective(
4557                    DSAStack->getCurrentDirective())) {
4558       assert(CaptureRegions.empty() &&
4559              "No captured regions in loop transformation directives.");
4560     } else if (CaptureRegions.size() > 1 ||
4561                CaptureRegions.back() != OMPD_unknown) {
4562       if (auto *C = OMPClauseWithPreInit::get(Clause))
4563         PICs.push_back(C);
4564       if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
4565         if (Expr *E = C->getPostUpdateExpr())
4566           MarkDeclarationsReferencedInExpr(E);
4567       }
4568     }
4569     if (Clause->getClauseKind() == OMPC_schedule)
4570       SC = cast<OMPScheduleClause>(Clause);
4571     else if (Clause->getClauseKind() == OMPC_ordered)
4572       OC = cast<OMPOrderedClause>(Clause);
4573     else if (Clause->getClauseKind() == OMPC_linear)
4574       LCs.push_back(cast<OMPLinearClause>(Clause));
4575   }
4576   // Capture allocator expressions if used.
4577   for (Expr *E : DSAStack->getInnerAllocators())
4578     MarkDeclarationsReferencedInExpr(E);
4579   // OpenMP, 2.7.1 Loop Construct, Restrictions
4580   // The nonmonotonic modifier cannot be specified if an ordered clause is
4581   // specified.
4582   if (SC &&
4583       (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
4584        SC->getSecondScheduleModifier() ==
4585            OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
4586       OC) {
4587     Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
4588              ? SC->getFirstScheduleModifierLoc()
4589              : SC->getSecondScheduleModifierLoc(),
4590          diag::err_omp_simple_clause_incompatible_with_ordered)
4591         << getOpenMPClauseName(OMPC_schedule)
4592         << getOpenMPSimpleClauseTypeName(OMPC_schedule,
4593                                          OMPC_SCHEDULE_MODIFIER_nonmonotonic)
4594         << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
4595     ErrorFound = true;
4596   }
4597   // OpenMP 5.0, 2.9.2 Worksharing-Loop Construct, Restrictions.
4598   // If an order(concurrent) clause is present, an ordered clause may not appear
4599   // on the same directive.
4600   if (checkOrderedOrderSpecified(*this, Clauses))
4601     ErrorFound = true;
4602   if (!LCs.empty() && OC && OC->getNumForLoops()) {
4603     for (const OMPLinearClause *C : LCs) {
4604       Diag(C->getBeginLoc(), diag::err_omp_linear_ordered)
4605           << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
4606     }
4607     ErrorFound = true;
4608   }
4609   if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
4610       isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
4611       OC->getNumForLoops()) {
4612     Diag(OC->getBeginLoc(), diag::err_omp_ordered_simd)
4613         << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
4614     ErrorFound = true;
4615   }
4616   if (ErrorFound) {
4617     return StmtError();
4618   }
4619   StmtResult SR = S;
4620   unsigned CompletedRegions = 0;
4621   for (OpenMPDirectiveKind ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
4622     // Mark all variables in private list clauses as used in inner region.
4623     // Required for proper codegen of combined directives.
4624     // TODO: add processing for other clauses.
4625     if (ThisCaptureRegion != OMPD_unknown) {
4626       for (const clang::OMPClauseWithPreInit *C : PICs) {
4627         OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
4628         // Find the particular capture region for the clause if the
4629         // directive is a combined one with multiple capture regions.
4630         // If the directive is not a combined one, the capture region
4631         // associated with the clause is OMPD_unknown and is generated
4632         // only once.
4633         if (CaptureRegion == ThisCaptureRegion ||
4634             CaptureRegion == OMPD_unknown) {
4635           if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
4636             for (Decl *D : DS->decls())
4637               MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
4638           }
4639         }
4640       }
4641     }
4642     if (ThisCaptureRegion == OMPD_target) {
4643       // Capture allocator traits in the target region. They are used implicitly
4644       // and, thus, are not captured by default.
4645       for (OMPClause *C : Clauses) {
4646         if (const auto *UAC = dyn_cast<OMPUsesAllocatorsClause>(C)) {
4647           for (unsigned I = 0, End = UAC->getNumberOfAllocators(); I < End;
4648                ++I) {
4649             OMPUsesAllocatorsClause::Data D = UAC->getAllocatorData(I);
4650             if (Expr *E = D.AllocatorTraits)
4651               MarkDeclarationsReferencedInExpr(E);
4652           }
4653           continue;
4654         }
4655       }
4656     }
4657     if (ThisCaptureRegion == OMPD_parallel) {
4658       // Capture temp arrays for inscan reductions and locals in aligned
4659       // clauses.
4660       for (OMPClause *C : Clauses) {
4661         if (auto *RC = dyn_cast<OMPReductionClause>(C)) {
4662           if (RC->getModifier() != OMPC_REDUCTION_inscan)
4663             continue;
4664           for (Expr *E : RC->copy_array_temps())
4665             MarkDeclarationsReferencedInExpr(E);
4666         }
4667         if (auto *AC = dyn_cast<OMPAlignedClause>(C)) {
4668           for (Expr *E : AC->varlists())
4669             MarkDeclarationsReferencedInExpr(E);
4670         }
4671       }
4672     }
4673     if (++CompletedRegions == CaptureRegions.size())
4674       DSAStack->setBodyComplete();
4675     SR = ActOnCapturedRegionEnd(SR.get());
4676   }
4677   return SR;
4678 }
4679 
4680 static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
4681                               OpenMPDirectiveKind CancelRegion,
4682                               SourceLocation StartLoc) {
4683   // CancelRegion is only needed for cancel and cancellation_point.
4684   if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
4685     return false;
4686 
4687   if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
4688       CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
4689     return false;
4690 
4691   SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
4692       << getOpenMPDirectiveName(CancelRegion);
4693   return true;
4694 }
4695 
4696 static bool checkNestingOfRegions(Sema &SemaRef, const DSAStackTy *Stack,
4697                                   OpenMPDirectiveKind CurrentRegion,
4698                                   const DeclarationNameInfo &CurrentName,
4699                                   OpenMPDirectiveKind CancelRegion,
4700                                   OpenMPBindClauseKind BindKind,
4701                                   SourceLocation StartLoc) {
4702   if (Stack->getCurScope()) {
4703     OpenMPDirectiveKind ParentRegion = Stack->getParentDirective();
4704     OpenMPDirectiveKind OffendingRegion = ParentRegion;
4705     bool NestingProhibited = false;
4706     bool CloseNesting = true;
4707     bool OrphanSeen = false;
4708     enum {
4709       NoRecommend,
4710       ShouldBeInParallelRegion,
4711       ShouldBeInOrderedRegion,
4712       ShouldBeInTargetRegion,
4713       ShouldBeInTeamsRegion,
4714       ShouldBeInLoopSimdRegion,
4715     } Recommend = NoRecommend;
4716     if (isOpenMPSimdDirective(ParentRegion) &&
4717         ((SemaRef.LangOpts.OpenMP <= 45 && CurrentRegion != OMPD_ordered) ||
4718          (SemaRef.LangOpts.OpenMP >= 50 && CurrentRegion != OMPD_ordered &&
4719           CurrentRegion != OMPD_simd && CurrentRegion != OMPD_atomic &&
4720           CurrentRegion != OMPD_scan))) {
4721       // OpenMP [2.16, Nesting of Regions]
4722       // OpenMP constructs may not be nested inside a simd region.
4723       // OpenMP [2.8.1,simd Construct, Restrictions]
4724       // An ordered construct with the simd clause is the only OpenMP
4725       // construct that can appear in the simd region.
4726       // Allowing a SIMD construct nested in another SIMD construct is an
4727       // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
4728       // message.
4729       // OpenMP 5.0 [2.9.3.1, simd Construct, Restrictions]
4730       // The only OpenMP constructs that can be encountered during execution of
4731       // a simd region are the atomic construct, the loop construct, the simd
4732       // construct and the ordered construct with the simd clause.
4733       SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
4734                                  ? diag::err_omp_prohibited_region_simd
4735                                  : diag::warn_omp_nesting_simd)
4736           << (SemaRef.LangOpts.OpenMP >= 50 ? 1 : 0);
4737       return CurrentRegion != OMPD_simd;
4738     }
4739     if (ParentRegion == OMPD_atomic) {
4740       // OpenMP [2.16, Nesting of Regions]
4741       // OpenMP constructs may not be nested inside an atomic region.
4742       SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
4743       return true;
4744     }
4745     if (CurrentRegion == OMPD_section) {
4746       // OpenMP [2.7.2, sections Construct, Restrictions]
4747       // Orphaned section directives are prohibited. That is, the section
4748       // directives must appear within the sections construct and must not be
4749       // encountered elsewhere in the sections region.
4750       if (ParentRegion != OMPD_sections &&
4751           ParentRegion != OMPD_parallel_sections) {
4752         SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
4753             << (ParentRegion != OMPD_unknown)
4754             << getOpenMPDirectiveName(ParentRegion);
4755         return true;
4756       }
4757       return false;
4758     }
4759     // Allow some constructs (except teams and cancellation constructs) to be
4760     // orphaned (they could be used in functions, called from OpenMP regions
4761     // with the required preconditions).
4762     if (ParentRegion == OMPD_unknown &&
4763         !isOpenMPNestingTeamsDirective(CurrentRegion) &&
4764         CurrentRegion != OMPD_cancellation_point &&
4765         CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_scan)
4766       return false;
4767     if (CurrentRegion == OMPD_cancellation_point ||
4768         CurrentRegion == OMPD_cancel) {
4769       // OpenMP [2.16, Nesting of Regions]
4770       // A cancellation point construct for which construct-type-clause is
4771       // taskgroup must be nested inside a task construct. A cancellation
4772       // point construct for which construct-type-clause is not taskgroup must
4773       // be closely nested inside an OpenMP construct that matches the type
4774       // specified in construct-type-clause.
4775       // A cancel construct for which construct-type-clause is taskgroup must be
4776       // nested inside a task construct. A cancel construct for which
4777       // construct-type-clause is not taskgroup must be closely nested inside an
4778       // OpenMP construct that matches the type specified in
4779       // construct-type-clause.
4780       NestingProhibited =
4781           !((CancelRegion == OMPD_parallel &&
4782              (ParentRegion == OMPD_parallel ||
4783               ParentRegion == OMPD_target_parallel)) ||
4784             (CancelRegion == OMPD_for &&
4785              (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
4786               ParentRegion == OMPD_target_parallel_for ||
4787               ParentRegion == OMPD_distribute_parallel_for ||
4788               ParentRegion == OMPD_teams_distribute_parallel_for ||
4789               ParentRegion == OMPD_target_teams_distribute_parallel_for)) ||
4790             (CancelRegion == OMPD_taskgroup &&
4791              (ParentRegion == OMPD_task ||
4792               (SemaRef.getLangOpts().OpenMP >= 50 &&
4793                (ParentRegion == OMPD_taskloop ||
4794                 ParentRegion == OMPD_master_taskloop ||
4795                 ParentRegion == OMPD_parallel_master_taskloop)))) ||
4796             (CancelRegion == OMPD_sections &&
4797              (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
4798               ParentRegion == OMPD_parallel_sections)));
4799       OrphanSeen = ParentRegion == OMPD_unknown;
4800     } else if (CurrentRegion == OMPD_master || CurrentRegion == OMPD_masked) {
4801       // OpenMP 5.1 [2.22, Nesting of Regions]
4802       // A masked region may not be closely nested inside a worksharing, loop,
4803       // atomic, task, or taskloop region.
4804       NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
4805                           isOpenMPGenericLoopDirective(ParentRegion) ||
4806                           isOpenMPTaskingDirective(ParentRegion);
4807     } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
4808       // OpenMP [2.16, Nesting of Regions]
4809       // A critical region may not be nested (closely or otherwise) inside a
4810       // critical region with the same name. Note that this restriction is not
4811       // sufficient to prevent deadlock.
4812       SourceLocation PreviousCriticalLoc;
4813       bool DeadLock = Stack->hasDirective(
4814           [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
4815                                               const DeclarationNameInfo &DNI,
4816                                               SourceLocation Loc) {
4817             if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
4818               PreviousCriticalLoc = Loc;
4819               return true;
4820             }
4821             return false;
4822           },
4823           false /* skip top directive */);
4824       if (DeadLock) {
4825         SemaRef.Diag(StartLoc,
4826                      diag::err_omp_prohibited_region_critical_same_name)
4827             << CurrentName.getName();
4828         if (PreviousCriticalLoc.isValid())
4829           SemaRef.Diag(PreviousCriticalLoc,
4830                        diag::note_omp_previous_critical_region);
4831         return true;
4832       }
4833     } else if (CurrentRegion == OMPD_barrier) {
4834       // OpenMP 5.1 [2.22, Nesting of Regions]
4835       // A barrier region may not be closely nested inside a worksharing, loop,
4836       // task, taskloop, critical, ordered, atomic, or masked region.
4837       NestingProhibited =
4838           isOpenMPWorksharingDirective(ParentRegion) ||
4839           isOpenMPGenericLoopDirective(ParentRegion) ||
4840           isOpenMPTaskingDirective(ParentRegion) ||
4841           ParentRegion == OMPD_master || ParentRegion == OMPD_masked ||
4842           ParentRegion == OMPD_parallel_master ||
4843           ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered;
4844     } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
4845                !isOpenMPParallelDirective(CurrentRegion) &&
4846                !isOpenMPTeamsDirective(CurrentRegion)) {
4847       // OpenMP 5.1 [2.22, Nesting of Regions]
4848       // A loop region that binds to a parallel region or a worksharing region
4849       // may not be closely nested inside a worksharing, loop, task, taskloop,
4850       // critical, ordered, atomic, or masked region.
4851       NestingProhibited =
4852           isOpenMPWorksharingDirective(ParentRegion) ||
4853           isOpenMPGenericLoopDirective(ParentRegion) ||
4854           isOpenMPTaskingDirective(ParentRegion) ||
4855           ParentRegion == OMPD_master || ParentRegion == OMPD_masked ||
4856           ParentRegion == OMPD_parallel_master ||
4857           ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered;
4858       Recommend = ShouldBeInParallelRegion;
4859     } else if (CurrentRegion == OMPD_ordered) {
4860       // OpenMP [2.16, Nesting of Regions]
4861       // An ordered region may not be closely nested inside a critical,
4862       // atomic, or explicit task region.
4863       // An ordered region must be closely nested inside a loop region (or
4864       // parallel loop region) with an ordered clause.
4865       // OpenMP [2.8.1,simd Construct, Restrictions]
4866       // An ordered construct with the simd clause is the only OpenMP construct
4867       // that can appear in the simd region.
4868       NestingProhibited = ParentRegion == OMPD_critical ||
4869                           isOpenMPTaskingDirective(ParentRegion) ||
4870                           !(isOpenMPSimdDirective(ParentRegion) ||
4871                             Stack->isParentOrderedRegion());
4872       Recommend = ShouldBeInOrderedRegion;
4873     } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
4874       // OpenMP [2.16, Nesting of Regions]
4875       // If specified, a teams construct must be contained within a target
4876       // construct.
4877       NestingProhibited =
4878           (SemaRef.LangOpts.OpenMP <= 45 && ParentRegion != OMPD_target) ||
4879           (SemaRef.LangOpts.OpenMP >= 50 && ParentRegion != OMPD_unknown &&
4880            ParentRegion != OMPD_target);
4881       OrphanSeen = ParentRegion == OMPD_unknown;
4882       Recommend = ShouldBeInTargetRegion;
4883     } else if (CurrentRegion == OMPD_scan) {
4884       // OpenMP [2.16, Nesting of Regions]
4885       // If specified, a teams construct must be contained within a target
4886       // construct.
4887       NestingProhibited =
4888           SemaRef.LangOpts.OpenMP < 50 ||
4889           (ParentRegion != OMPD_simd && ParentRegion != OMPD_for &&
4890            ParentRegion != OMPD_for_simd && ParentRegion != OMPD_parallel_for &&
4891            ParentRegion != OMPD_parallel_for_simd);
4892       OrphanSeen = ParentRegion == OMPD_unknown;
4893       Recommend = ShouldBeInLoopSimdRegion;
4894     }
4895     if (!NestingProhibited &&
4896         !isOpenMPTargetExecutionDirective(CurrentRegion) &&
4897         !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
4898         (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
4899       // OpenMP [5.1, 2.22, Nesting of Regions]
4900       // distribute, distribute simd, distribute parallel worksharing-loop,
4901       // distribute parallel worksharing-loop SIMD, loop, parallel regions,
4902       // including any parallel regions arising from combined constructs,
4903       // omp_get_num_teams() regions, and omp_get_team_num() regions are the
4904       // only OpenMP regions that may be strictly nested inside the teams
4905       // region.
4906       NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
4907                           !isOpenMPDistributeDirective(CurrentRegion) &&
4908                           CurrentRegion != OMPD_loop;
4909       Recommend = ShouldBeInParallelRegion;
4910     }
4911     if (!NestingProhibited && CurrentRegion == OMPD_loop) {
4912       // OpenMP [5.1, 2.11.7, loop Construct, Restrictions]
4913       // If the bind clause is present on the loop construct and binding is
4914       // teams then the corresponding loop region must be strictly nested inside
4915       // a teams region.
4916       NestingProhibited = BindKind == OMPC_BIND_teams &&
4917                           ParentRegion != OMPD_teams &&
4918                           ParentRegion != OMPD_target_teams;
4919       Recommend = ShouldBeInTeamsRegion;
4920     }
4921     if (!NestingProhibited &&
4922         isOpenMPNestingDistributeDirective(CurrentRegion)) {
4923       // OpenMP 4.5 [2.17 Nesting of Regions]
4924       // The region associated with the distribute construct must be strictly
4925       // nested inside a teams region
4926       NestingProhibited =
4927           (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
4928       Recommend = ShouldBeInTeamsRegion;
4929     }
4930     if (!NestingProhibited &&
4931         (isOpenMPTargetExecutionDirective(CurrentRegion) ||
4932          isOpenMPTargetDataManagementDirective(CurrentRegion))) {
4933       // OpenMP 4.5 [2.17 Nesting of Regions]
4934       // If a target, target update, target data, target enter data, or
4935       // target exit data construct is encountered during execution of a
4936       // target region, the behavior is unspecified.
4937       NestingProhibited = Stack->hasDirective(
4938           [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
4939                              SourceLocation) {
4940             if (isOpenMPTargetExecutionDirective(K)) {
4941               OffendingRegion = K;
4942               return true;
4943             }
4944             return false;
4945           },
4946           false /* don't skip top directive */);
4947       CloseNesting = false;
4948     }
4949     if (NestingProhibited) {
4950       if (OrphanSeen) {
4951         SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
4952             << getOpenMPDirectiveName(CurrentRegion) << Recommend;
4953       } else {
4954         SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
4955             << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
4956             << Recommend << getOpenMPDirectiveName(CurrentRegion);
4957       }
4958       return true;
4959     }
4960   }
4961   return false;
4962 }
4963 
4964 struct Kind2Unsigned {
4965   using argument_type = OpenMPDirectiveKind;
4966   unsigned operator()(argument_type DK) { return unsigned(DK); }
4967 };
4968 static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
4969                            ArrayRef<OMPClause *> Clauses,
4970                            ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
4971   bool ErrorFound = false;
4972   unsigned NamedModifiersNumber = 0;
4973   llvm::IndexedMap<const OMPIfClause *, Kind2Unsigned> FoundNameModifiers;
4974   FoundNameModifiers.resize(llvm::omp::Directive_enumSize + 1);
4975   SmallVector<SourceLocation, 4> NameModifierLoc;
4976   for (const OMPClause *C : Clauses) {
4977     if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
4978       // At most one if clause without a directive-name-modifier can appear on
4979       // the directive.
4980       OpenMPDirectiveKind CurNM = IC->getNameModifier();
4981       if (FoundNameModifiers[CurNM]) {
4982         S.Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
4983             << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
4984             << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
4985         ErrorFound = true;
4986       } else if (CurNM != OMPD_unknown) {
4987         NameModifierLoc.push_back(IC->getNameModifierLoc());
4988         ++NamedModifiersNumber;
4989       }
4990       FoundNameModifiers[CurNM] = IC;
4991       if (CurNM == OMPD_unknown)
4992         continue;
4993       // Check if the specified name modifier is allowed for the current
4994       // directive.
4995       // At most one if clause with the particular directive-name-modifier can
4996       // appear on the directive.
4997       if (!llvm::is_contained(AllowedNameModifiers, CurNM)) {
4998         S.Diag(IC->getNameModifierLoc(),
4999                diag::err_omp_wrong_if_directive_name_modifier)
5000             << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
5001         ErrorFound = true;
5002       }
5003     }
5004   }
5005   // If any if clause on the directive includes a directive-name-modifier then
5006   // all if clauses on the directive must include a directive-name-modifier.
5007   if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
5008     if (NamedModifiersNumber == AllowedNameModifiers.size()) {
5009       S.Diag(FoundNameModifiers[OMPD_unknown]->getBeginLoc(),
5010              diag::err_omp_no_more_if_clause);
5011     } else {
5012       std::string Values;
5013       std::string Sep(", ");
5014       unsigned AllowedCnt = 0;
5015       unsigned TotalAllowedNum =
5016           AllowedNameModifiers.size() - NamedModifiersNumber;
5017       for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
5018            ++Cnt) {
5019         OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
5020         if (!FoundNameModifiers[NM]) {
5021           Values += "'";
5022           Values += getOpenMPDirectiveName(NM);
5023           Values += "'";
5024           if (AllowedCnt + 2 == TotalAllowedNum)
5025             Values += " or ";
5026           else if (AllowedCnt + 1 != TotalAllowedNum)
5027             Values += Sep;
5028           ++AllowedCnt;
5029         }
5030       }
5031       S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getBeginLoc(),
5032              diag::err_omp_unnamed_if_clause)
5033           << (TotalAllowedNum > 1) << Values;
5034     }
5035     for (SourceLocation Loc : NameModifierLoc) {
5036       S.Diag(Loc, diag::note_omp_previous_named_if_clause);
5037     }
5038     ErrorFound = true;
5039   }
5040   return ErrorFound;
5041 }
5042 
5043 static std::pair<ValueDecl *, bool> getPrivateItem(Sema &S, Expr *&RefExpr,
5044                                                    SourceLocation &ELoc,
5045                                                    SourceRange &ERange,
5046                                                    bool AllowArraySection) {
5047   if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
5048       RefExpr->containsUnexpandedParameterPack())
5049     return std::make_pair(nullptr, true);
5050 
5051   // OpenMP [3.1, C/C++]
5052   //  A list item is a variable name.
5053   // OpenMP  [2.9.3.3, Restrictions, p.1]
5054   //  A variable that is part of another variable (as an array or
5055   //  structure element) cannot appear in a private clause.
5056   RefExpr = RefExpr->IgnoreParens();
5057   enum {
5058     NoArrayExpr = -1,
5059     ArraySubscript = 0,
5060     OMPArraySection = 1
5061   } IsArrayExpr = NoArrayExpr;
5062   if (AllowArraySection) {
5063     if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
5064       Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
5065       while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
5066         Base = TempASE->getBase()->IgnoreParenImpCasts();
5067       RefExpr = Base;
5068       IsArrayExpr = ArraySubscript;
5069     } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
5070       Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
5071       while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
5072         Base = TempOASE->getBase()->IgnoreParenImpCasts();
5073       while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
5074         Base = TempASE->getBase()->IgnoreParenImpCasts();
5075       RefExpr = Base;
5076       IsArrayExpr = OMPArraySection;
5077     }
5078   }
5079   ELoc = RefExpr->getExprLoc();
5080   ERange = RefExpr->getSourceRange();
5081   RefExpr = RefExpr->IgnoreParenImpCasts();
5082   auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
5083   auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
5084   if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
5085       (S.getCurrentThisType().isNull() || !ME ||
5086        !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
5087        !isa<FieldDecl>(ME->getMemberDecl()))) {
5088     if (IsArrayExpr != NoArrayExpr) {
5089       S.Diag(ELoc, diag::err_omp_expected_base_var_name)
5090           << IsArrayExpr << ERange;
5091     } else {
5092       S.Diag(ELoc,
5093              AllowArraySection
5094                  ? diag::err_omp_expected_var_name_member_expr_or_array_item
5095                  : diag::err_omp_expected_var_name_member_expr)
5096           << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
5097     }
5098     return std::make_pair(nullptr, false);
5099   }
5100   return std::make_pair(
5101       getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false);
5102 }
5103 
5104 namespace {
5105 /// Checks if the allocator is used in uses_allocators clause to be allowed in
5106 /// target regions.
5107 class AllocatorChecker final : public ConstStmtVisitor<AllocatorChecker, bool> {
5108   DSAStackTy *S = nullptr;
5109 
5110 public:
5111   bool VisitDeclRefExpr(const DeclRefExpr *E) {
5112     return S->isUsesAllocatorsDecl(E->getDecl())
5113                .getValueOr(
5114                    DSAStackTy::UsesAllocatorsDeclKind::AllocatorTrait) ==
5115            DSAStackTy::UsesAllocatorsDeclKind::AllocatorTrait;
5116   }
5117   bool VisitStmt(const Stmt *S) {
5118     for (const Stmt *Child : S->children()) {
5119       if (Child && Visit(Child))
5120         return true;
5121     }
5122     return false;
5123   }
5124   explicit AllocatorChecker(DSAStackTy *S) : S(S) {}
5125 };
5126 } // namespace
5127 
5128 static void checkAllocateClauses(Sema &S, DSAStackTy *Stack,
5129                                  ArrayRef<OMPClause *> Clauses) {
5130   assert(!S.CurContext->isDependentContext() &&
5131          "Expected non-dependent context.");
5132   auto AllocateRange =
5133       llvm::make_filter_range(Clauses, OMPAllocateClause::classof);
5134   llvm::DenseMap<CanonicalDeclPtr<Decl>, CanonicalDeclPtr<VarDecl>> DeclToCopy;
5135   auto PrivateRange = llvm::make_filter_range(Clauses, [](const OMPClause *C) {
5136     return isOpenMPPrivate(C->getClauseKind());
5137   });
5138   for (OMPClause *Cl : PrivateRange) {
5139     MutableArrayRef<Expr *>::iterator I, It, Et;
5140     if (Cl->getClauseKind() == OMPC_private) {
5141       auto *PC = cast<OMPPrivateClause>(Cl);
5142       I = PC->private_copies().begin();
5143       It = PC->varlist_begin();
5144       Et = PC->varlist_end();
5145     } else if (Cl->getClauseKind() == OMPC_firstprivate) {
5146       auto *PC = cast<OMPFirstprivateClause>(Cl);
5147       I = PC->private_copies().begin();
5148       It = PC->varlist_begin();
5149       Et = PC->varlist_end();
5150     } else if (Cl->getClauseKind() == OMPC_lastprivate) {
5151       auto *PC = cast<OMPLastprivateClause>(Cl);
5152       I = PC->private_copies().begin();
5153       It = PC->varlist_begin();
5154       Et = PC->varlist_end();
5155     } else if (Cl->getClauseKind() == OMPC_linear) {
5156       auto *PC = cast<OMPLinearClause>(Cl);
5157       I = PC->privates().begin();
5158       It = PC->varlist_begin();
5159       Et = PC->varlist_end();
5160     } else if (Cl->getClauseKind() == OMPC_reduction) {
5161       auto *PC = cast<OMPReductionClause>(Cl);
5162       I = PC->privates().begin();
5163       It = PC->varlist_begin();
5164       Et = PC->varlist_end();
5165     } else if (Cl->getClauseKind() == OMPC_task_reduction) {
5166       auto *PC = cast<OMPTaskReductionClause>(Cl);
5167       I = PC->privates().begin();
5168       It = PC->varlist_begin();
5169       Et = PC->varlist_end();
5170     } else if (Cl->getClauseKind() == OMPC_in_reduction) {
5171       auto *PC = cast<OMPInReductionClause>(Cl);
5172       I = PC->privates().begin();
5173       It = PC->varlist_begin();
5174       Et = PC->varlist_end();
5175     } else {
5176       llvm_unreachable("Expected private clause.");
5177     }
5178     for (Expr *E : llvm::make_range(It, Et)) {
5179       if (!*I) {
5180         ++I;
5181         continue;
5182       }
5183       SourceLocation ELoc;
5184       SourceRange ERange;
5185       Expr *SimpleRefExpr = E;
5186       auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
5187                                 /*AllowArraySection=*/true);
5188       DeclToCopy.try_emplace(Res.first,
5189                              cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()));
5190       ++I;
5191     }
5192   }
5193   for (OMPClause *C : AllocateRange) {
5194     auto *AC = cast<OMPAllocateClause>(C);
5195     if (S.getLangOpts().OpenMP >= 50 &&
5196         !Stack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>() &&
5197         isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
5198         AC->getAllocator()) {
5199       Expr *Allocator = AC->getAllocator();
5200       // OpenMP, 2.12.5 target Construct
5201       // Memory allocators that do not appear in a uses_allocators clause cannot
5202       // appear as an allocator in an allocate clause or be used in the target
5203       // region unless a requires directive with the dynamic_allocators clause
5204       // is present in the same compilation unit.
5205       AllocatorChecker Checker(Stack);
5206       if (Checker.Visit(Allocator))
5207         S.Diag(Allocator->getExprLoc(),
5208                diag::err_omp_allocator_not_in_uses_allocators)
5209             << Allocator->getSourceRange();
5210     }
5211     OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind =
5212         getAllocatorKind(S, Stack, AC->getAllocator());
5213     // OpenMP, 2.11.4 allocate Clause, Restrictions.
5214     // For task, taskloop or target directives, allocation requests to memory
5215     // allocators with the trait access set to thread result in unspecified
5216     // behavior.
5217     if (AllocatorKind == OMPAllocateDeclAttr::OMPThreadMemAlloc &&
5218         (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
5219          isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()))) {
5220       S.Diag(AC->getAllocator()->getExprLoc(),
5221              diag::warn_omp_allocate_thread_on_task_target_directive)
5222           << getOpenMPDirectiveName(Stack->getCurrentDirective());
5223     }
5224     for (Expr *E : AC->varlists()) {
5225       SourceLocation ELoc;
5226       SourceRange ERange;
5227       Expr *SimpleRefExpr = E;
5228       auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange);
5229       ValueDecl *VD = Res.first;
5230       DSAStackTy::DSAVarData Data = Stack->getTopDSA(VD, /*FromParent=*/false);
5231       if (!isOpenMPPrivate(Data.CKind)) {
5232         S.Diag(E->getExprLoc(),
5233                diag::err_omp_expected_private_copy_for_allocate);
5234         continue;
5235       }
5236       VarDecl *PrivateVD = DeclToCopy[VD];
5237       if (checkPreviousOMPAllocateAttribute(S, Stack, E, PrivateVD,
5238                                             AllocatorKind, AC->getAllocator()))
5239         continue;
5240       // Placeholder until allocate clause supports align modifier.
5241       Expr *Alignment = nullptr;
5242       applyOMPAllocateAttribute(S, PrivateVD, AllocatorKind, AC->getAllocator(),
5243                                 Alignment, E->getSourceRange());
5244     }
5245   }
5246 }
5247 
5248 namespace {
5249 /// Rewrite statements and expressions for Sema \p Actions CurContext.
5250 ///
5251 /// Used to wrap already parsed statements/expressions into a new CapturedStmt
5252 /// context. DeclRefExpr used inside the new context are changed to refer to the
5253 /// captured variable instead.
5254 class CaptureVars : public TreeTransform<CaptureVars> {
5255   using BaseTransform = TreeTransform<CaptureVars>;
5256 
5257 public:
5258   CaptureVars(Sema &Actions) : BaseTransform(Actions) {}
5259 
5260   bool AlwaysRebuild() { return true; }
5261 };
5262 } // namespace
5263 
5264 static VarDecl *precomputeExpr(Sema &Actions,
5265                                SmallVectorImpl<Stmt *> &BodyStmts, Expr *E,
5266                                StringRef Name) {
5267   Expr *NewE = AssertSuccess(CaptureVars(Actions).TransformExpr(E));
5268   VarDecl *NewVar = buildVarDecl(Actions, {}, NewE->getType(), Name, nullptr,
5269                                  dyn_cast<DeclRefExpr>(E->IgnoreImplicit()));
5270   auto *NewDeclStmt = cast<DeclStmt>(AssertSuccess(
5271       Actions.ActOnDeclStmt(Actions.ConvertDeclToDeclGroup(NewVar), {}, {})));
5272   Actions.AddInitializerToDecl(NewDeclStmt->getSingleDecl(), NewE, false);
5273   BodyStmts.push_back(NewDeclStmt);
5274   return NewVar;
5275 }
5276 
5277 /// Create a closure that computes the number of iterations of a loop.
5278 ///
5279 /// \param Actions   The Sema object.
5280 /// \param LogicalTy Type for the logical iteration number.
5281 /// \param Rel       Comparison operator of the loop condition.
5282 /// \param StartExpr Value of the loop counter at the first iteration.
5283 /// \param StopExpr  Expression the loop counter is compared against in the loop
5284 /// condition. \param StepExpr      Amount of increment after each iteration.
5285 ///
5286 /// \return Closure (CapturedStmt) of the distance calculation.
5287 static CapturedStmt *buildDistanceFunc(Sema &Actions, QualType LogicalTy,
5288                                        BinaryOperator::Opcode Rel,
5289                                        Expr *StartExpr, Expr *StopExpr,
5290                                        Expr *StepExpr) {
5291   ASTContext &Ctx = Actions.getASTContext();
5292   TypeSourceInfo *LogicalTSI = Ctx.getTrivialTypeSourceInfo(LogicalTy);
5293 
5294   // Captured regions currently don't support return values, we use an
5295   // out-parameter instead. All inputs are implicit captures.
5296   // TODO: Instead of capturing each DeclRefExpr occurring in
5297   // StartExpr/StopExpr/Step, these could also be passed as a value capture.
5298   QualType ResultTy = Ctx.getLValueReferenceType(LogicalTy);
5299   Sema::CapturedParamNameType Params[] = {{"Distance", ResultTy},
5300                                           {StringRef(), QualType()}};
5301   Actions.ActOnCapturedRegionStart({}, nullptr, CR_Default, Params);
5302 
5303   Stmt *Body;
5304   {
5305     Sema::CompoundScopeRAII CompoundScope(Actions);
5306     CapturedDecl *CS = cast<CapturedDecl>(Actions.CurContext);
5307 
5308     // Get the LValue expression for the result.
5309     ImplicitParamDecl *DistParam = CS->getParam(0);
5310     DeclRefExpr *DistRef = Actions.BuildDeclRefExpr(
5311         DistParam, LogicalTy, VK_LValue, {}, nullptr, nullptr, {}, nullptr);
5312 
5313     SmallVector<Stmt *, 4> BodyStmts;
5314 
5315     // Capture all referenced variable references.
5316     // TODO: Instead of computing NewStart/NewStop/NewStep inside the
5317     // CapturedStmt, we could compute them before and capture the result, to be
5318     // used jointly with the LoopVar function.
5319     VarDecl *NewStart = precomputeExpr(Actions, BodyStmts, StartExpr, ".start");
5320     VarDecl *NewStop = precomputeExpr(Actions, BodyStmts, StopExpr, ".stop");
5321     VarDecl *NewStep = precomputeExpr(Actions, BodyStmts, StepExpr, ".step");
5322     auto BuildVarRef = [&](VarDecl *VD) {
5323       return buildDeclRefExpr(Actions, VD, VD->getType(), {});
5324     };
5325 
5326     IntegerLiteral *Zero = IntegerLiteral::Create(
5327         Ctx, llvm::APInt(Ctx.getIntWidth(LogicalTy), 0), LogicalTy, {});
5328     Expr *Dist;
5329     if (Rel == BO_NE) {
5330       // When using a != comparison, the increment can be +1 or -1. This can be
5331       // dynamic at runtime, so we need to check for the direction.
5332       Expr *IsNegStep = AssertSuccess(
5333           Actions.BuildBinOp(nullptr, {}, BO_LT, BuildVarRef(NewStep), Zero));
5334 
5335       // Positive increment.
5336       Expr *ForwardRange = AssertSuccess(Actions.BuildBinOp(
5337           nullptr, {}, BO_Sub, BuildVarRef(NewStop), BuildVarRef(NewStart)));
5338       ForwardRange = AssertSuccess(
5339           Actions.BuildCStyleCastExpr({}, LogicalTSI, {}, ForwardRange));
5340       Expr *ForwardDist = AssertSuccess(Actions.BuildBinOp(
5341           nullptr, {}, BO_Div, ForwardRange, BuildVarRef(NewStep)));
5342 
5343       // Negative increment.
5344       Expr *BackwardRange = AssertSuccess(Actions.BuildBinOp(
5345           nullptr, {}, BO_Sub, BuildVarRef(NewStart), BuildVarRef(NewStop)));
5346       BackwardRange = AssertSuccess(
5347           Actions.BuildCStyleCastExpr({}, LogicalTSI, {}, BackwardRange));
5348       Expr *NegIncAmount = AssertSuccess(
5349           Actions.BuildUnaryOp(nullptr, {}, UO_Minus, BuildVarRef(NewStep)));
5350       Expr *BackwardDist = AssertSuccess(
5351           Actions.BuildBinOp(nullptr, {}, BO_Div, BackwardRange, NegIncAmount));
5352 
5353       // Use the appropriate case.
5354       Dist = AssertSuccess(Actions.ActOnConditionalOp(
5355           {}, {}, IsNegStep, BackwardDist, ForwardDist));
5356     } else {
5357       assert((Rel == BO_LT || Rel == BO_LE || Rel == BO_GE || Rel == BO_GT) &&
5358              "Expected one of these relational operators");
5359 
5360       // We can derive the direction from any other comparison operator. It is
5361       // non well-formed OpenMP if Step increments/decrements in the other
5362       // directions. Whether at least the first iteration passes the loop
5363       // condition.
5364       Expr *HasAnyIteration = AssertSuccess(Actions.BuildBinOp(
5365           nullptr, {}, Rel, BuildVarRef(NewStart), BuildVarRef(NewStop)));
5366 
5367       // Compute the range between first and last counter value.
5368       Expr *Range;
5369       if (Rel == BO_GE || Rel == BO_GT)
5370         Range = AssertSuccess(Actions.BuildBinOp(
5371             nullptr, {}, BO_Sub, BuildVarRef(NewStart), BuildVarRef(NewStop)));
5372       else
5373         Range = AssertSuccess(Actions.BuildBinOp(
5374             nullptr, {}, BO_Sub, BuildVarRef(NewStop), BuildVarRef(NewStart)));
5375 
5376       // Ensure unsigned range space.
5377       Range =
5378           AssertSuccess(Actions.BuildCStyleCastExpr({}, LogicalTSI, {}, Range));
5379 
5380       if (Rel == BO_LE || Rel == BO_GE) {
5381         // Add one to the range if the relational operator is inclusive.
5382         Range = AssertSuccess(Actions.BuildBinOp(
5383             nullptr, {}, BO_Add, Range,
5384             Actions.ActOnIntegerConstant(SourceLocation(), 1).get()));
5385       }
5386 
5387       // Divide by the absolute step amount.
5388       Expr *Divisor = BuildVarRef(NewStep);
5389       if (Rel == BO_GE || Rel == BO_GT)
5390         Divisor =
5391             AssertSuccess(Actions.BuildUnaryOp(nullptr, {}, UO_Minus, Divisor));
5392       Dist = AssertSuccess(
5393           Actions.BuildBinOp(nullptr, {}, BO_Div, Range, Divisor));
5394 
5395       // If there is not at least one iteration, the range contains garbage. Fix
5396       // to zero in this case.
5397       Dist = AssertSuccess(
5398           Actions.ActOnConditionalOp({}, {}, HasAnyIteration, Dist, Zero));
5399     }
5400 
5401     // Assign the result to the out-parameter.
5402     Stmt *ResultAssign = AssertSuccess(Actions.BuildBinOp(
5403         Actions.getCurScope(), {}, BO_Assign, DistRef, Dist));
5404     BodyStmts.push_back(ResultAssign);
5405 
5406     Body = AssertSuccess(Actions.ActOnCompoundStmt({}, {}, BodyStmts, false));
5407   }
5408 
5409   return cast<CapturedStmt>(
5410       AssertSuccess(Actions.ActOnCapturedRegionEnd(Body)));
5411 }
5412 
5413 /// Create a closure that computes the loop variable from the logical iteration
5414 /// number.
5415 ///
5416 /// \param Actions   The Sema object.
5417 /// \param LoopVarTy Type for the loop variable used for result value.
5418 /// \param LogicalTy Type for the logical iteration number.
5419 /// \param StartExpr Value of the loop counter at the first iteration.
5420 /// \param Step      Amount of increment after each iteration.
5421 /// \param Deref     Whether the loop variable is a dereference of the loop
5422 /// counter variable.
5423 ///
5424 /// \return Closure (CapturedStmt) of the loop value calculation.
5425 static CapturedStmt *buildLoopVarFunc(Sema &Actions, QualType LoopVarTy,
5426                                       QualType LogicalTy,
5427                                       DeclRefExpr *StartExpr, Expr *Step,
5428                                       bool Deref) {
5429   ASTContext &Ctx = Actions.getASTContext();
5430 
5431   // Pass the result as an out-parameter. Passing as return value would require
5432   // the OpenMPIRBuilder to know additional C/C++ semantics, such as how to
5433   // invoke a copy constructor.
5434   QualType TargetParamTy = Ctx.getLValueReferenceType(LoopVarTy);
5435   Sema::CapturedParamNameType Params[] = {{"LoopVar", TargetParamTy},
5436                                           {"Logical", LogicalTy},
5437                                           {StringRef(), QualType()}};
5438   Actions.ActOnCapturedRegionStart({}, nullptr, CR_Default, Params);
5439 
5440   // Capture the initial iterator which represents the LoopVar value at the
5441   // zero's logical iteration. Since the original ForStmt/CXXForRangeStmt update
5442   // it in every iteration, capture it by value before it is modified.
5443   VarDecl *StartVar = cast<VarDecl>(StartExpr->getDecl());
5444   bool Invalid = Actions.tryCaptureVariable(StartVar, {},
5445                                             Sema::TryCapture_ExplicitByVal, {});
5446   (void)Invalid;
5447   assert(!Invalid && "Expecting capture-by-value to work.");
5448 
5449   Expr *Body;
5450   {
5451     Sema::CompoundScopeRAII CompoundScope(Actions);
5452     auto *CS = cast<CapturedDecl>(Actions.CurContext);
5453 
5454     ImplicitParamDecl *TargetParam = CS->getParam(0);
5455     DeclRefExpr *TargetRef = Actions.BuildDeclRefExpr(
5456         TargetParam, LoopVarTy, VK_LValue, {}, nullptr, nullptr, {}, nullptr);
5457     ImplicitParamDecl *IndvarParam = CS->getParam(1);
5458     DeclRefExpr *LogicalRef = Actions.BuildDeclRefExpr(
5459         IndvarParam, LogicalTy, VK_LValue, {}, nullptr, nullptr, {}, nullptr);
5460 
5461     // Capture the Start expression.
5462     CaptureVars Recap(Actions);
5463     Expr *NewStart = AssertSuccess(Recap.TransformExpr(StartExpr));
5464     Expr *NewStep = AssertSuccess(Recap.TransformExpr(Step));
5465 
5466     Expr *Skip = AssertSuccess(
5467         Actions.BuildBinOp(nullptr, {}, BO_Mul, NewStep, LogicalRef));
5468     // TODO: Explicitly cast to the iterator's difference_type instead of
5469     // relying on implicit conversion.
5470     Expr *Advanced =
5471         AssertSuccess(Actions.BuildBinOp(nullptr, {}, BO_Add, NewStart, Skip));
5472 
5473     if (Deref) {
5474       // For range-based for-loops convert the loop counter value to a concrete
5475       // loop variable value by dereferencing the iterator.
5476       Advanced =
5477           AssertSuccess(Actions.BuildUnaryOp(nullptr, {}, UO_Deref, Advanced));
5478     }
5479 
5480     // Assign the result to the output parameter.
5481     Body = AssertSuccess(Actions.BuildBinOp(Actions.getCurScope(), {},
5482                                             BO_Assign, TargetRef, Advanced));
5483   }
5484   return cast<CapturedStmt>(
5485       AssertSuccess(Actions.ActOnCapturedRegionEnd(Body)));
5486 }
5487 
5488 StmtResult Sema::ActOnOpenMPCanonicalLoop(Stmt *AStmt) {
5489   ASTContext &Ctx = getASTContext();
5490 
5491   // Extract the common elements of ForStmt and CXXForRangeStmt:
5492   // Loop variable, repeat condition, increment
5493   Expr *Cond, *Inc;
5494   VarDecl *LIVDecl, *LUVDecl;
5495   if (auto *For = dyn_cast<ForStmt>(AStmt)) {
5496     Stmt *Init = For->getInit();
5497     if (auto *LCVarDeclStmt = dyn_cast<DeclStmt>(Init)) {
5498       // For statement declares loop variable.
5499       LIVDecl = cast<VarDecl>(LCVarDeclStmt->getSingleDecl());
5500     } else if (auto *LCAssign = dyn_cast<BinaryOperator>(Init)) {
5501       // For statement reuses variable.
5502       assert(LCAssign->getOpcode() == BO_Assign &&
5503              "init part must be a loop variable assignment");
5504       auto *CounterRef = cast<DeclRefExpr>(LCAssign->getLHS());
5505       LIVDecl = cast<VarDecl>(CounterRef->getDecl());
5506     } else
5507       llvm_unreachable("Cannot determine loop variable");
5508     LUVDecl = LIVDecl;
5509 
5510     Cond = For->getCond();
5511     Inc = For->getInc();
5512   } else if (auto *RangeFor = dyn_cast<CXXForRangeStmt>(AStmt)) {
5513     DeclStmt *BeginStmt = RangeFor->getBeginStmt();
5514     LIVDecl = cast<VarDecl>(BeginStmt->getSingleDecl());
5515     LUVDecl = RangeFor->getLoopVariable();
5516 
5517     Cond = RangeFor->getCond();
5518     Inc = RangeFor->getInc();
5519   } else
5520     llvm_unreachable("unhandled kind of loop");
5521 
5522   QualType CounterTy = LIVDecl->getType();
5523   QualType LVTy = LUVDecl->getType();
5524 
5525   // Analyze the loop condition.
5526   Expr *LHS, *RHS;
5527   BinaryOperator::Opcode CondRel;
5528   Cond = Cond->IgnoreImplicit();
5529   if (auto *CondBinExpr = dyn_cast<BinaryOperator>(Cond)) {
5530     LHS = CondBinExpr->getLHS();
5531     RHS = CondBinExpr->getRHS();
5532     CondRel = CondBinExpr->getOpcode();
5533   } else if (auto *CondCXXOp = dyn_cast<CXXOperatorCallExpr>(Cond)) {
5534     assert(CondCXXOp->getNumArgs() == 2 && "Comparison should have 2 operands");
5535     LHS = CondCXXOp->getArg(0);
5536     RHS = CondCXXOp->getArg(1);
5537     switch (CondCXXOp->getOperator()) {
5538     case OO_ExclaimEqual:
5539       CondRel = BO_NE;
5540       break;
5541     case OO_Less:
5542       CondRel = BO_LT;
5543       break;
5544     case OO_LessEqual:
5545       CondRel = BO_LE;
5546       break;
5547     case OO_Greater:
5548       CondRel = BO_GT;
5549       break;
5550     case OO_GreaterEqual:
5551       CondRel = BO_GE;
5552       break;
5553     default:
5554       llvm_unreachable("unexpected iterator operator");
5555     }
5556   } else
5557     llvm_unreachable("unexpected loop condition");
5558 
5559   // Normalize such that the loop counter is on the LHS.
5560   if (!isa<DeclRefExpr>(LHS->IgnoreImplicit()) ||
5561       cast<DeclRefExpr>(LHS->IgnoreImplicit())->getDecl() != LIVDecl) {
5562     std::swap(LHS, RHS);
5563     CondRel = BinaryOperator::reverseComparisonOp(CondRel);
5564   }
5565   auto *CounterRef = cast<DeclRefExpr>(LHS->IgnoreImplicit());
5566 
5567   // Decide the bit width for the logical iteration counter. By default use the
5568   // unsigned ptrdiff_t integer size (for iterators and pointers).
5569   // TODO: For iterators, use iterator::difference_type,
5570   // std::iterator_traits<>::difference_type or decltype(it - end).
5571   QualType LogicalTy = Ctx.getUnsignedPointerDiffType();
5572   if (CounterTy->isIntegerType()) {
5573     unsigned BitWidth = Ctx.getIntWidth(CounterTy);
5574     LogicalTy = Ctx.getIntTypeForBitwidth(BitWidth, false);
5575   }
5576 
5577   // Analyze the loop increment.
5578   Expr *Step;
5579   if (auto *IncUn = dyn_cast<UnaryOperator>(Inc)) {
5580     int Direction;
5581     switch (IncUn->getOpcode()) {
5582     case UO_PreInc:
5583     case UO_PostInc:
5584       Direction = 1;
5585       break;
5586     case UO_PreDec:
5587     case UO_PostDec:
5588       Direction = -1;
5589       break;
5590     default:
5591       llvm_unreachable("unhandled unary increment operator");
5592     }
5593     Step = IntegerLiteral::Create(
5594         Ctx, llvm::APInt(Ctx.getIntWidth(LogicalTy), Direction), LogicalTy, {});
5595   } else if (auto *IncBin = dyn_cast<BinaryOperator>(Inc)) {
5596     if (IncBin->getOpcode() == BO_AddAssign) {
5597       Step = IncBin->getRHS();
5598     } else if (IncBin->getOpcode() == BO_SubAssign) {
5599       Step =
5600           AssertSuccess(BuildUnaryOp(nullptr, {}, UO_Minus, IncBin->getRHS()));
5601     } else
5602       llvm_unreachable("unhandled binary increment operator");
5603   } else if (auto *CondCXXOp = dyn_cast<CXXOperatorCallExpr>(Inc)) {
5604     switch (CondCXXOp->getOperator()) {
5605     case OO_PlusPlus:
5606       Step = IntegerLiteral::Create(
5607           Ctx, llvm::APInt(Ctx.getIntWidth(LogicalTy), 1), LogicalTy, {});
5608       break;
5609     case OO_MinusMinus:
5610       Step = IntegerLiteral::Create(
5611           Ctx, llvm::APInt(Ctx.getIntWidth(LogicalTy), -1), LogicalTy, {});
5612       break;
5613     case OO_PlusEqual:
5614       Step = CondCXXOp->getArg(1);
5615       break;
5616     case OO_MinusEqual:
5617       Step = AssertSuccess(
5618           BuildUnaryOp(nullptr, {}, UO_Minus, CondCXXOp->getArg(1)));
5619       break;
5620     default:
5621       llvm_unreachable("unhandled overloaded increment operator");
5622     }
5623   } else
5624     llvm_unreachable("unknown increment expression");
5625 
5626   CapturedStmt *DistanceFunc =
5627       buildDistanceFunc(*this, LogicalTy, CondRel, LHS, RHS, Step);
5628   CapturedStmt *LoopVarFunc = buildLoopVarFunc(
5629       *this, LVTy, LogicalTy, CounterRef, Step, isa<CXXForRangeStmt>(AStmt));
5630   DeclRefExpr *LVRef = BuildDeclRefExpr(LUVDecl, LUVDecl->getType(), VK_LValue,
5631                                         {}, nullptr, nullptr, {}, nullptr);
5632   return OMPCanonicalLoop::create(getASTContext(), AStmt, DistanceFunc,
5633                                   LoopVarFunc, LVRef);
5634 }
5635 
5636 StmtResult Sema::ActOnOpenMPLoopnest(Stmt *AStmt) {
5637   // Handle a literal loop.
5638   if (isa<ForStmt>(AStmt) || isa<CXXForRangeStmt>(AStmt))
5639     return ActOnOpenMPCanonicalLoop(AStmt);
5640 
5641   // If not a literal loop, it must be the result of a loop transformation.
5642   OMPExecutableDirective *LoopTransform = cast<OMPExecutableDirective>(AStmt);
5643   assert(
5644       isOpenMPLoopTransformationDirective(LoopTransform->getDirectiveKind()) &&
5645       "Loop transformation directive expected");
5646   return LoopTransform;
5647 }
5648 
5649 static ExprResult buildUserDefinedMapperRef(Sema &SemaRef, Scope *S,
5650                                             CXXScopeSpec &MapperIdScopeSpec,
5651                                             const DeclarationNameInfo &MapperId,
5652                                             QualType Type,
5653                                             Expr *UnresolvedMapper);
5654 
5655 /// Perform DFS through the structure/class data members trying to find
5656 /// member(s) with user-defined 'default' mapper and generate implicit map
5657 /// clauses for such members with the found 'default' mapper.
5658 static void
5659 processImplicitMapsWithDefaultMappers(Sema &S, DSAStackTy *Stack,
5660                                       SmallVectorImpl<OMPClause *> &Clauses) {
5661   // Check for the deault mapper for data members.
5662   if (S.getLangOpts().OpenMP < 50)
5663     return;
5664   SmallVector<OMPClause *, 4> ImplicitMaps;
5665   for (int Cnt = 0, EndCnt = Clauses.size(); Cnt < EndCnt; ++Cnt) {
5666     auto *C = dyn_cast<OMPMapClause>(Clauses[Cnt]);
5667     if (!C)
5668       continue;
5669     SmallVector<Expr *, 4> SubExprs;
5670     auto *MI = C->mapperlist_begin();
5671     for (auto I = C->varlist_begin(), End = C->varlist_end(); I != End;
5672          ++I, ++MI) {
5673       // Expression is mapped using mapper - skip it.
5674       if (*MI)
5675         continue;
5676       Expr *E = *I;
5677       // Expression is dependent - skip it, build the mapper when it gets
5678       // instantiated.
5679       if (E->isTypeDependent() || E->isValueDependent() ||
5680           E->containsUnexpandedParameterPack())
5681         continue;
5682       // Array section - need to check for the mapping of the array section
5683       // element.
5684       QualType CanonType = E->getType().getCanonicalType();
5685       if (CanonType->isSpecificBuiltinType(BuiltinType::OMPArraySection)) {
5686         const auto *OASE = cast<OMPArraySectionExpr>(E->IgnoreParenImpCasts());
5687         QualType BaseType =
5688             OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
5689         QualType ElemType;
5690         if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
5691           ElemType = ATy->getElementType();
5692         else
5693           ElemType = BaseType->getPointeeType();
5694         CanonType = ElemType;
5695       }
5696 
5697       // DFS over data members in structures/classes.
5698       SmallVector<std::pair<QualType, FieldDecl *>, 4> Types(
5699           1, {CanonType, nullptr});
5700       llvm::DenseMap<const Type *, Expr *> Visited;
5701       SmallVector<std::pair<FieldDecl *, unsigned>, 4> ParentChain(
5702           1, {nullptr, 1});
5703       while (!Types.empty()) {
5704         QualType BaseType;
5705         FieldDecl *CurFD;
5706         std::tie(BaseType, CurFD) = Types.pop_back_val();
5707         while (ParentChain.back().second == 0)
5708           ParentChain.pop_back();
5709         --ParentChain.back().second;
5710         if (BaseType.isNull())
5711           continue;
5712         // Only structs/classes are allowed to have mappers.
5713         const RecordDecl *RD = BaseType.getCanonicalType()->getAsRecordDecl();
5714         if (!RD)
5715           continue;
5716         auto It = Visited.find(BaseType.getTypePtr());
5717         if (It == Visited.end()) {
5718           // Try to find the associated user-defined mapper.
5719           CXXScopeSpec MapperIdScopeSpec;
5720           DeclarationNameInfo DefaultMapperId;
5721           DefaultMapperId.setName(S.Context.DeclarationNames.getIdentifier(
5722               &S.Context.Idents.get("default")));
5723           DefaultMapperId.setLoc(E->getExprLoc());
5724           ExprResult ER = buildUserDefinedMapperRef(
5725               S, Stack->getCurScope(), MapperIdScopeSpec, DefaultMapperId,
5726               BaseType, /*UnresolvedMapper=*/nullptr);
5727           if (ER.isInvalid())
5728             continue;
5729           It = Visited.try_emplace(BaseType.getTypePtr(), ER.get()).first;
5730         }
5731         // Found default mapper.
5732         if (It->second) {
5733           auto *OE = new (S.Context) OpaqueValueExpr(E->getExprLoc(), CanonType,
5734                                                      VK_LValue, OK_Ordinary, E);
5735           OE->setIsUnique(/*V=*/true);
5736           Expr *BaseExpr = OE;
5737           for (const auto &P : ParentChain) {
5738             if (P.first) {
5739               BaseExpr = S.BuildMemberExpr(
5740                   BaseExpr, /*IsArrow=*/false, E->getExprLoc(),
5741                   NestedNameSpecifierLoc(), SourceLocation(), P.first,
5742                   DeclAccessPair::make(P.first, P.first->getAccess()),
5743                   /*HadMultipleCandidates=*/false, DeclarationNameInfo(),
5744                   P.first->getType(), VK_LValue, OK_Ordinary);
5745               BaseExpr = S.DefaultLvalueConversion(BaseExpr).get();
5746             }
5747           }
5748           if (CurFD)
5749             BaseExpr = S.BuildMemberExpr(
5750                 BaseExpr, /*IsArrow=*/false, E->getExprLoc(),
5751                 NestedNameSpecifierLoc(), SourceLocation(), CurFD,
5752                 DeclAccessPair::make(CurFD, CurFD->getAccess()),
5753                 /*HadMultipleCandidates=*/false, DeclarationNameInfo(),
5754                 CurFD->getType(), VK_LValue, OK_Ordinary);
5755           SubExprs.push_back(BaseExpr);
5756           continue;
5757         }
5758         // Check for the "default" mapper for data members.
5759         bool FirstIter = true;
5760         for (FieldDecl *FD : RD->fields()) {
5761           if (!FD)
5762             continue;
5763           QualType FieldTy = FD->getType();
5764           if (FieldTy.isNull() ||
5765               !(FieldTy->isStructureOrClassType() || FieldTy->isUnionType()))
5766             continue;
5767           if (FirstIter) {
5768             FirstIter = false;
5769             ParentChain.emplace_back(CurFD, 1);
5770           } else {
5771             ++ParentChain.back().second;
5772           }
5773           Types.emplace_back(FieldTy, FD);
5774         }
5775       }
5776     }
5777     if (SubExprs.empty())
5778       continue;
5779     CXXScopeSpec MapperIdScopeSpec;
5780     DeclarationNameInfo MapperId;
5781     if (OMPClause *NewClause = S.ActOnOpenMPMapClause(
5782             C->getMapTypeModifiers(), C->getMapTypeModifiersLoc(),
5783             MapperIdScopeSpec, MapperId, C->getMapType(),
5784             /*IsMapTypeImplicit=*/true, SourceLocation(), SourceLocation(),
5785             SubExprs, OMPVarListLocTy()))
5786       Clauses.push_back(NewClause);
5787   }
5788 }
5789 
5790 StmtResult Sema::ActOnOpenMPExecutableDirective(
5791     OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
5792     OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
5793     Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
5794   StmtResult Res = StmtError();
5795   OpenMPBindClauseKind BindKind = OMPC_BIND_unknown;
5796   if (const OMPBindClause *BC =
5797           OMPExecutableDirective::getSingleClause<OMPBindClause>(Clauses))
5798     BindKind = BC->getBindKind();
5799   // First check CancelRegion which is then used in checkNestingOfRegions.
5800   if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
5801       checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
5802                             BindKind, StartLoc))
5803     return StmtError();
5804 
5805   llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
5806   VarsWithInheritedDSAType VarsWithInheritedDSA;
5807   bool ErrorFound = false;
5808   ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
5809   if (AStmt && !CurContext->isDependentContext() && Kind != OMPD_atomic &&
5810       Kind != OMPD_critical && Kind != OMPD_section && Kind != OMPD_master &&
5811       Kind != OMPD_masked && !isOpenMPLoopTransformationDirective(Kind)) {
5812     assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5813 
5814     // Check default data sharing attributes for referenced variables.
5815     DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
5816     int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
5817     Stmt *S = AStmt;
5818     while (--ThisCaptureLevel >= 0)
5819       S = cast<CapturedStmt>(S)->getCapturedStmt();
5820     DSAChecker.Visit(S);
5821     if (!isOpenMPTargetDataManagementDirective(Kind) &&
5822         !isOpenMPTaskingDirective(Kind)) {
5823       // Visit subcaptures to generate implicit clauses for captured vars.
5824       auto *CS = cast<CapturedStmt>(AStmt);
5825       SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
5826       getOpenMPCaptureRegions(CaptureRegions, Kind);
5827       // Ignore outer tasking regions for target directives.
5828       if (CaptureRegions.size() > 1 && CaptureRegions.front() == OMPD_task)
5829         CS = cast<CapturedStmt>(CS->getCapturedStmt());
5830       DSAChecker.visitSubCaptures(CS);
5831     }
5832     if (DSAChecker.isErrorFound())
5833       return StmtError();
5834     // Generate list of implicitly defined firstprivate variables.
5835     VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
5836 
5837     SmallVector<Expr *, 4> ImplicitFirstprivates(
5838         DSAChecker.getImplicitFirstprivate().begin(),
5839         DSAChecker.getImplicitFirstprivate().end());
5840     const unsigned DefaultmapKindNum = OMPC_DEFAULTMAP_pointer + 1;
5841     SmallVector<Expr *, 4> ImplicitMaps[DefaultmapKindNum][OMPC_MAP_delete];
5842     SmallVector<OpenMPMapModifierKind, NumberOfOMPMapClauseModifiers>
5843         ImplicitMapModifiers[DefaultmapKindNum];
5844     SmallVector<SourceLocation, NumberOfOMPMapClauseModifiers>
5845         ImplicitMapModifiersLoc[DefaultmapKindNum];
5846     // Get the original location of present modifier from Defaultmap clause.
5847     SourceLocation PresentModifierLocs[DefaultmapKindNum];
5848     for (OMPClause *C : Clauses) {
5849       if (auto *DMC = dyn_cast<OMPDefaultmapClause>(C))
5850         if (DMC->getDefaultmapModifier() == OMPC_DEFAULTMAP_MODIFIER_present)
5851           PresentModifierLocs[DMC->getDefaultmapKind()] =
5852               DMC->getDefaultmapModifierLoc();
5853     }
5854     for (unsigned VC = 0; VC < DefaultmapKindNum; ++VC) {
5855       auto Kind = static_cast<OpenMPDefaultmapClauseKind>(VC);
5856       for (unsigned I = 0; I < OMPC_MAP_delete; ++I) {
5857         ArrayRef<Expr *> ImplicitMap = DSAChecker.getImplicitMap(
5858             Kind, static_cast<OpenMPMapClauseKind>(I));
5859         ImplicitMaps[VC][I].append(ImplicitMap.begin(), ImplicitMap.end());
5860       }
5861       ArrayRef<OpenMPMapModifierKind> ImplicitModifier =
5862           DSAChecker.getImplicitMapModifier(Kind);
5863       ImplicitMapModifiers[VC].append(ImplicitModifier.begin(),
5864                                       ImplicitModifier.end());
5865       std::fill_n(std::back_inserter(ImplicitMapModifiersLoc[VC]),
5866                   ImplicitModifier.size(), PresentModifierLocs[VC]);
5867     }
5868     // Mark taskgroup task_reduction descriptors as implicitly firstprivate.
5869     for (OMPClause *C : Clauses) {
5870       if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) {
5871         for (Expr *E : IRC->taskgroup_descriptors())
5872           if (E)
5873             ImplicitFirstprivates.emplace_back(E);
5874       }
5875       // OpenMP 5.0, 2.10.1 task Construct
5876       // [detach clause]... The event-handle will be considered as if it was
5877       // specified on a firstprivate clause.
5878       if (auto *DC = dyn_cast<OMPDetachClause>(C))
5879         ImplicitFirstprivates.push_back(DC->getEventHandler());
5880     }
5881     if (!ImplicitFirstprivates.empty()) {
5882       if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
5883               ImplicitFirstprivates, SourceLocation(), SourceLocation(),
5884               SourceLocation())) {
5885         ClausesWithImplicit.push_back(Implicit);
5886         ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
5887                      ImplicitFirstprivates.size();
5888       } else {
5889         ErrorFound = true;
5890       }
5891     }
5892     // OpenMP 5.0 [2.19.7]
5893     // If a list item appears in a reduction, lastprivate or linear
5894     // clause on a combined target construct then it is treated as
5895     // if it also appears in a map clause with a map-type of tofrom
5896     if (getLangOpts().OpenMP >= 50 && Kind != OMPD_target &&
5897         isOpenMPTargetExecutionDirective(Kind)) {
5898       SmallVector<Expr *, 4> ImplicitExprs;
5899       for (OMPClause *C : Clauses) {
5900         if (auto *RC = dyn_cast<OMPReductionClause>(C))
5901           for (Expr *E : RC->varlists())
5902             if (!isa<DeclRefExpr>(E->IgnoreParenImpCasts()))
5903               ImplicitExprs.emplace_back(E);
5904       }
5905       if (!ImplicitExprs.empty()) {
5906         ArrayRef<Expr *> Exprs = ImplicitExprs;
5907         CXXScopeSpec MapperIdScopeSpec;
5908         DeclarationNameInfo MapperId;
5909         if (OMPClause *Implicit = ActOnOpenMPMapClause(
5910                 OMPC_MAP_MODIFIER_unknown, SourceLocation(), MapperIdScopeSpec,
5911                 MapperId, OMPC_MAP_tofrom,
5912                 /*IsMapTypeImplicit=*/true, SourceLocation(), SourceLocation(),
5913                 Exprs, OMPVarListLocTy(), /*NoDiagnose=*/true))
5914           ClausesWithImplicit.emplace_back(Implicit);
5915       }
5916     }
5917     for (unsigned I = 0, E = DefaultmapKindNum; I < E; ++I) {
5918       int ClauseKindCnt = -1;
5919       for (ArrayRef<Expr *> ImplicitMap : ImplicitMaps[I]) {
5920         ++ClauseKindCnt;
5921         if (ImplicitMap.empty())
5922           continue;
5923         CXXScopeSpec MapperIdScopeSpec;
5924         DeclarationNameInfo MapperId;
5925         auto Kind = static_cast<OpenMPMapClauseKind>(ClauseKindCnt);
5926         if (OMPClause *Implicit = ActOnOpenMPMapClause(
5927                 ImplicitMapModifiers[I], ImplicitMapModifiersLoc[I],
5928                 MapperIdScopeSpec, MapperId, Kind, /*IsMapTypeImplicit=*/true,
5929                 SourceLocation(), SourceLocation(), ImplicitMap,
5930                 OMPVarListLocTy())) {
5931           ClausesWithImplicit.emplace_back(Implicit);
5932           ErrorFound |= cast<OMPMapClause>(Implicit)->varlist_size() !=
5933                         ImplicitMap.size();
5934         } else {
5935           ErrorFound = true;
5936         }
5937       }
5938     }
5939     // Build expressions for implicit maps of data members with 'default'
5940     // mappers.
5941     if (LangOpts.OpenMP >= 50)
5942       processImplicitMapsWithDefaultMappers(*this, DSAStack,
5943                                             ClausesWithImplicit);
5944   }
5945 
5946   llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
5947   switch (Kind) {
5948   case OMPD_parallel:
5949     Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
5950                                        EndLoc);
5951     AllowedNameModifiers.push_back(OMPD_parallel);
5952     break;
5953   case OMPD_simd:
5954     Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
5955                                    VarsWithInheritedDSA);
5956     if (LangOpts.OpenMP >= 50)
5957       AllowedNameModifiers.push_back(OMPD_simd);
5958     break;
5959   case OMPD_tile:
5960     Res =
5961         ActOnOpenMPTileDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
5962     break;
5963   case OMPD_unroll:
5964     Res = ActOnOpenMPUnrollDirective(ClausesWithImplicit, AStmt, StartLoc,
5965                                      EndLoc);
5966     break;
5967   case OMPD_for:
5968     Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
5969                                   VarsWithInheritedDSA);
5970     break;
5971   case OMPD_for_simd:
5972     Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
5973                                       EndLoc, VarsWithInheritedDSA);
5974     if (LangOpts.OpenMP >= 50)
5975       AllowedNameModifiers.push_back(OMPD_simd);
5976     break;
5977   case OMPD_sections:
5978     Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
5979                                        EndLoc);
5980     break;
5981   case OMPD_section:
5982     assert(ClausesWithImplicit.empty() &&
5983            "No clauses are allowed for 'omp section' directive");
5984     Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
5985     break;
5986   case OMPD_single:
5987     Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
5988                                      EndLoc);
5989     break;
5990   case OMPD_master:
5991     assert(ClausesWithImplicit.empty() &&
5992            "No clauses are allowed for 'omp master' directive");
5993     Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
5994     break;
5995   case OMPD_masked:
5996     Res = ActOnOpenMPMaskedDirective(ClausesWithImplicit, AStmt, StartLoc,
5997                                      EndLoc);
5998     break;
5999   case OMPD_critical:
6000     Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
6001                                        StartLoc, EndLoc);
6002     break;
6003   case OMPD_parallel_for:
6004     Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
6005                                           EndLoc, VarsWithInheritedDSA);
6006     AllowedNameModifiers.push_back(OMPD_parallel);
6007     break;
6008   case OMPD_parallel_for_simd:
6009     Res = ActOnOpenMPParallelForSimdDirective(
6010         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6011     AllowedNameModifiers.push_back(OMPD_parallel);
6012     if (LangOpts.OpenMP >= 50)
6013       AllowedNameModifiers.push_back(OMPD_simd);
6014     break;
6015   case OMPD_parallel_master:
6016     Res = ActOnOpenMPParallelMasterDirective(ClausesWithImplicit, AStmt,
6017                                              StartLoc, EndLoc);
6018     AllowedNameModifiers.push_back(OMPD_parallel);
6019     break;
6020   case OMPD_parallel_sections:
6021     Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
6022                                                StartLoc, EndLoc);
6023     AllowedNameModifiers.push_back(OMPD_parallel);
6024     break;
6025   case OMPD_task:
6026     Res =
6027         ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
6028     AllowedNameModifiers.push_back(OMPD_task);
6029     break;
6030   case OMPD_taskyield:
6031     assert(ClausesWithImplicit.empty() &&
6032            "No clauses are allowed for 'omp taskyield' directive");
6033     assert(AStmt == nullptr &&
6034            "No associated statement allowed for 'omp taskyield' directive");
6035     Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
6036     break;
6037   case OMPD_barrier:
6038     assert(ClausesWithImplicit.empty() &&
6039            "No clauses are allowed for 'omp barrier' directive");
6040     assert(AStmt == nullptr &&
6041            "No associated statement allowed for 'omp barrier' directive");
6042     Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
6043     break;
6044   case OMPD_taskwait:
6045     assert(AStmt == nullptr &&
6046            "No associated statement allowed for 'omp taskwait' directive");
6047     Res = ActOnOpenMPTaskwaitDirective(ClausesWithImplicit, StartLoc, EndLoc);
6048     break;
6049   case OMPD_taskgroup:
6050     Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc,
6051                                         EndLoc);
6052     break;
6053   case OMPD_flush:
6054     assert(AStmt == nullptr &&
6055            "No associated statement allowed for 'omp flush' directive");
6056     Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
6057     break;
6058   case OMPD_depobj:
6059     assert(AStmt == nullptr &&
6060            "No associated statement allowed for 'omp depobj' directive");
6061     Res = ActOnOpenMPDepobjDirective(ClausesWithImplicit, StartLoc, EndLoc);
6062     break;
6063   case OMPD_scan:
6064     assert(AStmt == nullptr &&
6065            "No associated statement allowed for 'omp scan' directive");
6066     Res = ActOnOpenMPScanDirective(ClausesWithImplicit, StartLoc, EndLoc);
6067     break;
6068   case OMPD_ordered:
6069     Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
6070                                       EndLoc);
6071     break;
6072   case OMPD_atomic:
6073     Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
6074                                      EndLoc);
6075     break;
6076   case OMPD_teams:
6077     Res =
6078         ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
6079     break;
6080   case OMPD_target:
6081     Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
6082                                      EndLoc);
6083     AllowedNameModifiers.push_back(OMPD_target);
6084     break;
6085   case OMPD_target_parallel:
6086     Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
6087                                              StartLoc, EndLoc);
6088     AllowedNameModifiers.push_back(OMPD_target);
6089     AllowedNameModifiers.push_back(OMPD_parallel);
6090     break;
6091   case OMPD_target_parallel_for:
6092     Res = ActOnOpenMPTargetParallelForDirective(
6093         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6094     AllowedNameModifiers.push_back(OMPD_target);
6095     AllowedNameModifiers.push_back(OMPD_parallel);
6096     break;
6097   case OMPD_cancellation_point:
6098     assert(ClausesWithImplicit.empty() &&
6099            "No clauses are allowed for 'omp cancellation point' directive");
6100     assert(AStmt == nullptr && "No associated statement allowed for 'omp "
6101                                "cancellation point' directive");
6102     Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
6103     break;
6104   case OMPD_cancel:
6105     assert(AStmt == nullptr &&
6106            "No associated statement allowed for 'omp cancel' directive");
6107     Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
6108                                      CancelRegion);
6109     AllowedNameModifiers.push_back(OMPD_cancel);
6110     break;
6111   case OMPD_target_data:
6112     Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
6113                                          EndLoc);
6114     AllowedNameModifiers.push_back(OMPD_target_data);
6115     break;
6116   case OMPD_target_enter_data:
6117     Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
6118                                               EndLoc, AStmt);
6119     AllowedNameModifiers.push_back(OMPD_target_enter_data);
6120     break;
6121   case OMPD_target_exit_data:
6122     Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
6123                                              EndLoc, AStmt);
6124     AllowedNameModifiers.push_back(OMPD_target_exit_data);
6125     break;
6126   case OMPD_taskloop:
6127     Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
6128                                        EndLoc, VarsWithInheritedDSA);
6129     AllowedNameModifiers.push_back(OMPD_taskloop);
6130     break;
6131   case OMPD_taskloop_simd:
6132     Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
6133                                            EndLoc, VarsWithInheritedDSA);
6134     AllowedNameModifiers.push_back(OMPD_taskloop);
6135     if (LangOpts.OpenMP >= 50)
6136       AllowedNameModifiers.push_back(OMPD_simd);
6137     break;
6138   case OMPD_master_taskloop:
6139     Res = ActOnOpenMPMasterTaskLoopDirective(
6140         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6141     AllowedNameModifiers.push_back(OMPD_taskloop);
6142     break;
6143   case OMPD_master_taskloop_simd:
6144     Res = ActOnOpenMPMasterTaskLoopSimdDirective(
6145         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6146     AllowedNameModifiers.push_back(OMPD_taskloop);
6147     if (LangOpts.OpenMP >= 50)
6148       AllowedNameModifiers.push_back(OMPD_simd);
6149     break;
6150   case OMPD_parallel_master_taskloop:
6151     Res = ActOnOpenMPParallelMasterTaskLoopDirective(
6152         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6153     AllowedNameModifiers.push_back(OMPD_taskloop);
6154     AllowedNameModifiers.push_back(OMPD_parallel);
6155     break;
6156   case OMPD_parallel_master_taskloop_simd:
6157     Res = ActOnOpenMPParallelMasterTaskLoopSimdDirective(
6158         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6159     AllowedNameModifiers.push_back(OMPD_taskloop);
6160     AllowedNameModifiers.push_back(OMPD_parallel);
6161     if (LangOpts.OpenMP >= 50)
6162       AllowedNameModifiers.push_back(OMPD_simd);
6163     break;
6164   case OMPD_distribute:
6165     Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
6166                                          EndLoc, VarsWithInheritedDSA);
6167     break;
6168   case OMPD_target_update:
6169     Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc,
6170                                            EndLoc, AStmt);
6171     AllowedNameModifiers.push_back(OMPD_target_update);
6172     break;
6173   case OMPD_distribute_parallel_for:
6174     Res = ActOnOpenMPDistributeParallelForDirective(
6175         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6176     AllowedNameModifiers.push_back(OMPD_parallel);
6177     break;
6178   case OMPD_distribute_parallel_for_simd:
6179     Res = ActOnOpenMPDistributeParallelForSimdDirective(
6180         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6181     AllowedNameModifiers.push_back(OMPD_parallel);
6182     if (LangOpts.OpenMP >= 50)
6183       AllowedNameModifiers.push_back(OMPD_simd);
6184     break;
6185   case OMPD_distribute_simd:
6186     Res = ActOnOpenMPDistributeSimdDirective(
6187         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6188     if (LangOpts.OpenMP >= 50)
6189       AllowedNameModifiers.push_back(OMPD_simd);
6190     break;
6191   case OMPD_target_parallel_for_simd:
6192     Res = ActOnOpenMPTargetParallelForSimdDirective(
6193         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6194     AllowedNameModifiers.push_back(OMPD_target);
6195     AllowedNameModifiers.push_back(OMPD_parallel);
6196     if (LangOpts.OpenMP >= 50)
6197       AllowedNameModifiers.push_back(OMPD_simd);
6198     break;
6199   case OMPD_target_simd:
6200     Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
6201                                          EndLoc, VarsWithInheritedDSA);
6202     AllowedNameModifiers.push_back(OMPD_target);
6203     if (LangOpts.OpenMP >= 50)
6204       AllowedNameModifiers.push_back(OMPD_simd);
6205     break;
6206   case OMPD_teams_distribute:
6207     Res = ActOnOpenMPTeamsDistributeDirective(
6208         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6209     break;
6210   case OMPD_teams_distribute_simd:
6211     Res = ActOnOpenMPTeamsDistributeSimdDirective(
6212         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6213     if (LangOpts.OpenMP >= 50)
6214       AllowedNameModifiers.push_back(OMPD_simd);
6215     break;
6216   case OMPD_teams_distribute_parallel_for_simd:
6217     Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
6218         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6219     AllowedNameModifiers.push_back(OMPD_parallel);
6220     if (LangOpts.OpenMP >= 50)
6221       AllowedNameModifiers.push_back(OMPD_simd);
6222     break;
6223   case OMPD_teams_distribute_parallel_for:
6224     Res = ActOnOpenMPTeamsDistributeParallelForDirective(
6225         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6226     AllowedNameModifiers.push_back(OMPD_parallel);
6227     break;
6228   case OMPD_target_teams:
6229     Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
6230                                           EndLoc);
6231     AllowedNameModifiers.push_back(OMPD_target);
6232     break;
6233   case OMPD_target_teams_distribute:
6234     Res = ActOnOpenMPTargetTeamsDistributeDirective(
6235         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6236     AllowedNameModifiers.push_back(OMPD_target);
6237     break;
6238   case OMPD_target_teams_distribute_parallel_for:
6239     Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
6240         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6241     AllowedNameModifiers.push_back(OMPD_target);
6242     AllowedNameModifiers.push_back(OMPD_parallel);
6243     break;
6244   case OMPD_target_teams_distribute_parallel_for_simd:
6245     Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
6246         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6247     AllowedNameModifiers.push_back(OMPD_target);
6248     AllowedNameModifiers.push_back(OMPD_parallel);
6249     if (LangOpts.OpenMP >= 50)
6250       AllowedNameModifiers.push_back(OMPD_simd);
6251     break;
6252   case OMPD_target_teams_distribute_simd:
6253     Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
6254         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6255     AllowedNameModifiers.push_back(OMPD_target);
6256     if (LangOpts.OpenMP >= 50)
6257       AllowedNameModifiers.push_back(OMPD_simd);
6258     break;
6259   case OMPD_interop:
6260     assert(AStmt == nullptr &&
6261            "No associated statement allowed for 'omp interop' directive");
6262     Res = ActOnOpenMPInteropDirective(ClausesWithImplicit, StartLoc, EndLoc);
6263     break;
6264   case OMPD_dispatch:
6265     Res = ActOnOpenMPDispatchDirective(ClausesWithImplicit, AStmt, StartLoc,
6266                                        EndLoc);
6267     break;
6268   case OMPD_loop:
6269     Res = ActOnOpenMPGenericLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
6270                                           EndLoc, VarsWithInheritedDSA);
6271     break;
6272   case OMPD_declare_target:
6273   case OMPD_end_declare_target:
6274   case OMPD_threadprivate:
6275   case OMPD_allocate:
6276   case OMPD_declare_reduction:
6277   case OMPD_declare_mapper:
6278   case OMPD_declare_simd:
6279   case OMPD_requires:
6280   case OMPD_declare_variant:
6281   case OMPD_begin_declare_variant:
6282   case OMPD_end_declare_variant:
6283     llvm_unreachable("OpenMP Directive is not allowed");
6284   case OMPD_unknown:
6285   default:
6286     llvm_unreachable("Unknown OpenMP directive");
6287   }
6288 
6289   ErrorFound = Res.isInvalid() || ErrorFound;
6290 
6291   // Check variables in the clauses if default(none) or
6292   // default(firstprivate) was specified.
6293   if (DSAStack->getDefaultDSA() == DSA_none ||
6294       DSAStack->getDefaultDSA() == DSA_firstprivate) {
6295     DSAAttrChecker DSAChecker(DSAStack, *this, nullptr);
6296     for (OMPClause *C : Clauses) {
6297       switch (C->getClauseKind()) {
6298       case OMPC_num_threads:
6299       case OMPC_dist_schedule:
6300         // Do not analyse if no parent teams directive.
6301         if (isOpenMPTeamsDirective(Kind))
6302           break;
6303         continue;
6304       case OMPC_if:
6305         if (isOpenMPTeamsDirective(Kind) &&
6306             cast<OMPIfClause>(C)->getNameModifier() != OMPD_target)
6307           break;
6308         if (isOpenMPParallelDirective(Kind) &&
6309             isOpenMPTaskLoopDirective(Kind) &&
6310             cast<OMPIfClause>(C)->getNameModifier() != OMPD_parallel)
6311           break;
6312         continue;
6313       case OMPC_schedule:
6314       case OMPC_detach:
6315         break;
6316       case OMPC_grainsize:
6317       case OMPC_num_tasks:
6318       case OMPC_final:
6319       case OMPC_priority:
6320       case OMPC_novariants:
6321       case OMPC_nocontext:
6322         // Do not analyze if no parent parallel directive.
6323         if (isOpenMPParallelDirective(Kind))
6324           break;
6325         continue;
6326       case OMPC_ordered:
6327       case OMPC_device:
6328       case OMPC_num_teams:
6329       case OMPC_thread_limit:
6330       case OMPC_hint:
6331       case OMPC_collapse:
6332       case OMPC_safelen:
6333       case OMPC_simdlen:
6334       case OMPC_sizes:
6335       case OMPC_default:
6336       case OMPC_proc_bind:
6337       case OMPC_private:
6338       case OMPC_firstprivate:
6339       case OMPC_lastprivate:
6340       case OMPC_shared:
6341       case OMPC_reduction:
6342       case OMPC_task_reduction:
6343       case OMPC_in_reduction:
6344       case OMPC_linear:
6345       case OMPC_aligned:
6346       case OMPC_copyin:
6347       case OMPC_copyprivate:
6348       case OMPC_nowait:
6349       case OMPC_untied:
6350       case OMPC_mergeable:
6351       case OMPC_allocate:
6352       case OMPC_read:
6353       case OMPC_write:
6354       case OMPC_update:
6355       case OMPC_capture:
6356       case OMPC_seq_cst:
6357       case OMPC_acq_rel:
6358       case OMPC_acquire:
6359       case OMPC_release:
6360       case OMPC_relaxed:
6361       case OMPC_depend:
6362       case OMPC_threads:
6363       case OMPC_simd:
6364       case OMPC_map:
6365       case OMPC_nogroup:
6366       case OMPC_defaultmap:
6367       case OMPC_to:
6368       case OMPC_from:
6369       case OMPC_use_device_ptr:
6370       case OMPC_use_device_addr:
6371       case OMPC_is_device_ptr:
6372       case OMPC_nontemporal:
6373       case OMPC_order:
6374       case OMPC_destroy:
6375       case OMPC_inclusive:
6376       case OMPC_exclusive:
6377       case OMPC_uses_allocators:
6378       case OMPC_affinity:
6379       case OMPC_bind:
6380         continue;
6381       case OMPC_allocator:
6382       case OMPC_flush:
6383       case OMPC_depobj:
6384       case OMPC_threadprivate:
6385       case OMPC_uniform:
6386       case OMPC_unknown:
6387       case OMPC_unified_address:
6388       case OMPC_unified_shared_memory:
6389       case OMPC_reverse_offload:
6390       case OMPC_dynamic_allocators:
6391       case OMPC_atomic_default_mem_order:
6392       case OMPC_device_type:
6393       case OMPC_match:
6394       case OMPC_when:
6395       default:
6396         llvm_unreachable("Unexpected clause");
6397       }
6398       for (Stmt *CC : C->children()) {
6399         if (CC)
6400           DSAChecker.Visit(CC);
6401       }
6402     }
6403     for (const auto &P : DSAChecker.getVarsWithInheritedDSA())
6404       VarsWithInheritedDSA[P.getFirst()] = P.getSecond();
6405   }
6406   for (const auto &P : VarsWithInheritedDSA) {
6407     if (P.getFirst()->isImplicit() || isa<OMPCapturedExprDecl>(P.getFirst()))
6408       continue;
6409     ErrorFound = true;
6410     if (DSAStack->getDefaultDSA() == DSA_none ||
6411         DSAStack->getDefaultDSA() == DSA_firstprivate) {
6412       Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
6413           << P.first << P.second->getSourceRange();
6414       Diag(DSAStack->getDefaultDSALocation(), diag::note_omp_default_dsa_none);
6415     } else if (getLangOpts().OpenMP >= 50) {
6416       Diag(P.second->getExprLoc(),
6417            diag::err_omp_defaultmap_no_attr_for_variable)
6418           << P.first << P.second->getSourceRange();
6419       Diag(DSAStack->getDefaultDSALocation(),
6420            diag::note_omp_defaultmap_attr_none);
6421     }
6422   }
6423 
6424   if (!AllowedNameModifiers.empty())
6425     ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
6426                  ErrorFound;
6427 
6428   if (ErrorFound)
6429     return StmtError();
6430 
6431   if (!CurContext->isDependentContext() &&
6432       isOpenMPTargetExecutionDirective(Kind) &&
6433       !(DSAStack->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() ||
6434         DSAStack->hasRequiresDeclWithClause<OMPUnifiedAddressClause>() ||
6435         DSAStack->hasRequiresDeclWithClause<OMPReverseOffloadClause>() ||
6436         DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())) {
6437     // Register target to DSA Stack.
6438     DSAStack->addTargetDirLocation(StartLoc);
6439   }
6440 
6441   return Res;
6442 }
6443 
6444 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
6445     DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
6446     ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
6447     ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
6448     ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
6449   assert(Aligneds.size() == Alignments.size());
6450   assert(Linears.size() == LinModifiers.size());
6451   assert(Linears.size() == Steps.size());
6452   if (!DG || DG.get().isNull())
6453     return DeclGroupPtrTy();
6454 
6455   const int SimdId = 0;
6456   if (!DG.get().isSingleDecl()) {
6457     Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd_variant)
6458         << SimdId;
6459     return DG;
6460   }
6461   Decl *ADecl = DG.get().getSingleDecl();
6462   if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
6463     ADecl = FTD->getTemplatedDecl();
6464 
6465   auto *FD = dyn_cast<FunctionDecl>(ADecl);
6466   if (!FD) {
6467     Diag(ADecl->getLocation(), diag::err_omp_function_expected) << SimdId;
6468     return DeclGroupPtrTy();
6469   }
6470 
6471   // OpenMP [2.8.2, declare simd construct, Description]
6472   // The parameter of the simdlen clause must be a constant positive integer
6473   // expression.
6474   ExprResult SL;
6475   if (Simdlen)
6476     SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
6477   // OpenMP [2.8.2, declare simd construct, Description]
6478   // The special this pointer can be used as if was one of the arguments to the
6479   // function in any of the linear, aligned, or uniform clauses.
6480   // The uniform clause declares one or more arguments to have an invariant
6481   // value for all concurrent invocations of the function in the execution of a
6482   // single SIMD loop.
6483   llvm::DenseMap<const Decl *, const Expr *> UniformedArgs;
6484   const Expr *UniformedLinearThis = nullptr;
6485   for (const Expr *E : Uniforms) {
6486     E = E->IgnoreParenImpCasts();
6487     if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
6488       if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
6489         if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
6490             FD->getParamDecl(PVD->getFunctionScopeIndex())
6491                     ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
6492           UniformedArgs.try_emplace(PVD->getCanonicalDecl(), E);
6493           continue;
6494         }
6495     if (isa<CXXThisExpr>(E)) {
6496       UniformedLinearThis = E;
6497       continue;
6498     }
6499     Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
6500         << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
6501   }
6502   // OpenMP [2.8.2, declare simd construct, Description]
6503   // The aligned clause declares that the object to which each list item points
6504   // is aligned to the number of bytes expressed in the optional parameter of
6505   // the aligned clause.
6506   // The special this pointer can be used as if was one of the arguments to the
6507   // function in any of the linear, aligned, or uniform clauses.
6508   // The type of list items appearing in the aligned clause must be array,
6509   // pointer, reference to array, or reference to pointer.
6510   llvm::DenseMap<const Decl *, const Expr *> AlignedArgs;
6511   const Expr *AlignedThis = nullptr;
6512   for (const Expr *E : Aligneds) {
6513     E = E->IgnoreParenImpCasts();
6514     if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
6515       if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
6516         const VarDecl *CanonPVD = PVD->getCanonicalDecl();
6517         if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
6518             FD->getParamDecl(PVD->getFunctionScopeIndex())
6519                     ->getCanonicalDecl() == CanonPVD) {
6520           // OpenMP  [2.8.1, simd construct, Restrictions]
6521           // A list-item cannot appear in more than one aligned clause.
6522           if (AlignedArgs.count(CanonPVD) > 0) {
6523             Diag(E->getExprLoc(), diag::err_omp_used_in_clause_twice)
6524                 << 1 << getOpenMPClauseName(OMPC_aligned)
6525                 << E->getSourceRange();
6526             Diag(AlignedArgs[CanonPVD]->getExprLoc(),
6527                  diag::note_omp_explicit_dsa)
6528                 << getOpenMPClauseName(OMPC_aligned);
6529             continue;
6530           }
6531           AlignedArgs[CanonPVD] = E;
6532           QualType QTy = PVD->getType()
6533                              .getNonReferenceType()
6534                              .getUnqualifiedType()
6535                              .getCanonicalType();
6536           const Type *Ty = QTy.getTypePtrOrNull();
6537           if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
6538             Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
6539                 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
6540             Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
6541           }
6542           continue;
6543         }
6544       }
6545     if (isa<CXXThisExpr>(E)) {
6546       if (AlignedThis) {
6547         Diag(E->getExprLoc(), diag::err_omp_used_in_clause_twice)
6548             << 2 << getOpenMPClauseName(OMPC_aligned) << E->getSourceRange();
6549         Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
6550             << getOpenMPClauseName(OMPC_aligned);
6551       }
6552       AlignedThis = E;
6553       continue;
6554     }
6555     Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
6556         << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
6557   }
6558   // The optional parameter of the aligned clause, alignment, must be a constant
6559   // positive integer expression. If no optional parameter is specified,
6560   // implementation-defined default alignments for SIMD instructions on the
6561   // target platforms are assumed.
6562   SmallVector<const Expr *, 4> NewAligns;
6563   for (Expr *E : Alignments) {
6564     ExprResult Align;
6565     if (E)
6566       Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
6567     NewAligns.push_back(Align.get());
6568   }
6569   // OpenMP [2.8.2, declare simd construct, Description]
6570   // The linear clause declares one or more list items to be private to a SIMD
6571   // lane and to have a linear relationship with respect to the iteration space
6572   // of a loop.
6573   // The special this pointer can be used as if was one of the arguments to the
6574   // function in any of the linear, aligned, or uniform clauses.
6575   // When a linear-step expression is specified in a linear clause it must be
6576   // either a constant integer expression or an integer-typed parameter that is
6577   // specified in a uniform clause on the directive.
6578   llvm::DenseMap<const Decl *, const Expr *> LinearArgs;
6579   const bool IsUniformedThis = UniformedLinearThis != nullptr;
6580   auto MI = LinModifiers.begin();
6581   for (const Expr *E : Linears) {
6582     auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
6583     ++MI;
6584     E = E->IgnoreParenImpCasts();
6585     if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
6586       if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
6587         const VarDecl *CanonPVD = PVD->getCanonicalDecl();
6588         if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
6589             FD->getParamDecl(PVD->getFunctionScopeIndex())
6590                     ->getCanonicalDecl() == CanonPVD) {
6591           // OpenMP  [2.15.3.7, linear Clause, Restrictions]
6592           // A list-item cannot appear in more than one linear clause.
6593           if (LinearArgs.count(CanonPVD) > 0) {
6594             Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
6595                 << getOpenMPClauseName(OMPC_linear)
6596                 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
6597             Diag(LinearArgs[CanonPVD]->getExprLoc(),
6598                  diag::note_omp_explicit_dsa)
6599                 << getOpenMPClauseName(OMPC_linear);
6600             continue;
6601           }
6602           // Each argument can appear in at most one uniform or linear clause.
6603           if (UniformedArgs.count(CanonPVD) > 0) {
6604             Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
6605                 << getOpenMPClauseName(OMPC_linear)
6606                 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
6607             Diag(UniformedArgs[CanonPVD]->getExprLoc(),
6608                  diag::note_omp_explicit_dsa)
6609                 << getOpenMPClauseName(OMPC_uniform);
6610             continue;
6611           }
6612           LinearArgs[CanonPVD] = E;
6613           if (E->isValueDependent() || E->isTypeDependent() ||
6614               E->isInstantiationDependent() ||
6615               E->containsUnexpandedParameterPack())
6616             continue;
6617           (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
6618                                       PVD->getOriginalType(),
6619                                       /*IsDeclareSimd=*/true);
6620           continue;
6621         }
6622       }
6623     if (isa<CXXThisExpr>(E)) {
6624       if (UniformedLinearThis) {
6625         Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
6626             << getOpenMPClauseName(OMPC_linear)
6627             << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
6628             << E->getSourceRange();
6629         Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
6630             << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
6631                                                    : OMPC_linear);
6632         continue;
6633       }
6634       UniformedLinearThis = E;
6635       if (E->isValueDependent() || E->isTypeDependent() ||
6636           E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
6637         continue;
6638       (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
6639                                   E->getType(), /*IsDeclareSimd=*/true);
6640       continue;
6641     }
6642     Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
6643         << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
6644   }
6645   Expr *Step = nullptr;
6646   Expr *NewStep = nullptr;
6647   SmallVector<Expr *, 4> NewSteps;
6648   for (Expr *E : Steps) {
6649     // Skip the same step expression, it was checked already.
6650     if (Step == E || !E) {
6651       NewSteps.push_back(E ? NewStep : nullptr);
6652       continue;
6653     }
6654     Step = E;
6655     if (const auto *DRE = dyn_cast<DeclRefExpr>(Step))
6656       if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
6657         const VarDecl *CanonPVD = PVD->getCanonicalDecl();
6658         if (UniformedArgs.count(CanonPVD) == 0) {
6659           Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
6660               << Step->getSourceRange();
6661         } else if (E->isValueDependent() || E->isTypeDependent() ||
6662                    E->isInstantiationDependent() ||
6663                    E->containsUnexpandedParameterPack() ||
6664                    CanonPVD->getType()->hasIntegerRepresentation()) {
6665           NewSteps.push_back(Step);
6666         } else {
6667           Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
6668               << Step->getSourceRange();
6669         }
6670         continue;
6671       }
6672     NewStep = Step;
6673     if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
6674         !Step->isInstantiationDependent() &&
6675         !Step->containsUnexpandedParameterPack()) {
6676       NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
6677                     .get();
6678       if (NewStep)
6679         NewStep =
6680             VerifyIntegerConstantExpression(NewStep, /*FIXME*/ AllowFold).get();
6681     }
6682     NewSteps.push_back(NewStep);
6683   }
6684   auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
6685       Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
6686       Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
6687       const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
6688       const_cast<Expr **>(Linears.data()), Linears.size(),
6689       const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
6690       NewSteps.data(), NewSteps.size(), SR);
6691   ADecl->addAttr(NewAttr);
6692   return DG;
6693 }
6694 
6695 static void setPrototype(Sema &S, FunctionDecl *FD, FunctionDecl *FDWithProto,
6696                          QualType NewType) {
6697   assert(NewType->isFunctionProtoType() &&
6698          "Expected function type with prototype.");
6699   assert(FD->getType()->isFunctionNoProtoType() &&
6700          "Expected function with type with no prototype.");
6701   assert(FDWithProto->getType()->isFunctionProtoType() &&
6702          "Expected function with prototype.");
6703   // Synthesize parameters with the same types.
6704   FD->setType(NewType);
6705   SmallVector<ParmVarDecl *, 16> Params;
6706   for (const ParmVarDecl *P : FDWithProto->parameters()) {
6707     auto *Param = ParmVarDecl::Create(S.getASTContext(), FD, SourceLocation(),
6708                                       SourceLocation(), nullptr, P->getType(),
6709                                       /*TInfo=*/nullptr, SC_None, nullptr);
6710     Param->setScopeInfo(0, Params.size());
6711     Param->setImplicit();
6712     Params.push_back(Param);
6713   }
6714 
6715   FD->setParams(Params);
6716 }
6717 
6718 void Sema::ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(Decl *D) {
6719   if (D->isInvalidDecl())
6720     return;
6721   FunctionDecl *FD = nullptr;
6722   if (auto *UTemplDecl = dyn_cast<FunctionTemplateDecl>(D))
6723     FD = UTemplDecl->getTemplatedDecl();
6724   else
6725     FD = cast<FunctionDecl>(D);
6726   assert(FD && "Expected a function declaration!");
6727 
6728   // If we are instantiating templates we do *not* apply scoped assumptions but
6729   // only global ones. We apply scoped assumption to the template definition
6730   // though.
6731   if (!inTemplateInstantiation()) {
6732     for (AssumptionAttr *AA : OMPAssumeScoped)
6733       FD->addAttr(AA);
6734   }
6735   for (AssumptionAttr *AA : OMPAssumeGlobal)
6736     FD->addAttr(AA);
6737 }
6738 
6739 Sema::OMPDeclareVariantScope::OMPDeclareVariantScope(OMPTraitInfo &TI)
6740     : TI(&TI), NameSuffix(TI.getMangledName()) {}
6741 
6742 void Sema::ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
6743     Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists,
6744     SmallVectorImpl<FunctionDecl *> &Bases) {
6745   if (!D.getIdentifier())
6746     return;
6747 
6748   OMPDeclareVariantScope &DVScope = OMPDeclareVariantScopes.back();
6749 
6750   // Template specialization is an extension, check if we do it.
6751   bool IsTemplated = !TemplateParamLists.empty();
6752   if (IsTemplated &
6753       !DVScope.TI->isExtensionActive(
6754           llvm::omp::TraitProperty::implementation_extension_allow_templates))
6755     return;
6756 
6757   IdentifierInfo *BaseII = D.getIdentifier();
6758   LookupResult Lookup(*this, DeclarationName(BaseII), D.getIdentifierLoc(),
6759                       LookupOrdinaryName);
6760   LookupParsedName(Lookup, S, &D.getCXXScopeSpec());
6761 
6762   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6763   QualType FType = TInfo->getType();
6764 
6765   bool IsConstexpr =
6766       D.getDeclSpec().getConstexprSpecifier() == ConstexprSpecKind::Constexpr;
6767   bool IsConsteval =
6768       D.getDeclSpec().getConstexprSpecifier() == ConstexprSpecKind::Consteval;
6769 
6770   for (auto *Candidate : Lookup) {
6771     auto *CandidateDecl = Candidate->getUnderlyingDecl();
6772     FunctionDecl *UDecl = nullptr;
6773     if (IsTemplated && isa<FunctionTemplateDecl>(CandidateDecl)) {
6774       auto *FTD = cast<FunctionTemplateDecl>(CandidateDecl);
6775       if (FTD->getTemplateParameters()->size() == TemplateParamLists.size())
6776         UDecl = FTD->getTemplatedDecl();
6777     } else if (!IsTemplated)
6778       UDecl = dyn_cast<FunctionDecl>(CandidateDecl);
6779     if (!UDecl)
6780       continue;
6781 
6782     // Don't specialize constexpr/consteval functions with
6783     // non-constexpr/consteval functions.
6784     if (UDecl->isConstexpr() && !IsConstexpr)
6785       continue;
6786     if (UDecl->isConsteval() && !IsConsteval)
6787       continue;
6788 
6789     QualType UDeclTy = UDecl->getType();
6790     if (!UDeclTy->isDependentType()) {
6791       QualType NewType = Context.mergeFunctionTypes(
6792           FType, UDeclTy, /* OfBlockPointer */ false,
6793           /* Unqualified */ false, /* AllowCXX */ true);
6794       if (NewType.isNull())
6795         continue;
6796     }
6797 
6798     // Found a base!
6799     Bases.push_back(UDecl);
6800   }
6801 
6802   bool UseImplicitBase = !DVScope.TI->isExtensionActive(
6803       llvm::omp::TraitProperty::implementation_extension_disable_implicit_base);
6804   // If no base was found we create a declaration that we use as base.
6805   if (Bases.empty() && UseImplicitBase) {
6806     D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration);
6807     Decl *BaseD = HandleDeclarator(S, D, TemplateParamLists);
6808     BaseD->setImplicit(true);
6809     if (auto *BaseTemplD = dyn_cast<FunctionTemplateDecl>(BaseD))
6810       Bases.push_back(BaseTemplD->getTemplatedDecl());
6811     else
6812       Bases.push_back(cast<FunctionDecl>(BaseD));
6813   }
6814 
6815   std::string MangledName;
6816   MangledName += D.getIdentifier()->getName();
6817   MangledName += getOpenMPVariantManglingSeparatorStr();
6818   MangledName += DVScope.NameSuffix;
6819   IdentifierInfo &VariantII = Context.Idents.get(MangledName);
6820 
6821   VariantII.setMangledOpenMPVariantName(true);
6822   D.SetIdentifier(&VariantII, D.getBeginLoc());
6823 }
6824 
6825 void Sema::ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(
6826     Decl *D, SmallVectorImpl<FunctionDecl *> &Bases) {
6827   // Do not mark function as is used to prevent its emission if this is the
6828   // only place where it is used.
6829   EnterExpressionEvaluationContext Unevaluated(
6830       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6831 
6832   FunctionDecl *FD = nullptr;
6833   if (auto *UTemplDecl = dyn_cast<FunctionTemplateDecl>(D))
6834     FD = UTemplDecl->getTemplatedDecl();
6835   else
6836     FD = cast<FunctionDecl>(D);
6837   auto *VariantFuncRef = DeclRefExpr::Create(
6838       Context, NestedNameSpecifierLoc(), SourceLocation(), FD,
6839       /* RefersToEnclosingVariableOrCapture */ false,
6840       /* NameLoc */ FD->getLocation(), FD->getType(),
6841       ExprValueKind::VK_PRValue);
6842 
6843   OMPDeclareVariantScope &DVScope = OMPDeclareVariantScopes.back();
6844   auto *OMPDeclareVariantA = OMPDeclareVariantAttr::CreateImplicit(
6845       Context, VariantFuncRef, DVScope.TI,
6846       /*NothingArgs=*/nullptr, /*NothingArgsSize=*/0,
6847       /*NeedDevicePtrArgs=*/nullptr, /*NeedDevicePtrArgsSize=*/0,
6848       /*AppendArgs=*/nullptr, /*AppendArgsSize=*/0);
6849   for (FunctionDecl *BaseFD : Bases)
6850     BaseFD->addAttr(OMPDeclareVariantA);
6851 }
6852 
6853 ExprResult Sema::ActOnOpenMPCall(ExprResult Call, Scope *Scope,
6854                                  SourceLocation LParenLoc,
6855                                  MultiExprArg ArgExprs,
6856                                  SourceLocation RParenLoc, Expr *ExecConfig) {
6857   // The common case is a regular call we do not want to specialize at all. Try
6858   // to make that case fast by bailing early.
6859   CallExpr *CE = dyn_cast<CallExpr>(Call.get());
6860   if (!CE)
6861     return Call;
6862 
6863   FunctionDecl *CalleeFnDecl = CE->getDirectCallee();
6864   if (!CalleeFnDecl)
6865     return Call;
6866 
6867   if (!CalleeFnDecl->hasAttr<OMPDeclareVariantAttr>())
6868     return Call;
6869 
6870   ASTContext &Context = getASTContext();
6871   std::function<void(StringRef)> DiagUnknownTrait = [this,
6872                                                      CE](StringRef ISATrait) {
6873     // TODO Track the selector locations in a way that is accessible here to
6874     // improve the diagnostic location.
6875     Diag(CE->getBeginLoc(), diag::warn_unknown_declare_variant_isa_trait)
6876         << ISATrait;
6877   };
6878   TargetOMPContext OMPCtx(Context, std::move(DiagUnknownTrait),
6879                           getCurFunctionDecl(), DSAStack->getConstructTraits());
6880 
6881   QualType CalleeFnType = CalleeFnDecl->getType();
6882 
6883   SmallVector<Expr *, 4> Exprs;
6884   SmallVector<VariantMatchInfo, 4> VMIs;
6885   while (CalleeFnDecl) {
6886     for (OMPDeclareVariantAttr *A :
6887          CalleeFnDecl->specific_attrs<OMPDeclareVariantAttr>()) {
6888       Expr *VariantRef = A->getVariantFuncRef();
6889 
6890       VariantMatchInfo VMI;
6891       OMPTraitInfo &TI = A->getTraitInfo();
6892       TI.getAsVariantMatchInfo(Context, VMI);
6893       if (!isVariantApplicableInContext(VMI, OMPCtx,
6894                                         /* DeviceSetOnly */ false))
6895         continue;
6896 
6897       VMIs.push_back(VMI);
6898       Exprs.push_back(VariantRef);
6899     }
6900 
6901     CalleeFnDecl = CalleeFnDecl->getPreviousDecl();
6902   }
6903 
6904   ExprResult NewCall;
6905   do {
6906     int BestIdx = getBestVariantMatchForContext(VMIs, OMPCtx);
6907     if (BestIdx < 0)
6908       return Call;
6909     Expr *BestExpr = cast<DeclRefExpr>(Exprs[BestIdx]);
6910     Decl *BestDecl = cast<DeclRefExpr>(BestExpr)->getDecl();
6911 
6912     {
6913       // Try to build a (member) call expression for the current best applicable
6914       // variant expression. We allow this to fail in which case we continue
6915       // with the next best variant expression. The fail case is part of the
6916       // implementation defined behavior in the OpenMP standard when it talks
6917       // about what differences in the function prototypes: "Any differences
6918       // that the specific OpenMP context requires in the prototype of the
6919       // variant from the base function prototype are implementation defined."
6920       // This wording is there to allow the specialized variant to have a
6921       // different type than the base function. This is intended and OK but if
6922       // we cannot create a call the difference is not in the "implementation
6923       // defined range" we allow.
6924       Sema::TentativeAnalysisScope Trap(*this);
6925 
6926       if (auto *SpecializedMethod = dyn_cast<CXXMethodDecl>(BestDecl)) {
6927         auto *MemberCall = dyn_cast<CXXMemberCallExpr>(CE);
6928         BestExpr = MemberExpr::CreateImplicit(
6929             Context, MemberCall->getImplicitObjectArgument(),
6930             /* IsArrow */ false, SpecializedMethod, Context.BoundMemberTy,
6931             MemberCall->getValueKind(), MemberCall->getObjectKind());
6932       }
6933       NewCall = BuildCallExpr(Scope, BestExpr, LParenLoc, ArgExprs, RParenLoc,
6934                               ExecConfig);
6935       if (NewCall.isUsable()) {
6936         if (CallExpr *NCE = dyn_cast<CallExpr>(NewCall.get())) {
6937           FunctionDecl *NewCalleeFnDecl = NCE->getDirectCallee();
6938           QualType NewType = Context.mergeFunctionTypes(
6939               CalleeFnType, NewCalleeFnDecl->getType(),
6940               /* OfBlockPointer */ false,
6941               /* Unqualified */ false, /* AllowCXX */ true);
6942           if (!NewType.isNull())
6943             break;
6944           // Don't use the call if the function type was not compatible.
6945           NewCall = nullptr;
6946         }
6947       }
6948     }
6949 
6950     VMIs.erase(VMIs.begin() + BestIdx);
6951     Exprs.erase(Exprs.begin() + BestIdx);
6952   } while (!VMIs.empty());
6953 
6954   if (!NewCall.isUsable())
6955     return Call;
6956   return PseudoObjectExpr::Create(Context, CE, {NewCall.get()}, 0);
6957 }
6958 
6959 Optional<std::pair<FunctionDecl *, Expr *>>
6960 Sema::checkOpenMPDeclareVariantFunction(Sema::DeclGroupPtrTy DG,
6961                                         Expr *VariantRef, OMPTraitInfo &TI,
6962                                         unsigned NumAppendArgs,
6963                                         SourceRange SR) {
6964   if (!DG || DG.get().isNull())
6965     return None;
6966 
6967   const int VariantId = 1;
6968   // Must be applied only to single decl.
6969   if (!DG.get().isSingleDecl()) {
6970     Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd_variant)
6971         << VariantId << SR;
6972     return None;
6973   }
6974   Decl *ADecl = DG.get().getSingleDecl();
6975   if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
6976     ADecl = FTD->getTemplatedDecl();
6977 
6978   // Decl must be a function.
6979   auto *FD = dyn_cast<FunctionDecl>(ADecl);
6980   if (!FD) {
6981     Diag(ADecl->getLocation(), diag::err_omp_function_expected)
6982         << VariantId << SR;
6983     return None;
6984   }
6985 
6986   auto &&HasMultiVersionAttributes = [](const FunctionDecl *FD) {
6987     return FD->hasAttrs() &&
6988            (FD->hasAttr<CPUDispatchAttr>() || FD->hasAttr<CPUSpecificAttr>() ||
6989             FD->hasAttr<TargetAttr>());
6990   };
6991   // OpenMP is not compatible with CPU-specific attributes.
6992   if (HasMultiVersionAttributes(FD)) {
6993     Diag(FD->getLocation(), diag::err_omp_declare_variant_incompat_attributes)
6994         << SR;
6995     return None;
6996   }
6997 
6998   // Allow #pragma omp declare variant only if the function is not used.
6999   if (FD->isUsed(false))
7000     Diag(SR.getBegin(), diag::warn_omp_declare_variant_after_used)
7001         << FD->getLocation();
7002 
7003   // Check if the function was emitted already.
7004   const FunctionDecl *Definition;
7005   if (!FD->isThisDeclarationADefinition() && FD->isDefined(Definition) &&
7006       (LangOpts.EmitAllDecls || Context.DeclMustBeEmitted(Definition)))
7007     Diag(SR.getBegin(), diag::warn_omp_declare_variant_after_emitted)
7008         << FD->getLocation();
7009 
7010   // The VariantRef must point to function.
7011   if (!VariantRef) {
7012     Diag(SR.getBegin(), diag::err_omp_function_expected) << VariantId;
7013     return None;
7014   }
7015 
7016   auto ShouldDelayChecks = [](Expr *&E, bool) {
7017     return E && (E->isTypeDependent() || E->isValueDependent() ||
7018                  E->containsUnexpandedParameterPack() ||
7019                  E->isInstantiationDependent());
7020   };
7021   // Do not check templates, wait until instantiation.
7022   if (FD->isDependentContext() || ShouldDelayChecks(VariantRef, false) ||
7023       TI.anyScoreOrCondition(ShouldDelayChecks))
7024     return std::make_pair(FD, VariantRef);
7025 
7026   // Deal with non-constant score and user condition expressions.
7027   auto HandleNonConstantScoresAndConditions = [this](Expr *&E,
7028                                                      bool IsScore) -> bool {
7029     if (!E || E->isIntegerConstantExpr(Context))
7030       return false;
7031 
7032     if (IsScore) {
7033       // We warn on non-constant scores and pretend they were not present.
7034       Diag(E->getExprLoc(), diag::warn_omp_declare_variant_score_not_constant)
7035           << E;
7036       E = nullptr;
7037     } else {
7038       // We could replace a non-constant user condition with "false" but we
7039       // will soon need to handle these anyway for the dynamic version of
7040       // OpenMP context selectors.
7041       Diag(E->getExprLoc(),
7042            diag::err_omp_declare_variant_user_condition_not_constant)
7043           << E;
7044     }
7045     return true;
7046   };
7047   if (TI.anyScoreOrCondition(HandleNonConstantScoresAndConditions))
7048     return None;
7049 
7050   QualType AdjustedFnType = FD->getType();
7051   if (NumAppendArgs) {
7052     if (isa<FunctionNoProtoType>(FD->getType())) {
7053       Diag(FD->getLocation(), diag::err_omp_declare_variant_prototype_required)
7054           << SR;
7055       return None;
7056     }
7057     // Adjust the function type to account for an extra omp_interop_t for each
7058     // specified in the append_args clause.
7059     const TypeDecl *TD = nullptr;
7060     LookupResult Result(*this, &Context.Idents.get("omp_interop_t"),
7061                         SR.getBegin(), Sema::LookupOrdinaryName);
7062     if (LookupName(Result, getCurScope())) {
7063       NamedDecl *ND = Result.getFoundDecl();
7064       TD = dyn_cast_or_null<TypeDecl>(ND);
7065     }
7066     if (!TD) {
7067       Diag(SR.getBegin(), diag::err_omp_interop_type_not_found) << SR;
7068       return None;
7069     }
7070     QualType InteropType = QualType(TD->getTypeForDecl(), 0);
7071     auto *PTy = cast<FunctionProtoType>(FD->getType());
7072     if (PTy->isVariadic()) {
7073       Diag(FD->getLocation(), diag::err_omp_append_args_with_varargs) << SR;
7074       return None;
7075     }
7076     llvm::SmallVector<QualType, 8> Params;
7077     Params.append(PTy->param_type_begin(), PTy->param_type_end());
7078     Params.insert(Params.end(), NumAppendArgs, InteropType);
7079     AdjustedFnType = Context.getFunctionType(PTy->getReturnType(), Params,
7080                                              PTy->getExtProtoInfo());
7081   }
7082 
7083   // Convert VariantRef expression to the type of the original function to
7084   // resolve possible conflicts.
7085   ExprResult VariantRefCast = VariantRef;
7086   if (LangOpts.CPlusPlus) {
7087     QualType FnPtrType;
7088     auto *Method = dyn_cast<CXXMethodDecl>(FD);
7089     if (Method && !Method->isStatic()) {
7090       const Type *ClassType =
7091           Context.getTypeDeclType(Method->getParent()).getTypePtr();
7092       FnPtrType = Context.getMemberPointerType(AdjustedFnType, ClassType);
7093       ExprResult ER;
7094       {
7095         // Build adrr_of unary op to correctly handle type checks for member
7096         // functions.
7097         Sema::TentativeAnalysisScope Trap(*this);
7098         ER = CreateBuiltinUnaryOp(VariantRef->getBeginLoc(), UO_AddrOf,
7099                                   VariantRef);
7100       }
7101       if (!ER.isUsable()) {
7102         Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
7103             << VariantId << VariantRef->getSourceRange();
7104         return None;
7105       }
7106       VariantRef = ER.get();
7107     } else {
7108       FnPtrType = Context.getPointerType(AdjustedFnType);
7109     }
7110     QualType VarianPtrType = Context.getPointerType(VariantRef->getType());
7111     if (VarianPtrType.getUnqualifiedType() != FnPtrType.getUnqualifiedType()) {
7112       ImplicitConversionSequence ICS = TryImplicitConversion(
7113           VariantRef, FnPtrType.getUnqualifiedType(),
7114           /*SuppressUserConversions=*/false, AllowedExplicit::None,
7115           /*InOverloadResolution=*/false,
7116           /*CStyle=*/false,
7117           /*AllowObjCWritebackConversion=*/false);
7118       if (ICS.isFailure()) {
7119         Diag(VariantRef->getExprLoc(),
7120              diag::err_omp_declare_variant_incompat_types)
7121             << VariantRef->getType()
7122             << ((Method && !Method->isStatic()) ? FnPtrType : FD->getType())
7123             << (NumAppendArgs ? 1 : 0) << VariantRef->getSourceRange();
7124         return None;
7125       }
7126       VariantRefCast = PerformImplicitConversion(
7127           VariantRef, FnPtrType.getUnqualifiedType(), AA_Converting);
7128       if (!VariantRefCast.isUsable())
7129         return None;
7130     }
7131     // Drop previously built artificial addr_of unary op for member functions.
7132     if (Method && !Method->isStatic()) {
7133       Expr *PossibleAddrOfVariantRef = VariantRefCast.get();
7134       if (auto *UO = dyn_cast<UnaryOperator>(
7135               PossibleAddrOfVariantRef->IgnoreImplicit()))
7136         VariantRefCast = UO->getSubExpr();
7137     }
7138   }
7139 
7140   ExprResult ER = CheckPlaceholderExpr(VariantRefCast.get());
7141   if (!ER.isUsable() ||
7142       !ER.get()->IgnoreParenImpCasts()->getType()->isFunctionType()) {
7143     Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
7144         << VariantId << VariantRef->getSourceRange();
7145     return None;
7146   }
7147 
7148   // The VariantRef must point to function.
7149   auto *DRE = dyn_cast<DeclRefExpr>(ER.get()->IgnoreParenImpCasts());
7150   if (!DRE) {
7151     Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
7152         << VariantId << VariantRef->getSourceRange();
7153     return None;
7154   }
7155   auto *NewFD = dyn_cast_or_null<FunctionDecl>(DRE->getDecl());
7156   if (!NewFD) {
7157     Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
7158         << VariantId << VariantRef->getSourceRange();
7159     return None;
7160   }
7161 
7162   // Check if function types are compatible in C.
7163   if (!LangOpts.CPlusPlus) {
7164     QualType NewType =
7165         Context.mergeFunctionTypes(AdjustedFnType, NewFD->getType());
7166     if (NewType.isNull()) {
7167       Diag(VariantRef->getExprLoc(),
7168            diag::err_omp_declare_variant_incompat_types)
7169           << NewFD->getType() << FD->getType() << (NumAppendArgs ? 1 : 0)
7170           << VariantRef->getSourceRange();
7171       return None;
7172     }
7173     if (NewType->isFunctionProtoType()) {
7174       if (FD->getType()->isFunctionNoProtoType())
7175         setPrototype(*this, FD, NewFD, NewType);
7176       else if (NewFD->getType()->isFunctionNoProtoType())
7177         setPrototype(*this, NewFD, FD, NewType);
7178     }
7179   }
7180 
7181   // Check if variant function is not marked with declare variant directive.
7182   if (NewFD->hasAttrs() && NewFD->hasAttr<OMPDeclareVariantAttr>()) {
7183     Diag(VariantRef->getExprLoc(),
7184          diag::warn_omp_declare_variant_marked_as_declare_variant)
7185         << VariantRef->getSourceRange();
7186     SourceRange SR =
7187         NewFD->specific_attr_begin<OMPDeclareVariantAttr>()->getRange();
7188     Diag(SR.getBegin(), diag::note_omp_marked_declare_variant_here) << SR;
7189     return None;
7190   }
7191 
7192   enum DoesntSupport {
7193     VirtFuncs = 1,
7194     Constructors = 3,
7195     Destructors = 4,
7196     DeletedFuncs = 5,
7197     DefaultedFuncs = 6,
7198     ConstexprFuncs = 7,
7199     ConstevalFuncs = 8,
7200   };
7201   if (const auto *CXXFD = dyn_cast<CXXMethodDecl>(FD)) {
7202     if (CXXFD->isVirtual()) {
7203       Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
7204           << VirtFuncs;
7205       return None;
7206     }
7207 
7208     if (isa<CXXConstructorDecl>(FD)) {
7209       Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
7210           << Constructors;
7211       return None;
7212     }
7213 
7214     if (isa<CXXDestructorDecl>(FD)) {
7215       Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
7216           << Destructors;
7217       return None;
7218     }
7219   }
7220 
7221   if (FD->isDeleted()) {
7222     Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
7223         << DeletedFuncs;
7224     return None;
7225   }
7226 
7227   if (FD->isDefaulted()) {
7228     Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
7229         << DefaultedFuncs;
7230     return None;
7231   }
7232 
7233   if (FD->isConstexpr()) {
7234     Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
7235         << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
7236     return None;
7237   }
7238 
7239   // Check general compatibility.
7240   if (areMultiversionVariantFunctionsCompatible(
7241           FD, NewFD, PartialDiagnostic::NullDiagnostic(),
7242           PartialDiagnosticAt(SourceLocation(),
7243                               PartialDiagnostic::NullDiagnostic()),
7244           PartialDiagnosticAt(
7245               VariantRef->getExprLoc(),
7246               PDiag(diag::err_omp_declare_variant_doesnt_support)),
7247           PartialDiagnosticAt(VariantRef->getExprLoc(),
7248                               PDiag(diag::err_omp_declare_variant_diff)
7249                                   << FD->getLocation()),
7250           /*TemplatesSupported=*/true, /*ConstexprSupported=*/false,
7251           /*CLinkageMayDiffer=*/true))
7252     return None;
7253   return std::make_pair(FD, cast<Expr>(DRE));
7254 }
7255 
7256 void Sema::ActOnOpenMPDeclareVariantDirective(
7257     FunctionDecl *FD, Expr *VariantRef, OMPTraitInfo &TI,
7258     ArrayRef<Expr *> AdjustArgsNothing,
7259     ArrayRef<Expr *> AdjustArgsNeedDevicePtr,
7260     ArrayRef<OMPDeclareVariantAttr::InteropType> AppendArgs,
7261     SourceLocation AdjustArgsLoc, SourceLocation AppendArgsLoc,
7262     SourceRange SR) {
7263 
7264   // OpenMP 5.1 [2.3.5, declare variant directive, Restrictions]
7265   // An adjust_args clause or append_args clause can only be specified if the
7266   // dispatch selector of the construct selector set appears in the match
7267   // clause.
7268 
7269   SmallVector<Expr *, 8> AllAdjustArgs;
7270   llvm::append_range(AllAdjustArgs, AdjustArgsNothing);
7271   llvm::append_range(AllAdjustArgs, AdjustArgsNeedDevicePtr);
7272 
7273   if (!AllAdjustArgs.empty() || !AppendArgs.empty()) {
7274     VariantMatchInfo VMI;
7275     TI.getAsVariantMatchInfo(Context, VMI);
7276     if (!llvm::is_contained(
7277             VMI.ConstructTraits,
7278             llvm::omp::TraitProperty::construct_dispatch_dispatch)) {
7279       if (!AllAdjustArgs.empty())
7280         Diag(AdjustArgsLoc, diag::err_omp_clause_requires_dispatch_construct)
7281             << getOpenMPClauseName(OMPC_adjust_args);
7282       if (!AppendArgs.empty())
7283         Diag(AppendArgsLoc, diag::err_omp_clause_requires_dispatch_construct)
7284             << getOpenMPClauseName(OMPC_append_args);
7285       return;
7286     }
7287   }
7288 
7289   // OpenMP 5.1 [2.3.5, declare variant directive, Restrictions]
7290   // Each argument can only appear in a single adjust_args clause for each
7291   // declare variant directive.
7292   llvm::SmallPtrSet<const VarDecl *, 4> AdjustVars;
7293 
7294   for (Expr *E : AllAdjustArgs) {
7295     E = E->IgnoreParenImpCasts();
7296     if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) {
7297       if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
7298         const VarDecl *CanonPVD = PVD->getCanonicalDecl();
7299         if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
7300             FD->getParamDecl(PVD->getFunctionScopeIndex())
7301                     ->getCanonicalDecl() == CanonPVD) {
7302           // It's a parameter of the function, check duplicates.
7303           if (!AdjustVars.insert(CanonPVD).second) {
7304             Diag(DRE->getLocation(), diag::err_omp_adjust_arg_multiple_clauses)
7305                 << PVD;
7306             return;
7307           }
7308           continue;
7309         }
7310       }
7311     }
7312     // Anything that is not a function parameter is an error.
7313     Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause) << FD << 0;
7314     return;
7315   }
7316 
7317   auto *NewAttr = OMPDeclareVariantAttr::CreateImplicit(
7318       Context, VariantRef, &TI, const_cast<Expr **>(AdjustArgsNothing.data()),
7319       AdjustArgsNothing.size(),
7320       const_cast<Expr **>(AdjustArgsNeedDevicePtr.data()),
7321       AdjustArgsNeedDevicePtr.size(),
7322       const_cast<OMPDeclareVariantAttr::InteropType *>(AppendArgs.data()),
7323       AppendArgs.size(), SR);
7324   FD->addAttr(NewAttr);
7325 }
7326 
7327 StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
7328                                               Stmt *AStmt,
7329                                               SourceLocation StartLoc,
7330                                               SourceLocation EndLoc) {
7331   if (!AStmt)
7332     return StmtError();
7333 
7334   auto *CS = cast<CapturedStmt>(AStmt);
7335   // 1.2.2 OpenMP Language Terminology
7336   // Structured block - An executable statement with a single entry at the
7337   // top and a single exit at the bottom.
7338   // The point of exit cannot be a branch out of the structured block.
7339   // longjmp() and throw() must not violate the entry/exit criteria.
7340   CS->getCapturedDecl()->setNothrow();
7341 
7342   setFunctionHasBranchProtectedScope();
7343 
7344   return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
7345                                       DSAStack->getTaskgroupReductionRef(),
7346                                       DSAStack->isCancelRegion());
7347 }
7348 
7349 namespace {
7350 /// Iteration space of a single for loop.
7351 struct LoopIterationSpace final {
7352   /// True if the condition operator is the strict compare operator (<, > or
7353   /// !=).
7354   bool IsStrictCompare = false;
7355   /// Condition of the loop.
7356   Expr *PreCond = nullptr;
7357   /// This expression calculates the number of iterations in the loop.
7358   /// It is always possible to calculate it before starting the loop.
7359   Expr *NumIterations = nullptr;
7360   /// The loop counter variable.
7361   Expr *CounterVar = nullptr;
7362   /// Private loop counter variable.
7363   Expr *PrivateCounterVar = nullptr;
7364   /// This is initializer for the initial value of #CounterVar.
7365   Expr *CounterInit = nullptr;
7366   /// This is step for the #CounterVar used to generate its update:
7367   /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
7368   Expr *CounterStep = nullptr;
7369   /// Should step be subtracted?
7370   bool Subtract = false;
7371   /// Source range of the loop init.
7372   SourceRange InitSrcRange;
7373   /// Source range of the loop condition.
7374   SourceRange CondSrcRange;
7375   /// Source range of the loop increment.
7376   SourceRange IncSrcRange;
7377   /// Minimum value that can have the loop control variable. Used to support
7378   /// non-rectangular loops. Applied only for LCV with the non-iterator types,
7379   /// since only such variables can be used in non-loop invariant expressions.
7380   Expr *MinValue = nullptr;
7381   /// Maximum value that can have the loop control variable. Used to support
7382   /// non-rectangular loops. Applied only for LCV with the non-iterator type,
7383   /// since only such variables can be used in non-loop invariant expressions.
7384   Expr *MaxValue = nullptr;
7385   /// true, if the lower bound depends on the outer loop control var.
7386   bool IsNonRectangularLB = false;
7387   /// true, if the upper bound depends on the outer loop control var.
7388   bool IsNonRectangularUB = false;
7389   /// Index of the loop this loop depends on and forms non-rectangular loop
7390   /// nest.
7391   unsigned LoopDependentIdx = 0;
7392   /// Final condition for the non-rectangular loop nest support. It is used to
7393   /// check that the number of iterations for this particular counter must be
7394   /// finished.
7395   Expr *FinalCondition = nullptr;
7396 };
7397 
7398 /// Helper class for checking canonical form of the OpenMP loops and
7399 /// extracting iteration space of each loop in the loop nest, that will be used
7400 /// for IR generation.
7401 class OpenMPIterationSpaceChecker {
7402   /// Reference to Sema.
7403   Sema &SemaRef;
7404   /// Does the loop associated directive support non-rectangular loops?
7405   bool SupportsNonRectangular;
7406   /// Data-sharing stack.
7407   DSAStackTy &Stack;
7408   /// A location for diagnostics (when there is no some better location).
7409   SourceLocation DefaultLoc;
7410   /// A location for diagnostics (when increment is not compatible).
7411   SourceLocation ConditionLoc;
7412   /// A source location for referring to loop init later.
7413   SourceRange InitSrcRange;
7414   /// A source location for referring to condition later.
7415   SourceRange ConditionSrcRange;
7416   /// A source location for referring to increment later.
7417   SourceRange IncrementSrcRange;
7418   /// Loop variable.
7419   ValueDecl *LCDecl = nullptr;
7420   /// Reference to loop variable.
7421   Expr *LCRef = nullptr;
7422   /// Lower bound (initializer for the var).
7423   Expr *LB = nullptr;
7424   /// Upper bound.
7425   Expr *UB = nullptr;
7426   /// Loop step (increment).
7427   Expr *Step = nullptr;
7428   /// This flag is true when condition is one of:
7429   ///   Var <  UB
7430   ///   Var <= UB
7431   ///   UB  >  Var
7432   ///   UB  >= Var
7433   /// This will have no value when the condition is !=
7434   llvm::Optional<bool> TestIsLessOp;
7435   /// This flag is true when condition is strict ( < or > ).
7436   bool TestIsStrictOp = false;
7437   /// This flag is true when step is subtracted on each iteration.
7438   bool SubtractStep = false;
7439   /// The outer loop counter this loop depends on (if any).
7440   const ValueDecl *DepDecl = nullptr;
7441   /// Contains number of loop (starts from 1) on which loop counter init
7442   /// expression of this loop depends on.
7443   Optional<unsigned> InitDependOnLC;
7444   /// Contains number of loop (starts from 1) on which loop counter condition
7445   /// expression of this loop depends on.
7446   Optional<unsigned> CondDependOnLC;
7447   /// Checks if the provide statement depends on the loop counter.
7448   Optional<unsigned> doesDependOnLoopCounter(const Stmt *S, bool IsInitializer);
7449   /// Original condition required for checking of the exit condition for
7450   /// non-rectangular loop.
7451   Expr *Condition = nullptr;
7452 
7453 public:
7454   OpenMPIterationSpaceChecker(Sema &SemaRef, bool SupportsNonRectangular,
7455                               DSAStackTy &Stack, SourceLocation DefaultLoc)
7456       : SemaRef(SemaRef), SupportsNonRectangular(SupportsNonRectangular),
7457         Stack(Stack), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {}
7458   /// Check init-expr for canonical loop form and save loop counter
7459   /// variable - #Var and its initialization value - #LB.
7460   bool checkAndSetInit(Stmt *S, bool EmitDiags = true);
7461   /// Check test-expr for canonical form, save upper-bound (#UB), flags
7462   /// for less/greater and for strict/non-strict comparison.
7463   bool checkAndSetCond(Expr *S);
7464   /// Check incr-expr for canonical loop form and return true if it
7465   /// does not conform, otherwise save loop step (#Step).
7466   bool checkAndSetInc(Expr *S);
7467   /// Return the loop counter variable.
7468   ValueDecl *getLoopDecl() const { return LCDecl; }
7469   /// Return the reference expression to loop counter variable.
7470   Expr *getLoopDeclRefExpr() const { return LCRef; }
7471   /// Source range of the loop init.
7472   SourceRange getInitSrcRange() const { return InitSrcRange; }
7473   /// Source range of the loop condition.
7474   SourceRange getConditionSrcRange() const { return ConditionSrcRange; }
7475   /// Source range of the loop increment.
7476   SourceRange getIncrementSrcRange() const { return IncrementSrcRange; }
7477   /// True if the step should be subtracted.
7478   bool shouldSubtractStep() const { return SubtractStep; }
7479   /// True, if the compare operator is strict (<, > or !=).
7480   bool isStrictTestOp() const { return TestIsStrictOp; }
7481   /// Build the expression to calculate the number of iterations.
7482   Expr *buildNumIterations(
7483       Scope *S, ArrayRef<LoopIterationSpace> ResultIterSpaces, bool LimitedType,
7484       llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
7485   /// Build the precondition expression for the loops.
7486   Expr *
7487   buildPreCond(Scope *S, Expr *Cond,
7488                llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
7489   /// Build reference expression to the counter be used for codegen.
7490   DeclRefExpr *
7491   buildCounterVar(llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
7492                   DSAStackTy &DSA) const;
7493   /// Build reference expression to the private counter be used for
7494   /// codegen.
7495   Expr *buildPrivateCounterVar() const;
7496   /// Build initialization of the counter be used for codegen.
7497   Expr *buildCounterInit() const;
7498   /// Build step of the counter be used for codegen.
7499   Expr *buildCounterStep() const;
7500   /// Build loop data with counter value for depend clauses in ordered
7501   /// directives.
7502   Expr *
7503   buildOrderedLoopData(Scope *S, Expr *Counter,
7504                        llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
7505                        SourceLocation Loc, Expr *Inc = nullptr,
7506                        OverloadedOperatorKind OOK = OO_Amp);
7507   /// Builds the minimum value for the loop counter.
7508   std::pair<Expr *, Expr *> buildMinMaxValues(
7509       Scope *S, llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
7510   /// Builds final condition for the non-rectangular loops.
7511   Expr *buildFinalCondition(Scope *S) const;
7512   /// Return true if any expression is dependent.
7513   bool dependent() const;
7514   /// Returns true if the initializer forms non-rectangular loop.
7515   bool doesInitDependOnLC() const { return InitDependOnLC.hasValue(); }
7516   /// Returns true if the condition forms non-rectangular loop.
7517   bool doesCondDependOnLC() const { return CondDependOnLC.hasValue(); }
7518   /// Returns index of the loop we depend on (starting from 1), or 0 otherwise.
7519   unsigned getLoopDependentIdx() const {
7520     return InitDependOnLC.getValueOr(CondDependOnLC.getValueOr(0));
7521   }
7522 
7523 private:
7524   /// Check the right-hand side of an assignment in the increment
7525   /// expression.
7526   bool checkAndSetIncRHS(Expr *RHS);
7527   /// Helper to set loop counter variable and its initializer.
7528   bool setLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB,
7529                       bool EmitDiags);
7530   /// Helper to set upper bound.
7531   bool setUB(Expr *NewUB, llvm::Optional<bool> LessOp, bool StrictOp,
7532              SourceRange SR, SourceLocation SL);
7533   /// Helper to set loop increment.
7534   bool setStep(Expr *NewStep, bool Subtract);
7535 };
7536 
7537 bool OpenMPIterationSpaceChecker::dependent() const {
7538   if (!LCDecl) {
7539     assert(!LB && !UB && !Step);
7540     return false;
7541   }
7542   return LCDecl->getType()->isDependentType() ||
7543          (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
7544          (Step && Step->isValueDependent());
7545 }
7546 
7547 bool OpenMPIterationSpaceChecker::setLCDeclAndLB(ValueDecl *NewLCDecl,
7548                                                  Expr *NewLCRefExpr,
7549                                                  Expr *NewLB, bool EmitDiags) {
7550   // State consistency checking to ensure correct usage.
7551   assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
7552          UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
7553   if (!NewLCDecl || !NewLB || NewLB->containsErrors())
7554     return true;
7555   LCDecl = getCanonicalDecl(NewLCDecl);
7556   LCRef = NewLCRefExpr;
7557   if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
7558     if (const CXXConstructorDecl *Ctor = CE->getConstructor())
7559       if ((Ctor->isCopyOrMoveConstructor() ||
7560            Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
7561           CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
7562         NewLB = CE->getArg(0)->IgnoreParenImpCasts();
7563   LB = NewLB;
7564   if (EmitDiags)
7565     InitDependOnLC = doesDependOnLoopCounter(LB, /*IsInitializer=*/true);
7566   return false;
7567 }
7568 
7569 bool OpenMPIterationSpaceChecker::setUB(Expr *NewUB,
7570                                         llvm::Optional<bool> LessOp,
7571                                         bool StrictOp, SourceRange SR,
7572                                         SourceLocation SL) {
7573   // State consistency checking to ensure correct usage.
7574   assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
7575          Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
7576   if (!NewUB || NewUB->containsErrors())
7577     return true;
7578   UB = NewUB;
7579   if (LessOp)
7580     TestIsLessOp = LessOp;
7581   TestIsStrictOp = StrictOp;
7582   ConditionSrcRange = SR;
7583   ConditionLoc = SL;
7584   CondDependOnLC = doesDependOnLoopCounter(UB, /*IsInitializer=*/false);
7585   return false;
7586 }
7587 
7588 bool OpenMPIterationSpaceChecker::setStep(Expr *NewStep, bool Subtract) {
7589   // State consistency checking to ensure correct usage.
7590   assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
7591   if (!NewStep || NewStep->containsErrors())
7592     return true;
7593   if (!NewStep->isValueDependent()) {
7594     // Check that the step is integer expression.
7595     SourceLocation StepLoc = NewStep->getBeginLoc();
7596     ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion(
7597         StepLoc, getExprAsWritten(NewStep));
7598     if (Val.isInvalid())
7599       return true;
7600     NewStep = Val.get();
7601 
7602     // OpenMP [2.6, Canonical Loop Form, Restrictions]
7603     //  If test-expr is of form var relational-op b and relational-op is < or
7604     //  <= then incr-expr must cause var to increase on each iteration of the
7605     //  loop. If test-expr is of form var relational-op b and relational-op is
7606     //  > or >= then incr-expr must cause var to decrease on each iteration of
7607     //  the loop.
7608     //  If test-expr is of form b relational-op var and relational-op is < or
7609     //  <= then incr-expr must cause var to decrease on each iteration of the
7610     //  loop. If test-expr is of form b relational-op var and relational-op is
7611     //  > or >= then incr-expr must cause var to increase on each iteration of
7612     //  the loop.
7613     Optional<llvm::APSInt> Result =
7614         NewStep->getIntegerConstantExpr(SemaRef.Context);
7615     bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
7616     bool IsConstNeg =
7617         Result && Result->isSigned() && (Subtract != Result->isNegative());
7618     bool IsConstPos =
7619         Result && Result->isSigned() && (Subtract == Result->isNegative());
7620     bool IsConstZero = Result && !Result->getBoolValue();
7621 
7622     // != with increment is treated as <; != with decrement is treated as >
7623     if (!TestIsLessOp.hasValue())
7624       TestIsLessOp = IsConstPos || (IsUnsigned && !Subtract);
7625     if (UB &&
7626         (IsConstZero || (TestIsLessOp.getValue()
7627                              ? (IsConstNeg || (IsUnsigned && Subtract))
7628                              : (IsConstPos || (IsUnsigned && !Subtract))))) {
7629       SemaRef.Diag(NewStep->getExprLoc(),
7630                    diag::err_omp_loop_incr_not_compatible)
7631           << LCDecl << TestIsLessOp.getValue() << NewStep->getSourceRange();
7632       SemaRef.Diag(ConditionLoc,
7633                    diag::note_omp_loop_cond_requres_compatible_incr)
7634           << TestIsLessOp.getValue() << ConditionSrcRange;
7635       return true;
7636     }
7637     if (TestIsLessOp.getValue() == Subtract) {
7638       NewStep =
7639           SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
7640               .get();
7641       Subtract = !Subtract;
7642     }
7643   }
7644 
7645   Step = NewStep;
7646   SubtractStep = Subtract;
7647   return false;
7648 }
7649 
7650 namespace {
7651 /// Checker for the non-rectangular loops. Checks if the initializer or
7652 /// condition expression references loop counter variable.
7653 class LoopCounterRefChecker final
7654     : public ConstStmtVisitor<LoopCounterRefChecker, bool> {
7655   Sema &SemaRef;
7656   DSAStackTy &Stack;
7657   const ValueDecl *CurLCDecl = nullptr;
7658   const ValueDecl *DepDecl = nullptr;
7659   const ValueDecl *PrevDepDecl = nullptr;
7660   bool IsInitializer = true;
7661   bool SupportsNonRectangular;
7662   unsigned BaseLoopId = 0;
7663   bool checkDecl(const Expr *E, const ValueDecl *VD) {
7664     if (getCanonicalDecl(VD) == getCanonicalDecl(CurLCDecl)) {
7665       SemaRef.Diag(E->getExprLoc(), diag::err_omp_stmt_depends_on_loop_counter)
7666           << (IsInitializer ? 0 : 1);
7667       return false;
7668     }
7669     const auto &&Data = Stack.isLoopControlVariable(VD);
7670     // OpenMP, 2.9.1 Canonical Loop Form, Restrictions.
7671     // The type of the loop iterator on which we depend may not have a random
7672     // access iterator type.
7673     if (Data.first && VD->getType()->isRecordType()) {
7674       SmallString<128> Name;
7675       llvm::raw_svector_ostream OS(Name);
7676       VD->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(),
7677                                /*Qualified=*/true);
7678       SemaRef.Diag(E->getExprLoc(),
7679                    diag::err_omp_wrong_dependency_iterator_type)
7680           << OS.str();
7681       SemaRef.Diag(VD->getLocation(), diag::note_previous_decl) << VD;
7682       return false;
7683     }
7684     if (Data.first && !SupportsNonRectangular) {
7685       SemaRef.Diag(E->getExprLoc(), diag::err_omp_invariant_dependency);
7686       return false;
7687     }
7688     if (Data.first &&
7689         (DepDecl || (PrevDepDecl &&
7690                      getCanonicalDecl(VD) != getCanonicalDecl(PrevDepDecl)))) {
7691       if (!DepDecl && PrevDepDecl)
7692         DepDecl = PrevDepDecl;
7693       SmallString<128> Name;
7694       llvm::raw_svector_ostream OS(Name);
7695       DepDecl->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(),
7696                                     /*Qualified=*/true);
7697       SemaRef.Diag(E->getExprLoc(),
7698                    diag::err_omp_invariant_or_linear_dependency)
7699           << OS.str();
7700       return false;
7701     }
7702     if (Data.first) {
7703       DepDecl = VD;
7704       BaseLoopId = Data.first;
7705     }
7706     return Data.first;
7707   }
7708 
7709 public:
7710   bool VisitDeclRefExpr(const DeclRefExpr *E) {
7711     const ValueDecl *VD = E->getDecl();
7712     if (isa<VarDecl>(VD))
7713       return checkDecl(E, VD);
7714     return false;
7715   }
7716   bool VisitMemberExpr(const MemberExpr *E) {
7717     if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
7718       const ValueDecl *VD = E->getMemberDecl();
7719       if (isa<VarDecl>(VD) || isa<FieldDecl>(VD))
7720         return checkDecl(E, VD);
7721     }
7722     return false;
7723   }
7724   bool VisitStmt(const Stmt *S) {
7725     bool Res = false;
7726     for (const Stmt *Child : S->children())
7727       Res = (Child && Visit(Child)) || Res;
7728     return Res;
7729   }
7730   explicit LoopCounterRefChecker(Sema &SemaRef, DSAStackTy &Stack,
7731                                  const ValueDecl *CurLCDecl, bool IsInitializer,
7732                                  const ValueDecl *PrevDepDecl = nullptr,
7733                                  bool SupportsNonRectangular = true)
7734       : SemaRef(SemaRef), Stack(Stack), CurLCDecl(CurLCDecl),
7735         PrevDepDecl(PrevDepDecl), IsInitializer(IsInitializer),
7736         SupportsNonRectangular(SupportsNonRectangular) {}
7737   unsigned getBaseLoopId() const {
7738     assert(CurLCDecl && "Expected loop dependency.");
7739     return BaseLoopId;
7740   }
7741   const ValueDecl *getDepDecl() const {
7742     assert(CurLCDecl && "Expected loop dependency.");
7743     return DepDecl;
7744   }
7745 };
7746 } // namespace
7747 
7748 Optional<unsigned>
7749 OpenMPIterationSpaceChecker::doesDependOnLoopCounter(const Stmt *S,
7750                                                      bool IsInitializer) {
7751   // Check for the non-rectangular loops.
7752   LoopCounterRefChecker LoopStmtChecker(SemaRef, Stack, LCDecl, IsInitializer,
7753                                         DepDecl, SupportsNonRectangular);
7754   if (LoopStmtChecker.Visit(S)) {
7755     DepDecl = LoopStmtChecker.getDepDecl();
7756     return LoopStmtChecker.getBaseLoopId();
7757   }
7758   return llvm::None;
7759 }
7760 
7761 bool OpenMPIterationSpaceChecker::checkAndSetInit(Stmt *S, bool EmitDiags) {
7762   // Check init-expr for canonical loop form and save loop counter
7763   // variable - #Var and its initialization value - #LB.
7764   // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
7765   //   var = lb
7766   //   integer-type var = lb
7767   //   random-access-iterator-type var = lb
7768   //   pointer-type var = lb
7769   //
7770   if (!S) {
7771     if (EmitDiags) {
7772       SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
7773     }
7774     return true;
7775   }
7776   if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
7777     if (!ExprTemp->cleanupsHaveSideEffects())
7778       S = ExprTemp->getSubExpr();
7779 
7780   InitSrcRange = S->getSourceRange();
7781   if (Expr *E = dyn_cast<Expr>(S))
7782     S = E->IgnoreParens();
7783   if (auto *BO = dyn_cast<BinaryOperator>(S)) {
7784     if (BO->getOpcode() == BO_Assign) {
7785       Expr *LHS = BO->getLHS()->IgnoreParens();
7786       if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
7787         if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
7788           if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
7789             return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
7790                                   EmitDiags);
7791         return setLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS(), EmitDiags);
7792       }
7793       if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
7794         if (ME->isArrow() &&
7795             isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
7796           return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
7797                                 EmitDiags);
7798       }
7799     }
7800   } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
7801     if (DS->isSingleDecl()) {
7802       if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
7803         if (Var->hasInit() && !Var->getType()->isReferenceType()) {
7804           // Accept non-canonical init form here but emit ext. warning.
7805           if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
7806             SemaRef.Diag(S->getBeginLoc(),
7807                          diag::ext_omp_loop_not_canonical_init)
7808                 << S->getSourceRange();
7809           return setLCDeclAndLB(
7810               Var,
7811               buildDeclRefExpr(SemaRef, Var,
7812                                Var->getType().getNonReferenceType(),
7813                                DS->getBeginLoc()),
7814               Var->getInit(), EmitDiags);
7815         }
7816       }
7817     }
7818   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
7819     if (CE->getOperator() == OO_Equal) {
7820       Expr *LHS = CE->getArg(0);
7821       if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
7822         if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
7823           if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
7824             return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
7825                                   EmitDiags);
7826         return setLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1), EmitDiags);
7827       }
7828       if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
7829         if (ME->isArrow() &&
7830             isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
7831           return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
7832                                 EmitDiags);
7833       }
7834     }
7835   }
7836 
7837   if (dependent() || SemaRef.CurContext->isDependentContext())
7838     return false;
7839   if (EmitDiags) {
7840     SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_init)
7841         << S->getSourceRange();
7842   }
7843   return true;
7844 }
7845 
7846 /// Ignore parenthesizes, implicit casts, copy constructor and return the
7847 /// variable (which may be the loop variable) if possible.
7848 static const ValueDecl *getInitLCDecl(const Expr *E) {
7849   if (!E)
7850     return nullptr;
7851   E = getExprAsWritten(E);
7852   if (const auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
7853     if (const CXXConstructorDecl *Ctor = CE->getConstructor())
7854       if ((Ctor->isCopyOrMoveConstructor() ||
7855            Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
7856           CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
7857         E = CE->getArg(0)->IgnoreParenImpCasts();
7858   if (const auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
7859     if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
7860       return getCanonicalDecl(VD);
7861   }
7862   if (const auto *ME = dyn_cast_or_null<MemberExpr>(E))
7863     if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
7864       return getCanonicalDecl(ME->getMemberDecl());
7865   return nullptr;
7866 }
7867 
7868 bool OpenMPIterationSpaceChecker::checkAndSetCond(Expr *S) {
7869   // Check test-expr for canonical form, save upper-bound UB, flags for
7870   // less/greater and for strict/non-strict comparison.
7871   // OpenMP [2.9] Canonical loop form. Test-expr may be one of the following:
7872   //   var relational-op b
7873   //   b relational-op var
7874   //
7875   bool IneqCondIsCanonical = SemaRef.getLangOpts().OpenMP >= 50;
7876   if (!S) {
7877     SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond)
7878         << (IneqCondIsCanonical ? 1 : 0) << LCDecl;
7879     return true;
7880   }
7881   Condition = S;
7882   S = getExprAsWritten(S);
7883   SourceLocation CondLoc = S->getBeginLoc();
7884   auto &&CheckAndSetCond = [this, IneqCondIsCanonical](
7885                                BinaryOperatorKind Opcode, const Expr *LHS,
7886                                const Expr *RHS, SourceRange SR,
7887                                SourceLocation OpLoc) -> llvm::Optional<bool> {
7888     if (BinaryOperator::isRelationalOp(Opcode)) {
7889       if (getInitLCDecl(LHS) == LCDecl)
7890         return setUB(const_cast<Expr *>(RHS),
7891                      (Opcode == BO_LT || Opcode == BO_LE),
7892                      (Opcode == BO_LT || Opcode == BO_GT), SR, OpLoc);
7893       if (getInitLCDecl(RHS) == LCDecl)
7894         return setUB(const_cast<Expr *>(LHS),
7895                      (Opcode == BO_GT || Opcode == BO_GE),
7896                      (Opcode == BO_LT || Opcode == BO_GT), SR, OpLoc);
7897     } else if (IneqCondIsCanonical && Opcode == BO_NE) {
7898       return setUB(const_cast<Expr *>(getInitLCDecl(LHS) == LCDecl ? RHS : LHS),
7899                    /*LessOp=*/llvm::None,
7900                    /*StrictOp=*/true, SR, OpLoc);
7901     }
7902     return llvm::None;
7903   };
7904   llvm::Optional<bool> Res;
7905   if (auto *RBO = dyn_cast<CXXRewrittenBinaryOperator>(S)) {
7906     CXXRewrittenBinaryOperator::DecomposedForm DF = RBO->getDecomposedForm();
7907     Res = CheckAndSetCond(DF.Opcode, DF.LHS, DF.RHS, RBO->getSourceRange(),
7908                           RBO->getOperatorLoc());
7909   } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
7910     Res = CheckAndSetCond(BO->getOpcode(), BO->getLHS(), BO->getRHS(),
7911                           BO->getSourceRange(), BO->getOperatorLoc());
7912   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
7913     if (CE->getNumArgs() == 2) {
7914       Res = CheckAndSetCond(
7915           BinaryOperator::getOverloadedOpcode(CE->getOperator()), CE->getArg(0),
7916           CE->getArg(1), CE->getSourceRange(), CE->getOperatorLoc());
7917     }
7918   }
7919   if (Res.hasValue())
7920     return *Res;
7921   if (dependent() || SemaRef.CurContext->isDependentContext())
7922     return false;
7923   SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
7924       << (IneqCondIsCanonical ? 1 : 0) << S->getSourceRange() << LCDecl;
7925   return true;
7926 }
7927 
7928 bool OpenMPIterationSpaceChecker::checkAndSetIncRHS(Expr *RHS) {
7929   // RHS of canonical loop form increment can be:
7930   //   var + incr
7931   //   incr + var
7932   //   var - incr
7933   //
7934   RHS = RHS->IgnoreParenImpCasts();
7935   if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
7936     if (BO->isAdditiveOp()) {
7937       bool IsAdd = BO->getOpcode() == BO_Add;
7938       if (getInitLCDecl(BO->getLHS()) == LCDecl)
7939         return setStep(BO->getRHS(), !IsAdd);
7940       if (IsAdd && getInitLCDecl(BO->getRHS()) == LCDecl)
7941         return setStep(BO->getLHS(), /*Subtract=*/false);
7942     }
7943   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
7944     bool IsAdd = CE->getOperator() == OO_Plus;
7945     if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
7946       if (getInitLCDecl(CE->getArg(0)) == LCDecl)
7947         return setStep(CE->getArg(1), !IsAdd);
7948       if (IsAdd && getInitLCDecl(CE->getArg(1)) == LCDecl)
7949         return setStep(CE->getArg(0), /*Subtract=*/false);
7950     }
7951   }
7952   if (dependent() || SemaRef.CurContext->isDependentContext())
7953     return false;
7954   SemaRef.Diag(RHS->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
7955       << RHS->getSourceRange() << LCDecl;
7956   return true;
7957 }
7958 
7959 bool OpenMPIterationSpaceChecker::checkAndSetInc(Expr *S) {
7960   // Check incr-expr for canonical loop form and return true if it
7961   // does not conform.
7962   // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
7963   //   ++var
7964   //   var++
7965   //   --var
7966   //   var--
7967   //   var += incr
7968   //   var -= incr
7969   //   var = var + incr
7970   //   var = incr + var
7971   //   var = var - incr
7972   //
7973   if (!S) {
7974     SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
7975     return true;
7976   }
7977   if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
7978     if (!ExprTemp->cleanupsHaveSideEffects())
7979       S = ExprTemp->getSubExpr();
7980 
7981   IncrementSrcRange = S->getSourceRange();
7982   S = S->IgnoreParens();
7983   if (auto *UO = dyn_cast<UnaryOperator>(S)) {
7984     if (UO->isIncrementDecrementOp() &&
7985         getInitLCDecl(UO->getSubExpr()) == LCDecl)
7986       return setStep(SemaRef
7987                          .ActOnIntegerConstant(UO->getBeginLoc(),
7988                                                (UO->isDecrementOp() ? -1 : 1))
7989                          .get(),
7990                      /*Subtract=*/false);
7991   } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
7992     switch (BO->getOpcode()) {
7993     case BO_AddAssign:
7994     case BO_SubAssign:
7995       if (getInitLCDecl(BO->getLHS()) == LCDecl)
7996         return setStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
7997       break;
7998     case BO_Assign:
7999       if (getInitLCDecl(BO->getLHS()) == LCDecl)
8000         return checkAndSetIncRHS(BO->getRHS());
8001       break;
8002     default:
8003       break;
8004     }
8005   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
8006     switch (CE->getOperator()) {
8007     case OO_PlusPlus:
8008     case OO_MinusMinus:
8009       if (getInitLCDecl(CE->getArg(0)) == LCDecl)
8010         return setStep(SemaRef
8011                            .ActOnIntegerConstant(
8012                                CE->getBeginLoc(),
8013                                ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
8014                            .get(),
8015                        /*Subtract=*/false);
8016       break;
8017     case OO_PlusEqual:
8018     case OO_MinusEqual:
8019       if (getInitLCDecl(CE->getArg(0)) == LCDecl)
8020         return setStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
8021       break;
8022     case OO_Equal:
8023       if (getInitLCDecl(CE->getArg(0)) == LCDecl)
8024         return checkAndSetIncRHS(CE->getArg(1));
8025       break;
8026     default:
8027       break;
8028     }
8029   }
8030   if (dependent() || SemaRef.CurContext->isDependentContext())
8031     return false;
8032   SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
8033       << S->getSourceRange() << LCDecl;
8034   return true;
8035 }
8036 
8037 static ExprResult
8038 tryBuildCapture(Sema &SemaRef, Expr *Capture,
8039                 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
8040   if (SemaRef.CurContext->isDependentContext() || Capture->containsErrors())
8041     return Capture;
8042   if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
8043     return SemaRef.PerformImplicitConversion(
8044         Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
8045         /*AllowExplicit=*/true);
8046   auto I = Captures.find(Capture);
8047   if (I != Captures.end())
8048     return buildCapture(SemaRef, Capture, I->second);
8049   DeclRefExpr *Ref = nullptr;
8050   ExprResult Res = buildCapture(SemaRef, Capture, Ref);
8051   Captures[Capture] = Ref;
8052   return Res;
8053 }
8054 
8055 /// Calculate number of iterations, transforming to unsigned, if number of
8056 /// iterations may be larger than the original type.
8057 static Expr *
8058 calculateNumIters(Sema &SemaRef, Scope *S, SourceLocation DefaultLoc,
8059                   Expr *Lower, Expr *Upper, Expr *Step, QualType LCTy,
8060                   bool TestIsStrictOp, bool RoundToStep,
8061                   llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
8062   ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
8063   if (!NewStep.isUsable())
8064     return nullptr;
8065   llvm::APSInt LRes, SRes;
8066   bool IsLowerConst = false, IsStepConst = false;
8067   if (Optional<llvm::APSInt> Res =
8068           Lower->getIntegerConstantExpr(SemaRef.Context)) {
8069     LRes = *Res;
8070     IsLowerConst = true;
8071   }
8072   if (Optional<llvm::APSInt> Res =
8073           Step->getIntegerConstantExpr(SemaRef.Context)) {
8074     SRes = *Res;
8075     IsStepConst = true;
8076   }
8077   bool NoNeedToConvert = IsLowerConst && !RoundToStep &&
8078                          ((!TestIsStrictOp && LRes.isNonNegative()) ||
8079                           (TestIsStrictOp && LRes.isStrictlyPositive()));
8080   bool NeedToReorganize = false;
8081   // Check if any subexpressions in Lower -Step [+ 1] lead to overflow.
8082   if (!NoNeedToConvert && IsLowerConst &&
8083       (TestIsStrictOp || (RoundToStep && IsStepConst))) {
8084     NoNeedToConvert = true;
8085     if (RoundToStep) {
8086       unsigned BW = LRes.getBitWidth() > SRes.getBitWidth()
8087                         ? LRes.getBitWidth()
8088                         : SRes.getBitWidth();
8089       LRes = LRes.extend(BW + 1);
8090       LRes.setIsSigned(true);
8091       SRes = SRes.extend(BW + 1);
8092       SRes.setIsSigned(true);
8093       LRes -= SRes;
8094       NoNeedToConvert = LRes.trunc(BW).extend(BW + 1) == LRes;
8095       LRes = LRes.trunc(BW);
8096     }
8097     if (TestIsStrictOp) {
8098       unsigned BW = LRes.getBitWidth();
8099       LRes = LRes.extend(BW + 1);
8100       LRes.setIsSigned(true);
8101       ++LRes;
8102       NoNeedToConvert =
8103           NoNeedToConvert && LRes.trunc(BW).extend(BW + 1) == LRes;
8104       // truncate to the original bitwidth.
8105       LRes = LRes.trunc(BW);
8106     }
8107     NeedToReorganize = NoNeedToConvert;
8108   }
8109   llvm::APSInt URes;
8110   bool IsUpperConst = false;
8111   if (Optional<llvm::APSInt> Res =
8112           Upper->getIntegerConstantExpr(SemaRef.Context)) {
8113     URes = *Res;
8114     IsUpperConst = true;
8115   }
8116   if (NoNeedToConvert && IsLowerConst && IsUpperConst &&
8117       (!RoundToStep || IsStepConst)) {
8118     unsigned BW = LRes.getBitWidth() > URes.getBitWidth() ? LRes.getBitWidth()
8119                                                           : URes.getBitWidth();
8120     LRes = LRes.extend(BW + 1);
8121     LRes.setIsSigned(true);
8122     URes = URes.extend(BW + 1);
8123     URes.setIsSigned(true);
8124     URes -= LRes;
8125     NoNeedToConvert = URes.trunc(BW).extend(BW + 1) == URes;
8126     NeedToReorganize = NoNeedToConvert;
8127   }
8128   // If the boundaries are not constant or (Lower - Step [+ 1]) is not constant
8129   // or less than zero (Upper - (Lower - Step [+ 1]) may overflow) - promote to
8130   // unsigned.
8131   if ((!NoNeedToConvert || (LRes.isNegative() && !IsUpperConst)) &&
8132       !LCTy->isDependentType() && LCTy->isIntegerType()) {
8133     QualType LowerTy = Lower->getType();
8134     QualType UpperTy = Upper->getType();
8135     uint64_t LowerSize = SemaRef.Context.getTypeSize(LowerTy);
8136     uint64_t UpperSize = SemaRef.Context.getTypeSize(UpperTy);
8137     if ((LowerSize <= UpperSize && UpperTy->hasSignedIntegerRepresentation()) ||
8138         (LowerSize > UpperSize && LowerTy->hasSignedIntegerRepresentation())) {
8139       QualType CastType = SemaRef.Context.getIntTypeForBitwidth(
8140           LowerSize > UpperSize ? LowerSize : UpperSize, /*Signed=*/0);
8141       Upper =
8142           SemaRef
8143               .PerformImplicitConversion(
8144                   SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Upper).get(),
8145                   CastType, Sema::AA_Converting)
8146               .get();
8147       Lower = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Lower).get();
8148       NewStep = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, NewStep.get());
8149     }
8150   }
8151   if (!Lower || !Upper || NewStep.isInvalid())
8152     return nullptr;
8153 
8154   ExprResult Diff;
8155   // If need to reorganize, then calculate the form as Upper - (Lower - Step [+
8156   // 1]).
8157   if (NeedToReorganize) {
8158     Diff = Lower;
8159 
8160     if (RoundToStep) {
8161       // Lower - Step
8162       Diff =
8163           SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Diff.get(), NewStep.get());
8164       if (!Diff.isUsable())
8165         return nullptr;
8166     }
8167 
8168     // Lower - Step [+ 1]
8169     if (TestIsStrictOp)
8170       Diff = SemaRef.BuildBinOp(
8171           S, DefaultLoc, BO_Add, Diff.get(),
8172           SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
8173     if (!Diff.isUsable())
8174       return nullptr;
8175 
8176     Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
8177     if (!Diff.isUsable())
8178       return nullptr;
8179 
8180     // Upper - (Lower - Step [+ 1]).
8181     Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Diff.get());
8182     if (!Diff.isUsable())
8183       return nullptr;
8184   } else {
8185     Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
8186 
8187     if (!Diff.isUsable() && LCTy->getAsCXXRecordDecl()) {
8188       // BuildBinOp already emitted error, this one is to point user to upper
8189       // and lower bound, and to tell what is passed to 'operator-'.
8190       SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
8191           << Upper->getSourceRange() << Lower->getSourceRange();
8192       return nullptr;
8193     }
8194 
8195     if (!Diff.isUsable())
8196       return nullptr;
8197 
8198     // Upper - Lower [- 1]
8199     if (TestIsStrictOp)
8200       Diff = SemaRef.BuildBinOp(
8201           S, DefaultLoc, BO_Sub, Diff.get(),
8202           SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
8203     if (!Diff.isUsable())
8204       return nullptr;
8205 
8206     if (RoundToStep) {
8207       // Upper - Lower [- 1] + Step
8208       Diff =
8209           SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
8210       if (!Diff.isUsable())
8211         return nullptr;
8212     }
8213   }
8214 
8215   // Parentheses (for dumping/debugging purposes only).
8216   Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
8217   if (!Diff.isUsable())
8218     return nullptr;
8219 
8220   // (Upper - Lower [- 1] + Step) / Step or (Upper - Lower) / Step
8221   Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
8222   if (!Diff.isUsable())
8223     return nullptr;
8224 
8225   return Diff.get();
8226 }
8227 
8228 /// Build the expression to calculate the number of iterations.
8229 Expr *OpenMPIterationSpaceChecker::buildNumIterations(
8230     Scope *S, ArrayRef<LoopIterationSpace> ResultIterSpaces, bool LimitedType,
8231     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
8232   QualType VarType = LCDecl->getType().getNonReferenceType();
8233   if (!VarType->isIntegerType() && !VarType->isPointerType() &&
8234       !SemaRef.getLangOpts().CPlusPlus)
8235     return nullptr;
8236   Expr *LBVal = LB;
8237   Expr *UBVal = UB;
8238   // LB = TestIsLessOp.getValue() ? min(LB(MinVal), LB(MaxVal)) :
8239   // max(LB(MinVal), LB(MaxVal))
8240   if (InitDependOnLC) {
8241     const LoopIterationSpace &IS = ResultIterSpaces[*InitDependOnLC - 1];
8242     if (!IS.MinValue || !IS.MaxValue)
8243       return nullptr;
8244     // OuterVar = Min
8245     ExprResult MinValue =
8246         SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MinValue);
8247     if (!MinValue.isUsable())
8248       return nullptr;
8249 
8250     ExprResult LBMinVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
8251                                              IS.CounterVar, MinValue.get());
8252     if (!LBMinVal.isUsable())
8253       return nullptr;
8254     // OuterVar = Min, LBVal
8255     LBMinVal =
8256         SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, LBMinVal.get(), LBVal);
8257     if (!LBMinVal.isUsable())
8258       return nullptr;
8259     // (OuterVar = Min, LBVal)
8260     LBMinVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, LBMinVal.get());
8261     if (!LBMinVal.isUsable())
8262       return nullptr;
8263 
8264     // OuterVar = Max
8265     ExprResult MaxValue =
8266         SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MaxValue);
8267     if (!MaxValue.isUsable())
8268       return nullptr;
8269 
8270     ExprResult LBMaxVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
8271                                              IS.CounterVar, MaxValue.get());
8272     if (!LBMaxVal.isUsable())
8273       return nullptr;
8274     // OuterVar = Max, LBVal
8275     LBMaxVal =
8276         SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, LBMaxVal.get(), LBVal);
8277     if (!LBMaxVal.isUsable())
8278       return nullptr;
8279     // (OuterVar = Max, LBVal)
8280     LBMaxVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, LBMaxVal.get());
8281     if (!LBMaxVal.isUsable())
8282       return nullptr;
8283 
8284     Expr *LBMin = tryBuildCapture(SemaRef, LBMinVal.get(), Captures).get();
8285     Expr *LBMax = tryBuildCapture(SemaRef, LBMaxVal.get(), Captures).get();
8286     if (!LBMin || !LBMax)
8287       return nullptr;
8288     // LB(MinVal) < LB(MaxVal)
8289     ExprResult MinLessMaxRes =
8290         SemaRef.BuildBinOp(S, DefaultLoc, BO_LT, LBMin, LBMax);
8291     if (!MinLessMaxRes.isUsable())
8292       return nullptr;
8293     Expr *MinLessMax =
8294         tryBuildCapture(SemaRef, MinLessMaxRes.get(), Captures).get();
8295     if (!MinLessMax)
8296       return nullptr;
8297     if (TestIsLessOp.getValue()) {
8298       // LB(MinVal) < LB(MaxVal) ? LB(MinVal) : LB(MaxVal) - min(LB(MinVal),
8299       // LB(MaxVal))
8300       ExprResult MinLB = SemaRef.ActOnConditionalOp(DefaultLoc, DefaultLoc,
8301                                                     MinLessMax, LBMin, LBMax);
8302       if (!MinLB.isUsable())
8303         return nullptr;
8304       LBVal = MinLB.get();
8305     } else {
8306       // LB(MinVal) < LB(MaxVal) ? LB(MaxVal) : LB(MinVal) - max(LB(MinVal),
8307       // LB(MaxVal))
8308       ExprResult MaxLB = SemaRef.ActOnConditionalOp(DefaultLoc, DefaultLoc,
8309                                                     MinLessMax, LBMax, LBMin);
8310       if (!MaxLB.isUsable())
8311         return nullptr;
8312       LBVal = MaxLB.get();
8313     }
8314   }
8315   // UB = TestIsLessOp.getValue() ? max(UB(MinVal), UB(MaxVal)) :
8316   // min(UB(MinVal), UB(MaxVal))
8317   if (CondDependOnLC) {
8318     const LoopIterationSpace &IS = ResultIterSpaces[*CondDependOnLC - 1];
8319     if (!IS.MinValue || !IS.MaxValue)
8320       return nullptr;
8321     // OuterVar = Min
8322     ExprResult MinValue =
8323         SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MinValue);
8324     if (!MinValue.isUsable())
8325       return nullptr;
8326 
8327     ExprResult UBMinVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
8328                                              IS.CounterVar, MinValue.get());
8329     if (!UBMinVal.isUsable())
8330       return nullptr;
8331     // OuterVar = Min, UBVal
8332     UBMinVal =
8333         SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, UBMinVal.get(), UBVal);
8334     if (!UBMinVal.isUsable())
8335       return nullptr;
8336     // (OuterVar = Min, UBVal)
8337     UBMinVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, UBMinVal.get());
8338     if (!UBMinVal.isUsable())
8339       return nullptr;
8340 
8341     // OuterVar = Max
8342     ExprResult MaxValue =
8343         SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MaxValue);
8344     if (!MaxValue.isUsable())
8345       return nullptr;
8346 
8347     ExprResult UBMaxVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
8348                                              IS.CounterVar, MaxValue.get());
8349     if (!UBMaxVal.isUsable())
8350       return nullptr;
8351     // OuterVar = Max, UBVal
8352     UBMaxVal =
8353         SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, UBMaxVal.get(), UBVal);
8354     if (!UBMaxVal.isUsable())
8355       return nullptr;
8356     // (OuterVar = Max, UBVal)
8357     UBMaxVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, UBMaxVal.get());
8358     if (!UBMaxVal.isUsable())
8359       return nullptr;
8360 
8361     Expr *UBMin = tryBuildCapture(SemaRef, UBMinVal.get(), Captures).get();
8362     Expr *UBMax = tryBuildCapture(SemaRef, UBMaxVal.get(), Captures).get();
8363     if (!UBMin || !UBMax)
8364       return nullptr;
8365     // UB(MinVal) > UB(MaxVal)
8366     ExprResult MinGreaterMaxRes =
8367         SemaRef.BuildBinOp(S, DefaultLoc, BO_GT, UBMin, UBMax);
8368     if (!MinGreaterMaxRes.isUsable())
8369       return nullptr;
8370     Expr *MinGreaterMax =
8371         tryBuildCapture(SemaRef, MinGreaterMaxRes.get(), Captures).get();
8372     if (!MinGreaterMax)
8373       return nullptr;
8374     if (TestIsLessOp.getValue()) {
8375       // UB(MinVal) > UB(MaxVal) ? UB(MinVal) : UB(MaxVal) - max(UB(MinVal),
8376       // UB(MaxVal))
8377       ExprResult MaxUB = SemaRef.ActOnConditionalOp(
8378           DefaultLoc, DefaultLoc, MinGreaterMax, UBMin, UBMax);
8379       if (!MaxUB.isUsable())
8380         return nullptr;
8381       UBVal = MaxUB.get();
8382     } else {
8383       // UB(MinVal) > UB(MaxVal) ? UB(MaxVal) : UB(MinVal) - min(UB(MinVal),
8384       // UB(MaxVal))
8385       ExprResult MinUB = SemaRef.ActOnConditionalOp(
8386           DefaultLoc, DefaultLoc, MinGreaterMax, UBMax, UBMin);
8387       if (!MinUB.isUsable())
8388         return nullptr;
8389       UBVal = MinUB.get();
8390     }
8391   }
8392   Expr *UBExpr = TestIsLessOp.getValue() ? UBVal : LBVal;
8393   Expr *LBExpr = TestIsLessOp.getValue() ? LBVal : UBVal;
8394   Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
8395   Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
8396   if (!Upper || !Lower)
8397     return nullptr;
8398 
8399   ExprResult Diff = calculateNumIters(SemaRef, S, DefaultLoc, Lower, Upper,
8400                                       Step, VarType, TestIsStrictOp,
8401                                       /*RoundToStep=*/true, Captures);
8402   if (!Diff.isUsable())
8403     return nullptr;
8404 
8405   // OpenMP runtime requires 32-bit or 64-bit loop variables.
8406   QualType Type = Diff.get()->getType();
8407   ASTContext &C = SemaRef.Context;
8408   bool UseVarType = VarType->hasIntegerRepresentation() &&
8409                     C.getTypeSize(Type) > C.getTypeSize(VarType);
8410   if (!Type->isIntegerType() || UseVarType) {
8411     unsigned NewSize =
8412         UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
8413     bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
8414                                : Type->hasSignedIntegerRepresentation();
8415     Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
8416     if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
8417       Diff = SemaRef.PerformImplicitConversion(
8418           Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
8419       if (!Diff.isUsable())
8420         return nullptr;
8421     }
8422   }
8423   if (LimitedType) {
8424     unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
8425     if (NewSize != C.getTypeSize(Type)) {
8426       if (NewSize < C.getTypeSize(Type)) {
8427         assert(NewSize == 64 && "incorrect loop var size");
8428         SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
8429             << InitSrcRange << ConditionSrcRange;
8430       }
8431       QualType NewType = C.getIntTypeForBitwidth(
8432           NewSize, Type->hasSignedIntegerRepresentation() ||
8433                        C.getTypeSize(Type) < NewSize);
8434       if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
8435         Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
8436                                                  Sema::AA_Converting, true);
8437         if (!Diff.isUsable())
8438           return nullptr;
8439       }
8440     }
8441   }
8442 
8443   return Diff.get();
8444 }
8445 
8446 std::pair<Expr *, Expr *> OpenMPIterationSpaceChecker::buildMinMaxValues(
8447     Scope *S, llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
8448   // Do not build for iterators, they cannot be used in non-rectangular loop
8449   // nests.
8450   if (LCDecl->getType()->isRecordType())
8451     return std::make_pair(nullptr, nullptr);
8452   // If we subtract, the min is in the condition, otherwise the min is in the
8453   // init value.
8454   Expr *MinExpr = nullptr;
8455   Expr *MaxExpr = nullptr;
8456   Expr *LBExpr = TestIsLessOp.getValue() ? LB : UB;
8457   Expr *UBExpr = TestIsLessOp.getValue() ? UB : LB;
8458   bool LBNonRect = TestIsLessOp.getValue() ? InitDependOnLC.hasValue()
8459                                            : CondDependOnLC.hasValue();
8460   bool UBNonRect = TestIsLessOp.getValue() ? CondDependOnLC.hasValue()
8461                                            : InitDependOnLC.hasValue();
8462   Expr *Lower =
8463       LBNonRect ? LBExpr : tryBuildCapture(SemaRef, LBExpr, Captures).get();
8464   Expr *Upper =
8465       UBNonRect ? UBExpr : tryBuildCapture(SemaRef, UBExpr, Captures).get();
8466   if (!Upper || !Lower)
8467     return std::make_pair(nullptr, nullptr);
8468 
8469   if (TestIsLessOp.getValue())
8470     MinExpr = Lower;
8471   else
8472     MaxExpr = Upper;
8473 
8474   // Build minimum/maximum value based on number of iterations.
8475   QualType VarType = LCDecl->getType().getNonReferenceType();
8476 
8477   ExprResult Diff = calculateNumIters(SemaRef, S, DefaultLoc, Lower, Upper,
8478                                       Step, VarType, TestIsStrictOp,
8479                                       /*RoundToStep=*/false, Captures);
8480   if (!Diff.isUsable())
8481     return std::make_pair(nullptr, nullptr);
8482 
8483   // ((Upper - Lower [- 1]) / Step) * Step
8484   // Parentheses (for dumping/debugging purposes only).
8485   Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
8486   if (!Diff.isUsable())
8487     return std::make_pair(nullptr, nullptr);
8488 
8489   ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
8490   if (!NewStep.isUsable())
8491     return std::make_pair(nullptr, nullptr);
8492   Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Mul, Diff.get(), NewStep.get());
8493   if (!Diff.isUsable())
8494     return std::make_pair(nullptr, nullptr);
8495 
8496   // Parentheses (for dumping/debugging purposes only).
8497   Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
8498   if (!Diff.isUsable())
8499     return std::make_pair(nullptr, nullptr);
8500 
8501   // Convert to the ptrdiff_t, if original type is pointer.
8502   if (VarType->isAnyPointerType() &&
8503       !SemaRef.Context.hasSameType(
8504           Diff.get()->getType(),
8505           SemaRef.Context.getUnsignedPointerDiffType())) {
8506     Diff = SemaRef.PerformImplicitConversion(
8507         Diff.get(), SemaRef.Context.getUnsignedPointerDiffType(),
8508         Sema::AA_Converting, /*AllowExplicit=*/true);
8509   }
8510   if (!Diff.isUsable())
8511     return std::make_pair(nullptr, nullptr);
8512 
8513   if (TestIsLessOp.getValue()) {
8514     // MinExpr = Lower;
8515     // MaxExpr = Lower + (((Upper - Lower [- 1]) / Step) * Step)
8516     Diff = SemaRef.BuildBinOp(
8517         S, DefaultLoc, BO_Add,
8518         SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Lower).get(),
8519         Diff.get());
8520     if (!Diff.isUsable())
8521       return std::make_pair(nullptr, nullptr);
8522   } else {
8523     // MaxExpr = Upper;
8524     // MinExpr = Upper - (((Upper - Lower [- 1]) / Step) * Step)
8525     Diff = SemaRef.BuildBinOp(
8526         S, DefaultLoc, BO_Sub,
8527         SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Upper).get(),
8528         Diff.get());
8529     if (!Diff.isUsable())
8530       return std::make_pair(nullptr, nullptr);
8531   }
8532 
8533   // Convert to the original type.
8534   if (SemaRef.Context.hasSameType(Diff.get()->getType(), VarType))
8535     Diff = SemaRef.PerformImplicitConversion(Diff.get(), VarType,
8536                                              Sema::AA_Converting,
8537                                              /*AllowExplicit=*/true);
8538   if (!Diff.isUsable())
8539     return std::make_pair(nullptr, nullptr);
8540 
8541   Sema::TentativeAnalysisScope Trap(SemaRef);
8542   Diff = SemaRef.ActOnFinishFullExpr(Diff.get(), /*DiscardedValue=*/false);
8543   if (!Diff.isUsable())
8544     return std::make_pair(nullptr, nullptr);
8545 
8546   if (TestIsLessOp.getValue())
8547     MaxExpr = Diff.get();
8548   else
8549     MinExpr = Diff.get();
8550 
8551   return std::make_pair(MinExpr, MaxExpr);
8552 }
8553 
8554 Expr *OpenMPIterationSpaceChecker::buildFinalCondition(Scope *S) const {
8555   if (InitDependOnLC || CondDependOnLC)
8556     return Condition;
8557   return nullptr;
8558 }
8559 
8560 Expr *OpenMPIterationSpaceChecker::buildPreCond(
8561     Scope *S, Expr *Cond,
8562     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
8563   // Do not build a precondition when the condition/initialization is dependent
8564   // to prevent pessimistic early loop exit.
8565   // TODO: this can be improved by calculating min/max values but not sure that
8566   // it will be very effective.
8567   if (CondDependOnLC || InitDependOnLC)
8568     return SemaRef
8569         .PerformImplicitConversion(
8570             SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get(),
8571             SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
8572             /*AllowExplicit=*/true)
8573         .get();
8574 
8575   // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
8576   Sema::TentativeAnalysisScope Trap(SemaRef);
8577 
8578   ExprResult NewLB = tryBuildCapture(SemaRef, LB, Captures);
8579   ExprResult NewUB = tryBuildCapture(SemaRef, UB, Captures);
8580   if (!NewLB.isUsable() || !NewUB.isUsable())
8581     return nullptr;
8582 
8583   ExprResult CondExpr = SemaRef.BuildBinOp(
8584       S, DefaultLoc,
8585       TestIsLessOp.getValue() ? (TestIsStrictOp ? BO_LT : BO_LE)
8586                               : (TestIsStrictOp ? BO_GT : BO_GE),
8587       NewLB.get(), NewUB.get());
8588   if (CondExpr.isUsable()) {
8589     if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
8590                                                 SemaRef.Context.BoolTy))
8591       CondExpr = SemaRef.PerformImplicitConversion(
8592           CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
8593           /*AllowExplicit=*/true);
8594   }
8595 
8596   // Otherwise use original loop condition and evaluate it in runtime.
8597   return CondExpr.isUsable() ? CondExpr.get() : Cond;
8598 }
8599 
8600 /// Build reference expression to the counter be used for codegen.
8601 DeclRefExpr *OpenMPIterationSpaceChecker::buildCounterVar(
8602     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
8603     DSAStackTy &DSA) const {
8604   auto *VD = dyn_cast<VarDecl>(LCDecl);
8605   if (!VD) {
8606     VD = SemaRef.isOpenMPCapturedDecl(LCDecl);
8607     DeclRefExpr *Ref = buildDeclRefExpr(
8608         SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
8609     const DSAStackTy::DSAVarData Data =
8610         DSA.getTopDSA(LCDecl, /*FromParent=*/false);
8611     // If the loop control decl is explicitly marked as private, do not mark it
8612     // as captured again.
8613     if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
8614       Captures.insert(std::make_pair(LCRef, Ref));
8615     return Ref;
8616   }
8617   return cast<DeclRefExpr>(LCRef);
8618 }
8619 
8620 Expr *OpenMPIterationSpaceChecker::buildPrivateCounterVar() const {
8621   if (LCDecl && !LCDecl->isInvalidDecl()) {
8622     QualType Type = LCDecl->getType().getNonReferenceType();
8623     VarDecl *PrivateVar = buildVarDecl(
8624         SemaRef, DefaultLoc, Type, LCDecl->getName(),
8625         LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr,
8626         isa<VarDecl>(LCDecl)
8627             ? buildDeclRefExpr(SemaRef, cast<VarDecl>(LCDecl), Type, DefaultLoc)
8628             : nullptr);
8629     if (PrivateVar->isInvalidDecl())
8630       return nullptr;
8631     return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
8632   }
8633   return nullptr;
8634 }
8635 
8636 /// Build initialization of the counter to be used for codegen.
8637 Expr *OpenMPIterationSpaceChecker::buildCounterInit() const { return LB; }
8638 
8639 /// Build step of the counter be used for codegen.
8640 Expr *OpenMPIterationSpaceChecker::buildCounterStep() const { return Step; }
8641 
8642 Expr *OpenMPIterationSpaceChecker::buildOrderedLoopData(
8643     Scope *S, Expr *Counter,
8644     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, SourceLocation Loc,
8645     Expr *Inc, OverloadedOperatorKind OOK) {
8646   Expr *Cnt = SemaRef.DefaultLvalueConversion(Counter).get();
8647   if (!Cnt)
8648     return nullptr;
8649   if (Inc) {
8650     assert((OOK == OO_Plus || OOK == OO_Minus) &&
8651            "Expected only + or - operations for depend clauses.");
8652     BinaryOperatorKind BOK = (OOK == OO_Plus) ? BO_Add : BO_Sub;
8653     Cnt = SemaRef.BuildBinOp(S, Loc, BOK, Cnt, Inc).get();
8654     if (!Cnt)
8655       return nullptr;
8656   }
8657   QualType VarType = LCDecl->getType().getNonReferenceType();
8658   if (!VarType->isIntegerType() && !VarType->isPointerType() &&
8659       !SemaRef.getLangOpts().CPlusPlus)
8660     return nullptr;
8661   // Upper - Lower
8662   Expr *Upper = TestIsLessOp.getValue()
8663                     ? Cnt
8664                     : tryBuildCapture(SemaRef, LB, Captures).get();
8665   Expr *Lower = TestIsLessOp.getValue()
8666                     ? tryBuildCapture(SemaRef, LB, Captures).get()
8667                     : Cnt;
8668   if (!Upper || !Lower)
8669     return nullptr;
8670 
8671   ExprResult Diff = calculateNumIters(
8672       SemaRef, S, DefaultLoc, Lower, Upper, Step, VarType,
8673       /*TestIsStrictOp=*/false, /*RoundToStep=*/false, Captures);
8674   if (!Diff.isUsable())
8675     return nullptr;
8676 
8677   return Diff.get();
8678 }
8679 } // namespace
8680 
8681 void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
8682   assert(getLangOpts().OpenMP && "OpenMP is not active.");
8683   assert(Init && "Expected loop in canonical form.");
8684   unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
8685   if (AssociatedLoops > 0 &&
8686       isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
8687     DSAStack->loopStart();
8688     OpenMPIterationSpaceChecker ISC(*this, /*SupportsNonRectangular=*/true,
8689                                     *DSAStack, ForLoc);
8690     if (!ISC.checkAndSetInit(Init, /*EmitDiags=*/false)) {
8691       if (ValueDecl *D = ISC.getLoopDecl()) {
8692         auto *VD = dyn_cast<VarDecl>(D);
8693         DeclRefExpr *PrivateRef = nullptr;
8694         if (!VD) {
8695           if (VarDecl *Private = isOpenMPCapturedDecl(D)) {
8696             VD = Private;
8697           } else {
8698             PrivateRef = buildCapture(*this, D, ISC.getLoopDeclRefExpr(),
8699                                       /*WithInit=*/false);
8700             VD = cast<VarDecl>(PrivateRef->getDecl());
8701           }
8702         }
8703         DSAStack->addLoopControlVariable(D, VD);
8704         const Decl *LD = DSAStack->getPossiblyLoopCunter();
8705         if (LD != D->getCanonicalDecl()) {
8706           DSAStack->resetPossibleLoopCounter();
8707           if (auto *Var = dyn_cast_or_null<VarDecl>(LD))
8708             MarkDeclarationsReferencedInExpr(
8709                 buildDeclRefExpr(*this, const_cast<VarDecl *>(Var),
8710                                  Var->getType().getNonLValueExprType(Context),
8711                                  ForLoc, /*RefersToCapture=*/true));
8712         }
8713         OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
8714         // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables
8715         // Referenced in a Construct, C/C++]. The loop iteration variable in the
8716         // associated for-loop of a simd construct with just one associated
8717         // for-loop may be listed in a linear clause with a constant-linear-step
8718         // that is the increment of the associated for-loop. The loop iteration
8719         // variable(s) in the associated for-loop(s) of a for or parallel for
8720         // construct may be listed in a private or lastprivate clause.
8721         DSAStackTy::DSAVarData DVar =
8722             DSAStack->getTopDSA(D, /*FromParent=*/false);
8723         // If LoopVarRefExpr is nullptr it means the corresponding loop variable
8724         // is declared in the loop and it is predetermined as a private.
8725         Expr *LoopDeclRefExpr = ISC.getLoopDeclRefExpr();
8726         OpenMPClauseKind PredeterminedCKind =
8727             isOpenMPSimdDirective(DKind)
8728                 ? (DSAStack->hasMutipleLoops() ? OMPC_lastprivate : OMPC_linear)
8729                 : OMPC_private;
8730         if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
8731               DVar.CKind != PredeterminedCKind && DVar.RefExpr &&
8732               (LangOpts.OpenMP <= 45 || (DVar.CKind != OMPC_lastprivate &&
8733                                          DVar.CKind != OMPC_private))) ||
8734              ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
8735                DKind == OMPD_master_taskloop ||
8736                DKind == OMPD_parallel_master_taskloop ||
8737                isOpenMPDistributeDirective(DKind)) &&
8738               !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
8739               DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
8740             (DVar.CKind != OMPC_private || DVar.RefExpr)) {
8741           Diag(Init->getBeginLoc(), diag::err_omp_loop_var_dsa)
8742               << getOpenMPClauseName(DVar.CKind)
8743               << getOpenMPDirectiveName(DKind)
8744               << getOpenMPClauseName(PredeterminedCKind);
8745           if (DVar.RefExpr == nullptr)
8746             DVar.CKind = PredeterminedCKind;
8747           reportOriginalDsa(*this, DSAStack, D, DVar,
8748                             /*IsLoopIterVar=*/true);
8749         } else if (LoopDeclRefExpr) {
8750           // Make the loop iteration variable private (for worksharing
8751           // constructs), linear (for simd directives with the only one
8752           // associated loop) or lastprivate (for simd directives with several
8753           // collapsed or ordered loops).
8754           if (DVar.CKind == OMPC_unknown)
8755             DSAStack->addDSA(D, LoopDeclRefExpr, PredeterminedCKind,
8756                              PrivateRef);
8757         }
8758       }
8759     }
8760     DSAStack->setAssociatedLoops(AssociatedLoops - 1);
8761   }
8762 }
8763 
8764 /// Called on a for stmt to check and extract its iteration space
8765 /// for further processing (such as collapsing).
8766 static bool checkOpenMPIterationSpace(
8767     OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
8768     unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
8769     unsigned TotalNestedLoopCount, Expr *CollapseLoopCountExpr,
8770     Expr *OrderedLoopCountExpr,
8771     Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
8772     llvm::MutableArrayRef<LoopIterationSpace> ResultIterSpaces,
8773     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
8774   bool SupportsNonRectangular = !isOpenMPLoopTransformationDirective(DKind);
8775   // OpenMP [2.9.1, Canonical Loop Form]
8776   //   for (init-expr; test-expr; incr-expr) structured-block
8777   //   for (range-decl: range-expr) structured-block
8778   if (auto *CanonLoop = dyn_cast_or_null<OMPCanonicalLoop>(S))
8779     S = CanonLoop->getLoopStmt();
8780   auto *For = dyn_cast_or_null<ForStmt>(S);
8781   auto *CXXFor = dyn_cast_or_null<CXXForRangeStmt>(S);
8782   // Ranged for is supported only in OpenMP 5.0.
8783   if (!For && (SemaRef.LangOpts.OpenMP <= 45 || !CXXFor)) {
8784     SemaRef.Diag(S->getBeginLoc(), diag::err_omp_not_for)
8785         << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
8786         << getOpenMPDirectiveName(DKind) << TotalNestedLoopCount
8787         << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
8788     if (TotalNestedLoopCount > 1) {
8789       if (CollapseLoopCountExpr && OrderedLoopCountExpr)
8790         SemaRef.Diag(DSA.getConstructLoc(),
8791                      diag::note_omp_collapse_ordered_expr)
8792             << 2 << CollapseLoopCountExpr->getSourceRange()
8793             << OrderedLoopCountExpr->getSourceRange();
8794       else if (CollapseLoopCountExpr)
8795         SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
8796                      diag::note_omp_collapse_ordered_expr)
8797             << 0 << CollapseLoopCountExpr->getSourceRange();
8798       else
8799         SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
8800                      diag::note_omp_collapse_ordered_expr)
8801             << 1 << OrderedLoopCountExpr->getSourceRange();
8802     }
8803     return true;
8804   }
8805   assert(((For && For->getBody()) || (CXXFor && CXXFor->getBody())) &&
8806          "No loop body.");
8807   // Postpone analysis in dependent contexts for ranged for loops.
8808   if (CXXFor && SemaRef.CurContext->isDependentContext())
8809     return false;
8810 
8811   OpenMPIterationSpaceChecker ISC(SemaRef, SupportsNonRectangular, DSA,
8812                                   For ? For->getForLoc() : CXXFor->getForLoc());
8813 
8814   // Check init.
8815   Stmt *Init = For ? For->getInit() : CXXFor->getBeginStmt();
8816   if (ISC.checkAndSetInit(Init))
8817     return true;
8818 
8819   bool HasErrors = false;
8820 
8821   // Check loop variable's type.
8822   if (ValueDecl *LCDecl = ISC.getLoopDecl()) {
8823     // OpenMP [2.6, Canonical Loop Form]
8824     // Var is one of the following:
8825     //   A variable of signed or unsigned integer type.
8826     //   For C++, a variable of a random access iterator type.
8827     //   For C, a variable of a pointer type.
8828     QualType VarType = LCDecl->getType().getNonReferenceType();
8829     if (!VarType->isDependentType() && !VarType->isIntegerType() &&
8830         !VarType->isPointerType() &&
8831         !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
8832       SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_variable_type)
8833           << SemaRef.getLangOpts().CPlusPlus;
8834       HasErrors = true;
8835     }
8836 
8837     // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
8838     // a Construct
8839     // The loop iteration variable(s) in the associated for-loop(s) of a for or
8840     // parallel for construct is (are) private.
8841     // The loop iteration variable in the associated for-loop of a simd
8842     // construct with just one associated for-loop is linear with a
8843     // constant-linear-step that is the increment of the associated for-loop.
8844     // Exclude loop var from the list of variables with implicitly defined data
8845     // sharing attributes.
8846     VarsWithImplicitDSA.erase(LCDecl);
8847 
8848     assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
8849 
8850     // Check test-expr.
8851     HasErrors |= ISC.checkAndSetCond(For ? For->getCond() : CXXFor->getCond());
8852 
8853     // Check incr-expr.
8854     HasErrors |= ISC.checkAndSetInc(For ? For->getInc() : CXXFor->getInc());
8855   }
8856 
8857   if (ISC.dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
8858     return HasErrors;
8859 
8860   // Build the loop's iteration space representation.
8861   ResultIterSpaces[CurrentNestedLoopCount].PreCond = ISC.buildPreCond(
8862       DSA.getCurScope(), For ? For->getCond() : CXXFor->getCond(), Captures);
8863   ResultIterSpaces[CurrentNestedLoopCount].NumIterations =
8864       ISC.buildNumIterations(DSA.getCurScope(), ResultIterSpaces,
8865                              (isOpenMPWorksharingDirective(DKind) ||
8866                               isOpenMPGenericLoopDirective(DKind) ||
8867                               isOpenMPTaskLoopDirective(DKind) ||
8868                               isOpenMPDistributeDirective(DKind) ||
8869                               isOpenMPLoopTransformationDirective(DKind)),
8870                              Captures);
8871   ResultIterSpaces[CurrentNestedLoopCount].CounterVar =
8872       ISC.buildCounterVar(Captures, DSA);
8873   ResultIterSpaces[CurrentNestedLoopCount].PrivateCounterVar =
8874       ISC.buildPrivateCounterVar();
8875   ResultIterSpaces[CurrentNestedLoopCount].CounterInit = ISC.buildCounterInit();
8876   ResultIterSpaces[CurrentNestedLoopCount].CounterStep = ISC.buildCounterStep();
8877   ResultIterSpaces[CurrentNestedLoopCount].InitSrcRange = ISC.getInitSrcRange();
8878   ResultIterSpaces[CurrentNestedLoopCount].CondSrcRange =
8879       ISC.getConditionSrcRange();
8880   ResultIterSpaces[CurrentNestedLoopCount].IncSrcRange =
8881       ISC.getIncrementSrcRange();
8882   ResultIterSpaces[CurrentNestedLoopCount].Subtract = ISC.shouldSubtractStep();
8883   ResultIterSpaces[CurrentNestedLoopCount].IsStrictCompare =
8884       ISC.isStrictTestOp();
8885   std::tie(ResultIterSpaces[CurrentNestedLoopCount].MinValue,
8886            ResultIterSpaces[CurrentNestedLoopCount].MaxValue) =
8887       ISC.buildMinMaxValues(DSA.getCurScope(), Captures);
8888   ResultIterSpaces[CurrentNestedLoopCount].FinalCondition =
8889       ISC.buildFinalCondition(DSA.getCurScope());
8890   ResultIterSpaces[CurrentNestedLoopCount].IsNonRectangularLB =
8891       ISC.doesInitDependOnLC();
8892   ResultIterSpaces[CurrentNestedLoopCount].IsNonRectangularUB =
8893       ISC.doesCondDependOnLC();
8894   ResultIterSpaces[CurrentNestedLoopCount].LoopDependentIdx =
8895       ISC.getLoopDependentIdx();
8896 
8897   HasErrors |=
8898       (ResultIterSpaces[CurrentNestedLoopCount].PreCond == nullptr ||
8899        ResultIterSpaces[CurrentNestedLoopCount].NumIterations == nullptr ||
8900        ResultIterSpaces[CurrentNestedLoopCount].CounterVar == nullptr ||
8901        ResultIterSpaces[CurrentNestedLoopCount].PrivateCounterVar == nullptr ||
8902        ResultIterSpaces[CurrentNestedLoopCount].CounterInit == nullptr ||
8903        ResultIterSpaces[CurrentNestedLoopCount].CounterStep == nullptr);
8904   if (!HasErrors && DSA.isOrderedRegion()) {
8905     if (DSA.getOrderedRegionParam().second->getNumForLoops()) {
8906       if (CurrentNestedLoopCount <
8907           DSA.getOrderedRegionParam().second->getLoopNumIterations().size()) {
8908         DSA.getOrderedRegionParam().second->setLoopNumIterations(
8909             CurrentNestedLoopCount,
8910             ResultIterSpaces[CurrentNestedLoopCount].NumIterations);
8911         DSA.getOrderedRegionParam().second->setLoopCounter(
8912             CurrentNestedLoopCount,
8913             ResultIterSpaces[CurrentNestedLoopCount].CounterVar);
8914       }
8915     }
8916     for (auto &Pair : DSA.getDoacrossDependClauses()) {
8917       if (CurrentNestedLoopCount >= Pair.first->getNumLoops()) {
8918         // Erroneous case - clause has some problems.
8919         continue;
8920       }
8921       if (Pair.first->getDependencyKind() == OMPC_DEPEND_sink &&
8922           Pair.second.size() <= CurrentNestedLoopCount) {
8923         // Erroneous case - clause has some problems.
8924         Pair.first->setLoopData(CurrentNestedLoopCount, nullptr);
8925         continue;
8926       }
8927       Expr *CntValue;
8928       if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
8929         CntValue = ISC.buildOrderedLoopData(
8930             DSA.getCurScope(),
8931             ResultIterSpaces[CurrentNestedLoopCount].CounterVar, Captures,
8932             Pair.first->getDependencyLoc());
8933       else
8934         CntValue = ISC.buildOrderedLoopData(
8935             DSA.getCurScope(),
8936             ResultIterSpaces[CurrentNestedLoopCount].CounterVar, Captures,
8937             Pair.first->getDependencyLoc(),
8938             Pair.second[CurrentNestedLoopCount].first,
8939             Pair.second[CurrentNestedLoopCount].second);
8940       Pair.first->setLoopData(CurrentNestedLoopCount, CntValue);
8941     }
8942   }
8943 
8944   return HasErrors;
8945 }
8946 
8947 /// Build 'VarRef = Start.
8948 static ExprResult
8949 buildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
8950                  ExprResult Start, bool IsNonRectangularLB,
8951                  llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
8952   // Build 'VarRef = Start.
8953   ExprResult NewStart = IsNonRectangularLB
8954                             ? Start.get()
8955                             : tryBuildCapture(SemaRef, Start.get(), Captures);
8956   if (!NewStart.isUsable())
8957     return ExprError();
8958   if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
8959                                    VarRef.get()->getType())) {
8960     NewStart = SemaRef.PerformImplicitConversion(
8961         NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
8962         /*AllowExplicit=*/true);
8963     if (!NewStart.isUsable())
8964       return ExprError();
8965   }
8966 
8967   ExprResult Init =
8968       SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
8969   return Init;
8970 }
8971 
8972 /// Build 'VarRef = Start + Iter * Step'.
8973 static ExprResult buildCounterUpdate(
8974     Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
8975     ExprResult Start, ExprResult Iter, ExprResult Step, bool Subtract,
8976     bool IsNonRectangularLB,
8977     llvm::MapVector<const Expr *, DeclRefExpr *> *Captures = nullptr) {
8978   // Add parentheses (for debugging purposes only).
8979   Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
8980   if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
8981       !Step.isUsable())
8982     return ExprError();
8983 
8984   ExprResult NewStep = Step;
8985   if (Captures)
8986     NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
8987   if (NewStep.isInvalid())
8988     return ExprError();
8989   ExprResult Update =
8990       SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
8991   if (!Update.isUsable())
8992     return ExprError();
8993 
8994   // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
8995   // 'VarRef = Start (+|-) Iter * Step'.
8996   if (!Start.isUsable())
8997     return ExprError();
8998   ExprResult NewStart = SemaRef.ActOnParenExpr(Loc, Loc, Start.get());
8999   if (!NewStart.isUsable())
9000     return ExprError();
9001   if (Captures && !IsNonRectangularLB)
9002     NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
9003   if (NewStart.isInvalid())
9004     return ExprError();
9005 
9006   // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
9007   ExprResult SavedUpdate = Update;
9008   ExprResult UpdateVal;
9009   if (VarRef.get()->getType()->isOverloadableType() ||
9010       NewStart.get()->getType()->isOverloadableType() ||
9011       Update.get()->getType()->isOverloadableType()) {
9012     Sema::TentativeAnalysisScope Trap(SemaRef);
9013 
9014     Update =
9015         SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
9016     if (Update.isUsable()) {
9017       UpdateVal =
9018           SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
9019                              VarRef.get(), SavedUpdate.get());
9020       if (UpdateVal.isUsable()) {
9021         Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
9022                                             UpdateVal.get());
9023       }
9024     }
9025   }
9026 
9027   // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
9028   if (!Update.isUsable() || !UpdateVal.isUsable()) {
9029     Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
9030                                 NewStart.get(), SavedUpdate.get());
9031     if (!Update.isUsable())
9032       return ExprError();
9033 
9034     if (!SemaRef.Context.hasSameType(Update.get()->getType(),
9035                                      VarRef.get()->getType())) {
9036       Update = SemaRef.PerformImplicitConversion(
9037           Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
9038       if (!Update.isUsable())
9039         return ExprError();
9040     }
9041 
9042     Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
9043   }
9044   return Update;
9045 }
9046 
9047 /// Convert integer expression \a E to make it have at least \a Bits
9048 /// bits.
9049 static ExprResult widenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
9050   if (E == nullptr)
9051     return ExprError();
9052   ASTContext &C = SemaRef.Context;
9053   QualType OldType = E->getType();
9054   unsigned HasBits = C.getTypeSize(OldType);
9055   if (HasBits >= Bits)
9056     return ExprResult(E);
9057   // OK to convert to signed, because new type has more bits than old.
9058   QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
9059   return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
9060                                            true);
9061 }
9062 
9063 /// Check if the given expression \a E is a constant integer that fits
9064 /// into \a Bits bits.
9065 static bool fitsInto(unsigned Bits, bool Signed, const Expr *E, Sema &SemaRef) {
9066   if (E == nullptr)
9067     return false;
9068   if (Optional<llvm::APSInt> Result =
9069           E->getIntegerConstantExpr(SemaRef.Context))
9070     return Signed ? Result->isSignedIntN(Bits) : Result->isIntN(Bits);
9071   return false;
9072 }
9073 
9074 /// Build preinits statement for the given declarations.
9075 static Stmt *buildPreInits(ASTContext &Context,
9076                            MutableArrayRef<Decl *> PreInits) {
9077   if (!PreInits.empty()) {
9078     return new (Context) DeclStmt(
9079         DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
9080         SourceLocation(), SourceLocation());
9081   }
9082   return nullptr;
9083 }
9084 
9085 /// Build preinits statement for the given declarations.
9086 static Stmt *
9087 buildPreInits(ASTContext &Context,
9088               const llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
9089   if (!Captures.empty()) {
9090     SmallVector<Decl *, 16> PreInits;
9091     for (const auto &Pair : Captures)
9092       PreInits.push_back(Pair.second->getDecl());
9093     return buildPreInits(Context, PreInits);
9094   }
9095   return nullptr;
9096 }
9097 
9098 /// Build postupdate expression for the given list of postupdates expressions.
9099 static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
9100   Expr *PostUpdate = nullptr;
9101   if (!PostUpdates.empty()) {
9102     for (Expr *E : PostUpdates) {
9103       Expr *ConvE = S.BuildCStyleCastExpr(
9104                          E->getExprLoc(),
9105                          S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
9106                          E->getExprLoc(), E)
9107                         .get();
9108       PostUpdate = PostUpdate
9109                        ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
9110                                               PostUpdate, ConvE)
9111                              .get()
9112                        : ConvE;
9113     }
9114   }
9115   return PostUpdate;
9116 }
9117 
9118 /// Called on a for stmt to check itself and nested loops (if any).
9119 /// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
9120 /// number of collapsed loops otherwise.
9121 static unsigned
9122 checkOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
9123                 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
9124                 DSAStackTy &DSA,
9125                 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
9126                 OMPLoopBasedDirective::HelperExprs &Built) {
9127   unsigned NestedLoopCount = 1;
9128   bool SupportsNonPerfectlyNested = (SemaRef.LangOpts.OpenMP >= 50) &&
9129                                     !isOpenMPLoopTransformationDirective(DKind);
9130 
9131   if (CollapseLoopCountExpr) {
9132     // Found 'collapse' clause - calculate collapse number.
9133     Expr::EvalResult Result;
9134     if (!CollapseLoopCountExpr->isValueDependent() &&
9135         CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
9136       NestedLoopCount = Result.Val.getInt().getLimitedValue();
9137     } else {
9138       Built.clear(/*Size=*/1);
9139       return 1;
9140     }
9141   }
9142   unsigned OrderedLoopCount = 1;
9143   if (OrderedLoopCountExpr) {
9144     // Found 'ordered' clause - calculate collapse number.
9145     Expr::EvalResult EVResult;
9146     if (!OrderedLoopCountExpr->isValueDependent() &&
9147         OrderedLoopCountExpr->EvaluateAsInt(EVResult,
9148                                             SemaRef.getASTContext())) {
9149       llvm::APSInt Result = EVResult.Val.getInt();
9150       if (Result.getLimitedValue() < NestedLoopCount) {
9151         SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
9152                      diag::err_omp_wrong_ordered_loop_count)
9153             << OrderedLoopCountExpr->getSourceRange();
9154         SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
9155                      diag::note_collapse_loop_count)
9156             << CollapseLoopCountExpr->getSourceRange();
9157       }
9158       OrderedLoopCount = Result.getLimitedValue();
9159     } else {
9160       Built.clear(/*Size=*/1);
9161       return 1;
9162     }
9163   }
9164   // This is helper routine for loop directives (e.g., 'for', 'simd',
9165   // 'for simd', etc.).
9166   llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
9167   unsigned NumLoops = std::max(OrderedLoopCount, NestedLoopCount);
9168   SmallVector<LoopIterationSpace, 4> IterSpaces(NumLoops);
9169   if (!OMPLoopBasedDirective::doForAllLoops(
9170           AStmt->IgnoreContainers(!isOpenMPLoopTransformationDirective(DKind)),
9171           SupportsNonPerfectlyNested, NumLoops,
9172           [DKind, &SemaRef, &DSA, NumLoops, NestedLoopCount,
9173            CollapseLoopCountExpr, OrderedLoopCountExpr, &VarsWithImplicitDSA,
9174            &IterSpaces, &Captures](unsigned Cnt, Stmt *CurStmt) {
9175             if (checkOpenMPIterationSpace(
9176                     DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
9177                     NumLoops, CollapseLoopCountExpr, OrderedLoopCountExpr,
9178                     VarsWithImplicitDSA, IterSpaces, Captures))
9179               return true;
9180             if (Cnt > 0 && Cnt >= NestedLoopCount &&
9181                 IterSpaces[Cnt].CounterVar) {
9182               // Handle initialization of captured loop iterator variables.
9183               auto *DRE = cast<DeclRefExpr>(IterSpaces[Cnt].CounterVar);
9184               if (isa<OMPCapturedExprDecl>(DRE->getDecl())) {
9185                 Captures[DRE] = DRE;
9186               }
9187             }
9188             return false;
9189           },
9190           [&SemaRef, &Captures](OMPLoopTransformationDirective *Transform) {
9191             Stmt *DependentPreInits = Transform->getPreInits();
9192             if (!DependentPreInits)
9193               return;
9194             for (Decl *C : cast<DeclStmt>(DependentPreInits)->getDeclGroup()) {
9195               auto *D = cast<VarDecl>(C);
9196               DeclRefExpr *Ref = buildDeclRefExpr(SemaRef, D, D->getType(),
9197                                                   Transform->getBeginLoc());
9198               Captures[Ref] = Ref;
9199             }
9200           }))
9201     return 0;
9202 
9203   Built.clear(/* size */ NestedLoopCount);
9204 
9205   if (SemaRef.CurContext->isDependentContext())
9206     return NestedLoopCount;
9207 
9208   // An example of what is generated for the following code:
9209   //
9210   //   #pragma omp simd collapse(2) ordered(2)
9211   //   for (i = 0; i < NI; ++i)
9212   //     for (k = 0; k < NK; ++k)
9213   //       for (j = J0; j < NJ; j+=2) {
9214   //         <loop body>
9215   //       }
9216   //
9217   // We generate the code below.
9218   // Note: the loop body may be outlined in CodeGen.
9219   // Note: some counters may be C++ classes, operator- is used to find number of
9220   // iterations and operator+= to calculate counter value.
9221   // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
9222   // or i64 is currently supported).
9223   //
9224   //   #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
9225   //   for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
9226   //     .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
9227   //     .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
9228   //     // similar updates for vars in clauses (e.g. 'linear')
9229   //     <loop body (using local i and j)>
9230   //   }
9231   //   i = NI; // assign final values of counters
9232   //   j = NJ;
9233   //
9234 
9235   // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
9236   // the iteration counts of the collapsed for loops.
9237   // Precondition tests if there is at least one iteration (all conditions are
9238   // true).
9239   auto PreCond = ExprResult(IterSpaces[0].PreCond);
9240   Expr *N0 = IterSpaces[0].NumIterations;
9241   ExprResult LastIteration32 =
9242       widenIterationCount(/*Bits=*/32,
9243                           SemaRef
9244                               .PerformImplicitConversion(
9245                                   N0->IgnoreImpCasts(), N0->getType(),
9246                                   Sema::AA_Converting, /*AllowExplicit=*/true)
9247                               .get(),
9248                           SemaRef);
9249   ExprResult LastIteration64 = widenIterationCount(
9250       /*Bits=*/64,
9251       SemaRef
9252           .PerformImplicitConversion(N0->IgnoreImpCasts(), N0->getType(),
9253                                      Sema::AA_Converting,
9254                                      /*AllowExplicit=*/true)
9255           .get(),
9256       SemaRef);
9257 
9258   if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
9259     return NestedLoopCount;
9260 
9261   ASTContext &C = SemaRef.Context;
9262   bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
9263 
9264   Scope *CurScope = DSA.getCurScope();
9265   for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
9266     if (PreCond.isUsable()) {
9267       PreCond =
9268           SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
9269                              PreCond.get(), IterSpaces[Cnt].PreCond);
9270     }
9271     Expr *N = IterSpaces[Cnt].NumIterations;
9272     SourceLocation Loc = N->getExprLoc();
9273     AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
9274     if (LastIteration32.isUsable())
9275       LastIteration32 = SemaRef.BuildBinOp(
9276           CurScope, Loc, BO_Mul, LastIteration32.get(),
9277           SemaRef
9278               .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
9279                                          Sema::AA_Converting,
9280                                          /*AllowExplicit=*/true)
9281               .get());
9282     if (LastIteration64.isUsable())
9283       LastIteration64 = SemaRef.BuildBinOp(
9284           CurScope, Loc, BO_Mul, LastIteration64.get(),
9285           SemaRef
9286               .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
9287                                          Sema::AA_Converting,
9288                                          /*AllowExplicit=*/true)
9289               .get());
9290   }
9291 
9292   // Choose either the 32-bit or 64-bit version.
9293   ExprResult LastIteration = LastIteration64;
9294   if (SemaRef.getLangOpts().OpenMPOptimisticCollapse ||
9295       (LastIteration32.isUsable() &&
9296        C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
9297        (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
9298         fitsInto(
9299             /*Bits=*/32,
9300             LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
9301             LastIteration64.get(), SemaRef))))
9302     LastIteration = LastIteration32;
9303   QualType VType = LastIteration.get()->getType();
9304   QualType RealVType = VType;
9305   QualType StrideVType = VType;
9306   if (isOpenMPTaskLoopDirective(DKind)) {
9307     VType =
9308         SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
9309     StrideVType =
9310         SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
9311   }
9312 
9313   if (!LastIteration.isUsable())
9314     return 0;
9315 
9316   // Save the number of iterations.
9317   ExprResult NumIterations = LastIteration;
9318   {
9319     LastIteration = SemaRef.BuildBinOp(
9320         CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
9321         LastIteration.get(),
9322         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
9323     if (!LastIteration.isUsable())
9324       return 0;
9325   }
9326 
9327   // Calculate the last iteration number beforehand instead of doing this on
9328   // each iteration. Do not do this if the number of iterations may be kfold-ed.
9329   bool IsConstant = LastIteration.get()->isIntegerConstantExpr(SemaRef.Context);
9330   ExprResult CalcLastIteration;
9331   if (!IsConstant) {
9332     ExprResult SaveRef =
9333         tryBuildCapture(SemaRef, LastIteration.get(), Captures);
9334     LastIteration = SaveRef;
9335 
9336     // Prepare SaveRef + 1.
9337     NumIterations = SemaRef.BuildBinOp(
9338         CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
9339         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
9340     if (!NumIterations.isUsable())
9341       return 0;
9342   }
9343 
9344   SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
9345 
9346   // Build variables passed into runtime, necessary for worksharing directives.
9347   ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
9348   if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
9349       isOpenMPDistributeDirective(DKind) ||
9350       isOpenMPGenericLoopDirective(DKind) ||
9351       isOpenMPLoopTransformationDirective(DKind)) {
9352     // Lower bound variable, initialized with zero.
9353     VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
9354     LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
9355     SemaRef.AddInitializerToDecl(LBDecl,
9356                                  SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
9357                                  /*DirectInit*/ false);
9358 
9359     // Upper bound variable, initialized with last iteration number.
9360     VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
9361     UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
9362     SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
9363                                  /*DirectInit*/ false);
9364 
9365     // A 32-bit variable-flag where runtime returns 1 for the last iteration.
9366     // This will be used to implement clause 'lastprivate'.
9367     QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
9368     VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
9369     IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
9370     SemaRef.AddInitializerToDecl(ILDecl,
9371                                  SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
9372                                  /*DirectInit*/ false);
9373 
9374     // Stride variable returned by runtime (we initialize it to 1 by default).
9375     VarDecl *STDecl =
9376         buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
9377     ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
9378     SemaRef.AddInitializerToDecl(STDecl,
9379                                  SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
9380                                  /*DirectInit*/ false);
9381 
9382     // Build expression: UB = min(UB, LastIteration)
9383     // It is necessary for CodeGen of directives with static scheduling.
9384     ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
9385                                                 UB.get(), LastIteration.get());
9386     ExprResult CondOp = SemaRef.ActOnConditionalOp(
9387         LastIteration.get()->getExprLoc(), InitLoc, IsUBGreater.get(),
9388         LastIteration.get(), UB.get());
9389     EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
9390                              CondOp.get());
9391     EUB = SemaRef.ActOnFinishFullExpr(EUB.get(), /*DiscardedValue*/ false);
9392 
9393     // If we have a combined directive that combines 'distribute', 'for' or
9394     // 'simd' we need to be able to access the bounds of the schedule of the
9395     // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
9396     // by scheduling 'distribute' have to be passed to the schedule of 'for'.
9397     if (isOpenMPLoopBoundSharingDirective(DKind)) {
9398       // Lower bound variable, initialized with zero.
9399       VarDecl *CombLBDecl =
9400           buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
9401       CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
9402       SemaRef.AddInitializerToDecl(
9403           CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
9404           /*DirectInit*/ false);
9405 
9406       // Upper bound variable, initialized with last iteration number.
9407       VarDecl *CombUBDecl =
9408           buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
9409       CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
9410       SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
9411                                    /*DirectInit*/ false);
9412 
9413       ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
9414           CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
9415       ExprResult CombCondOp =
9416           SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
9417                                      LastIteration.get(), CombUB.get());
9418       CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
9419                                    CombCondOp.get());
9420       CombEUB =
9421           SemaRef.ActOnFinishFullExpr(CombEUB.get(), /*DiscardedValue*/ false);
9422 
9423       const CapturedDecl *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
9424       // We expect to have at least 2 more parameters than the 'parallel'
9425       // directive does - the lower and upper bounds of the previous schedule.
9426       assert(CD->getNumParams() >= 4 &&
9427              "Unexpected number of parameters in loop combined directive");
9428 
9429       // Set the proper type for the bounds given what we learned from the
9430       // enclosed loops.
9431       ImplicitParamDecl *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
9432       ImplicitParamDecl *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
9433 
9434       // Previous lower and upper bounds are obtained from the region
9435       // parameters.
9436       PrevLB =
9437           buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
9438       PrevUB =
9439           buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
9440     }
9441   }
9442 
9443   // Build the iteration variable and its initialization before loop.
9444   ExprResult IV;
9445   ExprResult Init, CombInit;
9446   {
9447     VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
9448     IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
9449     Expr *RHS = (isOpenMPWorksharingDirective(DKind) ||
9450                  isOpenMPGenericLoopDirective(DKind) ||
9451                  isOpenMPTaskLoopDirective(DKind) ||
9452                  isOpenMPDistributeDirective(DKind) ||
9453                  isOpenMPLoopTransformationDirective(DKind))
9454                     ? LB.get()
9455                     : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
9456     Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
9457     Init = SemaRef.ActOnFinishFullExpr(Init.get(), /*DiscardedValue*/ false);
9458 
9459     if (isOpenMPLoopBoundSharingDirective(DKind)) {
9460       Expr *CombRHS =
9461           (isOpenMPWorksharingDirective(DKind) ||
9462            isOpenMPGenericLoopDirective(DKind) ||
9463            isOpenMPTaskLoopDirective(DKind) ||
9464            isOpenMPDistributeDirective(DKind))
9465               ? CombLB.get()
9466               : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
9467       CombInit =
9468           SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
9469       CombInit =
9470           SemaRef.ActOnFinishFullExpr(CombInit.get(), /*DiscardedValue*/ false);
9471     }
9472   }
9473 
9474   bool UseStrictCompare =
9475       RealVType->hasUnsignedIntegerRepresentation() &&
9476       llvm::all_of(IterSpaces, [](const LoopIterationSpace &LIS) {
9477         return LIS.IsStrictCompare;
9478       });
9479   // Loop condition (IV < NumIterations) or (IV <= UB or IV < UB + 1 (for
9480   // unsigned IV)) for worksharing loops.
9481   SourceLocation CondLoc = AStmt->getBeginLoc();
9482   Expr *BoundUB = UB.get();
9483   if (UseStrictCompare) {
9484     BoundUB =
9485         SemaRef
9486             .BuildBinOp(CurScope, CondLoc, BO_Add, BoundUB,
9487                         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
9488             .get();
9489     BoundUB =
9490         SemaRef.ActOnFinishFullExpr(BoundUB, /*DiscardedValue*/ false).get();
9491   }
9492   ExprResult Cond =
9493       (isOpenMPWorksharingDirective(DKind) ||
9494        isOpenMPGenericLoopDirective(DKind) ||
9495        isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind) ||
9496        isOpenMPLoopTransformationDirective(DKind))
9497           ? SemaRef.BuildBinOp(CurScope, CondLoc,
9498                                UseStrictCompare ? BO_LT : BO_LE, IV.get(),
9499                                BoundUB)
9500           : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
9501                                NumIterations.get());
9502   ExprResult CombDistCond;
9503   if (isOpenMPLoopBoundSharingDirective(DKind)) {
9504     CombDistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
9505                                       NumIterations.get());
9506   }
9507 
9508   ExprResult CombCond;
9509   if (isOpenMPLoopBoundSharingDirective(DKind)) {
9510     Expr *BoundCombUB = CombUB.get();
9511     if (UseStrictCompare) {
9512       BoundCombUB =
9513           SemaRef
9514               .BuildBinOp(
9515                   CurScope, CondLoc, BO_Add, BoundCombUB,
9516                   SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
9517               .get();
9518       BoundCombUB =
9519           SemaRef.ActOnFinishFullExpr(BoundCombUB, /*DiscardedValue*/ false)
9520               .get();
9521     }
9522     CombCond =
9523         SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
9524                            IV.get(), BoundCombUB);
9525   }
9526   // Loop increment (IV = IV + 1)
9527   SourceLocation IncLoc = AStmt->getBeginLoc();
9528   ExprResult Inc =
9529       SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
9530                          SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
9531   if (!Inc.isUsable())
9532     return 0;
9533   Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
9534   Inc = SemaRef.ActOnFinishFullExpr(Inc.get(), /*DiscardedValue*/ false);
9535   if (!Inc.isUsable())
9536     return 0;
9537 
9538   // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
9539   // Used for directives with static scheduling.
9540   // In combined construct, add combined version that use CombLB and CombUB
9541   // base variables for the update
9542   ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
9543   if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
9544       isOpenMPGenericLoopDirective(DKind) ||
9545       isOpenMPDistributeDirective(DKind) ||
9546       isOpenMPLoopTransformationDirective(DKind)) {
9547     // LB + ST
9548     NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
9549     if (!NextLB.isUsable())
9550       return 0;
9551     // LB = LB + ST
9552     NextLB =
9553         SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
9554     NextLB =
9555         SemaRef.ActOnFinishFullExpr(NextLB.get(), /*DiscardedValue*/ false);
9556     if (!NextLB.isUsable())
9557       return 0;
9558     // UB + ST
9559     NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
9560     if (!NextUB.isUsable())
9561       return 0;
9562     // UB = UB + ST
9563     NextUB =
9564         SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
9565     NextUB =
9566         SemaRef.ActOnFinishFullExpr(NextUB.get(), /*DiscardedValue*/ false);
9567     if (!NextUB.isUsable())
9568       return 0;
9569     if (isOpenMPLoopBoundSharingDirective(DKind)) {
9570       CombNextLB =
9571           SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
9572       if (!NextLB.isUsable())
9573         return 0;
9574       // LB = LB + ST
9575       CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
9576                                       CombNextLB.get());
9577       CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get(),
9578                                                /*DiscardedValue*/ false);
9579       if (!CombNextLB.isUsable())
9580         return 0;
9581       // UB + ST
9582       CombNextUB =
9583           SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
9584       if (!CombNextUB.isUsable())
9585         return 0;
9586       // UB = UB + ST
9587       CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
9588                                       CombNextUB.get());
9589       CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get(),
9590                                                /*DiscardedValue*/ false);
9591       if (!CombNextUB.isUsable())
9592         return 0;
9593     }
9594   }
9595 
9596   // Create increment expression for distribute loop when combined in a same
9597   // directive with for as IV = IV + ST; ensure upper bound expression based
9598   // on PrevUB instead of NumIterations - used to implement 'for' when found
9599   // in combination with 'distribute', like in 'distribute parallel for'
9600   SourceLocation DistIncLoc = AStmt->getBeginLoc();
9601   ExprResult DistCond, DistInc, PrevEUB, ParForInDistCond;
9602   if (isOpenMPLoopBoundSharingDirective(DKind)) {
9603     DistCond = SemaRef.BuildBinOp(
9604         CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE, IV.get(), BoundUB);
9605     assert(DistCond.isUsable() && "distribute cond expr was not built");
9606 
9607     DistInc =
9608         SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
9609     assert(DistInc.isUsable() && "distribute inc expr was not built");
9610     DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
9611                                  DistInc.get());
9612     DistInc =
9613         SemaRef.ActOnFinishFullExpr(DistInc.get(), /*DiscardedValue*/ false);
9614     assert(DistInc.isUsable() && "distribute inc expr was not built");
9615 
9616     // Build expression: UB = min(UB, prevUB) for #for in composite or combined
9617     // construct
9618     ExprResult NewPrevUB = PrevUB;
9619     SourceLocation DistEUBLoc = AStmt->getBeginLoc();
9620     if (!SemaRef.Context.hasSameType(UB.get()->getType(),
9621                                      PrevUB.get()->getType())) {
9622       NewPrevUB = SemaRef.BuildCStyleCastExpr(
9623           DistEUBLoc,
9624           SemaRef.Context.getTrivialTypeSourceInfo(UB.get()->getType()),
9625           DistEUBLoc, NewPrevUB.get());
9626       if (!NewPrevUB.isUsable())
9627         return 0;
9628     }
9629     ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT,
9630                                                 UB.get(), NewPrevUB.get());
9631     ExprResult CondOp = SemaRef.ActOnConditionalOp(
9632         DistEUBLoc, DistEUBLoc, IsUBGreater.get(), NewPrevUB.get(), UB.get());
9633     PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
9634                                  CondOp.get());
9635     PrevEUB =
9636         SemaRef.ActOnFinishFullExpr(PrevEUB.get(), /*DiscardedValue*/ false);
9637 
9638     // Build IV <= PrevUB or IV < PrevUB + 1 for unsigned IV to be used in
9639     // parallel for is in combination with a distribute directive with
9640     // schedule(static, 1)
9641     Expr *BoundPrevUB = PrevUB.get();
9642     if (UseStrictCompare) {
9643       BoundPrevUB =
9644           SemaRef
9645               .BuildBinOp(
9646                   CurScope, CondLoc, BO_Add, BoundPrevUB,
9647                   SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
9648               .get();
9649       BoundPrevUB =
9650           SemaRef.ActOnFinishFullExpr(BoundPrevUB, /*DiscardedValue*/ false)
9651               .get();
9652     }
9653     ParForInDistCond =
9654         SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
9655                            IV.get(), BoundPrevUB);
9656   }
9657 
9658   // Build updates and final values of the loop counters.
9659   bool HasErrors = false;
9660   Built.Counters.resize(NestedLoopCount);
9661   Built.Inits.resize(NestedLoopCount);
9662   Built.Updates.resize(NestedLoopCount);
9663   Built.Finals.resize(NestedLoopCount);
9664   Built.DependentCounters.resize(NestedLoopCount);
9665   Built.DependentInits.resize(NestedLoopCount);
9666   Built.FinalsConditions.resize(NestedLoopCount);
9667   {
9668     // We implement the following algorithm for obtaining the
9669     // original loop iteration variable values based on the
9670     // value of the collapsed loop iteration variable IV.
9671     //
9672     // Let n+1 be the number of collapsed loops in the nest.
9673     // Iteration variables (I0, I1, .... In)
9674     // Iteration counts (N0, N1, ... Nn)
9675     //
9676     // Acc = IV;
9677     //
9678     // To compute Ik for loop k, 0 <= k <= n, generate:
9679     //    Prod = N(k+1) * N(k+2) * ... * Nn;
9680     //    Ik = Acc / Prod;
9681     //    Acc -= Ik * Prod;
9682     //
9683     ExprResult Acc = IV;
9684     for (unsigned int Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
9685       LoopIterationSpace &IS = IterSpaces[Cnt];
9686       SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
9687       ExprResult Iter;
9688 
9689       // Compute prod
9690       ExprResult Prod = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
9691       for (unsigned int K = Cnt + 1; K < NestedLoopCount; ++K)
9692         Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Prod.get(),
9693                                   IterSpaces[K].NumIterations);
9694 
9695       // Iter = Acc / Prod
9696       // If there is at least one more inner loop to avoid
9697       // multiplication by 1.
9698       if (Cnt + 1 < NestedLoopCount)
9699         Iter =
9700             SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, Acc.get(), Prod.get());
9701       else
9702         Iter = Acc;
9703       if (!Iter.isUsable()) {
9704         HasErrors = true;
9705         break;
9706       }
9707 
9708       // Update Acc:
9709       // Acc -= Iter * Prod
9710       // Check if there is at least one more inner loop to avoid
9711       // multiplication by 1.
9712       if (Cnt + 1 < NestedLoopCount)
9713         Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Iter.get(),
9714                                   Prod.get());
9715       else
9716         Prod = Iter;
9717       Acc = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Sub, Acc.get(), Prod.get());
9718 
9719       // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
9720       auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
9721       DeclRefExpr *CounterVar = buildDeclRefExpr(
9722           SemaRef, VD, IS.CounterVar->getType(), IS.CounterVar->getExprLoc(),
9723           /*RefersToCapture=*/true);
9724       ExprResult Init =
9725           buildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
9726                            IS.CounterInit, IS.IsNonRectangularLB, Captures);
9727       if (!Init.isUsable()) {
9728         HasErrors = true;
9729         break;
9730       }
9731       ExprResult Update = buildCounterUpdate(
9732           SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
9733           IS.CounterStep, IS.Subtract, IS.IsNonRectangularLB, &Captures);
9734       if (!Update.isUsable()) {
9735         HasErrors = true;
9736         break;
9737       }
9738 
9739       // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
9740       ExprResult Final =
9741           buildCounterUpdate(SemaRef, CurScope, UpdLoc, CounterVar,
9742                              IS.CounterInit, IS.NumIterations, IS.CounterStep,
9743                              IS.Subtract, IS.IsNonRectangularLB, &Captures);
9744       if (!Final.isUsable()) {
9745         HasErrors = true;
9746         break;
9747       }
9748 
9749       if (!Update.isUsable() || !Final.isUsable()) {
9750         HasErrors = true;
9751         break;
9752       }
9753       // Save results
9754       Built.Counters[Cnt] = IS.CounterVar;
9755       Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
9756       Built.Inits[Cnt] = Init.get();
9757       Built.Updates[Cnt] = Update.get();
9758       Built.Finals[Cnt] = Final.get();
9759       Built.DependentCounters[Cnt] = nullptr;
9760       Built.DependentInits[Cnt] = nullptr;
9761       Built.FinalsConditions[Cnt] = nullptr;
9762       if (IS.IsNonRectangularLB || IS.IsNonRectangularUB) {
9763         Built.DependentCounters[Cnt] =
9764             Built.Counters[NestedLoopCount - 1 - IS.LoopDependentIdx];
9765         Built.DependentInits[Cnt] =
9766             Built.Inits[NestedLoopCount - 1 - IS.LoopDependentIdx];
9767         Built.FinalsConditions[Cnt] = IS.FinalCondition;
9768       }
9769     }
9770   }
9771 
9772   if (HasErrors)
9773     return 0;
9774 
9775   // Save results
9776   Built.IterationVarRef = IV.get();
9777   Built.LastIteration = LastIteration.get();
9778   Built.NumIterations = NumIterations.get();
9779   Built.CalcLastIteration = SemaRef
9780                                 .ActOnFinishFullExpr(CalcLastIteration.get(),
9781                                                      /*DiscardedValue=*/false)
9782                                 .get();
9783   Built.PreCond = PreCond.get();
9784   Built.PreInits = buildPreInits(C, Captures);
9785   Built.Cond = Cond.get();
9786   Built.Init = Init.get();
9787   Built.Inc = Inc.get();
9788   Built.LB = LB.get();
9789   Built.UB = UB.get();
9790   Built.IL = IL.get();
9791   Built.ST = ST.get();
9792   Built.EUB = EUB.get();
9793   Built.NLB = NextLB.get();
9794   Built.NUB = NextUB.get();
9795   Built.PrevLB = PrevLB.get();
9796   Built.PrevUB = PrevUB.get();
9797   Built.DistInc = DistInc.get();
9798   Built.PrevEUB = PrevEUB.get();
9799   Built.DistCombinedFields.LB = CombLB.get();
9800   Built.DistCombinedFields.UB = CombUB.get();
9801   Built.DistCombinedFields.EUB = CombEUB.get();
9802   Built.DistCombinedFields.Init = CombInit.get();
9803   Built.DistCombinedFields.Cond = CombCond.get();
9804   Built.DistCombinedFields.NLB = CombNextLB.get();
9805   Built.DistCombinedFields.NUB = CombNextUB.get();
9806   Built.DistCombinedFields.DistCond = CombDistCond.get();
9807   Built.DistCombinedFields.ParForInDistCond = ParForInDistCond.get();
9808 
9809   return NestedLoopCount;
9810 }
9811 
9812 static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
9813   auto CollapseClauses =
9814       OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
9815   if (CollapseClauses.begin() != CollapseClauses.end())
9816     return (*CollapseClauses.begin())->getNumForLoops();
9817   return nullptr;
9818 }
9819 
9820 static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
9821   auto OrderedClauses =
9822       OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
9823   if (OrderedClauses.begin() != OrderedClauses.end())
9824     return (*OrderedClauses.begin())->getNumForLoops();
9825   return nullptr;
9826 }
9827 
9828 static bool checkSimdlenSafelenSpecified(Sema &S,
9829                                          const ArrayRef<OMPClause *> Clauses) {
9830   const OMPSafelenClause *Safelen = nullptr;
9831   const OMPSimdlenClause *Simdlen = nullptr;
9832 
9833   for (const OMPClause *Clause : Clauses) {
9834     if (Clause->getClauseKind() == OMPC_safelen)
9835       Safelen = cast<OMPSafelenClause>(Clause);
9836     else if (Clause->getClauseKind() == OMPC_simdlen)
9837       Simdlen = cast<OMPSimdlenClause>(Clause);
9838     if (Safelen && Simdlen)
9839       break;
9840   }
9841 
9842   if (Simdlen && Safelen) {
9843     const Expr *SimdlenLength = Simdlen->getSimdlen();
9844     const Expr *SafelenLength = Safelen->getSafelen();
9845     if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
9846         SimdlenLength->isInstantiationDependent() ||
9847         SimdlenLength->containsUnexpandedParameterPack())
9848       return false;
9849     if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
9850         SafelenLength->isInstantiationDependent() ||
9851         SafelenLength->containsUnexpandedParameterPack())
9852       return false;
9853     Expr::EvalResult SimdlenResult, SafelenResult;
9854     SimdlenLength->EvaluateAsInt(SimdlenResult, S.Context);
9855     SafelenLength->EvaluateAsInt(SafelenResult, S.Context);
9856     llvm::APSInt SimdlenRes = SimdlenResult.Val.getInt();
9857     llvm::APSInt SafelenRes = SafelenResult.Val.getInt();
9858     // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
9859     // If both simdlen and safelen clauses are specified, the value of the
9860     // simdlen parameter must be less than or equal to the value of the safelen
9861     // parameter.
9862     if (SimdlenRes > SafelenRes) {
9863       S.Diag(SimdlenLength->getExprLoc(),
9864              diag::err_omp_wrong_simdlen_safelen_values)
9865           << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
9866       return true;
9867     }
9868   }
9869   return false;
9870 }
9871 
9872 StmtResult
9873 Sema::ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
9874                                SourceLocation StartLoc, SourceLocation EndLoc,
9875                                VarsWithInheritedDSAType &VarsWithImplicitDSA) {
9876   if (!AStmt)
9877     return StmtError();
9878 
9879   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9880   OMPLoopBasedDirective::HelperExprs B;
9881   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9882   // define the nested loops number.
9883   unsigned NestedLoopCount = checkOpenMPLoop(
9884       OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
9885       AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
9886   if (NestedLoopCount == 0)
9887     return StmtError();
9888 
9889   assert((CurContext->isDependentContext() || B.builtAll()) &&
9890          "omp simd loop exprs were not built");
9891 
9892   if (!CurContext->isDependentContext()) {
9893     // Finalize the clauses that need pre-built expressions for CodeGen.
9894     for (OMPClause *C : Clauses) {
9895       if (auto *LC = dyn_cast<OMPLinearClause>(C))
9896         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9897                                      B.NumIterations, *this, CurScope,
9898                                      DSAStack))
9899           return StmtError();
9900     }
9901   }
9902 
9903   if (checkSimdlenSafelenSpecified(*this, Clauses))
9904     return StmtError();
9905 
9906   setFunctionHasBranchProtectedScope();
9907   return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
9908                                   Clauses, AStmt, B);
9909 }
9910 
9911 StmtResult
9912 Sema::ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
9913                               SourceLocation StartLoc, SourceLocation EndLoc,
9914                               VarsWithInheritedDSAType &VarsWithImplicitDSA) {
9915   if (!AStmt)
9916     return StmtError();
9917 
9918   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9919   OMPLoopBasedDirective::HelperExprs B;
9920   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9921   // define the nested loops number.
9922   unsigned NestedLoopCount = checkOpenMPLoop(
9923       OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
9924       AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
9925   if (NestedLoopCount == 0)
9926     return StmtError();
9927 
9928   assert((CurContext->isDependentContext() || B.builtAll()) &&
9929          "omp for loop exprs were not built");
9930 
9931   if (!CurContext->isDependentContext()) {
9932     // Finalize the clauses that need pre-built expressions for CodeGen.
9933     for (OMPClause *C : Clauses) {
9934       if (auto *LC = dyn_cast<OMPLinearClause>(C))
9935         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9936                                      B.NumIterations, *this, CurScope,
9937                                      DSAStack))
9938           return StmtError();
9939     }
9940   }
9941 
9942   setFunctionHasBranchProtectedScope();
9943   return OMPForDirective::Create(
9944       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
9945       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
9946 }
9947 
9948 StmtResult Sema::ActOnOpenMPForSimdDirective(
9949     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9950     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
9951   if (!AStmt)
9952     return StmtError();
9953 
9954   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9955   OMPLoopBasedDirective::HelperExprs B;
9956   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9957   // define the nested loops number.
9958   unsigned NestedLoopCount =
9959       checkOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
9960                       getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
9961                       VarsWithImplicitDSA, B);
9962   if (NestedLoopCount == 0)
9963     return StmtError();
9964 
9965   assert((CurContext->isDependentContext() || B.builtAll()) &&
9966          "omp for simd loop exprs were not built");
9967 
9968   if (!CurContext->isDependentContext()) {
9969     // Finalize the clauses that need pre-built expressions for CodeGen.
9970     for (OMPClause *C : Clauses) {
9971       if (auto *LC = dyn_cast<OMPLinearClause>(C))
9972         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9973                                      B.NumIterations, *this, CurScope,
9974                                      DSAStack))
9975           return StmtError();
9976     }
9977   }
9978 
9979   if (checkSimdlenSafelenSpecified(*this, Clauses))
9980     return StmtError();
9981 
9982   setFunctionHasBranchProtectedScope();
9983   return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
9984                                      Clauses, AStmt, B);
9985 }
9986 
9987 StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
9988                                               Stmt *AStmt,
9989                                               SourceLocation StartLoc,
9990                                               SourceLocation EndLoc) {
9991   if (!AStmt)
9992     return StmtError();
9993 
9994   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9995   auto BaseStmt = AStmt;
9996   while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
9997     BaseStmt = CS->getCapturedStmt();
9998   if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
9999     auto S = C->children();
10000     if (S.begin() == S.end())
10001       return StmtError();
10002     // All associated statements must be '#pragma omp section' except for
10003     // the first one.
10004     for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
10005       if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
10006         if (SectionStmt)
10007           Diag(SectionStmt->getBeginLoc(),
10008                diag::err_omp_sections_substmt_not_section);
10009         return StmtError();
10010       }
10011       cast<OMPSectionDirective>(SectionStmt)
10012           ->setHasCancel(DSAStack->isCancelRegion());
10013     }
10014   } else {
10015     Diag(AStmt->getBeginLoc(), diag::err_omp_sections_not_compound_stmt);
10016     return StmtError();
10017   }
10018 
10019   setFunctionHasBranchProtectedScope();
10020 
10021   return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
10022                                       DSAStack->getTaskgroupReductionRef(),
10023                                       DSAStack->isCancelRegion());
10024 }
10025 
10026 StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
10027                                              SourceLocation StartLoc,
10028                                              SourceLocation EndLoc) {
10029   if (!AStmt)
10030     return StmtError();
10031 
10032   setFunctionHasBranchProtectedScope();
10033   DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
10034 
10035   return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
10036                                      DSAStack->isCancelRegion());
10037 }
10038 
10039 static Expr *getDirectCallExpr(Expr *E) {
10040   E = E->IgnoreParenCasts()->IgnoreImplicit();
10041   if (auto *CE = dyn_cast<CallExpr>(E))
10042     if (CE->getDirectCallee())
10043       return E;
10044   return nullptr;
10045 }
10046 
10047 StmtResult Sema::ActOnOpenMPDispatchDirective(ArrayRef<OMPClause *> Clauses,
10048                                               Stmt *AStmt,
10049                                               SourceLocation StartLoc,
10050                                               SourceLocation EndLoc) {
10051   if (!AStmt)
10052     return StmtError();
10053 
10054   Stmt *S = cast<CapturedStmt>(AStmt)->getCapturedStmt();
10055 
10056   // 5.1 OpenMP
10057   // expression-stmt : an expression statement with one of the following forms:
10058   //   expression = target-call ( [expression-list] );
10059   //   target-call ( [expression-list] );
10060 
10061   SourceLocation TargetCallLoc;
10062 
10063   if (!CurContext->isDependentContext()) {
10064     Expr *TargetCall = nullptr;
10065 
10066     auto *E = dyn_cast<Expr>(S);
10067     if (!E) {
10068       Diag(S->getBeginLoc(), diag::err_omp_dispatch_statement_call);
10069       return StmtError();
10070     }
10071 
10072     E = E->IgnoreParenCasts()->IgnoreImplicit();
10073 
10074     if (auto *BO = dyn_cast<BinaryOperator>(E)) {
10075       if (BO->getOpcode() == BO_Assign)
10076         TargetCall = getDirectCallExpr(BO->getRHS());
10077     } else {
10078       if (auto *COCE = dyn_cast<CXXOperatorCallExpr>(E))
10079         if (COCE->getOperator() == OO_Equal)
10080           TargetCall = getDirectCallExpr(COCE->getArg(1));
10081       if (!TargetCall)
10082         TargetCall = getDirectCallExpr(E);
10083     }
10084     if (!TargetCall) {
10085       Diag(E->getBeginLoc(), diag::err_omp_dispatch_statement_call);
10086       return StmtError();
10087     }
10088     TargetCallLoc = TargetCall->getExprLoc();
10089   }
10090 
10091   setFunctionHasBranchProtectedScope();
10092 
10093   return OMPDispatchDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
10094                                       TargetCallLoc);
10095 }
10096 
10097 StmtResult Sema::ActOnOpenMPGenericLoopDirective(
10098     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10099     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
10100   if (!AStmt)
10101     return StmtError();
10102 
10103   // OpenMP 5.1 [2.11.7, loop construct]
10104   // A list item may not appear in a lastprivate clause unless it is the
10105   // loop iteration variable of a loop that is associated with the construct.
10106   for (OMPClause *C : Clauses) {
10107     if (auto *LPC = dyn_cast<OMPLastprivateClause>(C)) {
10108       for (Expr *RefExpr : LPC->varlists()) {
10109         SourceLocation ELoc;
10110         SourceRange ERange;
10111         Expr *SimpleRefExpr = RefExpr;
10112         auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
10113         if (ValueDecl *D = Res.first) {
10114           auto &&Info = DSAStack->isLoopControlVariable(D);
10115           if (!Info.first) {
10116             Diag(ELoc, diag::err_omp_lastprivate_loop_var_non_loop_iteration);
10117             return StmtError();
10118           }
10119         }
10120       }
10121     }
10122   }
10123 
10124   auto *CS = cast<CapturedStmt>(AStmt);
10125   // 1.2.2 OpenMP Language Terminology
10126   // Structured block - An executable statement with a single entry at the
10127   // top and a single exit at the bottom.
10128   // The point of exit cannot be a branch out of the structured block.
10129   // longjmp() and throw() must not violate the entry/exit criteria.
10130   CS->getCapturedDecl()->setNothrow();
10131 
10132   OMPLoopDirective::HelperExprs B;
10133   // In presence of clause 'collapse', it will define the nested loops number.
10134   unsigned NestedLoopCount = checkOpenMPLoop(
10135       OMPD_loop, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
10136       AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
10137   if (NestedLoopCount == 0)
10138     return StmtError();
10139 
10140   assert((CurContext->isDependentContext() || B.builtAll()) &&
10141          "omp loop exprs were not built");
10142 
10143   setFunctionHasBranchProtectedScope();
10144   return OMPGenericLoopDirective::Create(Context, StartLoc, EndLoc,
10145                                          NestedLoopCount, Clauses, AStmt, B);
10146 }
10147 
10148 StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
10149                                             Stmt *AStmt,
10150                                             SourceLocation StartLoc,
10151                                             SourceLocation EndLoc) {
10152   if (!AStmt)
10153     return StmtError();
10154 
10155   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
10156 
10157   setFunctionHasBranchProtectedScope();
10158 
10159   // OpenMP [2.7.3, single Construct, Restrictions]
10160   // The copyprivate clause must not be used with the nowait clause.
10161   const OMPClause *Nowait = nullptr;
10162   const OMPClause *Copyprivate = nullptr;
10163   for (const OMPClause *Clause : Clauses) {
10164     if (Clause->getClauseKind() == OMPC_nowait)
10165       Nowait = Clause;
10166     else if (Clause->getClauseKind() == OMPC_copyprivate)
10167       Copyprivate = Clause;
10168     if (Copyprivate && Nowait) {
10169       Diag(Copyprivate->getBeginLoc(),
10170            diag::err_omp_single_copyprivate_with_nowait);
10171       Diag(Nowait->getBeginLoc(), diag::note_omp_nowait_clause_here);
10172       return StmtError();
10173     }
10174   }
10175 
10176   return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
10177 }
10178 
10179 StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
10180                                             SourceLocation StartLoc,
10181                                             SourceLocation EndLoc) {
10182   if (!AStmt)
10183     return StmtError();
10184 
10185   setFunctionHasBranchProtectedScope();
10186 
10187   return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
10188 }
10189 
10190 StmtResult Sema::ActOnOpenMPMaskedDirective(ArrayRef<OMPClause *> Clauses,
10191                                             Stmt *AStmt,
10192                                             SourceLocation StartLoc,
10193                                             SourceLocation EndLoc) {
10194   if (!AStmt)
10195     return StmtError();
10196 
10197   setFunctionHasBranchProtectedScope();
10198 
10199   return OMPMaskedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
10200 }
10201 
10202 StmtResult Sema::ActOnOpenMPCriticalDirective(
10203     const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
10204     Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
10205   if (!AStmt)
10206     return StmtError();
10207 
10208   bool ErrorFound = false;
10209   llvm::APSInt Hint;
10210   SourceLocation HintLoc;
10211   bool DependentHint = false;
10212   for (const OMPClause *C : Clauses) {
10213     if (C->getClauseKind() == OMPC_hint) {
10214       if (!DirName.getName()) {
10215         Diag(C->getBeginLoc(), diag::err_omp_hint_clause_no_name);
10216         ErrorFound = true;
10217       }
10218       Expr *E = cast<OMPHintClause>(C)->getHint();
10219       if (E->isTypeDependent() || E->isValueDependent() ||
10220           E->isInstantiationDependent()) {
10221         DependentHint = true;
10222       } else {
10223         Hint = E->EvaluateKnownConstInt(Context);
10224         HintLoc = C->getBeginLoc();
10225       }
10226     }
10227   }
10228   if (ErrorFound)
10229     return StmtError();
10230   const auto Pair = DSAStack->getCriticalWithHint(DirName);
10231   if (Pair.first && DirName.getName() && !DependentHint) {
10232     if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
10233       Diag(StartLoc, diag::err_omp_critical_with_hint);
10234       if (HintLoc.isValid())
10235         Diag(HintLoc, diag::note_omp_critical_hint_here)
10236             << 0 << toString(Hint, /*Radix=*/10, /*Signed=*/false);
10237       else
10238         Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
10239       if (const auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
10240         Diag(C->getBeginLoc(), diag::note_omp_critical_hint_here)
10241             << 1
10242             << toString(C->getHint()->EvaluateKnownConstInt(Context),
10243                         /*Radix=*/10, /*Signed=*/false);
10244       } else {
10245         Diag(Pair.first->getBeginLoc(), diag::note_omp_critical_no_hint) << 1;
10246       }
10247     }
10248   }
10249 
10250   setFunctionHasBranchProtectedScope();
10251 
10252   auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
10253                                            Clauses, AStmt);
10254   if (!Pair.first && DirName.getName() && !DependentHint)
10255     DSAStack->addCriticalWithHint(Dir, Hint);
10256   return Dir;
10257 }
10258 
10259 StmtResult Sema::ActOnOpenMPParallelForDirective(
10260     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10261     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
10262   if (!AStmt)
10263     return StmtError();
10264 
10265   auto *CS = cast<CapturedStmt>(AStmt);
10266   // 1.2.2 OpenMP Language Terminology
10267   // Structured block - An executable statement with a single entry at the
10268   // top and a single exit at the bottom.
10269   // The point of exit cannot be a branch out of the structured block.
10270   // longjmp() and throw() must not violate the entry/exit criteria.
10271   CS->getCapturedDecl()->setNothrow();
10272 
10273   OMPLoopBasedDirective::HelperExprs B;
10274   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
10275   // define the nested loops number.
10276   unsigned NestedLoopCount =
10277       checkOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
10278                       getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
10279                       VarsWithImplicitDSA, B);
10280   if (NestedLoopCount == 0)
10281     return StmtError();
10282 
10283   assert((CurContext->isDependentContext() || B.builtAll()) &&
10284          "omp parallel for loop exprs were not built");
10285 
10286   if (!CurContext->isDependentContext()) {
10287     // Finalize the clauses that need pre-built expressions for CodeGen.
10288     for (OMPClause *C : Clauses) {
10289       if (auto *LC = dyn_cast<OMPLinearClause>(C))
10290         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10291                                      B.NumIterations, *this, CurScope,
10292                                      DSAStack))
10293           return StmtError();
10294     }
10295   }
10296 
10297   setFunctionHasBranchProtectedScope();
10298   return OMPParallelForDirective::Create(
10299       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
10300       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
10301 }
10302 
10303 StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
10304     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10305     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
10306   if (!AStmt)
10307     return StmtError();
10308 
10309   auto *CS = cast<CapturedStmt>(AStmt);
10310   // 1.2.2 OpenMP Language Terminology
10311   // Structured block - An executable statement with a single entry at the
10312   // top and a single exit at the bottom.
10313   // The point of exit cannot be a branch out of the structured block.
10314   // longjmp() and throw() must not violate the entry/exit criteria.
10315   CS->getCapturedDecl()->setNothrow();
10316 
10317   OMPLoopBasedDirective::HelperExprs B;
10318   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
10319   // define the nested loops number.
10320   unsigned NestedLoopCount =
10321       checkOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
10322                       getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
10323                       VarsWithImplicitDSA, B);
10324   if (NestedLoopCount == 0)
10325     return StmtError();
10326 
10327   if (!CurContext->isDependentContext()) {
10328     // Finalize the clauses that need pre-built expressions for CodeGen.
10329     for (OMPClause *C : Clauses) {
10330       if (auto *LC = dyn_cast<OMPLinearClause>(C))
10331         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10332                                      B.NumIterations, *this, CurScope,
10333                                      DSAStack))
10334           return StmtError();
10335     }
10336   }
10337 
10338   if (checkSimdlenSafelenSpecified(*this, Clauses))
10339     return StmtError();
10340 
10341   setFunctionHasBranchProtectedScope();
10342   return OMPParallelForSimdDirective::Create(
10343       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10344 }
10345 
10346 StmtResult
10347 Sema::ActOnOpenMPParallelMasterDirective(ArrayRef<OMPClause *> Clauses,
10348                                          Stmt *AStmt, SourceLocation StartLoc,
10349                                          SourceLocation EndLoc) {
10350   if (!AStmt)
10351     return StmtError();
10352 
10353   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
10354   auto *CS = cast<CapturedStmt>(AStmt);
10355   // 1.2.2 OpenMP Language Terminology
10356   // Structured block - An executable statement with a single entry at the
10357   // top and a single exit at the bottom.
10358   // The point of exit cannot be a branch out of the structured block.
10359   // longjmp() and throw() must not violate the entry/exit criteria.
10360   CS->getCapturedDecl()->setNothrow();
10361 
10362   setFunctionHasBranchProtectedScope();
10363 
10364   return OMPParallelMasterDirective::Create(
10365       Context, StartLoc, EndLoc, Clauses, AStmt,
10366       DSAStack->getTaskgroupReductionRef());
10367 }
10368 
10369 StmtResult
10370 Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
10371                                            Stmt *AStmt, SourceLocation StartLoc,
10372                                            SourceLocation EndLoc) {
10373   if (!AStmt)
10374     return StmtError();
10375 
10376   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
10377   auto BaseStmt = AStmt;
10378   while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
10379     BaseStmt = CS->getCapturedStmt();
10380   if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
10381     auto S = C->children();
10382     if (S.begin() == S.end())
10383       return StmtError();
10384     // All associated statements must be '#pragma omp section' except for
10385     // the first one.
10386     for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
10387       if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
10388         if (SectionStmt)
10389           Diag(SectionStmt->getBeginLoc(),
10390                diag::err_omp_parallel_sections_substmt_not_section);
10391         return StmtError();
10392       }
10393       cast<OMPSectionDirective>(SectionStmt)
10394           ->setHasCancel(DSAStack->isCancelRegion());
10395     }
10396   } else {
10397     Diag(AStmt->getBeginLoc(),
10398          diag::err_omp_parallel_sections_not_compound_stmt);
10399     return StmtError();
10400   }
10401 
10402   setFunctionHasBranchProtectedScope();
10403 
10404   return OMPParallelSectionsDirective::Create(
10405       Context, StartLoc, EndLoc, Clauses, AStmt,
10406       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
10407 }
10408 
10409 /// Find and diagnose mutually exclusive clause kinds.
10410 static bool checkMutuallyExclusiveClauses(
10411     Sema &S, ArrayRef<OMPClause *> Clauses,
10412     ArrayRef<OpenMPClauseKind> MutuallyExclusiveClauses) {
10413   const OMPClause *PrevClause = nullptr;
10414   bool ErrorFound = false;
10415   for (const OMPClause *C : Clauses) {
10416     if (llvm::is_contained(MutuallyExclusiveClauses, C->getClauseKind())) {
10417       if (!PrevClause) {
10418         PrevClause = C;
10419       } else if (PrevClause->getClauseKind() != C->getClauseKind()) {
10420         S.Diag(C->getBeginLoc(), diag::err_omp_clauses_mutually_exclusive)
10421             << getOpenMPClauseName(C->getClauseKind())
10422             << getOpenMPClauseName(PrevClause->getClauseKind());
10423         S.Diag(PrevClause->getBeginLoc(), diag::note_omp_previous_clause)
10424             << getOpenMPClauseName(PrevClause->getClauseKind());
10425         ErrorFound = true;
10426       }
10427     }
10428   }
10429   return ErrorFound;
10430 }
10431 
10432 StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
10433                                           Stmt *AStmt, SourceLocation StartLoc,
10434                                           SourceLocation EndLoc) {
10435   if (!AStmt)
10436     return StmtError();
10437 
10438   // OpenMP 5.0, 2.10.1 task Construct
10439   // If a detach clause appears on the directive, then a mergeable clause cannot
10440   // appear on the same directive.
10441   if (checkMutuallyExclusiveClauses(*this, Clauses,
10442                                     {OMPC_detach, OMPC_mergeable}))
10443     return StmtError();
10444 
10445   auto *CS = cast<CapturedStmt>(AStmt);
10446   // 1.2.2 OpenMP Language Terminology
10447   // Structured block - An executable statement with a single entry at the
10448   // top and a single exit at the bottom.
10449   // The point of exit cannot be a branch out of the structured block.
10450   // longjmp() and throw() must not violate the entry/exit criteria.
10451   CS->getCapturedDecl()->setNothrow();
10452 
10453   setFunctionHasBranchProtectedScope();
10454 
10455   return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
10456                                   DSAStack->isCancelRegion());
10457 }
10458 
10459 StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
10460                                                SourceLocation EndLoc) {
10461   return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
10462 }
10463 
10464 StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
10465                                              SourceLocation EndLoc) {
10466   return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
10467 }
10468 
10469 StmtResult Sema::ActOnOpenMPTaskwaitDirective(ArrayRef<OMPClause *> Clauses,
10470                                               SourceLocation StartLoc,
10471                                               SourceLocation EndLoc) {
10472   return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc, Clauses);
10473 }
10474 
10475 StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
10476                                                Stmt *AStmt,
10477                                                SourceLocation StartLoc,
10478                                                SourceLocation EndLoc) {
10479   if (!AStmt)
10480     return StmtError();
10481 
10482   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
10483 
10484   setFunctionHasBranchProtectedScope();
10485 
10486   return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses,
10487                                        AStmt,
10488                                        DSAStack->getTaskgroupReductionRef());
10489 }
10490 
10491 StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
10492                                            SourceLocation StartLoc,
10493                                            SourceLocation EndLoc) {
10494   OMPFlushClause *FC = nullptr;
10495   OMPClause *OrderClause = nullptr;
10496   for (OMPClause *C : Clauses) {
10497     if (C->getClauseKind() == OMPC_flush)
10498       FC = cast<OMPFlushClause>(C);
10499     else
10500       OrderClause = C;
10501   }
10502   OpenMPClauseKind MemOrderKind = OMPC_unknown;
10503   SourceLocation MemOrderLoc;
10504   for (const OMPClause *C : Clauses) {
10505     if (C->getClauseKind() == OMPC_acq_rel ||
10506         C->getClauseKind() == OMPC_acquire ||
10507         C->getClauseKind() == OMPC_release) {
10508       if (MemOrderKind != OMPC_unknown) {
10509         Diag(C->getBeginLoc(), diag::err_omp_several_mem_order_clauses)
10510             << getOpenMPDirectiveName(OMPD_flush) << 1
10511             << SourceRange(C->getBeginLoc(), C->getEndLoc());
10512         Diag(MemOrderLoc, diag::note_omp_previous_mem_order_clause)
10513             << getOpenMPClauseName(MemOrderKind);
10514       } else {
10515         MemOrderKind = C->getClauseKind();
10516         MemOrderLoc = C->getBeginLoc();
10517       }
10518     }
10519   }
10520   if (FC && OrderClause) {
10521     Diag(FC->getLParenLoc(), diag::err_omp_flush_order_clause_and_list)
10522         << getOpenMPClauseName(OrderClause->getClauseKind());
10523     Diag(OrderClause->getBeginLoc(), diag::note_omp_flush_order_clause_here)
10524         << getOpenMPClauseName(OrderClause->getClauseKind());
10525     return StmtError();
10526   }
10527   return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
10528 }
10529 
10530 StmtResult Sema::ActOnOpenMPDepobjDirective(ArrayRef<OMPClause *> Clauses,
10531                                             SourceLocation StartLoc,
10532                                             SourceLocation EndLoc) {
10533   if (Clauses.empty()) {
10534     Diag(StartLoc, diag::err_omp_depobj_expected);
10535     return StmtError();
10536   } else if (Clauses[0]->getClauseKind() != OMPC_depobj) {
10537     Diag(Clauses[0]->getBeginLoc(), diag::err_omp_depobj_expected);
10538     return StmtError();
10539   }
10540   // Only depobj expression and another single clause is allowed.
10541   if (Clauses.size() > 2) {
10542     Diag(Clauses[2]->getBeginLoc(),
10543          diag::err_omp_depobj_single_clause_expected);
10544     return StmtError();
10545   } else if (Clauses.size() < 1) {
10546     Diag(Clauses[0]->getEndLoc(), diag::err_omp_depobj_single_clause_expected);
10547     return StmtError();
10548   }
10549   return OMPDepobjDirective::Create(Context, StartLoc, EndLoc, Clauses);
10550 }
10551 
10552 StmtResult Sema::ActOnOpenMPScanDirective(ArrayRef<OMPClause *> Clauses,
10553                                           SourceLocation StartLoc,
10554                                           SourceLocation EndLoc) {
10555   // Check that exactly one clause is specified.
10556   if (Clauses.size() != 1) {
10557     Diag(Clauses.empty() ? EndLoc : Clauses[1]->getBeginLoc(),
10558          diag::err_omp_scan_single_clause_expected);
10559     return StmtError();
10560   }
10561   // Check that scan directive is used in the scopeof the OpenMP loop body.
10562   if (Scope *S = DSAStack->getCurScope()) {
10563     Scope *ParentS = S->getParent();
10564     if (!ParentS || ParentS->getParent() != ParentS->getBreakParent() ||
10565         !ParentS->getBreakParent()->isOpenMPLoopScope())
10566       return StmtError(Diag(StartLoc, diag::err_omp_orphaned_device_directive)
10567                        << getOpenMPDirectiveName(OMPD_scan) << 5);
10568   }
10569   // Check that only one instance of scan directives is used in the same outer
10570   // region.
10571   if (DSAStack->doesParentHasScanDirective()) {
10572     Diag(StartLoc, diag::err_omp_several_directives_in_region) << "scan";
10573     Diag(DSAStack->getParentScanDirectiveLoc(),
10574          diag::note_omp_previous_directive)
10575         << "scan";
10576     return StmtError();
10577   }
10578   DSAStack->setParentHasScanDirective(StartLoc);
10579   return OMPScanDirective::Create(Context, StartLoc, EndLoc, Clauses);
10580 }
10581 
10582 StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
10583                                              Stmt *AStmt,
10584                                              SourceLocation StartLoc,
10585                                              SourceLocation EndLoc) {
10586   const OMPClause *DependFound = nullptr;
10587   const OMPClause *DependSourceClause = nullptr;
10588   const OMPClause *DependSinkClause = nullptr;
10589   bool ErrorFound = false;
10590   const OMPThreadsClause *TC = nullptr;
10591   const OMPSIMDClause *SC = nullptr;
10592   for (const OMPClause *C : Clauses) {
10593     if (auto *DC = dyn_cast<OMPDependClause>(C)) {
10594       DependFound = C;
10595       if (DC->getDependencyKind() == OMPC_DEPEND_source) {
10596         if (DependSourceClause) {
10597           Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
10598               << getOpenMPDirectiveName(OMPD_ordered)
10599               << getOpenMPClauseName(OMPC_depend) << 2;
10600           ErrorFound = true;
10601         } else {
10602           DependSourceClause = C;
10603         }
10604         if (DependSinkClause) {
10605           Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
10606               << 0;
10607           ErrorFound = true;
10608         }
10609       } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
10610         if (DependSourceClause) {
10611           Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
10612               << 1;
10613           ErrorFound = true;
10614         }
10615         DependSinkClause = C;
10616       }
10617     } else if (C->getClauseKind() == OMPC_threads) {
10618       TC = cast<OMPThreadsClause>(C);
10619     } else if (C->getClauseKind() == OMPC_simd) {
10620       SC = cast<OMPSIMDClause>(C);
10621     }
10622   }
10623   if (!ErrorFound && !SC &&
10624       isOpenMPSimdDirective(DSAStack->getParentDirective())) {
10625     // OpenMP [2.8.1,simd Construct, Restrictions]
10626     // An ordered construct with the simd clause is the only OpenMP construct
10627     // that can appear in the simd region.
10628     Diag(StartLoc, diag::err_omp_prohibited_region_simd)
10629         << (LangOpts.OpenMP >= 50 ? 1 : 0);
10630     ErrorFound = true;
10631   } else if (DependFound && (TC || SC)) {
10632     Diag(DependFound->getBeginLoc(), diag::err_omp_depend_clause_thread_simd)
10633         << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
10634     ErrorFound = true;
10635   } else if (DependFound && !DSAStack->getParentOrderedRegionParam().first) {
10636     Diag(DependFound->getBeginLoc(),
10637          diag::err_omp_ordered_directive_without_param);
10638     ErrorFound = true;
10639   } else if (TC || Clauses.empty()) {
10640     if (const Expr *Param = DSAStack->getParentOrderedRegionParam().first) {
10641       SourceLocation ErrLoc = TC ? TC->getBeginLoc() : StartLoc;
10642       Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
10643           << (TC != nullptr);
10644       Diag(Param->getBeginLoc(), diag::note_omp_ordered_param) << 1;
10645       ErrorFound = true;
10646     }
10647   }
10648   if ((!AStmt && !DependFound) || ErrorFound)
10649     return StmtError();
10650 
10651   // OpenMP 5.0, 2.17.9, ordered Construct, Restrictions.
10652   // During execution of an iteration of a worksharing-loop or a loop nest
10653   // within a worksharing-loop, simd, or worksharing-loop SIMD region, a thread
10654   // must not execute more than one ordered region corresponding to an ordered
10655   // construct without a depend clause.
10656   if (!DependFound) {
10657     if (DSAStack->doesParentHasOrderedDirective()) {
10658       Diag(StartLoc, diag::err_omp_several_directives_in_region) << "ordered";
10659       Diag(DSAStack->getParentOrderedDirectiveLoc(),
10660            diag::note_omp_previous_directive)
10661           << "ordered";
10662       return StmtError();
10663     }
10664     DSAStack->setParentHasOrderedDirective(StartLoc);
10665   }
10666 
10667   if (AStmt) {
10668     assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
10669 
10670     setFunctionHasBranchProtectedScope();
10671   }
10672 
10673   return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
10674 }
10675 
10676 namespace {
10677 /// Helper class for checking expression in 'omp atomic [update]'
10678 /// construct.
10679 class OpenMPAtomicUpdateChecker {
10680   /// Error results for atomic update expressions.
10681   enum ExprAnalysisErrorCode {
10682     /// A statement is not an expression statement.
10683     NotAnExpression,
10684     /// Expression is not builtin binary or unary operation.
10685     NotABinaryOrUnaryExpression,
10686     /// Unary operation is not post-/pre- increment/decrement operation.
10687     NotAnUnaryIncDecExpression,
10688     /// An expression is not of scalar type.
10689     NotAScalarType,
10690     /// A binary operation is not an assignment operation.
10691     NotAnAssignmentOp,
10692     /// RHS part of the binary operation is not a binary expression.
10693     NotABinaryExpression,
10694     /// RHS part is not additive/multiplicative/shift/biwise binary
10695     /// expression.
10696     NotABinaryOperator,
10697     /// RHS binary operation does not have reference to the updated LHS
10698     /// part.
10699     NotAnUpdateExpression,
10700     /// No errors is found.
10701     NoError
10702   };
10703   /// Reference to Sema.
10704   Sema &SemaRef;
10705   /// A location for note diagnostics (when error is found).
10706   SourceLocation NoteLoc;
10707   /// 'x' lvalue part of the source atomic expression.
10708   Expr *X;
10709   /// 'expr' rvalue part of the source atomic expression.
10710   Expr *E;
10711   /// Helper expression of the form
10712   /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
10713   /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
10714   Expr *UpdateExpr;
10715   /// Is 'x' a LHS in a RHS part of full update expression. It is
10716   /// important for non-associative operations.
10717   bool IsXLHSInRHSPart;
10718   BinaryOperatorKind Op;
10719   SourceLocation OpLoc;
10720   /// true if the source expression is a postfix unary operation, false
10721   /// if it is a prefix unary operation.
10722   bool IsPostfixUpdate;
10723 
10724 public:
10725   OpenMPAtomicUpdateChecker(Sema &SemaRef)
10726       : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
10727         IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
10728   /// Check specified statement that it is suitable for 'atomic update'
10729   /// constructs and extract 'x', 'expr' and Operation from the original
10730   /// expression. If DiagId and NoteId == 0, then only check is performed
10731   /// without error notification.
10732   /// \param DiagId Diagnostic which should be emitted if error is found.
10733   /// \param NoteId Diagnostic note for the main error message.
10734   /// \return true if statement is not an update expression, false otherwise.
10735   bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
10736   /// Return the 'x' lvalue part of the source atomic expression.
10737   Expr *getX() const { return X; }
10738   /// Return the 'expr' rvalue part of the source atomic expression.
10739   Expr *getExpr() const { return E; }
10740   /// Return the update expression used in calculation of the updated
10741   /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
10742   /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
10743   Expr *getUpdateExpr() const { return UpdateExpr; }
10744   /// Return true if 'x' is LHS in RHS part of full update expression,
10745   /// false otherwise.
10746   bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
10747 
10748   /// true if the source expression is a postfix unary operation, false
10749   /// if it is a prefix unary operation.
10750   bool isPostfixUpdate() const { return IsPostfixUpdate; }
10751 
10752 private:
10753   bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
10754                             unsigned NoteId = 0);
10755 };
10756 } // namespace
10757 
10758 bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
10759     BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
10760   ExprAnalysisErrorCode ErrorFound = NoError;
10761   SourceLocation ErrorLoc, NoteLoc;
10762   SourceRange ErrorRange, NoteRange;
10763   // Allowed constructs are:
10764   //  x = x binop expr;
10765   //  x = expr binop x;
10766   if (AtomicBinOp->getOpcode() == BO_Assign) {
10767     X = AtomicBinOp->getLHS();
10768     if (const auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
10769             AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
10770       if (AtomicInnerBinOp->isMultiplicativeOp() ||
10771           AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
10772           AtomicInnerBinOp->isBitwiseOp()) {
10773         Op = AtomicInnerBinOp->getOpcode();
10774         OpLoc = AtomicInnerBinOp->getOperatorLoc();
10775         Expr *LHS = AtomicInnerBinOp->getLHS();
10776         Expr *RHS = AtomicInnerBinOp->getRHS();
10777         llvm::FoldingSetNodeID XId, LHSId, RHSId;
10778         X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
10779                                           /*Canonical=*/true);
10780         LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
10781                                             /*Canonical=*/true);
10782         RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
10783                                             /*Canonical=*/true);
10784         if (XId == LHSId) {
10785           E = RHS;
10786           IsXLHSInRHSPart = true;
10787         } else if (XId == RHSId) {
10788           E = LHS;
10789           IsXLHSInRHSPart = false;
10790         } else {
10791           ErrorLoc = AtomicInnerBinOp->getExprLoc();
10792           ErrorRange = AtomicInnerBinOp->getSourceRange();
10793           NoteLoc = X->getExprLoc();
10794           NoteRange = X->getSourceRange();
10795           ErrorFound = NotAnUpdateExpression;
10796         }
10797       } else {
10798         ErrorLoc = AtomicInnerBinOp->getExprLoc();
10799         ErrorRange = AtomicInnerBinOp->getSourceRange();
10800         NoteLoc = AtomicInnerBinOp->getOperatorLoc();
10801         NoteRange = SourceRange(NoteLoc, NoteLoc);
10802         ErrorFound = NotABinaryOperator;
10803       }
10804     } else {
10805       NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
10806       NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
10807       ErrorFound = NotABinaryExpression;
10808     }
10809   } else {
10810     ErrorLoc = AtomicBinOp->getExprLoc();
10811     ErrorRange = AtomicBinOp->getSourceRange();
10812     NoteLoc = AtomicBinOp->getOperatorLoc();
10813     NoteRange = SourceRange(NoteLoc, NoteLoc);
10814     ErrorFound = NotAnAssignmentOp;
10815   }
10816   if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
10817     SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
10818     SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
10819     return true;
10820   }
10821   if (SemaRef.CurContext->isDependentContext())
10822     E = X = UpdateExpr = nullptr;
10823   return ErrorFound != NoError;
10824 }
10825 
10826 bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
10827                                                unsigned NoteId) {
10828   ExprAnalysisErrorCode ErrorFound = NoError;
10829   SourceLocation ErrorLoc, NoteLoc;
10830   SourceRange ErrorRange, NoteRange;
10831   // Allowed constructs are:
10832   //  x++;
10833   //  x--;
10834   //  ++x;
10835   //  --x;
10836   //  x binop= expr;
10837   //  x = x binop expr;
10838   //  x = expr binop x;
10839   if (auto *AtomicBody = dyn_cast<Expr>(S)) {
10840     AtomicBody = AtomicBody->IgnoreParenImpCasts();
10841     if (AtomicBody->getType()->isScalarType() ||
10842         AtomicBody->isInstantiationDependent()) {
10843       if (const auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
10844               AtomicBody->IgnoreParenImpCasts())) {
10845         // Check for Compound Assignment Operation
10846         Op = BinaryOperator::getOpForCompoundAssignment(
10847             AtomicCompAssignOp->getOpcode());
10848         OpLoc = AtomicCompAssignOp->getOperatorLoc();
10849         E = AtomicCompAssignOp->getRHS();
10850         X = AtomicCompAssignOp->getLHS()->IgnoreParens();
10851         IsXLHSInRHSPart = true;
10852       } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
10853                      AtomicBody->IgnoreParenImpCasts())) {
10854         // Check for Binary Operation
10855         if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
10856           return true;
10857       } else if (const auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
10858                      AtomicBody->IgnoreParenImpCasts())) {
10859         // Check for Unary Operation
10860         if (AtomicUnaryOp->isIncrementDecrementOp()) {
10861           IsPostfixUpdate = AtomicUnaryOp->isPostfix();
10862           Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
10863           OpLoc = AtomicUnaryOp->getOperatorLoc();
10864           X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
10865           E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
10866           IsXLHSInRHSPart = true;
10867         } else {
10868           ErrorFound = NotAnUnaryIncDecExpression;
10869           ErrorLoc = AtomicUnaryOp->getExprLoc();
10870           ErrorRange = AtomicUnaryOp->getSourceRange();
10871           NoteLoc = AtomicUnaryOp->getOperatorLoc();
10872           NoteRange = SourceRange(NoteLoc, NoteLoc);
10873         }
10874       } else if (!AtomicBody->isInstantiationDependent()) {
10875         ErrorFound = NotABinaryOrUnaryExpression;
10876         NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
10877         NoteRange = ErrorRange = AtomicBody->getSourceRange();
10878       }
10879     } else {
10880       ErrorFound = NotAScalarType;
10881       NoteLoc = ErrorLoc = AtomicBody->getBeginLoc();
10882       NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
10883     }
10884   } else {
10885     ErrorFound = NotAnExpression;
10886     NoteLoc = ErrorLoc = S->getBeginLoc();
10887     NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
10888   }
10889   if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
10890     SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
10891     SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
10892     return true;
10893   }
10894   if (SemaRef.CurContext->isDependentContext())
10895     E = X = UpdateExpr = nullptr;
10896   if (ErrorFound == NoError && E && X) {
10897     // Build an update expression of form 'OpaqueValueExpr(x) binop
10898     // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
10899     // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
10900     auto *OVEX = new (SemaRef.getASTContext())
10901         OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_PRValue);
10902     auto *OVEExpr = new (SemaRef.getASTContext())
10903         OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_PRValue);
10904     ExprResult Update =
10905         SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
10906                                    IsXLHSInRHSPart ? OVEExpr : OVEX);
10907     if (Update.isInvalid())
10908       return true;
10909     Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
10910                                                Sema::AA_Casting);
10911     if (Update.isInvalid())
10912       return true;
10913     UpdateExpr = Update.get();
10914   }
10915   return ErrorFound != NoError;
10916 }
10917 
10918 StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
10919                                             Stmt *AStmt,
10920                                             SourceLocation StartLoc,
10921                                             SourceLocation EndLoc) {
10922   // Register location of the first atomic directive.
10923   DSAStack->addAtomicDirectiveLoc(StartLoc);
10924   if (!AStmt)
10925     return StmtError();
10926 
10927   // 1.2.2 OpenMP Language Terminology
10928   // Structured block - An executable statement with a single entry at the
10929   // top and a single exit at the bottom.
10930   // The point of exit cannot be a branch out of the structured block.
10931   // longjmp() and throw() must not violate the entry/exit criteria.
10932   OpenMPClauseKind AtomicKind = OMPC_unknown;
10933   SourceLocation AtomicKindLoc;
10934   OpenMPClauseKind MemOrderKind = OMPC_unknown;
10935   SourceLocation MemOrderLoc;
10936   for (const OMPClause *C : Clauses) {
10937     if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
10938         C->getClauseKind() == OMPC_update ||
10939         C->getClauseKind() == OMPC_capture) {
10940       if (AtomicKind != OMPC_unknown) {
10941         Diag(C->getBeginLoc(), diag::err_omp_atomic_several_clauses)
10942             << SourceRange(C->getBeginLoc(), C->getEndLoc());
10943         Diag(AtomicKindLoc, diag::note_omp_previous_mem_order_clause)
10944             << getOpenMPClauseName(AtomicKind);
10945       } else {
10946         AtomicKind = C->getClauseKind();
10947         AtomicKindLoc = C->getBeginLoc();
10948       }
10949     }
10950     if (C->getClauseKind() == OMPC_seq_cst ||
10951         C->getClauseKind() == OMPC_acq_rel ||
10952         C->getClauseKind() == OMPC_acquire ||
10953         C->getClauseKind() == OMPC_release ||
10954         C->getClauseKind() == OMPC_relaxed) {
10955       if (MemOrderKind != OMPC_unknown) {
10956         Diag(C->getBeginLoc(), diag::err_omp_several_mem_order_clauses)
10957             << getOpenMPDirectiveName(OMPD_atomic) << 0
10958             << SourceRange(C->getBeginLoc(), C->getEndLoc());
10959         Diag(MemOrderLoc, diag::note_omp_previous_mem_order_clause)
10960             << getOpenMPClauseName(MemOrderKind);
10961       } else {
10962         MemOrderKind = C->getClauseKind();
10963         MemOrderLoc = C->getBeginLoc();
10964       }
10965     }
10966   }
10967   // OpenMP 5.0, 2.17.7 atomic Construct, Restrictions
10968   // If atomic-clause is read then memory-order-clause must not be acq_rel or
10969   // release.
10970   // If atomic-clause is write then memory-order-clause must not be acq_rel or
10971   // acquire.
10972   // If atomic-clause is update or not present then memory-order-clause must not
10973   // be acq_rel or acquire.
10974   if ((AtomicKind == OMPC_read &&
10975        (MemOrderKind == OMPC_acq_rel || MemOrderKind == OMPC_release)) ||
10976       ((AtomicKind == OMPC_write || AtomicKind == OMPC_update ||
10977         AtomicKind == OMPC_unknown) &&
10978        (MemOrderKind == OMPC_acq_rel || MemOrderKind == OMPC_acquire))) {
10979     SourceLocation Loc = AtomicKindLoc;
10980     if (AtomicKind == OMPC_unknown)
10981       Loc = StartLoc;
10982     Diag(Loc, diag::err_omp_atomic_incompatible_mem_order_clause)
10983         << getOpenMPClauseName(AtomicKind)
10984         << (AtomicKind == OMPC_unknown ? 1 : 0)
10985         << getOpenMPClauseName(MemOrderKind);
10986     Diag(MemOrderLoc, diag::note_omp_previous_mem_order_clause)
10987         << getOpenMPClauseName(MemOrderKind);
10988   }
10989 
10990   Stmt *Body = AStmt;
10991   if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
10992     Body = EWC->getSubExpr();
10993 
10994   Expr *X = nullptr;
10995   Expr *V = nullptr;
10996   Expr *E = nullptr;
10997   Expr *UE = nullptr;
10998   bool IsXLHSInRHSPart = false;
10999   bool IsPostfixUpdate = false;
11000   // OpenMP [2.12.6, atomic Construct]
11001   // In the next expressions:
11002   // * x and v (as applicable) are both l-value expressions with scalar type.
11003   // * During the execution of an atomic region, multiple syntactic
11004   // occurrences of x must designate the same storage location.
11005   // * Neither of v and expr (as applicable) may access the storage location
11006   // designated by x.
11007   // * Neither of x and expr (as applicable) may access the storage location
11008   // designated by v.
11009   // * expr is an expression with scalar type.
11010   // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
11011   // * binop, binop=, ++, and -- are not overloaded operators.
11012   // * The expression x binop expr must be numerically equivalent to x binop
11013   // (expr). This requirement is satisfied if the operators in expr have
11014   // precedence greater than binop, or by using parentheses around expr or
11015   // subexpressions of expr.
11016   // * The expression expr binop x must be numerically equivalent to (expr)
11017   // binop x. This requirement is satisfied if the operators in expr have
11018   // precedence equal to or greater than binop, or by using parentheses around
11019   // expr or subexpressions of expr.
11020   // * For forms that allow multiple occurrences of x, the number of times
11021   // that x is evaluated is unspecified.
11022   if (AtomicKind == OMPC_read) {
11023     enum {
11024       NotAnExpression,
11025       NotAnAssignmentOp,
11026       NotAScalarType,
11027       NotAnLValue,
11028       NoError
11029     } ErrorFound = NoError;
11030     SourceLocation ErrorLoc, NoteLoc;
11031     SourceRange ErrorRange, NoteRange;
11032     // If clause is read:
11033     //  v = x;
11034     if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
11035       const auto *AtomicBinOp =
11036           dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
11037       if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
11038         X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
11039         V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
11040         if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
11041             (V->isInstantiationDependent() || V->getType()->isScalarType())) {
11042           if (!X->isLValue() || !V->isLValue()) {
11043             const Expr *NotLValueExpr = X->isLValue() ? V : X;
11044             ErrorFound = NotAnLValue;
11045             ErrorLoc = AtomicBinOp->getExprLoc();
11046             ErrorRange = AtomicBinOp->getSourceRange();
11047             NoteLoc = NotLValueExpr->getExprLoc();
11048             NoteRange = NotLValueExpr->getSourceRange();
11049           }
11050         } else if (!X->isInstantiationDependent() ||
11051                    !V->isInstantiationDependent()) {
11052           const Expr *NotScalarExpr =
11053               (X->isInstantiationDependent() || X->getType()->isScalarType())
11054                   ? V
11055                   : X;
11056           ErrorFound = NotAScalarType;
11057           ErrorLoc = AtomicBinOp->getExprLoc();
11058           ErrorRange = AtomicBinOp->getSourceRange();
11059           NoteLoc = NotScalarExpr->getExprLoc();
11060           NoteRange = NotScalarExpr->getSourceRange();
11061         }
11062       } else if (!AtomicBody->isInstantiationDependent()) {
11063         ErrorFound = NotAnAssignmentOp;
11064         ErrorLoc = AtomicBody->getExprLoc();
11065         ErrorRange = AtomicBody->getSourceRange();
11066         NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
11067                               : AtomicBody->getExprLoc();
11068         NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
11069                                 : AtomicBody->getSourceRange();
11070       }
11071     } else {
11072       ErrorFound = NotAnExpression;
11073       NoteLoc = ErrorLoc = Body->getBeginLoc();
11074       NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
11075     }
11076     if (ErrorFound != NoError) {
11077       Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
11078           << ErrorRange;
11079       Diag(NoteLoc, diag::note_omp_atomic_read_write)
11080           << ErrorFound << NoteRange;
11081       return StmtError();
11082     }
11083     if (CurContext->isDependentContext())
11084       V = X = nullptr;
11085   } else if (AtomicKind == OMPC_write) {
11086     enum {
11087       NotAnExpression,
11088       NotAnAssignmentOp,
11089       NotAScalarType,
11090       NotAnLValue,
11091       NoError
11092     } ErrorFound = NoError;
11093     SourceLocation ErrorLoc, NoteLoc;
11094     SourceRange ErrorRange, NoteRange;
11095     // If clause is write:
11096     //  x = expr;
11097     if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
11098       const auto *AtomicBinOp =
11099           dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
11100       if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
11101         X = AtomicBinOp->getLHS();
11102         E = AtomicBinOp->getRHS();
11103         if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
11104             (E->isInstantiationDependent() || E->getType()->isScalarType())) {
11105           if (!X->isLValue()) {
11106             ErrorFound = NotAnLValue;
11107             ErrorLoc = AtomicBinOp->getExprLoc();
11108             ErrorRange = AtomicBinOp->getSourceRange();
11109             NoteLoc = X->getExprLoc();
11110             NoteRange = X->getSourceRange();
11111           }
11112         } else if (!X->isInstantiationDependent() ||
11113                    !E->isInstantiationDependent()) {
11114           const Expr *NotScalarExpr =
11115               (X->isInstantiationDependent() || X->getType()->isScalarType())
11116                   ? E
11117                   : X;
11118           ErrorFound = NotAScalarType;
11119           ErrorLoc = AtomicBinOp->getExprLoc();
11120           ErrorRange = AtomicBinOp->getSourceRange();
11121           NoteLoc = NotScalarExpr->getExprLoc();
11122           NoteRange = NotScalarExpr->getSourceRange();
11123         }
11124       } else if (!AtomicBody->isInstantiationDependent()) {
11125         ErrorFound = NotAnAssignmentOp;
11126         ErrorLoc = AtomicBody->getExprLoc();
11127         ErrorRange = AtomicBody->getSourceRange();
11128         NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
11129                               : AtomicBody->getExprLoc();
11130         NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
11131                                 : AtomicBody->getSourceRange();
11132       }
11133     } else {
11134       ErrorFound = NotAnExpression;
11135       NoteLoc = ErrorLoc = Body->getBeginLoc();
11136       NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
11137     }
11138     if (ErrorFound != NoError) {
11139       Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
11140           << ErrorRange;
11141       Diag(NoteLoc, diag::note_omp_atomic_read_write)
11142           << ErrorFound << NoteRange;
11143       return StmtError();
11144     }
11145     if (CurContext->isDependentContext())
11146       E = X = nullptr;
11147   } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
11148     // If clause is update:
11149     //  x++;
11150     //  x--;
11151     //  ++x;
11152     //  --x;
11153     //  x binop= expr;
11154     //  x = x binop expr;
11155     //  x = expr binop x;
11156     OpenMPAtomicUpdateChecker Checker(*this);
11157     if (Checker.checkStatement(
11158             Body,
11159             (AtomicKind == OMPC_update)
11160                 ? diag::err_omp_atomic_update_not_expression_statement
11161                 : diag::err_omp_atomic_not_expression_statement,
11162             diag::note_omp_atomic_update))
11163       return StmtError();
11164     if (!CurContext->isDependentContext()) {
11165       E = Checker.getExpr();
11166       X = Checker.getX();
11167       UE = Checker.getUpdateExpr();
11168       IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
11169     }
11170   } else if (AtomicKind == OMPC_capture) {
11171     enum {
11172       NotAnAssignmentOp,
11173       NotACompoundStatement,
11174       NotTwoSubstatements,
11175       NotASpecificExpression,
11176       NoError
11177     } ErrorFound = NoError;
11178     SourceLocation ErrorLoc, NoteLoc;
11179     SourceRange ErrorRange, NoteRange;
11180     if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
11181       // If clause is a capture:
11182       //  v = x++;
11183       //  v = x--;
11184       //  v = ++x;
11185       //  v = --x;
11186       //  v = x binop= expr;
11187       //  v = x = x binop expr;
11188       //  v = x = expr binop x;
11189       const auto *AtomicBinOp =
11190           dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
11191       if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
11192         V = AtomicBinOp->getLHS();
11193         Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
11194         OpenMPAtomicUpdateChecker Checker(*this);
11195         if (Checker.checkStatement(
11196                 Body, diag::err_omp_atomic_capture_not_expression_statement,
11197                 diag::note_omp_atomic_update))
11198           return StmtError();
11199         E = Checker.getExpr();
11200         X = Checker.getX();
11201         UE = Checker.getUpdateExpr();
11202         IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
11203         IsPostfixUpdate = Checker.isPostfixUpdate();
11204       } else if (!AtomicBody->isInstantiationDependent()) {
11205         ErrorLoc = AtomicBody->getExprLoc();
11206         ErrorRange = AtomicBody->getSourceRange();
11207         NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
11208                               : AtomicBody->getExprLoc();
11209         NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
11210                                 : AtomicBody->getSourceRange();
11211         ErrorFound = NotAnAssignmentOp;
11212       }
11213       if (ErrorFound != NoError) {
11214         Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
11215             << ErrorRange;
11216         Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
11217         return StmtError();
11218       }
11219       if (CurContext->isDependentContext())
11220         UE = V = E = X = nullptr;
11221     } else {
11222       // If clause is a capture:
11223       //  { v = x; x = expr; }
11224       //  { v = x; x++; }
11225       //  { v = x; x--; }
11226       //  { v = x; ++x; }
11227       //  { v = x; --x; }
11228       //  { v = x; x binop= expr; }
11229       //  { v = x; x = x binop expr; }
11230       //  { v = x; x = expr binop x; }
11231       //  { x++; v = x; }
11232       //  { x--; v = x; }
11233       //  { ++x; v = x; }
11234       //  { --x; v = x; }
11235       //  { x binop= expr; v = x; }
11236       //  { x = x binop expr; v = x; }
11237       //  { x = expr binop x; v = x; }
11238       if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
11239         // Check that this is { expr1; expr2; }
11240         if (CS->size() == 2) {
11241           Stmt *First = CS->body_front();
11242           Stmt *Second = CS->body_back();
11243           if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
11244             First = EWC->getSubExpr()->IgnoreParenImpCasts();
11245           if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
11246             Second = EWC->getSubExpr()->IgnoreParenImpCasts();
11247           // Need to find what subexpression is 'v' and what is 'x'.
11248           OpenMPAtomicUpdateChecker Checker(*this);
11249           bool IsUpdateExprFound = !Checker.checkStatement(Second);
11250           BinaryOperator *BinOp = nullptr;
11251           if (IsUpdateExprFound) {
11252             BinOp = dyn_cast<BinaryOperator>(First);
11253             IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
11254           }
11255           if (IsUpdateExprFound && !CurContext->isDependentContext()) {
11256             //  { v = x; x++; }
11257             //  { v = x; x--; }
11258             //  { v = x; ++x; }
11259             //  { v = x; --x; }
11260             //  { v = x; x binop= expr; }
11261             //  { v = x; x = x binop expr; }
11262             //  { v = x; x = expr binop x; }
11263             // Check that the first expression has form v = x.
11264             Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
11265             llvm::FoldingSetNodeID XId, PossibleXId;
11266             Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
11267             PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
11268             IsUpdateExprFound = XId == PossibleXId;
11269             if (IsUpdateExprFound) {
11270               V = BinOp->getLHS();
11271               X = Checker.getX();
11272               E = Checker.getExpr();
11273               UE = Checker.getUpdateExpr();
11274               IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
11275               IsPostfixUpdate = true;
11276             }
11277           }
11278           if (!IsUpdateExprFound) {
11279             IsUpdateExprFound = !Checker.checkStatement(First);
11280             BinOp = nullptr;
11281             if (IsUpdateExprFound) {
11282               BinOp = dyn_cast<BinaryOperator>(Second);
11283               IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
11284             }
11285             if (IsUpdateExprFound && !CurContext->isDependentContext()) {
11286               //  { x++; v = x; }
11287               //  { x--; v = x; }
11288               //  { ++x; v = x; }
11289               //  { --x; v = x; }
11290               //  { x binop= expr; v = x; }
11291               //  { x = x binop expr; v = x; }
11292               //  { x = expr binop x; v = x; }
11293               // Check that the second expression has form v = x.
11294               Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
11295               llvm::FoldingSetNodeID XId, PossibleXId;
11296               Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
11297               PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
11298               IsUpdateExprFound = XId == PossibleXId;
11299               if (IsUpdateExprFound) {
11300                 V = BinOp->getLHS();
11301                 X = Checker.getX();
11302                 E = Checker.getExpr();
11303                 UE = Checker.getUpdateExpr();
11304                 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
11305                 IsPostfixUpdate = false;
11306               }
11307             }
11308           }
11309           if (!IsUpdateExprFound) {
11310             //  { v = x; x = expr; }
11311             auto *FirstExpr = dyn_cast<Expr>(First);
11312             auto *SecondExpr = dyn_cast<Expr>(Second);
11313             if (!FirstExpr || !SecondExpr ||
11314                 !(FirstExpr->isInstantiationDependent() ||
11315                   SecondExpr->isInstantiationDependent())) {
11316               auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
11317               if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
11318                 ErrorFound = NotAnAssignmentOp;
11319                 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
11320                                                 : First->getBeginLoc();
11321                 NoteRange = ErrorRange = FirstBinOp
11322                                              ? FirstBinOp->getSourceRange()
11323                                              : SourceRange(ErrorLoc, ErrorLoc);
11324               } else {
11325                 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
11326                 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
11327                   ErrorFound = NotAnAssignmentOp;
11328                   NoteLoc = ErrorLoc = SecondBinOp
11329                                            ? SecondBinOp->getOperatorLoc()
11330                                            : Second->getBeginLoc();
11331                   NoteRange = ErrorRange =
11332                       SecondBinOp ? SecondBinOp->getSourceRange()
11333                                   : SourceRange(ErrorLoc, ErrorLoc);
11334                 } else {
11335                   Expr *PossibleXRHSInFirst =
11336                       FirstBinOp->getRHS()->IgnoreParenImpCasts();
11337                   Expr *PossibleXLHSInSecond =
11338                       SecondBinOp->getLHS()->IgnoreParenImpCasts();
11339                   llvm::FoldingSetNodeID X1Id, X2Id;
11340                   PossibleXRHSInFirst->Profile(X1Id, Context,
11341                                                /*Canonical=*/true);
11342                   PossibleXLHSInSecond->Profile(X2Id, Context,
11343                                                 /*Canonical=*/true);
11344                   IsUpdateExprFound = X1Id == X2Id;
11345                   if (IsUpdateExprFound) {
11346                     V = FirstBinOp->getLHS();
11347                     X = SecondBinOp->getLHS();
11348                     E = SecondBinOp->getRHS();
11349                     UE = nullptr;
11350                     IsXLHSInRHSPart = false;
11351                     IsPostfixUpdate = true;
11352                   } else {
11353                     ErrorFound = NotASpecificExpression;
11354                     ErrorLoc = FirstBinOp->getExprLoc();
11355                     ErrorRange = FirstBinOp->getSourceRange();
11356                     NoteLoc = SecondBinOp->getLHS()->getExprLoc();
11357                     NoteRange = SecondBinOp->getRHS()->getSourceRange();
11358                   }
11359                 }
11360               }
11361             }
11362           }
11363         } else {
11364           NoteLoc = ErrorLoc = Body->getBeginLoc();
11365           NoteRange = ErrorRange =
11366               SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
11367           ErrorFound = NotTwoSubstatements;
11368         }
11369       } else {
11370         NoteLoc = ErrorLoc = Body->getBeginLoc();
11371         NoteRange = ErrorRange =
11372             SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
11373         ErrorFound = NotACompoundStatement;
11374       }
11375       if (ErrorFound != NoError) {
11376         Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
11377             << ErrorRange;
11378         Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
11379         return StmtError();
11380       }
11381       if (CurContext->isDependentContext())
11382         UE = V = E = X = nullptr;
11383     }
11384   }
11385 
11386   setFunctionHasBranchProtectedScope();
11387 
11388   return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
11389                                     X, V, E, UE, IsXLHSInRHSPart,
11390                                     IsPostfixUpdate);
11391 }
11392 
11393 StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
11394                                             Stmt *AStmt,
11395                                             SourceLocation StartLoc,
11396                                             SourceLocation EndLoc) {
11397   if (!AStmt)
11398     return StmtError();
11399 
11400   auto *CS = cast<CapturedStmt>(AStmt);
11401   // 1.2.2 OpenMP Language Terminology
11402   // Structured block - An executable statement with a single entry at the
11403   // top and a single exit at the bottom.
11404   // The point of exit cannot be a branch out of the structured block.
11405   // longjmp() and throw() must not violate the entry/exit criteria.
11406   CS->getCapturedDecl()->setNothrow();
11407   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target);
11408        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11409     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11410     // 1.2.2 OpenMP Language Terminology
11411     // Structured block - An executable statement with a single entry at the
11412     // top and a single exit at the bottom.
11413     // The point of exit cannot be a branch out of the structured block.
11414     // longjmp() and throw() must not violate the entry/exit criteria.
11415     CS->getCapturedDecl()->setNothrow();
11416   }
11417 
11418   // OpenMP [2.16, Nesting of Regions]
11419   // If specified, a teams construct must be contained within a target
11420   // construct. That target construct must contain no statements or directives
11421   // outside of the teams construct.
11422   if (DSAStack->hasInnerTeamsRegion()) {
11423     const Stmt *S = CS->IgnoreContainers(/*IgnoreCaptured=*/true);
11424     bool OMPTeamsFound = true;
11425     if (const auto *CS = dyn_cast<CompoundStmt>(S)) {
11426       auto I = CS->body_begin();
11427       while (I != CS->body_end()) {
11428         const auto *OED = dyn_cast<OMPExecutableDirective>(*I);
11429         if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind()) ||
11430             OMPTeamsFound) {
11431 
11432           OMPTeamsFound = false;
11433           break;
11434         }
11435         ++I;
11436       }
11437       assert(I != CS->body_end() && "Not found statement");
11438       S = *I;
11439     } else {
11440       const auto *OED = dyn_cast<OMPExecutableDirective>(S);
11441       OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
11442     }
11443     if (!OMPTeamsFound) {
11444       Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
11445       Diag(DSAStack->getInnerTeamsRegionLoc(),
11446            diag::note_omp_nested_teams_construct_here);
11447       Diag(S->getBeginLoc(), diag::note_omp_nested_statement_here)
11448           << isa<OMPExecutableDirective>(S);
11449       return StmtError();
11450     }
11451   }
11452 
11453   setFunctionHasBranchProtectedScope();
11454 
11455   return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
11456 }
11457 
11458 StmtResult
11459 Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
11460                                          Stmt *AStmt, SourceLocation StartLoc,
11461                                          SourceLocation EndLoc) {
11462   if (!AStmt)
11463     return StmtError();
11464 
11465   auto *CS = cast<CapturedStmt>(AStmt);
11466   // 1.2.2 OpenMP Language Terminology
11467   // Structured block - An executable statement with a single entry at the
11468   // top and a single exit at the bottom.
11469   // The point of exit cannot be a branch out of the structured block.
11470   // longjmp() and throw() must not violate the entry/exit criteria.
11471   CS->getCapturedDecl()->setNothrow();
11472   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel);
11473        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11474     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11475     // 1.2.2 OpenMP Language Terminology
11476     // Structured block - An executable statement with a single entry at the
11477     // top and a single exit at the bottom.
11478     // The point of exit cannot be a branch out of the structured block.
11479     // longjmp() and throw() must not violate the entry/exit criteria.
11480     CS->getCapturedDecl()->setNothrow();
11481   }
11482 
11483   setFunctionHasBranchProtectedScope();
11484 
11485   return OMPTargetParallelDirective::Create(
11486       Context, StartLoc, EndLoc, Clauses, AStmt,
11487       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
11488 }
11489 
11490 StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
11491     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11492     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11493   if (!AStmt)
11494     return StmtError();
11495 
11496   auto *CS = cast<CapturedStmt>(AStmt);
11497   // 1.2.2 OpenMP Language Terminology
11498   // Structured block - An executable statement with a single entry at the
11499   // top and a single exit at the bottom.
11500   // The point of exit cannot be a branch out of the structured block.
11501   // longjmp() and throw() must not violate the entry/exit criteria.
11502   CS->getCapturedDecl()->setNothrow();
11503   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
11504        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11505     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11506     // 1.2.2 OpenMP Language Terminology
11507     // Structured block - An executable statement with a single entry at the
11508     // top and a single exit at the bottom.
11509     // The point of exit cannot be a branch out of the structured block.
11510     // longjmp() and throw() must not violate the entry/exit criteria.
11511     CS->getCapturedDecl()->setNothrow();
11512   }
11513 
11514   OMPLoopBasedDirective::HelperExprs B;
11515   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
11516   // define the nested loops number.
11517   unsigned NestedLoopCount =
11518       checkOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
11519                       getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
11520                       VarsWithImplicitDSA, B);
11521   if (NestedLoopCount == 0)
11522     return StmtError();
11523 
11524   assert((CurContext->isDependentContext() || B.builtAll()) &&
11525          "omp target parallel for loop exprs were not built");
11526 
11527   if (!CurContext->isDependentContext()) {
11528     // Finalize the clauses that need pre-built expressions for CodeGen.
11529     for (OMPClause *C : Clauses) {
11530       if (auto *LC = dyn_cast<OMPLinearClause>(C))
11531         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
11532                                      B.NumIterations, *this, CurScope,
11533                                      DSAStack))
11534           return StmtError();
11535     }
11536   }
11537 
11538   setFunctionHasBranchProtectedScope();
11539   return OMPTargetParallelForDirective::Create(
11540       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
11541       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
11542 }
11543 
11544 /// Check for existence of a map clause in the list of clauses.
11545 static bool hasClauses(ArrayRef<OMPClause *> Clauses,
11546                        const OpenMPClauseKind K) {
11547   return llvm::any_of(
11548       Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; });
11549 }
11550 
11551 template <typename... Params>
11552 static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K,
11553                        const Params... ClauseTypes) {
11554   return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...);
11555 }
11556 
11557 StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
11558                                                 Stmt *AStmt,
11559                                                 SourceLocation StartLoc,
11560                                                 SourceLocation EndLoc) {
11561   if (!AStmt)
11562     return StmtError();
11563 
11564   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
11565 
11566   // OpenMP [2.12.2, target data Construct, Restrictions]
11567   // At least one map, use_device_addr or use_device_ptr clause must appear on
11568   // the directive.
11569   if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr) &&
11570       (LangOpts.OpenMP < 50 || !hasClauses(Clauses, OMPC_use_device_addr))) {
11571     StringRef Expected;
11572     if (LangOpts.OpenMP < 50)
11573       Expected = "'map' or 'use_device_ptr'";
11574     else
11575       Expected = "'map', 'use_device_ptr', or 'use_device_addr'";
11576     Diag(StartLoc, diag::err_omp_no_clause_for_directive)
11577         << Expected << getOpenMPDirectiveName(OMPD_target_data);
11578     return StmtError();
11579   }
11580 
11581   setFunctionHasBranchProtectedScope();
11582 
11583   return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
11584                                         AStmt);
11585 }
11586 
11587 StmtResult
11588 Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
11589                                           SourceLocation StartLoc,
11590                                           SourceLocation EndLoc, Stmt *AStmt) {
11591   if (!AStmt)
11592     return StmtError();
11593 
11594   auto *CS = cast<CapturedStmt>(AStmt);
11595   // 1.2.2 OpenMP Language Terminology
11596   // Structured block - An executable statement with a single entry at the
11597   // top and a single exit at the bottom.
11598   // The point of exit cannot be a branch out of the structured block.
11599   // longjmp() and throw() must not violate the entry/exit criteria.
11600   CS->getCapturedDecl()->setNothrow();
11601   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_enter_data);
11602        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11603     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11604     // 1.2.2 OpenMP Language Terminology
11605     // Structured block - An executable statement with a single entry at the
11606     // top and a single exit at the bottom.
11607     // The point of exit cannot be a branch out of the structured block.
11608     // longjmp() and throw() must not violate the entry/exit criteria.
11609     CS->getCapturedDecl()->setNothrow();
11610   }
11611 
11612   // OpenMP [2.10.2, Restrictions, p. 99]
11613   // At least one map clause must appear on the directive.
11614   if (!hasClauses(Clauses, OMPC_map)) {
11615     Diag(StartLoc, diag::err_omp_no_clause_for_directive)
11616         << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data);
11617     return StmtError();
11618   }
11619 
11620   return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
11621                                              AStmt);
11622 }
11623 
11624 StmtResult
11625 Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
11626                                          SourceLocation StartLoc,
11627                                          SourceLocation EndLoc, Stmt *AStmt) {
11628   if (!AStmt)
11629     return StmtError();
11630 
11631   auto *CS = cast<CapturedStmt>(AStmt);
11632   // 1.2.2 OpenMP Language Terminology
11633   // Structured block - An executable statement with a single entry at the
11634   // top and a single exit at the bottom.
11635   // The point of exit cannot be a branch out of the structured block.
11636   // longjmp() and throw() must not violate the entry/exit criteria.
11637   CS->getCapturedDecl()->setNothrow();
11638   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_exit_data);
11639        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11640     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11641     // 1.2.2 OpenMP Language Terminology
11642     // Structured block - An executable statement with a single entry at the
11643     // top and a single exit at the bottom.
11644     // The point of exit cannot be a branch out of the structured block.
11645     // longjmp() and throw() must not violate the entry/exit criteria.
11646     CS->getCapturedDecl()->setNothrow();
11647   }
11648 
11649   // OpenMP [2.10.3, Restrictions, p. 102]
11650   // At least one map clause must appear on the directive.
11651   if (!hasClauses(Clauses, OMPC_map)) {
11652     Diag(StartLoc, diag::err_omp_no_clause_for_directive)
11653         << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data);
11654     return StmtError();
11655   }
11656 
11657   return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
11658                                             AStmt);
11659 }
11660 
11661 StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
11662                                                   SourceLocation StartLoc,
11663                                                   SourceLocation EndLoc,
11664                                                   Stmt *AStmt) {
11665   if (!AStmt)
11666     return StmtError();
11667 
11668   auto *CS = cast<CapturedStmt>(AStmt);
11669   // 1.2.2 OpenMP Language Terminology
11670   // Structured block - An executable statement with a single entry at the
11671   // top and a single exit at the bottom.
11672   // The point of exit cannot be a branch out of the structured block.
11673   // longjmp() and throw() must not violate the entry/exit criteria.
11674   CS->getCapturedDecl()->setNothrow();
11675   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_update);
11676        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11677     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11678     // 1.2.2 OpenMP Language Terminology
11679     // Structured block - An executable statement with a single entry at the
11680     // top and a single exit at the bottom.
11681     // The point of exit cannot be a branch out of the structured block.
11682     // longjmp() and throw() must not violate the entry/exit criteria.
11683     CS->getCapturedDecl()->setNothrow();
11684   }
11685 
11686   if (!hasClauses(Clauses, OMPC_to, OMPC_from)) {
11687     Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
11688     return StmtError();
11689   }
11690   return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses,
11691                                           AStmt);
11692 }
11693 
11694 StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
11695                                            Stmt *AStmt, SourceLocation StartLoc,
11696                                            SourceLocation EndLoc) {
11697   if (!AStmt)
11698     return StmtError();
11699 
11700   auto *CS = cast<CapturedStmt>(AStmt);
11701   // 1.2.2 OpenMP Language Terminology
11702   // Structured block - An executable statement with a single entry at the
11703   // top and a single exit at the bottom.
11704   // The point of exit cannot be a branch out of the structured block.
11705   // longjmp() and throw() must not violate the entry/exit criteria.
11706   CS->getCapturedDecl()->setNothrow();
11707 
11708   setFunctionHasBranchProtectedScope();
11709 
11710   DSAStack->setParentTeamsRegionLoc(StartLoc);
11711 
11712   return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
11713 }
11714 
11715 StmtResult
11716 Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
11717                                             SourceLocation EndLoc,
11718                                             OpenMPDirectiveKind CancelRegion) {
11719   if (DSAStack->isParentNowaitRegion()) {
11720     Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
11721     return StmtError();
11722   }
11723   if (DSAStack->isParentOrderedRegion()) {
11724     Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
11725     return StmtError();
11726   }
11727   return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
11728                                                CancelRegion);
11729 }
11730 
11731 StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
11732                                             SourceLocation StartLoc,
11733                                             SourceLocation EndLoc,
11734                                             OpenMPDirectiveKind CancelRegion) {
11735   if (DSAStack->isParentNowaitRegion()) {
11736     Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
11737     return StmtError();
11738   }
11739   if (DSAStack->isParentOrderedRegion()) {
11740     Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
11741     return StmtError();
11742   }
11743   DSAStack->setParentCancelRegion(/*Cancel=*/true);
11744   return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
11745                                     CancelRegion);
11746 }
11747 
11748 static bool checkReductionClauseWithNogroup(Sema &S,
11749                                             ArrayRef<OMPClause *> Clauses) {
11750   const OMPClause *ReductionClause = nullptr;
11751   const OMPClause *NogroupClause = nullptr;
11752   for (const OMPClause *C : Clauses) {
11753     if (C->getClauseKind() == OMPC_reduction) {
11754       ReductionClause = C;
11755       if (NogroupClause)
11756         break;
11757       continue;
11758     }
11759     if (C->getClauseKind() == OMPC_nogroup) {
11760       NogroupClause = C;
11761       if (ReductionClause)
11762         break;
11763       continue;
11764     }
11765   }
11766   if (ReductionClause && NogroupClause) {
11767     S.Diag(ReductionClause->getBeginLoc(), diag::err_omp_reduction_with_nogroup)
11768         << SourceRange(NogroupClause->getBeginLoc(),
11769                        NogroupClause->getEndLoc());
11770     return true;
11771   }
11772   return false;
11773 }
11774 
11775 StmtResult Sema::ActOnOpenMPTaskLoopDirective(
11776     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11777     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11778   if (!AStmt)
11779     return StmtError();
11780 
11781   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
11782   OMPLoopBasedDirective::HelperExprs B;
11783   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
11784   // define the nested loops number.
11785   unsigned NestedLoopCount =
11786       checkOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
11787                       /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
11788                       VarsWithImplicitDSA, B);
11789   if (NestedLoopCount == 0)
11790     return StmtError();
11791 
11792   assert((CurContext->isDependentContext() || B.builtAll()) &&
11793          "omp for loop exprs were not built");
11794 
11795   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
11796   // The grainsize clause and num_tasks clause are mutually exclusive and may
11797   // not appear on the same taskloop directive.
11798   if (checkMutuallyExclusiveClauses(*this, Clauses,
11799                                     {OMPC_grainsize, OMPC_num_tasks}))
11800     return StmtError();
11801   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
11802   // If a reduction clause is present on the taskloop directive, the nogroup
11803   // clause must not be specified.
11804   if (checkReductionClauseWithNogroup(*this, Clauses))
11805     return StmtError();
11806 
11807   setFunctionHasBranchProtectedScope();
11808   return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
11809                                       NestedLoopCount, Clauses, AStmt, B,
11810                                       DSAStack->isCancelRegion());
11811 }
11812 
11813 StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
11814     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11815     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11816   if (!AStmt)
11817     return StmtError();
11818 
11819   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
11820   OMPLoopBasedDirective::HelperExprs B;
11821   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
11822   // define the nested loops number.
11823   unsigned NestedLoopCount =
11824       checkOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
11825                       /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
11826                       VarsWithImplicitDSA, B);
11827   if (NestedLoopCount == 0)
11828     return StmtError();
11829 
11830   assert((CurContext->isDependentContext() || B.builtAll()) &&
11831          "omp for loop exprs were not built");
11832 
11833   if (!CurContext->isDependentContext()) {
11834     // Finalize the clauses that need pre-built expressions for CodeGen.
11835     for (OMPClause *C : Clauses) {
11836       if (auto *LC = dyn_cast<OMPLinearClause>(C))
11837         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
11838                                      B.NumIterations, *this, CurScope,
11839                                      DSAStack))
11840           return StmtError();
11841     }
11842   }
11843 
11844   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
11845   // The grainsize clause and num_tasks clause are mutually exclusive and may
11846   // not appear on the same taskloop directive.
11847   if (checkMutuallyExclusiveClauses(*this, Clauses,
11848                                     {OMPC_grainsize, OMPC_num_tasks}))
11849     return StmtError();
11850   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
11851   // If a reduction clause is present on the taskloop directive, the nogroup
11852   // clause must not be specified.
11853   if (checkReductionClauseWithNogroup(*this, Clauses))
11854     return StmtError();
11855   if (checkSimdlenSafelenSpecified(*this, Clauses))
11856     return StmtError();
11857 
11858   setFunctionHasBranchProtectedScope();
11859   return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
11860                                           NestedLoopCount, Clauses, AStmt, B);
11861 }
11862 
11863 StmtResult Sema::ActOnOpenMPMasterTaskLoopDirective(
11864     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11865     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11866   if (!AStmt)
11867     return StmtError();
11868 
11869   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
11870   OMPLoopBasedDirective::HelperExprs B;
11871   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
11872   // define the nested loops number.
11873   unsigned NestedLoopCount =
11874       checkOpenMPLoop(OMPD_master_taskloop, getCollapseNumberExpr(Clauses),
11875                       /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
11876                       VarsWithImplicitDSA, B);
11877   if (NestedLoopCount == 0)
11878     return StmtError();
11879 
11880   assert((CurContext->isDependentContext() || B.builtAll()) &&
11881          "omp for loop exprs were not built");
11882 
11883   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
11884   // The grainsize clause and num_tasks clause are mutually exclusive and may
11885   // not appear on the same taskloop directive.
11886   if (checkMutuallyExclusiveClauses(*this, Clauses,
11887                                     {OMPC_grainsize, OMPC_num_tasks}))
11888     return StmtError();
11889   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
11890   // If a reduction clause is present on the taskloop directive, the nogroup
11891   // clause must not be specified.
11892   if (checkReductionClauseWithNogroup(*this, Clauses))
11893     return StmtError();
11894 
11895   setFunctionHasBranchProtectedScope();
11896   return OMPMasterTaskLoopDirective::Create(Context, StartLoc, EndLoc,
11897                                             NestedLoopCount, Clauses, AStmt, B,
11898                                             DSAStack->isCancelRegion());
11899 }
11900 
11901 StmtResult Sema::ActOnOpenMPMasterTaskLoopSimdDirective(
11902     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11903     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11904   if (!AStmt)
11905     return StmtError();
11906 
11907   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
11908   OMPLoopBasedDirective::HelperExprs B;
11909   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
11910   // define the nested loops number.
11911   unsigned NestedLoopCount =
11912       checkOpenMPLoop(OMPD_master_taskloop_simd, getCollapseNumberExpr(Clauses),
11913                       /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
11914                       VarsWithImplicitDSA, B);
11915   if (NestedLoopCount == 0)
11916     return StmtError();
11917 
11918   assert((CurContext->isDependentContext() || B.builtAll()) &&
11919          "omp for loop exprs were not built");
11920 
11921   if (!CurContext->isDependentContext()) {
11922     // Finalize the clauses that need pre-built expressions for CodeGen.
11923     for (OMPClause *C : Clauses) {
11924       if (auto *LC = dyn_cast<OMPLinearClause>(C))
11925         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
11926                                      B.NumIterations, *this, CurScope,
11927                                      DSAStack))
11928           return StmtError();
11929     }
11930   }
11931 
11932   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
11933   // The grainsize clause and num_tasks clause are mutually exclusive and may
11934   // not appear on the same taskloop directive.
11935   if (checkMutuallyExclusiveClauses(*this, Clauses,
11936                                     {OMPC_grainsize, OMPC_num_tasks}))
11937     return StmtError();
11938   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
11939   // If a reduction clause is present on the taskloop directive, the nogroup
11940   // clause must not be specified.
11941   if (checkReductionClauseWithNogroup(*this, Clauses))
11942     return StmtError();
11943   if (checkSimdlenSafelenSpecified(*this, Clauses))
11944     return StmtError();
11945 
11946   setFunctionHasBranchProtectedScope();
11947   return OMPMasterTaskLoopSimdDirective::Create(
11948       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
11949 }
11950 
11951 StmtResult Sema::ActOnOpenMPParallelMasterTaskLoopDirective(
11952     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11953     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11954   if (!AStmt)
11955     return StmtError();
11956 
11957   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
11958   auto *CS = cast<CapturedStmt>(AStmt);
11959   // 1.2.2 OpenMP Language Terminology
11960   // Structured block - An executable statement with a single entry at the
11961   // top and a single exit at the bottom.
11962   // The point of exit cannot be a branch out of the structured block.
11963   // longjmp() and throw() must not violate the entry/exit criteria.
11964   CS->getCapturedDecl()->setNothrow();
11965   for (int ThisCaptureLevel =
11966            getOpenMPCaptureLevels(OMPD_parallel_master_taskloop);
11967        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11968     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11969     // 1.2.2 OpenMP Language Terminology
11970     // Structured block - An executable statement with a single entry at the
11971     // top and a single exit at the bottom.
11972     // The point of exit cannot be a branch out of the structured block.
11973     // longjmp() and throw() must not violate the entry/exit criteria.
11974     CS->getCapturedDecl()->setNothrow();
11975   }
11976 
11977   OMPLoopBasedDirective::HelperExprs B;
11978   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
11979   // define the nested loops number.
11980   unsigned NestedLoopCount = checkOpenMPLoop(
11981       OMPD_parallel_master_taskloop, getCollapseNumberExpr(Clauses),
11982       /*OrderedLoopCountExpr=*/nullptr, CS, *this, *DSAStack,
11983       VarsWithImplicitDSA, B);
11984   if (NestedLoopCount == 0)
11985     return StmtError();
11986 
11987   assert((CurContext->isDependentContext() || B.builtAll()) &&
11988          "omp for loop exprs were not built");
11989 
11990   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
11991   // The grainsize clause and num_tasks clause are mutually exclusive and may
11992   // not appear on the same taskloop directive.
11993   if (checkMutuallyExclusiveClauses(*this, Clauses,
11994                                     {OMPC_grainsize, OMPC_num_tasks}))
11995     return StmtError();
11996   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
11997   // If a reduction clause is present on the taskloop directive, the nogroup
11998   // clause must not be specified.
11999   if (checkReductionClauseWithNogroup(*this, Clauses))
12000     return StmtError();
12001 
12002   setFunctionHasBranchProtectedScope();
12003   return OMPParallelMasterTaskLoopDirective::Create(
12004       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
12005       DSAStack->isCancelRegion());
12006 }
12007 
12008 StmtResult Sema::ActOnOpenMPParallelMasterTaskLoopSimdDirective(
12009     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12010     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12011   if (!AStmt)
12012     return StmtError();
12013 
12014   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
12015   auto *CS = cast<CapturedStmt>(AStmt);
12016   // 1.2.2 OpenMP Language Terminology
12017   // Structured block - An executable statement with a single entry at the
12018   // top and a single exit at the bottom.
12019   // The point of exit cannot be a branch out of the structured block.
12020   // longjmp() and throw() must not violate the entry/exit criteria.
12021   CS->getCapturedDecl()->setNothrow();
12022   for (int ThisCaptureLevel =
12023            getOpenMPCaptureLevels(OMPD_parallel_master_taskloop_simd);
12024        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12025     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12026     // 1.2.2 OpenMP Language Terminology
12027     // Structured block - An executable statement with a single entry at the
12028     // top and a single exit at the bottom.
12029     // The point of exit cannot be a branch out of the structured block.
12030     // longjmp() and throw() must not violate the entry/exit criteria.
12031     CS->getCapturedDecl()->setNothrow();
12032   }
12033 
12034   OMPLoopBasedDirective::HelperExprs B;
12035   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
12036   // define the nested loops number.
12037   unsigned NestedLoopCount = checkOpenMPLoop(
12038       OMPD_parallel_master_taskloop_simd, getCollapseNumberExpr(Clauses),
12039       /*OrderedLoopCountExpr=*/nullptr, CS, *this, *DSAStack,
12040       VarsWithImplicitDSA, B);
12041   if (NestedLoopCount == 0)
12042     return StmtError();
12043 
12044   assert((CurContext->isDependentContext() || B.builtAll()) &&
12045          "omp for loop exprs were not built");
12046 
12047   if (!CurContext->isDependentContext()) {
12048     // Finalize the clauses that need pre-built expressions for CodeGen.
12049     for (OMPClause *C : Clauses) {
12050       if (auto *LC = dyn_cast<OMPLinearClause>(C))
12051         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
12052                                      B.NumIterations, *this, CurScope,
12053                                      DSAStack))
12054           return StmtError();
12055     }
12056   }
12057 
12058   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
12059   // The grainsize clause and num_tasks clause are mutually exclusive and may
12060   // not appear on the same taskloop directive.
12061   if (checkMutuallyExclusiveClauses(*this, Clauses,
12062                                     {OMPC_grainsize, OMPC_num_tasks}))
12063     return StmtError();
12064   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
12065   // If a reduction clause is present on the taskloop directive, the nogroup
12066   // clause must not be specified.
12067   if (checkReductionClauseWithNogroup(*this, Clauses))
12068     return StmtError();
12069   if (checkSimdlenSafelenSpecified(*this, Clauses))
12070     return StmtError();
12071 
12072   setFunctionHasBranchProtectedScope();
12073   return OMPParallelMasterTaskLoopSimdDirective::Create(
12074       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
12075 }
12076 
12077 StmtResult Sema::ActOnOpenMPDistributeDirective(
12078     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12079     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12080   if (!AStmt)
12081     return StmtError();
12082 
12083   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
12084   OMPLoopBasedDirective::HelperExprs B;
12085   // In presence of clause 'collapse' with number of loops, it will
12086   // define the nested loops number.
12087   unsigned NestedLoopCount =
12088       checkOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
12089                       nullptr /*ordered not a clause on distribute*/, AStmt,
12090                       *this, *DSAStack, VarsWithImplicitDSA, B);
12091   if (NestedLoopCount == 0)
12092     return StmtError();
12093 
12094   assert((CurContext->isDependentContext() || B.builtAll()) &&
12095          "omp for loop exprs were not built");
12096 
12097   setFunctionHasBranchProtectedScope();
12098   return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
12099                                         NestedLoopCount, Clauses, AStmt, B);
12100 }
12101 
12102 StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
12103     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12104     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12105   if (!AStmt)
12106     return StmtError();
12107 
12108   auto *CS = cast<CapturedStmt>(AStmt);
12109   // 1.2.2 OpenMP Language Terminology
12110   // Structured block - An executable statement with a single entry at the
12111   // top and a single exit at the bottom.
12112   // The point of exit cannot be a branch out of the structured block.
12113   // longjmp() and throw() must not violate the entry/exit criteria.
12114   CS->getCapturedDecl()->setNothrow();
12115   for (int ThisCaptureLevel =
12116            getOpenMPCaptureLevels(OMPD_distribute_parallel_for);
12117        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12118     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12119     // 1.2.2 OpenMP Language Terminology
12120     // Structured block - An executable statement with a single entry at the
12121     // top and a single exit at the bottom.
12122     // The point of exit cannot be a branch out of the structured block.
12123     // longjmp() and throw() must not violate the entry/exit criteria.
12124     CS->getCapturedDecl()->setNothrow();
12125   }
12126 
12127   OMPLoopBasedDirective::HelperExprs B;
12128   // In presence of clause 'collapse' with number of loops, it will
12129   // define the nested loops number.
12130   unsigned NestedLoopCount = checkOpenMPLoop(
12131       OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
12132       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
12133       VarsWithImplicitDSA, B);
12134   if (NestedLoopCount == 0)
12135     return StmtError();
12136 
12137   assert((CurContext->isDependentContext() || B.builtAll()) &&
12138          "omp for loop exprs were not built");
12139 
12140   setFunctionHasBranchProtectedScope();
12141   return OMPDistributeParallelForDirective::Create(
12142       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
12143       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
12144 }
12145 
12146 StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
12147     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12148     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12149   if (!AStmt)
12150     return StmtError();
12151 
12152   auto *CS = cast<CapturedStmt>(AStmt);
12153   // 1.2.2 OpenMP Language Terminology
12154   // Structured block - An executable statement with a single entry at the
12155   // top and a single exit at the bottom.
12156   // The point of exit cannot be a branch out of the structured block.
12157   // longjmp() and throw() must not violate the entry/exit criteria.
12158   CS->getCapturedDecl()->setNothrow();
12159   for (int ThisCaptureLevel =
12160            getOpenMPCaptureLevels(OMPD_distribute_parallel_for_simd);
12161        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12162     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12163     // 1.2.2 OpenMP Language Terminology
12164     // Structured block - An executable statement with a single entry at the
12165     // top and a single exit at the bottom.
12166     // The point of exit cannot be a branch out of the structured block.
12167     // longjmp() and throw() must not violate the entry/exit criteria.
12168     CS->getCapturedDecl()->setNothrow();
12169   }
12170 
12171   OMPLoopBasedDirective::HelperExprs B;
12172   // In presence of clause 'collapse' with number of loops, it will
12173   // define the nested loops number.
12174   unsigned NestedLoopCount = checkOpenMPLoop(
12175       OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
12176       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
12177       VarsWithImplicitDSA, B);
12178   if (NestedLoopCount == 0)
12179     return StmtError();
12180 
12181   assert((CurContext->isDependentContext() || B.builtAll()) &&
12182          "omp for loop exprs were not built");
12183 
12184   if (!CurContext->isDependentContext()) {
12185     // Finalize the clauses that need pre-built expressions for CodeGen.
12186     for (OMPClause *C : Clauses) {
12187       if (auto *LC = dyn_cast<OMPLinearClause>(C))
12188         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
12189                                      B.NumIterations, *this, CurScope,
12190                                      DSAStack))
12191           return StmtError();
12192     }
12193   }
12194 
12195   if (checkSimdlenSafelenSpecified(*this, Clauses))
12196     return StmtError();
12197 
12198   setFunctionHasBranchProtectedScope();
12199   return OMPDistributeParallelForSimdDirective::Create(
12200       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
12201 }
12202 
12203 StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
12204     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12205     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12206   if (!AStmt)
12207     return StmtError();
12208 
12209   auto *CS = cast<CapturedStmt>(AStmt);
12210   // 1.2.2 OpenMP Language Terminology
12211   // Structured block - An executable statement with a single entry at the
12212   // top and a single exit at the bottom.
12213   // The point of exit cannot be a branch out of the structured block.
12214   // longjmp() and throw() must not violate the entry/exit criteria.
12215   CS->getCapturedDecl()->setNothrow();
12216   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_distribute_simd);
12217        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12218     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12219     // 1.2.2 OpenMP Language Terminology
12220     // Structured block - An executable statement with a single entry at the
12221     // top and a single exit at the bottom.
12222     // The point of exit cannot be a branch out of the structured block.
12223     // longjmp() and throw() must not violate the entry/exit criteria.
12224     CS->getCapturedDecl()->setNothrow();
12225   }
12226 
12227   OMPLoopBasedDirective::HelperExprs B;
12228   // In presence of clause 'collapse' with number of loops, it will
12229   // define the nested loops number.
12230   unsigned NestedLoopCount =
12231       checkOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
12232                       nullptr /*ordered not a clause on distribute*/, CS, *this,
12233                       *DSAStack, VarsWithImplicitDSA, B);
12234   if (NestedLoopCount == 0)
12235     return StmtError();
12236 
12237   assert((CurContext->isDependentContext() || B.builtAll()) &&
12238          "omp for loop exprs were not built");
12239 
12240   if (!CurContext->isDependentContext()) {
12241     // Finalize the clauses that need pre-built expressions for CodeGen.
12242     for (OMPClause *C : Clauses) {
12243       if (auto *LC = dyn_cast<OMPLinearClause>(C))
12244         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
12245                                      B.NumIterations, *this, CurScope,
12246                                      DSAStack))
12247           return StmtError();
12248     }
12249   }
12250 
12251   if (checkSimdlenSafelenSpecified(*this, Clauses))
12252     return StmtError();
12253 
12254   setFunctionHasBranchProtectedScope();
12255   return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
12256                                             NestedLoopCount, Clauses, AStmt, B);
12257 }
12258 
12259 StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
12260     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12261     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12262   if (!AStmt)
12263     return StmtError();
12264 
12265   auto *CS = cast<CapturedStmt>(AStmt);
12266   // 1.2.2 OpenMP Language Terminology
12267   // Structured block - An executable statement with a single entry at the
12268   // top and a single exit at the bottom.
12269   // The point of exit cannot be a branch out of the structured block.
12270   // longjmp() and throw() must not violate the entry/exit criteria.
12271   CS->getCapturedDecl()->setNothrow();
12272   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
12273        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12274     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12275     // 1.2.2 OpenMP Language Terminology
12276     // Structured block - An executable statement with a single entry at the
12277     // top and a single exit at the bottom.
12278     // The point of exit cannot be a branch out of the structured block.
12279     // longjmp() and throw() must not violate the entry/exit criteria.
12280     CS->getCapturedDecl()->setNothrow();
12281   }
12282 
12283   OMPLoopBasedDirective::HelperExprs B;
12284   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
12285   // define the nested loops number.
12286   unsigned NestedLoopCount = checkOpenMPLoop(
12287       OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
12288       getOrderedNumberExpr(Clauses), CS, *this, *DSAStack, VarsWithImplicitDSA,
12289       B);
12290   if (NestedLoopCount == 0)
12291     return StmtError();
12292 
12293   assert((CurContext->isDependentContext() || B.builtAll()) &&
12294          "omp target parallel for simd loop exprs were not built");
12295 
12296   if (!CurContext->isDependentContext()) {
12297     // Finalize the clauses that need pre-built expressions for CodeGen.
12298     for (OMPClause *C : Clauses) {
12299       if (auto *LC = dyn_cast<OMPLinearClause>(C))
12300         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
12301                                      B.NumIterations, *this, CurScope,
12302                                      DSAStack))
12303           return StmtError();
12304     }
12305   }
12306   if (checkSimdlenSafelenSpecified(*this, Clauses))
12307     return StmtError();
12308 
12309   setFunctionHasBranchProtectedScope();
12310   return OMPTargetParallelForSimdDirective::Create(
12311       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
12312 }
12313 
12314 StmtResult Sema::ActOnOpenMPTargetSimdDirective(
12315     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12316     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12317   if (!AStmt)
12318     return StmtError();
12319 
12320   auto *CS = cast<CapturedStmt>(AStmt);
12321   // 1.2.2 OpenMP Language Terminology
12322   // Structured block - An executable statement with a single entry at the
12323   // top and a single exit at the bottom.
12324   // The point of exit cannot be a branch out of the structured block.
12325   // longjmp() and throw() must not violate the entry/exit criteria.
12326   CS->getCapturedDecl()->setNothrow();
12327   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_simd);
12328        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12329     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12330     // 1.2.2 OpenMP Language Terminology
12331     // Structured block - An executable statement with a single entry at the
12332     // top and a single exit at the bottom.
12333     // The point of exit cannot be a branch out of the structured block.
12334     // longjmp() and throw() must not violate the entry/exit criteria.
12335     CS->getCapturedDecl()->setNothrow();
12336   }
12337 
12338   OMPLoopBasedDirective::HelperExprs B;
12339   // In presence of clause 'collapse' with number of loops, it will define the
12340   // nested loops number.
12341   unsigned NestedLoopCount =
12342       checkOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
12343                       getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
12344                       VarsWithImplicitDSA, B);
12345   if (NestedLoopCount == 0)
12346     return StmtError();
12347 
12348   assert((CurContext->isDependentContext() || B.builtAll()) &&
12349          "omp target simd loop exprs were not built");
12350 
12351   if (!CurContext->isDependentContext()) {
12352     // Finalize the clauses that need pre-built expressions for CodeGen.
12353     for (OMPClause *C : Clauses) {
12354       if (auto *LC = dyn_cast<OMPLinearClause>(C))
12355         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
12356                                      B.NumIterations, *this, CurScope,
12357                                      DSAStack))
12358           return StmtError();
12359     }
12360   }
12361 
12362   if (checkSimdlenSafelenSpecified(*this, Clauses))
12363     return StmtError();
12364 
12365   setFunctionHasBranchProtectedScope();
12366   return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
12367                                         NestedLoopCount, Clauses, AStmt, B);
12368 }
12369 
12370 StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
12371     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12372     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12373   if (!AStmt)
12374     return StmtError();
12375 
12376   auto *CS = cast<CapturedStmt>(AStmt);
12377   // 1.2.2 OpenMP Language Terminology
12378   // Structured block - An executable statement with a single entry at the
12379   // top and a single exit at the bottom.
12380   // The point of exit cannot be a branch out of the structured block.
12381   // longjmp() and throw() must not violate the entry/exit criteria.
12382   CS->getCapturedDecl()->setNothrow();
12383   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_teams_distribute);
12384        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12385     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12386     // 1.2.2 OpenMP Language Terminology
12387     // Structured block - An executable statement with a single entry at the
12388     // top and a single exit at the bottom.
12389     // The point of exit cannot be a branch out of the structured block.
12390     // longjmp() and throw() must not violate the entry/exit criteria.
12391     CS->getCapturedDecl()->setNothrow();
12392   }
12393 
12394   OMPLoopBasedDirective::HelperExprs B;
12395   // In presence of clause 'collapse' with number of loops, it will
12396   // define the nested loops number.
12397   unsigned NestedLoopCount =
12398       checkOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
12399                       nullptr /*ordered not a clause on distribute*/, CS, *this,
12400                       *DSAStack, VarsWithImplicitDSA, B);
12401   if (NestedLoopCount == 0)
12402     return StmtError();
12403 
12404   assert((CurContext->isDependentContext() || B.builtAll()) &&
12405          "omp teams distribute loop exprs were not built");
12406 
12407   setFunctionHasBranchProtectedScope();
12408 
12409   DSAStack->setParentTeamsRegionLoc(StartLoc);
12410 
12411   return OMPTeamsDistributeDirective::Create(
12412       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
12413 }
12414 
12415 StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
12416     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12417     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12418   if (!AStmt)
12419     return StmtError();
12420 
12421   auto *CS = cast<CapturedStmt>(AStmt);
12422   // 1.2.2 OpenMP Language Terminology
12423   // Structured block - An executable statement with a single entry at the
12424   // top and a single exit at the bottom.
12425   // The point of exit cannot be a branch out of the structured block.
12426   // longjmp() and throw() must not violate the entry/exit criteria.
12427   CS->getCapturedDecl()->setNothrow();
12428   for (int ThisCaptureLevel =
12429            getOpenMPCaptureLevels(OMPD_teams_distribute_simd);
12430        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12431     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12432     // 1.2.2 OpenMP Language Terminology
12433     // Structured block - An executable statement with a single entry at the
12434     // top and a single exit at the bottom.
12435     // The point of exit cannot be a branch out of the structured block.
12436     // longjmp() and throw() must not violate the entry/exit criteria.
12437     CS->getCapturedDecl()->setNothrow();
12438   }
12439 
12440   OMPLoopBasedDirective::HelperExprs B;
12441   // In presence of clause 'collapse' with number of loops, it will
12442   // define the nested loops number.
12443   unsigned NestedLoopCount = checkOpenMPLoop(
12444       OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
12445       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
12446       VarsWithImplicitDSA, B);
12447 
12448   if (NestedLoopCount == 0)
12449     return StmtError();
12450 
12451   assert((CurContext->isDependentContext() || B.builtAll()) &&
12452          "omp teams distribute simd loop exprs were not built");
12453 
12454   if (!CurContext->isDependentContext()) {
12455     // Finalize the clauses that need pre-built expressions for CodeGen.
12456     for (OMPClause *C : Clauses) {
12457       if (auto *LC = dyn_cast<OMPLinearClause>(C))
12458         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
12459                                      B.NumIterations, *this, CurScope,
12460                                      DSAStack))
12461           return StmtError();
12462     }
12463   }
12464 
12465   if (checkSimdlenSafelenSpecified(*this, Clauses))
12466     return StmtError();
12467 
12468   setFunctionHasBranchProtectedScope();
12469 
12470   DSAStack->setParentTeamsRegionLoc(StartLoc);
12471 
12472   return OMPTeamsDistributeSimdDirective::Create(
12473       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
12474 }
12475 
12476 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
12477     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12478     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12479   if (!AStmt)
12480     return StmtError();
12481 
12482   auto *CS = cast<CapturedStmt>(AStmt);
12483   // 1.2.2 OpenMP Language Terminology
12484   // Structured block - An executable statement with a single entry at the
12485   // top and a single exit at the bottom.
12486   // The point of exit cannot be a branch out of the structured block.
12487   // longjmp() and throw() must not violate the entry/exit criteria.
12488   CS->getCapturedDecl()->setNothrow();
12489 
12490   for (int ThisCaptureLevel =
12491            getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for_simd);
12492        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12493     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12494     // 1.2.2 OpenMP Language Terminology
12495     // Structured block - An executable statement with a single entry at the
12496     // top and a single exit at the bottom.
12497     // The point of exit cannot be a branch out of the structured block.
12498     // longjmp() and throw() must not violate the entry/exit criteria.
12499     CS->getCapturedDecl()->setNothrow();
12500   }
12501 
12502   OMPLoopBasedDirective::HelperExprs B;
12503   // In presence of clause 'collapse' with number of loops, it will
12504   // define the nested loops number.
12505   unsigned NestedLoopCount = checkOpenMPLoop(
12506       OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
12507       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
12508       VarsWithImplicitDSA, B);
12509 
12510   if (NestedLoopCount == 0)
12511     return StmtError();
12512 
12513   assert((CurContext->isDependentContext() || B.builtAll()) &&
12514          "omp for loop exprs were not built");
12515 
12516   if (!CurContext->isDependentContext()) {
12517     // Finalize the clauses that need pre-built expressions for CodeGen.
12518     for (OMPClause *C : Clauses) {
12519       if (auto *LC = dyn_cast<OMPLinearClause>(C))
12520         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
12521                                      B.NumIterations, *this, CurScope,
12522                                      DSAStack))
12523           return StmtError();
12524     }
12525   }
12526 
12527   if (checkSimdlenSafelenSpecified(*this, Clauses))
12528     return StmtError();
12529 
12530   setFunctionHasBranchProtectedScope();
12531 
12532   DSAStack->setParentTeamsRegionLoc(StartLoc);
12533 
12534   return OMPTeamsDistributeParallelForSimdDirective::Create(
12535       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
12536 }
12537 
12538 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
12539     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12540     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12541   if (!AStmt)
12542     return StmtError();
12543 
12544   auto *CS = cast<CapturedStmt>(AStmt);
12545   // 1.2.2 OpenMP Language Terminology
12546   // Structured block - An executable statement with a single entry at the
12547   // top and a single exit at the bottom.
12548   // The point of exit cannot be a branch out of the structured block.
12549   // longjmp() and throw() must not violate the entry/exit criteria.
12550   CS->getCapturedDecl()->setNothrow();
12551 
12552   for (int ThisCaptureLevel =
12553            getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for);
12554        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12555     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12556     // 1.2.2 OpenMP Language Terminology
12557     // Structured block - An executable statement with a single entry at the
12558     // top and a single exit at the bottom.
12559     // The point of exit cannot be a branch out of the structured block.
12560     // longjmp() and throw() must not violate the entry/exit criteria.
12561     CS->getCapturedDecl()->setNothrow();
12562   }
12563 
12564   OMPLoopBasedDirective::HelperExprs B;
12565   // In presence of clause 'collapse' with number of loops, it will
12566   // define the nested loops number.
12567   unsigned NestedLoopCount = checkOpenMPLoop(
12568       OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
12569       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
12570       VarsWithImplicitDSA, B);
12571 
12572   if (NestedLoopCount == 0)
12573     return StmtError();
12574 
12575   assert((CurContext->isDependentContext() || B.builtAll()) &&
12576          "omp for loop exprs were not built");
12577 
12578   setFunctionHasBranchProtectedScope();
12579 
12580   DSAStack->setParentTeamsRegionLoc(StartLoc);
12581 
12582   return OMPTeamsDistributeParallelForDirective::Create(
12583       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
12584       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
12585 }
12586 
12587 StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
12588                                                  Stmt *AStmt,
12589                                                  SourceLocation StartLoc,
12590                                                  SourceLocation EndLoc) {
12591   if (!AStmt)
12592     return StmtError();
12593 
12594   auto *CS = cast<CapturedStmt>(AStmt);
12595   // 1.2.2 OpenMP Language Terminology
12596   // Structured block - An executable statement with a single entry at the
12597   // top and a single exit at the bottom.
12598   // The point of exit cannot be a branch out of the structured block.
12599   // longjmp() and throw() must not violate the entry/exit criteria.
12600   CS->getCapturedDecl()->setNothrow();
12601 
12602   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams);
12603        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12604     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12605     // 1.2.2 OpenMP Language Terminology
12606     // Structured block - An executable statement with a single entry at the
12607     // top and a single exit at the bottom.
12608     // The point of exit cannot be a branch out of the structured block.
12609     // longjmp() and throw() must not violate the entry/exit criteria.
12610     CS->getCapturedDecl()->setNothrow();
12611   }
12612   setFunctionHasBranchProtectedScope();
12613 
12614   return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
12615                                          AStmt);
12616 }
12617 
12618 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
12619     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12620     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12621   if (!AStmt)
12622     return StmtError();
12623 
12624   auto *CS = cast<CapturedStmt>(AStmt);
12625   // 1.2.2 OpenMP Language Terminology
12626   // Structured block - An executable statement with a single entry at the
12627   // top and a single exit at the bottom.
12628   // The point of exit cannot be a branch out of the structured block.
12629   // longjmp() and throw() must not violate the entry/exit criteria.
12630   CS->getCapturedDecl()->setNothrow();
12631   for (int ThisCaptureLevel =
12632            getOpenMPCaptureLevels(OMPD_target_teams_distribute);
12633        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12634     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12635     // 1.2.2 OpenMP Language Terminology
12636     // Structured block - An executable statement with a single entry at the
12637     // top and a single exit at the bottom.
12638     // The point of exit cannot be a branch out of the structured block.
12639     // longjmp() and throw() must not violate the entry/exit criteria.
12640     CS->getCapturedDecl()->setNothrow();
12641   }
12642 
12643   OMPLoopBasedDirective::HelperExprs B;
12644   // In presence of clause 'collapse' with number of loops, it will
12645   // define the nested loops number.
12646   unsigned NestedLoopCount = checkOpenMPLoop(
12647       OMPD_target_teams_distribute, getCollapseNumberExpr(Clauses),
12648       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
12649       VarsWithImplicitDSA, B);
12650   if (NestedLoopCount == 0)
12651     return StmtError();
12652 
12653   assert((CurContext->isDependentContext() || B.builtAll()) &&
12654          "omp target teams distribute loop exprs were not built");
12655 
12656   setFunctionHasBranchProtectedScope();
12657   return OMPTargetTeamsDistributeDirective::Create(
12658       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
12659 }
12660 
12661 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
12662     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12663     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12664   if (!AStmt)
12665     return StmtError();
12666 
12667   auto *CS = cast<CapturedStmt>(AStmt);
12668   // 1.2.2 OpenMP Language Terminology
12669   // Structured block - An executable statement with a single entry at the
12670   // top and a single exit at the bottom.
12671   // The point of exit cannot be a branch out of the structured block.
12672   // longjmp() and throw() must not violate the entry/exit criteria.
12673   CS->getCapturedDecl()->setNothrow();
12674   for (int ThisCaptureLevel =
12675            getOpenMPCaptureLevels(OMPD_target_teams_distribute_parallel_for);
12676        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12677     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12678     // 1.2.2 OpenMP Language Terminology
12679     // Structured block - An executable statement with a single entry at the
12680     // top and a single exit at the bottom.
12681     // The point of exit cannot be a branch out of the structured block.
12682     // longjmp() and throw() must not violate the entry/exit criteria.
12683     CS->getCapturedDecl()->setNothrow();
12684   }
12685 
12686   OMPLoopBasedDirective::HelperExprs B;
12687   // In presence of clause 'collapse' with number of loops, it will
12688   // define the nested loops number.
12689   unsigned NestedLoopCount = checkOpenMPLoop(
12690       OMPD_target_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
12691       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
12692       VarsWithImplicitDSA, B);
12693   if (NestedLoopCount == 0)
12694     return StmtError();
12695 
12696   assert((CurContext->isDependentContext() || B.builtAll()) &&
12697          "omp target teams distribute parallel for loop exprs were not built");
12698 
12699   if (!CurContext->isDependentContext()) {
12700     // Finalize the clauses that need pre-built expressions for CodeGen.
12701     for (OMPClause *C : Clauses) {
12702       if (auto *LC = dyn_cast<OMPLinearClause>(C))
12703         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
12704                                      B.NumIterations, *this, CurScope,
12705                                      DSAStack))
12706           return StmtError();
12707     }
12708   }
12709 
12710   setFunctionHasBranchProtectedScope();
12711   return OMPTargetTeamsDistributeParallelForDirective::Create(
12712       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
12713       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
12714 }
12715 
12716 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
12717     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12718     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12719   if (!AStmt)
12720     return StmtError();
12721 
12722   auto *CS = cast<CapturedStmt>(AStmt);
12723   // 1.2.2 OpenMP Language Terminology
12724   // Structured block - An executable statement with a single entry at the
12725   // top and a single exit at the bottom.
12726   // The point of exit cannot be a branch out of the structured block.
12727   // longjmp() and throw() must not violate the entry/exit criteria.
12728   CS->getCapturedDecl()->setNothrow();
12729   for (int ThisCaptureLevel = getOpenMPCaptureLevels(
12730            OMPD_target_teams_distribute_parallel_for_simd);
12731        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12732     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12733     // 1.2.2 OpenMP Language Terminology
12734     // Structured block - An executable statement with a single entry at the
12735     // top and a single exit at the bottom.
12736     // The point of exit cannot be a branch out of the structured block.
12737     // longjmp() and throw() must not violate the entry/exit criteria.
12738     CS->getCapturedDecl()->setNothrow();
12739   }
12740 
12741   OMPLoopBasedDirective::HelperExprs B;
12742   // In presence of clause 'collapse' with number of loops, it will
12743   // define the nested loops number.
12744   unsigned NestedLoopCount =
12745       checkOpenMPLoop(OMPD_target_teams_distribute_parallel_for_simd,
12746                       getCollapseNumberExpr(Clauses),
12747                       nullptr /*ordered not a clause on distribute*/, CS, *this,
12748                       *DSAStack, VarsWithImplicitDSA, B);
12749   if (NestedLoopCount == 0)
12750     return StmtError();
12751 
12752   assert((CurContext->isDependentContext() || B.builtAll()) &&
12753          "omp target teams distribute parallel for simd loop exprs were not "
12754          "built");
12755 
12756   if (!CurContext->isDependentContext()) {
12757     // Finalize the clauses that need pre-built expressions for CodeGen.
12758     for (OMPClause *C : Clauses) {
12759       if (auto *LC = dyn_cast<OMPLinearClause>(C))
12760         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
12761                                      B.NumIterations, *this, CurScope,
12762                                      DSAStack))
12763           return StmtError();
12764     }
12765   }
12766 
12767   if (checkSimdlenSafelenSpecified(*this, Clauses))
12768     return StmtError();
12769 
12770   setFunctionHasBranchProtectedScope();
12771   return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
12772       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
12773 }
12774 
12775 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
12776     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12777     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12778   if (!AStmt)
12779     return StmtError();
12780 
12781   auto *CS = cast<CapturedStmt>(AStmt);
12782   // 1.2.2 OpenMP Language Terminology
12783   // Structured block - An executable statement with a single entry at the
12784   // top and a single exit at the bottom.
12785   // The point of exit cannot be a branch out of the structured block.
12786   // longjmp() and throw() must not violate the entry/exit criteria.
12787   CS->getCapturedDecl()->setNothrow();
12788   for (int ThisCaptureLevel =
12789            getOpenMPCaptureLevels(OMPD_target_teams_distribute_simd);
12790        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12791     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12792     // 1.2.2 OpenMP Language Terminology
12793     // Structured block - An executable statement with a single entry at the
12794     // top and a single exit at the bottom.
12795     // The point of exit cannot be a branch out of the structured block.
12796     // longjmp() and throw() must not violate the entry/exit criteria.
12797     CS->getCapturedDecl()->setNothrow();
12798   }
12799 
12800   OMPLoopBasedDirective::HelperExprs B;
12801   // In presence of clause 'collapse' with number of loops, it will
12802   // define the nested loops number.
12803   unsigned NestedLoopCount = checkOpenMPLoop(
12804       OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
12805       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
12806       VarsWithImplicitDSA, B);
12807   if (NestedLoopCount == 0)
12808     return StmtError();
12809 
12810   assert((CurContext->isDependentContext() || B.builtAll()) &&
12811          "omp target teams distribute simd loop exprs were not built");
12812 
12813   if (!CurContext->isDependentContext()) {
12814     // Finalize the clauses that need pre-built expressions for CodeGen.
12815     for (OMPClause *C : Clauses) {
12816       if (auto *LC = dyn_cast<OMPLinearClause>(C))
12817         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
12818                                      B.NumIterations, *this, CurScope,
12819                                      DSAStack))
12820           return StmtError();
12821     }
12822   }
12823 
12824   if (checkSimdlenSafelenSpecified(*this, Clauses))
12825     return StmtError();
12826 
12827   setFunctionHasBranchProtectedScope();
12828   return OMPTargetTeamsDistributeSimdDirective::Create(
12829       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
12830 }
12831 
12832 bool Sema::checkTransformableLoopNest(
12833     OpenMPDirectiveKind Kind, Stmt *AStmt, int NumLoops,
12834     SmallVectorImpl<OMPLoopBasedDirective::HelperExprs> &LoopHelpers,
12835     Stmt *&Body,
12836     SmallVectorImpl<SmallVector<llvm::PointerUnion<Stmt *, Decl *>, 0>>
12837         &OriginalInits) {
12838   OriginalInits.emplace_back();
12839   bool Result = OMPLoopBasedDirective::doForAllLoops(
12840       AStmt->IgnoreContainers(), /*TryImperfectlyNestedLoops=*/false, NumLoops,
12841       [this, &LoopHelpers, &Body, &OriginalInits, Kind](unsigned Cnt,
12842                                                         Stmt *CurStmt) {
12843         VarsWithInheritedDSAType TmpDSA;
12844         unsigned SingleNumLoops =
12845             checkOpenMPLoop(Kind, nullptr, nullptr, CurStmt, *this, *DSAStack,
12846                             TmpDSA, LoopHelpers[Cnt]);
12847         if (SingleNumLoops == 0)
12848           return true;
12849         assert(SingleNumLoops == 1 && "Expect single loop iteration space");
12850         if (auto *For = dyn_cast<ForStmt>(CurStmt)) {
12851           OriginalInits.back().push_back(For->getInit());
12852           Body = For->getBody();
12853         } else {
12854           assert(isa<CXXForRangeStmt>(CurStmt) &&
12855                  "Expected canonical for or range-based for loops.");
12856           auto *CXXFor = cast<CXXForRangeStmt>(CurStmt);
12857           OriginalInits.back().push_back(CXXFor->getBeginStmt());
12858           Body = CXXFor->getBody();
12859         }
12860         OriginalInits.emplace_back();
12861         return false;
12862       },
12863       [&OriginalInits](OMPLoopBasedDirective *Transform) {
12864         Stmt *DependentPreInits;
12865         if (auto *Dir = dyn_cast<OMPTileDirective>(Transform))
12866           DependentPreInits = Dir->getPreInits();
12867         else if (auto *Dir = dyn_cast<OMPUnrollDirective>(Transform))
12868           DependentPreInits = Dir->getPreInits();
12869         else
12870           llvm_unreachable("Unhandled loop transformation");
12871         if (!DependentPreInits)
12872           return;
12873         for (Decl *C : cast<DeclStmt>(DependentPreInits)->getDeclGroup())
12874           OriginalInits.back().push_back(C);
12875       });
12876   assert(OriginalInits.back().empty() && "No preinit after innermost loop");
12877   OriginalInits.pop_back();
12878   return Result;
12879 }
12880 
12881 StmtResult Sema::ActOnOpenMPTileDirective(ArrayRef<OMPClause *> Clauses,
12882                                           Stmt *AStmt, SourceLocation StartLoc,
12883                                           SourceLocation EndLoc) {
12884   auto SizesClauses =
12885       OMPExecutableDirective::getClausesOfKind<OMPSizesClause>(Clauses);
12886   if (SizesClauses.empty()) {
12887     // A missing 'sizes' clause is already reported by the parser.
12888     return StmtError();
12889   }
12890   const OMPSizesClause *SizesClause = *SizesClauses.begin();
12891   unsigned NumLoops = SizesClause->getNumSizes();
12892 
12893   // Empty statement should only be possible if there already was an error.
12894   if (!AStmt)
12895     return StmtError();
12896 
12897   // Verify and diagnose loop nest.
12898   SmallVector<OMPLoopBasedDirective::HelperExprs, 4> LoopHelpers(NumLoops);
12899   Stmt *Body = nullptr;
12900   SmallVector<SmallVector<llvm::PointerUnion<Stmt *, Decl *>, 0>, 4>
12901       OriginalInits;
12902   if (!checkTransformableLoopNest(OMPD_tile, AStmt, NumLoops, LoopHelpers, Body,
12903                                   OriginalInits))
12904     return StmtError();
12905 
12906   // Delay tiling to when template is completely instantiated.
12907   if (CurContext->isDependentContext())
12908     return OMPTileDirective::Create(Context, StartLoc, EndLoc, Clauses,
12909                                     NumLoops, AStmt, nullptr, nullptr);
12910 
12911   SmallVector<Decl *, 4> PreInits;
12912 
12913   // Create iteration variables for the generated loops.
12914   SmallVector<VarDecl *, 4> FloorIndVars;
12915   SmallVector<VarDecl *, 4> TileIndVars;
12916   FloorIndVars.resize(NumLoops);
12917   TileIndVars.resize(NumLoops);
12918   for (unsigned I = 0; I < NumLoops; ++I) {
12919     OMPLoopBasedDirective::HelperExprs &LoopHelper = LoopHelpers[I];
12920 
12921     assert(LoopHelper.Counters.size() == 1 &&
12922            "Expect single-dimensional loop iteration space");
12923     auto *OrigCntVar = cast<DeclRefExpr>(LoopHelper.Counters.front());
12924     std::string OrigVarName = OrigCntVar->getNameInfo().getAsString();
12925     DeclRefExpr *IterVarRef = cast<DeclRefExpr>(LoopHelper.IterationVarRef);
12926     QualType CntTy = IterVarRef->getType();
12927 
12928     // Iteration variable for the floor (i.e. outer) loop.
12929     {
12930       std::string FloorCntName =
12931           (Twine(".floor_") + llvm::utostr(I) + ".iv." + OrigVarName).str();
12932       VarDecl *FloorCntDecl =
12933           buildVarDecl(*this, {}, CntTy, FloorCntName, nullptr, OrigCntVar);
12934       FloorIndVars[I] = FloorCntDecl;
12935     }
12936 
12937     // Iteration variable for the tile (i.e. inner) loop.
12938     {
12939       std::string TileCntName =
12940           (Twine(".tile_") + llvm::utostr(I) + ".iv." + OrigVarName).str();
12941 
12942       // Reuse the iteration variable created by checkOpenMPLoop. It is also
12943       // used by the expressions to derive the original iteration variable's
12944       // value from the logical iteration number.
12945       auto *TileCntDecl = cast<VarDecl>(IterVarRef->getDecl());
12946       TileCntDecl->setDeclName(&PP.getIdentifierTable().get(TileCntName));
12947       TileIndVars[I] = TileCntDecl;
12948     }
12949     for (auto &P : OriginalInits[I]) {
12950       if (auto *D = P.dyn_cast<Decl *>())
12951         PreInits.push_back(D);
12952       else if (auto *PI = dyn_cast_or_null<DeclStmt>(P.dyn_cast<Stmt *>()))
12953         PreInits.append(PI->decl_begin(), PI->decl_end());
12954     }
12955     if (auto *PI = cast_or_null<DeclStmt>(LoopHelper.PreInits))
12956       PreInits.append(PI->decl_begin(), PI->decl_end());
12957     // Gather declarations for the data members used as counters.
12958     for (Expr *CounterRef : LoopHelper.Counters) {
12959       auto *CounterDecl = cast<DeclRefExpr>(CounterRef)->getDecl();
12960       if (isa<OMPCapturedExprDecl>(CounterDecl))
12961         PreInits.push_back(CounterDecl);
12962     }
12963   }
12964 
12965   // Once the original iteration values are set, append the innermost body.
12966   Stmt *Inner = Body;
12967 
12968   // Create tile loops from the inside to the outside.
12969   for (int I = NumLoops - 1; I >= 0; --I) {
12970     OMPLoopBasedDirective::HelperExprs &LoopHelper = LoopHelpers[I];
12971     Expr *NumIterations = LoopHelper.NumIterations;
12972     auto *OrigCntVar = cast<DeclRefExpr>(LoopHelper.Counters[0]);
12973     QualType CntTy = OrigCntVar->getType();
12974     Expr *DimTileSize = SizesClause->getSizesRefs()[I];
12975     Scope *CurScope = getCurScope();
12976 
12977     // Commonly used variables.
12978     DeclRefExpr *TileIV = buildDeclRefExpr(*this, TileIndVars[I], CntTy,
12979                                            OrigCntVar->getExprLoc());
12980     DeclRefExpr *FloorIV = buildDeclRefExpr(*this, FloorIndVars[I], CntTy,
12981                                             OrigCntVar->getExprLoc());
12982 
12983     // For init-statement: auto .tile.iv = .floor.iv
12984     AddInitializerToDecl(TileIndVars[I], DefaultLvalueConversion(FloorIV).get(),
12985                          /*DirectInit=*/false);
12986     Decl *CounterDecl = TileIndVars[I];
12987     StmtResult InitStmt = new (Context)
12988         DeclStmt(DeclGroupRef::Create(Context, &CounterDecl, 1),
12989                  OrigCntVar->getBeginLoc(), OrigCntVar->getEndLoc());
12990     if (!InitStmt.isUsable())
12991       return StmtError();
12992 
12993     // For cond-expression: .tile.iv < min(.floor.iv + DimTileSize,
12994     // NumIterations)
12995     ExprResult EndOfTile = BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(),
12996                                       BO_Add, FloorIV, DimTileSize);
12997     if (!EndOfTile.isUsable())
12998       return StmtError();
12999     ExprResult IsPartialTile =
13000         BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), BO_LT,
13001                    NumIterations, EndOfTile.get());
13002     if (!IsPartialTile.isUsable())
13003       return StmtError();
13004     ExprResult MinTileAndIterSpace = ActOnConditionalOp(
13005         LoopHelper.Cond->getBeginLoc(), LoopHelper.Cond->getEndLoc(),
13006         IsPartialTile.get(), NumIterations, EndOfTile.get());
13007     if (!MinTileAndIterSpace.isUsable())
13008       return StmtError();
13009     ExprResult CondExpr = BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(),
13010                                      BO_LT, TileIV, MinTileAndIterSpace.get());
13011     if (!CondExpr.isUsable())
13012       return StmtError();
13013 
13014     // For incr-statement: ++.tile.iv
13015     ExprResult IncrStmt =
13016         BuildUnaryOp(CurScope, LoopHelper.Inc->getExprLoc(), UO_PreInc, TileIV);
13017     if (!IncrStmt.isUsable())
13018       return StmtError();
13019 
13020     // Statements to set the original iteration variable's value from the
13021     // logical iteration number.
13022     // Generated for loop is:
13023     // Original_for_init;
13024     // for (auto .tile.iv = .floor.iv; .tile.iv < min(.floor.iv + DimTileSize,
13025     // NumIterations); ++.tile.iv) {
13026     //   Original_Body;
13027     //   Original_counter_update;
13028     // }
13029     // FIXME: If the innermost body is an loop itself, inserting these
13030     // statements stops it being recognized  as a perfectly nested loop (e.g.
13031     // for applying tiling again). If this is the case, sink the expressions
13032     // further into the inner loop.
13033     SmallVector<Stmt *, 4> BodyParts;
13034     BodyParts.append(LoopHelper.Updates.begin(), LoopHelper.Updates.end());
13035     BodyParts.push_back(Inner);
13036     Inner = CompoundStmt::Create(Context, BodyParts, Inner->getBeginLoc(),
13037                                  Inner->getEndLoc());
13038     Inner = new (Context)
13039         ForStmt(Context, InitStmt.get(), CondExpr.get(), nullptr,
13040                 IncrStmt.get(), Inner, LoopHelper.Init->getBeginLoc(),
13041                 LoopHelper.Init->getBeginLoc(), LoopHelper.Inc->getEndLoc());
13042   }
13043 
13044   // Create floor loops from the inside to the outside.
13045   for (int I = NumLoops - 1; I >= 0; --I) {
13046     auto &LoopHelper = LoopHelpers[I];
13047     Expr *NumIterations = LoopHelper.NumIterations;
13048     DeclRefExpr *OrigCntVar = cast<DeclRefExpr>(LoopHelper.Counters[0]);
13049     QualType CntTy = OrigCntVar->getType();
13050     Expr *DimTileSize = SizesClause->getSizesRefs()[I];
13051     Scope *CurScope = getCurScope();
13052 
13053     // Commonly used variables.
13054     DeclRefExpr *FloorIV = buildDeclRefExpr(*this, FloorIndVars[I], CntTy,
13055                                             OrigCntVar->getExprLoc());
13056 
13057     // For init-statement: auto .floor.iv = 0
13058     AddInitializerToDecl(
13059         FloorIndVars[I],
13060         ActOnIntegerConstant(LoopHelper.Init->getExprLoc(), 0).get(),
13061         /*DirectInit=*/false);
13062     Decl *CounterDecl = FloorIndVars[I];
13063     StmtResult InitStmt = new (Context)
13064         DeclStmt(DeclGroupRef::Create(Context, &CounterDecl, 1),
13065                  OrigCntVar->getBeginLoc(), OrigCntVar->getEndLoc());
13066     if (!InitStmt.isUsable())
13067       return StmtError();
13068 
13069     // For cond-expression: .floor.iv < NumIterations
13070     ExprResult CondExpr = BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(),
13071                                      BO_LT, FloorIV, NumIterations);
13072     if (!CondExpr.isUsable())
13073       return StmtError();
13074 
13075     // For incr-statement: .floor.iv += DimTileSize
13076     ExprResult IncrStmt = BuildBinOp(CurScope, LoopHelper.Inc->getExprLoc(),
13077                                      BO_AddAssign, FloorIV, DimTileSize);
13078     if (!IncrStmt.isUsable())
13079       return StmtError();
13080 
13081     Inner = new (Context)
13082         ForStmt(Context, InitStmt.get(), CondExpr.get(), nullptr,
13083                 IncrStmt.get(), Inner, LoopHelper.Init->getBeginLoc(),
13084                 LoopHelper.Init->getBeginLoc(), LoopHelper.Inc->getEndLoc());
13085   }
13086 
13087   return OMPTileDirective::Create(Context, StartLoc, EndLoc, Clauses, NumLoops,
13088                                   AStmt, Inner,
13089                                   buildPreInits(Context, PreInits));
13090 }
13091 
13092 StmtResult Sema::ActOnOpenMPUnrollDirective(ArrayRef<OMPClause *> Clauses,
13093                                             Stmt *AStmt,
13094                                             SourceLocation StartLoc,
13095                                             SourceLocation EndLoc) {
13096   // Empty statement should only be possible if there already was an error.
13097   if (!AStmt)
13098     return StmtError();
13099 
13100   if (checkMutuallyExclusiveClauses(*this, Clauses, {OMPC_partial, OMPC_full}))
13101     return StmtError();
13102 
13103   const OMPFullClause *FullClause =
13104       OMPExecutableDirective::getSingleClause<OMPFullClause>(Clauses);
13105   const OMPPartialClause *PartialClause =
13106       OMPExecutableDirective::getSingleClause<OMPPartialClause>(Clauses);
13107   assert(!(FullClause && PartialClause) &&
13108          "mutual exclusivity must have been checked before");
13109 
13110   constexpr unsigned NumLoops = 1;
13111   Stmt *Body = nullptr;
13112   SmallVector<OMPLoopBasedDirective::HelperExprs, NumLoops> LoopHelpers(
13113       NumLoops);
13114   SmallVector<SmallVector<llvm::PointerUnion<Stmt *, Decl *>, 0>, NumLoops + 1>
13115       OriginalInits;
13116   if (!checkTransformableLoopNest(OMPD_unroll, AStmt, NumLoops, LoopHelpers,
13117                                   Body, OriginalInits))
13118     return StmtError();
13119 
13120   unsigned NumGeneratedLoops = PartialClause ? 1 : 0;
13121 
13122   // Delay unrolling to when template is completely instantiated.
13123   if (CurContext->isDependentContext())
13124     return OMPUnrollDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
13125                                       NumGeneratedLoops, nullptr, nullptr);
13126 
13127   OMPLoopBasedDirective::HelperExprs &LoopHelper = LoopHelpers.front();
13128 
13129   if (FullClause) {
13130     if (!VerifyPositiveIntegerConstantInClause(
13131              LoopHelper.NumIterations, OMPC_full, /*StrictlyPositive=*/false,
13132              /*SuppressExprDigs=*/true)
13133              .isUsable()) {
13134       Diag(AStmt->getBeginLoc(), diag::err_omp_unroll_full_variable_trip_count);
13135       Diag(FullClause->getBeginLoc(), diag::note_omp_directive_here)
13136           << "#pragma omp unroll full";
13137       return StmtError();
13138     }
13139   }
13140 
13141   // The generated loop may only be passed to other loop-associated directive
13142   // when a partial clause is specified. Without the requirement it is
13143   // sufficient to generate loop unroll metadata at code-generation.
13144   if (NumGeneratedLoops == 0)
13145     return OMPUnrollDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
13146                                       NumGeneratedLoops, nullptr, nullptr);
13147 
13148   // Otherwise, we need to provide a de-sugared/transformed AST that can be
13149   // associated with another loop directive.
13150   //
13151   // The canonical loop analysis return by checkTransformableLoopNest assumes
13152   // the following structure to be the same loop without transformations or
13153   // directives applied: \code OriginalInits; LoopHelper.PreInits;
13154   // LoopHelper.Counters;
13155   // for (; IV < LoopHelper.NumIterations; ++IV) {
13156   //   LoopHelper.Updates;
13157   //   Body;
13158   // }
13159   // \endcode
13160   // where IV is a variable declared and initialized to 0 in LoopHelper.PreInits
13161   // and referenced by LoopHelper.IterationVarRef.
13162   //
13163   // The unrolling directive transforms this into the following loop:
13164   // \code
13165   // OriginalInits;         \
13166   // LoopHelper.PreInits;    > NewPreInits
13167   // LoopHelper.Counters;   /
13168   // for (auto UIV = 0; UIV < LoopHelper.NumIterations; UIV+=Factor) {
13169   //   #pragma clang loop unroll_count(Factor)
13170   //   for (IV = UIV; IV < UIV + Factor && UIV < LoopHelper.NumIterations; ++IV)
13171   //   {
13172   //     LoopHelper.Updates;
13173   //     Body;
13174   //   }
13175   // }
13176   // \endcode
13177   // where UIV is a new logical iteration counter. IV must be the same VarDecl
13178   // as the original LoopHelper.IterationVarRef because LoopHelper.Updates
13179   // references it. If the partially unrolled loop is associated with another
13180   // loop directive (like an OMPForDirective), it will use checkOpenMPLoop to
13181   // analyze this loop, i.e. the outer loop must fulfill the constraints of an
13182   // OpenMP canonical loop. The inner loop is not an associable canonical loop
13183   // and only exists to defer its unrolling to LLVM's LoopUnroll instead of
13184   // doing it in the frontend (by adding loop metadata). NewPreInits becomes a
13185   // property of the OMPLoopBasedDirective instead of statements in
13186   // CompoundStatement. This is to allow the loop to become a non-outermost loop
13187   // of a canonical loop nest where these PreInits are emitted before the
13188   // outermost directive.
13189 
13190   // Determine the PreInit declarations.
13191   SmallVector<Decl *, 4> PreInits;
13192   assert(OriginalInits.size() == 1 &&
13193          "Expecting a single-dimensional loop iteration space");
13194   for (auto &P : OriginalInits[0]) {
13195     if (auto *D = P.dyn_cast<Decl *>())
13196       PreInits.push_back(D);
13197     else if (auto *PI = dyn_cast_or_null<DeclStmt>(P.dyn_cast<Stmt *>()))
13198       PreInits.append(PI->decl_begin(), PI->decl_end());
13199   }
13200   if (auto *PI = cast_or_null<DeclStmt>(LoopHelper.PreInits))
13201     PreInits.append(PI->decl_begin(), PI->decl_end());
13202   // Gather declarations for the data members used as counters.
13203   for (Expr *CounterRef : LoopHelper.Counters) {
13204     auto *CounterDecl = cast<DeclRefExpr>(CounterRef)->getDecl();
13205     if (isa<OMPCapturedExprDecl>(CounterDecl))
13206       PreInits.push_back(CounterDecl);
13207   }
13208 
13209   auto *IterationVarRef = cast<DeclRefExpr>(LoopHelper.IterationVarRef);
13210   QualType IVTy = IterationVarRef->getType();
13211   assert(LoopHelper.Counters.size() == 1 &&
13212          "Expecting a single-dimensional loop iteration space");
13213   auto *OrigVar = cast<DeclRefExpr>(LoopHelper.Counters.front());
13214 
13215   // Determine the unroll factor.
13216   uint64_t Factor;
13217   SourceLocation FactorLoc;
13218   if (Expr *FactorVal = PartialClause->getFactor()) {
13219     Factor =
13220         FactorVal->getIntegerConstantExpr(Context).getValue().getZExtValue();
13221     FactorLoc = FactorVal->getExprLoc();
13222   } else {
13223     // TODO: Use a better profitability model.
13224     Factor = 2;
13225   }
13226   assert(Factor > 0 && "Expected positive unroll factor");
13227   auto MakeFactorExpr = [this, Factor, IVTy, FactorLoc]() {
13228     return IntegerLiteral::Create(
13229         Context, llvm::APInt(Context.getIntWidth(IVTy), Factor), IVTy,
13230         FactorLoc);
13231   };
13232 
13233   // Iteration variable SourceLocations.
13234   SourceLocation OrigVarLoc = OrigVar->getExprLoc();
13235   SourceLocation OrigVarLocBegin = OrigVar->getBeginLoc();
13236   SourceLocation OrigVarLocEnd = OrigVar->getEndLoc();
13237 
13238   // Internal variable names.
13239   std::string OrigVarName = OrigVar->getNameInfo().getAsString();
13240   std::string OuterIVName = (Twine(".unrolled.iv.") + OrigVarName).str();
13241   std::string InnerIVName = (Twine(".unroll_inner.iv.") + OrigVarName).str();
13242   std::string InnerTripCountName =
13243       (Twine(".unroll_inner.tripcount.") + OrigVarName).str();
13244 
13245   // Create the iteration variable for the unrolled loop.
13246   VarDecl *OuterIVDecl =
13247       buildVarDecl(*this, {}, IVTy, OuterIVName, nullptr, OrigVar);
13248   auto MakeOuterRef = [this, OuterIVDecl, IVTy, OrigVarLoc]() {
13249     return buildDeclRefExpr(*this, OuterIVDecl, IVTy, OrigVarLoc);
13250   };
13251 
13252   // Iteration variable for the inner loop: Reuse the iteration variable created
13253   // by checkOpenMPLoop.
13254   auto *InnerIVDecl = cast<VarDecl>(IterationVarRef->getDecl());
13255   InnerIVDecl->setDeclName(&PP.getIdentifierTable().get(InnerIVName));
13256   auto MakeInnerRef = [this, InnerIVDecl, IVTy, OrigVarLoc]() {
13257     return buildDeclRefExpr(*this, InnerIVDecl, IVTy, OrigVarLoc);
13258   };
13259 
13260   // Make a copy of the NumIterations expression for each use: By the AST
13261   // constraints, every expression object in a DeclContext must be unique.
13262   CaptureVars CopyTransformer(*this);
13263   auto MakeNumIterations = [&CopyTransformer, &LoopHelper]() -> Expr * {
13264     return AssertSuccess(
13265         CopyTransformer.TransformExpr(LoopHelper.NumIterations));
13266   };
13267 
13268   // Inner For init-statement: auto .unroll_inner.iv = .unrolled.iv
13269   ExprResult LValueConv = DefaultLvalueConversion(MakeOuterRef());
13270   AddInitializerToDecl(InnerIVDecl, LValueConv.get(), /*DirectInit=*/false);
13271   StmtResult InnerInit = new (Context)
13272       DeclStmt(DeclGroupRef(InnerIVDecl), OrigVarLocBegin, OrigVarLocEnd);
13273   if (!InnerInit.isUsable())
13274     return StmtError();
13275 
13276   // Inner For cond-expression:
13277   // \code
13278   //   .unroll_inner.iv < .unrolled.iv + Factor &&
13279   //   .unroll_inner.iv < NumIterations
13280   // \endcode
13281   // This conjunction of two conditions allows ScalarEvolution to derive the
13282   // maximum trip count of the inner loop.
13283   ExprResult EndOfTile = BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(),
13284                                     BO_Add, MakeOuterRef(), MakeFactorExpr());
13285   if (!EndOfTile.isUsable())
13286     return StmtError();
13287   ExprResult InnerCond1 = BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(),
13288                                      BO_LE, MakeInnerRef(), EndOfTile.get());
13289   if (!InnerCond1.isUsable())
13290     return StmtError();
13291   ExprResult InnerCond2 =
13292       BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), BO_LE, MakeInnerRef(),
13293                  MakeNumIterations());
13294   if (!InnerCond2.isUsable())
13295     return StmtError();
13296   ExprResult InnerCond =
13297       BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), BO_LAnd,
13298                  InnerCond1.get(), InnerCond2.get());
13299   if (!InnerCond.isUsable())
13300     return StmtError();
13301 
13302   // Inner For incr-statement: ++.unroll_inner.iv
13303   ExprResult InnerIncr = BuildUnaryOp(CurScope, LoopHelper.Inc->getExprLoc(),
13304                                       UO_PreInc, MakeInnerRef());
13305   if (!InnerIncr.isUsable())
13306     return StmtError();
13307 
13308   // Inner For statement.
13309   SmallVector<Stmt *> InnerBodyStmts;
13310   InnerBodyStmts.append(LoopHelper.Updates.begin(), LoopHelper.Updates.end());
13311   InnerBodyStmts.push_back(Body);
13312   CompoundStmt *InnerBody = CompoundStmt::Create(
13313       Context, InnerBodyStmts, Body->getBeginLoc(), Body->getEndLoc());
13314   ForStmt *InnerFor = new (Context)
13315       ForStmt(Context, InnerInit.get(), InnerCond.get(), nullptr,
13316               InnerIncr.get(), InnerBody, LoopHelper.Init->getBeginLoc(),
13317               LoopHelper.Init->getBeginLoc(), LoopHelper.Inc->getEndLoc());
13318 
13319   // Unroll metadata for the inner loop.
13320   // This needs to take into account the remainder portion of the unrolled loop,
13321   // hence `unroll(full)` does not apply here, even though the LoopUnroll pass
13322   // supports multiple loop exits. Instead, unroll using a factor equivalent to
13323   // the maximum trip count, which will also generate a remainder loop. Just
13324   // `unroll(enable)` (which could have been useful if the user has not
13325   // specified a concrete factor; even though the outer loop cannot be
13326   // influenced anymore, would avoid more code bloat than necessary) will refuse
13327   // the loop because "Won't unroll; remainder loop could not be generated when
13328   // assuming runtime trip count". Even if it did work, it must not choose a
13329   // larger unroll factor than the maximum loop length, or it would always just
13330   // execute the remainder loop.
13331   LoopHintAttr *UnrollHintAttr =
13332       LoopHintAttr::CreateImplicit(Context, LoopHintAttr::UnrollCount,
13333                                    LoopHintAttr::Numeric, MakeFactorExpr());
13334   AttributedStmt *InnerUnrolled =
13335       AttributedStmt::Create(Context, StartLoc, {UnrollHintAttr}, InnerFor);
13336 
13337   // Outer For init-statement: auto .unrolled.iv = 0
13338   AddInitializerToDecl(
13339       OuterIVDecl, ActOnIntegerConstant(LoopHelper.Init->getExprLoc(), 0).get(),
13340       /*DirectInit=*/false);
13341   StmtResult OuterInit = new (Context)
13342       DeclStmt(DeclGroupRef(OuterIVDecl), OrigVarLocBegin, OrigVarLocEnd);
13343   if (!OuterInit.isUsable())
13344     return StmtError();
13345 
13346   // Outer For cond-expression: .unrolled.iv < NumIterations
13347   ExprResult OuterConde =
13348       BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), BO_LT, MakeOuterRef(),
13349                  MakeNumIterations());
13350   if (!OuterConde.isUsable())
13351     return StmtError();
13352 
13353   // Outer For incr-statement: .unrolled.iv += Factor
13354   ExprResult OuterIncr =
13355       BuildBinOp(CurScope, LoopHelper.Inc->getExprLoc(), BO_AddAssign,
13356                  MakeOuterRef(), MakeFactorExpr());
13357   if (!OuterIncr.isUsable())
13358     return StmtError();
13359 
13360   // Outer For statement.
13361   ForStmt *OuterFor = new (Context)
13362       ForStmt(Context, OuterInit.get(), OuterConde.get(), nullptr,
13363               OuterIncr.get(), InnerUnrolled, LoopHelper.Init->getBeginLoc(),
13364               LoopHelper.Init->getBeginLoc(), LoopHelper.Inc->getEndLoc());
13365 
13366   return OMPUnrollDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
13367                                     NumGeneratedLoops, OuterFor,
13368                                     buildPreInits(Context, PreInits));
13369 }
13370 
13371 OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
13372                                              SourceLocation StartLoc,
13373                                              SourceLocation LParenLoc,
13374                                              SourceLocation EndLoc) {
13375   OMPClause *Res = nullptr;
13376   switch (Kind) {
13377   case OMPC_final:
13378     Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
13379     break;
13380   case OMPC_num_threads:
13381     Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
13382     break;
13383   case OMPC_safelen:
13384     Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
13385     break;
13386   case OMPC_simdlen:
13387     Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
13388     break;
13389   case OMPC_allocator:
13390     Res = ActOnOpenMPAllocatorClause(Expr, StartLoc, LParenLoc, EndLoc);
13391     break;
13392   case OMPC_collapse:
13393     Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
13394     break;
13395   case OMPC_ordered:
13396     Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
13397     break;
13398   case OMPC_num_teams:
13399     Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
13400     break;
13401   case OMPC_thread_limit:
13402     Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
13403     break;
13404   case OMPC_priority:
13405     Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
13406     break;
13407   case OMPC_grainsize:
13408     Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
13409     break;
13410   case OMPC_num_tasks:
13411     Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
13412     break;
13413   case OMPC_hint:
13414     Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
13415     break;
13416   case OMPC_depobj:
13417     Res = ActOnOpenMPDepobjClause(Expr, StartLoc, LParenLoc, EndLoc);
13418     break;
13419   case OMPC_detach:
13420     Res = ActOnOpenMPDetachClause(Expr, StartLoc, LParenLoc, EndLoc);
13421     break;
13422   case OMPC_novariants:
13423     Res = ActOnOpenMPNovariantsClause(Expr, StartLoc, LParenLoc, EndLoc);
13424     break;
13425   case OMPC_nocontext:
13426     Res = ActOnOpenMPNocontextClause(Expr, StartLoc, LParenLoc, EndLoc);
13427     break;
13428   case OMPC_filter:
13429     Res = ActOnOpenMPFilterClause(Expr, StartLoc, LParenLoc, EndLoc);
13430     break;
13431   case OMPC_partial:
13432     Res = ActOnOpenMPPartialClause(Expr, StartLoc, LParenLoc, EndLoc);
13433     break;
13434   case OMPC_align:
13435     Res = ActOnOpenMPAlignClause(Expr, StartLoc, LParenLoc, EndLoc);
13436     break;
13437   case OMPC_device:
13438   case OMPC_if:
13439   case OMPC_default:
13440   case OMPC_proc_bind:
13441   case OMPC_schedule:
13442   case OMPC_private:
13443   case OMPC_firstprivate:
13444   case OMPC_lastprivate:
13445   case OMPC_shared:
13446   case OMPC_reduction:
13447   case OMPC_task_reduction:
13448   case OMPC_in_reduction:
13449   case OMPC_linear:
13450   case OMPC_aligned:
13451   case OMPC_copyin:
13452   case OMPC_copyprivate:
13453   case OMPC_nowait:
13454   case OMPC_untied:
13455   case OMPC_mergeable:
13456   case OMPC_threadprivate:
13457   case OMPC_sizes:
13458   case OMPC_allocate:
13459   case OMPC_flush:
13460   case OMPC_read:
13461   case OMPC_write:
13462   case OMPC_update:
13463   case OMPC_capture:
13464   case OMPC_seq_cst:
13465   case OMPC_acq_rel:
13466   case OMPC_acquire:
13467   case OMPC_release:
13468   case OMPC_relaxed:
13469   case OMPC_depend:
13470   case OMPC_threads:
13471   case OMPC_simd:
13472   case OMPC_map:
13473   case OMPC_nogroup:
13474   case OMPC_dist_schedule:
13475   case OMPC_defaultmap:
13476   case OMPC_unknown:
13477   case OMPC_uniform:
13478   case OMPC_to:
13479   case OMPC_from:
13480   case OMPC_use_device_ptr:
13481   case OMPC_use_device_addr:
13482   case OMPC_is_device_ptr:
13483   case OMPC_unified_address:
13484   case OMPC_unified_shared_memory:
13485   case OMPC_reverse_offload:
13486   case OMPC_dynamic_allocators:
13487   case OMPC_atomic_default_mem_order:
13488   case OMPC_device_type:
13489   case OMPC_match:
13490   case OMPC_nontemporal:
13491   case OMPC_order:
13492   case OMPC_destroy:
13493   case OMPC_inclusive:
13494   case OMPC_exclusive:
13495   case OMPC_uses_allocators:
13496   case OMPC_affinity:
13497   case OMPC_when:
13498   case OMPC_bind:
13499   default:
13500     llvm_unreachable("Clause is not allowed.");
13501   }
13502   return Res;
13503 }
13504 
13505 // An OpenMP directive such as 'target parallel' has two captured regions:
13506 // for the 'target' and 'parallel' respectively.  This function returns
13507 // the region in which to capture expressions associated with a clause.
13508 // A return value of OMPD_unknown signifies that the expression should not
13509 // be captured.
13510 static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
13511     OpenMPDirectiveKind DKind, OpenMPClauseKind CKind, unsigned OpenMPVersion,
13512     OpenMPDirectiveKind NameModifier = OMPD_unknown) {
13513   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
13514   switch (CKind) {
13515   case OMPC_if:
13516     switch (DKind) {
13517     case OMPD_target_parallel_for_simd:
13518       if (OpenMPVersion >= 50 &&
13519           (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) {
13520         CaptureRegion = OMPD_parallel;
13521         break;
13522       }
13523       LLVM_FALLTHROUGH;
13524     case OMPD_target_parallel:
13525     case OMPD_target_parallel_for:
13526       // If this clause applies to the nested 'parallel' region, capture within
13527       // the 'target' region, otherwise do not capture.
13528       if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
13529         CaptureRegion = OMPD_target;
13530       break;
13531     case OMPD_target_teams_distribute_parallel_for_simd:
13532       if (OpenMPVersion >= 50 &&
13533           (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) {
13534         CaptureRegion = OMPD_parallel;
13535         break;
13536       }
13537       LLVM_FALLTHROUGH;
13538     case OMPD_target_teams_distribute_parallel_for:
13539       // If this clause applies to the nested 'parallel' region, capture within
13540       // the 'teams' region, otherwise do not capture.
13541       if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
13542         CaptureRegion = OMPD_teams;
13543       break;
13544     case OMPD_teams_distribute_parallel_for_simd:
13545       if (OpenMPVersion >= 50 &&
13546           (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) {
13547         CaptureRegion = OMPD_parallel;
13548         break;
13549       }
13550       LLVM_FALLTHROUGH;
13551     case OMPD_teams_distribute_parallel_for:
13552       CaptureRegion = OMPD_teams;
13553       break;
13554     case OMPD_target_update:
13555     case OMPD_target_enter_data:
13556     case OMPD_target_exit_data:
13557       CaptureRegion = OMPD_task;
13558       break;
13559     case OMPD_parallel_master_taskloop:
13560       if (NameModifier == OMPD_unknown || NameModifier == OMPD_taskloop)
13561         CaptureRegion = OMPD_parallel;
13562       break;
13563     case OMPD_parallel_master_taskloop_simd:
13564       if ((OpenMPVersion <= 45 && NameModifier == OMPD_unknown) ||
13565           NameModifier == OMPD_taskloop) {
13566         CaptureRegion = OMPD_parallel;
13567         break;
13568       }
13569       if (OpenMPVersion <= 45)
13570         break;
13571       if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)
13572         CaptureRegion = OMPD_taskloop;
13573       break;
13574     case OMPD_parallel_for_simd:
13575       if (OpenMPVersion <= 45)
13576         break;
13577       if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)
13578         CaptureRegion = OMPD_parallel;
13579       break;
13580     case OMPD_taskloop_simd:
13581     case OMPD_master_taskloop_simd:
13582       if (OpenMPVersion <= 45)
13583         break;
13584       if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)
13585         CaptureRegion = OMPD_taskloop;
13586       break;
13587     case OMPD_distribute_parallel_for_simd:
13588       if (OpenMPVersion <= 45)
13589         break;
13590       if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)
13591         CaptureRegion = OMPD_parallel;
13592       break;
13593     case OMPD_target_simd:
13594       if (OpenMPVersion >= 50 &&
13595           (NameModifier == OMPD_unknown || NameModifier == OMPD_simd))
13596         CaptureRegion = OMPD_target;
13597       break;
13598     case OMPD_teams_distribute_simd:
13599     case OMPD_target_teams_distribute_simd:
13600       if (OpenMPVersion >= 50 &&
13601           (NameModifier == OMPD_unknown || NameModifier == OMPD_simd))
13602         CaptureRegion = OMPD_teams;
13603       break;
13604     case OMPD_cancel:
13605     case OMPD_parallel:
13606     case OMPD_parallel_master:
13607     case OMPD_parallel_sections:
13608     case OMPD_parallel_for:
13609     case OMPD_target:
13610     case OMPD_target_teams:
13611     case OMPD_target_teams_distribute:
13612     case OMPD_distribute_parallel_for:
13613     case OMPD_task:
13614     case OMPD_taskloop:
13615     case OMPD_master_taskloop:
13616     case OMPD_target_data:
13617     case OMPD_simd:
13618     case OMPD_for_simd:
13619     case OMPD_distribute_simd:
13620       // Do not capture if-clause expressions.
13621       break;
13622     case OMPD_threadprivate:
13623     case OMPD_allocate:
13624     case OMPD_taskyield:
13625     case OMPD_barrier:
13626     case OMPD_taskwait:
13627     case OMPD_cancellation_point:
13628     case OMPD_flush:
13629     case OMPD_depobj:
13630     case OMPD_scan:
13631     case OMPD_declare_reduction:
13632     case OMPD_declare_mapper:
13633     case OMPD_declare_simd:
13634     case OMPD_declare_variant:
13635     case OMPD_begin_declare_variant:
13636     case OMPD_end_declare_variant:
13637     case OMPD_declare_target:
13638     case OMPD_end_declare_target:
13639     case OMPD_loop:
13640     case OMPD_teams:
13641     case OMPD_tile:
13642     case OMPD_unroll:
13643     case OMPD_for:
13644     case OMPD_sections:
13645     case OMPD_section:
13646     case OMPD_single:
13647     case OMPD_master:
13648     case OMPD_masked:
13649     case OMPD_critical:
13650     case OMPD_taskgroup:
13651     case OMPD_distribute:
13652     case OMPD_ordered:
13653     case OMPD_atomic:
13654     case OMPD_teams_distribute:
13655     case OMPD_requires:
13656     case OMPD_metadirective:
13657       llvm_unreachable("Unexpected OpenMP directive with if-clause");
13658     case OMPD_unknown:
13659     default:
13660       llvm_unreachable("Unknown OpenMP directive");
13661     }
13662     break;
13663   case OMPC_num_threads:
13664     switch (DKind) {
13665     case OMPD_target_parallel:
13666     case OMPD_target_parallel_for:
13667     case OMPD_target_parallel_for_simd:
13668       CaptureRegion = OMPD_target;
13669       break;
13670     case OMPD_teams_distribute_parallel_for:
13671     case OMPD_teams_distribute_parallel_for_simd:
13672     case OMPD_target_teams_distribute_parallel_for:
13673     case OMPD_target_teams_distribute_parallel_for_simd:
13674       CaptureRegion = OMPD_teams;
13675       break;
13676     case OMPD_parallel:
13677     case OMPD_parallel_master:
13678     case OMPD_parallel_sections:
13679     case OMPD_parallel_for:
13680     case OMPD_parallel_for_simd:
13681     case OMPD_distribute_parallel_for:
13682     case OMPD_distribute_parallel_for_simd:
13683     case OMPD_parallel_master_taskloop:
13684     case OMPD_parallel_master_taskloop_simd:
13685       // Do not capture num_threads-clause expressions.
13686       break;
13687     case OMPD_target_data:
13688     case OMPD_target_enter_data:
13689     case OMPD_target_exit_data:
13690     case OMPD_target_update:
13691     case OMPD_target:
13692     case OMPD_target_simd:
13693     case OMPD_target_teams:
13694     case OMPD_target_teams_distribute:
13695     case OMPD_target_teams_distribute_simd:
13696     case OMPD_cancel:
13697     case OMPD_task:
13698     case OMPD_taskloop:
13699     case OMPD_taskloop_simd:
13700     case OMPD_master_taskloop:
13701     case OMPD_master_taskloop_simd:
13702     case OMPD_threadprivate:
13703     case OMPD_allocate:
13704     case OMPD_taskyield:
13705     case OMPD_barrier:
13706     case OMPD_taskwait:
13707     case OMPD_cancellation_point:
13708     case OMPD_flush:
13709     case OMPD_depobj:
13710     case OMPD_scan:
13711     case OMPD_declare_reduction:
13712     case OMPD_declare_mapper:
13713     case OMPD_declare_simd:
13714     case OMPD_declare_variant:
13715     case OMPD_begin_declare_variant:
13716     case OMPD_end_declare_variant:
13717     case OMPD_declare_target:
13718     case OMPD_end_declare_target:
13719     case OMPD_loop:
13720     case OMPD_teams:
13721     case OMPD_simd:
13722     case OMPD_tile:
13723     case OMPD_unroll:
13724     case OMPD_for:
13725     case OMPD_for_simd:
13726     case OMPD_sections:
13727     case OMPD_section:
13728     case OMPD_single:
13729     case OMPD_master:
13730     case OMPD_masked:
13731     case OMPD_critical:
13732     case OMPD_taskgroup:
13733     case OMPD_distribute:
13734     case OMPD_ordered:
13735     case OMPD_atomic:
13736     case OMPD_distribute_simd:
13737     case OMPD_teams_distribute:
13738     case OMPD_teams_distribute_simd:
13739     case OMPD_requires:
13740     case OMPD_metadirective:
13741       llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
13742     case OMPD_unknown:
13743     default:
13744       llvm_unreachable("Unknown OpenMP directive");
13745     }
13746     break;
13747   case OMPC_num_teams:
13748     switch (DKind) {
13749     case OMPD_target_teams:
13750     case OMPD_target_teams_distribute:
13751     case OMPD_target_teams_distribute_simd:
13752     case OMPD_target_teams_distribute_parallel_for:
13753     case OMPD_target_teams_distribute_parallel_for_simd:
13754       CaptureRegion = OMPD_target;
13755       break;
13756     case OMPD_teams_distribute_parallel_for:
13757     case OMPD_teams_distribute_parallel_for_simd:
13758     case OMPD_teams:
13759     case OMPD_teams_distribute:
13760     case OMPD_teams_distribute_simd:
13761       // Do not capture num_teams-clause expressions.
13762       break;
13763     case OMPD_distribute_parallel_for:
13764     case OMPD_distribute_parallel_for_simd:
13765     case OMPD_task:
13766     case OMPD_taskloop:
13767     case OMPD_taskloop_simd:
13768     case OMPD_master_taskloop:
13769     case OMPD_master_taskloop_simd:
13770     case OMPD_parallel_master_taskloop:
13771     case OMPD_parallel_master_taskloop_simd:
13772     case OMPD_target_data:
13773     case OMPD_target_enter_data:
13774     case OMPD_target_exit_data:
13775     case OMPD_target_update:
13776     case OMPD_cancel:
13777     case OMPD_parallel:
13778     case OMPD_parallel_master:
13779     case OMPD_parallel_sections:
13780     case OMPD_parallel_for:
13781     case OMPD_parallel_for_simd:
13782     case OMPD_target:
13783     case OMPD_target_simd:
13784     case OMPD_target_parallel:
13785     case OMPD_target_parallel_for:
13786     case OMPD_target_parallel_for_simd:
13787     case OMPD_threadprivate:
13788     case OMPD_allocate:
13789     case OMPD_taskyield:
13790     case OMPD_barrier:
13791     case OMPD_taskwait:
13792     case OMPD_cancellation_point:
13793     case OMPD_flush:
13794     case OMPD_depobj:
13795     case OMPD_scan:
13796     case OMPD_declare_reduction:
13797     case OMPD_declare_mapper:
13798     case OMPD_declare_simd:
13799     case OMPD_declare_variant:
13800     case OMPD_begin_declare_variant:
13801     case OMPD_end_declare_variant:
13802     case OMPD_declare_target:
13803     case OMPD_end_declare_target:
13804     case OMPD_loop:
13805     case OMPD_simd:
13806     case OMPD_tile:
13807     case OMPD_unroll:
13808     case OMPD_for:
13809     case OMPD_for_simd:
13810     case OMPD_sections:
13811     case OMPD_section:
13812     case OMPD_single:
13813     case OMPD_master:
13814     case OMPD_masked:
13815     case OMPD_critical:
13816     case OMPD_taskgroup:
13817     case OMPD_distribute:
13818     case OMPD_ordered:
13819     case OMPD_atomic:
13820     case OMPD_distribute_simd:
13821     case OMPD_requires:
13822     case OMPD_metadirective:
13823       llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
13824     case OMPD_unknown:
13825     default:
13826       llvm_unreachable("Unknown OpenMP directive");
13827     }
13828     break;
13829   case OMPC_thread_limit:
13830     switch (DKind) {
13831     case OMPD_target_teams:
13832     case OMPD_target_teams_distribute:
13833     case OMPD_target_teams_distribute_simd:
13834     case OMPD_target_teams_distribute_parallel_for:
13835     case OMPD_target_teams_distribute_parallel_for_simd:
13836       CaptureRegion = OMPD_target;
13837       break;
13838     case OMPD_teams_distribute_parallel_for:
13839     case OMPD_teams_distribute_parallel_for_simd:
13840     case OMPD_teams:
13841     case OMPD_teams_distribute:
13842     case OMPD_teams_distribute_simd:
13843       // Do not capture thread_limit-clause expressions.
13844       break;
13845     case OMPD_distribute_parallel_for:
13846     case OMPD_distribute_parallel_for_simd:
13847     case OMPD_task:
13848     case OMPD_taskloop:
13849     case OMPD_taskloop_simd:
13850     case OMPD_master_taskloop:
13851     case OMPD_master_taskloop_simd:
13852     case OMPD_parallel_master_taskloop:
13853     case OMPD_parallel_master_taskloop_simd:
13854     case OMPD_target_data:
13855     case OMPD_target_enter_data:
13856     case OMPD_target_exit_data:
13857     case OMPD_target_update:
13858     case OMPD_cancel:
13859     case OMPD_parallel:
13860     case OMPD_parallel_master:
13861     case OMPD_parallel_sections:
13862     case OMPD_parallel_for:
13863     case OMPD_parallel_for_simd:
13864     case OMPD_target:
13865     case OMPD_target_simd:
13866     case OMPD_target_parallel:
13867     case OMPD_target_parallel_for:
13868     case OMPD_target_parallel_for_simd:
13869     case OMPD_threadprivate:
13870     case OMPD_allocate:
13871     case OMPD_taskyield:
13872     case OMPD_barrier:
13873     case OMPD_taskwait:
13874     case OMPD_cancellation_point:
13875     case OMPD_flush:
13876     case OMPD_depobj:
13877     case OMPD_scan:
13878     case OMPD_declare_reduction:
13879     case OMPD_declare_mapper:
13880     case OMPD_declare_simd:
13881     case OMPD_declare_variant:
13882     case OMPD_begin_declare_variant:
13883     case OMPD_end_declare_variant:
13884     case OMPD_declare_target:
13885     case OMPD_end_declare_target:
13886     case OMPD_loop:
13887     case OMPD_simd:
13888     case OMPD_tile:
13889     case OMPD_unroll:
13890     case OMPD_for:
13891     case OMPD_for_simd:
13892     case OMPD_sections:
13893     case OMPD_section:
13894     case OMPD_single:
13895     case OMPD_master:
13896     case OMPD_masked:
13897     case OMPD_critical:
13898     case OMPD_taskgroup:
13899     case OMPD_distribute:
13900     case OMPD_ordered:
13901     case OMPD_atomic:
13902     case OMPD_distribute_simd:
13903     case OMPD_requires:
13904     case OMPD_metadirective:
13905       llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
13906     case OMPD_unknown:
13907     default:
13908       llvm_unreachable("Unknown OpenMP directive");
13909     }
13910     break;
13911   case OMPC_schedule:
13912     switch (DKind) {
13913     case OMPD_parallel_for:
13914     case OMPD_parallel_for_simd:
13915     case OMPD_distribute_parallel_for:
13916     case OMPD_distribute_parallel_for_simd:
13917     case OMPD_teams_distribute_parallel_for:
13918     case OMPD_teams_distribute_parallel_for_simd:
13919     case OMPD_target_parallel_for:
13920     case OMPD_target_parallel_for_simd:
13921     case OMPD_target_teams_distribute_parallel_for:
13922     case OMPD_target_teams_distribute_parallel_for_simd:
13923       CaptureRegion = OMPD_parallel;
13924       break;
13925     case OMPD_for:
13926     case OMPD_for_simd:
13927       // Do not capture schedule-clause expressions.
13928       break;
13929     case OMPD_task:
13930     case OMPD_taskloop:
13931     case OMPD_taskloop_simd:
13932     case OMPD_master_taskloop:
13933     case OMPD_master_taskloop_simd:
13934     case OMPD_parallel_master_taskloop:
13935     case OMPD_parallel_master_taskloop_simd:
13936     case OMPD_target_data:
13937     case OMPD_target_enter_data:
13938     case OMPD_target_exit_data:
13939     case OMPD_target_update:
13940     case OMPD_teams:
13941     case OMPD_teams_distribute:
13942     case OMPD_teams_distribute_simd:
13943     case OMPD_target_teams_distribute:
13944     case OMPD_target_teams_distribute_simd:
13945     case OMPD_target:
13946     case OMPD_target_simd:
13947     case OMPD_target_parallel:
13948     case OMPD_cancel:
13949     case OMPD_parallel:
13950     case OMPD_parallel_master:
13951     case OMPD_parallel_sections:
13952     case OMPD_threadprivate:
13953     case OMPD_allocate:
13954     case OMPD_taskyield:
13955     case OMPD_barrier:
13956     case OMPD_taskwait:
13957     case OMPD_cancellation_point:
13958     case OMPD_flush:
13959     case OMPD_depobj:
13960     case OMPD_scan:
13961     case OMPD_declare_reduction:
13962     case OMPD_declare_mapper:
13963     case OMPD_declare_simd:
13964     case OMPD_declare_variant:
13965     case OMPD_begin_declare_variant:
13966     case OMPD_end_declare_variant:
13967     case OMPD_declare_target:
13968     case OMPD_end_declare_target:
13969     case OMPD_loop:
13970     case OMPD_simd:
13971     case OMPD_tile:
13972     case OMPD_unroll:
13973     case OMPD_sections:
13974     case OMPD_section:
13975     case OMPD_single:
13976     case OMPD_master:
13977     case OMPD_masked:
13978     case OMPD_critical:
13979     case OMPD_taskgroup:
13980     case OMPD_distribute:
13981     case OMPD_ordered:
13982     case OMPD_atomic:
13983     case OMPD_distribute_simd:
13984     case OMPD_target_teams:
13985     case OMPD_requires:
13986     case OMPD_metadirective:
13987       llvm_unreachable("Unexpected OpenMP directive with schedule clause");
13988     case OMPD_unknown:
13989     default:
13990       llvm_unreachable("Unknown OpenMP directive");
13991     }
13992     break;
13993   case OMPC_dist_schedule:
13994     switch (DKind) {
13995     case OMPD_teams_distribute_parallel_for:
13996     case OMPD_teams_distribute_parallel_for_simd:
13997     case OMPD_teams_distribute:
13998     case OMPD_teams_distribute_simd:
13999     case OMPD_target_teams_distribute_parallel_for:
14000     case OMPD_target_teams_distribute_parallel_for_simd:
14001     case OMPD_target_teams_distribute:
14002     case OMPD_target_teams_distribute_simd:
14003       CaptureRegion = OMPD_teams;
14004       break;
14005     case OMPD_distribute_parallel_for:
14006     case OMPD_distribute_parallel_for_simd:
14007     case OMPD_distribute:
14008     case OMPD_distribute_simd:
14009       // Do not capture dist_schedule-clause expressions.
14010       break;
14011     case OMPD_parallel_for:
14012     case OMPD_parallel_for_simd:
14013     case OMPD_target_parallel_for_simd:
14014     case OMPD_target_parallel_for:
14015     case OMPD_task:
14016     case OMPD_taskloop:
14017     case OMPD_taskloop_simd:
14018     case OMPD_master_taskloop:
14019     case OMPD_master_taskloop_simd:
14020     case OMPD_parallel_master_taskloop:
14021     case OMPD_parallel_master_taskloop_simd:
14022     case OMPD_target_data:
14023     case OMPD_target_enter_data:
14024     case OMPD_target_exit_data:
14025     case OMPD_target_update:
14026     case OMPD_teams:
14027     case OMPD_target:
14028     case OMPD_target_simd:
14029     case OMPD_target_parallel:
14030     case OMPD_cancel:
14031     case OMPD_parallel:
14032     case OMPD_parallel_master:
14033     case OMPD_parallel_sections:
14034     case OMPD_threadprivate:
14035     case OMPD_allocate:
14036     case OMPD_taskyield:
14037     case OMPD_barrier:
14038     case OMPD_taskwait:
14039     case OMPD_cancellation_point:
14040     case OMPD_flush:
14041     case OMPD_depobj:
14042     case OMPD_scan:
14043     case OMPD_declare_reduction:
14044     case OMPD_declare_mapper:
14045     case OMPD_declare_simd:
14046     case OMPD_declare_variant:
14047     case OMPD_begin_declare_variant:
14048     case OMPD_end_declare_variant:
14049     case OMPD_declare_target:
14050     case OMPD_end_declare_target:
14051     case OMPD_loop:
14052     case OMPD_simd:
14053     case OMPD_tile:
14054     case OMPD_unroll:
14055     case OMPD_for:
14056     case OMPD_for_simd:
14057     case OMPD_sections:
14058     case OMPD_section:
14059     case OMPD_single:
14060     case OMPD_master:
14061     case OMPD_masked:
14062     case OMPD_critical:
14063     case OMPD_taskgroup:
14064     case OMPD_ordered:
14065     case OMPD_atomic:
14066     case OMPD_target_teams:
14067     case OMPD_requires:
14068     case OMPD_metadirective:
14069       llvm_unreachable("Unexpected OpenMP directive with dist_schedule clause");
14070     case OMPD_unknown:
14071     default:
14072       llvm_unreachable("Unknown OpenMP directive");
14073     }
14074     break;
14075   case OMPC_device:
14076     switch (DKind) {
14077     case OMPD_target_update:
14078     case OMPD_target_enter_data:
14079     case OMPD_target_exit_data:
14080     case OMPD_target:
14081     case OMPD_target_simd:
14082     case OMPD_target_teams:
14083     case OMPD_target_parallel:
14084     case OMPD_target_teams_distribute:
14085     case OMPD_target_teams_distribute_simd:
14086     case OMPD_target_parallel_for:
14087     case OMPD_target_parallel_for_simd:
14088     case OMPD_target_teams_distribute_parallel_for:
14089     case OMPD_target_teams_distribute_parallel_for_simd:
14090     case OMPD_dispatch:
14091       CaptureRegion = OMPD_task;
14092       break;
14093     case OMPD_target_data:
14094     case OMPD_interop:
14095       // Do not capture device-clause expressions.
14096       break;
14097     case OMPD_teams_distribute_parallel_for:
14098     case OMPD_teams_distribute_parallel_for_simd:
14099     case OMPD_teams:
14100     case OMPD_teams_distribute:
14101     case OMPD_teams_distribute_simd:
14102     case OMPD_distribute_parallel_for:
14103     case OMPD_distribute_parallel_for_simd:
14104     case OMPD_task:
14105     case OMPD_taskloop:
14106     case OMPD_taskloop_simd:
14107     case OMPD_master_taskloop:
14108     case OMPD_master_taskloop_simd:
14109     case OMPD_parallel_master_taskloop:
14110     case OMPD_parallel_master_taskloop_simd:
14111     case OMPD_cancel:
14112     case OMPD_parallel:
14113     case OMPD_parallel_master:
14114     case OMPD_parallel_sections:
14115     case OMPD_parallel_for:
14116     case OMPD_parallel_for_simd:
14117     case OMPD_threadprivate:
14118     case OMPD_allocate:
14119     case OMPD_taskyield:
14120     case OMPD_barrier:
14121     case OMPD_taskwait:
14122     case OMPD_cancellation_point:
14123     case OMPD_flush:
14124     case OMPD_depobj:
14125     case OMPD_scan:
14126     case OMPD_declare_reduction:
14127     case OMPD_declare_mapper:
14128     case OMPD_declare_simd:
14129     case OMPD_declare_variant:
14130     case OMPD_begin_declare_variant:
14131     case OMPD_end_declare_variant:
14132     case OMPD_declare_target:
14133     case OMPD_end_declare_target:
14134     case OMPD_loop:
14135     case OMPD_simd:
14136     case OMPD_tile:
14137     case OMPD_unroll:
14138     case OMPD_for:
14139     case OMPD_for_simd:
14140     case OMPD_sections:
14141     case OMPD_section:
14142     case OMPD_single:
14143     case OMPD_master:
14144     case OMPD_masked:
14145     case OMPD_critical:
14146     case OMPD_taskgroup:
14147     case OMPD_distribute:
14148     case OMPD_ordered:
14149     case OMPD_atomic:
14150     case OMPD_distribute_simd:
14151     case OMPD_requires:
14152     case OMPD_metadirective:
14153       llvm_unreachable("Unexpected OpenMP directive with device-clause");
14154     case OMPD_unknown:
14155     default:
14156       llvm_unreachable("Unknown OpenMP directive");
14157     }
14158     break;
14159   case OMPC_grainsize:
14160   case OMPC_num_tasks:
14161   case OMPC_final:
14162   case OMPC_priority:
14163     switch (DKind) {
14164     case OMPD_task:
14165     case OMPD_taskloop:
14166     case OMPD_taskloop_simd:
14167     case OMPD_master_taskloop:
14168     case OMPD_master_taskloop_simd:
14169       break;
14170     case OMPD_parallel_master_taskloop:
14171     case OMPD_parallel_master_taskloop_simd:
14172       CaptureRegion = OMPD_parallel;
14173       break;
14174     case OMPD_target_update:
14175     case OMPD_target_enter_data:
14176     case OMPD_target_exit_data:
14177     case OMPD_target:
14178     case OMPD_target_simd:
14179     case OMPD_target_teams:
14180     case OMPD_target_parallel:
14181     case OMPD_target_teams_distribute:
14182     case OMPD_target_teams_distribute_simd:
14183     case OMPD_target_parallel_for:
14184     case OMPD_target_parallel_for_simd:
14185     case OMPD_target_teams_distribute_parallel_for:
14186     case OMPD_target_teams_distribute_parallel_for_simd:
14187     case OMPD_target_data:
14188     case OMPD_teams_distribute_parallel_for:
14189     case OMPD_teams_distribute_parallel_for_simd:
14190     case OMPD_teams:
14191     case OMPD_teams_distribute:
14192     case OMPD_teams_distribute_simd:
14193     case OMPD_distribute_parallel_for:
14194     case OMPD_distribute_parallel_for_simd:
14195     case OMPD_cancel:
14196     case OMPD_parallel:
14197     case OMPD_parallel_master:
14198     case OMPD_parallel_sections:
14199     case OMPD_parallel_for:
14200     case OMPD_parallel_for_simd:
14201     case OMPD_threadprivate:
14202     case OMPD_allocate:
14203     case OMPD_taskyield:
14204     case OMPD_barrier:
14205     case OMPD_taskwait:
14206     case OMPD_cancellation_point:
14207     case OMPD_flush:
14208     case OMPD_depobj:
14209     case OMPD_scan:
14210     case OMPD_declare_reduction:
14211     case OMPD_declare_mapper:
14212     case OMPD_declare_simd:
14213     case OMPD_declare_variant:
14214     case OMPD_begin_declare_variant:
14215     case OMPD_end_declare_variant:
14216     case OMPD_declare_target:
14217     case OMPD_end_declare_target:
14218     case OMPD_loop:
14219     case OMPD_simd:
14220     case OMPD_tile:
14221     case OMPD_unroll:
14222     case OMPD_for:
14223     case OMPD_for_simd:
14224     case OMPD_sections:
14225     case OMPD_section:
14226     case OMPD_single:
14227     case OMPD_master:
14228     case OMPD_masked:
14229     case OMPD_critical:
14230     case OMPD_taskgroup:
14231     case OMPD_distribute:
14232     case OMPD_ordered:
14233     case OMPD_atomic:
14234     case OMPD_distribute_simd:
14235     case OMPD_requires:
14236     case OMPD_metadirective:
14237       llvm_unreachable("Unexpected OpenMP directive with grainsize-clause");
14238     case OMPD_unknown:
14239     default:
14240       llvm_unreachable("Unknown OpenMP directive");
14241     }
14242     break;
14243   case OMPC_novariants:
14244   case OMPC_nocontext:
14245     switch (DKind) {
14246     case OMPD_dispatch:
14247       CaptureRegion = OMPD_task;
14248       break;
14249     default:
14250       llvm_unreachable("Unexpected OpenMP directive");
14251     }
14252     break;
14253   case OMPC_filter:
14254     // Do not capture filter-clause expressions.
14255     break;
14256   case OMPC_when:
14257     if (DKind == OMPD_metadirective) {
14258       CaptureRegion = OMPD_metadirective;
14259     } else if (DKind == OMPD_unknown) {
14260       llvm_unreachable("Unknown OpenMP directive");
14261     } else {
14262       llvm_unreachable("Unexpected OpenMP directive with when clause");
14263     }
14264     break;
14265   case OMPC_firstprivate:
14266   case OMPC_lastprivate:
14267   case OMPC_reduction:
14268   case OMPC_task_reduction:
14269   case OMPC_in_reduction:
14270   case OMPC_linear:
14271   case OMPC_default:
14272   case OMPC_proc_bind:
14273   case OMPC_safelen:
14274   case OMPC_simdlen:
14275   case OMPC_sizes:
14276   case OMPC_allocator:
14277   case OMPC_collapse:
14278   case OMPC_private:
14279   case OMPC_shared:
14280   case OMPC_aligned:
14281   case OMPC_copyin:
14282   case OMPC_copyprivate:
14283   case OMPC_ordered:
14284   case OMPC_nowait:
14285   case OMPC_untied:
14286   case OMPC_mergeable:
14287   case OMPC_threadprivate:
14288   case OMPC_allocate:
14289   case OMPC_flush:
14290   case OMPC_depobj:
14291   case OMPC_read:
14292   case OMPC_write:
14293   case OMPC_update:
14294   case OMPC_capture:
14295   case OMPC_seq_cst:
14296   case OMPC_acq_rel:
14297   case OMPC_acquire:
14298   case OMPC_release:
14299   case OMPC_relaxed:
14300   case OMPC_depend:
14301   case OMPC_threads:
14302   case OMPC_simd:
14303   case OMPC_map:
14304   case OMPC_nogroup:
14305   case OMPC_hint:
14306   case OMPC_defaultmap:
14307   case OMPC_unknown:
14308   case OMPC_uniform:
14309   case OMPC_to:
14310   case OMPC_from:
14311   case OMPC_use_device_ptr:
14312   case OMPC_use_device_addr:
14313   case OMPC_is_device_ptr:
14314   case OMPC_unified_address:
14315   case OMPC_unified_shared_memory:
14316   case OMPC_reverse_offload:
14317   case OMPC_dynamic_allocators:
14318   case OMPC_atomic_default_mem_order:
14319   case OMPC_device_type:
14320   case OMPC_match:
14321   case OMPC_nontemporal:
14322   case OMPC_order:
14323   case OMPC_destroy:
14324   case OMPC_detach:
14325   case OMPC_inclusive:
14326   case OMPC_exclusive:
14327   case OMPC_uses_allocators:
14328   case OMPC_affinity:
14329   case OMPC_bind:
14330   default:
14331     llvm_unreachable("Unexpected OpenMP clause.");
14332   }
14333   return CaptureRegion;
14334 }
14335 
14336 OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
14337                                      Expr *Condition, SourceLocation StartLoc,
14338                                      SourceLocation LParenLoc,
14339                                      SourceLocation NameModifierLoc,
14340                                      SourceLocation ColonLoc,
14341                                      SourceLocation EndLoc) {
14342   Expr *ValExpr = Condition;
14343   Stmt *HelperValStmt = nullptr;
14344   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
14345   if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
14346       !Condition->isInstantiationDependent() &&
14347       !Condition->containsUnexpandedParameterPack()) {
14348     ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
14349     if (Val.isInvalid())
14350       return nullptr;
14351 
14352     ValExpr = Val.get();
14353 
14354     OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
14355     CaptureRegion = getOpenMPCaptureRegionForClause(
14356         DKind, OMPC_if, LangOpts.OpenMP, NameModifier);
14357     if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
14358       ValExpr = MakeFullExpr(ValExpr).get();
14359       llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
14360       ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
14361       HelperValStmt = buildPreInits(Context, Captures);
14362     }
14363   }
14364 
14365   return new (Context)
14366       OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
14367                   LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
14368 }
14369 
14370 OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
14371                                         SourceLocation StartLoc,
14372                                         SourceLocation LParenLoc,
14373                                         SourceLocation EndLoc) {
14374   Expr *ValExpr = Condition;
14375   Stmt *HelperValStmt = nullptr;
14376   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
14377   if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
14378       !Condition->isInstantiationDependent() &&
14379       !Condition->containsUnexpandedParameterPack()) {
14380     ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
14381     if (Val.isInvalid())
14382       return nullptr;
14383 
14384     ValExpr = MakeFullExpr(Val.get()).get();
14385 
14386     OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
14387     CaptureRegion =
14388         getOpenMPCaptureRegionForClause(DKind, OMPC_final, LangOpts.OpenMP);
14389     if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
14390       ValExpr = MakeFullExpr(ValExpr).get();
14391       llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
14392       ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
14393       HelperValStmt = buildPreInits(Context, Captures);
14394     }
14395   }
14396 
14397   return new (Context) OMPFinalClause(ValExpr, HelperValStmt, CaptureRegion,
14398                                       StartLoc, LParenLoc, EndLoc);
14399 }
14400 
14401 ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
14402                                                         Expr *Op) {
14403   if (!Op)
14404     return ExprError();
14405 
14406   class IntConvertDiagnoser : public ICEConvertDiagnoser {
14407   public:
14408     IntConvertDiagnoser()
14409         : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
14410     SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
14411                                          QualType T) override {
14412       return S.Diag(Loc, diag::err_omp_not_integral) << T;
14413     }
14414     SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
14415                                              QualType T) override {
14416       return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
14417     }
14418     SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
14419                                                QualType T,
14420                                                QualType ConvTy) override {
14421       return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
14422     }
14423     SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
14424                                            QualType ConvTy) override {
14425       return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
14426              << ConvTy->isEnumeralType() << ConvTy;
14427     }
14428     SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
14429                                             QualType T) override {
14430       return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
14431     }
14432     SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
14433                                         QualType ConvTy) override {
14434       return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
14435              << ConvTy->isEnumeralType() << ConvTy;
14436     }
14437     SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
14438                                              QualType) override {
14439       llvm_unreachable("conversion functions are permitted");
14440     }
14441   } ConvertDiagnoser;
14442   return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
14443 }
14444 
14445 static bool
14446 isNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef, OpenMPClauseKind CKind,
14447                           bool StrictlyPositive, bool BuildCapture = false,
14448                           OpenMPDirectiveKind DKind = OMPD_unknown,
14449                           OpenMPDirectiveKind *CaptureRegion = nullptr,
14450                           Stmt **HelperValStmt = nullptr) {
14451   if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
14452       !ValExpr->isInstantiationDependent()) {
14453     SourceLocation Loc = ValExpr->getExprLoc();
14454     ExprResult Value =
14455         SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
14456     if (Value.isInvalid())
14457       return false;
14458 
14459     ValExpr = Value.get();
14460     // The expression must evaluate to a non-negative integer value.
14461     if (Optional<llvm::APSInt> Result =
14462             ValExpr->getIntegerConstantExpr(SemaRef.Context)) {
14463       if (Result->isSigned() &&
14464           !((!StrictlyPositive && Result->isNonNegative()) ||
14465             (StrictlyPositive && Result->isStrictlyPositive()))) {
14466         SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
14467             << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
14468             << ValExpr->getSourceRange();
14469         return false;
14470       }
14471     }
14472     if (!BuildCapture)
14473       return true;
14474     *CaptureRegion =
14475         getOpenMPCaptureRegionForClause(DKind, CKind, SemaRef.LangOpts.OpenMP);
14476     if (*CaptureRegion != OMPD_unknown &&
14477         !SemaRef.CurContext->isDependentContext()) {
14478       ValExpr = SemaRef.MakeFullExpr(ValExpr).get();
14479       llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
14480       ValExpr = tryBuildCapture(SemaRef, ValExpr, Captures).get();
14481       *HelperValStmt = buildPreInits(SemaRef.Context, Captures);
14482     }
14483   }
14484   return true;
14485 }
14486 
14487 OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
14488                                              SourceLocation StartLoc,
14489                                              SourceLocation LParenLoc,
14490                                              SourceLocation EndLoc) {
14491   Expr *ValExpr = NumThreads;
14492   Stmt *HelperValStmt = nullptr;
14493 
14494   // OpenMP [2.5, Restrictions]
14495   //  The num_threads expression must evaluate to a positive integer value.
14496   if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
14497                                  /*StrictlyPositive=*/true))
14498     return nullptr;
14499 
14500   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
14501   OpenMPDirectiveKind CaptureRegion =
14502       getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads, LangOpts.OpenMP);
14503   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
14504     ValExpr = MakeFullExpr(ValExpr).get();
14505     llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
14506     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
14507     HelperValStmt = buildPreInits(Context, Captures);
14508   }
14509 
14510   return new (Context) OMPNumThreadsClause(
14511       ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
14512 }
14513 
14514 ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
14515                                                        OpenMPClauseKind CKind,
14516                                                        bool StrictlyPositive,
14517                                                        bool SuppressExprDiags) {
14518   if (!E)
14519     return ExprError();
14520   if (E->isValueDependent() || E->isTypeDependent() ||
14521       E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
14522     return E;
14523 
14524   llvm::APSInt Result;
14525   ExprResult ICE;
14526   if (SuppressExprDiags) {
14527     // Use a custom diagnoser that suppresses 'note' diagnostics about the
14528     // expression.
14529     struct SuppressedDiagnoser : public Sema::VerifyICEDiagnoser {
14530       SuppressedDiagnoser() : VerifyICEDiagnoser(/*Suppress=*/true) {}
14531       Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
14532                                                  SourceLocation Loc) override {
14533         llvm_unreachable("Diagnostic suppressed");
14534       }
14535     } Diagnoser;
14536     ICE = VerifyIntegerConstantExpression(E, &Result, Diagnoser, AllowFold);
14537   } else {
14538     ICE = VerifyIntegerConstantExpression(E, &Result, /*FIXME*/ AllowFold);
14539   }
14540   if (ICE.isInvalid())
14541     return ExprError();
14542 
14543   if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
14544       (!StrictlyPositive && !Result.isNonNegative())) {
14545     Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
14546         << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
14547         << E->getSourceRange();
14548     return ExprError();
14549   }
14550   if ((CKind == OMPC_aligned || CKind == OMPC_align) && !Result.isPowerOf2()) {
14551     Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
14552         << E->getSourceRange();
14553     return ExprError();
14554   }
14555   if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
14556     DSAStack->setAssociatedLoops(Result.getExtValue());
14557   else if (CKind == OMPC_ordered)
14558     DSAStack->setAssociatedLoops(Result.getExtValue());
14559   return ICE;
14560 }
14561 
14562 OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
14563                                           SourceLocation LParenLoc,
14564                                           SourceLocation EndLoc) {
14565   // OpenMP [2.8.1, simd construct, Description]
14566   // The parameter of the safelen clause must be a constant
14567   // positive integer expression.
14568   ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
14569   if (Safelen.isInvalid())
14570     return nullptr;
14571   return new (Context)
14572       OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
14573 }
14574 
14575 OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
14576                                           SourceLocation LParenLoc,
14577                                           SourceLocation EndLoc) {
14578   // OpenMP [2.8.1, simd construct, Description]
14579   // The parameter of the simdlen clause must be a constant
14580   // positive integer expression.
14581   ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
14582   if (Simdlen.isInvalid())
14583     return nullptr;
14584   return new (Context)
14585       OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
14586 }
14587 
14588 /// Tries to find omp_allocator_handle_t type.
14589 static bool findOMPAllocatorHandleT(Sema &S, SourceLocation Loc,
14590                                     DSAStackTy *Stack) {
14591   QualType OMPAllocatorHandleT = Stack->getOMPAllocatorHandleT();
14592   if (!OMPAllocatorHandleT.isNull())
14593     return true;
14594   // Build the predefined allocator expressions.
14595   bool ErrorFound = false;
14596   for (int I = 0; I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
14597     auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
14598     StringRef Allocator =
14599         OMPAllocateDeclAttr::ConvertAllocatorTypeTyToStr(AllocatorKind);
14600     DeclarationName AllocatorName = &S.getASTContext().Idents.get(Allocator);
14601     auto *VD = dyn_cast_or_null<ValueDecl>(
14602         S.LookupSingleName(S.TUScope, AllocatorName, Loc, Sema::LookupAnyName));
14603     if (!VD) {
14604       ErrorFound = true;
14605       break;
14606     }
14607     QualType AllocatorType =
14608         VD->getType().getNonLValueExprType(S.getASTContext());
14609     ExprResult Res = S.BuildDeclRefExpr(VD, AllocatorType, VK_LValue, Loc);
14610     if (!Res.isUsable()) {
14611       ErrorFound = true;
14612       break;
14613     }
14614     if (OMPAllocatorHandleT.isNull())
14615       OMPAllocatorHandleT = AllocatorType;
14616     if (!S.getASTContext().hasSameType(OMPAllocatorHandleT, AllocatorType)) {
14617       ErrorFound = true;
14618       break;
14619     }
14620     Stack->setAllocator(AllocatorKind, Res.get());
14621   }
14622   if (ErrorFound) {
14623     S.Diag(Loc, diag::err_omp_implied_type_not_found)
14624         << "omp_allocator_handle_t";
14625     return false;
14626   }
14627   OMPAllocatorHandleT.addConst();
14628   Stack->setOMPAllocatorHandleT(OMPAllocatorHandleT);
14629   return true;
14630 }
14631 
14632 OMPClause *Sema::ActOnOpenMPAllocatorClause(Expr *A, SourceLocation StartLoc,
14633                                             SourceLocation LParenLoc,
14634                                             SourceLocation EndLoc) {
14635   // OpenMP [2.11.3, allocate Directive, Description]
14636   // allocator is an expression of omp_allocator_handle_t type.
14637   if (!findOMPAllocatorHandleT(*this, A->getExprLoc(), DSAStack))
14638     return nullptr;
14639 
14640   ExprResult Allocator = DefaultLvalueConversion(A);
14641   if (Allocator.isInvalid())
14642     return nullptr;
14643   Allocator = PerformImplicitConversion(Allocator.get(),
14644                                         DSAStack->getOMPAllocatorHandleT(),
14645                                         Sema::AA_Initializing,
14646                                         /*AllowExplicit=*/true);
14647   if (Allocator.isInvalid())
14648     return nullptr;
14649   return new (Context)
14650       OMPAllocatorClause(Allocator.get(), StartLoc, LParenLoc, EndLoc);
14651 }
14652 
14653 OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
14654                                            SourceLocation StartLoc,
14655                                            SourceLocation LParenLoc,
14656                                            SourceLocation EndLoc) {
14657   // OpenMP [2.7.1, loop construct, Description]
14658   // OpenMP [2.8.1, simd construct, Description]
14659   // OpenMP [2.9.6, distribute construct, Description]
14660   // The parameter of the collapse clause must be a constant
14661   // positive integer expression.
14662   ExprResult NumForLoopsResult =
14663       VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
14664   if (NumForLoopsResult.isInvalid())
14665     return nullptr;
14666   return new (Context)
14667       OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
14668 }
14669 
14670 OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
14671                                           SourceLocation EndLoc,
14672                                           SourceLocation LParenLoc,
14673                                           Expr *NumForLoops) {
14674   // OpenMP [2.7.1, loop construct, Description]
14675   // OpenMP [2.8.1, simd construct, Description]
14676   // OpenMP [2.9.6, distribute construct, Description]
14677   // The parameter of the ordered clause must be a constant
14678   // positive integer expression if any.
14679   if (NumForLoops && LParenLoc.isValid()) {
14680     ExprResult NumForLoopsResult =
14681         VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
14682     if (NumForLoopsResult.isInvalid())
14683       return nullptr;
14684     NumForLoops = NumForLoopsResult.get();
14685   } else {
14686     NumForLoops = nullptr;
14687   }
14688   auto *Clause = OMPOrderedClause::Create(
14689       Context, NumForLoops, NumForLoops ? DSAStack->getAssociatedLoops() : 0,
14690       StartLoc, LParenLoc, EndLoc);
14691   DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops, Clause);
14692   return Clause;
14693 }
14694 
14695 OMPClause *Sema::ActOnOpenMPSimpleClause(
14696     OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
14697     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
14698   OMPClause *Res = nullptr;
14699   switch (Kind) {
14700   case OMPC_default:
14701     Res = ActOnOpenMPDefaultClause(static_cast<DefaultKind>(Argument),
14702                                    ArgumentLoc, StartLoc, LParenLoc, EndLoc);
14703     break;
14704   case OMPC_proc_bind:
14705     Res = ActOnOpenMPProcBindClause(static_cast<ProcBindKind>(Argument),
14706                                     ArgumentLoc, StartLoc, LParenLoc, EndLoc);
14707     break;
14708   case OMPC_atomic_default_mem_order:
14709     Res = ActOnOpenMPAtomicDefaultMemOrderClause(
14710         static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Argument),
14711         ArgumentLoc, StartLoc, LParenLoc, EndLoc);
14712     break;
14713   case OMPC_order:
14714     Res = ActOnOpenMPOrderClause(static_cast<OpenMPOrderClauseKind>(Argument),
14715                                  ArgumentLoc, StartLoc, LParenLoc, EndLoc);
14716     break;
14717   case OMPC_update:
14718     Res = ActOnOpenMPUpdateClause(static_cast<OpenMPDependClauseKind>(Argument),
14719                                   ArgumentLoc, StartLoc, LParenLoc, EndLoc);
14720     break;
14721   case OMPC_bind:
14722     Res = ActOnOpenMPBindClause(static_cast<OpenMPBindClauseKind>(Argument),
14723                                 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
14724     break;
14725   case OMPC_if:
14726   case OMPC_final:
14727   case OMPC_num_threads:
14728   case OMPC_safelen:
14729   case OMPC_simdlen:
14730   case OMPC_sizes:
14731   case OMPC_allocator:
14732   case OMPC_collapse:
14733   case OMPC_schedule:
14734   case OMPC_private:
14735   case OMPC_firstprivate:
14736   case OMPC_lastprivate:
14737   case OMPC_shared:
14738   case OMPC_reduction:
14739   case OMPC_task_reduction:
14740   case OMPC_in_reduction:
14741   case OMPC_linear:
14742   case OMPC_aligned:
14743   case OMPC_copyin:
14744   case OMPC_copyprivate:
14745   case OMPC_ordered:
14746   case OMPC_nowait:
14747   case OMPC_untied:
14748   case OMPC_mergeable:
14749   case OMPC_threadprivate:
14750   case OMPC_allocate:
14751   case OMPC_flush:
14752   case OMPC_depobj:
14753   case OMPC_read:
14754   case OMPC_write:
14755   case OMPC_capture:
14756   case OMPC_seq_cst:
14757   case OMPC_acq_rel:
14758   case OMPC_acquire:
14759   case OMPC_release:
14760   case OMPC_relaxed:
14761   case OMPC_depend:
14762   case OMPC_device:
14763   case OMPC_threads:
14764   case OMPC_simd:
14765   case OMPC_map:
14766   case OMPC_num_teams:
14767   case OMPC_thread_limit:
14768   case OMPC_priority:
14769   case OMPC_grainsize:
14770   case OMPC_nogroup:
14771   case OMPC_num_tasks:
14772   case OMPC_hint:
14773   case OMPC_dist_schedule:
14774   case OMPC_defaultmap:
14775   case OMPC_unknown:
14776   case OMPC_uniform:
14777   case OMPC_to:
14778   case OMPC_from:
14779   case OMPC_use_device_ptr:
14780   case OMPC_use_device_addr:
14781   case OMPC_is_device_ptr:
14782   case OMPC_unified_address:
14783   case OMPC_unified_shared_memory:
14784   case OMPC_reverse_offload:
14785   case OMPC_dynamic_allocators:
14786   case OMPC_device_type:
14787   case OMPC_match:
14788   case OMPC_nontemporal:
14789   case OMPC_destroy:
14790   case OMPC_novariants:
14791   case OMPC_nocontext:
14792   case OMPC_detach:
14793   case OMPC_inclusive:
14794   case OMPC_exclusive:
14795   case OMPC_uses_allocators:
14796   case OMPC_affinity:
14797   case OMPC_when:
14798   default:
14799     llvm_unreachable("Clause is not allowed.");
14800   }
14801   return Res;
14802 }
14803 
14804 static std::string
14805 getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
14806                         ArrayRef<unsigned> Exclude = llvm::None) {
14807   SmallString<256> Buffer;
14808   llvm::raw_svector_ostream Out(Buffer);
14809   unsigned Skipped = Exclude.size();
14810   auto S = Exclude.begin(), E = Exclude.end();
14811   for (unsigned I = First; I < Last; ++I) {
14812     if (std::find(S, E, I) != E) {
14813       --Skipped;
14814       continue;
14815     }
14816     Out << "'" << getOpenMPSimpleClauseTypeName(K, I) << "'";
14817     if (I + Skipped + 2 == Last)
14818       Out << " or ";
14819     else if (I + Skipped + 1 != Last)
14820       Out << ", ";
14821   }
14822   return std::string(Out.str());
14823 }
14824 
14825 OMPClause *Sema::ActOnOpenMPDefaultClause(DefaultKind Kind,
14826                                           SourceLocation KindKwLoc,
14827                                           SourceLocation StartLoc,
14828                                           SourceLocation LParenLoc,
14829                                           SourceLocation EndLoc) {
14830   if (Kind == OMP_DEFAULT_unknown) {
14831     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
14832         << getListOfPossibleValues(OMPC_default, /*First=*/0,
14833                                    /*Last=*/unsigned(OMP_DEFAULT_unknown))
14834         << getOpenMPClauseName(OMPC_default);
14835     return nullptr;
14836   }
14837 
14838   switch (Kind) {
14839   case OMP_DEFAULT_none:
14840     DSAStack->setDefaultDSANone(KindKwLoc);
14841     break;
14842   case OMP_DEFAULT_shared:
14843     DSAStack->setDefaultDSAShared(KindKwLoc);
14844     break;
14845   case OMP_DEFAULT_firstprivate:
14846     DSAStack->setDefaultDSAFirstPrivate(KindKwLoc);
14847     break;
14848   default:
14849     llvm_unreachable("DSA unexpected in OpenMP default clause");
14850   }
14851 
14852   return new (Context)
14853       OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
14854 }
14855 
14856 OMPClause *Sema::ActOnOpenMPProcBindClause(ProcBindKind Kind,
14857                                            SourceLocation KindKwLoc,
14858                                            SourceLocation StartLoc,
14859                                            SourceLocation LParenLoc,
14860                                            SourceLocation EndLoc) {
14861   if (Kind == OMP_PROC_BIND_unknown) {
14862     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
14863         << getListOfPossibleValues(OMPC_proc_bind,
14864                                    /*First=*/unsigned(OMP_PROC_BIND_master),
14865                                    /*Last=*/
14866                                    unsigned(LangOpts.OpenMP > 50
14867                                                 ? OMP_PROC_BIND_primary
14868                                                 : OMP_PROC_BIND_spread) +
14869                                        1)
14870         << getOpenMPClauseName(OMPC_proc_bind);
14871     return nullptr;
14872   }
14873   if (Kind == OMP_PROC_BIND_primary && LangOpts.OpenMP < 51)
14874     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
14875         << getListOfPossibleValues(OMPC_proc_bind,
14876                                    /*First=*/unsigned(OMP_PROC_BIND_master),
14877                                    /*Last=*/
14878                                    unsigned(OMP_PROC_BIND_spread) + 1)
14879         << getOpenMPClauseName(OMPC_proc_bind);
14880   return new (Context)
14881       OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
14882 }
14883 
14884 OMPClause *Sema::ActOnOpenMPAtomicDefaultMemOrderClause(
14885     OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindKwLoc,
14886     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
14887   if (Kind == OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown) {
14888     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
14889         << getListOfPossibleValues(
14890                OMPC_atomic_default_mem_order, /*First=*/0,
14891                /*Last=*/OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown)
14892         << getOpenMPClauseName(OMPC_atomic_default_mem_order);
14893     return nullptr;
14894   }
14895   return new (Context) OMPAtomicDefaultMemOrderClause(Kind, KindKwLoc, StartLoc,
14896                                                       LParenLoc, EndLoc);
14897 }
14898 
14899 OMPClause *Sema::ActOnOpenMPOrderClause(OpenMPOrderClauseKind Kind,
14900                                         SourceLocation KindKwLoc,
14901                                         SourceLocation StartLoc,
14902                                         SourceLocation LParenLoc,
14903                                         SourceLocation EndLoc) {
14904   if (Kind == OMPC_ORDER_unknown) {
14905     static_assert(OMPC_ORDER_unknown > 0,
14906                   "OMPC_ORDER_unknown not greater than 0");
14907     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
14908         << getListOfPossibleValues(OMPC_order, /*First=*/0,
14909                                    /*Last=*/OMPC_ORDER_unknown)
14910         << getOpenMPClauseName(OMPC_order);
14911     return nullptr;
14912   }
14913   return new (Context)
14914       OMPOrderClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
14915 }
14916 
14917 OMPClause *Sema::ActOnOpenMPUpdateClause(OpenMPDependClauseKind Kind,
14918                                          SourceLocation KindKwLoc,
14919                                          SourceLocation StartLoc,
14920                                          SourceLocation LParenLoc,
14921                                          SourceLocation EndLoc) {
14922   if (Kind == OMPC_DEPEND_unknown || Kind == OMPC_DEPEND_source ||
14923       Kind == OMPC_DEPEND_sink || Kind == OMPC_DEPEND_depobj) {
14924     unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink,
14925                          OMPC_DEPEND_depobj};
14926     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
14927         << getListOfPossibleValues(OMPC_depend, /*First=*/0,
14928                                    /*Last=*/OMPC_DEPEND_unknown, Except)
14929         << getOpenMPClauseName(OMPC_update);
14930     return nullptr;
14931   }
14932   return OMPUpdateClause::Create(Context, StartLoc, LParenLoc, KindKwLoc, Kind,
14933                                  EndLoc);
14934 }
14935 
14936 OMPClause *Sema::ActOnOpenMPSizesClause(ArrayRef<Expr *> SizeExprs,
14937                                         SourceLocation StartLoc,
14938                                         SourceLocation LParenLoc,
14939                                         SourceLocation EndLoc) {
14940   for (Expr *SizeExpr : SizeExprs) {
14941     ExprResult NumForLoopsResult = VerifyPositiveIntegerConstantInClause(
14942         SizeExpr, OMPC_sizes, /*StrictlyPositive=*/true);
14943     if (!NumForLoopsResult.isUsable())
14944       return nullptr;
14945   }
14946 
14947   DSAStack->setAssociatedLoops(SizeExprs.size());
14948   return OMPSizesClause::Create(Context, StartLoc, LParenLoc, EndLoc,
14949                                 SizeExprs);
14950 }
14951 
14952 OMPClause *Sema::ActOnOpenMPFullClause(SourceLocation StartLoc,
14953                                        SourceLocation EndLoc) {
14954   return OMPFullClause::Create(Context, StartLoc, EndLoc);
14955 }
14956 
14957 OMPClause *Sema::ActOnOpenMPPartialClause(Expr *FactorExpr,
14958                                           SourceLocation StartLoc,
14959                                           SourceLocation LParenLoc,
14960                                           SourceLocation EndLoc) {
14961   if (FactorExpr) {
14962     // If an argument is specified, it must be a constant (or an unevaluated
14963     // template expression).
14964     ExprResult FactorResult = VerifyPositiveIntegerConstantInClause(
14965         FactorExpr, OMPC_partial, /*StrictlyPositive=*/true);
14966     if (FactorResult.isInvalid())
14967       return nullptr;
14968     FactorExpr = FactorResult.get();
14969   }
14970 
14971   return OMPPartialClause::Create(Context, StartLoc, LParenLoc, EndLoc,
14972                                   FactorExpr);
14973 }
14974 
14975 OMPClause *Sema::ActOnOpenMPAlignClause(Expr *A, SourceLocation StartLoc,
14976                                         SourceLocation LParenLoc,
14977                                         SourceLocation EndLoc) {
14978   ExprResult AlignVal;
14979   AlignVal = VerifyPositiveIntegerConstantInClause(A, OMPC_align);
14980   if (AlignVal.isInvalid())
14981     return nullptr;
14982   return OMPAlignClause::Create(Context, AlignVal.get(), StartLoc, LParenLoc,
14983                                 EndLoc);
14984 }
14985 
14986 OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
14987     OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
14988     SourceLocation StartLoc, SourceLocation LParenLoc,
14989     ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
14990     SourceLocation EndLoc) {
14991   OMPClause *Res = nullptr;
14992   switch (Kind) {
14993   case OMPC_schedule:
14994     enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
14995     assert(Argument.size() == NumberOfElements &&
14996            ArgumentLoc.size() == NumberOfElements);
14997     Res = ActOnOpenMPScheduleClause(
14998         static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
14999         static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
15000         static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
15001         StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
15002         ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
15003     break;
15004   case OMPC_if:
15005     assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
15006     Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
15007                               Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
15008                               DelimLoc, EndLoc);
15009     break;
15010   case OMPC_dist_schedule:
15011     Res = ActOnOpenMPDistScheduleClause(
15012         static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
15013         StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
15014     break;
15015   case OMPC_defaultmap:
15016     enum { Modifier, DefaultmapKind };
15017     Res = ActOnOpenMPDefaultmapClause(
15018         static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
15019         static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
15020         StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
15021         EndLoc);
15022     break;
15023   case OMPC_device:
15024     assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
15025     Res = ActOnOpenMPDeviceClause(
15026         static_cast<OpenMPDeviceClauseModifier>(Argument.back()), Expr,
15027         StartLoc, LParenLoc, ArgumentLoc.back(), EndLoc);
15028     break;
15029   case OMPC_final:
15030   case OMPC_num_threads:
15031   case OMPC_safelen:
15032   case OMPC_simdlen:
15033   case OMPC_sizes:
15034   case OMPC_allocator:
15035   case OMPC_collapse:
15036   case OMPC_default:
15037   case OMPC_proc_bind:
15038   case OMPC_private:
15039   case OMPC_firstprivate:
15040   case OMPC_lastprivate:
15041   case OMPC_shared:
15042   case OMPC_reduction:
15043   case OMPC_task_reduction:
15044   case OMPC_in_reduction:
15045   case OMPC_linear:
15046   case OMPC_aligned:
15047   case OMPC_copyin:
15048   case OMPC_copyprivate:
15049   case OMPC_ordered:
15050   case OMPC_nowait:
15051   case OMPC_untied:
15052   case OMPC_mergeable:
15053   case OMPC_threadprivate:
15054   case OMPC_allocate:
15055   case OMPC_flush:
15056   case OMPC_depobj:
15057   case OMPC_read:
15058   case OMPC_write:
15059   case OMPC_update:
15060   case OMPC_capture:
15061   case OMPC_seq_cst:
15062   case OMPC_acq_rel:
15063   case OMPC_acquire:
15064   case OMPC_release:
15065   case OMPC_relaxed:
15066   case OMPC_depend:
15067   case OMPC_threads:
15068   case OMPC_simd:
15069   case OMPC_map:
15070   case OMPC_num_teams:
15071   case OMPC_thread_limit:
15072   case OMPC_priority:
15073   case OMPC_grainsize:
15074   case OMPC_nogroup:
15075   case OMPC_num_tasks:
15076   case OMPC_hint:
15077   case OMPC_unknown:
15078   case OMPC_uniform:
15079   case OMPC_to:
15080   case OMPC_from:
15081   case OMPC_use_device_ptr:
15082   case OMPC_use_device_addr:
15083   case OMPC_is_device_ptr:
15084   case OMPC_unified_address:
15085   case OMPC_unified_shared_memory:
15086   case OMPC_reverse_offload:
15087   case OMPC_dynamic_allocators:
15088   case OMPC_atomic_default_mem_order:
15089   case OMPC_device_type:
15090   case OMPC_match:
15091   case OMPC_nontemporal:
15092   case OMPC_order:
15093   case OMPC_destroy:
15094   case OMPC_novariants:
15095   case OMPC_nocontext:
15096   case OMPC_detach:
15097   case OMPC_inclusive:
15098   case OMPC_exclusive:
15099   case OMPC_uses_allocators:
15100   case OMPC_affinity:
15101   case OMPC_when:
15102   case OMPC_bind:
15103   default:
15104     llvm_unreachable("Clause is not allowed.");
15105   }
15106   return Res;
15107 }
15108 
15109 static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
15110                                    OpenMPScheduleClauseModifier M2,
15111                                    SourceLocation M1Loc, SourceLocation M2Loc) {
15112   if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
15113     SmallVector<unsigned, 2> Excluded;
15114     if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
15115       Excluded.push_back(M2);
15116     if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
15117       Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
15118     if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
15119       Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
15120     S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
15121         << getListOfPossibleValues(OMPC_schedule,
15122                                    /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
15123                                    /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
15124                                    Excluded)
15125         << getOpenMPClauseName(OMPC_schedule);
15126     return true;
15127   }
15128   return false;
15129 }
15130 
15131 OMPClause *Sema::ActOnOpenMPScheduleClause(
15132     OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
15133     OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
15134     SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
15135     SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
15136   if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
15137       checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
15138     return nullptr;
15139   // OpenMP, 2.7.1, Loop Construct, Restrictions
15140   // Either the monotonic modifier or the nonmonotonic modifier can be specified
15141   // but not both.
15142   if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
15143       (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
15144        M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
15145       (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
15146        M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
15147     Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
15148         << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
15149         << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
15150     return nullptr;
15151   }
15152   if (Kind == OMPC_SCHEDULE_unknown) {
15153     std::string Values;
15154     if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
15155       unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
15156       Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
15157                                        /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
15158                                        Exclude);
15159     } else {
15160       Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
15161                                        /*Last=*/OMPC_SCHEDULE_unknown);
15162     }
15163     Diag(KindLoc, diag::err_omp_unexpected_clause_value)
15164         << Values << getOpenMPClauseName(OMPC_schedule);
15165     return nullptr;
15166   }
15167   // OpenMP, 2.7.1, Loop Construct, Restrictions
15168   // The nonmonotonic modifier can only be specified with schedule(dynamic) or
15169   // schedule(guided).
15170   // OpenMP 5.0 does not have this restriction.
15171   if (LangOpts.OpenMP < 50 &&
15172       (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
15173        M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
15174       Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
15175     Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
15176          diag::err_omp_schedule_nonmonotonic_static);
15177     return nullptr;
15178   }
15179   Expr *ValExpr = ChunkSize;
15180   Stmt *HelperValStmt = nullptr;
15181   if (ChunkSize) {
15182     if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
15183         !ChunkSize->isInstantiationDependent() &&
15184         !ChunkSize->containsUnexpandedParameterPack()) {
15185       SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
15186       ExprResult Val =
15187           PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
15188       if (Val.isInvalid())
15189         return nullptr;
15190 
15191       ValExpr = Val.get();
15192 
15193       // OpenMP [2.7.1, Restrictions]
15194       //  chunk_size must be a loop invariant integer expression with a positive
15195       //  value.
15196       if (Optional<llvm::APSInt> Result =
15197               ValExpr->getIntegerConstantExpr(Context)) {
15198         if (Result->isSigned() && !Result->isStrictlyPositive()) {
15199           Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
15200               << "schedule" << 1 << ChunkSize->getSourceRange();
15201           return nullptr;
15202         }
15203       } else if (getOpenMPCaptureRegionForClause(
15204                      DSAStack->getCurrentDirective(), OMPC_schedule,
15205                      LangOpts.OpenMP) != OMPD_unknown &&
15206                  !CurContext->isDependentContext()) {
15207         ValExpr = MakeFullExpr(ValExpr).get();
15208         llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
15209         ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
15210         HelperValStmt = buildPreInits(Context, Captures);
15211       }
15212     }
15213   }
15214 
15215   return new (Context)
15216       OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
15217                         ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
15218 }
15219 
15220 OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
15221                                    SourceLocation StartLoc,
15222                                    SourceLocation EndLoc) {
15223   OMPClause *Res = nullptr;
15224   switch (Kind) {
15225   case OMPC_ordered:
15226     Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
15227     break;
15228   case OMPC_nowait:
15229     Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
15230     break;
15231   case OMPC_untied:
15232     Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
15233     break;
15234   case OMPC_mergeable:
15235     Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
15236     break;
15237   case OMPC_read:
15238     Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
15239     break;
15240   case OMPC_write:
15241     Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
15242     break;
15243   case OMPC_update:
15244     Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
15245     break;
15246   case OMPC_capture:
15247     Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
15248     break;
15249   case OMPC_seq_cst:
15250     Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
15251     break;
15252   case OMPC_acq_rel:
15253     Res = ActOnOpenMPAcqRelClause(StartLoc, EndLoc);
15254     break;
15255   case OMPC_acquire:
15256     Res = ActOnOpenMPAcquireClause(StartLoc, EndLoc);
15257     break;
15258   case OMPC_release:
15259     Res = ActOnOpenMPReleaseClause(StartLoc, EndLoc);
15260     break;
15261   case OMPC_relaxed:
15262     Res = ActOnOpenMPRelaxedClause(StartLoc, EndLoc);
15263     break;
15264   case OMPC_threads:
15265     Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
15266     break;
15267   case OMPC_simd:
15268     Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
15269     break;
15270   case OMPC_nogroup:
15271     Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
15272     break;
15273   case OMPC_unified_address:
15274     Res = ActOnOpenMPUnifiedAddressClause(StartLoc, EndLoc);
15275     break;
15276   case OMPC_unified_shared_memory:
15277     Res = ActOnOpenMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
15278     break;
15279   case OMPC_reverse_offload:
15280     Res = ActOnOpenMPReverseOffloadClause(StartLoc, EndLoc);
15281     break;
15282   case OMPC_dynamic_allocators:
15283     Res = ActOnOpenMPDynamicAllocatorsClause(StartLoc, EndLoc);
15284     break;
15285   case OMPC_destroy:
15286     Res = ActOnOpenMPDestroyClause(/*InteropVar=*/nullptr, StartLoc,
15287                                    /*LParenLoc=*/SourceLocation(),
15288                                    /*VarLoc=*/SourceLocation(), EndLoc);
15289     break;
15290   case OMPC_full:
15291     Res = ActOnOpenMPFullClause(StartLoc, EndLoc);
15292     break;
15293   case OMPC_partial:
15294     Res = ActOnOpenMPPartialClause(nullptr, StartLoc, /*LParenLoc=*/{}, EndLoc);
15295     break;
15296   case OMPC_if:
15297   case OMPC_final:
15298   case OMPC_num_threads:
15299   case OMPC_safelen:
15300   case OMPC_simdlen:
15301   case OMPC_sizes:
15302   case OMPC_allocator:
15303   case OMPC_collapse:
15304   case OMPC_schedule:
15305   case OMPC_private:
15306   case OMPC_firstprivate:
15307   case OMPC_lastprivate:
15308   case OMPC_shared:
15309   case OMPC_reduction:
15310   case OMPC_task_reduction:
15311   case OMPC_in_reduction:
15312   case OMPC_linear:
15313   case OMPC_aligned:
15314   case OMPC_copyin:
15315   case OMPC_copyprivate:
15316   case OMPC_default:
15317   case OMPC_proc_bind:
15318   case OMPC_threadprivate:
15319   case OMPC_allocate:
15320   case OMPC_flush:
15321   case OMPC_depobj:
15322   case OMPC_depend:
15323   case OMPC_device:
15324   case OMPC_map:
15325   case OMPC_num_teams:
15326   case OMPC_thread_limit:
15327   case OMPC_priority:
15328   case OMPC_grainsize:
15329   case OMPC_num_tasks:
15330   case OMPC_hint:
15331   case OMPC_dist_schedule:
15332   case OMPC_defaultmap:
15333   case OMPC_unknown:
15334   case OMPC_uniform:
15335   case OMPC_to:
15336   case OMPC_from:
15337   case OMPC_use_device_ptr:
15338   case OMPC_use_device_addr:
15339   case OMPC_is_device_ptr:
15340   case OMPC_atomic_default_mem_order:
15341   case OMPC_device_type:
15342   case OMPC_match:
15343   case OMPC_nontemporal:
15344   case OMPC_order:
15345   case OMPC_novariants:
15346   case OMPC_nocontext:
15347   case OMPC_detach:
15348   case OMPC_inclusive:
15349   case OMPC_exclusive:
15350   case OMPC_uses_allocators:
15351   case OMPC_affinity:
15352   case OMPC_when:
15353   default:
15354     llvm_unreachable("Clause is not allowed.");
15355   }
15356   return Res;
15357 }
15358 
15359 OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
15360                                          SourceLocation EndLoc) {
15361   DSAStack->setNowaitRegion();
15362   return new (Context) OMPNowaitClause(StartLoc, EndLoc);
15363 }
15364 
15365 OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
15366                                          SourceLocation EndLoc) {
15367   return new (Context) OMPUntiedClause(StartLoc, EndLoc);
15368 }
15369 
15370 OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
15371                                             SourceLocation EndLoc) {
15372   return new (Context) OMPMergeableClause(StartLoc, EndLoc);
15373 }
15374 
15375 OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
15376                                        SourceLocation EndLoc) {
15377   return new (Context) OMPReadClause(StartLoc, EndLoc);
15378 }
15379 
15380 OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
15381                                         SourceLocation EndLoc) {
15382   return new (Context) OMPWriteClause(StartLoc, EndLoc);
15383 }
15384 
15385 OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
15386                                          SourceLocation EndLoc) {
15387   return OMPUpdateClause::Create(Context, StartLoc, EndLoc);
15388 }
15389 
15390 OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
15391                                           SourceLocation EndLoc) {
15392   return new (Context) OMPCaptureClause(StartLoc, EndLoc);
15393 }
15394 
15395 OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
15396                                          SourceLocation EndLoc) {
15397   return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
15398 }
15399 
15400 OMPClause *Sema::ActOnOpenMPAcqRelClause(SourceLocation StartLoc,
15401                                          SourceLocation EndLoc) {
15402   return new (Context) OMPAcqRelClause(StartLoc, EndLoc);
15403 }
15404 
15405 OMPClause *Sema::ActOnOpenMPAcquireClause(SourceLocation StartLoc,
15406                                           SourceLocation EndLoc) {
15407   return new (Context) OMPAcquireClause(StartLoc, EndLoc);
15408 }
15409 
15410 OMPClause *Sema::ActOnOpenMPReleaseClause(SourceLocation StartLoc,
15411                                           SourceLocation EndLoc) {
15412   return new (Context) OMPReleaseClause(StartLoc, EndLoc);
15413 }
15414 
15415 OMPClause *Sema::ActOnOpenMPRelaxedClause(SourceLocation StartLoc,
15416                                           SourceLocation EndLoc) {
15417   return new (Context) OMPRelaxedClause(StartLoc, EndLoc);
15418 }
15419 
15420 OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
15421                                           SourceLocation EndLoc) {
15422   return new (Context) OMPThreadsClause(StartLoc, EndLoc);
15423 }
15424 
15425 OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
15426                                        SourceLocation EndLoc) {
15427   return new (Context) OMPSIMDClause(StartLoc, EndLoc);
15428 }
15429 
15430 OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
15431                                           SourceLocation EndLoc) {
15432   return new (Context) OMPNogroupClause(StartLoc, EndLoc);
15433 }
15434 
15435 OMPClause *Sema::ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc,
15436                                                  SourceLocation EndLoc) {
15437   return new (Context) OMPUnifiedAddressClause(StartLoc, EndLoc);
15438 }
15439 
15440 OMPClause *Sema::ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc,
15441                                                       SourceLocation EndLoc) {
15442   return new (Context) OMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
15443 }
15444 
15445 OMPClause *Sema::ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc,
15446                                                  SourceLocation EndLoc) {
15447   return new (Context) OMPReverseOffloadClause(StartLoc, EndLoc);
15448 }
15449 
15450 OMPClause *Sema::ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc,
15451                                                     SourceLocation EndLoc) {
15452   return new (Context) OMPDynamicAllocatorsClause(StartLoc, EndLoc);
15453 }
15454 
15455 StmtResult Sema::ActOnOpenMPInteropDirective(ArrayRef<OMPClause *> Clauses,
15456                                              SourceLocation StartLoc,
15457                                              SourceLocation EndLoc) {
15458 
15459   // OpenMP 5.1 [2.15.1, interop Construct, Restrictions]
15460   // At least one action-clause must appear on a directive.
15461   if (!hasClauses(Clauses, OMPC_init, OMPC_use, OMPC_destroy, OMPC_nowait)) {
15462     StringRef Expected = "'init', 'use', 'destroy', or 'nowait'";
15463     Diag(StartLoc, diag::err_omp_no_clause_for_directive)
15464         << Expected << getOpenMPDirectiveName(OMPD_interop);
15465     return StmtError();
15466   }
15467 
15468   // OpenMP 5.1 [2.15.1, interop Construct, Restrictions]
15469   // A depend clause can only appear on the directive if a targetsync
15470   // interop-type is present or the interop-var was initialized with
15471   // the targetsync interop-type.
15472 
15473   // If there is any 'init' clause diagnose if there is no 'init' clause with
15474   // interop-type of 'targetsync'. Cases involving other directives cannot be
15475   // diagnosed.
15476   const OMPDependClause *DependClause = nullptr;
15477   bool HasInitClause = false;
15478   bool IsTargetSync = false;
15479   for (const OMPClause *C : Clauses) {
15480     if (IsTargetSync)
15481       break;
15482     if (const auto *InitClause = dyn_cast<OMPInitClause>(C)) {
15483       HasInitClause = true;
15484       if (InitClause->getIsTargetSync())
15485         IsTargetSync = true;
15486     } else if (const auto *DC = dyn_cast<OMPDependClause>(C)) {
15487       DependClause = DC;
15488     }
15489   }
15490   if (DependClause && HasInitClause && !IsTargetSync) {
15491     Diag(DependClause->getBeginLoc(), diag::err_omp_interop_bad_depend_clause);
15492     return StmtError();
15493   }
15494 
15495   // OpenMP 5.1 [2.15.1, interop Construct, Restrictions]
15496   // Each interop-var may be specified for at most one action-clause of each
15497   // interop construct.
15498   llvm::SmallPtrSet<const VarDecl *, 4> InteropVars;
15499   for (const OMPClause *C : Clauses) {
15500     OpenMPClauseKind ClauseKind = C->getClauseKind();
15501     const DeclRefExpr *DRE = nullptr;
15502     SourceLocation VarLoc;
15503 
15504     if (ClauseKind == OMPC_init) {
15505       const auto *IC = cast<OMPInitClause>(C);
15506       VarLoc = IC->getVarLoc();
15507       DRE = dyn_cast_or_null<DeclRefExpr>(IC->getInteropVar());
15508     } else if (ClauseKind == OMPC_use) {
15509       const auto *UC = cast<OMPUseClause>(C);
15510       VarLoc = UC->getVarLoc();
15511       DRE = dyn_cast_or_null<DeclRefExpr>(UC->getInteropVar());
15512     } else if (ClauseKind == OMPC_destroy) {
15513       const auto *DC = cast<OMPDestroyClause>(C);
15514       VarLoc = DC->getVarLoc();
15515       DRE = dyn_cast_or_null<DeclRefExpr>(DC->getInteropVar());
15516     }
15517 
15518     if (!DRE)
15519       continue;
15520 
15521     if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
15522       if (!InteropVars.insert(VD->getCanonicalDecl()).second) {
15523         Diag(VarLoc, diag::err_omp_interop_var_multiple_actions) << VD;
15524         return StmtError();
15525       }
15526     }
15527   }
15528 
15529   return OMPInteropDirective::Create(Context, StartLoc, EndLoc, Clauses);
15530 }
15531 
15532 static bool isValidInteropVariable(Sema &SemaRef, Expr *InteropVarExpr,
15533                                    SourceLocation VarLoc,
15534                                    OpenMPClauseKind Kind) {
15535   if (InteropVarExpr->isValueDependent() || InteropVarExpr->isTypeDependent() ||
15536       InteropVarExpr->isInstantiationDependent() ||
15537       InteropVarExpr->containsUnexpandedParameterPack())
15538     return true;
15539 
15540   const auto *DRE = dyn_cast<DeclRefExpr>(InteropVarExpr);
15541   if (!DRE || !isa<VarDecl>(DRE->getDecl())) {
15542     SemaRef.Diag(VarLoc, diag::err_omp_interop_variable_expected) << 0;
15543     return false;
15544   }
15545 
15546   // Interop variable should be of type omp_interop_t.
15547   bool HasError = false;
15548   QualType InteropType;
15549   LookupResult Result(SemaRef, &SemaRef.Context.Idents.get("omp_interop_t"),
15550                       VarLoc, Sema::LookupOrdinaryName);
15551   if (SemaRef.LookupName(Result, SemaRef.getCurScope())) {
15552     NamedDecl *ND = Result.getFoundDecl();
15553     if (const auto *TD = dyn_cast<TypeDecl>(ND)) {
15554       InteropType = QualType(TD->getTypeForDecl(), 0);
15555     } else {
15556       HasError = true;
15557     }
15558   } else {
15559     HasError = true;
15560   }
15561 
15562   if (HasError) {
15563     SemaRef.Diag(VarLoc, diag::err_omp_implied_type_not_found)
15564         << "omp_interop_t";
15565     return false;
15566   }
15567 
15568   QualType VarType = InteropVarExpr->getType().getUnqualifiedType();
15569   if (!SemaRef.Context.hasSameType(InteropType, VarType)) {
15570     SemaRef.Diag(VarLoc, diag::err_omp_interop_variable_wrong_type);
15571     return false;
15572   }
15573 
15574   // OpenMP 5.1 [2.15.1, interop Construct, Restrictions]
15575   // The interop-var passed to init or destroy must be non-const.
15576   if ((Kind == OMPC_init || Kind == OMPC_destroy) &&
15577       isConstNotMutableType(SemaRef, InteropVarExpr->getType())) {
15578     SemaRef.Diag(VarLoc, diag::err_omp_interop_variable_expected)
15579         << /*non-const*/ 1;
15580     return false;
15581   }
15582   return true;
15583 }
15584 
15585 OMPClause *
15586 Sema::ActOnOpenMPInitClause(Expr *InteropVar, ArrayRef<Expr *> PrefExprs,
15587                             bool IsTarget, bool IsTargetSync,
15588                             SourceLocation StartLoc, SourceLocation LParenLoc,
15589                             SourceLocation VarLoc, SourceLocation EndLoc) {
15590 
15591   if (!isValidInteropVariable(*this, InteropVar, VarLoc, OMPC_init))
15592     return nullptr;
15593 
15594   // Check prefer_type values.  These foreign-runtime-id values are either
15595   // string literals or constant integral expressions.
15596   for (const Expr *E : PrefExprs) {
15597     if (E->isValueDependent() || E->isTypeDependent() ||
15598         E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
15599       continue;
15600     if (E->isIntegerConstantExpr(Context))
15601       continue;
15602     if (isa<StringLiteral>(E))
15603       continue;
15604     Diag(E->getExprLoc(), diag::err_omp_interop_prefer_type);
15605     return nullptr;
15606   }
15607 
15608   return OMPInitClause::Create(Context, InteropVar, PrefExprs, IsTarget,
15609                                IsTargetSync, StartLoc, LParenLoc, VarLoc,
15610                                EndLoc);
15611 }
15612 
15613 OMPClause *Sema::ActOnOpenMPUseClause(Expr *InteropVar, SourceLocation StartLoc,
15614                                       SourceLocation LParenLoc,
15615                                       SourceLocation VarLoc,
15616                                       SourceLocation EndLoc) {
15617 
15618   if (!isValidInteropVariable(*this, InteropVar, VarLoc, OMPC_use))
15619     return nullptr;
15620 
15621   return new (Context)
15622       OMPUseClause(InteropVar, StartLoc, LParenLoc, VarLoc, EndLoc);
15623 }
15624 
15625 OMPClause *Sema::ActOnOpenMPDestroyClause(Expr *InteropVar,
15626                                           SourceLocation StartLoc,
15627                                           SourceLocation LParenLoc,
15628                                           SourceLocation VarLoc,
15629                                           SourceLocation EndLoc) {
15630   if (InteropVar &&
15631       !isValidInteropVariable(*this, InteropVar, VarLoc, OMPC_destroy))
15632     return nullptr;
15633 
15634   return new (Context)
15635       OMPDestroyClause(InteropVar, StartLoc, LParenLoc, VarLoc, EndLoc);
15636 }
15637 
15638 OMPClause *Sema::ActOnOpenMPNovariantsClause(Expr *Condition,
15639                                              SourceLocation StartLoc,
15640                                              SourceLocation LParenLoc,
15641                                              SourceLocation EndLoc) {
15642   Expr *ValExpr = Condition;
15643   Stmt *HelperValStmt = nullptr;
15644   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
15645   if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
15646       !Condition->isInstantiationDependent() &&
15647       !Condition->containsUnexpandedParameterPack()) {
15648     ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
15649     if (Val.isInvalid())
15650       return nullptr;
15651 
15652     ValExpr = MakeFullExpr(Val.get()).get();
15653 
15654     OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
15655     CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_novariants,
15656                                                     LangOpts.OpenMP);
15657     if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
15658       ValExpr = MakeFullExpr(ValExpr).get();
15659       llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
15660       ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
15661       HelperValStmt = buildPreInits(Context, Captures);
15662     }
15663   }
15664 
15665   return new (Context) OMPNovariantsClause(
15666       ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
15667 }
15668 
15669 OMPClause *Sema::ActOnOpenMPNocontextClause(Expr *Condition,
15670                                             SourceLocation StartLoc,
15671                                             SourceLocation LParenLoc,
15672                                             SourceLocation EndLoc) {
15673   Expr *ValExpr = Condition;
15674   Stmt *HelperValStmt = nullptr;
15675   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
15676   if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
15677       !Condition->isInstantiationDependent() &&
15678       !Condition->containsUnexpandedParameterPack()) {
15679     ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
15680     if (Val.isInvalid())
15681       return nullptr;
15682 
15683     ValExpr = MakeFullExpr(Val.get()).get();
15684 
15685     OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
15686     CaptureRegion =
15687         getOpenMPCaptureRegionForClause(DKind, OMPC_nocontext, LangOpts.OpenMP);
15688     if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
15689       ValExpr = MakeFullExpr(ValExpr).get();
15690       llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
15691       ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
15692       HelperValStmt = buildPreInits(Context, Captures);
15693     }
15694   }
15695 
15696   return new (Context) OMPNocontextClause(ValExpr, HelperValStmt, CaptureRegion,
15697                                           StartLoc, LParenLoc, EndLoc);
15698 }
15699 
15700 OMPClause *Sema::ActOnOpenMPFilterClause(Expr *ThreadID,
15701                                          SourceLocation StartLoc,
15702                                          SourceLocation LParenLoc,
15703                                          SourceLocation EndLoc) {
15704   Expr *ValExpr = ThreadID;
15705   Stmt *HelperValStmt = nullptr;
15706 
15707   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
15708   OpenMPDirectiveKind CaptureRegion =
15709       getOpenMPCaptureRegionForClause(DKind, OMPC_filter, LangOpts.OpenMP);
15710   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
15711     ValExpr = MakeFullExpr(ValExpr).get();
15712     llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
15713     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
15714     HelperValStmt = buildPreInits(Context, Captures);
15715   }
15716 
15717   return new (Context) OMPFilterClause(ValExpr, HelperValStmt, CaptureRegion,
15718                                        StartLoc, LParenLoc, EndLoc);
15719 }
15720 
15721 OMPClause *Sema::ActOnOpenMPVarListClause(
15722     OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *DepModOrTailExpr,
15723     const OMPVarListLocTy &Locs, SourceLocation ColonLoc,
15724     CXXScopeSpec &ReductionOrMapperIdScopeSpec,
15725     DeclarationNameInfo &ReductionOrMapperId, int ExtraModifier,
15726     ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
15727     ArrayRef<SourceLocation> MapTypeModifiersLoc, bool IsMapTypeImplicit,
15728     SourceLocation ExtraModifierLoc,
15729     ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
15730     ArrayRef<SourceLocation> MotionModifiersLoc) {
15731   SourceLocation StartLoc = Locs.StartLoc;
15732   SourceLocation LParenLoc = Locs.LParenLoc;
15733   SourceLocation EndLoc = Locs.EndLoc;
15734   OMPClause *Res = nullptr;
15735   switch (Kind) {
15736   case OMPC_private:
15737     Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
15738     break;
15739   case OMPC_firstprivate:
15740     Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
15741     break;
15742   case OMPC_lastprivate:
15743     assert(0 <= ExtraModifier && ExtraModifier <= OMPC_LASTPRIVATE_unknown &&
15744            "Unexpected lastprivate modifier.");
15745     Res = ActOnOpenMPLastprivateClause(
15746         VarList, static_cast<OpenMPLastprivateModifier>(ExtraModifier),
15747         ExtraModifierLoc, ColonLoc, StartLoc, LParenLoc, EndLoc);
15748     break;
15749   case OMPC_shared:
15750     Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
15751     break;
15752   case OMPC_reduction:
15753     assert(0 <= ExtraModifier && ExtraModifier <= OMPC_REDUCTION_unknown &&
15754            "Unexpected lastprivate modifier.");
15755     Res = ActOnOpenMPReductionClause(
15756         VarList, static_cast<OpenMPReductionClauseModifier>(ExtraModifier),
15757         StartLoc, LParenLoc, ExtraModifierLoc, ColonLoc, EndLoc,
15758         ReductionOrMapperIdScopeSpec, ReductionOrMapperId);
15759     break;
15760   case OMPC_task_reduction:
15761     Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
15762                                          EndLoc, ReductionOrMapperIdScopeSpec,
15763                                          ReductionOrMapperId);
15764     break;
15765   case OMPC_in_reduction:
15766     Res = ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
15767                                        EndLoc, ReductionOrMapperIdScopeSpec,
15768                                        ReductionOrMapperId);
15769     break;
15770   case OMPC_linear:
15771     assert(0 <= ExtraModifier && ExtraModifier <= OMPC_LINEAR_unknown &&
15772            "Unexpected linear modifier.");
15773     Res = ActOnOpenMPLinearClause(
15774         VarList, DepModOrTailExpr, StartLoc, LParenLoc,
15775         static_cast<OpenMPLinearClauseKind>(ExtraModifier), ExtraModifierLoc,
15776         ColonLoc, EndLoc);
15777     break;
15778   case OMPC_aligned:
15779     Res = ActOnOpenMPAlignedClause(VarList, DepModOrTailExpr, StartLoc,
15780                                    LParenLoc, ColonLoc, EndLoc);
15781     break;
15782   case OMPC_copyin:
15783     Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
15784     break;
15785   case OMPC_copyprivate:
15786     Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
15787     break;
15788   case OMPC_flush:
15789     Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
15790     break;
15791   case OMPC_depend:
15792     assert(0 <= ExtraModifier && ExtraModifier <= OMPC_DEPEND_unknown &&
15793            "Unexpected depend modifier.");
15794     Res = ActOnOpenMPDependClause(
15795         DepModOrTailExpr, static_cast<OpenMPDependClauseKind>(ExtraModifier),
15796         ExtraModifierLoc, ColonLoc, VarList, StartLoc, LParenLoc, EndLoc);
15797     break;
15798   case OMPC_map:
15799     assert(0 <= ExtraModifier && ExtraModifier <= OMPC_MAP_unknown &&
15800            "Unexpected map modifier.");
15801     Res = ActOnOpenMPMapClause(
15802         MapTypeModifiers, MapTypeModifiersLoc, ReductionOrMapperIdScopeSpec,
15803         ReductionOrMapperId, static_cast<OpenMPMapClauseKind>(ExtraModifier),
15804         IsMapTypeImplicit, ExtraModifierLoc, ColonLoc, VarList, Locs);
15805     break;
15806   case OMPC_to:
15807     Res = ActOnOpenMPToClause(MotionModifiers, MotionModifiersLoc,
15808                               ReductionOrMapperIdScopeSpec, ReductionOrMapperId,
15809                               ColonLoc, VarList, Locs);
15810     break;
15811   case OMPC_from:
15812     Res = ActOnOpenMPFromClause(MotionModifiers, MotionModifiersLoc,
15813                                 ReductionOrMapperIdScopeSpec,
15814                                 ReductionOrMapperId, ColonLoc, VarList, Locs);
15815     break;
15816   case OMPC_use_device_ptr:
15817     Res = ActOnOpenMPUseDevicePtrClause(VarList, Locs);
15818     break;
15819   case OMPC_use_device_addr:
15820     Res = ActOnOpenMPUseDeviceAddrClause(VarList, Locs);
15821     break;
15822   case OMPC_is_device_ptr:
15823     Res = ActOnOpenMPIsDevicePtrClause(VarList, Locs);
15824     break;
15825   case OMPC_allocate:
15826     Res = ActOnOpenMPAllocateClause(DepModOrTailExpr, VarList, StartLoc,
15827                                     LParenLoc, ColonLoc, EndLoc);
15828     break;
15829   case OMPC_nontemporal:
15830     Res = ActOnOpenMPNontemporalClause(VarList, StartLoc, LParenLoc, EndLoc);
15831     break;
15832   case OMPC_inclusive:
15833     Res = ActOnOpenMPInclusiveClause(VarList, StartLoc, LParenLoc, EndLoc);
15834     break;
15835   case OMPC_exclusive:
15836     Res = ActOnOpenMPExclusiveClause(VarList, StartLoc, LParenLoc, EndLoc);
15837     break;
15838   case OMPC_affinity:
15839     Res = ActOnOpenMPAffinityClause(StartLoc, LParenLoc, ColonLoc, EndLoc,
15840                                     DepModOrTailExpr, VarList);
15841     break;
15842   case OMPC_if:
15843   case OMPC_depobj:
15844   case OMPC_final:
15845   case OMPC_num_threads:
15846   case OMPC_safelen:
15847   case OMPC_simdlen:
15848   case OMPC_sizes:
15849   case OMPC_allocator:
15850   case OMPC_collapse:
15851   case OMPC_default:
15852   case OMPC_proc_bind:
15853   case OMPC_schedule:
15854   case OMPC_ordered:
15855   case OMPC_nowait:
15856   case OMPC_untied:
15857   case OMPC_mergeable:
15858   case OMPC_threadprivate:
15859   case OMPC_read:
15860   case OMPC_write:
15861   case OMPC_update:
15862   case OMPC_capture:
15863   case OMPC_seq_cst:
15864   case OMPC_acq_rel:
15865   case OMPC_acquire:
15866   case OMPC_release:
15867   case OMPC_relaxed:
15868   case OMPC_device:
15869   case OMPC_threads:
15870   case OMPC_simd:
15871   case OMPC_num_teams:
15872   case OMPC_thread_limit:
15873   case OMPC_priority:
15874   case OMPC_grainsize:
15875   case OMPC_nogroup:
15876   case OMPC_num_tasks:
15877   case OMPC_hint:
15878   case OMPC_dist_schedule:
15879   case OMPC_defaultmap:
15880   case OMPC_unknown:
15881   case OMPC_uniform:
15882   case OMPC_unified_address:
15883   case OMPC_unified_shared_memory:
15884   case OMPC_reverse_offload:
15885   case OMPC_dynamic_allocators:
15886   case OMPC_atomic_default_mem_order:
15887   case OMPC_device_type:
15888   case OMPC_match:
15889   case OMPC_order:
15890   case OMPC_destroy:
15891   case OMPC_novariants:
15892   case OMPC_nocontext:
15893   case OMPC_detach:
15894   case OMPC_uses_allocators:
15895   case OMPC_when:
15896   case OMPC_bind:
15897   default:
15898     llvm_unreachable("Clause is not allowed.");
15899   }
15900   return Res;
15901 }
15902 
15903 ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
15904                                        ExprObjectKind OK, SourceLocation Loc) {
15905   ExprResult Res = BuildDeclRefExpr(
15906       Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
15907   if (!Res.isUsable())
15908     return ExprError();
15909   if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
15910     Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
15911     if (!Res.isUsable())
15912       return ExprError();
15913   }
15914   if (VK != VK_LValue && Res.get()->isGLValue()) {
15915     Res = DefaultLvalueConversion(Res.get());
15916     if (!Res.isUsable())
15917       return ExprError();
15918   }
15919   return Res;
15920 }
15921 
15922 OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
15923                                           SourceLocation StartLoc,
15924                                           SourceLocation LParenLoc,
15925                                           SourceLocation EndLoc) {
15926   SmallVector<Expr *, 8> Vars;
15927   SmallVector<Expr *, 8> PrivateCopies;
15928   for (Expr *RefExpr : VarList) {
15929     assert(RefExpr && "NULL expr in OpenMP private clause.");
15930     SourceLocation ELoc;
15931     SourceRange ERange;
15932     Expr *SimpleRefExpr = RefExpr;
15933     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
15934     if (Res.second) {
15935       // It will be analyzed later.
15936       Vars.push_back(RefExpr);
15937       PrivateCopies.push_back(nullptr);
15938     }
15939     ValueDecl *D = Res.first;
15940     if (!D)
15941       continue;
15942 
15943     QualType Type = D->getType();
15944     auto *VD = dyn_cast<VarDecl>(D);
15945 
15946     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
15947     //  A variable that appears in a private clause must not have an incomplete
15948     //  type or a reference type.
15949     if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
15950       continue;
15951     Type = Type.getNonReferenceType();
15952 
15953     // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
15954     // A variable that is privatized must not have a const-qualified type
15955     // unless it is of class type with a mutable member. This restriction does
15956     // not apply to the firstprivate clause.
15957     //
15958     // OpenMP 3.1 [2.9.3.3, private clause, Restrictions]
15959     // A variable that appears in a private clause must not have a
15960     // const-qualified type unless it is of class type with a mutable member.
15961     if (rejectConstNotMutableType(*this, D, Type, OMPC_private, ELoc))
15962       continue;
15963 
15964     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
15965     // in a Construct]
15966     //  Variables with the predetermined data-sharing attributes may not be
15967     //  listed in data-sharing attributes clauses, except for the cases
15968     //  listed below. For these exceptions only, listing a predetermined
15969     //  variable in a data-sharing attribute clause is allowed and overrides
15970     //  the variable's predetermined data-sharing attributes.
15971     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
15972     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
15973       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
15974                                           << getOpenMPClauseName(OMPC_private);
15975       reportOriginalDsa(*this, DSAStack, D, DVar);
15976       continue;
15977     }
15978 
15979     OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
15980     // Variably modified types are not supported for tasks.
15981     if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
15982         isOpenMPTaskingDirective(CurrDir)) {
15983       Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
15984           << getOpenMPClauseName(OMPC_private) << Type
15985           << getOpenMPDirectiveName(CurrDir);
15986       bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
15987                                VarDecl::DeclarationOnly;
15988       Diag(D->getLocation(),
15989            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
15990           << D;
15991       continue;
15992     }
15993 
15994     // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
15995     // A list item cannot appear in both a map clause and a data-sharing
15996     // attribute clause on the same construct
15997     //
15998     // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
15999     // A list item cannot appear in both a map clause and a data-sharing
16000     // attribute clause on the same construct unless the construct is a
16001     // combined construct.
16002     if ((LangOpts.OpenMP <= 45 && isOpenMPTargetExecutionDirective(CurrDir)) ||
16003         CurrDir == OMPD_target) {
16004       OpenMPClauseKind ConflictKind;
16005       if (DSAStack->checkMappableExprComponentListsForDecl(
16006               VD, /*CurrentRegionOnly=*/true,
16007               [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
16008                   OpenMPClauseKind WhereFoundClauseKind) -> bool {
16009                 ConflictKind = WhereFoundClauseKind;
16010                 return true;
16011               })) {
16012         Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
16013             << getOpenMPClauseName(OMPC_private)
16014             << getOpenMPClauseName(ConflictKind)
16015             << getOpenMPDirectiveName(CurrDir);
16016         reportOriginalDsa(*this, DSAStack, D, DVar);
16017         continue;
16018       }
16019     }
16020 
16021     // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
16022     //  A variable of class type (or array thereof) that appears in a private
16023     //  clause requires an accessible, unambiguous default constructor for the
16024     //  class type.
16025     // Generate helper private variable and initialize it with the default
16026     // value. The address of the original variable is replaced by the address of
16027     // the new private variable in CodeGen. This new variable is not added to
16028     // IdResolver, so the code in the OpenMP region uses original variable for
16029     // proper diagnostics.
16030     Type = Type.getUnqualifiedType();
16031     VarDecl *VDPrivate =
16032         buildVarDecl(*this, ELoc, Type, D->getName(),
16033                      D->hasAttrs() ? &D->getAttrs() : nullptr,
16034                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
16035     ActOnUninitializedDecl(VDPrivate);
16036     if (VDPrivate->isInvalidDecl())
16037       continue;
16038     DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
16039         *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
16040 
16041     DeclRefExpr *Ref = nullptr;
16042     if (!VD && !CurContext->isDependentContext())
16043       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
16044     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
16045     Vars.push_back((VD || CurContext->isDependentContext())
16046                        ? RefExpr->IgnoreParens()
16047                        : Ref);
16048     PrivateCopies.push_back(VDPrivateRefExpr);
16049   }
16050 
16051   if (Vars.empty())
16052     return nullptr;
16053 
16054   return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
16055                                   PrivateCopies);
16056 }
16057 
16058 OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
16059                                                SourceLocation StartLoc,
16060                                                SourceLocation LParenLoc,
16061                                                SourceLocation EndLoc) {
16062   SmallVector<Expr *, 8> Vars;
16063   SmallVector<Expr *, 8> PrivateCopies;
16064   SmallVector<Expr *, 8> Inits;
16065   SmallVector<Decl *, 4> ExprCaptures;
16066   bool IsImplicitClause =
16067       StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
16068   SourceLocation ImplicitClauseLoc = DSAStack->getConstructLoc();
16069 
16070   for (Expr *RefExpr : VarList) {
16071     assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
16072     SourceLocation ELoc;
16073     SourceRange ERange;
16074     Expr *SimpleRefExpr = RefExpr;
16075     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
16076     if (Res.second) {
16077       // It will be analyzed later.
16078       Vars.push_back(RefExpr);
16079       PrivateCopies.push_back(nullptr);
16080       Inits.push_back(nullptr);
16081     }
16082     ValueDecl *D = Res.first;
16083     if (!D)
16084       continue;
16085 
16086     ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
16087     QualType Type = D->getType();
16088     auto *VD = dyn_cast<VarDecl>(D);
16089 
16090     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
16091     //  A variable that appears in a private clause must not have an incomplete
16092     //  type or a reference type.
16093     if (RequireCompleteType(ELoc, Type,
16094                             diag::err_omp_firstprivate_incomplete_type))
16095       continue;
16096     Type = Type.getNonReferenceType();
16097 
16098     // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
16099     //  A variable of class type (or array thereof) that appears in a private
16100     //  clause requires an accessible, unambiguous copy constructor for the
16101     //  class type.
16102     QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
16103 
16104     // If an implicit firstprivate variable found it was checked already.
16105     DSAStackTy::DSAVarData TopDVar;
16106     if (!IsImplicitClause) {
16107       DSAStackTy::DSAVarData DVar =
16108           DSAStack->getTopDSA(D, /*FromParent=*/false);
16109       TopDVar = DVar;
16110       OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
16111       bool IsConstant = ElemType.isConstant(Context);
16112       // OpenMP [2.4.13, Data-sharing Attribute Clauses]
16113       //  A list item that specifies a given variable may not appear in more
16114       // than one clause on the same directive, except that a variable may be
16115       //  specified in both firstprivate and lastprivate clauses.
16116       // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
16117       // A list item may appear in a firstprivate or lastprivate clause but not
16118       // both.
16119       if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
16120           (isOpenMPDistributeDirective(CurrDir) ||
16121            DVar.CKind != OMPC_lastprivate) &&
16122           DVar.RefExpr) {
16123         Diag(ELoc, diag::err_omp_wrong_dsa)
16124             << getOpenMPClauseName(DVar.CKind)
16125             << getOpenMPClauseName(OMPC_firstprivate);
16126         reportOriginalDsa(*this, DSAStack, D, DVar);
16127         continue;
16128       }
16129 
16130       // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
16131       // in a Construct]
16132       //  Variables with the predetermined data-sharing attributes may not be
16133       //  listed in data-sharing attributes clauses, except for the cases
16134       //  listed below. For these exceptions only, listing a predetermined
16135       //  variable in a data-sharing attribute clause is allowed and overrides
16136       //  the variable's predetermined data-sharing attributes.
16137       // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
16138       // in a Construct, C/C++, p.2]
16139       //  Variables with const-qualified type having no mutable member may be
16140       //  listed in a firstprivate clause, even if they are static data members.
16141       if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
16142           DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
16143         Diag(ELoc, diag::err_omp_wrong_dsa)
16144             << getOpenMPClauseName(DVar.CKind)
16145             << getOpenMPClauseName(OMPC_firstprivate);
16146         reportOriginalDsa(*this, DSAStack, D, DVar);
16147         continue;
16148       }
16149 
16150       // OpenMP [2.9.3.4, Restrictions, p.2]
16151       //  A list item that is private within a parallel region must not appear
16152       //  in a firstprivate clause on a worksharing construct if any of the
16153       //  worksharing regions arising from the worksharing construct ever bind
16154       //  to any of the parallel regions arising from the parallel construct.
16155       // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
16156       // A list item that is private within a teams region must not appear in a
16157       // firstprivate clause on a distribute construct if any of the distribute
16158       // regions arising from the distribute construct ever bind to any of the
16159       // teams regions arising from the teams construct.
16160       // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
16161       // A list item that appears in a reduction clause of a teams construct
16162       // must not appear in a firstprivate clause on a distribute construct if
16163       // any of the distribute regions arising from the distribute construct
16164       // ever bind to any of the teams regions arising from the teams construct.
16165       if ((isOpenMPWorksharingDirective(CurrDir) ||
16166            isOpenMPDistributeDirective(CurrDir)) &&
16167           !isOpenMPParallelDirective(CurrDir) &&
16168           !isOpenMPTeamsDirective(CurrDir)) {
16169         DVar = DSAStack->getImplicitDSA(D, true);
16170         if (DVar.CKind != OMPC_shared &&
16171             (isOpenMPParallelDirective(DVar.DKind) ||
16172              isOpenMPTeamsDirective(DVar.DKind) ||
16173              DVar.DKind == OMPD_unknown)) {
16174           Diag(ELoc, diag::err_omp_required_access)
16175               << getOpenMPClauseName(OMPC_firstprivate)
16176               << getOpenMPClauseName(OMPC_shared);
16177           reportOriginalDsa(*this, DSAStack, D, DVar);
16178           continue;
16179         }
16180       }
16181       // OpenMP [2.9.3.4, Restrictions, p.3]
16182       //  A list item that appears in a reduction clause of a parallel construct
16183       //  must not appear in a firstprivate clause on a worksharing or task
16184       //  construct if any of the worksharing or task regions arising from the
16185       //  worksharing or task construct ever bind to any of the parallel regions
16186       //  arising from the parallel construct.
16187       // OpenMP [2.9.3.4, Restrictions, p.4]
16188       //  A list item that appears in a reduction clause in worksharing
16189       //  construct must not appear in a firstprivate clause in a task construct
16190       //  encountered during execution of any of the worksharing regions arising
16191       //  from the worksharing construct.
16192       if (isOpenMPTaskingDirective(CurrDir)) {
16193         DVar = DSAStack->hasInnermostDSA(
16194             D,
16195             [](OpenMPClauseKind C, bool AppliedToPointee) {
16196               return C == OMPC_reduction && !AppliedToPointee;
16197             },
16198             [](OpenMPDirectiveKind K) {
16199               return isOpenMPParallelDirective(K) ||
16200                      isOpenMPWorksharingDirective(K) ||
16201                      isOpenMPTeamsDirective(K);
16202             },
16203             /*FromParent=*/true);
16204         if (DVar.CKind == OMPC_reduction &&
16205             (isOpenMPParallelDirective(DVar.DKind) ||
16206              isOpenMPWorksharingDirective(DVar.DKind) ||
16207              isOpenMPTeamsDirective(DVar.DKind))) {
16208           Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
16209               << getOpenMPDirectiveName(DVar.DKind);
16210           reportOriginalDsa(*this, DSAStack, D, DVar);
16211           continue;
16212         }
16213       }
16214 
16215       // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
16216       // A list item cannot appear in both a map clause and a data-sharing
16217       // attribute clause on the same construct
16218       //
16219       // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
16220       // A list item cannot appear in both a map clause and a data-sharing
16221       // attribute clause on the same construct unless the construct is a
16222       // combined construct.
16223       if ((LangOpts.OpenMP <= 45 &&
16224            isOpenMPTargetExecutionDirective(CurrDir)) ||
16225           CurrDir == OMPD_target) {
16226         OpenMPClauseKind ConflictKind;
16227         if (DSAStack->checkMappableExprComponentListsForDecl(
16228                 VD, /*CurrentRegionOnly=*/true,
16229                 [&ConflictKind](
16230                     OMPClauseMappableExprCommon::MappableExprComponentListRef,
16231                     OpenMPClauseKind WhereFoundClauseKind) {
16232                   ConflictKind = WhereFoundClauseKind;
16233                   return true;
16234                 })) {
16235           Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
16236               << getOpenMPClauseName(OMPC_firstprivate)
16237               << getOpenMPClauseName(ConflictKind)
16238               << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
16239           reportOriginalDsa(*this, DSAStack, D, DVar);
16240           continue;
16241         }
16242       }
16243     }
16244 
16245     // Variably modified types are not supported for tasks.
16246     if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
16247         isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
16248       Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
16249           << getOpenMPClauseName(OMPC_firstprivate) << Type
16250           << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
16251       bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
16252                                VarDecl::DeclarationOnly;
16253       Diag(D->getLocation(),
16254            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
16255           << D;
16256       continue;
16257     }
16258 
16259     Type = Type.getUnqualifiedType();
16260     VarDecl *VDPrivate =
16261         buildVarDecl(*this, ELoc, Type, D->getName(),
16262                      D->hasAttrs() ? &D->getAttrs() : nullptr,
16263                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
16264     // Generate helper private variable and initialize it with the value of the
16265     // original variable. The address of the original variable is replaced by
16266     // the address of the new private variable in the CodeGen. This new variable
16267     // is not added to IdResolver, so the code in the OpenMP region uses
16268     // original variable for proper diagnostics and variable capturing.
16269     Expr *VDInitRefExpr = nullptr;
16270     // For arrays generate initializer for single element and replace it by the
16271     // original array element in CodeGen.
16272     if (Type->isArrayType()) {
16273       VarDecl *VDInit =
16274           buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
16275       VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
16276       Expr *Init = DefaultLvalueConversion(VDInitRefExpr).get();
16277       ElemType = ElemType.getUnqualifiedType();
16278       VarDecl *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
16279                                          ".firstprivate.temp");
16280       InitializedEntity Entity =
16281           InitializedEntity::InitializeVariable(VDInitTemp);
16282       InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
16283 
16284       InitializationSequence InitSeq(*this, Entity, Kind, Init);
16285       ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
16286       if (Result.isInvalid())
16287         VDPrivate->setInvalidDecl();
16288       else
16289         VDPrivate->setInit(Result.getAs<Expr>());
16290       // Remove temp variable declaration.
16291       Context.Deallocate(VDInitTemp);
16292     } else {
16293       VarDecl *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
16294                                      ".firstprivate.temp");
16295       VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
16296                                        RefExpr->getExprLoc());
16297       AddInitializerToDecl(VDPrivate,
16298                            DefaultLvalueConversion(VDInitRefExpr).get(),
16299                            /*DirectInit=*/false);
16300     }
16301     if (VDPrivate->isInvalidDecl()) {
16302       if (IsImplicitClause) {
16303         Diag(RefExpr->getExprLoc(),
16304              diag::note_omp_task_predetermined_firstprivate_here);
16305       }
16306       continue;
16307     }
16308     CurContext->addDecl(VDPrivate);
16309     DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
16310         *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
16311         RefExpr->getExprLoc());
16312     DeclRefExpr *Ref = nullptr;
16313     if (!VD && !CurContext->isDependentContext()) {
16314       if (TopDVar.CKind == OMPC_lastprivate) {
16315         Ref = TopDVar.PrivateCopy;
16316       } else {
16317         Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
16318         if (!isOpenMPCapturedDecl(D))
16319           ExprCaptures.push_back(Ref->getDecl());
16320       }
16321     }
16322     if (!IsImplicitClause)
16323       DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
16324     Vars.push_back((VD || CurContext->isDependentContext())
16325                        ? RefExpr->IgnoreParens()
16326                        : Ref);
16327     PrivateCopies.push_back(VDPrivateRefExpr);
16328     Inits.push_back(VDInitRefExpr);
16329   }
16330 
16331   if (Vars.empty())
16332     return nullptr;
16333 
16334   return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
16335                                        Vars, PrivateCopies, Inits,
16336                                        buildPreInits(Context, ExprCaptures));
16337 }
16338 
16339 OMPClause *Sema::ActOnOpenMPLastprivateClause(
16340     ArrayRef<Expr *> VarList, OpenMPLastprivateModifier LPKind,
16341     SourceLocation LPKindLoc, SourceLocation ColonLoc, SourceLocation StartLoc,
16342     SourceLocation LParenLoc, SourceLocation EndLoc) {
16343   if (LPKind == OMPC_LASTPRIVATE_unknown && LPKindLoc.isValid()) {
16344     assert(ColonLoc.isValid() && "Colon location must be valid.");
16345     Diag(LPKindLoc, diag::err_omp_unexpected_clause_value)
16346         << getListOfPossibleValues(OMPC_lastprivate, /*First=*/0,
16347                                    /*Last=*/OMPC_LASTPRIVATE_unknown)
16348         << getOpenMPClauseName(OMPC_lastprivate);
16349     return nullptr;
16350   }
16351 
16352   SmallVector<Expr *, 8> Vars;
16353   SmallVector<Expr *, 8> SrcExprs;
16354   SmallVector<Expr *, 8> DstExprs;
16355   SmallVector<Expr *, 8> AssignmentOps;
16356   SmallVector<Decl *, 4> ExprCaptures;
16357   SmallVector<Expr *, 4> ExprPostUpdates;
16358   for (Expr *RefExpr : VarList) {
16359     assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
16360     SourceLocation ELoc;
16361     SourceRange ERange;
16362     Expr *SimpleRefExpr = RefExpr;
16363     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
16364     if (Res.second) {
16365       // It will be analyzed later.
16366       Vars.push_back(RefExpr);
16367       SrcExprs.push_back(nullptr);
16368       DstExprs.push_back(nullptr);
16369       AssignmentOps.push_back(nullptr);
16370     }
16371     ValueDecl *D = Res.first;
16372     if (!D)
16373       continue;
16374 
16375     QualType Type = D->getType();
16376     auto *VD = dyn_cast<VarDecl>(D);
16377 
16378     // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
16379     //  A variable that appears in a lastprivate clause must not have an
16380     //  incomplete type or a reference type.
16381     if (RequireCompleteType(ELoc, Type,
16382                             diag::err_omp_lastprivate_incomplete_type))
16383       continue;
16384     Type = Type.getNonReferenceType();
16385 
16386     // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
16387     // A variable that is privatized must not have a const-qualified type
16388     // unless it is of class type with a mutable member. This restriction does
16389     // not apply to the firstprivate clause.
16390     //
16391     // OpenMP 3.1 [2.9.3.5, lastprivate clause, Restrictions]
16392     // A variable that appears in a lastprivate clause must not have a
16393     // const-qualified type unless it is of class type with a mutable member.
16394     if (rejectConstNotMutableType(*this, D, Type, OMPC_lastprivate, ELoc))
16395       continue;
16396 
16397     // OpenMP 5.0 [2.19.4.5 lastprivate Clause, Restrictions]
16398     // A list item that appears in a lastprivate clause with the conditional
16399     // modifier must be a scalar variable.
16400     if (LPKind == OMPC_LASTPRIVATE_conditional && !Type->isScalarType()) {
16401       Diag(ELoc, diag::err_omp_lastprivate_conditional_non_scalar);
16402       bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
16403                                VarDecl::DeclarationOnly;
16404       Diag(D->getLocation(),
16405            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
16406           << D;
16407       continue;
16408     }
16409 
16410     OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
16411     // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
16412     // in a Construct]
16413     //  Variables with the predetermined data-sharing attributes may not be
16414     //  listed in data-sharing attributes clauses, except for the cases
16415     //  listed below.
16416     // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
16417     // A list item may appear in a firstprivate or lastprivate clause but not
16418     // both.
16419     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
16420     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
16421         (isOpenMPDistributeDirective(CurrDir) ||
16422          DVar.CKind != OMPC_firstprivate) &&
16423         (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
16424       Diag(ELoc, diag::err_omp_wrong_dsa)
16425           << getOpenMPClauseName(DVar.CKind)
16426           << getOpenMPClauseName(OMPC_lastprivate);
16427       reportOriginalDsa(*this, DSAStack, D, DVar);
16428       continue;
16429     }
16430 
16431     // OpenMP [2.14.3.5, Restrictions, p.2]
16432     // A list item that is private within a parallel region, or that appears in
16433     // the reduction clause of a parallel construct, must not appear in a
16434     // lastprivate clause on a worksharing construct if any of the corresponding
16435     // worksharing regions ever binds to any of the corresponding parallel
16436     // regions.
16437     DSAStackTy::DSAVarData TopDVar = DVar;
16438     if (isOpenMPWorksharingDirective(CurrDir) &&
16439         !isOpenMPParallelDirective(CurrDir) &&
16440         !isOpenMPTeamsDirective(CurrDir)) {
16441       DVar = DSAStack->getImplicitDSA(D, true);
16442       if (DVar.CKind != OMPC_shared) {
16443         Diag(ELoc, diag::err_omp_required_access)
16444             << getOpenMPClauseName(OMPC_lastprivate)
16445             << getOpenMPClauseName(OMPC_shared);
16446         reportOriginalDsa(*this, DSAStack, D, DVar);
16447         continue;
16448       }
16449     }
16450 
16451     // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
16452     //  A variable of class type (or array thereof) that appears in a
16453     //  lastprivate clause requires an accessible, unambiguous default
16454     //  constructor for the class type, unless the list item is also specified
16455     //  in a firstprivate clause.
16456     //  A variable of class type (or array thereof) that appears in a
16457     //  lastprivate clause requires an accessible, unambiguous copy assignment
16458     //  operator for the class type.
16459     Type = Context.getBaseElementType(Type).getNonReferenceType();
16460     VarDecl *SrcVD = buildVarDecl(*this, ERange.getBegin(),
16461                                   Type.getUnqualifiedType(), ".lastprivate.src",
16462                                   D->hasAttrs() ? &D->getAttrs() : nullptr);
16463     DeclRefExpr *PseudoSrcExpr =
16464         buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
16465     VarDecl *DstVD =
16466         buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
16467                      D->hasAttrs() ? &D->getAttrs() : nullptr);
16468     DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
16469     // For arrays generate assignment operation for single element and replace
16470     // it by the original array element in CodeGen.
16471     ExprResult AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
16472                                          PseudoDstExpr, PseudoSrcExpr);
16473     if (AssignmentOp.isInvalid())
16474       continue;
16475     AssignmentOp =
16476         ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
16477     if (AssignmentOp.isInvalid())
16478       continue;
16479 
16480     DeclRefExpr *Ref = nullptr;
16481     if (!VD && !CurContext->isDependentContext()) {
16482       if (TopDVar.CKind == OMPC_firstprivate) {
16483         Ref = TopDVar.PrivateCopy;
16484       } else {
16485         Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
16486         if (!isOpenMPCapturedDecl(D))
16487           ExprCaptures.push_back(Ref->getDecl());
16488       }
16489       if ((TopDVar.CKind == OMPC_firstprivate && !TopDVar.PrivateCopy) ||
16490           (!isOpenMPCapturedDecl(D) &&
16491            Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
16492         ExprResult RefRes = DefaultLvalueConversion(Ref);
16493         if (!RefRes.isUsable())
16494           continue;
16495         ExprResult PostUpdateRes =
16496             BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
16497                        RefRes.get());
16498         if (!PostUpdateRes.isUsable())
16499           continue;
16500         ExprPostUpdates.push_back(
16501             IgnoredValueConversions(PostUpdateRes.get()).get());
16502       }
16503     }
16504     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
16505     Vars.push_back((VD || CurContext->isDependentContext())
16506                        ? RefExpr->IgnoreParens()
16507                        : Ref);
16508     SrcExprs.push_back(PseudoSrcExpr);
16509     DstExprs.push_back(PseudoDstExpr);
16510     AssignmentOps.push_back(AssignmentOp.get());
16511   }
16512 
16513   if (Vars.empty())
16514     return nullptr;
16515 
16516   return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
16517                                       Vars, SrcExprs, DstExprs, AssignmentOps,
16518                                       LPKind, LPKindLoc, ColonLoc,
16519                                       buildPreInits(Context, ExprCaptures),
16520                                       buildPostUpdate(*this, ExprPostUpdates));
16521 }
16522 
16523 OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
16524                                          SourceLocation StartLoc,
16525                                          SourceLocation LParenLoc,
16526                                          SourceLocation EndLoc) {
16527   SmallVector<Expr *, 8> Vars;
16528   for (Expr *RefExpr : VarList) {
16529     assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
16530     SourceLocation ELoc;
16531     SourceRange ERange;
16532     Expr *SimpleRefExpr = RefExpr;
16533     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
16534     if (Res.second) {
16535       // It will be analyzed later.
16536       Vars.push_back(RefExpr);
16537     }
16538     ValueDecl *D = Res.first;
16539     if (!D)
16540       continue;
16541 
16542     auto *VD = dyn_cast<VarDecl>(D);
16543     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
16544     // in a Construct]
16545     //  Variables with the predetermined data-sharing attributes may not be
16546     //  listed in data-sharing attributes clauses, except for the cases
16547     //  listed below. For these exceptions only, listing a predetermined
16548     //  variable in a data-sharing attribute clause is allowed and overrides
16549     //  the variable's predetermined data-sharing attributes.
16550     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
16551     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
16552         DVar.RefExpr) {
16553       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
16554                                           << getOpenMPClauseName(OMPC_shared);
16555       reportOriginalDsa(*this, DSAStack, D, DVar);
16556       continue;
16557     }
16558 
16559     DeclRefExpr *Ref = nullptr;
16560     if (!VD && isOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
16561       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
16562     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
16563     Vars.push_back((VD || !Ref || CurContext->isDependentContext())
16564                        ? RefExpr->IgnoreParens()
16565                        : Ref);
16566   }
16567 
16568   if (Vars.empty())
16569     return nullptr;
16570 
16571   return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
16572 }
16573 
16574 namespace {
16575 class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
16576   DSAStackTy *Stack;
16577 
16578 public:
16579   bool VisitDeclRefExpr(DeclRefExpr *E) {
16580     if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
16581       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
16582       if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
16583         return false;
16584       if (DVar.CKind != OMPC_unknown)
16585         return true;
16586       DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
16587           VD,
16588           [](OpenMPClauseKind C, bool AppliedToPointee) {
16589             return isOpenMPPrivate(C) && !AppliedToPointee;
16590           },
16591           [](OpenMPDirectiveKind) { return true; },
16592           /*FromParent=*/true);
16593       return DVarPrivate.CKind != OMPC_unknown;
16594     }
16595     return false;
16596   }
16597   bool VisitStmt(Stmt *S) {
16598     for (Stmt *Child : S->children()) {
16599       if (Child && Visit(Child))
16600         return true;
16601     }
16602     return false;
16603   }
16604   explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
16605 };
16606 } // namespace
16607 
16608 namespace {
16609 // Transform MemberExpression for specified FieldDecl of current class to
16610 // DeclRefExpr to specified OMPCapturedExprDecl.
16611 class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
16612   typedef TreeTransform<TransformExprToCaptures> BaseTransform;
16613   ValueDecl *Field = nullptr;
16614   DeclRefExpr *CapturedExpr = nullptr;
16615 
16616 public:
16617   TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
16618       : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
16619 
16620   ExprResult TransformMemberExpr(MemberExpr *E) {
16621     if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
16622         E->getMemberDecl() == Field) {
16623       CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
16624       return CapturedExpr;
16625     }
16626     return BaseTransform::TransformMemberExpr(E);
16627   }
16628   DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
16629 };
16630 } // namespace
16631 
16632 template <typename T, typename U>
16633 static T filterLookupForUDReductionAndMapper(
16634     SmallVectorImpl<U> &Lookups, const llvm::function_ref<T(ValueDecl *)> Gen) {
16635   for (U &Set : Lookups) {
16636     for (auto *D : Set) {
16637       if (T Res = Gen(cast<ValueDecl>(D)))
16638         return Res;
16639     }
16640   }
16641   return T();
16642 }
16643 
16644 static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) {
16645   assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case");
16646 
16647   for (auto RD : D->redecls()) {
16648     // Don't bother with extra checks if we already know this one isn't visible.
16649     if (RD == D)
16650       continue;
16651 
16652     auto ND = cast<NamedDecl>(RD);
16653     if (LookupResult::isVisible(SemaRef, ND))
16654       return ND;
16655   }
16656 
16657   return nullptr;
16658 }
16659 
16660 static void
16661 argumentDependentLookup(Sema &SemaRef, const DeclarationNameInfo &Id,
16662                         SourceLocation Loc, QualType Ty,
16663                         SmallVectorImpl<UnresolvedSet<8>> &Lookups) {
16664   // Find all of the associated namespaces and classes based on the
16665   // arguments we have.
16666   Sema::AssociatedNamespaceSet AssociatedNamespaces;
16667   Sema::AssociatedClassSet AssociatedClasses;
16668   OpaqueValueExpr OVE(Loc, Ty, VK_LValue);
16669   SemaRef.FindAssociatedClassesAndNamespaces(Loc, &OVE, AssociatedNamespaces,
16670                                              AssociatedClasses);
16671 
16672   // C++ [basic.lookup.argdep]p3:
16673   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
16674   //   and let Y be the lookup set produced by argument dependent
16675   //   lookup (defined as follows). If X contains [...] then Y is
16676   //   empty. Otherwise Y is the set of declarations found in the
16677   //   namespaces associated with the argument types as described
16678   //   below. The set of declarations found by the lookup of the name
16679   //   is the union of X and Y.
16680   //
16681   // Here, we compute Y and add its members to the overloaded
16682   // candidate set.
16683   for (auto *NS : AssociatedNamespaces) {
16684     //   When considering an associated namespace, the lookup is the
16685     //   same as the lookup performed when the associated namespace is
16686     //   used as a qualifier (3.4.3.2) except that:
16687     //
16688     //     -- Any using-directives in the associated namespace are
16689     //        ignored.
16690     //
16691     //     -- Any namespace-scope friend functions declared in
16692     //        associated classes are visible within their respective
16693     //        namespaces even if they are not visible during an ordinary
16694     //        lookup (11.4).
16695     DeclContext::lookup_result R = NS->lookup(Id.getName());
16696     for (auto *D : R) {
16697       auto *Underlying = D;
16698       if (auto *USD = dyn_cast<UsingShadowDecl>(D))
16699         Underlying = USD->getTargetDecl();
16700 
16701       if (!isa<OMPDeclareReductionDecl>(Underlying) &&
16702           !isa<OMPDeclareMapperDecl>(Underlying))
16703         continue;
16704 
16705       if (!SemaRef.isVisible(D)) {
16706         D = findAcceptableDecl(SemaRef, D);
16707         if (!D)
16708           continue;
16709         if (auto *USD = dyn_cast<UsingShadowDecl>(D))
16710           Underlying = USD->getTargetDecl();
16711       }
16712       Lookups.emplace_back();
16713       Lookups.back().addDecl(Underlying);
16714     }
16715   }
16716 }
16717 
16718 static ExprResult
16719 buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
16720                          Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
16721                          const DeclarationNameInfo &ReductionId, QualType Ty,
16722                          CXXCastPath &BasePath, Expr *UnresolvedReduction) {
16723   if (ReductionIdScopeSpec.isInvalid())
16724     return ExprError();
16725   SmallVector<UnresolvedSet<8>, 4> Lookups;
16726   if (S) {
16727     LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
16728     Lookup.suppressDiagnostics();
16729     while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
16730       NamedDecl *D = Lookup.getRepresentativeDecl();
16731       do {
16732         S = S->getParent();
16733       } while (S && !S->isDeclScope(D));
16734       if (S)
16735         S = S->getParent();
16736       Lookups.emplace_back();
16737       Lookups.back().append(Lookup.begin(), Lookup.end());
16738       Lookup.clear();
16739     }
16740   } else if (auto *ULE =
16741                  cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
16742     Lookups.push_back(UnresolvedSet<8>());
16743     Decl *PrevD = nullptr;
16744     for (NamedDecl *D : ULE->decls()) {
16745       if (D == PrevD)
16746         Lookups.push_back(UnresolvedSet<8>());
16747       else if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(D))
16748         Lookups.back().addDecl(DRD);
16749       PrevD = D;
16750     }
16751   }
16752   if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() ||
16753       Ty->isInstantiationDependentType() ||
16754       Ty->containsUnexpandedParameterPack() ||
16755       filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
16756         return !D->isInvalidDecl() &&
16757                (D->getType()->isDependentType() ||
16758                 D->getType()->isInstantiationDependentType() ||
16759                 D->getType()->containsUnexpandedParameterPack());
16760       })) {
16761     UnresolvedSet<8> ResSet;
16762     for (const UnresolvedSet<8> &Set : Lookups) {
16763       if (Set.empty())
16764         continue;
16765       ResSet.append(Set.begin(), Set.end());
16766       // The last item marks the end of all declarations at the specified scope.
16767       ResSet.addDecl(Set[Set.size() - 1]);
16768     }
16769     return UnresolvedLookupExpr::Create(
16770         SemaRef.Context, /*NamingClass=*/nullptr,
16771         ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
16772         /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
16773   }
16774   // Lookup inside the classes.
16775   // C++ [over.match.oper]p3:
16776   //   For a unary operator @ with an operand of a type whose
16777   //   cv-unqualified version is T1, and for a binary operator @ with
16778   //   a left operand of a type whose cv-unqualified version is T1 and
16779   //   a right operand of a type whose cv-unqualified version is T2,
16780   //   three sets of candidate functions, designated member
16781   //   candidates, non-member candidates and built-in candidates, are
16782   //   constructed as follows:
16783   //     -- If T1 is a complete class type or a class currently being
16784   //        defined, the set of member candidates is the result of the
16785   //        qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
16786   //        the set of member candidates is empty.
16787   LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
16788   Lookup.suppressDiagnostics();
16789   if (const auto *TyRec = Ty->getAs<RecordType>()) {
16790     // Complete the type if it can be completed.
16791     // If the type is neither complete nor being defined, bail out now.
16792     if (SemaRef.isCompleteType(Loc, Ty) || TyRec->isBeingDefined() ||
16793         TyRec->getDecl()->getDefinition()) {
16794       Lookup.clear();
16795       SemaRef.LookupQualifiedName(Lookup, TyRec->getDecl());
16796       if (Lookup.empty()) {
16797         Lookups.emplace_back();
16798         Lookups.back().append(Lookup.begin(), Lookup.end());
16799       }
16800     }
16801   }
16802   // Perform ADL.
16803   if (SemaRef.getLangOpts().CPlusPlus)
16804     argumentDependentLookup(SemaRef, ReductionId, Loc, Ty, Lookups);
16805   if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
16806           Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
16807             if (!D->isInvalidDecl() &&
16808                 SemaRef.Context.hasSameType(D->getType(), Ty))
16809               return D;
16810             return nullptr;
16811           }))
16812     return SemaRef.BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(),
16813                                     VK_LValue, Loc);
16814   if (SemaRef.getLangOpts().CPlusPlus) {
16815     if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
16816             Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
16817               if (!D->isInvalidDecl() &&
16818                   SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
16819                   !Ty.isMoreQualifiedThan(D->getType()))
16820                 return D;
16821               return nullptr;
16822             })) {
16823       CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
16824                          /*DetectVirtual=*/false);
16825       if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
16826         if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
16827                 VD->getType().getUnqualifiedType()))) {
16828           if (SemaRef.CheckBaseClassAccess(
16829                   Loc, VD->getType(), Ty, Paths.front(),
16830                   /*DiagID=*/0) != Sema::AR_inaccessible) {
16831             SemaRef.BuildBasePathArray(Paths, BasePath);
16832             return SemaRef.BuildDeclRefExpr(
16833                 VD, VD->getType().getNonReferenceType(), VK_LValue, Loc);
16834           }
16835         }
16836       }
16837     }
16838   }
16839   if (ReductionIdScopeSpec.isSet()) {
16840     SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier)
16841         << Ty << Range;
16842     return ExprError();
16843   }
16844   return ExprEmpty();
16845 }
16846 
16847 namespace {
16848 /// Data for the reduction-based clauses.
16849 struct ReductionData {
16850   /// List of original reduction items.
16851   SmallVector<Expr *, 8> Vars;
16852   /// List of private copies of the reduction items.
16853   SmallVector<Expr *, 8> Privates;
16854   /// LHS expressions for the reduction_op expressions.
16855   SmallVector<Expr *, 8> LHSs;
16856   /// RHS expressions for the reduction_op expressions.
16857   SmallVector<Expr *, 8> RHSs;
16858   /// Reduction operation expression.
16859   SmallVector<Expr *, 8> ReductionOps;
16860   /// inscan copy operation expressions.
16861   SmallVector<Expr *, 8> InscanCopyOps;
16862   /// inscan copy temp array expressions for prefix sums.
16863   SmallVector<Expr *, 8> InscanCopyArrayTemps;
16864   /// inscan copy temp array element expressions for prefix sums.
16865   SmallVector<Expr *, 8> InscanCopyArrayElems;
16866   /// Taskgroup descriptors for the corresponding reduction items in
16867   /// in_reduction clauses.
16868   SmallVector<Expr *, 8> TaskgroupDescriptors;
16869   /// List of captures for clause.
16870   SmallVector<Decl *, 4> ExprCaptures;
16871   /// List of postupdate expressions.
16872   SmallVector<Expr *, 4> ExprPostUpdates;
16873   /// Reduction modifier.
16874   unsigned RedModifier = 0;
16875   ReductionData() = delete;
16876   /// Reserves required memory for the reduction data.
16877   ReductionData(unsigned Size, unsigned Modifier = 0) : RedModifier(Modifier) {
16878     Vars.reserve(Size);
16879     Privates.reserve(Size);
16880     LHSs.reserve(Size);
16881     RHSs.reserve(Size);
16882     ReductionOps.reserve(Size);
16883     if (RedModifier == OMPC_REDUCTION_inscan) {
16884       InscanCopyOps.reserve(Size);
16885       InscanCopyArrayTemps.reserve(Size);
16886       InscanCopyArrayElems.reserve(Size);
16887     }
16888     TaskgroupDescriptors.reserve(Size);
16889     ExprCaptures.reserve(Size);
16890     ExprPostUpdates.reserve(Size);
16891   }
16892   /// Stores reduction item and reduction operation only (required for dependent
16893   /// reduction item).
16894   void push(Expr *Item, Expr *ReductionOp) {
16895     Vars.emplace_back(Item);
16896     Privates.emplace_back(nullptr);
16897     LHSs.emplace_back(nullptr);
16898     RHSs.emplace_back(nullptr);
16899     ReductionOps.emplace_back(ReductionOp);
16900     TaskgroupDescriptors.emplace_back(nullptr);
16901     if (RedModifier == OMPC_REDUCTION_inscan) {
16902       InscanCopyOps.push_back(nullptr);
16903       InscanCopyArrayTemps.push_back(nullptr);
16904       InscanCopyArrayElems.push_back(nullptr);
16905     }
16906   }
16907   /// Stores reduction data.
16908   void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp,
16909             Expr *TaskgroupDescriptor, Expr *CopyOp, Expr *CopyArrayTemp,
16910             Expr *CopyArrayElem) {
16911     Vars.emplace_back(Item);
16912     Privates.emplace_back(Private);
16913     LHSs.emplace_back(LHS);
16914     RHSs.emplace_back(RHS);
16915     ReductionOps.emplace_back(ReductionOp);
16916     TaskgroupDescriptors.emplace_back(TaskgroupDescriptor);
16917     if (RedModifier == OMPC_REDUCTION_inscan) {
16918       InscanCopyOps.push_back(CopyOp);
16919       InscanCopyArrayTemps.push_back(CopyArrayTemp);
16920       InscanCopyArrayElems.push_back(CopyArrayElem);
16921     } else {
16922       assert(CopyOp == nullptr && CopyArrayTemp == nullptr &&
16923              CopyArrayElem == nullptr &&
16924              "Copy operation must be used for inscan reductions only.");
16925     }
16926   }
16927 };
16928 } // namespace
16929 
16930 static bool checkOMPArraySectionConstantForReduction(
16931     ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement,
16932     SmallVectorImpl<llvm::APSInt> &ArraySizes) {
16933   const Expr *Length = OASE->getLength();
16934   if (Length == nullptr) {
16935     // For array sections of the form [1:] or [:], we would need to analyze
16936     // the lower bound...
16937     if (OASE->getColonLocFirst().isValid())
16938       return false;
16939 
16940     // This is an array subscript which has implicit length 1!
16941     SingleElement = true;
16942     ArraySizes.push_back(llvm::APSInt::get(1));
16943   } else {
16944     Expr::EvalResult Result;
16945     if (!Length->EvaluateAsInt(Result, Context))
16946       return false;
16947 
16948     llvm::APSInt ConstantLengthValue = Result.Val.getInt();
16949     SingleElement = (ConstantLengthValue.getSExtValue() == 1);
16950     ArraySizes.push_back(ConstantLengthValue);
16951   }
16952 
16953   // Get the base of this array section and walk up from there.
16954   const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
16955 
16956   // We require length = 1 for all array sections except the right-most to
16957   // guarantee that the memory region is contiguous and has no holes in it.
16958   while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) {
16959     Length = TempOASE->getLength();
16960     if (Length == nullptr) {
16961       // For array sections of the form [1:] or [:], we would need to analyze
16962       // the lower bound...
16963       if (OASE->getColonLocFirst().isValid())
16964         return false;
16965 
16966       // This is an array subscript which has implicit length 1!
16967       ArraySizes.push_back(llvm::APSInt::get(1));
16968     } else {
16969       Expr::EvalResult Result;
16970       if (!Length->EvaluateAsInt(Result, Context))
16971         return false;
16972 
16973       llvm::APSInt ConstantLengthValue = Result.Val.getInt();
16974       if (ConstantLengthValue.getSExtValue() != 1)
16975         return false;
16976 
16977       ArraySizes.push_back(ConstantLengthValue);
16978     }
16979     Base = TempOASE->getBase()->IgnoreParenImpCasts();
16980   }
16981 
16982   // If we have a single element, we don't need to add the implicit lengths.
16983   if (!SingleElement) {
16984     while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) {
16985       // Has implicit length 1!
16986       ArraySizes.push_back(llvm::APSInt::get(1));
16987       Base = TempASE->getBase()->IgnoreParenImpCasts();
16988     }
16989   }
16990 
16991   // This array section can be privatized as a single value or as a constant
16992   // sized array.
16993   return true;
16994 }
16995 
16996 static BinaryOperatorKind
16997 getRelatedCompoundReductionOp(BinaryOperatorKind BOK) {
16998   if (BOK == BO_Add)
16999     return BO_AddAssign;
17000   if (BOK == BO_Mul)
17001     return BO_MulAssign;
17002   if (BOK == BO_And)
17003     return BO_AndAssign;
17004   if (BOK == BO_Or)
17005     return BO_OrAssign;
17006   if (BOK == BO_Xor)
17007     return BO_XorAssign;
17008   return BOK;
17009 }
17010 
17011 static bool actOnOMPReductionKindClause(
17012     Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind,
17013     ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
17014     SourceLocation ColonLoc, SourceLocation EndLoc,
17015     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
17016     ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) {
17017   DeclarationName DN = ReductionId.getName();
17018   OverloadedOperatorKind OOK = DN.getCXXOverloadedOperator();
17019   BinaryOperatorKind BOK = BO_Comma;
17020 
17021   ASTContext &Context = S.Context;
17022   // OpenMP [2.14.3.6, reduction clause]
17023   // C
17024   // reduction-identifier is either an identifier or one of the following
17025   // operators: +, -, *,  &, |, ^, && and ||
17026   // C++
17027   // reduction-identifier is either an id-expression or one of the following
17028   // operators: +, -, *, &, |, ^, && and ||
17029   switch (OOK) {
17030   case OO_Plus:
17031   case OO_Minus:
17032     BOK = BO_Add;
17033     break;
17034   case OO_Star:
17035     BOK = BO_Mul;
17036     break;
17037   case OO_Amp:
17038     BOK = BO_And;
17039     break;
17040   case OO_Pipe:
17041     BOK = BO_Or;
17042     break;
17043   case OO_Caret:
17044     BOK = BO_Xor;
17045     break;
17046   case OO_AmpAmp:
17047     BOK = BO_LAnd;
17048     break;
17049   case OO_PipePipe:
17050     BOK = BO_LOr;
17051     break;
17052   case OO_New:
17053   case OO_Delete:
17054   case OO_Array_New:
17055   case OO_Array_Delete:
17056   case OO_Slash:
17057   case OO_Percent:
17058   case OO_Tilde:
17059   case OO_Exclaim:
17060   case OO_Equal:
17061   case OO_Less:
17062   case OO_Greater:
17063   case OO_LessEqual:
17064   case OO_GreaterEqual:
17065   case OO_PlusEqual:
17066   case OO_MinusEqual:
17067   case OO_StarEqual:
17068   case OO_SlashEqual:
17069   case OO_PercentEqual:
17070   case OO_CaretEqual:
17071   case OO_AmpEqual:
17072   case OO_PipeEqual:
17073   case OO_LessLess:
17074   case OO_GreaterGreater:
17075   case OO_LessLessEqual:
17076   case OO_GreaterGreaterEqual:
17077   case OO_EqualEqual:
17078   case OO_ExclaimEqual:
17079   case OO_Spaceship:
17080   case OO_PlusPlus:
17081   case OO_MinusMinus:
17082   case OO_Comma:
17083   case OO_ArrowStar:
17084   case OO_Arrow:
17085   case OO_Call:
17086   case OO_Subscript:
17087   case OO_Conditional:
17088   case OO_Coawait:
17089   case NUM_OVERLOADED_OPERATORS:
17090     llvm_unreachable("Unexpected reduction identifier");
17091   case OO_None:
17092     if (IdentifierInfo *II = DN.getAsIdentifierInfo()) {
17093       if (II->isStr("max"))
17094         BOK = BO_GT;
17095       else if (II->isStr("min"))
17096         BOK = BO_LT;
17097     }
17098     break;
17099   }
17100   SourceRange ReductionIdRange;
17101   if (ReductionIdScopeSpec.isValid())
17102     ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
17103   else
17104     ReductionIdRange.setBegin(ReductionId.getBeginLoc());
17105   ReductionIdRange.setEnd(ReductionId.getEndLoc());
17106 
17107   auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
17108   bool FirstIter = true;
17109   for (Expr *RefExpr : VarList) {
17110     assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
17111     // OpenMP [2.1, C/C++]
17112     //  A list item is a variable or array section, subject to the restrictions
17113     //  specified in Section 2.4 on page 42 and in each of the sections
17114     // describing clauses and directives for which a list appears.
17115     // OpenMP  [2.14.3.3, Restrictions, p.1]
17116     //  A variable that is part of another variable (as an array or
17117     //  structure element) cannot appear in a private clause.
17118     if (!FirstIter && IR != ER)
17119       ++IR;
17120     FirstIter = false;
17121     SourceLocation ELoc;
17122     SourceRange ERange;
17123     Expr *SimpleRefExpr = RefExpr;
17124     auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
17125                               /*AllowArraySection=*/true);
17126     if (Res.second) {
17127       // Try to find 'declare reduction' corresponding construct before using
17128       // builtin/overloaded operators.
17129       QualType Type = Context.DependentTy;
17130       CXXCastPath BasePath;
17131       ExprResult DeclareReductionRef = buildDeclareReductionRef(
17132           S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
17133           ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
17134       Expr *ReductionOp = nullptr;
17135       if (S.CurContext->isDependentContext() &&
17136           (DeclareReductionRef.isUnset() ||
17137            isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
17138         ReductionOp = DeclareReductionRef.get();
17139       // It will be analyzed later.
17140       RD.push(RefExpr, ReductionOp);
17141     }
17142     ValueDecl *D = Res.first;
17143     if (!D)
17144       continue;
17145 
17146     Expr *TaskgroupDescriptor = nullptr;
17147     QualType Type;
17148     auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
17149     auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
17150     if (ASE) {
17151       Type = ASE->getType().getNonReferenceType();
17152     } else if (OASE) {
17153       QualType BaseType =
17154           OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
17155       if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
17156         Type = ATy->getElementType();
17157       else
17158         Type = BaseType->getPointeeType();
17159       Type = Type.getNonReferenceType();
17160     } else {
17161       Type = Context.getBaseElementType(D->getType().getNonReferenceType());
17162     }
17163     auto *VD = dyn_cast<VarDecl>(D);
17164 
17165     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
17166     //  A variable that appears in a private clause must not have an incomplete
17167     //  type or a reference type.
17168     if (S.RequireCompleteType(ELoc, D->getType(),
17169                               diag::err_omp_reduction_incomplete_type))
17170       continue;
17171     // OpenMP [2.14.3.6, reduction clause, Restrictions]
17172     // A list item that appears in a reduction clause must not be
17173     // const-qualified.
17174     if (rejectConstNotMutableType(S, D, Type, ClauseKind, ELoc,
17175                                   /*AcceptIfMutable*/ false, ASE || OASE))
17176       continue;
17177 
17178     OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective();
17179     // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
17180     //  If a list-item is a reference type then it must bind to the same object
17181     //  for all threads of the team.
17182     if (!ASE && !OASE) {
17183       if (VD) {
17184         VarDecl *VDDef = VD->getDefinition();
17185         if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
17186           DSARefChecker Check(Stack);
17187           if (Check.Visit(VDDef->getInit())) {
17188             S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg)
17189                 << getOpenMPClauseName(ClauseKind) << ERange;
17190             S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
17191             continue;
17192           }
17193         }
17194       }
17195 
17196       // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
17197       // in a Construct]
17198       //  Variables with the predetermined data-sharing attributes may not be
17199       //  listed in data-sharing attributes clauses, except for the cases
17200       //  listed below. For these exceptions only, listing a predetermined
17201       //  variable in a data-sharing attribute clause is allowed and overrides
17202       //  the variable's predetermined data-sharing attributes.
17203       // OpenMP [2.14.3.6, Restrictions, p.3]
17204       //  Any number of reduction clauses can be specified on the directive,
17205       //  but a list item can appear only once in the reduction clauses for that
17206       //  directive.
17207       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false);
17208       if (DVar.CKind == OMPC_reduction) {
17209         S.Diag(ELoc, diag::err_omp_once_referenced)
17210             << getOpenMPClauseName(ClauseKind);
17211         if (DVar.RefExpr)
17212           S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
17213         continue;
17214       }
17215       if (DVar.CKind != OMPC_unknown) {
17216         S.Diag(ELoc, diag::err_omp_wrong_dsa)
17217             << getOpenMPClauseName(DVar.CKind)
17218             << getOpenMPClauseName(OMPC_reduction);
17219         reportOriginalDsa(S, Stack, D, DVar);
17220         continue;
17221       }
17222 
17223       // OpenMP [2.14.3.6, Restrictions, p.1]
17224       //  A list item that appears in a reduction clause of a worksharing
17225       //  construct must be shared in the parallel regions to which any of the
17226       //  worksharing regions arising from the worksharing construct bind.
17227       if (isOpenMPWorksharingDirective(CurrDir) &&
17228           !isOpenMPParallelDirective(CurrDir) &&
17229           !isOpenMPTeamsDirective(CurrDir)) {
17230         DVar = Stack->getImplicitDSA(D, true);
17231         if (DVar.CKind != OMPC_shared) {
17232           S.Diag(ELoc, diag::err_omp_required_access)
17233               << getOpenMPClauseName(OMPC_reduction)
17234               << getOpenMPClauseName(OMPC_shared);
17235           reportOriginalDsa(S, Stack, D, DVar);
17236           continue;
17237         }
17238       }
17239     } else {
17240       // Threadprivates cannot be shared between threads, so dignose if the base
17241       // is a threadprivate variable.
17242       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false);
17243       if (DVar.CKind == OMPC_threadprivate) {
17244         S.Diag(ELoc, diag::err_omp_wrong_dsa)
17245             << getOpenMPClauseName(DVar.CKind)
17246             << getOpenMPClauseName(OMPC_reduction);
17247         reportOriginalDsa(S, Stack, D, DVar);
17248         continue;
17249       }
17250     }
17251 
17252     // Try to find 'declare reduction' corresponding construct before using
17253     // builtin/overloaded operators.
17254     CXXCastPath BasePath;
17255     ExprResult DeclareReductionRef = buildDeclareReductionRef(
17256         S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
17257         ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
17258     if (DeclareReductionRef.isInvalid())
17259       continue;
17260     if (S.CurContext->isDependentContext() &&
17261         (DeclareReductionRef.isUnset() ||
17262          isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
17263       RD.push(RefExpr, DeclareReductionRef.get());
17264       continue;
17265     }
17266     if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
17267       // Not allowed reduction identifier is found.
17268       S.Diag(ReductionId.getBeginLoc(),
17269              diag::err_omp_unknown_reduction_identifier)
17270           << Type << ReductionIdRange;
17271       continue;
17272     }
17273 
17274     // OpenMP [2.14.3.6, reduction clause, Restrictions]
17275     // The type of a list item that appears in a reduction clause must be valid
17276     // for the reduction-identifier. For a max or min reduction in C, the type
17277     // of the list item must be an allowed arithmetic data type: char, int,
17278     // float, double, or _Bool, possibly modified with long, short, signed, or
17279     // unsigned. For a max or min reduction in C++, the type of the list item
17280     // must be an allowed arithmetic data type: char, wchar_t, int, float,
17281     // double, or bool, possibly modified with long, short, signed, or unsigned.
17282     if (DeclareReductionRef.isUnset()) {
17283       if ((BOK == BO_GT || BOK == BO_LT) &&
17284           !(Type->isScalarType() ||
17285             (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
17286         S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
17287             << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus;
17288         if (!ASE && !OASE) {
17289           bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
17290                                    VarDecl::DeclarationOnly;
17291           S.Diag(D->getLocation(),
17292                  IsDecl ? diag::note_previous_decl : diag::note_defined_here)
17293               << D;
17294         }
17295         continue;
17296       }
17297       if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
17298           !S.getLangOpts().CPlusPlus && Type->isFloatingType()) {
17299         S.Diag(ELoc, diag::err_omp_clause_floating_type_arg)
17300             << getOpenMPClauseName(ClauseKind);
17301         if (!ASE && !OASE) {
17302           bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
17303                                    VarDecl::DeclarationOnly;
17304           S.Diag(D->getLocation(),
17305                  IsDecl ? diag::note_previous_decl : diag::note_defined_here)
17306               << D;
17307         }
17308         continue;
17309       }
17310     }
17311 
17312     Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
17313     VarDecl *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs",
17314                                   D->hasAttrs() ? &D->getAttrs() : nullptr);
17315     VarDecl *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(),
17316                                   D->hasAttrs() ? &D->getAttrs() : nullptr);
17317     QualType PrivateTy = Type;
17318 
17319     // Try if we can determine constant lengths for all array sections and avoid
17320     // the VLA.
17321     bool ConstantLengthOASE = false;
17322     if (OASE) {
17323       bool SingleElement;
17324       llvm::SmallVector<llvm::APSInt, 4> ArraySizes;
17325       ConstantLengthOASE = checkOMPArraySectionConstantForReduction(
17326           Context, OASE, SingleElement, ArraySizes);
17327 
17328       // If we don't have a single element, we must emit a constant array type.
17329       if (ConstantLengthOASE && !SingleElement) {
17330         for (llvm::APSInt &Size : ArraySizes)
17331           PrivateTy = Context.getConstantArrayType(PrivateTy, Size, nullptr,
17332                                                    ArrayType::Normal,
17333                                                    /*IndexTypeQuals=*/0);
17334       }
17335     }
17336 
17337     if ((OASE && !ConstantLengthOASE) ||
17338         (!OASE && !ASE &&
17339          D->getType().getNonReferenceType()->isVariablyModifiedType())) {
17340       if (!Context.getTargetInfo().isVLASupported()) {
17341         if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective())) {
17342           S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
17343           S.Diag(ELoc, diag::note_vla_unsupported);
17344           continue;
17345         } else {
17346           S.targetDiag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
17347           S.targetDiag(ELoc, diag::note_vla_unsupported);
17348         }
17349       }
17350       // For arrays/array sections only:
17351       // Create pseudo array type for private copy. The size for this array will
17352       // be generated during codegen.
17353       // For array subscripts or single variables Private Ty is the same as Type
17354       // (type of the variable or single array element).
17355       PrivateTy = Context.getVariableArrayType(
17356           Type,
17357           new (Context)
17358               OpaqueValueExpr(ELoc, Context.getSizeType(), VK_PRValue),
17359           ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
17360     } else if (!ASE && !OASE &&
17361                Context.getAsArrayType(D->getType().getNonReferenceType())) {
17362       PrivateTy = D->getType().getNonReferenceType();
17363     }
17364     // Private copy.
17365     VarDecl *PrivateVD =
17366         buildVarDecl(S, ELoc, PrivateTy, D->getName(),
17367                      D->hasAttrs() ? &D->getAttrs() : nullptr,
17368                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
17369     // Add initializer for private variable.
17370     Expr *Init = nullptr;
17371     DeclRefExpr *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc);
17372     DeclRefExpr *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc);
17373     if (DeclareReductionRef.isUsable()) {
17374       auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
17375       auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
17376       if (DRD->getInitializer()) {
17377         Init = DRDRef;
17378         RHSVD->setInit(DRDRef);
17379         RHSVD->setInitStyle(VarDecl::CallInit);
17380       }
17381     } else {
17382       switch (BOK) {
17383       case BO_Add:
17384       case BO_Xor:
17385       case BO_Or:
17386       case BO_LOr:
17387         // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
17388         if (Type->isScalarType() || Type->isAnyComplexType())
17389           Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get();
17390         break;
17391       case BO_Mul:
17392       case BO_LAnd:
17393         if (Type->isScalarType() || Type->isAnyComplexType()) {
17394           // '*' and '&&' reduction ops - initializer is '1'.
17395           Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get();
17396         }
17397         break;
17398       case BO_And: {
17399         // '&' reduction op - initializer is '~0'.
17400         QualType OrigType = Type;
17401         if (auto *ComplexTy = OrigType->getAs<ComplexType>())
17402           Type = ComplexTy->getElementType();
17403         if (Type->isRealFloatingType()) {
17404           llvm::APFloat InitValue = llvm::APFloat::getAllOnesValue(
17405               Context.getFloatTypeSemantics(Type));
17406           Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
17407                                          Type, ELoc);
17408         } else if (Type->isScalarType()) {
17409           uint64_t Size = Context.getTypeSize(Type);
17410           QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
17411           llvm::APInt InitValue = llvm::APInt::getAllOnes(Size);
17412           Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
17413         }
17414         if (Init && OrigType->isAnyComplexType()) {
17415           // Init = 0xFFFF + 0xFFFFi;
17416           auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
17417           Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
17418         }
17419         Type = OrigType;
17420         break;
17421       }
17422       case BO_LT:
17423       case BO_GT: {
17424         // 'min' reduction op - initializer is 'Largest representable number in
17425         // the reduction list item type'.
17426         // 'max' reduction op - initializer is 'Least representable number in
17427         // the reduction list item type'.
17428         if (Type->isIntegerType() || Type->isPointerType()) {
17429           bool IsSigned = Type->hasSignedIntegerRepresentation();
17430           uint64_t Size = Context.getTypeSize(Type);
17431           QualType IntTy =
17432               Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
17433           llvm::APInt InitValue =
17434               (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
17435                                         : llvm::APInt::getMinValue(Size)
17436               : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
17437                              : llvm::APInt::getMaxValue(Size);
17438           Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
17439           if (Type->isPointerType()) {
17440             // Cast to pointer type.
17441             ExprResult CastExpr = S.BuildCStyleCastExpr(
17442                 ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init);
17443             if (CastExpr.isInvalid())
17444               continue;
17445             Init = CastExpr.get();
17446           }
17447         } else if (Type->isRealFloatingType()) {
17448           llvm::APFloat InitValue = llvm::APFloat::getLargest(
17449               Context.getFloatTypeSemantics(Type), BOK != BO_LT);
17450           Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
17451                                          Type, ELoc);
17452         }
17453         break;
17454       }
17455       case BO_PtrMemD:
17456       case BO_PtrMemI:
17457       case BO_MulAssign:
17458       case BO_Div:
17459       case BO_Rem:
17460       case BO_Sub:
17461       case BO_Shl:
17462       case BO_Shr:
17463       case BO_LE:
17464       case BO_GE:
17465       case BO_EQ:
17466       case BO_NE:
17467       case BO_Cmp:
17468       case BO_AndAssign:
17469       case BO_XorAssign:
17470       case BO_OrAssign:
17471       case BO_Assign:
17472       case BO_AddAssign:
17473       case BO_SubAssign:
17474       case BO_DivAssign:
17475       case BO_RemAssign:
17476       case BO_ShlAssign:
17477       case BO_ShrAssign:
17478       case BO_Comma:
17479         llvm_unreachable("Unexpected reduction operation");
17480       }
17481     }
17482     if (Init && DeclareReductionRef.isUnset()) {
17483       S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
17484       // Store initializer for single element in private copy. Will be used
17485       // during codegen.
17486       PrivateVD->setInit(RHSVD->getInit());
17487       PrivateVD->setInitStyle(RHSVD->getInitStyle());
17488     } else if (!Init) {
17489       S.ActOnUninitializedDecl(RHSVD);
17490       // Store initializer for single element in private copy. Will be used
17491       // during codegen.
17492       PrivateVD->setInit(RHSVD->getInit());
17493       PrivateVD->setInitStyle(RHSVD->getInitStyle());
17494     }
17495     if (RHSVD->isInvalidDecl())
17496       continue;
17497     if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) {
17498       S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible)
17499           << Type << ReductionIdRange;
17500       bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
17501                                VarDecl::DeclarationOnly;
17502       S.Diag(D->getLocation(),
17503              IsDecl ? diag::note_previous_decl : diag::note_defined_here)
17504           << D;
17505       continue;
17506     }
17507     DeclRefExpr *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc);
17508     ExprResult ReductionOp;
17509     if (DeclareReductionRef.isUsable()) {
17510       QualType RedTy = DeclareReductionRef.get()->getType();
17511       QualType PtrRedTy = Context.getPointerType(RedTy);
17512       ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
17513       ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
17514       if (!BasePath.empty()) {
17515         LHS = S.DefaultLvalueConversion(LHS.get());
17516         RHS = S.DefaultLvalueConversion(RHS.get());
17517         LHS = ImplicitCastExpr::Create(
17518             Context, PtrRedTy, CK_UncheckedDerivedToBase, LHS.get(), &BasePath,
17519             LHS.get()->getValueKind(), FPOptionsOverride());
17520         RHS = ImplicitCastExpr::Create(
17521             Context, PtrRedTy, CK_UncheckedDerivedToBase, RHS.get(), &BasePath,
17522             RHS.get()->getValueKind(), FPOptionsOverride());
17523       }
17524       FunctionProtoType::ExtProtoInfo EPI;
17525       QualType Params[] = {PtrRedTy, PtrRedTy};
17526       QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
17527       auto *OVE = new (Context) OpaqueValueExpr(
17528           ELoc, Context.getPointerType(FnTy), VK_PRValue, OK_Ordinary,
17529           S.DefaultLvalueConversion(DeclareReductionRef.get()).get());
17530       Expr *Args[] = {LHS.get(), RHS.get()};
17531       ReductionOp =
17532           CallExpr::Create(Context, OVE, Args, Context.VoidTy, VK_PRValue, ELoc,
17533                            S.CurFPFeatureOverrides());
17534     } else {
17535       BinaryOperatorKind CombBOK = getRelatedCompoundReductionOp(BOK);
17536       if (Type->isRecordType() && CombBOK != BOK) {
17537         Sema::TentativeAnalysisScope Trap(S);
17538         ReductionOp =
17539             S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
17540                          CombBOK, LHSDRE, RHSDRE);
17541       }
17542       if (!ReductionOp.isUsable()) {
17543         ReductionOp =
17544             S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(), BOK,
17545                          LHSDRE, RHSDRE);
17546         if (ReductionOp.isUsable()) {
17547           if (BOK != BO_LT && BOK != BO_GT) {
17548             ReductionOp =
17549                 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
17550                              BO_Assign, LHSDRE, ReductionOp.get());
17551           } else {
17552             auto *ConditionalOp = new (Context)
17553                 ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc,
17554                                     RHSDRE, Type, VK_LValue, OK_Ordinary);
17555             ReductionOp =
17556                 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
17557                              BO_Assign, LHSDRE, ConditionalOp);
17558           }
17559         }
17560       }
17561       if (ReductionOp.isUsable())
17562         ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get(),
17563                                             /*DiscardedValue*/ false);
17564       if (!ReductionOp.isUsable())
17565         continue;
17566     }
17567 
17568     // Add copy operations for inscan reductions.
17569     // LHS = RHS;
17570     ExprResult CopyOpRes, TempArrayRes, TempArrayElem;
17571     if (ClauseKind == OMPC_reduction &&
17572         RD.RedModifier == OMPC_REDUCTION_inscan) {
17573       ExprResult RHS = S.DefaultLvalueConversion(RHSDRE);
17574       CopyOpRes = S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, LHSDRE,
17575                                RHS.get());
17576       if (!CopyOpRes.isUsable())
17577         continue;
17578       CopyOpRes =
17579           S.ActOnFinishFullExpr(CopyOpRes.get(), /*DiscardedValue=*/true);
17580       if (!CopyOpRes.isUsable())
17581         continue;
17582       // For simd directive and simd-based directives in simd mode no need to
17583       // construct temp array, need just a single temp element.
17584       if (Stack->getCurrentDirective() == OMPD_simd ||
17585           (S.getLangOpts().OpenMPSimd &&
17586            isOpenMPSimdDirective(Stack->getCurrentDirective()))) {
17587         VarDecl *TempArrayVD =
17588             buildVarDecl(S, ELoc, PrivateTy, D->getName(),
17589                          D->hasAttrs() ? &D->getAttrs() : nullptr);
17590         // Add a constructor to the temp decl.
17591         S.ActOnUninitializedDecl(TempArrayVD);
17592         TempArrayRes = buildDeclRefExpr(S, TempArrayVD, PrivateTy, ELoc);
17593       } else {
17594         // Build temp array for prefix sum.
17595         auto *Dim = new (S.Context)
17596             OpaqueValueExpr(ELoc, S.Context.getSizeType(), VK_PRValue);
17597         QualType ArrayTy =
17598             S.Context.getVariableArrayType(PrivateTy, Dim, ArrayType::Normal,
17599                                            /*IndexTypeQuals=*/0, {ELoc, ELoc});
17600         VarDecl *TempArrayVD =
17601             buildVarDecl(S, ELoc, ArrayTy, D->getName(),
17602                          D->hasAttrs() ? &D->getAttrs() : nullptr);
17603         // Add a constructor to the temp decl.
17604         S.ActOnUninitializedDecl(TempArrayVD);
17605         TempArrayRes = buildDeclRefExpr(S, TempArrayVD, ArrayTy, ELoc);
17606         TempArrayElem =
17607             S.DefaultFunctionArrayLvalueConversion(TempArrayRes.get());
17608         auto *Idx = new (S.Context)
17609             OpaqueValueExpr(ELoc, S.Context.getSizeType(), VK_PRValue);
17610         TempArrayElem = S.CreateBuiltinArraySubscriptExpr(TempArrayElem.get(),
17611                                                           ELoc, Idx, ELoc);
17612       }
17613     }
17614 
17615     // OpenMP [2.15.4.6, Restrictions, p.2]
17616     // A list item that appears in an in_reduction clause of a task construct
17617     // must appear in a task_reduction clause of a construct associated with a
17618     // taskgroup region that includes the participating task in its taskgroup
17619     // set. The construct associated with the innermost region that meets this
17620     // condition must specify the same reduction-identifier as the in_reduction
17621     // clause.
17622     if (ClauseKind == OMPC_in_reduction) {
17623       SourceRange ParentSR;
17624       BinaryOperatorKind ParentBOK;
17625       const Expr *ParentReductionOp = nullptr;
17626       Expr *ParentBOKTD = nullptr, *ParentReductionOpTD = nullptr;
17627       DSAStackTy::DSAVarData ParentBOKDSA =
17628           Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK,
17629                                                   ParentBOKTD);
17630       DSAStackTy::DSAVarData ParentReductionOpDSA =
17631           Stack->getTopMostTaskgroupReductionData(
17632               D, ParentSR, ParentReductionOp, ParentReductionOpTD);
17633       bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown;
17634       bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown;
17635       if ((DeclareReductionRef.isUnset() && IsParentReductionOp) ||
17636           (DeclareReductionRef.isUsable() && IsParentBOK) ||
17637           (IsParentBOK && BOK != ParentBOK) || IsParentReductionOp) {
17638         bool EmitError = true;
17639         if (IsParentReductionOp && DeclareReductionRef.isUsable()) {
17640           llvm::FoldingSetNodeID RedId, ParentRedId;
17641           ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true);
17642           DeclareReductionRef.get()->Profile(RedId, Context,
17643                                              /*Canonical=*/true);
17644           EmitError = RedId != ParentRedId;
17645         }
17646         if (EmitError) {
17647           S.Diag(ReductionId.getBeginLoc(),
17648                  diag::err_omp_reduction_identifier_mismatch)
17649               << ReductionIdRange << RefExpr->getSourceRange();
17650           S.Diag(ParentSR.getBegin(),
17651                  diag::note_omp_previous_reduction_identifier)
17652               << ParentSR
17653               << (IsParentBOK ? ParentBOKDSA.RefExpr
17654                               : ParentReductionOpDSA.RefExpr)
17655                      ->getSourceRange();
17656           continue;
17657         }
17658       }
17659       TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD;
17660     }
17661 
17662     DeclRefExpr *Ref = nullptr;
17663     Expr *VarsExpr = RefExpr->IgnoreParens();
17664     if (!VD && !S.CurContext->isDependentContext()) {
17665       if (ASE || OASE) {
17666         TransformExprToCaptures RebuildToCapture(S, D);
17667         VarsExpr =
17668             RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
17669         Ref = RebuildToCapture.getCapturedExpr();
17670       } else {
17671         VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false);
17672       }
17673       if (!S.isOpenMPCapturedDecl(D)) {
17674         RD.ExprCaptures.emplace_back(Ref->getDecl());
17675         if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
17676           ExprResult RefRes = S.DefaultLvalueConversion(Ref);
17677           if (!RefRes.isUsable())
17678             continue;
17679           ExprResult PostUpdateRes =
17680               S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
17681                            RefRes.get());
17682           if (!PostUpdateRes.isUsable())
17683             continue;
17684           if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
17685               Stack->getCurrentDirective() == OMPD_taskgroup) {
17686             S.Diag(RefExpr->getExprLoc(),
17687                    diag::err_omp_reduction_non_addressable_expression)
17688                 << RefExpr->getSourceRange();
17689             continue;
17690           }
17691           RD.ExprPostUpdates.emplace_back(
17692               S.IgnoredValueConversions(PostUpdateRes.get()).get());
17693         }
17694       }
17695     }
17696     // All reduction items are still marked as reduction (to do not increase
17697     // code base size).
17698     unsigned Modifier = RD.RedModifier;
17699     // Consider task_reductions as reductions with task modifier. Required for
17700     // correct analysis of in_reduction clauses.
17701     if (CurrDir == OMPD_taskgroup && ClauseKind == OMPC_task_reduction)
17702       Modifier = OMPC_REDUCTION_task;
17703     Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref, Modifier,
17704                   ASE || OASE);
17705     if (Modifier == OMPC_REDUCTION_task &&
17706         (CurrDir == OMPD_taskgroup ||
17707          ((isOpenMPParallelDirective(CurrDir) ||
17708            isOpenMPWorksharingDirective(CurrDir)) &&
17709           !isOpenMPSimdDirective(CurrDir)))) {
17710       if (DeclareReductionRef.isUsable())
17711         Stack->addTaskgroupReductionData(D, ReductionIdRange,
17712                                          DeclareReductionRef.get());
17713       else
17714         Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK);
17715     }
17716     RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(),
17717             TaskgroupDescriptor, CopyOpRes.get(), TempArrayRes.get(),
17718             TempArrayElem.get());
17719   }
17720   return RD.Vars.empty();
17721 }
17722 
17723 OMPClause *Sema::ActOnOpenMPReductionClause(
17724     ArrayRef<Expr *> VarList, OpenMPReductionClauseModifier Modifier,
17725     SourceLocation StartLoc, SourceLocation LParenLoc,
17726     SourceLocation ModifierLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
17727     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
17728     ArrayRef<Expr *> UnresolvedReductions) {
17729   if (ModifierLoc.isValid() && Modifier == OMPC_REDUCTION_unknown) {
17730     Diag(LParenLoc, diag::err_omp_unexpected_clause_value)
17731         << getListOfPossibleValues(OMPC_reduction, /*First=*/0,
17732                                    /*Last=*/OMPC_REDUCTION_unknown)
17733         << getOpenMPClauseName(OMPC_reduction);
17734     return nullptr;
17735   }
17736   // OpenMP 5.0, 2.19.5.4 reduction Clause, Restrictions
17737   // A reduction clause with the inscan reduction-modifier may only appear on a
17738   // worksharing-loop construct, a worksharing-loop SIMD construct, a simd
17739   // construct, a parallel worksharing-loop construct or a parallel
17740   // worksharing-loop SIMD construct.
17741   if (Modifier == OMPC_REDUCTION_inscan &&
17742       (DSAStack->getCurrentDirective() != OMPD_for &&
17743        DSAStack->getCurrentDirective() != OMPD_for_simd &&
17744        DSAStack->getCurrentDirective() != OMPD_simd &&
17745        DSAStack->getCurrentDirective() != OMPD_parallel_for &&
17746        DSAStack->getCurrentDirective() != OMPD_parallel_for_simd)) {
17747     Diag(ModifierLoc, diag::err_omp_wrong_inscan_reduction);
17748     return nullptr;
17749   }
17750 
17751   ReductionData RD(VarList.size(), Modifier);
17752   if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList,
17753                                   StartLoc, LParenLoc, ColonLoc, EndLoc,
17754                                   ReductionIdScopeSpec, ReductionId,
17755                                   UnresolvedReductions, RD))
17756     return nullptr;
17757 
17758   return OMPReductionClause::Create(
17759       Context, StartLoc, LParenLoc, ModifierLoc, ColonLoc, EndLoc, Modifier,
17760       RD.Vars, ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
17761       RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.InscanCopyOps,
17762       RD.InscanCopyArrayTemps, RD.InscanCopyArrayElems,
17763       buildPreInits(Context, RD.ExprCaptures),
17764       buildPostUpdate(*this, RD.ExprPostUpdates));
17765 }
17766 
17767 OMPClause *Sema::ActOnOpenMPTaskReductionClause(
17768     ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
17769     SourceLocation ColonLoc, SourceLocation EndLoc,
17770     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
17771     ArrayRef<Expr *> UnresolvedReductions) {
17772   ReductionData RD(VarList.size());
17773   if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction, VarList,
17774                                   StartLoc, LParenLoc, ColonLoc, EndLoc,
17775                                   ReductionIdScopeSpec, ReductionId,
17776                                   UnresolvedReductions, RD))
17777     return nullptr;
17778 
17779   return OMPTaskReductionClause::Create(
17780       Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
17781       ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
17782       RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
17783       buildPreInits(Context, RD.ExprCaptures),
17784       buildPostUpdate(*this, RD.ExprPostUpdates));
17785 }
17786 
17787 OMPClause *Sema::ActOnOpenMPInReductionClause(
17788     ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
17789     SourceLocation ColonLoc, SourceLocation EndLoc,
17790     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
17791     ArrayRef<Expr *> UnresolvedReductions) {
17792   ReductionData RD(VarList.size());
17793   if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList,
17794                                   StartLoc, LParenLoc, ColonLoc, EndLoc,
17795                                   ReductionIdScopeSpec, ReductionId,
17796                                   UnresolvedReductions, RD))
17797     return nullptr;
17798 
17799   return OMPInReductionClause::Create(
17800       Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
17801       ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
17802       RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors,
17803       buildPreInits(Context, RD.ExprCaptures),
17804       buildPostUpdate(*this, RD.ExprPostUpdates));
17805 }
17806 
17807 bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
17808                                      SourceLocation LinLoc) {
17809   if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
17810       LinKind == OMPC_LINEAR_unknown) {
17811     Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
17812     return true;
17813   }
17814   return false;
17815 }
17816 
17817 bool Sema::CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc,
17818                                  OpenMPLinearClauseKind LinKind, QualType Type,
17819                                  bool IsDeclareSimd) {
17820   const auto *VD = dyn_cast_or_null<VarDecl>(D);
17821   // A variable must not have an incomplete type or a reference type.
17822   if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
17823     return true;
17824   if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
17825       !Type->isReferenceType()) {
17826     Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
17827         << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
17828     return true;
17829   }
17830   Type = Type.getNonReferenceType();
17831 
17832   // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
17833   // A variable that is privatized must not have a const-qualified type
17834   // unless it is of class type with a mutable member. This restriction does
17835   // not apply to the firstprivate clause, nor to the linear clause on
17836   // declarative directives (like declare simd).
17837   if (!IsDeclareSimd &&
17838       rejectConstNotMutableType(*this, D, Type, OMPC_linear, ELoc))
17839     return true;
17840 
17841   // A list item must be of integral or pointer type.
17842   Type = Type.getUnqualifiedType().getCanonicalType();
17843   const auto *Ty = Type.getTypePtrOrNull();
17844   if (!Ty || (LinKind != OMPC_LINEAR_ref && !Ty->isDependentType() &&
17845               !Ty->isIntegralType(Context) && !Ty->isPointerType())) {
17846     Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
17847     if (D) {
17848       bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
17849                                VarDecl::DeclarationOnly;
17850       Diag(D->getLocation(),
17851            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
17852           << D;
17853     }
17854     return true;
17855   }
17856   return false;
17857 }
17858 
17859 OMPClause *Sema::ActOnOpenMPLinearClause(
17860     ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
17861     SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
17862     SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
17863   SmallVector<Expr *, 8> Vars;
17864   SmallVector<Expr *, 8> Privates;
17865   SmallVector<Expr *, 8> Inits;
17866   SmallVector<Decl *, 4> ExprCaptures;
17867   SmallVector<Expr *, 4> ExprPostUpdates;
17868   if (CheckOpenMPLinearModifier(LinKind, LinLoc))
17869     LinKind = OMPC_LINEAR_val;
17870   for (Expr *RefExpr : VarList) {
17871     assert(RefExpr && "NULL expr in OpenMP linear clause.");
17872     SourceLocation ELoc;
17873     SourceRange ERange;
17874     Expr *SimpleRefExpr = RefExpr;
17875     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
17876     if (Res.second) {
17877       // It will be analyzed later.
17878       Vars.push_back(RefExpr);
17879       Privates.push_back(nullptr);
17880       Inits.push_back(nullptr);
17881     }
17882     ValueDecl *D = Res.first;
17883     if (!D)
17884       continue;
17885 
17886     QualType Type = D->getType();
17887     auto *VD = dyn_cast<VarDecl>(D);
17888 
17889     // OpenMP [2.14.3.7, linear clause]
17890     //  A list-item cannot appear in more than one linear clause.
17891     //  A list-item that appears in a linear clause cannot appear in any
17892     //  other data-sharing attribute clause.
17893     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
17894     if (DVar.RefExpr) {
17895       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
17896                                           << getOpenMPClauseName(OMPC_linear);
17897       reportOriginalDsa(*this, DSAStack, D, DVar);
17898       continue;
17899     }
17900 
17901     if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
17902       continue;
17903     Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
17904 
17905     // Build private copy of original var.
17906     VarDecl *Private =
17907         buildVarDecl(*this, ELoc, Type, D->getName(),
17908                      D->hasAttrs() ? &D->getAttrs() : nullptr,
17909                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
17910     DeclRefExpr *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
17911     // Build var to save initial value.
17912     VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
17913     Expr *InitExpr;
17914     DeclRefExpr *Ref = nullptr;
17915     if (!VD && !CurContext->isDependentContext()) {
17916       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
17917       if (!isOpenMPCapturedDecl(D)) {
17918         ExprCaptures.push_back(Ref->getDecl());
17919         if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
17920           ExprResult RefRes = DefaultLvalueConversion(Ref);
17921           if (!RefRes.isUsable())
17922             continue;
17923           ExprResult PostUpdateRes =
17924               BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
17925                          SimpleRefExpr, RefRes.get());
17926           if (!PostUpdateRes.isUsable())
17927             continue;
17928           ExprPostUpdates.push_back(
17929               IgnoredValueConversions(PostUpdateRes.get()).get());
17930         }
17931       }
17932     }
17933     if (LinKind == OMPC_LINEAR_uval)
17934       InitExpr = VD ? VD->getInit() : SimpleRefExpr;
17935     else
17936       InitExpr = VD ? SimpleRefExpr : Ref;
17937     AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
17938                          /*DirectInit=*/false);
17939     DeclRefExpr *InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
17940 
17941     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
17942     Vars.push_back((VD || CurContext->isDependentContext())
17943                        ? RefExpr->IgnoreParens()
17944                        : Ref);
17945     Privates.push_back(PrivateRef);
17946     Inits.push_back(InitRef);
17947   }
17948 
17949   if (Vars.empty())
17950     return nullptr;
17951 
17952   Expr *StepExpr = Step;
17953   Expr *CalcStepExpr = nullptr;
17954   if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
17955       !Step->isInstantiationDependent() &&
17956       !Step->containsUnexpandedParameterPack()) {
17957     SourceLocation StepLoc = Step->getBeginLoc();
17958     ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
17959     if (Val.isInvalid())
17960       return nullptr;
17961     StepExpr = Val.get();
17962 
17963     // Build var to save the step value.
17964     VarDecl *SaveVar =
17965         buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
17966     ExprResult SaveRef =
17967         buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
17968     ExprResult CalcStep =
17969         BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
17970     CalcStep = ActOnFinishFullExpr(CalcStep.get(), /*DiscardedValue*/ false);
17971 
17972     // Warn about zero linear step (it would be probably better specified as
17973     // making corresponding variables 'const').
17974     if (Optional<llvm::APSInt> Result =
17975             StepExpr->getIntegerConstantExpr(Context)) {
17976       if (!Result->isNegative() && !Result->isStrictlyPositive())
17977         Diag(StepLoc, diag::warn_omp_linear_step_zero)
17978             << Vars[0] << (Vars.size() > 1);
17979     } else if (CalcStep.isUsable()) {
17980       // Calculate the step beforehand instead of doing this on each iteration.
17981       // (This is not used if the number of iterations may be kfold-ed).
17982       CalcStepExpr = CalcStep.get();
17983     }
17984   }
17985 
17986   return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
17987                                  ColonLoc, EndLoc, Vars, Privates, Inits,
17988                                  StepExpr, CalcStepExpr,
17989                                  buildPreInits(Context, ExprCaptures),
17990                                  buildPostUpdate(*this, ExprPostUpdates));
17991 }
17992 
17993 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
17994                                      Expr *NumIterations, Sema &SemaRef,
17995                                      Scope *S, DSAStackTy *Stack) {
17996   // Walk the vars and build update/final expressions for the CodeGen.
17997   SmallVector<Expr *, 8> Updates;
17998   SmallVector<Expr *, 8> Finals;
17999   SmallVector<Expr *, 8> UsedExprs;
18000   Expr *Step = Clause.getStep();
18001   Expr *CalcStep = Clause.getCalcStep();
18002   // OpenMP [2.14.3.7, linear clause]
18003   // If linear-step is not specified it is assumed to be 1.
18004   if (!Step)
18005     Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
18006   else if (CalcStep)
18007     Step = cast<BinaryOperator>(CalcStep)->getLHS();
18008   bool HasErrors = false;
18009   auto CurInit = Clause.inits().begin();
18010   auto CurPrivate = Clause.privates().begin();
18011   OpenMPLinearClauseKind LinKind = Clause.getModifier();
18012   for (Expr *RefExpr : Clause.varlists()) {
18013     SourceLocation ELoc;
18014     SourceRange ERange;
18015     Expr *SimpleRefExpr = RefExpr;
18016     auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange);
18017     ValueDecl *D = Res.first;
18018     if (Res.second || !D) {
18019       Updates.push_back(nullptr);
18020       Finals.push_back(nullptr);
18021       HasErrors = true;
18022       continue;
18023     }
18024     auto &&Info = Stack->isLoopControlVariable(D);
18025     // OpenMP [2.15.11, distribute simd Construct]
18026     // A list item may not appear in a linear clause, unless it is the loop
18027     // iteration variable.
18028     if (isOpenMPDistributeDirective(Stack->getCurrentDirective()) &&
18029         isOpenMPSimdDirective(Stack->getCurrentDirective()) && !Info.first) {
18030       SemaRef.Diag(ELoc,
18031                    diag::err_omp_linear_distribute_var_non_loop_iteration);
18032       Updates.push_back(nullptr);
18033       Finals.push_back(nullptr);
18034       HasErrors = true;
18035       continue;
18036     }
18037     Expr *InitExpr = *CurInit;
18038 
18039     // Build privatized reference to the current linear var.
18040     auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
18041     Expr *CapturedRef;
18042     if (LinKind == OMPC_LINEAR_uval)
18043       CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
18044     else
18045       CapturedRef =
18046           buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
18047                            DE->getType().getUnqualifiedType(), DE->getExprLoc(),
18048                            /*RefersToCapture=*/true);
18049 
18050     // Build update: Var = InitExpr + IV * Step
18051     ExprResult Update;
18052     if (!Info.first)
18053       Update = buildCounterUpdate(
18054           SemaRef, S, RefExpr->getExprLoc(), *CurPrivate, InitExpr, IV, Step,
18055           /*Subtract=*/false, /*IsNonRectangularLB=*/false);
18056     else
18057       Update = *CurPrivate;
18058     Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getBeginLoc(),
18059                                          /*DiscardedValue*/ false);
18060 
18061     // Build final: Var = PrivCopy;
18062     ExprResult Final;
18063     if (!Info.first)
18064       Final = SemaRef.BuildBinOp(
18065           S, RefExpr->getExprLoc(), BO_Assign, CapturedRef,
18066           SemaRef.DefaultLvalueConversion(*CurPrivate).get());
18067     else
18068       Final = *CurPrivate;
18069     Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getBeginLoc(),
18070                                         /*DiscardedValue*/ false);
18071 
18072     if (!Update.isUsable() || !Final.isUsable()) {
18073       Updates.push_back(nullptr);
18074       Finals.push_back(nullptr);
18075       UsedExprs.push_back(nullptr);
18076       HasErrors = true;
18077     } else {
18078       Updates.push_back(Update.get());
18079       Finals.push_back(Final.get());
18080       if (!Info.first)
18081         UsedExprs.push_back(SimpleRefExpr);
18082     }
18083     ++CurInit;
18084     ++CurPrivate;
18085   }
18086   if (Expr *S = Clause.getStep())
18087     UsedExprs.push_back(S);
18088   // Fill the remaining part with the nullptr.
18089   UsedExprs.append(Clause.varlist_size() + 1 - UsedExprs.size(), nullptr);
18090   Clause.setUpdates(Updates);
18091   Clause.setFinals(Finals);
18092   Clause.setUsedExprs(UsedExprs);
18093   return HasErrors;
18094 }
18095 
18096 OMPClause *Sema::ActOnOpenMPAlignedClause(
18097     ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
18098     SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
18099   SmallVector<Expr *, 8> Vars;
18100   for (Expr *RefExpr : VarList) {
18101     assert(RefExpr && "NULL expr in OpenMP linear clause.");
18102     SourceLocation ELoc;
18103     SourceRange ERange;
18104     Expr *SimpleRefExpr = RefExpr;
18105     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
18106     if (Res.second) {
18107       // It will be analyzed later.
18108       Vars.push_back(RefExpr);
18109     }
18110     ValueDecl *D = Res.first;
18111     if (!D)
18112       continue;
18113 
18114     QualType QType = D->getType();
18115     auto *VD = dyn_cast<VarDecl>(D);
18116 
18117     // OpenMP  [2.8.1, simd construct, Restrictions]
18118     // The type of list items appearing in the aligned clause must be
18119     // array, pointer, reference to array, or reference to pointer.
18120     QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
18121     const Type *Ty = QType.getTypePtrOrNull();
18122     if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
18123       Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
18124           << QType << getLangOpts().CPlusPlus << ERange;
18125       bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
18126                                VarDecl::DeclarationOnly;
18127       Diag(D->getLocation(),
18128            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
18129           << D;
18130       continue;
18131     }
18132 
18133     // OpenMP  [2.8.1, simd construct, Restrictions]
18134     // A list-item cannot appear in more than one aligned clause.
18135     if (const Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
18136       Diag(ELoc, diag::err_omp_used_in_clause_twice)
18137           << 0 << getOpenMPClauseName(OMPC_aligned) << ERange;
18138       Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
18139           << getOpenMPClauseName(OMPC_aligned);
18140       continue;
18141     }
18142 
18143     DeclRefExpr *Ref = nullptr;
18144     if (!VD && isOpenMPCapturedDecl(D))
18145       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
18146     Vars.push_back(DefaultFunctionArrayConversion(
18147                        (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
18148                        .get());
18149   }
18150 
18151   // OpenMP [2.8.1, simd construct, Description]
18152   // The parameter of the aligned clause, alignment, must be a constant
18153   // positive integer expression.
18154   // If no optional parameter is specified, implementation-defined default
18155   // alignments for SIMD instructions on the target platforms are assumed.
18156   if (Alignment != nullptr) {
18157     ExprResult AlignResult =
18158         VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
18159     if (AlignResult.isInvalid())
18160       return nullptr;
18161     Alignment = AlignResult.get();
18162   }
18163   if (Vars.empty())
18164     return nullptr;
18165 
18166   return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
18167                                   EndLoc, Vars, Alignment);
18168 }
18169 
18170 OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
18171                                          SourceLocation StartLoc,
18172                                          SourceLocation LParenLoc,
18173                                          SourceLocation EndLoc) {
18174   SmallVector<Expr *, 8> Vars;
18175   SmallVector<Expr *, 8> SrcExprs;
18176   SmallVector<Expr *, 8> DstExprs;
18177   SmallVector<Expr *, 8> AssignmentOps;
18178   for (Expr *RefExpr : VarList) {
18179     assert(RefExpr && "NULL expr in OpenMP copyin clause.");
18180     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
18181       // It will be analyzed later.
18182       Vars.push_back(RefExpr);
18183       SrcExprs.push_back(nullptr);
18184       DstExprs.push_back(nullptr);
18185       AssignmentOps.push_back(nullptr);
18186       continue;
18187     }
18188 
18189     SourceLocation ELoc = RefExpr->getExprLoc();
18190     // OpenMP [2.1, C/C++]
18191     //  A list item is a variable name.
18192     // OpenMP  [2.14.4.1, Restrictions, p.1]
18193     //  A list item that appears in a copyin clause must be threadprivate.
18194     auto *DE = dyn_cast<DeclRefExpr>(RefExpr);
18195     if (!DE || !isa<VarDecl>(DE->getDecl())) {
18196       Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
18197           << 0 << RefExpr->getSourceRange();
18198       continue;
18199     }
18200 
18201     Decl *D = DE->getDecl();
18202     auto *VD = cast<VarDecl>(D);
18203 
18204     QualType Type = VD->getType();
18205     if (Type->isDependentType() || Type->isInstantiationDependentType()) {
18206       // It will be analyzed later.
18207       Vars.push_back(DE);
18208       SrcExprs.push_back(nullptr);
18209       DstExprs.push_back(nullptr);
18210       AssignmentOps.push_back(nullptr);
18211       continue;
18212     }
18213 
18214     // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
18215     //  A list item that appears in a copyin clause must be threadprivate.
18216     if (!DSAStack->isThreadPrivate(VD)) {
18217       Diag(ELoc, diag::err_omp_required_access)
18218           << getOpenMPClauseName(OMPC_copyin)
18219           << getOpenMPDirectiveName(OMPD_threadprivate);
18220       continue;
18221     }
18222 
18223     // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
18224     //  A variable of class type (or array thereof) that appears in a
18225     //  copyin clause requires an accessible, unambiguous copy assignment
18226     //  operator for the class type.
18227     QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
18228     VarDecl *SrcVD =
18229         buildVarDecl(*this, DE->getBeginLoc(), ElemType.getUnqualifiedType(),
18230                      ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
18231     DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(
18232         *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
18233     VarDecl *DstVD =
18234         buildVarDecl(*this, DE->getBeginLoc(), ElemType, ".copyin.dst",
18235                      VD->hasAttrs() ? &VD->getAttrs() : nullptr);
18236     DeclRefExpr *PseudoDstExpr =
18237         buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
18238     // For arrays generate assignment operation for single element and replace
18239     // it by the original array element in CodeGen.
18240     ExprResult AssignmentOp =
18241         BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign, PseudoDstExpr,
18242                    PseudoSrcExpr);
18243     if (AssignmentOp.isInvalid())
18244       continue;
18245     AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
18246                                        /*DiscardedValue*/ false);
18247     if (AssignmentOp.isInvalid())
18248       continue;
18249 
18250     DSAStack->addDSA(VD, DE, OMPC_copyin);
18251     Vars.push_back(DE);
18252     SrcExprs.push_back(PseudoSrcExpr);
18253     DstExprs.push_back(PseudoDstExpr);
18254     AssignmentOps.push_back(AssignmentOp.get());
18255   }
18256 
18257   if (Vars.empty())
18258     return nullptr;
18259 
18260   return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
18261                                  SrcExprs, DstExprs, AssignmentOps);
18262 }
18263 
18264 OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
18265                                               SourceLocation StartLoc,
18266                                               SourceLocation LParenLoc,
18267                                               SourceLocation EndLoc) {
18268   SmallVector<Expr *, 8> Vars;
18269   SmallVector<Expr *, 8> SrcExprs;
18270   SmallVector<Expr *, 8> DstExprs;
18271   SmallVector<Expr *, 8> AssignmentOps;
18272   for (Expr *RefExpr : VarList) {
18273     assert(RefExpr && "NULL expr in OpenMP linear clause.");
18274     SourceLocation ELoc;
18275     SourceRange ERange;
18276     Expr *SimpleRefExpr = RefExpr;
18277     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
18278     if (Res.second) {
18279       // It will be analyzed later.
18280       Vars.push_back(RefExpr);
18281       SrcExprs.push_back(nullptr);
18282       DstExprs.push_back(nullptr);
18283       AssignmentOps.push_back(nullptr);
18284     }
18285     ValueDecl *D = Res.first;
18286     if (!D)
18287       continue;
18288 
18289     QualType Type = D->getType();
18290     auto *VD = dyn_cast<VarDecl>(D);
18291 
18292     // OpenMP [2.14.4.2, Restrictions, p.2]
18293     //  A list item that appears in a copyprivate clause may not appear in a
18294     //  private or firstprivate clause on the single construct.
18295     if (!VD || !DSAStack->isThreadPrivate(VD)) {
18296       DSAStackTy::DSAVarData DVar =
18297           DSAStack->getTopDSA(D, /*FromParent=*/false);
18298       if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
18299           DVar.RefExpr) {
18300         Diag(ELoc, diag::err_omp_wrong_dsa)
18301             << getOpenMPClauseName(DVar.CKind)
18302             << getOpenMPClauseName(OMPC_copyprivate);
18303         reportOriginalDsa(*this, DSAStack, D, DVar);
18304         continue;
18305       }
18306 
18307       // OpenMP [2.11.4.2, Restrictions, p.1]
18308       //  All list items that appear in a copyprivate clause must be either
18309       //  threadprivate or private in the enclosing context.
18310       if (DVar.CKind == OMPC_unknown) {
18311         DVar = DSAStack->getImplicitDSA(D, false);
18312         if (DVar.CKind == OMPC_shared) {
18313           Diag(ELoc, diag::err_omp_required_access)
18314               << getOpenMPClauseName(OMPC_copyprivate)
18315               << "threadprivate or private in the enclosing context";
18316           reportOriginalDsa(*this, DSAStack, D, DVar);
18317           continue;
18318         }
18319       }
18320     }
18321 
18322     // Variably modified types are not supported.
18323     if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
18324       Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
18325           << getOpenMPClauseName(OMPC_copyprivate) << Type
18326           << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
18327       bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
18328                                VarDecl::DeclarationOnly;
18329       Diag(D->getLocation(),
18330            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
18331           << D;
18332       continue;
18333     }
18334 
18335     // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
18336     //  A variable of class type (or array thereof) that appears in a
18337     //  copyin clause requires an accessible, unambiguous copy assignment
18338     //  operator for the class type.
18339     Type = Context.getBaseElementType(Type.getNonReferenceType())
18340                .getUnqualifiedType();
18341     VarDecl *SrcVD =
18342         buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.src",
18343                      D->hasAttrs() ? &D->getAttrs() : nullptr);
18344     DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
18345     VarDecl *DstVD =
18346         buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.dst",
18347                      D->hasAttrs() ? &D->getAttrs() : nullptr);
18348     DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
18349     ExprResult AssignmentOp = BuildBinOp(
18350         DSAStack->getCurScope(), ELoc, BO_Assign, PseudoDstExpr, PseudoSrcExpr);
18351     if (AssignmentOp.isInvalid())
18352       continue;
18353     AssignmentOp =
18354         ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
18355     if (AssignmentOp.isInvalid())
18356       continue;
18357 
18358     // No need to mark vars as copyprivate, they are already threadprivate or
18359     // implicitly private.
18360     assert(VD || isOpenMPCapturedDecl(D));
18361     Vars.push_back(
18362         VD ? RefExpr->IgnoreParens()
18363            : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
18364     SrcExprs.push_back(PseudoSrcExpr);
18365     DstExprs.push_back(PseudoDstExpr);
18366     AssignmentOps.push_back(AssignmentOp.get());
18367   }
18368 
18369   if (Vars.empty())
18370     return nullptr;
18371 
18372   return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
18373                                       Vars, SrcExprs, DstExprs, AssignmentOps);
18374 }
18375 
18376 OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
18377                                         SourceLocation StartLoc,
18378                                         SourceLocation LParenLoc,
18379                                         SourceLocation EndLoc) {
18380   if (VarList.empty())
18381     return nullptr;
18382 
18383   return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
18384 }
18385 
18386 /// Tries to find omp_depend_t. type.
18387 static bool findOMPDependT(Sema &S, SourceLocation Loc, DSAStackTy *Stack,
18388                            bool Diagnose = true) {
18389   QualType OMPDependT = Stack->getOMPDependT();
18390   if (!OMPDependT.isNull())
18391     return true;
18392   IdentifierInfo *II = &S.PP.getIdentifierTable().get("omp_depend_t");
18393   ParsedType PT = S.getTypeName(*II, Loc, S.getCurScope());
18394   if (!PT.getAsOpaquePtr() || PT.get().isNull()) {
18395     if (Diagnose)
18396       S.Diag(Loc, diag::err_omp_implied_type_not_found) << "omp_depend_t";
18397     return false;
18398   }
18399   Stack->setOMPDependT(PT.get());
18400   return true;
18401 }
18402 
18403 OMPClause *Sema::ActOnOpenMPDepobjClause(Expr *Depobj, SourceLocation StartLoc,
18404                                          SourceLocation LParenLoc,
18405                                          SourceLocation EndLoc) {
18406   if (!Depobj)
18407     return nullptr;
18408 
18409   bool OMPDependTFound = findOMPDependT(*this, StartLoc, DSAStack);
18410 
18411   // OpenMP 5.0, 2.17.10.1 depobj Construct
18412   // depobj is an lvalue expression of type omp_depend_t.
18413   if (!Depobj->isTypeDependent() && !Depobj->isValueDependent() &&
18414       !Depobj->isInstantiationDependent() &&
18415       !Depobj->containsUnexpandedParameterPack() &&
18416       (OMPDependTFound &&
18417        !Context.typesAreCompatible(DSAStack->getOMPDependT(), Depobj->getType(),
18418                                    /*CompareUnqualified=*/true))) {
18419     Diag(Depobj->getExprLoc(), diag::err_omp_expected_omp_depend_t_lvalue)
18420         << 0 << Depobj->getType() << Depobj->getSourceRange();
18421   }
18422 
18423   if (!Depobj->isLValue()) {
18424     Diag(Depobj->getExprLoc(), diag::err_omp_expected_omp_depend_t_lvalue)
18425         << 1 << Depobj->getSourceRange();
18426   }
18427 
18428   return OMPDepobjClause::Create(Context, StartLoc, LParenLoc, EndLoc, Depobj);
18429 }
18430 
18431 OMPClause *
18432 Sema::ActOnOpenMPDependClause(Expr *DepModifier, OpenMPDependClauseKind DepKind,
18433                               SourceLocation DepLoc, SourceLocation ColonLoc,
18434                               ArrayRef<Expr *> VarList, SourceLocation StartLoc,
18435                               SourceLocation LParenLoc, SourceLocation EndLoc) {
18436   if (DSAStack->getCurrentDirective() == OMPD_ordered &&
18437       DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
18438     Diag(DepLoc, diag::err_omp_unexpected_clause_value)
18439         << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
18440     return nullptr;
18441   }
18442   if (DSAStack->getCurrentDirective() == OMPD_taskwait &&
18443       DepKind == OMPC_DEPEND_mutexinoutset) {
18444     Diag(DepLoc, diag::err_omp_taskwait_depend_mutexinoutset_not_allowed);
18445     return nullptr;
18446   }
18447   if ((DSAStack->getCurrentDirective() != OMPD_ordered ||
18448        DSAStack->getCurrentDirective() == OMPD_depobj) &&
18449       (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
18450        DepKind == OMPC_DEPEND_sink ||
18451        ((LangOpts.OpenMP < 50 ||
18452          DSAStack->getCurrentDirective() == OMPD_depobj) &&
18453         DepKind == OMPC_DEPEND_depobj))) {
18454     SmallVector<unsigned, 3> Except;
18455     Except.push_back(OMPC_DEPEND_source);
18456     Except.push_back(OMPC_DEPEND_sink);
18457     if (LangOpts.OpenMP < 50 || DSAStack->getCurrentDirective() == OMPD_depobj)
18458       Except.push_back(OMPC_DEPEND_depobj);
18459     std::string Expected = (LangOpts.OpenMP >= 50 && !DepModifier)
18460                                ? "depend modifier(iterator) or "
18461                                : "";
18462     Diag(DepLoc, diag::err_omp_unexpected_clause_value)
18463         << Expected + getListOfPossibleValues(OMPC_depend, /*First=*/0,
18464                                               /*Last=*/OMPC_DEPEND_unknown,
18465                                               Except)
18466         << getOpenMPClauseName(OMPC_depend);
18467     return nullptr;
18468   }
18469   if (DepModifier &&
18470       (DepKind == OMPC_DEPEND_source || DepKind == OMPC_DEPEND_sink)) {
18471     Diag(DepModifier->getExprLoc(),
18472          diag::err_omp_depend_sink_source_with_modifier);
18473     return nullptr;
18474   }
18475   if (DepModifier &&
18476       !DepModifier->getType()->isSpecificBuiltinType(BuiltinType::OMPIterator))
18477     Diag(DepModifier->getExprLoc(), diag::err_omp_depend_modifier_not_iterator);
18478 
18479   SmallVector<Expr *, 8> Vars;
18480   DSAStackTy::OperatorOffsetTy OpsOffs;
18481   llvm::APSInt DepCounter(/*BitWidth=*/32);
18482   llvm::APSInt TotalDepCount(/*BitWidth=*/32);
18483   if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) {
18484     if (const Expr *OrderedCountExpr =
18485             DSAStack->getParentOrderedRegionParam().first) {
18486       TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
18487       TotalDepCount.setIsUnsigned(/*Val=*/true);
18488     }
18489   }
18490   for (Expr *RefExpr : VarList) {
18491     assert(RefExpr && "NULL expr in OpenMP shared clause.");
18492     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
18493       // It will be analyzed later.
18494       Vars.push_back(RefExpr);
18495       continue;
18496     }
18497 
18498     SourceLocation ELoc = RefExpr->getExprLoc();
18499     Expr *SimpleExpr = RefExpr->IgnoreParenCasts();
18500     if (DepKind == OMPC_DEPEND_sink) {
18501       if (DSAStack->getParentOrderedRegionParam().first &&
18502           DepCounter >= TotalDepCount) {
18503         Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
18504         continue;
18505       }
18506       ++DepCounter;
18507       // OpenMP  [2.13.9, Summary]
18508       // depend(dependence-type : vec), where dependence-type is:
18509       // 'sink' and where vec is the iteration vector, which has the form:
18510       //  x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
18511       // where n is the value specified by the ordered clause in the loop
18512       // directive, xi denotes the loop iteration variable of the i-th nested
18513       // loop associated with the loop directive, and di is a constant
18514       // non-negative integer.
18515       if (CurContext->isDependentContext()) {
18516         // It will be analyzed later.
18517         Vars.push_back(RefExpr);
18518         continue;
18519       }
18520       SimpleExpr = SimpleExpr->IgnoreImplicit();
18521       OverloadedOperatorKind OOK = OO_None;
18522       SourceLocation OOLoc;
18523       Expr *LHS = SimpleExpr;
18524       Expr *RHS = nullptr;
18525       if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
18526         OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
18527         OOLoc = BO->getOperatorLoc();
18528         LHS = BO->getLHS()->IgnoreParenImpCasts();
18529         RHS = BO->getRHS()->IgnoreParenImpCasts();
18530       } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
18531         OOK = OCE->getOperator();
18532         OOLoc = OCE->getOperatorLoc();
18533         LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
18534         RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
18535       } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
18536         OOK = MCE->getMethodDecl()
18537                   ->getNameInfo()
18538                   .getName()
18539                   .getCXXOverloadedOperator();
18540         OOLoc = MCE->getCallee()->getExprLoc();
18541         LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
18542         RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
18543       }
18544       SourceLocation ELoc;
18545       SourceRange ERange;
18546       auto Res = getPrivateItem(*this, LHS, ELoc, ERange);
18547       if (Res.second) {
18548         // It will be analyzed later.
18549         Vars.push_back(RefExpr);
18550       }
18551       ValueDecl *D = Res.first;
18552       if (!D)
18553         continue;
18554 
18555       if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
18556         Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
18557         continue;
18558       }
18559       if (RHS) {
18560         ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
18561             RHS, OMPC_depend, /*StrictlyPositive=*/false);
18562         if (RHSRes.isInvalid())
18563           continue;
18564       }
18565       if (!CurContext->isDependentContext() &&
18566           DSAStack->getParentOrderedRegionParam().first &&
18567           DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
18568         const ValueDecl *VD =
18569             DSAStack->getParentLoopControlVariable(DepCounter.getZExtValue());
18570         if (VD)
18571           Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
18572               << 1 << VD;
18573         else
18574           Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0;
18575         continue;
18576       }
18577       OpsOffs.emplace_back(RHS, OOK);
18578     } else {
18579       bool OMPDependTFound = LangOpts.OpenMP >= 50;
18580       if (OMPDependTFound)
18581         OMPDependTFound = findOMPDependT(*this, StartLoc, DSAStack,
18582                                          DepKind == OMPC_DEPEND_depobj);
18583       if (DepKind == OMPC_DEPEND_depobj) {
18584         // OpenMP 5.0, 2.17.11 depend Clause, Restrictions, C/C++
18585         // List items used in depend clauses with the depobj dependence type
18586         // must be expressions of the omp_depend_t type.
18587         if (!RefExpr->isValueDependent() && !RefExpr->isTypeDependent() &&
18588             !RefExpr->isInstantiationDependent() &&
18589             !RefExpr->containsUnexpandedParameterPack() &&
18590             (OMPDependTFound &&
18591              !Context.hasSameUnqualifiedType(DSAStack->getOMPDependT(),
18592                                              RefExpr->getType()))) {
18593           Diag(ELoc, diag::err_omp_expected_omp_depend_t_lvalue)
18594               << 0 << RefExpr->getType() << RefExpr->getSourceRange();
18595           continue;
18596         }
18597         if (!RefExpr->isLValue()) {
18598           Diag(ELoc, diag::err_omp_expected_omp_depend_t_lvalue)
18599               << 1 << RefExpr->getType() << RefExpr->getSourceRange();
18600           continue;
18601         }
18602       } else {
18603         // OpenMP 5.0 [2.17.11, Restrictions]
18604         // List items used in depend clauses cannot be zero-length array
18605         // sections.
18606         QualType ExprTy = RefExpr->getType().getNonReferenceType();
18607         const auto *OASE = dyn_cast<OMPArraySectionExpr>(SimpleExpr);
18608         if (OASE) {
18609           QualType BaseType =
18610               OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
18611           if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
18612             ExprTy = ATy->getElementType();
18613           else
18614             ExprTy = BaseType->getPointeeType();
18615           ExprTy = ExprTy.getNonReferenceType();
18616           const Expr *Length = OASE->getLength();
18617           Expr::EvalResult Result;
18618           if (Length && !Length->isValueDependent() &&
18619               Length->EvaluateAsInt(Result, Context) &&
18620               Result.Val.getInt().isZero()) {
18621             Diag(ELoc,
18622                  diag::err_omp_depend_zero_length_array_section_not_allowed)
18623                 << SimpleExpr->getSourceRange();
18624             continue;
18625           }
18626         }
18627 
18628         // OpenMP 5.0, 2.17.11 depend Clause, Restrictions, C/C++
18629         // List items used in depend clauses with the in, out, inout or
18630         // mutexinoutset dependence types cannot be expressions of the
18631         // omp_depend_t type.
18632         if (!RefExpr->isValueDependent() && !RefExpr->isTypeDependent() &&
18633             !RefExpr->isInstantiationDependent() &&
18634             !RefExpr->containsUnexpandedParameterPack() &&
18635             (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
18636              (OMPDependTFound &&
18637               DSAStack->getOMPDependT().getTypePtr() == ExprTy.getTypePtr()))) {
18638           Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
18639               << (LangOpts.OpenMP >= 50 ? 1 : 0)
18640               << (LangOpts.OpenMP >= 50 ? 1 : 0) << RefExpr->getSourceRange();
18641           continue;
18642         }
18643 
18644         auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
18645         if (ASE && !ASE->getBase()->isTypeDependent() &&
18646             !ASE->getBase()->getType().getNonReferenceType()->isPointerType() &&
18647             !ASE->getBase()->getType().getNonReferenceType()->isArrayType()) {
18648           Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
18649               << (LangOpts.OpenMP >= 50 ? 1 : 0)
18650               << (LangOpts.OpenMP >= 50 ? 1 : 0) << RefExpr->getSourceRange();
18651           continue;
18652         }
18653 
18654         ExprResult Res;
18655         {
18656           Sema::TentativeAnalysisScope Trap(*this);
18657           Res = CreateBuiltinUnaryOp(ELoc, UO_AddrOf,
18658                                      RefExpr->IgnoreParenImpCasts());
18659         }
18660         if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr) &&
18661             !isa<OMPArrayShapingExpr>(SimpleExpr)) {
18662           Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
18663               << (LangOpts.OpenMP >= 50 ? 1 : 0)
18664               << (LangOpts.OpenMP >= 50 ? 1 : 0) << RefExpr->getSourceRange();
18665           continue;
18666         }
18667       }
18668     }
18669     Vars.push_back(RefExpr->IgnoreParenImpCasts());
18670   }
18671 
18672   if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
18673       TotalDepCount > VarList.size() &&
18674       DSAStack->getParentOrderedRegionParam().first &&
18675       DSAStack->getParentLoopControlVariable(VarList.size() + 1)) {
18676     Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
18677         << 1 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
18678   }
18679   if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
18680       Vars.empty())
18681     return nullptr;
18682 
18683   auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
18684                                     DepModifier, DepKind, DepLoc, ColonLoc,
18685                                     Vars, TotalDepCount.getZExtValue());
18686   if ((DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) &&
18687       DSAStack->isParentOrderedRegion())
18688     DSAStack->addDoacrossDependClause(C, OpsOffs);
18689   return C;
18690 }
18691 
18692 OMPClause *Sema::ActOnOpenMPDeviceClause(OpenMPDeviceClauseModifier Modifier,
18693                                          Expr *Device, SourceLocation StartLoc,
18694                                          SourceLocation LParenLoc,
18695                                          SourceLocation ModifierLoc,
18696                                          SourceLocation EndLoc) {
18697   assert((ModifierLoc.isInvalid() || LangOpts.OpenMP >= 50) &&
18698          "Unexpected device modifier in OpenMP < 50.");
18699 
18700   bool ErrorFound = false;
18701   if (ModifierLoc.isValid() && Modifier == OMPC_DEVICE_unknown) {
18702     std::string Values =
18703         getListOfPossibleValues(OMPC_device, /*First=*/0, OMPC_DEVICE_unknown);
18704     Diag(ModifierLoc, diag::err_omp_unexpected_clause_value)
18705         << Values << getOpenMPClauseName(OMPC_device);
18706     ErrorFound = true;
18707   }
18708 
18709   Expr *ValExpr = Device;
18710   Stmt *HelperValStmt = nullptr;
18711 
18712   // OpenMP [2.9.1, Restrictions]
18713   // The device expression must evaluate to a non-negative integer value.
18714   ErrorFound = !isNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
18715                                           /*StrictlyPositive=*/false) ||
18716                ErrorFound;
18717   if (ErrorFound)
18718     return nullptr;
18719 
18720   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
18721   OpenMPDirectiveKind CaptureRegion =
18722       getOpenMPCaptureRegionForClause(DKind, OMPC_device, LangOpts.OpenMP);
18723   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
18724     ValExpr = MakeFullExpr(ValExpr).get();
18725     llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
18726     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
18727     HelperValStmt = buildPreInits(Context, Captures);
18728   }
18729 
18730   return new (Context)
18731       OMPDeviceClause(Modifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
18732                       LParenLoc, ModifierLoc, EndLoc);
18733 }
18734 
18735 static bool checkTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
18736                               DSAStackTy *Stack, QualType QTy,
18737                               bool FullCheck = true) {
18738   if (SemaRef.RequireCompleteType(SL, QTy, diag::err_incomplete_type))
18739     return false;
18740   if (FullCheck && !SemaRef.CurContext->isDependentContext() &&
18741       !QTy.isTriviallyCopyableType(SemaRef.Context))
18742     SemaRef.Diag(SL, diag::warn_omp_non_trivial_type_mapped) << QTy << SR;
18743   return true;
18744 }
18745 
18746 /// Return true if it can be proven that the provided array expression
18747 /// (array section or array subscript) does NOT specify the whole size of the
18748 /// array whose base type is \a BaseQTy.
18749 static bool checkArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
18750                                                         const Expr *E,
18751                                                         QualType BaseQTy) {
18752   const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
18753 
18754   // If this is an array subscript, it refers to the whole size if the size of
18755   // the dimension is constant and equals 1. Also, an array section assumes the
18756   // format of an array subscript if no colon is used.
18757   if (isa<ArraySubscriptExpr>(E) ||
18758       (OASE && OASE->getColonLocFirst().isInvalid())) {
18759     if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
18760       return ATy->getSize().getSExtValue() != 1;
18761     // Size can't be evaluated statically.
18762     return false;
18763   }
18764 
18765   assert(OASE && "Expecting array section if not an array subscript.");
18766   const Expr *LowerBound = OASE->getLowerBound();
18767   const Expr *Length = OASE->getLength();
18768 
18769   // If there is a lower bound that does not evaluates to zero, we are not
18770   // covering the whole dimension.
18771   if (LowerBound) {
18772     Expr::EvalResult Result;
18773     if (!LowerBound->EvaluateAsInt(Result, SemaRef.getASTContext()))
18774       return false; // Can't get the integer value as a constant.
18775 
18776     llvm::APSInt ConstLowerBound = Result.Val.getInt();
18777     if (ConstLowerBound.getSExtValue())
18778       return true;
18779   }
18780 
18781   // If we don't have a length we covering the whole dimension.
18782   if (!Length)
18783     return false;
18784 
18785   // If the base is a pointer, we don't have a way to get the size of the
18786   // pointee.
18787   if (BaseQTy->isPointerType())
18788     return false;
18789 
18790   // We can only check if the length is the same as the size of the dimension
18791   // if we have a constant array.
18792   const auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
18793   if (!CATy)
18794     return false;
18795 
18796   Expr::EvalResult Result;
18797   if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
18798     return false; // Can't get the integer value as a constant.
18799 
18800   llvm::APSInt ConstLength = Result.Val.getInt();
18801   return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
18802 }
18803 
18804 // Return true if it can be proven that the provided array expression (array
18805 // section or array subscript) does NOT specify a single element of the array
18806 // whose base type is \a BaseQTy.
18807 static bool checkArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
18808                                                         const Expr *E,
18809                                                         QualType BaseQTy) {
18810   const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
18811 
18812   // An array subscript always refer to a single element. Also, an array section
18813   // assumes the format of an array subscript if no colon is used.
18814   if (isa<ArraySubscriptExpr>(E) ||
18815       (OASE && OASE->getColonLocFirst().isInvalid()))
18816     return false;
18817 
18818   assert(OASE && "Expecting array section if not an array subscript.");
18819   const Expr *Length = OASE->getLength();
18820 
18821   // If we don't have a length we have to check if the array has unitary size
18822   // for this dimension. Also, we should always expect a length if the base type
18823   // is pointer.
18824   if (!Length) {
18825     if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
18826       return ATy->getSize().getSExtValue() != 1;
18827     // We cannot assume anything.
18828     return false;
18829   }
18830 
18831   // Check if the length evaluates to 1.
18832   Expr::EvalResult Result;
18833   if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
18834     return false; // Can't get the integer value as a constant.
18835 
18836   llvm::APSInt ConstLength = Result.Val.getInt();
18837   return ConstLength.getSExtValue() != 1;
18838 }
18839 
18840 // The base of elements of list in a map clause have to be either:
18841 //  - a reference to variable or field.
18842 //  - a member expression.
18843 //  - an array expression.
18844 //
18845 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
18846 // reference to 'r'.
18847 //
18848 // If we have:
18849 //
18850 // struct SS {
18851 //   Bla S;
18852 //   foo() {
18853 //     #pragma omp target map (S.Arr[:12]);
18854 //   }
18855 // }
18856 //
18857 // We want to retrieve the member expression 'this->S';
18858 
18859 // OpenMP 5.0 [2.19.7.1, map Clause, Restrictions, p.2]
18860 //  If a list item is an array section, it must specify contiguous storage.
18861 //
18862 // For this restriction it is sufficient that we make sure only references
18863 // to variables or fields and array expressions, and that no array sections
18864 // exist except in the rightmost expression (unless they cover the whole
18865 // dimension of the array). E.g. these would be invalid:
18866 //
18867 //   r.ArrS[3:5].Arr[6:7]
18868 //
18869 //   r.ArrS[3:5].x
18870 //
18871 // but these would be valid:
18872 //   r.ArrS[3].Arr[6:7]
18873 //
18874 //   r.ArrS[3].x
18875 namespace {
18876 class MapBaseChecker final : public StmtVisitor<MapBaseChecker, bool> {
18877   Sema &SemaRef;
18878   OpenMPClauseKind CKind = OMPC_unknown;
18879   OpenMPDirectiveKind DKind = OMPD_unknown;
18880   OMPClauseMappableExprCommon::MappableExprComponentList &Components;
18881   bool IsNonContiguous = false;
18882   bool NoDiagnose = false;
18883   const Expr *RelevantExpr = nullptr;
18884   bool AllowUnitySizeArraySection = true;
18885   bool AllowWholeSizeArraySection = true;
18886   bool AllowAnotherPtr = true;
18887   SourceLocation ELoc;
18888   SourceRange ERange;
18889 
18890   void emitErrorMsg() {
18891     // If nothing else worked, this is not a valid map clause expression.
18892     if (SemaRef.getLangOpts().OpenMP < 50) {
18893       SemaRef.Diag(ELoc,
18894                    diag::err_omp_expected_named_var_member_or_array_expression)
18895           << ERange;
18896     } else {
18897       SemaRef.Diag(ELoc, diag::err_omp_non_lvalue_in_map_or_motion_clauses)
18898           << getOpenMPClauseName(CKind) << ERange;
18899     }
18900   }
18901 
18902 public:
18903   bool VisitDeclRefExpr(DeclRefExpr *DRE) {
18904     if (!isa<VarDecl>(DRE->getDecl())) {
18905       emitErrorMsg();
18906       return false;
18907     }
18908     assert(!RelevantExpr && "RelevantExpr is expected to be nullptr");
18909     RelevantExpr = DRE;
18910     // Record the component.
18911     Components.emplace_back(DRE, DRE->getDecl(), IsNonContiguous);
18912     return true;
18913   }
18914 
18915   bool VisitMemberExpr(MemberExpr *ME) {
18916     Expr *E = ME;
18917     Expr *BaseE = ME->getBase()->IgnoreParenCasts();
18918 
18919     if (isa<CXXThisExpr>(BaseE)) {
18920       assert(!RelevantExpr && "RelevantExpr is expected to be nullptr");
18921       // We found a base expression: this->Val.
18922       RelevantExpr = ME;
18923     } else {
18924       E = BaseE;
18925     }
18926 
18927     if (!isa<FieldDecl>(ME->getMemberDecl())) {
18928       if (!NoDiagnose) {
18929         SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
18930             << ME->getSourceRange();
18931         return false;
18932       }
18933       if (RelevantExpr)
18934         return false;
18935       return Visit(E);
18936     }
18937 
18938     auto *FD = cast<FieldDecl>(ME->getMemberDecl());
18939 
18940     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
18941     //  A bit-field cannot appear in a map clause.
18942     //
18943     if (FD->isBitField()) {
18944       if (!NoDiagnose) {
18945         SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
18946             << ME->getSourceRange() << getOpenMPClauseName(CKind);
18947         return false;
18948       }
18949       if (RelevantExpr)
18950         return false;
18951       return Visit(E);
18952     }
18953 
18954     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
18955     //  If the type of a list item is a reference to a type T then the type
18956     //  will be considered to be T for all purposes of this clause.
18957     QualType CurType = BaseE->getType().getNonReferenceType();
18958 
18959     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
18960     //  A list item cannot be a variable that is a member of a structure with
18961     //  a union type.
18962     //
18963     if (CurType->isUnionType()) {
18964       if (!NoDiagnose) {
18965         SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
18966             << ME->getSourceRange();
18967         return false;
18968       }
18969       return RelevantExpr || Visit(E);
18970     }
18971 
18972     // If we got a member expression, we should not expect any array section
18973     // before that:
18974     //
18975     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
18976     //  If a list item is an element of a structure, only the rightmost symbol
18977     //  of the variable reference can be an array section.
18978     //
18979     AllowUnitySizeArraySection = false;
18980     AllowWholeSizeArraySection = false;
18981 
18982     // Record the component.
18983     Components.emplace_back(ME, FD, IsNonContiguous);
18984     return RelevantExpr || Visit(E);
18985   }
18986 
18987   bool VisitArraySubscriptExpr(ArraySubscriptExpr *AE) {
18988     Expr *E = AE->getBase()->IgnoreParenImpCasts();
18989 
18990     if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
18991       if (!NoDiagnose) {
18992         SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
18993             << 0 << AE->getSourceRange();
18994         return false;
18995       }
18996       return RelevantExpr || Visit(E);
18997     }
18998 
18999     // If we got an array subscript that express the whole dimension we
19000     // can have any array expressions before. If it only expressing part of
19001     // the dimension, we can only have unitary-size array expressions.
19002     if (checkArrayExpressionDoesNotReferToWholeSize(SemaRef, AE, E->getType()))
19003       AllowWholeSizeArraySection = false;
19004 
19005     if (const auto *TE = dyn_cast<CXXThisExpr>(E->IgnoreParenCasts())) {
19006       Expr::EvalResult Result;
19007       if (!AE->getIdx()->isValueDependent() &&
19008           AE->getIdx()->EvaluateAsInt(Result, SemaRef.getASTContext()) &&
19009           !Result.Val.getInt().isZero()) {
19010         SemaRef.Diag(AE->getIdx()->getExprLoc(),
19011                      diag::err_omp_invalid_map_this_expr);
19012         SemaRef.Diag(AE->getIdx()->getExprLoc(),
19013                      diag::note_omp_invalid_subscript_on_this_ptr_map);
19014       }
19015       assert(!RelevantExpr && "RelevantExpr is expected to be nullptr");
19016       RelevantExpr = TE;
19017     }
19018 
19019     // Record the component - we don't have any declaration associated.
19020     Components.emplace_back(AE, nullptr, IsNonContiguous);
19021 
19022     return RelevantExpr || Visit(E);
19023   }
19024 
19025   bool VisitOMPArraySectionExpr(OMPArraySectionExpr *OASE) {
19026     // After OMP 5.0  Array section in reduction clause will be implicitly
19027     // mapped
19028     assert(!(SemaRef.getLangOpts().OpenMP < 50 && NoDiagnose) &&
19029            "Array sections cannot be implicitly mapped.");
19030     Expr *E = OASE->getBase()->IgnoreParenImpCasts();
19031     QualType CurType =
19032         OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
19033 
19034     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
19035     //  If the type of a list item is a reference to a type T then the type
19036     //  will be considered to be T for all purposes of this clause.
19037     if (CurType->isReferenceType())
19038       CurType = CurType->getPointeeType();
19039 
19040     bool IsPointer = CurType->isAnyPointerType();
19041 
19042     if (!IsPointer && !CurType->isArrayType()) {
19043       SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
19044           << 0 << OASE->getSourceRange();
19045       return false;
19046     }
19047 
19048     bool NotWhole =
19049         checkArrayExpressionDoesNotReferToWholeSize(SemaRef, OASE, CurType);
19050     bool NotUnity =
19051         checkArrayExpressionDoesNotReferToUnitySize(SemaRef, OASE, CurType);
19052 
19053     if (AllowWholeSizeArraySection) {
19054       // Any array section is currently allowed. Allowing a whole size array
19055       // section implies allowing a unity array section as well.
19056       //
19057       // If this array section refers to the whole dimension we can still
19058       // accept other array sections before this one, except if the base is a
19059       // pointer. Otherwise, only unitary sections are accepted.
19060       if (NotWhole || IsPointer)
19061         AllowWholeSizeArraySection = false;
19062     } else if (DKind == OMPD_target_update &&
19063                SemaRef.getLangOpts().OpenMP >= 50) {
19064       if (IsPointer && !AllowAnotherPtr)
19065         SemaRef.Diag(ELoc, diag::err_omp_section_length_undefined)
19066             << /*array of unknown bound */ 1;
19067       else
19068         IsNonContiguous = true;
19069     } else if (AllowUnitySizeArraySection && NotUnity) {
19070       // A unity or whole array section is not allowed and that is not
19071       // compatible with the properties of the current array section.
19072       if (NoDiagnose)
19073         return false;
19074       SemaRef.Diag(ELoc,
19075                    diag::err_array_section_does_not_specify_contiguous_storage)
19076           << OASE->getSourceRange();
19077       return false;
19078     }
19079 
19080     if (IsPointer)
19081       AllowAnotherPtr = false;
19082 
19083     if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
19084       Expr::EvalResult ResultR;
19085       Expr::EvalResult ResultL;
19086       if (!OASE->getLength()->isValueDependent() &&
19087           OASE->getLength()->EvaluateAsInt(ResultR, SemaRef.getASTContext()) &&
19088           !ResultR.Val.getInt().isOne()) {
19089         SemaRef.Diag(OASE->getLength()->getExprLoc(),
19090                      diag::err_omp_invalid_map_this_expr);
19091         SemaRef.Diag(OASE->getLength()->getExprLoc(),
19092                      diag::note_omp_invalid_length_on_this_ptr_mapping);
19093       }
19094       if (OASE->getLowerBound() && !OASE->getLowerBound()->isValueDependent() &&
19095           OASE->getLowerBound()->EvaluateAsInt(ResultL,
19096                                                SemaRef.getASTContext()) &&
19097           !ResultL.Val.getInt().isZero()) {
19098         SemaRef.Diag(OASE->getLowerBound()->getExprLoc(),
19099                      diag::err_omp_invalid_map_this_expr);
19100         SemaRef.Diag(OASE->getLowerBound()->getExprLoc(),
19101                      diag::note_omp_invalid_lower_bound_on_this_ptr_mapping);
19102       }
19103       assert(!RelevantExpr && "RelevantExpr is expected to be nullptr");
19104       RelevantExpr = TE;
19105     }
19106 
19107     // Record the component - we don't have any declaration associated.
19108     Components.emplace_back(OASE, nullptr, /*IsNonContiguous=*/false);
19109     return RelevantExpr || Visit(E);
19110   }
19111   bool VisitOMPArrayShapingExpr(OMPArrayShapingExpr *E) {
19112     Expr *Base = E->getBase();
19113 
19114     // Record the component - we don't have any declaration associated.
19115     Components.emplace_back(E, nullptr, IsNonContiguous);
19116 
19117     return Visit(Base->IgnoreParenImpCasts());
19118   }
19119 
19120   bool VisitUnaryOperator(UnaryOperator *UO) {
19121     if (SemaRef.getLangOpts().OpenMP < 50 || !UO->isLValue() ||
19122         UO->getOpcode() != UO_Deref) {
19123       emitErrorMsg();
19124       return false;
19125     }
19126     if (!RelevantExpr) {
19127       // Record the component if haven't found base decl.
19128       Components.emplace_back(UO, nullptr, /*IsNonContiguous=*/false);
19129     }
19130     return RelevantExpr || Visit(UO->getSubExpr()->IgnoreParenImpCasts());
19131   }
19132   bool VisitBinaryOperator(BinaryOperator *BO) {
19133     if (SemaRef.getLangOpts().OpenMP < 50 || !BO->getType()->isPointerType()) {
19134       emitErrorMsg();
19135       return false;
19136     }
19137 
19138     // Pointer arithmetic is the only thing we expect to happen here so after we
19139     // make sure the binary operator is a pointer type, the we only thing need
19140     // to to is to visit the subtree that has the same type as root (so that we
19141     // know the other subtree is just an offset)
19142     Expr *LE = BO->getLHS()->IgnoreParenImpCasts();
19143     Expr *RE = BO->getRHS()->IgnoreParenImpCasts();
19144     Components.emplace_back(BO, nullptr, false);
19145     assert((LE->getType().getTypePtr() == BO->getType().getTypePtr() ||
19146             RE->getType().getTypePtr() == BO->getType().getTypePtr()) &&
19147            "Either LHS or RHS have base decl inside");
19148     if (BO->getType().getTypePtr() == LE->getType().getTypePtr())
19149       return RelevantExpr || Visit(LE);
19150     return RelevantExpr || Visit(RE);
19151   }
19152   bool VisitCXXThisExpr(CXXThisExpr *CTE) {
19153     assert(!RelevantExpr && "RelevantExpr is expected to be nullptr");
19154     RelevantExpr = CTE;
19155     Components.emplace_back(CTE, nullptr, IsNonContiguous);
19156     return true;
19157   }
19158   bool VisitCXXOperatorCallExpr(CXXOperatorCallExpr *COCE) {
19159     assert(!RelevantExpr && "RelevantExpr is expected to be nullptr");
19160     Components.emplace_back(COCE, nullptr, IsNonContiguous);
19161     return true;
19162   }
19163   bool VisitOpaqueValueExpr(OpaqueValueExpr *E) {
19164     Expr *Source = E->getSourceExpr();
19165     if (!Source) {
19166       emitErrorMsg();
19167       return false;
19168     }
19169     return Visit(Source);
19170   }
19171   bool VisitStmt(Stmt *) {
19172     emitErrorMsg();
19173     return false;
19174   }
19175   const Expr *getFoundBase() const { return RelevantExpr; }
19176   explicit MapBaseChecker(
19177       Sema &SemaRef, OpenMPClauseKind CKind, OpenMPDirectiveKind DKind,
19178       OMPClauseMappableExprCommon::MappableExprComponentList &Components,
19179       bool NoDiagnose, SourceLocation &ELoc, SourceRange &ERange)
19180       : SemaRef(SemaRef), CKind(CKind), DKind(DKind), Components(Components),
19181         NoDiagnose(NoDiagnose), ELoc(ELoc), ERange(ERange) {}
19182 };
19183 } // namespace
19184 
19185 /// Return the expression of the base of the mappable expression or null if it
19186 /// cannot be determined and do all the necessary checks to see if the
19187 /// expression is valid as a standalone mappable expression. In the process,
19188 /// record all the components of the expression.
19189 static const Expr *checkMapClauseExpressionBase(
19190     Sema &SemaRef, Expr *E,
19191     OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
19192     OpenMPClauseKind CKind, OpenMPDirectiveKind DKind, bool NoDiagnose) {
19193   SourceLocation ELoc = E->getExprLoc();
19194   SourceRange ERange = E->getSourceRange();
19195   MapBaseChecker Checker(SemaRef, CKind, DKind, CurComponents, NoDiagnose, ELoc,
19196                          ERange);
19197   if (Checker.Visit(E->IgnoreParens())) {
19198     // Check if the highest dimension array section has length specified
19199     if (SemaRef.getLangOpts().OpenMP >= 50 && !CurComponents.empty() &&
19200         (CKind == OMPC_to || CKind == OMPC_from)) {
19201       auto CI = CurComponents.rbegin();
19202       auto CE = CurComponents.rend();
19203       for (; CI != CE; ++CI) {
19204         const auto *OASE =
19205             dyn_cast<OMPArraySectionExpr>(CI->getAssociatedExpression());
19206         if (!OASE)
19207           continue;
19208         if (OASE && OASE->getLength())
19209           break;
19210         SemaRef.Diag(ELoc, diag::err_array_section_does_not_specify_length)
19211             << ERange;
19212       }
19213     }
19214     return Checker.getFoundBase();
19215   }
19216   return nullptr;
19217 }
19218 
19219 // Return true if expression E associated with value VD has conflicts with other
19220 // map information.
19221 static bool checkMapConflicts(
19222     Sema &SemaRef, DSAStackTy *DSAS, const ValueDecl *VD, const Expr *E,
19223     bool CurrentRegionOnly,
19224     OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
19225     OpenMPClauseKind CKind) {
19226   assert(VD && E);
19227   SourceLocation ELoc = E->getExprLoc();
19228   SourceRange ERange = E->getSourceRange();
19229 
19230   // In order to easily check the conflicts we need to match each component of
19231   // the expression under test with the components of the expressions that are
19232   // already in the stack.
19233 
19234   assert(!CurComponents.empty() && "Map clause expression with no components!");
19235   assert(CurComponents.back().getAssociatedDeclaration() == VD &&
19236          "Map clause expression with unexpected base!");
19237 
19238   // Variables to help detecting enclosing problems in data environment nests.
19239   bool IsEnclosedByDataEnvironmentExpr = false;
19240   const Expr *EnclosingExpr = nullptr;
19241 
19242   bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
19243       VD, CurrentRegionOnly,
19244       [&IsEnclosedByDataEnvironmentExpr, &SemaRef, VD, CurrentRegionOnly, ELoc,
19245        ERange, CKind, &EnclosingExpr,
19246        CurComponents](OMPClauseMappableExprCommon::MappableExprComponentListRef
19247                           StackComponents,
19248                       OpenMPClauseKind Kind) {
19249         if (CKind == Kind && SemaRef.LangOpts.OpenMP >= 50)
19250           return false;
19251         assert(!StackComponents.empty() &&
19252                "Map clause expression with no components!");
19253         assert(StackComponents.back().getAssociatedDeclaration() == VD &&
19254                "Map clause expression with unexpected base!");
19255         (void)VD;
19256 
19257         // The whole expression in the stack.
19258         const Expr *RE = StackComponents.front().getAssociatedExpression();
19259 
19260         // Expressions must start from the same base. Here we detect at which
19261         // point both expressions diverge from each other and see if we can
19262         // detect if the memory referred to both expressions is contiguous and
19263         // do not overlap.
19264         auto CI = CurComponents.rbegin();
19265         auto CE = CurComponents.rend();
19266         auto SI = StackComponents.rbegin();
19267         auto SE = StackComponents.rend();
19268         for (; CI != CE && SI != SE; ++CI, ++SI) {
19269 
19270           // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
19271           //  At most one list item can be an array item derived from a given
19272           //  variable in map clauses of the same construct.
19273           if (CurrentRegionOnly &&
19274               (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
19275                isa<OMPArraySectionExpr>(CI->getAssociatedExpression()) ||
19276                isa<OMPArrayShapingExpr>(CI->getAssociatedExpression())) &&
19277               (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
19278                isa<OMPArraySectionExpr>(SI->getAssociatedExpression()) ||
19279                isa<OMPArrayShapingExpr>(SI->getAssociatedExpression()))) {
19280             SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
19281                          diag::err_omp_multiple_array_items_in_map_clause)
19282                 << CI->getAssociatedExpression()->getSourceRange();
19283             SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
19284                          diag::note_used_here)
19285                 << SI->getAssociatedExpression()->getSourceRange();
19286             return true;
19287           }
19288 
19289           // Do both expressions have the same kind?
19290           if (CI->getAssociatedExpression()->getStmtClass() !=
19291               SI->getAssociatedExpression()->getStmtClass())
19292             break;
19293 
19294           // Are we dealing with different variables/fields?
19295           if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
19296             break;
19297         }
19298         // Check if the extra components of the expressions in the enclosing
19299         // data environment are redundant for the current base declaration.
19300         // If they are, the maps completely overlap, which is legal.
19301         for (; SI != SE; ++SI) {
19302           QualType Type;
19303           if (const auto *ASE =
19304                   dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
19305             Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
19306           } else if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(
19307                          SI->getAssociatedExpression())) {
19308             const Expr *E = OASE->getBase()->IgnoreParenImpCasts();
19309             Type =
19310                 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
19311           } else if (const auto *OASE = dyn_cast<OMPArrayShapingExpr>(
19312                          SI->getAssociatedExpression())) {
19313             Type = OASE->getBase()->getType()->getPointeeType();
19314           }
19315           if (Type.isNull() || Type->isAnyPointerType() ||
19316               checkArrayExpressionDoesNotReferToWholeSize(
19317                   SemaRef, SI->getAssociatedExpression(), Type))
19318             break;
19319         }
19320 
19321         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
19322         //  List items of map clauses in the same construct must not share
19323         //  original storage.
19324         //
19325         // If the expressions are exactly the same or one is a subset of the
19326         // other, it means they are sharing storage.
19327         if (CI == CE && SI == SE) {
19328           if (CurrentRegionOnly) {
19329             if (CKind == OMPC_map) {
19330               SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
19331             } else {
19332               assert(CKind == OMPC_to || CKind == OMPC_from);
19333               SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
19334                   << ERange;
19335             }
19336             SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
19337                 << RE->getSourceRange();
19338             return true;
19339           }
19340           // If we find the same expression in the enclosing data environment,
19341           // that is legal.
19342           IsEnclosedByDataEnvironmentExpr = true;
19343           return false;
19344         }
19345 
19346         QualType DerivedType =
19347             std::prev(CI)->getAssociatedDeclaration()->getType();
19348         SourceLocation DerivedLoc =
19349             std::prev(CI)->getAssociatedExpression()->getExprLoc();
19350 
19351         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
19352         //  If the type of a list item is a reference to a type T then the type
19353         //  will be considered to be T for all purposes of this clause.
19354         DerivedType = DerivedType.getNonReferenceType();
19355 
19356         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
19357         //  A variable for which the type is pointer and an array section
19358         //  derived from that variable must not appear as list items of map
19359         //  clauses of the same construct.
19360         //
19361         // Also, cover one of the cases in:
19362         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
19363         //  If any part of the original storage of a list item has corresponding
19364         //  storage in the device data environment, all of the original storage
19365         //  must have corresponding storage in the device data environment.
19366         //
19367         if (DerivedType->isAnyPointerType()) {
19368           if (CI == CE || SI == SE) {
19369             SemaRef.Diag(
19370                 DerivedLoc,
19371                 diag::err_omp_pointer_mapped_along_with_derived_section)
19372                 << DerivedLoc;
19373             SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
19374                 << RE->getSourceRange();
19375             return true;
19376           }
19377           if (CI->getAssociatedExpression()->getStmtClass() !=
19378                   SI->getAssociatedExpression()->getStmtClass() ||
19379               CI->getAssociatedDeclaration()->getCanonicalDecl() ==
19380                   SI->getAssociatedDeclaration()->getCanonicalDecl()) {
19381             assert(CI != CE && SI != SE);
19382             SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_dereferenced)
19383                 << DerivedLoc;
19384             SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
19385                 << RE->getSourceRange();
19386             return true;
19387           }
19388         }
19389 
19390         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
19391         //  List items of map clauses in the same construct must not share
19392         //  original storage.
19393         //
19394         // An expression is a subset of the other.
19395         if (CurrentRegionOnly && (CI == CE || SI == SE)) {
19396           if (CKind == OMPC_map) {
19397             if (CI != CE || SI != SE) {
19398               // Allow constructs like this: map(s, s.ptr[0:1]), where s.ptr is
19399               // a pointer.
19400               auto Begin =
19401                   CI != CE ? CurComponents.begin() : StackComponents.begin();
19402               auto End = CI != CE ? CurComponents.end() : StackComponents.end();
19403               auto It = Begin;
19404               while (It != End && !It->getAssociatedDeclaration())
19405                 std::advance(It, 1);
19406               assert(It != End &&
19407                      "Expected at least one component with the declaration.");
19408               if (It != Begin && It->getAssociatedDeclaration()
19409                                      ->getType()
19410                                      .getCanonicalType()
19411                                      ->isAnyPointerType()) {
19412                 IsEnclosedByDataEnvironmentExpr = false;
19413                 EnclosingExpr = nullptr;
19414                 return false;
19415               }
19416             }
19417             SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
19418           } else {
19419             assert(CKind == OMPC_to || CKind == OMPC_from);
19420             SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
19421                 << ERange;
19422           }
19423           SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
19424               << RE->getSourceRange();
19425           return true;
19426         }
19427 
19428         // The current expression uses the same base as other expression in the
19429         // data environment but does not contain it completely.
19430         if (!CurrentRegionOnly && SI != SE)
19431           EnclosingExpr = RE;
19432 
19433         // The current expression is a subset of the expression in the data
19434         // environment.
19435         IsEnclosedByDataEnvironmentExpr |=
19436             (!CurrentRegionOnly && CI != CE && SI == SE);
19437 
19438         return false;
19439       });
19440 
19441   if (CurrentRegionOnly)
19442     return FoundError;
19443 
19444   // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
19445   //  If any part of the original storage of a list item has corresponding
19446   //  storage in the device data environment, all of the original storage must
19447   //  have corresponding storage in the device data environment.
19448   // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
19449   //  If a list item is an element of a structure, and a different element of
19450   //  the structure has a corresponding list item in the device data environment
19451   //  prior to a task encountering the construct associated with the map clause,
19452   //  then the list item must also have a corresponding list item in the device
19453   //  data environment prior to the task encountering the construct.
19454   //
19455   if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
19456     SemaRef.Diag(ELoc,
19457                  diag::err_omp_original_storage_is_shared_and_does_not_contain)
19458         << ERange;
19459     SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
19460         << EnclosingExpr->getSourceRange();
19461     return true;
19462   }
19463 
19464   return FoundError;
19465 }
19466 
19467 // Look up the user-defined mapper given the mapper name and mapped type, and
19468 // build a reference to it.
19469 static ExprResult buildUserDefinedMapperRef(Sema &SemaRef, Scope *S,
19470                                             CXXScopeSpec &MapperIdScopeSpec,
19471                                             const DeclarationNameInfo &MapperId,
19472                                             QualType Type,
19473                                             Expr *UnresolvedMapper) {
19474   if (MapperIdScopeSpec.isInvalid())
19475     return ExprError();
19476   // Get the actual type for the array type.
19477   if (Type->isArrayType()) {
19478     assert(Type->getAsArrayTypeUnsafe() && "Expect to get a valid array type");
19479     Type = Type->getAsArrayTypeUnsafe()->getElementType().getCanonicalType();
19480   }
19481   // Find all user-defined mappers with the given MapperId.
19482   SmallVector<UnresolvedSet<8>, 4> Lookups;
19483   LookupResult Lookup(SemaRef, MapperId, Sema::LookupOMPMapperName);
19484   Lookup.suppressDiagnostics();
19485   if (S) {
19486     while (S && SemaRef.LookupParsedName(Lookup, S, &MapperIdScopeSpec)) {
19487       NamedDecl *D = Lookup.getRepresentativeDecl();
19488       while (S && !S->isDeclScope(D))
19489         S = S->getParent();
19490       if (S)
19491         S = S->getParent();
19492       Lookups.emplace_back();
19493       Lookups.back().append(Lookup.begin(), Lookup.end());
19494       Lookup.clear();
19495     }
19496   } else if (auto *ULE = cast_or_null<UnresolvedLookupExpr>(UnresolvedMapper)) {
19497     // Extract the user-defined mappers with the given MapperId.
19498     Lookups.push_back(UnresolvedSet<8>());
19499     for (NamedDecl *D : ULE->decls()) {
19500       auto *DMD = cast<OMPDeclareMapperDecl>(D);
19501       assert(DMD && "Expect valid OMPDeclareMapperDecl during instantiation.");
19502       Lookups.back().addDecl(DMD);
19503     }
19504   }
19505   // Defer the lookup for dependent types. The results will be passed through
19506   // UnresolvedMapper on instantiation.
19507   if (SemaRef.CurContext->isDependentContext() || Type->isDependentType() ||
19508       Type->isInstantiationDependentType() ||
19509       Type->containsUnexpandedParameterPack() ||
19510       filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
19511         return !D->isInvalidDecl() &&
19512                (D->getType()->isDependentType() ||
19513                 D->getType()->isInstantiationDependentType() ||
19514                 D->getType()->containsUnexpandedParameterPack());
19515       })) {
19516     UnresolvedSet<8> URS;
19517     for (const UnresolvedSet<8> &Set : Lookups) {
19518       if (Set.empty())
19519         continue;
19520       URS.append(Set.begin(), Set.end());
19521     }
19522     return UnresolvedLookupExpr::Create(
19523         SemaRef.Context, /*NamingClass=*/nullptr,
19524         MapperIdScopeSpec.getWithLocInContext(SemaRef.Context), MapperId,
19525         /*ADL=*/false, /*Overloaded=*/true, URS.begin(), URS.end());
19526   }
19527   SourceLocation Loc = MapperId.getLoc();
19528   // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
19529   //  The type must be of struct, union or class type in C and C++
19530   if (!Type->isStructureOrClassType() && !Type->isUnionType() &&
19531       (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default")) {
19532     SemaRef.Diag(Loc, diag::err_omp_mapper_wrong_type);
19533     return ExprError();
19534   }
19535   // Perform argument dependent lookup.
19536   if (SemaRef.getLangOpts().CPlusPlus && !MapperIdScopeSpec.isSet())
19537     argumentDependentLookup(SemaRef, MapperId, Loc, Type, Lookups);
19538   // Return the first user-defined mapper with the desired type.
19539   if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
19540           Lookups, [&SemaRef, Type](ValueDecl *D) -> ValueDecl * {
19541             if (!D->isInvalidDecl() &&
19542                 SemaRef.Context.hasSameType(D->getType(), Type))
19543               return D;
19544             return nullptr;
19545           }))
19546     return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
19547   // Find the first user-defined mapper with a type derived from the desired
19548   // type.
19549   if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
19550           Lookups, [&SemaRef, Type, Loc](ValueDecl *D) -> ValueDecl * {
19551             if (!D->isInvalidDecl() &&
19552                 SemaRef.IsDerivedFrom(Loc, Type, D->getType()) &&
19553                 !Type.isMoreQualifiedThan(D->getType()))
19554               return D;
19555             return nullptr;
19556           })) {
19557     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
19558                        /*DetectVirtual=*/false);
19559     if (SemaRef.IsDerivedFrom(Loc, Type, VD->getType(), Paths)) {
19560       if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
19561               VD->getType().getUnqualifiedType()))) {
19562         if (SemaRef.CheckBaseClassAccess(
19563                 Loc, VD->getType(), Type, Paths.front(),
19564                 /*DiagID=*/0) != Sema::AR_inaccessible) {
19565           return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
19566         }
19567       }
19568     }
19569   }
19570   // Report error if a mapper is specified, but cannot be found.
19571   if (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default") {
19572     SemaRef.Diag(Loc, diag::err_omp_invalid_mapper)
19573         << Type << MapperId.getName();
19574     return ExprError();
19575   }
19576   return ExprEmpty();
19577 }
19578 
19579 namespace {
19580 // Utility struct that gathers all the related lists associated with a mappable
19581 // expression.
19582 struct MappableVarListInfo {
19583   // The list of expressions.
19584   ArrayRef<Expr *> VarList;
19585   // The list of processed expressions.
19586   SmallVector<Expr *, 16> ProcessedVarList;
19587   // The mappble components for each expression.
19588   OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
19589   // The base declaration of the variable.
19590   SmallVector<ValueDecl *, 16> VarBaseDeclarations;
19591   // The reference to the user-defined mapper associated with every expression.
19592   SmallVector<Expr *, 16> UDMapperList;
19593 
19594   MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
19595     // We have a list of components and base declarations for each entry in the
19596     // variable list.
19597     VarComponents.reserve(VarList.size());
19598     VarBaseDeclarations.reserve(VarList.size());
19599   }
19600 };
19601 } // namespace
19602 
19603 // Check the validity of the provided variable list for the provided clause kind
19604 // \a CKind. In the check process the valid expressions, mappable expression
19605 // components, variables, and user-defined mappers are extracted and used to
19606 // fill \a ProcessedVarList, \a VarComponents, \a VarBaseDeclarations, and \a
19607 // UDMapperList in MVLI. \a MapType, \a IsMapTypeImplicit, \a MapperIdScopeSpec,
19608 // and \a MapperId are expected to be valid if the clause kind is 'map'.
19609 static void checkMappableExpressionList(
19610     Sema &SemaRef, DSAStackTy *DSAS, OpenMPClauseKind CKind,
19611     MappableVarListInfo &MVLI, SourceLocation StartLoc,
19612     CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo MapperId,
19613     ArrayRef<Expr *> UnresolvedMappers,
19614     OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
19615     ArrayRef<OpenMPMapModifierKind> Modifiers = None,
19616     bool IsMapTypeImplicit = false, bool NoDiagnose = false) {
19617   // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
19618   assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
19619          "Unexpected clause kind with mappable expressions!");
19620 
19621   // If the identifier of user-defined mapper is not specified, it is "default".
19622   // We do not change the actual name in this clause to distinguish whether a
19623   // mapper is specified explicitly, i.e., it is not explicitly specified when
19624   // MapperId.getName() is empty.
19625   if (!MapperId.getName() || MapperId.getName().isEmpty()) {
19626     auto &DeclNames = SemaRef.getASTContext().DeclarationNames;
19627     MapperId.setName(DeclNames.getIdentifier(
19628         &SemaRef.getASTContext().Idents.get("default")));
19629     MapperId.setLoc(StartLoc);
19630   }
19631 
19632   // Iterators to find the current unresolved mapper expression.
19633   auto UMIt = UnresolvedMappers.begin(), UMEnd = UnresolvedMappers.end();
19634   bool UpdateUMIt = false;
19635   Expr *UnresolvedMapper = nullptr;
19636 
19637   bool HasHoldModifier =
19638       llvm::is_contained(Modifiers, OMPC_MAP_MODIFIER_ompx_hold);
19639 
19640   // Keep track of the mappable components and base declarations in this clause.
19641   // Each entry in the list is going to have a list of components associated. We
19642   // record each set of the components so that we can build the clause later on.
19643   // In the end we should have the same amount of declarations and component
19644   // lists.
19645 
19646   for (Expr *RE : MVLI.VarList) {
19647     assert(RE && "Null expr in omp to/from/map clause");
19648     SourceLocation ELoc = RE->getExprLoc();
19649 
19650     // Find the current unresolved mapper expression.
19651     if (UpdateUMIt && UMIt != UMEnd) {
19652       UMIt++;
19653       assert(
19654           UMIt != UMEnd &&
19655           "Expect the size of UnresolvedMappers to match with that of VarList");
19656     }
19657     UpdateUMIt = true;
19658     if (UMIt != UMEnd)
19659       UnresolvedMapper = *UMIt;
19660 
19661     const Expr *VE = RE->IgnoreParenLValueCasts();
19662 
19663     if (VE->isValueDependent() || VE->isTypeDependent() ||
19664         VE->isInstantiationDependent() ||
19665         VE->containsUnexpandedParameterPack()) {
19666       // Try to find the associated user-defined mapper.
19667       ExprResult ER = buildUserDefinedMapperRef(
19668           SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
19669           VE->getType().getCanonicalType(), UnresolvedMapper);
19670       if (ER.isInvalid())
19671         continue;
19672       MVLI.UDMapperList.push_back(ER.get());
19673       // We can only analyze this information once the missing information is
19674       // resolved.
19675       MVLI.ProcessedVarList.push_back(RE);
19676       continue;
19677     }
19678 
19679     Expr *SimpleExpr = RE->IgnoreParenCasts();
19680 
19681     if (!RE->isLValue()) {
19682       if (SemaRef.getLangOpts().OpenMP < 50) {
19683         SemaRef.Diag(
19684             ELoc, diag::err_omp_expected_named_var_member_or_array_expression)
19685             << RE->getSourceRange();
19686       } else {
19687         SemaRef.Diag(ELoc, diag::err_omp_non_lvalue_in_map_or_motion_clauses)
19688             << getOpenMPClauseName(CKind) << RE->getSourceRange();
19689       }
19690       continue;
19691     }
19692 
19693     OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
19694     ValueDecl *CurDeclaration = nullptr;
19695 
19696     // Obtain the array or member expression bases if required. Also, fill the
19697     // components array with all the components identified in the process.
19698     const Expr *BE =
19699         checkMapClauseExpressionBase(SemaRef, SimpleExpr, CurComponents, CKind,
19700                                      DSAS->getCurrentDirective(), NoDiagnose);
19701     if (!BE)
19702       continue;
19703 
19704     assert(!CurComponents.empty() &&
19705            "Invalid mappable expression information.");
19706 
19707     if (const auto *TE = dyn_cast<CXXThisExpr>(BE)) {
19708       // Add store "this" pointer to class in DSAStackTy for future checking
19709       DSAS->addMappedClassesQualTypes(TE->getType());
19710       // Try to find the associated user-defined mapper.
19711       ExprResult ER = buildUserDefinedMapperRef(
19712           SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
19713           VE->getType().getCanonicalType(), UnresolvedMapper);
19714       if (ER.isInvalid())
19715         continue;
19716       MVLI.UDMapperList.push_back(ER.get());
19717       // Skip restriction checking for variable or field declarations
19718       MVLI.ProcessedVarList.push_back(RE);
19719       MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
19720       MVLI.VarComponents.back().append(CurComponents.begin(),
19721                                        CurComponents.end());
19722       MVLI.VarBaseDeclarations.push_back(nullptr);
19723       continue;
19724     }
19725 
19726     // For the following checks, we rely on the base declaration which is
19727     // expected to be associated with the last component. The declaration is
19728     // expected to be a variable or a field (if 'this' is being mapped).
19729     CurDeclaration = CurComponents.back().getAssociatedDeclaration();
19730     assert(CurDeclaration && "Null decl on map clause.");
19731     assert(
19732         CurDeclaration->isCanonicalDecl() &&
19733         "Expecting components to have associated only canonical declarations.");
19734 
19735     auto *VD = dyn_cast<VarDecl>(CurDeclaration);
19736     const auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
19737 
19738     assert((VD || FD) && "Only variables or fields are expected here!");
19739     (void)FD;
19740 
19741     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
19742     // threadprivate variables cannot appear in a map clause.
19743     // OpenMP 4.5 [2.10.5, target update Construct]
19744     // threadprivate variables cannot appear in a from clause.
19745     if (VD && DSAS->isThreadPrivate(VD)) {
19746       if (NoDiagnose)
19747         continue;
19748       DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
19749       SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
19750           << getOpenMPClauseName(CKind);
19751       reportOriginalDsa(SemaRef, DSAS, VD, DVar);
19752       continue;
19753     }
19754 
19755     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
19756     //  A list item cannot appear in both a map clause and a data-sharing
19757     //  attribute clause on the same construct.
19758 
19759     // Check conflicts with other map clause expressions. We check the conflicts
19760     // with the current construct separately from the enclosing data
19761     // environment, because the restrictions are different. We only have to
19762     // check conflicts across regions for the map clauses.
19763     if (checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
19764                           /*CurrentRegionOnly=*/true, CurComponents, CKind))
19765       break;
19766     if (CKind == OMPC_map &&
19767         (SemaRef.getLangOpts().OpenMP <= 45 || StartLoc.isValid()) &&
19768         checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
19769                           /*CurrentRegionOnly=*/false, CurComponents, CKind))
19770       break;
19771 
19772     // OpenMP 4.5 [2.10.5, target update Construct]
19773     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
19774     //  If the type of a list item is a reference to a type T then the type will
19775     //  be considered to be T for all purposes of this clause.
19776     auto I = llvm::find_if(
19777         CurComponents,
19778         [](const OMPClauseMappableExprCommon::MappableComponent &MC) {
19779           return MC.getAssociatedDeclaration();
19780         });
19781     assert(I != CurComponents.end() && "Null decl on map clause.");
19782     (void)I;
19783     QualType Type;
19784     auto *ASE = dyn_cast<ArraySubscriptExpr>(VE->IgnoreParens());
19785     auto *OASE = dyn_cast<OMPArraySectionExpr>(VE->IgnoreParens());
19786     auto *OAShE = dyn_cast<OMPArrayShapingExpr>(VE->IgnoreParens());
19787     if (ASE) {
19788       Type = ASE->getType().getNonReferenceType();
19789     } else if (OASE) {
19790       QualType BaseType =
19791           OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
19792       if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
19793         Type = ATy->getElementType();
19794       else
19795         Type = BaseType->getPointeeType();
19796       Type = Type.getNonReferenceType();
19797     } else if (OAShE) {
19798       Type = OAShE->getBase()->getType()->getPointeeType();
19799     } else {
19800       Type = VE->getType();
19801     }
19802 
19803     // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
19804     // A list item in a to or from clause must have a mappable type.
19805     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
19806     //  A list item must have a mappable type.
19807     if (!checkTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
19808                            DSAS, Type, /*FullCheck=*/true))
19809       continue;
19810 
19811     if (CKind == OMPC_map) {
19812       // target enter data
19813       // OpenMP [2.10.2, Restrictions, p. 99]
19814       // A map-type must be specified in all map clauses and must be either
19815       // to or alloc.
19816       OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
19817       if (DKind == OMPD_target_enter_data &&
19818           !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
19819         SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
19820             << (IsMapTypeImplicit ? 1 : 0)
19821             << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
19822             << getOpenMPDirectiveName(DKind);
19823         continue;
19824       }
19825 
19826       // target exit_data
19827       // OpenMP [2.10.3, Restrictions, p. 102]
19828       // A map-type must be specified in all map clauses and must be either
19829       // from, release, or delete.
19830       if (DKind == OMPD_target_exit_data &&
19831           !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
19832             MapType == OMPC_MAP_delete)) {
19833         SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
19834             << (IsMapTypeImplicit ? 1 : 0)
19835             << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
19836             << getOpenMPDirectiveName(DKind);
19837         continue;
19838       }
19839 
19840       // The 'ompx_hold' modifier is specifically intended to be used on a
19841       // 'target' or 'target data' directive to prevent data from being unmapped
19842       // during the associated statement.  It is not permitted on a 'target
19843       // enter data' or 'target exit data' directive, which have no associated
19844       // statement.
19845       if ((DKind == OMPD_target_enter_data || DKind == OMPD_target_exit_data) &&
19846           HasHoldModifier) {
19847         SemaRef.Diag(StartLoc,
19848                      diag::err_omp_invalid_map_type_modifier_for_directive)
19849             << getOpenMPSimpleClauseTypeName(OMPC_map,
19850                                              OMPC_MAP_MODIFIER_ompx_hold)
19851             << getOpenMPDirectiveName(DKind);
19852         continue;
19853       }
19854 
19855       // target, target data
19856       // OpenMP 5.0 [2.12.2, Restrictions, p. 163]
19857       // OpenMP 5.0 [2.12.5, Restrictions, p. 174]
19858       // A map-type in a map clause must be to, from, tofrom or alloc
19859       if ((DKind == OMPD_target_data ||
19860            isOpenMPTargetExecutionDirective(DKind)) &&
19861           !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_from ||
19862             MapType == OMPC_MAP_tofrom || MapType == OMPC_MAP_alloc)) {
19863         SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
19864             << (IsMapTypeImplicit ? 1 : 0)
19865             << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
19866             << getOpenMPDirectiveName(DKind);
19867         continue;
19868       }
19869 
19870       // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
19871       // A list item cannot appear in both a map clause and a data-sharing
19872       // attribute clause on the same construct
19873       //
19874       // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
19875       // A list item cannot appear in both a map clause and a data-sharing
19876       // attribute clause on the same construct unless the construct is a
19877       // combined construct.
19878       if (VD && ((SemaRef.LangOpts.OpenMP <= 45 &&
19879                   isOpenMPTargetExecutionDirective(DKind)) ||
19880                  DKind == OMPD_target)) {
19881         DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
19882         if (isOpenMPPrivate(DVar.CKind)) {
19883           SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
19884               << getOpenMPClauseName(DVar.CKind)
19885               << getOpenMPClauseName(OMPC_map)
19886               << getOpenMPDirectiveName(DSAS->getCurrentDirective());
19887           reportOriginalDsa(SemaRef, DSAS, CurDeclaration, DVar);
19888           continue;
19889         }
19890       }
19891     }
19892 
19893     // Try to find the associated user-defined mapper.
19894     ExprResult ER = buildUserDefinedMapperRef(
19895         SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
19896         Type.getCanonicalType(), UnresolvedMapper);
19897     if (ER.isInvalid())
19898       continue;
19899     MVLI.UDMapperList.push_back(ER.get());
19900 
19901     // Save the current expression.
19902     MVLI.ProcessedVarList.push_back(RE);
19903 
19904     // Store the components in the stack so that they can be used to check
19905     // against other clauses later on.
19906     DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
19907                                           /*WhereFoundClauseKind=*/OMPC_map);
19908 
19909     // Save the components and declaration to create the clause. For purposes of
19910     // the clause creation, any component list that has has base 'this' uses
19911     // null as base declaration.
19912     MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
19913     MVLI.VarComponents.back().append(CurComponents.begin(),
19914                                      CurComponents.end());
19915     MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
19916                                                            : CurDeclaration);
19917   }
19918 }
19919 
19920 OMPClause *Sema::ActOnOpenMPMapClause(
19921     ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
19922     ArrayRef<SourceLocation> MapTypeModifiersLoc,
19923     CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId,
19924     OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, SourceLocation MapLoc,
19925     SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
19926     const OMPVarListLocTy &Locs, bool NoDiagnose,
19927     ArrayRef<Expr *> UnresolvedMappers) {
19928   OpenMPMapModifierKind Modifiers[] = {
19929       OMPC_MAP_MODIFIER_unknown, OMPC_MAP_MODIFIER_unknown,
19930       OMPC_MAP_MODIFIER_unknown, OMPC_MAP_MODIFIER_unknown,
19931       OMPC_MAP_MODIFIER_unknown};
19932   SourceLocation ModifiersLoc[NumberOfOMPMapClauseModifiers];
19933 
19934   // Process map-type-modifiers, flag errors for duplicate modifiers.
19935   unsigned Count = 0;
19936   for (unsigned I = 0, E = MapTypeModifiers.size(); I < E; ++I) {
19937     if (MapTypeModifiers[I] != OMPC_MAP_MODIFIER_unknown &&
19938         llvm::is_contained(Modifiers, MapTypeModifiers[I])) {
19939       Diag(MapTypeModifiersLoc[I], diag::err_omp_duplicate_map_type_modifier);
19940       continue;
19941     }
19942     assert(Count < NumberOfOMPMapClauseModifiers &&
19943            "Modifiers exceed the allowed number of map type modifiers");
19944     Modifiers[Count] = MapTypeModifiers[I];
19945     ModifiersLoc[Count] = MapTypeModifiersLoc[I];
19946     ++Count;
19947   }
19948 
19949   MappableVarListInfo MVLI(VarList);
19950   checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, Locs.StartLoc,
19951                               MapperIdScopeSpec, MapperId, UnresolvedMappers,
19952                               MapType, Modifiers, IsMapTypeImplicit,
19953                               NoDiagnose);
19954 
19955   // We need to produce a map clause even if we don't have variables so that
19956   // other diagnostics related with non-existing map clauses are accurate.
19957   return OMPMapClause::Create(Context, Locs, MVLI.ProcessedVarList,
19958                               MVLI.VarBaseDeclarations, MVLI.VarComponents,
19959                               MVLI.UDMapperList, Modifiers, ModifiersLoc,
19960                               MapperIdScopeSpec.getWithLocInContext(Context),
19961                               MapperId, MapType, IsMapTypeImplicit, MapLoc);
19962 }
19963 
19964 QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
19965                                                TypeResult ParsedType) {
19966   assert(ParsedType.isUsable());
19967 
19968   QualType ReductionType = GetTypeFromParser(ParsedType.get());
19969   if (ReductionType.isNull())
19970     return QualType();
19971 
19972   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
19973   // A type name in a declare reduction directive cannot be a function type, an
19974   // array type, a reference type, or a type qualified with const, volatile or
19975   // restrict.
19976   if (ReductionType.hasQualifiers()) {
19977     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
19978     return QualType();
19979   }
19980 
19981   if (ReductionType->isFunctionType()) {
19982     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
19983     return QualType();
19984   }
19985   if (ReductionType->isReferenceType()) {
19986     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
19987     return QualType();
19988   }
19989   if (ReductionType->isArrayType()) {
19990     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
19991     return QualType();
19992   }
19993   return ReductionType;
19994 }
19995 
19996 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
19997     Scope *S, DeclContext *DC, DeclarationName Name,
19998     ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
19999     AccessSpecifier AS, Decl *PrevDeclInScope) {
20000   SmallVector<Decl *, 8> Decls;
20001   Decls.reserve(ReductionTypes.size());
20002 
20003   LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
20004                       forRedeclarationInCurContext());
20005   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
20006   // A reduction-identifier may not be re-declared in the current scope for the
20007   // same type or for a type that is compatible according to the base language
20008   // rules.
20009   llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
20010   OMPDeclareReductionDecl *PrevDRD = nullptr;
20011   bool InCompoundScope = true;
20012   if (S != nullptr) {
20013     // Find previous declaration with the same name not referenced in other
20014     // declarations.
20015     FunctionScopeInfo *ParentFn = getEnclosingFunction();
20016     InCompoundScope =
20017         (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
20018     LookupName(Lookup, S);
20019     FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
20020                          /*AllowInlineNamespace=*/false);
20021     llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
20022     LookupResult::Filter Filter = Lookup.makeFilter();
20023     while (Filter.hasNext()) {
20024       auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
20025       if (InCompoundScope) {
20026         auto I = UsedAsPrevious.find(PrevDecl);
20027         if (I == UsedAsPrevious.end())
20028           UsedAsPrevious[PrevDecl] = false;
20029         if (OMPDeclareReductionDecl *D = PrevDecl->getPrevDeclInScope())
20030           UsedAsPrevious[D] = true;
20031       }
20032       PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
20033           PrevDecl->getLocation();
20034     }
20035     Filter.done();
20036     if (InCompoundScope) {
20037       for (const auto &PrevData : UsedAsPrevious) {
20038         if (!PrevData.second) {
20039           PrevDRD = PrevData.first;
20040           break;
20041         }
20042       }
20043     }
20044   } else if (PrevDeclInScope != nullptr) {
20045     auto *PrevDRDInScope = PrevDRD =
20046         cast<OMPDeclareReductionDecl>(PrevDeclInScope);
20047     do {
20048       PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
20049           PrevDRDInScope->getLocation();
20050       PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
20051     } while (PrevDRDInScope != nullptr);
20052   }
20053   for (const auto &TyData : ReductionTypes) {
20054     const auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
20055     bool Invalid = false;
20056     if (I != PreviousRedeclTypes.end()) {
20057       Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
20058           << TyData.first;
20059       Diag(I->second, diag::note_previous_definition);
20060       Invalid = true;
20061     }
20062     PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
20063     auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
20064                                                 Name, TyData.first, PrevDRD);
20065     DC->addDecl(DRD);
20066     DRD->setAccess(AS);
20067     Decls.push_back(DRD);
20068     if (Invalid)
20069       DRD->setInvalidDecl();
20070     else
20071       PrevDRD = DRD;
20072   }
20073 
20074   return DeclGroupPtrTy::make(
20075       DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
20076 }
20077 
20078 void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
20079   auto *DRD = cast<OMPDeclareReductionDecl>(D);
20080 
20081   // Enter new function scope.
20082   PushFunctionScope();
20083   setFunctionHasBranchProtectedScope();
20084   getCurFunction()->setHasOMPDeclareReductionCombiner();
20085 
20086   if (S != nullptr)
20087     PushDeclContext(S, DRD);
20088   else
20089     CurContext = DRD;
20090 
20091   PushExpressionEvaluationContext(
20092       ExpressionEvaluationContext::PotentiallyEvaluated);
20093 
20094   QualType ReductionType = DRD->getType();
20095   // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
20096   // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
20097   // uses semantics of argument handles by value, but it should be passed by
20098   // reference. C lang does not support references, so pass all parameters as
20099   // pointers.
20100   // Create 'T omp_in;' variable.
20101   VarDecl *OmpInParm =
20102       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
20103   // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
20104   // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
20105   // uses semantics of argument handles by value, but it should be passed by
20106   // reference. C lang does not support references, so pass all parameters as
20107   // pointers.
20108   // Create 'T omp_out;' variable.
20109   VarDecl *OmpOutParm =
20110       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
20111   if (S != nullptr) {
20112     PushOnScopeChains(OmpInParm, S);
20113     PushOnScopeChains(OmpOutParm, S);
20114   } else {
20115     DRD->addDecl(OmpInParm);
20116     DRD->addDecl(OmpOutParm);
20117   }
20118   Expr *InE =
20119       ::buildDeclRefExpr(*this, OmpInParm, ReductionType, D->getLocation());
20120   Expr *OutE =
20121       ::buildDeclRefExpr(*this, OmpOutParm, ReductionType, D->getLocation());
20122   DRD->setCombinerData(InE, OutE);
20123 }
20124 
20125 void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
20126   auto *DRD = cast<OMPDeclareReductionDecl>(D);
20127   DiscardCleanupsInEvaluationContext();
20128   PopExpressionEvaluationContext();
20129 
20130   PopDeclContext();
20131   PopFunctionScopeInfo();
20132 
20133   if (Combiner != nullptr)
20134     DRD->setCombiner(Combiner);
20135   else
20136     DRD->setInvalidDecl();
20137 }
20138 
20139 VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
20140   auto *DRD = cast<OMPDeclareReductionDecl>(D);
20141 
20142   // Enter new function scope.
20143   PushFunctionScope();
20144   setFunctionHasBranchProtectedScope();
20145 
20146   if (S != nullptr)
20147     PushDeclContext(S, DRD);
20148   else
20149     CurContext = DRD;
20150 
20151   PushExpressionEvaluationContext(
20152       ExpressionEvaluationContext::PotentiallyEvaluated);
20153 
20154   QualType ReductionType = DRD->getType();
20155   // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
20156   // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
20157   // uses semantics of argument handles by value, but it should be passed by
20158   // reference. C lang does not support references, so pass all parameters as
20159   // pointers.
20160   // Create 'T omp_priv;' variable.
20161   VarDecl *OmpPrivParm =
20162       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
20163   // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
20164   // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
20165   // uses semantics of argument handles by value, but it should be passed by
20166   // reference. C lang does not support references, so pass all parameters as
20167   // pointers.
20168   // Create 'T omp_orig;' variable.
20169   VarDecl *OmpOrigParm =
20170       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
20171   if (S != nullptr) {
20172     PushOnScopeChains(OmpPrivParm, S);
20173     PushOnScopeChains(OmpOrigParm, S);
20174   } else {
20175     DRD->addDecl(OmpPrivParm);
20176     DRD->addDecl(OmpOrigParm);
20177   }
20178   Expr *OrigE =
20179       ::buildDeclRefExpr(*this, OmpOrigParm, ReductionType, D->getLocation());
20180   Expr *PrivE =
20181       ::buildDeclRefExpr(*this, OmpPrivParm, ReductionType, D->getLocation());
20182   DRD->setInitializerData(OrigE, PrivE);
20183   return OmpPrivParm;
20184 }
20185 
20186 void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
20187                                                      VarDecl *OmpPrivParm) {
20188   auto *DRD = cast<OMPDeclareReductionDecl>(D);
20189   DiscardCleanupsInEvaluationContext();
20190   PopExpressionEvaluationContext();
20191 
20192   PopDeclContext();
20193   PopFunctionScopeInfo();
20194 
20195   if (Initializer != nullptr) {
20196     DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit);
20197   } else if (OmpPrivParm->hasInit()) {
20198     DRD->setInitializer(OmpPrivParm->getInit(),
20199                         OmpPrivParm->isDirectInit()
20200                             ? OMPDeclareReductionDecl::DirectInit
20201                             : OMPDeclareReductionDecl::CopyInit);
20202   } else {
20203     DRD->setInvalidDecl();
20204   }
20205 }
20206 
20207 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
20208     Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
20209   for (Decl *D : DeclReductions.get()) {
20210     if (IsValid) {
20211       if (S)
20212         PushOnScopeChains(cast<OMPDeclareReductionDecl>(D), S,
20213                           /*AddToContext=*/false);
20214     } else {
20215       D->setInvalidDecl();
20216     }
20217   }
20218   return DeclReductions;
20219 }
20220 
20221 TypeResult Sema::ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D) {
20222   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
20223   QualType T = TInfo->getType();
20224   if (D.isInvalidType())
20225     return true;
20226 
20227   if (getLangOpts().CPlusPlus) {
20228     // Check that there are no default arguments (C++ only).
20229     CheckExtraCXXDefaultArguments(D);
20230   }
20231 
20232   return CreateParsedType(T, TInfo);
20233 }
20234 
20235 QualType Sema::ActOnOpenMPDeclareMapperType(SourceLocation TyLoc,
20236                                             TypeResult ParsedType) {
20237   assert(ParsedType.isUsable() && "Expect usable parsed mapper type");
20238 
20239   QualType MapperType = GetTypeFromParser(ParsedType.get());
20240   assert(!MapperType.isNull() && "Expect valid mapper type");
20241 
20242   // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
20243   //  The type must be of struct, union or class type in C and C++
20244   if (!MapperType->isStructureOrClassType() && !MapperType->isUnionType()) {
20245     Diag(TyLoc, diag::err_omp_mapper_wrong_type);
20246     return QualType();
20247   }
20248   return MapperType;
20249 }
20250 
20251 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareMapperDirective(
20252     Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType,
20253     SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS,
20254     Expr *MapperVarRef, ArrayRef<OMPClause *> Clauses, Decl *PrevDeclInScope) {
20255   LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPMapperName,
20256                       forRedeclarationInCurContext());
20257   // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
20258   //  A mapper-identifier may not be redeclared in the current scope for the
20259   //  same type or for a type that is compatible according to the base language
20260   //  rules.
20261   llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
20262   OMPDeclareMapperDecl *PrevDMD = nullptr;
20263   bool InCompoundScope = true;
20264   if (S != nullptr) {
20265     // Find previous declaration with the same name not referenced in other
20266     // declarations.
20267     FunctionScopeInfo *ParentFn = getEnclosingFunction();
20268     InCompoundScope =
20269         (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
20270     LookupName(Lookup, S);
20271     FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
20272                          /*AllowInlineNamespace=*/false);
20273     llvm::DenseMap<OMPDeclareMapperDecl *, bool> UsedAsPrevious;
20274     LookupResult::Filter Filter = Lookup.makeFilter();
20275     while (Filter.hasNext()) {
20276       auto *PrevDecl = cast<OMPDeclareMapperDecl>(Filter.next());
20277       if (InCompoundScope) {
20278         auto I = UsedAsPrevious.find(PrevDecl);
20279         if (I == UsedAsPrevious.end())
20280           UsedAsPrevious[PrevDecl] = false;
20281         if (OMPDeclareMapperDecl *D = PrevDecl->getPrevDeclInScope())
20282           UsedAsPrevious[D] = true;
20283       }
20284       PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
20285           PrevDecl->getLocation();
20286     }
20287     Filter.done();
20288     if (InCompoundScope) {
20289       for (const auto &PrevData : UsedAsPrevious) {
20290         if (!PrevData.second) {
20291           PrevDMD = PrevData.first;
20292           break;
20293         }
20294       }
20295     }
20296   } else if (PrevDeclInScope) {
20297     auto *PrevDMDInScope = PrevDMD =
20298         cast<OMPDeclareMapperDecl>(PrevDeclInScope);
20299     do {
20300       PreviousRedeclTypes[PrevDMDInScope->getType().getCanonicalType()] =
20301           PrevDMDInScope->getLocation();
20302       PrevDMDInScope = PrevDMDInScope->getPrevDeclInScope();
20303     } while (PrevDMDInScope != nullptr);
20304   }
20305   const auto I = PreviousRedeclTypes.find(MapperType.getCanonicalType());
20306   bool Invalid = false;
20307   if (I != PreviousRedeclTypes.end()) {
20308     Diag(StartLoc, diag::err_omp_declare_mapper_redefinition)
20309         << MapperType << Name;
20310     Diag(I->second, diag::note_previous_definition);
20311     Invalid = true;
20312   }
20313   // Build expressions for implicit maps of data members with 'default'
20314   // mappers.
20315   SmallVector<OMPClause *, 4> ClausesWithImplicit(Clauses.begin(),
20316                                                   Clauses.end());
20317   if (LangOpts.OpenMP >= 50)
20318     processImplicitMapsWithDefaultMappers(*this, DSAStack, ClausesWithImplicit);
20319   auto *DMD =
20320       OMPDeclareMapperDecl::Create(Context, DC, StartLoc, Name, MapperType, VN,
20321                                    ClausesWithImplicit, PrevDMD);
20322   if (S)
20323     PushOnScopeChains(DMD, S);
20324   else
20325     DC->addDecl(DMD);
20326   DMD->setAccess(AS);
20327   if (Invalid)
20328     DMD->setInvalidDecl();
20329 
20330   auto *VD = cast<DeclRefExpr>(MapperVarRef)->getDecl();
20331   VD->setDeclContext(DMD);
20332   VD->setLexicalDeclContext(DMD);
20333   DMD->addDecl(VD);
20334   DMD->setMapperVarRef(MapperVarRef);
20335 
20336   return DeclGroupPtrTy::make(DeclGroupRef(DMD));
20337 }
20338 
20339 ExprResult
20340 Sema::ActOnOpenMPDeclareMapperDirectiveVarDecl(Scope *S, QualType MapperType,
20341                                                SourceLocation StartLoc,
20342                                                DeclarationName VN) {
20343   TypeSourceInfo *TInfo =
20344       Context.getTrivialTypeSourceInfo(MapperType, StartLoc);
20345   auto *VD = VarDecl::Create(Context, Context.getTranslationUnitDecl(),
20346                              StartLoc, StartLoc, VN.getAsIdentifierInfo(),
20347                              MapperType, TInfo, SC_None);
20348   if (S)
20349     PushOnScopeChains(VD, S, /*AddToContext=*/false);
20350   Expr *E = buildDeclRefExpr(*this, VD, MapperType, StartLoc);
20351   DSAStack->addDeclareMapperVarRef(E);
20352   return E;
20353 }
20354 
20355 bool Sema::isOpenMPDeclareMapperVarDeclAllowed(const VarDecl *VD) const {
20356   assert(LangOpts.OpenMP && "Expected OpenMP mode.");
20357   const Expr *Ref = DSAStack->getDeclareMapperVarRef();
20358   if (const auto *DRE = cast_or_null<DeclRefExpr>(Ref)) {
20359     if (VD->getCanonicalDecl() == DRE->getDecl()->getCanonicalDecl())
20360       return true;
20361     if (VD->isUsableInConstantExpressions(Context))
20362       return true;
20363     return false;
20364   }
20365   return true;
20366 }
20367 
20368 const ValueDecl *Sema::getOpenMPDeclareMapperVarName() const {
20369   assert(LangOpts.OpenMP && "Expected OpenMP mode.");
20370   return cast<DeclRefExpr>(DSAStack->getDeclareMapperVarRef())->getDecl();
20371 }
20372 
20373 OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
20374                                            SourceLocation StartLoc,
20375                                            SourceLocation LParenLoc,
20376                                            SourceLocation EndLoc) {
20377   Expr *ValExpr = NumTeams;
20378   Stmt *HelperValStmt = nullptr;
20379 
20380   // OpenMP [teams Constrcut, Restrictions]
20381   // The num_teams expression must evaluate to a positive integer value.
20382   if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
20383                                  /*StrictlyPositive=*/true))
20384     return nullptr;
20385 
20386   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
20387   OpenMPDirectiveKind CaptureRegion =
20388       getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams, LangOpts.OpenMP);
20389   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
20390     ValExpr = MakeFullExpr(ValExpr).get();
20391     llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
20392     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
20393     HelperValStmt = buildPreInits(Context, Captures);
20394   }
20395 
20396   return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
20397                                          StartLoc, LParenLoc, EndLoc);
20398 }
20399 
20400 OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
20401                                               SourceLocation StartLoc,
20402                                               SourceLocation LParenLoc,
20403                                               SourceLocation EndLoc) {
20404   Expr *ValExpr = ThreadLimit;
20405   Stmt *HelperValStmt = nullptr;
20406 
20407   // OpenMP [teams Constrcut, Restrictions]
20408   // The thread_limit expression must evaluate to a positive integer value.
20409   if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
20410                                  /*StrictlyPositive=*/true))
20411     return nullptr;
20412 
20413   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
20414   OpenMPDirectiveKind CaptureRegion = getOpenMPCaptureRegionForClause(
20415       DKind, OMPC_thread_limit, LangOpts.OpenMP);
20416   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
20417     ValExpr = MakeFullExpr(ValExpr).get();
20418     llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
20419     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
20420     HelperValStmt = buildPreInits(Context, Captures);
20421   }
20422 
20423   return new (Context) OMPThreadLimitClause(
20424       ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
20425 }
20426 
20427 OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
20428                                            SourceLocation StartLoc,
20429                                            SourceLocation LParenLoc,
20430                                            SourceLocation EndLoc) {
20431   Expr *ValExpr = Priority;
20432   Stmt *HelperValStmt = nullptr;
20433   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
20434 
20435   // OpenMP [2.9.1, task Constrcut]
20436   // The priority-value is a non-negative numerical scalar expression.
20437   if (!isNonNegativeIntegerValue(
20438           ValExpr, *this, OMPC_priority,
20439           /*StrictlyPositive=*/false, /*BuildCapture=*/true,
20440           DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt))
20441     return nullptr;
20442 
20443   return new (Context) OMPPriorityClause(ValExpr, HelperValStmt, CaptureRegion,
20444                                          StartLoc, LParenLoc, EndLoc);
20445 }
20446 
20447 OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
20448                                             SourceLocation StartLoc,
20449                                             SourceLocation LParenLoc,
20450                                             SourceLocation EndLoc) {
20451   Expr *ValExpr = Grainsize;
20452   Stmt *HelperValStmt = nullptr;
20453   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
20454 
20455   // OpenMP [2.9.2, taskloop Constrcut]
20456   // The parameter of the grainsize clause must be a positive integer
20457   // expression.
20458   if (!isNonNegativeIntegerValue(
20459           ValExpr, *this, OMPC_grainsize,
20460           /*StrictlyPositive=*/true, /*BuildCapture=*/true,
20461           DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt))
20462     return nullptr;
20463 
20464   return new (Context) OMPGrainsizeClause(ValExpr, HelperValStmt, CaptureRegion,
20465                                           StartLoc, LParenLoc, EndLoc);
20466 }
20467 
20468 OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
20469                                            SourceLocation StartLoc,
20470                                            SourceLocation LParenLoc,
20471                                            SourceLocation EndLoc) {
20472   Expr *ValExpr = NumTasks;
20473   Stmt *HelperValStmt = nullptr;
20474   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
20475 
20476   // OpenMP [2.9.2, taskloop Constrcut]
20477   // The parameter of the num_tasks clause must be a positive integer
20478   // expression.
20479   if (!isNonNegativeIntegerValue(
20480           ValExpr, *this, OMPC_num_tasks,
20481           /*StrictlyPositive=*/true, /*BuildCapture=*/true,
20482           DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt))
20483     return nullptr;
20484 
20485   return new (Context) OMPNumTasksClause(ValExpr, HelperValStmt, CaptureRegion,
20486                                          StartLoc, LParenLoc, EndLoc);
20487 }
20488 
20489 OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
20490                                        SourceLocation LParenLoc,
20491                                        SourceLocation EndLoc) {
20492   // OpenMP [2.13.2, critical construct, Description]
20493   // ... where hint-expression is an integer constant expression that evaluates
20494   // to a valid lock hint.
20495   ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
20496   if (HintExpr.isInvalid())
20497     return nullptr;
20498   return new (Context)
20499       OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
20500 }
20501 
20502 /// Tries to find omp_event_handle_t type.
20503 static bool findOMPEventHandleT(Sema &S, SourceLocation Loc,
20504                                 DSAStackTy *Stack) {
20505   QualType OMPEventHandleT = Stack->getOMPEventHandleT();
20506   if (!OMPEventHandleT.isNull())
20507     return true;
20508   IdentifierInfo *II = &S.PP.getIdentifierTable().get("omp_event_handle_t");
20509   ParsedType PT = S.getTypeName(*II, Loc, S.getCurScope());
20510   if (!PT.getAsOpaquePtr() || PT.get().isNull()) {
20511     S.Diag(Loc, diag::err_omp_implied_type_not_found) << "omp_event_handle_t";
20512     return false;
20513   }
20514   Stack->setOMPEventHandleT(PT.get());
20515   return true;
20516 }
20517 
20518 OMPClause *Sema::ActOnOpenMPDetachClause(Expr *Evt, SourceLocation StartLoc,
20519                                          SourceLocation LParenLoc,
20520                                          SourceLocation EndLoc) {
20521   if (!Evt->isValueDependent() && !Evt->isTypeDependent() &&
20522       !Evt->isInstantiationDependent() &&
20523       !Evt->containsUnexpandedParameterPack()) {
20524     if (!findOMPEventHandleT(*this, Evt->getExprLoc(), DSAStack))
20525       return nullptr;
20526     // OpenMP 5.0, 2.10.1 task Construct.
20527     // event-handle is a variable of the omp_event_handle_t type.
20528     auto *Ref = dyn_cast<DeclRefExpr>(Evt->IgnoreParenImpCasts());
20529     if (!Ref) {
20530       Diag(Evt->getExprLoc(), diag::err_omp_var_expected)
20531           << "omp_event_handle_t" << 0 << Evt->getSourceRange();
20532       return nullptr;
20533     }
20534     auto *VD = dyn_cast_or_null<VarDecl>(Ref->getDecl());
20535     if (!VD) {
20536       Diag(Evt->getExprLoc(), diag::err_omp_var_expected)
20537           << "omp_event_handle_t" << 0 << Evt->getSourceRange();
20538       return nullptr;
20539     }
20540     if (!Context.hasSameUnqualifiedType(DSAStack->getOMPEventHandleT(),
20541                                         VD->getType()) ||
20542         VD->getType().isConstant(Context)) {
20543       Diag(Evt->getExprLoc(), diag::err_omp_var_expected)
20544           << "omp_event_handle_t" << 1 << VD->getType()
20545           << Evt->getSourceRange();
20546       return nullptr;
20547     }
20548     // OpenMP 5.0, 2.10.1 task Construct
20549     // [detach clause]... The event-handle will be considered as if it was
20550     // specified on a firstprivate clause.
20551     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, /*FromParent=*/false);
20552     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
20553         DVar.RefExpr) {
20554       Diag(Evt->getExprLoc(), diag::err_omp_wrong_dsa)
20555           << getOpenMPClauseName(DVar.CKind)
20556           << getOpenMPClauseName(OMPC_firstprivate);
20557       reportOriginalDsa(*this, DSAStack, VD, DVar);
20558       return nullptr;
20559     }
20560   }
20561 
20562   return new (Context) OMPDetachClause(Evt, StartLoc, LParenLoc, EndLoc);
20563 }
20564 
20565 OMPClause *Sema::ActOnOpenMPDistScheduleClause(
20566     OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
20567     SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
20568     SourceLocation EndLoc) {
20569   if (Kind == OMPC_DIST_SCHEDULE_unknown) {
20570     std::string Values;
20571     Values += "'";
20572     Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
20573     Values += "'";
20574     Diag(KindLoc, diag::err_omp_unexpected_clause_value)
20575         << Values << getOpenMPClauseName(OMPC_dist_schedule);
20576     return nullptr;
20577   }
20578   Expr *ValExpr = ChunkSize;
20579   Stmt *HelperValStmt = nullptr;
20580   if (ChunkSize) {
20581     if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
20582         !ChunkSize->isInstantiationDependent() &&
20583         !ChunkSize->containsUnexpandedParameterPack()) {
20584       SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
20585       ExprResult Val =
20586           PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
20587       if (Val.isInvalid())
20588         return nullptr;
20589 
20590       ValExpr = Val.get();
20591 
20592       // OpenMP [2.7.1, Restrictions]
20593       //  chunk_size must be a loop invariant integer expression with a positive
20594       //  value.
20595       if (Optional<llvm::APSInt> Result =
20596               ValExpr->getIntegerConstantExpr(Context)) {
20597         if (Result->isSigned() && !Result->isStrictlyPositive()) {
20598           Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
20599               << "dist_schedule" << ChunkSize->getSourceRange();
20600           return nullptr;
20601         }
20602       } else if (getOpenMPCaptureRegionForClause(
20603                      DSAStack->getCurrentDirective(), OMPC_dist_schedule,
20604                      LangOpts.OpenMP) != OMPD_unknown &&
20605                  !CurContext->isDependentContext()) {
20606         ValExpr = MakeFullExpr(ValExpr).get();
20607         llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
20608         ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
20609         HelperValStmt = buildPreInits(Context, Captures);
20610       }
20611     }
20612   }
20613 
20614   return new (Context)
20615       OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
20616                             Kind, ValExpr, HelperValStmt);
20617 }
20618 
20619 OMPClause *Sema::ActOnOpenMPDefaultmapClause(
20620     OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
20621     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
20622     SourceLocation KindLoc, SourceLocation EndLoc) {
20623   if (getLangOpts().OpenMP < 50) {
20624     if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom ||
20625         Kind != OMPC_DEFAULTMAP_scalar) {
20626       std::string Value;
20627       SourceLocation Loc;
20628       Value += "'";
20629       if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
20630         Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
20631                                                OMPC_DEFAULTMAP_MODIFIER_tofrom);
20632         Loc = MLoc;
20633       } else {
20634         Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
20635                                                OMPC_DEFAULTMAP_scalar);
20636         Loc = KindLoc;
20637       }
20638       Value += "'";
20639       Diag(Loc, diag::err_omp_unexpected_clause_value)
20640           << Value << getOpenMPClauseName(OMPC_defaultmap);
20641       return nullptr;
20642     }
20643   } else {
20644     bool isDefaultmapModifier = (M != OMPC_DEFAULTMAP_MODIFIER_unknown);
20645     bool isDefaultmapKind = (Kind != OMPC_DEFAULTMAP_unknown) ||
20646                             (LangOpts.OpenMP >= 50 && KindLoc.isInvalid());
20647     if (!isDefaultmapKind || !isDefaultmapModifier) {
20648       StringRef KindValue = "'scalar', 'aggregate', 'pointer'";
20649       if (LangOpts.OpenMP == 50) {
20650         StringRef ModifierValue = "'alloc', 'from', 'to', 'tofrom', "
20651                                   "'firstprivate', 'none', 'default'";
20652         if (!isDefaultmapKind && isDefaultmapModifier) {
20653           Diag(KindLoc, diag::err_omp_unexpected_clause_value)
20654               << KindValue << getOpenMPClauseName(OMPC_defaultmap);
20655         } else if (isDefaultmapKind && !isDefaultmapModifier) {
20656           Diag(MLoc, diag::err_omp_unexpected_clause_value)
20657               << ModifierValue << getOpenMPClauseName(OMPC_defaultmap);
20658         } else {
20659           Diag(MLoc, diag::err_omp_unexpected_clause_value)
20660               << ModifierValue << getOpenMPClauseName(OMPC_defaultmap);
20661           Diag(KindLoc, diag::err_omp_unexpected_clause_value)
20662               << KindValue << getOpenMPClauseName(OMPC_defaultmap);
20663         }
20664       } else {
20665         StringRef ModifierValue =
20666             "'alloc', 'from', 'to', 'tofrom', "
20667             "'firstprivate', 'none', 'default', 'present'";
20668         if (!isDefaultmapKind && isDefaultmapModifier) {
20669           Diag(KindLoc, diag::err_omp_unexpected_clause_value)
20670               << KindValue << getOpenMPClauseName(OMPC_defaultmap);
20671         } else if (isDefaultmapKind && !isDefaultmapModifier) {
20672           Diag(MLoc, diag::err_omp_unexpected_clause_value)
20673               << ModifierValue << getOpenMPClauseName(OMPC_defaultmap);
20674         } else {
20675           Diag(MLoc, diag::err_omp_unexpected_clause_value)
20676               << ModifierValue << getOpenMPClauseName(OMPC_defaultmap);
20677           Diag(KindLoc, diag::err_omp_unexpected_clause_value)
20678               << KindValue << getOpenMPClauseName(OMPC_defaultmap);
20679         }
20680       }
20681       return nullptr;
20682     }
20683 
20684     // OpenMP [5.0, 2.12.5, Restrictions, p. 174]
20685     //  At most one defaultmap clause for each category can appear on the
20686     //  directive.
20687     if (DSAStack->checkDefaultmapCategory(Kind)) {
20688       Diag(StartLoc, diag::err_omp_one_defaultmap_each_category);
20689       return nullptr;
20690     }
20691   }
20692   if (Kind == OMPC_DEFAULTMAP_unknown) {
20693     // Variable category is not specified - mark all categories.
20694     DSAStack->setDefaultDMAAttr(M, OMPC_DEFAULTMAP_aggregate, StartLoc);
20695     DSAStack->setDefaultDMAAttr(M, OMPC_DEFAULTMAP_scalar, StartLoc);
20696     DSAStack->setDefaultDMAAttr(M, OMPC_DEFAULTMAP_pointer, StartLoc);
20697   } else {
20698     DSAStack->setDefaultDMAAttr(M, Kind, StartLoc);
20699   }
20700 
20701   return new (Context)
20702       OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
20703 }
20704 
20705 bool Sema::ActOnStartOpenMPDeclareTargetContext(
20706     DeclareTargetContextInfo &DTCI) {
20707   DeclContext *CurLexicalContext = getCurLexicalContext();
20708   if (!CurLexicalContext->isFileContext() &&
20709       !CurLexicalContext->isExternCContext() &&
20710       !CurLexicalContext->isExternCXXContext() &&
20711       !isa<CXXRecordDecl>(CurLexicalContext) &&
20712       !isa<ClassTemplateDecl>(CurLexicalContext) &&
20713       !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) &&
20714       !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) {
20715     Diag(DTCI.Loc, diag::err_omp_region_not_file_context);
20716     return false;
20717   }
20718   DeclareTargetNesting.push_back(DTCI);
20719   return true;
20720 }
20721 
20722 const Sema::DeclareTargetContextInfo
20723 Sema::ActOnOpenMPEndDeclareTargetDirective() {
20724   assert(!DeclareTargetNesting.empty() &&
20725          "check isInOpenMPDeclareTargetContext() first!");
20726   return DeclareTargetNesting.pop_back_val();
20727 }
20728 
20729 void Sema::ActOnFinishedOpenMPDeclareTargetContext(
20730     DeclareTargetContextInfo &DTCI) {
20731   for (auto &It : DTCI.ExplicitlyMapped)
20732     ActOnOpenMPDeclareTargetName(It.first, It.second.Loc, It.second.MT,
20733                                  DTCI.DT);
20734 }
20735 
20736 NamedDecl *Sema::lookupOpenMPDeclareTargetName(Scope *CurScope,
20737                                                CXXScopeSpec &ScopeSpec,
20738                                                const DeclarationNameInfo &Id) {
20739   LookupResult Lookup(*this, Id, LookupOrdinaryName);
20740   LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
20741 
20742   if (Lookup.isAmbiguous())
20743     return nullptr;
20744   Lookup.suppressDiagnostics();
20745 
20746   if (!Lookup.isSingleResult()) {
20747     VarOrFuncDeclFilterCCC CCC(*this);
20748     if (TypoCorrection Corrected =
20749             CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC,
20750                         CTK_ErrorRecovery)) {
20751       diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
20752                                   << Id.getName());
20753       checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
20754       return nullptr;
20755     }
20756 
20757     Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
20758     return nullptr;
20759   }
20760 
20761   NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
20762   if (!isa<VarDecl>(ND) && !isa<FunctionDecl>(ND) &&
20763       !isa<FunctionTemplateDecl>(ND)) {
20764     Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
20765     return nullptr;
20766   }
20767   return ND;
20768 }
20769 
20770 void Sema::ActOnOpenMPDeclareTargetName(
20771     NamedDecl *ND, SourceLocation Loc, OMPDeclareTargetDeclAttr::MapTypeTy MT,
20772     OMPDeclareTargetDeclAttr::DevTypeTy DT) {
20773   assert((isa<VarDecl>(ND) || isa<FunctionDecl>(ND) ||
20774           isa<FunctionTemplateDecl>(ND)) &&
20775          "Expected variable, function or function template.");
20776 
20777   // Diagnose marking after use as it may lead to incorrect diagnosis and
20778   // codegen.
20779   if (LangOpts.OpenMP >= 50 &&
20780       (ND->isUsed(/*CheckUsedAttr=*/false) || ND->isReferenced()))
20781     Diag(Loc, diag::warn_omp_declare_target_after_first_use);
20782 
20783   // Explicit declare target lists have precedence.
20784   const unsigned Level = -1;
20785 
20786   auto *VD = cast<ValueDecl>(ND);
20787   llvm::Optional<OMPDeclareTargetDeclAttr *> ActiveAttr =
20788       OMPDeclareTargetDeclAttr::getActiveAttr(VD);
20789   if (ActiveAttr.hasValue() && ActiveAttr.getValue()->getDevType() != DT &&
20790       ActiveAttr.getValue()->getLevel() == Level) {
20791     Diag(Loc, diag::err_omp_device_type_mismatch)
20792         << OMPDeclareTargetDeclAttr::ConvertDevTypeTyToStr(DT)
20793         << OMPDeclareTargetDeclAttr::ConvertDevTypeTyToStr(
20794                ActiveAttr.getValue()->getDevType());
20795     return;
20796   }
20797   if (ActiveAttr.hasValue() && ActiveAttr.getValue()->getMapType() != MT &&
20798       ActiveAttr.getValue()->getLevel() == Level) {
20799     Diag(Loc, diag::err_omp_declare_target_to_and_link) << ND;
20800     return;
20801   }
20802 
20803   if (ActiveAttr.hasValue() && ActiveAttr.getValue()->getLevel() == Level)
20804     return;
20805 
20806   auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT, DT, Level,
20807                                                      SourceRange(Loc, Loc));
20808   ND->addAttr(A);
20809   if (ASTMutationListener *ML = Context.getASTMutationListener())
20810     ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
20811   checkDeclIsAllowedInOpenMPTarget(nullptr, ND, Loc);
20812 }
20813 
20814 static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
20815                                      Sema &SemaRef, Decl *D) {
20816   if (!D || !isa<VarDecl>(D))
20817     return;
20818   auto *VD = cast<VarDecl>(D);
20819   Optional<OMPDeclareTargetDeclAttr::MapTypeTy> MapTy =
20820       OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
20821   if (SemaRef.LangOpts.OpenMP >= 50 &&
20822       (SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true) ||
20823        SemaRef.getCurBlock() || SemaRef.getCurCapturedRegion()) &&
20824       VD->hasGlobalStorage()) {
20825     if (!MapTy || *MapTy != OMPDeclareTargetDeclAttr::MT_To) {
20826       // OpenMP 5.0, 2.12.7 declare target Directive, Restrictions
20827       // If a lambda declaration and definition appears between a
20828       // declare target directive and the matching end declare target
20829       // directive, all variables that are captured by the lambda
20830       // expression must also appear in a to clause.
20831       SemaRef.Diag(VD->getLocation(),
20832                    diag::err_omp_lambda_capture_in_declare_target_not_to);
20833       SemaRef.Diag(SL, diag::note_var_explicitly_captured_here)
20834           << VD << 0 << SR;
20835       return;
20836     }
20837   }
20838   if (MapTy.hasValue())
20839     return;
20840   SemaRef.Diag(VD->getLocation(), diag::warn_omp_not_in_target_context);
20841   SemaRef.Diag(SL, diag::note_used_here) << SR;
20842 }
20843 
20844 static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
20845                                    Sema &SemaRef, DSAStackTy *Stack,
20846                                    ValueDecl *VD) {
20847   return OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD) ||
20848          checkTypeMappable(SL, SR, SemaRef, Stack, VD->getType(),
20849                            /*FullCheck=*/false);
20850 }
20851 
20852 void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
20853                                             SourceLocation IdLoc) {
20854   if (!D || D->isInvalidDecl())
20855     return;
20856   SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
20857   SourceLocation SL = E ? E->getBeginLoc() : D->getLocation();
20858   if (auto *VD = dyn_cast<VarDecl>(D)) {
20859     // Only global variables can be marked as declare target.
20860     if (!VD->isFileVarDecl() && !VD->isStaticLocal() &&
20861         !VD->isStaticDataMember())
20862       return;
20863     // 2.10.6: threadprivate variable cannot appear in a declare target
20864     // directive.
20865     if (DSAStack->isThreadPrivate(VD)) {
20866       Diag(SL, diag::err_omp_threadprivate_in_target);
20867       reportOriginalDsa(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
20868       return;
20869     }
20870   }
20871   if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(D))
20872     D = FTD->getTemplatedDecl();
20873   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
20874     llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
20875         OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(FD);
20876     if (IdLoc.isValid() && Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) {
20877       Diag(IdLoc, diag::err_omp_function_in_link_clause);
20878       Diag(FD->getLocation(), diag::note_defined_here) << FD;
20879       return;
20880     }
20881   }
20882   if (auto *VD = dyn_cast<ValueDecl>(D)) {
20883     // Problem if any with var declared with incomplete type will be reported
20884     // as normal, so no need to check it here.
20885     if ((E || !VD->getType()->isIncompleteType()) &&
20886         !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD))
20887       return;
20888     if (!E && isInOpenMPDeclareTargetContext()) {
20889       // Checking declaration inside declare target region.
20890       if (isa<VarDecl>(D) || isa<FunctionDecl>(D) ||
20891           isa<FunctionTemplateDecl>(D)) {
20892         llvm::Optional<OMPDeclareTargetDeclAttr *> ActiveAttr =
20893             OMPDeclareTargetDeclAttr::getActiveAttr(VD);
20894         unsigned Level = DeclareTargetNesting.size();
20895         if (ActiveAttr.hasValue() && ActiveAttr.getValue()->getLevel() >= Level)
20896           return;
20897         DeclareTargetContextInfo &DTCI = DeclareTargetNesting.back();
20898         auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(
20899             Context, OMPDeclareTargetDeclAttr::MT_To, DTCI.DT, Level,
20900             SourceRange(DTCI.Loc, DTCI.Loc));
20901         D->addAttr(A);
20902         if (ASTMutationListener *ML = Context.getASTMutationListener())
20903           ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
20904       }
20905       return;
20906     }
20907   }
20908   if (!E)
20909     return;
20910   checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
20911 }
20912 
20913 OMPClause *Sema::ActOnOpenMPToClause(
20914     ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
20915     ArrayRef<SourceLocation> MotionModifiersLoc,
20916     CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId,
20917     SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
20918     const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) {
20919   OpenMPMotionModifierKind Modifiers[] = {OMPC_MOTION_MODIFIER_unknown,
20920                                           OMPC_MOTION_MODIFIER_unknown};
20921   SourceLocation ModifiersLoc[NumberOfOMPMotionModifiers];
20922 
20923   // Process motion-modifiers, flag errors for duplicate modifiers.
20924   unsigned Count = 0;
20925   for (unsigned I = 0, E = MotionModifiers.size(); I < E; ++I) {
20926     if (MotionModifiers[I] != OMPC_MOTION_MODIFIER_unknown &&
20927         llvm::is_contained(Modifiers, MotionModifiers[I])) {
20928       Diag(MotionModifiersLoc[I], diag::err_omp_duplicate_motion_modifier);
20929       continue;
20930     }
20931     assert(Count < NumberOfOMPMotionModifiers &&
20932            "Modifiers exceed the allowed number of motion modifiers");
20933     Modifiers[Count] = MotionModifiers[I];
20934     ModifiersLoc[Count] = MotionModifiersLoc[I];
20935     ++Count;
20936   }
20937 
20938   MappableVarListInfo MVLI(VarList);
20939   checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, Locs.StartLoc,
20940                               MapperIdScopeSpec, MapperId, UnresolvedMappers);
20941   if (MVLI.ProcessedVarList.empty())
20942     return nullptr;
20943 
20944   return OMPToClause::Create(
20945       Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
20946       MVLI.VarComponents, MVLI.UDMapperList, Modifiers, ModifiersLoc,
20947       MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
20948 }
20949 
20950 OMPClause *Sema::ActOnOpenMPFromClause(
20951     ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
20952     ArrayRef<SourceLocation> MotionModifiersLoc,
20953     CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId,
20954     SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
20955     const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) {
20956   OpenMPMotionModifierKind Modifiers[] = {OMPC_MOTION_MODIFIER_unknown,
20957                                           OMPC_MOTION_MODIFIER_unknown};
20958   SourceLocation ModifiersLoc[NumberOfOMPMotionModifiers];
20959 
20960   // Process motion-modifiers, flag errors for duplicate modifiers.
20961   unsigned Count = 0;
20962   for (unsigned I = 0, E = MotionModifiers.size(); I < E; ++I) {
20963     if (MotionModifiers[I] != OMPC_MOTION_MODIFIER_unknown &&
20964         llvm::is_contained(Modifiers, MotionModifiers[I])) {
20965       Diag(MotionModifiersLoc[I], diag::err_omp_duplicate_motion_modifier);
20966       continue;
20967     }
20968     assert(Count < NumberOfOMPMotionModifiers &&
20969            "Modifiers exceed the allowed number of motion modifiers");
20970     Modifiers[Count] = MotionModifiers[I];
20971     ModifiersLoc[Count] = MotionModifiersLoc[I];
20972     ++Count;
20973   }
20974 
20975   MappableVarListInfo MVLI(VarList);
20976   checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, Locs.StartLoc,
20977                               MapperIdScopeSpec, MapperId, UnresolvedMappers);
20978   if (MVLI.ProcessedVarList.empty())
20979     return nullptr;
20980 
20981   return OMPFromClause::Create(
20982       Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
20983       MVLI.VarComponents, MVLI.UDMapperList, Modifiers, ModifiersLoc,
20984       MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
20985 }
20986 
20987 OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
20988                                                const OMPVarListLocTy &Locs) {
20989   MappableVarListInfo MVLI(VarList);
20990   SmallVector<Expr *, 8> PrivateCopies;
20991   SmallVector<Expr *, 8> Inits;
20992 
20993   for (Expr *RefExpr : VarList) {
20994     assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
20995     SourceLocation ELoc;
20996     SourceRange ERange;
20997     Expr *SimpleRefExpr = RefExpr;
20998     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
20999     if (Res.second) {
21000       // It will be analyzed later.
21001       MVLI.ProcessedVarList.push_back(RefExpr);
21002       PrivateCopies.push_back(nullptr);
21003       Inits.push_back(nullptr);
21004     }
21005     ValueDecl *D = Res.first;
21006     if (!D)
21007       continue;
21008 
21009     QualType Type = D->getType();
21010     Type = Type.getNonReferenceType().getUnqualifiedType();
21011 
21012     auto *VD = dyn_cast<VarDecl>(D);
21013 
21014     // Item should be a pointer or reference to pointer.
21015     if (!Type->isPointerType()) {
21016       Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
21017           << 0 << RefExpr->getSourceRange();
21018       continue;
21019     }
21020 
21021     // Build the private variable and the expression that refers to it.
21022     auto VDPrivate =
21023         buildVarDecl(*this, ELoc, Type, D->getName(),
21024                      D->hasAttrs() ? &D->getAttrs() : nullptr,
21025                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
21026     if (VDPrivate->isInvalidDecl())
21027       continue;
21028 
21029     CurContext->addDecl(VDPrivate);
21030     DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
21031         *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
21032 
21033     // Add temporary variable to initialize the private copy of the pointer.
21034     VarDecl *VDInit =
21035         buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
21036     DeclRefExpr *VDInitRefExpr = buildDeclRefExpr(
21037         *this, VDInit, RefExpr->getType(), RefExpr->getExprLoc());
21038     AddInitializerToDecl(VDPrivate,
21039                          DefaultLvalueConversion(VDInitRefExpr).get(),
21040                          /*DirectInit=*/false);
21041 
21042     // If required, build a capture to implement the privatization initialized
21043     // with the current list item value.
21044     DeclRefExpr *Ref = nullptr;
21045     if (!VD)
21046       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
21047     MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
21048     PrivateCopies.push_back(VDPrivateRefExpr);
21049     Inits.push_back(VDInitRefExpr);
21050 
21051     // We need to add a data sharing attribute for this variable to make sure it
21052     // is correctly captured. A variable that shows up in a use_device_ptr has
21053     // similar properties of a first private variable.
21054     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
21055 
21056     // Create a mappable component for the list item. List items in this clause
21057     // only need a component.
21058     MVLI.VarBaseDeclarations.push_back(D);
21059     MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
21060     MVLI.VarComponents.back().emplace_back(SimpleRefExpr, D,
21061                                            /*IsNonContiguous=*/false);
21062   }
21063 
21064   if (MVLI.ProcessedVarList.empty())
21065     return nullptr;
21066 
21067   return OMPUseDevicePtrClause::Create(
21068       Context, Locs, MVLI.ProcessedVarList, PrivateCopies, Inits,
21069       MVLI.VarBaseDeclarations, MVLI.VarComponents);
21070 }
21071 
21072 OMPClause *Sema::ActOnOpenMPUseDeviceAddrClause(ArrayRef<Expr *> VarList,
21073                                                 const OMPVarListLocTy &Locs) {
21074   MappableVarListInfo MVLI(VarList);
21075 
21076   for (Expr *RefExpr : VarList) {
21077     assert(RefExpr && "NULL expr in OpenMP use_device_addr clause.");
21078     SourceLocation ELoc;
21079     SourceRange ERange;
21080     Expr *SimpleRefExpr = RefExpr;
21081     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
21082                               /*AllowArraySection=*/true);
21083     if (Res.second) {
21084       // It will be analyzed later.
21085       MVLI.ProcessedVarList.push_back(RefExpr);
21086     }
21087     ValueDecl *D = Res.first;
21088     if (!D)
21089       continue;
21090     auto *VD = dyn_cast<VarDecl>(D);
21091 
21092     // If required, build a capture to implement the privatization initialized
21093     // with the current list item value.
21094     DeclRefExpr *Ref = nullptr;
21095     if (!VD)
21096       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
21097     MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
21098 
21099     // We need to add a data sharing attribute for this variable to make sure it
21100     // is correctly captured. A variable that shows up in a use_device_addr has
21101     // similar properties of a first private variable.
21102     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
21103 
21104     // Create a mappable component for the list item. List items in this clause
21105     // only need a component.
21106     MVLI.VarBaseDeclarations.push_back(D);
21107     MVLI.VarComponents.emplace_back();
21108     Expr *Component = SimpleRefExpr;
21109     if (VD && (isa<OMPArraySectionExpr>(RefExpr->IgnoreParenImpCasts()) ||
21110                isa<ArraySubscriptExpr>(RefExpr->IgnoreParenImpCasts())))
21111       Component = DefaultFunctionArrayLvalueConversion(SimpleRefExpr).get();
21112     MVLI.VarComponents.back().emplace_back(Component, D,
21113                                            /*IsNonContiguous=*/false);
21114   }
21115 
21116   if (MVLI.ProcessedVarList.empty())
21117     return nullptr;
21118 
21119   return OMPUseDeviceAddrClause::Create(Context, Locs, MVLI.ProcessedVarList,
21120                                         MVLI.VarBaseDeclarations,
21121                                         MVLI.VarComponents);
21122 }
21123 
21124 OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
21125                                               const OMPVarListLocTy &Locs) {
21126   MappableVarListInfo MVLI(VarList);
21127   for (Expr *RefExpr : VarList) {
21128     assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
21129     SourceLocation ELoc;
21130     SourceRange ERange;
21131     Expr *SimpleRefExpr = RefExpr;
21132     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
21133     if (Res.second) {
21134       // It will be analyzed later.
21135       MVLI.ProcessedVarList.push_back(RefExpr);
21136     }
21137     ValueDecl *D = Res.first;
21138     if (!D)
21139       continue;
21140 
21141     QualType Type = D->getType();
21142     // item should be a pointer or array or reference to pointer or array
21143     if (!Type.getNonReferenceType()->isPointerType() &&
21144         !Type.getNonReferenceType()->isArrayType()) {
21145       Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
21146           << 0 << RefExpr->getSourceRange();
21147       continue;
21148     }
21149 
21150     // Check if the declaration in the clause does not show up in any data
21151     // sharing attribute.
21152     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
21153     if (isOpenMPPrivate(DVar.CKind)) {
21154       Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
21155           << getOpenMPClauseName(DVar.CKind)
21156           << getOpenMPClauseName(OMPC_is_device_ptr)
21157           << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
21158       reportOriginalDsa(*this, DSAStack, D, DVar);
21159       continue;
21160     }
21161 
21162     const Expr *ConflictExpr;
21163     if (DSAStack->checkMappableExprComponentListsForDecl(
21164             D, /*CurrentRegionOnly=*/true,
21165             [&ConflictExpr](
21166                 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
21167                 OpenMPClauseKind) -> bool {
21168               ConflictExpr = R.front().getAssociatedExpression();
21169               return true;
21170             })) {
21171       Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
21172       Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
21173           << ConflictExpr->getSourceRange();
21174       continue;
21175     }
21176 
21177     // Store the components in the stack so that they can be used to check
21178     // against other clauses later on.
21179     OMPClauseMappableExprCommon::MappableComponent MC(
21180         SimpleRefExpr, D, /*IsNonContiguous=*/false);
21181     DSAStack->addMappableExpressionComponents(
21182         D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
21183 
21184     // Record the expression we've just processed.
21185     MVLI.ProcessedVarList.push_back(SimpleRefExpr);
21186 
21187     // Create a mappable component for the list item. List items in this clause
21188     // only need a component. We use a null declaration to signal fields in
21189     // 'this'.
21190     assert((isa<DeclRefExpr>(SimpleRefExpr) ||
21191             isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
21192            "Unexpected device pointer expression!");
21193     MVLI.VarBaseDeclarations.push_back(
21194         isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
21195     MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
21196     MVLI.VarComponents.back().push_back(MC);
21197   }
21198 
21199   if (MVLI.ProcessedVarList.empty())
21200     return nullptr;
21201 
21202   return OMPIsDevicePtrClause::Create(Context, Locs, MVLI.ProcessedVarList,
21203                                       MVLI.VarBaseDeclarations,
21204                                       MVLI.VarComponents);
21205 }
21206 
21207 OMPClause *Sema::ActOnOpenMPAllocateClause(
21208     Expr *Allocator, ArrayRef<Expr *> VarList, SourceLocation StartLoc,
21209     SourceLocation ColonLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
21210   if (Allocator) {
21211     // OpenMP [2.11.4 allocate Clause, Description]
21212     // allocator is an expression of omp_allocator_handle_t type.
21213     if (!findOMPAllocatorHandleT(*this, Allocator->getExprLoc(), DSAStack))
21214       return nullptr;
21215 
21216     ExprResult AllocatorRes = DefaultLvalueConversion(Allocator);
21217     if (AllocatorRes.isInvalid())
21218       return nullptr;
21219     AllocatorRes = PerformImplicitConversion(AllocatorRes.get(),
21220                                              DSAStack->getOMPAllocatorHandleT(),
21221                                              Sema::AA_Initializing,
21222                                              /*AllowExplicit=*/true);
21223     if (AllocatorRes.isInvalid())
21224       return nullptr;
21225     Allocator = AllocatorRes.get();
21226   } else {
21227     // OpenMP 5.0, 2.11.4 allocate Clause, Restrictions.
21228     // allocate clauses that appear on a target construct or on constructs in a
21229     // target region must specify an allocator expression unless a requires
21230     // directive with the dynamic_allocators clause is present in the same
21231     // compilation unit.
21232     if (LangOpts.OpenMPIsDevice &&
21233         !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())
21234       targetDiag(StartLoc, diag::err_expected_allocator_expression);
21235   }
21236   // Analyze and build list of variables.
21237   SmallVector<Expr *, 8> Vars;
21238   for (Expr *RefExpr : VarList) {
21239     assert(RefExpr && "NULL expr in OpenMP private clause.");
21240     SourceLocation ELoc;
21241     SourceRange ERange;
21242     Expr *SimpleRefExpr = RefExpr;
21243     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
21244     if (Res.second) {
21245       // It will be analyzed later.
21246       Vars.push_back(RefExpr);
21247     }
21248     ValueDecl *D = Res.first;
21249     if (!D)
21250       continue;
21251 
21252     auto *VD = dyn_cast<VarDecl>(D);
21253     DeclRefExpr *Ref = nullptr;
21254     if (!VD && !CurContext->isDependentContext())
21255       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
21256     Vars.push_back((VD || CurContext->isDependentContext())
21257                        ? RefExpr->IgnoreParens()
21258                        : Ref);
21259   }
21260 
21261   if (Vars.empty())
21262     return nullptr;
21263 
21264   if (Allocator)
21265     DSAStack->addInnerAllocatorExpr(Allocator);
21266   return OMPAllocateClause::Create(Context, StartLoc, LParenLoc, Allocator,
21267                                    ColonLoc, EndLoc, Vars);
21268 }
21269 
21270 OMPClause *Sema::ActOnOpenMPNontemporalClause(ArrayRef<Expr *> VarList,
21271                                               SourceLocation StartLoc,
21272                                               SourceLocation LParenLoc,
21273                                               SourceLocation EndLoc) {
21274   SmallVector<Expr *, 8> Vars;
21275   for (Expr *RefExpr : VarList) {
21276     assert(RefExpr && "NULL expr in OpenMP nontemporal clause.");
21277     SourceLocation ELoc;
21278     SourceRange ERange;
21279     Expr *SimpleRefExpr = RefExpr;
21280     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
21281     if (Res.second)
21282       // It will be analyzed later.
21283       Vars.push_back(RefExpr);
21284     ValueDecl *D = Res.first;
21285     if (!D)
21286       continue;
21287 
21288     // OpenMP 5.0, 2.9.3.1 simd Construct, Restrictions.
21289     // A list-item cannot appear in more than one nontemporal clause.
21290     if (const Expr *PrevRef =
21291             DSAStack->addUniqueNontemporal(D, SimpleRefExpr)) {
21292       Diag(ELoc, diag::err_omp_used_in_clause_twice)
21293           << 0 << getOpenMPClauseName(OMPC_nontemporal) << ERange;
21294       Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
21295           << getOpenMPClauseName(OMPC_nontemporal);
21296       continue;
21297     }
21298 
21299     Vars.push_back(RefExpr);
21300   }
21301 
21302   if (Vars.empty())
21303     return nullptr;
21304 
21305   return OMPNontemporalClause::Create(Context, StartLoc, LParenLoc, EndLoc,
21306                                       Vars);
21307 }
21308 
21309 OMPClause *Sema::ActOnOpenMPInclusiveClause(ArrayRef<Expr *> VarList,
21310                                             SourceLocation StartLoc,
21311                                             SourceLocation LParenLoc,
21312                                             SourceLocation EndLoc) {
21313   SmallVector<Expr *, 8> Vars;
21314   for (Expr *RefExpr : VarList) {
21315     assert(RefExpr && "NULL expr in OpenMP nontemporal clause.");
21316     SourceLocation ELoc;
21317     SourceRange ERange;
21318     Expr *SimpleRefExpr = RefExpr;
21319     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
21320                               /*AllowArraySection=*/true);
21321     if (Res.second)
21322       // It will be analyzed later.
21323       Vars.push_back(RefExpr);
21324     ValueDecl *D = Res.first;
21325     if (!D)
21326       continue;
21327 
21328     const DSAStackTy::DSAVarData DVar =
21329         DSAStack->getTopDSA(D, /*FromParent=*/true);
21330     // OpenMP 5.0, 2.9.6, scan Directive, Restrictions.
21331     // A list item that appears in the inclusive or exclusive clause must appear
21332     // in a reduction clause with the inscan modifier on the enclosing
21333     // worksharing-loop, worksharing-loop SIMD, or simd construct.
21334     if (DVar.CKind != OMPC_reduction || DVar.Modifier != OMPC_REDUCTION_inscan)
21335       Diag(ELoc, diag::err_omp_inclusive_exclusive_not_reduction)
21336           << RefExpr->getSourceRange();
21337 
21338     if (DSAStack->getParentDirective() != OMPD_unknown)
21339       DSAStack->markDeclAsUsedInScanDirective(D);
21340     Vars.push_back(RefExpr);
21341   }
21342 
21343   if (Vars.empty())
21344     return nullptr;
21345 
21346   return OMPInclusiveClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
21347 }
21348 
21349 OMPClause *Sema::ActOnOpenMPExclusiveClause(ArrayRef<Expr *> VarList,
21350                                             SourceLocation StartLoc,
21351                                             SourceLocation LParenLoc,
21352                                             SourceLocation EndLoc) {
21353   SmallVector<Expr *, 8> Vars;
21354   for (Expr *RefExpr : VarList) {
21355     assert(RefExpr && "NULL expr in OpenMP nontemporal clause.");
21356     SourceLocation ELoc;
21357     SourceRange ERange;
21358     Expr *SimpleRefExpr = RefExpr;
21359     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
21360                               /*AllowArraySection=*/true);
21361     if (Res.second)
21362       // It will be analyzed later.
21363       Vars.push_back(RefExpr);
21364     ValueDecl *D = Res.first;
21365     if (!D)
21366       continue;
21367 
21368     OpenMPDirectiveKind ParentDirective = DSAStack->getParentDirective();
21369     DSAStackTy::DSAVarData DVar;
21370     if (ParentDirective != OMPD_unknown)
21371       DVar = DSAStack->getTopDSA(D, /*FromParent=*/true);
21372     // OpenMP 5.0, 2.9.6, scan Directive, Restrictions.
21373     // A list item that appears in the inclusive or exclusive clause must appear
21374     // in a reduction clause with the inscan modifier on the enclosing
21375     // worksharing-loop, worksharing-loop SIMD, or simd construct.
21376     if (ParentDirective == OMPD_unknown || DVar.CKind != OMPC_reduction ||
21377         DVar.Modifier != OMPC_REDUCTION_inscan) {
21378       Diag(ELoc, diag::err_omp_inclusive_exclusive_not_reduction)
21379           << RefExpr->getSourceRange();
21380     } else {
21381       DSAStack->markDeclAsUsedInScanDirective(D);
21382     }
21383     Vars.push_back(RefExpr);
21384   }
21385 
21386   if (Vars.empty())
21387     return nullptr;
21388 
21389   return OMPExclusiveClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
21390 }
21391 
21392 /// Tries to find omp_alloctrait_t type.
21393 static bool findOMPAlloctraitT(Sema &S, SourceLocation Loc, DSAStackTy *Stack) {
21394   QualType OMPAlloctraitT = Stack->getOMPAlloctraitT();
21395   if (!OMPAlloctraitT.isNull())
21396     return true;
21397   IdentifierInfo &II = S.PP.getIdentifierTable().get("omp_alloctrait_t");
21398   ParsedType PT = S.getTypeName(II, Loc, S.getCurScope());
21399   if (!PT.getAsOpaquePtr() || PT.get().isNull()) {
21400     S.Diag(Loc, diag::err_omp_implied_type_not_found) << "omp_alloctrait_t";
21401     return false;
21402   }
21403   Stack->setOMPAlloctraitT(PT.get());
21404   return true;
21405 }
21406 
21407 OMPClause *Sema::ActOnOpenMPUsesAllocatorClause(
21408     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc,
21409     ArrayRef<UsesAllocatorsData> Data) {
21410   // OpenMP [2.12.5, target Construct]
21411   // allocator is an identifier of omp_allocator_handle_t type.
21412   if (!findOMPAllocatorHandleT(*this, StartLoc, DSAStack))
21413     return nullptr;
21414   // OpenMP [2.12.5, target Construct]
21415   // allocator-traits-array is an identifier of const omp_alloctrait_t * type.
21416   if (llvm::any_of(
21417           Data,
21418           [](const UsesAllocatorsData &D) { return D.AllocatorTraits; }) &&
21419       !findOMPAlloctraitT(*this, StartLoc, DSAStack))
21420     return nullptr;
21421   llvm::SmallPtrSet<CanonicalDeclPtr<Decl>, 4> PredefinedAllocators;
21422   for (int I = 0; I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
21423     auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
21424     StringRef Allocator =
21425         OMPAllocateDeclAttr::ConvertAllocatorTypeTyToStr(AllocatorKind);
21426     DeclarationName AllocatorName = &Context.Idents.get(Allocator);
21427     PredefinedAllocators.insert(LookupSingleName(
21428         TUScope, AllocatorName, StartLoc, Sema::LookupAnyName));
21429   }
21430 
21431   SmallVector<OMPUsesAllocatorsClause::Data, 4> NewData;
21432   for (const UsesAllocatorsData &D : Data) {
21433     Expr *AllocatorExpr = nullptr;
21434     // Check allocator expression.
21435     if (D.Allocator->isTypeDependent()) {
21436       AllocatorExpr = D.Allocator;
21437     } else {
21438       // Traits were specified - need to assign new allocator to the specified
21439       // allocator, so it must be an lvalue.
21440       AllocatorExpr = D.Allocator->IgnoreParenImpCasts();
21441       auto *DRE = dyn_cast<DeclRefExpr>(AllocatorExpr);
21442       bool IsPredefinedAllocator = false;
21443       if (DRE)
21444         IsPredefinedAllocator = PredefinedAllocators.count(DRE->getDecl());
21445       if (!DRE ||
21446           !(Context.hasSameUnqualifiedType(
21447                 AllocatorExpr->getType(), DSAStack->getOMPAllocatorHandleT()) ||
21448             Context.typesAreCompatible(AllocatorExpr->getType(),
21449                                        DSAStack->getOMPAllocatorHandleT(),
21450                                        /*CompareUnqualified=*/true)) ||
21451           (!IsPredefinedAllocator &&
21452            (AllocatorExpr->getType().isConstant(Context) ||
21453             !AllocatorExpr->isLValue()))) {
21454         Diag(D.Allocator->getExprLoc(), diag::err_omp_var_expected)
21455             << "omp_allocator_handle_t" << (DRE ? 1 : 0)
21456             << AllocatorExpr->getType() << D.Allocator->getSourceRange();
21457         continue;
21458       }
21459       // OpenMP [2.12.5, target Construct]
21460       // Predefined allocators appearing in a uses_allocators clause cannot have
21461       // traits specified.
21462       if (IsPredefinedAllocator && D.AllocatorTraits) {
21463         Diag(D.AllocatorTraits->getExprLoc(),
21464              diag::err_omp_predefined_allocator_with_traits)
21465             << D.AllocatorTraits->getSourceRange();
21466         Diag(D.Allocator->getExprLoc(), diag::note_omp_predefined_allocator)
21467             << cast<NamedDecl>(DRE->getDecl())->getName()
21468             << D.Allocator->getSourceRange();
21469         continue;
21470       }
21471       // OpenMP [2.12.5, target Construct]
21472       // Non-predefined allocators appearing in a uses_allocators clause must
21473       // have traits specified.
21474       if (!IsPredefinedAllocator && !D.AllocatorTraits) {
21475         Diag(D.Allocator->getExprLoc(),
21476              diag::err_omp_nonpredefined_allocator_without_traits);
21477         continue;
21478       }
21479       // No allocator traits - just convert it to rvalue.
21480       if (!D.AllocatorTraits)
21481         AllocatorExpr = DefaultLvalueConversion(AllocatorExpr).get();
21482       DSAStack->addUsesAllocatorsDecl(
21483           DRE->getDecl(),
21484           IsPredefinedAllocator
21485               ? DSAStackTy::UsesAllocatorsDeclKind::PredefinedAllocator
21486               : DSAStackTy::UsesAllocatorsDeclKind::UserDefinedAllocator);
21487     }
21488     Expr *AllocatorTraitsExpr = nullptr;
21489     if (D.AllocatorTraits) {
21490       if (D.AllocatorTraits->isTypeDependent()) {
21491         AllocatorTraitsExpr = D.AllocatorTraits;
21492       } else {
21493         // OpenMP [2.12.5, target Construct]
21494         // Arrays that contain allocator traits that appear in a uses_allocators
21495         // clause must be constant arrays, have constant values and be defined
21496         // in the same scope as the construct in which the clause appears.
21497         AllocatorTraitsExpr = D.AllocatorTraits->IgnoreParenImpCasts();
21498         // Check that traits expr is a constant array.
21499         QualType TraitTy;
21500         if (const ArrayType *Ty =
21501                 AllocatorTraitsExpr->getType()->getAsArrayTypeUnsafe())
21502           if (const auto *ConstArrayTy = dyn_cast<ConstantArrayType>(Ty))
21503             TraitTy = ConstArrayTy->getElementType();
21504         if (TraitTy.isNull() ||
21505             !(Context.hasSameUnqualifiedType(TraitTy,
21506                                              DSAStack->getOMPAlloctraitT()) ||
21507               Context.typesAreCompatible(TraitTy, DSAStack->getOMPAlloctraitT(),
21508                                          /*CompareUnqualified=*/true))) {
21509           Diag(D.AllocatorTraits->getExprLoc(),
21510                diag::err_omp_expected_array_alloctraits)
21511               << AllocatorTraitsExpr->getType();
21512           continue;
21513         }
21514         // Do not map by default allocator traits if it is a standalone
21515         // variable.
21516         if (auto *DRE = dyn_cast<DeclRefExpr>(AllocatorTraitsExpr))
21517           DSAStack->addUsesAllocatorsDecl(
21518               DRE->getDecl(),
21519               DSAStackTy::UsesAllocatorsDeclKind::AllocatorTrait);
21520       }
21521     }
21522     OMPUsesAllocatorsClause::Data &NewD = NewData.emplace_back();
21523     NewD.Allocator = AllocatorExpr;
21524     NewD.AllocatorTraits = AllocatorTraitsExpr;
21525     NewD.LParenLoc = D.LParenLoc;
21526     NewD.RParenLoc = D.RParenLoc;
21527   }
21528   return OMPUsesAllocatorsClause::Create(Context, StartLoc, LParenLoc, EndLoc,
21529                                          NewData);
21530 }
21531 
21532 OMPClause *Sema::ActOnOpenMPAffinityClause(
21533     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
21534     SourceLocation EndLoc, Expr *Modifier, ArrayRef<Expr *> Locators) {
21535   SmallVector<Expr *, 8> Vars;
21536   for (Expr *RefExpr : Locators) {
21537     assert(RefExpr && "NULL expr in OpenMP shared clause.");
21538     if (isa<DependentScopeDeclRefExpr>(RefExpr) || RefExpr->isTypeDependent()) {
21539       // It will be analyzed later.
21540       Vars.push_back(RefExpr);
21541       continue;
21542     }
21543 
21544     SourceLocation ELoc = RefExpr->getExprLoc();
21545     Expr *SimpleExpr = RefExpr->IgnoreParenImpCasts();
21546 
21547     if (!SimpleExpr->isLValue()) {
21548       Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
21549           << 1 << 0 << RefExpr->getSourceRange();
21550       continue;
21551     }
21552 
21553     ExprResult Res;
21554     {
21555       Sema::TentativeAnalysisScope Trap(*this);
21556       Res = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, SimpleExpr);
21557     }
21558     if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr) &&
21559         !isa<OMPArrayShapingExpr>(SimpleExpr)) {
21560       Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
21561           << 1 << 0 << RefExpr->getSourceRange();
21562       continue;
21563     }
21564     Vars.push_back(SimpleExpr);
21565   }
21566 
21567   return OMPAffinityClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
21568                                    EndLoc, Modifier, Vars);
21569 }
21570 
21571 OMPClause *Sema::ActOnOpenMPBindClause(OpenMPBindClauseKind Kind,
21572                                        SourceLocation KindLoc,
21573                                        SourceLocation StartLoc,
21574                                        SourceLocation LParenLoc,
21575                                        SourceLocation EndLoc) {
21576   if (Kind == OMPC_BIND_unknown) {
21577     Diag(KindLoc, diag::err_omp_unexpected_clause_value)
21578         << getListOfPossibleValues(OMPC_bind, /*First=*/0,
21579                                    /*Last=*/unsigned(OMPC_BIND_unknown))
21580         << getOpenMPClauseName(OMPC_bind);
21581     return nullptr;
21582   }
21583 
21584   return OMPBindClause::Create(Context, Kind, KindLoc, StartLoc, LParenLoc,
21585                                EndLoc);
21586 }
21587