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 
314 public:
315   explicit DSAStackTy(Sema &S) : SemaRef(S) {}
316 
317   /// Sets omp_allocator_handle_t type.
318   void setOMPAllocatorHandleT(QualType Ty) { OMPAllocatorHandleT = Ty; }
319   /// Gets omp_allocator_handle_t type.
320   QualType getOMPAllocatorHandleT() const { return OMPAllocatorHandleT; }
321   /// Sets omp_alloctrait_t type.
322   void setOMPAlloctraitT(QualType Ty) { OMPAlloctraitT = Ty; }
323   /// Gets omp_alloctrait_t type.
324   QualType getOMPAlloctraitT() const { return OMPAlloctraitT; }
325   /// Sets the given default allocator.
326   void setAllocator(OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind,
327                     Expr *Allocator) {
328     OMPPredefinedAllocators[AllocatorKind] = Allocator;
329   }
330   /// Returns the specified default allocator.
331   Expr *getAllocator(OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind) const {
332     return OMPPredefinedAllocators[AllocatorKind];
333   }
334   /// Sets omp_depend_t type.
335   void setOMPDependT(QualType Ty) { OMPDependT = Ty; }
336   /// Gets omp_depend_t type.
337   QualType getOMPDependT() const { return OMPDependT; }
338 
339   /// Sets omp_event_handle_t type.
340   void setOMPEventHandleT(QualType Ty) { OMPEventHandleT = Ty; }
341   /// Gets omp_event_handle_t type.
342   QualType getOMPEventHandleT() const { return OMPEventHandleT; }
343 
344   bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
345   OpenMPClauseKind getClauseParsingMode() const {
346     assert(isClauseParsingMode() && "Must be in clause parsing mode.");
347     return ClauseKindMode;
348   }
349   void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
350 
351   bool isBodyComplete() const {
352     const SharingMapTy *Top = getTopOfStackOrNull();
353     return Top && Top->BodyComplete;
354   }
355   void setBodyComplete() {
356     getTopOfStack().BodyComplete = true;
357   }
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   public:
394     ParentDirectiveScope(DSAStackTy &Self, bool Activate)
395         : Self(Self), Active(false) {
396       if (Activate)
397         enable();
398     }
399     ~ParentDirectiveScope() { disable(); }
400     void disable() {
401       if (Active) {
402         --Self.IgnoredStackElements;
403         Active = false;
404       }
405     }
406     void enable() {
407       if (!Active) {
408         ++Self.IgnoredStackElements;
409         Active = true;
410       }
411     }
412   };
413 
414   /// Marks that we're started loop parsing.
415   void loopInit() {
416     assert(isOpenMPLoopDirective(getCurrentDirective()) &&
417            "Expected loop-based directive.");
418     getTopOfStack().LoopStart = true;
419   }
420   /// Start capturing of the variables in the loop context.
421   void loopStart() {
422     assert(isOpenMPLoopDirective(getCurrentDirective()) &&
423            "Expected loop-based directive.");
424     getTopOfStack().LoopStart = false;
425   }
426   /// true, if variables are captured, false otherwise.
427   bool isLoopStarted() const {
428     assert(isOpenMPLoopDirective(getCurrentDirective()) &&
429            "Expected loop-based directive.");
430     return !getTopOfStack().LoopStart;
431   }
432   /// Marks (or clears) declaration as possibly loop counter.
433   void resetPossibleLoopCounter(const Decl *D = nullptr) {
434     getTopOfStack().PossiblyLoopCounter =
435         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.count(D) > 0;
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) {
633     RequiresDecls.push_back(RD);
634   }
635 
636   /// Checks if the defined 'requires' directive has specified type of clause.
637   template <typename ClauseType>
638   bool hasRequiresDeclWithClause() const {
639     return llvm::any_of(RequiresDecls, [](const OMPRequiresDecl *D) {
640       return llvm::any_of(D->clauselists(), [](const OMPClause *C) {
641         return isa<ClauseType>(C);
642       });
643     });
644   }
645 
646   /// Checks for a duplicate clause amongst previously declared requires
647   /// directives
648   bool hasDuplicateRequiresClause(ArrayRef<OMPClause *> ClauseList) const {
649     bool IsDuplicate = false;
650     for (OMPClause *CNew : ClauseList) {
651       for (const OMPRequiresDecl *D : RequiresDecls) {
652         for (const OMPClause *CPrev : D->clauselists()) {
653           if (CNew->getClauseKind() == CPrev->getClauseKind()) {
654             SemaRef.Diag(CNew->getBeginLoc(),
655                          diag::err_omp_requires_clause_redeclaration)
656                 << getOpenMPClauseName(CNew->getClauseKind());
657             SemaRef.Diag(CPrev->getBeginLoc(),
658                          diag::note_omp_requires_previous_clause)
659                 << getOpenMPClauseName(CPrev->getClauseKind());
660             IsDuplicate = true;
661           }
662         }
663       }
664     }
665     return IsDuplicate;
666   }
667 
668   /// Add location of previously encountered target to internal vector
669   void addTargetDirLocation(SourceLocation LocStart) {
670     TargetLocations.push_back(LocStart);
671   }
672 
673   /// Add location for the first encountered atomicc directive.
674   void addAtomicDirectiveLoc(SourceLocation Loc) {
675     if (AtomicLocation.isInvalid())
676       AtomicLocation = Loc;
677   }
678 
679   /// Returns the location of the first encountered atomic directive in the
680   /// module.
681   SourceLocation getAtomicDirectiveLoc() const {
682     return AtomicLocation;
683   }
684 
685   // Return previously encountered target region locations.
686   ArrayRef<SourceLocation> getEncounteredTargetLocs() const {
687     return TargetLocations;
688   }
689 
690   /// Set default data sharing attribute to none.
691   void setDefaultDSANone(SourceLocation Loc) {
692     getTopOfStack().DefaultAttr = DSA_none;
693     getTopOfStack().DefaultAttrLoc = Loc;
694   }
695   /// Set default data sharing attribute to shared.
696   void setDefaultDSAShared(SourceLocation Loc) {
697     getTopOfStack().DefaultAttr = DSA_shared;
698     getTopOfStack().DefaultAttrLoc = Loc;
699   }
700   /// Set default data sharing attribute to firstprivate.
701   void setDefaultDSAFirstPrivate(SourceLocation Loc) {
702     getTopOfStack().DefaultAttr = DSA_firstprivate;
703     getTopOfStack().DefaultAttrLoc = Loc;
704   }
705   /// Set default data mapping attribute to Modifier:Kind
706   void setDefaultDMAAttr(OpenMPDefaultmapClauseModifier M,
707                          OpenMPDefaultmapClauseKind Kind,
708                          SourceLocation Loc) {
709     DefaultmapInfo &DMI = getTopOfStack().DefaultmapMap[Kind];
710     DMI.ImplicitBehavior = M;
711     DMI.SLoc = Loc;
712   }
713   /// Check whether the implicit-behavior has been set in defaultmap
714   bool checkDefaultmapCategory(OpenMPDefaultmapClauseKind VariableCategory) {
715     if (VariableCategory == OMPC_DEFAULTMAP_unknown)
716       return getTopOfStack()
717                      .DefaultmapMap[OMPC_DEFAULTMAP_aggregate]
718                      .ImplicitBehavior != OMPC_DEFAULTMAP_MODIFIER_unknown ||
719              getTopOfStack()
720                      .DefaultmapMap[OMPC_DEFAULTMAP_scalar]
721                      .ImplicitBehavior != OMPC_DEFAULTMAP_MODIFIER_unknown ||
722              getTopOfStack()
723                      .DefaultmapMap[OMPC_DEFAULTMAP_pointer]
724                      .ImplicitBehavior != OMPC_DEFAULTMAP_MODIFIER_unknown;
725     return getTopOfStack().DefaultmapMap[VariableCategory].ImplicitBehavior !=
726            OMPC_DEFAULTMAP_MODIFIER_unknown;
727   }
728 
729   DefaultDataSharingAttributes getDefaultDSA(unsigned Level) const {
730     return getStackSize() <= Level ? DSA_unspecified
731                                    : getStackElemAtLevel(Level).DefaultAttr;
732   }
733   DefaultDataSharingAttributes getDefaultDSA() const {
734     return isStackEmpty() ? DSA_unspecified
735                           : getTopOfStack().DefaultAttr;
736   }
737   SourceLocation getDefaultDSALocation() const {
738     return isStackEmpty() ? SourceLocation()
739                           : getTopOfStack().DefaultAttrLoc;
740   }
741   OpenMPDefaultmapClauseModifier
742   getDefaultmapModifier(OpenMPDefaultmapClauseKind Kind) const {
743     return isStackEmpty()
744                ? OMPC_DEFAULTMAP_MODIFIER_unknown
745                : getTopOfStack().DefaultmapMap[Kind].ImplicitBehavior;
746   }
747   OpenMPDefaultmapClauseModifier
748   getDefaultmapModifierAtLevel(unsigned Level,
749                                OpenMPDefaultmapClauseKind Kind) const {
750     return getStackElemAtLevel(Level).DefaultmapMap[Kind].ImplicitBehavior;
751   }
752   bool isDefaultmapCapturedByRef(unsigned Level,
753                                  OpenMPDefaultmapClauseKind Kind) const {
754     OpenMPDefaultmapClauseModifier M =
755         getDefaultmapModifierAtLevel(Level, Kind);
756     if (Kind == OMPC_DEFAULTMAP_scalar || Kind == OMPC_DEFAULTMAP_pointer) {
757       return (M == OMPC_DEFAULTMAP_MODIFIER_alloc) ||
758              (M == OMPC_DEFAULTMAP_MODIFIER_to) ||
759              (M == OMPC_DEFAULTMAP_MODIFIER_from) ||
760              (M == OMPC_DEFAULTMAP_MODIFIER_tofrom);
761     }
762     return true;
763   }
764   static bool mustBeFirstprivateBase(OpenMPDefaultmapClauseModifier M,
765                                      OpenMPDefaultmapClauseKind Kind) {
766     switch (Kind) {
767     case OMPC_DEFAULTMAP_scalar:
768     case OMPC_DEFAULTMAP_pointer:
769       return (M == OMPC_DEFAULTMAP_MODIFIER_unknown) ||
770              (M == OMPC_DEFAULTMAP_MODIFIER_firstprivate) ||
771              (M == OMPC_DEFAULTMAP_MODIFIER_default);
772     case OMPC_DEFAULTMAP_aggregate:
773       return M == OMPC_DEFAULTMAP_MODIFIER_firstprivate;
774     default:
775       break;
776     }
777     llvm_unreachable("Unexpected OpenMPDefaultmapClauseKind enum");
778   }
779   bool mustBeFirstprivateAtLevel(unsigned Level,
780                                  OpenMPDefaultmapClauseKind Kind) const {
781     OpenMPDefaultmapClauseModifier M =
782         getDefaultmapModifierAtLevel(Level, Kind);
783     return mustBeFirstprivateBase(M, Kind);
784   }
785   bool mustBeFirstprivate(OpenMPDefaultmapClauseKind Kind) const {
786     OpenMPDefaultmapClauseModifier M = getDefaultmapModifier(Kind);
787     return mustBeFirstprivateBase(M, Kind);
788   }
789 
790   /// Checks if the specified variable is a threadprivate.
791   bool isThreadPrivate(VarDecl *D) {
792     const DSAVarData DVar = getTopDSA(D, false);
793     return isOpenMPThreadPrivate(DVar.CKind);
794   }
795 
796   /// Marks current region as ordered (it has an 'ordered' clause).
797   void setOrderedRegion(bool IsOrdered, const Expr *Param,
798                         OMPOrderedClause *Clause) {
799     if (IsOrdered)
800       getTopOfStack().OrderedRegion.emplace(Param, Clause);
801     else
802       getTopOfStack().OrderedRegion.reset();
803   }
804   /// Returns true, if region is ordered (has associated 'ordered' clause),
805   /// false - otherwise.
806   bool isOrderedRegion() const {
807     if (const SharingMapTy *Top = getTopOfStackOrNull())
808       return Top->OrderedRegion.hasValue();
809     return false;
810   }
811   /// Returns optional parameter for the ordered region.
812   std::pair<const Expr *, OMPOrderedClause *> getOrderedRegionParam() const {
813     if (const SharingMapTy *Top = getTopOfStackOrNull())
814       if (Top->OrderedRegion.hasValue())
815         return Top->OrderedRegion.getValue();
816     return std::make_pair(nullptr, nullptr);
817   }
818   /// Returns true, if parent region is ordered (has associated
819   /// 'ordered' clause), false - otherwise.
820   bool isParentOrderedRegion() const {
821     if (const SharingMapTy *Parent = getSecondOnStackOrNull())
822       return Parent->OrderedRegion.hasValue();
823     return false;
824   }
825   /// Returns optional parameter for the ordered region.
826   std::pair<const Expr *, OMPOrderedClause *>
827   getParentOrderedRegionParam() const {
828     if (const SharingMapTy *Parent = getSecondOnStackOrNull())
829       if (Parent->OrderedRegion.hasValue())
830         return Parent->OrderedRegion.getValue();
831     return std::make_pair(nullptr, nullptr);
832   }
833   /// Marks current region as nowait (it has a 'nowait' clause).
834   void setNowaitRegion(bool IsNowait = true) {
835     getTopOfStack().NowaitRegion = IsNowait;
836   }
837   /// Returns true, if parent region is nowait (has associated
838   /// 'nowait' clause), false - otherwise.
839   bool isParentNowaitRegion() const {
840     if (const SharingMapTy *Parent = getSecondOnStackOrNull())
841       return Parent->NowaitRegion;
842     return false;
843   }
844   /// Marks parent region as cancel region.
845   void setParentCancelRegion(bool Cancel = true) {
846     if (SharingMapTy *Parent = getSecondOnStackOrNull())
847       Parent->CancelRegion |= Cancel;
848   }
849   /// Return true if current region has inner cancel construct.
850   bool isCancelRegion() const {
851     const SharingMapTy *Top = getTopOfStackOrNull();
852     return Top ? Top->CancelRegion : false;
853   }
854 
855   /// Mark that parent region already has scan directive.
856   void setParentHasScanDirective(SourceLocation Loc) {
857     if (SharingMapTy *Parent = getSecondOnStackOrNull())
858       Parent->PrevScanLocation = Loc;
859   }
860   /// Return true if current region has inner cancel construct.
861   bool doesParentHasScanDirective() const {
862     const SharingMapTy *Top = getSecondOnStackOrNull();
863     return Top ? Top->PrevScanLocation.isValid() : false;
864   }
865   /// Return true if current region has inner cancel construct.
866   SourceLocation getParentScanDirectiveLoc() const {
867     const SharingMapTy *Top = getSecondOnStackOrNull();
868     return Top ? Top->PrevScanLocation : SourceLocation();
869   }
870   /// Mark that parent region already has ordered directive.
871   void setParentHasOrderedDirective(SourceLocation Loc) {
872     if (SharingMapTy *Parent = getSecondOnStackOrNull())
873       Parent->PrevOrderedLocation = Loc;
874   }
875   /// Return true if current region has inner ordered construct.
876   bool doesParentHasOrderedDirective() const {
877     const SharingMapTy *Top = getSecondOnStackOrNull();
878     return Top ? Top->PrevOrderedLocation.isValid() : false;
879   }
880   /// Returns the location of the previously specified ordered directive.
881   SourceLocation getParentOrderedDirectiveLoc() const {
882     const SharingMapTy *Top = getSecondOnStackOrNull();
883     return Top ? Top->PrevOrderedLocation : SourceLocation();
884   }
885 
886   /// Set collapse value for the region.
887   void setAssociatedLoops(unsigned Val) {
888     getTopOfStack().AssociatedLoops = Val;
889     if (Val > 1)
890       getTopOfStack().HasMutipleLoops = true;
891   }
892   /// Return collapse value for region.
893   unsigned getAssociatedLoops() const {
894     const SharingMapTy *Top = getTopOfStackOrNull();
895     return Top ? Top->AssociatedLoops : 0;
896   }
897   /// Returns true if the construct is associated with multiple loops.
898   bool hasMutipleLoops() const {
899     const SharingMapTy *Top = getTopOfStackOrNull();
900     return Top ? Top->HasMutipleLoops : false;
901   }
902 
903   /// Marks current target region as one with closely nested teams
904   /// region.
905   void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
906     if (SharingMapTy *Parent = getSecondOnStackOrNull())
907       Parent->InnerTeamsRegionLoc = TeamsRegionLoc;
908   }
909   /// Returns true, if current region has closely nested teams region.
910   bool hasInnerTeamsRegion() const {
911     return getInnerTeamsRegionLoc().isValid();
912   }
913   /// Returns location of the nested teams region (if any).
914   SourceLocation getInnerTeamsRegionLoc() const {
915     const SharingMapTy *Top = getTopOfStackOrNull();
916     return Top ? Top->InnerTeamsRegionLoc : SourceLocation();
917   }
918 
919   Scope *getCurScope() const {
920     const SharingMapTy *Top = getTopOfStackOrNull();
921     return Top ? Top->CurScope : nullptr;
922   }
923   void setContext(DeclContext *DC) { getTopOfStack().Context = DC; }
924   SourceLocation getConstructLoc() const {
925     const SharingMapTy *Top = getTopOfStackOrNull();
926     return Top ? Top->ConstructLoc : SourceLocation();
927   }
928 
929   /// Do the check specified in \a Check to all component lists and return true
930   /// if any issue is found.
931   bool checkMappableExprComponentListsForDecl(
932       const ValueDecl *VD, bool CurrentRegionOnly,
933       const llvm::function_ref<
934           bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
935                OpenMPClauseKind)>
936           Check) const {
937     if (isStackEmpty())
938       return false;
939     auto SI = begin();
940     auto SE = end();
941 
942     if (SI == SE)
943       return false;
944 
945     if (CurrentRegionOnly)
946       SE = std::next(SI);
947     else
948       std::advance(SI, 1);
949 
950     for (; SI != SE; ++SI) {
951       auto MI = SI->MappedExprComponents.find(VD);
952       if (MI != SI->MappedExprComponents.end())
953         for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
954              MI->second.Components)
955           if (Check(L, MI->second.Kind))
956             return true;
957     }
958     return false;
959   }
960 
961   /// Do the check specified in \a Check to all component lists at a given level
962   /// and return true if any issue is found.
963   bool checkMappableExprComponentListsForDeclAtLevel(
964       const ValueDecl *VD, unsigned Level,
965       const llvm::function_ref<
966           bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
967                OpenMPClauseKind)>
968           Check) const {
969     if (getStackSize() <= Level)
970       return false;
971 
972     const SharingMapTy &StackElem = getStackElemAtLevel(Level);
973     auto MI = StackElem.MappedExprComponents.find(VD);
974     if (MI != StackElem.MappedExprComponents.end())
975       for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
976            MI->second.Components)
977         if (Check(L, MI->second.Kind))
978           return true;
979     return false;
980   }
981 
982   /// Create a new mappable expression component list associated with a given
983   /// declaration and initialize it with the provided list of components.
984   void addMappableExpressionComponents(
985       const ValueDecl *VD,
986       OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
987       OpenMPClauseKind WhereFoundClauseKind) {
988     MappedExprComponentTy &MEC = getTopOfStack().MappedExprComponents[VD];
989     // Create new entry and append the new components there.
990     MEC.Components.resize(MEC.Components.size() + 1);
991     MEC.Components.back().append(Components.begin(), Components.end());
992     MEC.Kind = WhereFoundClauseKind;
993   }
994 
995   unsigned getNestingLevel() const {
996     assert(!isStackEmpty());
997     return getStackSize() - 1;
998   }
999   void addDoacrossDependClause(OMPDependClause *C,
1000                                const OperatorOffsetTy &OpsOffs) {
1001     SharingMapTy *Parent = getSecondOnStackOrNull();
1002     assert(Parent && isOpenMPWorksharingDirective(Parent->Directive));
1003     Parent->DoacrossDepends.try_emplace(C, OpsOffs);
1004   }
1005   llvm::iterator_range<DoacrossDependMapTy::const_iterator>
1006   getDoacrossDependClauses() const {
1007     const SharingMapTy &StackElem = getTopOfStack();
1008     if (isOpenMPWorksharingDirective(StackElem.Directive)) {
1009       const DoacrossDependMapTy &Ref = StackElem.DoacrossDepends;
1010       return llvm::make_range(Ref.begin(), Ref.end());
1011     }
1012     return llvm::make_range(StackElem.DoacrossDepends.end(),
1013                             StackElem.DoacrossDepends.end());
1014   }
1015 
1016   // Store types of classes which have been explicitly mapped
1017   void addMappedClassesQualTypes(QualType QT) {
1018     SharingMapTy &StackElem = getTopOfStack();
1019     StackElem.MappedClassesQualTypes.insert(QT);
1020   }
1021 
1022   // Return set of mapped classes types
1023   bool isClassPreviouslyMapped(QualType QT) const {
1024     const SharingMapTy &StackElem = getTopOfStack();
1025     return StackElem.MappedClassesQualTypes.count(QT) != 0;
1026   }
1027 
1028   /// Adds global declare target to the parent target region.
1029   void addToParentTargetRegionLinkGlobals(DeclRefExpr *E) {
1030     assert(*OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
1031                E->getDecl()) == OMPDeclareTargetDeclAttr::MT_Link &&
1032            "Expected declare target link global.");
1033     for (auto &Elem : *this) {
1034       if (isOpenMPTargetExecutionDirective(Elem.Directive)) {
1035         Elem.DeclareTargetLinkVarDecls.push_back(E);
1036         return;
1037       }
1038     }
1039   }
1040 
1041   /// Returns the list of globals with declare target link if current directive
1042   /// is target.
1043   ArrayRef<DeclRefExpr *> getLinkGlobals() const {
1044     assert(isOpenMPTargetExecutionDirective(getCurrentDirective()) &&
1045            "Expected target executable directive.");
1046     return getTopOfStack().DeclareTargetLinkVarDecls;
1047   }
1048 
1049   /// Adds list of allocators expressions.
1050   void addInnerAllocatorExpr(Expr *E) {
1051     getTopOfStack().InnerUsedAllocators.push_back(E);
1052   }
1053   /// Return list of used allocators.
1054   ArrayRef<Expr *> getInnerAllocators() const {
1055     return getTopOfStack().InnerUsedAllocators;
1056   }
1057   /// Marks the declaration as implicitly firstprivate nin the task-based
1058   /// regions.
1059   void addImplicitTaskFirstprivate(unsigned Level, Decl *D) {
1060     getStackElemAtLevel(Level).ImplicitTaskFirstprivates.insert(D);
1061   }
1062   /// Checks if the decl is implicitly firstprivate in the task-based region.
1063   bool isImplicitTaskFirstprivate(Decl *D) const {
1064     return getTopOfStack().ImplicitTaskFirstprivates.count(D) > 0;
1065   }
1066 
1067   /// Marks decl as used in uses_allocators clause as the allocator.
1068   void addUsesAllocatorsDecl(const Decl *D, UsesAllocatorsDeclKind Kind) {
1069     getTopOfStack().UsesAllocatorsDecls.try_emplace(D, Kind);
1070   }
1071   /// Checks if specified decl is used in uses allocator clause as the
1072   /// allocator.
1073   Optional<UsesAllocatorsDeclKind> isUsesAllocatorsDecl(unsigned Level,
1074                                                         const Decl *D) const {
1075     const SharingMapTy &StackElem = getTopOfStack();
1076     auto I = StackElem.UsesAllocatorsDecls.find(D);
1077     if (I == StackElem.UsesAllocatorsDecls.end())
1078       return None;
1079     return I->getSecond();
1080   }
1081   Optional<UsesAllocatorsDeclKind> isUsesAllocatorsDecl(const Decl *D) const {
1082     const SharingMapTy &StackElem = getTopOfStack();
1083     auto I = StackElem.UsesAllocatorsDecls.find(D);
1084     if (I == StackElem.UsesAllocatorsDecls.end())
1085       return None;
1086     return I->getSecond();
1087   }
1088 
1089   void addDeclareMapperVarRef(Expr *Ref) {
1090     SharingMapTy &StackElem = getTopOfStack();
1091     StackElem.DeclareMapperVar = Ref;
1092   }
1093   const Expr *getDeclareMapperVarRef() const {
1094     const SharingMapTy *Top = getTopOfStackOrNull();
1095     return Top ? Top->DeclareMapperVar : nullptr;
1096   }
1097 };
1098 
1099 bool isImplicitTaskingRegion(OpenMPDirectiveKind DKind) {
1100   return isOpenMPParallelDirective(DKind) || isOpenMPTeamsDirective(DKind);
1101 }
1102 
1103 bool isImplicitOrExplicitTaskingRegion(OpenMPDirectiveKind DKind) {
1104   return isImplicitTaskingRegion(DKind) || isOpenMPTaskingDirective(DKind) ||
1105          DKind == OMPD_unknown;
1106 }
1107 
1108 } // namespace
1109 
1110 static const Expr *getExprAsWritten(const Expr *E) {
1111   if (const auto *FE = dyn_cast<FullExpr>(E))
1112     E = FE->getSubExpr();
1113 
1114   if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
1115     E = MTE->getSubExpr();
1116 
1117   while (const auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
1118     E = Binder->getSubExpr();
1119 
1120   if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
1121     E = ICE->getSubExprAsWritten();
1122   return E->IgnoreParens();
1123 }
1124 
1125 static Expr *getExprAsWritten(Expr *E) {
1126   return const_cast<Expr *>(getExprAsWritten(const_cast<const Expr *>(E)));
1127 }
1128 
1129 static const ValueDecl *getCanonicalDecl(const ValueDecl *D) {
1130   if (const auto *CED = dyn_cast<OMPCapturedExprDecl>(D))
1131     if (const auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
1132       D = ME->getMemberDecl();
1133   const auto *VD = dyn_cast<VarDecl>(D);
1134   const auto *FD = dyn_cast<FieldDecl>(D);
1135   if (VD != nullptr) {
1136     VD = VD->getCanonicalDecl();
1137     D = VD;
1138   } else {
1139     assert(FD);
1140     FD = FD->getCanonicalDecl();
1141     D = FD;
1142   }
1143   return D;
1144 }
1145 
1146 static ValueDecl *getCanonicalDecl(ValueDecl *D) {
1147   return const_cast<ValueDecl *>(
1148       getCanonicalDecl(const_cast<const ValueDecl *>(D)));
1149 }
1150 
1151 DSAStackTy::DSAVarData DSAStackTy::getDSA(const_iterator &Iter,
1152                                           ValueDecl *D) const {
1153   D = getCanonicalDecl(D);
1154   auto *VD = dyn_cast<VarDecl>(D);
1155   const auto *FD = dyn_cast<FieldDecl>(D);
1156   DSAVarData DVar;
1157   if (Iter == end()) {
1158     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1159     // in a region but not in construct]
1160     //  File-scope or namespace-scope variables referenced in called routines
1161     //  in the region are shared unless they appear in a threadprivate
1162     //  directive.
1163     if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(VD))
1164       DVar.CKind = OMPC_shared;
1165 
1166     // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
1167     // in a region but not in construct]
1168     //  Variables with static storage duration that are declared in called
1169     //  routines in the region are shared.
1170     if (VD && VD->hasGlobalStorage())
1171       DVar.CKind = OMPC_shared;
1172 
1173     // Non-static data members are shared by default.
1174     if (FD)
1175       DVar.CKind = OMPC_shared;
1176 
1177     return DVar;
1178   }
1179 
1180   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1181   // in a Construct, C/C++, predetermined, p.1]
1182   // Variables with automatic storage duration that are declared in a scope
1183   // inside the construct are private.
1184   if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() &&
1185       (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) {
1186     DVar.CKind = OMPC_private;
1187     return DVar;
1188   }
1189 
1190   DVar.DKind = Iter->Directive;
1191   // Explicitly specified attributes and local variables with predetermined
1192   // attributes.
1193   if (Iter->SharingMap.count(D)) {
1194     const DSAInfo &Data = Iter->SharingMap.lookup(D);
1195     DVar.RefExpr = Data.RefExpr.getPointer();
1196     DVar.PrivateCopy = Data.PrivateCopy;
1197     DVar.CKind = Data.Attributes;
1198     DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
1199     DVar.Modifier = Data.Modifier;
1200     DVar.AppliedToPointee = Data.AppliedToPointee;
1201     return DVar;
1202   }
1203 
1204   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1205   // in a Construct, C/C++, implicitly determined, p.1]
1206   //  In a parallel or task construct, the data-sharing attributes of these
1207   //  variables are determined by the default clause, if present.
1208   switch (Iter->DefaultAttr) {
1209   case DSA_shared:
1210     DVar.CKind = OMPC_shared;
1211     DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
1212     return DVar;
1213   case DSA_none:
1214     return DVar;
1215   case DSA_firstprivate:
1216     if (VD->getStorageDuration() == SD_Static &&
1217         VD->getDeclContext()->isFileContext()) {
1218       DVar.CKind = OMPC_unknown;
1219     } else {
1220       DVar.CKind = OMPC_firstprivate;
1221     }
1222     DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
1223     return DVar;
1224   case DSA_unspecified:
1225     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1226     // in a Construct, implicitly determined, p.2]
1227     //  In a parallel construct, if no default clause is present, these
1228     //  variables are shared.
1229     DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
1230     if ((isOpenMPParallelDirective(DVar.DKind) &&
1231          !isOpenMPTaskLoopDirective(DVar.DKind)) ||
1232         isOpenMPTeamsDirective(DVar.DKind)) {
1233       DVar.CKind = OMPC_shared;
1234       return DVar;
1235     }
1236 
1237     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1238     // in a Construct, implicitly determined, p.4]
1239     //  In a task construct, if no default clause is present, a variable that in
1240     //  the enclosing context is determined to be shared by all implicit tasks
1241     //  bound to the current team is shared.
1242     if (isOpenMPTaskingDirective(DVar.DKind)) {
1243       DSAVarData DVarTemp;
1244       const_iterator I = Iter, E = end();
1245       do {
1246         ++I;
1247         // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
1248         // Referenced in a Construct, implicitly determined, p.6]
1249         //  In a task construct, if no default clause is present, a variable
1250         //  whose data-sharing attribute is not determined by the rules above is
1251         //  firstprivate.
1252         DVarTemp = getDSA(I, D);
1253         if (DVarTemp.CKind != OMPC_shared) {
1254           DVar.RefExpr = nullptr;
1255           DVar.CKind = OMPC_firstprivate;
1256           return DVar;
1257         }
1258       } while (I != E && !isImplicitTaskingRegion(I->Directive));
1259       DVar.CKind =
1260           (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
1261       return DVar;
1262     }
1263   }
1264   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1265   // in a Construct, implicitly determined, p.3]
1266   //  For constructs other than task, if no default clause is present, these
1267   //  variables inherit their data-sharing attributes from the enclosing
1268   //  context.
1269   return getDSA(++Iter, D);
1270 }
1271 
1272 const Expr *DSAStackTy::addUniqueAligned(const ValueDecl *D,
1273                                          const Expr *NewDE) {
1274   assert(!isStackEmpty() && "Data sharing attributes stack is empty");
1275   D = getCanonicalDecl(D);
1276   SharingMapTy &StackElem = getTopOfStack();
1277   auto It = StackElem.AlignedMap.find(D);
1278   if (It == StackElem.AlignedMap.end()) {
1279     assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
1280     StackElem.AlignedMap[D] = NewDE;
1281     return nullptr;
1282   }
1283   assert(It->second && "Unexpected nullptr expr in the aligned map");
1284   return It->second;
1285 }
1286 
1287 const Expr *DSAStackTy::addUniqueNontemporal(const ValueDecl *D,
1288                                              const Expr *NewDE) {
1289   assert(!isStackEmpty() && "Data sharing attributes stack is empty");
1290   D = getCanonicalDecl(D);
1291   SharingMapTy &StackElem = getTopOfStack();
1292   auto It = StackElem.NontemporalMap.find(D);
1293   if (It == StackElem.NontemporalMap.end()) {
1294     assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
1295     StackElem.NontemporalMap[D] = NewDE;
1296     return nullptr;
1297   }
1298   assert(It->second && "Unexpected nullptr expr in the aligned map");
1299   return It->second;
1300 }
1301 
1302 void DSAStackTy::addLoopControlVariable(const ValueDecl *D, VarDecl *Capture) {
1303   assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
1304   D = getCanonicalDecl(D);
1305   SharingMapTy &StackElem = getTopOfStack();
1306   StackElem.LCVMap.try_emplace(
1307       D, LCDeclInfo(StackElem.LCVMap.size() + 1, Capture));
1308 }
1309 
1310 const DSAStackTy::LCDeclInfo
1311 DSAStackTy::isLoopControlVariable(const ValueDecl *D) const {
1312   assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
1313   D = getCanonicalDecl(D);
1314   const SharingMapTy &StackElem = getTopOfStack();
1315   auto It = StackElem.LCVMap.find(D);
1316   if (It != StackElem.LCVMap.end())
1317     return It->second;
1318   return {0, nullptr};
1319 }
1320 
1321 const DSAStackTy::LCDeclInfo
1322 DSAStackTy::isLoopControlVariable(const ValueDecl *D, unsigned Level) const {
1323   assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
1324   D = getCanonicalDecl(D);
1325   for (unsigned I = Level + 1; I > 0; --I) {
1326     const SharingMapTy &StackElem = getStackElemAtLevel(I - 1);
1327     auto It = StackElem.LCVMap.find(D);
1328     if (It != StackElem.LCVMap.end())
1329       return It->second;
1330   }
1331   return {0, nullptr};
1332 }
1333 
1334 const DSAStackTy::LCDeclInfo
1335 DSAStackTy::isParentLoopControlVariable(const ValueDecl *D) const {
1336   const SharingMapTy *Parent = getSecondOnStackOrNull();
1337   assert(Parent && "Data-sharing attributes stack is empty");
1338   D = getCanonicalDecl(D);
1339   auto It = Parent->LCVMap.find(D);
1340   if (It != Parent->LCVMap.end())
1341     return It->second;
1342   return {0, nullptr};
1343 }
1344 
1345 const ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) const {
1346   const SharingMapTy *Parent = getSecondOnStackOrNull();
1347   assert(Parent && "Data-sharing attributes stack is empty");
1348   if (Parent->LCVMap.size() < I)
1349     return nullptr;
1350   for (const auto &Pair : Parent->LCVMap)
1351     if (Pair.second.first == I)
1352       return Pair.first;
1353   return nullptr;
1354 }
1355 
1356 void DSAStackTy::addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
1357                         DeclRefExpr *PrivateCopy, unsigned Modifier,
1358                         bool AppliedToPointee) {
1359   D = getCanonicalDecl(D);
1360   if (A == OMPC_threadprivate) {
1361     DSAInfo &Data = Threadprivates[D];
1362     Data.Attributes = A;
1363     Data.RefExpr.setPointer(E);
1364     Data.PrivateCopy = nullptr;
1365     Data.Modifier = Modifier;
1366   } else {
1367     DSAInfo &Data = getTopOfStack().SharingMap[D];
1368     assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
1369            (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) ||
1370            (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) ||
1371            (isLoopControlVariable(D).first && A == OMPC_private));
1372     Data.Modifier = Modifier;
1373     if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) {
1374       Data.RefExpr.setInt(/*IntVal=*/true);
1375       return;
1376     }
1377     const bool IsLastprivate =
1378         A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate;
1379     Data.Attributes = A;
1380     Data.RefExpr.setPointerAndInt(E, IsLastprivate);
1381     Data.PrivateCopy = PrivateCopy;
1382     Data.AppliedToPointee = AppliedToPointee;
1383     if (PrivateCopy) {
1384       DSAInfo &Data = getTopOfStack().SharingMap[PrivateCopy->getDecl()];
1385       Data.Modifier = Modifier;
1386       Data.Attributes = A;
1387       Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate);
1388       Data.PrivateCopy = nullptr;
1389       Data.AppliedToPointee = AppliedToPointee;
1390     }
1391   }
1392 }
1393 
1394 /// Build a variable declaration for OpenMP loop iteration variable.
1395 static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
1396                              StringRef Name, const AttrVec *Attrs = nullptr,
1397                              DeclRefExpr *OrigRef = nullptr) {
1398   DeclContext *DC = SemaRef.CurContext;
1399   IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
1400   TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
1401   auto *Decl =
1402       VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
1403   if (Attrs) {
1404     for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
1405          I != E; ++I)
1406       Decl->addAttr(*I);
1407   }
1408   Decl->setImplicit();
1409   if (OrigRef) {
1410     Decl->addAttr(
1411         OMPReferencedVarAttr::CreateImplicit(SemaRef.Context, OrigRef));
1412   }
1413   return Decl;
1414 }
1415 
1416 static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
1417                                      SourceLocation Loc,
1418                                      bool RefersToCapture = false) {
1419   D->setReferenced();
1420   D->markUsed(S.Context);
1421   return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
1422                              SourceLocation(), D, RefersToCapture, Loc, Ty,
1423                              VK_LValue);
1424 }
1425 
1426 void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
1427                                            BinaryOperatorKind BOK) {
1428   D = getCanonicalDecl(D);
1429   assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
1430   assert(
1431       getTopOfStack().SharingMap[D].Attributes == OMPC_reduction &&
1432       "Additional reduction info may be specified only for reduction items.");
1433   ReductionData &ReductionData = getTopOfStack().ReductionMap[D];
1434   assert(ReductionData.ReductionRange.isInvalid() &&
1435          (getTopOfStack().Directive == OMPD_taskgroup ||
1436           ((isOpenMPParallelDirective(getTopOfStack().Directive) ||
1437             isOpenMPWorksharingDirective(getTopOfStack().Directive)) &&
1438            !isOpenMPSimdDirective(getTopOfStack().Directive))) &&
1439          "Additional reduction info may be specified only once for reduction "
1440          "items.");
1441   ReductionData.set(BOK, SR);
1442   Expr *&TaskgroupReductionRef =
1443       getTopOfStack().TaskgroupReductionRef;
1444   if (!TaskgroupReductionRef) {
1445     VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
1446                                SemaRef.Context.VoidPtrTy, ".task_red.");
1447     TaskgroupReductionRef =
1448         buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
1449   }
1450 }
1451 
1452 void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
1453                                            const Expr *ReductionRef) {
1454   D = getCanonicalDecl(D);
1455   assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
1456   assert(
1457       getTopOfStack().SharingMap[D].Attributes == OMPC_reduction &&
1458       "Additional reduction info may be specified only for reduction items.");
1459   ReductionData &ReductionData = getTopOfStack().ReductionMap[D];
1460   assert(ReductionData.ReductionRange.isInvalid() &&
1461          (getTopOfStack().Directive == OMPD_taskgroup ||
1462           ((isOpenMPParallelDirective(getTopOfStack().Directive) ||
1463             isOpenMPWorksharingDirective(getTopOfStack().Directive)) &&
1464            !isOpenMPSimdDirective(getTopOfStack().Directive))) &&
1465          "Additional reduction info may be specified only once for reduction "
1466          "items.");
1467   ReductionData.set(ReductionRef, SR);
1468   Expr *&TaskgroupReductionRef =
1469       getTopOfStack().TaskgroupReductionRef;
1470   if (!TaskgroupReductionRef) {
1471     VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
1472                                SemaRef.Context.VoidPtrTy, ".task_red.");
1473     TaskgroupReductionRef =
1474         buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
1475   }
1476 }
1477 
1478 const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
1479     const ValueDecl *D, SourceRange &SR, BinaryOperatorKind &BOK,
1480     Expr *&TaskgroupDescriptor) const {
1481   D = getCanonicalDecl(D);
1482   assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
1483   for (const_iterator I = begin() + 1, E = end(); I != E; ++I) {
1484     const DSAInfo &Data = I->SharingMap.lookup(D);
1485     if (Data.Attributes != OMPC_reduction ||
1486         Data.Modifier != OMPC_REDUCTION_task)
1487       continue;
1488     const ReductionData &ReductionData = I->ReductionMap.lookup(D);
1489     if (!ReductionData.ReductionOp ||
1490         ReductionData.ReductionOp.is<const Expr *>())
1491       return DSAVarData();
1492     SR = ReductionData.ReductionRange;
1493     BOK = ReductionData.ReductionOp.get<ReductionData::BOKPtrType>();
1494     assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
1495                                        "expression for the descriptor is not "
1496                                        "set.");
1497     TaskgroupDescriptor = I->TaskgroupReductionRef;
1498     return DSAVarData(I->Directive, OMPC_reduction, Data.RefExpr.getPointer(),
1499                       Data.PrivateCopy, I->DefaultAttrLoc, OMPC_REDUCTION_task,
1500                       /*AppliedToPointee=*/false);
1501   }
1502   return DSAVarData();
1503 }
1504 
1505 const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
1506     const ValueDecl *D, SourceRange &SR, const Expr *&ReductionRef,
1507     Expr *&TaskgroupDescriptor) const {
1508   D = getCanonicalDecl(D);
1509   assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
1510   for (const_iterator I = begin() + 1, E = end(); I != E; ++I) {
1511     const DSAInfo &Data = I->SharingMap.lookup(D);
1512     if (Data.Attributes != OMPC_reduction ||
1513         Data.Modifier != OMPC_REDUCTION_task)
1514       continue;
1515     const ReductionData &ReductionData = I->ReductionMap.lookup(D);
1516     if (!ReductionData.ReductionOp ||
1517         !ReductionData.ReductionOp.is<const Expr *>())
1518       return DSAVarData();
1519     SR = ReductionData.ReductionRange;
1520     ReductionRef = ReductionData.ReductionOp.get<const Expr *>();
1521     assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
1522                                        "expression for the descriptor is not "
1523                                        "set.");
1524     TaskgroupDescriptor = I->TaskgroupReductionRef;
1525     return DSAVarData(I->Directive, OMPC_reduction, Data.RefExpr.getPointer(),
1526                       Data.PrivateCopy, I->DefaultAttrLoc, OMPC_REDUCTION_task,
1527                       /*AppliedToPointee=*/false);
1528   }
1529   return DSAVarData();
1530 }
1531 
1532 bool DSAStackTy::isOpenMPLocal(VarDecl *D, const_iterator I) const {
1533   D = D->getCanonicalDecl();
1534   for (const_iterator E = end(); I != E; ++I) {
1535     if (isImplicitOrExplicitTaskingRegion(I->Directive) ||
1536         isOpenMPTargetExecutionDirective(I->Directive)) {
1537       if (I->CurScope) {
1538         Scope *TopScope = I->CurScope->getParent();
1539         Scope *CurScope = getCurScope();
1540         while (CurScope && CurScope != TopScope && !CurScope->isDeclScope(D))
1541           CurScope = CurScope->getParent();
1542         return CurScope != TopScope;
1543       }
1544       for (DeclContext *DC = D->getDeclContext(); DC; DC = DC->getParent())
1545         if (I->Context == DC)
1546           return true;
1547       return false;
1548     }
1549   }
1550   return false;
1551 }
1552 
1553 static bool isConstNotMutableType(Sema &SemaRef, QualType Type,
1554                                   bool AcceptIfMutable = true,
1555                                   bool *IsClassType = nullptr) {
1556   ASTContext &Context = SemaRef.getASTContext();
1557   Type = Type.getNonReferenceType().getCanonicalType();
1558   bool IsConstant = Type.isConstant(Context);
1559   Type = Context.getBaseElementType(Type);
1560   const CXXRecordDecl *RD = AcceptIfMutable && SemaRef.getLangOpts().CPlusPlus
1561                                 ? Type->getAsCXXRecordDecl()
1562                                 : nullptr;
1563   if (const auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
1564     if (const ClassTemplateDecl *CTD = CTSD->getSpecializedTemplate())
1565       RD = CTD->getTemplatedDecl();
1566   if (IsClassType)
1567     *IsClassType = RD;
1568   return IsConstant && !(SemaRef.getLangOpts().CPlusPlus && RD &&
1569                          RD->hasDefinition() && RD->hasMutableFields());
1570 }
1571 
1572 static bool rejectConstNotMutableType(Sema &SemaRef, const ValueDecl *D,
1573                                       QualType Type, OpenMPClauseKind CKind,
1574                                       SourceLocation ELoc,
1575                                       bool AcceptIfMutable = true,
1576                                       bool ListItemNotVar = false) {
1577   ASTContext &Context = SemaRef.getASTContext();
1578   bool IsClassType;
1579   if (isConstNotMutableType(SemaRef, Type, AcceptIfMutable, &IsClassType)) {
1580     unsigned Diag = ListItemNotVar
1581                         ? diag::err_omp_const_list_item
1582                         : IsClassType ? diag::err_omp_const_not_mutable_variable
1583                                       : diag::err_omp_const_variable;
1584     SemaRef.Diag(ELoc, Diag) << getOpenMPClauseName(CKind);
1585     if (!ListItemNotVar && D) {
1586       const VarDecl *VD = dyn_cast<VarDecl>(D);
1587       bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
1588                                VarDecl::DeclarationOnly;
1589       SemaRef.Diag(D->getLocation(),
1590                    IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1591           << D;
1592     }
1593     return true;
1594   }
1595   return false;
1596 }
1597 
1598 const DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D,
1599                                                    bool FromParent) {
1600   D = getCanonicalDecl(D);
1601   DSAVarData DVar;
1602 
1603   auto *VD = dyn_cast<VarDecl>(D);
1604   auto TI = Threadprivates.find(D);
1605   if (TI != Threadprivates.end()) {
1606     DVar.RefExpr = TI->getSecond().RefExpr.getPointer();
1607     DVar.CKind = OMPC_threadprivate;
1608     DVar.Modifier = TI->getSecond().Modifier;
1609     return DVar;
1610   }
1611   if (VD && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
1612     DVar.RefExpr = buildDeclRefExpr(
1613         SemaRef, VD, D->getType().getNonReferenceType(),
1614         VD->getAttr<OMPThreadPrivateDeclAttr>()->getLocation());
1615     DVar.CKind = OMPC_threadprivate;
1616     addDSA(D, DVar.RefExpr, OMPC_threadprivate);
1617     return DVar;
1618   }
1619   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1620   // in a Construct, C/C++, predetermined, p.1]
1621   //  Variables appearing in threadprivate directives are threadprivate.
1622   if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
1623        !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
1624          SemaRef.getLangOpts().OpenMPUseTLS &&
1625          SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
1626       (VD && VD->getStorageClass() == SC_Register &&
1627        VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
1628     DVar.RefExpr = buildDeclRefExpr(
1629         SemaRef, VD, D->getType().getNonReferenceType(), D->getLocation());
1630     DVar.CKind = OMPC_threadprivate;
1631     addDSA(D, DVar.RefExpr, OMPC_threadprivate);
1632     return DVar;
1633   }
1634   if (SemaRef.getLangOpts().OpenMPCUDAMode && VD &&
1635       VD->isLocalVarDeclOrParm() && !isStackEmpty() &&
1636       !isLoopControlVariable(D).first) {
1637     const_iterator IterTarget =
1638         std::find_if(begin(), end(), [](const SharingMapTy &Data) {
1639           return isOpenMPTargetExecutionDirective(Data.Directive);
1640         });
1641     if (IterTarget != end()) {
1642       const_iterator ParentIterTarget = IterTarget + 1;
1643       for (const_iterator Iter = begin();
1644            Iter != ParentIterTarget; ++Iter) {
1645         if (isOpenMPLocal(VD, Iter)) {
1646           DVar.RefExpr =
1647               buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
1648                                D->getLocation());
1649           DVar.CKind = OMPC_threadprivate;
1650           return DVar;
1651         }
1652       }
1653       if (!isClauseParsingMode() || IterTarget != begin()) {
1654         auto DSAIter = IterTarget->SharingMap.find(D);
1655         if (DSAIter != IterTarget->SharingMap.end() &&
1656             isOpenMPPrivate(DSAIter->getSecond().Attributes)) {
1657           DVar.RefExpr = DSAIter->getSecond().RefExpr.getPointer();
1658           DVar.CKind = OMPC_threadprivate;
1659           return DVar;
1660         }
1661         const_iterator End = end();
1662         if (!SemaRef.isOpenMPCapturedByRef(
1663                 D, std::distance(ParentIterTarget, End),
1664                 /*OpenMPCaptureLevel=*/0)) {
1665           DVar.RefExpr =
1666               buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
1667                                IterTarget->ConstructLoc);
1668           DVar.CKind = OMPC_threadprivate;
1669           return DVar;
1670         }
1671       }
1672     }
1673   }
1674 
1675   if (isStackEmpty())
1676     // Not in OpenMP execution region and top scope was already checked.
1677     return DVar;
1678 
1679   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1680   // in a Construct, C/C++, predetermined, p.4]
1681   //  Static data members are shared.
1682   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1683   // in a Construct, C/C++, predetermined, p.7]
1684   //  Variables with static storage duration that are declared in a scope
1685   //  inside the construct are shared.
1686   if (VD && VD->isStaticDataMember()) {
1687     // Check for explicitly specified attributes.
1688     const_iterator I = begin();
1689     const_iterator EndI = end();
1690     if (FromParent && I != EndI)
1691       ++I;
1692     if (I != EndI) {
1693       auto It = I->SharingMap.find(D);
1694       if (It != I->SharingMap.end()) {
1695         const DSAInfo &Data = It->getSecond();
1696         DVar.RefExpr = Data.RefExpr.getPointer();
1697         DVar.PrivateCopy = Data.PrivateCopy;
1698         DVar.CKind = Data.Attributes;
1699         DVar.ImplicitDSALoc = I->DefaultAttrLoc;
1700         DVar.DKind = I->Directive;
1701         DVar.Modifier = Data.Modifier;
1702         DVar.AppliedToPointee = Data.AppliedToPointee;
1703         return DVar;
1704       }
1705     }
1706 
1707     DVar.CKind = OMPC_shared;
1708     return DVar;
1709   }
1710 
1711   auto &&MatchesAlways = [](OpenMPDirectiveKind) { return true; };
1712   // The predetermined shared attribute for const-qualified types having no
1713   // mutable members was removed after OpenMP 3.1.
1714   if (SemaRef.LangOpts.OpenMP <= 31) {
1715     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1716     // in a Construct, C/C++, predetermined, p.6]
1717     //  Variables with const qualified type having no mutable member are
1718     //  shared.
1719     if (isConstNotMutableType(SemaRef, D->getType())) {
1720       // Variables with const-qualified type having no mutable member may be
1721       // listed in a firstprivate clause, even if they are static data members.
1722       DSAVarData DVarTemp = hasInnermostDSA(
1723           D,
1724           [](OpenMPClauseKind C, bool) {
1725             return C == OMPC_firstprivate || C == OMPC_shared;
1726           },
1727           MatchesAlways, FromParent);
1728       if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
1729         return DVarTemp;
1730 
1731       DVar.CKind = OMPC_shared;
1732       return DVar;
1733     }
1734   }
1735 
1736   // Explicitly specified attributes and local variables with predetermined
1737   // attributes.
1738   const_iterator I = begin();
1739   const_iterator EndI = end();
1740   if (FromParent && I != EndI)
1741     ++I;
1742   if (I == EndI)
1743     return DVar;
1744   auto It = I->SharingMap.find(D);
1745   if (It != I->SharingMap.end()) {
1746     const DSAInfo &Data = It->getSecond();
1747     DVar.RefExpr = Data.RefExpr.getPointer();
1748     DVar.PrivateCopy = Data.PrivateCopy;
1749     DVar.CKind = Data.Attributes;
1750     DVar.ImplicitDSALoc = I->DefaultAttrLoc;
1751     DVar.DKind = I->Directive;
1752     DVar.Modifier = Data.Modifier;
1753     DVar.AppliedToPointee = Data.AppliedToPointee;
1754   }
1755 
1756   return DVar;
1757 }
1758 
1759 const DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
1760                                                         bool FromParent) const {
1761   if (isStackEmpty()) {
1762     const_iterator I;
1763     return getDSA(I, D);
1764   }
1765   D = getCanonicalDecl(D);
1766   const_iterator StartI = begin();
1767   const_iterator EndI = end();
1768   if (FromParent && StartI != EndI)
1769     ++StartI;
1770   return getDSA(StartI, D);
1771 }
1772 
1773 const DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
1774                                                         unsigned Level) const {
1775   if (getStackSize() <= Level)
1776     return DSAVarData();
1777   D = getCanonicalDecl(D);
1778   const_iterator StartI = std::next(begin(), getStackSize() - 1 - Level);
1779   return getDSA(StartI, D);
1780 }
1781 
1782 const DSAStackTy::DSAVarData
1783 DSAStackTy::hasDSA(ValueDecl *D,
1784                    const llvm::function_ref<bool(OpenMPClauseKind, bool)> CPred,
1785                    const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
1786                    bool FromParent) const {
1787   if (isStackEmpty())
1788     return {};
1789   D = getCanonicalDecl(D);
1790   const_iterator I = begin();
1791   const_iterator EndI = end();
1792   if (FromParent && I != EndI)
1793     ++I;
1794   for (; I != EndI; ++I) {
1795     if (!DPred(I->Directive) &&
1796         !isImplicitOrExplicitTaskingRegion(I->Directive))
1797       continue;
1798     const_iterator NewI = I;
1799     DSAVarData DVar = getDSA(NewI, D);
1800     if (I == NewI && CPred(DVar.CKind, DVar.AppliedToPointee))
1801       return DVar;
1802   }
1803   return {};
1804 }
1805 
1806 const DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
1807     ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind, bool)> CPred,
1808     const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
1809     bool FromParent) const {
1810   if (isStackEmpty())
1811     return {};
1812   D = getCanonicalDecl(D);
1813   const_iterator StartI = begin();
1814   const_iterator EndI = end();
1815   if (FromParent && StartI != EndI)
1816     ++StartI;
1817   if (StartI == EndI || !DPred(StartI->Directive))
1818     return {};
1819   const_iterator NewI = StartI;
1820   DSAVarData DVar = getDSA(NewI, D);
1821   return (NewI == StartI && CPred(DVar.CKind, DVar.AppliedToPointee))
1822              ? DVar
1823              : DSAVarData();
1824 }
1825 
1826 bool DSAStackTy::hasExplicitDSA(
1827     const ValueDecl *D,
1828     const llvm::function_ref<bool(OpenMPClauseKind, bool)> CPred,
1829     unsigned Level, bool NotLastprivate) const {
1830   if (getStackSize() <= Level)
1831     return false;
1832   D = getCanonicalDecl(D);
1833   const SharingMapTy &StackElem = getStackElemAtLevel(Level);
1834   auto I = StackElem.SharingMap.find(D);
1835   if (I != StackElem.SharingMap.end() && I->getSecond().RefExpr.getPointer() &&
1836       CPred(I->getSecond().Attributes, I->getSecond().AppliedToPointee) &&
1837       (!NotLastprivate || !I->getSecond().RefExpr.getInt()))
1838     return true;
1839   // Check predetermined rules for the loop control variables.
1840   auto LI = StackElem.LCVMap.find(D);
1841   if (LI != StackElem.LCVMap.end())
1842     return CPred(OMPC_private, /*AppliedToPointee=*/false);
1843   return false;
1844 }
1845 
1846 bool DSAStackTy::hasExplicitDirective(
1847     const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
1848     unsigned Level) const {
1849   if (getStackSize() <= Level)
1850     return false;
1851   const SharingMapTy &StackElem = getStackElemAtLevel(Level);
1852   return DPred(StackElem.Directive);
1853 }
1854 
1855 bool DSAStackTy::hasDirective(
1856     const llvm::function_ref<bool(OpenMPDirectiveKind,
1857                                   const DeclarationNameInfo &, SourceLocation)>
1858         DPred,
1859     bool FromParent) const {
1860   // We look only in the enclosing region.
1861   size_t Skip = FromParent ? 2 : 1;
1862   for (const_iterator I = begin() + std::min(Skip, getStackSize()), E = end();
1863        I != E; ++I) {
1864     if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
1865       return true;
1866   }
1867   return false;
1868 }
1869 
1870 void Sema::InitDataSharingAttributesStack() {
1871   VarDataSharingAttributesStack = new DSAStackTy(*this);
1872 }
1873 
1874 #define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
1875 
1876 void Sema::pushOpenMPFunctionRegion() {
1877   DSAStack->pushFunction();
1878 }
1879 
1880 void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) {
1881   DSAStack->popFunction(OldFSI);
1882 }
1883 
1884 static bool isOpenMPDeviceDelayedContext(Sema &S) {
1885   assert(S.LangOpts.OpenMP && S.LangOpts.OpenMPIsDevice &&
1886          "Expected OpenMP device compilation.");
1887   return !S.isInOpenMPTargetExecutionDirective();
1888 }
1889 
1890 namespace {
1891 /// Status of the function emission on the host/device.
1892 enum class FunctionEmissionStatus {
1893   Emitted,
1894   Discarded,
1895   Unknown,
1896 };
1897 } // anonymous namespace
1898 
1899 Sema::SemaDiagnosticBuilder Sema::diagIfOpenMPDeviceCode(SourceLocation Loc,
1900                                                          unsigned DiagID,
1901                                                          FunctionDecl *FD) {
1902   assert(LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
1903          "Expected OpenMP device compilation.");
1904 
1905   SemaDiagnosticBuilder::Kind Kind = SemaDiagnosticBuilder::K_Nop;
1906   if (FD) {
1907     FunctionEmissionStatus FES = getEmissionStatus(FD);
1908     switch (FES) {
1909     case FunctionEmissionStatus::Emitted:
1910       Kind = SemaDiagnosticBuilder::K_Immediate;
1911       break;
1912     case FunctionEmissionStatus::Unknown:
1913       // TODO: We should always delay diagnostics here in case a target
1914       //       region is in a function we do not emit. However, as the
1915       //       current diagnostics are associated with the function containing
1916       //       the target region and we do not emit that one, we would miss out
1917       //       on diagnostics for the target region itself. We need to anchor
1918       //       the diagnostics with the new generated function *or* ensure we
1919       //       emit diagnostics associated with the surrounding function.
1920       Kind = isOpenMPDeviceDelayedContext(*this)
1921                  ? SemaDiagnosticBuilder::K_Deferred
1922                  : SemaDiagnosticBuilder::K_Immediate;
1923       break;
1924     case FunctionEmissionStatus::TemplateDiscarded:
1925     case FunctionEmissionStatus::OMPDiscarded:
1926       Kind = SemaDiagnosticBuilder::K_Nop;
1927       break;
1928     case FunctionEmissionStatus::CUDADiscarded:
1929       llvm_unreachable("CUDADiscarded unexpected in OpenMP device compilation");
1930       break;
1931     }
1932   }
1933 
1934   return SemaDiagnosticBuilder(Kind, Loc, DiagID, FD, *this);
1935 }
1936 
1937 Sema::SemaDiagnosticBuilder Sema::diagIfOpenMPHostCode(SourceLocation Loc,
1938                                                        unsigned DiagID,
1939                                                        FunctionDecl *FD) {
1940   assert(LangOpts.OpenMP && !LangOpts.OpenMPIsDevice &&
1941          "Expected OpenMP host compilation.");
1942 
1943   SemaDiagnosticBuilder::Kind Kind = SemaDiagnosticBuilder::K_Nop;
1944   if (FD) {
1945     FunctionEmissionStatus FES = getEmissionStatus(FD);
1946     switch (FES) {
1947     case FunctionEmissionStatus::Emitted:
1948       Kind = SemaDiagnosticBuilder::K_Immediate;
1949       break;
1950     case FunctionEmissionStatus::Unknown:
1951       Kind = SemaDiagnosticBuilder::K_Deferred;
1952       break;
1953     case FunctionEmissionStatus::TemplateDiscarded:
1954     case FunctionEmissionStatus::OMPDiscarded:
1955     case FunctionEmissionStatus::CUDADiscarded:
1956       Kind = SemaDiagnosticBuilder::K_Nop;
1957       break;
1958     }
1959   }
1960 
1961   return SemaDiagnosticBuilder(Kind, Loc, DiagID, FD, *this);
1962 }
1963 
1964 static OpenMPDefaultmapClauseKind
1965 getVariableCategoryFromDecl(const LangOptions &LO, const ValueDecl *VD) {
1966   if (LO.OpenMP <= 45) {
1967     if (VD->getType().getNonReferenceType()->isScalarType())
1968       return OMPC_DEFAULTMAP_scalar;
1969     return OMPC_DEFAULTMAP_aggregate;
1970   }
1971   if (VD->getType().getNonReferenceType()->isAnyPointerType())
1972     return OMPC_DEFAULTMAP_pointer;
1973   if (VD->getType().getNonReferenceType()->isScalarType())
1974     return OMPC_DEFAULTMAP_scalar;
1975   return OMPC_DEFAULTMAP_aggregate;
1976 }
1977 
1978 bool Sema::isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level,
1979                                  unsigned OpenMPCaptureLevel) const {
1980   assert(LangOpts.OpenMP && "OpenMP is not allowed");
1981 
1982   ASTContext &Ctx = getASTContext();
1983   bool IsByRef = true;
1984 
1985   // Find the directive that is associated with the provided scope.
1986   D = cast<ValueDecl>(D->getCanonicalDecl());
1987   QualType Ty = D->getType();
1988 
1989   bool IsVariableUsedInMapClause = false;
1990   if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
1991     // This table summarizes how a given variable should be passed to the device
1992     // given its type and the clauses where it appears. This table is based on
1993     // the description in OpenMP 4.5 [2.10.4, target Construct] and
1994     // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
1995     //
1996     // =========================================================================
1997     // | type |  defaultmap   | pvt | first | is_device_ptr |    map   | res.  |
1998     // |      |(tofrom:scalar)|     |  pvt  |               |          |       |
1999     // =========================================================================
2000     // | scl  |               |     |       |       -       |          | bycopy|
2001     // | scl  |               |  -  |   x   |       -       |     -    | bycopy|
2002     // | scl  |               |  x  |   -   |       -       |     -    | null  |
2003     // | scl  |       x       |     |       |       -       |          | byref |
2004     // | scl  |       x       |  -  |   x   |       -       |     -    | bycopy|
2005     // | scl  |       x       |  x  |   -   |       -       |     -    | null  |
2006     // | scl  |               |  -  |   -   |       -       |     x    | byref |
2007     // | scl  |       x       |  -  |   -   |       -       |     x    | byref |
2008     //
2009     // | agg  |      n.a.     |     |       |       -       |          | byref |
2010     // | agg  |      n.a.     |  -  |   x   |       -       |     -    | byref |
2011     // | agg  |      n.a.     |  x  |   -   |       -       |     -    | null  |
2012     // | agg  |      n.a.     |  -  |   -   |       -       |     x    | byref |
2013     // | agg  |      n.a.     |  -  |   -   |       -       |    x[]   | byref |
2014     //
2015     // | ptr  |      n.a.     |     |       |       -       |          | bycopy|
2016     // | ptr  |      n.a.     |  -  |   x   |       -       |     -    | bycopy|
2017     // | ptr  |      n.a.     |  x  |   -   |       -       |     -    | null  |
2018     // | ptr  |      n.a.     |  -  |   -   |       -       |     x    | byref |
2019     // | ptr  |      n.a.     |  -  |   -   |       -       |    x[]   | bycopy|
2020     // | ptr  |      n.a.     |  -  |   -   |       x       |          | bycopy|
2021     // | ptr  |      n.a.     |  -  |   -   |       x       |     x    | bycopy|
2022     // | ptr  |      n.a.     |  -  |   -   |       x       |    x[]   | bycopy|
2023     // =========================================================================
2024     // Legend:
2025     //  scl - scalar
2026     //  ptr - pointer
2027     //  agg - aggregate
2028     //  x - applies
2029     //  - - invalid in this combination
2030     //  [] - mapped with an array section
2031     //  byref - should be mapped by reference
2032     //  byval - should be mapped by value
2033     //  null - initialize a local variable to null on the device
2034     //
2035     // Observations:
2036     //  - All scalar declarations that show up in a map clause have to be passed
2037     //    by reference, because they may have been mapped in the enclosing data
2038     //    environment.
2039     //  - If the scalar value does not fit the size of uintptr, it has to be
2040     //    passed by reference, regardless the result in the table above.
2041     //  - For pointers mapped by value that have either an implicit map or an
2042     //    array section, the runtime library may pass the NULL value to the
2043     //    device instead of the value passed to it by the compiler.
2044 
2045     if (Ty->isReferenceType())
2046       Ty = Ty->castAs<ReferenceType>()->getPointeeType();
2047 
2048     // Locate map clauses and see if the variable being captured is referred to
2049     // in any of those clauses. Here we only care about variables, not fields,
2050     // because fields are part of aggregates.
2051     bool IsVariableAssociatedWithSection = false;
2052 
2053     DSAStack->checkMappableExprComponentListsForDeclAtLevel(
2054         D, Level,
2055         [&IsVariableUsedInMapClause, &IsVariableAssociatedWithSection, D](
2056             OMPClauseMappableExprCommon::MappableExprComponentListRef
2057                 MapExprComponents,
2058             OpenMPClauseKind WhereFoundClauseKind) {
2059           // Only the map clause information influences how a variable is
2060           // captured. E.g. is_device_ptr does not require changing the default
2061           // behavior.
2062           if (WhereFoundClauseKind != OMPC_map)
2063             return false;
2064 
2065           auto EI = MapExprComponents.rbegin();
2066           auto EE = MapExprComponents.rend();
2067 
2068           assert(EI != EE && "Invalid map expression!");
2069 
2070           if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
2071             IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
2072 
2073           ++EI;
2074           if (EI == EE)
2075             return false;
2076 
2077           if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
2078               isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
2079               isa<MemberExpr>(EI->getAssociatedExpression()) ||
2080               isa<OMPArrayShapingExpr>(EI->getAssociatedExpression())) {
2081             IsVariableAssociatedWithSection = true;
2082             // There is nothing more we need to know about this variable.
2083             return true;
2084           }
2085 
2086           // Keep looking for more map info.
2087           return false;
2088         });
2089 
2090     if (IsVariableUsedInMapClause) {
2091       // If variable is identified in a map clause it is always captured by
2092       // reference except if it is a pointer that is dereferenced somehow.
2093       IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
2094     } else {
2095       // By default, all the data that has a scalar type is mapped by copy
2096       // (except for reduction variables).
2097       // Defaultmap scalar is mutual exclusive to defaultmap pointer
2098       IsByRef = (DSAStack->isForceCaptureByReferenceInTargetExecutable() &&
2099                  !Ty->isAnyPointerType()) ||
2100                 !Ty->isScalarType() ||
2101                 DSAStack->isDefaultmapCapturedByRef(
2102                     Level, getVariableCategoryFromDecl(LangOpts, D)) ||
2103                 DSAStack->hasExplicitDSA(
2104                     D,
2105                     [](OpenMPClauseKind K, bool AppliedToPointee) {
2106                       return K == OMPC_reduction && !AppliedToPointee;
2107                     },
2108                     Level);
2109     }
2110   }
2111 
2112   if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
2113     IsByRef =
2114         ((IsVariableUsedInMapClause &&
2115           DSAStack->getCaptureRegion(Level, OpenMPCaptureLevel) ==
2116               OMPD_target) ||
2117          !(DSAStack->hasExplicitDSA(
2118                D,
2119                [](OpenMPClauseKind K, bool AppliedToPointee) -> bool {
2120                  return K == OMPC_firstprivate ||
2121                         (K == OMPC_reduction && AppliedToPointee);
2122                },
2123                Level, /*NotLastprivate=*/true) ||
2124            DSAStack->isUsesAllocatorsDecl(Level, D))) &&
2125         // If the variable is artificial and must be captured by value - try to
2126         // capture by value.
2127         !(isa<OMPCapturedExprDecl>(D) && !D->hasAttr<OMPCaptureNoInitAttr>() &&
2128           !cast<OMPCapturedExprDecl>(D)->getInit()->isGLValue()) &&
2129         // If the variable is implicitly firstprivate and scalar - capture by
2130         // copy
2131         !(DSAStack->getDefaultDSA() == DSA_firstprivate &&
2132           !DSAStack->hasExplicitDSA(
2133               D, [](OpenMPClauseKind K, bool) { return K != OMPC_unknown; },
2134               Level) &&
2135           !DSAStack->isLoopControlVariable(D, Level).first);
2136   }
2137 
2138   // When passing data by copy, we need to make sure it fits the uintptr size
2139   // and alignment, because the runtime library only deals with uintptr types.
2140   // If it does not fit the uintptr size, we need to pass the data by reference
2141   // instead.
2142   if (!IsByRef &&
2143       (Ctx.getTypeSizeInChars(Ty) >
2144            Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
2145        Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
2146     IsByRef = true;
2147   }
2148 
2149   return IsByRef;
2150 }
2151 
2152 unsigned Sema::getOpenMPNestingLevel() const {
2153   assert(getLangOpts().OpenMP);
2154   return DSAStack->getNestingLevel();
2155 }
2156 
2157 bool Sema::isInOpenMPTargetExecutionDirective() const {
2158   return (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) &&
2159           !DSAStack->isClauseParsingMode()) ||
2160          DSAStack->hasDirective(
2161              [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
2162                 SourceLocation) -> bool {
2163                return isOpenMPTargetExecutionDirective(K);
2164              },
2165              false);
2166 }
2167 
2168 VarDecl *Sema::isOpenMPCapturedDecl(ValueDecl *D, bool CheckScopeInfo,
2169                                     unsigned StopAt) {
2170   assert(LangOpts.OpenMP && "OpenMP is not allowed");
2171   D = getCanonicalDecl(D);
2172 
2173   auto *VD = dyn_cast<VarDecl>(D);
2174   // Do not capture constexpr variables.
2175   if (VD && VD->isConstexpr())
2176     return nullptr;
2177 
2178   // If we want to determine whether the variable should be captured from the
2179   // perspective of the current capturing scope, and we've already left all the
2180   // capturing scopes of the top directive on the stack, check from the
2181   // perspective of its parent directive (if any) instead.
2182   DSAStackTy::ParentDirectiveScope InParentDirectiveRAII(
2183       *DSAStack, CheckScopeInfo && DSAStack->isBodyComplete());
2184 
2185   // If we are attempting to capture a global variable in a directive with
2186   // 'target' we return true so that this global is also mapped to the device.
2187   //
2188   if (VD && !VD->hasLocalStorage() &&
2189       (getCurCapturedRegion() || getCurBlock() || getCurLambda())) {
2190     if (isInOpenMPDeclareTargetContext()) {
2191       // Try to mark variable as declare target if it is used in capturing
2192       // regions.
2193       if (LangOpts.OpenMP <= 45 &&
2194           !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
2195         checkDeclIsAllowedInOpenMPTarget(nullptr, VD);
2196       return nullptr;
2197     }
2198     if (isInOpenMPTargetExecutionDirective()) {
2199       // If the declaration is enclosed in a 'declare target' directive,
2200       // then it should not be captured.
2201       //
2202       if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
2203         return nullptr;
2204       CapturedRegionScopeInfo *CSI = nullptr;
2205       for (FunctionScopeInfo *FSI : llvm::drop_begin(
2206                llvm::reverse(FunctionScopes),
2207                CheckScopeInfo ? (FunctionScopes.size() - (StopAt + 1)) : 0)) {
2208         if (!isa<CapturingScopeInfo>(FSI))
2209           return nullptr;
2210         if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(FSI))
2211           if (RSI->CapRegionKind == CR_OpenMP) {
2212             CSI = RSI;
2213             break;
2214           }
2215       }
2216       assert(CSI && "Failed to find CapturedRegionScopeInfo");
2217       SmallVector<OpenMPDirectiveKind, 4> Regions;
2218       getOpenMPCaptureRegions(Regions,
2219                               DSAStack->getDirective(CSI->OpenMPLevel));
2220       if (Regions[CSI->OpenMPCaptureLevel] != OMPD_task)
2221         return VD;
2222     }
2223   }
2224 
2225   if (CheckScopeInfo) {
2226     bool OpenMPFound = false;
2227     for (unsigned I = StopAt + 1; I > 0; --I) {
2228       FunctionScopeInfo *FSI = FunctionScopes[I - 1];
2229       if(!isa<CapturingScopeInfo>(FSI))
2230         return nullptr;
2231       if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(FSI))
2232         if (RSI->CapRegionKind == CR_OpenMP) {
2233           OpenMPFound = true;
2234           break;
2235         }
2236     }
2237     if (!OpenMPFound)
2238       return nullptr;
2239   }
2240 
2241   if (DSAStack->getCurrentDirective() != OMPD_unknown &&
2242       (!DSAStack->isClauseParsingMode() ||
2243        DSAStack->getParentDirective() != OMPD_unknown)) {
2244     auto &&Info = DSAStack->isLoopControlVariable(D);
2245     if (Info.first ||
2246         (VD && VD->hasLocalStorage() &&
2247          isImplicitOrExplicitTaskingRegion(DSAStack->getCurrentDirective())) ||
2248         (VD && DSAStack->isForceVarCapturing()))
2249       return VD ? VD : Info.second;
2250     DSAStackTy::DSAVarData DVarTop =
2251         DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
2252     if (DVarTop.CKind != OMPC_unknown && isOpenMPPrivate(DVarTop.CKind) &&
2253         (!VD || VD->hasLocalStorage() || !DVarTop.AppliedToPointee))
2254       return VD ? VD : cast<VarDecl>(DVarTop.PrivateCopy->getDecl());
2255     // Threadprivate variables must not be captured.
2256     if (isOpenMPThreadPrivate(DVarTop.CKind))
2257       return nullptr;
2258     // The variable is not private or it is the variable in the directive with
2259     // default(none) clause and not used in any clause.
2260     DSAStackTy::DSAVarData DVarPrivate = DSAStack->hasDSA(
2261         D,
2262         [](OpenMPClauseKind C, bool AppliedToPointee) {
2263           return isOpenMPPrivate(C) && !AppliedToPointee;
2264         },
2265         [](OpenMPDirectiveKind) { return true; },
2266         DSAStack->isClauseParsingMode());
2267     // Global shared must not be captured.
2268     if (VD && !VD->hasLocalStorage() && DVarPrivate.CKind == OMPC_unknown &&
2269         ((DSAStack->getDefaultDSA() != DSA_none &&
2270           DSAStack->getDefaultDSA() != DSA_firstprivate) ||
2271          DVarTop.CKind == OMPC_shared))
2272       return nullptr;
2273     if (DVarPrivate.CKind != OMPC_unknown ||
2274         (VD && (DSAStack->getDefaultDSA() == DSA_none ||
2275                 DSAStack->getDefaultDSA() == DSA_firstprivate)))
2276       return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
2277   }
2278   return nullptr;
2279 }
2280 
2281 void Sema::adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex,
2282                                         unsigned Level) const {
2283   FunctionScopesIndex -= getOpenMPCaptureLevels(DSAStack->getDirective(Level));
2284 }
2285 
2286 void Sema::startOpenMPLoop() {
2287   assert(LangOpts.OpenMP && "OpenMP must be enabled.");
2288   if (isOpenMPLoopDirective(DSAStack->getCurrentDirective()))
2289     DSAStack->loopInit();
2290 }
2291 
2292 void Sema::startOpenMPCXXRangeFor() {
2293   assert(LangOpts.OpenMP && "OpenMP must be enabled.");
2294   if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
2295     DSAStack->resetPossibleLoopCounter();
2296     DSAStack->loopStart();
2297   }
2298 }
2299 
2300 OpenMPClauseKind Sema::isOpenMPPrivateDecl(ValueDecl *D, unsigned Level,
2301                                            unsigned CapLevel) const {
2302   assert(LangOpts.OpenMP && "OpenMP is not allowed");
2303   if (DSAStack->hasExplicitDirective(
2304           [](OpenMPDirectiveKind K) { return isOpenMPTaskingDirective(K); },
2305           Level)) {
2306     bool IsTriviallyCopyable =
2307         D->getType().getNonReferenceType().isTriviallyCopyableType(Context) &&
2308         !D->getType()
2309              .getNonReferenceType()
2310              .getCanonicalType()
2311              ->getAsCXXRecordDecl();
2312     OpenMPDirectiveKind DKind = DSAStack->getDirective(Level);
2313     SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
2314     getOpenMPCaptureRegions(CaptureRegions, DKind);
2315     if (isOpenMPTaskingDirective(CaptureRegions[CapLevel]) &&
2316         (IsTriviallyCopyable ||
2317          !isOpenMPTaskLoopDirective(CaptureRegions[CapLevel]))) {
2318       if (DSAStack->hasExplicitDSA(
2319               D,
2320               [](OpenMPClauseKind K, bool) { return K == OMPC_firstprivate; },
2321               Level, /*NotLastprivate=*/true))
2322         return OMPC_firstprivate;
2323       DSAStackTy::DSAVarData DVar = DSAStack->getImplicitDSA(D, Level);
2324       if (DVar.CKind != OMPC_shared &&
2325           !DSAStack->isLoopControlVariable(D, Level).first && !DVar.RefExpr) {
2326         DSAStack->addImplicitTaskFirstprivate(Level, D);
2327         return OMPC_firstprivate;
2328       }
2329     }
2330   }
2331   if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
2332     if (DSAStack->getAssociatedLoops() > 0 &&
2333         !DSAStack->isLoopStarted()) {
2334       DSAStack->resetPossibleLoopCounter(D);
2335       DSAStack->loopStart();
2336       return OMPC_private;
2337     }
2338     if ((DSAStack->getPossiblyLoopCunter() == D->getCanonicalDecl() ||
2339          DSAStack->isLoopControlVariable(D).first) &&
2340         !DSAStack->hasExplicitDSA(
2341             D, [](OpenMPClauseKind K, bool) { return K != OMPC_private; },
2342             Level) &&
2343         !isOpenMPSimdDirective(DSAStack->getCurrentDirective()))
2344       return OMPC_private;
2345   }
2346   if (const auto *VD = dyn_cast<VarDecl>(D)) {
2347     if (DSAStack->isThreadPrivate(const_cast<VarDecl *>(VD)) &&
2348         DSAStack->isForceVarCapturing() &&
2349         !DSAStack->hasExplicitDSA(
2350             D, [](OpenMPClauseKind K, bool) { return K == OMPC_copyin; },
2351             Level))
2352       return OMPC_private;
2353   }
2354   // User-defined allocators are private since they must be defined in the
2355   // context of target region.
2356   if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level) &&
2357       DSAStack->isUsesAllocatorsDecl(Level, D).getValueOr(
2358           DSAStackTy::UsesAllocatorsDeclKind::AllocatorTrait) ==
2359           DSAStackTy::UsesAllocatorsDeclKind::UserDefinedAllocator)
2360     return OMPC_private;
2361   return (DSAStack->hasExplicitDSA(
2362               D, [](OpenMPClauseKind K, bool) { return K == OMPC_private; },
2363               Level) ||
2364           (DSAStack->isClauseParsingMode() &&
2365            DSAStack->getClauseParsingMode() == OMPC_private) ||
2366           // Consider taskgroup reduction descriptor variable a private
2367           // to avoid possible capture in the region.
2368           (DSAStack->hasExplicitDirective(
2369                [](OpenMPDirectiveKind K) {
2370                  return K == OMPD_taskgroup ||
2371                         ((isOpenMPParallelDirective(K) ||
2372                           isOpenMPWorksharingDirective(K)) &&
2373                          !isOpenMPSimdDirective(K));
2374                },
2375                Level) &&
2376            DSAStack->isTaskgroupReductionRef(D, Level)))
2377              ? OMPC_private
2378              : OMPC_unknown;
2379 }
2380 
2381 void Sema::setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D,
2382                                 unsigned Level) {
2383   assert(LangOpts.OpenMP && "OpenMP is not allowed");
2384   D = getCanonicalDecl(D);
2385   OpenMPClauseKind OMPC = OMPC_unknown;
2386   for (unsigned I = DSAStack->getNestingLevel() + 1; I > Level; --I) {
2387     const unsigned NewLevel = I - 1;
2388     if (DSAStack->hasExplicitDSA(
2389             D,
2390             [&OMPC](const OpenMPClauseKind K, bool AppliedToPointee) {
2391               if (isOpenMPPrivate(K) && !AppliedToPointee) {
2392                 OMPC = K;
2393                 return true;
2394               }
2395               return false;
2396             },
2397             NewLevel))
2398       break;
2399     if (DSAStack->checkMappableExprComponentListsForDeclAtLevel(
2400             D, NewLevel,
2401             [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
2402                OpenMPClauseKind) { return true; })) {
2403       OMPC = OMPC_map;
2404       break;
2405     }
2406     if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
2407                                        NewLevel)) {
2408       OMPC = OMPC_map;
2409       if (DSAStack->mustBeFirstprivateAtLevel(
2410               NewLevel, getVariableCategoryFromDecl(LangOpts, D)))
2411         OMPC = OMPC_firstprivate;
2412       break;
2413     }
2414   }
2415   if (OMPC != OMPC_unknown)
2416     FD->addAttr(OMPCaptureKindAttr::CreateImplicit(Context, unsigned(OMPC)));
2417 }
2418 
2419 bool Sema::isOpenMPTargetCapturedDecl(const ValueDecl *D, unsigned Level,
2420                                       unsigned CaptureLevel) const {
2421   assert(LangOpts.OpenMP && "OpenMP is not allowed");
2422   // Return true if the current level is no longer enclosed in a target region.
2423 
2424   SmallVector<OpenMPDirectiveKind, 4> Regions;
2425   getOpenMPCaptureRegions(Regions, DSAStack->getDirective(Level));
2426   const auto *VD = dyn_cast<VarDecl>(D);
2427   return VD && !VD->hasLocalStorage() &&
2428          DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
2429                                         Level) &&
2430          Regions[CaptureLevel] != OMPD_task;
2431 }
2432 
2433 bool Sema::isOpenMPGlobalCapturedDecl(ValueDecl *D, unsigned Level,
2434                                       unsigned CaptureLevel) const {
2435   assert(LangOpts.OpenMP && "OpenMP is not allowed");
2436   // Return true if the current level is no longer enclosed in a target region.
2437 
2438   if (const auto *VD = dyn_cast<VarDecl>(D)) {
2439     if (!VD->hasLocalStorage()) {
2440       if (isInOpenMPTargetExecutionDirective())
2441         return true;
2442       DSAStackTy::DSAVarData TopDVar =
2443           DSAStack->getTopDSA(D, /*FromParent=*/false);
2444       unsigned NumLevels =
2445           getOpenMPCaptureLevels(DSAStack->getDirective(Level));
2446       if (Level == 0)
2447         return (NumLevels == CaptureLevel + 1) && TopDVar.CKind != OMPC_shared;
2448       do {
2449         --Level;
2450         DSAStackTy::DSAVarData DVar = DSAStack->getImplicitDSA(D, Level);
2451         if (DVar.CKind != OMPC_shared)
2452           return true;
2453       } while (Level > 0);
2454     }
2455   }
2456   return true;
2457 }
2458 
2459 void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
2460 
2461 void Sema::ActOnOpenMPBeginDeclareVariant(SourceLocation Loc,
2462                                           OMPTraitInfo &TI) {
2463   OMPDeclareVariantScopes.push_back(OMPDeclareVariantScope(TI));
2464 }
2465 
2466 void Sema::ActOnOpenMPEndDeclareVariant() {
2467   assert(isInOpenMPDeclareVariantScope() &&
2468          "Not in OpenMP declare variant scope!");
2469 
2470   OMPDeclareVariantScopes.pop_back();
2471 }
2472 
2473 void Sema::finalizeOpenMPDelayedAnalysis(const FunctionDecl *Caller,
2474                                          const FunctionDecl *Callee,
2475                                          SourceLocation Loc) {
2476   assert(LangOpts.OpenMP && "Expected OpenMP compilation mode.");
2477   Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
2478       OMPDeclareTargetDeclAttr::getDeviceType(Caller->getMostRecentDecl());
2479   // Ignore host functions during device analyzis.
2480   if (LangOpts.OpenMPIsDevice && DevTy &&
2481       *DevTy == OMPDeclareTargetDeclAttr::DT_Host)
2482     return;
2483   // Ignore nohost functions during host analyzis.
2484   if (!LangOpts.OpenMPIsDevice && DevTy &&
2485       *DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
2486     return;
2487   const FunctionDecl *FD = Callee->getMostRecentDecl();
2488   DevTy = OMPDeclareTargetDeclAttr::getDeviceType(FD);
2489   if (LangOpts.OpenMPIsDevice && DevTy &&
2490       *DevTy == OMPDeclareTargetDeclAttr::DT_Host) {
2491     // Diagnose host function called during device codegen.
2492     StringRef HostDevTy =
2493         getOpenMPSimpleClauseTypeName(OMPC_device_type, OMPC_DEVICE_TYPE_host);
2494     Diag(Loc, diag::err_omp_wrong_device_function_call) << HostDevTy << 0;
2495     Diag(*OMPDeclareTargetDeclAttr::getLocation(FD),
2496          diag::note_omp_marked_device_type_here)
2497         << HostDevTy;
2498     return;
2499   }
2500       if (!LangOpts.OpenMPIsDevice && DevTy &&
2501           *DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) {
2502         // Diagnose nohost function called during host codegen.
2503         StringRef NoHostDevTy = getOpenMPSimpleClauseTypeName(
2504             OMPC_device_type, OMPC_DEVICE_TYPE_nohost);
2505         Diag(Loc, diag::err_omp_wrong_device_function_call) << NoHostDevTy << 1;
2506         Diag(*OMPDeclareTargetDeclAttr::getLocation(FD),
2507              diag::note_omp_marked_device_type_here)
2508             << NoHostDevTy;
2509       }
2510 }
2511 
2512 void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
2513                                const DeclarationNameInfo &DirName,
2514                                Scope *CurScope, SourceLocation Loc) {
2515   DSAStack->push(DKind, DirName, CurScope, Loc);
2516   PushExpressionEvaluationContext(
2517       ExpressionEvaluationContext::PotentiallyEvaluated);
2518 }
2519 
2520 void Sema::StartOpenMPClause(OpenMPClauseKind K) {
2521   DSAStack->setClauseParsingMode(K);
2522 }
2523 
2524 void Sema::EndOpenMPClause() {
2525   DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
2526 }
2527 
2528 static std::pair<ValueDecl *, bool>
2529 getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
2530                SourceRange &ERange, bool AllowArraySection = false);
2531 
2532 /// Check consistency of the reduction clauses.
2533 static void checkReductionClauses(Sema &S, DSAStackTy *Stack,
2534                                   ArrayRef<OMPClause *> Clauses) {
2535   bool InscanFound = false;
2536   SourceLocation InscanLoc;
2537   // OpenMP 5.0, 2.19.5.4 reduction Clause, Restrictions.
2538   // A reduction clause without the inscan reduction-modifier may not appear on
2539   // a construct on which a reduction clause with the inscan reduction-modifier
2540   // appears.
2541   for (OMPClause *C : Clauses) {
2542     if (C->getClauseKind() != OMPC_reduction)
2543       continue;
2544     auto *RC = cast<OMPReductionClause>(C);
2545     if (RC->getModifier() == OMPC_REDUCTION_inscan) {
2546       InscanFound = true;
2547       InscanLoc = RC->getModifierLoc();
2548       continue;
2549     }
2550     if (RC->getModifier() == OMPC_REDUCTION_task) {
2551       // OpenMP 5.0, 2.19.5.4 reduction Clause.
2552       // A reduction clause with the task reduction-modifier may only appear on
2553       // a parallel construct, a worksharing construct or a combined or
2554       // composite construct for which any of the aforementioned constructs is a
2555       // constituent construct and simd or loop are not constituent constructs.
2556       OpenMPDirectiveKind CurDir = Stack->getCurrentDirective();
2557       if (!(isOpenMPParallelDirective(CurDir) ||
2558             isOpenMPWorksharingDirective(CurDir)) ||
2559           isOpenMPSimdDirective(CurDir))
2560         S.Diag(RC->getModifierLoc(),
2561                diag::err_omp_reduction_task_not_parallel_or_worksharing);
2562       continue;
2563     }
2564   }
2565   if (InscanFound) {
2566     for (OMPClause *C : Clauses) {
2567       if (C->getClauseKind() != OMPC_reduction)
2568         continue;
2569       auto *RC = cast<OMPReductionClause>(C);
2570       if (RC->getModifier() != OMPC_REDUCTION_inscan) {
2571         S.Diag(RC->getModifier() == OMPC_REDUCTION_unknown
2572                    ? RC->getBeginLoc()
2573                    : RC->getModifierLoc(),
2574                diag::err_omp_inscan_reduction_expected);
2575         S.Diag(InscanLoc, diag::note_omp_previous_inscan_reduction);
2576         continue;
2577       }
2578       for (Expr *Ref : RC->varlists()) {
2579         assert(Ref && "NULL expr in OpenMP nontemporal clause.");
2580         SourceLocation ELoc;
2581         SourceRange ERange;
2582         Expr *SimpleRefExpr = Ref;
2583         auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
2584                                   /*AllowArraySection=*/true);
2585         ValueDecl *D = Res.first;
2586         if (!D)
2587           continue;
2588         if (!Stack->isUsedInScanDirective(getCanonicalDecl(D))) {
2589           S.Diag(Ref->getExprLoc(),
2590                  diag::err_omp_reduction_not_inclusive_exclusive)
2591               << Ref->getSourceRange();
2592         }
2593       }
2594     }
2595   }
2596 }
2597 
2598 static void checkAllocateClauses(Sema &S, DSAStackTy *Stack,
2599                                  ArrayRef<OMPClause *> Clauses);
2600 static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
2601                                  bool WithInit);
2602 
2603 static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack,
2604                               const ValueDecl *D,
2605                               const DSAStackTy::DSAVarData &DVar,
2606                               bool IsLoopIterVar = false);
2607 
2608 void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
2609   // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
2610   //  A variable of class type (or array thereof) that appears in a lastprivate
2611   //  clause requires an accessible, unambiguous default constructor for the
2612   //  class type, unless the list item is also specified in a firstprivate
2613   //  clause.
2614   if (const auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
2615     for (OMPClause *C : D->clauses()) {
2616       if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
2617         SmallVector<Expr *, 8> PrivateCopies;
2618         for (Expr *DE : Clause->varlists()) {
2619           if (DE->isValueDependent() || DE->isTypeDependent()) {
2620             PrivateCopies.push_back(nullptr);
2621             continue;
2622           }
2623           auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
2624           auto *VD = cast<VarDecl>(DRE->getDecl());
2625           QualType Type = VD->getType().getNonReferenceType();
2626           const DSAStackTy::DSAVarData DVar =
2627               DSAStack->getTopDSA(VD, /*FromParent=*/false);
2628           if (DVar.CKind == OMPC_lastprivate) {
2629             // Generate helper private variable and initialize it with the
2630             // default value. The address of the original variable is replaced
2631             // by the address of the new private variable in CodeGen. This new
2632             // variable is not added to IdResolver, so the code in the OpenMP
2633             // region uses original variable for proper diagnostics.
2634             VarDecl *VDPrivate = buildVarDecl(
2635                 *this, DE->getExprLoc(), Type.getUnqualifiedType(),
2636                 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr, DRE);
2637             ActOnUninitializedDecl(VDPrivate);
2638             if (VDPrivate->isInvalidDecl()) {
2639               PrivateCopies.push_back(nullptr);
2640               continue;
2641             }
2642             PrivateCopies.push_back(buildDeclRefExpr(
2643                 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
2644           } else {
2645             // The variable is also a firstprivate, so initialization sequence
2646             // for private copy is generated already.
2647             PrivateCopies.push_back(nullptr);
2648           }
2649         }
2650         Clause->setPrivateCopies(PrivateCopies);
2651         continue;
2652       }
2653       // Finalize nontemporal clause by handling private copies, if any.
2654       if (auto *Clause = dyn_cast<OMPNontemporalClause>(C)) {
2655         SmallVector<Expr *, 8> PrivateRefs;
2656         for (Expr *RefExpr : Clause->varlists()) {
2657           assert(RefExpr && "NULL expr in OpenMP nontemporal clause.");
2658           SourceLocation ELoc;
2659           SourceRange ERange;
2660           Expr *SimpleRefExpr = RefExpr;
2661           auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
2662           if (Res.second)
2663             // It will be analyzed later.
2664             PrivateRefs.push_back(RefExpr);
2665           ValueDecl *D = Res.first;
2666           if (!D)
2667             continue;
2668 
2669           const DSAStackTy::DSAVarData DVar =
2670               DSAStack->getTopDSA(D, /*FromParent=*/false);
2671           PrivateRefs.push_back(DVar.PrivateCopy ? DVar.PrivateCopy
2672                                                  : SimpleRefExpr);
2673         }
2674         Clause->setPrivateRefs(PrivateRefs);
2675         continue;
2676       }
2677       if (auto *Clause = dyn_cast<OMPUsesAllocatorsClause>(C)) {
2678         for (unsigned I = 0, E = Clause->getNumberOfAllocators(); I < E; ++I) {
2679           OMPUsesAllocatorsClause::Data D = Clause->getAllocatorData(I);
2680           auto *DRE = dyn_cast<DeclRefExpr>(D.Allocator->IgnoreParenImpCasts());
2681           if (!DRE)
2682             continue;
2683           ValueDecl *VD = DRE->getDecl();
2684           if (!VD || !isa<VarDecl>(VD))
2685             continue;
2686           DSAStackTy::DSAVarData DVar =
2687               DSAStack->getTopDSA(VD, /*FromParent=*/false);
2688           // OpenMP [2.12.5, target Construct]
2689           // Memory allocators that appear in a uses_allocators clause cannot
2690           // appear in other data-sharing attribute clauses or data-mapping
2691           // attribute clauses in the same construct.
2692           Expr *MapExpr = nullptr;
2693           if (DVar.RefExpr ||
2694               DSAStack->checkMappableExprComponentListsForDecl(
2695                   VD, /*CurrentRegionOnly=*/true,
2696                   [VD, &MapExpr](
2697                       OMPClauseMappableExprCommon::MappableExprComponentListRef
2698                           MapExprComponents,
2699                       OpenMPClauseKind C) {
2700                     auto MI = MapExprComponents.rbegin();
2701                     auto ME = MapExprComponents.rend();
2702                     if (MI != ME &&
2703                         MI->getAssociatedDeclaration()->getCanonicalDecl() ==
2704                             VD->getCanonicalDecl()) {
2705                       MapExpr = MI->getAssociatedExpression();
2706                       return true;
2707                     }
2708                     return false;
2709                   })) {
2710             Diag(D.Allocator->getExprLoc(),
2711                  diag::err_omp_allocator_used_in_clauses)
2712                 << D.Allocator->getSourceRange();
2713             if (DVar.RefExpr)
2714               reportOriginalDsa(*this, DSAStack, VD, DVar);
2715             else
2716               Diag(MapExpr->getExprLoc(), diag::note_used_here)
2717                   << MapExpr->getSourceRange();
2718           }
2719         }
2720         continue;
2721       }
2722     }
2723     // Check allocate clauses.
2724     if (!CurContext->isDependentContext())
2725       checkAllocateClauses(*this, DSAStack, D->clauses());
2726     checkReductionClauses(*this, DSAStack, D->clauses());
2727   }
2728 
2729   DSAStack->pop();
2730   DiscardCleanupsInEvaluationContext();
2731   PopExpressionEvaluationContext();
2732 }
2733 
2734 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
2735                                      Expr *NumIterations, Sema &SemaRef,
2736                                      Scope *S, DSAStackTy *Stack);
2737 
2738 namespace {
2739 
2740 class VarDeclFilterCCC final : public CorrectionCandidateCallback {
2741 private:
2742   Sema &SemaRef;
2743 
2744 public:
2745   explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
2746   bool ValidateCandidate(const TypoCorrection &Candidate) override {
2747     NamedDecl *ND = Candidate.getCorrectionDecl();
2748     if (const auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
2749       return VD->hasGlobalStorage() &&
2750              SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
2751                                    SemaRef.getCurScope());
2752     }
2753     return false;
2754   }
2755 
2756   std::unique_ptr<CorrectionCandidateCallback> clone() override {
2757     return std::make_unique<VarDeclFilterCCC>(*this);
2758   }
2759 
2760 };
2761 
2762 class VarOrFuncDeclFilterCCC final : public CorrectionCandidateCallback {
2763 private:
2764   Sema &SemaRef;
2765 
2766 public:
2767   explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
2768   bool ValidateCandidate(const TypoCorrection &Candidate) override {
2769     NamedDecl *ND = Candidate.getCorrectionDecl();
2770     if (ND && ((isa<VarDecl>(ND) && ND->getKind() == Decl::Var) ||
2771                isa<FunctionDecl>(ND))) {
2772       return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
2773                                    SemaRef.getCurScope());
2774     }
2775     return false;
2776   }
2777 
2778   std::unique_ptr<CorrectionCandidateCallback> clone() override {
2779     return std::make_unique<VarOrFuncDeclFilterCCC>(*this);
2780   }
2781 };
2782 
2783 } // namespace
2784 
2785 ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
2786                                          CXXScopeSpec &ScopeSpec,
2787                                          const DeclarationNameInfo &Id,
2788                                          OpenMPDirectiveKind Kind) {
2789   LookupResult Lookup(*this, Id, LookupOrdinaryName);
2790   LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
2791 
2792   if (Lookup.isAmbiguous())
2793     return ExprError();
2794 
2795   VarDecl *VD;
2796   if (!Lookup.isSingleResult()) {
2797     VarDeclFilterCCC CCC(*this);
2798     if (TypoCorrection Corrected =
2799             CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC,
2800                         CTK_ErrorRecovery)) {
2801       diagnoseTypo(Corrected,
2802                    PDiag(Lookup.empty()
2803                              ? diag::err_undeclared_var_use_suggest
2804                              : diag::err_omp_expected_var_arg_suggest)
2805                        << Id.getName());
2806       VD = Corrected.getCorrectionDeclAs<VarDecl>();
2807     } else {
2808       Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
2809                                        : diag::err_omp_expected_var_arg)
2810           << Id.getName();
2811       return ExprError();
2812     }
2813   } else if (!(VD = Lookup.getAsSingle<VarDecl>())) {
2814     Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
2815     Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
2816     return ExprError();
2817   }
2818   Lookup.suppressDiagnostics();
2819 
2820   // OpenMP [2.9.2, Syntax, C/C++]
2821   //   Variables must be file-scope, namespace-scope, or static block-scope.
2822   if (Kind == OMPD_threadprivate && !VD->hasGlobalStorage()) {
2823     Diag(Id.getLoc(), diag::err_omp_global_var_arg)
2824         << getOpenMPDirectiveName(Kind) << !VD->isStaticLocal();
2825     bool IsDecl =
2826         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2827     Diag(VD->getLocation(),
2828          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2829         << VD;
2830     return ExprError();
2831   }
2832 
2833   VarDecl *CanonicalVD = VD->getCanonicalDecl();
2834   NamedDecl *ND = CanonicalVD;
2835   // OpenMP [2.9.2, Restrictions, C/C++, p.2]
2836   //   A threadprivate directive for file-scope variables must appear outside
2837   //   any definition or declaration.
2838   if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
2839       !getCurLexicalContext()->isTranslationUnit()) {
2840     Diag(Id.getLoc(), diag::err_omp_var_scope)
2841         << getOpenMPDirectiveName(Kind) << VD;
2842     bool IsDecl =
2843         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2844     Diag(VD->getLocation(),
2845          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2846         << VD;
2847     return ExprError();
2848   }
2849   // OpenMP [2.9.2, Restrictions, C/C++, p.3]
2850   //   A threadprivate directive for static class member variables must appear
2851   //   in the class definition, in the same scope in which the member
2852   //   variables are declared.
2853   if (CanonicalVD->isStaticDataMember() &&
2854       !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
2855     Diag(Id.getLoc(), diag::err_omp_var_scope)
2856         << getOpenMPDirectiveName(Kind) << VD;
2857     bool IsDecl =
2858         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2859     Diag(VD->getLocation(),
2860          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2861         << VD;
2862     return ExprError();
2863   }
2864   // OpenMP [2.9.2, Restrictions, C/C++, p.4]
2865   //   A threadprivate directive for namespace-scope variables must appear
2866   //   outside any definition or declaration other than the namespace
2867   //   definition itself.
2868   if (CanonicalVD->getDeclContext()->isNamespace() &&
2869       (!getCurLexicalContext()->isFileContext() ||
2870        !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
2871     Diag(Id.getLoc(), diag::err_omp_var_scope)
2872         << getOpenMPDirectiveName(Kind) << VD;
2873     bool IsDecl =
2874         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2875     Diag(VD->getLocation(),
2876          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2877         << VD;
2878     return ExprError();
2879   }
2880   // OpenMP [2.9.2, Restrictions, C/C++, p.6]
2881   //   A threadprivate directive for static block-scope variables must appear
2882   //   in the scope of the variable and not in a nested scope.
2883   if (CanonicalVD->isLocalVarDecl() && CurScope &&
2884       !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
2885     Diag(Id.getLoc(), diag::err_omp_var_scope)
2886         << getOpenMPDirectiveName(Kind) << VD;
2887     bool IsDecl =
2888         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2889     Diag(VD->getLocation(),
2890          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2891         << VD;
2892     return ExprError();
2893   }
2894 
2895   // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
2896   //   A threadprivate directive must lexically precede all references to any
2897   //   of the variables in its list.
2898   if (Kind == OMPD_threadprivate && VD->isUsed() &&
2899       !DSAStack->isThreadPrivate(VD)) {
2900     Diag(Id.getLoc(), diag::err_omp_var_used)
2901         << getOpenMPDirectiveName(Kind) << VD;
2902     return ExprError();
2903   }
2904 
2905   QualType ExprType = VD->getType().getNonReferenceType();
2906   return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
2907                              SourceLocation(), VD,
2908                              /*RefersToEnclosingVariableOrCapture=*/false,
2909                              Id.getLoc(), ExprType, VK_LValue);
2910 }
2911 
2912 Sema::DeclGroupPtrTy
2913 Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
2914                                         ArrayRef<Expr *> VarList) {
2915   if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
2916     CurContext->addDecl(D);
2917     return DeclGroupPtrTy::make(DeclGroupRef(D));
2918   }
2919   return nullptr;
2920 }
2921 
2922 namespace {
2923 class LocalVarRefChecker final
2924     : public ConstStmtVisitor<LocalVarRefChecker, bool> {
2925   Sema &SemaRef;
2926 
2927 public:
2928   bool VisitDeclRefExpr(const DeclRefExpr *E) {
2929     if (const auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
2930       if (VD->hasLocalStorage()) {
2931         SemaRef.Diag(E->getBeginLoc(),
2932                      diag::err_omp_local_var_in_threadprivate_init)
2933             << E->getSourceRange();
2934         SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
2935             << VD << VD->getSourceRange();
2936         return true;
2937       }
2938     }
2939     return false;
2940   }
2941   bool VisitStmt(const Stmt *S) {
2942     for (const Stmt *Child : S->children()) {
2943       if (Child && Visit(Child))
2944         return true;
2945     }
2946     return false;
2947   }
2948   explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
2949 };
2950 } // namespace
2951 
2952 OMPThreadPrivateDecl *
2953 Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
2954   SmallVector<Expr *, 8> Vars;
2955   for (Expr *RefExpr : VarList) {
2956     auto *DE = cast<DeclRefExpr>(RefExpr);
2957     auto *VD = cast<VarDecl>(DE->getDecl());
2958     SourceLocation ILoc = DE->getExprLoc();
2959 
2960     // Mark variable as used.
2961     VD->setReferenced();
2962     VD->markUsed(Context);
2963 
2964     QualType QType = VD->getType();
2965     if (QType->isDependentType() || QType->isInstantiationDependentType()) {
2966       // It will be analyzed later.
2967       Vars.push_back(DE);
2968       continue;
2969     }
2970 
2971     // OpenMP [2.9.2, Restrictions, C/C++, p.10]
2972     //   A threadprivate variable must not have an incomplete type.
2973     if (RequireCompleteType(ILoc, VD->getType(),
2974                             diag::err_omp_threadprivate_incomplete_type)) {
2975       continue;
2976     }
2977 
2978     // OpenMP [2.9.2, Restrictions, C/C++, p.10]
2979     //   A threadprivate variable must not have a reference type.
2980     if (VD->getType()->isReferenceType()) {
2981       Diag(ILoc, diag::err_omp_ref_type_arg)
2982           << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
2983       bool IsDecl =
2984           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2985       Diag(VD->getLocation(),
2986            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2987           << VD;
2988       continue;
2989     }
2990 
2991     // Check if this is a TLS variable. If TLS is not being supported, produce
2992     // the corresponding diagnostic.
2993     if ((VD->getTLSKind() != VarDecl::TLS_None &&
2994          !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
2995            getLangOpts().OpenMPUseTLS &&
2996            getASTContext().getTargetInfo().isTLSSupported())) ||
2997         (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
2998          !VD->isLocalVarDecl())) {
2999       Diag(ILoc, diag::err_omp_var_thread_local)
3000           << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
3001       bool IsDecl =
3002           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
3003       Diag(VD->getLocation(),
3004            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
3005           << VD;
3006       continue;
3007     }
3008 
3009     // Check if initial value of threadprivate variable reference variable with
3010     // local storage (it is not supported by runtime).
3011     if (const Expr *Init = VD->getAnyInitializer()) {
3012       LocalVarRefChecker Checker(*this);
3013       if (Checker.Visit(Init))
3014         continue;
3015     }
3016 
3017     Vars.push_back(RefExpr);
3018     DSAStack->addDSA(VD, DE, OMPC_threadprivate);
3019     VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
3020         Context, SourceRange(Loc, Loc)));
3021     if (ASTMutationListener *ML = Context.getASTMutationListener())
3022       ML->DeclarationMarkedOpenMPThreadPrivate(VD);
3023   }
3024   OMPThreadPrivateDecl *D = nullptr;
3025   if (!Vars.empty()) {
3026     D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
3027                                      Vars);
3028     D->setAccess(AS_public);
3029   }
3030   return D;
3031 }
3032 
3033 static OMPAllocateDeclAttr::AllocatorTypeTy
3034 getAllocatorKind(Sema &S, DSAStackTy *Stack, Expr *Allocator) {
3035   if (!Allocator)
3036     return OMPAllocateDeclAttr::OMPNullMemAlloc;
3037   if (Allocator->isTypeDependent() || Allocator->isValueDependent() ||
3038       Allocator->isInstantiationDependent() ||
3039       Allocator->containsUnexpandedParameterPack())
3040     return OMPAllocateDeclAttr::OMPUserDefinedMemAlloc;
3041   auto AllocatorKindRes = OMPAllocateDeclAttr::OMPUserDefinedMemAlloc;
3042   const Expr *AE = Allocator->IgnoreParenImpCasts();
3043   for (int I = 0; I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
3044     auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
3045     const Expr *DefAllocator = Stack->getAllocator(AllocatorKind);
3046     llvm::FoldingSetNodeID AEId, DAEId;
3047     AE->Profile(AEId, S.getASTContext(), /*Canonical=*/true);
3048     DefAllocator->Profile(DAEId, S.getASTContext(), /*Canonical=*/true);
3049     if (AEId == DAEId) {
3050       AllocatorKindRes = AllocatorKind;
3051       break;
3052     }
3053   }
3054   return AllocatorKindRes;
3055 }
3056 
3057 static bool checkPreviousOMPAllocateAttribute(
3058     Sema &S, DSAStackTy *Stack, Expr *RefExpr, VarDecl *VD,
3059     OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind, Expr *Allocator) {
3060   if (!VD->hasAttr<OMPAllocateDeclAttr>())
3061     return false;
3062   const auto *A = VD->getAttr<OMPAllocateDeclAttr>();
3063   Expr *PrevAllocator = A->getAllocator();
3064   OMPAllocateDeclAttr::AllocatorTypeTy PrevAllocatorKind =
3065       getAllocatorKind(S, Stack, PrevAllocator);
3066   bool AllocatorsMatch = AllocatorKind == PrevAllocatorKind;
3067   if (AllocatorsMatch &&
3068       AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc &&
3069       Allocator && PrevAllocator) {
3070     const Expr *AE = Allocator->IgnoreParenImpCasts();
3071     const Expr *PAE = PrevAllocator->IgnoreParenImpCasts();
3072     llvm::FoldingSetNodeID AEId, PAEId;
3073     AE->Profile(AEId, S.Context, /*Canonical=*/true);
3074     PAE->Profile(PAEId, S.Context, /*Canonical=*/true);
3075     AllocatorsMatch = AEId == PAEId;
3076   }
3077   if (!AllocatorsMatch) {
3078     SmallString<256> AllocatorBuffer;
3079     llvm::raw_svector_ostream AllocatorStream(AllocatorBuffer);
3080     if (Allocator)
3081       Allocator->printPretty(AllocatorStream, nullptr, S.getPrintingPolicy());
3082     SmallString<256> PrevAllocatorBuffer;
3083     llvm::raw_svector_ostream PrevAllocatorStream(PrevAllocatorBuffer);
3084     if (PrevAllocator)
3085       PrevAllocator->printPretty(PrevAllocatorStream, nullptr,
3086                                  S.getPrintingPolicy());
3087 
3088     SourceLocation AllocatorLoc =
3089         Allocator ? Allocator->getExprLoc() : RefExpr->getExprLoc();
3090     SourceRange AllocatorRange =
3091         Allocator ? Allocator->getSourceRange() : RefExpr->getSourceRange();
3092     SourceLocation PrevAllocatorLoc =
3093         PrevAllocator ? PrevAllocator->getExprLoc() : A->getLocation();
3094     SourceRange PrevAllocatorRange =
3095         PrevAllocator ? PrevAllocator->getSourceRange() : A->getRange();
3096     S.Diag(AllocatorLoc, diag::warn_omp_used_different_allocator)
3097         << (Allocator ? 1 : 0) << AllocatorStream.str()
3098         << (PrevAllocator ? 1 : 0) << PrevAllocatorStream.str()
3099         << AllocatorRange;
3100     S.Diag(PrevAllocatorLoc, diag::note_omp_previous_allocator)
3101         << PrevAllocatorRange;
3102     return true;
3103   }
3104   return false;
3105 }
3106 
3107 static void
3108 applyOMPAllocateAttribute(Sema &S, VarDecl *VD,
3109                           OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind,
3110                           Expr *Allocator, SourceRange SR) {
3111   if (VD->hasAttr<OMPAllocateDeclAttr>())
3112     return;
3113   if (Allocator &&
3114       (Allocator->isTypeDependent() || Allocator->isValueDependent() ||
3115        Allocator->isInstantiationDependent() ||
3116        Allocator->containsUnexpandedParameterPack()))
3117     return;
3118   auto *A = OMPAllocateDeclAttr::CreateImplicit(S.Context, AllocatorKind,
3119                                                 Allocator, SR);
3120   VD->addAttr(A);
3121   if (ASTMutationListener *ML = S.Context.getASTMutationListener())
3122     ML->DeclarationMarkedOpenMPAllocate(VD, A);
3123 }
3124 
3125 Sema::DeclGroupPtrTy Sema::ActOnOpenMPAllocateDirective(
3126     SourceLocation Loc, ArrayRef<Expr *> VarList,
3127     ArrayRef<OMPClause *> Clauses, DeclContext *Owner) {
3128   assert(Clauses.size() <= 1 && "Expected at most one clause.");
3129   Expr *Allocator = nullptr;
3130   if (Clauses.empty()) {
3131     // OpenMP 5.0, 2.11.3 allocate Directive, Restrictions.
3132     // allocate directives that appear in a target region must specify an
3133     // allocator clause unless a requires directive with the dynamic_allocators
3134     // clause is present in the same compilation unit.
3135     if (LangOpts.OpenMPIsDevice &&
3136         !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())
3137       targetDiag(Loc, diag::err_expected_allocator_clause);
3138   } else {
3139     Allocator = cast<OMPAllocatorClause>(Clauses.back())->getAllocator();
3140   }
3141   OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind =
3142       getAllocatorKind(*this, DSAStack, Allocator);
3143   SmallVector<Expr *, 8> Vars;
3144   for (Expr *RefExpr : VarList) {
3145     auto *DE = cast<DeclRefExpr>(RefExpr);
3146     auto *VD = cast<VarDecl>(DE->getDecl());
3147 
3148     // Check if this is a TLS variable or global register.
3149     if (VD->getTLSKind() != VarDecl::TLS_None ||
3150         VD->hasAttr<OMPThreadPrivateDeclAttr>() ||
3151         (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
3152          !VD->isLocalVarDecl()))
3153       continue;
3154 
3155     // If the used several times in the allocate directive, the same allocator
3156     // must be used.
3157     if (checkPreviousOMPAllocateAttribute(*this, DSAStack, RefExpr, VD,
3158                                           AllocatorKind, Allocator))
3159       continue;
3160 
3161     // OpenMP, 2.11.3 allocate Directive, Restrictions, C / C++
3162     // If a list item has a static storage type, the allocator expression in the
3163     // allocator clause must be a constant expression that evaluates to one of
3164     // the predefined memory allocator values.
3165     if (Allocator && VD->hasGlobalStorage()) {
3166       if (AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc) {
3167         Diag(Allocator->getExprLoc(),
3168              diag::err_omp_expected_predefined_allocator)
3169             << Allocator->getSourceRange();
3170         bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
3171                       VarDecl::DeclarationOnly;
3172         Diag(VD->getLocation(),
3173              IsDecl ? diag::note_previous_decl : diag::note_defined_here)
3174             << VD;
3175         continue;
3176       }
3177     }
3178 
3179     Vars.push_back(RefExpr);
3180     applyOMPAllocateAttribute(*this, VD, AllocatorKind, Allocator,
3181                               DE->getSourceRange());
3182   }
3183   if (Vars.empty())
3184     return nullptr;
3185   if (!Owner)
3186     Owner = getCurLexicalContext();
3187   auto *D = OMPAllocateDecl::Create(Context, Owner, Loc, Vars, Clauses);
3188   D->setAccess(AS_public);
3189   Owner->addDecl(D);
3190   return DeclGroupPtrTy::make(DeclGroupRef(D));
3191 }
3192 
3193 Sema::DeclGroupPtrTy
3194 Sema::ActOnOpenMPRequiresDirective(SourceLocation Loc,
3195                                    ArrayRef<OMPClause *> ClauseList) {
3196   OMPRequiresDecl *D = nullptr;
3197   if (!CurContext->isFileContext()) {
3198     Diag(Loc, diag::err_omp_invalid_scope) << "requires";
3199   } else {
3200     D = CheckOMPRequiresDecl(Loc, ClauseList);
3201     if (D) {
3202       CurContext->addDecl(D);
3203       DSAStack->addRequiresDecl(D);
3204     }
3205   }
3206   return DeclGroupPtrTy::make(DeclGroupRef(D));
3207 }
3208 
3209 void Sema::ActOnOpenMPAssumesDirective(SourceLocation Loc,
3210                                        OpenMPDirectiveKind DKind,
3211                                        ArrayRef<StringRef> Assumptions,
3212                                        bool SkippedClauses) {
3213   if (!SkippedClauses && Assumptions.empty())
3214     Diag(Loc, diag::err_omp_no_clause_for_directive)
3215         << llvm::omp::getAllAssumeClauseOptions()
3216         << llvm::omp::getOpenMPDirectiveName(DKind);
3217 
3218   auto *AA = AssumptionAttr::Create(Context, llvm::join(Assumptions, ","), Loc);
3219   if (DKind == llvm::omp::Directive::OMPD_begin_assumes) {
3220     OMPAssumeScoped.push_back(AA);
3221     return;
3222   }
3223 
3224   // Global assumes without assumption clauses are ignored.
3225   if (Assumptions.empty())
3226     return;
3227 
3228   assert(DKind == llvm::omp::Directive::OMPD_assumes &&
3229          "Unexpected omp assumption directive!");
3230   OMPAssumeGlobal.push_back(AA);
3231 
3232   // The OMPAssumeGlobal scope above will take care of new declarations but
3233   // we also want to apply the assumption to existing ones, e.g., to
3234   // declarations in included headers. To this end, we traverse all existing
3235   // declaration contexts and annotate function declarations here.
3236   SmallVector<DeclContext *, 8> DeclContexts;
3237   auto *Ctx = CurContext;
3238   while (Ctx->getLexicalParent())
3239     Ctx = Ctx->getLexicalParent();
3240   DeclContexts.push_back(Ctx);
3241   while (!DeclContexts.empty()) {
3242     DeclContext *DC = DeclContexts.pop_back_val();
3243     for (auto *SubDC : DC->decls()) {
3244       if (SubDC->isInvalidDecl())
3245         continue;
3246       if (auto *CTD = dyn_cast<ClassTemplateDecl>(SubDC)) {
3247         DeclContexts.push_back(CTD->getTemplatedDecl());
3248         for (auto *S : CTD->specializations())
3249           DeclContexts.push_back(S);
3250         continue;
3251       }
3252       if (auto *DC = dyn_cast<DeclContext>(SubDC))
3253         DeclContexts.push_back(DC);
3254       if (auto *F = dyn_cast<FunctionDecl>(SubDC)) {
3255         F->addAttr(AA);
3256         continue;
3257       }
3258     }
3259   }
3260 }
3261 
3262 void Sema::ActOnOpenMPEndAssumesDirective() {
3263   assert(isInOpenMPAssumeScope() && "Not in OpenMP assumes scope!");
3264   OMPAssumeScoped.pop_back();
3265 }
3266 
3267 OMPRequiresDecl *Sema::CheckOMPRequiresDecl(SourceLocation Loc,
3268                                             ArrayRef<OMPClause *> ClauseList) {
3269   /// For target specific clauses, the requires directive cannot be
3270   /// specified after the handling of any of the target regions in the
3271   /// current compilation unit.
3272   ArrayRef<SourceLocation> TargetLocations =
3273       DSAStack->getEncounteredTargetLocs();
3274   SourceLocation AtomicLoc = DSAStack->getAtomicDirectiveLoc();
3275   if (!TargetLocations.empty() || !AtomicLoc.isInvalid()) {
3276     for (const OMPClause *CNew : ClauseList) {
3277       // Check if any of the requires clauses affect target regions.
3278       if (isa<OMPUnifiedSharedMemoryClause>(CNew) ||
3279           isa<OMPUnifiedAddressClause>(CNew) ||
3280           isa<OMPReverseOffloadClause>(CNew) ||
3281           isa<OMPDynamicAllocatorsClause>(CNew)) {
3282         Diag(Loc, diag::err_omp_directive_before_requires)
3283             << "target" << getOpenMPClauseName(CNew->getClauseKind());
3284         for (SourceLocation TargetLoc : TargetLocations) {
3285           Diag(TargetLoc, diag::note_omp_requires_encountered_directive)
3286               << "target";
3287         }
3288       } else if (!AtomicLoc.isInvalid() &&
3289                  isa<OMPAtomicDefaultMemOrderClause>(CNew)) {
3290         Diag(Loc, diag::err_omp_directive_before_requires)
3291             << "atomic" << getOpenMPClauseName(CNew->getClauseKind());
3292         Diag(AtomicLoc, diag::note_omp_requires_encountered_directive)
3293             << "atomic";
3294       }
3295     }
3296   }
3297 
3298   if (!DSAStack->hasDuplicateRequiresClause(ClauseList))
3299     return OMPRequiresDecl::Create(Context, getCurLexicalContext(), Loc,
3300                                    ClauseList);
3301   return nullptr;
3302 }
3303 
3304 static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack,
3305                               const ValueDecl *D,
3306                               const DSAStackTy::DSAVarData &DVar,
3307                               bool IsLoopIterVar) {
3308   if (DVar.RefExpr) {
3309     SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
3310         << getOpenMPClauseName(DVar.CKind);
3311     return;
3312   }
3313   enum {
3314     PDSA_StaticMemberShared,
3315     PDSA_StaticLocalVarShared,
3316     PDSA_LoopIterVarPrivate,
3317     PDSA_LoopIterVarLinear,
3318     PDSA_LoopIterVarLastprivate,
3319     PDSA_ConstVarShared,
3320     PDSA_GlobalVarShared,
3321     PDSA_TaskVarFirstprivate,
3322     PDSA_LocalVarPrivate,
3323     PDSA_Implicit
3324   } Reason = PDSA_Implicit;
3325   bool ReportHint = false;
3326   auto ReportLoc = D->getLocation();
3327   auto *VD = dyn_cast<VarDecl>(D);
3328   if (IsLoopIterVar) {
3329     if (DVar.CKind == OMPC_private)
3330       Reason = PDSA_LoopIterVarPrivate;
3331     else if (DVar.CKind == OMPC_lastprivate)
3332       Reason = PDSA_LoopIterVarLastprivate;
3333     else
3334       Reason = PDSA_LoopIterVarLinear;
3335   } else if (isOpenMPTaskingDirective(DVar.DKind) &&
3336              DVar.CKind == OMPC_firstprivate) {
3337     Reason = PDSA_TaskVarFirstprivate;
3338     ReportLoc = DVar.ImplicitDSALoc;
3339   } else if (VD && VD->isStaticLocal())
3340     Reason = PDSA_StaticLocalVarShared;
3341   else if (VD && VD->isStaticDataMember())
3342     Reason = PDSA_StaticMemberShared;
3343   else if (VD && VD->isFileVarDecl())
3344     Reason = PDSA_GlobalVarShared;
3345   else if (D->getType().isConstant(SemaRef.getASTContext()))
3346     Reason = PDSA_ConstVarShared;
3347   else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
3348     ReportHint = true;
3349     Reason = PDSA_LocalVarPrivate;
3350   }
3351   if (Reason != PDSA_Implicit) {
3352     SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
3353         << Reason << ReportHint
3354         << getOpenMPDirectiveName(Stack->getCurrentDirective());
3355   } else if (DVar.ImplicitDSALoc.isValid()) {
3356     SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
3357         << getOpenMPClauseName(DVar.CKind);
3358   }
3359 }
3360 
3361 static OpenMPMapClauseKind
3362 getMapClauseKindFromModifier(OpenMPDefaultmapClauseModifier M,
3363                              bool IsAggregateOrDeclareTarget) {
3364   OpenMPMapClauseKind Kind = OMPC_MAP_unknown;
3365   switch (M) {
3366   case OMPC_DEFAULTMAP_MODIFIER_alloc:
3367     Kind = OMPC_MAP_alloc;
3368     break;
3369   case OMPC_DEFAULTMAP_MODIFIER_to:
3370     Kind = OMPC_MAP_to;
3371     break;
3372   case OMPC_DEFAULTMAP_MODIFIER_from:
3373     Kind = OMPC_MAP_from;
3374     break;
3375   case OMPC_DEFAULTMAP_MODIFIER_tofrom:
3376     Kind = OMPC_MAP_tofrom;
3377     break;
3378   case OMPC_DEFAULTMAP_MODIFIER_present:
3379     // OpenMP 5.1 [2.21.7.3] defaultmap clause, Description]
3380     // If implicit-behavior is present, each variable referenced in the
3381     // construct in the category specified by variable-category is treated as if
3382     // it had been listed in a map clause with the map-type of alloc and
3383     // map-type-modifier of present.
3384     Kind = OMPC_MAP_alloc;
3385     break;
3386   case OMPC_DEFAULTMAP_MODIFIER_firstprivate:
3387   case OMPC_DEFAULTMAP_MODIFIER_last:
3388     llvm_unreachable("Unexpected defaultmap implicit behavior");
3389   case OMPC_DEFAULTMAP_MODIFIER_none:
3390   case OMPC_DEFAULTMAP_MODIFIER_default:
3391   case OMPC_DEFAULTMAP_MODIFIER_unknown:
3392     // IsAggregateOrDeclareTarget could be true if:
3393     // 1. the implicit behavior for aggregate is tofrom
3394     // 2. it's a declare target link
3395     if (IsAggregateOrDeclareTarget) {
3396       Kind = OMPC_MAP_tofrom;
3397       break;
3398     }
3399     llvm_unreachable("Unexpected defaultmap implicit behavior");
3400   }
3401   assert(Kind != OMPC_MAP_unknown && "Expect map kind to be known");
3402   return Kind;
3403 }
3404 
3405 namespace {
3406 class DSAAttrChecker final : public StmtVisitor<DSAAttrChecker, void> {
3407   DSAStackTy *Stack;
3408   Sema &SemaRef;
3409   bool ErrorFound = false;
3410   bool TryCaptureCXXThisMembers = false;
3411   CapturedStmt *CS = nullptr;
3412   const static unsigned DefaultmapKindNum = OMPC_DEFAULTMAP_pointer + 1;
3413   llvm::SmallVector<Expr *, 4> ImplicitFirstprivate;
3414   llvm::SmallVector<Expr *, 4> ImplicitMap[DefaultmapKindNum][OMPC_MAP_delete];
3415   llvm::SmallVector<OpenMPMapModifierKind, NumberOfOMPMapClauseModifiers>
3416       ImplicitMapModifier[DefaultmapKindNum];
3417   Sema::VarsWithInheritedDSAType VarsWithInheritedDSA;
3418   llvm::SmallDenseSet<const ValueDecl *, 4> ImplicitDeclarations;
3419 
3420   void VisitSubCaptures(OMPExecutableDirective *S) {
3421     // Check implicitly captured variables.
3422     if (!S->hasAssociatedStmt() || !S->getAssociatedStmt())
3423       return;
3424     if (S->getDirectiveKind() == OMPD_atomic ||
3425         S->getDirectiveKind() == OMPD_critical ||
3426         S->getDirectiveKind() == OMPD_section ||
3427         S->getDirectiveKind() == OMPD_master ||
3428         isOpenMPLoopTransformationDirective(S->getDirectiveKind())) {
3429       Visit(S->getAssociatedStmt());
3430       return;
3431     }
3432     visitSubCaptures(S->getInnermostCapturedStmt());
3433     // Try to capture inner this->member references to generate correct mappings
3434     // and diagnostics.
3435     if (TryCaptureCXXThisMembers ||
3436         (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
3437          llvm::any_of(S->getInnermostCapturedStmt()->captures(),
3438                       [](const CapturedStmt::Capture &C) {
3439                         return C.capturesThis();
3440                       }))) {
3441       bool SavedTryCaptureCXXThisMembers = TryCaptureCXXThisMembers;
3442       TryCaptureCXXThisMembers = true;
3443       Visit(S->getInnermostCapturedStmt()->getCapturedStmt());
3444       TryCaptureCXXThisMembers = SavedTryCaptureCXXThisMembers;
3445     }
3446     // In tasks firstprivates are not captured anymore, need to analyze them
3447     // explicitly.
3448     if (isOpenMPTaskingDirective(S->getDirectiveKind()) &&
3449         !isOpenMPTaskLoopDirective(S->getDirectiveKind())) {
3450       for (OMPClause *C : S->clauses())
3451         if (auto *FC = dyn_cast<OMPFirstprivateClause>(C)) {
3452           for (Expr *Ref : FC->varlists())
3453             Visit(Ref);
3454         }
3455     }
3456   }
3457 
3458 public:
3459   void VisitDeclRefExpr(DeclRefExpr *E) {
3460     if (TryCaptureCXXThisMembers || E->isTypeDependent() ||
3461         E->isValueDependent() || E->containsUnexpandedParameterPack() ||
3462         E->isInstantiationDependent())
3463       return;
3464     if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
3465       // Check the datasharing rules for the expressions in the clauses.
3466       if (!CS) {
3467         if (auto *CED = dyn_cast<OMPCapturedExprDecl>(VD))
3468           if (!CED->hasAttr<OMPCaptureNoInitAttr>()) {
3469             Visit(CED->getInit());
3470             return;
3471           }
3472       } else if (VD->isImplicit() || isa<OMPCapturedExprDecl>(VD))
3473         // Do not analyze internal variables and do not enclose them into
3474         // implicit clauses.
3475         return;
3476       VD = VD->getCanonicalDecl();
3477       // Skip internally declared variables.
3478       if (VD->hasLocalStorage() && CS && !CS->capturesVariable(VD) &&
3479           !Stack->isImplicitTaskFirstprivate(VD))
3480         return;
3481       // Skip allocators in uses_allocators clauses.
3482       if (Stack->isUsesAllocatorsDecl(VD).hasValue())
3483         return;
3484 
3485       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
3486       // Check if the variable has explicit DSA set and stop analysis if it so.
3487       if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second)
3488         return;
3489 
3490       // Skip internally declared static variables.
3491       llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
3492           OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
3493       if (VD->hasGlobalStorage() && CS && !CS->capturesVariable(VD) &&
3494           (Stack->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() ||
3495            !Res || *Res != OMPDeclareTargetDeclAttr::MT_Link) &&
3496           !Stack->isImplicitTaskFirstprivate(VD))
3497         return;
3498 
3499       SourceLocation ELoc = E->getExprLoc();
3500       OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
3501       // The default(none) clause requires that each variable that is referenced
3502       // in the construct, and does not have a predetermined data-sharing
3503       // attribute, must have its data-sharing attribute explicitly determined
3504       // by being listed in a data-sharing attribute clause.
3505       if (DVar.CKind == OMPC_unknown &&
3506           (Stack->getDefaultDSA() == DSA_none ||
3507            Stack->getDefaultDSA() == DSA_firstprivate) &&
3508           isImplicitOrExplicitTaskingRegion(DKind) &&
3509           VarsWithInheritedDSA.count(VD) == 0) {
3510         bool InheritedDSA = Stack->getDefaultDSA() == DSA_none;
3511         if (!InheritedDSA && Stack->getDefaultDSA() == DSA_firstprivate) {
3512           DSAStackTy::DSAVarData DVar =
3513               Stack->getImplicitDSA(VD, /*FromParent=*/false);
3514           InheritedDSA = DVar.CKind == OMPC_unknown;
3515         }
3516         if (InheritedDSA)
3517           VarsWithInheritedDSA[VD] = E;
3518         return;
3519       }
3520 
3521       // OpenMP 5.0 [2.19.7.2, defaultmap clause, Description]
3522       // If implicit-behavior is none, each variable referenced in the
3523       // construct that does not have a predetermined data-sharing attribute
3524       // and does not appear in a to or link clause on a declare target
3525       // directive must be listed in a data-mapping attribute clause, a
3526       // data-haring attribute clause (including a data-sharing attribute
3527       // clause on a combined construct where target. is one of the
3528       // constituent constructs), or an is_device_ptr clause.
3529       OpenMPDefaultmapClauseKind ClauseKind =
3530           getVariableCategoryFromDecl(SemaRef.getLangOpts(), VD);
3531       if (SemaRef.getLangOpts().OpenMP >= 50) {
3532         bool IsModifierNone = Stack->getDefaultmapModifier(ClauseKind) ==
3533                               OMPC_DEFAULTMAP_MODIFIER_none;
3534         if (DVar.CKind == OMPC_unknown && IsModifierNone &&
3535             VarsWithInheritedDSA.count(VD) == 0 && !Res) {
3536           // Only check for data-mapping attribute and is_device_ptr here
3537           // since we have already make sure that the declaration does not
3538           // have a data-sharing attribute above
3539           if (!Stack->checkMappableExprComponentListsForDecl(
3540                   VD, /*CurrentRegionOnly=*/true,
3541                   [VD](OMPClauseMappableExprCommon::MappableExprComponentListRef
3542                            MapExprComponents,
3543                        OpenMPClauseKind) {
3544                     auto MI = MapExprComponents.rbegin();
3545                     auto ME = MapExprComponents.rend();
3546                     return MI != ME && MI->getAssociatedDeclaration() == VD;
3547                   })) {
3548             VarsWithInheritedDSA[VD] = E;
3549             return;
3550           }
3551         }
3552       }
3553       if (SemaRef.getLangOpts().OpenMP > 50) {
3554         bool IsModifierPresent = Stack->getDefaultmapModifier(ClauseKind) ==
3555                                  OMPC_DEFAULTMAP_MODIFIER_present;
3556         if (IsModifierPresent) {
3557           if (llvm::find(ImplicitMapModifier[ClauseKind],
3558                          OMPC_MAP_MODIFIER_present) ==
3559               std::end(ImplicitMapModifier[ClauseKind])) {
3560             ImplicitMapModifier[ClauseKind].push_back(
3561                 OMPC_MAP_MODIFIER_present);
3562           }
3563         }
3564       }
3565 
3566       if (isOpenMPTargetExecutionDirective(DKind) &&
3567           !Stack->isLoopControlVariable(VD).first) {
3568         if (!Stack->checkMappableExprComponentListsForDecl(
3569                 VD, /*CurrentRegionOnly=*/true,
3570                 [this](OMPClauseMappableExprCommon::MappableExprComponentListRef
3571                            StackComponents,
3572                        OpenMPClauseKind) {
3573                   if (SemaRef.LangOpts.OpenMP >= 50)
3574                     return !StackComponents.empty();
3575                   // Variable is used if it has been marked as an array, array
3576                   // section, array shaping or the variable iself.
3577                   return StackComponents.size() == 1 ||
3578                          std::all_of(
3579                              std::next(StackComponents.rbegin()),
3580                              StackComponents.rend(),
3581                              [](const OMPClauseMappableExprCommon::
3582                                     MappableComponent &MC) {
3583                                return MC.getAssociatedDeclaration() ==
3584                                           nullptr &&
3585                                       (isa<OMPArraySectionExpr>(
3586                                            MC.getAssociatedExpression()) ||
3587                                        isa<OMPArrayShapingExpr>(
3588                                            MC.getAssociatedExpression()) ||
3589                                        isa<ArraySubscriptExpr>(
3590                                            MC.getAssociatedExpression()));
3591                              });
3592                 })) {
3593           bool IsFirstprivate = false;
3594           // By default lambdas are captured as firstprivates.
3595           if (const auto *RD =
3596                   VD->getType().getNonReferenceType()->getAsCXXRecordDecl())
3597             IsFirstprivate = RD->isLambda();
3598           IsFirstprivate =
3599               IsFirstprivate || (Stack->mustBeFirstprivate(ClauseKind) && !Res);
3600           if (IsFirstprivate) {
3601             ImplicitFirstprivate.emplace_back(E);
3602           } else {
3603             OpenMPDefaultmapClauseModifier M =
3604                 Stack->getDefaultmapModifier(ClauseKind);
3605             OpenMPMapClauseKind Kind = getMapClauseKindFromModifier(
3606                 M, ClauseKind == OMPC_DEFAULTMAP_aggregate || Res);
3607             ImplicitMap[ClauseKind][Kind].emplace_back(E);
3608           }
3609           return;
3610         }
3611       }
3612 
3613       // OpenMP [2.9.3.6, Restrictions, p.2]
3614       //  A list item that appears in a reduction clause of the innermost
3615       //  enclosing worksharing or parallel construct may not be accessed in an
3616       //  explicit task.
3617       DVar = Stack->hasInnermostDSA(
3618           VD,
3619           [](OpenMPClauseKind C, bool AppliedToPointee) {
3620             return C == OMPC_reduction && !AppliedToPointee;
3621           },
3622           [](OpenMPDirectiveKind K) {
3623             return isOpenMPParallelDirective(K) ||
3624                    isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
3625           },
3626           /*FromParent=*/true);
3627       if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
3628         ErrorFound = true;
3629         SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
3630         reportOriginalDsa(SemaRef, Stack, VD, DVar);
3631         return;
3632       }
3633 
3634       // Define implicit data-sharing attributes for task.
3635       DVar = Stack->getImplicitDSA(VD, /*FromParent=*/false);
3636       if (((isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared) ||
3637            (Stack->getDefaultDSA() == DSA_firstprivate &&
3638             DVar.CKind == OMPC_firstprivate && !DVar.RefExpr)) &&
3639           !Stack->isLoopControlVariable(VD).first) {
3640         ImplicitFirstprivate.push_back(E);
3641         return;
3642       }
3643 
3644       // Store implicitly used globals with declare target link for parent
3645       // target.
3646       if (!isOpenMPTargetExecutionDirective(DKind) && Res &&
3647           *Res == OMPDeclareTargetDeclAttr::MT_Link) {
3648         Stack->addToParentTargetRegionLinkGlobals(E);
3649         return;
3650       }
3651     }
3652   }
3653   void VisitMemberExpr(MemberExpr *E) {
3654     if (E->isTypeDependent() || E->isValueDependent() ||
3655         E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
3656       return;
3657     auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
3658     OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
3659     if (auto *TE = dyn_cast<CXXThisExpr>(E->getBase()->IgnoreParenCasts())) {
3660       if (!FD)
3661         return;
3662       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(FD, /*FromParent=*/false);
3663       // Check if the variable has explicit DSA set and stop analysis if it
3664       // so.
3665       if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second)
3666         return;
3667 
3668       if (isOpenMPTargetExecutionDirective(DKind) &&
3669           !Stack->isLoopControlVariable(FD).first &&
3670           !Stack->checkMappableExprComponentListsForDecl(
3671               FD, /*CurrentRegionOnly=*/true,
3672               [](OMPClauseMappableExprCommon::MappableExprComponentListRef
3673                      StackComponents,
3674                  OpenMPClauseKind) {
3675                 return isa<CXXThisExpr>(
3676                     cast<MemberExpr>(
3677                         StackComponents.back().getAssociatedExpression())
3678                         ->getBase()
3679                         ->IgnoreParens());
3680               })) {
3681         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
3682         //  A bit-field cannot appear in a map clause.
3683         //
3684         if (FD->isBitField())
3685           return;
3686 
3687         // Check to see if the member expression is referencing a class that
3688         // has already been explicitly mapped
3689         if (Stack->isClassPreviouslyMapped(TE->getType()))
3690           return;
3691 
3692         OpenMPDefaultmapClauseModifier Modifier =
3693             Stack->getDefaultmapModifier(OMPC_DEFAULTMAP_aggregate);
3694         OpenMPDefaultmapClauseKind ClauseKind =
3695             getVariableCategoryFromDecl(SemaRef.getLangOpts(), FD);
3696         OpenMPMapClauseKind Kind = getMapClauseKindFromModifier(
3697             Modifier, /*IsAggregateOrDeclareTarget*/ true);
3698         ImplicitMap[ClauseKind][Kind].emplace_back(E);
3699         return;
3700       }
3701 
3702       SourceLocation ELoc = E->getExprLoc();
3703       // OpenMP [2.9.3.6, Restrictions, p.2]
3704       //  A list item that appears in a reduction clause of the innermost
3705       //  enclosing worksharing or parallel construct may not be accessed in
3706       //  an  explicit task.
3707       DVar = Stack->hasInnermostDSA(
3708           FD,
3709           [](OpenMPClauseKind C, bool AppliedToPointee) {
3710             return C == OMPC_reduction && !AppliedToPointee;
3711           },
3712           [](OpenMPDirectiveKind K) {
3713             return isOpenMPParallelDirective(K) ||
3714                    isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
3715           },
3716           /*FromParent=*/true);
3717       if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
3718         ErrorFound = true;
3719         SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
3720         reportOriginalDsa(SemaRef, Stack, FD, DVar);
3721         return;
3722       }
3723 
3724       // Define implicit data-sharing attributes for task.
3725       DVar = Stack->getImplicitDSA(FD, /*FromParent=*/false);
3726       if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
3727           !Stack->isLoopControlVariable(FD).first) {
3728         // Check if there is a captured expression for the current field in the
3729         // region. Do not mark it as firstprivate unless there is no captured
3730         // expression.
3731         // TODO: try to make it firstprivate.
3732         if (DVar.CKind != OMPC_unknown)
3733           ImplicitFirstprivate.push_back(E);
3734       }
3735       return;
3736     }
3737     if (isOpenMPTargetExecutionDirective(DKind)) {
3738       OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
3739       if (!checkMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map,
3740                                         Stack->getCurrentDirective(),
3741                                         /*NoDiagnose=*/true))
3742         return;
3743       const auto *VD = cast<ValueDecl>(
3744           CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl());
3745       if (!Stack->checkMappableExprComponentListsForDecl(
3746               VD, /*CurrentRegionOnly=*/true,
3747               [&CurComponents](
3748                   OMPClauseMappableExprCommon::MappableExprComponentListRef
3749                       StackComponents,
3750                   OpenMPClauseKind) {
3751                 auto CCI = CurComponents.rbegin();
3752                 auto CCE = CurComponents.rend();
3753                 for (const auto &SC : llvm::reverse(StackComponents)) {
3754                   // Do both expressions have the same kind?
3755                   if (CCI->getAssociatedExpression()->getStmtClass() !=
3756                       SC.getAssociatedExpression()->getStmtClass())
3757                     if (!((isa<OMPArraySectionExpr>(
3758                                SC.getAssociatedExpression()) ||
3759                            isa<OMPArrayShapingExpr>(
3760                                SC.getAssociatedExpression())) &&
3761                           isa<ArraySubscriptExpr>(
3762                               CCI->getAssociatedExpression())))
3763                       return false;
3764 
3765                   const Decl *CCD = CCI->getAssociatedDeclaration();
3766                   const Decl *SCD = SC.getAssociatedDeclaration();
3767                   CCD = CCD ? CCD->getCanonicalDecl() : nullptr;
3768                   SCD = SCD ? SCD->getCanonicalDecl() : nullptr;
3769                   if (SCD != CCD)
3770                     return false;
3771                   std::advance(CCI, 1);
3772                   if (CCI == CCE)
3773                     break;
3774                 }
3775                 return true;
3776               })) {
3777         Visit(E->getBase());
3778       }
3779     } else if (!TryCaptureCXXThisMembers) {
3780       Visit(E->getBase());
3781     }
3782   }
3783   void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
3784     for (OMPClause *C : S->clauses()) {
3785       // Skip analysis of arguments of implicitly defined firstprivate clause
3786       // for task|target directives.
3787       // Skip analysis of arguments of implicitly defined map clause for target
3788       // directives.
3789       if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) &&
3790                  C->isImplicit() &&
3791                  !isOpenMPTaskingDirective(Stack->getCurrentDirective()))) {
3792         for (Stmt *CC : C->children()) {
3793           if (CC)
3794             Visit(CC);
3795         }
3796       }
3797     }
3798     // Check implicitly captured variables.
3799     VisitSubCaptures(S);
3800   }
3801 
3802   void VisitOMPTileDirective(OMPTileDirective *S) {
3803     // #pragma omp tile does not introduce data sharing.
3804     VisitStmt(S);
3805   }
3806 
3807   void VisitStmt(Stmt *S) {
3808     for (Stmt *C : S->children()) {
3809       if (C) {
3810         // Check implicitly captured variables in the task-based directives to
3811         // check if they must be firstprivatized.
3812         Visit(C);
3813       }
3814     }
3815   }
3816 
3817   void visitSubCaptures(CapturedStmt *S) {
3818     for (const CapturedStmt::Capture &Cap : S->captures()) {
3819       if (!Cap.capturesVariable() && !Cap.capturesVariableByCopy())
3820         continue;
3821       VarDecl *VD = Cap.getCapturedVar();
3822       // Do not try to map the variable if it or its sub-component was mapped
3823       // already.
3824       if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
3825           Stack->checkMappableExprComponentListsForDecl(
3826               VD, /*CurrentRegionOnly=*/true,
3827               [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
3828                  OpenMPClauseKind) { return true; }))
3829         continue;
3830       DeclRefExpr *DRE = buildDeclRefExpr(
3831           SemaRef, VD, VD->getType().getNonLValueExprType(SemaRef.Context),
3832           Cap.getLocation(), /*RefersToCapture=*/true);
3833       Visit(DRE);
3834     }
3835   }
3836   bool isErrorFound() const { return ErrorFound; }
3837   ArrayRef<Expr *> getImplicitFirstprivate() const {
3838     return ImplicitFirstprivate;
3839   }
3840   ArrayRef<Expr *> getImplicitMap(OpenMPDefaultmapClauseKind DK,
3841                                   OpenMPMapClauseKind MK) const {
3842     return ImplicitMap[DK][MK];
3843   }
3844   ArrayRef<OpenMPMapModifierKind>
3845   getImplicitMapModifier(OpenMPDefaultmapClauseKind Kind) const {
3846     return ImplicitMapModifier[Kind];
3847   }
3848   const Sema::VarsWithInheritedDSAType &getVarsWithInheritedDSA() const {
3849     return VarsWithInheritedDSA;
3850   }
3851 
3852   DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
3853       : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {
3854     // Process declare target link variables for the target directives.
3855     if (isOpenMPTargetExecutionDirective(S->getCurrentDirective())) {
3856       for (DeclRefExpr *E : Stack->getLinkGlobals())
3857         Visit(E);
3858     }
3859   }
3860 };
3861 } // namespace
3862 
3863 void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
3864   switch (DKind) {
3865   case OMPD_parallel:
3866   case OMPD_parallel_for:
3867   case OMPD_parallel_for_simd:
3868   case OMPD_parallel_sections:
3869   case OMPD_parallel_master:
3870   case OMPD_teams:
3871   case OMPD_teams_distribute:
3872   case OMPD_teams_distribute_simd: {
3873     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3874     QualType KmpInt32PtrTy =
3875         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3876     Sema::CapturedParamNameType Params[] = {
3877         std::make_pair(".global_tid.", KmpInt32PtrTy),
3878         std::make_pair(".bound_tid.", KmpInt32PtrTy),
3879         std::make_pair(StringRef(), QualType()) // __context with shared vars
3880     };
3881     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3882                              Params);
3883     break;
3884   }
3885   case OMPD_target_teams:
3886   case OMPD_target_parallel:
3887   case OMPD_target_parallel_for:
3888   case OMPD_target_parallel_for_simd:
3889   case OMPD_target_teams_distribute:
3890   case OMPD_target_teams_distribute_simd: {
3891     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3892     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3893     QualType KmpInt32PtrTy =
3894         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3895     QualType Args[] = {VoidPtrTy};
3896     FunctionProtoType::ExtProtoInfo EPI;
3897     EPI.Variadic = true;
3898     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3899     Sema::CapturedParamNameType Params[] = {
3900         std::make_pair(".global_tid.", KmpInt32Ty),
3901         std::make_pair(".part_id.", KmpInt32PtrTy),
3902         std::make_pair(".privates.", VoidPtrTy),
3903         std::make_pair(
3904             ".copy_fn.",
3905             Context.getPointerType(CopyFnType).withConst().withRestrict()),
3906         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3907         std::make_pair(StringRef(), QualType()) // __context with shared vars
3908     };
3909     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3910                              Params, /*OpenMPCaptureLevel=*/0);
3911     // Mark this captured region as inlined, because we don't use outlined
3912     // function directly.
3913     getCurCapturedRegion()->TheCapturedDecl->addAttr(
3914         AlwaysInlineAttr::CreateImplicit(
3915             Context, {}, AttributeCommonInfo::AS_Keyword,
3916             AlwaysInlineAttr::Keyword_forceinline));
3917     Sema::CapturedParamNameType ParamsTarget[] = {
3918         std::make_pair(StringRef(), QualType()) // __context with shared vars
3919     };
3920     // Start a captured region for 'target' with no implicit parameters.
3921     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3922                              ParamsTarget, /*OpenMPCaptureLevel=*/1);
3923     Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
3924         std::make_pair(".global_tid.", KmpInt32PtrTy),
3925         std::make_pair(".bound_tid.", KmpInt32PtrTy),
3926         std::make_pair(StringRef(), QualType()) // __context with shared vars
3927     };
3928     // Start a captured region for 'teams' or 'parallel'.  Both regions have
3929     // the same implicit parameters.
3930     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3931                              ParamsTeamsOrParallel, /*OpenMPCaptureLevel=*/2);
3932     break;
3933   }
3934   case OMPD_target:
3935   case OMPD_target_simd: {
3936     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3937     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3938     QualType KmpInt32PtrTy =
3939         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3940     QualType Args[] = {VoidPtrTy};
3941     FunctionProtoType::ExtProtoInfo EPI;
3942     EPI.Variadic = true;
3943     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3944     Sema::CapturedParamNameType Params[] = {
3945         std::make_pair(".global_tid.", KmpInt32Ty),
3946         std::make_pair(".part_id.", KmpInt32PtrTy),
3947         std::make_pair(".privates.", VoidPtrTy),
3948         std::make_pair(
3949             ".copy_fn.",
3950             Context.getPointerType(CopyFnType).withConst().withRestrict()),
3951         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3952         std::make_pair(StringRef(), QualType()) // __context with shared vars
3953     };
3954     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3955                              Params, /*OpenMPCaptureLevel=*/0);
3956     // Mark this captured region as inlined, because we don't use outlined
3957     // function directly.
3958     getCurCapturedRegion()->TheCapturedDecl->addAttr(
3959         AlwaysInlineAttr::CreateImplicit(
3960             Context, {}, AttributeCommonInfo::AS_Keyword,
3961             AlwaysInlineAttr::Keyword_forceinline));
3962     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3963                              std::make_pair(StringRef(), QualType()),
3964                              /*OpenMPCaptureLevel=*/1);
3965     break;
3966   }
3967   case OMPD_atomic:
3968   case OMPD_critical:
3969   case OMPD_section:
3970   case OMPD_master:
3971   case OMPD_tile:
3972     break;
3973   case OMPD_simd:
3974   case OMPD_for:
3975   case OMPD_for_simd:
3976   case OMPD_sections:
3977   case OMPD_single:
3978   case OMPD_taskgroup:
3979   case OMPD_distribute:
3980   case OMPD_distribute_simd:
3981   case OMPD_ordered:
3982   case OMPD_target_data: {
3983     Sema::CapturedParamNameType Params[] = {
3984         std::make_pair(StringRef(), QualType()) // __context with shared vars
3985     };
3986     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3987                              Params);
3988     break;
3989   }
3990   case OMPD_task: {
3991     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3992     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3993     QualType KmpInt32PtrTy =
3994         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3995     QualType Args[] = {VoidPtrTy};
3996     FunctionProtoType::ExtProtoInfo EPI;
3997     EPI.Variadic = true;
3998     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3999     Sema::CapturedParamNameType Params[] = {
4000         std::make_pair(".global_tid.", KmpInt32Ty),
4001         std::make_pair(".part_id.", KmpInt32PtrTy),
4002         std::make_pair(".privates.", VoidPtrTy),
4003         std::make_pair(
4004             ".copy_fn.",
4005             Context.getPointerType(CopyFnType).withConst().withRestrict()),
4006         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
4007         std::make_pair(StringRef(), QualType()) // __context with shared vars
4008     };
4009     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4010                              Params);
4011     // Mark this captured region as inlined, because we don't use outlined
4012     // function directly.
4013     getCurCapturedRegion()->TheCapturedDecl->addAttr(
4014         AlwaysInlineAttr::CreateImplicit(
4015             Context, {}, AttributeCommonInfo::AS_Keyword,
4016             AlwaysInlineAttr::Keyword_forceinline));
4017     break;
4018   }
4019   case OMPD_taskloop:
4020   case OMPD_taskloop_simd:
4021   case OMPD_master_taskloop:
4022   case OMPD_master_taskloop_simd: {
4023     QualType KmpInt32Ty =
4024         Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1)
4025             .withConst();
4026     QualType KmpUInt64Ty =
4027         Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0)
4028             .withConst();
4029     QualType KmpInt64Ty =
4030         Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1)
4031             .withConst();
4032     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
4033     QualType KmpInt32PtrTy =
4034         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
4035     QualType Args[] = {VoidPtrTy};
4036     FunctionProtoType::ExtProtoInfo EPI;
4037     EPI.Variadic = true;
4038     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
4039     Sema::CapturedParamNameType Params[] = {
4040         std::make_pair(".global_tid.", KmpInt32Ty),
4041         std::make_pair(".part_id.", KmpInt32PtrTy),
4042         std::make_pair(".privates.", VoidPtrTy),
4043         std::make_pair(
4044             ".copy_fn.",
4045             Context.getPointerType(CopyFnType).withConst().withRestrict()),
4046         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
4047         std::make_pair(".lb.", KmpUInt64Ty),
4048         std::make_pair(".ub.", KmpUInt64Ty),
4049         std::make_pair(".st.", KmpInt64Ty),
4050         std::make_pair(".liter.", KmpInt32Ty),
4051         std::make_pair(".reductions.", VoidPtrTy),
4052         std::make_pair(StringRef(), QualType()) // __context with shared vars
4053     };
4054     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4055                              Params);
4056     // Mark this captured region as inlined, because we don't use outlined
4057     // function directly.
4058     getCurCapturedRegion()->TheCapturedDecl->addAttr(
4059         AlwaysInlineAttr::CreateImplicit(
4060             Context, {}, AttributeCommonInfo::AS_Keyword,
4061             AlwaysInlineAttr::Keyword_forceinline));
4062     break;
4063   }
4064   case OMPD_parallel_master_taskloop:
4065   case OMPD_parallel_master_taskloop_simd: {
4066     QualType KmpInt32Ty =
4067         Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1)
4068             .withConst();
4069     QualType KmpUInt64Ty =
4070         Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0)
4071             .withConst();
4072     QualType KmpInt64Ty =
4073         Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1)
4074             .withConst();
4075     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
4076     QualType KmpInt32PtrTy =
4077         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
4078     Sema::CapturedParamNameType ParamsParallel[] = {
4079         std::make_pair(".global_tid.", KmpInt32PtrTy),
4080         std::make_pair(".bound_tid.", KmpInt32PtrTy),
4081         std::make_pair(StringRef(), QualType()) // __context with shared vars
4082     };
4083     // Start a captured region for 'parallel'.
4084     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4085                              ParamsParallel, /*OpenMPCaptureLevel=*/0);
4086     QualType Args[] = {VoidPtrTy};
4087     FunctionProtoType::ExtProtoInfo EPI;
4088     EPI.Variadic = true;
4089     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
4090     Sema::CapturedParamNameType Params[] = {
4091         std::make_pair(".global_tid.", KmpInt32Ty),
4092         std::make_pair(".part_id.", KmpInt32PtrTy),
4093         std::make_pair(".privates.", VoidPtrTy),
4094         std::make_pair(
4095             ".copy_fn.",
4096             Context.getPointerType(CopyFnType).withConst().withRestrict()),
4097         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
4098         std::make_pair(".lb.", KmpUInt64Ty),
4099         std::make_pair(".ub.", KmpUInt64Ty),
4100         std::make_pair(".st.", KmpInt64Ty),
4101         std::make_pair(".liter.", KmpInt32Ty),
4102         std::make_pair(".reductions.", VoidPtrTy),
4103         std::make_pair(StringRef(), QualType()) // __context with shared vars
4104     };
4105     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4106                              Params, /*OpenMPCaptureLevel=*/1);
4107     // Mark this captured region as inlined, because we don't use outlined
4108     // function directly.
4109     getCurCapturedRegion()->TheCapturedDecl->addAttr(
4110         AlwaysInlineAttr::CreateImplicit(
4111             Context, {}, AttributeCommonInfo::AS_Keyword,
4112             AlwaysInlineAttr::Keyword_forceinline));
4113     break;
4114   }
4115   case OMPD_distribute_parallel_for_simd:
4116   case OMPD_distribute_parallel_for: {
4117     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
4118     QualType KmpInt32PtrTy =
4119         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
4120     Sema::CapturedParamNameType Params[] = {
4121         std::make_pair(".global_tid.", KmpInt32PtrTy),
4122         std::make_pair(".bound_tid.", KmpInt32PtrTy),
4123         std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
4124         std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
4125         std::make_pair(StringRef(), QualType()) // __context with shared vars
4126     };
4127     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4128                              Params);
4129     break;
4130   }
4131   case OMPD_target_teams_distribute_parallel_for:
4132   case OMPD_target_teams_distribute_parallel_for_simd: {
4133     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
4134     QualType KmpInt32PtrTy =
4135         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
4136     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
4137 
4138     QualType Args[] = {VoidPtrTy};
4139     FunctionProtoType::ExtProtoInfo EPI;
4140     EPI.Variadic = true;
4141     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
4142     Sema::CapturedParamNameType Params[] = {
4143         std::make_pair(".global_tid.", KmpInt32Ty),
4144         std::make_pair(".part_id.", KmpInt32PtrTy),
4145         std::make_pair(".privates.", VoidPtrTy),
4146         std::make_pair(
4147             ".copy_fn.",
4148             Context.getPointerType(CopyFnType).withConst().withRestrict()),
4149         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
4150         std::make_pair(StringRef(), QualType()) // __context with shared vars
4151     };
4152     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4153                              Params, /*OpenMPCaptureLevel=*/0);
4154     // Mark this captured region as inlined, because we don't use outlined
4155     // function directly.
4156     getCurCapturedRegion()->TheCapturedDecl->addAttr(
4157         AlwaysInlineAttr::CreateImplicit(
4158             Context, {}, AttributeCommonInfo::AS_Keyword,
4159             AlwaysInlineAttr::Keyword_forceinline));
4160     Sema::CapturedParamNameType ParamsTarget[] = {
4161         std::make_pair(StringRef(), QualType()) // __context with shared vars
4162     };
4163     // Start a captured region for 'target' with no implicit parameters.
4164     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4165                              ParamsTarget, /*OpenMPCaptureLevel=*/1);
4166 
4167     Sema::CapturedParamNameType ParamsTeams[] = {
4168         std::make_pair(".global_tid.", KmpInt32PtrTy),
4169         std::make_pair(".bound_tid.", KmpInt32PtrTy),
4170         std::make_pair(StringRef(), QualType()) // __context with shared vars
4171     };
4172     // Start a captured region for 'target' with no implicit parameters.
4173     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4174                              ParamsTeams, /*OpenMPCaptureLevel=*/2);
4175 
4176     Sema::CapturedParamNameType ParamsParallel[] = {
4177         std::make_pair(".global_tid.", KmpInt32PtrTy),
4178         std::make_pair(".bound_tid.", KmpInt32PtrTy),
4179         std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
4180         std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
4181         std::make_pair(StringRef(), QualType()) // __context with shared vars
4182     };
4183     // Start a captured region for 'teams' or 'parallel'.  Both regions have
4184     // the same implicit parameters.
4185     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4186                              ParamsParallel, /*OpenMPCaptureLevel=*/3);
4187     break;
4188   }
4189 
4190   case OMPD_teams_distribute_parallel_for:
4191   case OMPD_teams_distribute_parallel_for_simd: {
4192     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
4193     QualType KmpInt32PtrTy =
4194         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
4195 
4196     Sema::CapturedParamNameType ParamsTeams[] = {
4197         std::make_pair(".global_tid.", KmpInt32PtrTy),
4198         std::make_pair(".bound_tid.", KmpInt32PtrTy),
4199         std::make_pair(StringRef(), QualType()) // __context with shared vars
4200     };
4201     // Start a captured region for 'target' with no implicit parameters.
4202     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4203                              ParamsTeams, /*OpenMPCaptureLevel=*/0);
4204 
4205     Sema::CapturedParamNameType ParamsParallel[] = {
4206         std::make_pair(".global_tid.", KmpInt32PtrTy),
4207         std::make_pair(".bound_tid.", KmpInt32PtrTy),
4208         std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
4209         std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
4210         std::make_pair(StringRef(), QualType()) // __context with shared vars
4211     };
4212     // Start a captured region for 'teams' or 'parallel'.  Both regions have
4213     // the same implicit parameters.
4214     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4215                              ParamsParallel, /*OpenMPCaptureLevel=*/1);
4216     break;
4217   }
4218   case OMPD_target_update:
4219   case OMPD_target_enter_data:
4220   case OMPD_target_exit_data: {
4221     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
4222     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
4223     QualType KmpInt32PtrTy =
4224         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
4225     QualType Args[] = {VoidPtrTy};
4226     FunctionProtoType::ExtProtoInfo EPI;
4227     EPI.Variadic = true;
4228     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
4229     Sema::CapturedParamNameType Params[] = {
4230         std::make_pair(".global_tid.", KmpInt32Ty),
4231         std::make_pair(".part_id.", KmpInt32PtrTy),
4232         std::make_pair(".privates.", VoidPtrTy),
4233         std::make_pair(
4234             ".copy_fn.",
4235             Context.getPointerType(CopyFnType).withConst().withRestrict()),
4236         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
4237         std::make_pair(StringRef(), QualType()) // __context with shared vars
4238     };
4239     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4240                              Params);
4241     // Mark this captured region as inlined, because we don't use outlined
4242     // function directly.
4243     getCurCapturedRegion()->TheCapturedDecl->addAttr(
4244         AlwaysInlineAttr::CreateImplicit(
4245             Context, {}, AttributeCommonInfo::AS_Keyword,
4246             AlwaysInlineAttr::Keyword_forceinline));
4247     break;
4248   }
4249   case OMPD_threadprivate:
4250   case OMPD_allocate:
4251   case OMPD_taskyield:
4252   case OMPD_barrier:
4253   case OMPD_taskwait:
4254   case OMPD_cancellation_point:
4255   case OMPD_cancel:
4256   case OMPD_flush:
4257   case OMPD_depobj:
4258   case OMPD_scan:
4259   case OMPD_declare_reduction:
4260   case OMPD_declare_mapper:
4261   case OMPD_declare_simd:
4262   case OMPD_declare_target:
4263   case OMPD_end_declare_target:
4264   case OMPD_requires:
4265   case OMPD_declare_variant:
4266   case OMPD_begin_declare_variant:
4267   case OMPD_end_declare_variant:
4268     llvm_unreachable("OpenMP Directive is not allowed");
4269   case OMPD_unknown:
4270   default:
4271     llvm_unreachable("Unknown OpenMP directive");
4272   }
4273   DSAStack->setContext(CurContext);
4274 }
4275 
4276 int Sema::getNumberOfConstructScopes(unsigned Level) const {
4277   return getOpenMPCaptureLevels(DSAStack->getDirective(Level));
4278 }
4279 
4280 int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
4281   SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
4282   getOpenMPCaptureRegions(CaptureRegions, DKind);
4283   return CaptureRegions.size();
4284 }
4285 
4286 static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
4287                                              Expr *CaptureExpr, bool WithInit,
4288                                              bool AsExpression) {
4289   assert(CaptureExpr);
4290   ASTContext &C = S.getASTContext();
4291   Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
4292   QualType Ty = Init->getType();
4293   if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
4294     if (S.getLangOpts().CPlusPlus) {
4295       Ty = C.getLValueReferenceType(Ty);
4296     } else {
4297       Ty = C.getPointerType(Ty);
4298       ExprResult Res =
4299           S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
4300       if (!Res.isUsable())
4301         return nullptr;
4302       Init = Res.get();
4303     }
4304     WithInit = true;
4305   }
4306   auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
4307                                           CaptureExpr->getBeginLoc());
4308   if (!WithInit)
4309     CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C));
4310   S.CurContext->addHiddenDecl(CED);
4311   Sema::TentativeAnalysisScope Trap(S);
4312   S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
4313   return CED;
4314 }
4315 
4316 static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
4317                                  bool WithInit) {
4318   OMPCapturedExprDecl *CD;
4319   if (VarDecl *VD = S.isOpenMPCapturedDecl(D))
4320     CD = cast<OMPCapturedExprDecl>(VD);
4321   else
4322     CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
4323                           /*AsExpression=*/false);
4324   return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
4325                           CaptureExpr->getExprLoc());
4326 }
4327 
4328 static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
4329   CaptureExpr = S.DefaultLvalueConversion(CaptureExpr).get();
4330   if (!Ref) {
4331     OMPCapturedExprDecl *CD = buildCaptureDecl(
4332         S, &S.getASTContext().Idents.get(".capture_expr."), CaptureExpr,
4333         /*WithInit=*/true, /*AsExpression=*/true);
4334     Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
4335                            CaptureExpr->getExprLoc());
4336   }
4337   ExprResult Res = Ref;
4338   if (!S.getLangOpts().CPlusPlus &&
4339       CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
4340       Ref->getType()->isPointerType()) {
4341     Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
4342     if (!Res.isUsable())
4343       return ExprError();
4344   }
4345   return S.DefaultLvalueConversion(Res.get());
4346 }
4347 
4348 namespace {
4349 // OpenMP directives parsed in this section are represented as a
4350 // CapturedStatement with an associated statement.  If a syntax error
4351 // is detected during the parsing of the associated statement, the
4352 // compiler must abort processing and close the CapturedStatement.
4353 //
4354 // Combined directives such as 'target parallel' have more than one
4355 // nested CapturedStatements.  This RAII ensures that we unwind out
4356 // of all the nested CapturedStatements when an error is found.
4357 class CaptureRegionUnwinderRAII {
4358 private:
4359   Sema &S;
4360   bool &ErrorFound;
4361   OpenMPDirectiveKind DKind = OMPD_unknown;
4362 
4363 public:
4364   CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
4365                             OpenMPDirectiveKind DKind)
4366       : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
4367   ~CaptureRegionUnwinderRAII() {
4368     if (ErrorFound) {
4369       int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
4370       while (--ThisCaptureLevel >= 0)
4371         S.ActOnCapturedRegionError();
4372     }
4373   }
4374 };
4375 } // namespace
4376 
4377 void Sema::tryCaptureOpenMPLambdas(ValueDecl *V) {
4378   // Capture variables captured by reference in lambdas for target-based
4379   // directives.
4380   if (!CurContext->isDependentContext() &&
4381       (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) ||
4382        isOpenMPTargetDataManagementDirective(
4383            DSAStack->getCurrentDirective()))) {
4384     QualType Type = V->getType();
4385     if (const auto *RD = Type.getCanonicalType()
4386                              .getNonReferenceType()
4387                              ->getAsCXXRecordDecl()) {
4388       bool SavedForceCaptureByReferenceInTargetExecutable =
4389           DSAStack->isForceCaptureByReferenceInTargetExecutable();
4390       DSAStack->setForceCaptureByReferenceInTargetExecutable(
4391           /*V=*/true);
4392       if (RD->isLambda()) {
4393         llvm::DenseMap<const VarDecl *, FieldDecl *> Captures;
4394         FieldDecl *ThisCapture;
4395         RD->getCaptureFields(Captures, ThisCapture);
4396         for (const LambdaCapture &LC : RD->captures()) {
4397           if (LC.getCaptureKind() == LCK_ByRef) {
4398             VarDecl *VD = LC.getCapturedVar();
4399             DeclContext *VDC = VD->getDeclContext();
4400             if (!VDC->Encloses(CurContext))
4401               continue;
4402             MarkVariableReferenced(LC.getLocation(), VD);
4403           } else if (LC.getCaptureKind() == LCK_This) {
4404             QualType ThisTy = getCurrentThisType();
4405             if (!ThisTy.isNull() &&
4406                 Context.typesAreCompatible(ThisTy, ThisCapture->getType()))
4407               CheckCXXThisCapture(LC.getLocation());
4408           }
4409         }
4410       }
4411       DSAStack->setForceCaptureByReferenceInTargetExecutable(
4412           SavedForceCaptureByReferenceInTargetExecutable);
4413     }
4414   }
4415 }
4416 
4417 static bool checkOrderedOrderSpecified(Sema &S,
4418                                        const ArrayRef<OMPClause *> Clauses) {
4419   const OMPOrderedClause *Ordered = nullptr;
4420   const OMPOrderClause *Order = nullptr;
4421 
4422   for (const OMPClause *Clause : Clauses) {
4423     if (Clause->getClauseKind() == OMPC_ordered)
4424       Ordered = cast<OMPOrderedClause>(Clause);
4425     else if (Clause->getClauseKind() == OMPC_order) {
4426       Order = cast<OMPOrderClause>(Clause);
4427       if (Order->getKind() != OMPC_ORDER_concurrent)
4428         Order = nullptr;
4429     }
4430     if (Ordered && Order)
4431       break;
4432   }
4433 
4434   if (Ordered && Order) {
4435     S.Diag(Order->getKindKwLoc(),
4436            diag::err_omp_simple_clause_incompatible_with_ordered)
4437         << getOpenMPClauseName(OMPC_order)
4438         << getOpenMPSimpleClauseTypeName(OMPC_order, OMPC_ORDER_concurrent)
4439         << SourceRange(Order->getBeginLoc(), Order->getEndLoc());
4440     S.Diag(Ordered->getBeginLoc(), diag::note_omp_ordered_param)
4441         << 0 << SourceRange(Ordered->getBeginLoc(), Ordered->getEndLoc());
4442     return true;
4443   }
4444   return false;
4445 }
4446 
4447 StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
4448                                       ArrayRef<OMPClause *> Clauses) {
4449   if (DSAStack->getCurrentDirective() == OMPD_atomic ||
4450       DSAStack->getCurrentDirective() == OMPD_critical ||
4451       DSAStack->getCurrentDirective() == OMPD_section ||
4452       DSAStack->getCurrentDirective() == OMPD_master)
4453     return S;
4454 
4455   bool ErrorFound = false;
4456   CaptureRegionUnwinderRAII CaptureRegionUnwinder(
4457       *this, ErrorFound, DSAStack->getCurrentDirective());
4458   if (!S.isUsable()) {
4459     ErrorFound = true;
4460     return StmtError();
4461   }
4462 
4463   SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
4464   getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
4465   OMPOrderedClause *OC = nullptr;
4466   OMPScheduleClause *SC = nullptr;
4467   SmallVector<const OMPLinearClause *, 4> LCs;
4468   SmallVector<const OMPClauseWithPreInit *, 4> PICs;
4469   // This is required for proper codegen.
4470   for (OMPClause *Clause : Clauses) {
4471     if (!LangOpts.OpenMPSimd &&
4472         isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) &&
4473         Clause->getClauseKind() == OMPC_in_reduction) {
4474       // Capture taskgroup task_reduction descriptors inside the tasking regions
4475       // with the corresponding in_reduction items.
4476       auto *IRC = cast<OMPInReductionClause>(Clause);
4477       for (Expr *E : IRC->taskgroup_descriptors())
4478         if (E)
4479           MarkDeclarationsReferencedInExpr(E);
4480     }
4481     if (isOpenMPPrivate(Clause->getClauseKind()) ||
4482         Clause->getClauseKind() == OMPC_copyprivate ||
4483         (getLangOpts().OpenMPUseTLS &&
4484          getASTContext().getTargetInfo().isTLSSupported() &&
4485          Clause->getClauseKind() == OMPC_copyin)) {
4486       DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
4487       // Mark all variables in private list clauses as used in inner region.
4488       for (Stmt *VarRef : Clause->children()) {
4489         if (auto *E = cast_or_null<Expr>(VarRef)) {
4490           MarkDeclarationsReferencedInExpr(E);
4491         }
4492       }
4493       DSAStack->setForceVarCapturing(/*V=*/false);
4494     } else if (isOpenMPLoopTransformationDirective(
4495                    DSAStack->getCurrentDirective())) {
4496       assert(CaptureRegions.empty() &&
4497              "No captured regions in loop transformation directives.");
4498     } else if (CaptureRegions.size() > 1 ||
4499                CaptureRegions.back() != OMPD_unknown) {
4500       if (auto *C = OMPClauseWithPreInit::get(Clause))
4501         PICs.push_back(C);
4502       if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
4503         if (Expr *E = C->getPostUpdateExpr())
4504           MarkDeclarationsReferencedInExpr(E);
4505       }
4506     }
4507     if (Clause->getClauseKind() == OMPC_schedule)
4508       SC = cast<OMPScheduleClause>(Clause);
4509     else if (Clause->getClauseKind() == OMPC_ordered)
4510       OC = cast<OMPOrderedClause>(Clause);
4511     else if (Clause->getClauseKind() == OMPC_linear)
4512       LCs.push_back(cast<OMPLinearClause>(Clause));
4513   }
4514   // Capture allocator expressions if used.
4515   for (Expr *E : DSAStack->getInnerAllocators())
4516     MarkDeclarationsReferencedInExpr(E);
4517   // OpenMP, 2.7.1 Loop Construct, Restrictions
4518   // The nonmonotonic modifier cannot be specified if an ordered clause is
4519   // specified.
4520   if (SC &&
4521       (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
4522        SC->getSecondScheduleModifier() ==
4523            OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
4524       OC) {
4525     Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
4526              ? SC->getFirstScheduleModifierLoc()
4527              : SC->getSecondScheduleModifierLoc(),
4528          diag::err_omp_simple_clause_incompatible_with_ordered)
4529         << getOpenMPClauseName(OMPC_schedule)
4530         << getOpenMPSimpleClauseTypeName(OMPC_schedule,
4531                                          OMPC_SCHEDULE_MODIFIER_nonmonotonic)
4532         << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
4533     ErrorFound = true;
4534   }
4535   // OpenMP 5.0, 2.9.2 Worksharing-Loop Construct, Restrictions.
4536   // If an order(concurrent) clause is present, an ordered clause may not appear
4537   // on the same directive.
4538   if (checkOrderedOrderSpecified(*this, Clauses))
4539     ErrorFound = true;
4540   if (!LCs.empty() && OC && OC->getNumForLoops()) {
4541     for (const OMPLinearClause *C : LCs) {
4542       Diag(C->getBeginLoc(), diag::err_omp_linear_ordered)
4543           << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
4544     }
4545     ErrorFound = true;
4546   }
4547   if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
4548       isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
4549       OC->getNumForLoops()) {
4550     Diag(OC->getBeginLoc(), diag::err_omp_ordered_simd)
4551         << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
4552     ErrorFound = true;
4553   }
4554   if (ErrorFound) {
4555     return StmtError();
4556   }
4557   StmtResult SR = S;
4558   unsigned CompletedRegions = 0;
4559   for (OpenMPDirectiveKind ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
4560     // Mark all variables in private list clauses as used in inner region.
4561     // Required for proper codegen of combined directives.
4562     // TODO: add processing for other clauses.
4563     if (ThisCaptureRegion != OMPD_unknown) {
4564       for (const clang::OMPClauseWithPreInit *C : PICs) {
4565         OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
4566         // Find the particular capture region for the clause if the
4567         // directive is a combined one with multiple capture regions.
4568         // If the directive is not a combined one, the capture region
4569         // associated with the clause is OMPD_unknown and is generated
4570         // only once.
4571         if (CaptureRegion == ThisCaptureRegion ||
4572             CaptureRegion == OMPD_unknown) {
4573           if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
4574             for (Decl *D : DS->decls())
4575               MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
4576           }
4577         }
4578       }
4579     }
4580     if (ThisCaptureRegion == OMPD_target) {
4581       // Capture allocator traits in the target region. They are used implicitly
4582       // and, thus, are not captured by default.
4583       for (OMPClause *C : Clauses) {
4584         if (const auto *UAC = dyn_cast<OMPUsesAllocatorsClause>(C)) {
4585           for (unsigned I = 0, End = UAC->getNumberOfAllocators(); I < End;
4586                ++I) {
4587             OMPUsesAllocatorsClause::Data D = UAC->getAllocatorData(I);
4588             if (Expr *E = D.AllocatorTraits)
4589               MarkDeclarationsReferencedInExpr(E);
4590           }
4591           continue;
4592         }
4593       }
4594     }
4595     if (++CompletedRegions == CaptureRegions.size())
4596       DSAStack->setBodyComplete();
4597     SR = ActOnCapturedRegionEnd(SR.get());
4598   }
4599   return SR;
4600 }
4601 
4602 static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
4603                               OpenMPDirectiveKind CancelRegion,
4604                               SourceLocation StartLoc) {
4605   // CancelRegion is only needed for cancel and cancellation_point.
4606   if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
4607     return false;
4608 
4609   if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
4610       CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
4611     return false;
4612 
4613   SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
4614       << getOpenMPDirectiveName(CancelRegion);
4615   return true;
4616 }
4617 
4618 static bool checkNestingOfRegions(Sema &SemaRef, const DSAStackTy *Stack,
4619                                   OpenMPDirectiveKind CurrentRegion,
4620                                   const DeclarationNameInfo &CurrentName,
4621                                   OpenMPDirectiveKind CancelRegion,
4622                                   SourceLocation StartLoc) {
4623   if (Stack->getCurScope()) {
4624     OpenMPDirectiveKind ParentRegion = Stack->getParentDirective();
4625     OpenMPDirectiveKind OffendingRegion = ParentRegion;
4626     bool NestingProhibited = false;
4627     bool CloseNesting = true;
4628     bool OrphanSeen = false;
4629     enum {
4630       NoRecommend,
4631       ShouldBeInParallelRegion,
4632       ShouldBeInOrderedRegion,
4633       ShouldBeInTargetRegion,
4634       ShouldBeInTeamsRegion,
4635       ShouldBeInLoopSimdRegion,
4636     } Recommend = NoRecommend;
4637     if (isOpenMPSimdDirective(ParentRegion) &&
4638         ((SemaRef.LangOpts.OpenMP <= 45 && CurrentRegion != OMPD_ordered) ||
4639          (SemaRef.LangOpts.OpenMP >= 50 && CurrentRegion != OMPD_ordered &&
4640           CurrentRegion != OMPD_simd && CurrentRegion != OMPD_atomic &&
4641           CurrentRegion != OMPD_scan))) {
4642       // OpenMP [2.16, Nesting of Regions]
4643       // OpenMP constructs may not be nested inside a simd region.
4644       // OpenMP [2.8.1,simd Construct, Restrictions]
4645       // An ordered construct with the simd clause is the only OpenMP
4646       // construct that can appear in the simd region.
4647       // Allowing a SIMD construct nested in another SIMD construct is an
4648       // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
4649       // message.
4650       // OpenMP 5.0 [2.9.3.1, simd Construct, Restrictions]
4651       // The only OpenMP constructs that can be encountered during execution of
4652       // a simd region are the atomic construct, the loop construct, the simd
4653       // construct and the ordered construct with the simd clause.
4654       SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
4655                                  ? diag::err_omp_prohibited_region_simd
4656                                  : diag::warn_omp_nesting_simd)
4657           << (SemaRef.LangOpts.OpenMP >= 50 ? 1 : 0);
4658       return CurrentRegion != OMPD_simd;
4659     }
4660     if (ParentRegion == OMPD_atomic) {
4661       // OpenMP [2.16, Nesting of Regions]
4662       // OpenMP constructs may not be nested inside an atomic region.
4663       SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
4664       return true;
4665     }
4666     if (CurrentRegion == OMPD_section) {
4667       // OpenMP [2.7.2, sections Construct, Restrictions]
4668       // Orphaned section directives are prohibited. That is, the section
4669       // directives must appear within the sections construct and must not be
4670       // encountered elsewhere in the sections region.
4671       if (ParentRegion != OMPD_sections &&
4672           ParentRegion != OMPD_parallel_sections) {
4673         SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
4674             << (ParentRegion != OMPD_unknown)
4675             << getOpenMPDirectiveName(ParentRegion);
4676         return true;
4677       }
4678       return false;
4679     }
4680     // Allow some constructs (except teams and cancellation constructs) to be
4681     // orphaned (they could be used in functions, called from OpenMP regions
4682     // with the required preconditions).
4683     if (ParentRegion == OMPD_unknown &&
4684         !isOpenMPNestingTeamsDirective(CurrentRegion) &&
4685         CurrentRegion != OMPD_cancellation_point &&
4686         CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_scan)
4687       return false;
4688     if (CurrentRegion == OMPD_cancellation_point ||
4689         CurrentRegion == OMPD_cancel) {
4690       // OpenMP [2.16, Nesting of Regions]
4691       // A cancellation point construct for which construct-type-clause is
4692       // taskgroup must be nested inside a task construct. A cancellation
4693       // point construct for which construct-type-clause is not taskgroup must
4694       // be closely nested inside an OpenMP construct that matches the type
4695       // specified in construct-type-clause.
4696       // A cancel construct for which construct-type-clause is taskgroup must be
4697       // nested inside a task construct. A cancel construct for which
4698       // construct-type-clause is not taskgroup must be closely nested inside an
4699       // OpenMP construct that matches the type specified in
4700       // construct-type-clause.
4701       NestingProhibited =
4702           !((CancelRegion == OMPD_parallel &&
4703              (ParentRegion == OMPD_parallel ||
4704               ParentRegion == OMPD_target_parallel)) ||
4705             (CancelRegion == OMPD_for &&
4706              (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
4707               ParentRegion == OMPD_target_parallel_for ||
4708               ParentRegion == OMPD_distribute_parallel_for ||
4709               ParentRegion == OMPD_teams_distribute_parallel_for ||
4710               ParentRegion == OMPD_target_teams_distribute_parallel_for)) ||
4711             (CancelRegion == OMPD_taskgroup &&
4712              (ParentRegion == OMPD_task ||
4713               (SemaRef.getLangOpts().OpenMP >= 50 &&
4714                (ParentRegion == OMPD_taskloop ||
4715                 ParentRegion == OMPD_master_taskloop ||
4716                 ParentRegion == OMPD_parallel_master_taskloop)))) ||
4717             (CancelRegion == OMPD_sections &&
4718              (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
4719               ParentRegion == OMPD_parallel_sections)));
4720       OrphanSeen = ParentRegion == OMPD_unknown;
4721     } else if (CurrentRegion == OMPD_master) {
4722       // OpenMP [2.16, Nesting of Regions]
4723       // A master region may not be closely nested inside a worksharing,
4724       // atomic, or explicit task region.
4725       NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
4726                           isOpenMPTaskingDirective(ParentRegion);
4727     } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
4728       // OpenMP [2.16, Nesting of Regions]
4729       // A critical region may not be nested (closely or otherwise) inside a
4730       // critical region with the same name. Note that this restriction is not
4731       // sufficient to prevent deadlock.
4732       SourceLocation PreviousCriticalLoc;
4733       bool DeadLock = Stack->hasDirective(
4734           [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
4735                                               const DeclarationNameInfo &DNI,
4736                                               SourceLocation Loc) {
4737             if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
4738               PreviousCriticalLoc = Loc;
4739               return true;
4740             }
4741             return false;
4742           },
4743           false /* skip top directive */);
4744       if (DeadLock) {
4745         SemaRef.Diag(StartLoc,
4746                      diag::err_omp_prohibited_region_critical_same_name)
4747             << CurrentName.getName();
4748         if (PreviousCriticalLoc.isValid())
4749           SemaRef.Diag(PreviousCriticalLoc,
4750                        diag::note_omp_previous_critical_region);
4751         return true;
4752       }
4753     } else if (CurrentRegion == OMPD_barrier) {
4754       // OpenMP [2.16, Nesting of Regions]
4755       // A barrier region may not be closely nested inside a worksharing,
4756       // explicit task, critical, ordered, atomic, or master region.
4757       NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
4758                           isOpenMPTaskingDirective(ParentRegion) ||
4759                           ParentRegion == OMPD_master ||
4760                           ParentRegion == OMPD_parallel_master ||
4761                           ParentRegion == OMPD_critical ||
4762                           ParentRegion == OMPD_ordered;
4763     } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
4764                !isOpenMPParallelDirective(CurrentRegion) &&
4765                !isOpenMPTeamsDirective(CurrentRegion)) {
4766       // OpenMP [2.16, Nesting of Regions]
4767       // A worksharing region may not be closely nested inside a worksharing,
4768       // explicit task, critical, ordered, atomic, or master region.
4769       NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
4770                           isOpenMPTaskingDirective(ParentRegion) ||
4771                           ParentRegion == OMPD_master ||
4772                           ParentRegion == OMPD_parallel_master ||
4773                           ParentRegion == OMPD_critical ||
4774                           ParentRegion == OMPD_ordered;
4775       Recommend = ShouldBeInParallelRegion;
4776     } else if (CurrentRegion == OMPD_ordered) {
4777       // OpenMP [2.16, Nesting of Regions]
4778       // An ordered region may not be closely nested inside a critical,
4779       // atomic, or explicit task region.
4780       // An ordered region must be closely nested inside a loop region (or
4781       // parallel loop region) with an ordered clause.
4782       // OpenMP [2.8.1,simd Construct, Restrictions]
4783       // An ordered construct with the simd clause is the only OpenMP construct
4784       // that can appear in the simd region.
4785       NestingProhibited = ParentRegion == OMPD_critical ||
4786                           isOpenMPTaskingDirective(ParentRegion) ||
4787                           !(isOpenMPSimdDirective(ParentRegion) ||
4788                             Stack->isParentOrderedRegion());
4789       Recommend = ShouldBeInOrderedRegion;
4790     } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
4791       // OpenMP [2.16, Nesting of Regions]
4792       // If specified, a teams construct must be contained within a target
4793       // construct.
4794       NestingProhibited =
4795           (SemaRef.LangOpts.OpenMP <= 45 && ParentRegion != OMPD_target) ||
4796           (SemaRef.LangOpts.OpenMP >= 50 && ParentRegion != OMPD_unknown &&
4797            ParentRegion != OMPD_target);
4798       OrphanSeen = ParentRegion == OMPD_unknown;
4799       Recommend = ShouldBeInTargetRegion;
4800     } else if (CurrentRegion == OMPD_scan) {
4801       // OpenMP [2.16, Nesting of Regions]
4802       // If specified, a teams construct must be contained within a target
4803       // construct.
4804       NestingProhibited =
4805           SemaRef.LangOpts.OpenMP < 50 ||
4806           (ParentRegion != OMPD_simd && ParentRegion != OMPD_for &&
4807            ParentRegion != OMPD_for_simd && ParentRegion != OMPD_parallel_for &&
4808            ParentRegion != OMPD_parallel_for_simd);
4809       OrphanSeen = ParentRegion == OMPD_unknown;
4810       Recommend = ShouldBeInLoopSimdRegion;
4811     }
4812     if (!NestingProhibited &&
4813         !isOpenMPTargetExecutionDirective(CurrentRegion) &&
4814         !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
4815         (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
4816       // OpenMP [2.16, Nesting of Regions]
4817       // distribute, parallel, parallel sections, parallel workshare, and the
4818       // parallel loop and parallel loop SIMD constructs are the only OpenMP
4819       // constructs that can be closely nested in the teams region.
4820       NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
4821                           !isOpenMPDistributeDirective(CurrentRegion);
4822       Recommend = ShouldBeInParallelRegion;
4823     }
4824     if (!NestingProhibited &&
4825         isOpenMPNestingDistributeDirective(CurrentRegion)) {
4826       // OpenMP 4.5 [2.17 Nesting of Regions]
4827       // The region associated with the distribute construct must be strictly
4828       // nested inside a teams region
4829       NestingProhibited =
4830           (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
4831       Recommend = ShouldBeInTeamsRegion;
4832     }
4833     if (!NestingProhibited &&
4834         (isOpenMPTargetExecutionDirective(CurrentRegion) ||
4835          isOpenMPTargetDataManagementDirective(CurrentRegion))) {
4836       // OpenMP 4.5 [2.17 Nesting of Regions]
4837       // If a target, target update, target data, target enter data, or
4838       // target exit data construct is encountered during execution of a
4839       // target region, the behavior is unspecified.
4840       NestingProhibited = Stack->hasDirective(
4841           [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
4842                              SourceLocation) {
4843             if (isOpenMPTargetExecutionDirective(K)) {
4844               OffendingRegion = K;
4845               return true;
4846             }
4847             return false;
4848           },
4849           false /* don't skip top directive */);
4850       CloseNesting = false;
4851     }
4852     if (NestingProhibited) {
4853       if (OrphanSeen) {
4854         SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
4855             << getOpenMPDirectiveName(CurrentRegion) << Recommend;
4856       } else {
4857         SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
4858             << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
4859             << Recommend << getOpenMPDirectiveName(CurrentRegion);
4860       }
4861       return true;
4862     }
4863   }
4864   return false;
4865 }
4866 
4867 struct Kind2Unsigned {
4868   using argument_type = OpenMPDirectiveKind;
4869   unsigned operator()(argument_type DK) { return unsigned(DK); }
4870 };
4871 static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
4872                            ArrayRef<OMPClause *> Clauses,
4873                            ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
4874   bool ErrorFound = false;
4875   unsigned NamedModifiersNumber = 0;
4876   llvm::IndexedMap<const OMPIfClause *, Kind2Unsigned> FoundNameModifiers;
4877   FoundNameModifiers.resize(llvm::omp::Directive_enumSize + 1);
4878   SmallVector<SourceLocation, 4> NameModifierLoc;
4879   for (const OMPClause *C : Clauses) {
4880     if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
4881       // At most one if clause without a directive-name-modifier can appear on
4882       // the directive.
4883       OpenMPDirectiveKind CurNM = IC->getNameModifier();
4884       if (FoundNameModifiers[CurNM]) {
4885         S.Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
4886             << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
4887             << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
4888         ErrorFound = true;
4889       } else if (CurNM != OMPD_unknown) {
4890         NameModifierLoc.push_back(IC->getNameModifierLoc());
4891         ++NamedModifiersNumber;
4892       }
4893       FoundNameModifiers[CurNM] = IC;
4894       if (CurNM == OMPD_unknown)
4895         continue;
4896       // Check if the specified name modifier is allowed for the current
4897       // directive.
4898       // At most one if clause with the particular directive-name-modifier can
4899       // appear on the directive.
4900       bool MatchFound = false;
4901       for (auto NM : AllowedNameModifiers) {
4902         if (CurNM == NM) {
4903           MatchFound = true;
4904           break;
4905         }
4906       }
4907       if (!MatchFound) {
4908         S.Diag(IC->getNameModifierLoc(),
4909                diag::err_omp_wrong_if_directive_name_modifier)
4910             << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
4911         ErrorFound = true;
4912       }
4913     }
4914   }
4915   // If any if clause on the directive includes a directive-name-modifier then
4916   // all if clauses on the directive must include a directive-name-modifier.
4917   if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
4918     if (NamedModifiersNumber == AllowedNameModifiers.size()) {
4919       S.Diag(FoundNameModifiers[OMPD_unknown]->getBeginLoc(),
4920              diag::err_omp_no_more_if_clause);
4921     } else {
4922       std::string Values;
4923       std::string Sep(", ");
4924       unsigned AllowedCnt = 0;
4925       unsigned TotalAllowedNum =
4926           AllowedNameModifiers.size() - NamedModifiersNumber;
4927       for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
4928            ++Cnt) {
4929         OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
4930         if (!FoundNameModifiers[NM]) {
4931           Values += "'";
4932           Values += getOpenMPDirectiveName(NM);
4933           Values += "'";
4934           if (AllowedCnt + 2 == TotalAllowedNum)
4935             Values += " or ";
4936           else if (AllowedCnt + 1 != TotalAllowedNum)
4937             Values += Sep;
4938           ++AllowedCnt;
4939         }
4940       }
4941       S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getBeginLoc(),
4942              diag::err_omp_unnamed_if_clause)
4943           << (TotalAllowedNum > 1) << Values;
4944     }
4945     for (SourceLocation Loc : NameModifierLoc) {
4946       S.Diag(Loc, diag::note_omp_previous_named_if_clause);
4947     }
4948     ErrorFound = true;
4949   }
4950   return ErrorFound;
4951 }
4952 
4953 static std::pair<ValueDecl *, bool> getPrivateItem(Sema &S, Expr *&RefExpr,
4954                                                    SourceLocation &ELoc,
4955                                                    SourceRange &ERange,
4956                                                    bool AllowArraySection) {
4957   if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
4958       RefExpr->containsUnexpandedParameterPack())
4959     return std::make_pair(nullptr, true);
4960 
4961   // OpenMP [3.1, C/C++]
4962   //  A list item is a variable name.
4963   // OpenMP  [2.9.3.3, Restrictions, p.1]
4964   //  A variable that is part of another variable (as an array or
4965   //  structure element) cannot appear in a private clause.
4966   RefExpr = RefExpr->IgnoreParens();
4967   enum {
4968     NoArrayExpr = -1,
4969     ArraySubscript = 0,
4970     OMPArraySection = 1
4971   } IsArrayExpr = NoArrayExpr;
4972   if (AllowArraySection) {
4973     if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
4974       Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
4975       while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
4976         Base = TempASE->getBase()->IgnoreParenImpCasts();
4977       RefExpr = Base;
4978       IsArrayExpr = ArraySubscript;
4979     } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
4980       Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
4981       while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
4982         Base = TempOASE->getBase()->IgnoreParenImpCasts();
4983       while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
4984         Base = TempASE->getBase()->IgnoreParenImpCasts();
4985       RefExpr = Base;
4986       IsArrayExpr = OMPArraySection;
4987     }
4988   }
4989   ELoc = RefExpr->getExprLoc();
4990   ERange = RefExpr->getSourceRange();
4991   RefExpr = RefExpr->IgnoreParenImpCasts();
4992   auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
4993   auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
4994   if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
4995       (S.getCurrentThisType().isNull() || !ME ||
4996        !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
4997        !isa<FieldDecl>(ME->getMemberDecl()))) {
4998     if (IsArrayExpr != NoArrayExpr) {
4999       S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
5000                                                          << ERange;
5001     } else {
5002       S.Diag(ELoc,
5003              AllowArraySection
5004                  ? diag::err_omp_expected_var_name_member_expr_or_array_item
5005                  : diag::err_omp_expected_var_name_member_expr)
5006           << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
5007     }
5008     return std::make_pair(nullptr, false);
5009   }
5010   return std::make_pair(
5011       getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false);
5012 }
5013 
5014 namespace {
5015 /// Checks if the allocator is used in uses_allocators clause to be allowed in
5016 /// target regions.
5017 class AllocatorChecker final : public ConstStmtVisitor<AllocatorChecker, bool> {
5018   DSAStackTy *S = nullptr;
5019 
5020 public:
5021   bool VisitDeclRefExpr(const DeclRefExpr *E) {
5022     return S->isUsesAllocatorsDecl(E->getDecl())
5023                .getValueOr(
5024                    DSAStackTy::UsesAllocatorsDeclKind::AllocatorTrait) ==
5025            DSAStackTy::UsesAllocatorsDeclKind::AllocatorTrait;
5026   }
5027   bool VisitStmt(const Stmt *S) {
5028     for (const Stmt *Child : S->children()) {
5029       if (Child && Visit(Child))
5030         return true;
5031     }
5032     return false;
5033   }
5034   explicit AllocatorChecker(DSAStackTy *S) : S(S) {}
5035 };
5036 } // namespace
5037 
5038 static void checkAllocateClauses(Sema &S, DSAStackTy *Stack,
5039                                  ArrayRef<OMPClause *> Clauses) {
5040   assert(!S.CurContext->isDependentContext() &&
5041          "Expected non-dependent context.");
5042   auto AllocateRange =
5043       llvm::make_filter_range(Clauses, OMPAllocateClause::classof);
5044   llvm::DenseMap<CanonicalDeclPtr<Decl>, CanonicalDeclPtr<VarDecl>>
5045       DeclToCopy;
5046   auto PrivateRange = llvm::make_filter_range(Clauses, [](const OMPClause *C) {
5047     return isOpenMPPrivate(C->getClauseKind());
5048   });
5049   for (OMPClause *Cl : PrivateRange) {
5050     MutableArrayRef<Expr *>::iterator I, It, Et;
5051     if (Cl->getClauseKind() == OMPC_private) {
5052       auto *PC = cast<OMPPrivateClause>(Cl);
5053       I = PC->private_copies().begin();
5054       It = PC->varlist_begin();
5055       Et = PC->varlist_end();
5056     } else if (Cl->getClauseKind() == OMPC_firstprivate) {
5057       auto *PC = cast<OMPFirstprivateClause>(Cl);
5058       I = PC->private_copies().begin();
5059       It = PC->varlist_begin();
5060       Et = PC->varlist_end();
5061     } else if (Cl->getClauseKind() == OMPC_lastprivate) {
5062       auto *PC = cast<OMPLastprivateClause>(Cl);
5063       I = PC->private_copies().begin();
5064       It = PC->varlist_begin();
5065       Et = PC->varlist_end();
5066     } else if (Cl->getClauseKind() == OMPC_linear) {
5067       auto *PC = cast<OMPLinearClause>(Cl);
5068       I = PC->privates().begin();
5069       It = PC->varlist_begin();
5070       Et = PC->varlist_end();
5071     } else if (Cl->getClauseKind() == OMPC_reduction) {
5072       auto *PC = cast<OMPReductionClause>(Cl);
5073       I = PC->privates().begin();
5074       It = PC->varlist_begin();
5075       Et = PC->varlist_end();
5076     } else if (Cl->getClauseKind() == OMPC_task_reduction) {
5077       auto *PC = cast<OMPTaskReductionClause>(Cl);
5078       I = PC->privates().begin();
5079       It = PC->varlist_begin();
5080       Et = PC->varlist_end();
5081     } else if (Cl->getClauseKind() == OMPC_in_reduction) {
5082       auto *PC = cast<OMPInReductionClause>(Cl);
5083       I = PC->privates().begin();
5084       It = PC->varlist_begin();
5085       Et = PC->varlist_end();
5086     } else {
5087       llvm_unreachable("Expected private clause.");
5088     }
5089     for (Expr *E : llvm::make_range(It, Et)) {
5090       if (!*I) {
5091         ++I;
5092         continue;
5093       }
5094       SourceLocation ELoc;
5095       SourceRange ERange;
5096       Expr *SimpleRefExpr = E;
5097       auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
5098                                 /*AllowArraySection=*/true);
5099       DeclToCopy.try_emplace(Res.first,
5100                              cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()));
5101       ++I;
5102     }
5103   }
5104   for (OMPClause *C : AllocateRange) {
5105     auto *AC = cast<OMPAllocateClause>(C);
5106     if (S.getLangOpts().OpenMP >= 50 &&
5107         !Stack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>() &&
5108         isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
5109         AC->getAllocator()) {
5110       Expr *Allocator = AC->getAllocator();
5111       // OpenMP, 2.12.5 target Construct
5112       // Memory allocators that do not appear in a uses_allocators clause cannot
5113       // appear as an allocator in an allocate clause or be used in the target
5114       // region unless a requires directive with the dynamic_allocators clause
5115       // is present in the same compilation unit.
5116       AllocatorChecker Checker(Stack);
5117       if (Checker.Visit(Allocator))
5118         S.Diag(Allocator->getExprLoc(),
5119                diag::err_omp_allocator_not_in_uses_allocators)
5120             << Allocator->getSourceRange();
5121     }
5122     OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind =
5123         getAllocatorKind(S, Stack, AC->getAllocator());
5124     // OpenMP, 2.11.4 allocate Clause, Restrictions.
5125     // For task, taskloop or target directives, allocation requests to memory
5126     // allocators with the trait access set to thread result in unspecified
5127     // behavior.
5128     if (AllocatorKind == OMPAllocateDeclAttr::OMPThreadMemAlloc &&
5129         (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
5130          isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()))) {
5131       S.Diag(AC->getAllocator()->getExprLoc(),
5132              diag::warn_omp_allocate_thread_on_task_target_directive)
5133           << getOpenMPDirectiveName(Stack->getCurrentDirective());
5134     }
5135     for (Expr *E : AC->varlists()) {
5136       SourceLocation ELoc;
5137       SourceRange ERange;
5138       Expr *SimpleRefExpr = E;
5139       auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange);
5140       ValueDecl *VD = Res.first;
5141       DSAStackTy::DSAVarData Data = Stack->getTopDSA(VD, /*FromParent=*/false);
5142       if (!isOpenMPPrivate(Data.CKind)) {
5143         S.Diag(E->getExprLoc(),
5144                diag::err_omp_expected_private_copy_for_allocate);
5145         continue;
5146       }
5147       VarDecl *PrivateVD = DeclToCopy[VD];
5148       if (checkPreviousOMPAllocateAttribute(S, Stack, E, PrivateVD,
5149                                             AllocatorKind, AC->getAllocator()))
5150         continue;
5151       applyOMPAllocateAttribute(S, PrivateVD, AllocatorKind, AC->getAllocator(),
5152                                 E->getSourceRange());
5153     }
5154   }
5155 }
5156 
5157 namespace {
5158 /// Rewrite statements and expressions for Sema \p Actions CurContext.
5159 ///
5160 /// Used to wrap already parsed statements/expressions into a new CapturedStmt
5161 /// context. DeclRefExpr used inside the new context are changed to refer to the
5162 /// captured variable instead.
5163 class CaptureVars : public TreeTransform<CaptureVars> {
5164   using BaseTransform = TreeTransform<CaptureVars>;
5165 
5166 public:
5167   CaptureVars(Sema &Actions) : BaseTransform(Actions) {}
5168 
5169   bool AlwaysRebuild() { return true; }
5170 };
5171 } // namespace
5172 
5173 static VarDecl *precomputeExpr(Sema &Actions,
5174                                SmallVectorImpl<Stmt *> &BodyStmts, Expr *E,
5175                                StringRef Name) {
5176   Expr *NewE = AssertSuccess(CaptureVars(Actions).TransformExpr(E));
5177   VarDecl *NewVar = buildVarDecl(Actions, {}, NewE->getType(), Name, nullptr,
5178                                  dyn_cast<DeclRefExpr>(E->IgnoreImplicit()));
5179   auto *NewDeclStmt = cast<DeclStmt>(AssertSuccess(
5180       Actions.ActOnDeclStmt(Actions.ConvertDeclToDeclGroup(NewVar), {}, {})));
5181   Actions.AddInitializerToDecl(NewDeclStmt->getSingleDecl(), NewE, false);
5182   BodyStmts.push_back(NewDeclStmt);
5183   return NewVar;
5184 }
5185 
5186 /// Create a closure that computes the number of iterations of a loop.
5187 ///
5188 /// \param Actions   The Sema object.
5189 /// \param LogicalTy Type for the logical iteration number.
5190 /// \param Rel       Comparison operator of the loop condition.
5191 /// \param StartExpr Value of the loop counter at the first iteration.
5192 /// \param StopExpr  Expression the loop counter is compared against in the loop
5193 /// condition. \param StepExpr      Amount of increment after each iteration.
5194 ///
5195 /// \return Closure (CapturedStmt) of the distance calculation.
5196 static CapturedStmt *buildDistanceFunc(Sema &Actions, QualType LogicalTy,
5197                                        BinaryOperator::Opcode Rel,
5198                                        Expr *StartExpr, Expr *StopExpr,
5199                                        Expr *StepExpr) {
5200   ASTContext &Ctx = Actions.getASTContext();
5201   TypeSourceInfo *LogicalTSI = Ctx.getTrivialTypeSourceInfo(LogicalTy);
5202 
5203   // Captured regions currently don't support return values, we use an
5204   // out-parameter instead. All inputs are implicit captures.
5205   // TODO: Instead of capturing each DeclRefExpr occurring in
5206   // StartExpr/StopExpr/Step, these could also be passed as a value capture.
5207   QualType ResultTy = Ctx.getLValueReferenceType(LogicalTy);
5208   Sema::CapturedParamNameType Params[] = {{"Distance", ResultTy},
5209                                           {StringRef(), QualType()}};
5210   Actions.ActOnCapturedRegionStart({}, nullptr, CR_Default, Params);
5211 
5212   Stmt *Body;
5213   {
5214     Sema::CompoundScopeRAII CompoundScope(Actions);
5215     CapturedDecl *CS = cast<CapturedDecl>(Actions.CurContext);
5216 
5217     // Get the LValue expression for the result.
5218     ImplicitParamDecl *DistParam = CS->getParam(0);
5219     DeclRefExpr *DistRef = Actions.BuildDeclRefExpr(
5220         DistParam, LogicalTy, VK_LValue, {}, nullptr, nullptr, {}, nullptr);
5221 
5222     SmallVector<Stmt *, 4> BodyStmts;
5223 
5224     // Capture all referenced variable references.
5225     // TODO: Instead of computing NewStart/NewStop/NewStep inside the
5226     // CapturedStmt, we could compute them before and capture the result, to be
5227     // used jointly with the LoopVar function.
5228     VarDecl *NewStart = precomputeExpr(Actions, BodyStmts, StartExpr, ".start");
5229     VarDecl *NewStop = precomputeExpr(Actions, BodyStmts, StopExpr, ".stop");
5230     VarDecl *NewStep = precomputeExpr(Actions, BodyStmts, StepExpr, ".step");
5231     auto BuildVarRef = [&](VarDecl *VD) {
5232       return buildDeclRefExpr(Actions, VD, VD->getType(), {});
5233     };
5234 
5235     IntegerLiteral *Zero = IntegerLiteral::Create(
5236         Ctx, llvm::APInt(Ctx.getIntWidth(LogicalTy), 0), LogicalTy, {});
5237     Expr *Dist;
5238     if (Rel == BO_NE) {
5239       // When using a != comparison, the increment can be +1 or -1. This can be
5240       // dynamic at runtime, so we need to check for the direction.
5241       Expr *IsNegStep = AssertSuccess(
5242           Actions.BuildBinOp(nullptr, {}, BO_LT, BuildVarRef(NewStep), Zero));
5243 
5244       // Positive increment.
5245       Expr *ForwardRange = AssertSuccess(Actions.BuildBinOp(
5246           nullptr, {}, BO_Sub, BuildVarRef(NewStop), BuildVarRef(NewStart)));
5247       ForwardRange = AssertSuccess(
5248           Actions.BuildCStyleCastExpr({}, LogicalTSI, {}, ForwardRange));
5249       Expr *ForwardDist = AssertSuccess(Actions.BuildBinOp(
5250           nullptr, {}, BO_Div, ForwardRange, BuildVarRef(NewStep)));
5251 
5252       // Negative increment.
5253       Expr *BackwardRange = AssertSuccess(Actions.BuildBinOp(
5254           nullptr, {}, BO_Sub, BuildVarRef(NewStart), BuildVarRef(NewStop)));
5255       BackwardRange = AssertSuccess(
5256           Actions.BuildCStyleCastExpr({}, LogicalTSI, {}, BackwardRange));
5257       Expr *NegIncAmount = AssertSuccess(
5258           Actions.BuildUnaryOp(nullptr, {}, UO_Minus, BuildVarRef(NewStep)));
5259       Expr *BackwardDist = AssertSuccess(
5260           Actions.BuildBinOp(nullptr, {}, BO_Div, BackwardRange, NegIncAmount));
5261 
5262       // Use the appropriate case.
5263       Dist = AssertSuccess(Actions.ActOnConditionalOp(
5264           {}, {}, IsNegStep, BackwardDist, ForwardDist));
5265     } else {
5266       assert((Rel == BO_LT || Rel == BO_LE || Rel == BO_GE || Rel == BO_GT) &&
5267              "Expected one of these relational operators");
5268 
5269       // We can derive the direction from any other comparison operator. It is
5270       // non well-formed OpenMP if Step increments/decrements in the other
5271       // directions. Whether at least the first iteration passes the loop
5272       // condition.
5273       Expr *HasAnyIteration = AssertSuccess(Actions.BuildBinOp(
5274           nullptr, {}, Rel, BuildVarRef(NewStart), BuildVarRef(NewStop)));
5275 
5276       // Compute the range between first and last counter value.
5277       Expr *Range;
5278       if (Rel == BO_GE || Rel == BO_GT)
5279         Range = AssertSuccess(Actions.BuildBinOp(
5280             nullptr, {}, BO_Sub, BuildVarRef(NewStart), BuildVarRef(NewStop)));
5281       else
5282         Range = AssertSuccess(Actions.BuildBinOp(
5283             nullptr, {}, BO_Sub, BuildVarRef(NewStop), BuildVarRef(NewStart)));
5284 
5285       // Ensure unsigned range space.
5286       Range =
5287           AssertSuccess(Actions.BuildCStyleCastExpr({}, LogicalTSI, {}, Range));
5288 
5289       if (Rel == BO_LE || Rel == BO_GE) {
5290         // Add one to the range if the relational operator is inclusive.
5291         Range =
5292             AssertSuccess(Actions.BuildUnaryOp(nullptr, {}, UO_PreInc, Range));
5293       }
5294 
5295       // Divide by the absolute step amount.
5296       Expr *Divisor = BuildVarRef(NewStep);
5297       if (Rel == BO_GE || Rel == BO_GT)
5298         Divisor =
5299             AssertSuccess(Actions.BuildUnaryOp(nullptr, {}, UO_Minus, Divisor));
5300       Dist = AssertSuccess(
5301           Actions.BuildBinOp(nullptr, {}, BO_Div, Range, Divisor));
5302 
5303       // If there is not at least one iteration, the range contains garbage. Fix
5304       // to zero in this case.
5305       Dist = AssertSuccess(
5306           Actions.ActOnConditionalOp({}, {}, HasAnyIteration, Dist, Zero));
5307     }
5308 
5309     // Assign the result to the out-parameter.
5310     Stmt *ResultAssign = AssertSuccess(Actions.BuildBinOp(
5311         Actions.getCurScope(), {}, BO_Assign, DistRef, Dist));
5312     BodyStmts.push_back(ResultAssign);
5313 
5314     Body = AssertSuccess(Actions.ActOnCompoundStmt({}, {}, BodyStmts, false));
5315   }
5316 
5317   return cast<CapturedStmt>(
5318       AssertSuccess(Actions.ActOnCapturedRegionEnd(Body)));
5319 }
5320 
5321 /// Create a closure that computes the loop variable from the logical iteration
5322 /// number.
5323 ///
5324 /// \param Actions   The Sema object.
5325 /// \param LoopVarTy Type for the loop variable used for result value.
5326 /// \param LogicalTy Type for the logical iteration number.
5327 /// \param StartExpr Value of the loop counter at the first iteration.
5328 /// \param Step      Amount of increment after each iteration.
5329 /// \param Deref     Whether the loop variable is a dereference of the loop
5330 /// counter variable.
5331 ///
5332 /// \return Closure (CapturedStmt) of the loop value calculation.
5333 static CapturedStmt *buildLoopVarFunc(Sema &Actions, QualType LoopVarTy,
5334                                       QualType LogicalTy,
5335                                       DeclRefExpr *StartExpr, Expr *Step,
5336                                       bool Deref) {
5337   ASTContext &Ctx = Actions.getASTContext();
5338 
5339   // Pass the result as an out-parameter. Passing as return value would require
5340   // the OpenMPIRBuilder to know additional C/C++ semantics, such as how to
5341   // invoke a copy constructor.
5342   QualType TargetParamTy = Ctx.getLValueReferenceType(LoopVarTy);
5343   Sema::CapturedParamNameType Params[] = {{"LoopVar", TargetParamTy},
5344                                           {"Logical", LogicalTy},
5345                                           {StringRef(), QualType()}};
5346   Actions.ActOnCapturedRegionStart({}, nullptr, CR_Default, Params);
5347 
5348   // Capture the initial iterator which represents the LoopVar value at the
5349   // zero's logical iteration. Since the original ForStmt/CXXForRangeStmt update
5350   // it in every iteration, capture it by value before it is modified.
5351   VarDecl *StartVar = cast<VarDecl>(StartExpr->getDecl());
5352   bool Invalid = Actions.tryCaptureVariable(StartVar, {},
5353                                             Sema::TryCapture_ExplicitByVal, {});
5354   (void)Invalid;
5355   assert(!Invalid && "Expecting capture-by-value to work.");
5356 
5357   Expr *Body;
5358   {
5359     Sema::CompoundScopeRAII CompoundScope(Actions);
5360     auto *CS = cast<CapturedDecl>(Actions.CurContext);
5361 
5362     ImplicitParamDecl *TargetParam = CS->getParam(0);
5363     DeclRefExpr *TargetRef = Actions.BuildDeclRefExpr(
5364         TargetParam, LoopVarTy, VK_LValue, {}, nullptr, nullptr, {}, nullptr);
5365     ImplicitParamDecl *IndvarParam = CS->getParam(1);
5366     DeclRefExpr *LogicalRef = Actions.BuildDeclRefExpr(
5367         IndvarParam, LogicalTy, VK_LValue, {}, nullptr, nullptr, {}, nullptr);
5368 
5369     // Capture the Start expression.
5370     CaptureVars Recap(Actions);
5371     Expr *NewStart = AssertSuccess(Recap.TransformExpr(StartExpr));
5372     Expr *NewStep = AssertSuccess(Recap.TransformExpr(Step));
5373 
5374     Expr *Skip = AssertSuccess(
5375         Actions.BuildBinOp(nullptr, {}, BO_Mul, NewStep, LogicalRef));
5376     // TODO: Explicitly cast to the iterator's difference_type instead of
5377     // relying on implicit conversion.
5378     Expr *Advanced =
5379         AssertSuccess(Actions.BuildBinOp(nullptr, {}, BO_Add, NewStart, Skip));
5380 
5381     if (Deref) {
5382       // For range-based for-loops convert the loop counter value to a concrete
5383       // loop variable value by dereferencing the iterator.
5384       Advanced =
5385           AssertSuccess(Actions.BuildUnaryOp(nullptr, {}, UO_Deref, Advanced));
5386     }
5387 
5388     // Assign the result to the output parameter.
5389     Body = AssertSuccess(Actions.BuildBinOp(Actions.getCurScope(), {},
5390                                             BO_Assign, TargetRef, Advanced));
5391   }
5392   return cast<CapturedStmt>(
5393       AssertSuccess(Actions.ActOnCapturedRegionEnd(Body)));
5394 }
5395 
5396 StmtResult Sema::ActOnOpenMPCanonicalLoop(Stmt *AStmt) {
5397   ASTContext &Ctx = getASTContext();
5398 
5399   // Extract the common elements of ForStmt and CXXForRangeStmt:
5400   // Loop variable, repeat condition, increment
5401   Expr *Cond, *Inc;
5402   VarDecl *LIVDecl, *LUVDecl;
5403   if (auto *For = dyn_cast<ForStmt>(AStmt)) {
5404     Stmt *Init = For->getInit();
5405     if (auto *LCVarDeclStmt = dyn_cast<DeclStmt>(Init)) {
5406       // For statement declares loop variable.
5407       LIVDecl = cast<VarDecl>(LCVarDeclStmt->getSingleDecl());
5408     } else if (auto *LCAssign = dyn_cast<BinaryOperator>(Init)) {
5409       // For statement reuses variable.
5410       assert(LCAssign->getOpcode() == BO_Assign &&
5411              "init part must be a loop variable assignment");
5412       auto *CounterRef = cast<DeclRefExpr>(LCAssign->getLHS());
5413       LIVDecl = cast<VarDecl>(CounterRef->getDecl());
5414     } else
5415       llvm_unreachable("Cannot determine loop variable");
5416     LUVDecl = LIVDecl;
5417 
5418     Cond = For->getCond();
5419     Inc = For->getInc();
5420   } else if (auto *RangeFor = dyn_cast<CXXForRangeStmt>(AStmt)) {
5421     DeclStmt *BeginStmt = RangeFor->getBeginStmt();
5422     LIVDecl = cast<VarDecl>(BeginStmt->getSingleDecl());
5423     LUVDecl = RangeFor->getLoopVariable();
5424 
5425     Cond = RangeFor->getCond();
5426     Inc = RangeFor->getInc();
5427   } else
5428     llvm_unreachable("unhandled kind of loop");
5429 
5430   QualType CounterTy = LIVDecl->getType();
5431   QualType LVTy = LUVDecl->getType();
5432 
5433   // Analyze the loop condition.
5434   Expr *LHS, *RHS;
5435   BinaryOperator::Opcode CondRel;
5436   Cond = Cond->IgnoreImplicit();
5437   if (auto *CondBinExpr = dyn_cast<BinaryOperator>(Cond)) {
5438     LHS = CondBinExpr->getLHS();
5439     RHS = CondBinExpr->getRHS();
5440     CondRel = CondBinExpr->getOpcode();
5441   } else if (auto *CondCXXOp = dyn_cast<CXXOperatorCallExpr>(Cond)) {
5442     assert(CondCXXOp->getNumArgs() == 2 && "Comparison should have 2 operands");
5443     LHS = CondCXXOp->getArg(0);
5444     RHS = CondCXXOp->getArg(1);
5445     switch (CondCXXOp->getOperator()) {
5446     case OO_ExclaimEqual:
5447       CondRel = BO_NE;
5448       break;
5449     case OO_Less:
5450       CondRel = BO_LT;
5451       break;
5452     case OO_LessEqual:
5453       CondRel = BO_LE;
5454       break;
5455     case OO_Greater:
5456       CondRel = BO_GT;
5457       break;
5458     case OO_GreaterEqual:
5459       CondRel = BO_GE;
5460       break;
5461     default:
5462       llvm_unreachable("unexpected iterator operator");
5463     }
5464   } else
5465     llvm_unreachable("unexpected loop condition");
5466 
5467   // Normalize such that the loop counter is on the LHS.
5468   if (!isa<DeclRefExpr>(LHS->IgnoreImplicit()) ||
5469       cast<DeclRefExpr>(LHS->IgnoreImplicit())->getDecl() != LIVDecl) {
5470     std::swap(LHS, RHS);
5471     CondRel = BinaryOperator::reverseComparisonOp(CondRel);
5472   }
5473   auto *CounterRef = cast<DeclRefExpr>(LHS->IgnoreImplicit());
5474 
5475   // Decide the bit width for the logical iteration counter. By default use the
5476   // unsigned ptrdiff_t integer size (for iterators and pointers).
5477   // TODO: For iterators, use iterator::difference_type,
5478   // std::iterator_traits<>::difference_type or decltype(it - end).
5479   QualType LogicalTy = Ctx.getUnsignedPointerDiffType();
5480   if (CounterTy->isIntegerType()) {
5481     unsigned BitWidth = Ctx.getIntWidth(CounterTy);
5482     LogicalTy = Ctx.getIntTypeForBitwidth(BitWidth, false);
5483   }
5484 
5485   // Analyze the loop increment.
5486   Expr *Step;
5487   if (auto *IncUn = dyn_cast<UnaryOperator>(Inc)) {
5488     int Direction;
5489     switch (IncUn->getOpcode()) {
5490     case UO_PreInc:
5491     case UO_PostInc:
5492       Direction = 1;
5493       break;
5494     case UO_PreDec:
5495     case UO_PostDec:
5496       Direction = -1;
5497       break;
5498     default:
5499       llvm_unreachable("unhandled unary increment operator");
5500     }
5501     Step = IntegerLiteral::Create(
5502         Ctx, llvm::APInt(Ctx.getIntWidth(LogicalTy), Direction), LogicalTy, {});
5503   } else if (auto *IncBin = dyn_cast<BinaryOperator>(Inc)) {
5504     if (IncBin->getOpcode() == BO_AddAssign) {
5505       Step = IncBin->getRHS();
5506     } else if (IncBin->getOpcode() == BO_SubAssign) {
5507       Step =
5508           AssertSuccess(BuildUnaryOp(nullptr, {}, UO_Minus, IncBin->getRHS()));
5509     } else
5510       llvm_unreachable("unhandled binary increment operator");
5511   } else if (auto *CondCXXOp = dyn_cast<CXXOperatorCallExpr>(Inc)) {
5512     switch (CondCXXOp->getOperator()) {
5513     case OO_PlusPlus:
5514       Step = IntegerLiteral::Create(
5515           Ctx, llvm::APInt(Ctx.getIntWidth(LogicalTy), 1), LogicalTy, {});
5516       break;
5517     case OO_MinusMinus:
5518       Step = IntegerLiteral::Create(
5519           Ctx, llvm::APInt(Ctx.getIntWidth(LogicalTy), -1), LogicalTy, {});
5520       break;
5521     case OO_PlusEqual:
5522       Step = CondCXXOp->getArg(1);
5523       break;
5524     case OO_MinusEqual:
5525       Step = AssertSuccess(
5526           BuildUnaryOp(nullptr, {}, UO_Minus, CondCXXOp->getArg(1)));
5527       break;
5528     default:
5529       llvm_unreachable("unhandled overloaded increment operator");
5530     }
5531   } else
5532     llvm_unreachable("unknown increment expression");
5533 
5534   CapturedStmt *DistanceFunc =
5535       buildDistanceFunc(*this, LogicalTy, CondRel, LHS, RHS, Step);
5536   CapturedStmt *LoopVarFunc = buildLoopVarFunc(
5537       *this, LVTy, LogicalTy, CounterRef, Step, isa<CXXForRangeStmt>(AStmt));
5538   DeclRefExpr *LVRef = BuildDeclRefExpr(LUVDecl, LUVDecl->getType(), VK_LValue,
5539                                         {}, nullptr, nullptr, {}, nullptr);
5540   return OMPCanonicalLoop::create(getASTContext(), AStmt, DistanceFunc,
5541                                   LoopVarFunc, LVRef);
5542 }
5543 
5544 static ExprResult buildUserDefinedMapperRef(Sema &SemaRef, Scope *S,
5545                                             CXXScopeSpec &MapperIdScopeSpec,
5546                                             const DeclarationNameInfo &MapperId,
5547                                             QualType Type,
5548                                             Expr *UnresolvedMapper);
5549 
5550 /// Perform DFS through the structure/class data members trying to find
5551 /// member(s) with user-defined 'default' mapper and generate implicit map
5552 /// clauses for such members with the found 'default' mapper.
5553 static void
5554 processImplicitMapsWithDefaultMappers(Sema &S, DSAStackTy *Stack,
5555                                       SmallVectorImpl<OMPClause *> &Clauses) {
5556   // Check for the deault mapper for data members.
5557   if (S.getLangOpts().OpenMP < 50)
5558     return;
5559   SmallVector<OMPClause *, 4> ImplicitMaps;
5560   DeclarationNameInfo DefaultMapperId;
5561   DefaultMapperId.setName(S.Context.DeclarationNames.getIdentifier(
5562       &S.Context.Idents.get("default")));
5563   for (int Cnt = 0, EndCnt = Clauses.size(); Cnt < EndCnt; ++Cnt) {
5564     auto *C = dyn_cast<OMPMapClause>(Clauses[Cnt]);
5565     if (!C)
5566       continue;
5567     SmallVector<Expr *, 4> SubExprs;
5568     auto *MI = C->mapperlist_begin();
5569     for (auto I = C->varlist_begin(), End = C->varlist_end(); I != End;
5570          ++I, ++MI) {
5571       // Expression is mapped using mapper - skip it.
5572       if (*MI)
5573         continue;
5574       Expr *E = *I;
5575       // Expression is dependent - skip it, build the mapper when it gets
5576       // instantiated.
5577       if (E->isTypeDependent() || E->isValueDependent() ||
5578           E->containsUnexpandedParameterPack())
5579         continue;
5580       // Array section - need to check for the mapping of the array section
5581       // element.
5582       QualType CanonType = E->getType().getCanonicalType();
5583       if (CanonType->isSpecificBuiltinType(BuiltinType::OMPArraySection)) {
5584         const auto *OASE = cast<OMPArraySectionExpr>(E->IgnoreParenImpCasts());
5585         QualType BaseType =
5586             OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
5587         QualType ElemType;
5588         if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
5589           ElemType = ATy->getElementType();
5590         else
5591           ElemType = BaseType->getPointeeType();
5592         CanonType = ElemType;
5593       }
5594 
5595       // DFS over data members in structures/classes.
5596       SmallVector<std::pair<QualType, FieldDecl *>, 4> Types(
5597           1, {CanonType, nullptr});
5598       llvm::DenseMap<const Type *, Expr *> Visited;
5599       SmallVector<std::pair<FieldDecl *, unsigned>, 4> ParentChain(
5600           1, {nullptr, 1});
5601       while (!Types.empty()) {
5602         QualType BaseType;
5603         FieldDecl *CurFD;
5604         std::tie(BaseType, CurFD) = Types.pop_back_val();
5605         while (ParentChain.back().second == 0)
5606           ParentChain.pop_back();
5607         --ParentChain.back().second;
5608         if (BaseType.isNull())
5609           continue;
5610         // Only structs/classes are allowed to have mappers.
5611         const RecordDecl *RD = BaseType.getCanonicalType()->getAsRecordDecl();
5612         if (!RD)
5613           continue;
5614         auto It = Visited.find(BaseType.getTypePtr());
5615         if (It == Visited.end()) {
5616           // Try to find the associated user-defined mapper.
5617           CXXScopeSpec MapperIdScopeSpec;
5618           ExprResult ER = buildUserDefinedMapperRef(
5619               S, Stack->getCurScope(), MapperIdScopeSpec, DefaultMapperId,
5620               BaseType, /*UnresolvedMapper=*/nullptr);
5621           if (ER.isInvalid())
5622             continue;
5623           It = Visited.try_emplace(BaseType.getTypePtr(), ER.get()).first;
5624         }
5625         // Found default mapper.
5626         if (It->second) {
5627           auto *OE = new (S.Context) OpaqueValueExpr(E->getExprLoc(), CanonType,
5628                                                      VK_LValue, OK_Ordinary, E);
5629           OE->setIsUnique(/*V=*/true);
5630           Expr *BaseExpr = OE;
5631           for (const auto &P : ParentChain) {
5632             if (P.first) {
5633               BaseExpr = S.BuildMemberExpr(
5634                   BaseExpr, /*IsArrow=*/false, E->getExprLoc(),
5635                   NestedNameSpecifierLoc(), SourceLocation(), P.first,
5636                   DeclAccessPair::make(P.first, P.first->getAccess()),
5637                   /*HadMultipleCandidates=*/false, DeclarationNameInfo(),
5638                   P.first->getType(), VK_LValue, OK_Ordinary);
5639               BaseExpr = S.DefaultLvalueConversion(BaseExpr).get();
5640             }
5641           }
5642           if (CurFD)
5643             BaseExpr = S.BuildMemberExpr(
5644                 BaseExpr, /*IsArrow=*/false, E->getExprLoc(),
5645                 NestedNameSpecifierLoc(), SourceLocation(), CurFD,
5646                 DeclAccessPair::make(CurFD, CurFD->getAccess()),
5647                 /*HadMultipleCandidates=*/false, DeclarationNameInfo(),
5648                 CurFD->getType(), VK_LValue, OK_Ordinary);
5649           SubExprs.push_back(BaseExpr);
5650           continue;
5651         }
5652         // Check for the "default" mapper for data memebers.
5653         bool FirstIter = true;
5654         for (FieldDecl *FD : RD->fields()) {
5655           if (!FD)
5656             continue;
5657           QualType FieldTy = FD->getType();
5658           if (FieldTy.isNull() ||
5659               !(FieldTy->isStructureOrClassType() || FieldTy->isUnionType()))
5660             continue;
5661           if (FirstIter) {
5662             FirstIter = false;
5663             ParentChain.emplace_back(CurFD, 1);
5664           } else {
5665             ++ParentChain.back().second;
5666           }
5667           Types.emplace_back(FieldTy, FD);
5668         }
5669       }
5670     }
5671     if (SubExprs.empty())
5672       continue;
5673     CXXScopeSpec MapperIdScopeSpec;
5674     DeclarationNameInfo MapperId;
5675     if (OMPClause *NewClause = S.ActOnOpenMPMapClause(
5676             C->getMapTypeModifiers(), C->getMapTypeModifiersLoc(),
5677             MapperIdScopeSpec, MapperId, C->getMapType(),
5678             /*IsMapTypeImplicit=*/true, SourceLocation(), SourceLocation(),
5679             SubExprs, OMPVarListLocTy()))
5680       Clauses.push_back(NewClause);
5681   }
5682 }
5683 
5684 StmtResult Sema::ActOnOpenMPExecutableDirective(
5685     OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
5686     OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
5687     Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
5688   StmtResult Res = StmtError();
5689   // First check CancelRegion which is then used in checkNestingOfRegions.
5690   if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
5691       checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
5692                             StartLoc))
5693     return StmtError();
5694 
5695   llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
5696   VarsWithInheritedDSAType VarsWithInheritedDSA;
5697   bool ErrorFound = false;
5698   ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
5699   if (AStmt && !CurContext->isDependentContext() && Kind != OMPD_atomic &&
5700       Kind != OMPD_critical && Kind != OMPD_section && Kind != OMPD_master &&
5701       !isOpenMPLoopTransformationDirective(Kind)) {
5702     assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5703 
5704     // Check default data sharing attributes for referenced variables.
5705     DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
5706     int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
5707     Stmt *S = AStmt;
5708     while (--ThisCaptureLevel >= 0)
5709       S = cast<CapturedStmt>(S)->getCapturedStmt();
5710     DSAChecker.Visit(S);
5711     if (!isOpenMPTargetDataManagementDirective(Kind) &&
5712         !isOpenMPTaskingDirective(Kind)) {
5713       // Visit subcaptures to generate implicit clauses for captured vars.
5714       auto *CS = cast<CapturedStmt>(AStmt);
5715       SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
5716       getOpenMPCaptureRegions(CaptureRegions, Kind);
5717       // Ignore outer tasking regions for target directives.
5718       if (CaptureRegions.size() > 1 && CaptureRegions.front() == OMPD_task)
5719         CS = cast<CapturedStmt>(CS->getCapturedStmt());
5720       DSAChecker.visitSubCaptures(CS);
5721     }
5722     if (DSAChecker.isErrorFound())
5723       return StmtError();
5724     // Generate list of implicitly defined firstprivate variables.
5725     VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
5726 
5727     SmallVector<Expr *, 4> ImplicitFirstprivates(
5728         DSAChecker.getImplicitFirstprivate().begin(),
5729         DSAChecker.getImplicitFirstprivate().end());
5730     const unsigned DefaultmapKindNum = OMPC_DEFAULTMAP_pointer + 1;
5731     SmallVector<Expr *, 4> ImplicitMaps[DefaultmapKindNum][OMPC_MAP_delete];
5732     SmallVector<OpenMPMapModifierKind, NumberOfOMPMapClauseModifiers>
5733         ImplicitMapModifiers[DefaultmapKindNum];
5734     SmallVector<SourceLocation, NumberOfOMPMapClauseModifiers>
5735         ImplicitMapModifiersLoc[DefaultmapKindNum];
5736     // Get the original location of present modifier from Defaultmap clause.
5737     SourceLocation PresentModifierLocs[DefaultmapKindNum];
5738     for (OMPClause *C : Clauses) {
5739       if (auto *DMC = dyn_cast<OMPDefaultmapClause>(C))
5740         if (DMC->getDefaultmapModifier() == OMPC_DEFAULTMAP_MODIFIER_present)
5741           PresentModifierLocs[DMC->getDefaultmapKind()] =
5742               DMC->getDefaultmapModifierLoc();
5743     }
5744     for (unsigned VC = 0; VC < DefaultmapKindNum; ++VC) {
5745       auto Kind = static_cast<OpenMPDefaultmapClauseKind>(VC);
5746       for (unsigned I = 0; I < OMPC_MAP_delete; ++I) {
5747         ArrayRef<Expr *> ImplicitMap = DSAChecker.getImplicitMap(
5748             Kind, static_cast<OpenMPMapClauseKind>(I));
5749         ImplicitMaps[VC][I].append(ImplicitMap.begin(), ImplicitMap.end());
5750       }
5751       ArrayRef<OpenMPMapModifierKind> ImplicitModifier =
5752           DSAChecker.getImplicitMapModifier(Kind);
5753       ImplicitMapModifiers[VC].append(ImplicitModifier.begin(),
5754                                       ImplicitModifier.end());
5755       std::fill_n(std::back_inserter(ImplicitMapModifiersLoc[VC]),
5756                   ImplicitModifier.size(), PresentModifierLocs[VC]);
5757     }
5758     // Mark taskgroup task_reduction descriptors as implicitly firstprivate.
5759     for (OMPClause *C : Clauses) {
5760       if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) {
5761         for (Expr *E : IRC->taskgroup_descriptors())
5762           if (E)
5763             ImplicitFirstprivates.emplace_back(E);
5764       }
5765       // OpenMP 5.0, 2.10.1 task Construct
5766       // [detach clause]... The event-handle will be considered as if it was
5767       // specified on a firstprivate clause.
5768       if (auto *DC = dyn_cast<OMPDetachClause>(C))
5769         ImplicitFirstprivates.push_back(DC->getEventHandler());
5770     }
5771     if (!ImplicitFirstprivates.empty()) {
5772       if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
5773               ImplicitFirstprivates, SourceLocation(), SourceLocation(),
5774               SourceLocation())) {
5775         ClausesWithImplicit.push_back(Implicit);
5776         ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
5777                      ImplicitFirstprivates.size();
5778       } else {
5779         ErrorFound = true;
5780       }
5781     }
5782     for (unsigned I = 0, E = DefaultmapKindNum; I < E; ++I) {
5783       int ClauseKindCnt = -1;
5784       for (ArrayRef<Expr *> ImplicitMap : ImplicitMaps[I]) {
5785         ++ClauseKindCnt;
5786         if (ImplicitMap.empty())
5787           continue;
5788         CXXScopeSpec MapperIdScopeSpec;
5789         DeclarationNameInfo MapperId;
5790         auto Kind = static_cast<OpenMPMapClauseKind>(ClauseKindCnt);
5791         if (OMPClause *Implicit = ActOnOpenMPMapClause(
5792                 ImplicitMapModifiers[I], ImplicitMapModifiersLoc[I],
5793                 MapperIdScopeSpec, MapperId, Kind, /*IsMapTypeImplicit=*/true,
5794                 SourceLocation(), SourceLocation(), ImplicitMap,
5795                 OMPVarListLocTy())) {
5796           ClausesWithImplicit.emplace_back(Implicit);
5797           ErrorFound |= cast<OMPMapClause>(Implicit)->varlist_size() !=
5798                         ImplicitMap.size();
5799         } else {
5800           ErrorFound = true;
5801         }
5802       }
5803     }
5804     // Build expressions for implicit maps of data members with 'default'
5805     // mappers.
5806     if (LangOpts.OpenMP >= 50)
5807       processImplicitMapsWithDefaultMappers(*this, DSAStack,
5808                                             ClausesWithImplicit);
5809   }
5810 
5811   llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
5812   switch (Kind) {
5813   case OMPD_parallel:
5814     Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
5815                                        EndLoc);
5816     AllowedNameModifiers.push_back(OMPD_parallel);
5817     break;
5818   case OMPD_simd:
5819     Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
5820                                    VarsWithInheritedDSA);
5821     if (LangOpts.OpenMP >= 50)
5822       AllowedNameModifiers.push_back(OMPD_simd);
5823     break;
5824   case OMPD_tile:
5825     Res =
5826         ActOnOpenMPTileDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
5827     break;
5828   case OMPD_for:
5829     Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
5830                                   VarsWithInheritedDSA);
5831     break;
5832   case OMPD_for_simd:
5833     Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
5834                                       EndLoc, VarsWithInheritedDSA);
5835     if (LangOpts.OpenMP >= 50)
5836       AllowedNameModifiers.push_back(OMPD_simd);
5837     break;
5838   case OMPD_sections:
5839     Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
5840                                        EndLoc);
5841     break;
5842   case OMPD_section:
5843     assert(ClausesWithImplicit.empty() &&
5844            "No clauses are allowed for 'omp section' directive");
5845     Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
5846     break;
5847   case OMPD_single:
5848     Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
5849                                      EndLoc);
5850     break;
5851   case OMPD_master:
5852     assert(ClausesWithImplicit.empty() &&
5853            "No clauses are allowed for 'omp master' directive");
5854     Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
5855     break;
5856   case OMPD_critical:
5857     Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
5858                                        StartLoc, EndLoc);
5859     break;
5860   case OMPD_parallel_for:
5861     Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
5862                                           EndLoc, VarsWithInheritedDSA);
5863     AllowedNameModifiers.push_back(OMPD_parallel);
5864     break;
5865   case OMPD_parallel_for_simd:
5866     Res = ActOnOpenMPParallelForSimdDirective(
5867         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
5868     AllowedNameModifiers.push_back(OMPD_parallel);
5869     if (LangOpts.OpenMP >= 50)
5870       AllowedNameModifiers.push_back(OMPD_simd);
5871     break;
5872   case OMPD_parallel_master:
5873     Res = ActOnOpenMPParallelMasterDirective(ClausesWithImplicit, AStmt,
5874                                                StartLoc, EndLoc);
5875     AllowedNameModifiers.push_back(OMPD_parallel);
5876     break;
5877   case OMPD_parallel_sections:
5878     Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
5879                                                StartLoc, EndLoc);
5880     AllowedNameModifiers.push_back(OMPD_parallel);
5881     break;
5882   case OMPD_task:
5883     Res =
5884         ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
5885     AllowedNameModifiers.push_back(OMPD_task);
5886     break;
5887   case OMPD_taskyield:
5888     assert(ClausesWithImplicit.empty() &&
5889            "No clauses are allowed for 'omp taskyield' directive");
5890     assert(AStmt == nullptr &&
5891            "No associated statement allowed for 'omp taskyield' directive");
5892     Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
5893     break;
5894   case OMPD_barrier:
5895     assert(ClausesWithImplicit.empty() &&
5896            "No clauses are allowed for 'omp barrier' directive");
5897     assert(AStmt == nullptr &&
5898            "No associated statement allowed for 'omp barrier' directive");
5899     Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
5900     break;
5901   case OMPD_taskwait:
5902     assert(ClausesWithImplicit.empty() &&
5903            "No clauses are allowed for 'omp taskwait' directive");
5904     assert(AStmt == nullptr &&
5905            "No associated statement allowed for 'omp taskwait' directive");
5906     Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
5907     break;
5908   case OMPD_taskgroup:
5909     Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc,
5910                                         EndLoc);
5911     break;
5912   case OMPD_flush:
5913     assert(AStmt == nullptr &&
5914            "No associated statement allowed for 'omp flush' directive");
5915     Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
5916     break;
5917   case OMPD_depobj:
5918     assert(AStmt == nullptr &&
5919            "No associated statement allowed for 'omp depobj' directive");
5920     Res = ActOnOpenMPDepobjDirective(ClausesWithImplicit, StartLoc, EndLoc);
5921     break;
5922   case OMPD_scan:
5923     assert(AStmt == nullptr &&
5924            "No associated statement allowed for 'omp scan' directive");
5925     Res = ActOnOpenMPScanDirective(ClausesWithImplicit, StartLoc, EndLoc);
5926     break;
5927   case OMPD_ordered:
5928     Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
5929                                       EndLoc);
5930     break;
5931   case OMPD_atomic:
5932     Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
5933                                      EndLoc);
5934     break;
5935   case OMPD_teams:
5936     Res =
5937         ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
5938     break;
5939   case OMPD_target:
5940     Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
5941                                      EndLoc);
5942     AllowedNameModifiers.push_back(OMPD_target);
5943     break;
5944   case OMPD_target_parallel:
5945     Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
5946                                              StartLoc, EndLoc);
5947     AllowedNameModifiers.push_back(OMPD_target);
5948     AllowedNameModifiers.push_back(OMPD_parallel);
5949     break;
5950   case OMPD_target_parallel_for:
5951     Res = ActOnOpenMPTargetParallelForDirective(
5952         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
5953     AllowedNameModifiers.push_back(OMPD_target);
5954     AllowedNameModifiers.push_back(OMPD_parallel);
5955     break;
5956   case OMPD_cancellation_point:
5957     assert(ClausesWithImplicit.empty() &&
5958            "No clauses are allowed for 'omp cancellation point' directive");
5959     assert(AStmt == nullptr && "No associated statement allowed for 'omp "
5960                                "cancellation point' directive");
5961     Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
5962     break;
5963   case OMPD_cancel:
5964     assert(AStmt == nullptr &&
5965            "No associated statement allowed for 'omp cancel' directive");
5966     Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
5967                                      CancelRegion);
5968     AllowedNameModifiers.push_back(OMPD_cancel);
5969     break;
5970   case OMPD_target_data:
5971     Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
5972                                          EndLoc);
5973     AllowedNameModifiers.push_back(OMPD_target_data);
5974     break;
5975   case OMPD_target_enter_data:
5976     Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
5977                                               EndLoc, AStmt);
5978     AllowedNameModifiers.push_back(OMPD_target_enter_data);
5979     break;
5980   case OMPD_target_exit_data:
5981     Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
5982                                              EndLoc, AStmt);
5983     AllowedNameModifiers.push_back(OMPD_target_exit_data);
5984     break;
5985   case OMPD_taskloop:
5986     Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
5987                                        EndLoc, VarsWithInheritedDSA);
5988     AllowedNameModifiers.push_back(OMPD_taskloop);
5989     break;
5990   case OMPD_taskloop_simd:
5991     Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
5992                                            EndLoc, VarsWithInheritedDSA);
5993     AllowedNameModifiers.push_back(OMPD_taskloop);
5994     if (LangOpts.OpenMP >= 50)
5995       AllowedNameModifiers.push_back(OMPD_simd);
5996     break;
5997   case OMPD_master_taskloop:
5998     Res = ActOnOpenMPMasterTaskLoopDirective(
5999         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6000     AllowedNameModifiers.push_back(OMPD_taskloop);
6001     break;
6002   case OMPD_master_taskloop_simd:
6003     Res = ActOnOpenMPMasterTaskLoopSimdDirective(
6004         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6005     AllowedNameModifiers.push_back(OMPD_taskloop);
6006     if (LangOpts.OpenMP >= 50)
6007       AllowedNameModifiers.push_back(OMPD_simd);
6008     break;
6009   case OMPD_parallel_master_taskloop:
6010     Res = ActOnOpenMPParallelMasterTaskLoopDirective(
6011         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6012     AllowedNameModifiers.push_back(OMPD_taskloop);
6013     AllowedNameModifiers.push_back(OMPD_parallel);
6014     break;
6015   case OMPD_parallel_master_taskloop_simd:
6016     Res = ActOnOpenMPParallelMasterTaskLoopSimdDirective(
6017         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6018     AllowedNameModifiers.push_back(OMPD_taskloop);
6019     AllowedNameModifiers.push_back(OMPD_parallel);
6020     if (LangOpts.OpenMP >= 50)
6021       AllowedNameModifiers.push_back(OMPD_simd);
6022     break;
6023   case OMPD_distribute:
6024     Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
6025                                          EndLoc, VarsWithInheritedDSA);
6026     break;
6027   case OMPD_target_update:
6028     Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc,
6029                                            EndLoc, AStmt);
6030     AllowedNameModifiers.push_back(OMPD_target_update);
6031     break;
6032   case OMPD_distribute_parallel_for:
6033     Res = ActOnOpenMPDistributeParallelForDirective(
6034         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6035     AllowedNameModifiers.push_back(OMPD_parallel);
6036     break;
6037   case OMPD_distribute_parallel_for_simd:
6038     Res = ActOnOpenMPDistributeParallelForSimdDirective(
6039         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6040     AllowedNameModifiers.push_back(OMPD_parallel);
6041     if (LangOpts.OpenMP >= 50)
6042       AllowedNameModifiers.push_back(OMPD_simd);
6043     break;
6044   case OMPD_distribute_simd:
6045     Res = ActOnOpenMPDistributeSimdDirective(
6046         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6047     if (LangOpts.OpenMP >= 50)
6048       AllowedNameModifiers.push_back(OMPD_simd);
6049     break;
6050   case OMPD_target_parallel_for_simd:
6051     Res = ActOnOpenMPTargetParallelForSimdDirective(
6052         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6053     AllowedNameModifiers.push_back(OMPD_target);
6054     AllowedNameModifiers.push_back(OMPD_parallel);
6055     if (LangOpts.OpenMP >= 50)
6056       AllowedNameModifiers.push_back(OMPD_simd);
6057     break;
6058   case OMPD_target_simd:
6059     Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
6060                                          EndLoc, VarsWithInheritedDSA);
6061     AllowedNameModifiers.push_back(OMPD_target);
6062     if (LangOpts.OpenMP >= 50)
6063       AllowedNameModifiers.push_back(OMPD_simd);
6064     break;
6065   case OMPD_teams_distribute:
6066     Res = ActOnOpenMPTeamsDistributeDirective(
6067         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6068     break;
6069   case OMPD_teams_distribute_simd:
6070     Res = ActOnOpenMPTeamsDistributeSimdDirective(
6071         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6072     if (LangOpts.OpenMP >= 50)
6073       AllowedNameModifiers.push_back(OMPD_simd);
6074     break;
6075   case OMPD_teams_distribute_parallel_for_simd:
6076     Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
6077         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6078     AllowedNameModifiers.push_back(OMPD_parallel);
6079     if (LangOpts.OpenMP >= 50)
6080       AllowedNameModifiers.push_back(OMPD_simd);
6081     break;
6082   case OMPD_teams_distribute_parallel_for:
6083     Res = ActOnOpenMPTeamsDistributeParallelForDirective(
6084         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6085     AllowedNameModifiers.push_back(OMPD_parallel);
6086     break;
6087   case OMPD_target_teams:
6088     Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
6089                                           EndLoc);
6090     AllowedNameModifiers.push_back(OMPD_target);
6091     break;
6092   case OMPD_target_teams_distribute:
6093     Res = ActOnOpenMPTargetTeamsDistributeDirective(
6094         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6095     AllowedNameModifiers.push_back(OMPD_target);
6096     break;
6097   case OMPD_target_teams_distribute_parallel_for:
6098     Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
6099         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6100     AllowedNameModifiers.push_back(OMPD_target);
6101     AllowedNameModifiers.push_back(OMPD_parallel);
6102     break;
6103   case OMPD_target_teams_distribute_parallel_for_simd:
6104     Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
6105         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6106     AllowedNameModifiers.push_back(OMPD_target);
6107     AllowedNameModifiers.push_back(OMPD_parallel);
6108     if (LangOpts.OpenMP >= 50)
6109       AllowedNameModifiers.push_back(OMPD_simd);
6110     break;
6111   case OMPD_target_teams_distribute_simd:
6112     Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
6113         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6114     AllowedNameModifiers.push_back(OMPD_target);
6115     if (LangOpts.OpenMP >= 50)
6116       AllowedNameModifiers.push_back(OMPD_simd);
6117     break;
6118   case OMPD_interop:
6119     assert(AStmt == nullptr &&
6120            "No associated statement allowed for 'omp interop' directive");
6121     Res = ActOnOpenMPInteropDirective(ClausesWithImplicit, StartLoc, EndLoc);
6122     break;
6123   case OMPD_declare_target:
6124   case OMPD_end_declare_target:
6125   case OMPD_threadprivate:
6126   case OMPD_allocate:
6127   case OMPD_declare_reduction:
6128   case OMPD_declare_mapper:
6129   case OMPD_declare_simd:
6130   case OMPD_requires:
6131   case OMPD_declare_variant:
6132   case OMPD_begin_declare_variant:
6133   case OMPD_end_declare_variant:
6134     llvm_unreachable("OpenMP Directive is not allowed");
6135   case OMPD_unknown:
6136   default:
6137     llvm_unreachable("Unknown OpenMP directive");
6138   }
6139 
6140   ErrorFound = Res.isInvalid() || ErrorFound;
6141 
6142   // Check variables in the clauses if default(none) or
6143   // default(firstprivate) was specified.
6144   if (DSAStack->getDefaultDSA() == DSA_none ||
6145       DSAStack->getDefaultDSA() == DSA_firstprivate) {
6146     DSAAttrChecker DSAChecker(DSAStack, *this, nullptr);
6147     for (OMPClause *C : Clauses) {
6148       switch (C->getClauseKind()) {
6149       case OMPC_num_threads:
6150       case OMPC_dist_schedule:
6151         // Do not analyse if no parent teams directive.
6152         if (isOpenMPTeamsDirective(Kind))
6153           break;
6154         continue;
6155       case OMPC_if:
6156         if (isOpenMPTeamsDirective(Kind) &&
6157             cast<OMPIfClause>(C)->getNameModifier() != OMPD_target)
6158           break;
6159         if (isOpenMPParallelDirective(Kind) &&
6160             isOpenMPTaskLoopDirective(Kind) &&
6161             cast<OMPIfClause>(C)->getNameModifier() != OMPD_parallel)
6162           break;
6163         continue;
6164       case OMPC_schedule:
6165       case OMPC_detach:
6166         break;
6167       case OMPC_grainsize:
6168       case OMPC_num_tasks:
6169       case OMPC_final:
6170       case OMPC_priority:
6171         // Do not analyze if no parent parallel directive.
6172         if (isOpenMPParallelDirective(Kind))
6173           break;
6174         continue;
6175       case OMPC_ordered:
6176       case OMPC_device:
6177       case OMPC_num_teams:
6178       case OMPC_thread_limit:
6179       case OMPC_hint:
6180       case OMPC_collapse:
6181       case OMPC_safelen:
6182       case OMPC_simdlen:
6183       case OMPC_sizes:
6184       case OMPC_default:
6185       case OMPC_proc_bind:
6186       case OMPC_private:
6187       case OMPC_firstprivate:
6188       case OMPC_lastprivate:
6189       case OMPC_shared:
6190       case OMPC_reduction:
6191       case OMPC_task_reduction:
6192       case OMPC_in_reduction:
6193       case OMPC_linear:
6194       case OMPC_aligned:
6195       case OMPC_copyin:
6196       case OMPC_copyprivate:
6197       case OMPC_nowait:
6198       case OMPC_untied:
6199       case OMPC_mergeable:
6200       case OMPC_allocate:
6201       case OMPC_read:
6202       case OMPC_write:
6203       case OMPC_update:
6204       case OMPC_capture:
6205       case OMPC_seq_cst:
6206       case OMPC_acq_rel:
6207       case OMPC_acquire:
6208       case OMPC_release:
6209       case OMPC_relaxed:
6210       case OMPC_depend:
6211       case OMPC_threads:
6212       case OMPC_simd:
6213       case OMPC_map:
6214       case OMPC_nogroup:
6215       case OMPC_defaultmap:
6216       case OMPC_to:
6217       case OMPC_from:
6218       case OMPC_use_device_ptr:
6219       case OMPC_use_device_addr:
6220       case OMPC_is_device_ptr:
6221       case OMPC_nontemporal:
6222       case OMPC_order:
6223       case OMPC_destroy:
6224       case OMPC_inclusive:
6225       case OMPC_exclusive:
6226       case OMPC_uses_allocators:
6227       case OMPC_affinity:
6228         continue;
6229       case OMPC_allocator:
6230       case OMPC_flush:
6231       case OMPC_depobj:
6232       case OMPC_threadprivate:
6233       case OMPC_uniform:
6234       case OMPC_unknown:
6235       case OMPC_unified_address:
6236       case OMPC_unified_shared_memory:
6237       case OMPC_reverse_offload:
6238       case OMPC_dynamic_allocators:
6239       case OMPC_atomic_default_mem_order:
6240       case OMPC_device_type:
6241       case OMPC_match:
6242       default:
6243         llvm_unreachable("Unexpected clause");
6244       }
6245       for (Stmt *CC : C->children()) {
6246         if (CC)
6247           DSAChecker.Visit(CC);
6248       }
6249     }
6250     for (const auto &P : DSAChecker.getVarsWithInheritedDSA())
6251       VarsWithInheritedDSA[P.getFirst()] = P.getSecond();
6252   }
6253   for (const auto &P : VarsWithInheritedDSA) {
6254     if (P.getFirst()->isImplicit() || isa<OMPCapturedExprDecl>(P.getFirst()))
6255       continue;
6256     ErrorFound = true;
6257     if (DSAStack->getDefaultDSA() == DSA_none ||
6258         DSAStack->getDefaultDSA() == DSA_firstprivate) {
6259       Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
6260           << P.first << P.second->getSourceRange();
6261       Diag(DSAStack->getDefaultDSALocation(), diag::note_omp_default_dsa_none);
6262     } else if (getLangOpts().OpenMP >= 50) {
6263       Diag(P.second->getExprLoc(),
6264            diag::err_omp_defaultmap_no_attr_for_variable)
6265           << P.first << P.second->getSourceRange();
6266       Diag(DSAStack->getDefaultDSALocation(),
6267            diag::note_omp_defaultmap_attr_none);
6268     }
6269   }
6270 
6271   if (!AllowedNameModifiers.empty())
6272     ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
6273                  ErrorFound;
6274 
6275   if (ErrorFound)
6276     return StmtError();
6277 
6278   if (!CurContext->isDependentContext() &&
6279       isOpenMPTargetExecutionDirective(Kind) &&
6280       !(DSAStack->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() ||
6281         DSAStack->hasRequiresDeclWithClause<OMPUnifiedAddressClause>() ||
6282         DSAStack->hasRequiresDeclWithClause<OMPReverseOffloadClause>() ||
6283         DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())) {
6284     // Register target to DSA Stack.
6285     DSAStack->addTargetDirLocation(StartLoc);
6286   }
6287 
6288   return Res;
6289 }
6290 
6291 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
6292     DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
6293     ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
6294     ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
6295     ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
6296   assert(Aligneds.size() == Alignments.size());
6297   assert(Linears.size() == LinModifiers.size());
6298   assert(Linears.size() == Steps.size());
6299   if (!DG || DG.get().isNull())
6300     return DeclGroupPtrTy();
6301 
6302   const int SimdId = 0;
6303   if (!DG.get().isSingleDecl()) {
6304     Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd_variant)
6305         << SimdId;
6306     return DG;
6307   }
6308   Decl *ADecl = DG.get().getSingleDecl();
6309   if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
6310     ADecl = FTD->getTemplatedDecl();
6311 
6312   auto *FD = dyn_cast<FunctionDecl>(ADecl);
6313   if (!FD) {
6314     Diag(ADecl->getLocation(), diag::err_omp_function_expected) << SimdId;
6315     return DeclGroupPtrTy();
6316   }
6317 
6318   // OpenMP [2.8.2, declare simd construct, Description]
6319   // The parameter of the simdlen clause must be a constant positive integer
6320   // expression.
6321   ExprResult SL;
6322   if (Simdlen)
6323     SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
6324   // OpenMP [2.8.2, declare simd construct, Description]
6325   // The special this pointer can be used as if was one of the arguments to the
6326   // function in any of the linear, aligned, or uniform clauses.
6327   // The uniform clause declares one or more arguments to have an invariant
6328   // value for all concurrent invocations of the function in the execution of a
6329   // single SIMD loop.
6330   llvm::DenseMap<const Decl *, const Expr *> UniformedArgs;
6331   const Expr *UniformedLinearThis = nullptr;
6332   for (const Expr *E : Uniforms) {
6333     E = E->IgnoreParenImpCasts();
6334     if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
6335       if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
6336         if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
6337             FD->getParamDecl(PVD->getFunctionScopeIndex())
6338                     ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
6339           UniformedArgs.try_emplace(PVD->getCanonicalDecl(), E);
6340           continue;
6341         }
6342     if (isa<CXXThisExpr>(E)) {
6343       UniformedLinearThis = E;
6344       continue;
6345     }
6346     Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
6347         << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
6348   }
6349   // OpenMP [2.8.2, declare simd construct, Description]
6350   // The aligned clause declares that the object to which each list item points
6351   // is aligned to the number of bytes expressed in the optional parameter of
6352   // the aligned clause.
6353   // The special this pointer can be used as if was one of the arguments to the
6354   // function in any of the linear, aligned, or uniform clauses.
6355   // The type of list items appearing in the aligned clause must be array,
6356   // pointer, reference to array, or reference to pointer.
6357   llvm::DenseMap<const Decl *, const Expr *> AlignedArgs;
6358   const Expr *AlignedThis = nullptr;
6359   for (const Expr *E : Aligneds) {
6360     E = E->IgnoreParenImpCasts();
6361     if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
6362       if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
6363         const VarDecl *CanonPVD = PVD->getCanonicalDecl();
6364         if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
6365             FD->getParamDecl(PVD->getFunctionScopeIndex())
6366                     ->getCanonicalDecl() == CanonPVD) {
6367           // OpenMP  [2.8.1, simd construct, Restrictions]
6368           // A list-item cannot appear in more than one aligned clause.
6369           if (AlignedArgs.count(CanonPVD) > 0) {
6370             Diag(E->getExprLoc(), diag::err_omp_used_in_clause_twice)
6371                 << 1 << getOpenMPClauseName(OMPC_aligned)
6372                 << E->getSourceRange();
6373             Diag(AlignedArgs[CanonPVD]->getExprLoc(),
6374                  diag::note_omp_explicit_dsa)
6375                 << getOpenMPClauseName(OMPC_aligned);
6376             continue;
6377           }
6378           AlignedArgs[CanonPVD] = E;
6379           QualType QTy = PVD->getType()
6380                              .getNonReferenceType()
6381                              .getUnqualifiedType()
6382                              .getCanonicalType();
6383           const Type *Ty = QTy.getTypePtrOrNull();
6384           if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
6385             Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
6386                 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
6387             Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
6388           }
6389           continue;
6390         }
6391       }
6392     if (isa<CXXThisExpr>(E)) {
6393       if (AlignedThis) {
6394         Diag(E->getExprLoc(), diag::err_omp_used_in_clause_twice)
6395             << 2 << getOpenMPClauseName(OMPC_aligned) << E->getSourceRange();
6396         Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
6397             << getOpenMPClauseName(OMPC_aligned);
6398       }
6399       AlignedThis = E;
6400       continue;
6401     }
6402     Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
6403         << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
6404   }
6405   // The optional parameter of the aligned clause, alignment, must be a constant
6406   // positive integer expression. If no optional parameter is specified,
6407   // implementation-defined default alignments for SIMD instructions on the
6408   // target platforms are assumed.
6409   SmallVector<const Expr *, 4> NewAligns;
6410   for (Expr *E : Alignments) {
6411     ExprResult Align;
6412     if (E)
6413       Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
6414     NewAligns.push_back(Align.get());
6415   }
6416   // OpenMP [2.8.2, declare simd construct, Description]
6417   // The linear clause declares one or more list items to be private to a SIMD
6418   // lane and to have a linear relationship with respect to the iteration space
6419   // of a loop.
6420   // The special this pointer can be used as if was one of the arguments to the
6421   // function in any of the linear, aligned, or uniform clauses.
6422   // When a linear-step expression is specified in a linear clause it must be
6423   // either a constant integer expression or an integer-typed parameter that is
6424   // specified in a uniform clause on the directive.
6425   llvm::DenseMap<const Decl *, const Expr *> LinearArgs;
6426   const bool IsUniformedThis = UniformedLinearThis != nullptr;
6427   auto MI = LinModifiers.begin();
6428   for (const Expr *E : Linears) {
6429     auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
6430     ++MI;
6431     E = E->IgnoreParenImpCasts();
6432     if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
6433       if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
6434         const VarDecl *CanonPVD = PVD->getCanonicalDecl();
6435         if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
6436             FD->getParamDecl(PVD->getFunctionScopeIndex())
6437                     ->getCanonicalDecl() == CanonPVD) {
6438           // OpenMP  [2.15.3.7, linear Clause, Restrictions]
6439           // A list-item cannot appear in more than one linear clause.
6440           if (LinearArgs.count(CanonPVD) > 0) {
6441             Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
6442                 << getOpenMPClauseName(OMPC_linear)
6443                 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
6444             Diag(LinearArgs[CanonPVD]->getExprLoc(),
6445                  diag::note_omp_explicit_dsa)
6446                 << getOpenMPClauseName(OMPC_linear);
6447             continue;
6448           }
6449           // Each argument can appear in at most one uniform or linear clause.
6450           if (UniformedArgs.count(CanonPVD) > 0) {
6451             Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
6452                 << getOpenMPClauseName(OMPC_linear)
6453                 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
6454             Diag(UniformedArgs[CanonPVD]->getExprLoc(),
6455                  diag::note_omp_explicit_dsa)
6456                 << getOpenMPClauseName(OMPC_uniform);
6457             continue;
6458           }
6459           LinearArgs[CanonPVD] = E;
6460           if (E->isValueDependent() || E->isTypeDependent() ||
6461               E->isInstantiationDependent() ||
6462               E->containsUnexpandedParameterPack())
6463             continue;
6464           (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
6465                                       PVD->getOriginalType(),
6466                                       /*IsDeclareSimd=*/true);
6467           continue;
6468         }
6469       }
6470     if (isa<CXXThisExpr>(E)) {
6471       if (UniformedLinearThis) {
6472         Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
6473             << getOpenMPClauseName(OMPC_linear)
6474             << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
6475             << E->getSourceRange();
6476         Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
6477             << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
6478                                                    : OMPC_linear);
6479         continue;
6480       }
6481       UniformedLinearThis = E;
6482       if (E->isValueDependent() || E->isTypeDependent() ||
6483           E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
6484         continue;
6485       (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
6486                                   E->getType(), /*IsDeclareSimd=*/true);
6487       continue;
6488     }
6489     Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
6490         << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
6491   }
6492   Expr *Step = nullptr;
6493   Expr *NewStep = nullptr;
6494   SmallVector<Expr *, 4> NewSteps;
6495   for (Expr *E : Steps) {
6496     // Skip the same step expression, it was checked already.
6497     if (Step == E || !E) {
6498       NewSteps.push_back(E ? NewStep : nullptr);
6499       continue;
6500     }
6501     Step = E;
6502     if (const auto *DRE = dyn_cast<DeclRefExpr>(Step))
6503       if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
6504         const VarDecl *CanonPVD = PVD->getCanonicalDecl();
6505         if (UniformedArgs.count(CanonPVD) == 0) {
6506           Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
6507               << Step->getSourceRange();
6508         } else if (E->isValueDependent() || E->isTypeDependent() ||
6509                    E->isInstantiationDependent() ||
6510                    E->containsUnexpandedParameterPack() ||
6511                    CanonPVD->getType()->hasIntegerRepresentation()) {
6512           NewSteps.push_back(Step);
6513         } else {
6514           Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
6515               << Step->getSourceRange();
6516         }
6517         continue;
6518       }
6519     NewStep = Step;
6520     if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
6521         !Step->isInstantiationDependent() &&
6522         !Step->containsUnexpandedParameterPack()) {
6523       NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
6524                     .get();
6525       if (NewStep)
6526         NewStep =
6527             VerifyIntegerConstantExpression(NewStep, /*FIXME*/ AllowFold).get();
6528     }
6529     NewSteps.push_back(NewStep);
6530   }
6531   auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
6532       Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
6533       Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
6534       const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
6535       const_cast<Expr **>(Linears.data()), Linears.size(),
6536       const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
6537       NewSteps.data(), NewSteps.size(), SR);
6538   ADecl->addAttr(NewAttr);
6539   return DG;
6540 }
6541 
6542 static void setPrototype(Sema &S, FunctionDecl *FD, FunctionDecl *FDWithProto,
6543                          QualType NewType) {
6544   assert(NewType->isFunctionProtoType() &&
6545          "Expected function type with prototype.");
6546   assert(FD->getType()->isFunctionNoProtoType() &&
6547          "Expected function with type with no prototype.");
6548   assert(FDWithProto->getType()->isFunctionProtoType() &&
6549          "Expected function with prototype.");
6550   // Synthesize parameters with the same types.
6551   FD->setType(NewType);
6552   SmallVector<ParmVarDecl *, 16> Params;
6553   for (const ParmVarDecl *P : FDWithProto->parameters()) {
6554     auto *Param = ParmVarDecl::Create(S.getASTContext(), FD, SourceLocation(),
6555                                       SourceLocation(), nullptr, P->getType(),
6556                                       /*TInfo=*/nullptr, SC_None, nullptr);
6557     Param->setScopeInfo(0, Params.size());
6558     Param->setImplicit();
6559     Params.push_back(Param);
6560   }
6561 
6562   FD->setParams(Params);
6563 }
6564 
6565 void Sema::ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(Decl *D) {
6566   if (D->isInvalidDecl())
6567     return;
6568   FunctionDecl *FD = nullptr;
6569   if (auto *UTemplDecl = dyn_cast<FunctionTemplateDecl>(D))
6570     FD = UTemplDecl->getTemplatedDecl();
6571   else
6572     FD = cast<FunctionDecl>(D);
6573   assert(FD && "Expected a function declaration!");
6574 
6575   // If we are intantiating templates we do *not* apply scoped assumptions but
6576   // only global ones. We apply scoped assumption to the template definition
6577   // though.
6578   if (!inTemplateInstantiation()) {
6579     for (AssumptionAttr *AA : OMPAssumeScoped)
6580       FD->addAttr(AA);
6581   }
6582   for (AssumptionAttr *AA : OMPAssumeGlobal)
6583     FD->addAttr(AA);
6584 }
6585 
6586 Sema::OMPDeclareVariantScope::OMPDeclareVariantScope(OMPTraitInfo &TI)
6587     : TI(&TI), NameSuffix(TI.getMangledName()) {}
6588 
6589 void Sema::ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
6590     Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists,
6591     SmallVectorImpl<FunctionDecl *> &Bases) {
6592   if (!D.getIdentifier())
6593     return;
6594 
6595   OMPDeclareVariantScope &DVScope = OMPDeclareVariantScopes.back();
6596 
6597   // Template specialization is an extension, check if we do it.
6598   bool IsTemplated = !TemplateParamLists.empty();
6599   if (IsTemplated &
6600       !DVScope.TI->isExtensionActive(
6601           llvm::omp::TraitProperty::implementation_extension_allow_templates))
6602     return;
6603 
6604   IdentifierInfo *BaseII = D.getIdentifier();
6605   LookupResult Lookup(*this, DeclarationName(BaseII), D.getIdentifierLoc(),
6606                       LookupOrdinaryName);
6607   LookupParsedName(Lookup, S, &D.getCXXScopeSpec());
6608 
6609   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6610   QualType FType = TInfo->getType();
6611 
6612   bool IsConstexpr =
6613       D.getDeclSpec().getConstexprSpecifier() == ConstexprSpecKind::Constexpr;
6614   bool IsConsteval =
6615       D.getDeclSpec().getConstexprSpecifier() == ConstexprSpecKind::Consteval;
6616 
6617   for (auto *Candidate : Lookup) {
6618     auto *CandidateDecl = Candidate->getUnderlyingDecl();
6619     FunctionDecl *UDecl = nullptr;
6620     if (IsTemplated && isa<FunctionTemplateDecl>(CandidateDecl))
6621       UDecl = cast<FunctionTemplateDecl>(CandidateDecl)->getTemplatedDecl();
6622     else if (!IsTemplated)
6623       UDecl = dyn_cast<FunctionDecl>(CandidateDecl);
6624     if (!UDecl)
6625       continue;
6626 
6627     // Don't specialize constexpr/consteval functions with
6628     // non-constexpr/consteval functions.
6629     if (UDecl->isConstexpr() && !IsConstexpr)
6630       continue;
6631     if (UDecl->isConsteval() && !IsConsteval)
6632       continue;
6633 
6634     QualType UDeclTy = UDecl->getType();
6635     if (!UDeclTy->isDependentType()) {
6636       QualType NewType = Context.mergeFunctionTypes(
6637           FType, UDeclTy, /* OfBlockPointer */ false,
6638           /* Unqualified */ false, /* AllowCXX */ true);
6639       if (NewType.isNull())
6640         continue;
6641     }
6642 
6643     // Found a base!
6644     Bases.push_back(UDecl);
6645   }
6646 
6647   bool UseImplicitBase = !DVScope.TI->isExtensionActive(
6648       llvm::omp::TraitProperty::implementation_extension_disable_implicit_base);
6649   // If no base was found we create a declaration that we use as base.
6650   if (Bases.empty() && UseImplicitBase) {
6651     D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration);
6652     Decl *BaseD = HandleDeclarator(S, D, TemplateParamLists);
6653     BaseD->setImplicit(true);
6654     if (auto *BaseTemplD = dyn_cast<FunctionTemplateDecl>(BaseD))
6655       Bases.push_back(BaseTemplD->getTemplatedDecl());
6656     else
6657       Bases.push_back(cast<FunctionDecl>(BaseD));
6658   }
6659 
6660   std::string MangledName;
6661   MangledName += D.getIdentifier()->getName();
6662   MangledName += getOpenMPVariantManglingSeparatorStr();
6663   MangledName += DVScope.NameSuffix;
6664   IdentifierInfo &VariantII = Context.Idents.get(MangledName);
6665 
6666   VariantII.setMangledOpenMPVariantName(true);
6667   D.SetIdentifier(&VariantII, D.getBeginLoc());
6668 }
6669 
6670 void Sema::ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(
6671     Decl *D, SmallVectorImpl<FunctionDecl *> &Bases) {
6672   // Do not mark function as is used to prevent its emission if this is the
6673   // only place where it is used.
6674   EnterExpressionEvaluationContext Unevaluated(
6675       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6676 
6677   FunctionDecl *FD = nullptr;
6678   if (auto *UTemplDecl = dyn_cast<FunctionTemplateDecl>(D))
6679     FD = UTemplDecl->getTemplatedDecl();
6680   else
6681     FD = cast<FunctionDecl>(D);
6682   auto *VariantFuncRef = DeclRefExpr::Create(
6683       Context, NestedNameSpecifierLoc(), SourceLocation(), FD,
6684       /* RefersToEnclosingVariableOrCapture */ false,
6685       /* NameLoc */ FD->getLocation(), FD->getType(), ExprValueKind::VK_RValue);
6686 
6687   OMPDeclareVariantScope &DVScope = OMPDeclareVariantScopes.back();
6688   auto *OMPDeclareVariantA = OMPDeclareVariantAttr::CreateImplicit(
6689       Context, VariantFuncRef, DVScope.TI);
6690   for (FunctionDecl *BaseFD : Bases)
6691     BaseFD->addAttr(OMPDeclareVariantA);
6692 }
6693 
6694 ExprResult Sema::ActOnOpenMPCall(ExprResult Call, Scope *Scope,
6695                                  SourceLocation LParenLoc,
6696                                  MultiExprArg ArgExprs,
6697                                  SourceLocation RParenLoc, Expr *ExecConfig) {
6698   // The common case is a regular call we do not want to specialize at all. Try
6699   // to make that case fast by bailing early.
6700   CallExpr *CE = dyn_cast<CallExpr>(Call.get());
6701   if (!CE)
6702     return Call;
6703 
6704   FunctionDecl *CalleeFnDecl = CE->getDirectCallee();
6705   if (!CalleeFnDecl)
6706     return Call;
6707 
6708   if (!CalleeFnDecl->hasAttr<OMPDeclareVariantAttr>())
6709     return Call;
6710 
6711   ASTContext &Context = getASTContext();
6712   std::function<void(StringRef)> DiagUnknownTrait = [this,
6713                                                      CE](StringRef ISATrait) {
6714     // TODO Track the selector locations in a way that is accessible here to
6715     // improve the diagnostic location.
6716     Diag(CE->getBeginLoc(), diag::warn_unknown_declare_variant_isa_trait)
6717         << ISATrait;
6718   };
6719   TargetOMPContext OMPCtx(Context, std::move(DiagUnknownTrait),
6720                           getCurFunctionDecl());
6721 
6722   QualType CalleeFnType = CalleeFnDecl->getType();
6723 
6724   SmallVector<Expr *, 4> Exprs;
6725   SmallVector<VariantMatchInfo, 4> VMIs;
6726   while (CalleeFnDecl) {
6727     for (OMPDeclareVariantAttr *A :
6728          CalleeFnDecl->specific_attrs<OMPDeclareVariantAttr>()) {
6729       Expr *VariantRef = A->getVariantFuncRef();
6730 
6731       VariantMatchInfo VMI;
6732       OMPTraitInfo &TI = A->getTraitInfo();
6733       TI.getAsVariantMatchInfo(Context, VMI);
6734       if (!isVariantApplicableInContext(VMI, OMPCtx,
6735                                         /* DeviceSetOnly */ false))
6736         continue;
6737 
6738       VMIs.push_back(VMI);
6739       Exprs.push_back(VariantRef);
6740     }
6741 
6742     CalleeFnDecl = CalleeFnDecl->getPreviousDecl();
6743   }
6744 
6745   ExprResult NewCall;
6746   do {
6747     int BestIdx = getBestVariantMatchForContext(VMIs, OMPCtx);
6748     if (BestIdx < 0)
6749       return Call;
6750     Expr *BestExpr = cast<DeclRefExpr>(Exprs[BestIdx]);
6751     Decl *BestDecl = cast<DeclRefExpr>(BestExpr)->getDecl();
6752 
6753     {
6754       // Try to build a (member) call expression for the current best applicable
6755       // variant expression. We allow this to fail in which case we continue
6756       // with the next best variant expression. The fail case is part of the
6757       // implementation defined behavior in the OpenMP standard when it talks
6758       // about what differences in the function prototypes: "Any differences
6759       // that the specific OpenMP context requires in the prototype of the
6760       // variant from the base function prototype are implementation defined."
6761       // This wording is there to allow the specialized variant to have a
6762       // different type than the base function. This is intended and OK but if
6763       // we cannot create a call the difference is not in the "implementation
6764       // defined range" we allow.
6765       Sema::TentativeAnalysisScope Trap(*this);
6766 
6767       if (auto *SpecializedMethod = dyn_cast<CXXMethodDecl>(BestDecl)) {
6768         auto *MemberCall = dyn_cast<CXXMemberCallExpr>(CE);
6769         BestExpr = MemberExpr::CreateImplicit(
6770             Context, MemberCall->getImplicitObjectArgument(),
6771             /* IsArrow */ false, SpecializedMethod, Context.BoundMemberTy,
6772             MemberCall->getValueKind(), MemberCall->getObjectKind());
6773       }
6774       NewCall = BuildCallExpr(Scope, BestExpr, LParenLoc, ArgExprs, RParenLoc,
6775                               ExecConfig);
6776       if (NewCall.isUsable()) {
6777         if (CallExpr *NCE = dyn_cast<CallExpr>(NewCall.get())) {
6778           FunctionDecl *NewCalleeFnDecl = NCE->getDirectCallee();
6779           QualType NewType = Context.mergeFunctionTypes(
6780               CalleeFnType, NewCalleeFnDecl->getType(),
6781               /* OfBlockPointer */ false,
6782               /* Unqualified */ false, /* AllowCXX */ true);
6783           if (!NewType.isNull())
6784             break;
6785           // Don't use the call if the function type was not compatible.
6786           NewCall = nullptr;
6787         }
6788       }
6789     }
6790 
6791     VMIs.erase(VMIs.begin() + BestIdx);
6792     Exprs.erase(Exprs.begin() + BestIdx);
6793   } while (!VMIs.empty());
6794 
6795   if (!NewCall.isUsable())
6796     return Call;
6797   return PseudoObjectExpr::Create(Context, CE, {NewCall.get()}, 0);
6798 }
6799 
6800 Optional<std::pair<FunctionDecl *, Expr *>>
6801 Sema::checkOpenMPDeclareVariantFunction(Sema::DeclGroupPtrTy DG,
6802                                         Expr *VariantRef, OMPTraitInfo &TI,
6803                                         SourceRange SR) {
6804   if (!DG || DG.get().isNull())
6805     return None;
6806 
6807   const int VariantId = 1;
6808   // Must be applied only to single decl.
6809   if (!DG.get().isSingleDecl()) {
6810     Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd_variant)
6811         << VariantId << SR;
6812     return None;
6813   }
6814   Decl *ADecl = DG.get().getSingleDecl();
6815   if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
6816     ADecl = FTD->getTemplatedDecl();
6817 
6818   // Decl must be a function.
6819   auto *FD = dyn_cast<FunctionDecl>(ADecl);
6820   if (!FD) {
6821     Diag(ADecl->getLocation(), diag::err_omp_function_expected)
6822         << VariantId << SR;
6823     return None;
6824   }
6825 
6826   auto &&HasMultiVersionAttributes = [](const FunctionDecl *FD) {
6827     return FD->hasAttrs() &&
6828            (FD->hasAttr<CPUDispatchAttr>() || FD->hasAttr<CPUSpecificAttr>() ||
6829             FD->hasAttr<TargetAttr>());
6830   };
6831   // OpenMP is not compatible with CPU-specific attributes.
6832   if (HasMultiVersionAttributes(FD)) {
6833     Diag(FD->getLocation(), diag::err_omp_declare_variant_incompat_attributes)
6834         << SR;
6835     return None;
6836   }
6837 
6838   // Allow #pragma omp declare variant only if the function is not used.
6839   if (FD->isUsed(false))
6840     Diag(SR.getBegin(), diag::warn_omp_declare_variant_after_used)
6841         << FD->getLocation();
6842 
6843   // Check if the function was emitted already.
6844   const FunctionDecl *Definition;
6845   if (!FD->isThisDeclarationADefinition() && FD->isDefined(Definition) &&
6846       (LangOpts.EmitAllDecls || Context.DeclMustBeEmitted(Definition)))
6847     Diag(SR.getBegin(), diag::warn_omp_declare_variant_after_emitted)
6848         << FD->getLocation();
6849 
6850   // The VariantRef must point to function.
6851   if (!VariantRef) {
6852     Diag(SR.getBegin(), diag::err_omp_function_expected) << VariantId;
6853     return None;
6854   }
6855 
6856   auto ShouldDelayChecks = [](Expr *&E, bool) {
6857     return E && (E->isTypeDependent() || E->isValueDependent() ||
6858                  E->containsUnexpandedParameterPack() ||
6859                  E->isInstantiationDependent());
6860   };
6861   // Do not check templates, wait until instantiation.
6862   if (FD->isDependentContext() || ShouldDelayChecks(VariantRef, false) ||
6863       TI.anyScoreOrCondition(ShouldDelayChecks))
6864     return std::make_pair(FD, VariantRef);
6865 
6866   // Deal with non-constant score and user condition expressions.
6867   auto HandleNonConstantScoresAndConditions = [this](Expr *&E,
6868                                                      bool IsScore) -> bool {
6869     if (!E || E->isIntegerConstantExpr(Context))
6870       return false;
6871 
6872     if (IsScore) {
6873       // We warn on non-constant scores and pretend they were not present.
6874       Diag(E->getExprLoc(), diag::warn_omp_declare_variant_score_not_constant)
6875           << E;
6876       E = nullptr;
6877     } else {
6878       // We could replace a non-constant user condition with "false" but we
6879       // will soon need to handle these anyway for the dynamic version of
6880       // OpenMP context selectors.
6881       Diag(E->getExprLoc(),
6882            diag::err_omp_declare_variant_user_condition_not_constant)
6883           << E;
6884     }
6885     return true;
6886   };
6887   if (TI.anyScoreOrCondition(HandleNonConstantScoresAndConditions))
6888     return None;
6889 
6890   // Convert VariantRef expression to the type of the original function to
6891   // resolve possible conflicts.
6892   ExprResult VariantRefCast = VariantRef;
6893   if (LangOpts.CPlusPlus) {
6894     QualType FnPtrType;
6895     auto *Method = dyn_cast<CXXMethodDecl>(FD);
6896     if (Method && !Method->isStatic()) {
6897       const Type *ClassType =
6898           Context.getTypeDeclType(Method->getParent()).getTypePtr();
6899       FnPtrType = Context.getMemberPointerType(FD->getType(), ClassType);
6900       ExprResult ER;
6901       {
6902         // Build adrr_of unary op to correctly handle type checks for member
6903         // functions.
6904         Sema::TentativeAnalysisScope Trap(*this);
6905         ER = CreateBuiltinUnaryOp(VariantRef->getBeginLoc(), UO_AddrOf,
6906                                   VariantRef);
6907       }
6908       if (!ER.isUsable()) {
6909         Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
6910             << VariantId << VariantRef->getSourceRange();
6911         return None;
6912       }
6913       VariantRef = ER.get();
6914     } else {
6915       FnPtrType = Context.getPointerType(FD->getType());
6916     }
6917     QualType VarianPtrType = Context.getPointerType(VariantRef->getType());
6918     if (VarianPtrType.getUnqualifiedType() != FnPtrType.getUnqualifiedType()) {
6919       ImplicitConversionSequence ICS = TryImplicitConversion(
6920           VariantRef, FnPtrType.getUnqualifiedType(),
6921           /*SuppressUserConversions=*/false, AllowedExplicit::None,
6922           /*InOverloadResolution=*/false,
6923           /*CStyle=*/false,
6924           /*AllowObjCWritebackConversion=*/false);
6925       if (ICS.isFailure()) {
6926         Diag(VariantRef->getExprLoc(),
6927              diag::err_omp_declare_variant_incompat_types)
6928             << VariantRef->getType()
6929             << ((Method && !Method->isStatic()) ? FnPtrType : FD->getType())
6930             << VariantRef->getSourceRange();
6931         return None;
6932       }
6933       VariantRefCast = PerformImplicitConversion(
6934           VariantRef, FnPtrType.getUnqualifiedType(), AA_Converting);
6935       if (!VariantRefCast.isUsable())
6936         return None;
6937     }
6938     // Drop previously built artificial addr_of unary op for member functions.
6939     if (Method && !Method->isStatic()) {
6940       Expr *PossibleAddrOfVariantRef = VariantRefCast.get();
6941       if (auto *UO = dyn_cast<UnaryOperator>(
6942               PossibleAddrOfVariantRef->IgnoreImplicit()))
6943         VariantRefCast = UO->getSubExpr();
6944     }
6945   }
6946 
6947   ExprResult ER = CheckPlaceholderExpr(VariantRefCast.get());
6948   if (!ER.isUsable() ||
6949       !ER.get()->IgnoreParenImpCasts()->getType()->isFunctionType()) {
6950     Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
6951         << VariantId << VariantRef->getSourceRange();
6952     return None;
6953   }
6954 
6955   // The VariantRef must point to function.
6956   auto *DRE = dyn_cast<DeclRefExpr>(ER.get()->IgnoreParenImpCasts());
6957   if (!DRE) {
6958     Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
6959         << VariantId << VariantRef->getSourceRange();
6960     return None;
6961   }
6962   auto *NewFD = dyn_cast_or_null<FunctionDecl>(DRE->getDecl());
6963   if (!NewFD) {
6964     Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
6965         << VariantId << VariantRef->getSourceRange();
6966     return None;
6967   }
6968 
6969   // Check if function types are compatible in C.
6970   if (!LangOpts.CPlusPlus) {
6971     QualType NewType =
6972         Context.mergeFunctionTypes(FD->getType(), NewFD->getType());
6973     if (NewType.isNull()) {
6974       Diag(VariantRef->getExprLoc(),
6975            diag::err_omp_declare_variant_incompat_types)
6976           << NewFD->getType() << FD->getType() << VariantRef->getSourceRange();
6977       return None;
6978     }
6979     if (NewType->isFunctionProtoType()) {
6980       if (FD->getType()->isFunctionNoProtoType())
6981         setPrototype(*this, FD, NewFD, NewType);
6982       else if (NewFD->getType()->isFunctionNoProtoType())
6983         setPrototype(*this, NewFD, FD, NewType);
6984     }
6985   }
6986 
6987   // Check if variant function is not marked with declare variant directive.
6988   if (NewFD->hasAttrs() && NewFD->hasAttr<OMPDeclareVariantAttr>()) {
6989     Diag(VariantRef->getExprLoc(),
6990          diag::warn_omp_declare_variant_marked_as_declare_variant)
6991         << VariantRef->getSourceRange();
6992     SourceRange SR =
6993         NewFD->specific_attr_begin<OMPDeclareVariantAttr>()->getRange();
6994     Diag(SR.getBegin(), diag::note_omp_marked_declare_variant_here) << SR;
6995     return None;
6996   }
6997 
6998   enum DoesntSupport {
6999     VirtFuncs = 1,
7000     Constructors = 3,
7001     Destructors = 4,
7002     DeletedFuncs = 5,
7003     DefaultedFuncs = 6,
7004     ConstexprFuncs = 7,
7005     ConstevalFuncs = 8,
7006   };
7007   if (const auto *CXXFD = dyn_cast<CXXMethodDecl>(FD)) {
7008     if (CXXFD->isVirtual()) {
7009       Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
7010           << VirtFuncs;
7011       return None;
7012     }
7013 
7014     if (isa<CXXConstructorDecl>(FD)) {
7015       Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
7016           << Constructors;
7017       return None;
7018     }
7019 
7020     if (isa<CXXDestructorDecl>(FD)) {
7021       Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
7022           << Destructors;
7023       return None;
7024     }
7025   }
7026 
7027   if (FD->isDeleted()) {
7028     Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
7029         << DeletedFuncs;
7030     return None;
7031   }
7032 
7033   if (FD->isDefaulted()) {
7034     Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
7035         << DefaultedFuncs;
7036     return None;
7037   }
7038 
7039   if (FD->isConstexpr()) {
7040     Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
7041         << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
7042     return None;
7043   }
7044 
7045   // Check general compatibility.
7046   if (areMultiversionVariantFunctionsCompatible(
7047           FD, NewFD, PartialDiagnostic::NullDiagnostic(),
7048           PartialDiagnosticAt(SourceLocation(),
7049                               PartialDiagnostic::NullDiagnostic()),
7050           PartialDiagnosticAt(
7051               VariantRef->getExprLoc(),
7052               PDiag(diag::err_omp_declare_variant_doesnt_support)),
7053           PartialDiagnosticAt(VariantRef->getExprLoc(),
7054                               PDiag(diag::err_omp_declare_variant_diff)
7055                                   << FD->getLocation()),
7056           /*TemplatesSupported=*/true, /*ConstexprSupported=*/false,
7057           /*CLinkageMayDiffer=*/true))
7058     return None;
7059   return std::make_pair(FD, cast<Expr>(DRE));
7060 }
7061 
7062 void Sema::ActOnOpenMPDeclareVariantDirective(FunctionDecl *FD,
7063                                               Expr *VariantRef,
7064                                               OMPTraitInfo &TI,
7065                                               SourceRange SR) {
7066   auto *NewAttr =
7067       OMPDeclareVariantAttr::CreateImplicit(Context, VariantRef, &TI, SR);
7068   FD->addAttr(NewAttr);
7069 }
7070 
7071 StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
7072                                               Stmt *AStmt,
7073                                               SourceLocation StartLoc,
7074                                               SourceLocation EndLoc) {
7075   if (!AStmt)
7076     return StmtError();
7077 
7078   auto *CS = cast<CapturedStmt>(AStmt);
7079   // 1.2.2 OpenMP Language Terminology
7080   // Structured block - An executable statement with a single entry at the
7081   // top and a single exit at the bottom.
7082   // The point of exit cannot be a branch out of the structured block.
7083   // longjmp() and throw() must not violate the entry/exit criteria.
7084   CS->getCapturedDecl()->setNothrow();
7085 
7086   setFunctionHasBranchProtectedScope();
7087 
7088   return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
7089                                       DSAStack->getTaskgroupReductionRef(),
7090                                       DSAStack->isCancelRegion());
7091 }
7092 
7093 namespace {
7094 /// Iteration space of a single for loop.
7095 struct LoopIterationSpace final {
7096   /// True if the condition operator is the strict compare operator (<, > or
7097   /// !=).
7098   bool IsStrictCompare = false;
7099   /// Condition of the loop.
7100   Expr *PreCond = nullptr;
7101   /// This expression calculates the number of iterations in the loop.
7102   /// It is always possible to calculate it before starting the loop.
7103   Expr *NumIterations = nullptr;
7104   /// The loop counter variable.
7105   Expr *CounterVar = nullptr;
7106   /// Private loop counter variable.
7107   Expr *PrivateCounterVar = nullptr;
7108   /// This is initializer for the initial value of #CounterVar.
7109   Expr *CounterInit = nullptr;
7110   /// This is step for the #CounterVar used to generate its update:
7111   /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
7112   Expr *CounterStep = nullptr;
7113   /// Should step be subtracted?
7114   bool Subtract = false;
7115   /// Source range of the loop init.
7116   SourceRange InitSrcRange;
7117   /// Source range of the loop condition.
7118   SourceRange CondSrcRange;
7119   /// Source range of the loop increment.
7120   SourceRange IncSrcRange;
7121   /// Minimum value that can have the loop control variable. Used to support
7122   /// non-rectangular loops. Applied only for LCV with the non-iterator types,
7123   /// since only such variables can be used in non-loop invariant expressions.
7124   Expr *MinValue = nullptr;
7125   /// Maximum value that can have the loop control variable. Used to support
7126   /// non-rectangular loops. Applied only for LCV with the non-iterator type,
7127   /// since only such variables can be used in non-loop invariant expressions.
7128   Expr *MaxValue = nullptr;
7129   /// true, if the lower bound depends on the outer loop control var.
7130   bool IsNonRectangularLB = false;
7131   /// true, if the upper bound depends on the outer loop control var.
7132   bool IsNonRectangularUB = false;
7133   /// Index of the loop this loop depends on and forms non-rectangular loop
7134   /// nest.
7135   unsigned LoopDependentIdx = 0;
7136   /// Final condition for the non-rectangular loop nest support. It is used to
7137   /// check that the number of iterations for this particular counter must be
7138   /// finished.
7139   Expr *FinalCondition = nullptr;
7140 };
7141 
7142 /// Helper class for checking canonical form of the OpenMP loops and
7143 /// extracting iteration space of each loop in the loop nest, that will be used
7144 /// for IR generation.
7145 class OpenMPIterationSpaceChecker {
7146   /// Reference to Sema.
7147   Sema &SemaRef;
7148   /// Does the loop associated directive support non-rectangular loops?
7149   bool SupportsNonRectangular;
7150   /// Data-sharing stack.
7151   DSAStackTy &Stack;
7152   /// A location for diagnostics (when there is no some better location).
7153   SourceLocation DefaultLoc;
7154   /// A location for diagnostics (when increment is not compatible).
7155   SourceLocation ConditionLoc;
7156   /// A source location for referring to loop init later.
7157   SourceRange InitSrcRange;
7158   /// A source location for referring to condition later.
7159   SourceRange ConditionSrcRange;
7160   /// A source location for referring to increment later.
7161   SourceRange IncrementSrcRange;
7162   /// Loop variable.
7163   ValueDecl *LCDecl = nullptr;
7164   /// Reference to loop variable.
7165   Expr *LCRef = nullptr;
7166   /// Lower bound (initializer for the var).
7167   Expr *LB = nullptr;
7168   /// Upper bound.
7169   Expr *UB = nullptr;
7170   /// Loop step (increment).
7171   Expr *Step = nullptr;
7172   /// This flag is true when condition is one of:
7173   ///   Var <  UB
7174   ///   Var <= UB
7175   ///   UB  >  Var
7176   ///   UB  >= Var
7177   /// This will have no value when the condition is !=
7178   llvm::Optional<bool> TestIsLessOp;
7179   /// This flag is true when condition is strict ( < or > ).
7180   bool TestIsStrictOp = false;
7181   /// This flag is true when step is subtracted on each iteration.
7182   bool SubtractStep = false;
7183   /// The outer loop counter this loop depends on (if any).
7184   const ValueDecl *DepDecl = nullptr;
7185   /// Contains number of loop (starts from 1) on which loop counter init
7186   /// expression of this loop depends on.
7187   Optional<unsigned> InitDependOnLC;
7188   /// Contains number of loop (starts from 1) on which loop counter condition
7189   /// expression of this loop depends on.
7190   Optional<unsigned> CondDependOnLC;
7191   /// Checks if the provide statement depends on the loop counter.
7192   Optional<unsigned> doesDependOnLoopCounter(const Stmt *S, bool IsInitializer);
7193   /// Original condition required for checking of the exit condition for
7194   /// non-rectangular loop.
7195   Expr *Condition = nullptr;
7196 
7197 public:
7198   OpenMPIterationSpaceChecker(Sema &SemaRef, bool SupportsNonRectangular,
7199                               DSAStackTy &Stack, SourceLocation DefaultLoc)
7200       : SemaRef(SemaRef), SupportsNonRectangular(SupportsNonRectangular),
7201         Stack(Stack), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {}
7202   /// Check init-expr for canonical loop form and save loop counter
7203   /// variable - #Var and its initialization value - #LB.
7204   bool checkAndSetInit(Stmt *S, bool EmitDiags = true);
7205   /// Check test-expr for canonical form, save upper-bound (#UB), flags
7206   /// for less/greater and for strict/non-strict comparison.
7207   bool checkAndSetCond(Expr *S);
7208   /// Check incr-expr for canonical loop form and return true if it
7209   /// does not conform, otherwise save loop step (#Step).
7210   bool checkAndSetInc(Expr *S);
7211   /// Return the loop counter variable.
7212   ValueDecl *getLoopDecl() const { return LCDecl; }
7213   /// Return the reference expression to loop counter variable.
7214   Expr *getLoopDeclRefExpr() const { return LCRef; }
7215   /// Source range of the loop init.
7216   SourceRange getInitSrcRange() const { return InitSrcRange; }
7217   /// Source range of the loop condition.
7218   SourceRange getConditionSrcRange() const { return ConditionSrcRange; }
7219   /// Source range of the loop increment.
7220   SourceRange getIncrementSrcRange() const { return IncrementSrcRange; }
7221   /// True if the step should be subtracted.
7222   bool shouldSubtractStep() const { return SubtractStep; }
7223   /// True, if the compare operator is strict (<, > or !=).
7224   bool isStrictTestOp() const { return TestIsStrictOp; }
7225   /// Build the expression to calculate the number of iterations.
7226   Expr *buildNumIterations(
7227       Scope *S, ArrayRef<LoopIterationSpace> ResultIterSpaces, bool LimitedType,
7228       llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
7229   /// Build the precondition expression for the loops.
7230   Expr *
7231   buildPreCond(Scope *S, Expr *Cond,
7232                llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
7233   /// Build reference expression to the counter be used for codegen.
7234   DeclRefExpr *
7235   buildCounterVar(llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
7236                   DSAStackTy &DSA) const;
7237   /// Build reference expression to the private counter be used for
7238   /// codegen.
7239   Expr *buildPrivateCounterVar() const;
7240   /// Build initialization of the counter be used for codegen.
7241   Expr *buildCounterInit() const;
7242   /// Build step of the counter be used for codegen.
7243   Expr *buildCounterStep() const;
7244   /// Build loop data with counter value for depend clauses in ordered
7245   /// directives.
7246   Expr *
7247   buildOrderedLoopData(Scope *S, Expr *Counter,
7248                        llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
7249                        SourceLocation Loc, Expr *Inc = nullptr,
7250                        OverloadedOperatorKind OOK = OO_Amp);
7251   /// Builds the minimum value for the loop counter.
7252   std::pair<Expr *, Expr *> buildMinMaxValues(
7253       Scope *S, llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
7254   /// Builds final condition for the non-rectangular loops.
7255   Expr *buildFinalCondition(Scope *S) const;
7256   /// Return true if any expression is dependent.
7257   bool dependent() const;
7258   /// Returns true if the initializer forms non-rectangular loop.
7259   bool doesInitDependOnLC() const { return InitDependOnLC.hasValue(); }
7260   /// Returns true if the condition forms non-rectangular loop.
7261   bool doesCondDependOnLC() const { return CondDependOnLC.hasValue(); }
7262   /// Returns index of the loop we depend on (starting from 1), or 0 otherwise.
7263   unsigned getLoopDependentIdx() const {
7264     return InitDependOnLC.getValueOr(CondDependOnLC.getValueOr(0));
7265   }
7266 
7267 private:
7268   /// Check the right-hand side of an assignment in the increment
7269   /// expression.
7270   bool checkAndSetIncRHS(Expr *RHS);
7271   /// Helper to set loop counter variable and its initializer.
7272   bool setLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB,
7273                       bool EmitDiags);
7274   /// Helper to set upper bound.
7275   bool setUB(Expr *NewUB, llvm::Optional<bool> LessOp, bool StrictOp,
7276              SourceRange SR, SourceLocation SL);
7277   /// Helper to set loop increment.
7278   bool setStep(Expr *NewStep, bool Subtract);
7279 };
7280 
7281 bool OpenMPIterationSpaceChecker::dependent() const {
7282   if (!LCDecl) {
7283     assert(!LB && !UB && !Step);
7284     return false;
7285   }
7286   return LCDecl->getType()->isDependentType() ||
7287          (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
7288          (Step && Step->isValueDependent());
7289 }
7290 
7291 bool OpenMPIterationSpaceChecker::setLCDeclAndLB(ValueDecl *NewLCDecl,
7292                                                  Expr *NewLCRefExpr,
7293                                                  Expr *NewLB, bool EmitDiags) {
7294   // State consistency checking to ensure correct usage.
7295   assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
7296          UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
7297   if (!NewLCDecl || !NewLB)
7298     return true;
7299   LCDecl = getCanonicalDecl(NewLCDecl);
7300   LCRef = NewLCRefExpr;
7301   if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
7302     if (const CXXConstructorDecl *Ctor = CE->getConstructor())
7303       if ((Ctor->isCopyOrMoveConstructor() ||
7304            Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
7305           CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
7306         NewLB = CE->getArg(0)->IgnoreParenImpCasts();
7307   LB = NewLB;
7308   if (EmitDiags)
7309     InitDependOnLC = doesDependOnLoopCounter(LB, /*IsInitializer=*/true);
7310   return false;
7311 }
7312 
7313 bool OpenMPIterationSpaceChecker::setUB(Expr *NewUB,
7314                                         llvm::Optional<bool> LessOp,
7315                                         bool StrictOp, SourceRange SR,
7316                                         SourceLocation SL) {
7317   // State consistency checking to ensure correct usage.
7318   assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
7319          Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
7320   if (!NewUB)
7321     return true;
7322   UB = NewUB;
7323   if (LessOp)
7324     TestIsLessOp = LessOp;
7325   TestIsStrictOp = StrictOp;
7326   ConditionSrcRange = SR;
7327   ConditionLoc = SL;
7328   CondDependOnLC = doesDependOnLoopCounter(UB, /*IsInitializer=*/false);
7329   return false;
7330 }
7331 
7332 bool OpenMPIterationSpaceChecker::setStep(Expr *NewStep, bool Subtract) {
7333   // State consistency checking to ensure correct usage.
7334   assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
7335   if (!NewStep)
7336     return true;
7337   if (!NewStep->isValueDependent()) {
7338     // Check that the step is integer expression.
7339     SourceLocation StepLoc = NewStep->getBeginLoc();
7340     ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion(
7341         StepLoc, getExprAsWritten(NewStep));
7342     if (Val.isInvalid())
7343       return true;
7344     NewStep = Val.get();
7345 
7346     // OpenMP [2.6, Canonical Loop Form, Restrictions]
7347     //  If test-expr is of form var relational-op b and relational-op is < or
7348     //  <= then incr-expr must cause var to increase on each iteration of the
7349     //  loop. If test-expr is of form var relational-op b and relational-op is
7350     //  > or >= then incr-expr must cause var to decrease on each iteration of
7351     //  the loop.
7352     //  If test-expr is of form b relational-op var and relational-op is < or
7353     //  <= then incr-expr must cause var to decrease on each iteration of the
7354     //  loop. If test-expr is of form b relational-op var and relational-op is
7355     //  > or >= then incr-expr must cause var to increase on each iteration of
7356     //  the loop.
7357     Optional<llvm::APSInt> Result =
7358         NewStep->getIntegerConstantExpr(SemaRef.Context);
7359     bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
7360     bool IsConstNeg =
7361         Result && Result->isSigned() && (Subtract != Result->isNegative());
7362     bool IsConstPos =
7363         Result && Result->isSigned() && (Subtract == Result->isNegative());
7364     bool IsConstZero = Result && !Result->getBoolValue();
7365 
7366     // != with increment is treated as <; != with decrement is treated as >
7367     if (!TestIsLessOp.hasValue())
7368       TestIsLessOp = IsConstPos || (IsUnsigned && !Subtract);
7369     if (UB && (IsConstZero ||
7370                (TestIsLessOp.getValue() ?
7371                   (IsConstNeg || (IsUnsigned && Subtract)) :
7372                   (IsConstPos || (IsUnsigned && !Subtract))))) {
7373       SemaRef.Diag(NewStep->getExprLoc(),
7374                    diag::err_omp_loop_incr_not_compatible)
7375           << LCDecl << TestIsLessOp.getValue() << NewStep->getSourceRange();
7376       SemaRef.Diag(ConditionLoc,
7377                    diag::note_omp_loop_cond_requres_compatible_incr)
7378           << TestIsLessOp.getValue() << ConditionSrcRange;
7379       return true;
7380     }
7381     if (TestIsLessOp.getValue() == Subtract) {
7382       NewStep =
7383           SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
7384               .get();
7385       Subtract = !Subtract;
7386     }
7387   }
7388 
7389   Step = NewStep;
7390   SubtractStep = Subtract;
7391   return false;
7392 }
7393 
7394 namespace {
7395 /// Checker for the non-rectangular loops. Checks if the initializer or
7396 /// condition expression references loop counter variable.
7397 class LoopCounterRefChecker final
7398     : public ConstStmtVisitor<LoopCounterRefChecker, bool> {
7399   Sema &SemaRef;
7400   DSAStackTy &Stack;
7401   const ValueDecl *CurLCDecl = nullptr;
7402   const ValueDecl *DepDecl = nullptr;
7403   const ValueDecl *PrevDepDecl = nullptr;
7404   bool IsInitializer = true;
7405   bool SupportsNonRectangular;
7406   unsigned BaseLoopId = 0;
7407   bool checkDecl(const Expr *E, const ValueDecl *VD) {
7408     if (getCanonicalDecl(VD) == getCanonicalDecl(CurLCDecl)) {
7409       SemaRef.Diag(E->getExprLoc(), diag::err_omp_stmt_depends_on_loop_counter)
7410           << (IsInitializer ? 0 : 1);
7411       return false;
7412     }
7413     const auto &&Data = Stack.isLoopControlVariable(VD);
7414     // OpenMP, 2.9.1 Canonical Loop Form, Restrictions.
7415     // The type of the loop iterator on which we depend may not have a random
7416     // access iterator type.
7417     if (Data.first && VD->getType()->isRecordType()) {
7418       SmallString<128> Name;
7419       llvm::raw_svector_ostream OS(Name);
7420       VD->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(),
7421                                /*Qualified=*/true);
7422       SemaRef.Diag(E->getExprLoc(),
7423                    diag::err_omp_wrong_dependency_iterator_type)
7424           << OS.str();
7425       SemaRef.Diag(VD->getLocation(), diag::note_previous_decl) << VD;
7426       return false;
7427     }
7428     if (Data.first && !SupportsNonRectangular) {
7429       SemaRef.Diag(E->getExprLoc(), diag::err_omp_invariant_dependency);
7430       return false;
7431     }
7432     if (Data.first &&
7433         (DepDecl || (PrevDepDecl &&
7434                      getCanonicalDecl(VD) != getCanonicalDecl(PrevDepDecl)))) {
7435       if (!DepDecl && PrevDepDecl)
7436         DepDecl = PrevDepDecl;
7437       SmallString<128> Name;
7438       llvm::raw_svector_ostream OS(Name);
7439       DepDecl->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(),
7440                                     /*Qualified=*/true);
7441       SemaRef.Diag(E->getExprLoc(),
7442                    diag::err_omp_invariant_or_linear_dependency)
7443           << OS.str();
7444       return false;
7445     }
7446     if (Data.first) {
7447       DepDecl = VD;
7448       BaseLoopId = Data.first;
7449     }
7450     return Data.first;
7451   }
7452 
7453 public:
7454   bool VisitDeclRefExpr(const DeclRefExpr *E) {
7455     const ValueDecl *VD = E->getDecl();
7456     if (isa<VarDecl>(VD))
7457       return checkDecl(E, VD);
7458     return false;
7459   }
7460   bool VisitMemberExpr(const MemberExpr *E) {
7461     if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
7462       const ValueDecl *VD = E->getMemberDecl();
7463       if (isa<VarDecl>(VD) || isa<FieldDecl>(VD))
7464         return checkDecl(E, VD);
7465     }
7466     return false;
7467   }
7468   bool VisitStmt(const Stmt *S) {
7469     bool Res = false;
7470     for (const Stmt *Child : S->children())
7471       Res = (Child && Visit(Child)) || Res;
7472     return Res;
7473   }
7474   explicit LoopCounterRefChecker(Sema &SemaRef, DSAStackTy &Stack,
7475                                  const ValueDecl *CurLCDecl, bool IsInitializer,
7476                                  const ValueDecl *PrevDepDecl = nullptr,
7477                                  bool SupportsNonRectangular = true)
7478       : SemaRef(SemaRef), Stack(Stack), CurLCDecl(CurLCDecl),
7479         PrevDepDecl(PrevDepDecl), IsInitializer(IsInitializer),
7480         SupportsNonRectangular(SupportsNonRectangular) {}
7481   unsigned getBaseLoopId() const {
7482     assert(CurLCDecl && "Expected loop dependency.");
7483     return BaseLoopId;
7484   }
7485   const ValueDecl *getDepDecl() const {
7486     assert(CurLCDecl && "Expected loop dependency.");
7487     return DepDecl;
7488   }
7489 };
7490 } // namespace
7491 
7492 Optional<unsigned>
7493 OpenMPIterationSpaceChecker::doesDependOnLoopCounter(const Stmt *S,
7494                                                      bool IsInitializer) {
7495   // Check for the non-rectangular loops.
7496   LoopCounterRefChecker LoopStmtChecker(SemaRef, Stack, LCDecl, IsInitializer,
7497                                         DepDecl, SupportsNonRectangular);
7498   if (LoopStmtChecker.Visit(S)) {
7499     DepDecl = LoopStmtChecker.getDepDecl();
7500     return LoopStmtChecker.getBaseLoopId();
7501   }
7502   return llvm::None;
7503 }
7504 
7505 bool OpenMPIterationSpaceChecker::checkAndSetInit(Stmt *S, bool EmitDiags) {
7506   // Check init-expr for canonical loop form and save loop counter
7507   // variable - #Var and its initialization value - #LB.
7508   // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
7509   //   var = lb
7510   //   integer-type var = lb
7511   //   random-access-iterator-type var = lb
7512   //   pointer-type var = lb
7513   //
7514   if (!S) {
7515     if (EmitDiags) {
7516       SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
7517     }
7518     return true;
7519   }
7520   if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
7521     if (!ExprTemp->cleanupsHaveSideEffects())
7522       S = ExprTemp->getSubExpr();
7523 
7524   InitSrcRange = S->getSourceRange();
7525   if (Expr *E = dyn_cast<Expr>(S))
7526     S = E->IgnoreParens();
7527   if (auto *BO = dyn_cast<BinaryOperator>(S)) {
7528     if (BO->getOpcode() == BO_Assign) {
7529       Expr *LHS = BO->getLHS()->IgnoreParens();
7530       if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
7531         if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
7532           if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
7533             return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
7534                                   EmitDiags);
7535         return setLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS(), EmitDiags);
7536       }
7537       if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
7538         if (ME->isArrow() &&
7539             isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
7540           return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
7541                                 EmitDiags);
7542       }
7543     }
7544   } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
7545     if (DS->isSingleDecl()) {
7546       if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
7547         if (Var->hasInit() && !Var->getType()->isReferenceType()) {
7548           // Accept non-canonical init form here but emit ext. warning.
7549           if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
7550             SemaRef.Diag(S->getBeginLoc(),
7551                          diag::ext_omp_loop_not_canonical_init)
7552                 << S->getSourceRange();
7553           return setLCDeclAndLB(
7554               Var,
7555               buildDeclRefExpr(SemaRef, Var,
7556                                Var->getType().getNonReferenceType(),
7557                                DS->getBeginLoc()),
7558               Var->getInit(), EmitDiags);
7559         }
7560       }
7561     }
7562   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
7563     if (CE->getOperator() == OO_Equal) {
7564       Expr *LHS = CE->getArg(0);
7565       if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
7566         if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
7567           if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
7568             return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
7569                                   EmitDiags);
7570         return setLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1), EmitDiags);
7571       }
7572       if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
7573         if (ME->isArrow() &&
7574             isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
7575           return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
7576                                 EmitDiags);
7577       }
7578     }
7579   }
7580 
7581   if (dependent() || SemaRef.CurContext->isDependentContext())
7582     return false;
7583   if (EmitDiags) {
7584     SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_init)
7585         << S->getSourceRange();
7586   }
7587   return true;
7588 }
7589 
7590 /// Ignore parenthesizes, implicit casts, copy constructor and return the
7591 /// variable (which may be the loop variable) if possible.
7592 static const ValueDecl *getInitLCDecl(const Expr *E) {
7593   if (!E)
7594     return nullptr;
7595   E = getExprAsWritten(E);
7596   if (const auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
7597     if (const CXXConstructorDecl *Ctor = CE->getConstructor())
7598       if ((Ctor->isCopyOrMoveConstructor() ||
7599            Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
7600           CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
7601         E = CE->getArg(0)->IgnoreParenImpCasts();
7602   if (const auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
7603     if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
7604       return getCanonicalDecl(VD);
7605   }
7606   if (const auto *ME = dyn_cast_or_null<MemberExpr>(E))
7607     if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
7608       return getCanonicalDecl(ME->getMemberDecl());
7609   return nullptr;
7610 }
7611 
7612 bool OpenMPIterationSpaceChecker::checkAndSetCond(Expr *S) {
7613   // Check test-expr for canonical form, save upper-bound UB, flags for
7614   // less/greater and for strict/non-strict comparison.
7615   // OpenMP [2.9] Canonical loop form. Test-expr may be one of the following:
7616   //   var relational-op b
7617   //   b relational-op var
7618   //
7619   bool IneqCondIsCanonical = SemaRef.getLangOpts().OpenMP >= 50;
7620   if (!S) {
7621     SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond)
7622         << (IneqCondIsCanonical ? 1 : 0) << LCDecl;
7623     return true;
7624   }
7625   Condition = S;
7626   S = getExprAsWritten(S);
7627   SourceLocation CondLoc = S->getBeginLoc();
7628   if (auto *BO = dyn_cast<BinaryOperator>(S)) {
7629     if (BO->isRelationalOp()) {
7630       if (getInitLCDecl(BO->getLHS()) == LCDecl)
7631         return setUB(BO->getRHS(),
7632                      (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
7633                      (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
7634                      BO->getSourceRange(), BO->getOperatorLoc());
7635       if (getInitLCDecl(BO->getRHS()) == LCDecl)
7636         return setUB(BO->getLHS(),
7637                      (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
7638                      (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
7639                      BO->getSourceRange(), BO->getOperatorLoc());
7640     } else if (IneqCondIsCanonical && BO->getOpcode() == BO_NE)
7641       return setUB(
7642           getInitLCDecl(BO->getLHS()) == LCDecl ? BO->getRHS() : BO->getLHS(),
7643           /*LessOp=*/llvm::None,
7644           /*StrictOp=*/true, BO->getSourceRange(), BO->getOperatorLoc());
7645   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
7646     if (CE->getNumArgs() == 2) {
7647       auto Op = CE->getOperator();
7648       switch (Op) {
7649       case OO_Greater:
7650       case OO_GreaterEqual:
7651       case OO_Less:
7652       case OO_LessEqual:
7653         if (getInitLCDecl(CE->getArg(0)) == LCDecl)
7654           return setUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
7655                        Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
7656                        CE->getOperatorLoc());
7657         if (getInitLCDecl(CE->getArg(1)) == LCDecl)
7658           return setUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
7659                        Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
7660                        CE->getOperatorLoc());
7661         break;
7662       case OO_ExclaimEqual:
7663         if (IneqCondIsCanonical)
7664           return setUB(getInitLCDecl(CE->getArg(0)) == LCDecl ? CE->getArg(1)
7665                                                               : CE->getArg(0),
7666                        /*LessOp=*/llvm::None,
7667                        /*StrictOp=*/true, CE->getSourceRange(),
7668                        CE->getOperatorLoc());
7669         break;
7670       default:
7671         break;
7672       }
7673     }
7674   }
7675   if (dependent() || SemaRef.CurContext->isDependentContext())
7676     return false;
7677   SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
7678       << (IneqCondIsCanonical ? 1 : 0) << S->getSourceRange() << LCDecl;
7679   return true;
7680 }
7681 
7682 bool OpenMPIterationSpaceChecker::checkAndSetIncRHS(Expr *RHS) {
7683   // RHS of canonical loop form increment can be:
7684   //   var + incr
7685   //   incr + var
7686   //   var - incr
7687   //
7688   RHS = RHS->IgnoreParenImpCasts();
7689   if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
7690     if (BO->isAdditiveOp()) {
7691       bool IsAdd = BO->getOpcode() == BO_Add;
7692       if (getInitLCDecl(BO->getLHS()) == LCDecl)
7693         return setStep(BO->getRHS(), !IsAdd);
7694       if (IsAdd && getInitLCDecl(BO->getRHS()) == LCDecl)
7695         return setStep(BO->getLHS(), /*Subtract=*/false);
7696     }
7697   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
7698     bool IsAdd = CE->getOperator() == OO_Plus;
7699     if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
7700       if (getInitLCDecl(CE->getArg(0)) == LCDecl)
7701         return setStep(CE->getArg(1), !IsAdd);
7702       if (IsAdd && getInitLCDecl(CE->getArg(1)) == LCDecl)
7703         return setStep(CE->getArg(0), /*Subtract=*/false);
7704     }
7705   }
7706   if (dependent() || SemaRef.CurContext->isDependentContext())
7707     return false;
7708   SemaRef.Diag(RHS->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
7709       << RHS->getSourceRange() << LCDecl;
7710   return true;
7711 }
7712 
7713 bool OpenMPIterationSpaceChecker::checkAndSetInc(Expr *S) {
7714   // Check incr-expr for canonical loop form and return true if it
7715   // does not conform.
7716   // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
7717   //   ++var
7718   //   var++
7719   //   --var
7720   //   var--
7721   //   var += incr
7722   //   var -= incr
7723   //   var = var + incr
7724   //   var = incr + var
7725   //   var = var - incr
7726   //
7727   if (!S) {
7728     SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
7729     return true;
7730   }
7731   if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
7732     if (!ExprTemp->cleanupsHaveSideEffects())
7733       S = ExprTemp->getSubExpr();
7734 
7735   IncrementSrcRange = S->getSourceRange();
7736   S = S->IgnoreParens();
7737   if (auto *UO = dyn_cast<UnaryOperator>(S)) {
7738     if (UO->isIncrementDecrementOp() &&
7739         getInitLCDecl(UO->getSubExpr()) == LCDecl)
7740       return setStep(SemaRef
7741                          .ActOnIntegerConstant(UO->getBeginLoc(),
7742                                                (UO->isDecrementOp() ? -1 : 1))
7743                          .get(),
7744                      /*Subtract=*/false);
7745   } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
7746     switch (BO->getOpcode()) {
7747     case BO_AddAssign:
7748     case BO_SubAssign:
7749       if (getInitLCDecl(BO->getLHS()) == LCDecl)
7750         return setStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
7751       break;
7752     case BO_Assign:
7753       if (getInitLCDecl(BO->getLHS()) == LCDecl)
7754         return checkAndSetIncRHS(BO->getRHS());
7755       break;
7756     default:
7757       break;
7758     }
7759   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
7760     switch (CE->getOperator()) {
7761     case OO_PlusPlus:
7762     case OO_MinusMinus:
7763       if (getInitLCDecl(CE->getArg(0)) == LCDecl)
7764         return setStep(SemaRef
7765                            .ActOnIntegerConstant(
7766                                CE->getBeginLoc(),
7767                                ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
7768                            .get(),
7769                        /*Subtract=*/false);
7770       break;
7771     case OO_PlusEqual:
7772     case OO_MinusEqual:
7773       if (getInitLCDecl(CE->getArg(0)) == LCDecl)
7774         return setStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
7775       break;
7776     case OO_Equal:
7777       if (getInitLCDecl(CE->getArg(0)) == LCDecl)
7778         return checkAndSetIncRHS(CE->getArg(1));
7779       break;
7780     default:
7781       break;
7782     }
7783   }
7784   if (dependent() || SemaRef.CurContext->isDependentContext())
7785     return false;
7786   SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
7787       << S->getSourceRange() << LCDecl;
7788   return true;
7789 }
7790 
7791 static ExprResult
7792 tryBuildCapture(Sema &SemaRef, Expr *Capture,
7793                 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
7794   if (SemaRef.CurContext->isDependentContext() || Capture->containsErrors())
7795     return Capture;
7796   if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
7797     return SemaRef.PerformImplicitConversion(
7798         Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
7799         /*AllowExplicit=*/true);
7800   auto I = Captures.find(Capture);
7801   if (I != Captures.end())
7802     return buildCapture(SemaRef, Capture, I->second);
7803   DeclRefExpr *Ref = nullptr;
7804   ExprResult Res = buildCapture(SemaRef, Capture, Ref);
7805   Captures[Capture] = Ref;
7806   return Res;
7807 }
7808 
7809 /// Calculate number of iterations, transforming to unsigned, if number of
7810 /// iterations may be larger than the original type.
7811 static Expr *
7812 calculateNumIters(Sema &SemaRef, Scope *S, SourceLocation DefaultLoc,
7813                   Expr *Lower, Expr *Upper, Expr *Step, QualType LCTy,
7814                   bool TestIsStrictOp, bool RoundToStep,
7815                   llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
7816   ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
7817   if (!NewStep.isUsable())
7818     return nullptr;
7819   llvm::APSInt LRes, SRes;
7820   bool IsLowerConst = false, IsStepConst = false;
7821   if (Optional<llvm::APSInt> Res = Lower->getIntegerConstantExpr(SemaRef.Context)) {
7822     LRes = *Res;
7823     IsLowerConst = true;
7824   }
7825   if (Optional<llvm::APSInt> Res = Step->getIntegerConstantExpr(SemaRef.Context)) {
7826     SRes = *Res;
7827     IsStepConst = true;
7828   }
7829   bool NoNeedToConvert = IsLowerConst && !RoundToStep &&
7830                          ((!TestIsStrictOp && LRes.isNonNegative()) ||
7831                           (TestIsStrictOp && LRes.isStrictlyPositive()));
7832   bool NeedToReorganize = false;
7833   // Check if any subexpressions in Lower -Step [+ 1] lead to overflow.
7834   if (!NoNeedToConvert && IsLowerConst &&
7835       (TestIsStrictOp || (RoundToStep && IsStepConst))) {
7836     NoNeedToConvert = true;
7837     if (RoundToStep) {
7838       unsigned BW = LRes.getBitWidth() > SRes.getBitWidth()
7839                         ? LRes.getBitWidth()
7840                         : SRes.getBitWidth();
7841       LRes = LRes.extend(BW + 1);
7842       LRes.setIsSigned(true);
7843       SRes = SRes.extend(BW + 1);
7844       SRes.setIsSigned(true);
7845       LRes -= SRes;
7846       NoNeedToConvert = LRes.trunc(BW).extend(BW + 1) == LRes;
7847       LRes = LRes.trunc(BW);
7848     }
7849     if (TestIsStrictOp) {
7850       unsigned BW = LRes.getBitWidth();
7851       LRes = LRes.extend(BW + 1);
7852       LRes.setIsSigned(true);
7853       ++LRes;
7854       NoNeedToConvert =
7855           NoNeedToConvert && LRes.trunc(BW).extend(BW + 1) == LRes;
7856       // truncate to the original bitwidth.
7857       LRes = LRes.trunc(BW);
7858     }
7859     NeedToReorganize = NoNeedToConvert;
7860   }
7861   llvm::APSInt URes;
7862   bool IsUpperConst = false;
7863   if (Optional<llvm::APSInt> Res = Upper->getIntegerConstantExpr(SemaRef.Context)) {
7864     URes = *Res;
7865     IsUpperConst = true;
7866   }
7867   if (NoNeedToConvert && IsLowerConst && IsUpperConst &&
7868       (!RoundToStep || IsStepConst)) {
7869     unsigned BW = LRes.getBitWidth() > URes.getBitWidth() ? LRes.getBitWidth()
7870                                                           : URes.getBitWidth();
7871     LRes = LRes.extend(BW + 1);
7872     LRes.setIsSigned(true);
7873     URes = URes.extend(BW + 1);
7874     URes.setIsSigned(true);
7875     URes -= LRes;
7876     NoNeedToConvert = URes.trunc(BW).extend(BW + 1) == URes;
7877     NeedToReorganize = NoNeedToConvert;
7878   }
7879   // If the boundaries are not constant or (Lower - Step [+ 1]) is not constant
7880   // or less than zero (Upper - (Lower - Step [+ 1]) may overflow) - promote to
7881   // unsigned.
7882   if ((!NoNeedToConvert || (LRes.isNegative() && !IsUpperConst)) &&
7883       !LCTy->isDependentType() && LCTy->isIntegerType()) {
7884     QualType LowerTy = Lower->getType();
7885     QualType UpperTy = Upper->getType();
7886     uint64_t LowerSize = SemaRef.Context.getTypeSize(LowerTy);
7887     uint64_t UpperSize = SemaRef.Context.getTypeSize(UpperTy);
7888     if ((LowerSize <= UpperSize && UpperTy->hasSignedIntegerRepresentation()) ||
7889         (LowerSize > UpperSize && LowerTy->hasSignedIntegerRepresentation())) {
7890       QualType CastType = SemaRef.Context.getIntTypeForBitwidth(
7891           LowerSize > UpperSize ? LowerSize : UpperSize, /*Signed=*/0);
7892       Upper =
7893           SemaRef
7894               .PerformImplicitConversion(
7895                   SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Upper).get(),
7896                   CastType, Sema::AA_Converting)
7897               .get();
7898       Lower = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Lower).get();
7899       NewStep = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, NewStep.get());
7900     }
7901   }
7902   if (!Lower || !Upper || NewStep.isInvalid())
7903     return nullptr;
7904 
7905   ExprResult Diff;
7906   // If need to reorganize, then calculate the form as Upper - (Lower - Step [+
7907   // 1]).
7908   if (NeedToReorganize) {
7909     Diff = Lower;
7910 
7911     if (RoundToStep) {
7912       // Lower - Step
7913       Diff =
7914           SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Diff.get(), NewStep.get());
7915       if (!Diff.isUsable())
7916         return nullptr;
7917     }
7918 
7919     // Lower - Step [+ 1]
7920     if (TestIsStrictOp)
7921       Diff = SemaRef.BuildBinOp(
7922           S, DefaultLoc, BO_Add, Diff.get(),
7923           SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
7924     if (!Diff.isUsable())
7925       return nullptr;
7926 
7927     Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
7928     if (!Diff.isUsable())
7929       return nullptr;
7930 
7931     // Upper - (Lower - Step [+ 1]).
7932     Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Diff.get());
7933     if (!Diff.isUsable())
7934       return nullptr;
7935   } else {
7936     Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
7937 
7938     if (!Diff.isUsable() && LCTy->getAsCXXRecordDecl()) {
7939       // BuildBinOp already emitted error, this one is to point user to upper
7940       // and lower bound, and to tell what is passed to 'operator-'.
7941       SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
7942           << Upper->getSourceRange() << Lower->getSourceRange();
7943       return nullptr;
7944     }
7945 
7946     if (!Diff.isUsable())
7947       return nullptr;
7948 
7949     // Upper - Lower [- 1]
7950     if (TestIsStrictOp)
7951       Diff = SemaRef.BuildBinOp(
7952           S, DefaultLoc, BO_Sub, Diff.get(),
7953           SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
7954     if (!Diff.isUsable())
7955       return nullptr;
7956 
7957     if (RoundToStep) {
7958       // Upper - Lower [- 1] + Step
7959       Diff =
7960           SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
7961       if (!Diff.isUsable())
7962         return nullptr;
7963     }
7964   }
7965 
7966   // Parentheses (for dumping/debugging purposes only).
7967   Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
7968   if (!Diff.isUsable())
7969     return nullptr;
7970 
7971   // (Upper - Lower [- 1] + Step) / Step or (Upper - Lower) / Step
7972   Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
7973   if (!Diff.isUsable())
7974     return nullptr;
7975 
7976   return Diff.get();
7977 }
7978 
7979 /// Build the expression to calculate the number of iterations.
7980 Expr *OpenMPIterationSpaceChecker::buildNumIterations(
7981     Scope *S, ArrayRef<LoopIterationSpace> ResultIterSpaces, bool LimitedType,
7982     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
7983   QualType VarType = LCDecl->getType().getNonReferenceType();
7984   if (!VarType->isIntegerType() && !VarType->isPointerType() &&
7985       !SemaRef.getLangOpts().CPlusPlus)
7986     return nullptr;
7987   Expr *LBVal = LB;
7988   Expr *UBVal = UB;
7989   // LB = TestIsLessOp.getValue() ? min(LB(MinVal), LB(MaxVal)) :
7990   // max(LB(MinVal), LB(MaxVal))
7991   if (InitDependOnLC) {
7992     const LoopIterationSpace &IS = ResultIterSpaces[*InitDependOnLC - 1];
7993     if (!IS.MinValue || !IS.MaxValue)
7994       return nullptr;
7995     // OuterVar = Min
7996     ExprResult MinValue =
7997         SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MinValue);
7998     if (!MinValue.isUsable())
7999       return nullptr;
8000 
8001     ExprResult LBMinVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
8002                                              IS.CounterVar, MinValue.get());
8003     if (!LBMinVal.isUsable())
8004       return nullptr;
8005     // OuterVar = Min, LBVal
8006     LBMinVal =
8007         SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, LBMinVal.get(), LBVal);
8008     if (!LBMinVal.isUsable())
8009       return nullptr;
8010     // (OuterVar = Min, LBVal)
8011     LBMinVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, LBMinVal.get());
8012     if (!LBMinVal.isUsable())
8013       return nullptr;
8014 
8015     // OuterVar = Max
8016     ExprResult MaxValue =
8017         SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MaxValue);
8018     if (!MaxValue.isUsable())
8019       return nullptr;
8020 
8021     ExprResult LBMaxVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
8022                                              IS.CounterVar, MaxValue.get());
8023     if (!LBMaxVal.isUsable())
8024       return nullptr;
8025     // OuterVar = Max, LBVal
8026     LBMaxVal =
8027         SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, LBMaxVal.get(), LBVal);
8028     if (!LBMaxVal.isUsable())
8029       return nullptr;
8030     // (OuterVar = Max, LBVal)
8031     LBMaxVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, LBMaxVal.get());
8032     if (!LBMaxVal.isUsable())
8033       return nullptr;
8034 
8035     Expr *LBMin = tryBuildCapture(SemaRef, LBMinVal.get(), Captures).get();
8036     Expr *LBMax = tryBuildCapture(SemaRef, LBMaxVal.get(), Captures).get();
8037     if (!LBMin || !LBMax)
8038       return nullptr;
8039     // LB(MinVal) < LB(MaxVal)
8040     ExprResult MinLessMaxRes =
8041         SemaRef.BuildBinOp(S, DefaultLoc, BO_LT, LBMin, LBMax);
8042     if (!MinLessMaxRes.isUsable())
8043       return nullptr;
8044     Expr *MinLessMax =
8045         tryBuildCapture(SemaRef, MinLessMaxRes.get(), Captures).get();
8046     if (!MinLessMax)
8047       return nullptr;
8048     if (TestIsLessOp.getValue()) {
8049       // LB(MinVal) < LB(MaxVal) ? LB(MinVal) : LB(MaxVal) - min(LB(MinVal),
8050       // LB(MaxVal))
8051       ExprResult MinLB = SemaRef.ActOnConditionalOp(DefaultLoc, DefaultLoc,
8052                                                     MinLessMax, LBMin, LBMax);
8053       if (!MinLB.isUsable())
8054         return nullptr;
8055       LBVal = MinLB.get();
8056     } else {
8057       // LB(MinVal) < LB(MaxVal) ? LB(MaxVal) : LB(MinVal) - max(LB(MinVal),
8058       // LB(MaxVal))
8059       ExprResult MaxLB = SemaRef.ActOnConditionalOp(DefaultLoc, DefaultLoc,
8060                                                     MinLessMax, LBMax, LBMin);
8061       if (!MaxLB.isUsable())
8062         return nullptr;
8063       LBVal = MaxLB.get();
8064     }
8065   }
8066   // UB = TestIsLessOp.getValue() ? max(UB(MinVal), UB(MaxVal)) :
8067   // min(UB(MinVal), UB(MaxVal))
8068   if (CondDependOnLC) {
8069     const LoopIterationSpace &IS = ResultIterSpaces[*CondDependOnLC - 1];
8070     if (!IS.MinValue || !IS.MaxValue)
8071       return nullptr;
8072     // OuterVar = Min
8073     ExprResult MinValue =
8074         SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MinValue);
8075     if (!MinValue.isUsable())
8076       return nullptr;
8077 
8078     ExprResult UBMinVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
8079                                              IS.CounterVar, MinValue.get());
8080     if (!UBMinVal.isUsable())
8081       return nullptr;
8082     // OuterVar = Min, UBVal
8083     UBMinVal =
8084         SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, UBMinVal.get(), UBVal);
8085     if (!UBMinVal.isUsable())
8086       return nullptr;
8087     // (OuterVar = Min, UBVal)
8088     UBMinVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, UBMinVal.get());
8089     if (!UBMinVal.isUsable())
8090       return nullptr;
8091 
8092     // OuterVar = Max
8093     ExprResult MaxValue =
8094         SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MaxValue);
8095     if (!MaxValue.isUsable())
8096       return nullptr;
8097 
8098     ExprResult UBMaxVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
8099                                              IS.CounterVar, MaxValue.get());
8100     if (!UBMaxVal.isUsable())
8101       return nullptr;
8102     // OuterVar = Max, UBVal
8103     UBMaxVal =
8104         SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, UBMaxVal.get(), UBVal);
8105     if (!UBMaxVal.isUsable())
8106       return nullptr;
8107     // (OuterVar = Max, UBVal)
8108     UBMaxVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, UBMaxVal.get());
8109     if (!UBMaxVal.isUsable())
8110       return nullptr;
8111 
8112     Expr *UBMin = tryBuildCapture(SemaRef, UBMinVal.get(), Captures).get();
8113     Expr *UBMax = tryBuildCapture(SemaRef, UBMaxVal.get(), Captures).get();
8114     if (!UBMin || !UBMax)
8115       return nullptr;
8116     // UB(MinVal) > UB(MaxVal)
8117     ExprResult MinGreaterMaxRes =
8118         SemaRef.BuildBinOp(S, DefaultLoc, BO_GT, UBMin, UBMax);
8119     if (!MinGreaterMaxRes.isUsable())
8120       return nullptr;
8121     Expr *MinGreaterMax =
8122         tryBuildCapture(SemaRef, MinGreaterMaxRes.get(), Captures).get();
8123     if (!MinGreaterMax)
8124       return nullptr;
8125     if (TestIsLessOp.getValue()) {
8126       // UB(MinVal) > UB(MaxVal) ? UB(MinVal) : UB(MaxVal) - max(UB(MinVal),
8127       // UB(MaxVal))
8128       ExprResult MaxUB = SemaRef.ActOnConditionalOp(
8129           DefaultLoc, DefaultLoc, MinGreaterMax, UBMin, UBMax);
8130       if (!MaxUB.isUsable())
8131         return nullptr;
8132       UBVal = MaxUB.get();
8133     } else {
8134       // UB(MinVal) > UB(MaxVal) ? UB(MaxVal) : UB(MinVal) - min(UB(MinVal),
8135       // UB(MaxVal))
8136       ExprResult MinUB = SemaRef.ActOnConditionalOp(
8137           DefaultLoc, DefaultLoc, MinGreaterMax, UBMax, UBMin);
8138       if (!MinUB.isUsable())
8139         return nullptr;
8140       UBVal = MinUB.get();
8141     }
8142   }
8143   Expr *UBExpr = TestIsLessOp.getValue() ? UBVal : LBVal;
8144   Expr *LBExpr = TestIsLessOp.getValue() ? LBVal : UBVal;
8145   Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
8146   Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
8147   if (!Upper || !Lower)
8148     return nullptr;
8149 
8150   ExprResult Diff = calculateNumIters(SemaRef, S, DefaultLoc, Lower, Upper,
8151                                       Step, VarType, TestIsStrictOp,
8152                                       /*RoundToStep=*/true, Captures);
8153   if (!Diff.isUsable())
8154     return nullptr;
8155 
8156   // OpenMP runtime requires 32-bit or 64-bit loop variables.
8157   QualType Type = Diff.get()->getType();
8158   ASTContext &C = SemaRef.Context;
8159   bool UseVarType = VarType->hasIntegerRepresentation() &&
8160                     C.getTypeSize(Type) > C.getTypeSize(VarType);
8161   if (!Type->isIntegerType() || UseVarType) {
8162     unsigned NewSize =
8163         UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
8164     bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
8165                                : Type->hasSignedIntegerRepresentation();
8166     Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
8167     if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
8168       Diff = SemaRef.PerformImplicitConversion(
8169           Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
8170       if (!Diff.isUsable())
8171         return nullptr;
8172     }
8173   }
8174   if (LimitedType) {
8175     unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
8176     if (NewSize != C.getTypeSize(Type)) {
8177       if (NewSize < C.getTypeSize(Type)) {
8178         assert(NewSize == 64 && "incorrect loop var size");
8179         SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
8180             << InitSrcRange << ConditionSrcRange;
8181       }
8182       QualType NewType = C.getIntTypeForBitwidth(
8183           NewSize, Type->hasSignedIntegerRepresentation() ||
8184                        C.getTypeSize(Type) < NewSize);
8185       if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
8186         Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
8187                                                  Sema::AA_Converting, true);
8188         if (!Diff.isUsable())
8189           return nullptr;
8190       }
8191     }
8192   }
8193 
8194   return Diff.get();
8195 }
8196 
8197 std::pair<Expr *, Expr *> OpenMPIterationSpaceChecker::buildMinMaxValues(
8198     Scope *S, llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
8199   // Do not build for iterators, they cannot be used in non-rectangular loop
8200   // nests.
8201   if (LCDecl->getType()->isRecordType())
8202     return std::make_pair(nullptr, nullptr);
8203   // If we subtract, the min is in the condition, otherwise the min is in the
8204   // init value.
8205   Expr *MinExpr = nullptr;
8206   Expr *MaxExpr = nullptr;
8207   Expr *LBExpr = TestIsLessOp.getValue() ? LB : UB;
8208   Expr *UBExpr = TestIsLessOp.getValue() ? UB : LB;
8209   bool LBNonRect = TestIsLessOp.getValue() ? InitDependOnLC.hasValue()
8210                                            : CondDependOnLC.hasValue();
8211   bool UBNonRect = TestIsLessOp.getValue() ? CondDependOnLC.hasValue()
8212                                            : InitDependOnLC.hasValue();
8213   Expr *Lower =
8214       LBNonRect ? LBExpr : tryBuildCapture(SemaRef, LBExpr, Captures).get();
8215   Expr *Upper =
8216       UBNonRect ? UBExpr : tryBuildCapture(SemaRef, UBExpr, Captures).get();
8217   if (!Upper || !Lower)
8218     return std::make_pair(nullptr, nullptr);
8219 
8220   if (TestIsLessOp.getValue())
8221     MinExpr = Lower;
8222   else
8223     MaxExpr = Upper;
8224 
8225   // Build minimum/maximum value based on number of iterations.
8226   QualType VarType = LCDecl->getType().getNonReferenceType();
8227 
8228   ExprResult Diff = calculateNumIters(SemaRef, S, DefaultLoc, Lower, Upper,
8229                                       Step, VarType, TestIsStrictOp,
8230                                       /*RoundToStep=*/false, Captures);
8231   if (!Diff.isUsable())
8232     return std::make_pair(nullptr, nullptr);
8233 
8234   // ((Upper - Lower [- 1]) / Step) * Step
8235   // Parentheses (for dumping/debugging purposes only).
8236   Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
8237   if (!Diff.isUsable())
8238     return std::make_pair(nullptr, nullptr);
8239 
8240   ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
8241   if (!NewStep.isUsable())
8242     return std::make_pair(nullptr, nullptr);
8243   Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Mul, Diff.get(), NewStep.get());
8244   if (!Diff.isUsable())
8245     return std::make_pair(nullptr, nullptr);
8246 
8247   // Parentheses (for dumping/debugging purposes only).
8248   Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
8249   if (!Diff.isUsable())
8250     return std::make_pair(nullptr, nullptr);
8251 
8252   // Convert to the ptrdiff_t, if original type is pointer.
8253   if (VarType->isAnyPointerType() &&
8254       !SemaRef.Context.hasSameType(
8255           Diff.get()->getType(),
8256           SemaRef.Context.getUnsignedPointerDiffType())) {
8257     Diff = SemaRef.PerformImplicitConversion(
8258         Diff.get(), SemaRef.Context.getUnsignedPointerDiffType(),
8259         Sema::AA_Converting, /*AllowExplicit=*/true);
8260   }
8261   if (!Diff.isUsable())
8262     return std::make_pair(nullptr, nullptr);
8263 
8264   if (TestIsLessOp.getValue()) {
8265     // MinExpr = Lower;
8266     // MaxExpr = Lower + (((Upper - Lower [- 1]) / Step) * Step)
8267     Diff = SemaRef.BuildBinOp(
8268         S, DefaultLoc, BO_Add,
8269         SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Lower).get(),
8270         Diff.get());
8271     if (!Diff.isUsable())
8272       return std::make_pair(nullptr, nullptr);
8273   } else {
8274     // MaxExpr = Upper;
8275     // MinExpr = Upper - (((Upper - Lower [- 1]) / Step) * Step)
8276     Diff = SemaRef.BuildBinOp(
8277         S, DefaultLoc, BO_Sub,
8278         SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Upper).get(),
8279         Diff.get());
8280     if (!Diff.isUsable())
8281       return std::make_pair(nullptr, nullptr);
8282   }
8283 
8284   // Convert to the original type.
8285   if (SemaRef.Context.hasSameType(Diff.get()->getType(), VarType))
8286     Diff = SemaRef.PerformImplicitConversion(Diff.get(), VarType,
8287                                              Sema::AA_Converting,
8288                                              /*AllowExplicit=*/true);
8289   if (!Diff.isUsable())
8290     return std::make_pair(nullptr, nullptr);
8291 
8292   Sema::TentativeAnalysisScope Trap(SemaRef);
8293   Diff = SemaRef.ActOnFinishFullExpr(Diff.get(), /*DiscardedValue=*/false);
8294   if (!Diff.isUsable())
8295     return std::make_pair(nullptr, nullptr);
8296 
8297   if (TestIsLessOp.getValue())
8298     MaxExpr = Diff.get();
8299   else
8300     MinExpr = Diff.get();
8301 
8302   return std::make_pair(MinExpr, MaxExpr);
8303 }
8304 
8305 Expr *OpenMPIterationSpaceChecker::buildFinalCondition(Scope *S) const {
8306   if (InitDependOnLC || CondDependOnLC)
8307     return Condition;
8308   return nullptr;
8309 }
8310 
8311 Expr *OpenMPIterationSpaceChecker::buildPreCond(
8312     Scope *S, Expr *Cond,
8313     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
8314   // Do not build a precondition when the condition/initialization is dependent
8315   // to prevent pessimistic early loop exit.
8316   // TODO: this can be improved by calculating min/max values but not sure that
8317   // it will be very effective.
8318   if (CondDependOnLC || InitDependOnLC)
8319     return SemaRef.PerformImplicitConversion(
8320         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get(),
8321         SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
8322         /*AllowExplicit=*/true).get();
8323 
8324   // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
8325   Sema::TentativeAnalysisScope Trap(SemaRef);
8326 
8327   ExprResult NewLB = tryBuildCapture(SemaRef, LB, Captures);
8328   ExprResult NewUB = tryBuildCapture(SemaRef, UB, Captures);
8329   if (!NewLB.isUsable() || !NewUB.isUsable())
8330     return nullptr;
8331 
8332   ExprResult CondExpr =
8333       SemaRef.BuildBinOp(S, DefaultLoc,
8334                          TestIsLessOp.getValue() ?
8335                            (TestIsStrictOp ? BO_LT : BO_LE) :
8336                            (TestIsStrictOp ? BO_GT : BO_GE),
8337                          NewLB.get(), NewUB.get());
8338   if (CondExpr.isUsable()) {
8339     if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
8340                                                 SemaRef.Context.BoolTy))
8341       CondExpr = SemaRef.PerformImplicitConversion(
8342           CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
8343           /*AllowExplicit=*/true);
8344   }
8345 
8346   // Otherwise use original loop condition and evaluate it in runtime.
8347   return CondExpr.isUsable() ? CondExpr.get() : Cond;
8348 }
8349 
8350 /// Build reference expression to the counter be used for codegen.
8351 DeclRefExpr *OpenMPIterationSpaceChecker::buildCounterVar(
8352     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
8353     DSAStackTy &DSA) const {
8354   auto *VD = dyn_cast<VarDecl>(LCDecl);
8355   if (!VD) {
8356     VD = SemaRef.isOpenMPCapturedDecl(LCDecl);
8357     DeclRefExpr *Ref = buildDeclRefExpr(
8358         SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
8359     const DSAStackTy::DSAVarData Data =
8360         DSA.getTopDSA(LCDecl, /*FromParent=*/false);
8361     // If the loop control decl is explicitly marked as private, do not mark it
8362     // as captured again.
8363     if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
8364       Captures.insert(std::make_pair(LCRef, Ref));
8365     return Ref;
8366   }
8367   return cast<DeclRefExpr>(LCRef);
8368 }
8369 
8370 Expr *OpenMPIterationSpaceChecker::buildPrivateCounterVar() const {
8371   if (LCDecl && !LCDecl->isInvalidDecl()) {
8372     QualType Type = LCDecl->getType().getNonReferenceType();
8373     VarDecl *PrivateVar = buildVarDecl(
8374         SemaRef, DefaultLoc, Type, LCDecl->getName(),
8375         LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr,
8376         isa<VarDecl>(LCDecl)
8377             ? buildDeclRefExpr(SemaRef, cast<VarDecl>(LCDecl), Type, DefaultLoc)
8378             : nullptr);
8379     if (PrivateVar->isInvalidDecl())
8380       return nullptr;
8381     return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
8382   }
8383   return nullptr;
8384 }
8385 
8386 /// Build initialization of the counter to be used for codegen.
8387 Expr *OpenMPIterationSpaceChecker::buildCounterInit() const { return LB; }
8388 
8389 /// Build step of the counter be used for codegen.
8390 Expr *OpenMPIterationSpaceChecker::buildCounterStep() const { return Step; }
8391 
8392 Expr *OpenMPIterationSpaceChecker::buildOrderedLoopData(
8393     Scope *S, Expr *Counter,
8394     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, SourceLocation Loc,
8395     Expr *Inc, OverloadedOperatorKind OOK) {
8396   Expr *Cnt = SemaRef.DefaultLvalueConversion(Counter).get();
8397   if (!Cnt)
8398     return nullptr;
8399   if (Inc) {
8400     assert((OOK == OO_Plus || OOK == OO_Minus) &&
8401            "Expected only + or - operations for depend clauses.");
8402     BinaryOperatorKind BOK = (OOK == OO_Plus) ? BO_Add : BO_Sub;
8403     Cnt = SemaRef.BuildBinOp(S, Loc, BOK, Cnt, Inc).get();
8404     if (!Cnt)
8405       return nullptr;
8406   }
8407   QualType VarType = LCDecl->getType().getNonReferenceType();
8408   if (!VarType->isIntegerType() && !VarType->isPointerType() &&
8409       !SemaRef.getLangOpts().CPlusPlus)
8410     return nullptr;
8411   // Upper - Lower
8412   Expr *Upper = TestIsLessOp.getValue()
8413                     ? Cnt
8414                     : tryBuildCapture(SemaRef, LB, Captures).get();
8415   Expr *Lower = TestIsLessOp.getValue()
8416                     ? tryBuildCapture(SemaRef, LB, Captures).get()
8417                     : Cnt;
8418   if (!Upper || !Lower)
8419     return nullptr;
8420 
8421   ExprResult Diff = calculateNumIters(
8422       SemaRef, S, DefaultLoc, Lower, Upper, Step, VarType,
8423       /*TestIsStrictOp=*/false, /*RoundToStep=*/false, Captures);
8424   if (!Diff.isUsable())
8425     return nullptr;
8426 
8427   return Diff.get();
8428 }
8429 } // namespace
8430 
8431 void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
8432   assert(getLangOpts().OpenMP && "OpenMP is not active.");
8433   assert(Init && "Expected loop in canonical form.");
8434   unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
8435   if (AssociatedLoops > 0 &&
8436       isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
8437     DSAStack->loopStart();
8438     OpenMPIterationSpaceChecker ISC(*this, /*SupportsNonRectangular=*/true,
8439                                     *DSAStack, ForLoc);
8440     if (!ISC.checkAndSetInit(Init, /*EmitDiags=*/false)) {
8441       if (ValueDecl *D = ISC.getLoopDecl()) {
8442         auto *VD = dyn_cast<VarDecl>(D);
8443         DeclRefExpr *PrivateRef = nullptr;
8444         if (!VD) {
8445           if (VarDecl *Private = isOpenMPCapturedDecl(D)) {
8446             VD = Private;
8447           } else {
8448             PrivateRef = buildCapture(*this, D, ISC.getLoopDeclRefExpr(),
8449                                       /*WithInit=*/false);
8450             VD = cast<VarDecl>(PrivateRef->getDecl());
8451           }
8452         }
8453         DSAStack->addLoopControlVariable(D, VD);
8454         const Decl *LD = DSAStack->getPossiblyLoopCunter();
8455         if (LD != D->getCanonicalDecl()) {
8456           DSAStack->resetPossibleLoopCounter();
8457           if (auto *Var = dyn_cast_or_null<VarDecl>(LD))
8458             MarkDeclarationsReferencedInExpr(
8459                 buildDeclRefExpr(*this, const_cast<VarDecl *>(Var),
8460                                  Var->getType().getNonLValueExprType(Context),
8461                                  ForLoc, /*RefersToCapture=*/true));
8462         }
8463         OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
8464         // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables
8465         // Referenced in a Construct, C/C++]. The loop iteration variable in the
8466         // associated for-loop of a simd construct with just one associated
8467         // for-loop may be listed in a linear clause with a constant-linear-step
8468         // that is the increment of the associated for-loop. The loop iteration
8469         // variable(s) in the associated for-loop(s) of a for or parallel for
8470         // construct may be listed in a private or lastprivate clause.
8471         DSAStackTy::DSAVarData DVar =
8472             DSAStack->getTopDSA(D, /*FromParent=*/false);
8473         // If LoopVarRefExpr is nullptr it means the corresponding loop variable
8474         // is declared in the loop and it is predetermined as a private.
8475         Expr *LoopDeclRefExpr = ISC.getLoopDeclRefExpr();
8476         OpenMPClauseKind PredeterminedCKind =
8477             isOpenMPSimdDirective(DKind)
8478                 ? (DSAStack->hasMutipleLoops() ? OMPC_lastprivate : OMPC_linear)
8479                 : OMPC_private;
8480         if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
8481               DVar.CKind != PredeterminedCKind && DVar.RefExpr &&
8482               (LangOpts.OpenMP <= 45 || (DVar.CKind != OMPC_lastprivate &&
8483                                          DVar.CKind != OMPC_private))) ||
8484              ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
8485                DKind == OMPD_master_taskloop ||
8486                DKind == OMPD_parallel_master_taskloop ||
8487                isOpenMPDistributeDirective(DKind)) &&
8488               !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
8489               DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
8490             (DVar.CKind != OMPC_private || DVar.RefExpr)) {
8491           Diag(Init->getBeginLoc(), diag::err_omp_loop_var_dsa)
8492               << getOpenMPClauseName(DVar.CKind)
8493               << getOpenMPDirectiveName(DKind)
8494               << getOpenMPClauseName(PredeterminedCKind);
8495           if (DVar.RefExpr == nullptr)
8496             DVar.CKind = PredeterminedCKind;
8497           reportOriginalDsa(*this, DSAStack, D, DVar,
8498                             /*IsLoopIterVar=*/true);
8499         } else if (LoopDeclRefExpr) {
8500           // Make the loop iteration variable private (for worksharing
8501           // constructs), linear (for simd directives with the only one
8502           // associated loop) or lastprivate (for simd directives with several
8503           // collapsed or ordered loops).
8504           if (DVar.CKind == OMPC_unknown)
8505             DSAStack->addDSA(D, LoopDeclRefExpr, PredeterminedCKind,
8506                              PrivateRef);
8507         }
8508       }
8509     }
8510     DSAStack->setAssociatedLoops(AssociatedLoops - 1);
8511   }
8512 }
8513 
8514 /// Called on a for stmt to check and extract its iteration space
8515 /// for further processing (such as collapsing).
8516 static bool checkOpenMPIterationSpace(
8517     OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
8518     unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
8519     unsigned TotalNestedLoopCount, Expr *CollapseLoopCountExpr,
8520     Expr *OrderedLoopCountExpr,
8521     Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
8522     llvm::MutableArrayRef<LoopIterationSpace> ResultIterSpaces,
8523     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
8524   bool SupportsNonRectangular = !isOpenMPLoopTransformationDirective(DKind);
8525   // OpenMP [2.9.1, Canonical Loop Form]
8526   //   for (init-expr; test-expr; incr-expr) structured-block
8527   //   for (range-decl: range-expr) structured-block
8528   if (auto *CanonLoop = dyn_cast_or_null<OMPCanonicalLoop>(S))
8529     S = CanonLoop->getLoopStmt();
8530   auto *For = dyn_cast_or_null<ForStmt>(S);
8531   auto *CXXFor = dyn_cast_or_null<CXXForRangeStmt>(S);
8532   // Ranged for is supported only in OpenMP 5.0.
8533   if (!For && (SemaRef.LangOpts.OpenMP <= 45 || !CXXFor)) {
8534     SemaRef.Diag(S->getBeginLoc(), diag::err_omp_not_for)
8535         << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
8536         << getOpenMPDirectiveName(DKind) << TotalNestedLoopCount
8537         << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
8538     if (TotalNestedLoopCount > 1) {
8539       if (CollapseLoopCountExpr && OrderedLoopCountExpr)
8540         SemaRef.Diag(DSA.getConstructLoc(),
8541                      diag::note_omp_collapse_ordered_expr)
8542             << 2 << CollapseLoopCountExpr->getSourceRange()
8543             << OrderedLoopCountExpr->getSourceRange();
8544       else if (CollapseLoopCountExpr)
8545         SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
8546                      diag::note_omp_collapse_ordered_expr)
8547             << 0 << CollapseLoopCountExpr->getSourceRange();
8548       else
8549         SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
8550                      diag::note_omp_collapse_ordered_expr)
8551             << 1 << OrderedLoopCountExpr->getSourceRange();
8552     }
8553     return true;
8554   }
8555   assert(((For && For->getBody()) || (CXXFor && CXXFor->getBody())) &&
8556          "No loop body.");
8557 
8558   OpenMPIterationSpaceChecker ISC(SemaRef, SupportsNonRectangular, DSA,
8559                                   For ? For->getForLoc() : CXXFor->getForLoc());
8560 
8561   // Check init.
8562   Stmt *Init = For ? For->getInit() : CXXFor->getBeginStmt();
8563   if (ISC.checkAndSetInit(Init))
8564     return true;
8565 
8566   bool HasErrors = false;
8567 
8568   // Check loop variable's type.
8569   if (ValueDecl *LCDecl = ISC.getLoopDecl()) {
8570     // OpenMP [2.6, Canonical Loop Form]
8571     // Var is one of the following:
8572     //   A variable of signed or unsigned integer type.
8573     //   For C++, a variable of a random access iterator type.
8574     //   For C, a variable of a pointer type.
8575     QualType VarType = LCDecl->getType().getNonReferenceType();
8576     if (!VarType->isDependentType() && !VarType->isIntegerType() &&
8577         !VarType->isPointerType() &&
8578         !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
8579       SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_variable_type)
8580           << SemaRef.getLangOpts().CPlusPlus;
8581       HasErrors = true;
8582     }
8583 
8584     // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
8585     // a Construct
8586     // The loop iteration variable(s) in the associated for-loop(s) of a for or
8587     // parallel for construct is (are) private.
8588     // The loop iteration variable in the associated for-loop of a simd
8589     // construct with just one associated for-loop is linear with a
8590     // constant-linear-step that is the increment of the associated for-loop.
8591     // Exclude loop var from the list of variables with implicitly defined data
8592     // sharing attributes.
8593     VarsWithImplicitDSA.erase(LCDecl);
8594 
8595     assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
8596 
8597     // Check test-expr.
8598     HasErrors |= ISC.checkAndSetCond(For ? For->getCond() : CXXFor->getCond());
8599 
8600     // Check incr-expr.
8601     HasErrors |= ISC.checkAndSetInc(For ? For->getInc() : CXXFor->getInc());
8602   }
8603 
8604   if (ISC.dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
8605     return HasErrors;
8606 
8607   // Build the loop's iteration space representation.
8608   ResultIterSpaces[CurrentNestedLoopCount].PreCond = ISC.buildPreCond(
8609       DSA.getCurScope(), For ? For->getCond() : CXXFor->getCond(), Captures);
8610   ResultIterSpaces[CurrentNestedLoopCount].NumIterations =
8611       ISC.buildNumIterations(DSA.getCurScope(), ResultIterSpaces,
8612                              (isOpenMPWorksharingDirective(DKind) ||
8613                               isOpenMPTaskLoopDirective(DKind) ||
8614                               isOpenMPDistributeDirective(DKind) ||
8615                               isOpenMPLoopTransformationDirective(DKind)),
8616                              Captures);
8617   ResultIterSpaces[CurrentNestedLoopCount].CounterVar =
8618       ISC.buildCounterVar(Captures, DSA);
8619   ResultIterSpaces[CurrentNestedLoopCount].PrivateCounterVar =
8620       ISC.buildPrivateCounterVar();
8621   ResultIterSpaces[CurrentNestedLoopCount].CounterInit = ISC.buildCounterInit();
8622   ResultIterSpaces[CurrentNestedLoopCount].CounterStep = ISC.buildCounterStep();
8623   ResultIterSpaces[CurrentNestedLoopCount].InitSrcRange = ISC.getInitSrcRange();
8624   ResultIterSpaces[CurrentNestedLoopCount].CondSrcRange =
8625       ISC.getConditionSrcRange();
8626   ResultIterSpaces[CurrentNestedLoopCount].IncSrcRange =
8627       ISC.getIncrementSrcRange();
8628   ResultIterSpaces[CurrentNestedLoopCount].Subtract = ISC.shouldSubtractStep();
8629   ResultIterSpaces[CurrentNestedLoopCount].IsStrictCompare =
8630       ISC.isStrictTestOp();
8631   std::tie(ResultIterSpaces[CurrentNestedLoopCount].MinValue,
8632            ResultIterSpaces[CurrentNestedLoopCount].MaxValue) =
8633       ISC.buildMinMaxValues(DSA.getCurScope(), Captures);
8634   ResultIterSpaces[CurrentNestedLoopCount].FinalCondition =
8635       ISC.buildFinalCondition(DSA.getCurScope());
8636   ResultIterSpaces[CurrentNestedLoopCount].IsNonRectangularLB =
8637       ISC.doesInitDependOnLC();
8638   ResultIterSpaces[CurrentNestedLoopCount].IsNonRectangularUB =
8639       ISC.doesCondDependOnLC();
8640   ResultIterSpaces[CurrentNestedLoopCount].LoopDependentIdx =
8641       ISC.getLoopDependentIdx();
8642 
8643   HasErrors |=
8644       (ResultIterSpaces[CurrentNestedLoopCount].PreCond == nullptr ||
8645        ResultIterSpaces[CurrentNestedLoopCount].NumIterations == nullptr ||
8646        ResultIterSpaces[CurrentNestedLoopCount].CounterVar == nullptr ||
8647        ResultIterSpaces[CurrentNestedLoopCount].PrivateCounterVar == nullptr ||
8648        ResultIterSpaces[CurrentNestedLoopCount].CounterInit == nullptr ||
8649        ResultIterSpaces[CurrentNestedLoopCount].CounterStep == nullptr);
8650   if (!HasErrors && DSA.isOrderedRegion()) {
8651     if (DSA.getOrderedRegionParam().second->getNumForLoops()) {
8652       if (CurrentNestedLoopCount <
8653           DSA.getOrderedRegionParam().second->getLoopNumIterations().size()) {
8654         DSA.getOrderedRegionParam().second->setLoopNumIterations(
8655             CurrentNestedLoopCount,
8656             ResultIterSpaces[CurrentNestedLoopCount].NumIterations);
8657         DSA.getOrderedRegionParam().second->setLoopCounter(
8658             CurrentNestedLoopCount,
8659             ResultIterSpaces[CurrentNestedLoopCount].CounterVar);
8660       }
8661     }
8662     for (auto &Pair : DSA.getDoacrossDependClauses()) {
8663       if (CurrentNestedLoopCount >= Pair.first->getNumLoops()) {
8664         // Erroneous case - clause has some problems.
8665         continue;
8666       }
8667       if (Pair.first->getDependencyKind() == OMPC_DEPEND_sink &&
8668           Pair.second.size() <= CurrentNestedLoopCount) {
8669         // Erroneous case - clause has some problems.
8670         Pair.first->setLoopData(CurrentNestedLoopCount, nullptr);
8671         continue;
8672       }
8673       Expr *CntValue;
8674       if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
8675         CntValue = ISC.buildOrderedLoopData(
8676             DSA.getCurScope(),
8677             ResultIterSpaces[CurrentNestedLoopCount].CounterVar, Captures,
8678             Pair.first->getDependencyLoc());
8679       else
8680         CntValue = ISC.buildOrderedLoopData(
8681             DSA.getCurScope(),
8682             ResultIterSpaces[CurrentNestedLoopCount].CounterVar, Captures,
8683             Pair.first->getDependencyLoc(),
8684             Pair.second[CurrentNestedLoopCount].first,
8685             Pair.second[CurrentNestedLoopCount].second);
8686       Pair.first->setLoopData(CurrentNestedLoopCount, CntValue);
8687     }
8688   }
8689 
8690   return HasErrors;
8691 }
8692 
8693 /// Build 'VarRef = Start.
8694 static ExprResult
8695 buildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
8696                  ExprResult Start, bool IsNonRectangularLB,
8697                  llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
8698   // Build 'VarRef = Start.
8699   ExprResult NewStart = IsNonRectangularLB
8700                             ? Start.get()
8701                             : tryBuildCapture(SemaRef, Start.get(), Captures);
8702   if (!NewStart.isUsable())
8703     return ExprError();
8704   if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
8705                                    VarRef.get()->getType())) {
8706     NewStart = SemaRef.PerformImplicitConversion(
8707         NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
8708         /*AllowExplicit=*/true);
8709     if (!NewStart.isUsable())
8710       return ExprError();
8711   }
8712 
8713   ExprResult Init =
8714       SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
8715   return Init;
8716 }
8717 
8718 /// Build 'VarRef = Start + Iter * Step'.
8719 static ExprResult buildCounterUpdate(
8720     Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
8721     ExprResult Start, ExprResult Iter, ExprResult Step, bool Subtract,
8722     bool IsNonRectangularLB,
8723     llvm::MapVector<const Expr *, DeclRefExpr *> *Captures = nullptr) {
8724   // Add parentheses (for debugging purposes only).
8725   Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
8726   if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
8727       !Step.isUsable())
8728     return ExprError();
8729 
8730   ExprResult NewStep = Step;
8731   if (Captures)
8732     NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
8733   if (NewStep.isInvalid())
8734     return ExprError();
8735   ExprResult Update =
8736       SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
8737   if (!Update.isUsable())
8738     return ExprError();
8739 
8740   // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
8741   // 'VarRef = Start (+|-) Iter * Step'.
8742   if (!Start.isUsable())
8743     return ExprError();
8744   ExprResult NewStart = SemaRef.ActOnParenExpr(Loc, Loc, Start.get());
8745   if (!NewStart.isUsable())
8746     return ExprError();
8747   if (Captures && !IsNonRectangularLB)
8748     NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
8749   if (NewStart.isInvalid())
8750     return ExprError();
8751 
8752   // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
8753   ExprResult SavedUpdate = Update;
8754   ExprResult UpdateVal;
8755   if (VarRef.get()->getType()->isOverloadableType() ||
8756       NewStart.get()->getType()->isOverloadableType() ||
8757       Update.get()->getType()->isOverloadableType()) {
8758     Sema::TentativeAnalysisScope Trap(SemaRef);
8759 
8760     Update =
8761         SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
8762     if (Update.isUsable()) {
8763       UpdateVal =
8764           SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
8765                              VarRef.get(), SavedUpdate.get());
8766       if (UpdateVal.isUsable()) {
8767         Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
8768                                             UpdateVal.get());
8769       }
8770     }
8771   }
8772 
8773   // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
8774   if (!Update.isUsable() || !UpdateVal.isUsable()) {
8775     Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
8776                                 NewStart.get(), SavedUpdate.get());
8777     if (!Update.isUsable())
8778       return ExprError();
8779 
8780     if (!SemaRef.Context.hasSameType(Update.get()->getType(),
8781                                      VarRef.get()->getType())) {
8782       Update = SemaRef.PerformImplicitConversion(
8783           Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
8784       if (!Update.isUsable())
8785         return ExprError();
8786     }
8787 
8788     Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
8789   }
8790   return Update;
8791 }
8792 
8793 /// Convert integer expression \a E to make it have at least \a Bits
8794 /// bits.
8795 static ExprResult widenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
8796   if (E == nullptr)
8797     return ExprError();
8798   ASTContext &C = SemaRef.Context;
8799   QualType OldType = E->getType();
8800   unsigned HasBits = C.getTypeSize(OldType);
8801   if (HasBits >= Bits)
8802     return ExprResult(E);
8803   // OK to convert to signed, because new type has more bits than old.
8804   QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
8805   return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
8806                                            true);
8807 }
8808 
8809 /// Check if the given expression \a E is a constant integer that fits
8810 /// into \a Bits bits.
8811 static bool fitsInto(unsigned Bits, bool Signed, const Expr *E, Sema &SemaRef) {
8812   if (E == nullptr)
8813     return false;
8814   if (Optional<llvm::APSInt> Result =
8815           E->getIntegerConstantExpr(SemaRef.Context))
8816     return Signed ? Result->isSignedIntN(Bits) : Result->isIntN(Bits);
8817   return false;
8818 }
8819 
8820 /// Build preinits statement for the given declarations.
8821 static Stmt *buildPreInits(ASTContext &Context,
8822                            MutableArrayRef<Decl *> PreInits) {
8823   if (!PreInits.empty()) {
8824     return new (Context) DeclStmt(
8825         DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
8826         SourceLocation(), SourceLocation());
8827   }
8828   return nullptr;
8829 }
8830 
8831 /// Build preinits statement for the given declarations.
8832 static Stmt *
8833 buildPreInits(ASTContext &Context,
8834               const llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
8835   if (!Captures.empty()) {
8836     SmallVector<Decl *, 16> PreInits;
8837     for (const auto &Pair : Captures)
8838       PreInits.push_back(Pair.second->getDecl());
8839     return buildPreInits(Context, PreInits);
8840   }
8841   return nullptr;
8842 }
8843 
8844 /// Build postupdate expression for the given list of postupdates expressions.
8845 static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
8846   Expr *PostUpdate = nullptr;
8847   if (!PostUpdates.empty()) {
8848     for (Expr *E : PostUpdates) {
8849       Expr *ConvE = S.BuildCStyleCastExpr(
8850                          E->getExprLoc(),
8851                          S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
8852                          E->getExprLoc(), E)
8853                         .get();
8854       PostUpdate = PostUpdate
8855                        ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
8856                                               PostUpdate, ConvE)
8857                              .get()
8858                        : ConvE;
8859     }
8860   }
8861   return PostUpdate;
8862 }
8863 
8864 /// Called on a for stmt to check itself and nested loops (if any).
8865 /// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
8866 /// number of collapsed loops otherwise.
8867 static unsigned
8868 checkOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
8869                 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
8870                 DSAStackTy &DSA,
8871                 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
8872                 OMPLoopBasedDirective::HelperExprs &Built) {
8873   unsigned NestedLoopCount = 1;
8874   bool SupportsNonPerfectlyNested = (SemaRef.LangOpts.OpenMP >= 50) &&
8875                                     !isOpenMPLoopTransformationDirective(DKind);
8876 
8877   if (CollapseLoopCountExpr) {
8878     // Found 'collapse' clause - calculate collapse number.
8879     Expr::EvalResult Result;
8880     if (!CollapseLoopCountExpr->isValueDependent() &&
8881         CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
8882       NestedLoopCount = Result.Val.getInt().getLimitedValue();
8883     } else {
8884       Built.clear(/*Size=*/1);
8885       return 1;
8886     }
8887   }
8888   unsigned OrderedLoopCount = 1;
8889   if (OrderedLoopCountExpr) {
8890     // Found 'ordered' clause - calculate collapse number.
8891     Expr::EvalResult EVResult;
8892     if (!OrderedLoopCountExpr->isValueDependent() &&
8893         OrderedLoopCountExpr->EvaluateAsInt(EVResult,
8894                                             SemaRef.getASTContext())) {
8895       llvm::APSInt Result = EVResult.Val.getInt();
8896       if (Result.getLimitedValue() < NestedLoopCount) {
8897         SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
8898                      diag::err_omp_wrong_ordered_loop_count)
8899             << OrderedLoopCountExpr->getSourceRange();
8900         SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
8901                      diag::note_collapse_loop_count)
8902             << CollapseLoopCountExpr->getSourceRange();
8903       }
8904       OrderedLoopCount = Result.getLimitedValue();
8905     } else {
8906       Built.clear(/*Size=*/1);
8907       return 1;
8908     }
8909   }
8910   // This is helper routine for loop directives (e.g., 'for', 'simd',
8911   // 'for simd', etc.).
8912   llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
8913   unsigned NumLoops = std::max(OrderedLoopCount, NestedLoopCount);
8914   SmallVector<LoopIterationSpace, 4> IterSpaces(NumLoops);
8915   if (!OMPLoopBasedDirective::doForAllLoops(
8916           AStmt->IgnoreContainers(!isOpenMPLoopTransformationDirective(DKind)),
8917           SupportsNonPerfectlyNested, NumLoops,
8918           [DKind, &SemaRef, &DSA, NumLoops, NestedLoopCount,
8919            CollapseLoopCountExpr, OrderedLoopCountExpr, &VarsWithImplicitDSA,
8920            &IterSpaces, &Captures](unsigned Cnt, Stmt *CurStmt) {
8921             if (checkOpenMPIterationSpace(
8922                     DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
8923                     NumLoops, CollapseLoopCountExpr, OrderedLoopCountExpr,
8924                     VarsWithImplicitDSA, IterSpaces, Captures))
8925               return true;
8926             if (Cnt > 0 && Cnt >= NestedLoopCount &&
8927                 IterSpaces[Cnt].CounterVar) {
8928               // Handle initialization of captured loop iterator variables.
8929               auto *DRE = cast<DeclRefExpr>(IterSpaces[Cnt].CounterVar);
8930               if (isa<OMPCapturedExprDecl>(DRE->getDecl())) {
8931                 Captures[DRE] = DRE;
8932               }
8933             }
8934             return false;
8935           }))
8936     return 0;
8937 
8938   Built.clear(/* size */ NestedLoopCount);
8939 
8940   if (SemaRef.CurContext->isDependentContext())
8941     return NestedLoopCount;
8942 
8943   // An example of what is generated for the following code:
8944   //
8945   //   #pragma omp simd collapse(2) ordered(2)
8946   //   for (i = 0; i < NI; ++i)
8947   //     for (k = 0; k < NK; ++k)
8948   //       for (j = J0; j < NJ; j+=2) {
8949   //         <loop body>
8950   //       }
8951   //
8952   // We generate the code below.
8953   // Note: the loop body may be outlined in CodeGen.
8954   // Note: some counters may be C++ classes, operator- is used to find number of
8955   // iterations and operator+= to calculate counter value.
8956   // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
8957   // or i64 is currently supported).
8958   //
8959   //   #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
8960   //   for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
8961   //     .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
8962   //     .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
8963   //     // similar updates for vars in clauses (e.g. 'linear')
8964   //     <loop body (using local i and j)>
8965   //   }
8966   //   i = NI; // assign final values of counters
8967   //   j = NJ;
8968   //
8969 
8970   // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
8971   // the iteration counts of the collapsed for loops.
8972   // Precondition tests if there is at least one iteration (all conditions are
8973   // true).
8974   auto PreCond = ExprResult(IterSpaces[0].PreCond);
8975   Expr *N0 = IterSpaces[0].NumIterations;
8976   ExprResult LastIteration32 =
8977       widenIterationCount(/*Bits=*/32,
8978                           SemaRef
8979                               .PerformImplicitConversion(
8980                                   N0->IgnoreImpCasts(), N0->getType(),
8981                                   Sema::AA_Converting, /*AllowExplicit=*/true)
8982                               .get(),
8983                           SemaRef);
8984   ExprResult LastIteration64 = widenIterationCount(
8985       /*Bits=*/64,
8986       SemaRef
8987           .PerformImplicitConversion(N0->IgnoreImpCasts(), N0->getType(),
8988                                      Sema::AA_Converting,
8989                                      /*AllowExplicit=*/true)
8990           .get(),
8991       SemaRef);
8992 
8993   if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
8994     return NestedLoopCount;
8995 
8996   ASTContext &C = SemaRef.Context;
8997   bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
8998 
8999   Scope *CurScope = DSA.getCurScope();
9000   for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
9001     if (PreCond.isUsable()) {
9002       PreCond =
9003           SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
9004                              PreCond.get(), IterSpaces[Cnt].PreCond);
9005     }
9006     Expr *N = IterSpaces[Cnt].NumIterations;
9007     SourceLocation Loc = N->getExprLoc();
9008     AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
9009     if (LastIteration32.isUsable())
9010       LastIteration32 = SemaRef.BuildBinOp(
9011           CurScope, Loc, BO_Mul, LastIteration32.get(),
9012           SemaRef
9013               .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
9014                                          Sema::AA_Converting,
9015                                          /*AllowExplicit=*/true)
9016               .get());
9017     if (LastIteration64.isUsable())
9018       LastIteration64 = SemaRef.BuildBinOp(
9019           CurScope, Loc, BO_Mul, LastIteration64.get(),
9020           SemaRef
9021               .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
9022                                          Sema::AA_Converting,
9023                                          /*AllowExplicit=*/true)
9024               .get());
9025   }
9026 
9027   // Choose either the 32-bit or 64-bit version.
9028   ExprResult LastIteration = LastIteration64;
9029   if (SemaRef.getLangOpts().OpenMPOptimisticCollapse ||
9030       (LastIteration32.isUsable() &&
9031        C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
9032        (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
9033         fitsInto(
9034             /*Bits=*/32,
9035             LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
9036             LastIteration64.get(), SemaRef))))
9037     LastIteration = LastIteration32;
9038   QualType VType = LastIteration.get()->getType();
9039   QualType RealVType = VType;
9040   QualType StrideVType = VType;
9041   if (isOpenMPTaskLoopDirective(DKind)) {
9042     VType =
9043         SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
9044     StrideVType =
9045         SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
9046   }
9047 
9048   if (!LastIteration.isUsable())
9049     return 0;
9050 
9051   // Save the number of iterations.
9052   ExprResult NumIterations = LastIteration;
9053   {
9054     LastIteration = SemaRef.BuildBinOp(
9055         CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
9056         LastIteration.get(),
9057         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
9058     if (!LastIteration.isUsable())
9059       return 0;
9060   }
9061 
9062   // Calculate the last iteration number beforehand instead of doing this on
9063   // each iteration. Do not do this if the number of iterations may be kfold-ed.
9064   bool IsConstant = LastIteration.get()->isIntegerConstantExpr(SemaRef.Context);
9065   ExprResult CalcLastIteration;
9066   if (!IsConstant) {
9067     ExprResult SaveRef =
9068         tryBuildCapture(SemaRef, LastIteration.get(), Captures);
9069     LastIteration = SaveRef;
9070 
9071     // Prepare SaveRef + 1.
9072     NumIterations = SemaRef.BuildBinOp(
9073         CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
9074         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
9075     if (!NumIterations.isUsable())
9076       return 0;
9077   }
9078 
9079   SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
9080 
9081   // Build variables passed into runtime, necessary for worksharing directives.
9082   ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
9083   if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
9084       isOpenMPDistributeDirective(DKind) ||
9085       isOpenMPLoopTransformationDirective(DKind)) {
9086     // Lower bound variable, initialized with zero.
9087     VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
9088     LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
9089     SemaRef.AddInitializerToDecl(LBDecl,
9090                                  SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
9091                                  /*DirectInit*/ false);
9092 
9093     // Upper bound variable, initialized with last iteration number.
9094     VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
9095     UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
9096     SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
9097                                  /*DirectInit*/ false);
9098 
9099     // A 32-bit variable-flag where runtime returns 1 for the last iteration.
9100     // This will be used to implement clause 'lastprivate'.
9101     QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
9102     VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
9103     IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
9104     SemaRef.AddInitializerToDecl(ILDecl,
9105                                  SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
9106                                  /*DirectInit*/ false);
9107 
9108     // Stride variable returned by runtime (we initialize it to 1 by default).
9109     VarDecl *STDecl =
9110         buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
9111     ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
9112     SemaRef.AddInitializerToDecl(STDecl,
9113                                  SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
9114                                  /*DirectInit*/ false);
9115 
9116     // Build expression: UB = min(UB, LastIteration)
9117     // It is necessary for CodeGen of directives with static scheduling.
9118     ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
9119                                                 UB.get(), LastIteration.get());
9120     ExprResult CondOp = SemaRef.ActOnConditionalOp(
9121         LastIteration.get()->getExprLoc(), InitLoc, IsUBGreater.get(),
9122         LastIteration.get(), UB.get());
9123     EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
9124                              CondOp.get());
9125     EUB = SemaRef.ActOnFinishFullExpr(EUB.get(), /*DiscardedValue*/ false);
9126 
9127     // If we have a combined directive that combines 'distribute', 'for' or
9128     // 'simd' we need to be able to access the bounds of the schedule of the
9129     // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
9130     // by scheduling 'distribute' have to be passed to the schedule of 'for'.
9131     if (isOpenMPLoopBoundSharingDirective(DKind)) {
9132       // Lower bound variable, initialized with zero.
9133       VarDecl *CombLBDecl =
9134           buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
9135       CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
9136       SemaRef.AddInitializerToDecl(
9137           CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
9138           /*DirectInit*/ false);
9139 
9140       // Upper bound variable, initialized with last iteration number.
9141       VarDecl *CombUBDecl =
9142           buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
9143       CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
9144       SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
9145                                    /*DirectInit*/ false);
9146 
9147       ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
9148           CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
9149       ExprResult CombCondOp =
9150           SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
9151                                      LastIteration.get(), CombUB.get());
9152       CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
9153                                    CombCondOp.get());
9154       CombEUB =
9155           SemaRef.ActOnFinishFullExpr(CombEUB.get(), /*DiscardedValue*/ false);
9156 
9157       const CapturedDecl *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
9158       // We expect to have at least 2 more parameters than the 'parallel'
9159       // directive does - the lower and upper bounds of the previous schedule.
9160       assert(CD->getNumParams() >= 4 &&
9161              "Unexpected number of parameters in loop combined directive");
9162 
9163       // Set the proper type for the bounds given what we learned from the
9164       // enclosed loops.
9165       ImplicitParamDecl *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
9166       ImplicitParamDecl *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
9167 
9168       // Previous lower and upper bounds are obtained from the region
9169       // parameters.
9170       PrevLB =
9171           buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
9172       PrevUB =
9173           buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
9174     }
9175   }
9176 
9177   // Build the iteration variable and its initialization before loop.
9178   ExprResult IV;
9179   ExprResult Init, CombInit;
9180   {
9181     VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
9182     IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
9183     Expr *RHS = (isOpenMPWorksharingDirective(DKind) ||
9184                  isOpenMPTaskLoopDirective(DKind) ||
9185                  isOpenMPDistributeDirective(DKind) ||
9186                  isOpenMPLoopTransformationDirective(DKind))
9187                     ? LB.get()
9188                     : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
9189     Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
9190     Init = SemaRef.ActOnFinishFullExpr(Init.get(), /*DiscardedValue*/ false);
9191 
9192     if (isOpenMPLoopBoundSharingDirective(DKind)) {
9193       Expr *CombRHS =
9194           (isOpenMPWorksharingDirective(DKind) ||
9195            isOpenMPTaskLoopDirective(DKind) ||
9196            isOpenMPDistributeDirective(DKind))
9197               ? CombLB.get()
9198               : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
9199       CombInit =
9200           SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
9201       CombInit =
9202           SemaRef.ActOnFinishFullExpr(CombInit.get(), /*DiscardedValue*/ false);
9203     }
9204   }
9205 
9206   bool UseStrictCompare =
9207       RealVType->hasUnsignedIntegerRepresentation() &&
9208       llvm::all_of(IterSpaces, [](const LoopIterationSpace &LIS) {
9209         return LIS.IsStrictCompare;
9210       });
9211   // Loop condition (IV < NumIterations) or (IV <= UB or IV < UB + 1 (for
9212   // unsigned IV)) for worksharing loops.
9213   SourceLocation CondLoc = AStmt->getBeginLoc();
9214   Expr *BoundUB = UB.get();
9215   if (UseStrictCompare) {
9216     BoundUB =
9217         SemaRef
9218             .BuildBinOp(CurScope, CondLoc, BO_Add, BoundUB,
9219                         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
9220             .get();
9221     BoundUB =
9222         SemaRef.ActOnFinishFullExpr(BoundUB, /*DiscardedValue*/ false).get();
9223   }
9224   ExprResult Cond =
9225       (isOpenMPWorksharingDirective(DKind) ||
9226        isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind) ||
9227        isOpenMPLoopTransformationDirective(DKind))
9228           ? SemaRef.BuildBinOp(CurScope, CondLoc,
9229                                UseStrictCompare ? BO_LT : BO_LE, IV.get(),
9230                                BoundUB)
9231           : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
9232                                NumIterations.get());
9233   ExprResult CombDistCond;
9234   if (isOpenMPLoopBoundSharingDirective(DKind)) {
9235     CombDistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
9236                                       NumIterations.get());
9237   }
9238 
9239   ExprResult CombCond;
9240   if (isOpenMPLoopBoundSharingDirective(DKind)) {
9241     Expr *BoundCombUB = CombUB.get();
9242     if (UseStrictCompare) {
9243       BoundCombUB =
9244           SemaRef
9245               .BuildBinOp(
9246                   CurScope, CondLoc, BO_Add, BoundCombUB,
9247                   SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
9248               .get();
9249       BoundCombUB =
9250           SemaRef.ActOnFinishFullExpr(BoundCombUB, /*DiscardedValue*/ false)
9251               .get();
9252     }
9253     CombCond =
9254         SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
9255                            IV.get(), BoundCombUB);
9256   }
9257   // Loop increment (IV = IV + 1)
9258   SourceLocation IncLoc = AStmt->getBeginLoc();
9259   ExprResult Inc =
9260       SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
9261                          SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
9262   if (!Inc.isUsable())
9263     return 0;
9264   Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
9265   Inc = SemaRef.ActOnFinishFullExpr(Inc.get(), /*DiscardedValue*/ false);
9266   if (!Inc.isUsable())
9267     return 0;
9268 
9269   // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
9270   // Used for directives with static scheduling.
9271   // In combined construct, add combined version that use CombLB and CombUB
9272   // base variables for the update
9273   ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
9274   if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
9275       isOpenMPDistributeDirective(DKind) ||
9276       isOpenMPLoopTransformationDirective(DKind)) {
9277     // LB + ST
9278     NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
9279     if (!NextLB.isUsable())
9280       return 0;
9281     // LB = LB + ST
9282     NextLB =
9283         SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
9284     NextLB =
9285         SemaRef.ActOnFinishFullExpr(NextLB.get(), /*DiscardedValue*/ false);
9286     if (!NextLB.isUsable())
9287       return 0;
9288     // UB + ST
9289     NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
9290     if (!NextUB.isUsable())
9291       return 0;
9292     // UB = UB + ST
9293     NextUB =
9294         SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
9295     NextUB =
9296         SemaRef.ActOnFinishFullExpr(NextUB.get(), /*DiscardedValue*/ false);
9297     if (!NextUB.isUsable())
9298       return 0;
9299     if (isOpenMPLoopBoundSharingDirective(DKind)) {
9300       CombNextLB =
9301           SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
9302       if (!NextLB.isUsable())
9303         return 0;
9304       // LB = LB + ST
9305       CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
9306                                       CombNextLB.get());
9307       CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get(),
9308                                                /*DiscardedValue*/ false);
9309       if (!CombNextLB.isUsable())
9310         return 0;
9311       // UB + ST
9312       CombNextUB =
9313           SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
9314       if (!CombNextUB.isUsable())
9315         return 0;
9316       // UB = UB + ST
9317       CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
9318                                       CombNextUB.get());
9319       CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get(),
9320                                                /*DiscardedValue*/ false);
9321       if (!CombNextUB.isUsable())
9322         return 0;
9323     }
9324   }
9325 
9326   // Create increment expression for distribute loop when combined in a same
9327   // directive with for as IV = IV + ST; ensure upper bound expression based
9328   // on PrevUB instead of NumIterations - used to implement 'for' when found
9329   // in combination with 'distribute', like in 'distribute parallel for'
9330   SourceLocation DistIncLoc = AStmt->getBeginLoc();
9331   ExprResult DistCond, DistInc, PrevEUB, ParForInDistCond;
9332   if (isOpenMPLoopBoundSharingDirective(DKind)) {
9333     DistCond = SemaRef.BuildBinOp(
9334         CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE, IV.get(), BoundUB);
9335     assert(DistCond.isUsable() && "distribute cond expr was not built");
9336 
9337     DistInc =
9338         SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
9339     assert(DistInc.isUsable() && "distribute inc expr was not built");
9340     DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
9341                                  DistInc.get());
9342     DistInc =
9343         SemaRef.ActOnFinishFullExpr(DistInc.get(), /*DiscardedValue*/ false);
9344     assert(DistInc.isUsable() && "distribute inc expr was not built");
9345 
9346     // Build expression: UB = min(UB, prevUB) for #for in composite or combined
9347     // construct
9348     SourceLocation DistEUBLoc = AStmt->getBeginLoc();
9349     ExprResult IsUBGreater =
9350         SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get());
9351     ExprResult CondOp = SemaRef.ActOnConditionalOp(
9352         DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get());
9353     PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
9354                                  CondOp.get());
9355     PrevEUB =
9356         SemaRef.ActOnFinishFullExpr(PrevEUB.get(), /*DiscardedValue*/ false);
9357 
9358     // Build IV <= PrevUB or IV < PrevUB + 1 for unsigned IV to be used in
9359     // parallel for is in combination with a distribute directive with
9360     // schedule(static, 1)
9361     Expr *BoundPrevUB = PrevUB.get();
9362     if (UseStrictCompare) {
9363       BoundPrevUB =
9364           SemaRef
9365               .BuildBinOp(
9366                   CurScope, CondLoc, BO_Add, BoundPrevUB,
9367                   SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
9368               .get();
9369       BoundPrevUB =
9370           SemaRef.ActOnFinishFullExpr(BoundPrevUB, /*DiscardedValue*/ false)
9371               .get();
9372     }
9373     ParForInDistCond =
9374         SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
9375                            IV.get(), BoundPrevUB);
9376   }
9377 
9378   // Build updates and final values of the loop counters.
9379   bool HasErrors = false;
9380   Built.Counters.resize(NestedLoopCount);
9381   Built.Inits.resize(NestedLoopCount);
9382   Built.Updates.resize(NestedLoopCount);
9383   Built.Finals.resize(NestedLoopCount);
9384   Built.DependentCounters.resize(NestedLoopCount);
9385   Built.DependentInits.resize(NestedLoopCount);
9386   Built.FinalsConditions.resize(NestedLoopCount);
9387   {
9388     // We implement the following algorithm for obtaining the
9389     // original loop iteration variable values based on the
9390     // value of the collapsed loop iteration variable IV.
9391     //
9392     // Let n+1 be the number of collapsed loops in the nest.
9393     // Iteration variables (I0, I1, .... In)
9394     // Iteration counts (N0, N1, ... Nn)
9395     //
9396     // Acc = IV;
9397     //
9398     // To compute Ik for loop k, 0 <= k <= n, generate:
9399     //    Prod = N(k+1) * N(k+2) * ... * Nn;
9400     //    Ik = Acc / Prod;
9401     //    Acc -= Ik * Prod;
9402     //
9403     ExprResult Acc = IV;
9404     for (unsigned int Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
9405       LoopIterationSpace &IS = IterSpaces[Cnt];
9406       SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
9407       ExprResult Iter;
9408 
9409       // Compute prod
9410       ExprResult Prod =
9411           SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
9412       for (unsigned int K = Cnt+1; K < NestedLoopCount; ++K)
9413         Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Prod.get(),
9414                                   IterSpaces[K].NumIterations);
9415 
9416       // Iter = Acc / Prod
9417       // If there is at least one more inner loop to avoid
9418       // multiplication by 1.
9419       if (Cnt + 1 < NestedLoopCount)
9420         Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div,
9421                                   Acc.get(), Prod.get());
9422       else
9423         Iter = Acc;
9424       if (!Iter.isUsable()) {
9425         HasErrors = true;
9426         break;
9427       }
9428 
9429       // Update Acc:
9430       // Acc -= Iter * Prod
9431       // Check if there is at least one more inner loop to avoid
9432       // multiplication by 1.
9433       if (Cnt + 1 < NestedLoopCount)
9434         Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul,
9435                                   Iter.get(), Prod.get());
9436       else
9437         Prod = Iter;
9438       Acc = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Sub,
9439                                Acc.get(), Prod.get());
9440 
9441       // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
9442       auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
9443       DeclRefExpr *CounterVar = buildDeclRefExpr(
9444           SemaRef, VD, IS.CounterVar->getType(), IS.CounterVar->getExprLoc(),
9445           /*RefersToCapture=*/true);
9446       ExprResult Init =
9447           buildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
9448                            IS.CounterInit, IS.IsNonRectangularLB, Captures);
9449       if (!Init.isUsable()) {
9450         HasErrors = true;
9451         break;
9452       }
9453       ExprResult Update = buildCounterUpdate(
9454           SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
9455           IS.CounterStep, IS.Subtract, IS.IsNonRectangularLB, &Captures);
9456       if (!Update.isUsable()) {
9457         HasErrors = true;
9458         break;
9459       }
9460 
9461       // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
9462       ExprResult Final =
9463           buildCounterUpdate(SemaRef, CurScope, UpdLoc, CounterVar,
9464                              IS.CounterInit, IS.NumIterations, IS.CounterStep,
9465                              IS.Subtract, IS.IsNonRectangularLB, &Captures);
9466       if (!Final.isUsable()) {
9467         HasErrors = true;
9468         break;
9469       }
9470 
9471       if (!Update.isUsable() || !Final.isUsable()) {
9472         HasErrors = true;
9473         break;
9474       }
9475       // Save results
9476       Built.Counters[Cnt] = IS.CounterVar;
9477       Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
9478       Built.Inits[Cnt] = Init.get();
9479       Built.Updates[Cnt] = Update.get();
9480       Built.Finals[Cnt] = Final.get();
9481       Built.DependentCounters[Cnt] = nullptr;
9482       Built.DependentInits[Cnt] = nullptr;
9483       Built.FinalsConditions[Cnt] = nullptr;
9484       if (IS.IsNonRectangularLB || IS.IsNonRectangularUB) {
9485         Built.DependentCounters[Cnt] =
9486             Built.Counters[NestedLoopCount - 1 - IS.LoopDependentIdx];
9487         Built.DependentInits[Cnt] =
9488             Built.Inits[NestedLoopCount - 1 - IS.LoopDependentIdx];
9489         Built.FinalsConditions[Cnt] = IS.FinalCondition;
9490       }
9491     }
9492   }
9493 
9494   if (HasErrors)
9495     return 0;
9496 
9497   // Save results
9498   Built.IterationVarRef = IV.get();
9499   Built.LastIteration = LastIteration.get();
9500   Built.NumIterations = NumIterations.get();
9501   Built.CalcLastIteration = SemaRef
9502                                 .ActOnFinishFullExpr(CalcLastIteration.get(),
9503                                                      /*DiscardedValue=*/false)
9504                                 .get();
9505   Built.PreCond = PreCond.get();
9506   Built.PreInits = buildPreInits(C, Captures);
9507   Built.Cond = Cond.get();
9508   Built.Init = Init.get();
9509   Built.Inc = Inc.get();
9510   Built.LB = LB.get();
9511   Built.UB = UB.get();
9512   Built.IL = IL.get();
9513   Built.ST = ST.get();
9514   Built.EUB = EUB.get();
9515   Built.NLB = NextLB.get();
9516   Built.NUB = NextUB.get();
9517   Built.PrevLB = PrevLB.get();
9518   Built.PrevUB = PrevUB.get();
9519   Built.DistInc = DistInc.get();
9520   Built.PrevEUB = PrevEUB.get();
9521   Built.DistCombinedFields.LB = CombLB.get();
9522   Built.DistCombinedFields.UB = CombUB.get();
9523   Built.DistCombinedFields.EUB = CombEUB.get();
9524   Built.DistCombinedFields.Init = CombInit.get();
9525   Built.DistCombinedFields.Cond = CombCond.get();
9526   Built.DistCombinedFields.NLB = CombNextLB.get();
9527   Built.DistCombinedFields.NUB = CombNextUB.get();
9528   Built.DistCombinedFields.DistCond = CombDistCond.get();
9529   Built.DistCombinedFields.ParForInDistCond = ParForInDistCond.get();
9530 
9531   return NestedLoopCount;
9532 }
9533 
9534 static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
9535   auto CollapseClauses =
9536       OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
9537   if (CollapseClauses.begin() != CollapseClauses.end())
9538     return (*CollapseClauses.begin())->getNumForLoops();
9539   return nullptr;
9540 }
9541 
9542 static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
9543   auto OrderedClauses =
9544       OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
9545   if (OrderedClauses.begin() != OrderedClauses.end())
9546     return (*OrderedClauses.begin())->getNumForLoops();
9547   return nullptr;
9548 }
9549 
9550 static bool checkSimdlenSafelenSpecified(Sema &S,
9551                                          const ArrayRef<OMPClause *> Clauses) {
9552   const OMPSafelenClause *Safelen = nullptr;
9553   const OMPSimdlenClause *Simdlen = nullptr;
9554 
9555   for (const OMPClause *Clause : Clauses) {
9556     if (Clause->getClauseKind() == OMPC_safelen)
9557       Safelen = cast<OMPSafelenClause>(Clause);
9558     else if (Clause->getClauseKind() == OMPC_simdlen)
9559       Simdlen = cast<OMPSimdlenClause>(Clause);
9560     if (Safelen && Simdlen)
9561       break;
9562   }
9563 
9564   if (Simdlen && Safelen) {
9565     const Expr *SimdlenLength = Simdlen->getSimdlen();
9566     const Expr *SafelenLength = Safelen->getSafelen();
9567     if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
9568         SimdlenLength->isInstantiationDependent() ||
9569         SimdlenLength->containsUnexpandedParameterPack())
9570       return false;
9571     if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
9572         SafelenLength->isInstantiationDependent() ||
9573         SafelenLength->containsUnexpandedParameterPack())
9574       return false;
9575     Expr::EvalResult SimdlenResult, SafelenResult;
9576     SimdlenLength->EvaluateAsInt(SimdlenResult, S.Context);
9577     SafelenLength->EvaluateAsInt(SafelenResult, S.Context);
9578     llvm::APSInt SimdlenRes = SimdlenResult.Val.getInt();
9579     llvm::APSInt SafelenRes = SafelenResult.Val.getInt();
9580     // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
9581     // If both simdlen and safelen clauses are specified, the value of the
9582     // simdlen parameter must be less than or equal to the value of the safelen
9583     // parameter.
9584     if (SimdlenRes > SafelenRes) {
9585       S.Diag(SimdlenLength->getExprLoc(),
9586              diag::err_omp_wrong_simdlen_safelen_values)
9587           << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
9588       return true;
9589     }
9590   }
9591   return false;
9592 }
9593 
9594 StmtResult
9595 Sema::ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
9596                                SourceLocation StartLoc, SourceLocation EndLoc,
9597                                VarsWithInheritedDSAType &VarsWithImplicitDSA) {
9598   if (!AStmt)
9599     return StmtError();
9600 
9601   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9602   OMPLoopBasedDirective::HelperExprs B;
9603   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9604   // define the nested loops number.
9605   unsigned NestedLoopCount = checkOpenMPLoop(
9606       OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
9607       AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
9608   if (NestedLoopCount == 0)
9609     return StmtError();
9610 
9611   assert((CurContext->isDependentContext() || B.builtAll()) &&
9612          "omp simd loop exprs were not built");
9613 
9614   if (!CurContext->isDependentContext()) {
9615     // Finalize the clauses that need pre-built expressions for CodeGen.
9616     for (OMPClause *C : Clauses) {
9617       if (auto *LC = dyn_cast<OMPLinearClause>(C))
9618         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9619                                      B.NumIterations, *this, CurScope,
9620                                      DSAStack))
9621           return StmtError();
9622     }
9623   }
9624 
9625   if (checkSimdlenSafelenSpecified(*this, Clauses))
9626     return StmtError();
9627 
9628   setFunctionHasBranchProtectedScope();
9629   return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
9630                                   Clauses, AStmt, B);
9631 }
9632 
9633 StmtResult
9634 Sema::ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
9635                               SourceLocation StartLoc, SourceLocation EndLoc,
9636                               VarsWithInheritedDSAType &VarsWithImplicitDSA) {
9637   if (!AStmt)
9638     return StmtError();
9639 
9640   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9641   OMPLoopBasedDirective::HelperExprs B;
9642   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9643   // define the nested loops number.
9644   unsigned NestedLoopCount = checkOpenMPLoop(
9645       OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
9646       AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
9647   if (NestedLoopCount == 0)
9648     return StmtError();
9649 
9650   assert((CurContext->isDependentContext() || B.builtAll()) &&
9651          "omp for loop exprs were not built");
9652 
9653   if (!CurContext->isDependentContext()) {
9654     // Finalize the clauses that need pre-built expressions for CodeGen.
9655     for (OMPClause *C : Clauses) {
9656       if (auto *LC = dyn_cast<OMPLinearClause>(C))
9657         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9658                                      B.NumIterations, *this, CurScope,
9659                                      DSAStack))
9660           return StmtError();
9661     }
9662   }
9663 
9664   setFunctionHasBranchProtectedScope();
9665   return OMPForDirective::Create(
9666       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
9667       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
9668 }
9669 
9670 StmtResult Sema::ActOnOpenMPForSimdDirective(
9671     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9672     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
9673   if (!AStmt)
9674     return StmtError();
9675 
9676   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9677   OMPLoopBasedDirective::HelperExprs B;
9678   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9679   // define the nested loops number.
9680   unsigned NestedLoopCount =
9681       checkOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
9682                       getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
9683                       VarsWithImplicitDSA, B);
9684   if (NestedLoopCount == 0)
9685     return StmtError();
9686 
9687   assert((CurContext->isDependentContext() || B.builtAll()) &&
9688          "omp for simd loop exprs were not built");
9689 
9690   if (!CurContext->isDependentContext()) {
9691     // Finalize the clauses that need pre-built expressions for CodeGen.
9692     for (OMPClause *C : Clauses) {
9693       if (auto *LC = dyn_cast<OMPLinearClause>(C))
9694         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9695                                      B.NumIterations, *this, CurScope,
9696                                      DSAStack))
9697           return StmtError();
9698     }
9699   }
9700 
9701   if (checkSimdlenSafelenSpecified(*this, Clauses))
9702     return StmtError();
9703 
9704   setFunctionHasBranchProtectedScope();
9705   return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
9706                                      Clauses, AStmt, B);
9707 }
9708 
9709 StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
9710                                               Stmt *AStmt,
9711                                               SourceLocation StartLoc,
9712                                               SourceLocation EndLoc) {
9713   if (!AStmt)
9714     return StmtError();
9715 
9716   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9717   auto BaseStmt = AStmt;
9718   while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
9719     BaseStmt = CS->getCapturedStmt();
9720   if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
9721     auto S = C->children();
9722     if (S.begin() == S.end())
9723       return StmtError();
9724     // All associated statements must be '#pragma omp section' except for
9725     // the first one.
9726     for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
9727       if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
9728         if (SectionStmt)
9729           Diag(SectionStmt->getBeginLoc(),
9730                diag::err_omp_sections_substmt_not_section);
9731         return StmtError();
9732       }
9733       cast<OMPSectionDirective>(SectionStmt)
9734           ->setHasCancel(DSAStack->isCancelRegion());
9735     }
9736   } else {
9737     Diag(AStmt->getBeginLoc(), diag::err_omp_sections_not_compound_stmt);
9738     return StmtError();
9739   }
9740 
9741   setFunctionHasBranchProtectedScope();
9742 
9743   return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
9744                                       DSAStack->getTaskgroupReductionRef(),
9745                                       DSAStack->isCancelRegion());
9746 }
9747 
9748 StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
9749                                              SourceLocation StartLoc,
9750                                              SourceLocation EndLoc) {
9751   if (!AStmt)
9752     return StmtError();
9753 
9754   setFunctionHasBranchProtectedScope();
9755   DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
9756 
9757   return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
9758                                      DSAStack->isCancelRegion());
9759 }
9760 
9761 StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
9762                                             Stmt *AStmt,
9763                                             SourceLocation StartLoc,
9764                                             SourceLocation EndLoc) {
9765   if (!AStmt)
9766     return StmtError();
9767 
9768   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9769 
9770   setFunctionHasBranchProtectedScope();
9771 
9772   // OpenMP [2.7.3, single Construct, Restrictions]
9773   // The copyprivate clause must not be used with the nowait clause.
9774   const OMPClause *Nowait = nullptr;
9775   const OMPClause *Copyprivate = nullptr;
9776   for (const OMPClause *Clause : Clauses) {
9777     if (Clause->getClauseKind() == OMPC_nowait)
9778       Nowait = Clause;
9779     else if (Clause->getClauseKind() == OMPC_copyprivate)
9780       Copyprivate = Clause;
9781     if (Copyprivate && Nowait) {
9782       Diag(Copyprivate->getBeginLoc(),
9783            diag::err_omp_single_copyprivate_with_nowait);
9784       Diag(Nowait->getBeginLoc(), diag::note_omp_nowait_clause_here);
9785       return StmtError();
9786     }
9787   }
9788 
9789   return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
9790 }
9791 
9792 StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
9793                                             SourceLocation StartLoc,
9794                                             SourceLocation EndLoc) {
9795   if (!AStmt)
9796     return StmtError();
9797 
9798   setFunctionHasBranchProtectedScope();
9799 
9800   return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
9801 }
9802 
9803 StmtResult Sema::ActOnOpenMPCriticalDirective(
9804     const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
9805     Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
9806   if (!AStmt)
9807     return StmtError();
9808 
9809   bool ErrorFound = false;
9810   llvm::APSInt Hint;
9811   SourceLocation HintLoc;
9812   bool DependentHint = false;
9813   for (const OMPClause *C : Clauses) {
9814     if (C->getClauseKind() == OMPC_hint) {
9815       if (!DirName.getName()) {
9816         Diag(C->getBeginLoc(), diag::err_omp_hint_clause_no_name);
9817         ErrorFound = true;
9818       }
9819       Expr *E = cast<OMPHintClause>(C)->getHint();
9820       if (E->isTypeDependent() || E->isValueDependent() ||
9821           E->isInstantiationDependent()) {
9822         DependentHint = true;
9823       } else {
9824         Hint = E->EvaluateKnownConstInt(Context);
9825         HintLoc = C->getBeginLoc();
9826       }
9827     }
9828   }
9829   if (ErrorFound)
9830     return StmtError();
9831   const auto Pair = DSAStack->getCriticalWithHint(DirName);
9832   if (Pair.first && DirName.getName() && !DependentHint) {
9833     if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
9834       Diag(StartLoc, diag::err_omp_critical_with_hint);
9835       if (HintLoc.isValid())
9836         Diag(HintLoc, diag::note_omp_critical_hint_here)
9837             << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
9838       else
9839         Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
9840       if (const auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
9841         Diag(C->getBeginLoc(), diag::note_omp_critical_hint_here)
9842             << 1
9843             << C->getHint()->EvaluateKnownConstInt(Context).toString(
9844                    /*Radix=*/10, /*Signed=*/false);
9845       } else {
9846         Diag(Pair.first->getBeginLoc(), diag::note_omp_critical_no_hint) << 1;
9847       }
9848     }
9849   }
9850 
9851   setFunctionHasBranchProtectedScope();
9852 
9853   auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
9854                                            Clauses, AStmt);
9855   if (!Pair.first && DirName.getName() && !DependentHint)
9856     DSAStack->addCriticalWithHint(Dir, Hint);
9857   return Dir;
9858 }
9859 
9860 StmtResult Sema::ActOnOpenMPParallelForDirective(
9861     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9862     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
9863   if (!AStmt)
9864     return StmtError();
9865 
9866   auto *CS = cast<CapturedStmt>(AStmt);
9867   // 1.2.2 OpenMP Language Terminology
9868   // Structured block - An executable statement with a single entry at the
9869   // top and a single exit at the bottom.
9870   // The point of exit cannot be a branch out of the structured block.
9871   // longjmp() and throw() must not violate the entry/exit criteria.
9872   CS->getCapturedDecl()->setNothrow();
9873 
9874   OMPLoopBasedDirective::HelperExprs B;
9875   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9876   // define the nested loops number.
9877   unsigned NestedLoopCount =
9878       checkOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
9879                       getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
9880                       VarsWithImplicitDSA, B);
9881   if (NestedLoopCount == 0)
9882     return StmtError();
9883 
9884   assert((CurContext->isDependentContext() || B.builtAll()) &&
9885          "omp parallel for loop exprs were not built");
9886 
9887   if (!CurContext->isDependentContext()) {
9888     // Finalize the clauses that need pre-built expressions for CodeGen.
9889     for (OMPClause *C : Clauses) {
9890       if (auto *LC = dyn_cast<OMPLinearClause>(C))
9891         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9892                                      B.NumIterations, *this, CurScope,
9893                                      DSAStack))
9894           return StmtError();
9895     }
9896   }
9897 
9898   setFunctionHasBranchProtectedScope();
9899   return OMPParallelForDirective::Create(
9900       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
9901       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
9902 }
9903 
9904 StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
9905     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9906     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
9907   if (!AStmt)
9908     return StmtError();
9909 
9910   auto *CS = cast<CapturedStmt>(AStmt);
9911   // 1.2.2 OpenMP Language Terminology
9912   // Structured block - An executable statement with a single entry at the
9913   // top and a single exit at the bottom.
9914   // The point of exit cannot be a branch out of the structured block.
9915   // longjmp() and throw() must not violate the entry/exit criteria.
9916   CS->getCapturedDecl()->setNothrow();
9917 
9918   OMPLoopBasedDirective::HelperExprs B;
9919   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9920   // define the nested loops number.
9921   unsigned NestedLoopCount =
9922       checkOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
9923                       getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
9924                       VarsWithImplicitDSA, B);
9925   if (NestedLoopCount == 0)
9926     return StmtError();
9927 
9928   if (!CurContext->isDependentContext()) {
9929     // Finalize the clauses that need pre-built expressions for CodeGen.
9930     for (OMPClause *C : Clauses) {
9931       if (auto *LC = dyn_cast<OMPLinearClause>(C))
9932         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9933                                      B.NumIterations, *this, CurScope,
9934                                      DSAStack))
9935           return StmtError();
9936     }
9937   }
9938 
9939   if (checkSimdlenSafelenSpecified(*this, Clauses))
9940     return StmtError();
9941 
9942   setFunctionHasBranchProtectedScope();
9943   return OMPParallelForSimdDirective::Create(
9944       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
9945 }
9946 
9947 StmtResult
9948 Sema::ActOnOpenMPParallelMasterDirective(ArrayRef<OMPClause *> Clauses,
9949                                          Stmt *AStmt, SourceLocation StartLoc,
9950                                          SourceLocation EndLoc) {
9951   if (!AStmt)
9952     return StmtError();
9953 
9954   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9955   auto *CS = cast<CapturedStmt>(AStmt);
9956   // 1.2.2 OpenMP Language Terminology
9957   // Structured block - An executable statement with a single entry at the
9958   // top and a single exit at the bottom.
9959   // The point of exit cannot be a branch out of the structured block.
9960   // longjmp() and throw() must not violate the entry/exit criteria.
9961   CS->getCapturedDecl()->setNothrow();
9962 
9963   setFunctionHasBranchProtectedScope();
9964 
9965   return OMPParallelMasterDirective::Create(
9966       Context, StartLoc, EndLoc, Clauses, AStmt,
9967       DSAStack->getTaskgroupReductionRef());
9968 }
9969 
9970 StmtResult
9971 Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
9972                                            Stmt *AStmt, SourceLocation StartLoc,
9973                                            SourceLocation EndLoc) {
9974   if (!AStmt)
9975     return StmtError();
9976 
9977   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9978   auto BaseStmt = AStmt;
9979   while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
9980     BaseStmt = CS->getCapturedStmt();
9981   if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
9982     auto S = C->children();
9983     if (S.begin() == S.end())
9984       return StmtError();
9985     // All associated statements must be '#pragma omp section' except for
9986     // the first one.
9987     for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
9988       if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
9989         if (SectionStmt)
9990           Diag(SectionStmt->getBeginLoc(),
9991                diag::err_omp_parallel_sections_substmt_not_section);
9992         return StmtError();
9993       }
9994       cast<OMPSectionDirective>(SectionStmt)
9995           ->setHasCancel(DSAStack->isCancelRegion());
9996     }
9997   } else {
9998     Diag(AStmt->getBeginLoc(),
9999          diag::err_omp_parallel_sections_not_compound_stmt);
10000     return StmtError();
10001   }
10002 
10003   setFunctionHasBranchProtectedScope();
10004 
10005   return OMPParallelSectionsDirective::Create(
10006       Context, StartLoc, EndLoc, Clauses, AStmt,
10007       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
10008 }
10009 
10010 /// detach and mergeable clauses are mutially exclusive, check for it.
10011 static bool checkDetachMergeableClauses(Sema &S,
10012                                         ArrayRef<OMPClause *> Clauses) {
10013   const OMPClause *PrevClause = nullptr;
10014   bool ErrorFound = false;
10015   for (const OMPClause *C : Clauses) {
10016     if (C->getClauseKind() == OMPC_detach ||
10017         C->getClauseKind() == OMPC_mergeable) {
10018       if (!PrevClause) {
10019         PrevClause = C;
10020       } else if (PrevClause->getClauseKind() != C->getClauseKind()) {
10021         S.Diag(C->getBeginLoc(), diag::err_omp_clauses_mutually_exclusive)
10022             << getOpenMPClauseName(C->getClauseKind())
10023             << getOpenMPClauseName(PrevClause->getClauseKind());
10024         S.Diag(PrevClause->getBeginLoc(), diag::note_omp_previous_clause)
10025             << getOpenMPClauseName(PrevClause->getClauseKind());
10026         ErrorFound = true;
10027       }
10028     }
10029   }
10030   return ErrorFound;
10031 }
10032 
10033 StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
10034                                           Stmt *AStmt, SourceLocation StartLoc,
10035                                           SourceLocation EndLoc) {
10036   if (!AStmt)
10037     return StmtError();
10038 
10039   // OpenMP 5.0, 2.10.1 task Construct
10040   // If a detach clause appears on the directive, then a mergeable clause cannot
10041   // appear on the same directive.
10042   if (checkDetachMergeableClauses(*this, Clauses))
10043     return StmtError();
10044 
10045   auto *CS = cast<CapturedStmt>(AStmt);
10046   // 1.2.2 OpenMP Language Terminology
10047   // Structured block - An executable statement with a single entry at the
10048   // top and a single exit at the bottom.
10049   // The point of exit cannot be a branch out of the structured block.
10050   // longjmp() and throw() must not violate the entry/exit criteria.
10051   CS->getCapturedDecl()->setNothrow();
10052 
10053   setFunctionHasBranchProtectedScope();
10054 
10055   return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
10056                                   DSAStack->isCancelRegion());
10057 }
10058 
10059 StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
10060                                                SourceLocation EndLoc) {
10061   return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
10062 }
10063 
10064 StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
10065                                              SourceLocation EndLoc) {
10066   return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
10067 }
10068 
10069 StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
10070                                               SourceLocation EndLoc) {
10071   return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
10072 }
10073 
10074 StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
10075                                                Stmt *AStmt,
10076                                                SourceLocation StartLoc,
10077                                                SourceLocation EndLoc) {
10078   if (!AStmt)
10079     return StmtError();
10080 
10081   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
10082 
10083   setFunctionHasBranchProtectedScope();
10084 
10085   return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses,
10086                                        AStmt,
10087                                        DSAStack->getTaskgroupReductionRef());
10088 }
10089 
10090 StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
10091                                            SourceLocation StartLoc,
10092                                            SourceLocation EndLoc) {
10093   OMPFlushClause *FC = nullptr;
10094   OMPClause *OrderClause = nullptr;
10095   for (OMPClause *C : Clauses) {
10096     if (C->getClauseKind() == OMPC_flush)
10097       FC = cast<OMPFlushClause>(C);
10098     else
10099       OrderClause = C;
10100   }
10101   OpenMPClauseKind MemOrderKind = OMPC_unknown;
10102   SourceLocation MemOrderLoc;
10103   for (const OMPClause *C : Clauses) {
10104     if (C->getClauseKind() == OMPC_acq_rel ||
10105         C->getClauseKind() == OMPC_acquire ||
10106         C->getClauseKind() == OMPC_release) {
10107       if (MemOrderKind != OMPC_unknown) {
10108         Diag(C->getBeginLoc(), diag::err_omp_several_mem_order_clauses)
10109             << getOpenMPDirectiveName(OMPD_flush) << 1
10110             << SourceRange(C->getBeginLoc(), C->getEndLoc());
10111         Diag(MemOrderLoc, diag::note_omp_previous_mem_order_clause)
10112             << getOpenMPClauseName(MemOrderKind);
10113       } else {
10114         MemOrderKind = C->getClauseKind();
10115         MemOrderLoc = C->getBeginLoc();
10116       }
10117     }
10118   }
10119   if (FC && OrderClause) {
10120     Diag(FC->getLParenLoc(), diag::err_omp_flush_order_clause_and_list)
10121         << getOpenMPClauseName(OrderClause->getClauseKind());
10122     Diag(OrderClause->getBeginLoc(), diag::note_omp_flush_order_clause_here)
10123         << getOpenMPClauseName(OrderClause->getClauseKind());
10124     return StmtError();
10125   }
10126   return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
10127 }
10128 
10129 StmtResult Sema::ActOnOpenMPDepobjDirective(ArrayRef<OMPClause *> Clauses,
10130                                             SourceLocation StartLoc,
10131                                             SourceLocation EndLoc) {
10132   if (Clauses.empty()) {
10133     Diag(StartLoc, diag::err_omp_depobj_expected);
10134     return StmtError();
10135   } else if (Clauses[0]->getClauseKind() != OMPC_depobj) {
10136     Diag(Clauses[0]->getBeginLoc(), diag::err_omp_depobj_expected);
10137     return StmtError();
10138   }
10139   // Only depobj expression and another single clause is allowed.
10140   if (Clauses.size() > 2) {
10141     Diag(Clauses[2]->getBeginLoc(),
10142          diag::err_omp_depobj_single_clause_expected);
10143     return StmtError();
10144   } else if (Clauses.size() < 1) {
10145     Diag(Clauses[0]->getEndLoc(), diag::err_omp_depobj_single_clause_expected);
10146     return StmtError();
10147   }
10148   return OMPDepobjDirective::Create(Context, StartLoc, EndLoc, Clauses);
10149 }
10150 
10151 StmtResult Sema::ActOnOpenMPScanDirective(ArrayRef<OMPClause *> Clauses,
10152                                           SourceLocation StartLoc,
10153                                           SourceLocation EndLoc) {
10154   // Check that exactly one clause is specified.
10155   if (Clauses.size() != 1) {
10156     Diag(Clauses.empty() ? EndLoc : Clauses[1]->getBeginLoc(),
10157          diag::err_omp_scan_single_clause_expected);
10158     return StmtError();
10159   }
10160   // Check that scan directive is used in the scopeof the OpenMP loop body.
10161   if (Scope *S = DSAStack->getCurScope()) {
10162     Scope *ParentS = S->getParent();
10163     if (!ParentS || ParentS->getParent() != ParentS->getBreakParent() ||
10164         !ParentS->getBreakParent()->isOpenMPLoopScope())
10165       return StmtError(Diag(StartLoc, diag::err_omp_orphaned_device_directive)
10166                        << getOpenMPDirectiveName(OMPD_scan) << 5);
10167   }
10168   // Check that only one instance of scan directives is used in the same outer
10169   // region.
10170   if (DSAStack->doesParentHasScanDirective()) {
10171     Diag(StartLoc, diag::err_omp_several_directives_in_region) << "scan";
10172     Diag(DSAStack->getParentScanDirectiveLoc(),
10173          diag::note_omp_previous_directive)
10174         << "scan";
10175     return StmtError();
10176   }
10177   DSAStack->setParentHasScanDirective(StartLoc);
10178   return OMPScanDirective::Create(Context, StartLoc, EndLoc, Clauses);
10179 }
10180 
10181 StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
10182                                              Stmt *AStmt,
10183                                              SourceLocation StartLoc,
10184                                              SourceLocation EndLoc) {
10185   const OMPClause *DependFound = nullptr;
10186   const OMPClause *DependSourceClause = nullptr;
10187   const OMPClause *DependSinkClause = nullptr;
10188   bool ErrorFound = false;
10189   const OMPThreadsClause *TC = nullptr;
10190   const OMPSIMDClause *SC = nullptr;
10191   for (const OMPClause *C : Clauses) {
10192     if (auto *DC = dyn_cast<OMPDependClause>(C)) {
10193       DependFound = C;
10194       if (DC->getDependencyKind() == OMPC_DEPEND_source) {
10195         if (DependSourceClause) {
10196           Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
10197               << getOpenMPDirectiveName(OMPD_ordered)
10198               << getOpenMPClauseName(OMPC_depend) << 2;
10199           ErrorFound = true;
10200         } else {
10201           DependSourceClause = C;
10202         }
10203         if (DependSinkClause) {
10204           Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
10205               << 0;
10206           ErrorFound = true;
10207         }
10208       } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
10209         if (DependSourceClause) {
10210           Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
10211               << 1;
10212           ErrorFound = true;
10213         }
10214         DependSinkClause = C;
10215       }
10216     } else if (C->getClauseKind() == OMPC_threads) {
10217       TC = cast<OMPThreadsClause>(C);
10218     } else if (C->getClauseKind() == OMPC_simd) {
10219       SC = cast<OMPSIMDClause>(C);
10220     }
10221   }
10222   if (!ErrorFound && !SC &&
10223       isOpenMPSimdDirective(DSAStack->getParentDirective())) {
10224     // OpenMP [2.8.1,simd Construct, Restrictions]
10225     // An ordered construct with the simd clause is the only OpenMP construct
10226     // that can appear in the simd region.
10227     Diag(StartLoc, diag::err_omp_prohibited_region_simd)
10228         << (LangOpts.OpenMP >= 50 ? 1 : 0);
10229     ErrorFound = true;
10230   } else if (DependFound && (TC || SC)) {
10231     Diag(DependFound->getBeginLoc(), diag::err_omp_depend_clause_thread_simd)
10232         << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
10233     ErrorFound = true;
10234   } else if (DependFound && !DSAStack->getParentOrderedRegionParam().first) {
10235     Diag(DependFound->getBeginLoc(),
10236          diag::err_omp_ordered_directive_without_param);
10237     ErrorFound = true;
10238   } else if (TC || Clauses.empty()) {
10239     if (const Expr *Param = DSAStack->getParentOrderedRegionParam().first) {
10240       SourceLocation ErrLoc = TC ? TC->getBeginLoc() : StartLoc;
10241       Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
10242           << (TC != nullptr);
10243       Diag(Param->getBeginLoc(), diag::note_omp_ordered_param) << 1;
10244       ErrorFound = true;
10245     }
10246   }
10247   if ((!AStmt && !DependFound) || ErrorFound)
10248     return StmtError();
10249 
10250   // OpenMP 5.0, 2.17.9, ordered Construct, Restrictions.
10251   // During execution of an iteration of a worksharing-loop or a loop nest
10252   // within a worksharing-loop, simd, or worksharing-loop SIMD region, a thread
10253   // must not execute more than one ordered region corresponding to an ordered
10254   // construct without a depend clause.
10255   if (!DependFound) {
10256     if (DSAStack->doesParentHasOrderedDirective()) {
10257       Diag(StartLoc, diag::err_omp_several_directives_in_region) << "ordered";
10258       Diag(DSAStack->getParentOrderedDirectiveLoc(),
10259            diag::note_omp_previous_directive)
10260           << "ordered";
10261       return StmtError();
10262     }
10263     DSAStack->setParentHasOrderedDirective(StartLoc);
10264   }
10265 
10266   if (AStmt) {
10267     assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
10268 
10269     setFunctionHasBranchProtectedScope();
10270   }
10271 
10272   return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
10273 }
10274 
10275 namespace {
10276 /// Helper class for checking expression in 'omp atomic [update]'
10277 /// construct.
10278 class OpenMPAtomicUpdateChecker {
10279   /// Error results for atomic update expressions.
10280   enum ExprAnalysisErrorCode {
10281     /// A statement is not an expression statement.
10282     NotAnExpression,
10283     /// Expression is not builtin binary or unary operation.
10284     NotABinaryOrUnaryExpression,
10285     /// Unary operation is not post-/pre- increment/decrement operation.
10286     NotAnUnaryIncDecExpression,
10287     /// An expression is not of scalar type.
10288     NotAScalarType,
10289     /// A binary operation is not an assignment operation.
10290     NotAnAssignmentOp,
10291     /// RHS part of the binary operation is not a binary expression.
10292     NotABinaryExpression,
10293     /// RHS part is not additive/multiplicative/shift/biwise binary
10294     /// expression.
10295     NotABinaryOperator,
10296     /// RHS binary operation does not have reference to the updated LHS
10297     /// part.
10298     NotAnUpdateExpression,
10299     /// No errors is found.
10300     NoError
10301   };
10302   /// Reference to Sema.
10303   Sema &SemaRef;
10304   /// A location for note diagnostics (when error is found).
10305   SourceLocation NoteLoc;
10306   /// 'x' lvalue part of the source atomic expression.
10307   Expr *X;
10308   /// 'expr' rvalue part of the source atomic expression.
10309   Expr *E;
10310   /// Helper expression of the form
10311   /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
10312   /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
10313   Expr *UpdateExpr;
10314   /// Is 'x' a LHS in a RHS part of full update expression. It is
10315   /// important for non-associative operations.
10316   bool IsXLHSInRHSPart;
10317   BinaryOperatorKind Op;
10318   SourceLocation OpLoc;
10319   /// true if the source expression is a postfix unary operation, false
10320   /// if it is a prefix unary operation.
10321   bool IsPostfixUpdate;
10322 
10323 public:
10324   OpenMPAtomicUpdateChecker(Sema &SemaRef)
10325       : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
10326         IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
10327   /// Check specified statement that it is suitable for 'atomic update'
10328   /// constructs and extract 'x', 'expr' and Operation from the original
10329   /// expression. If DiagId and NoteId == 0, then only check is performed
10330   /// without error notification.
10331   /// \param DiagId Diagnostic which should be emitted if error is found.
10332   /// \param NoteId Diagnostic note for the main error message.
10333   /// \return true if statement is not an update expression, false otherwise.
10334   bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
10335   /// Return the 'x' lvalue part of the source atomic expression.
10336   Expr *getX() const { return X; }
10337   /// Return the 'expr' rvalue part of the source atomic expression.
10338   Expr *getExpr() const { return E; }
10339   /// Return the update expression used in calculation of the updated
10340   /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
10341   /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
10342   Expr *getUpdateExpr() const { return UpdateExpr; }
10343   /// Return true if 'x' is LHS in RHS part of full update expression,
10344   /// false otherwise.
10345   bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
10346 
10347   /// true if the source expression is a postfix unary operation, false
10348   /// if it is a prefix unary operation.
10349   bool isPostfixUpdate() const { return IsPostfixUpdate; }
10350 
10351 private:
10352   bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
10353                             unsigned NoteId = 0);
10354 };
10355 } // namespace
10356 
10357 bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
10358     BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
10359   ExprAnalysisErrorCode ErrorFound = NoError;
10360   SourceLocation ErrorLoc, NoteLoc;
10361   SourceRange ErrorRange, NoteRange;
10362   // Allowed constructs are:
10363   //  x = x binop expr;
10364   //  x = expr binop x;
10365   if (AtomicBinOp->getOpcode() == BO_Assign) {
10366     X = AtomicBinOp->getLHS();
10367     if (const auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
10368             AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
10369       if (AtomicInnerBinOp->isMultiplicativeOp() ||
10370           AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
10371           AtomicInnerBinOp->isBitwiseOp()) {
10372         Op = AtomicInnerBinOp->getOpcode();
10373         OpLoc = AtomicInnerBinOp->getOperatorLoc();
10374         Expr *LHS = AtomicInnerBinOp->getLHS();
10375         Expr *RHS = AtomicInnerBinOp->getRHS();
10376         llvm::FoldingSetNodeID XId, LHSId, RHSId;
10377         X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
10378                                           /*Canonical=*/true);
10379         LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
10380                                             /*Canonical=*/true);
10381         RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
10382                                             /*Canonical=*/true);
10383         if (XId == LHSId) {
10384           E = RHS;
10385           IsXLHSInRHSPart = true;
10386         } else if (XId == RHSId) {
10387           E = LHS;
10388           IsXLHSInRHSPart = false;
10389         } else {
10390           ErrorLoc = AtomicInnerBinOp->getExprLoc();
10391           ErrorRange = AtomicInnerBinOp->getSourceRange();
10392           NoteLoc = X->getExprLoc();
10393           NoteRange = X->getSourceRange();
10394           ErrorFound = NotAnUpdateExpression;
10395         }
10396       } else {
10397         ErrorLoc = AtomicInnerBinOp->getExprLoc();
10398         ErrorRange = AtomicInnerBinOp->getSourceRange();
10399         NoteLoc = AtomicInnerBinOp->getOperatorLoc();
10400         NoteRange = SourceRange(NoteLoc, NoteLoc);
10401         ErrorFound = NotABinaryOperator;
10402       }
10403     } else {
10404       NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
10405       NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
10406       ErrorFound = NotABinaryExpression;
10407     }
10408   } else {
10409     ErrorLoc = AtomicBinOp->getExprLoc();
10410     ErrorRange = AtomicBinOp->getSourceRange();
10411     NoteLoc = AtomicBinOp->getOperatorLoc();
10412     NoteRange = SourceRange(NoteLoc, NoteLoc);
10413     ErrorFound = NotAnAssignmentOp;
10414   }
10415   if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
10416     SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
10417     SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
10418     return true;
10419   }
10420   if (SemaRef.CurContext->isDependentContext())
10421     E = X = UpdateExpr = nullptr;
10422   return ErrorFound != NoError;
10423 }
10424 
10425 bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
10426                                                unsigned NoteId) {
10427   ExprAnalysisErrorCode ErrorFound = NoError;
10428   SourceLocation ErrorLoc, NoteLoc;
10429   SourceRange ErrorRange, NoteRange;
10430   // Allowed constructs are:
10431   //  x++;
10432   //  x--;
10433   //  ++x;
10434   //  --x;
10435   //  x binop= expr;
10436   //  x = x binop expr;
10437   //  x = expr binop x;
10438   if (auto *AtomicBody = dyn_cast<Expr>(S)) {
10439     AtomicBody = AtomicBody->IgnoreParenImpCasts();
10440     if (AtomicBody->getType()->isScalarType() ||
10441         AtomicBody->isInstantiationDependent()) {
10442       if (const auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
10443               AtomicBody->IgnoreParenImpCasts())) {
10444         // Check for Compound Assignment Operation
10445         Op = BinaryOperator::getOpForCompoundAssignment(
10446             AtomicCompAssignOp->getOpcode());
10447         OpLoc = AtomicCompAssignOp->getOperatorLoc();
10448         E = AtomicCompAssignOp->getRHS();
10449         X = AtomicCompAssignOp->getLHS()->IgnoreParens();
10450         IsXLHSInRHSPart = true;
10451       } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
10452                      AtomicBody->IgnoreParenImpCasts())) {
10453         // Check for Binary Operation
10454         if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
10455           return true;
10456       } else if (const auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
10457                      AtomicBody->IgnoreParenImpCasts())) {
10458         // Check for Unary Operation
10459         if (AtomicUnaryOp->isIncrementDecrementOp()) {
10460           IsPostfixUpdate = AtomicUnaryOp->isPostfix();
10461           Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
10462           OpLoc = AtomicUnaryOp->getOperatorLoc();
10463           X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
10464           E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
10465           IsXLHSInRHSPart = true;
10466         } else {
10467           ErrorFound = NotAnUnaryIncDecExpression;
10468           ErrorLoc = AtomicUnaryOp->getExprLoc();
10469           ErrorRange = AtomicUnaryOp->getSourceRange();
10470           NoteLoc = AtomicUnaryOp->getOperatorLoc();
10471           NoteRange = SourceRange(NoteLoc, NoteLoc);
10472         }
10473       } else if (!AtomicBody->isInstantiationDependent()) {
10474         ErrorFound = NotABinaryOrUnaryExpression;
10475         NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
10476         NoteRange = ErrorRange = AtomicBody->getSourceRange();
10477       }
10478     } else {
10479       ErrorFound = NotAScalarType;
10480       NoteLoc = ErrorLoc = AtomicBody->getBeginLoc();
10481       NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
10482     }
10483   } else {
10484     ErrorFound = NotAnExpression;
10485     NoteLoc = ErrorLoc = S->getBeginLoc();
10486     NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
10487   }
10488   if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
10489     SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
10490     SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
10491     return true;
10492   }
10493   if (SemaRef.CurContext->isDependentContext())
10494     E = X = UpdateExpr = nullptr;
10495   if (ErrorFound == NoError && E && X) {
10496     // Build an update expression of form 'OpaqueValueExpr(x) binop
10497     // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
10498     // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
10499     auto *OVEX = new (SemaRef.getASTContext())
10500         OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
10501     auto *OVEExpr = new (SemaRef.getASTContext())
10502         OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
10503     ExprResult Update =
10504         SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
10505                                    IsXLHSInRHSPart ? OVEExpr : OVEX);
10506     if (Update.isInvalid())
10507       return true;
10508     Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
10509                                                Sema::AA_Casting);
10510     if (Update.isInvalid())
10511       return true;
10512     UpdateExpr = Update.get();
10513   }
10514   return ErrorFound != NoError;
10515 }
10516 
10517 StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
10518                                             Stmt *AStmt,
10519                                             SourceLocation StartLoc,
10520                                             SourceLocation EndLoc) {
10521   // Register location of the first atomic directive.
10522   DSAStack->addAtomicDirectiveLoc(StartLoc);
10523   if (!AStmt)
10524     return StmtError();
10525 
10526   // 1.2.2 OpenMP Language Terminology
10527   // Structured block - An executable statement with a single entry at the
10528   // top and a single exit at the bottom.
10529   // The point of exit cannot be a branch out of the structured block.
10530   // longjmp() and throw() must not violate the entry/exit criteria.
10531   OpenMPClauseKind AtomicKind = OMPC_unknown;
10532   SourceLocation AtomicKindLoc;
10533   OpenMPClauseKind MemOrderKind = OMPC_unknown;
10534   SourceLocation MemOrderLoc;
10535   for (const OMPClause *C : Clauses) {
10536     if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
10537         C->getClauseKind() == OMPC_update ||
10538         C->getClauseKind() == OMPC_capture) {
10539       if (AtomicKind != OMPC_unknown) {
10540         Diag(C->getBeginLoc(), diag::err_omp_atomic_several_clauses)
10541             << SourceRange(C->getBeginLoc(), C->getEndLoc());
10542         Diag(AtomicKindLoc, diag::note_omp_previous_mem_order_clause)
10543             << getOpenMPClauseName(AtomicKind);
10544       } else {
10545         AtomicKind = C->getClauseKind();
10546         AtomicKindLoc = C->getBeginLoc();
10547       }
10548     }
10549     if (C->getClauseKind() == OMPC_seq_cst ||
10550         C->getClauseKind() == OMPC_acq_rel ||
10551         C->getClauseKind() == OMPC_acquire ||
10552         C->getClauseKind() == OMPC_release ||
10553         C->getClauseKind() == OMPC_relaxed) {
10554       if (MemOrderKind != OMPC_unknown) {
10555         Diag(C->getBeginLoc(), diag::err_omp_several_mem_order_clauses)
10556             << getOpenMPDirectiveName(OMPD_atomic) << 0
10557             << SourceRange(C->getBeginLoc(), C->getEndLoc());
10558         Diag(MemOrderLoc, diag::note_omp_previous_mem_order_clause)
10559             << getOpenMPClauseName(MemOrderKind);
10560       } else {
10561         MemOrderKind = C->getClauseKind();
10562         MemOrderLoc = C->getBeginLoc();
10563       }
10564     }
10565   }
10566   // OpenMP 5.0, 2.17.7 atomic Construct, Restrictions
10567   // If atomic-clause is read then memory-order-clause must not be acq_rel or
10568   // release.
10569   // If atomic-clause is write then memory-order-clause must not be acq_rel or
10570   // acquire.
10571   // If atomic-clause is update or not present then memory-order-clause must not
10572   // be acq_rel or acquire.
10573   if ((AtomicKind == OMPC_read &&
10574        (MemOrderKind == OMPC_acq_rel || MemOrderKind == OMPC_release)) ||
10575       ((AtomicKind == OMPC_write || AtomicKind == OMPC_update ||
10576         AtomicKind == OMPC_unknown) &&
10577        (MemOrderKind == OMPC_acq_rel || MemOrderKind == OMPC_acquire))) {
10578     SourceLocation Loc = AtomicKindLoc;
10579     if (AtomicKind == OMPC_unknown)
10580       Loc = StartLoc;
10581     Diag(Loc, diag::err_omp_atomic_incompatible_mem_order_clause)
10582         << getOpenMPClauseName(AtomicKind)
10583         << (AtomicKind == OMPC_unknown ? 1 : 0)
10584         << getOpenMPClauseName(MemOrderKind);
10585     Diag(MemOrderLoc, diag::note_omp_previous_mem_order_clause)
10586         << getOpenMPClauseName(MemOrderKind);
10587   }
10588 
10589   Stmt *Body = AStmt;
10590   if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
10591     Body = EWC->getSubExpr();
10592 
10593   Expr *X = nullptr;
10594   Expr *V = nullptr;
10595   Expr *E = nullptr;
10596   Expr *UE = nullptr;
10597   bool IsXLHSInRHSPart = false;
10598   bool IsPostfixUpdate = false;
10599   // OpenMP [2.12.6, atomic Construct]
10600   // In the next expressions:
10601   // * x and v (as applicable) are both l-value expressions with scalar type.
10602   // * During the execution of an atomic region, multiple syntactic
10603   // occurrences of x must designate the same storage location.
10604   // * Neither of v and expr (as applicable) may access the storage location
10605   // designated by x.
10606   // * Neither of x and expr (as applicable) may access the storage location
10607   // designated by v.
10608   // * expr is an expression with scalar type.
10609   // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
10610   // * binop, binop=, ++, and -- are not overloaded operators.
10611   // * The expression x binop expr must be numerically equivalent to x binop
10612   // (expr). This requirement is satisfied if the operators in expr have
10613   // precedence greater than binop, or by using parentheses around expr or
10614   // subexpressions of expr.
10615   // * The expression expr binop x must be numerically equivalent to (expr)
10616   // binop x. This requirement is satisfied if the operators in expr have
10617   // precedence equal to or greater than binop, or by using parentheses around
10618   // expr or subexpressions of expr.
10619   // * For forms that allow multiple occurrences of x, the number of times
10620   // that x is evaluated is unspecified.
10621   if (AtomicKind == OMPC_read) {
10622     enum {
10623       NotAnExpression,
10624       NotAnAssignmentOp,
10625       NotAScalarType,
10626       NotAnLValue,
10627       NoError
10628     } ErrorFound = NoError;
10629     SourceLocation ErrorLoc, NoteLoc;
10630     SourceRange ErrorRange, NoteRange;
10631     // If clause is read:
10632     //  v = x;
10633     if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
10634       const auto *AtomicBinOp =
10635           dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
10636       if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
10637         X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
10638         V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
10639         if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
10640             (V->isInstantiationDependent() || V->getType()->isScalarType())) {
10641           if (!X->isLValue() || !V->isLValue()) {
10642             const Expr *NotLValueExpr = X->isLValue() ? V : X;
10643             ErrorFound = NotAnLValue;
10644             ErrorLoc = AtomicBinOp->getExprLoc();
10645             ErrorRange = AtomicBinOp->getSourceRange();
10646             NoteLoc = NotLValueExpr->getExprLoc();
10647             NoteRange = NotLValueExpr->getSourceRange();
10648           }
10649         } else if (!X->isInstantiationDependent() ||
10650                    !V->isInstantiationDependent()) {
10651           const Expr *NotScalarExpr =
10652               (X->isInstantiationDependent() || X->getType()->isScalarType())
10653                   ? V
10654                   : X;
10655           ErrorFound = NotAScalarType;
10656           ErrorLoc = AtomicBinOp->getExprLoc();
10657           ErrorRange = AtomicBinOp->getSourceRange();
10658           NoteLoc = NotScalarExpr->getExprLoc();
10659           NoteRange = NotScalarExpr->getSourceRange();
10660         }
10661       } else if (!AtomicBody->isInstantiationDependent()) {
10662         ErrorFound = NotAnAssignmentOp;
10663         ErrorLoc = AtomicBody->getExprLoc();
10664         ErrorRange = AtomicBody->getSourceRange();
10665         NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
10666                               : AtomicBody->getExprLoc();
10667         NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
10668                                 : AtomicBody->getSourceRange();
10669       }
10670     } else {
10671       ErrorFound = NotAnExpression;
10672       NoteLoc = ErrorLoc = Body->getBeginLoc();
10673       NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
10674     }
10675     if (ErrorFound != NoError) {
10676       Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
10677           << ErrorRange;
10678       Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
10679                                                       << NoteRange;
10680       return StmtError();
10681     }
10682     if (CurContext->isDependentContext())
10683       V = X = nullptr;
10684   } else if (AtomicKind == OMPC_write) {
10685     enum {
10686       NotAnExpression,
10687       NotAnAssignmentOp,
10688       NotAScalarType,
10689       NotAnLValue,
10690       NoError
10691     } ErrorFound = NoError;
10692     SourceLocation ErrorLoc, NoteLoc;
10693     SourceRange ErrorRange, NoteRange;
10694     // If clause is write:
10695     //  x = expr;
10696     if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
10697       const auto *AtomicBinOp =
10698           dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
10699       if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
10700         X = AtomicBinOp->getLHS();
10701         E = AtomicBinOp->getRHS();
10702         if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
10703             (E->isInstantiationDependent() || E->getType()->isScalarType())) {
10704           if (!X->isLValue()) {
10705             ErrorFound = NotAnLValue;
10706             ErrorLoc = AtomicBinOp->getExprLoc();
10707             ErrorRange = AtomicBinOp->getSourceRange();
10708             NoteLoc = X->getExprLoc();
10709             NoteRange = X->getSourceRange();
10710           }
10711         } else if (!X->isInstantiationDependent() ||
10712                    !E->isInstantiationDependent()) {
10713           const Expr *NotScalarExpr =
10714               (X->isInstantiationDependent() || X->getType()->isScalarType())
10715                   ? E
10716                   : X;
10717           ErrorFound = NotAScalarType;
10718           ErrorLoc = AtomicBinOp->getExprLoc();
10719           ErrorRange = AtomicBinOp->getSourceRange();
10720           NoteLoc = NotScalarExpr->getExprLoc();
10721           NoteRange = NotScalarExpr->getSourceRange();
10722         }
10723       } else if (!AtomicBody->isInstantiationDependent()) {
10724         ErrorFound = NotAnAssignmentOp;
10725         ErrorLoc = AtomicBody->getExprLoc();
10726         ErrorRange = AtomicBody->getSourceRange();
10727         NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
10728                               : AtomicBody->getExprLoc();
10729         NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
10730                                 : AtomicBody->getSourceRange();
10731       }
10732     } else {
10733       ErrorFound = NotAnExpression;
10734       NoteLoc = ErrorLoc = Body->getBeginLoc();
10735       NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
10736     }
10737     if (ErrorFound != NoError) {
10738       Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
10739           << ErrorRange;
10740       Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
10741                                                       << NoteRange;
10742       return StmtError();
10743     }
10744     if (CurContext->isDependentContext())
10745       E = X = nullptr;
10746   } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
10747     // If clause is update:
10748     //  x++;
10749     //  x--;
10750     //  ++x;
10751     //  --x;
10752     //  x binop= expr;
10753     //  x = x binop expr;
10754     //  x = expr binop x;
10755     OpenMPAtomicUpdateChecker Checker(*this);
10756     if (Checker.checkStatement(
10757             Body, (AtomicKind == OMPC_update)
10758                       ? diag::err_omp_atomic_update_not_expression_statement
10759                       : diag::err_omp_atomic_not_expression_statement,
10760             diag::note_omp_atomic_update))
10761       return StmtError();
10762     if (!CurContext->isDependentContext()) {
10763       E = Checker.getExpr();
10764       X = Checker.getX();
10765       UE = Checker.getUpdateExpr();
10766       IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
10767     }
10768   } else if (AtomicKind == OMPC_capture) {
10769     enum {
10770       NotAnAssignmentOp,
10771       NotACompoundStatement,
10772       NotTwoSubstatements,
10773       NotASpecificExpression,
10774       NoError
10775     } ErrorFound = NoError;
10776     SourceLocation ErrorLoc, NoteLoc;
10777     SourceRange ErrorRange, NoteRange;
10778     if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
10779       // If clause is a capture:
10780       //  v = x++;
10781       //  v = x--;
10782       //  v = ++x;
10783       //  v = --x;
10784       //  v = x binop= expr;
10785       //  v = x = x binop expr;
10786       //  v = x = expr binop x;
10787       const auto *AtomicBinOp =
10788           dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
10789       if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
10790         V = AtomicBinOp->getLHS();
10791         Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
10792         OpenMPAtomicUpdateChecker Checker(*this);
10793         if (Checker.checkStatement(
10794                 Body, diag::err_omp_atomic_capture_not_expression_statement,
10795                 diag::note_omp_atomic_update))
10796           return StmtError();
10797         E = Checker.getExpr();
10798         X = Checker.getX();
10799         UE = Checker.getUpdateExpr();
10800         IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
10801         IsPostfixUpdate = Checker.isPostfixUpdate();
10802       } else if (!AtomicBody->isInstantiationDependent()) {
10803         ErrorLoc = AtomicBody->getExprLoc();
10804         ErrorRange = AtomicBody->getSourceRange();
10805         NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
10806                               : AtomicBody->getExprLoc();
10807         NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
10808                                 : AtomicBody->getSourceRange();
10809         ErrorFound = NotAnAssignmentOp;
10810       }
10811       if (ErrorFound != NoError) {
10812         Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
10813             << ErrorRange;
10814         Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
10815         return StmtError();
10816       }
10817       if (CurContext->isDependentContext())
10818         UE = V = E = X = nullptr;
10819     } else {
10820       // If clause is a capture:
10821       //  { v = x; x = expr; }
10822       //  { v = x; x++; }
10823       //  { v = x; x--; }
10824       //  { v = x; ++x; }
10825       //  { v = x; --x; }
10826       //  { v = x; x binop= expr; }
10827       //  { v = x; x = x binop expr; }
10828       //  { v = x; x = expr binop x; }
10829       //  { x++; v = x; }
10830       //  { x--; v = x; }
10831       //  { ++x; v = x; }
10832       //  { --x; v = x; }
10833       //  { x binop= expr; v = x; }
10834       //  { x = x binop expr; v = x; }
10835       //  { x = expr binop x; v = x; }
10836       if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
10837         // Check that this is { expr1; expr2; }
10838         if (CS->size() == 2) {
10839           Stmt *First = CS->body_front();
10840           Stmt *Second = CS->body_back();
10841           if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
10842             First = EWC->getSubExpr()->IgnoreParenImpCasts();
10843           if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
10844             Second = EWC->getSubExpr()->IgnoreParenImpCasts();
10845           // Need to find what subexpression is 'v' and what is 'x'.
10846           OpenMPAtomicUpdateChecker Checker(*this);
10847           bool IsUpdateExprFound = !Checker.checkStatement(Second);
10848           BinaryOperator *BinOp = nullptr;
10849           if (IsUpdateExprFound) {
10850             BinOp = dyn_cast<BinaryOperator>(First);
10851             IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
10852           }
10853           if (IsUpdateExprFound && !CurContext->isDependentContext()) {
10854             //  { v = x; x++; }
10855             //  { v = x; x--; }
10856             //  { v = x; ++x; }
10857             //  { v = x; --x; }
10858             //  { v = x; x binop= expr; }
10859             //  { v = x; x = x binop expr; }
10860             //  { v = x; x = expr binop x; }
10861             // Check that the first expression has form v = x.
10862             Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
10863             llvm::FoldingSetNodeID XId, PossibleXId;
10864             Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
10865             PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
10866             IsUpdateExprFound = XId == PossibleXId;
10867             if (IsUpdateExprFound) {
10868               V = BinOp->getLHS();
10869               X = Checker.getX();
10870               E = Checker.getExpr();
10871               UE = Checker.getUpdateExpr();
10872               IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
10873               IsPostfixUpdate = true;
10874             }
10875           }
10876           if (!IsUpdateExprFound) {
10877             IsUpdateExprFound = !Checker.checkStatement(First);
10878             BinOp = nullptr;
10879             if (IsUpdateExprFound) {
10880               BinOp = dyn_cast<BinaryOperator>(Second);
10881               IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
10882             }
10883             if (IsUpdateExprFound && !CurContext->isDependentContext()) {
10884               //  { x++; v = x; }
10885               //  { x--; v = x; }
10886               //  { ++x; v = x; }
10887               //  { --x; v = x; }
10888               //  { x binop= expr; v = x; }
10889               //  { x = x binop expr; v = x; }
10890               //  { x = expr binop x; v = x; }
10891               // Check that the second expression has form v = x.
10892               Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
10893               llvm::FoldingSetNodeID XId, PossibleXId;
10894               Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
10895               PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
10896               IsUpdateExprFound = XId == PossibleXId;
10897               if (IsUpdateExprFound) {
10898                 V = BinOp->getLHS();
10899                 X = Checker.getX();
10900                 E = Checker.getExpr();
10901                 UE = Checker.getUpdateExpr();
10902                 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
10903                 IsPostfixUpdate = false;
10904               }
10905             }
10906           }
10907           if (!IsUpdateExprFound) {
10908             //  { v = x; x = expr; }
10909             auto *FirstExpr = dyn_cast<Expr>(First);
10910             auto *SecondExpr = dyn_cast<Expr>(Second);
10911             if (!FirstExpr || !SecondExpr ||
10912                 !(FirstExpr->isInstantiationDependent() ||
10913                   SecondExpr->isInstantiationDependent())) {
10914               auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
10915               if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
10916                 ErrorFound = NotAnAssignmentOp;
10917                 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
10918                                                 : First->getBeginLoc();
10919                 NoteRange = ErrorRange = FirstBinOp
10920                                              ? FirstBinOp->getSourceRange()
10921                                              : SourceRange(ErrorLoc, ErrorLoc);
10922               } else {
10923                 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
10924                 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
10925                   ErrorFound = NotAnAssignmentOp;
10926                   NoteLoc = ErrorLoc = SecondBinOp
10927                                            ? SecondBinOp->getOperatorLoc()
10928                                            : Second->getBeginLoc();
10929                   NoteRange = ErrorRange =
10930                       SecondBinOp ? SecondBinOp->getSourceRange()
10931                                   : SourceRange(ErrorLoc, ErrorLoc);
10932                 } else {
10933                   Expr *PossibleXRHSInFirst =
10934                       FirstBinOp->getRHS()->IgnoreParenImpCasts();
10935                   Expr *PossibleXLHSInSecond =
10936                       SecondBinOp->getLHS()->IgnoreParenImpCasts();
10937                   llvm::FoldingSetNodeID X1Id, X2Id;
10938                   PossibleXRHSInFirst->Profile(X1Id, Context,
10939                                                /*Canonical=*/true);
10940                   PossibleXLHSInSecond->Profile(X2Id, Context,
10941                                                 /*Canonical=*/true);
10942                   IsUpdateExprFound = X1Id == X2Id;
10943                   if (IsUpdateExprFound) {
10944                     V = FirstBinOp->getLHS();
10945                     X = SecondBinOp->getLHS();
10946                     E = SecondBinOp->getRHS();
10947                     UE = nullptr;
10948                     IsXLHSInRHSPart = false;
10949                     IsPostfixUpdate = true;
10950                   } else {
10951                     ErrorFound = NotASpecificExpression;
10952                     ErrorLoc = FirstBinOp->getExprLoc();
10953                     ErrorRange = FirstBinOp->getSourceRange();
10954                     NoteLoc = SecondBinOp->getLHS()->getExprLoc();
10955                     NoteRange = SecondBinOp->getRHS()->getSourceRange();
10956                   }
10957                 }
10958               }
10959             }
10960           }
10961         } else {
10962           NoteLoc = ErrorLoc = Body->getBeginLoc();
10963           NoteRange = ErrorRange =
10964               SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
10965           ErrorFound = NotTwoSubstatements;
10966         }
10967       } else {
10968         NoteLoc = ErrorLoc = Body->getBeginLoc();
10969         NoteRange = ErrorRange =
10970             SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
10971         ErrorFound = NotACompoundStatement;
10972       }
10973       if (ErrorFound != NoError) {
10974         Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
10975             << ErrorRange;
10976         Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
10977         return StmtError();
10978       }
10979       if (CurContext->isDependentContext())
10980         UE = V = E = X = nullptr;
10981     }
10982   }
10983 
10984   setFunctionHasBranchProtectedScope();
10985 
10986   return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
10987                                     X, V, E, UE, IsXLHSInRHSPart,
10988                                     IsPostfixUpdate);
10989 }
10990 
10991 StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
10992                                             Stmt *AStmt,
10993                                             SourceLocation StartLoc,
10994                                             SourceLocation EndLoc) {
10995   if (!AStmt)
10996     return StmtError();
10997 
10998   auto *CS = cast<CapturedStmt>(AStmt);
10999   // 1.2.2 OpenMP Language Terminology
11000   // Structured block - An executable statement with a single entry at the
11001   // top and a single exit at the bottom.
11002   // The point of exit cannot be a branch out of the structured block.
11003   // longjmp() and throw() must not violate the entry/exit criteria.
11004   CS->getCapturedDecl()->setNothrow();
11005   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target);
11006        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11007     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11008     // 1.2.2 OpenMP Language Terminology
11009     // Structured block - An executable statement with a single entry at the
11010     // top and a single exit at the bottom.
11011     // The point of exit cannot be a branch out of the structured block.
11012     // longjmp() and throw() must not violate the entry/exit criteria.
11013     CS->getCapturedDecl()->setNothrow();
11014   }
11015 
11016   // OpenMP [2.16, Nesting of Regions]
11017   // If specified, a teams construct must be contained within a target
11018   // construct. That target construct must contain no statements or directives
11019   // outside of the teams construct.
11020   if (DSAStack->hasInnerTeamsRegion()) {
11021     const Stmt *S = CS->IgnoreContainers(/*IgnoreCaptured=*/true);
11022     bool OMPTeamsFound = true;
11023     if (const auto *CS = dyn_cast<CompoundStmt>(S)) {
11024       auto I = CS->body_begin();
11025       while (I != CS->body_end()) {
11026         const auto *OED = dyn_cast<OMPExecutableDirective>(*I);
11027         if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind()) ||
11028             OMPTeamsFound) {
11029 
11030           OMPTeamsFound = false;
11031           break;
11032         }
11033         ++I;
11034       }
11035       assert(I != CS->body_end() && "Not found statement");
11036       S = *I;
11037     } else {
11038       const auto *OED = dyn_cast<OMPExecutableDirective>(S);
11039       OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
11040     }
11041     if (!OMPTeamsFound) {
11042       Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
11043       Diag(DSAStack->getInnerTeamsRegionLoc(),
11044            diag::note_omp_nested_teams_construct_here);
11045       Diag(S->getBeginLoc(), diag::note_omp_nested_statement_here)
11046           << isa<OMPExecutableDirective>(S);
11047       return StmtError();
11048     }
11049   }
11050 
11051   setFunctionHasBranchProtectedScope();
11052 
11053   return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
11054 }
11055 
11056 StmtResult
11057 Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
11058                                          Stmt *AStmt, SourceLocation StartLoc,
11059                                          SourceLocation EndLoc) {
11060   if (!AStmt)
11061     return StmtError();
11062 
11063   auto *CS = cast<CapturedStmt>(AStmt);
11064   // 1.2.2 OpenMP Language Terminology
11065   // Structured block - An executable statement with a single entry at the
11066   // top and a single exit at the bottom.
11067   // The point of exit cannot be a branch out of the structured block.
11068   // longjmp() and throw() must not violate the entry/exit criteria.
11069   CS->getCapturedDecl()->setNothrow();
11070   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel);
11071        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11072     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11073     // 1.2.2 OpenMP Language Terminology
11074     // Structured block - An executable statement with a single entry at the
11075     // top and a single exit at the bottom.
11076     // The point of exit cannot be a branch out of the structured block.
11077     // longjmp() and throw() must not violate the entry/exit criteria.
11078     CS->getCapturedDecl()->setNothrow();
11079   }
11080 
11081   setFunctionHasBranchProtectedScope();
11082 
11083   return OMPTargetParallelDirective::Create(
11084       Context, StartLoc, EndLoc, Clauses, AStmt,
11085       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
11086 }
11087 
11088 StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
11089     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11090     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11091   if (!AStmt)
11092     return StmtError();
11093 
11094   auto *CS = cast<CapturedStmt>(AStmt);
11095   // 1.2.2 OpenMP Language Terminology
11096   // Structured block - An executable statement with a single entry at the
11097   // top and a single exit at the bottom.
11098   // The point of exit cannot be a branch out of the structured block.
11099   // longjmp() and throw() must not violate the entry/exit criteria.
11100   CS->getCapturedDecl()->setNothrow();
11101   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
11102        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11103     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11104     // 1.2.2 OpenMP Language Terminology
11105     // Structured block - An executable statement with a single entry at the
11106     // top and a single exit at the bottom.
11107     // The point of exit cannot be a branch out of the structured block.
11108     // longjmp() and throw() must not violate the entry/exit criteria.
11109     CS->getCapturedDecl()->setNothrow();
11110   }
11111 
11112   OMPLoopBasedDirective::HelperExprs B;
11113   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
11114   // define the nested loops number.
11115   unsigned NestedLoopCount =
11116       checkOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
11117                       getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
11118                       VarsWithImplicitDSA, B);
11119   if (NestedLoopCount == 0)
11120     return StmtError();
11121 
11122   assert((CurContext->isDependentContext() || B.builtAll()) &&
11123          "omp target parallel for loop exprs were not built");
11124 
11125   if (!CurContext->isDependentContext()) {
11126     // Finalize the clauses that need pre-built expressions for CodeGen.
11127     for (OMPClause *C : Clauses) {
11128       if (auto *LC = dyn_cast<OMPLinearClause>(C))
11129         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
11130                                      B.NumIterations, *this, CurScope,
11131                                      DSAStack))
11132           return StmtError();
11133     }
11134   }
11135 
11136   setFunctionHasBranchProtectedScope();
11137   return OMPTargetParallelForDirective::Create(
11138       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
11139       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
11140 }
11141 
11142 /// Check for existence of a map clause in the list of clauses.
11143 static bool hasClauses(ArrayRef<OMPClause *> Clauses,
11144                        const OpenMPClauseKind K) {
11145   return llvm::any_of(
11146       Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; });
11147 }
11148 
11149 template <typename... Params>
11150 static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K,
11151                        const Params... ClauseTypes) {
11152   return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...);
11153 }
11154 
11155 StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
11156                                                 Stmt *AStmt,
11157                                                 SourceLocation StartLoc,
11158                                                 SourceLocation EndLoc) {
11159   if (!AStmt)
11160     return StmtError();
11161 
11162   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
11163 
11164   // OpenMP [2.12.2, target data Construct, Restrictions]
11165   // At least one map, use_device_addr or use_device_ptr clause must appear on
11166   // the directive.
11167   if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr) &&
11168       (LangOpts.OpenMP < 50 || !hasClauses(Clauses, OMPC_use_device_addr))) {
11169     StringRef Expected;
11170     if (LangOpts.OpenMP < 50)
11171       Expected = "'map' or 'use_device_ptr'";
11172     else
11173       Expected = "'map', 'use_device_ptr', or 'use_device_addr'";
11174     Diag(StartLoc, diag::err_omp_no_clause_for_directive)
11175         << Expected << getOpenMPDirectiveName(OMPD_target_data);
11176     return StmtError();
11177   }
11178 
11179   setFunctionHasBranchProtectedScope();
11180 
11181   return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
11182                                         AStmt);
11183 }
11184 
11185 StmtResult
11186 Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
11187                                           SourceLocation StartLoc,
11188                                           SourceLocation EndLoc, Stmt *AStmt) {
11189   if (!AStmt)
11190     return StmtError();
11191 
11192   auto *CS = cast<CapturedStmt>(AStmt);
11193   // 1.2.2 OpenMP Language Terminology
11194   // Structured block - An executable statement with a single entry at the
11195   // top and a single exit at the bottom.
11196   // The point of exit cannot be a branch out of the structured block.
11197   // longjmp() and throw() must not violate the entry/exit criteria.
11198   CS->getCapturedDecl()->setNothrow();
11199   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_enter_data);
11200        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11201     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11202     // 1.2.2 OpenMP Language Terminology
11203     // Structured block - An executable statement with a single entry at the
11204     // top and a single exit at the bottom.
11205     // The point of exit cannot be a branch out of the structured block.
11206     // longjmp() and throw() must not violate the entry/exit criteria.
11207     CS->getCapturedDecl()->setNothrow();
11208   }
11209 
11210   // OpenMP [2.10.2, Restrictions, p. 99]
11211   // At least one map clause must appear on the directive.
11212   if (!hasClauses(Clauses, OMPC_map)) {
11213     Diag(StartLoc, diag::err_omp_no_clause_for_directive)
11214         << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data);
11215     return StmtError();
11216   }
11217 
11218   return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
11219                                              AStmt);
11220 }
11221 
11222 StmtResult
11223 Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
11224                                          SourceLocation StartLoc,
11225                                          SourceLocation EndLoc, Stmt *AStmt) {
11226   if (!AStmt)
11227     return StmtError();
11228 
11229   auto *CS = cast<CapturedStmt>(AStmt);
11230   // 1.2.2 OpenMP Language Terminology
11231   // Structured block - An executable statement with a single entry at the
11232   // top and a single exit at the bottom.
11233   // The point of exit cannot be a branch out of the structured block.
11234   // longjmp() and throw() must not violate the entry/exit criteria.
11235   CS->getCapturedDecl()->setNothrow();
11236   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_exit_data);
11237        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11238     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11239     // 1.2.2 OpenMP Language Terminology
11240     // Structured block - An executable statement with a single entry at the
11241     // top and a single exit at the bottom.
11242     // The point of exit cannot be a branch out of the structured block.
11243     // longjmp() and throw() must not violate the entry/exit criteria.
11244     CS->getCapturedDecl()->setNothrow();
11245   }
11246 
11247   // OpenMP [2.10.3, Restrictions, p. 102]
11248   // At least one map clause must appear on the directive.
11249   if (!hasClauses(Clauses, OMPC_map)) {
11250     Diag(StartLoc, diag::err_omp_no_clause_for_directive)
11251         << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data);
11252     return StmtError();
11253   }
11254 
11255   return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
11256                                             AStmt);
11257 }
11258 
11259 StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
11260                                                   SourceLocation StartLoc,
11261                                                   SourceLocation EndLoc,
11262                                                   Stmt *AStmt) {
11263   if (!AStmt)
11264     return StmtError();
11265 
11266   auto *CS = cast<CapturedStmt>(AStmt);
11267   // 1.2.2 OpenMP Language Terminology
11268   // Structured block - An executable statement with a single entry at the
11269   // top and a single exit at the bottom.
11270   // The point of exit cannot be a branch out of the structured block.
11271   // longjmp() and throw() must not violate the entry/exit criteria.
11272   CS->getCapturedDecl()->setNothrow();
11273   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_update);
11274        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11275     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11276     // 1.2.2 OpenMP Language Terminology
11277     // Structured block - An executable statement with a single entry at the
11278     // top and a single exit at the bottom.
11279     // The point of exit cannot be a branch out of the structured block.
11280     // longjmp() and throw() must not violate the entry/exit criteria.
11281     CS->getCapturedDecl()->setNothrow();
11282   }
11283 
11284   if (!hasClauses(Clauses, OMPC_to, OMPC_from)) {
11285     Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
11286     return StmtError();
11287   }
11288   return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses,
11289                                           AStmt);
11290 }
11291 
11292 StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
11293                                            Stmt *AStmt, SourceLocation StartLoc,
11294                                            SourceLocation EndLoc) {
11295   if (!AStmt)
11296     return StmtError();
11297 
11298   auto *CS = cast<CapturedStmt>(AStmt);
11299   // 1.2.2 OpenMP Language Terminology
11300   // Structured block - An executable statement with a single entry at the
11301   // top and a single exit at the bottom.
11302   // The point of exit cannot be a branch out of the structured block.
11303   // longjmp() and throw() must not violate the entry/exit criteria.
11304   CS->getCapturedDecl()->setNothrow();
11305 
11306   setFunctionHasBranchProtectedScope();
11307 
11308   DSAStack->setParentTeamsRegionLoc(StartLoc);
11309 
11310   return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
11311 }
11312 
11313 StmtResult
11314 Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
11315                                             SourceLocation EndLoc,
11316                                             OpenMPDirectiveKind CancelRegion) {
11317   if (DSAStack->isParentNowaitRegion()) {
11318     Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
11319     return StmtError();
11320   }
11321   if (DSAStack->isParentOrderedRegion()) {
11322     Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
11323     return StmtError();
11324   }
11325   return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
11326                                                CancelRegion);
11327 }
11328 
11329 StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
11330                                             SourceLocation StartLoc,
11331                                             SourceLocation EndLoc,
11332                                             OpenMPDirectiveKind CancelRegion) {
11333   if (DSAStack->isParentNowaitRegion()) {
11334     Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
11335     return StmtError();
11336   }
11337   if (DSAStack->isParentOrderedRegion()) {
11338     Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
11339     return StmtError();
11340   }
11341   DSAStack->setParentCancelRegion(/*Cancel=*/true);
11342   return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
11343                                     CancelRegion);
11344 }
11345 
11346 static bool checkGrainsizeNumTasksClauses(Sema &S,
11347                                           ArrayRef<OMPClause *> Clauses) {
11348   const OMPClause *PrevClause = nullptr;
11349   bool ErrorFound = false;
11350   for (const OMPClause *C : Clauses) {
11351     if (C->getClauseKind() == OMPC_grainsize ||
11352         C->getClauseKind() == OMPC_num_tasks) {
11353       if (!PrevClause)
11354         PrevClause = C;
11355       else if (PrevClause->getClauseKind() != C->getClauseKind()) {
11356         S.Diag(C->getBeginLoc(), diag::err_omp_clauses_mutually_exclusive)
11357             << getOpenMPClauseName(C->getClauseKind())
11358             << getOpenMPClauseName(PrevClause->getClauseKind());
11359         S.Diag(PrevClause->getBeginLoc(), diag::note_omp_previous_clause)
11360             << getOpenMPClauseName(PrevClause->getClauseKind());
11361         ErrorFound = true;
11362       }
11363     }
11364   }
11365   return ErrorFound;
11366 }
11367 
11368 static bool checkReductionClauseWithNogroup(Sema &S,
11369                                             ArrayRef<OMPClause *> Clauses) {
11370   const OMPClause *ReductionClause = nullptr;
11371   const OMPClause *NogroupClause = nullptr;
11372   for (const OMPClause *C : Clauses) {
11373     if (C->getClauseKind() == OMPC_reduction) {
11374       ReductionClause = C;
11375       if (NogroupClause)
11376         break;
11377       continue;
11378     }
11379     if (C->getClauseKind() == OMPC_nogroup) {
11380       NogroupClause = C;
11381       if (ReductionClause)
11382         break;
11383       continue;
11384     }
11385   }
11386   if (ReductionClause && NogroupClause) {
11387     S.Diag(ReductionClause->getBeginLoc(), diag::err_omp_reduction_with_nogroup)
11388         << SourceRange(NogroupClause->getBeginLoc(),
11389                        NogroupClause->getEndLoc());
11390     return true;
11391   }
11392   return false;
11393 }
11394 
11395 StmtResult Sema::ActOnOpenMPTaskLoopDirective(
11396     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11397     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11398   if (!AStmt)
11399     return StmtError();
11400 
11401   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
11402   OMPLoopBasedDirective::HelperExprs B;
11403   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
11404   // define the nested loops number.
11405   unsigned NestedLoopCount =
11406       checkOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
11407                       /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
11408                       VarsWithImplicitDSA, B);
11409   if (NestedLoopCount == 0)
11410     return StmtError();
11411 
11412   assert((CurContext->isDependentContext() || B.builtAll()) &&
11413          "omp for loop exprs were not built");
11414 
11415   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
11416   // The grainsize clause and num_tasks clause are mutually exclusive and may
11417   // not appear on the same taskloop directive.
11418   if (checkGrainsizeNumTasksClauses(*this, Clauses))
11419     return StmtError();
11420   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
11421   // If a reduction clause is present on the taskloop directive, the nogroup
11422   // clause must not be specified.
11423   if (checkReductionClauseWithNogroup(*this, Clauses))
11424     return StmtError();
11425 
11426   setFunctionHasBranchProtectedScope();
11427   return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
11428                                       NestedLoopCount, Clauses, AStmt, B,
11429                                       DSAStack->isCancelRegion());
11430 }
11431 
11432 StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
11433     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11434     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11435   if (!AStmt)
11436     return StmtError();
11437 
11438   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
11439   OMPLoopBasedDirective::HelperExprs B;
11440   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
11441   // define the nested loops number.
11442   unsigned NestedLoopCount =
11443       checkOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
11444                       /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
11445                       VarsWithImplicitDSA, B);
11446   if (NestedLoopCount == 0)
11447     return StmtError();
11448 
11449   assert((CurContext->isDependentContext() || B.builtAll()) &&
11450          "omp for loop exprs were not built");
11451 
11452   if (!CurContext->isDependentContext()) {
11453     // Finalize the clauses that need pre-built expressions for CodeGen.
11454     for (OMPClause *C : Clauses) {
11455       if (auto *LC = dyn_cast<OMPLinearClause>(C))
11456         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
11457                                      B.NumIterations, *this, CurScope,
11458                                      DSAStack))
11459           return StmtError();
11460     }
11461   }
11462 
11463   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
11464   // The grainsize clause and num_tasks clause are mutually exclusive and may
11465   // not appear on the same taskloop directive.
11466   if (checkGrainsizeNumTasksClauses(*this, Clauses))
11467     return StmtError();
11468   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
11469   // If a reduction clause is present on the taskloop directive, the nogroup
11470   // clause must not be specified.
11471   if (checkReductionClauseWithNogroup(*this, Clauses))
11472     return StmtError();
11473   if (checkSimdlenSafelenSpecified(*this, Clauses))
11474     return StmtError();
11475 
11476   setFunctionHasBranchProtectedScope();
11477   return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
11478                                           NestedLoopCount, Clauses, AStmt, B);
11479 }
11480 
11481 StmtResult Sema::ActOnOpenMPMasterTaskLoopDirective(
11482     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11483     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11484   if (!AStmt)
11485     return StmtError();
11486 
11487   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
11488   OMPLoopBasedDirective::HelperExprs B;
11489   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
11490   // define the nested loops number.
11491   unsigned NestedLoopCount =
11492       checkOpenMPLoop(OMPD_master_taskloop, getCollapseNumberExpr(Clauses),
11493                       /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
11494                       VarsWithImplicitDSA, B);
11495   if (NestedLoopCount == 0)
11496     return StmtError();
11497 
11498   assert((CurContext->isDependentContext() || B.builtAll()) &&
11499          "omp for loop exprs were not built");
11500 
11501   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
11502   // The grainsize clause and num_tasks clause are mutually exclusive and may
11503   // not appear on the same taskloop directive.
11504   if (checkGrainsizeNumTasksClauses(*this, Clauses))
11505     return StmtError();
11506   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
11507   // If a reduction clause is present on the taskloop directive, the nogroup
11508   // clause must not be specified.
11509   if (checkReductionClauseWithNogroup(*this, Clauses))
11510     return StmtError();
11511 
11512   setFunctionHasBranchProtectedScope();
11513   return OMPMasterTaskLoopDirective::Create(Context, StartLoc, EndLoc,
11514                                             NestedLoopCount, Clauses, AStmt, B,
11515                                             DSAStack->isCancelRegion());
11516 }
11517 
11518 StmtResult Sema::ActOnOpenMPMasterTaskLoopSimdDirective(
11519     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11520     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11521   if (!AStmt)
11522     return StmtError();
11523 
11524   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
11525   OMPLoopBasedDirective::HelperExprs B;
11526   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
11527   // define the nested loops number.
11528   unsigned NestedLoopCount =
11529       checkOpenMPLoop(OMPD_master_taskloop_simd, getCollapseNumberExpr(Clauses),
11530                       /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
11531                       VarsWithImplicitDSA, B);
11532   if (NestedLoopCount == 0)
11533     return StmtError();
11534 
11535   assert((CurContext->isDependentContext() || B.builtAll()) &&
11536          "omp for loop exprs were not built");
11537 
11538   if (!CurContext->isDependentContext()) {
11539     // Finalize the clauses that need pre-built expressions for CodeGen.
11540     for (OMPClause *C : Clauses) {
11541       if (auto *LC = dyn_cast<OMPLinearClause>(C))
11542         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
11543                                      B.NumIterations, *this, CurScope,
11544                                      DSAStack))
11545           return StmtError();
11546     }
11547   }
11548 
11549   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
11550   // The grainsize clause and num_tasks clause are mutually exclusive and may
11551   // not appear on the same taskloop directive.
11552   if (checkGrainsizeNumTasksClauses(*this, Clauses))
11553     return StmtError();
11554   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
11555   // If a reduction clause is present on the taskloop directive, the nogroup
11556   // clause must not be specified.
11557   if (checkReductionClauseWithNogroup(*this, Clauses))
11558     return StmtError();
11559   if (checkSimdlenSafelenSpecified(*this, Clauses))
11560     return StmtError();
11561 
11562   setFunctionHasBranchProtectedScope();
11563   return OMPMasterTaskLoopSimdDirective::Create(
11564       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
11565 }
11566 
11567 StmtResult Sema::ActOnOpenMPParallelMasterTaskLoopDirective(
11568     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11569     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11570   if (!AStmt)
11571     return StmtError();
11572 
11573   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
11574   auto *CS = cast<CapturedStmt>(AStmt);
11575   // 1.2.2 OpenMP Language Terminology
11576   // Structured block - An executable statement with a single entry at the
11577   // top and a single exit at the bottom.
11578   // The point of exit cannot be a branch out of the structured block.
11579   // longjmp() and throw() must not violate the entry/exit criteria.
11580   CS->getCapturedDecl()->setNothrow();
11581   for (int ThisCaptureLevel =
11582            getOpenMPCaptureLevels(OMPD_parallel_master_taskloop);
11583        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11584     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11585     // 1.2.2 OpenMP Language Terminology
11586     // Structured block - An executable statement with a single entry at the
11587     // top and a single exit at the bottom.
11588     // The point of exit cannot be a branch out of the structured block.
11589     // longjmp() and throw() must not violate the entry/exit criteria.
11590     CS->getCapturedDecl()->setNothrow();
11591   }
11592 
11593   OMPLoopBasedDirective::HelperExprs B;
11594   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
11595   // define the nested loops number.
11596   unsigned NestedLoopCount = checkOpenMPLoop(
11597       OMPD_parallel_master_taskloop, getCollapseNumberExpr(Clauses),
11598       /*OrderedLoopCountExpr=*/nullptr, CS, *this, *DSAStack,
11599       VarsWithImplicitDSA, B);
11600   if (NestedLoopCount == 0)
11601     return StmtError();
11602 
11603   assert((CurContext->isDependentContext() || B.builtAll()) &&
11604          "omp for loop exprs were not built");
11605 
11606   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
11607   // The grainsize clause and num_tasks clause are mutually exclusive and may
11608   // not appear on the same taskloop directive.
11609   if (checkGrainsizeNumTasksClauses(*this, Clauses))
11610     return StmtError();
11611   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
11612   // If a reduction clause is present on the taskloop directive, the nogroup
11613   // clause must not be specified.
11614   if (checkReductionClauseWithNogroup(*this, Clauses))
11615     return StmtError();
11616 
11617   setFunctionHasBranchProtectedScope();
11618   return OMPParallelMasterTaskLoopDirective::Create(
11619       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
11620       DSAStack->isCancelRegion());
11621 }
11622 
11623 StmtResult Sema::ActOnOpenMPParallelMasterTaskLoopSimdDirective(
11624     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11625     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11626   if (!AStmt)
11627     return StmtError();
11628 
11629   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
11630   auto *CS = cast<CapturedStmt>(AStmt);
11631   // 1.2.2 OpenMP Language Terminology
11632   // Structured block - An executable statement with a single entry at the
11633   // top and a single exit at the bottom.
11634   // The point of exit cannot be a branch out of the structured block.
11635   // longjmp() and throw() must not violate the entry/exit criteria.
11636   CS->getCapturedDecl()->setNothrow();
11637   for (int ThisCaptureLevel =
11638            getOpenMPCaptureLevels(OMPD_parallel_master_taskloop_simd);
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   OMPLoopBasedDirective::HelperExprs B;
11650   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
11651   // define the nested loops number.
11652   unsigned NestedLoopCount = checkOpenMPLoop(
11653       OMPD_parallel_master_taskloop_simd, getCollapseNumberExpr(Clauses),
11654       /*OrderedLoopCountExpr=*/nullptr, CS, *this, *DSAStack,
11655       VarsWithImplicitDSA, B);
11656   if (NestedLoopCount == 0)
11657     return StmtError();
11658 
11659   assert((CurContext->isDependentContext() || B.builtAll()) &&
11660          "omp for loop exprs were not built");
11661 
11662   if (!CurContext->isDependentContext()) {
11663     // Finalize the clauses that need pre-built expressions for CodeGen.
11664     for (OMPClause *C : Clauses) {
11665       if (auto *LC = dyn_cast<OMPLinearClause>(C))
11666         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
11667                                      B.NumIterations, *this, CurScope,
11668                                      DSAStack))
11669           return StmtError();
11670     }
11671   }
11672 
11673   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
11674   // The grainsize clause and num_tasks clause are mutually exclusive and may
11675   // not appear on the same taskloop directive.
11676   if (checkGrainsizeNumTasksClauses(*this, Clauses))
11677     return StmtError();
11678   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
11679   // If a reduction clause is present on the taskloop directive, the nogroup
11680   // clause must not be specified.
11681   if (checkReductionClauseWithNogroup(*this, Clauses))
11682     return StmtError();
11683   if (checkSimdlenSafelenSpecified(*this, Clauses))
11684     return StmtError();
11685 
11686   setFunctionHasBranchProtectedScope();
11687   return OMPParallelMasterTaskLoopSimdDirective::Create(
11688       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
11689 }
11690 
11691 StmtResult Sema::ActOnOpenMPDistributeDirective(
11692     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11693     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11694   if (!AStmt)
11695     return StmtError();
11696 
11697   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
11698   OMPLoopBasedDirective::HelperExprs B;
11699   // In presence of clause 'collapse' with number of loops, it will
11700   // define the nested loops number.
11701   unsigned NestedLoopCount =
11702       checkOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
11703                       nullptr /*ordered not a clause on distribute*/, AStmt,
11704                       *this, *DSAStack, VarsWithImplicitDSA, B);
11705   if (NestedLoopCount == 0)
11706     return StmtError();
11707 
11708   assert((CurContext->isDependentContext() || B.builtAll()) &&
11709          "omp for loop exprs were not built");
11710 
11711   setFunctionHasBranchProtectedScope();
11712   return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
11713                                         NestedLoopCount, Clauses, AStmt, B);
11714 }
11715 
11716 StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
11717     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11718     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11719   if (!AStmt)
11720     return StmtError();
11721 
11722   auto *CS = cast<CapturedStmt>(AStmt);
11723   // 1.2.2 OpenMP Language Terminology
11724   // Structured block - An executable statement with a single entry at the
11725   // top and a single exit at the bottom.
11726   // The point of exit cannot be a branch out of the structured block.
11727   // longjmp() and throw() must not violate the entry/exit criteria.
11728   CS->getCapturedDecl()->setNothrow();
11729   for (int ThisCaptureLevel =
11730            getOpenMPCaptureLevels(OMPD_distribute_parallel_for);
11731        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11732     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11733     // 1.2.2 OpenMP Language Terminology
11734     // Structured block - An executable statement with a single entry at the
11735     // top and a single exit at the bottom.
11736     // The point of exit cannot be a branch out of the structured block.
11737     // longjmp() and throw() must not violate the entry/exit criteria.
11738     CS->getCapturedDecl()->setNothrow();
11739   }
11740 
11741   OMPLoopBasedDirective::HelperExprs B;
11742   // In presence of clause 'collapse' with number of loops, it will
11743   // define the nested loops number.
11744   unsigned NestedLoopCount = checkOpenMPLoop(
11745       OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
11746       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
11747       VarsWithImplicitDSA, B);
11748   if (NestedLoopCount == 0)
11749     return StmtError();
11750 
11751   assert((CurContext->isDependentContext() || B.builtAll()) &&
11752          "omp for loop exprs were not built");
11753 
11754   setFunctionHasBranchProtectedScope();
11755   return OMPDistributeParallelForDirective::Create(
11756       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
11757       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
11758 }
11759 
11760 StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
11761     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11762     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11763   if (!AStmt)
11764     return StmtError();
11765 
11766   auto *CS = cast<CapturedStmt>(AStmt);
11767   // 1.2.2 OpenMP Language Terminology
11768   // Structured block - An executable statement with a single entry at the
11769   // top and a single exit at the bottom.
11770   // The point of exit cannot be a branch out of the structured block.
11771   // longjmp() and throw() must not violate the entry/exit criteria.
11772   CS->getCapturedDecl()->setNothrow();
11773   for (int ThisCaptureLevel =
11774            getOpenMPCaptureLevels(OMPD_distribute_parallel_for_simd);
11775        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11776     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11777     // 1.2.2 OpenMP Language Terminology
11778     // Structured block - An executable statement with a single entry at the
11779     // top and a single exit at the bottom.
11780     // The point of exit cannot be a branch out of the structured block.
11781     // longjmp() and throw() must not violate the entry/exit criteria.
11782     CS->getCapturedDecl()->setNothrow();
11783   }
11784 
11785   OMPLoopBasedDirective::HelperExprs B;
11786   // In presence of clause 'collapse' with number of loops, it will
11787   // define the nested loops number.
11788   unsigned NestedLoopCount = checkOpenMPLoop(
11789       OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
11790       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
11791       VarsWithImplicitDSA, B);
11792   if (NestedLoopCount == 0)
11793     return StmtError();
11794 
11795   assert((CurContext->isDependentContext() || B.builtAll()) &&
11796          "omp for loop exprs were not built");
11797 
11798   if (!CurContext->isDependentContext()) {
11799     // Finalize the clauses that need pre-built expressions for CodeGen.
11800     for (OMPClause *C : Clauses) {
11801       if (auto *LC = dyn_cast<OMPLinearClause>(C))
11802         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
11803                                      B.NumIterations, *this, CurScope,
11804                                      DSAStack))
11805           return StmtError();
11806     }
11807   }
11808 
11809   if (checkSimdlenSafelenSpecified(*this, Clauses))
11810     return StmtError();
11811 
11812   setFunctionHasBranchProtectedScope();
11813   return OMPDistributeParallelForSimdDirective::Create(
11814       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
11815 }
11816 
11817 StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
11818     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11819     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11820   if (!AStmt)
11821     return StmtError();
11822 
11823   auto *CS = cast<CapturedStmt>(AStmt);
11824   // 1.2.2 OpenMP Language Terminology
11825   // Structured block - An executable statement with a single entry at the
11826   // top and a single exit at the bottom.
11827   // The point of exit cannot be a branch out of the structured block.
11828   // longjmp() and throw() must not violate the entry/exit criteria.
11829   CS->getCapturedDecl()->setNothrow();
11830   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_distribute_simd);
11831        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11832     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11833     // 1.2.2 OpenMP Language Terminology
11834     // Structured block - An executable statement with a single entry at the
11835     // top and a single exit at the bottom.
11836     // The point of exit cannot be a branch out of the structured block.
11837     // longjmp() and throw() must not violate the entry/exit criteria.
11838     CS->getCapturedDecl()->setNothrow();
11839   }
11840 
11841   OMPLoopBasedDirective::HelperExprs B;
11842   // In presence of clause 'collapse' with number of loops, it will
11843   // define the nested loops number.
11844   unsigned NestedLoopCount =
11845       checkOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
11846                       nullptr /*ordered not a clause on distribute*/, CS, *this,
11847                       *DSAStack, VarsWithImplicitDSA, B);
11848   if (NestedLoopCount == 0)
11849     return StmtError();
11850 
11851   assert((CurContext->isDependentContext() || B.builtAll()) &&
11852          "omp for loop exprs were not built");
11853 
11854   if (!CurContext->isDependentContext()) {
11855     // Finalize the clauses that need pre-built expressions for CodeGen.
11856     for (OMPClause *C : Clauses) {
11857       if (auto *LC = dyn_cast<OMPLinearClause>(C))
11858         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
11859                                      B.NumIterations, *this, CurScope,
11860                                      DSAStack))
11861           return StmtError();
11862     }
11863   }
11864 
11865   if (checkSimdlenSafelenSpecified(*this, Clauses))
11866     return StmtError();
11867 
11868   setFunctionHasBranchProtectedScope();
11869   return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
11870                                             NestedLoopCount, Clauses, AStmt, B);
11871 }
11872 
11873 StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
11874     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11875     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11876   if (!AStmt)
11877     return StmtError();
11878 
11879   auto *CS = cast<CapturedStmt>(AStmt);
11880   // 1.2.2 OpenMP Language Terminology
11881   // Structured block - An executable statement with a single entry at the
11882   // top and a single exit at the bottom.
11883   // The point of exit cannot be a branch out of the structured block.
11884   // longjmp() and throw() must not violate the entry/exit criteria.
11885   CS->getCapturedDecl()->setNothrow();
11886   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
11887        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11888     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11889     // 1.2.2 OpenMP Language Terminology
11890     // Structured block - An executable statement with a single entry at the
11891     // top and a single exit at the bottom.
11892     // The point of exit cannot be a branch out of the structured block.
11893     // longjmp() and throw() must not violate the entry/exit criteria.
11894     CS->getCapturedDecl()->setNothrow();
11895   }
11896 
11897   OMPLoopBasedDirective::HelperExprs B;
11898   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
11899   // define the nested loops number.
11900   unsigned NestedLoopCount = checkOpenMPLoop(
11901       OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
11902       getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
11903       VarsWithImplicitDSA, B);
11904   if (NestedLoopCount == 0)
11905     return StmtError();
11906 
11907   assert((CurContext->isDependentContext() || B.builtAll()) &&
11908          "omp target parallel for simd loop exprs were not built");
11909 
11910   if (!CurContext->isDependentContext()) {
11911     // Finalize the clauses that need pre-built expressions for CodeGen.
11912     for (OMPClause *C : Clauses) {
11913       if (auto *LC = dyn_cast<OMPLinearClause>(C))
11914         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
11915                                      B.NumIterations, *this, CurScope,
11916                                      DSAStack))
11917           return StmtError();
11918     }
11919   }
11920   if (checkSimdlenSafelenSpecified(*this, Clauses))
11921     return StmtError();
11922 
11923   setFunctionHasBranchProtectedScope();
11924   return OMPTargetParallelForSimdDirective::Create(
11925       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
11926 }
11927 
11928 StmtResult Sema::ActOnOpenMPTargetSimdDirective(
11929     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11930     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11931   if (!AStmt)
11932     return StmtError();
11933 
11934   auto *CS = cast<CapturedStmt>(AStmt);
11935   // 1.2.2 OpenMP Language Terminology
11936   // Structured block - An executable statement with a single entry at the
11937   // top and a single exit at the bottom.
11938   // The point of exit cannot be a branch out of the structured block.
11939   // longjmp() and throw() must not violate the entry/exit criteria.
11940   CS->getCapturedDecl()->setNothrow();
11941   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_simd);
11942        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11943     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11944     // 1.2.2 OpenMP Language Terminology
11945     // Structured block - An executable statement with a single entry at the
11946     // top and a single exit at the bottom.
11947     // The point of exit cannot be a branch out of the structured block.
11948     // longjmp() and throw() must not violate the entry/exit criteria.
11949     CS->getCapturedDecl()->setNothrow();
11950   }
11951 
11952   OMPLoopBasedDirective::HelperExprs B;
11953   // In presence of clause 'collapse' with number of loops, it will define the
11954   // nested loops number.
11955   unsigned NestedLoopCount =
11956       checkOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
11957                       getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
11958                       VarsWithImplicitDSA, B);
11959   if (NestedLoopCount == 0)
11960     return StmtError();
11961 
11962   assert((CurContext->isDependentContext() || B.builtAll()) &&
11963          "omp target simd loop exprs were not built");
11964 
11965   if (!CurContext->isDependentContext()) {
11966     // Finalize the clauses that need pre-built expressions for CodeGen.
11967     for (OMPClause *C : Clauses) {
11968       if (auto *LC = dyn_cast<OMPLinearClause>(C))
11969         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
11970                                      B.NumIterations, *this, CurScope,
11971                                      DSAStack))
11972           return StmtError();
11973     }
11974   }
11975 
11976   if (checkSimdlenSafelenSpecified(*this, Clauses))
11977     return StmtError();
11978 
11979   setFunctionHasBranchProtectedScope();
11980   return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
11981                                         NestedLoopCount, Clauses, AStmt, B);
11982 }
11983 
11984 StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
11985     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11986     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11987   if (!AStmt)
11988     return StmtError();
11989 
11990   auto *CS = cast<CapturedStmt>(AStmt);
11991   // 1.2.2 OpenMP Language Terminology
11992   // Structured block - An executable statement with a single entry at the
11993   // top and a single exit at the bottom.
11994   // The point of exit cannot be a branch out of the structured block.
11995   // longjmp() and throw() must not violate the entry/exit criteria.
11996   CS->getCapturedDecl()->setNothrow();
11997   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_teams_distribute);
11998        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11999     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12000     // 1.2.2 OpenMP Language Terminology
12001     // Structured block - An executable statement with a single entry at the
12002     // top and a single exit at the bottom.
12003     // The point of exit cannot be a branch out of the structured block.
12004     // longjmp() and throw() must not violate the entry/exit criteria.
12005     CS->getCapturedDecl()->setNothrow();
12006   }
12007 
12008   OMPLoopBasedDirective::HelperExprs B;
12009   // In presence of clause 'collapse' with number of loops, it will
12010   // define the nested loops number.
12011   unsigned NestedLoopCount =
12012       checkOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
12013                       nullptr /*ordered not a clause on distribute*/, CS, *this,
12014                       *DSAStack, VarsWithImplicitDSA, B);
12015   if (NestedLoopCount == 0)
12016     return StmtError();
12017 
12018   assert((CurContext->isDependentContext() || B.builtAll()) &&
12019          "omp teams distribute loop exprs were not built");
12020 
12021   setFunctionHasBranchProtectedScope();
12022 
12023   DSAStack->setParentTeamsRegionLoc(StartLoc);
12024 
12025   return OMPTeamsDistributeDirective::Create(
12026       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
12027 }
12028 
12029 StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
12030     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12031     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12032   if (!AStmt)
12033     return StmtError();
12034 
12035   auto *CS = cast<CapturedStmt>(AStmt);
12036   // 1.2.2 OpenMP Language Terminology
12037   // Structured block - An executable statement with a single entry at the
12038   // top and a single exit at the bottom.
12039   // The point of exit cannot be a branch out of the structured block.
12040   // longjmp() and throw() must not violate the entry/exit criteria.
12041   CS->getCapturedDecl()->setNothrow();
12042   for (int ThisCaptureLevel =
12043            getOpenMPCaptureLevels(OMPD_teams_distribute_simd);
12044        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12045     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12046     // 1.2.2 OpenMP Language Terminology
12047     // Structured block - An executable statement with a single entry at the
12048     // top and a single exit at the bottom.
12049     // The point of exit cannot be a branch out of the structured block.
12050     // longjmp() and throw() must not violate the entry/exit criteria.
12051     CS->getCapturedDecl()->setNothrow();
12052   }
12053 
12054   OMPLoopBasedDirective::HelperExprs B;
12055   // In presence of clause 'collapse' with number of loops, it will
12056   // define the nested loops number.
12057   unsigned NestedLoopCount = checkOpenMPLoop(
12058       OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
12059       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
12060       VarsWithImplicitDSA, B);
12061 
12062   if (NestedLoopCount == 0)
12063     return StmtError();
12064 
12065   assert((CurContext->isDependentContext() || B.builtAll()) &&
12066          "omp teams distribute simd loop exprs were not built");
12067 
12068   if (!CurContext->isDependentContext()) {
12069     // Finalize the clauses that need pre-built expressions for CodeGen.
12070     for (OMPClause *C : Clauses) {
12071       if (auto *LC = dyn_cast<OMPLinearClause>(C))
12072         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
12073                                      B.NumIterations, *this, CurScope,
12074                                      DSAStack))
12075           return StmtError();
12076     }
12077   }
12078 
12079   if (checkSimdlenSafelenSpecified(*this, Clauses))
12080     return StmtError();
12081 
12082   setFunctionHasBranchProtectedScope();
12083 
12084   DSAStack->setParentTeamsRegionLoc(StartLoc);
12085 
12086   return OMPTeamsDistributeSimdDirective::Create(
12087       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
12088 }
12089 
12090 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
12091     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12092     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12093   if (!AStmt)
12094     return StmtError();
12095 
12096   auto *CS = cast<CapturedStmt>(AStmt);
12097   // 1.2.2 OpenMP Language Terminology
12098   // Structured block - An executable statement with a single entry at the
12099   // top and a single exit at the bottom.
12100   // The point of exit cannot be a branch out of the structured block.
12101   // longjmp() and throw() must not violate the entry/exit criteria.
12102   CS->getCapturedDecl()->setNothrow();
12103 
12104   for (int ThisCaptureLevel =
12105            getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for_simd);
12106        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12107     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12108     // 1.2.2 OpenMP Language Terminology
12109     // Structured block - An executable statement with a single entry at the
12110     // top and a single exit at the bottom.
12111     // The point of exit cannot be a branch out of the structured block.
12112     // longjmp() and throw() must not violate the entry/exit criteria.
12113     CS->getCapturedDecl()->setNothrow();
12114   }
12115 
12116   OMPLoopBasedDirective::HelperExprs B;
12117   // In presence of clause 'collapse' with number of loops, it will
12118   // define the nested loops number.
12119   unsigned NestedLoopCount = checkOpenMPLoop(
12120       OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
12121       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
12122       VarsWithImplicitDSA, B);
12123 
12124   if (NestedLoopCount == 0)
12125     return StmtError();
12126 
12127   assert((CurContext->isDependentContext() || B.builtAll()) &&
12128          "omp for loop exprs were not built");
12129 
12130   if (!CurContext->isDependentContext()) {
12131     // Finalize the clauses that need pre-built expressions for CodeGen.
12132     for (OMPClause *C : Clauses) {
12133       if (auto *LC = dyn_cast<OMPLinearClause>(C))
12134         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
12135                                      B.NumIterations, *this, CurScope,
12136                                      DSAStack))
12137           return StmtError();
12138     }
12139   }
12140 
12141   if (checkSimdlenSafelenSpecified(*this, Clauses))
12142     return StmtError();
12143 
12144   setFunctionHasBranchProtectedScope();
12145 
12146   DSAStack->setParentTeamsRegionLoc(StartLoc);
12147 
12148   return OMPTeamsDistributeParallelForSimdDirective::Create(
12149       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
12150 }
12151 
12152 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
12153     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12154     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12155   if (!AStmt)
12156     return StmtError();
12157 
12158   auto *CS = cast<CapturedStmt>(AStmt);
12159   // 1.2.2 OpenMP Language Terminology
12160   // Structured block - An executable statement with a single entry at the
12161   // top and a single exit at the bottom.
12162   // The point of exit cannot be a branch out of the structured block.
12163   // longjmp() and throw() must not violate the entry/exit criteria.
12164   CS->getCapturedDecl()->setNothrow();
12165 
12166   for (int ThisCaptureLevel =
12167            getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for);
12168        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12169     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12170     // 1.2.2 OpenMP Language Terminology
12171     // Structured block - An executable statement with a single entry at the
12172     // top and a single exit at the bottom.
12173     // The point of exit cannot be a branch out of the structured block.
12174     // longjmp() and throw() must not violate the entry/exit criteria.
12175     CS->getCapturedDecl()->setNothrow();
12176   }
12177 
12178   OMPLoopBasedDirective::HelperExprs B;
12179   // In presence of clause 'collapse' with number of loops, it will
12180   // define the nested loops number.
12181   unsigned NestedLoopCount = checkOpenMPLoop(
12182       OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
12183       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
12184       VarsWithImplicitDSA, B);
12185 
12186   if (NestedLoopCount == 0)
12187     return StmtError();
12188 
12189   assert((CurContext->isDependentContext() || B.builtAll()) &&
12190          "omp for loop exprs were not built");
12191 
12192   setFunctionHasBranchProtectedScope();
12193 
12194   DSAStack->setParentTeamsRegionLoc(StartLoc);
12195 
12196   return OMPTeamsDistributeParallelForDirective::Create(
12197       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
12198       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
12199 }
12200 
12201 StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
12202                                                  Stmt *AStmt,
12203                                                  SourceLocation StartLoc,
12204                                                  SourceLocation EndLoc) {
12205   if (!AStmt)
12206     return StmtError();
12207 
12208   auto *CS = cast<CapturedStmt>(AStmt);
12209   // 1.2.2 OpenMP Language Terminology
12210   // Structured block - An executable statement with a single entry at the
12211   // top and a single exit at the bottom.
12212   // The point of exit cannot be a branch out of the structured block.
12213   // longjmp() and throw() must not violate the entry/exit criteria.
12214   CS->getCapturedDecl()->setNothrow();
12215 
12216   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams);
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   setFunctionHasBranchProtectedScope();
12227 
12228   return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
12229                                          AStmt);
12230 }
12231 
12232 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
12233     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12234     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12235   if (!AStmt)
12236     return StmtError();
12237 
12238   auto *CS = cast<CapturedStmt>(AStmt);
12239   // 1.2.2 OpenMP Language Terminology
12240   // Structured block - An executable statement with a single entry at the
12241   // top and a single exit at the bottom.
12242   // The point of exit cannot be a branch out of the structured block.
12243   // longjmp() and throw() must not violate the entry/exit criteria.
12244   CS->getCapturedDecl()->setNothrow();
12245   for (int ThisCaptureLevel =
12246            getOpenMPCaptureLevels(OMPD_target_teams_distribute);
12247        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12248     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12249     // 1.2.2 OpenMP Language Terminology
12250     // Structured block - An executable statement with a single entry at the
12251     // top and a single exit at the bottom.
12252     // The point of exit cannot be a branch out of the structured block.
12253     // longjmp() and throw() must not violate the entry/exit criteria.
12254     CS->getCapturedDecl()->setNothrow();
12255   }
12256 
12257   OMPLoopBasedDirective::HelperExprs B;
12258   // In presence of clause 'collapse' with number of loops, it will
12259   // define the nested loops number.
12260   unsigned NestedLoopCount = checkOpenMPLoop(
12261       OMPD_target_teams_distribute, getCollapseNumberExpr(Clauses),
12262       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
12263       VarsWithImplicitDSA, B);
12264   if (NestedLoopCount == 0)
12265     return StmtError();
12266 
12267   assert((CurContext->isDependentContext() || B.builtAll()) &&
12268          "omp target teams distribute loop exprs were not built");
12269 
12270   setFunctionHasBranchProtectedScope();
12271   return OMPTargetTeamsDistributeDirective::Create(
12272       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
12273 }
12274 
12275 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
12276     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12277     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12278   if (!AStmt)
12279     return StmtError();
12280 
12281   auto *CS = cast<CapturedStmt>(AStmt);
12282   // 1.2.2 OpenMP Language Terminology
12283   // Structured block - An executable statement with a single entry at the
12284   // top and a single exit at the bottom.
12285   // The point of exit cannot be a branch out of the structured block.
12286   // longjmp() and throw() must not violate the entry/exit criteria.
12287   CS->getCapturedDecl()->setNothrow();
12288   for (int ThisCaptureLevel =
12289            getOpenMPCaptureLevels(OMPD_target_teams_distribute_parallel_for);
12290        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12291     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12292     // 1.2.2 OpenMP Language Terminology
12293     // Structured block - An executable statement with a single entry at the
12294     // top and a single exit at the bottom.
12295     // The point of exit cannot be a branch out of the structured block.
12296     // longjmp() and throw() must not violate the entry/exit criteria.
12297     CS->getCapturedDecl()->setNothrow();
12298   }
12299 
12300   OMPLoopBasedDirective::HelperExprs B;
12301   // In presence of clause 'collapse' with number of loops, it will
12302   // define the nested loops number.
12303   unsigned NestedLoopCount = checkOpenMPLoop(
12304       OMPD_target_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
12305       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
12306       VarsWithImplicitDSA, B);
12307   if (NestedLoopCount == 0)
12308     return StmtError();
12309 
12310   assert((CurContext->isDependentContext() || B.builtAll()) &&
12311          "omp target teams distribute parallel for loop exprs were not built");
12312 
12313   if (!CurContext->isDependentContext()) {
12314     // Finalize the clauses that need pre-built expressions for CodeGen.
12315     for (OMPClause *C : Clauses) {
12316       if (auto *LC = dyn_cast<OMPLinearClause>(C))
12317         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
12318                                      B.NumIterations, *this, CurScope,
12319                                      DSAStack))
12320           return StmtError();
12321     }
12322   }
12323 
12324   setFunctionHasBranchProtectedScope();
12325   return OMPTargetTeamsDistributeParallelForDirective::Create(
12326       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
12327       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
12328 }
12329 
12330 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
12331     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12332     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12333   if (!AStmt)
12334     return StmtError();
12335 
12336   auto *CS = cast<CapturedStmt>(AStmt);
12337   // 1.2.2 OpenMP Language Terminology
12338   // Structured block - An executable statement with a single entry at the
12339   // top and a single exit at the bottom.
12340   // The point of exit cannot be a branch out of the structured block.
12341   // longjmp() and throw() must not violate the entry/exit criteria.
12342   CS->getCapturedDecl()->setNothrow();
12343   for (int ThisCaptureLevel = getOpenMPCaptureLevels(
12344            OMPD_target_teams_distribute_parallel_for_simd);
12345        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12346     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12347     // 1.2.2 OpenMP Language Terminology
12348     // Structured block - An executable statement with a single entry at the
12349     // top and a single exit at the bottom.
12350     // The point of exit cannot be a branch out of the structured block.
12351     // longjmp() and throw() must not violate the entry/exit criteria.
12352     CS->getCapturedDecl()->setNothrow();
12353   }
12354 
12355   OMPLoopBasedDirective::HelperExprs B;
12356   // In presence of clause 'collapse' with number of loops, it will
12357   // define the nested loops number.
12358   unsigned NestedLoopCount =
12359       checkOpenMPLoop(OMPD_target_teams_distribute_parallel_for_simd,
12360                       getCollapseNumberExpr(Clauses),
12361                       nullptr /*ordered not a clause on distribute*/, CS, *this,
12362                       *DSAStack, VarsWithImplicitDSA, B);
12363   if (NestedLoopCount == 0)
12364     return StmtError();
12365 
12366   assert((CurContext->isDependentContext() || B.builtAll()) &&
12367          "omp target teams distribute parallel for simd loop exprs were not "
12368          "built");
12369 
12370   if (!CurContext->isDependentContext()) {
12371     // Finalize the clauses that need pre-built expressions for CodeGen.
12372     for (OMPClause *C : Clauses) {
12373       if (auto *LC = dyn_cast<OMPLinearClause>(C))
12374         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
12375                                      B.NumIterations, *this, CurScope,
12376                                      DSAStack))
12377           return StmtError();
12378     }
12379   }
12380 
12381   if (checkSimdlenSafelenSpecified(*this, Clauses))
12382     return StmtError();
12383 
12384   setFunctionHasBranchProtectedScope();
12385   return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
12386       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
12387 }
12388 
12389 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
12390     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12391     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12392   if (!AStmt)
12393     return StmtError();
12394 
12395   auto *CS = cast<CapturedStmt>(AStmt);
12396   // 1.2.2 OpenMP Language Terminology
12397   // Structured block - An executable statement with a single entry at the
12398   // top and a single exit at the bottom.
12399   // The point of exit cannot be a branch out of the structured block.
12400   // longjmp() and throw() must not violate the entry/exit criteria.
12401   CS->getCapturedDecl()->setNothrow();
12402   for (int ThisCaptureLevel =
12403            getOpenMPCaptureLevels(OMPD_target_teams_distribute_simd);
12404        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12405     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12406     // 1.2.2 OpenMP Language Terminology
12407     // Structured block - An executable statement with a single entry at the
12408     // top and a single exit at the bottom.
12409     // The point of exit cannot be a branch out of the structured block.
12410     // longjmp() and throw() must not violate the entry/exit criteria.
12411     CS->getCapturedDecl()->setNothrow();
12412   }
12413 
12414   OMPLoopBasedDirective::HelperExprs B;
12415   // In presence of clause 'collapse' with number of loops, it will
12416   // define the nested loops number.
12417   unsigned NestedLoopCount = checkOpenMPLoop(
12418       OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
12419       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
12420       VarsWithImplicitDSA, B);
12421   if (NestedLoopCount == 0)
12422     return StmtError();
12423 
12424   assert((CurContext->isDependentContext() || B.builtAll()) &&
12425          "omp target teams distribute simd loop exprs were not built");
12426 
12427   if (!CurContext->isDependentContext()) {
12428     // Finalize the clauses that need pre-built expressions for CodeGen.
12429     for (OMPClause *C : Clauses) {
12430       if (auto *LC = dyn_cast<OMPLinearClause>(C))
12431         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
12432                                      B.NumIterations, *this, CurScope,
12433                                      DSAStack))
12434           return StmtError();
12435     }
12436   }
12437 
12438   if (checkSimdlenSafelenSpecified(*this, Clauses))
12439     return StmtError();
12440 
12441   setFunctionHasBranchProtectedScope();
12442   return OMPTargetTeamsDistributeSimdDirective::Create(
12443       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
12444 }
12445 
12446 StmtResult Sema::ActOnOpenMPTileDirective(ArrayRef<OMPClause *> Clauses,
12447                                           Stmt *AStmt, SourceLocation StartLoc,
12448                                           SourceLocation EndLoc) {
12449   auto SizesClauses =
12450       OMPExecutableDirective::getClausesOfKind<OMPSizesClause>(Clauses);
12451   if (SizesClauses.empty()) {
12452     // A missing 'sizes' clause is already reported by the parser.
12453     return StmtError();
12454   }
12455   const OMPSizesClause *SizesClause = *SizesClauses.begin();
12456   unsigned NumLoops = SizesClause->getNumSizes();
12457 
12458   // Empty statement should only be possible if there already was an error.
12459   if (!AStmt)
12460     return StmtError();
12461 
12462   // Verify and diagnose loop nest.
12463   SmallVector<OMPLoopBasedDirective::HelperExprs, 4> LoopHelpers(NumLoops);
12464   Stmt *Body = nullptr;
12465   SmallVector<Stmt *, 4> OriginalInits;
12466   if (!OMPLoopBasedDirective::doForAllLoops(
12467           AStmt->IgnoreContainers(), /*TryImperfectlyNestedLoops=*/false,
12468           NumLoops,
12469           [this, &LoopHelpers, &Body, &OriginalInits](unsigned Cnt,
12470                                                       Stmt *CurStmt) {
12471             VarsWithInheritedDSAType TmpDSA;
12472             unsigned SingleNumLoops =
12473                 checkOpenMPLoop(OMPD_tile, nullptr, nullptr, CurStmt, *this,
12474                                 *DSAStack, TmpDSA, LoopHelpers[Cnt]);
12475             if (SingleNumLoops == 0)
12476               return true;
12477             assert(SingleNumLoops == 1 && "Expect single loop iteration space");
12478             if (auto *For = dyn_cast<ForStmt>(CurStmt)) {
12479               OriginalInits.push_back(For->getInit());
12480               Body = For->getBody();
12481             } else {
12482               assert(isa<CXXForRangeStmt>(CurStmt) &&
12483                      "Expected canonical for or range-based for loops.");
12484               auto *CXXFor = cast<CXXForRangeStmt>(CurStmt);
12485               OriginalInits.push_back(CXXFor->getBeginStmt());
12486               Body = CXXFor->getBody();
12487             }
12488             return false;
12489           }))
12490     return StmtError();
12491 
12492   // Delay tiling to when template is completely instantiated.
12493   if (CurContext->isDependentContext())
12494     return OMPTileDirective::Create(Context, StartLoc, EndLoc, Clauses,
12495                                     NumLoops, AStmt, nullptr, nullptr);
12496 
12497   // Collection of generated variable declaration.
12498   SmallVector<Decl *, 4> PreInits;
12499 
12500   // Create iteration variables for the generated loops.
12501   SmallVector<VarDecl *, 4> FloorIndVars;
12502   SmallVector<VarDecl *, 4> TileIndVars;
12503   FloorIndVars.resize(NumLoops);
12504   TileIndVars.resize(NumLoops);
12505   for (unsigned I = 0; I < NumLoops; ++I) {
12506     OMPLoopBasedDirective::HelperExprs &LoopHelper = LoopHelpers[I];
12507     if (auto *PI = cast_or_null<DeclStmt>(LoopHelper.PreInits))
12508       PreInits.append(PI->decl_begin(), PI->decl_end());
12509     assert(LoopHelper.Counters.size() == 1 &&
12510            "Expect single-dimensional loop iteration space");
12511     auto *OrigCntVar = cast<DeclRefExpr>(LoopHelper.Counters.front());
12512     std::string OrigVarName = OrigCntVar->getNameInfo().getAsString();
12513     DeclRefExpr *IterVarRef = cast<DeclRefExpr>(LoopHelper.IterationVarRef);
12514     QualType CntTy = IterVarRef->getType();
12515 
12516     // Iteration variable for the floor (i.e. outer) loop.
12517     {
12518       std::string FloorCntName =
12519           (Twine(".floor_") + llvm::utostr(I) + ".iv." + OrigVarName).str();
12520       VarDecl *FloorCntDecl =
12521           buildVarDecl(*this, {}, CntTy, FloorCntName, nullptr, OrigCntVar);
12522       FloorIndVars[I] = FloorCntDecl;
12523     }
12524 
12525     // Iteration variable for the tile (i.e. inner) loop.
12526     {
12527       std::string TileCntName =
12528           (Twine(".tile_") + llvm::utostr(I) + ".iv." + OrigVarName).str();
12529 
12530       // Reuse the iteration variable created by checkOpenMPLoop. It is also
12531       // used by the expressions to derive the original iteration variable's
12532       // value from the logical iteration number.
12533       auto *TileCntDecl = cast<VarDecl>(IterVarRef->getDecl());
12534       TileCntDecl->setDeclName(&PP.getIdentifierTable().get(TileCntName));
12535       TileIndVars[I] = TileCntDecl;
12536     }
12537     if (auto *PI = dyn_cast_or_null<DeclStmt>(OriginalInits[I]))
12538       PreInits.append(PI->decl_begin(), PI->decl_end());
12539     // Gather declarations for the data members used as counters.
12540     for (Expr *CounterRef : LoopHelper.Counters) {
12541       auto *CounterDecl = cast<DeclRefExpr>(CounterRef)->getDecl();
12542       if (isa<OMPCapturedExprDecl>(CounterDecl))
12543         PreInits.push_back(CounterDecl);
12544     }
12545   }
12546 
12547   // Once the original iteration values are set, append the innermost body.
12548   Stmt *Inner = Body;
12549 
12550   // Create tile loops from the inside to the outside.
12551   for (int I = NumLoops - 1; I >= 0; --I) {
12552     OMPLoopBasedDirective::HelperExprs &LoopHelper = LoopHelpers[I];
12553     Expr *NumIterations = LoopHelper.NumIterations;
12554     auto *OrigCntVar = cast<DeclRefExpr>(LoopHelper.Counters[0]);
12555     QualType CntTy = OrigCntVar->getType();
12556     Expr *DimTileSize = SizesClause->getSizesRefs()[I];
12557     Scope *CurScope = getCurScope();
12558 
12559     // Commonly used variables.
12560     DeclRefExpr *TileIV = buildDeclRefExpr(*this, TileIndVars[I], CntTy,
12561                                            OrigCntVar->getExprLoc());
12562     DeclRefExpr *FloorIV = buildDeclRefExpr(*this, FloorIndVars[I], CntTy,
12563                                             OrigCntVar->getExprLoc());
12564 
12565     // For init-statement: auto .tile.iv = .floor.iv
12566     AddInitializerToDecl(TileIndVars[I], DefaultLvalueConversion(FloorIV).get(),
12567                          /*DirectInit=*/false);
12568     Decl *CounterDecl = TileIndVars[I];
12569     StmtResult InitStmt = new (Context)
12570         DeclStmt(DeclGroupRef::Create(Context, &CounterDecl, 1),
12571                  OrigCntVar->getBeginLoc(), OrigCntVar->getEndLoc());
12572     if (!InitStmt.isUsable())
12573       return StmtError();
12574 
12575     // For cond-expression: .tile.iv < min(.floor.iv + DimTileSize,
12576     // NumIterations)
12577     ExprResult EndOfTile = BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(),
12578                                       BO_Add, FloorIV, DimTileSize);
12579     if (!EndOfTile.isUsable())
12580       return StmtError();
12581     ExprResult IsPartialTile =
12582         BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), BO_LT,
12583                    NumIterations, EndOfTile.get());
12584     if (!IsPartialTile.isUsable())
12585       return StmtError();
12586     ExprResult MinTileAndIterSpace = ActOnConditionalOp(
12587         LoopHelper.Cond->getBeginLoc(), LoopHelper.Cond->getEndLoc(),
12588         IsPartialTile.get(), NumIterations, EndOfTile.get());
12589     if (!MinTileAndIterSpace.isUsable())
12590       return StmtError();
12591     ExprResult CondExpr = BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(),
12592                                      BO_LT, TileIV, MinTileAndIterSpace.get());
12593     if (!CondExpr.isUsable())
12594       return StmtError();
12595 
12596     // For incr-statement: ++.tile.iv
12597     ExprResult IncrStmt =
12598         BuildUnaryOp(CurScope, LoopHelper.Inc->getExprLoc(), UO_PreInc, TileIV);
12599     if (!IncrStmt.isUsable())
12600       return StmtError();
12601 
12602     // Statements to set the original iteration variable's value from the
12603     // logical iteration number.
12604     // Generated for loop is:
12605     // Original_for_init;
12606     // for (auto .tile.iv = .floor.iv; .tile.iv < min(.floor.iv + DimTileSize,
12607     // NumIterations); ++.tile.iv) {
12608     //   Original_Body;
12609     //   Original_counter_update;
12610     // }
12611     // FIXME: If the innermost body is an loop itself, inserting these
12612     // statements stops it being recognized  as a perfectly nested loop (e.g.
12613     // for applying tiling again). If this is the case, sink the expressions
12614     // further into the inner loop.
12615     SmallVector<Stmt *, 4> BodyParts;
12616     BodyParts.append(LoopHelper.Updates.begin(), LoopHelper.Updates.end());
12617     BodyParts.push_back(Inner);
12618     Inner = CompoundStmt::Create(Context, BodyParts, Inner->getBeginLoc(),
12619                                  Inner->getEndLoc());
12620     Inner = new (Context)
12621         ForStmt(Context, InitStmt.get(), CondExpr.get(), nullptr,
12622                 IncrStmt.get(), Inner, LoopHelper.Init->getBeginLoc(),
12623                 LoopHelper.Init->getBeginLoc(), LoopHelper.Inc->getEndLoc());
12624   }
12625 
12626   // Create floor loops from the inside to the outside.
12627   for (int I = NumLoops - 1; I >= 0; --I) {
12628     auto &LoopHelper = LoopHelpers[I];
12629     Expr *NumIterations = LoopHelper.NumIterations;
12630     DeclRefExpr *OrigCntVar = cast<DeclRefExpr>(LoopHelper.Counters[0]);
12631     QualType CntTy = OrigCntVar->getType();
12632     Expr *DimTileSize = SizesClause->getSizesRefs()[I];
12633     Scope *CurScope = getCurScope();
12634 
12635     // Commonly used variables.
12636     DeclRefExpr *FloorIV = buildDeclRefExpr(*this, FloorIndVars[I], CntTy,
12637                                             OrigCntVar->getExprLoc());
12638 
12639     // For init-statement: auto .floor.iv = 0
12640     AddInitializerToDecl(
12641         FloorIndVars[I],
12642         ActOnIntegerConstant(LoopHelper.Init->getExprLoc(), 0).get(),
12643         /*DirectInit=*/false);
12644     Decl *CounterDecl = FloorIndVars[I];
12645     StmtResult InitStmt = new (Context)
12646         DeclStmt(DeclGroupRef::Create(Context, &CounterDecl, 1),
12647                  OrigCntVar->getBeginLoc(), OrigCntVar->getEndLoc());
12648     if (!InitStmt.isUsable())
12649       return StmtError();
12650 
12651     // For cond-expression: .floor.iv < NumIterations
12652     ExprResult CondExpr = BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(),
12653                                      BO_LT, FloorIV, NumIterations);
12654     if (!CondExpr.isUsable())
12655       return StmtError();
12656 
12657     // For incr-statement: .floor.iv += DimTileSize
12658     ExprResult IncrStmt = BuildBinOp(CurScope, LoopHelper.Inc->getExprLoc(),
12659                                      BO_AddAssign, FloorIV, DimTileSize);
12660     if (!IncrStmt.isUsable())
12661       return StmtError();
12662 
12663     Inner = new (Context)
12664         ForStmt(Context, InitStmt.get(), CondExpr.get(), nullptr,
12665                 IncrStmt.get(), Inner, LoopHelper.Init->getBeginLoc(),
12666                 LoopHelper.Init->getBeginLoc(), LoopHelper.Inc->getEndLoc());
12667   }
12668 
12669   return OMPTileDirective::Create(Context, StartLoc, EndLoc, Clauses, NumLoops,
12670                                   AStmt, Inner,
12671                                   buildPreInits(Context, PreInits));
12672 }
12673 
12674 OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
12675                                              SourceLocation StartLoc,
12676                                              SourceLocation LParenLoc,
12677                                              SourceLocation EndLoc) {
12678   OMPClause *Res = nullptr;
12679   switch (Kind) {
12680   case OMPC_final:
12681     Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
12682     break;
12683   case OMPC_num_threads:
12684     Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
12685     break;
12686   case OMPC_safelen:
12687     Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
12688     break;
12689   case OMPC_simdlen:
12690     Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
12691     break;
12692   case OMPC_allocator:
12693     Res = ActOnOpenMPAllocatorClause(Expr, StartLoc, LParenLoc, EndLoc);
12694     break;
12695   case OMPC_collapse:
12696     Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
12697     break;
12698   case OMPC_ordered:
12699     Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
12700     break;
12701   case OMPC_num_teams:
12702     Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
12703     break;
12704   case OMPC_thread_limit:
12705     Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
12706     break;
12707   case OMPC_priority:
12708     Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
12709     break;
12710   case OMPC_grainsize:
12711     Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
12712     break;
12713   case OMPC_num_tasks:
12714     Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
12715     break;
12716   case OMPC_hint:
12717     Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
12718     break;
12719   case OMPC_depobj:
12720     Res = ActOnOpenMPDepobjClause(Expr, StartLoc, LParenLoc, EndLoc);
12721     break;
12722   case OMPC_detach:
12723     Res = ActOnOpenMPDetachClause(Expr, StartLoc, LParenLoc, EndLoc);
12724     break;
12725   case OMPC_device:
12726   case OMPC_if:
12727   case OMPC_default:
12728   case OMPC_proc_bind:
12729   case OMPC_schedule:
12730   case OMPC_private:
12731   case OMPC_firstprivate:
12732   case OMPC_lastprivate:
12733   case OMPC_shared:
12734   case OMPC_reduction:
12735   case OMPC_task_reduction:
12736   case OMPC_in_reduction:
12737   case OMPC_linear:
12738   case OMPC_aligned:
12739   case OMPC_copyin:
12740   case OMPC_copyprivate:
12741   case OMPC_nowait:
12742   case OMPC_untied:
12743   case OMPC_mergeable:
12744   case OMPC_threadprivate:
12745   case OMPC_sizes:
12746   case OMPC_allocate:
12747   case OMPC_flush:
12748   case OMPC_read:
12749   case OMPC_write:
12750   case OMPC_update:
12751   case OMPC_capture:
12752   case OMPC_seq_cst:
12753   case OMPC_acq_rel:
12754   case OMPC_acquire:
12755   case OMPC_release:
12756   case OMPC_relaxed:
12757   case OMPC_depend:
12758   case OMPC_threads:
12759   case OMPC_simd:
12760   case OMPC_map:
12761   case OMPC_nogroup:
12762   case OMPC_dist_schedule:
12763   case OMPC_defaultmap:
12764   case OMPC_unknown:
12765   case OMPC_uniform:
12766   case OMPC_to:
12767   case OMPC_from:
12768   case OMPC_use_device_ptr:
12769   case OMPC_use_device_addr:
12770   case OMPC_is_device_ptr:
12771   case OMPC_unified_address:
12772   case OMPC_unified_shared_memory:
12773   case OMPC_reverse_offload:
12774   case OMPC_dynamic_allocators:
12775   case OMPC_atomic_default_mem_order:
12776   case OMPC_device_type:
12777   case OMPC_match:
12778   case OMPC_nontemporal:
12779   case OMPC_order:
12780   case OMPC_destroy:
12781   case OMPC_inclusive:
12782   case OMPC_exclusive:
12783   case OMPC_uses_allocators:
12784   case OMPC_affinity:
12785   default:
12786     llvm_unreachable("Clause is not allowed.");
12787   }
12788   return Res;
12789 }
12790 
12791 // An OpenMP directive such as 'target parallel' has two captured regions:
12792 // for the 'target' and 'parallel' respectively.  This function returns
12793 // the region in which to capture expressions associated with a clause.
12794 // A return value of OMPD_unknown signifies that the expression should not
12795 // be captured.
12796 static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
12797     OpenMPDirectiveKind DKind, OpenMPClauseKind CKind, unsigned OpenMPVersion,
12798     OpenMPDirectiveKind NameModifier = OMPD_unknown) {
12799   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
12800   switch (CKind) {
12801   case OMPC_if:
12802     switch (DKind) {
12803     case OMPD_target_parallel_for_simd:
12804       if (OpenMPVersion >= 50 &&
12805           (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) {
12806         CaptureRegion = OMPD_parallel;
12807         break;
12808       }
12809       LLVM_FALLTHROUGH;
12810     case OMPD_target_parallel:
12811     case OMPD_target_parallel_for:
12812       // If this clause applies to the nested 'parallel' region, capture within
12813       // the 'target' region, otherwise do not capture.
12814       if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
12815         CaptureRegion = OMPD_target;
12816       break;
12817     case OMPD_target_teams_distribute_parallel_for_simd:
12818       if (OpenMPVersion >= 50 &&
12819           (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) {
12820         CaptureRegion = OMPD_parallel;
12821         break;
12822       }
12823       LLVM_FALLTHROUGH;
12824     case OMPD_target_teams_distribute_parallel_for:
12825       // If this clause applies to the nested 'parallel' region, capture within
12826       // the 'teams' region, otherwise do not capture.
12827       if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
12828         CaptureRegion = OMPD_teams;
12829       break;
12830     case OMPD_teams_distribute_parallel_for_simd:
12831       if (OpenMPVersion >= 50 &&
12832           (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) {
12833         CaptureRegion = OMPD_parallel;
12834         break;
12835       }
12836       LLVM_FALLTHROUGH;
12837     case OMPD_teams_distribute_parallel_for:
12838       CaptureRegion = OMPD_teams;
12839       break;
12840     case OMPD_target_update:
12841     case OMPD_target_enter_data:
12842     case OMPD_target_exit_data:
12843       CaptureRegion = OMPD_task;
12844       break;
12845     case OMPD_parallel_master_taskloop:
12846       if (NameModifier == OMPD_unknown || NameModifier == OMPD_taskloop)
12847         CaptureRegion = OMPD_parallel;
12848       break;
12849     case OMPD_parallel_master_taskloop_simd:
12850       if ((OpenMPVersion <= 45 && NameModifier == OMPD_unknown) ||
12851           NameModifier == OMPD_taskloop) {
12852         CaptureRegion = OMPD_parallel;
12853         break;
12854       }
12855       if (OpenMPVersion <= 45)
12856         break;
12857       if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)
12858         CaptureRegion = OMPD_taskloop;
12859       break;
12860     case OMPD_parallel_for_simd:
12861       if (OpenMPVersion <= 45)
12862         break;
12863       if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)
12864         CaptureRegion = OMPD_parallel;
12865       break;
12866     case OMPD_taskloop_simd:
12867     case OMPD_master_taskloop_simd:
12868       if (OpenMPVersion <= 45)
12869         break;
12870       if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)
12871         CaptureRegion = OMPD_taskloop;
12872       break;
12873     case OMPD_distribute_parallel_for_simd:
12874       if (OpenMPVersion <= 45)
12875         break;
12876       if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)
12877         CaptureRegion = OMPD_parallel;
12878       break;
12879     case OMPD_target_simd:
12880       if (OpenMPVersion >= 50 &&
12881           (NameModifier == OMPD_unknown || NameModifier == OMPD_simd))
12882         CaptureRegion = OMPD_target;
12883       break;
12884     case OMPD_teams_distribute_simd:
12885     case OMPD_target_teams_distribute_simd:
12886       if (OpenMPVersion >= 50 &&
12887           (NameModifier == OMPD_unknown || NameModifier == OMPD_simd))
12888         CaptureRegion = OMPD_teams;
12889       break;
12890     case OMPD_cancel:
12891     case OMPD_parallel:
12892     case OMPD_parallel_master:
12893     case OMPD_parallel_sections:
12894     case OMPD_parallel_for:
12895     case OMPD_target:
12896     case OMPD_target_teams:
12897     case OMPD_target_teams_distribute:
12898     case OMPD_distribute_parallel_for:
12899     case OMPD_task:
12900     case OMPD_taskloop:
12901     case OMPD_master_taskloop:
12902     case OMPD_target_data:
12903     case OMPD_simd:
12904     case OMPD_for_simd:
12905     case OMPD_distribute_simd:
12906       // Do not capture if-clause expressions.
12907       break;
12908     case OMPD_threadprivate:
12909     case OMPD_allocate:
12910     case OMPD_taskyield:
12911     case OMPD_barrier:
12912     case OMPD_taskwait:
12913     case OMPD_cancellation_point:
12914     case OMPD_flush:
12915     case OMPD_depobj:
12916     case OMPD_scan:
12917     case OMPD_declare_reduction:
12918     case OMPD_declare_mapper:
12919     case OMPD_declare_simd:
12920     case OMPD_declare_variant:
12921     case OMPD_begin_declare_variant:
12922     case OMPD_end_declare_variant:
12923     case OMPD_declare_target:
12924     case OMPD_end_declare_target:
12925     case OMPD_teams:
12926     case OMPD_tile:
12927     case OMPD_for:
12928     case OMPD_sections:
12929     case OMPD_section:
12930     case OMPD_single:
12931     case OMPD_master:
12932     case OMPD_critical:
12933     case OMPD_taskgroup:
12934     case OMPD_distribute:
12935     case OMPD_ordered:
12936     case OMPD_atomic:
12937     case OMPD_teams_distribute:
12938     case OMPD_requires:
12939       llvm_unreachable("Unexpected OpenMP directive with if-clause");
12940     case OMPD_unknown:
12941     default:
12942       llvm_unreachable("Unknown OpenMP directive");
12943     }
12944     break;
12945   case OMPC_num_threads:
12946     switch (DKind) {
12947     case OMPD_target_parallel:
12948     case OMPD_target_parallel_for:
12949     case OMPD_target_parallel_for_simd:
12950       CaptureRegion = OMPD_target;
12951       break;
12952     case OMPD_teams_distribute_parallel_for:
12953     case OMPD_teams_distribute_parallel_for_simd:
12954     case OMPD_target_teams_distribute_parallel_for:
12955     case OMPD_target_teams_distribute_parallel_for_simd:
12956       CaptureRegion = OMPD_teams;
12957       break;
12958     case OMPD_parallel:
12959     case OMPD_parallel_master:
12960     case OMPD_parallel_sections:
12961     case OMPD_parallel_for:
12962     case OMPD_parallel_for_simd:
12963     case OMPD_distribute_parallel_for:
12964     case OMPD_distribute_parallel_for_simd:
12965     case OMPD_parallel_master_taskloop:
12966     case OMPD_parallel_master_taskloop_simd:
12967       // Do not capture num_threads-clause expressions.
12968       break;
12969     case OMPD_target_data:
12970     case OMPD_target_enter_data:
12971     case OMPD_target_exit_data:
12972     case OMPD_target_update:
12973     case OMPD_target:
12974     case OMPD_target_simd:
12975     case OMPD_target_teams:
12976     case OMPD_target_teams_distribute:
12977     case OMPD_target_teams_distribute_simd:
12978     case OMPD_cancel:
12979     case OMPD_task:
12980     case OMPD_taskloop:
12981     case OMPD_taskloop_simd:
12982     case OMPD_master_taskloop:
12983     case OMPD_master_taskloop_simd:
12984     case OMPD_threadprivate:
12985     case OMPD_allocate:
12986     case OMPD_taskyield:
12987     case OMPD_barrier:
12988     case OMPD_taskwait:
12989     case OMPD_cancellation_point:
12990     case OMPD_flush:
12991     case OMPD_depobj:
12992     case OMPD_scan:
12993     case OMPD_declare_reduction:
12994     case OMPD_declare_mapper:
12995     case OMPD_declare_simd:
12996     case OMPD_declare_variant:
12997     case OMPD_begin_declare_variant:
12998     case OMPD_end_declare_variant:
12999     case OMPD_declare_target:
13000     case OMPD_end_declare_target:
13001     case OMPD_teams:
13002     case OMPD_simd:
13003     case OMPD_tile:
13004     case OMPD_for:
13005     case OMPD_for_simd:
13006     case OMPD_sections:
13007     case OMPD_section:
13008     case OMPD_single:
13009     case OMPD_master:
13010     case OMPD_critical:
13011     case OMPD_taskgroup:
13012     case OMPD_distribute:
13013     case OMPD_ordered:
13014     case OMPD_atomic:
13015     case OMPD_distribute_simd:
13016     case OMPD_teams_distribute:
13017     case OMPD_teams_distribute_simd:
13018     case OMPD_requires:
13019       llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
13020     case OMPD_unknown:
13021     default:
13022       llvm_unreachable("Unknown OpenMP directive");
13023     }
13024     break;
13025   case OMPC_num_teams:
13026     switch (DKind) {
13027     case OMPD_target_teams:
13028     case OMPD_target_teams_distribute:
13029     case OMPD_target_teams_distribute_simd:
13030     case OMPD_target_teams_distribute_parallel_for:
13031     case OMPD_target_teams_distribute_parallel_for_simd:
13032       CaptureRegion = OMPD_target;
13033       break;
13034     case OMPD_teams_distribute_parallel_for:
13035     case OMPD_teams_distribute_parallel_for_simd:
13036     case OMPD_teams:
13037     case OMPD_teams_distribute:
13038     case OMPD_teams_distribute_simd:
13039       // Do not capture num_teams-clause expressions.
13040       break;
13041     case OMPD_distribute_parallel_for:
13042     case OMPD_distribute_parallel_for_simd:
13043     case OMPD_task:
13044     case OMPD_taskloop:
13045     case OMPD_taskloop_simd:
13046     case OMPD_master_taskloop:
13047     case OMPD_master_taskloop_simd:
13048     case OMPD_parallel_master_taskloop:
13049     case OMPD_parallel_master_taskloop_simd:
13050     case OMPD_target_data:
13051     case OMPD_target_enter_data:
13052     case OMPD_target_exit_data:
13053     case OMPD_target_update:
13054     case OMPD_cancel:
13055     case OMPD_parallel:
13056     case OMPD_parallel_master:
13057     case OMPD_parallel_sections:
13058     case OMPD_parallel_for:
13059     case OMPD_parallel_for_simd:
13060     case OMPD_target:
13061     case OMPD_target_simd:
13062     case OMPD_target_parallel:
13063     case OMPD_target_parallel_for:
13064     case OMPD_target_parallel_for_simd:
13065     case OMPD_threadprivate:
13066     case OMPD_allocate:
13067     case OMPD_taskyield:
13068     case OMPD_barrier:
13069     case OMPD_taskwait:
13070     case OMPD_cancellation_point:
13071     case OMPD_flush:
13072     case OMPD_depobj:
13073     case OMPD_scan:
13074     case OMPD_declare_reduction:
13075     case OMPD_declare_mapper:
13076     case OMPD_declare_simd:
13077     case OMPD_declare_variant:
13078     case OMPD_begin_declare_variant:
13079     case OMPD_end_declare_variant:
13080     case OMPD_declare_target:
13081     case OMPD_end_declare_target:
13082     case OMPD_simd:
13083     case OMPD_tile:
13084     case OMPD_for:
13085     case OMPD_for_simd:
13086     case OMPD_sections:
13087     case OMPD_section:
13088     case OMPD_single:
13089     case OMPD_master:
13090     case OMPD_critical:
13091     case OMPD_taskgroup:
13092     case OMPD_distribute:
13093     case OMPD_ordered:
13094     case OMPD_atomic:
13095     case OMPD_distribute_simd:
13096     case OMPD_requires:
13097       llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
13098     case OMPD_unknown:
13099     default:
13100       llvm_unreachable("Unknown OpenMP directive");
13101     }
13102     break;
13103   case OMPC_thread_limit:
13104     switch (DKind) {
13105     case OMPD_target_teams:
13106     case OMPD_target_teams_distribute:
13107     case OMPD_target_teams_distribute_simd:
13108     case OMPD_target_teams_distribute_parallel_for:
13109     case OMPD_target_teams_distribute_parallel_for_simd:
13110       CaptureRegion = OMPD_target;
13111       break;
13112     case OMPD_teams_distribute_parallel_for:
13113     case OMPD_teams_distribute_parallel_for_simd:
13114     case OMPD_teams:
13115     case OMPD_teams_distribute:
13116     case OMPD_teams_distribute_simd:
13117       // Do not capture thread_limit-clause expressions.
13118       break;
13119     case OMPD_distribute_parallel_for:
13120     case OMPD_distribute_parallel_for_simd:
13121     case OMPD_task:
13122     case OMPD_taskloop:
13123     case OMPD_taskloop_simd:
13124     case OMPD_master_taskloop:
13125     case OMPD_master_taskloop_simd:
13126     case OMPD_parallel_master_taskloop:
13127     case OMPD_parallel_master_taskloop_simd:
13128     case OMPD_target_data:
13129     case OMPD_target_enter_data:
13130     case OMPD_target_exit_data:
13131     case OMPD_target_update:
13132     case OMPD_cancel:
13133     case OMPD_parallel:
13134     case OMPD_parallel_master:
13135     case OMPD_parallel_sections:
13136     case OMPD_parallel_for:
13137     case OMPD_parallel_for_simd:
13138     case OMPD_target:
13139     case OMPD_target_simd:
13140     case OMPD_target_parallel:
13141     case OMPD_target_parallel_for:
13142     case OMPD_target_parallel_for_simd:
13143     case OMPD_threadprivate:
13144     case OMPD_allocate:
13145     case OMPD_taskyield:
13146     case OMPD_barrier:
13147     case OMPD_taskwait:
13148     case OMPD_cancellation_point:
13149     case OMPD_flush:
13150     case OMPD_depobj:
13151     case OMPD_scan:
13152     case OMPD_declare_reduction:
13153     case OMPD_declare_mapper:
13154     case OMPD_declare_simd:
13155     case OMPD_declare_variant:
13156     case OMPD_begin_declare_variant:
13157     case OMPD_end_declare_variant:
13158     case OMPD_declare_target:
13159     case OMPD_end_declare_target:
13160     case OMPD_simd:
13161     case OMPD_tile:
13162     case OMPD_for:
13163     case OMPD_for_simd:
13164     case OMPD_sections:
13165     case OMPD_section:
13166     case OMPD_single:
13167     case OMPD_master:
13168     case OMPD_critical:
13169     case OMPD_taskgroup:
13170     case OMPD_distribute:
13171     case OMPD_ordered:
13172     case OMPD_atomic:
13173     case OMPD_distribute_simd:
13174     case OMPD_requires:
13175       llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
13176     case OMPD_unknown:
13177     default:
13178       llvm_unreachable("Unknown OpenMP directive");
13179     }
13180     break;
13181   case OMPC_schedule:
13182     switch (DKind) {
13183     case OMPD_parallel_for:
13184     case OMPD_parallel_for_simd:
13185     case OMPD_distribute_parallel_for:
13186     case OMPD_distribute_parallel_for_simd:
13187     case OMPD_teams_distribute_parallel_for:
13188     case OMPD_teams_distribute_parallel_for_simd:
13189     case OMPD_target_parallel_for:
13190     case OMPD_target_parallel_for_simd:
13191     case OMPD_target_teams_distribute_parallel_for:
13192     case OMPD_target_teams_distribute_parallel_for_simd:
13193       CaptureRegion = OMPD_parallel;
13194       break;
13195     case OMPD_for:
13196     case OMPD_for_simd:
13197       // Do not capture schedule-clause expressions.
13198       break;
13199     case OMPD_task:
13200     case OMPD_taskloop:
13201     case OMPD_taskloop_simd:
13202     case OMPD_master_taskloop:
13203     case OMPD_master_taskloop_simd:
13204     case OMPD_parallel_master_taskloop:
13205     case OMPD_parallel_master_taskloop_simd:
13206     case OMPD_target_data:
13207     case OMPD_target_enter_data:
13208     case OMPD_target_exit_data:
13209     case OMPD_target_update:
13210     case OMPD_teams:
13211     case OMPD_teams_distribute:
13212     case OMPD_teams_distribute_simd:
13213     case OMPD_target_teams_distribute:
13214     case OMPD_target_teams_distribute_simd:
13215     case OMPD_target:
13216     case OMPD_target_simd:
13217     case OMPD_target_parallel:
13218     case OMPD_cancel:
13219     case OMPD_parallel:
13220     case OMPD_parallel_master:
13221     case OMPD_parallel_sections:
13222     case OMPD_threadprivate:
13223     case OMPD_allocate:
13224     case OMPD_taskyield:
13225     case OMPD_barrier:
13226     case OMPD_taskwait:
13227     case OMPD_cancellation_point:
13228     case OMPD_flush:
13229     case OMPD_depobj:
13230     case OMPD_scan:
13231     case OMPD_declare_reduction:
13232     case OMPD_declare_mapper:
13233     case OMPD_declare_simd:
13234     case OMPD_declare_variant:
13235     case OMPD_begin_declare_variant:
13236     case OMPD_end_declare_variant:
13237     case OMPD_declare_target:
13238     case OMPD_end_declare_target:
13239     case OMPD_simd:
13240     case OMPD_tile:
13241     case OMPD_sections:
13242     case OMPD_section:
13243     case OMPD_single:
13244     case OMPD_master:
13245     case OMPD_critical:
13246     case OMPD_taskgroup:
13247     case OMPD_distribute:
13248     case OMPD_ordered:
13249     case OMPD_atomic:
13250     case OMPD_distribute_simd:
13251     case OMPD_target_teams:
13252     case OMPD_requires:
13253       llvm_unreachable("Unexpected OpenMP directive with schedule clause");
13254     case OMPD_unknown:
13255     default:
13256       llvm_unreachable("Unknown OpenMP directive");
13257     }
13258     break;
13259   case OMPC_dist_schedule:
13260     switch (DKind) {
13261     case OMPD_teams_distribute_parallel_for:
13262     case OMPD_teams_distribute_parallel_for_simd:
13263     case OMPD_teams_distribute:
13264     case OMPD_teams_distribute_simd:
13265     case OMPD_target_teams_distribute_parallel_for:
13266     case OMPD_target_teams_distribute_parallel_for_simd:
13267     case OMPD_target_teams_distribute:
13268     case OMPD_target_teams_distribute_simd:
13269       CaptureRegion = OMPD_teams;
13270       break;
13271     case OMPD_distribute_parallel_for:
13272     case OMPD_distribute_parallel_for_simd:
13273     case OMPD_distribute:
13274     case OMPD_distribute_simd:
13275       // Do not capture dist_schedule-clause expressions.
13276       break;
13277     case OMPD_parallel_for:
13278     case OMPD_parallel_for_simd:
13279     case OMPD_target_parallel_for_simd:
13280     case OMPD_target_parallel_for:
13281     case OMPD_task:
13282     case OMPD_taskloop:
13283     case OMPD_taskloop_simd:
13284     case OMPD_master_taskloop:
13285     case OMPD_master_taskloop_simd:
13286     case OMPD_parallel_master_taskloop:
13287     case OMPD_parallel_master_taskloop_simd:
13288     case OMPD_target_data:
13289     case OMPD_target_enter_data:
13290     case OMPD_target_exit_data:
13291     case OMPD_target_update:
13292     case OMPD_teams:
13293     case OMPD_target:
13294     case OMPD_target_simd:
13295     case OMPD_target_parallel:
13296     case OMPD_cancel:
13297     case OMPD_parallel:
13298     case OMPD_parallel_master:
13299     case OMPD_parallel_sections:
13300     case OMPD_threadprivate:
13301     case OMPD_allocate:
13302     case OMPD_taskyield:
13303     case OMPD_barrier:
13304     case OMPD_taskwait:
13305     case OMPD_cancellation_point:
13306     case OMPD_flush:
13307     case OMPD_depobj:
13308     case OMPD_scan:
13309     case OMPD_declare_reduction:
13310     case OMPD_declare_mapper:
13311     case OMPD_declare_simd:
13312     case OMPD_declare_variant:
13313     case OMPD_begin_declare_variant:
13314     case OMPD_end_declare_variant:
13315     case OMPD_declare_target:
13316     case OMPD_end_declare_target:
13317     case OMPD_simd:
13318     case OMPD_tile:
13319     case OMPD_for:
13320     case OMPD_for_simd:
13321     case OMPD_sections:
13322     case OMPD_section:
13323     case OMPD_single:
13324     case OMPD_master:
13325     case OMPD_critical:
13326     case OMPD_taskgroup:
13327     case OMPD_ordered:
13328     case OMPD_atomic:
13329     case OMPD_target_teams:
13330     case OMPD_requires:
13331       llvm_unreachable("Unexpected OpenMP directive with dist_schedule clause");
13332     case OMPD_unknown:
13333     default:
13334       llvm_unreachable("Unknown OpenMP directive");
13335     }
13336     break;
13337   case OMPC_device:
13338     switch (DKind) {
13339     case OMPD_target_update:
13340     case OMPD_target_enter_data:
13341     case OMPD_target_exit_data:
13342     case OMPD_target:
13343     case OMPD_target_simd:
13344     case OMPD_target_teams:
13345     case OMPD_target_parallel:
13346     case OMPD_target_teams_distribute:
13347     case OMPD_target_teams_distribute_simd:
13348     case OMPD_target_parallel_for:
13349     case OMPD_target_parallel_for_simd:
13350     case OMPD_target_teams_distribute_parallel_for:
13351     case OMPD_target_teams_distribute_parallel_for_simd:
13352       CaptureRegion = OMPD_task;
13353       break;
13354     case OMPD_target_data:
13355     case OMPD_interop:
13356       // Do not capture device-clause expressions.
13357       break;
13358     case OMPD_teams_distribute_parallel_for:
13359     case OMPD_teams_distribute_parallel_for_simd:
13360     case OMPD_teams:
13361     case OMPD_teams_distribute:
13362     case OMPD_teams_distribute_simd:
13363     case OMPD_distribute_parallel_for:
13364     case OMPD_distribute_parallel_for_simd:
13365     case OMPD_task:
13366     case OMPD_taskloop:
13367     case OMPD_taskloop_simd:
13368     case OMPD_master_taskloop:
13369     case OMPD_master_taskloop_simd:
13370     case OMPD_parallel_master_taskloop:
13371     case OMPD_parallel_master_taskloop_simd:
13372     case OMPD_cancel:
13373     case OMPD_parallel:
13374     case OMPD_parallel_master:
13375     case OMPD_parallel_sections:
13376     case OMPD_parallel_for:
13377     case OMPD_parallel_for_simd:
13378     case OMPD_threadprivate:
13379     case OMPD_allocate:
13380     case OMPD_taskyield:
13381     case OMPD_barrier:
13382     case OMPD_taskwait:
13383     case OMPD_cancellation_point:
13384     case OMPD_flush:
13385     case OMPD_depobj:
13386     case OMPD_scan:
13387     case OMPD_declare_reduction:
13388     case OMPD_declare_mapper:
13389     case OMPD_declare_simd:
13390     case OMPD_declare_variant:
13391     case OMPD_begin_declare_variant:
13392     case OMPD_end_declare_variant:
13393     case OMPD_declare_target:
13394     case OMPD_end_declare_target:
13395     case OMPD_simd:
13396     case OMPD_tile:
13397     case OMPD_for:
13398     case OMPD_for_simd:
13399     case OMPD_sections:
13400     case OMPD_section:
13401     case OMPD_single:
13402     case OMPD_master:
13403     case OMPD_critical:
13404     case OMPD_taskgroup:
13405     case OMPD_distribute:
13406     case OMPD_ordered:
13407     case OMPD_atomic:
13408     case OMPD_distribute_simd:
13409     case OMPD_requires:
13410       llvm_unreachable("Unexpected OpenMP directive with device-clause");
13411     case OMPD_unknown:
13412     default:
13413       llvm_unreachable("Unknown OpenMP directive");
13414     }
13415     break;
13416   case OMPC_grainsize:
13417   case OMPC_num_tasks:
13418   case OMPC_final:
13419   case OMPC_priority:
13420     switch (DKind) {
13421     case OMPD_task:
13422     case OMPD_taskloop:
13423     case OMPD_taskloop_simd:
13424     case OMPD_master_taskloop:
13425     case OMPD_master_taskloop_simd:
13426       break;
13427     case OMPD_parallel_master_taskloop:
13428     case OMPD_parallel_master_taskloop_simd:
13429       CaptureRegion = OMPD_parallel;
13430       break;
13431     case OMPD_target_update:
13432     case OMPD_target_enter_data:
13433     case OMPD_target_exit_data:
13434     case OMPD_target:
13435     case OMPD_target_simd:
13436     case OMPD_target_teams:
13437     case OMPD_target_parallel:
13438     case OMPD_target_teams_distribute:
13439     case OMPD_target_teams_distribute_simd:
13440     case OMPD_target_parallel_for:
13441     case OMPD_target_parallel_for_simd:
13442     case OMPD_target_teams_distribute_parallel_for:
13443     case OMPD_target_teams_distribute_parallel_for_simd:
13444     case OMPD_target_data:
13445     case OMPD_teams_distribute_parallel_for:
13446     case OMPD_teams_distribute_parallel_for_simd:
13447     case OMPD_teams:
13448     case OMPD_teams_distribute:
13449     case OMPD_teams_distribute_simd:
13450     case OMPD_distribute_parallel_for:
13451     case OMPD_distribute_parallel_for_simd:
13452     case OMPD_cancel:
13453     case OMPD_parallel:
13454     case OMPD_parallel_master:
13455     case OMPD_parallel_sections:
13456     case OMPD_parallel_for:
13457     case OMPD_parallel_for_simd:
13458     case OMPD_threadprivate:
13459     case OMPD_allocate:
13460     case OMPD_taskyield:
13461     case OMPD_barrier:
13462     case OMPD_taskwait:
13463     case OMPD_cancellation_point:
13464     case OMPD_flush:
13465     case OMPD_depobj:
13466     case OMPD_scan:
13467     case OMPD_declare_reduction:
13468     case OMPD_declare_mapper:
13469     case OMPD_declare_simd:
13470     case OMPD_declare_variant:
13471     case OMPD_begin_declare_variant:
13472     case OMPD_end_declare_variant:
13473     case OMPD_declare_target:
13474     case OMPD_end_declare_target:
13475     case OMPD_simd:
13476     case OMPD_tile:
13477     case OMPD_for:
13478     case OMPD_for_simd:
13479     case OMPD_sections:
13480     case OMPD_section:
13481     case OMPD_single:
13482     case OMPD_master:
13483     case OMPD_critical:
13484     case OMPD_taskgroup:
13485     case OMPD_distribute:
13486     case OMPD_ordered:
13487     case OMPD_atomic:
13488     case OMPD_distribute_simd:
13489     case OMPD_requires:
13490       llvm_unreachable("Unexpected OpenMP directive with grainsize-clause");
13491     case OMPD_unknown:
13492     default:
13493       llvm_unreachable("Unknown OpenMP directive");
13494     }
13495     break;
13496   case OMPC_firstprivate:
13497   case OMPC_lastprivate:
13498   case OMPC_reduction:
13499   case OMPC_task_reduction:
13500   case OMPC_in_reduction:
13501   case OMPC_linear:
13502   case OMPC_default:
13503   case OMPC_proc_bind:
13504   case OMPC_safelen:
13505   case OMPC_simdlen:
13506   case OMPC_sizes:
13507   case OMPC_allocator:
13508   case OMPC_collapse:
13509   case OMPC_private:
13510   case OMPC_shared:
13511   case OMPC_aligned:
13512   case OMPC_copyin:
13513   case OMPC_copyprivate:
13514   case OMPC_ordered:
13515   case OMPC_nowait:
13516   case OMPC_untied:
13517   case OMPC_mergeable:
13518   case OMPC_threadprivate:
13519   case OMPC_allocate:
13520   case OMPC_flush:
13521   case OMPC_depobj:
13522   case OMPC_read:
13523   case OMPC_write:
13524   case OMPC_update:
13525   case OMPC_capture:
13526   case OMPC_seq_cst:
13527   case OMPC_acq_rel:
13528   case OMPC_acquire:
13529   case OMPC_release:
13530   case OMPC_relaxed:
13531   case OMPC_depend:
13532   case OMPC_threads:
13533   case OMPC_simd:
13534   case OMPC_map:
13535   case OMPC_nogroup:
13536   case OMPC_hint:
13537   case OMPC_defaultmap:
13538   case OMPC_unknown:
13539   case OMPC_uniform:
13540   case OMPC_to:
13541   case OMPC_from:
13542   case OMPC_use_device_ptr:
13543   case OMPC_use_device_addr:
13544   case OMPC_is_device_ptr:
13545   case OMPC_unified_address:
13546   case OMPC_unified_shared_memory:
13547   case OMPC_reverse_offload:
13548   case OMPC_dynamic_allocators:
13549   case OMPC_atomic_default_mem_order:
13550   case OMPC_device_type:
13551   case OMPC_match:
13552   case OMPC_nontemporal:
13553   case OMPC_order:
13554   case OMPC_destroy:
13555   case OMPC_detach:
13556   case OMPC_inclusive:
13557   case OMPC_exclusive:
13558   case OMPC_uses_allocators:
13559   case OMPC_affinity:
13560   default:
13561     llvm_unreachable("Unexpected OpenMP clause.");
13562   }
13563   return CaptureRegion;
13564 }
13565 
13566 OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
13567                                      Expr *Condition, SourceLocation StartLoc,
13568                                      SourceLocation LParenLoc,
13569                                      SourceLocation NameModifierLoc,
13570                                      SourceLocation ColonLoc,
13571                                      SourceLocation EndLoc) {
13572   Expr *ValExpr = Condition;
13573   Stmt *HelperValStmt = nullptr;
13574   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
13575   if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
13576       !Condition->isInstantiationDependent() &&
13577       !Condition->containsUnexpandedParameterPack()) {
13578     ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
13579     if (Val.isInvalid())
13580       return nullptr;
13581 
13582     ValExpr = Val.get();
13583 
13584     OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
13585     CaptureRegion = getOpenMPCaptureRegionForClause(
13586         DKind, OMPC_if, LangOpts.OpenMP, NameModifier);
13587     if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
13588       ValExpr = MakeFullExpr(ValExpr).get();
13589       llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
13590       ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
13591       HelperValStmt = buildPreInits(Context, Captures);
13592     }
13593   }
13594 
13595   return new (Context)
13596       OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
13597                   LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
13598 }
13599 
13600 OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
13601                                         SourceLocation StartLoc,
13602                                         SourceLocation LParenLoc,
13603                                         SourceLocation EndLoc) {
13604   Expr *ValExpr = Condition;
13605   Stmt *HelperValStmt = nullptr;
13606   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
13607   if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
13608       !Condition->isInstantiationDependent() &&
13609       !Condition->containsUnexpandedParameterPack()) {
13610     ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
13611     if (Val.isInvalid())
13612       return nullptr;
13613 
13614     ValExpr = MakeFullExpr(Val.get()).get();
13615 
13616     OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
13617     CaptureRegion =
13618         getOpenMPCaptureRegionForClause(DKind, OMPC_final, LangOpts.OpenMP);
13619     if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
13620       ValExpr = MakeFullExpr(ValExpr).get();
13621       llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
13622       ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
13623       HelperValStmt = buildPreInits(Context, Captures);
13624     }
13625   }
13626 
13627   return new (Context) OMPFinalClause(ValExpr, HelperValStmt, CaptureRegion,
13628                                       StartLoc, LParenLoc, EndLoc);
13629 }
13630 
13631 ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
13632                                                         Expr *Op) {
13633   if (!Op)
13634     return ExprError();
13635 
13636   class IntConvertDiagnoser : public ICEConvertDiagnoser {
13637   public:
13638     IntConvertDiagnoser()
13639         : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
13640     SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
13641                                          QualType T) override {
13642       return S.Diag(Loc, diag::err_omp_not_integral) << T;
13643     }
13644     SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
13645                                              QualType T) override {
13646       return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
13647     }
13648     SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
13649                                                QualType T,
13650                                                QualType ConvTy) override {
13651       return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
13652     }
13653     SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
13654                                            QualType ConvTy) override {
13655       return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
13656              << ConvTy->isEnumeralType() << ConvTy;
13657     }
13658     SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
13659                                             QualType T) override {
13660       return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
13661     }
13662     SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
13663                                         QualType ConvTy) override {
13664       return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
13665              << ConvTy->isEnumeralType() << ConvTy;
13666     }
13667     SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
13668                                              QualType) override {
13669       llvm_unreachable("conversion functions are permitted");
13670     }
13671   } ConvertDiagnoser;
13672   return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
13673 }
13674 
13675 static bool
13676 isNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef, OpenMPClauseKind CKind,
13677                           bool StrictlyPositive, bool BuildCapture = false,
13678                           OpenMPDirectiveKind DKind = OMPD_unknown,
13679                           OpenMPDirectiveKind *CaptureRegion = nullptr,
13680                           Stmt **HelperValStmt = nullptr) {
13681   if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
13682       !ValExpr->isInstantiationDependent()) {
13683     SourceLocation Loc = ValExpr->getExprLoc();
13684     ExprResult Value =
13685         SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
13686     if (Value.isInvalid())
13687       return false;
13688 
13689     ValExpr = Value.get();
13690     // The expression must evaluate to a non-negative integer value.
13691     if (Optional<llvm::APSInt> Result =
13692             ValExpr->getIntegerConstantExpr(SemaRef.Context)) {
13693       if (Result->isSigned() &&
13694           !((!StrictlyPositive && Result->isNonNegative()) ||
13695             (StrictlyPositive && Result->isStrictlyPositive()))) {
13696         SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
13697             << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
13698             << ValExpr->getSourceRange();
13699         return false;
13700       }
13701     }
13702     if (!BuildCapture)
13703       return true;
13704     *CaptureRegion =
13705         getOpenMPCaptureRegionForClause(DKind, CKind, SemaRef.LangOpts.OpenMP);
13706     if (*CaptureRegion != OMPD_unknown &&
13707         !SemaRef.CurContext->isDependentContext()) {
13708       ValExpr = SemaRef.MakeFullExpr(ValExpr).get();
13709       llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
13710       ValExpr = tryBuildCapture(SemaRef, ValExpr, Captures).get();
13711       *HelperValStmt = buildPreInits(SemaRef.Context, Captures);
13712     }
13713   }
13714   return true;
13715 }
13716 
13717 OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
13718                                              SourceLocation StartLoc,
13719                                              SourceLocation LParenLoc,
13720                                              SourceLocation EndLoc) {
13721   Expr *ValExpr = NumThreads;
13722   Stmt *HelperValStmt = nullptr;
13723 
13724   // OpenMP [2.5, Restrictions]
13725   //  The num_threads expression must evaluate to a positive integer value.
13726   if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
13727                                  /*StrictlyPositive=*/true))
13728     return nullptr;
13729 
13730   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
13731   OpenMPDirectiveKind CaptureRegion =
13732       getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads, LangOpts.OpenMP);
13733   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
13734     ValExpr = MakeFullExpr(ValExpr).get();
13735     llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
13736     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
13737     HelperValStmt = buildPreInits(Context, Captures);
13738   }
13739 
13740   return new (Context) OMPNumThreadsClause(
13741       ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
13742 }
13743 
13744 ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
13745                                                        OpenMPClauseKind CKind,
13746                                                        bool StrictlyPositive) {
13747   if (!E)
13748     return ExprError();
13749   if (E->isValueDependent() || E->isTypeDependent() ||
13750       E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
13751     return E;
13752   llvm::APSInt Result;
13753   ExprResult ICE =
13754       VerifyIntegerConstantExpression(E, &Result, /*FIXME*/ AllowFold);
13755   if (ICE.isInvalid())
13756     return ExprError();
13757   if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
13758       (!StrictlyPositive && !Result.isNonNegative())) {
13759     Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
13760         << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
13761         << E->getSourceRange();
13762     return ExprError();
13763   }
13764   if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
13765     Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
13766         << E->getSourceRange();
13767     return ExprError();
13768   }
13769   if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
13770     DSAStack->setAssociatedLoops(Result.getExtValue());
13771   else if (CKind == OMPC_ordered)
13772     DSAStack->setAssociatedLoops(Result.getExtValue());
13773   return ICE;
13774 }
13775 
13776 OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
13777                                           SourceLocation LParenLoc,
13778                                           SourceLocation EndLoc) {
13779   // OpenMP [2.8.1, simd construct, Description]
13780   // The parameter of the safelen clause must be a constant
13781   // positive integer expression.
13782   ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
13783   if (Safelen.isInvalid())
13784     return nullptr;
13785   return new (Context)
13786       OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
13787 }
13788 
13789 OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
13790                                           SourceLocation LParenLoc,
13791                                           SourceLocation EndLoc) {
13792   // OpenMP [2.8.1, simd construct, Description]
13793   // The parameter of the simdlen clause must be a constant
13794   // positive integer expression.
13795   ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
13796   if (Simdlen.isInvalid())
13797     return nullptr;
13798   return new (Context)
13799       OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
13800 }
13801 
13802 /// Tries to find omp_allocator_handle_t type.
13803 static bool findOMPAllocatorHandleT(Sema &S, SourceLocation Loc,
13804                                     DSAStackTy *Stack) {
13805   QualType OMPAllocatorHandleT = Stack->getOMPAllocatorHandleT();
13806   if (!OMPAllocatorHandleT.isNull())
13807     return true;
13808   // Build the predefined allocator expressions.
13809   bool ErrorFound = false;
13810   for (int I = 0; I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
13811     auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
13812     StringRef Allocator =
13813         OMPAllocateDeclAttr::ConvertAllocatorTypeTyToStr(AllocatorKind);
13814     DeclarationName AllocatorName = &S.getASTContext().Idents.get(Allocator);
13815     auto *VD = dyn_cast_or_null<ValueDecl>(
13816         S.LookupSingleName(S.TUScope, AllocatorName, Loc, Sema::LookupAnyName));
13817     if (!VD) {
13818       ErrorFound = true;
13819       break;
13820     }
13821     QualType AllocatorType =
13822         VD->getType().getNonLValueExprType(S.getASTContext());
13823     ExprResult Res = S.BuildDeclRefExpr(VD, AllocatorType, VK_LValue, Loc);
13824     if (!Res.isUsable()) {
13825       ErrorFound = true;
13826       break;
13827     }
13828     if (OMPAllocatorHandleT.isNull())
13829       OMPAllocatorHandleT = AllocatorType;
13830     if (!S.getASTContext().hasSameType(OMPAllocatorHandleT, AllocatorType)) {
13831       ErrorFound = true;
13832       break;
13833     }
13834     Stack->setAllocator(AllocatorKind, Res.get());
13835   }
13836   if (ErrorFound) {
13837     S.Diag(Loc, diag::err_omp_implied_type_not_found)
13838         << "omp_allocator_handle_t";
13839     return false;
13840   }
13841   OMPAllocatorHandleT.addConst();
13842   Stack->setOMPAllocatorHandleT(OMPAllocatorHandleT);
13843   return true;
13844 }
13845 
13846 OMPClause *Sema::ActOnOpenMPAllocatorClause(Expr *A, SourceLocation StartLoc,
13847                                             SourceLocation LParenLoc,
13848                                             SourceLocation EndLoc) {
13849   // OpenMP [2.11.3, allocate Directive, Description]
13850   // allocator is an expression of omp_allocator_handle_t type.
13851   if (!findOMPAllocatorHandleT(*this, A->getExprLoc(), DSAStack))
13852     return nullptr;
13853 
13854   ExprResult Allocator = DefaultLvalueConversion(A);
13855   if (Allocator.isInvalid())
13856     return nullptr;
13857   Allocator = PerformImplicitConversion(Allocator.get(),
13858                                         DSAStack->getOMPAllocatorHandleT(),
13859                                         Sema::AA_Initializing,
13860                                         /*AllowExplicit=*/true);
13861   if (Allocator.isInvalid())
13862     return nullptr;
13863   return new (Context)
13864       OMPAllocatorClause(Allocator.get(), StartLoc, LParenLoc, EndLoc);
13865 }
13866 
13867 OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
13868                                            SourceLocation StartLoc,
13869                                            SourceLocation LParenLoc,
13870                                            SourceLocation EndLoc) {
13871   // OpenMP [2.7.1, loop construct, Description]
13872   // OpenMP [2.8.1, simd construct, Description]
13873   // OpenMP [2.9.6, distribute construct, Description]
13874   // The parameter of the collapse clause must be a constant
13875   // positive integer expression.
13876   ExprResult NumForLoopsResult =
13877       VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
13878   if (NumForLoopsResult.isInvalid())
13879     return nullptr;
13880   return new (Context)
13881       OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
13882 }
13883 
13884 OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
13885                                           SourceLocation EndLoc,
13886                                           SourceLocation LParenLoc,
13887                                           Expr *NumForLoops) {
13888   // OpenMP [2.7.1, loop construct, Description]
13889   // OpenMP [2.8.1, simd construct, Description]
13890   // OpenMP [2.9.6, distribute construct, Description]
13891   // The parameter of the ordered clause must be a constant
13892   // positive integer expression if any.
13893   if (NumForLoops && LParenLoc.isValid()) {
13894     ExprResult NumForLoopsResult =
13895         VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
13896     if (NumForLoopsResult.isInvalid())
13897       return nullptr;
13898     NumForLoops = NumForLoopsResult.get();
13899   } else {
13900     NumForLoops = nullptr;
13901   }
13902   auto *Clause = OMPOrderedClause::Create(
13903       Context, NumForLoops, NumForLoops ? DSAStack->getAssociatedLoops() : 0,
13904       StartLoc, LParenLoc, EndLoc);
13905   DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops, Clause);
13906   return Clause;
13907 }
13908 
13909 OMPClause *Sema::ActOnOpenMPSimpleClause(
13910     OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
13911     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
13912   OMPClause *Res = nullptr;
13913   switch (Kind) {
13914   case OMPC_default:
13915     Res = ActOnOpenMPDefaultClause(static_cast<DefaultKind>(Argument),
13916                                    ArgumentLoc, StartLoc, LParenLoc, EndLoc);
13917     break;
13918   case OMPC_proc_bind:
13919     Res = ActOnOpenMPProcBindClause(static_cast<ProcBindKind>(Argument),
13920                                     ArgumentLoc, StartLoc, LParenLoc, EndLoc);
13921     break;
13922   case OMPC_atomic_default_mem_order:
13923     Res = ActOnOpenMPAtomicDefaultMemOrderClause(
13924         static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Argument),
13925         ArgumentLoc, StartLoc, LParenLoc, EndLoc);
13926     break;
13927   case OMPC_order:
13928     Res = ActOnOpenMPOrderClause(static_cast<OpenMPOrderClauseKind>(Argument),
13929                                  ArgumentLoc, StartLoc, LParenLoc, EndLoc);
13930     break;
13931   case OMPC_update:
13932     Res = ActOnOpenMPUpdateClause(static_cast<OpenMPDependClauseKind>(Argument),
13933                                   ArgumentLoc, StartLoc, LParenLoc, EndLoc);
13934     break;
13935   case OMPC_if:
13936   case OMPC_final:
13937   case OMPC_num_threads:
13938   case OMPC_safelen:
13939   case OMPC_simdlen:
13940   case OMPC_sizes:
13941   case OMPC_allocator:
13942   case OMPC_collapse:
13943   case OMPC_schedule:
13944   case OMPC_private:
13945   case OMPC_firstprivate:
13946   case OMPC_lastprivate:
13947   case OMPC_shared:
13948   case OMPC_reduction:
13949   case OMPC_task_reduction:
13950   case OMPC_in_reduction:
13951   case OMPC_linear:
13952   case OMPC_aligned:
13953   case OMPC_copyin:
13954   case OMPC_copyprivate:
13955   case OMPC_ordered:
13956   case OMPC_nowait:
13957   case OMPC_untied:
13958   case OMPC_mergeable:
13959   case OMPC_threadprivate:
13960   case OMPC_allocate:
13961   case OMPC_flush:
13962   case OMPC_depobj:
13963   case OMPC_read:
13964   case OMPC_write:
13965   case OMPC_capture:
13966   case OMPC_seq_cst:
13967   case OMPC_acq_rel:
13968   case OMPC_acquire:
13969   case OMPC_release:
13970   case OMPC_relaxed:
13971   case OMPC_depend:
13972   case OMPC_device:
13973   case OMPC_threads:
13974   case OMPC_simd:
13975   case OMPC_map:
13976   case OMPC_num_teams:
13977   case OMPC_thread_limit:
13978   case OMPC_priority:
13979   case OMPC_grainsize:
13980   case OMPC_nogroup:
13981   case OMPC_num_tasks:
13982   case OMPC_hint:
13983   case OMPC_dist_schedule:
13984   case OMPC_defaultmap:
13985   case OMPC_unknown:
13986   case OMPC_uniform:
13987   case OMPC_to:
13988   case OMPC_from:
13989   case OMPC_use_device_ptr:
13990   case OMPC_use_device_addr:
13991   case OMPC_is_device_ptr:
13992   case OMPC_unified_address:
13993   case OMPC_unified_shared_memory:
13994   case OMPC_reverse_offload:
13995   case OMPC_dynamic_allocators:
13996   case OMPC_device_type:
13997   case OMPC_match:
13998   case OMPC_nontemporal:
13999   case OMPC_destroy:
14000   case OMPC_detach:
14001   case OMPC_inclusive:
14002   case OMPC_exclusive:
14003   case OMPC_uses_allocators:
14004   case OMPC_affinity:
14005   default:
14006     llvm_unreachable("Clause is not allowed.");
14007   }
14008   return Res;
14009 }
14010 
14011 static std::string
14012 getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
14013                         ArrayRef<unsigned> Exclude = llvm::None) {
14014   SmallString<256> Buffer;
14015   llvm::raw_svector_ostream Out(Buffer);
14016   unsigned Skipped = Exclude.size();
14017   auto S = Exclude.begin(), E = Exclude.end();
14018   for (unsigned I = First; I < Last; ++I) {
14019     if (std::find(S, E, I) != E) {
14020       --Skipped;
14021       continue;
14022     }
14023     Out << "'" << getOpenMPSimpleClauseTypeName(K, I) << "'";
14024     if (I + Skipped + 2 == Last)
14025       Out << " or ";
14026     else if (I + Skipped + 1 != Last)
14027       Out << ", ";
14028   }
14029   return std::string(Out.str());
14030 }
14031 
14032 OMPClause *Sema::ActOnOpenMPDefaultClause(DefaultKind Kind,
14033                                           SourceLocation KindKwLoc,
14034                                           SourceLocation StartLoc,
14035                                           SourceLocation LParenLoc,
14036                                           SourceLocation EndLoc) {
14037   if (Kind == OMP_DEFAULT_unknown) {
14038     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
14039         << getListOfPossibleValues(OMPC_default, /*First=*/0,
14040                                    /*Last=*/unsigned(OMP_DEFAULT_unknown))
14041         << getOpenMPClauseName(OMPC_default);
14042     return nullptr;
14043   }
14044 
14045   switch (Kind) {
14046   case OMP_DEFAULT_none:
14047     DSAStack->setDefaultDSANone(KindKwLoc);
14048     break;
14049   case OMP_DEFAULT_shared:
14050     DSAStack->setDefaultDSAShared(KindKwLoc);
14051     break;
14052   case OMP_DEFAULT_firstprivate:
14053     DSAStack->setDefaultDSAFirstPrivate(KindKwLoc);
14054     break;
14055   default:
14056     llvm_unreachable("DSA unexpected in OpenMP default clause");
14057   }
14058 
14059   return new (Context)
14060       OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
14061 }
14062 
14063 OMPClause *Sema::ActOnOpenMPProcBindClause(ProcBindKind Kind,
14064                                            SourceLocation KindKwLoc,
14065                                            SourceLocation StartLoc,
14066                                            SourceLocation LParenLoc,
14067                                            SourceLocation EndLoc) {
14068   if (Kind == OMP_PROC_BIND_unknown) {
14069     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
14070         << getListOfPossibleValues(OMPC_proc_bind,
14071                                    /*First=*/unsigned(OMP_PROC_BIND_master),
14072                                    /*Last=*/5)
14073         << getOpenMPClauseName(OMPC_proc_bind);
14074     return nullptr;
14075   }
14076   return new (Context)
14077       OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
14078 }
14079 
14080 OMPClause *Sema::ActOnOpenMPAtomicDefaultMemOrderClause(
14081     OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindKwLoc,
14082     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
14083   if (Kind == OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown) {
14084     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
14085         << getListOfPossibleValues(
14086                OMPC_atomic_default_mem_order, /*First=*/0,
14087                /*Last=*/OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown)
14088         << getOpenMPClauseName(OMPC_atomic_default_mem_order);
14089     return nullptr;
14090   }
14091   return new (Context) OMPAtomicDefaultMemOrderClause(Kind, KindKwLoc, StartLoc,
14092                                                       LParenLoc, EndLoc);
14093 }
14094 
14095 OMPClause *Sema::ActOnOpenMPOrderClause(OpenMPOrderClauseKind Kind,
14096                                         SourceLocation KindKwLoc,
14097                                         SourceLocation StartLoc,
14098                                         SourceLocation LParenLoc,
14099                                         SourceLocation EndLoc) {
14100   if (Kind == OMPC_ORDER_unknown) {
14101     static_assert(OMPC_ORDER_unknown > 0,
14102                   "OMPC_ORDER_unknown not greater than 0");
14103     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
14104         << getListOfPossibleValues(OMPC_order, /*First=*/0,
14105                                    /*Last=*/OMPC_ORDER_unknown)
14106         << getOpenMPClauseName(OMPC_order);
14107     return nullptr;
14108   }
14109   return new (Context)
14110       OMPOrderClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
14111 }
14112 
14113 OMPClause *Sema::ActOnOpenMPUpdateClause(OpenMPDependClauseKind Kind,
14114                                          SourceLocation KindKwLoc,
14115                                          SourceLocation StartLoc,
14116                                          SourceLocation LParenLoc,
14117                                          SourceLocation EndLoc) {
14118   if (Kind == OMPC_DEPEND_unknown || Kind == OMPC_DEPEND_source ||
14119       Kind == OMPC_DEPEND_sink || Kind == OMPC_DEPEND_depobj) {
14120     unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink,
14121                          OMPC_DEPEND_depobj};
14122     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
14123         << getListOfPossibleValues(OMPC_depend, /*First=*/0,
14124                                    /*Last=*/OMPC_DEPEND_unknown, Except)
14125         << getOpenMPClauseName(OMPC_update);
14126     return nullptr;
14127   }
14128   return OMPUpdateClause::Create(Context, StartLoc, LParenLoc, KindKwLoc, Kind,
14129                                  EndLoc);
14130 }
14131 
14132 OMPClause *Sema::ActOnOpenMPSizesClause(ArrayRef<Expr *> SizeExprs,
14133                                         SourceLocation StartLoc,
14134                                         SourceLocation LParenLoc,
14135                                         SourceLocation EndLoc) {
14136   for (Expr *SizeExpr : SizeExprs) {
14137     ExprResult NumForLoopsResult = VerifyPositiveIntegerConstantInClause(
14138         SizeExpr, OMPC_sizes, /*StrictlyPositive=*/true);
14139     if (!NumForLoopsResult.isUsable())
14140       return nullptr;
14141   }
14142 
14143   DSAStack->setAssociatedLoops(SizeExprs.size());
14144   return OMPSizesClause::Create(Context, StartLoc, LParenLoc, EndLoc,
14145                                 SizeExprs);
14146 }
14147 
14148 OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
14149     OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
14150     SourceLocation StartLoc, SourceLocation LParenLoc,
14151     ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
14152     SourceLocation EndLoc) {
14153   OMPClause *Res = nullptr;
14154   switch (Kind) {
14155   case OMPC_schedule:
14156     enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
14157     assert(Argument.size() == NumberOfElements &&
14158            ArgumentLoc.size() == NumberOfElements);
14159     Res = ActOnOpenMPScheduleClause(
14160         static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
14161         static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
14162         static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
14163         StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
14164         ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
14165     break;
14166   case OMPC_if:
14167     assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
14168     Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
14169                               Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
14170                               DelimLoc, EndLoc);
14171     break;
14172   case OMPC_dist_schedule:
14173     Res = ActOnOpenMPDistScheduleClause(
14174         static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
14175         StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
14176     break;
14177   case OMPC_defaultmap:
14178     enum { Modifier, DefaultmapKind };
14179     Res = ActOnOpenMPDefaultmapClause(
14180         static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
14181         static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
14182         StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
14183         EndLoc);
14184     break;
14185   case OMPC_device:
14186     assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
14187     Res = ActOnOpenMPDeviceClause(
14188         static_cast<OpenMPDeviceClauseModifier>(Argument.back()), Expr,
14189         StartLoc, LParenLoc, ArgumentLoc.back(), EndLoc);
14190     break;
14191   case OMPC_final:
14192   case OMPC_num_threads:
14193   case OMPC_safelen:
14194   case OMPC_simdlen:
14195   case OMPC_sizes:
14196   case OMPC_allocator:
14197   case OMPC_collapse:
14198   case OMPC_default:
14199   case OMPC_proc_bind:
14200   case OMPC_private:
14201   case OMPC_firstprivate:
14202   case OMPC_lastprivate:
14203   case OMPC_shared:
14204   case OMPC_reduction:
14205   case OMPC_task_reduction:
14206   case OMPC_in_reduction:
14207   case OMPC_linear:
14208   case OMPC_aligned:
14209   case OMPC_copyin:
14210   case OMPC_copyprivate:
14211   case OMPC_ordered:
14212   case OMPC_nowait:
14213   case OMPC_untied:
14214   case OMPC_mergeable:
14215   case OMPC_threadprivate:
14216   case OMPC_allocate:
14217   case OMPC_flush:
14218   case OMPC_depobj:
14219   case OMPC_read:
14220   case OMPC_write:
14221   case OMPC_update:
14222   case OMPC_capture:
14223   case OMPC_seq_cst:
14224   case OMPC_acq_rel:
14225   case OMPC_acquire:
14226   case OMPC_release:
14227   case OMPC_relaxed:
14228   case OMPC_depend:
14229   case OMPC_threads:
14230   case OMPC_simd:
14231   case OMPC_map:
14232   case OMPC_num_teams:
14233   case OMPC_thread_limit:
14234   case OMPC_priority:
14235   case OMPC_grainsize:
14236   case OMPC_nogroup:
14237   case OMPC_num_tasks:
14238   case OMPC_hint:
14239   case OMPC_unknown:
14240   case OMPC_uniform:
14241   case OMPC_to:
14242   case OMPC_from:
14243   case OMPC_use_device_ptr:
14244   case OMPC_use_device_addr:
14245   case OMPC_is_device_ptr:
14246   case OMPC_unified_address:
14247   case OMPC_unified_shared_memory:
14248   case OMPC_reverse_offload:
14249   case OMPC_dynamic_allocators:
14250   case OMPC_atomic_default_mem_order:
14251   case OMPC_device_type:
14252   case OMPC_match:
14253   case OMPC_nontemporal:
14254   case OMPC_order:
14255   case OMPC_destroy:
14256   case OMPC_detach:
14257   case OMPC_inclusive:
14258   case OMPC_exclusive:
14259   case OMPC_uses_allocators:
14260   case OMPC_affinity:
14261   default:
14262     llvm_unreachable("Clause is not allowed.");
14263   }
14264   return Res;
14265 }
14266 
14267 static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
14268                                    OpenMPScheduleClauseModifier M2,
14269                                    SourceLocation M1Loc, SourceLocation M2Loc) {
14270   if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
14271     SmallVector<unsigned, 2> Excluded;
14272     if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
14273       Excluded.push_back(M2);
14274     if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
14275       Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
14276     if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
14277       Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
14278     S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
14279         << getListOfPossibleValues(OMPC_schedule,
14280                                    /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
14281                                    /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
14282                                    Excluded)
14283         << getOpenMPClauseName(OMPC_schedule);
14284     return true;
14285   }
14286   return false;
14287 }
14288 
14289 OMPClause *Sema::ActOnOpenMPScheduleClause(
14290     OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
14291     OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
14292     SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
14293     SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
14294   if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
14295       checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
14296     return nullptr;
14297   // OpenMP, 2.7.1, Loop Construct, Restrictions
14298   // Either the monotonic modifier or the nonmonotonic modifier can be specified
14299   // but not both.
14300   if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
14301       (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
14302        M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
14303       (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
14304        M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
14305     Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
14306         << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
14307         << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
14308     return nullptr;
14309   }
14310   if (Kind == OMPC_SCHEDULE_unknown) {
14311     std::string Values;
14312     if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
14313       unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
14314       Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
14315                                        /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
14316                                        Exclude);
14317     } else {
14318       Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
14319                                        /*Last=*/OMPC_SCHEDULE_unknown);
14320     }
14321     Diag(KindLoc, diag::err_omp_unexpected_clause_value)
14322         << Values << getOpenMPClauseName(OMPC_schedule);
14323     return nullptr;
14324   }
14325   // OpenMP, 2.7.1, Loop Construct, Restrictions
14326   // The nonmonotonic modifier can only be specified with schedule(dynamic) or
14327   // schedule(guided).
14328   // OpenMP 5.0 does not have this restriction.
14329   if (LangOpts.OpenMP < 50 &&
14330       (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
14331        M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
14332       Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
14333     Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
14334          diag::err_omp_schedule_nonmonotonic_static);
14335     return nullptr;
14336   }
14337   Expr *ValExpr = ChunkSize;
14338   Stmt *HelperValStmt = nullptr;
14339   if (ChunkSize) {
14340     if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
14341         !ChunkSize->isInstantiationDependent() &&
14342         !ChunkSize->containsUnexpandedParameterPack()) {
14343       SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
14344       ExprResult Val =
14345           PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
14346       if (Val.isInvalid())
14347         return nullptr;
14348 
14349       ValExpr = Val.get();
14350 
14351       // OpenMP [2.7.1, Restrictions]
14352       //  chunk_size must be a loop invariant integer expression with a positive
14353       //  value.
14354       if (Optional<llvm::APSInt> Result =
14355               ValExpr->getIntegerConstantExpr(Context)) {
14356         if (Result->isSigned() && !Result->isStrictlyPositive()) {
14357           Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
14358               << "schedule" << 1 << ChunkSize->getSourceRange();
14359           return nullptr;
14360         }
14361       } else if (getOpenMPCaptureRegionForClause(
14362                      DSAStack->getCurrentDirective(), OMPC_schedule,
14363                      LangOpts.OpenMP) != OMPD_unknown &&
14364                  !CurContext->isDependentContext()) {
14365         ValExpr = MakeFullExpr(ValExpr).get();
14366         llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
14367         ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
14368         HelperValStmt = buildPreInits(Context, Captures);
14369       }
14370     }
14371   }
14372 
14373   return new (Context)
14374       OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
14375                         ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
14376 }
14377 
14378 OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
14379                                    SourceLocation StartLoc,
14380                                    SourceLocation EndLoc) {
14381   OMPClause *Res = nullptr;
14382   switch (Kind) {
14383   case OMPC_ordered:
14384     Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
14385     break;
14386   case OMPC_nowait:
14387     Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
14388     break;
14389   case OMPC_untied:
14390     Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
14391     break;
14392   case OMPC_mergeable:
14393     Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
14394     break;
14395   case OMPC_read:
14396     Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
14397     break;
14398   case OMPC_write:
14399     Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
14400     break;
14401   case OMPC_update:
14402     Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
14403     break;
14404   case OMPC_capture:
14405     Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
14406     break;
14407   case OMPC_seq_cst:
14408     Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
14409     break;
14410   case OMPC_acq_rel:
14411     Res = ActOnOpenMPAcqRelClause(StartLoc, EndLoc);
14412     break;
14413   case OMPC_acquire:
14414     Res = ActOnOpenMPAcquireClause(StartLoc, EndLoc);
14415     break;
14416   case OMPC_release:
14417     Res = ActOnOpenMPReleaseClause(StartLoc, EndLoc);
14418     break;
14419   case OMPC_relaxed:
14420     Res = ActOnOpenMPRelaxedClause(StartLoc, EndLoc);
14421     break;
14422   case OMPC_threads:
14423     Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
14424     break;
14425   case OMPC_simd:
14426     Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
14427     break;
14428   case OMPC_nogroup:
14429     Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
14430     break;
14431   case OMPC_unified_address:
14432     Res = ActOnOpenMPUnifiedAddressClause(StartLoc, EndLoc);
14433     break;
14434   case OMPC_unified_shared_memory:
14435     Res = ActOnOpenMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
14436     break;
14437   case OMPC_reverse_offload:
14438     Res = ActOnOpenMPReverseOffloadClause(StartLoc, EndLoc);
14439     break;
14440   case OMPC_dynamic_allocators:
14441     Res = ActOnOpenMPDynamicAllocatorsClause(StartLoc, EndLoc);
14442     break;
14443   case OMPC_destroy:
14444     Res = ActOnOpenMPDestroyClause(/*InteropVar=*/nullptr, StartLoc,
14445                                    /*LParenLoc=*/SourceLocation(),
14446                                    /*VarLoc=*/SourceLocation(), EndLoc);
14447     break;
14448   case OMPC_if:
14449   case OMPC_final:
14450   case OMPC_num_threads:
14451   case OMPC_safelen:
14452   case OMPC_simdlen:
14453   case OMPC_sizes:
14454   case OMPC_allocator:
14455   case OMPC_collapse:
14456   case OMPC_schedule:
14457   case OMPC_private:
14458   case OMPC_firstprivate:
14459   case OMPC_lastprivate:
14460   case OMPC_shared:
14461   case OMPC_reduction:
14462   case OMPC_task_reduction:
14463   case OMPC_in_reduction:
14464   case OMPC_linear:
14465   case OMPC_aligned:
14466   case OMPC_copyin:
14467   case OMPC_copyprivate:
14468   case OMPC_default:
14469   case OMPC_proc_bind:
14470   case OMPC_threadprivate:
14471   case OMPC_allocate:
14472   case OMPC_flush:
14473   case OMPC_depobj:
14474   case OMPC_depend:
14475   case OMPC_device:
14476   case OMPC_map:
14477   case OMPC_num_teams:
14478   case OMPC_thread_limit:
14479   case OMPC_priority:
14480   case OMPC_grainsize:
14481   case OMPC_num_tasks:
14482   case OMPC_hint:
14483   case OMPC_dist_schedule:
14484   case OMPC_defaultmap:
14485   case OMPC_unknown:
14486   case OMPC_uniform:
14487   case OMPC_to:
14488   case OMPC_from:
14489   case OMPC_use_device_ptr:
14490   case OMPC_use_device_addr:
14491   case OMPC_is_device_ptr:
14492   case OMPC_atomic_default_mem_order:
14493   case OMPC_device_type:
14494   case OMPC_match:
14495   case OMPC_nontemporal:
14496   case OMPC_order:
14497   case OMPC_detach:
14498   case OMPC_inclusive:
14499   case OMPC_exclusive:
14500   case OMPC_uses_allocators:
14501   case OMPC_affinity:
14502   default:
14503     llvm_unreachable("Clause is not allowed.");
14504   }
14505   return Res;
14506 }
14507 
14508 OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
14509                                          SourceLocation EndLoc) {
14510   DSAStack->setNowaitRegion();
14511   return new (Context) OMPNowaitClause(StartLoc, EndLoc);
14512 }
14513 
14514 OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
14515                                          SourceLocation EndLoc) {
14516   return new (Context) OMPUntiedClause(StartLoc, EndLoc);
14517 }
14518 
14519 OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
14520                                             SourceLocation EndLoc) {
14521   return new (Context) OMPMergeableClause(StartLoc, EndLoc);
14522 }
14523 
14524 OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
14525                                        SourceLocation EndLoc) {
14526   return new (Context) OMPReadClause(StartLoc, EndLoc);
14527 }
14528 
14529 OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
14530                                         SourceLocation EndLoc) {
14531   return new (Context) OMPWriteClause(StartLoc, EndLoc);
14532 }
14533 
14534 OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
14535                                          SourceLocation EndLoc) {
14536   return OMPUpdateClause::Create(Context, StartLoc, EndLoc);
14537 }
14538 
14539 OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
14540                                           SourceLocation EndLoc) {
14541   return new (Context) OMPCaptureClause(StartLoc, EndLoc);
14542 }
14543 
14544 OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
14545                                          SourceLocation EndLoc) {
14546   return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
14547 }
14548 
14549 OMPClause *Sema::ActOnOpenMPAcqRelClause(SourceLocation StartLoc,
14550                                          SourceLocation EndLoc) {
14551   return new (Context) OMPAcqRelClause(StartLoc, EndLoc);
14552 }
14553 
14554 OMPClause *Sema::ActOnOpenMPAcquireClause(SourceLocation StartLoc,
14555                                           SourceLocation EndLoc) {
14556   return new (Context) OMPAcquireClause(StartLoc, EndLoc);
14557 }
14558 
14559 OMPClause *Sema::ActOnOpenMPReleaseClause(SourceLocation StartLoc,
14560                                           SourceLocation EndLoc) {
14561   return new (Context) OMPReleaseClause(StartLoc, EndLoc);
14562 }
14563 
14564 OMPClause *Sema::ActOnOpenMPRelaxedClause(SourceLocation StartLoc,
14565                                           SourceLocation EndLoc) {
14566   return new (Context) OMPRelaxedClause(StartLoc, EndLoc);
14567 }
14568 
14569 OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
14570                                           SourceLocation EndLoc) {
14571   return new (Context) OMPThreadsClause(StartLoc, EndLoc);
14572 }
14573 
14574 OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
14575                                        SourceLocation EndLoc) {
14576   return new (Context) OMPSIMDClause(StartLoc, EndLoc);
14577 }
14578 
14579 OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
14580                                           SourceLocation EndLoc) {
14581   return new (Context) OMPNogroupClause(StartLoc, EndLoc);
14582 }
14583 
14584 OMPClause *Sema::ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc,
14585                                                  SourceLocation EndLoc) {
14586   return new (Context) OMPUnifiedAddressClause(StartLoc, EndLoc);
14587 }
14588 
14589 OMPClause *Sema::ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc,
14590                                                       SourceLocation EndLoc) {
14591   return new (Context) OMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
14592 }
14593 
14594 OMPClause *Sema::ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc,
14595                                                  SourceLocation EndLoc) {
14596   return new (Context) OMPReverseOffloadClause(StartLoc, EndLoc);
14597 }
14598 
14599 OMPClause *Sema::ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc,
14600                                                     SourceLocation EndLoc) {
14601   return new (Context) OMPDynamicAllocatorsClause(StartLoc, EndLoc);
14602 }
14603 
14604 StmtResult Sema::ActOnOpenMPInteropDirective(ArrayRef<OMPClause *> Clauses,
14605                                              SourceLocation StartLoc,
14606                                              SourceLocation EndLoc) {
14607 
14608   // OpenMP 5.1 [2.15.1, interop Construct, Restrictions]
14609   // At least one action-clause must appear on a directive.
14610   if (!hasClauses(Clauses, OMPC_init, OMPC_use, OMPC_destroy, OMPC_nowait)) {
14611     StringRef Expected = "'init', 'use', 'destroy', or 'nowait'";
14612     Diag(StartLoc, diag::err_omp_no_clause_for_directive)
14613         << Expected << getOpenMPDirectiveName(OMPD_interop);
14614     return StmtError();
14615   }
14616 
14617   // OpenMP 5.1 [2.15.1, interop Construct, Restrictions]
14618   // A depend clause can only appear on the directive if a targetsync
14619   // interop-type is present or the interop-var was initialized with
14620   // the targetsync interop-type.
14621 
14622   // If there is any 'init' clause diagnose if there is no 'init' clause with
14623   // interop-type of 'targetsync'. Cases involving other directives cannot be
14624   // diagnosed.
14625   const OMPDependClause *DependClause = nullptr;
14626   bool HasInitClause = false;
14627   bool IsTargetSync = false;
14628   for (const OMPClause *C : Clauses) {
14629     if (IsTargetSync)
14630       break;
14631     if (const auto *InitClause = dyn_cast<OMPInitClause>(C)) {
14632       HasInitClause = true;
14633       if (InitClause->getIsTargetSync())
14634         IsTargetSync = true;
14635     } else if (const auto *DC = dyn_cast<OMPDependClause>(C)) {
14636       DependClause = DC;
14637     }
14638   }
14639   if (DependClause && HasInitClause && !IsTargetSync) {
14640     Diag(DependClause->getBeginLoc(), diag::err_omp_interop_bad_depend_clause);
14641     return StmtError();
14642   }
14643 
14644   // OpenMP 5.1 [2.15.1, interop Construct, Restrictions]
14645   // Each interop-var may be specified for at most one action-clause of each
14646   // interop construct.
14647   llvm::SmallPtrSet<const VarDecl *, 4> InteropVars;
14648   for (const OMPClause *C : Clauses) {
14649     OpenMPClauseKind ClauseKind = C->getClauseKind();
14650     const DeclRefExpr *DRE = nullptr;
14651     SourceLocation VarLoc;
14652 
14653     if (ClauseKind == OMPC_init) {
14654       const auto *IC = cast<OMPInitClause>(C);
14655       VarLoc = IC->getVarLoc();
14656       DRE = dyn_cast_or_null<DeclRefExpr>(IC->getInteropVar());
14657     } else if (ClauseKind == OMPC_use) {
14658       const auto *UC = cast<OMPUseClause>(C);
14659       VarLoc = UC->getVarLoc();
14660       DRE = dyn_cast_or_null<DeclRefExpr>(UC->getInteropVar());
14661     } else if (ClauseKind == OMPC_destroy) {
14662       const auto *DC = cast<OMPDestroyClause>(C);
14663       VarLoc = DC->getVarLoc();
14664       DRE = dyn_cast_or_null<DeclRefExpr>(DC->getInteropVar());
14665     }
14666 
14667     if (!DRE)
14668       continue;
14669 
14670     if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
14671       if (!InteropVars.insert(VD->getCanonicalDecl()).second) {
14672         Diag(VarLoc, diag::err_omp_interop_var_multiple_actions) << VD;
14673         return StmtError();
14674       }
14675     }
14676   }
14677 
14678   return OMPInteropDirective::Create(Context, StartLoc, EndLoc, Clauses);
14679 }
14680 
14681 static bool isValidInteropVariable(Sema &SemaRef, Expr *InteropVarExpr,
14682                                    SourceLocation VarLoc,
14683                                    OpenMPClauseKind Kind) {
14684   if (InteropVarExpr->isValueDependent() || InteropVarExpr->isTypeDependent() ||
14685       InteropVarExpr->isInstantiationDependent() ||
14686       InteropVarExpr->containsUnexpandedParameterPack())
14687     return true;
14688 
14689   const auto *DRE = dyn_cast<DeclRefExpr>(InteropVarExpr);
14690   if (!DRE || !isa<VarDecl>(DRE->getDecl())) {
14691     SemaRef.Diag(VarLoc, diag::err_omp_interop_variable_expected) << 0;
14692     return false;
14693   }
14694 
14695   // Interop variable should be of type omp_interop_t.
14696   bool HasError = false;
14697   QualType InteropType;
14698   LookupResult Result(SemaRef, &SemaRef.Context.Idents.get("omp_interop_t"),
14699                       VarLoc, Sema::LookupOrdinaryName);
14700   if (SemaRef.LookupName(Result, SemaRef.getCurScope())) {
14701     NamedDecl *ND = Result.getFoundDecl();
14702     if (const auto *TD = dyn_cast<TypeDecl>(ND)) {
14703       InteropType = QualType(TD->getTypeForDecl(), 0);
14704     } else {
14705       HasError = true;
14706     }
14707   } else {
14708     HasError = true;
14709   }
14710 
14711   if (HasError) {
14712     SemaRef.Diag(VarLoc, diag::err_omp_implied_type_not_found)
14713         << "omp_interop_t";
14714     return false;
14715   }
14716 
14717   QualType VarType = InteropVarExpr->getType().getUnqualifiedType();
14718   if (!SemaRef.Context.hasSameType(InteropType, VarType)) {
14719     SemaRef.Diag(VarLoc, diag::err_omp_interop_variable_wrong_type);
14720     return false;
14721   }
14722 
14723   // OpenMP 5.1 [2.15.1, interop Construct, Restrictions]
14724   // The interop-var passed to init or destroy must be non-const.
14725   if ((Kind == OMPC_init || Kind == OMPC_destroy) &&
14726       isConstNotMutableType(SemaRef, InteropVarExpr->getType())) {
14727     SemaRef.Diag(VarLoc, diag::err_omp_interop_variable_expected)
14728         << /*non-const*/ 1;
14729     return false;
14730   }
14731   return true;
14732 }
14733 
14734 OMPClause *
14735 Sema::ActOnOpenMPInitClause(Expr *InteropVar, ArrayRef<Expr *> PrefExprs,
14736                             bool IsTarget, bool IsTargetSync,
14737                             SourceLocation StartLoc, SourceLocation LParenLoc,
14738                             SourceLocation VarLoc, SourceLocation EndLoc) {
14739 
14740   if (!isValidInteropVariable(*this, InteropVar, VarLoc, OMPC_init))
14741     return nullptr;
14742 
14743   // Check prefer_type values.  These foreign-runtime-id values are either
14744   // string literals or constant integral expressions.
14745   for (const Expr *E : PrefExprs) {
14746     if (E->isValueDependent() || E->isTypeDependent() ||
14747         E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
14748       continue;
14749     if (E->isIntegerConstantExpr(Context))
14750       continue;
14751     if (isa<StringLiteral>(E))
14752       continue;
14753     Diag(E->getExprLoc(), diag::err_omp_interop_prefer_type);
14754     return nullptr;
14755   }
14756 
14757   return OMPInitClause::Create(Context, InteropVar, PrefExprs, IsTarget,
14758                                IsTargetSync, StartLoc, LParenLoc, VarLoc,
14759                                EndLoc);
14760 }
14761 
14762 OMPClause *Sema::ActOnOpenMPUseClause(Expr *InteropVar, SourceLocation StartLoc,
14763                                       SourceLocation LParenLoc,
14764                                       SourceLocation VarLoc,
14765                                       SourceLocation EndLoc) {
14766 
14767   if (!isValidInteropVariable(*this, InteropVar, VarLoc, OMPC_use))
14768     return nullptr;
14769 
14770   return new (Context)
14771       OMPUseClause(InteropVar, StartLoc, LParenLoc, VarLoc, EndLoc);
14772 }
14773 
14774 OMPClause *Sema::ActOnOpenMPDestroyClause(Expr *InteropVar,
14775                                           SourceLocation StartLoc,
14776                                           SourceLocation LParenLoc,
14777                                           SourceLocation VarLoc,
14778                                           SourceLocation EndLoc) {
14779   if (InteropVar &&
14780       !isValidInteropVariable(*this, InteropVar, VarLoc, OMPC_destroy))
14781     return nullptr;
14782 
14783   return new (Context)
14784       OMPDestroyClause(InteropVar, StartLoc, LParenLoc, VarLoc, EndLoc);
14785 }
14786 
14787 OMPClause *Sema::ActOnOpenMPVarListClause(
14788     OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *DepModOrTailExpr,
14789     const OMPVarListLocTy &Locs, SourceLocation ColonLoc,
14790     CXXScopeSpec &ReductionOrMapperIdScopeSpec,
14791     DeclarationNameInfo &ReductionOrMapperId, int ExtraModifier,
14792     ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
14793     ArrayRef<SourceLocation> MapTypeModifiersLoc, bool IsMapTypeImplicit,
14794     SourceLocation ExtraModifierLoc,
14795     ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
14796     ArrayRef<SourceLocation> MotionModifiersLoc) {
14797   SourceLocation StartLoc = Locs.StartLoc;
14798   SourceLocation LParenLoc = Locs.LParenLoc;
14799   SourceLocation EndLoc = Locs.EndLoc;
14800   OMPClause *Res = nullptr;
14801   switch (Kind) {
14802   case OMPC_private:
14803     Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
14804     break;
14805   case OMPC_firstprivate:
14806     Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
14807     break;
14808   case OMPC_lastprivate:
14809     assert(0 <= ExtraModifier && ExtraModifier <= OMPC_LASTPRIVATE_unknown &&
14810            "Unexpected lastprivate modifier.");
14811     Res = ActOnOpenMPLastprivateClause(
14812         VarList, static_cast<OpenMPLastprivateModifier>(ExtraModifier),
14813         ExtraModifierLoc, ColonLoc, StartLoc, LParenLoc, EndLoc);
14814     break;
14815   case OMPC_shared:
14816     Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
14817     break;
14818   case OMPC_reduction:
14819     assert(0 <= ExtraModifier && ExtraModifier <= OMPC_REDUCTION_unknown &&
14820            "Unexpected lastprivate modifier.");
14821     Res = ActOnOpenMPReductionClause(
14822         VarList, static_cast<OpenMPReductionClauseModifier>(ExtraModifier),
14823         StartLoc, LParenLoc, ExtraModifierLoc, ColonLoc, EndLoc,
14824         ReductionOrMapperIdScopeSpec, ReductionOrMapperId);
14825     break;
14826   case OMPC_task_reduction:
14827     Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
14828                                          EndLoc, ReductionOrMapperIdScopeSpec,
14829                                          ReductionOrMapperId);
14830     break;
14831   case OMPC_in_reduction:
14832     Res = ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
14833                                        EndLoc, ReductionOrMapperIdScopeSpec,
14834                                        ReductionOrMapperId);
14835     break;
14836   case OMPC_linear:
14837     assert(0 <= ExtraModifier && ExtraModifier <= OMPC_LINEAR_unknown &&
14838            "Unexpected linear modifier.");
14839     Res = ActOnOpenMPLinearClause(
14840         VarList, DepModOrTailExpr, StartLoc, LParenLoc,
14841         static_cast<OpenMPLinearClauseKind>(ExtraModifier), ExtraModifierLoc,
14842         ColonLoc, EndLoc);
14843     break;
14844   case OMPC_aligned:
14845     Res = ActOnOpenMPAlignedClause(VarList, DepModOrTailExpr, StartLoc,
14846                                    LParenLoc, ColonLoc, EndLoc);
14847     break;
14848   case OMPC_copyin:
14849     Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
14850     break;
14851   case OMPC_copyprivate:
14852     Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
14853     break;
14854   case OMPC_flush:
14855     Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
14856     break;
14857   case OMPC_depend:
14858     assert(0 <= ExtraModifier && ExtraModifier <= OMPC_DEPEND_unknown &&
14859            "Unexpected depend modifier.");
14860     Res = ActOnOpenMPDependClause(
14861         DepModOrTailExpr, static_cast<OpenMPDependClauseKind>(ExtraModifier),
14862         ExtraModifierLoc, ColonLoc, VarList, StartLoc, LParenLoc, EndLoc);
14863     break;
14864   case OMPC_map:
14865     assert(0 <= ExtraModifier && ExtraModifier <= OMPC_MAP_unknown &&
14866            "Unexpected map modifier.");
14867     Res = ActOnOpenMPMapClause(
14868         MapTypeModifiers, MapTypeModifiersLoc, ReductionOrMapperIdScopeSpec,
14869         ReductionOrMapperId, static_cast<OpenMPMapClauseKind>(ExtraModifier),
14870         IsMapTypeImplicit, ExtraModifierLoc, ColonLoc, VarList, Locs);
14871     break;
14872   case OMPC_to:
14873     Res = ActOnOpenMPToClause(MotionModifiers, MotionModifiersLoc,
14874                               ReductionOrMapperIdScopeSpec, ReductionOrMapperId,
14875                               ColonLoc, VarList, Locs);
14876     break;
14877   case OMPC_from:
14878     Res = ActOnOpenMPFromClause(MotionModifiers, MotionModifiersLoc,
14879                                 ReductionOrMapperIdScopeSpec,
14880                                 ReductionOrMapperId, ColonLoc, VarList, Locs);
14881     break;
14882   case OMPC_use_device_ptr:
14883     Res = ActOnOpenMPUseDevicePtrClause(VarList, Locs);
14884     break;
14885   case OMPC_use_device_addr:
14886     Res = ActOnOpenMPUseDeviceAddrClause(VarList, Locs);
14887     break;
14888   case OMPC_is_device_ptr:
14889     Res = ActOnOpenMPIsDevicePtrClause(VarList, Locs);
14890     break;
14891   case OMPC_allocate:
14892     Res = ActOnOpenMPAllocateClause(DepModOrTailExpr, VarList, StartLoc,
14893                                     LParenLoc, ColonLoc, EndLoc);
14894     break;
14895   case OMPC_nontemporal:
14896     Res = ActOnOpenMPNontemporalClause(VarList, StartLoc, LParenLoc, EndLoc);
14897     break;
14898   case OMPC_inclusive:
14899     Res = ActOnOpenMPInclusiveClause(VarList, StartLoc, LParenLoc, EndLoc);
14900     break;
14901   case OMPC_exclusive:
14902     Res = ActOnOpenMPExclusiveClause(VarList, StartLoc, LParenLoc, EndLoc);
14903     break;
14904   case OMPC_affinity:
14905     Res = ActOnOpenMPAffinityClause(StartLoc, LParenLoc, ColonLoc, EndLoc,
14906                                     DepModOrTailExpr, VarList);
14907     break;
14908   case OMPC_if:
14909   case OMPC_depobj:
14910   case OMPC_final:
14911   case OMPC_num_threads:
14912   case OMPC_safelen:
14913   case OMPC_simdlen:
14914   case OMPC_sizes:
14915   case OMPC_allocator:
14916   case OMPC_collapse:
14917   case OMPC_default:
14918   case OMPC_proc_bind:
14919   case OMPC_schedule:
14920   case OMPC_ordered:
14921   case OMPC_nowait:
14922   case OMPC_untied:
14923   case OMPC_mergeable:
14924   case OMPC_threadprivate:
14925   case OMPC_read:
14926   case OMPC_write:
14927   case OMPC_update:
14928   case OMPC_capture:
14929   case OMPC_seq_cst:
14930   case OMPC_acq_rel:
14931   case OMPC_acquire:
14932   case OMPC_release:
14933   case OMPC_relaxed:
14934   case OMPC_device:
14935   case OMPC_threads:
14936   case OMPC_simd:
14937   case OMPC_num_teams:
14938   case OMPC_thread_limit:
14939   case OMPC_priority:
14940   case OMPC_grainsize:
14941   case OMPC_nogroup:
14942   case OMPC_num_tasks:
14943   case OMPC_hint:
14944   case OMPC_dist_schedule:
14945   case OMPC_defaultmap:
14946   case OMPC_unknown:
14947   case OMPC_uniform:
14948   case OMPC_unified_address:
14949   case OMPC_unified_shared_memory:
14950   case OMPC_reverse_offload:
14951   case OMPC_dynamic_allocators:
14952   case OMPC_atomic_default_mem_order:
14953   case OMPC_device_type:
14954   case OMPC_match:
14955   case OMPC_order:
14956   case OMPC_destroy:
14957   case OMPC_detach:
14958   case OMPC_uses_allocators:
14959   default:
14960     llvm_unreachable("Clause is not allowed.");
14961   }
14962   return Res;
14963 }
14964 
14965 ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
14966                                        ExprObjectKind OK, SourceLocation Loc) {
14967   ExprResult Res = BuildDeclRefExpr(
14968       Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
14969   if (!Res.isUsable())
14970     return ExprError();
14971   if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
14972     Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
14973     if (!Res.isUsable())
14974       return ExprError();
14975   }
14976   if (VK != VK_LValue && Res.get()->isGLValue()) {
14977     Res = DefaultLvalueConversion(Res.get());
14978     if (!Res.isUsable())
14979       return ExprError();
14980   }
14981   return Res;
14982 }
14983 
14984 OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
14985                                           SourceLocation StartLoc,
14986                                           SourceLocation LParenLoc,
14987                                           SourceLocation EndLoc) {
14988   SmallVector<Expr *, 8> Vars;
14989   SmallVector<Expr *, 8> PrivateCopies;
14990   for (Expr *RefExpr : VarList) {
14991     assert(RefExpr && "NULL expr in OpenMP private clause.");
14992     SourceLocation ELoc;
14993     SourceRange ERange;
14994     Expr *SimpleRefExpr = RefExpr;
14995     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
14996     if (Res.second) {
14997       // It will be analyzed later.
14998       Vars.push_back(RefExpr);
14999       PrivateCopies.push_back(nullptr);
15000     }
15001     ValueDecl *D = Res.first;
15002     if (!D)
15003       continue;
15004 
15005     QualType Type = D->getType();
15006     auto *VD = dyn_cast<VarDecl>(D);
15007 
15008     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
15009     //  A variable that appears in a private clause must not have an incomplete
15010     //  type or a reference type.
15011     if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
15012       continue;
15013     Type = Type.getNonReferenceType();
15014 
15015     // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
15016     // A variable that is privatized must not have a const-qualified type
15017     // unless it is of class type with a mutable member. This restriction does
15018     // not apply to the firstprivate clause.
15019     //
15020     // OpenMP 3.1 [2.9.3.3, private clause, Restrictions]
15021     // A variable that appears in a private clause must not have a
15022     // const-qualified type unless it is of class type with a mutable member.
15023     if (rejectConstNotMutableType(*this, D, Type, OMPC_private, ELoc))
15024       continue;
15025 
15026     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
15027     // in a Construct]
15028     //  Variables with the predetermined data-sharing attributes may not be
15029     //  listed in data-sharing attributes clauses, except for the cases
15030     //  listed below. For these exceptions only, listing a predetermined
15031     //  variable in a data-sharing attribute clause is allowed and overrides
15032     //  the variable's predetermined data-sharing attributes.
15033     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
15034     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
15035       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
15036                                           << getOpenMPClauseName(OMPC_private);
15037       reportOriginalDsa(*this, DSAStack, D, DVar);
15038       continue;
15039     }
15040 
15041     OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
15042     // Variably modified types are not supported for tasks.
15043     if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
15044         isOpenMPTaskingDirective(CurrDir)) {
15045       Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
15046           << getOpenMPClauseName(OMPC_private) << Type
15047           << getOpenMPDirectiveName(CurrDir);
15048       bool IsDecl =
15049           !VD ||
15050           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
15051       Diag(D->getLocation(),
15052            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
15053           << D;
15054       continue;
15055     }
15056 
15057     // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
15058     // A list item cannot appear in both a map clause and a data-sharing
15059     // attribute clause on the same construct
15060     //
15061     // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
15062     // A list item cannot appear in both a map clause and a data-sharing
15063     // attribute clause on the same construct unless the construct is a
15064     // combined construct.
15065     if ((LangOpts.OpenMP <= 45 && isOpenMPTargetExecutionDirective(CurrDir)) ||
15066         CurrDir == OMPD_target) {
15067       OpenMPClauseKind ConflictKind;
15068       if (DSAStack->checkMappableExprComponentListsForDecl(
15069               VD, /*CurrentRegionOnly=*/true,
15070               [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
15071                   OpenMPClauseKind WhereFoundClauseKind) -> bool {
15072                 ConflictKind = WhereFoundClauseKind;
15073                 return true;
15074               })) {
15075         Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
15076             << getOpenMPClauseName(OMPC_private)
15077             << getOpenMPClauseName(ConflictKind)
15078             << getOpenMPDirectiveName(CurrDir);
15079         reportOriginalDsa(*this, DSAStack, D, DVar);
15080         continue;
15081       }
15082     }
15083 
15084     // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
15085     //  A variable of class type (or array thereof) that appears in a private
15086     //  clause requires an accessible, unambiguous default constructor for the
15087     //  class type.
15088     // Generate helper private variable and initialize it with the default
15089     // value. The address of the original variable is replaced by the address of
15090     // the new private variable in CodeGen. This new variable is not added to
15091     // IdResolver, so the code in the OpenMP region uses original variable for
15092     // proper diagnostics.
15093     Type = Type.getUnqualifiedType();
15094     VarDecl *VDPrivate =
15095         buildVarDecl(*this, ELoc, Type, D->getName(),
15096                      D->hasAttrs() ? &D->getAttrs() : nullptr,
15097                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
15098     ActOnUninitializedDecl(VDPrivate);
15099     if (VDPrivate->isInvalidDecl())
15100       continue;
15101     DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
15102         *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
15103 
15104     DeclRefExpr *Ref = nullptr;
15105     if (!VD && !CurContext->isDependentContext())
15106       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
15107     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
15108     Vars.push_back((VD || CurContext->isDependentContext())
15109                        ? RefExpr->IgnoreParens()
15110                        : Ref);
15111     PrivateCopies.push_back(VDPrivateRefExpr);
15112   }
15113 
15114   if (Vars.empty())
15115     return nullptr;
15116 
15117   return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
15118                                   PrivateCopies);
15119 }
15120 
15121 namespace {
15122 class DiagsUninitializedSeveretyRAII {
15123 private:
15124   DiagnosticsEngine &Diags;
15125   SourceLocation SavedLoc;
15126   bool IsIgnored = false;
15127 
15128 public:
15129   DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
15130                                  bool IsIgnored)
15131       : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
15132     if (!IsIgnored) {
15133       Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
15134                         /*Map*/ diag::Severity::Ignored, Loc);
15135     }
15136   }
15137   ~DiagsUninitializedSeveretyRAII() {
15138     if (!IsIgnored)
15139       Diags.popMappings(SavedLoc);
15140   }
15141 };
15142 }
15143 
15144 OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
15145                                                SourceLocation StartLoc,
15146                                                SourceLocation LParenLoc,
15147                                                SourceLocation EndLoc) {
15148   SmallVector<Expr *, 8> Vars;
15149   SmallVector<Expr *, 8> PrivateCopies;
15150   SmallVector<Expr *, 8> Inits;
15151   SmallVector<Decl *, 4> ExprCaptures;
15152   bool IsImplicitClause =
15153       StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
15154   SourceLocation ImplicitClauseLoc = DSAStack->getConstructLoc();
15155 
15156   for (Expr *RefExpr : VarList) {
15157     assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
15158     SourceLocation ELoc;
15159     SourceRange ERange;
15160     Expr *SimpleRefExpr = RefExpr;
15161     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
15162     if (Res.second) {
15163       // It will be analyzed later.
15164       Vars.push_back(RefExpr);
15165       PrivateCopies.push_back(nullptr);
15166       Inits.push_back(nullptr);
15167     }
15168     ValueDecl *D = Res.first;
15169     if (!D)
15170       continue;
15171 
15172     ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
15173     QualType Type = D->getType();
15174     auto *VD = dyn_cast<VarDecl>(D);
15175 
15176     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
15177     //  A variable that appears in a private clause must not have an incomplete
15178     //  type or a reference type.
15179     if (RequireCompleteType(ELoc, Type,
15180                             diag::err_omp_firstprivate_incomplete_type))
15181       continue;
15182     Type = Type.getNonReferenceType();
15183 
15184     // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
15185     //  A variable of class type (or array thereof) that appears in a private
15186     //  clause requires an accessible, unambiguous copy constructor for the
15187     //  class type.
15188     QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
15189 
15190     // If an implicit firstprivate variable found it was checked already.
15191     DSAStackTy::DSAVarData TopDVar;
15192     if (!IsImplicitClause) {
15193       DSAStackTy::DSAVarData DVar =
15194           DSAStack->getTopDSA(D, /*FromParent=*/false);
15195       TopDVar = DVar;
15196       OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
15197       bool IsConstant = ElemType.isConstant(Context);
15198       // OpenMP [2.4.13, Data-sharing Attribute Clauses]
15199       //  A list item that specifies a given variable may not appear in more
15200       // than one clause on the same directive, except that a variable may be
15201       //  specified in both firstprivate and lastprivate clauses.
15202       // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
15203       // A list item may appear in a firstprivate or lastprivate clause but not
15204       // both.
15205       if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
15206           (isOpenMPDistributeDirective(CurrDir) ||
15207            DVar.CKind != OMPC_lastprivate) &&
15208           DVar.RefExpr) {
15209         Diag(ELoc, diag::err_omp_wrong_dsa)
15210             << getOpenMPClauseName(DVar.CKind)
15211             << getOpenMPClauseName(OMPC_firstprivate);
15212         reportOriginalDsa(*this, DSAStack, D, DVar);
15213         continue;
15214       }
15215 
15216       // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
15217       // in a Construct]
15218       //  Variables with the predetermined data-sharing attributes may not be
15219       //  listed in data-sharing attributes clauses, except for the cases
15220       //  listed below. For these exceptions only, listing a predetermined
15221       //  variable in a data-sharing attribute clause is allowed and overrides
15222       //  the variable's predetermined data-sharing attributes.
15223       // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
15224       // in a Construct, C/C++, p.2]
15225       //  Variables with const-qualified type having no mutable member may be
15226       //  listed in a firstprivate clause, even if they are static data members.
15227       if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
15228           DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
15229         Diag(ELoc, diag::err_omp_wrong_dsa)
15230             << getOpenMPClauseName(DVar.CKind)
15231             << getOpenMPClauseName(OMPC_firstprivate);
15232         reportOriginalDsa(*this, DSAStack, D, DVar);
15233         continue;
15234       }
15235 
15236       // OpenMP [2.9.3.4, Restrictions, p.2]
15237       //  A list item that is private within a parallel region must not appear
15238       //  in a firstprivate clause on a worksharing construct if any of the
15239       //  worksharing regions arising from the worksharing construct ever bind
15240       //  to any of the parallel regions arising from the parallel construct.
15241       // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
15242       // A list item that is private within a teams region must not appear in a
15243       // firstprivate clause on a distribute construct if any of the distribute
15244       // regions arising from the distribute construct ever bind to any of the
15245       // teams regions arising from the teams construct.
15246       // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
15247       // A list item that appears in a reduction clause of a teams construct
15248       // must not appear in a firstprivate clause on a distribute construct if
15249       // any of the distribute regions arising from the distribute construct
15250       // ever bind to any of the teams regions arising from the teams construct.
15251       if ((isOpenMPWorksharingDirective(CurrDir) ||
15252            isOpenMPDistributeDirective(CurrDir)) &&
15253           !isOpenMPParallelDirective(CurrDir) &&
15254           !isOpenMPTeamsDirective(CurrDir)) {
15255         DVar = DSAStack->getImplicitDSA(D, true);
15256         if (DVar.CKind != OMPC_shared &&
15257             (isOpenMPParallelDirective(DVar.DKind) ||
15258              isOpenMPTeamsDirective(DVar.DKind) ||
15259              DVar.DKind == OMPD_unknown)) {
15260           Diag(ELoc, diag::err_omp_required_access)
15261               << getOpenMPClauseName(OMPC_firstprivate)
15262               << getOpenMPClauseName(OMPC_shared);
15263           reportOriginalDsa(*this, DSAStack, D, DVar);
15264           continue;
15265         }
15266       }
15267       // OpenMP [2.9.3.4, Restrictions, p.3]
15268       //  A list item that appears in a reduction clause of a parallel construct
15269       //  must not appear in a firstprivate clause on a worksharing or task
15270       //  construct if any of the worksharing or task regions arising from the
15271       //  worksharing or task construct ever bind to any of the parallel regions
15272       //  arising from the parallel construct.
15273       // OpenMP [2.9.3.4, Restrictions, p.4]
15274       //  A list item that appears in a reduction clause in worksharing
15275       //  construct must not appear in a firstprivate clause in a task construct
15276       //  encountered during execution of any of the worksharing regions arising
15277       //  from the worksharing construct.
15278       if (isOpenMPTaskingDirective(CurrDir)) {
15279         DVar = DSAStack->hasInnermostDSA(
15280             D,
15281             [](OpenMPClauseKind C, bool AppliedToPointee) {
15282               return C == OMPC_reduction && !AppliedToPointee;
15283             },
15284             [](OpenMPDirectiveKind K) {
15285               return isOpenMPParallelDirective(K) ||
15286                      isOpenMPWorksharingDirective(K) ||
15287                      isOpenMPTeamsDirective(K);
15288             },
15289             /*FromParent=*/true);
15290         if (DVar.CKind == OMPC_reduction &&
15291             (isOpenMPParallelDirective(DVar.DKind) ||
15292              isOpenMPWorksharingDirective(DVar.DKind) ||
15293              isOpenMPTeamsDirective(DVar.DKind))) {
15294           Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
15295               << getOpenMPDirectiveName(DVar.DKind);
15296           reportOriginalDsa(*this, DSAStack, D, DVar);
15297           continue;
15298         }
15299       }
15300 
15301       // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
15302       // A list item cannot appear in both a map clause and a data-sharing
15303       // attribute clause on the same construct
15304       //
15305       // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
15306       // A list item cannot appear in both a map clause and a data-sharing
15307       // attribute clause on the same construct unless the construct is a
15308       // combined construct.
15309       if ((LangOpts.OpenMP <= 45 &&
15310            isOpenMPTargetExecutionDirective(CurrDir)) ||
15311           CurrDir == OMPD_target) {
15312         OpenMPClauseKind ConflictKind;
15313         if (DSAStack->checkMappableExprComponentListsForDecl(
15314                 VD, /*CurrentRegionOnly=*/true,
15315                 [&ConflictKind](
15316                     OMPClauseMappableExprCommon::MappableExprComponentListRef,
15317                     OpenMPClauseKind WhereFoundClauseKind) {
15318                   ConflictKind = WhereFoundClauseKind;
15319                   return true;
15320                 })) {
15321           Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
15322               << getOpenMPClauseName(OMPC_firstprivate)
15323               << getOpenMPClauseName(ConflictKind)
15324               << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
15325           reportOriginalDsa(*this, DSAStack, D, DVar);
15326           continue;
15327         }
15328       }
15329     }
15330 
15331     // Variably modified types are not supported for tasks.
15332     if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
15333         isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
15334       Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
15335           << getOpenMPClauseName(OMPC_firstprivate) << Type
15336           << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
15337       bool IsDecl =
15338           !VD ||
15339           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
15340       Diag(D->getLocation(),
15341            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
15342           << D;
15343       continue;
15344     }
15345 
15346     Type = Type.getUnqualifiedType();
15347     VarDecl *VDPrivate =
15348         buildVarDecl(*this, ELoc, Type, D->getName(),
15349                      D->hasAttrs() ? &D->getAttrs() : nullptr,
15350                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
15351     // Generate helper private variable and initialize it with the value of the
15352     // original variable. The address of the original variable is replaced by
15353     // the address of the new private variable in the CodeGen. This new variable
15354     // is not added to IdResolver, so the code in the OpenMP region uses
15355     // original variable for proper diagnostics and variable capturing.
15356     Expr *VDInitRefExpr = nullptr;
15357     // For arrays generate initializer for single element and replace it by the
15358     // original array element in CodeGen.
15359     if (Type->isArrayType()) {
15360       VarDecl *VDInit =
15361           buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
15362       VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
15363       Expr *Init = DefaultLvalueConversion(VDInitRefExpr).get();
15364       ElemType = ElemType.getUnqualifiedType();
15365       VarDecl *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
15366                                          ".firstprivate.temp");
15367       InitializedEntity Entity =
15368           InitializedEntity::InitializeVariable(VDInitTemp);
15369       InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
15370 
15371       InitializationSequence InitSeq(*this, Entity, Kind, Init);
15372       ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
15373       if (Result.isInvalid())
15374         VDPrivate->setInvalidDecl();
15375       else
15376         VDPrivate->setInit(Result.getAs<Expr>());
15377       // Remove temp variable declaration.
15378       Context.Deallocate(VDInitTemp);
15379     } else {
15380       VarDecl *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
15381                                      ".firstprivate.temp");
15382       VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
15383                                        RefExpr->getExprLoc());
15384       AddInitializerToDecl(VDPrivate,
15385                            DefaultLvalueConversion(VDInitRefExpr).get(),
15386                            /*DirectInit=*/false);
15387     }
15388     if (VDPrivate->isInvalidDecl()) {
15389       if (IsImplicitClause) {
15390         Diag(RefExpr->getExprLoc(),
15391              diag::note_omp_task_predetermined_firstprivate_here);
15392       }
15393       continue;
15394     }
15395     CurContext->addDecl(VDPrivate);
15396     DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
15397         *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
15398         RefExpr->getExprLoc());
15399     DeclRefExpr *Ref = nullptr;
15400     if (!VD && !CurContext->isDependentContext()) {
15401       if (TopDVar.CKind == OMPC_lastprivate) {
15402         Ref = TopDVar.PrivateCopy;
15403       } else {
15404         Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
15405         if (!isOpenMPCapturedDecl(D))
15406           ExprCaptures.push_back(Ref->getDecl());
15407       }
15408     }
15409     if (!IsImplicitClause)
15410       DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
15411     Vars.push_back((VD || CurContext->isDependentContext())
15412                        ? RefExpr->IgnoreParens()
15413                        : Ref);
15414     PrivateCopies.push_back(VDPrivateRefExpr);
15415     Inits.push_back(VDInitRefExpr);
15416   }
15417 
15418   if (Vars.empty())
15419     return nullptr;
15420 
15421   return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
15422                                        Vars, PrivateCopies, Inits,
15423                                        buildPreInits(Context, ExprCaptures));
15424 }
15425 
15426 OMPClause *Sema::ActOnOpenMPLastprivateClause(
15427     ArrayRef<Expr *> VarList, OpenMPLastprivateModifier LPKind,
15428     SourceLocation LPKindLoc, SourceLocation ColonLoc, SourceLocation StartLoc,
15429     SourceLocation LParenLoc, SourceLocation EndLoc) {
15430   if (LPKind == OMPC_LASTPRIVATE_unknown && LPKindLoc.isValid()) {
15431     assert(ColonLoc.isValid() && "Colon location must be valid.");
15432     Diag(LPKindLoc, diag::err_omp_unexpected_clause_value)
15433         << getListOfPossibleValues(OMPC_lastprivate, /*First=*/0,
15434                                    /*Last=*/OMPC_LASTPRIVATE_unknown)
15435         << getOpenMPClauseName(OMPC_lastprivate);
15436     return nullptr;
15437   }
15438 
15439   SmallVector<Expr *, 8> Vars;
15440   SmallVector<Expr *, 8> SrcExprs;
15441   SmallVector<Expr *, 8> DstExprs;
15442   SmallVector<Expr *, 8> AssignmentOps;
15443   SmallVector<Decl *, 4> ExprCaptures;
15444   SmallVector<Expr *, 4> ExprPostUpdates;
15445   for (Expr *RefExpr : VarList) {
15446     assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
15447     SourceLocation ELoc;
15448     SourceRange ERange;
15449     Expr *SimpleRefExpr = RefExpr;
15450     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
15451     if (Res.second) {
15452       // It will be analyzed later.
15453       Vars.push_back(RefExpr);
15454       SrcExprs.push_back(nullptr);
15455       DstExprs.push_back(nullptr);
15456       AssignmentOps.push_back(nullptr);
15457     }
15458     ValueDecl *D = Res.first;
15459     if (!D)
15460       continue;
15461 
15462     QualType Type = D->getType();
15463     auto *VD = dyn_cast<VarDecl>(D);
15464 
15465     // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
15466     //  A variable that appears in a lastprivate clause must not have an
15467     //  incomplete type or a reference type.
15468     if (RequireCompleteType(ELoc, Type,
15469                             diag::err_omp_lastprivate_incomplete_type))
15470       continue;
15471     Type = Type.getNonReferenceType();
15472 
15473     // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
15474     // A variable that is privatized must not have a const-qualified type
15475     // unless it is of class type with a mutable member. This restriction does
15476     // not apply to the firstprivate clause.
15477     //
15478     // OpenMP 3.1 [2.9.3.5, lastprivate clause, Restrictions]
15479     // A variable that appears in a lastprivate clause must not have a
15480     // const-qualified type unless it is of class type with a mutable member.
15481     if (rejectConstNotMutableType(*this, D, Type, OMPC_lastprivate, ELoc))
15482       continue;
15483 
15484     // OpenMP 5.0 [2.19.4.5 lastprivate Clause, Restrictions]
15485     // A list item that appears in a lastprivate clause with the conditional
15486     // modifier must be a scalar variable.
15487     if (LPKind == OMPC_LASTPRIVATE_conditional && !Type->isScalarType()) {
15488       Diag(ELoc, diag::err_omp_lastprivate_conditional_non_scalar);
15489       bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
15490                                VarDecl::DeclarationOnly;
15491       Diag(D->getLocation(),
15492            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
15493           << D;
15494       continue;
15495     }
15496 
15497     OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
15498     // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
15499     // in a Construct]
15500     //  Variables with the predetermined data-sharing attributes may not be
15501     //  listed in data-sharing attributes clauses, except for the cases
15502     //  listed below.
15503     // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
15504     // A list item may appear in a firstprivate or lastprivate clause but not
15505     // both.
15506     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
15507     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
15508         (isOpenMPDistributeDirective(CurrDir) ||
15509          DVar.CKind != OMPC_firstprivate) &&
15510         (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
15511       Diag(ELoc, diag::err_omp_wrong_dsa)
15512           << getOpenMPClauseName(DVar.CKind)
15513           << getOpenMPClauseName(OMPC_lastprivate);
15514       reportOriginalDsa(*this, DSAStack, D, DVar);
15515       continue;
15516     }
15517 
15518     // OpenMP [2.14.3.5, Restrictions, p.2]
15519     // A list item that is private within a parallel region, or that appears in
15520     // the reduction clause of a parallel construct, must not appear in a
15521     // lastprivate clause on a worksharing construct if any of the corresponding
15522     // worksharing regions ever binds to any of the corresponding parallel
15523     // regions.
15524     DSAStackTy::DSAVarData TopDVar = DVar;
15525     if (isOpenMPWorksharingDirective(CurrDir) &&
15526         !isOpenMPParallelDirective(CurrDir) &&
15527         !isOpenMPTeamsDirective(CurrDir)) {
15528       DVar = DSAStack->getImplicitDSA(D, true);
15529       if (DVar.CKind != OMPC_shared) {
15530         Diag(ELoc, diag::err_omp_required_access)
15531             << getOpenMPClauseName(OMPC_lastprivate)
15532             << getOpenMPClauseName(OMPC_shared);
15533         reportOriginalDsa(*this, DSAStack, D, DVar);
15534         continue;
15535       }
15536     }
15537 
15538     // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
15539     //  A variable of class type (or array thereof) that appears in a
15540     //  lastprivate clause requires an accessible, unambiguous default
15541     //  constructor for the class type, unless the list item is also specified
15542     //  in a firstprivate clause.
15543     //  A variable of class type (or array thereof) that appears in a
15544     //  lastprivate clause requires an accessible, unambiguous copy assignment
15545     //  operator for the class type.
15546     Type = Context.getBaseElementType(Type).getNonReferenceType();
15547     VarDecl *SrcVD = buildVarDecl(*this, ERange.getBegin(),
15548                                   Type.getUnqualifiedType(), ".lastprivate.src",
15549                                   D->hasAttrs() ? &D->getAttrs() : nullptr);
15550     DeclRefExpr *PseudoSrcExpr =
15551         buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
15552     VarDecl *DstVD =
15553         buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
15554                      D->hasAttrs() ? &D->getAttrs() : nullptr);
15555     DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
15556     // For arrays generate assignment operation for single element and replace
15557     // it by the original array element in CodeGen.
15558     ExprResult AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
15559                                          PseudoDstExpr, PseudoSrcExpr);
15560     if (AssignmentOp.isInvalid())
15561       continue;
15562     AssignmentOp =
15563         ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
15564     if (AssignmentOp.isInvalid())
15565       continue;
15566 
15567     DeclRefExpr *Ref = nullptr;
15568     if (!VD && !CurContext->isDependentContext()) {
15569       if (TopDVar.CKind == OMPC_firstprivate) {
15570         Ref = TopDVar.PrivateCopy;
15571       } else {
15572         Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
15573         if (!isOpenMPCapturedDecl(D))
15574           ExprCaptures.push_back(Ref->getDecl());
15575       }
15576       if ((TopDVar.CKind == OMPC_firstprivate && !TopDVar.PrivateCopy) ||
15577           (!isOpenMPCapturedDecl(D) &&
15578            Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
15579         ExprResult RefRes = DefaultLvalueConversion(Ref);
15580         if (!RefRes.isUsable())
15581           continue;
15582         ExprResult PostUpdateRes =
15583             BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
15584                        RefRes.get());
15585         if (!PostUpdateRes.isUsable())
15586           continue;
15587         ExprPostUpdates.push_back(
15588             IgnoredValueConversions(PostUpdateRes.get()).get());
15589       }
15590     }
15591     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
15592     Vars.push_back((VD || CurContext->isDependentContext())
15593                        ? RefExpr->IgnoreParens()
15594                        : Ref);
15595     SrcExprs.push_back(PseudoSrcExpr);
15596     DstExprs.push_back(PseudoDstExpr);
15597     AssignmentOps.push_back(AssignmentOp.get());
15598   }
15599 
15600   if (Vars.empty())
15601     return nullptr;
15602 
15603   return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
15604                                       Vars, SrcExprs, DstExprs, AssignmentOps,
15605                                       LPKind, LPKindLoc, ColonLoc,
15606                                       buildPreInits(Context, ExprCaptures),
15607                                       buildPostUpdate(*this, ExprPostUpdates));
15608 }
15609 
15610 OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
15611                                          SourceLocation StartLoc,
15612                                          SourceLocation LParenLoc,
15613                                          SourceLocation EndLoc) {
15614   SmallVector<Expr *, 8> Vars;
15615   for (Expr *RefExpr : VarList) {
15616     assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
15617     SourceLocation ELoc;
15618     SourceRange ERange;
15619     Expr *SimpleRefExpr = RefExpr;
15620     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
15621     if (Res.second) {
15622       // It will be analyzed later.
15623       Vars.push_back(RefExpr);
15624     }
15625     ValueDecl *D = Res.first;
15626     if (!D)
15627       continue;
15628 
15629     auto *VD = dyn_cast<VarDecl>(D);
15630     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
15631     // in a Construct]
15632     //  Variables with the predetermined data-sharing attributes may not be
15633     //  listed in data-sharing attributes clauses, except for the cases
15634     //  listed below. For these exceptions only, listing a predetermined
15635     //  variable in a data-sharing attribute clause is allowed and overrides
15636     //  the variable's predetermined data-sharing attributes.
15637     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
15638     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
15639         DVar.RefExpr) {
15640       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
15641                                           << getOpenMPClauseName(OMPC_shared);
15642       reportOriginalDsa(*this, DSAStack, D, DVar);
15643       continue;
15644     }
15645 
15646     DeclRefExpr *Ref = nullptr;
15647     if (!VD && isOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
15648       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
15649     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
15650     Vars.push_back((VD || !Ref || CurContext->isDependentContext())
15651                        ? RefExpr->IgnoreParens()
15652                        : Ref);
15653   }
15654 
15655   if (Vars.empty())
15656     return nullptr;
15657 
15658   return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
15659 }
15660 
15661 namespace {
15662 class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
15663   DSAStackTy *Stack;
15664 
15665 public:
15666   bool VisitDeclRefExpr(DeclRefExpr *E) {
15667     if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
15668       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
15669       if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
15670         return false;
15671       if (DVar.CKind != OMPC_unknown)
15672         return true;
15673       DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
15674           VD,
15675           [](OpenMPClauseKind C, bool AppliedToPointee) {
15676             return isOpenMPPrivate(C) && !AppliedToPointee;
15677           },
15678           [](OpenMPDirectiveKind) { return true; },
15679           /*FromParent=*/true);
15680       return DVarPrivate.CKind != OMPC_unknown;
15681     }
15682     return false;
15683   }
15684   bool VisitStmt(Stmt *S) {
15685     for (Stmt *Child : S->children()) {
15686       if (Child && Visit(Child))
15687         return true;
15688     }
15689     return false;
15690   }
15691   explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
15692 };
15693 } // namespace
15694 
15695 namespace {
15696 // Transform MemberExpression for specified FieldDecl of current class to
15697 // DeclRefExpr to specified OMPCapturedExprDecl.
15698 class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
15699   typedef TreeTransform<TransformExprToCaptures> BaseTransform;
15700   ValueDecl *Field = nullptr;
15701   DeclRefExpr *CapturedExpr = nullptr;
15702 
15703 public:
15704   TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
15705       : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
15706 
15707   ExprResult TransformMemberExpr(MemberExpr *E) {
15708     if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
15709         E->getMemberDecl() == Field) {
15710       CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
15711       return CapturedExpr;
15712     }
15713     return BaseTransform::TransformMemberExpr(E);
15714   }
15715   DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
15716 };
15717 } // namespace
15718 
15719 template <typename T, typename U>
15720 static T filterLookupForUDReductionAndMapper(
15721     SmallVectorImpl<U> &Lookups, const llvm::function_ref<T(ValueDecl *)> Gen) {
15722   for (U &Set : Lookups) {
15723     for (auto *D : Set) {
15724       if (T Res = Gen(cast<ValueDecl>(D)))
15725         return Res;
15726     }
15727   }
15728   return T();
15729 }
15730 
15731 static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) {
15732   assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case");
15733 
15734   for (auto RD : D->redecls()) {
15735     // Don't bother with extra checks if we already know this one isn't visible.
15736     if (RD == D)
15737       continue;
15738 
15739     auto ND = cast<NamedDecl>(RD);
15740     if (LookupResult::isVisible(SemaRef, ND))
15741       return ND;
15742   }
15743 
15744   return nullptr;
15745 }
15746 
15747 static void
15748 argumentDependentLookup(Sema &SemaRef, const DeclarationNameInfo &Id,
15749                         SourceLocation Loc, QualType Ty,
15750                         SmallVectorImpl<UnresolvedSet<8>> &Lookups) {
15751   // Find all of the associated namespaces and classes based on the
15752   // arguments we have.
15753   Sema::AssociatedNamespaceSet AssociatedNamespaces;
15754   Sema::AssociatedClassSet AssociatedClasses;
15755   OpaqueValueExpr OVE(Loc, Ty, VK_LValue);
15756   SemaRef.FindAssociatedClassesAndNamespaces(Loc, &OVE, AssociatedNamespaces,
15757                                              AssociatedClasses);
15758 
15759   // C++ [basic.lookup.argdep]p3:
15760   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
15761   //   and let Y be the lookup set produced by argument dependent
15762   //   lookup (defined as follows). If X contains [...] then Y is
15763   //   empty. Otherwise Y is the set of declarations found in the
15764   //   namespaces associated with the argument types as described
15765   //   below. The set of declarations found by the lookup of the name
15766   //   is the union of X and Y.
15767   //
15768   // Here, we compute Y and add its members to the overloaded
15769   // candidate set.
15770   for (auto *NS : AssociatedNamespaces) {
15771     //   When considering an associated namespace, the lookup is the
15772     //   same as the lookup performed when the associated namespace is
15773     //   used as a qualifier (3.4.3.2) except that:
15774     //
15775     //     -- Any using-directives in the associated namespace are
15776     //        ignored.
15777     //
15778     //     -- Any namespace-scope friend functions declared in
15779     //        associated classes are visible within their respective
15780     //        namespaces even if they are not visible during an ordinary
15781     //        lookup (11.4).
15782     DeclContext::lookup_result R = NS->lookup(Id.getName());
15783     for (auto *D : R) {
15784       auto *Underlying = D;
15785       if (auto *USD = dyn_cast<UsingShadowDecl>(D))
15786         Underlying = USD->getTargetDecl();
15787 
15788       if (!isa<OMPDeclareReductionDecl>(Underlying) &&
15789           !isa<OMPDeclareMapperDecl>(Underlying))
15790         continue;
15791 
15792       if (!SemaRef.isVisible(D)) {
15793         D = findAcceptableDecl(SemaRef, D);
15794         if (!D)
15795           continue;
15796         if (auto *USD = dyn_cast<UsingShadowDecl>(D))
15797           Underlying = USD->getTargetDecl();
15798       }
15799       Lookups.emplace_back();
15800       Lookups.back().addDecl(Underlying);
15801     }
15802   }
15803 }
15804 
15805 static ExprResult
15806 buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
15807                          Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
15808                          const DeclarationNameInfo &ReductionId, QualType Ty,
15809                          CXXCastPath &BasePath, Expr *UnresolvedReduction) {
15810   if (ReductionIdScopeSpec.isInvalid())
15811     return ExprError();
15812   SmallVector<UnresolvedSet<8>, 4> Lookups;
15813   if (S) {
15814     LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
15815     Lookup.suppressDiagnostics();
15816     while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
15817       NamedDecl *D = Lookup.getRepresentativeDecl();
15818       do {
15819         S = S->getParent();
15820       } while (S && !S->isDeclScope(D));
15821       if (S)
15822         S = S->getParent();
15823       Lookups.emplace_back();
15824       Lookups.back().append(Lookup.begin(), Lookup.end());
15825       Lookup.clear();
15826     }
15827   } else if (auto *ULE =
15828                  cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
15829     Lookups.push_back(UnresolvedSet<8>());
15830     Decl *PrevD = nullptr;
15831     for (NamedDecl *D : ULE->decls()) {
15832       if (D == PrevD)
15833         Lookups.push_back(UnresolvedSet<8>());
15834       else if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(D))
15835         Lookups.back().addDecl(DRD);
15836       PrevD = D;
15837     }
15838   }
15839   if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() ||
15840       Ty->isInstantiationDependentType() ||
15841       Ty->containsUnexpandedParameterPack() ||
15842       filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
15843         return !D->isInvalidDecl() &&
15844                (D->getType()->isDependentType() ||
15845                 D->getType()->isInstantiationDependentType() ||
15846                 D->getType()->containsUnexpandedParameterPack());
15847       })) {
15848     UnresolvedSet<8> ResSet;
15849     for (const UnresolvedSet<8> &Set : Lookups) {
15850       if (Set.empty())
15851         continue;
15852       ResSet.append(Set.begin(), Set.end());
15853       // The last item marks the end of all declarations at the specified scope.
15854       ResSet.addDecl(Set[Set.size() - 1]);
15855     }
15856     return UnresolvedLookupExpr::Create(
15857         SemaRef.Context, /*NamingClass=*/nullptr,
15858         ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
15859         /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
15860   }
15861   // Lookup inside the classes.
15862   // C++ [over.match.oper]p3:
15863   //   For a unary operator @ with an operand of a type whose
15864   //   cv-unqualified version is T1, and for a binary operator @ with
15865   //   a left operand of a type whose cv-unqualified version is T1 and
15866   //   a right operand of a type whose cv-unqualified version is T2,
15867   //   three sets of candidate functions, designated member
15868   //   candidates, non-member candidates and built-in candidates, are
15869   //   constructed as follows:
15870   //     -- If T1 is a complete class type or a class currently being
15871   //        defined, the set of member candidates is the result of the
15872   //        qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
15873   //        the set of member candidates is empty.
15874   LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
15875   Lookup.suppressDiagnostics();
15876   if (const auto *TyRec = Ty->getAs<RecordType>()) {
15877     // Complete the type if it can be completed.
15878     // If the type is neither complete nor being defined, bail out now.
15879     if (SemaRef.isCompleteType(Loc, Ty) || TyRec->isBeingDefined() ||
15880         TyRec->getDecl()->getDefinition()) {
15881       Lookup.clear();
15882       SemaRef.LookupQualifiedName(Lookup, TyRec->getDecl());
15883       if (Lookup.empty()) {
15884         Lookups.emplace_back();
15885         Lookups.back().append(Lookup.begin(), Lookup.end());
15886       }
15887     }
15888   }
15889   // Perform ADL.
15890   if (SemaRef.getLangOpts().CPlusPlus)
15891     argumentDependentLookup(SemaRef, ReductionId, Loc, Ty, Lookups);
15892   if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
15893           Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
15894             if (!D->isInvalidDecl() &&
15895                 SemaRef.Context.hasSameType(D->getType(), Ty))
15896               return D;
15897             return nullptr;
15898           }))
15899     return SemaRef.BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(),
15900                                     VK_LValue, Loc);
15901   if (SemaRef.getLangOpts().CPlusPlus) {
15902     if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
15903             Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
15904               if (!D->isInvalidDecl() &&
15905                   SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
15906                   !Ty.isMoreQualifiedThan(D->getType()))
15907                 return D;
15908               return nullptr;
15909             })) {
15910       CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
15911                          /*DetectVirtual=*/false);
15912       if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
15913         if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
15914                 VD->getType().getUnqualifiedType()))) {
15915           if (SemaRef.CheckBaseClassAccess(
15916                   Loc, VD->getType(), Ty, Paths.front(),
15917                   /*DiagID=*/0) != Sema::AR_inaccessible) {
15918             SemaRef.BuildBasePathArray(Paths, BasePath);
15919             return SemaRef.BuildDeclRefExpr(
15920                 VD, VD->getType().getNonReferenceType(), VK_LValue, Loc);
15921           }
15922         }
15923       }
15924     }
15925   }
15926   if (ReductionIdScopeSpec.isSet()) {
15927     SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier)
15928         << Ty << Range;
15929     return ExprError();
15930   }
15931   return ExprEmpty();
15932 }
15933 
15934 namespace {
15935 /// Data for the reduction-based clauses.
15936 struct ReductionData {
15937   /// List of original reduction items.
15938   SmallVector<Expr *, 8> Vars;
15939   /// List of private copies of the reduction items.
15940   SmallVector<Expr *, 8> Privates;
15941   /// LHS expressions for the reduction_op expressions.
15942   SmallVector<Expr *, 8> LHSs;
15943   /// RHS expressions for the reduction_op expressions.
15944   SmallVector<Expr *, 8> RHSs;
15945   /// Reduction operation expression.
15946   SmallVector<Expr *, 8> ReductionOps;
15947   /// inscan copy operation expressions.
15948   SmallVector<Expr *, 8> InscanCopyOps;
15949   /// inscan copy temp array expressions for prefix sums.
15950   SmallVector<Expr *, 8> InscanCopyArrayTemps;
15951   /// inscan copy temp array element expressions for prefix sums.
15952   SmallVector<Expr *, 8> InscanCopyArrayElems;
15953   /// Taskgroup descriptors for the corresponding reduction items in
15954   /// in_reduction clauses.
15955   SmallVector<Expr *, 8> TaskgroupDescriptors;
15956   /// List of captures for clause.
15957   SmallVector<Decl *, 4> ExprCaptures;
15958   /// List of postupdate expressions.
15959   SmallVector<Expr *, 4> ExprPostUpdates;
15960   /// Reduction modifier.
15961   unsigned RedModifier = 0;
15962   ReductionData() = delete;
15963   /// Reserves required memory for the reduction data.
15964   ReductionData(unsigned Size, unsigned Modifier = 0) : RedModifier(Modifier) {
15965     Vars.reserve(Size);
15966     Privates.reserve(Size);
15967     LHSs.reserve(Size);
15968     RHSs.reserve(Size);
15969     ReductionOps.reserve(Size);
15970     if (RedModifier == OMPC_REDUCTION_inscan) {
15971       InscanCopyOps.reserve(Size);
15972       InscanCopyArrayTemps.reserve(Size);
15973       InscanCopyArrayElems.reserve(Size);
15974     }
15975     TaskgroupDescriptors.reserve(Size);
15976     ExprCaptures.reserve(Size);
15977     ExprPostUpdates.reserve(Size);
15978   }
15979   /// Stores reduction item and reduction operation only (required for dependent
15980   /// reduction item).
15981   void push(Expr *Item, Expr *ReductionOp) {
15982     Vars.emplace_back(Item);
15983     Privates.emplace_back(nullptr);
15984     LHSs.emplace_back(nullptr);
15985     RHSs.emplace_back(nullptr);
15986     ReductionOps.emplace_back(ReductionOp);
15987     TaskgroupDescriptors.emplace_back(nullptr);
15988     if (RedModifier == OMPC_REDUCTION_inscan) {
15989       InscanCopyOps.push_back(nullptr);
15990       InscanCopyArrayTemps.push_back(nullptr);
15991       InscanCopyArrayElems.push_back(nullptr);
15992     }
15993   }
15994   /// Stores reduction data.
15995   void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp,
15996             Expr *TaskgroupDescriptor, Expr *CopyOp, Expr *CopyArrayTemp,
15997             Expr *CopyArrayElem) {
15998     Vars.emplace_back(Item);
15999     Privates.emplace_back(Private);
16000     LHSs.emplace_back(LHS);
16001     RHSs.emplace_back(RHS);
16002     ReductionOps.emplace_back(ReductionOp);
16003     TaskgroupDescriptors.emplace_back(TaskgroupDescriptor);
16004     if (RedModifier == OMPC_REDUCTION_inscan) {
16005       InscanCopyOps.push_back(CopyOp);
16006       InscanCopyArrayTemps.push_back(CopyArrayTemp);
16007       InscanCopyArrayElems.push_back(CopyArrayElem);
16008     } else {
16009       assert(CopyOp == nullptr && CopyArrayTemp == nullptr &&
16010              CopyArrayElem == nullptr &&
16011              "Copy operation must be used for inscan reductions only.");
16012     }
16013   }
16014 };
16015 } // namespace
16016 
16017 static bool checkOMPArraySectionConstantForReduction(
16018     ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement,
16019     SmallVectorImpl<llvm::APSInt> &ArraySizes) {
16020   const Expr *Length = OASE->getLength();
16021   if (Length == nullptr) {
16022     // For array sections of the form [1:] or [:], we would need to analyze
16023     // the lower bound...
16024     if (OASE->getColonLocFirst().isValid())
16025       return false;
16026 
16027     // This is an array subscript which has implicit length 1!
16028     SingleElement = true;
16029     ArraySizes.push_back(llvm::APSInt::get(1));
16030   } else {
16031     Expr::EvalResult Result;
16032     if (!Length->EvaluateAsInt(Result, Context))
16033       return false;
16034 
16035     llvm::APSInt ConstantLengthValue = Result.Val.getInt();
16036     SingleElement = (ConstantLengthValue.getSExtValue() == 1);
16037     ArraySizes.push_back(ConstantLengthValue);
16038   }
16039 
16040   // Get the base of this array section and walk up from there.
16041   const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
16042 
16043   // We require length = 1 for all array sections except the right-most to
16044   // guarantee that the memory region is contiguous and has no holes in it.
16045   while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) {
16046     Length = TempOASE->getLength();
16047     if (Length == nullptr) {
16048       // For array sections of the form [1:] or [:], we would need to analyze
16049       // the lower bound...
16050       if (OASE->getColonLocFirst().isValid())
16051         return false;
16052 
16053       // This is an array subscript which has implicit length 1!
16054       ArraySizes.push_back(llvm::APSInt::get(1));
16055     } else {
16056       Expr::EvalResult Result;
16057       if (!Length->EvaluateAsInt(Result, Context))
16058         return false;
16059 
16060       llvm::APSInt ConstantLengthValue = Result.Val.getInt();
16061       if (ConstantLengthValue.getSExtValue() != 1)
16062         return false;
16063 
16064       ArraySizes.push_back(ConstantLengthValue);
16065     }
16066     Base = TempOASE->getBase()->IgnoreParenImpCasts();
16067   }
16068 
16069   // If we have a single element, we don't need to add the implicit lengths.
16070   if (!SingleElement) {
16071     while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) {
16072       // Has implicit length 1!
16073       ArraySizes.push_back(llvm::APSInt::get(1));
16074       Base = TempASE->getBase()->IgnoreParenImpCasts();
16075     }
16076   }
16077 
16078   // This array section can be privatized as a single value or as a constant
16079   // sized array.
16080   return true;
16081 }
16082 
16083 static bool actOnOMPReductionKindClause(
16084     Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind,
16085     ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
16086     SourceLocation ColonLoc, SourceLocation EndLoc,
16087     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
16088     ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) {
16089   DeclarationName DN = ReductionId.getName();
16090   OverloadedOperatorKind OOK = DN.getCXXOverloadedOperator();
16091   BinaryOperatorKind BOK = BO_Comma;
16092 
16093   ASTContext &Context = S.Context;
16094   // OpenMP [2.14.3.6, reduction clause]
16095   // C
16096   // reduction-identifier is either an identifier or one of the following
16097   // operators: +, -, *,  &, |, ^, && and ||
16098   // C++
16099   // reduction-identifier is either an id-expression or one of the following
16100   // operators: +, -, *, &, |, ^, && and ||
16101   switch (OOK) {
16102   case OO_Plus:
16103   case OO_Minus:
16104     BOK = BO_Add;
16105     break;
16106   case OO_Star:
16107     BOK = BO_Mul;
16108     break;
16109   case OO_Amp:
16110     BOK = BO_And;
16111     break;
16112   case OO_Pipe:
16113     BOK = BO_Or;
16114     break;
16115   case OO_Caret:
16116     BOK = BO_Xor;
16117     break;
16118   case OO_AmpAmp:
16119     BOK = BO_LAnd;
16120     break;
16121   case OO_PipePipe:
16122     BOK = BO_LOr;
16123     break;
16124   case OO_New:
16125   case OO_Delete:
16126   case OO_Array_New:
16127   case OO_Array_Delete:
16128   case OO_Slash:
16129   case OO_Percent:
16130   case OO_Tilde:
16131   case OO_Exclaim:
16132   case OO_Equal:
16133   case OO_Less:
16134   case OO_Greater:
16135   case OO_LessEqual:
16136   case OO_GreaterEqual:
16137   case OO_PlusEqual:
16138   case OO_MinusEqual:
16139   case OO_StarEqual:
16140   case OO_SlashEqual:
16141   case OO_PercentEqual:
16142   case OO_CaretEqual:
16143   case OO_AmpEqual:
16144   case OO_PipeEqual:
16145   case OO_LessLess:
16146   case OO_GreaterGreater:
16147   case OO_LessLessEqual:
16148   case OO_GreaterGreaterEqual:
16149   case OO_EqualEqual:
16150   case OO_ExclaimEqual:
16151   case OO_Spaceship:
16152   case OO_PlusPlus:
16153   case OO_MinusMinus:
16154   case OO_Comma:
16155   case OO_ArrowStar:
16156   case OO_Arrow:
16157   case OO_Call:
16158   case OO_Subscript:
16159   case OO_Conditional:
16160   case OO_Coawait:
16161   case NUM_OVERLOADED_OPERATORS:
16162     llvm_unreachable("Unexpected reduction identifier");
16163   case OO_None:
16164     if (IdentifierInfo *II = DN.getAsIdentifierInfo()) {
16165       if (II->isStr("max"))
16166         BOK = BO_GT;
16167       else if (II->isStr("min"))
16168         BOK = BO_LT;
16169     }
16170     break;
16171   }
16172   SourceRange ReductionIdRange;
16173   if (ReductionIdScopeSpec.isValid())
16174     ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
16175   else
16176     ReductionIdRange.setBegin(ReductionId.getBeginLoc());
16177   ReductionIdRange.setEnd(ReductionId.getEndLoc());
16178 
16179   auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
16180   bool FirstIter = true;
16181   for (Expr *RefExpr : VarList) {
16182     assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
16183     // OpenMP [2.1, C/C++]
16184     //  A list item is a variable or array section, subject to the restrictions
16185     //  specified in Section 2.4 on page 42 and in each of the sections
16186     // describing clauses and directives for which a list appears.
16187     // OpenMP  [2.14.3.3, Restrictions, p.1]
16188     //  A variable that is part of another variable (as an array or
16189     //  structure element) cannot appear in a private clause.
16190     if (!FirstIter && IR != ER)
16191       ++IR;
16192     FirstIter = false;
16193     SourceLocation ELoc;
16194     SourceRange ERange;
16195     Expr *SimpleRefExpr = RefExpr;
16196     auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
16197                               /*AllowArraySection=*/true);
16198     if (Res.second) {
16199       // Try to find 'declare reduction' corresponding construct before using
16200       // builtin/overloaded operators.
16201       QualType Type = Context.DependentTy;
16202       CXXCastPath BasePath;
16203       ExprResult DeclareReductionRef = buildDeclareReductionRef(
16204           S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
16205           ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
16206       Expr *ReductionOp = nullptr;
16207       if (S.CurContext->isDependentContext() &&
16208           (DeclareReductionRef.isUnset() ||
16209            isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
16210         ReductionOp = DeclareReductionRef.get();
16211       // It will be analyzed later.
16212       RD.push(RefExpr, ReductionOp);
16213     }
16214     ValueDecl *D = Res.first;
16215     if (!D)
16216       continue;
16217 
16218     Expr *TaskgroupDescriptor = nullptr;
16219     QualType Type;
16220     auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
16221     auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
16222     if (ASE) {
16223       Type = ASE->getType().getNonReferenceType();
16224     } else if (OASE) {
16225       QualType BaseType =
16226           OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
16227       if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
16228         Type = ATy->getElementType();
16229       else
16230         Type = BaseType->getPointeeType();
16231       Type = Type.getNonReferenceType();
16232     } else {
16233       Type = Context.getBaseElementType(D->getType().getNonReferenceType());
16234     }
16235     auto *VD = dyn_cast<VarDecl>(D);
16236 
16237     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
16238     //  A variable that appears in a private clause must not have an incomplete
16239     //  type or a reference type.
16240     if (S.RequireCompleteType(ELoc, D->getType(),
16241                               diag::err_omp_reduction_incomplete_type))
16242       continue;
16243     // OpenMP [2.14.3.6, reduction clause, Restrictions]
16244     // A list item that appears in a reduction clause must not be
16245     // const-qualified.
16246     if (rejectConstNotMutableType(S, D, Type, ClauseKind, ELoc,
16247                                   /*AcceptIfMutable*/ false, ASE || OASE))
16248       continue;
16249 
16250     OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective();
16251     // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
16252     //  If a list-item is a reference type then it must bind to the same object
16253     //  for all threads of the team.
16254     if (!ASE && !OASE) {
16255       if (VD) {
16256         VarDecl *VDDef = VD->getDefinition();
16257         if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
16258           DSARefChecker Check(Stack);
16259           if (Check.Visit(VDDef->getInit())) {
16260             S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg)
16261                 << getOpenMPClauseName(ClauseKind) << ERange;
16262             S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
16263             continue;
16264           }
16265         }
16266       }
16267 
16268       // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
16269       // in a Construct]
16270       //  Variables with the predetermined data-sharing attributes may not be
16271       //  listed in data-sharing attributes clauses, except for the cases
16272       //  listed below. For these exceptions only, listing a predetermined
16273       //  variable in a data-sharing attribute clause is allowed and overrides
16274       //  the variable's predetermined data-sharing attributes.
16275       // OpenMP [2.14.3.6, Restrictions, p.3]
16276       //  Any number of reduction clauses can be specified on the directive,
16277       //  but a list item can appear only once in the reduction clauses for that
16278       //  directive.
16279       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false);
16280       if (DVar.CKind == OMPC_reduction) {
16281         S.Diag(ELoc, diag::err_omp_once_referenced)
16282             << getOpenMPClauseName(ClauseKind);
16283         if (DVar.RefExpr)
16284           S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
16285         continue;
16286       }
16287       if (DVar.CKind != OMPC_unknown) {
16288         S.Diag(ELoc, diag::err_omp_wrong_dsa)
16289             << getOpenMPClauseName(DVar.CKind)
16290             << getOpenMPClauseName(OMPC_reduction);
16291         reportOriginalDsa(S, Stack, D, DVar);
16292         continue;
16293       }
16294 
16295       // OpenMP [2.14.3.6, Restrictions, p.1]
16296       //  A list item that appears in a reduction clause of a worksharing
16297       //  construct must be shared in the parallel regions to which any of the
16298       //  worksharing regions arising from the worksharing construct bind.
16299       if (isOpenMPWorksharingDirective(CurrDir) &&
16300           !isOpenMPParallelDirective(CurrDir) &&
16301           !isOpenMPTeamsDirective(CurrDir)) {
16302         DVar = Stack->getImplicitDSA(D, true);
16303         if (DVar.CKind != OMPC_shared) {
16304           S.Diag(ELoc, diag::err_omp_required_access)
16305               << getOpenMPClauseName(OMPC_reduction)
16306               << getOpenMPClauseName(OMPC_shared);
16307           reportOriginalDsa(S, Stack, D, DVar);
16308           continue;
16309         }
16310       }
16311     } else {
16312       // Threadprivates cannot be shared between threads, so dignose if the base
16313       // is a threadprivate variable.
16314       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false);
16315       if (DVar.CKind == OMPC_threadprivate) {
16316         S.Diag(ELoc, diag::err_omp_wrong_dsa)
16317             << getOpenMPClauseName(DVar.CKind)
16318             << getOpenMPClauseName(OMPC_reduction);
16319         reportOriginalDsa(S, Stack, D, DVar);
16320         continue;
16321       }
16322     }
16323 
16324     // Try to find 'declare reduction' corresponding construct before using
16325     // builtin/overloaded operators.
16326     CXXCastPath BasePath;
16327     ExprResult DeclareReductionRef = buildDeclareReductionRef(
16328         S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
16329         ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
16330     if (DeclareReductionRef.isInvalid())
16331       continue;
16332     if (S.CurContext->isDependentContext() &&
16333         (DeclareReductionRef.isUnset() ||
16334          isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
16335       RD.push(RefExpr, DeclareReductionRef.get());
16336       continue;
16337     }
16338     if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
16339       // Not allowed reduction identifier is found.
16340       S.Diag(ReductionId.getBeginLoc(),
16341              diag::err_omp_unknown_reduction_identifier)
16342           << Type << ReductionIdRange;
16343       continue;
16344     }
16345 
16346     // OpenMP [2.14.3.6, reduction clause, Restrictions]
16347     // The type of a list item that appears in a reduction clause must be valid
16348     // for the reduction-identifier. For a max or min reduction in C, the type
16349     // of the list item must be an allowed arithmetic data type: char, int,
16350     // float, double, or _Bool, possibly modified with long, short, signed, or
16351     // unsigned. For a max or min reduction in C++, the type of the list item
16352     // must be an allowed arithmetic data type: char, wchar_t, int, float,
16353     // double, or bool, possibly modified with long, short, signed, or unsigned.
16354     if (DeclareReductionRef.isUnset()) {
16355       if ((BOK == BO_GT || BOK == BO_LT) &&
16356           !(Type->isScalarType() ||
16357             (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
16358         S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
16359             << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus;
16360         if (!ASE && !OASE) {
16361           bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
16362                                    VarDecl::DeclarationOnly;
16363           S.Diag(D->getLocation(),
16364                  IsDecl ? diag::note_previous_decl : diag::note_defined_here)
16365               << D;
16366         }
16367         continue;
16368       }
16369       if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
16370           !S.getLangOpts().CPlusPlus && Type->isFloatingType()) {
16371         S.Diag(ELoc, diag::err_omp_clause_floating_type_arg)
16372             << getOpenMPClauseName(ClauseKind);
16373         if (!ASE && !OASE) {
16374           bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
16375                                    VarDecl::DeclarationOnly;
16376           S.Diag(D->getLocation(),
16377                  IsDecl ? diag::note_previous_decl : diag::note_defined_here)
16378               << D;
16379         }
16380         continue;
16381       }
16382     }
16383 
16384     Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
16385     VarDecl *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs",
16386                                   D->hasAttrs() ? &D->getAttrs() : nullptr);
16387     VarDecl *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(),
16388                                   D->hasAttrs() ? &D->getAttrs() : nullptr);
16389     QualType PrivateTy = Type;
16390 
16391     // Try if we can determine constant lengths for all array sections and avoid
16392     // the VLA.
16393     bool ConstantLengthOASE = false;
16394     if (OASE) {
16395       bool SingleElement;
16396       llvm::SmallVector<llvm::APSInt, 4> ArraySizes;
16397       ConstantLengthOASE = checkOMPArraySectionConstantForReduction(
16398           Context, OASE, SingleElement, ArraySizes);
16399 
16400       // If we don't have a single element, we must emit a constant array type.
16401       if (ConstantLengthOASE && !SingleElement) {
16402         for (llvm::APSInt &Size : ArraySizes)
16403           PrivateTy = Context.getConstantArrayType(PrivateTy, Size, nullptr,
16404                                                    ArrayType::Normal,
16405                                                    /*IndexTypeQuals=*/0);
16406       }
16407     }
16408 
16409     if ((OASE && !ConstantLengthOASE) ||
16410         (!OASE && !ASE &&
16411          D->getType().getNonReferenceType()->isVariablyModifiedType())) {
16412       if (!Context.getTargetInfo().isVLASupported()) {
16413         if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective())) {
16414           S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
16415           S.Diag(ELoc, diag::note_vla_unsupported);
16416           continue;
16417         } else {
16418           S.targetDiag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
16419           S.targetDiag(ELoc, diag::note_vla_unsupported);
16420         }
16421       }
16422       // For arrays/array sections only:
16423       // Create pseudo array type for private copy. The size for this array will
16424       // be generated during codegen.
16425       // For array subscripts or single variables Private Ty is the same as Type
16426       // (type of the variable or single array element).
16427       PrivateTy = Context.getVariableArrayType(
16428           Type,
16429           new (Context) OpaqueValueExpr(ELoc, Context.getSizeType(), VK_RValue),
16430           ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
16431     } else if (!ASE && !OASE &&
16432                Context.getAsArrayType(D->getType().getNonReferenceType())) {
16433       PrivateTy = D->getType().getNonReferenceType();
16434     }
16435     // Private copy.
16436     VarDecl *PrivateVD =
16437         buildVarDecl(S, ELoc, PrivateTy, D->getName(),
16438                      D->hasAttrs() ? &D->getAttrs() : nullptr,
16439                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
16440     // Add initializer for private variable.
16441     Expr *Init = nullptr;
16442     DeclRefExpr *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc);
16443     DeclRefExpr *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc);
16444     if (DeclareReductionRef.isUsable()) {
16445       auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
16446       auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
16447       if (DRD->getInitializer()) {
16448         S.ActOnUninitializedDecl(PrivateVD);
16449         Init = DRDRef;
16450         RHSVD->setInit(DRDRef);
16451         RHSVD->setInitStyle(VarDecl::CallInit);
16452       }
16453     } else {
16454       switch (BOK) {
16455       case BO_Add:
16456       case BO_Xor:
16457       case BO_Or:
16458       case BO_LOr:
16459         // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
16460         if (Type->isScalarType() || Type->isAnyComplexType())
16461           Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get();
16462         break;
16463       case BO_Mul:
16464       case BO_LAnd:
16465         if (Type->isScalarType() || Type->isAnyComplexType()) {
16466           // '*' and '&&' reduction ops - initializer is '1'.
16467           Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get();
16468         }
16469         break;
16470       case BO_And: {
16471         // '&' reduction op - initializer is '~0'.
16472         QualType OrigType = Type;
16473         if (auto *ComplexTy = OrigType->getAs<ComplexType>())
16474           Type = ComplexTy->getElementType();
16475         if (Type->isRealFloatingType()) {
16476           llvm::APFloat InitValue = llvm::APFloat::getAllOnesValue(
16477               Context.getFloatTypeSemantics(Type),
16478               Context.getTypeSize(Type));
16479           Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
16480                                          Type, ELoc);
16481         } else if (Type->isScalarType()) {
16482           uint64_t Size = Context.getTypeSize(Type);
16483           QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
16484           llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
16485           Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
16486         }
16487         if (Init && OrigType->isAnyComplexType()) {
16488           // Init = 0xFFFF + 0xFFFFi;
16489           auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
16490           Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
16491         }
16492         Type = OrigType;
16493         break;
16494       }
16495       case BO_LT:
16496       case BO_GT: {
16497         // 'min' reduction op - initializer is 'Largest representable number in
16498         // the reduction list item type'.
16499         // 'max' reduction op - initializer is 'Least representable number in
16500         // the reduction list item type'.
16501         if (Type->isIntegerType() || Type->isPointerType()) {
16502           bool IsSigned = Type->hasSignedIntegerRepresentation();
16503           uint64_t Size = Context.getTypeSize(Type);
16504           QualType IntTy =
16505               Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
16506           llvm::APInt InitValue =
16507               (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
16508                                         : llvm::APInt::getMinValue(Size)
16509                              : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
16510                                         : llvm::APInt::getMaxValue(Size);
16511           Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
16512           if (Type->isPointerType()) {
16513             // Cast to pointer type.
16514             ExprResult CastExpr = S.BuildCStyleCastExpr(
16515                 ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init);
16516             if (CastExpr.isInvalid())
16517               continue;
16518             Init = CastExpr.get();
16519           }
16520         } else if (Type->isRealFloatingType()) {
16521           llvm::APFloat InitValue = llvm::APFloat::getLargest(
16522               Context.getFloatTypeSemantics(Type), BOK != BO_LT);
16523           Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
16524                                          Type, ELoc);
16525         }
16526         break;
16527       }
16528       case BO_PtrMemD:
16529       case BO_PtrMemI:
16530       case BO_MulAssign:
16531       case BO_Div:
16532       case BO_Rem:
16533       case BO_Sub:
16534       case BO_Shl:
16535       case BO_Shr:
16536       case BO_LE:
16537       case BO_GE:
16538       case BO_EQ:
16539       case BO_NE:
16540       case BO_Cmp:
16541       case BO_AndAssign:
16542       case BO_XorAssign:
16543       case BO_OrAssign:
16544       case BO_Assign:
16545       case BO_AddAssign:
16546       case BO_SubAssign:
16547       case BO_DivAssign:
16548       case BO_RemAssign:
16549       case BO_ShlAssign:
16550       case BO_ShrAssign:
16551       case BO_Comma:
16552         llvm_unreachable("Unexpected reduction operation");
16553       }
16554     }
16555     if (Init && DeclareReductionRef.isUnset()) {
16556       S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
16557       // Store initializer for single element in private copy. Will be used
16558       // during codegen.
16559       PrivateVD->setInit(RHSVD->getInit());
16560       PrivateVD->setInitStyle(RHSVD->getInitStyle());
16561     } else if (!Init) {
16562       S.ActOnUninitializedDecl(RHSVD);
16563       // Store initializer for single element in private copy. Will be used
16564       // during codegen.
16565       PrivateVD->setInit(RHSVD->getInit());
16566       PrivateVD->setInitStyle(RHSVD->getInitStyle());
16567     }
16568     if (RHSVD->isInvalidDecl())
16569       continue;
16570     if (!RHSVD->hasInit() &&
16571         (DeclareReductionRef.isUnset() || !S.LangOpts.CPlusPlus)) {
16572       S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible)
16573           << Type << ReductionIdRange;
16574       bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
16575                                VarDecl::DeclarationOnly;
16576       S.Diag(D->getLocation(),
16577              IsDecl ? diag::note_previous_decl : diag::note_defined_here)
16578           << D;
16579       continue;
16580     }
16581     DeclRefExpr *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc);
16582     ExprResult ReductionOp;
16583     if (DeclareReductionRef.isUsable()) {
16584       QualType RedTy = DeclareReductionRef.get()->getType();
16585       QualType PtrRedTy = Context.getPointerType(RedTy);
16586       ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
16587       ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
16588       if (!BasePath.empty()) {
16589         LHS = S.DefaultLvalueConversion(LHS.get());
16590         RHS = S.DefaultLvalueConversion(RHS.get());
16591         LHS = ImplicitCastExpr::Create(
16592             Context, PtrRedTy, CK_UncheckedDerivedToBase, LHS.get(), &BasePath,
16593             LHS.get()->getValueKind(), FPOptionsOverride());
16594         RHS = ImplicitCastExpr::Create(
16595             Context, PtrRedTy, CK_UncheckedDerivedToBase, RHS.get(), &BasePath,
16596             RHS.get()->getValueKind(), FPOptionsOverride());
16597       }
16598       FunctionProtoType::ExtProtoInfo EPI;
16599       QualType Params[] = {PtrRedTy, PtrRedTy};
16600       QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
16601       auto *OVE = new (Context) OpaqueValueExpr(
16602           ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
16603           S.DefaultLvalueConversion(DeclareReductionRef.get()).get());
16604       Expr *Args[] = {LHS.get(), RHS.get()};
16605       ReductionOp =
16606           CallExpr::Create(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc,
16607                            S.CurFPFeatureOverrides());
16608     } else {
16609       ReductionOp = S.BuildBinOp(
16610           Stack->getCurScope(), ReductionId.getBeginLoc(), BOK, LHSDRE, RHSDRE);
16611       if (ReductionOp.isUsable()) {
16612         if (BOK != BO_LT && BOK != BO_GT) {
16613           ReductionOp =
16614               S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
16615                            BO_Assign, LHSDRE, ReductionOp.get());
16616         } else {
16617           auto *ConditionalOp = new (Context)
16618               ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc, RHSDRE,
16619                                   Type, VK_LValue, OK_Ordinary);
16620           ReductionOp =
16621               S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
16622                            BO_Assign, LHSDRE, ConditionalOp);
16623         }
16624         if (ReductionOp.isUsable())
16625           ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get(),
16626                                               /*DiscardedValue*/ false);
16627       }
16628       if (!ReductionOp.isUsable())
16629         continue;
16630     }
16631 
16632     // Add copy operations for inscan reductions.
16633     // LHS = RHS;
16634     ExprResult CopyOpRes, TempArrayRes, TempArrayElem;
16635     if (ClauseKind == OMPC_reduction &&
16636         RD.RedModifier == OMPC_REDUCTION_inscan) {
16637       ExprResult RHS = S.DefaultLvalueConversion(RHSDRE);
16638       CopyOpRes = S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, LHSDRE,
16639                                RHS.get());
16640       if (!CopyOpRes.isUsable())
16641         continue;
16642       CopyOpRes =
16643           S.ActOnFinishFullExpr(CopyOpRes.get(), /*DiscardedValue=*/true);
16644       if (!CopyOpRes.isUsable())
16645         continue;
16646       // For simd directive and simd-based directives in simd mode no need to
16647       // construct temp array, need just a single temp element.
16648       if (Stack->getCurrentDirective() == OMPD_simd ||
16649           (S.getLangOpts().OpenMPSimd &&
16650            isOpenMPSimdDirective(Stack->getCurrentDirective()))) {
16651         VarDecl *TempArrayVD =
16652             buildVarDecl(S, ELoc, PrivateTy, D->getName(),
16653                          D->hasAttrs() ? &D->getAttrs() : nullptr);
16654         // Add a constructor to the temp decl.
16655         S.ActOnUninitializedDecl(TempArrayVD);
16656         TempArrayRes = buildDeclRefExpr(S, TempArrayVD, PrivateTy, ELoc);
16657       } else {
16658         // Build temp array for prefix sum.
16659         auto *Dim = new (S.Context)
16660             OpaqueValueExpr(ELoc, S.Context.getSizeType(), VK_RValue);
16661         QualType ArrayTy =
16662             S.Context.getVariableArrayType(PrivateTy, Dim, ArrayType::Normal,
16663                                            /*IndexTypeQuals=*/0, {ELoc, ELoc});
16664         VarDecl *TempArrayVD =
16665             buildVarDecl(S, ELoc, ArrayTy, D->getName(),
16666                          D->hasAttrs() ? &D->getAttrs() : nullptr);
16667         // Add a constructor to the temp decl.
16668         S.ActOnUninitializedDecl(TempArrayVD);
16669         TempArrayRes = buildDeclRefExpr(S, TempArrayVD, ArrayTy, ELoc);
16670         TempArrayElem =
16671             S.DefaultFunctionArrayLvalueConversion(TempArrayRes.get());
16672         auto *Idx = new (S.Context)
16673             OpaqueValueExpr(ELoc, S.Context.getSizeType(), VK_RValue);
16674         TempArrayElem = S.CreateBuiltinArraySubscriptExpr(TempArrayElem.get(),
16675                                                           ELoc, Idx, ELoc);
16676       }
16677     }
16678 
16679     // OpenMP [2.15.4.6, Restrictions, p.2]
16680     // A list item that appears in an in_reduction clause of a task construct
16681     // must appear in a task_reduction clause of a construct associated with a
16682     // taskgroup region that includes the participating task in its taskgroup
16683     // set. The construct associated with the innermost region that meets this
16684     // condition must specify the same reduction-identifier as the in_reduction
16685     // clause.
16686     if (ClauseKind == OMPC_in_reduction) {
16687       SourceRange ParentSR;
16688       BinaryOperatorKind ParentBOK;
16689       const Expr *ParentReductionOp = nullptr;
16690       Expr *ParentBOKTD = nullptr, *ParentReductionOpTD = nullptr;
16691       DSAStackTy::DSAVarData ParentBOKDSA =
16692           Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK,
16693                                                   ParentBOKTD);
16694       DSAStackTy::DSAVarData ParentReductionOpDSA =
16695           Stack->getTopMostTaskgroupReductionData(
16696               D, ParentSR, ParentReductionOp, ParentReductionOpTD);
16697       bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown;
16698       bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown;
16699       if ((DeclareReductionRef.isUnset() && IsParentReductionOp) ||
16700           (DeclareReductionRef.isUsable() && IsParentBOK) ||
16701           (IsParentBOK && BOK != ParentBOK) || IsParentReductionOp) {
16702         bool EmitError = true;
16703         if (IsParentReductionOp && DeclareReductionRef.isUsable()) {
16704           llvm::FoldingSetNodeID RedId, ParentRedId;
16705           ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true);
16706           DeclareReductionRef.get()->Profile(RedId, Context,
16707                                              /*Canonical=*/true);
16708           EmitError = RedId != ParentRedId;
16709         }
16710         if (EmitError) {
16711           S.Diag(ReductionId.getBeginLoc(),
16712                  diag::err_omp_reduction_identifier_mismatch)
16713               << ReductionIdRange << RefExpr->getSourceRange();
16714           S.Diag(ParentSR.getBegin(),
16715                  diag::note_omp_previous_reduction_identifier)
16716               << ParentSR
16717               << (IsParentBOK ? ParentBOKDSA.RefExpr
16718                               : ParentReductionOpDSA.RefExpr)
16719                      ->getSourceRange();
16720           continue;
16721         }
16722       }
16723       TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD;
16724     }
16725 
16726     DeclRefExpr *Ref = nullptr;
16727     Expr *VarsExpr = RefExpr->IgnoreParens();
16728     if (!VD && !S.CurContext->isDependentContext()) {
16729       if (ASE || OASE) {
16730         TransformExprToCaptures RebuildToCapture(S, D);
16731         VarsExpr =
16732             RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
16733         Ref = RebuildToCapture.getCapturedExpr();
16734       } else {
16735         VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false);
16736       }
16737       if (!S.isOpenMPCapturedDecl(D)) {
16738         RD.ExprCaptures.emplace_back(Ref->getDecl());
16739         if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
16740           ExprResult RefRes = S.DefaultLvalueConversion(Ref);
16741           if (!RefRes.isUsable())
16742             continue;
16743           ExprResult PostUpdateRes =
16744               S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
16745                            RefRes.get());
16746           if (!PostUpdateRes.isUsable())
16747             continue;
16748           if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
16749               Stack->getCurrentDirective() == OMPD_taskgroup) {
16750             S.Diag(RefExpr->getExprLoc(),
16751                    diag::err_omp_reduction_non_addressable_expression)
16752                 << RefExpr->getSourceRange();
16753             continue;
16754           }
16755           RD.ExprPostUpdates.emplace_back(
16756               S.IgnoredValueConversions(PostUpdateRes.get()).get());
16757         }
16758       }
16759     }
16760     // All reduction items are still marked as reduction (to do not increase
16761     // code base size).
16762     unsigned Modifier = RD.RedModifier;
16763     // Consider task_reductions as reductions with task modifier. Required for
16764     // correct analysis of in_reduction clauses.
16765     if (CurrDir == OMPD_taskgroup && ClauseKind == OMPC_task_reduction)
16766       Modifier = OMPC_REDUCTION_task;
16767     Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref, Modifier,
16768                   ASE || OASE);
16769     if (Modifier == OMPC_REDUCTION_task &&
16770         (CurrDir == OMPD_taskgroup ||
16771          ((isOpenMPParallelDirective(CurrDir) ||
16772            isOpenMPWorksharingDirective(CurrDir)) &&
16773           !isOpenMPSimdDirective(CurrDir)))) {
16774       if (DeclareReductionRef.isUsable())
16775         Stack->addTaskgroupReductionData(D, ReductionIdRange,
16776                                          DeclareReductionRef.get());
16777       else
16778         Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK);
16779     }
16780     RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(),
16781             TaskgroupDescriptor, CopyOpRes.get(), TempArrayRes.get(),
16782             TempArrayElem.get());
16783   }
16784   return RD.Vars.empty();
16785 }
16786 
16787 OMPClause *Sema::ActOnOpenMPReductionClause(
16788     ArrayRef<Expr *> VarList, OpenMPReductionClauseModifier Modifier,
16789     SourceLocation StartLoc, SourceLocation LParenLoc,
16790     SourceLocation ModifierLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
16791     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
16792     ArrayRef<Expr *> UnresolvedReductions) {
16793   if (ModifierLoc.isValid() && Modifier == OMPC_REDUCTION_unknown) {
16794     Diag(LParenLoc, diag::err_omp_unexpected_clause_value)
16795         << getListOfPossibleValues(OMPC_reduction, /*First=*/0,
16796                                    /*Last=*/OMPC_REDUCTION_unknown)
16797         << getOpenMPClauseName(OMPC_reduction);
16798     return nullptr;
16799   }
16800   // OpenMP 5.0, 2.19.5.4 reduction Clause, Restrictions
16801   // A reduction clause with the inscan reduction-modifier may only appear on a
16802   // worksharing-loop construct, a worksharing-loop SIMD construct, a simd
16803   // construct, a parallel worksharing-loop construct or a parallel
16804   // worksharing-loop SIMD construct.
16805   if (Modifier == OMPC_REDUCTION_inscan &&
16806       (DSAStack->getCurrentDirective() != OMPD_for &&
16807        DSAStack->getCurrentDirective() != OMPD_for_simd &&
16808        DSAStack->getCurrentDirective() != OMPD_simd &&
16809        DSAStack->getCurrentDirective() != OMPD_parallel_for &&
16810        DSAStack->getCurrentDirective() != OMPD_parallel_for_simd)) {
16811     Diag(ModifierLoc, diag::err_omp_wrong_inscan_reduction);
16812     return nullptr;
16813   }
16814 
16815   ReductionData RD(VarList.size(), Modifier);
16816   if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList,
16817                                   StartLoc, LParenLoc, ColonLoc, EndLoc,
16818                                   ReductionIdScopeSpec, ReductionId,
16819                                   UnresolvedReductions, RD))
16820     return nullptr;
16821 
16822   return OMPReductionClause::Create(
16823       Context, StartLoc, LParenLoc, ModifierLoc, ColonLoc, EndLoc, Modifier,
16824       RD.Vars, ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
16825       RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.InscanCopyOps,
16826       RD.InscanCopyArrayTemps, RD.InscanCopyArrayElems,
16827       buildPreInits(Context, RD.ExprCaptures),
16828       buildPostUpdate(*this, RD.ExprPostUpdates));
16829 }
16830 
16831 OMPClause *Sema::ActOnOpenMPTaskReductionClause(
16832     ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
16833     SourceLocation ColonLoc, SourceLocation EndLoc,
16834     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
16835     ArrayRef<Expr *> UnresolvedReductions) {
16836   ReductionData RD(VarList.size());
16837   if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction, VarList,
16838                                   StartLoc, LParenLoc, ColonLoc, EndLoc,
16839                                   ReductionIdScopeSpec, ReductionId,
16840                                   UnresolvedReductions, RD))
16841     return nullptr;
16842 
16843   return OMPTaskReductionClause::Create(
16844       Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
16845       ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
16846       RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
16847       buildPreInits(Context, RD.ExprCaptures),
16848       buildPostUpdate(*this, RD.ExprPostUpdates));
16849 }
16850 
16851 OMPClause *Sema::ActOnOpenMPInReductionClause(
16852     ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
16853     SourceLocation ColonLoc, SourceLocation EndLoc,
16854     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
16855     ArrayRef<Expr *> UnresolvedReductions) {
16856   ReductionData RD(VarList.size());
16857   if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList,
16858                                   StartLoc, LParenLoc, ColonLoc, EndLoc,
16859                                   ReductionIdScopeSpec, ReductionId,
16860                                   UnresolvedReductions, RD))
16861     return nullptr;
16862 
16863   return OMPInReductionClause::Create(
16864       Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
16865       ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
16866       RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors,
16867       buildPreInits(Context, RD.ExprCaptures),
16868       buildPostUpdate(*this, RD.ExprPostUpdates));
16869 }
16870 
16871 bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
16872                                      SourceLocation LinLoc) {
16873   if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
16874       LinKind == OMPC_LINEAR_unknown) {
16875     Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
16876     return true;
16877   }
16878   return false;
16879 }
16880 
16881 bool Sema::CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc,
16882                                  OpenMPLinearClauseKind LinKind, QualType Type,
16883                                  bool IsDeclareSimd) {
16884   const auto *VD = dyn_cast_or_null<VarDecl>(D);
16885   // A variable must not have an incomplete type or a reference type.
16886   if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
16887     return true;
16888   if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
16889       !Type->isReferenceType()) {
16890     Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
16891         << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
16892     return true;
16893   }
16894   Type = Type.getNonReferenceType();
16895 
16896   // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
16897   // A variable that is privatized must not have a const-qualified type
16898   // unless it is of class type with a mutable member. This restriction does
16899   // not apply to the firstprivate clause, nor to the linear clause on
16900   // declarative directives (like declare simd).
16901   if (!IsDeclareSimd &&
16902       rejectConstNotMutableType(*this, D, Type, OMPC_linear, ELoc))
16903     return true;
16904 
16905   // A list item must be of integral or pointer type.
16906   Type = Type.getUnqualifiedType().getCanonicalType();
16907   const auto *Ty = Type.getTypePtrOrNull();
16908   if (!Ty || (LinKind != OMPC_LINEAR_ref && !Ty->isDependentType() &&
16909               !Ty->isIntegralType(Context) && !Ty->isPointerType())) {
16910     Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
16911     if (D) {
16912       bool IsDecl =
16913           !VD ||
16914           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
16915       Diag(D->getLocation(),
16916            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
16917           << D;
16918     }
16919     return true;
16920   }
16921   return false;
16922 }
16923 
16924 OMPClause *Sema::ActOnOpenMPLinearClause(
16925     ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
16926     SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
16927     SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
16928   SmallVector<Expr *, 8> Vars;
16929   SmallVector<Expr *, 8> Privates;
16930   SmallVector<Expr *, 8> Inits;
16931   SmallVector<Decl *, 4> ExprCaptures;
16932   SmallVector<Expr *, 4> ExprPostUpdates;
16933   if (CheckOpenMPLinearModifier(LinKind, LinLoc))
16934     LinKind = OMPC_LINEAR_val;
16935   for (Expr *RefExpr : VarList) {
16936     assert(RefExpr && "NULL expr in OpenMP linear clause.");
16937     SourceLocation ELoc;
16938     SourceRange ERange;
16939     Expr *SimpleRefExpr = RefExpr;
16940     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
16941     if (Res.second) {
16942       // It will be analyzed later.
16943       Vars.push_back(RefExpr);
16944       Privates.push_back(nullptr);
16945       Inits.push_back(nullptr);
16946     }
16947     ValueDecl *D = Res.first;
16948     if (!D)
16949       continue;
16950 
16951     QualType Type = D->getType();
16952     auto *VD = dyn_cast<VarDecl>(D);
16953 
16954     // OpenMP [2.14.3.7, linear clause]
16955     //  A list-item cannot appear in more than one linear clause.
16956     //  A list-item that appears in a linear clause cannot appear in any
16957     //  other data-sharing attribute clause.
16958     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
16959     if (DVar.RefExpr) {
16960       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
16961                                           << getOpenMPClauseName(OMPC_linear);
16962       reportOriginalDsa(*this, DSAStack, D, DVar);
16963       continue;
16964     }
16965 
16966     if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
16967       continue;
16968     Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
16969 
16970     // Build private copy of original var.
16971     VarDecl *Private =
16972         buildVarDecl(*this, ELoc, Type, D->getName(),
16973                      D->hasAttrs() ? &D->getAttrs() : nullptr,
16974                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
16975     DeclRefExpr *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
16976     // Build var to save initial value.
16977     VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
16978     Expr *InitExpr;
16979     DeclRefExpr *Ref = nullptr;
16980     if (!VD && !CurContext->isDependentContext()) {
16981       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
16982       if (!isOpenMPCapturedDecl(D)) {
16983         ExprCaptures.push_back(Ref->getDecl());
16984         if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
16985           ExprResult RefRes = DefaultLvalueConversion(Ref);
16986           if (!RefRes.isUsable())
16987             continue;
16988           ExprResult PostUpdateRes =
16989               BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
16990                          SimpleRefExpr, RefRes.get());
16991           if (!PostUpdateRes.isUsable())
16992             continue;
16993           ExprPostUpdates.push_back(
16994               IgnoredValueConversions(PostUpdateRes.get()).get());
16995         }
16996       }
16997     }
16998     if (LinKind == OMPC_LINEAR_uval)
16999       InitExpr = VD ? VD->getInit() : SimpleRefExpr;
17000     else
17001       InitExpr = VD ? SimpleRefExpr : Ref;
17002     AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
17003                          /*DirectInit=*/false);
17004     DeclRefExpr *InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
17005 
17006     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
17007     Vars.push_back((VD || CurContext->isDependentContext())
17008                        ? RefExpr->IgnoreParens()
17009                        : Ref);
17010     Privates.push_back(PrivateRef);
17011     Inits.push_back(InitRef);
17012   }
17013 
17014   if (Vars.empty())
17015     return nullptr;
17016 
17017   Expr *StepExpr = Step;
17018   Expr *CalcStepExpr = nullptr;
17019   if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
17020       !Step->isInstantiationDependent() &&
17021       !Step->containsUnexpandedParameterPack()) {
17022     SourceLocation StepLoc = Step->getBeginLoc();
17023     ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
17024     if (Val.isInvalid())
17025       return nullptr;
17026     StepExpr = Val.get();
17027 
17028     // Build var to save the step value.
17029     VarDecl *SaveVar =
17030         buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
17031     ExprResult SaveRef =
17032         buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
17033     ExprResult CalcStep =
17034         BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
17035     CalcStep = ActOnFinishFullExpr(CalcStep.get(), /*DiscardedValue*/ false);
17036 
17037     // Warn about zero linear step (it would be probably better specified as
17038     // making corresponding variables 'const').
17039     if (Optional<llvm::APSInt> Result =
17040             StepExpr->getIntegerConstantExpr(Context)) {
17041       if (!Result->isNegative() && !Result->isStrictlyPositive())
17042         Diag(StepLoc, diag::warn_omp_linear_step_zero)
17043             << Vars[0] << (Vars.size() > 1);
17044     } else if (CalcStep.isUsable()) {
17045       // Calculate the step beforehand instead of doing this on each iteration.
17046       // (This is not used if the number of iterations may be kfold-ed).
17047       CalcStepExpr = CalcStep.get();
17048     }
17049   }
17050 
17051   return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
17052                                  ColonLoc, EndLoc, Vars, Privates, Inits,
17053                                  StepExpr, CalcStepExpr,
17054                                  buildPreInits(Context, ExprCaptures),
17055                                  buildPostUpdate(*this, ExprPostUpdates));
17056 }
17057 
17058 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
17059                                      Expr *NumIterations, Sema &SemaRef,
17060                                      Scope *S, DSAStackTy *Stack) {
17061   // Walk the vars and build update/final expressions for the CodeGen.
17062   SmallVector<Expr *, 8> Updates;
17063   SmallVector<Expr *, 8> Finals;
17064   SmallVector<Expr *, 8> UsedExprs;
17065   Expr *Step = Clause.getStep();
17066   Expr *CalcStep = Clause.getCalcStep();
17067   // OpenMP [2.14.3.7, linear clause]
17068   // If linear-step is not specified it is assumed to be 1.
17069   if (!Step)
17070     Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
17071   else if (CalcStep)
17072     Step = cast<BinaryOperator>(CalcStep)->getLHS();
17073   bool HasErrors = false;
17074   auto CurInit = Clause.inits().begin();
17075   auto CurPrivate = Clause.privates().begin();
17076   OpenMPLinearClauseKind LinKind = Clause.getModifier();
17077   for (Expr *RefExpr : Clause.varlists()) {
17078     SourceLocation ELoc;
17079     SourceRange ERange;
17080     Expr *SimpleRefExpr = RefExpr;
17081     auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange);
17082     ValueDecl *D = Res.first;
17083     if (Res.second || !D) {
17084       Updates.push_back(nullptr);
17085       Finals.push_back(nullptr);
17086       HasErrors = true;
17087       continue;
17088     }
17089     auto &&Info = Stack->isLoopControlVariable(D);
17090     // OpenMP [2.15.11, distribute simd Construct]
17091     // A list item may not appear in a linear clause, unless it is the loop
17092     // iteration variable.
17093     if (isOpenMPDistributeDirective(Stack->getCurrentDirective()) &&
17094         isOpenMPSimdDirective(Stack->getCurrentDirective()) && !Info.first) {
17095       SemaRef.Diag(ELoc,
17096                    diag::err_omp_linear_distribute_var_non_loop_iteration);
17097       Updates.push_back(nullptr);
17098       Finals.push_back(nullptr);
17099       HasErrors = true;
17100       continue;
17101     }
17102     Expr *InitExpr = *CurInit;
17103 
17104     // Build privatized reference to the current linear var.
17105     auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
17106     Expr *CapturedRef;
17107     if (LinKind == OMPC_LINEAR_uval)
17108       CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
17109     else
17110       CapturedRef =
17111           buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
17112                            DE->getType().getUnqualifiedType(), DE->getExprLoc(),
17113                            /*RefersToCapture=*/true);
17114 
17115     // Build update: Var = InitExpr + IV * Step
17116     ExprResult Update;
17117     if (!Info.first)
17118       Update = buildCounterUpdate(
17119           SemaRef, S, RefExpr->getExprLoc(), *CurPrivate, InitExpr, IV, Step,
17120           /*Subtract=*/false, /*IsNonRectangularLB=*/false);
17121     else
17122       Update = *CurPrivate;
17123     Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getBeginLoc(),
17124                                          /*DiscardedValue*/ false);
17125 
17126     // Build final: Var = InitExpr + NumIterations * Step
17127     ExprResult Final;
17128     if (!Info.first)
17129       Final =
17130           buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
17131                              InitExpr, NumIterations, Step, /*Subtract=*/false,
17132                              /*IsNonRectangularLB=*/false);
17133     else
17134       Final = *CurPrivate;
17135     Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getBeginLoc(),
17136                                         /*DiscardedValue*/ false);
17137 
17138     if (!Update.isUsable() || !Final.isUsable()) {
17139       Updates.push_back(nullptr);
17140       Finals.push_back(nullptr);
17141       UsedExprs.push_back(nullptr);
17142       HasErrors = true;
17143     } else {
17144       Updates.push_back(Update.get());
17145       Finals.push_back(Final.get());
17146       if (!Info.first)
17147         UsedExprs.push_back(SimpleRefExpr);
17148     }
17149     ++CurInit;
17150     ++CurPrivate;
17151   }
17152   if (Expr *S = Clause.getStep())
17153     UsedExprs.push_back(S);
17154   // Fill the remaining part with the nullptr.
17155   UsedExprs.append(Clause.varlist_size() + 1 - UsedExprs.size(), nullptr);
17156   Clause.setUpdates(Updates);
17157   Clause.setFinals(Finals);
17158   Clause.setUsedExprs(UsedExprs);
17159   return HasErrors;
17160 }
17161 
17162 OMPClause *Sema::ActOnOpenMPAlignedClause(
17163     ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
17164     SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
17165   SmallVector<Expr *, 8> Vars;
17166   for (Expr *RefExpr : VarList) {
17167     assert(RefExpr && "NULL expr in OpenMP linear clause.");
17168     SourceLocation ELoc;
17169     SourceRange ERange;
17170     Expr *SimpleRefExpr = RefExpr;
17171     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
17172     if (Res.second) {
17173       // It will be analyzed later.
17174       Vars.push_back(RefExpr);
17175     }
17176     ValueDecl *D = Res.first;
17177     if (!D)
17178       continue;
17179 
17180     QualType QType = D->getType();
17181     auto *VD = dyn_cast<VarDecl>(D);
17182 
17183     // OpenMP  [2.8.1, simd construct, Restrictions]
17184     // The type of list items appearing in the aligned clause must be
17185     // array, pointer, reference to array, or reference to pointer.
17186     QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
17187     const Type *Ty = QType.getTypePtrOrNull();
17188     if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
17189       Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
17190           << QType << getLangOpts().CPlusPlus << ERange;
17191       bool IsDecl =
17192           !VD ||
17193           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
17194       Diag(D->getLocation(),
17195            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
17196           << D;
17197       continue;
17198     }
17199 
17200     // OpenMP  [2.8.1, simd construct, Restrictions]
17201     // A list-item cannot appear in more than one aligned clause.
17202     if (const Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
17203       Diag(ELoc, diag::err_omp_used_in_clause_twice)
17204           << 0 << getOpenMPClauseName(OMPC_aligned) << ERange;
17205       Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
17206           << getOpenMPClauseName(OMPC_aligned);
17207       continue;
17208     }
17209 
17210     DeclRefExpr *Ref = nullptr;
17211     if (!VD && isOpenMPCapturedDecl(D))
17212       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
17213     Vars.push_back(DefaultFunctionArrayConversion(
17214                        (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
17215                        .get());
17216   }
17217 
17218   // OpenMP [2.8.1, simd construct, Description]
17219   // The parameter of the aligned clause, alignment, must be a constant
17220   // positive integer expression.
17221   // If no optional parameter is specified, implementation-defined default
17222   // alignments for SIMD instructions on the target platforms are assumed.
17223   if (Alignment != nullptr) {
17224     ExprResult AlignResult =
17225         VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
17226     if (AlignResult.isInvalid())
17227       return nullptr;
17228     Alignment = AlignResult.get();
17229   }
17230   if (Vars.empty())
17231     return nullptr;
17232 
17233   return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
17234                                   EndLoc, Vars, Alignment);
17235 }
17236 
17237 OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
17238                                          SourceLocation StartLoc,
17239                                          SourceLocation LParenLoc,
17240                                          SourceLocation EndLoc) {
17241   SmallVector<Expr *, 8> Vars;
17242   SmallVector<Expr *, 8> SrcExprs;
17243   SmallVector<Expr *, 8> DstExprs;
17244   SmallVector<Expr *, 8> AssignmentOps;
17245   for (Expr *RefExpr : VarList) {
17246     assert(RefExpr && "NULL expr in OpenMP copyin clause.");
17247     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
17248       // It will be analyzed later.
17249       Vars.push_back(RefExpr);
17250       SrcExprs.push_back(nullptr);
17251       DstExprs.push_back(nullptr);
17252       AssignmentOps.push_back(nullptr);
17253       continue;
17254     }
17255 
17256     SourceLocation ELoc = RefExpr->getExprLoc();
17257     // OpenMP [2.1, C/C++]
17258     //  A list item is a variable name.
17259     // OpenMP  [2.14.4.1, Restrictions, p.1]
17260     //  A list item that appears in a copyin clause must be threadprivate.
17261     auto *DE = dyn_cast<DeclRefExpr>(RefExpr);
17262     if (!DE || !isa<VarDecl>(DE->getDecl())) {
17263       Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
17264           << 0 << RefExpr->getSourceRange();
17265       continue;
17266     }
17267 
17268     Decl *D = DE->getDecl();
17269     auto *VD = cast<VarDecl>(D);
17270 
17271     QualType Type = VD->getType();
17272     if (Type->isDependentType() || Type->isInstantiationDependentType()) {
17273       // It will be analyzed later.
17274       Vars.push_back(DE);
17275       SrcExprs.push_back(nullptr);
17276       DstExprs.push_back(nullptr);
17277       AssignmentOps.push_back(nullptr);
17278       continue;
17279     }
17280 
17281     // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
17282     //  A list item that appears in a copyin clause must be threadprivate.
17283     if (!DSAStack->isThreadPrivate(VD)) {
17284       Diag(ELoc, diag::err_omp_required_access)
17285           << getOpenMPClauseName(OMPC_copyin)
17286           << getOpenMPDirectiveName(OMPD_threadprivate);
17287       continue;
17288     }
17289 
17290     // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
17291     //  A variable of class type (or array thereof) that appears in a
17292     //  copyin clause requires an accessible, unambiguous copy assignment
17293     //  operator for the class type.
17294     QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
17295     VarDecl *SrcVD =
17296         buildVarDecl(*this, DE->getBeginLoc(), ElemType.getUnqualifiedType(),
17297                      ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
17298     DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(
17299         *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
17300     VarDecl *DstVD =
17301         buildVarDecl(*this, DE->getBeginLoc(), ElemType, ".copyin.dst",
17302                      VD->hasAttrs() ? &VD->getAttrs() : nullptr);
17303     DeclRefExpr *PseudoDstExpr =
17304         buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
17305     // For arrays generate assignment operation for single element and replace
17306     // it by the original array element in CodeGen.
17307     ExprResult AssignmentOp =
17308         BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign, PseudoDstExpr,
17309                    PseudoSrcExpr);
17310     if (AssignmentOp.isInvalid())
17311       continue;
17312     AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
17313                                        /*DiscardedValue*/ false);
17314     if (AssignmentOp.isInvalid())
17315       continue;
17316 
17317     DSAStack->addDSA(VD, DE, OMPC_copyin);
17318     Vars.push_back(DE);
17319     SrcExprs.push_back(PseudoSrcExpr);
17320     DstExprs.push_back(PseudoDstExpr);
17321     AssignmentOps.push_back(AssignmentOp.get());
17322   }
17323 
17324   if (Vars.empty())
17325     return nullptr;
17326 
17327   return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
17328                                  SrcExprs, DstExprs, AssignmentOps);
17329 }
17330 
17331 OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
17332                                               SourceLocation StartLoc,
17333                                               SourceLocation LParenLoc,
17334                                               SourceLocation EndLoc) {
17335   SmallVector<Expr *, 8> Vars;
17336   SmallVector<Expr *, 8> SrcExprs;
17337   SmallVector<Expr *, 8> DstExprs;
17338   SmallVector<Expr *, 8> AssignmentOps;
17339   for (Expr *RefExpr : VarList) {
17340     assert(RefExpr && "NULL expr in OpenMP linear clause.");
17341     SourceLocation ELoc;
17342     SourceRange ERange;
17343     Expr *SimpleRefExpr = RefExpr;
17344     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
17345     if (Res.second) {
17346       // It will be analyzed later.
17347       Vars.push_back(RefExpr);
17348       SrcExprs.push_back(nullptr);
17349       DstExprs.push_back(nullptr);
17350       AssignmentOps.push_back(nullptr);
17351     }
17352     ValueDecl *D = Res.first;
17353     if (!D)
17354       continue;
17355 
17356     QualType Type = D->getType();
17357     auto *VD = dyn_cast<VarDecl>(D);
17358 
17359     // OpenMP [2.14.4.2, Restrictions, p.2]
17360     //  A list item that appears in a copyprivate clause may not appear in a
17361     //  private or firstprivate clause on the single construct.
17362     if (!VD || !DSAStack->isThreadPrivate(VD)) {
17363       DSAStackTy::DSAVarData DVar =
17364           DSAStack->getTopDSA(D, /*FromParent=*/false);
17365       if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
17366           DVar.RefExpr) {
17367         Diag(ELoc, diag::err_omp_wrong_dsa)
17368             << getOpenMPClauseName(DVar.CKind)
17369             << getOpenMPClauseName(OMPC_copyprivate);
17370         reportOriginalDsa(*this, DSAStack, D, DVar);
17371         continue;
17372       }
17373 
17374       // OpenMP [2.11.4.2, Restrictions, p.1]
17375       //  All list items that appear in a copyprivate clause must be either
17376       //  threadprivate or private in the enclosing context.
17377       if (DVar.CKind == OMPC_unknown) {
17378         DVar = DSAStack->getImplicitDSA(D, false);
17379         if (DVar.CKind == OMPC_shared) {
17380           Diag(ELoc, diag::err_omp_required_access)
17381               << getOpenMPClauseName(OMPC_copyprivate)
17382               << "threadprivate or private in the enclosing context";
17383           reportOriginalDsa(*this, DSAStack, D, DVar);
17384           continue;
17385         }
17386       }
17387     }
17388 
17389     // Variably modified types are not supported.
17390     if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
17391       Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
17392           << getOpenMPClauseName(OMPC_copyprivate) << Type
17393           << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
17394       bool IsDecl =
17395           !VD ||
17396           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
17397       Diag(D->getLocation(),
17398            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
17399           << D;
17400       continue;
17401     }
17402 
17403     // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
17404     //  A variable of class type (or array thereof) that appears in a
17405     //  copyin clause requires an accessible, unambiguous copy assignment
17406     //  operator for the class type.
17407     Type = Context.getBaseElementType(Type.getNonReferenceType())
17408                .getUnqualifiedType();
17409     VarDecl *SrcVD =
17410         buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.src",
17411                      D->hasAttrs() ? &D->getAttrs() : nullptr);
17412     DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
17413     VarDecl *DstVD =
17414         buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.dst",
17415                      D->hasAttrs() ? &D->getAttrs() : nullptr);
17416     DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
17417     ExprResult AssignmentOp = BuildBinOp(
17418         DSAStack->getCurScope(), ELoc, BO_Assign, PseudoDstExpr, PseudoSrcExpr);
17419     if (AssignmentOp.isInvalid())
17420       continue;
17421     AssignmentOp =
17422         ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
17423     if (AssignmentOp.isInvalid())
17424       continue;
17425 
17426     // No need to mark vars as copyprivate, they are already threadprivate or
17427     // implicitly private.
17428     assert(VD || isOpenMPCapturedDecl(D));
17429     Vars.push_back(
17430         VD ? RefExpr->IgnoreParens()
17431            : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
17432     SrcExprs.push_back(PseudoSrcExpr);
17433     DstExprs.push_back(PseudoDstExpr);
17434     AssignmentOps.push_back(AssignmentOp.get());
17435   }
17436 
17437   if (Vars.empty())
17438     return nullptr;
17439 
17440   return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
17441                                       Vars, SrcExprs, DstExprs, AssignmentOps);
17442 }
17443 
17444 OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
17445                                         SourceLocation StartLoc,
17446                                         SourceLocation LParenLoc,
17447                                         SourceLocation EndLoc) {
17448   if (VarList.empty())
17449     return nullptr;
17450 
17451   return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
17452 }
17453 
17454 /// Tries to find omp_depend_t. type.
17455 static bool findOMPDependT(Sema &S, SourceLocation Loc, DSAStackTy *Stack,
17456                            bool Diagnose = true) {
17457   QualType OMPDependT = Stack->getOMPDependT();
17458   if (!OMPDependT.isNull())
17459     return true;
17460   IdentifierInfo *II = &S.PP.getIdentifierTable().get("omp_depend_t");
17461   ParsedType PT = S.getTypeName(*II, Loc, S.getCurScope());
17462   if (!PT.getAsOpaquePtr() || PT.get().isNull()) {
17463     if (Diagnose)
17464       S.Diag(Loc, diag::err_omp_implied_type_not_found) << "omp_depend_t";
17465     return false;
17466   }
17467   Stack->setOMPDependT(PT.get());
17468   return true;
17469 }
17470 
17471 OMPClause *Sema::ActOnOpenMPDepobjClause(Expr *Depobj, SourceLocation StartLoc,
17472                                          SourceLocation LParenLoc,
17473                                          SourceLocation EndLoc) {
17474   if (!Depobj)
17475     return nullptr;
17476 
17477   bool OMPDependTFound = findOMPDependT(*this, StartLoc, DSAStack);
17478 
17479   // OpenMP 5.0, 2.17.10.1 depobj Construct
17480   // depobj is an lvalue expression of type omp_depend_t.
17481   if (!Depobj->isTypeDependent() && !Depobj->isValueDependent() &&
17482       !Depobj->isInstantiationDependent() &&
17483       !Depobj->containsUnexpandedParameterPack() &&
17484       (OMPDependTFound &&
17485        !Context.typesAreCompatible(DSAStack->getOMPDependT(), Depobj->getType(),
17486                                    /*CompareUnqualified=*/true))) {
17487     Diag(Depobj->getExprLoc(), diag::err_omp_expected_omp_depend_t_lvalue)
17488         << 0 << Depobj->getType() << Depobj->getSourceRange();
17489   }
17490 
17491   if (!Depobj->isLValue()) {
17492     Diag(Depobj->getExprLoc(), diag::err_omp_expected_omp_depend_t_lvalue)
17493         << 1 << Depobj->getSourceRange();
17494   }
17495 
17496   return OMPDepobjClause::Create(Context, StartLoc, LParenLoc, EndLoc, Depobj);
17497 }
17498 
17499 OMPClause *
17500 Sema::ActOnOpenMPDependClause(Expr *DepModifier, OpenMPDependClauseKind DepKind,
17501                               SourceLocation DepLoc, SourceLocation ColonLoc,
17502                               ArrayRef<Expr *> VarList, SourceLocation StartLoc,
17503                               SourceLocation LParenLoc, SourceLocation EndLoc) {
17504   if (DSAStack->getCurrentDirective() == OMPD_ordered &&
17505       DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
17506     Diag(DepLoc, diag::err_omp_unexpected_clause_value)
17507         << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
17508     return nullptr;
17509   }
17510   if ((DSAStack->getCurrentDirective() != OMPD_ordered ||
17511        DSAStack->getCurrentDirective() == OMPD_depobj) &&
17512       (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
17513        DepKind == OMPC_DEPEND_sink ||
17514        ((LangOpts.OpenMP < 50 ||
17515          DSAStack->getCurrentDirective() == OMPD_depobj) &&
17516         DepKind == OMPC_DEPEND_depobj))) {
17517     SmallVector<unsigned, 3> Except;
17518     Except.push_back(OMPC_DEPEND_source);
17519     Except.push_back(OMPC_DEPEND_sink);
17520     if (LangOpts.OpenMP < 50 || DSAStack->getCurrentDirective() == OMPD_depobj)
17521       Except.push_back(OMPC_DEPEND_depobj);
17522     std::string Expected = (LangOpts.OpenMP >= 50 && !DepModifier)
17523                                ? "depend modifier(iterator) or "
17524                                : "";
17525     Diag(DepLoc, diag::err_omp_unexpected_clause_value)
17526         << Expected + getListOfPossibleValues(OMPC_depend, /*First=*/0,
17527                                               /*Last=*/OMPC_DEPEND_unknown,
17528                                               Except)
17529         << getOpenMPClauseName(OMPC_depend);
17530     return nullptr;
17531   }
17532   if (DepModifier &&
17533       (DepKind == OMPC_DEPEND_source || DepKind == OMPC_DEPEND_sink)) {
17534     Diag(DepModifier->getExprLoc(),
17535          diag::err_omp_depend_sink_source_with_modifier);
17536     return nullptr;
17537   }
17538   if (DepModifier &&
17539       !DepModifier->getType()->isSpecificBuiltinType(BuiltinType::OMPIterator))
17540     Diag(DepModifier->getExprLoc(), diag::err_omp_depend_modifier_not_iterator);
17541 
17542   SmallVector<Expr *, 8> Vars;
17543   DSAStackTy::OperatorOffsetTy OpsOffs;
17544   llvm::APSInt DepCounter(/*BitWidth=*/32);
17545   llvm::APSInt TotalDepCount(/*BitWidth=*/32);
17546   if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) {
17547     if (const Expr *OrderedCountExpr =
17548             DSAStack->getParentOrderedRegionParam().first) {
17549       TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
17550       TotalDepCount.setIsUnsigned(/*Val=*/true);
17551     }
17552   }
17553   for (Expr *RefExpr : VarList) {
17554     assert(RefExpr && "NULL expr in OpenMP shared clause.");
17555     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
17556       // It will be analyzed later.
17557       Vars.push_back(RefExpr);
17558       continue;
17559     }
17560 
17561     SourceLocation ELoc = RefExpr->getExprLoc();
17562     Expr *SimpleExpr = RefExpr->IgnoreParenCasts();
17563     if (DepKind == OMPC_DEPEND_sink) {
17564       if (DSAStack->getParentOrderedRegionParam().first &&
17565           DepCounter >= TotalDepCount) {
17566         Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
17567         continue;
17568       }
17569       ++DepCounter;
17570       // OpenMP  [2.13.9, Summary]
17571       // depend(dependence-type : vec), where dependence-type is:
17572       // 'sink' and where vec is the iteration vector, which has the form:
17573       //  x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
17574       // where n is the value specified by the ordered clause in the loop
17575       // directive, xi denotes the loop iteration variable of the i-th nested
17576       // loop associated with the loop directive, and di is a constant
17577       // non-negative integer.
17578       if (CurContext->isDependentContext()) {
17579         // It will be analyzed later.
17580         Vars.push_back(RefExpr);
17581         continue;
17582       }
17583       SimpleExpr = SimpleExpr->IgnoreImplicit();
17584       OverloadedOperatorKind OOK = OO_None;
17585       SourceLocation OOLoc;
17586       Expr *LHS = SimpleExpr;
17587       Expr *RHS = nullptr;
17588       if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
17589         OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
17590         OOLoc = BO->getOperatorLoc();
17591         LHS = BO->getLHS()->IgnoreParenImpCasts();
17592         RHS = BO->getRHS()->IgnoreParenImpCasts();
17593       } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
17594         OOK = OCE->getOperator();
17595         OOLoc = OCE->getOperatorLoc();
17596         LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
17597         RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
17598       } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
17599         OOK = MCE->getMethodDecl()
17600                   ->getNameInfo()
17601                   .getName()
17602                   .getCXXOverloadedOperator();
17603         OOLoc = MCE->getCallee()->getExprLoc();
17604         LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
17605         RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
17606       }
17607       SourceLocation ELoc;
17608       SourceRange ERange;
17609       auto Res = getPrivateItem(*this, LHS, ELoc, ERange);
17610       if (Res.second) {
17611         // It will be analyzed later.
17612         Vars.push_back(RefExpr);
17613       }
17614       ValueDecl *D = Res.first;
17615       if (!D)
17616         continue;
17617 
17618       if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
17619         Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
17620         continue;
17621       }
17622       if (RHS) {
17623         ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
17624             RHS, OMPC_depend, /*StrictlyPositive=*/false);
17625         if (RHSRes.isInvalid())
17626           continue;
17627       }
17628       if (!CurContext->isDependentContext() &&
17629           DSAStack->getParentOrderedRegionParam().first &&
17630           DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
17631         const ValueDecl *VD =
17632             DSAStack->getParentLoopControlVariable(DepCounter.getZExtValue());
17633         if (VD)
17634           Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
17635               << 1 << VD;
17636         else
17637           Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0;
17638         continue;
17639       }
17640       OpsOffs.emplace_back(RHS, OOK);
17641     } else {
17642       bool OMPDependTFound = LangOpts.OpenMP >= 50;
17643       if (OMPDependTFound)
17644         OMPDependTFound = findOMPDependT(*this, StartLoc, DSAStack,
17645                                          DepKind == OMPC_DEPEND_depobj);
17646       if (DepKind == OMPC_DEPEND_depobj) {
17647         // OpenMP 5.0, 2.17.11 depend Clause, Restrictions, C/C++
17648         // List items used in depend clauses with the depobj dependence type
17649         // must be expressions of the omp_depend_t type.
17650         if (!RefExpr->isValueDependent() && !RefExpr->isTypeDependent() &&
17651             !RefExpr->isInstantiationDependent() &&
17652             !RefExpr->containsUnexpandedParameterPack() &&
17653             (OMPDependTFound &&
17654              !Context.hasSameUnqualifiedType(DSAStack->getOMPDependT(),
17655                                              RefExpr->getType()))) {
17656           Diag(ELoc, diag::err_omp_expected_omp_depend_t_lvalue)
17657               << 0 << RefExpr->getType() << RefExpr->getSourceRange();
17658           continue;
17659         }
17660         if (!RefExpr->isLValue()) {
17661           Diag(ELoc, diag::err_omp_expected_omp_depend_t_lvalue)
17662               << 1 << RefExpr->getType() << RefExpr->getSourceRange();
17663           continue;
17664         }
17665       } else {
17666         // OpenMP 5.0 [2.17.11, Restrictions]
17667         // List items used in depend clauses cannot be zero-length array
17668         // sections.
17669         QualType ExprTy = RefExpr->getType().getNonReferenceType();
17670         const auto *OASE = dyn_cast<OMPArraySectionExpr>(SimpleExpr);
17671         if (OASE) {
17672           QualType BaseType =
17673               OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
17674           if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
17675             ExprTy = ATy->getElementType();
17676           else
17677             ExprTy = BaseType->getPointeeType();
17678           ExprTy = ExprTy.getNonReferenceType();
17679           const Expr *Length = OASE->getLength();
17680           Expr::EvalResult Result;
17681           if (Length && !Length->isValueDependent() &&
17682               Length->EvaluateAsInt(Result, Context) &&
17683               Result.Val.getInt().isNullValue()) {
17684             Diag(ELoc,
17685                  diag::err_omp_depend_zero_length_array_section_not_allowed)
17686                 << SimpleExpr->getSourceRange();
17687             continue;
17688           }
17689         }
17690 
17691         // OpenMP 5.0, 2.17.11 depend Clause, Restrictions, C/C++
17692         // List items used in depend clauses with the in, out, inout or
17693         // mutexinoutset dependence types cannot be expressions of the
17694         // omp_depend_t type.
17695         if (!RefExpr->isValueDependent() && !RefExpr->isTypeDependent() &&
17696             !RefExpr->isInstantiationDependent() &&
17697             !RefExpr->containsUnexpandedParameterPack() &&
17698             (OMPDependTFound &&
17699              DSAStack->getOMPDependT().getTypePtr() == ExprTy.getTypePtr())) {
17700           Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
17701               << (LangOpts.OpenMP >= 50 ? 1 : 0) << 1
17702               << RefExpr->getSourceRange();
17703           continue;
17704         }
17705 
17706         auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
17707         if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
17708             (ASE && !ASE->getBase()->isTypeDependent() &&
17709              !ASE->getBase()
17710                   ->getType()
17711                   .getNonReferenceType()
17712                   ->isPointerType() &&
17713              !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
17714           Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
17715               << (LangOpts.OpenMP >= 50 ? 1 : 0)
17716               << (LangOpts.OpenMP >= 50 ? 1 : 0) << RefExpr->getSourceRange();
17717           continue;
17718         }
17719 
17720         ExprResult Res;
17721         {
17722           Sema::TentativeAnalysisScope Trap(*this);
17723           Res = CreateBuiltinUnaryOp(ELoc, UO_AddrOf,
17724                                      RefExpr->IgnoreParenImpCasts());
17725         }
17726         if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr) &&
17727             !isa<OMPArrayShapingExpr>(SimpleExpr)) {
17728           Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
17729               << (LangOpts.OpenMP >= 50 ? 1 : 0)
17730               << (LangOpts.OpenMP >= 50 ? 1 : 0) << RefExpr->getSourceRange();
17731           continue;
17732         }
17733       }
17734     }
17735     Vars.push_back(RefExpr->IgnoreParenImpCasts());
17736   }
17737 
17738   if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
17739       TotalDepCount > VarList.size() &&
17740       DSAStack->getParentOrderedRegionParam().first &&
17741       DSAStack->getParentLoopControlVariable(VarList.size() + 1)) {
17742     Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
17743         << 1 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
17744   }
17745   if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
17746       Vars.empty())
17747     return nullptr;
17748 
17749   auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
17750                                     DepModifier, DepKind, DepLoc, ColonLoc,
17751                                     Vars, TotalDepCount.getZExtValue());
17752   if ((DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) &&
17753       DSAStack->isParentOrderedRegion())
17754     DSAStack->addDoacrossDependClause(C, OpsOffs);
17755   return C;
17756 }
17757 
17758 OMPClause *Sema::ActOnOpenMPDeviceClause(OpenMPDeviceClauseModifier Modifier,
17759                                          Expr *Device, SourceLocation StartLoc,
17760                                          SourceLocation LParenLoc,
17761                                          SourceLocation ModifierLoc,
17762                                          SourceLocation EndLoc) {
17763   assert((ModifierLoc.isInvalid() || LangOpts.OpenMP >= 50) &&
17764          "Unexpected device modifier in OpenMP < 50.");
17765 
17766   bool ErrorFound = false;
17767   if (ModifierLoc.isValid() && Modifier == OMPC_DEVICE_unknown) {
17768     std::string Values =
17769         getListOfPossibleValues(OMPC_device, /*First=*/0, OMPC_DEVICE_unknown);
17770     Diag(ModifierLoc, diag::err_omp_unexpected_clause_value)
17771         << Values << getOpenMPClauseName(OMPC_device);
17772     ErrorFound = true;
17773   }
17774 
17775   Expr *ValExpr = Device;
17776   Stmt *HelperValStmt = nullptr;
17777 
17778   // OpenMP [2.9.1, Restrictions]
17779   // The device expression must evaluate to a non-negative integer value.
17780   ErrorFound = !isNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
17781                                           /*StrictlyPositive=*/false) ||
17782                ErrorFound;
17783   if (ErrorFound)
17784     return nullptr;
17785 
17786   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
17787   OpenMPDirectiveKind CaptureRegion =
17788       getOpenMPCaptureRegionForClause(DKind, OMPC_device, LangOpts.OpenMP);
17789   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
17790     ValExpr = MakeFullExpr(ValExpr).get();
17791     llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
17792     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
17793     HelperValStmt = buildPreInits(Context, Captures);
17794   }
17795 
17796   return new (Context)
17797       OMPDeviceClause(Modifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
17798                       LParenLoc, ModifierLoc, EndLoc);
17799 }
17800 
17801 static bool checkTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
17802                               DSAStackTy *Stack, QualType QTy,
17803                               bool FullCheck = true) {
17804   NamedDecl *ND;
17805   if (QTy->isIncompleteType(&ND)) {
17806     SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
17807     return false;
17808   }
17809   if (FullCheck && !SemaRef.CurContext->isDependentContext() &&
17810       !QTy.isTriviallyCopyableType(SemaRef.Context))
17811     SemaRef.Diag(SL, diag::warn_omp_non_trivial_type_mapped) << QTy << SR;
17812   return true;
17813 }
17814 
17815 /// Return true if it can be proven that the provided array expression
17816 /// (array section or array subscript) does NOT specify the whole size of the
17817 /// array whose base type is \a BaseQTy.
17818 static bool checkArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
17819                                                         const Expr *E,
17820                                                         QualType BaseQTy) {
17821   const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
17822 
17823   // If this is an array subscript, it refers to the whole size if the size of
17824   // the dimension is constant and equals 1. Also, an array section assumes the
17825   // format of an array subscript if no colon is used.
17826   if (isa<ArraySubscriptExpr>(E) ||
17827       (OASE && OASE->getColonLocFirst().isInvalid())) {
17828     if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
17829       return ATy->getSize().getSExtValue() != 1;
17830     // Size can't be evaluated statically.
17831     return false;
17832   }
17833 
17834   assert(OASE && "Expecting array section if not an array subscript.");
17835   const Expr *LowerBound = OASE->getLowerBound();
17836   const Expr *Length = OASE->getLength();
17837 
17838   // If there is a lower bound that does not evaluates to zero, we are not
17839   // covering the whole dimension.
17840   if (LowerBound) {
17841     Expr::EvalResult Result;
17842     if (!LowerBound->EvaluateAsInt(Result, SemaRef.getASTContext()))
17843       return false; // Can't get the integer value as a constant.
17844 
17845     llvm::APSInt ConstLowerBound = Result.Val.getInt();
17846     if (ConstLowerBound.getSExtValue())
17847       return true;
17848   }
17849 
17850   // If we don't have a length we covering the whole dimension.
17851   if (!Length)
17852     return false;
17853 
17854   // If the base is a pointer, we don't have a way to get the size of the
17855   // pointee.
17856   if (BaseQTy->isPointerType())
17857     return false;
17858 
17859   // We can only check if the length is the same as the size of the dimension
17860   // if we have a constant array.
17861   const auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
17862   if (!CATy)
17863     return false;
17864 
17865   Expr::EvalResult Result;
17866   if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
17867     return false; // Can't get the integer value as a constant.
17868 
17869   llvm::APSInt ConstLength = Result.Val.getInt();
17870   return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
17871 }
17872 
17873 // Return true if it can be proven that the provided array expression (array
17874 // section or array subscript) does NOT specify a single element of the array
17875 // whose base type is \a BaseQTy.
17876 static bool checkArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
17877                                                         const Expr *E,
17878                                                         QualType BaseQTy) {
17879   const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
17880 
17881   // An array subscript always refer to a single element. Also, an array section
17882   // assumes the format of an array subscript if no colon is used.
17883   if (isa<ArraySubscriptExpr>(E) ||
17884       (OASE && OASE->getColonLocFirst().isInvalid()))
17885     return false;
17886 
17887   assert(OASE && "Expecting array section if not an array subscript.");
17888   const Expr *Length = OASE->getLength();
17889 
17890   // If we don't have a length we have to check if the array has unitary size
17891   // for this dimension. Also, we should always expect a length if the base type
17892   // is pointer.
17893   if (!Length) {
17894     if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
17895       return ATy->getSize().getSExtValue() != 1;
17896     // We cannot assume anything.
17897     return false;
17898   }
17899 
17900   // Check if the length evaluates to 1.
17901   Expr::EvalResult Result;
17902   if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
17903     return false; // Can't get the integer value as a constant.
17904 
17905   llvm::APSInt ConstLength = Result.Val.getInt();
17906   return ConstLength.getSExtValue() != 1;
17907 }
17908 
17909 // The base of elements of list in a map clause have to be either:
17910 //  - a reference to variable or field.
17911 //  - a member expression.
17912 //  - an array expression.
17913 //
17914 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
17915 // reference to 'r'.
17916 //
17917 // If we have:
17918 //
17919 // struct SS {
17920 //   Bla S;
17921 //   foo() {
17922 //     #pragma omp target map (S.Arr[:12]);
17923 //   }
17924 // }
17925 //
17926 // We want to retrieve the member expression 'this->S';
17927 
17928 // OpenMP 5.0 [2.19.7.1, map Clause, Restrictions, p.2]
17929 //  If a list item is an array section, it must specify contiguous storage.
17930 //
17931 // For this restriction it is sufficient that we make sure only references
17932 // to variables or fields and array expressions, and that no array sections
17933 // exist except in the rightmost expression (unless they cover the whole
17934 // dimension of the array). E.g. these would be invalid:
17935 //
17936 //   r.ArrS[3:5].Arr[6:7]
17937 //
17938 //   r.ArrS[3:5].x
17939 //
17940 // but these would be valid:
17941 //   r.ArrS[3].Arr[6:7]
17942 //
17943 //   r.ArrS[3].x
17944 namespace {
17945 class MapBaseChecker final : public StmtVisitor<MapBaseChecker, bool> {
17946   Sema &SemaRef;
17947   OpenMPClauseKind CKind = OMPC_unknown;
17948   OpenMPDirectiveKind DKind = OMPD_unknown;
17949   OMPClauseMappableExprCommon::MappableExprComponentList &Components;
17950   bool IsNonContiguous = false;
17951   bool NoDiagnose = false;
17952   const Expr *RelevantExpr = nullptr;
17953   bool AllowUnitySizeArraySection = true;
17954   bool AllowWholeSizeArraySection = true;
17955   bool AllowAnotherPtr = true;
17956   SourceLocation ELoc;
17957   SourceRange ERange;
17958 
17959   void emitErrorMsg() {
17960     // If nothing else worked, this is not a valid map clause expression.
17961     if (SemaRef.getLangOpts().OpenMP < 50) {
17962       SemaRef.Diag(ELoc,
17963                    diag::err_omp_expected_named_var_member_or_array_expression)
17964           << ERange;
17965     } else {
17966       SemaRef.Diag(ELoc, diag::err_omp_non_lvalue_in_map_or_motion_clauses)
17967           << getOpenMPClauseName(CKind) << ERange;
17968     }
17969   }
17970 
17971 public:
17972   bool VisitDeclRefExpr(DeclRefExpr *DRE) {
17973     if (!isa<VarDecl>(DRE->getDecl())) {
17974       emitErrorMsg();
17975       return false;
17976     }
17977     assert(!RelevantExpr && "RelevantExpr is expected to be nullptr");
17978     RelevantExpr = DRE;
17979     // Record the component.
17980     Components.emplace_back(DRE, DRE->getDecl(), IsNonContiguous);
17981     return true;
17982   }
17983 
17984   bool VisitMemberExpr(MemberExpr *ME) {
17985     Expr *E = ME;
17986     Expr *BaseE = ME->getBase()->IgnoreParenCasts();
17987 
17988     if (isa<CXXThisExpr>(BaseE)) {
17989       assert(!RelevantExpr && "RelevantExpr is expected to be nullptr");
17990       // We found a base expression: this->Val.
17991       RelevantExpr = ME;
17992     } else {
17993       E = BaseE;
17994     }
17995 
17996     if (!isa<FieldDecl>(ME->getMemberDecl())) {
17997       if (!NoDiagnose) {
17998         SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
17999           << ME->getSourceRange();
18000         return false;
18001       }
18002       if (RelevantExpr)
18003         return false;
18004       return Visit(E);
18005     }
18006 
18007     auto *FD = cast<FieldDecl>(ME->getMemberDecl());
18008 
18009     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
18010     //  A bit-field cannot appear in a map clause.
18011     //
18012     if (FD->isBitField()) {
18013       if (!NoDiagnose) {
18014         SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
18015           << ME->getSourceRange() << getOpenMPClauseName(CKind);
18016         return false;
18017       }
18018       if (RelevantExpr)
18019         return false;
18020       return Visit(E);
18021     }
18022 
18023     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
18024     //  If the type of a list item is a reference to a type T then the type
18025     //  will be considered to be T for all purposes of this clause.
18026     QualType CurType = BaseE->getType().getNonReferenceType();
18027 
18028     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
18029     //  A list item cannot be a variable that is a member of a structure with
18030     //  a union type.
18031     //
18032     if (CurType->isUnionType()) {
18033       if (!NoDiagnose) {
18034         SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
18035           << ME->getSourceRange();
18036         return false;
18037       }
18038       return RelevantExpr || Visit(E);
18039     }
18040 
18041     // If we got a member expression, we should not expect any array section
18042     // before that:
18043     //
18044     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
18045     //  If a list item is an element of a structure, only the rightmost symbol
18046     //  of the variable reference can be an array section.
18047     //
18048     AllowUnitySizeArraySection = false;
18049     AllowWholeSizeArraySection = false;
18050 
18051     // Record the component.
18052     Components.emplace_back(ME, FD, IsNonContiguous);
18053     return RelevantExpr || Visit(E);
18054   }
18055 
18056   bool VisitArraySubscriptExpr(ArraySubscriptExpr *AE) {
18057     Expr *E = AE->getBase()->IgnoreParenImpCasts();
18058 
18059     if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
18060       if (!NoDiagnose) {
18061         SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
18062           << 0 << AE->getSourceRange();
18063         return false;
18064       }
18065       return RelevantExpr || Visit(E);
18066     }
18067 
18068     // If we got an array subscript that express the whole dimension we
18069     // can have any array expressions before. If it only expressing part of
18070     // the dimension, we can only have unitary-size array expressions.
18071     if (checkArrayExpressionDoesNotReferToWholeSize(SemaRef, AE,
18072                                                     E->getType()))
18073       AllowWholeSizeArraySection = false;
18074 
18075     if (const auto *TE = dyn_cast<CXXThisExpr>(E->IgnoreParenCasts())) {
18076       Expr::EvalResult Result;
18077       if (!AE->getIdx()->isValueDependent() &&
18078           AE->getIdx()->EvaluateAsInt(Result, SemaRef.getASTContext()) &&
18079           !Result.Val.getInt().isNullValue()) {
18080         SemaRef.Diag(AE->getIdx()->getExprLoc(),
18081                      diag::err_omp_invalid_map_this_expr);
18082         SemaRef.Diag(AE->getIdx()->getExprLoc(),
18083                      diag::note_omp_invalid_subscript_on_this_ptr_map);
18084       }
18085       assert(!RelevantExpr && "RelevantExpr is expected to be nullptr");
18086       RelevantExpr = TE;
18087     }
18088 
18089     // Record the component - we don't have any declaration associated.
18090     Components.emplace_back(AE, nullptr, IsNonContiguous);
18091 
18092     return RelevantExpr || Visit(E);
18093   }
18094 
18095   bool VisitOMPArraySectionExpr(OMPArraySectionExpr *OASE) {
18096     assert(!NoDiagnose && "Array sections cannot be implicitly mapped.");
18097     Expr *E = OASE->getBase()->IgnoreParenImpCasts();
18098     QualType CurType =
18099       OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
18100 
18101     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
18102     //  If the type of a list item is a reference to a type T then the type
18103     //  will be considered to be T for all purposes of this clause.
18104     if (CurType->isReferenceType())
18105       CurType = CurType->getPointeeType();
18106 
18107     bool IsPointer = CurType->isAnyPointerType();
18108 
18109     if (!IsPointer && !CurType->isArrayType()) {
18110       SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
18111         << 0 << OASE->getSourceRange();
18112       return false;
18113     }
18114 
18115     bool NotWhole =
18116       checkArrayExpressionDoesNotReferToWholeSize(SemaRef, OASE, CurType);
18117     bool NotUnity =
18118       checkArrayExpressionDoesNotReferToUnitySize(SemaRef, OASE, CurType);
18119 
18120     if (AllowWholeSizeArraySection) {
18121       // Any array section is currently allowed. Allowing a whole size array
18122       // section implies allowing a unity array section as well.
18123       //
18124       // If this array section refers to the whole dimension we can still
18125       // accept other array sections before this one, except if the base is a
18126       // pointer. Otherwise, only unitary sections are accepted.
18127       if (NotWhole || IsPointer)
18128         AllowWholeSizeArraySection = false;
18129     } else if (DKind == OMPD_target_update &&
18130                SemaRef.getLangOpts().OpenMP >= 50) {
18131       if (IsPointer && !AllowAnotherPtr)
18132         SemaRef.Diag(ELoc, diag::err_omp_section_length_undefined)
18133             << /*array of unknown bound */ 1;
18134       else
18135         IsNonContiguous = true;
18136     } else if (AllowUnitySizeArraySection && NotUnity) {
18137       // A unity or whole array section is not allowed and that is not
18138       // compatible with the properties of the current array section.
18139       SemaRef.Diag(
18140         ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
18141         << OASE->getSourceRange();
18142       return false;
18143     }
18144 
18145     if (IsPointer)
18146       AllowAnotherPtr = false;
18147 
18148     if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
18149       Expr::EvalResult ResultR;
18150       Expr::EvalResult ResultL;
18151       if (!OASE->getLength()->isValueDependent() &&
18152           OASE->getLength()->EvaluateAsInt(ResultR, SemaRef.getASTContext()) &&
18153           !ResultR.Val.getInt().isOneValue()) {
18154         SemaRef.Diag(OASE->getLength()->getExprLoc(),
18155                      diag::err_omp_invalid_map_this_expr);
18156         SemaRef.Diag(OASE->getLength()->getExprLoc(),
18157                      diag::note_omp_invalid_length_on_this_ptr_mapping);
18158       }
18159       if (OASE->getLowerBound() && !OASE->getLowerBound()->isValueDependent() &&
18160           OASE->getLowerBound()->EvaluateAsInt(ResultL,
18161                                                SemaRef.getASTContext()) &&
18162           !ResultL.Val.getInt().isNullValue()) {
18163         SemaRef.Diag(OASE->getLowerBound()->getExprLoc(),
18164                      diag::err_omp_invalid_map_this_expr);
18165         SemaRef.Diag(OASE->getLowerBound()->getExprLoc(),
18166                      diag::note_omp_invalid_lower_bound_on_this_ptr_mapping);
18167       }
18168       assert(!RelevantExpr && "RelevantExpr is expected to be nullptr");
18169       RelevantExpr = TE;
18170     }
18171 
18172     // Record the component - we don't have any declaration associated.
18173     Components.emplace_back(OASE, nullptr, /*IsNonContiguous=*/false);
18174     return RelevantExpr || Visit(E);
18175   }
18176   bool VisitOMPArrayShapingExpr(OMPArrayShapingExpr *E) {
18177     Expr *Base = E->getBase();
18178 
18179     // Record the component - we don't have any declaration associated.
18180     Components.emplace_back(E, nullptr, IsNonContiguous);
18181 
18182     return Visit(Base->IgnoreParenImpCasts());
18183   }
18184 
18185   bool VisitUnaryOperator(UnaryOperator *UO) {
18186     if (SemaRef.getLangOpts().OpenMP < 50 || !UO->isLValue() ||
18187         UO->getOpcode() != UO_Deref) {
18188       emitErrorMsg();
18189       return false;
18190     }
18191     if (!RelevantExpr) {
18192       // Record the component if haven't found base decl.
18193       Components.emplace_back(UO, nullptr, /*IsNonContiguous=*/false);
18194     }
18195     return RelevantExpr || Visit(UO->getSubExpr()->IgnoreParenImpCasts());
18196   }
18197   bool VisitBinaryOperator(BinaryOperator *BO) {
18198     if (SemaRef.getLangOpts().OpenMP < 50 || !BO->getType()->isPointerType()) {
18199       emitErrorMsg();
18200       return false;
18201     }
18202 
18203     // Pointer arithmetic is the only thing we expect to happen here so after we
18204     // make sure the binary operator is a pointer type, the we only thing need
18205     // to to is to visit the subtree that has the same type as root (so that we
18206     // know the other subtree is just an offset)
18207     Expr *LE = BO->getLHS()->IgnoreParenImpCasts();
18208     Expr *RE = BO->getRHS()->IgnoreParenImpCasts();
18209     Components.emplace_back(BO, nullptr, false);
18210     assert((LE->getType().getTypePtr() == BO->getType().getTypePtr() ||
18211             RE->getType().getTypePtr() == BO->getType().getTypePtr()) &&
18212            "Either LHS or RHS have base decl inside");
18213     if (BO->getType().getTypePtr() == LE->getType().getTypePtr())
18214       return RelevantExpr || Visit(LE);
18215     return RelevantExpr || Visit(RE);
18216   }
18217   bool VisitCXXThisExpr(CXXThisExpr *CTE) {
18218     assert(!RelevantExpr && "RelevantExpr is expected to be nullptr");
18219     RelevantExpr = CTE;
18220     Components.emplace_back(CTE, nullptr, IsNonContiguous);
18221     return true;
18222   }
18223   bool VisitCXXOperatorCallExpr(CXXOperatorCallExpr *COCE) {
18224     assert(!RelevantExpr && "RelevantExpr is expected to be nullptr");
18225     Components.emplace_back(COCE, nullptr, IsNonContiguous);
18226     return true;
18227   }
18228   bool VisitOpaqueValueExpr(OpaqueValueExpr *E) {
18229     Expr *Source = E->getSourceExpr();
18230     if (!Source) {
18231       emitErrorMsg();
18232       return false;
18233     }
18234     return Visit(Source);
18235   }
18236   bool VisitStmt(Stmt *) {
18237     emitErrorMsg();
18238     return false;
18239   }
18240   const Expr *getFoundBase() const {
18241     return RelevantExpr;
18242   }
18243   explicit MapBaseChecker(
18244       Sema &SemaRef, OpenMPClauseKind CKind, OpenMPDirectiveKind DKind,
18245       OMPClauseMappableExprCommon::MappableExprComponentList &Components,
18246       bool NoDiagnose, SourceLocation &ELoc, SourceRange &ERange)
18247       : SemaRef(SemaRef), CKind(CKind), DKind(DKind), Components(Components),
18248         NoDiagnose(NoDiagnose), ELoc(ELoc), ERange(ERange) {}
18249 };
18250 } // namespace
18251 
18252 /// Return the expression of the base of the mappable expression or null if it
18253 /// cannot be determined and do all the necessary checks to see if the expression
18254 /// is valid as a standalone mappable expression. In the process, record all the
18255 /// components of the expression.
18256 static const Expr *checkMapClauseExpressionBase(
18257     Sema &SemaRef, Expr *E,
18258     OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
18259     OpenMPClauseKind CKind, OpenMPDirectiveKind DKind, bool NoDiagnose) {
18260   SourceLocation ELoc = E->getExprLoc();
18261   SourceRange ERange = E->getSourceRange();
18262   MapBaseChecker Checker(SemaRef, CKind, DKind, CurComponents, NoDiagnose, ELoc,
18263                          ERange);
18264   if (Checker.Visit(E->IgnoreParens())) {
18265     // Check if the highest dimension array section has length specified
18266     if (SemaRef.getLangOpts().OpenMP >= 50 && !CurComponents.empty() &&
18267         (CKind == OMPC_to || CKind == OMPC_from)) {
18268       auto CI = CurComponents.rbegin();
18269       auto CE = CurComponents.rend();
18270       for (; CI != CE; ++CI) {
18271         const auto *OASE =
18272             dyn_cast<OMPArraySectionExpr>(CI->getAssociatedExpression());
18273         if (!OASE)
18274           continue;
18275         if (OASE && OASE->getLength())
18276           break;
18277         SemaRef.Diag(ELoc, diag::err_array_section_does_not_specify_length)
18278             << ERange;
18279       }
18280     }
18281     return Checker.getFoundBase();
18282   }
18283   return nullptr;
18284 }
18285 
18286 // Return true if expression E associated with value VD has conflicts with other
18287 // map information.
18288 static bool checkMapConflicts(
18289     Sema &SemaRef, DSAStackTy *DSAS, const ValueDecl *VD, const Expr *E,
18290     bool CurrentRegionOnly,
18291     OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
18292     OpenMPClauseKind CKind) {
18293   assert(VD && E);
18294   SourceLocation ELoc = E->getExprLoc();
18295   SourceRange ERange = E->getSourceRange();
18296 
18297   // In order to easily check the conflicts we need to match each component of
18298   // the expression under test with the components of the expressions that are
18299   // already in the stack.
18300 
18301   assert(!CurComponents.empty() && "Map clause expression with no components!");
18302   assert(CurComponents.back().getAssociatedDeclaration() == VD &&
18303          "Map clause expression with unexpected base!");
18304 
18305   // Variables to help detecting enclosing problems in data environment nests.
18306   bool IsEnclosedByDataEnvironmentExpr = false;
18307   const Expr *EnclosingExpr = nullptr;
18308 
18309   bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
18310       VD, CurrentRegionOnly,
18311       [&IsEnclosedByDataEnvironmentExpr, &SemaRef, VD, CurrentRegionOnly, ELoc,
18312        ERange, CKind, &EnclosingExpr,
18313        CurComponents](OMPClauseMappableExprCommon::MappableExprComponentListRef
18314                           StackComponents,
18315                       OpenMPClauseKind Kind) {
18316         if (CKind == Kind && SemaRef.LangOpts.OpenMP >= 50)
18317           return false;
18318         assert(!StackComponents.empty() &&
18319                "Map clause expression with no components!");
18320         assert(StackComponents.back().getAssociatedDeclaration() == VD &&
18321                "Map clause expression with unexpected base!");
18322         (void)VD;
18323 
18324         // The whole expression in the stack.
18325         const Expr *RE = StackComponents.front().getAssociatedExpression();
18326 
18327         // Expressions must start from the same base. Here we detect at which
18328         // point both expressions diverge from each other and see if we can
18329         // detect if the memory referred to both expressions is contiguous and
18330         // do not overlap.
18331         auto CI = CurComponents.rbegin();
18332         auto CE = CurComponents.rend();
18333         auto SI = StackComponents.rbegin();
18334         auto SE = StackComponents.rend();
18335         for (; CI != CE && SI != SE; ++CI, ++SI) {
18336 
18337           // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
18338           //  At most one list item can be an array item derived from a given
18339           //  variable in map clauses of the same construct.
18340           if (CurrentRegionOnly &&
18341               (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
18342                isa<OMPArraySectionExpr>(CI->getAssociatedExpression()) ||
18343                isa<OMPArrayShapingExpr>(CI->getAssociatedExpression())) &&
18344               (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
18345                isa<OMPArraySectionExpr>(SI->getAssociatedExpression()) ||
18346                isa<OMPArrayShapingExpr>(SI->getAssociatedExpression()))) {
18347             SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
18348                          diag::err_omp_multiple_array_items_in_map_clause)
18349                 << CI->getAssociatedExpression()->getSourceRange();
18350             SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
18351                          diag::note_used_here)
18352                 << SI->getAssociatedExpression()->getSourceRange();
18353             return true;
18354           }
18355 
18356           // Do both expressions have the same kind?
18357           if (CI->getAssociatedExpression()->getStmtClass() !=
18358               SI->getAssociatedExpression()->getStmtClass())
18359             break;
18360 
18361           // Are we dealing with different variables/fields?
18362           if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
18363             break;
18364         }
18365         // Check if the extra components of the expressions in the enclosing
18366         // data environment are redundant for the current base declaration.
18367         // If they are, the maps completely overlap, which is legal.
18368         for (; SI != SE; ++SI) {
18369           QualType Type;
18370           if (const auto *ASE =
18371                   dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
18372             Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
18373           } else if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(
18374                          SI->getAssociatedExpression())) {
18375             const Expr *E = OASE->getBase()->IgnoreParenImpCasts();
18376             Type =
18377                 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
18378           } else if (const auto *OASE = dyn_cast<OMPArrayShapingExpr>(
18379                          SI->getAssociatedExpression())) {
18380             Type = OASE->getBase()->getType()->getPointeeType();
18381           }
18382           if (Type.isNull() || Type->isAnyPointerType() ||
18383               checkArrayExpressionDoesNotReferToWholeSize(
18384                   SemaRef, SI->getAssociatedExpression(), Type))
18385             break;
18386         }
18387 
18388         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
18389         //  List items of map clauses in the same construct must not share
18390         //  original storage.
18391         //
18392         // If the expressions are exactly the same or one is a subset of the
18393         // other, it means they are sharing storage.
18394         if (CI == CE && SI == SE) {
18395           if (CurrentRegionOnly) {
18396             if (CKind == OMPC_map) {
18397               SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
18398             } else {
18399               assert(CKind == OMPC_to || CKind == OMPC_from);
18400               SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
18401                   << ERange;
18402             }
18403             SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
18404                 << RE->getSourceRange();
18405             return true;
18406           }
18407           // If we find the same expression in the enclosing data environment,
18408           // that is legal.
18409           IsEnclosedByDataEnvironmentExpr = true;
18410           return false;
18411         }
18412 
18413         QualType DerivedType =
18414             std::prev(CI)->getAssociatedDeclaration()->getType();
18415         SourceLocation DerivedLoc =
18416             std::prev(CI)->getAssociatedExpression()->getExprLoc();
18417 
18418         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
18419         //  If the type of a list item is a reference to a type T then the type
18420         //  will be considered to be T for all purposes of this clause.
18421         DerivedType = DerivedType.getNonReferenceType();
18422 
18423         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
18424         //  A variable for which the type is pointer and an array section
18425         //  derived from that variable must not appear as list items of map
18426         //  clauses of the same construct.
18427         //
18428         // Also, cover one of the cases in:
18429         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
18430         //  If any part of the original storage of a list item has corresponding
18431         //  storage in the device data environment, all of the original storage
18432         //  must have corresponding storage in the device data environment.
18433         //
18434         if (DerivedType->isAnyPointerType()) {
18435           if (CI == CE || SI == SE) {
18436             SemaRef.Diag(
18437                 DerivedLoc,
18438                 diag::err_omp_pointer_mapped_along_with_derived_section)
18439                 << DerivedLoc;
18440             SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
18441                 << RE->getSourceRange();
18442             return true;
18443           }
18444           if (CI->getAssociatedExpression()->getStmtClass() !=
18445                          SI->getAssociatedExpression()->getStmtClass() ||
18446                      CI->getAssociatedDeclaration()->getCanonicalDecl() ==
18447                          SI->getAssociatedDeclaration()->getCanonicalDecl()) {
18448             assert(CI != CE && SI != SE);
18449             SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_dereferenced)
18450                 << DerivedLoc;
18451             SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
18452                 << RE->getSourceRange();
18453             return true;
18454           }
18455         }
18456 
18457         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
18458         //  List items of map clauses in the same construct must not share
18459         //  original storage.
18460         //
18461         // An expression is a subset of the other.
18462         if (CurrentRegionOnly && (CI == CE || SI == SE)) {
18463           if (CKind == OMPC_map) {
18464             if (CI != CE || SI != SE) {
18465               // Allow constructs like this: map(s, s.ptr[0:1]), where s.ptr is
18466               // a pointer.
18467               auto Begin =
18468                   CI != CE ? CurComponents.begin() : StackComponents.begin();
18469               auto End = CI != CE ? CurComponents.end() : StackComponents.end();
18470               auto It = Begin;
18471               while (It != End && !It->getAssociatedDeclaration())
18472                 std::advance(It, 1);
18473               assert(It != End &&
18474                      "Expected at least one component with the declaration.");
18475               if (It != Begin && It->getAssociatedDeclaration()
18476                                      ->getType()
18477                                      .getCanonicalType()
18478                                      ->isAnyPointerType()) {
18479                 IsEnclosedByDataEnvironmentExpr = false;
18480                 EnclosingExpr = nullptr;
18481                 return false;
18482               }
18483             }
18484             SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
18485           } else {
18486             assert(CKind == OMPC_to || CKind == OMPC_from);
18487             SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
18488                 << ERange;
18489           }
18490           SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
18491               << RE->getSourceRange();
18492           return true;
18493         }
18494 
18495         // The current expression uses the same base as other expression in the
18496         // data environment but does not contain it completely.
18497         if (!CurrentRegionOnly && SI != SE)
18498           EnclosingExpr = RE;
18499 
18500         // The current expression is a subset of the expression in the data
18501         // environment.
18502         IsEnclosedByDataEnvironmentExpr |=
18503             (!CurrentRegionOnly && CI != CE && SI == SE);
18504 
18505         return false;
18506       });
18507 
18508   if (CurrentRegionOnly)
18509     return FoundError;
18510 
18511   // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
18512   //  If any part of the original storage of a list item has corresponding
18513   //  storage in the device data environment, all of the original storage must
18514   //  have corresponding storage in the device data environment.
18515   // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
18516   //  If a list item is an element of a structure, and a different element of
18517   //  the structure has a corresponding list item in the device data environment
18518   //  prior to a task encountering the construct associated with the map clause,
18519   //  then the list item must also have a corresponding list item in the device
18520   //  data environment prior to the task encountering the construct.
18521   //
18522   if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
18523     SemaRef.Diag(ELoc,
18524                  diag::err_omp_original_storage_is_shared_and_does_not_contain)
18525         << ERange;
18526     SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
18527         << EnclosingExpr->getSourceRange();
18528     return true;
18529   }
18530 
18531   return FoundError;
18532 }
18533 
18534 // Look up the user-defined mapper given the mapper name and mapped type, and
18535 // build a reference to it.
18536 static ExprResult buildUserDefinedMapperRef(Sema &SemaRef, Scope *S,
18537                                             CXXScopeSpec &MapperIdScopeSpec,
18538                                             const DeclarationNameInfo &MapperId,
18539                                             QualType Type,
18540                                             Expr *UnresolvedMapper) {
18541   if (MapperIdScopeSpec.isInvalid())
18542     return ExprError();
18543   // Get the actual type for the array type.
18544   if (Type->isArrayType()) {
18545     assert(Type->getAsArrayTypeUnsafe() && "Expect to get a valid array type");
18546     Type = Type->getAsArrayTypeUnsafe()->getElementType().getCanonicalType();
18547   }
18548   // Find all user-defined mappers with the given MapperId.
18549   SmallVector<UnresolvedSet<8>, 4> Lookups;
18550   LookupResult Lookup(SemaRef, MapperId, Sema::LookupOMPMapperName);
18551   Lookup.suppressDiagnostics();
18552   if (S) {
18553     while (S && SemaRef.LookupParsedName(Lookup, S, &MapperIdScopeSpec)) {
18554       NamedDecl *D = Lookup.getRepresentativeDecl();
18555       while (S && !S->isDeclScope(D))
18556         S = S->getParent();
18557       if (S)
18558         S = S->getParent();
18559       Lookups.emplace_back();
18560       Lookups.back().append(Lookup.begin(), Lookup.end());
18561       Lookup.clear();
18562     }
18563   } else if (auto *ULE = cast_or_null<UnresolvedLookupExpr>(UnresolvedMapper)) {
18564     // Extract the user-defined mappers with the given MapperId.
18565     Lookups.push_back(UnresolvedSet<8>());
18566     for (NamedDecl *D : ULE->decls()) {
18567       auto *DMD = cast<OMPDeclareMapperDecl>(D);
18568       assert(DMD && "Expect valid OMPDeclareMapperDecl during instantiation.");
18569       Lookups.back().addDecl(DMD);
18570     }
18571   }
18572   // Defer the lookup for dependent types. The results will be passed through
18573   // UnresolvedMapper on instantiation.
18574   if (SemaRef.CurContext->isDependentContext() || Type->isDependentType() ||
18575       Type->isInstantiationDependentType() ||
18576       Type->containsUnexpandedParameterPack() ||
18577       filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
18578         return !D->isInvalidDecl() &&
18579                (D->getType()->isDependentType() ||
18580                 D->getType()->isInstantiationDependentType() ||
18581                 D->getType()->containsUnexpandedParameterPack());
18582       })) {
18583     UnresolvedSet<8> URS;
18584     for (const UnresolvedSet<8> &Set : Lookups) {
18585       if (Set.empty())
18586         continue;
18587       URS.append(Set.begin(), Set.end());
18588     }
18589     return UnresolvedLookupExpr::Create(
18590         SemaRef.Context, /*NamingClass=*/nullptr,
18591         MapperIdScopeSpec.getWithLocInContext(SemaRef.Context), MapperId,
18592         /*ADL=*/false, /*Overloaded=*/true, URS.begin(), URS.end());
18593   }
18594   SourceLocation Loc = MapperId.getLoc();
18595   // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
18596   //  The type must be of struct, union or class type in C and C++
18597   if (!Type->isStructureOrClassType() && !Type->isUnionType() &&
18598       (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default")) {
18599     SemaRef.Diag(Loc, diag::err_omp_mapper_wrong_type);
18600     return ExprError();
18601   }
18602   // Perform argument dependent lookup.
18603   if (SemaRef.getLangOpts().CPlusPlus && !MapperIdScopeSpec.isSet())
18604     argumentDependentLookup(SemaRef, MapperId, Loc, Type, Lookups);
18605   // Return the first user-defined mapper with the desired type.
18606   if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
18607           Lookups, [&SemaRef, Type](ValueDecl *D) -> ValueDecl * {
18608             if (!D->isInvalidDecl() &&
18609                 SemaRef.Context.hasSameType(D->getType(), Type))
18610               return D;
18611             return nullptr;
18612           }))
18613     return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
18614   // Find the first user-defined mapper with a type derived from the desired
18615   // type.
18616   if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
18617           Lookups, [&SemaRef, Type, Loc](ValueDecl *D) -> ValueDecl * {
18618             if (!D->isInvalidDecl() &&
18619                 SemaRef.IsDerivedFrom(Loc, Type, D->getType()) &&
18620                 !Type.isMoreQualifiedThan(D->getType()))
18621               return D;
18622             return nullptr;
18623           })) {
18624     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
18625                        /*DetectVirtual=*/false);
18626     if (SemaRef.IsDerivedFrom(Loc, Type, VD->getType(), Paths)) {
18627       if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
18628               VD->getType().getUnqualifiedType()))) {
18629         if (SemaRef.CheckBaseClassAccess(
18630                 Loc, VD->getType(), Type, Paths.front(),
18631                 /*DiagID=*/0) != Sema::AR_inaccessible) {
18632           return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
18633         }
18634       }
18635     }
18636   }
18637   // Report error if a mapper is specified, but cannot be found.
18638   if (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default") {
18639     SemaRef.Diag(Loc, diag::err_omp_invalid_mapper)
18640         << Type << MapperId.getName();
18641     return ExprError();
18642   }
18643   return ExprEmpty();
18644 }
18645 
18646 namespace {
18647 // Utility struct that gathers all the related lists associated with a mappable
18648 // expression.
18649 struct MappableVarListInfo {
18650   // The list of expressions.
18651   ArrayRef<Expr *> VarList;
18652   // The list of processed expressions.
18653   SmallVector<Expr *, 16> ProcessedVarList;
18654   // The mappble components for each expression.
18655   OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
18656   // The base declaration of the variable.
18657   SmallVector<ValueDecl *, 16> VarBaseDeclarations;
18658   // The reference to the user-defined mapper associated with every expression.
18659   SmallVector<Expr *, 16> UDMapperList;
18660 
18661   MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
18662     // We have a list of components and base declarations for each entry in the
18663     // variable list.
18664     VarComponents.reserve(VarList.size());
18665     VarBaseDeclarations.reserve(VarList.size());
18666   }
18667 };
18668 }
18669 
18670 // Check the validity of the provided variable list for the provided clause kind
18671 // \a CKind. In the check process the valid expressions, mappable expression
18672 // components, variables, and user-defined mappers are extracted and used to
18673 // fill \a ProcessedVarList, \a VarComponents, \a VarBaseDeclarations, and \a
18674 // UDMapperList in MVLI. \a MapType, \a IsMapTypeImplicit, \a MapperIdScopeSpec,
18675 // and \a MapperId are expected to be valid if the clause kind is 'map'.
18676 static void checkMappableExpressionList(
18677     Sema &SemaRef, DSAStackTy *DSAS, OpenMPClauseKind CKind,
18678     MappableVarListInfo &MVLI, SourceLocation StartLoc,
18679     CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo MapperId,
18680     ArrayRef<Expr *> UnresolvedMappers,
18681     OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
18682     bool IsMapTypeImplicit = false) {
18683   // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
18684   assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
18685          "Unexpected clause kind with mappable expressions!");
18686 
18687   // If the identifier of user-defined mapper is not specified, it is "default".
18688   // We do not change the actual name in this clause to distinguish whether a
18689   // mapper is specified explicitly, i.e., it is not explicitly specified when
18690   // MapperId.getName() is empty.
18691   if (!MapperId.getName() || MapperId.getName().isEmpty()) {
18692     auto &DeclNames = SemaRef.getASTContext().DeclarationNames;
18693     MapperId.setName(DeclNames.getIdentifier(
18694         &SemaRef.getASTContext().Idents.get("default")));
18695     MapperId.setLoc(StartLoc);
18696   }
18697 
18698   // Iterators to find the current unresolved mapper expression.
18699   auto UMIt = UnresolvedMappers.begin(), UMEnd = UnresolvedMappers.end();
18700   bool UpdateUMIt = false;
18701   Expr *UnresolvedMapper = nullptr;
18702 
18703   // Keep track of the mappable components and base declarations in this clause.
18704   // Each entry in the list is going to have a list of components associated. We
18705   // record each set of the components so that we can build the clause later on.
18706   // In the end we should have the same amount of declarations and component
18707   // lists.
18708 
18709   for (Expr *RE : MVLI.VarList) {
18710     assert(RE && "Null expr in omp to/from/map clause");
18711     SourceLocation ELoc = RE->getExprLoc();
18712 
18713     // Find the current unresolved mapper expression.
18714     if (UpdateUMIt && UMIt != UMEnd) {
18715       UMIt++;
18716       assert(
18717           UMIt != UMEnd &&
18718           "Expect the size of UnresolvedMappers to match with that of VarList");
18719     }
18720     UpdateUMIt = true;
18721     if (UMIt != UMEnd)
18722       UnresolvedMapper = *UMIt;
18723 
18724     const Expr *VE = RE->IgnoreParenLValueCasts();
18725 
18726     if (VE->isValueDependent() || VE->isTypeDependent() ||
18727         VE->isInstantiationDependent() ||
18728         VE->containsUnexpandedParameterPack()) {
18729       // Try to find the associated user-defined mapper.
18730       ExprResult ER = buildUserDefinedMapperRef(
18731           SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
18732           VE->getType().getCanonicalType(), UnresolvedMapper);
18733       if (ER.isInvalid())
18734         continue;
18735       MVLI.UDMapperList.push_back(ER.get());
18736       // We can only analyze this information once the missing information is
18737       // resolved.
18738       MVLI.ProcessedVarList.push_back(RE);
18739       continue;
18740     }
18741 
18742     Expr *SimpleExpr = RE->IgnoreParenCasts();
18743 
18744     if (!RE->isLValue()) {
18745       if (SemaRef.getLangOpts().OpenMP < 50) {
18746         SemaRef.Diag(
18747             ELoc, diag::err_omp_expected_named_var_member_or_array_expression)
18748             << RE->getSourceRange();
18749       } else {
18750         SemaRef.Diag(ELoc, diag::err_omp_non_lvalue_in_map_or_motion_clauses)
18751             << getOpenMPClauseName(CKind) << RE->getSourceRange();
18752       }
18753       continue;
18754     }
18755 
18756     OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
18757     ValueDecl *CurDeclaration = nullptr;
18758 
18759     // Obtain the array or member expression bases if required. Also, fill the
18760     // components array with all the components identified in the process.
18761     const Expr *BE = checkMapClauseExpressionBase(
18762         SemaRef, SimpleExpr, CurComponents, CKind, DSAS->getCurrentDirective(),
18763         /*NoDiagnose=*/false);
18764     if (!BE)
18765       continue;
18766 
18767     assert(!CurComponents.empty() &&
18768            "Invalid mappable expression information.");
18769 
18770     if (const auto *TE = dyn_cast<CXXThisExpr>(BE)) {
18771       // Add store "this" pointer to class in DSAStackTy for future checking
18772       DSAS->addMappedClassesQualTypes(TE->getType());
18773       // Try to find the associated user-defined mapper.
18774       ExprResult ER = buildUserDefinedMapperRef(
18775           SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
18776           VE->getType().getCanonicalType(), UnresolvedMapper);
18777       if (ER.isInvalid())
18778         continue;
18779       MVLI.UDMapperList.push_back(ER.get());
18780       // Skip restriction checking for variable or field declarations
18781       MVLI.ProcessedVarList.push_back(RE);
18782       MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
18783       MVLI.VarComponents.back().append(CurComponents.begin(),
18784                                        CurComponents.end());
18785       MVLI.VarBaseDeclarations.push_back(nullptr);
18786       continue;
18787     }
18788 
18789     // For the following checks, we rely on the base declaration which is
18790     // expected to be associated with the last component. The declaration is
18791     // expected to be a variable or a field (if 'this' is being mapped).
18792     CurDeclaration = CurComponents.back().getAssociatedDeclaration();
18793     assert(CurDeclaration && "Null decl on map clause.");
18794     assert(
18795         CurDeclaration->isCanonicalDecl() &&
18796         "Expecting components to have associated only canonical declarations.");
18797 
18798     auto *VD = dyn_cast<VarDecl>(CurDeclaration);
18799     const auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
18800 
18801     assert((VD || FD) && "Only variables or fields are expected here!");
18802     (void)FD;
18803 
18804     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
18805     // threadprivate variables cannot appear in a map clause.
18806     // OpenMP 4.5 [2.10.5, target update Construct]
18807     // threadprivate variables cannot appear in a from clause.
18808     if (VD && DSAS->isThreadPrivate(VD)) {
18809       DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
18810       SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
18811           << getOpenMPClauseName(CKind);
18812       reportOriginalDsa(SemaRef, DSAS, VD, DVar);
18813       continue;
18814     }
18815 
18816     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
18817     //  A list item cannot appear in both a map clause and a data-sharing
18818     //  attribute clause on the same construct.
18819 
18820     // Check conflicts with other map clause expressions. We check the conflicts
18821     // with the current construct separately from the enclosing data
18822     // environment, because the restrictions are different. We only have to
18823     // check conflicts across regions for the map clauses.
18824     if (checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
18825                           /*CurrentRegionOnly=*/true, CurComponents, CKind))
18826       break;
18827     if (CKind == OMPC_map &&
18828         (SemaRef.getLangOpts().OpenMP <= 45 || StartLoc.isValid()) &&
18829         checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
18830                           /*CurrentRegionOnly=*/false, CurComponents, CKind))
18831       break;
18832 
18833     // OpenMP 4.5 [2.10.5, target update Construct]
18834     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
18835     //  If the type of a list item is a reference to a type T then the type will
18836     //  be considered to be T for all purposes of this clause.
18837     auto I = llvm::find_if(
18838         CurComponents,
18839         [](const OMPClauseMappableExprCommon::MappableComponent &MC) {
18840           return MC.getAssociatedDeclaration();
18841         });
18842     assert(I != CurComponents.end() && "Null decl on map clause.");
18843     (void)I;
18844     QualType Type;
18845     auto *ASE = dyn_cast<ArraySubscriptExpr>(VE->IgnoreParens());
18846     auto *OASE = dyn_cast<OMPArraySectionExpr>(VE->IgnoreParens());
18847     auto *OAShE = dyn_cast<OMPArrayShapingExpr>(VE->IgnoreParens());
18848     if (ASE) {
18849       Type = ASE->getType().getNonReferenceType();
18850     } else if (OASE) {
18851       QualType BaseType =
18852           OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
18853       if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
18854         Type = ATy->getElementType();
18855       else
18856         Type = BaseType->getPointeeType();
18857       Type = Type.getNonReferenceType();
18858     } else if (OAShE) {
18859       Type = OAShE->getBase()->getType()->getPointeeType();
18860     } else {
18861       Type = VE->getType();
18862     }
18863 
18864     // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
18865     // A list item in a to or from clause must have a mappable type.
18866     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
18867     //  A list item must have a mappable type.
18868     if (!checkTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
18869                            DSAS, Type))
18870       continue;
18871 
18872     if (CKind == OMPC_map) {
18873       // target enter data
18874       // OpenMP [2.10.2, Restrictions, p. 99]
18875       // A map-type must be specified in all map clauses and must be either
18876       // to or alloc.
18877       OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
18878       if (DKind == OMPD_target_enter_data &&
18879           !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
18880         SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
18881             << (IsMapTypeImplicit ? 1 : 0)
18882             << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
18883             << getOpenMPDirectiveName(DKind);
18884         continue;
18885       }
18886 
18887       // target exit_data
18888       // OpenMP [2.10.3, Restrictions, p. 102]
18889       // A map-type must be specified in all map clauses and must be either
18890       // from, release, or delete.
18891       if (DKind == OMPD_target_exit_data &&
18892           !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
18893             MapType == OMPC_MAP_delete)) {
18894         SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
18895             << (IsMapTypeImplicit ? 1 : 0)
18896             << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
18897             << getOpenMPDirectiveName(DKind);
18898         continue;
18899       }
18900 
18901       // target, target data
18902       // OpenMP 5.0 [2.12.2, Restrictions, p. 163]
18903       // OpenMP 5.0 [2.12.5, Restrictions, p. 174]
18904       // A map-type in a map clause must be to, from, tofrom or alloc
18905       if ((DKind == OMPD_target_data ||
18906            isOpenMPTargetExecutionDirective(DKind)) &&
18907           !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_from ||
18908             MapType == OMPC_MAP_tofrom || MapType == OMPC_MAP_alloc)) {
18909         SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
18910             << (IsMapTypeImplicit ? 1 : 0)
18911             << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
18912             << getOpenMPDirectiveName(DKind);
18913         continue;
18914       }
18915 
18916       // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
18917       // A list item cannot appear in both a map clause and a data-sharing
18918       // attribute clause on the same construct
18919       //
18920       // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
18921       // A list item cannot appear in both a map clause and a data-sharing
18922       // attribute clause on the same construct unless the construct is a
18923       // combined construct.
18924       if (VD && ((SemaRef.LangOpts.OpenMP <= 45 &&
18925                   isOpenMPTargetExecutionDirective(DKind)) ||
18926                  DKind == OMPD_target)) {
18927         DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
18928         if (isOpenMPPrivate(DVar.CKind)) {
18929           SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
18930               << getOpenMPClauseName(DVar.CKind)
18931               << getOpenMPClauseName(OMPC_map)
18932               << getOpenMPDirectiveName(DSAS->getCurrentDirective());
18933           reportOriginalDsa(SemaRef, DSAS, CurDeclaration, DVar);
18934           continue;
18935         }
18936       }
18937     }
18938 
18939     // Try to find the associated user-defined mapper.
18940     ExprResult ER = buildUserDefinedMapperRef(
18941         SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
18942         Type.getCanonicalType(), UnresolvedMapper);
18943     if (ER.isInvalid())
18944       continue;
18945     MVLI.UDMapperList.push_back(ER.get());
18946 
18947     // Save the current expression.
18948     MVLI.ProcessedVarList.push_back(RE);
18949 
18950     // Store the components in the stack so that they can be used to check
18951     // against other clauses later on.
18952     DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
18953                                           /*WhereFoundClauseKind=*/OMPC_map);
18954 
18955     // Save the components and declaration to create the clause. For purposes of
18956     // the clause creation, any component list that has has base 'this' uses
18957     // null as base declaration.
18958     MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
18959     MVLI.VarComponents.back().append(CurComponents.begin(),
18960                                      CurComponents.end());
18961     MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
18962                                                            : CurDeclaration);
18963   }
18964 }
18965 
18966 OMPClause *Sema::ActOnOpenMPMapClause(
18967     ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
18968     ArrayRef<SourceLocation> MapTypeModifiersLoc,
18969     CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId,
18970     OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, SourceLocation MapLoc,
18971     SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
18972     const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) {
18973   OpenMPMapModifierKind Modifiers[] = {
18974       OMPC_MAP_MODIFIER_unknown, OMPC_MAP_MODIFIER_unknown,
18975       OMPC_MAP_MODIFIER_unknown, OMPC_MAP_MODIFIER_unknown};
18976   SourceLocation ModifiersLoc[NumberOfOMPMapClauseModifiers];
18977 
18978   // Process map-type-modifiers, flag errors for duplicate modifiers.
18979   unsigned Count = 0;
18980   for (unsigned I = 0, E = MapTypeModifiers.size(); I < E; ++I) {
18981     if (MapTypeModifiers[I] != OMPC_MAP_MODIFIER_unknown &&
18982         llvm::find(Modifiers, MapTypeModifiers[I]) != std::end(Modifiers)) {
18983       Diag(MapTypeModifiersLoc[I], diag::err_omp_duplicate_map_type_modifier);
18984       continue;
18985     }
18986     assert(Count < NumberOfOMPMapClauseModifiers &&
18987            "Modifiers exceed the allowed number of map type modifiers");
18988     Modifiers[Count] = MapTypeModifiers[I];
18989     ModifiersLoc[Count] = MapTypeModifiersLoc[I];
18990     ++Count;
18991   }
18992 
18993   MappableVarListInfo MVLI(VarList);
18994   checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, Locs.StartLoc,
18995                               MapperIdScopeSpec, MapperId, UnresolvedMappers,
18996                               MapType, IsMapTypeImplicit);
18997 
18998   // We need to produce a map clause even if we don't have variables so that
18999   // other diagnostics related with non-existing map clauses are accurate.
19000   return OMPMapClause::Create(Context, Locs, MVLI.ProcessedVarList,
19001                               MVLI.VarBaseDeclarations, MVLI.VarComponents,
19002                               MVLI.UDMapperList, Modifiers, ModifiersLoc,
19003                               MapperIdScopeSpec.getWithLocInContext(Context),
19004                               MapperId, MapType, IsMapTypeImplicit, MapLoc);
19005 }
19006 
19007 QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
19008                                                TypeResult ParsedType) {
19009   assert(ParsedType.isUsable());
19010 
19011   QualType ReductionType = GetTypeFromParser(ParsedType.get());
19012   if (ReductionType.isNull())
19013     return QualType();
19014 
19015   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
19016   // A type name in a declare reduction directive cannot be a function type, an
19017   // array type, a reference type, or a type qualified with const, volatile or
19018   // restrict.
19019   if (ReductionType.hasQualifiers()) {
19020     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
19021     return QualType();
19022   }
19023 
19024   if (ReductionType->isFunctionType()) {
19025     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
19026     return QualType();
19027   }
19028   if (ReductionType->isReferenceType()) {
19029     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
19030     return QualType();
19031   }
19032   if (ReductionType->isArrayType()) {
19033     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
19034     return QualType();
19035   }
19036   return ReductionType;
19037 }
19038 
19039 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
19040     Scope *S, DeclContext *DC, DeclarationName Name,
19041     ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
19042     AccessSpecifier AS, Decl *PrevDeclInScope) {
19043   SmallVector<Decl *, 8> Decls;
19044   Decls.reserve(ReductionTypes.size());
19045 
19046   LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
19047                       forRedeclarationInCurContext());
19048   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
19049   // A reduction-identifier may not be re-declared in the current scope for the
19050   // same type or for a type that is compatible according to the base language
19051   // rules.
19052   llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
19053   OMPDeclareReductionDecl *PrevDRD = nullptr;
19054   bool InCompoundScope = true;
19055   if (S != nullptr) {
19056     // Find previous declaration with the same name not referenced in other
19057     // declarations.
19058     FunctionScopeInfo *ParentFn = getEnclosingFunction();
19059     InCompoundScope =
19060         (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
19061     LookupName(Lookup, S);
19062     FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
19063                          /*AllowInlineNamespace=*/false);
19064     llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
19065     LookupResult::Filter Filter = Lookup.makeFilter();
19066     while (Filter.hasNext()) {
19067       auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
19068       if (InCompoundScope) {
19069         auto I = UsedAsPrevious.find(PrevDecl);
19070         if (I == UsedAsPrevious.end())
19071           UsedAsPrevious[PrevDecl] = false;
19072         if (OMPDeclareReductionDecl *D = PrevDecl->getPrevDeclInScope())
19073           UsedAsPrevious[D] = true;
19074       }
19075       PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
19076           PrevDecl->getLocation();
19077     }
19078     Filter.done();
19079     if (InCompoundScope) {
19080       for (const auto &PrevData : UsedAsPrevious) {
19081         if (!PrevData.second) {
19082           PrevDRD = PrevData.first;
19083           break;
19084         }
19085       }
19086     }
19087   } else if (PrevDeclInScope != nullptr) {
19088     auto *PrevDRDInScope = PrevDRD =
19089         cast<OMPDeclareReductionDecl>(PrevDeclInScope);
19090     do {
19091       PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
19092           PrevDRDInScope->getLocation();
19093       PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
19094     } while (PrevDRDInScope != nullptr);
19095   }
19096   for (const auto &TyData : ReductionTypes) {
19097     const auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
19098     bool Invalid = false;
19099     if (I != PreviousRedeclTypes.end()) {
19100       Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
19101           << TyData.first;
19102       Diag(I->second, diag::note_previous_definition);
19103       Invalid = true;
19104     }
19105     PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
19106     auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
19107                                                 Name, TyData.first, PrevDRD);
19108     DC->addDecl(DRD);
19109     DRD->setAccess(AS);
19110     Decls.push_back(DRD);
19111     if (Invalid)
19112       DRD->setInvalidDecl();
19113     else
19114       PrevDRD = DRD;
19115   }
19116 
19117   return DeclGroupPtrTy::make(
19118       DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
19119 }
19120 
19121 void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
19122   auto *DRD = cast<OMPDeclareReductionDecl>(D);
19123 
19124   // Enter new function scope.
19125   PushFunctionScope();
19126   setFunctionHasBranchProtectedScope();
19127   getCurFunction()->setHasOMPDeclareReductionCombiner();
19128 
19129   if (S != nullptr)
19130     PushDeclContext(S, DRD);
19131   else
19132     CurContext = DRD;
19133 
19134   PushExpressionEvaluationContext(
19135       ExpressionEvaluationContext::PotentiallyEvaluated);
19136 
19137   QualType ReductionType = DRD->getType();
19138   // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
19139   // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
19140   // uses semantics of argument handles by value, but it should be passed by
19141   // reference. C lang does not support references, so pass all parameters as
19142   // pointers.
19143   // Create 'T omp_in;' variable.
19144   VarDecl *OmpInParm =
19145       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
19146   // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
19147   // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
19148   // uses semantics of argument handles by value, but it should be passed by
19149   // reference. C lang does not support references, so pass all parameters as
19150   // pointers.
19151   // Create 'T omp_out;' variable.
19152   VarDecl *OmpOutParm =
19153       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
19154   if (S != nullptr) {
19155     PushOnScopeChains(OmpInParm, S);
19156     PushOnScopeChains(OmpOutParm, S);
19157   } else {
19158     DRD->addDecl(OmpInParm);
19159     DRD->addDecl(OmpOutParm);
19160   }
19161   Expr *InE =
19162       ::buildDeclRefExpr(*this, OmpInParm, ReductionType, D->getLocation());
19163   Expr *OutE =
19164       ::buildDeclRefExpr(*this, OmpOutParm, ReductionType, D->getLocation());
19165   DRD->setCombinerData(InE, OutE);
19166 }
19167 
19168 void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
19169   auto *DRD = cast<OMPDeclareReductionDecl>(D);
19170   DiscardCleanupsInEvaluationContext();
19171   PopExpressionEvaluationContext();
19172 
19173   PopDeclContext();
19174   PopFunctionScopeInfo();
19175 
19176   if (Combiner != nullptr)
19177     DRD->setCombiner(Combiner);
19178   else
19179     DRD->setInvalidDecl();
19180 }
19181 
19182 VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
19183   auto *DRD = cast<OMPDeclareReductionDecl>(D);
19184 
19185   // Enter new function scope.
19186   PushFunctionScope();
19187   setFunctionHasBranchProtectedScope();
19188 
19189   if (S != nullptr)
19190     PushDeclContext(S, DRD);
19191   else
19192     CurContext = DRD;
19193 
19194   PushExpressionEvaluationContext(
19195       ExpressionEvaluationContext::PotentiallyEvaluated);
19196 
19197   QualType ReductionType = DRD->getType();
19198   // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
19199   // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
19200   // uses semantics of argument handles by value, but it should be passed by
19201   // reference. C lang does not support references, so pass all parameters as
19202   // pointers.
19203   // Create 'T omp_priv;' variable.
19204   VarDecl *OmpPrivParm =
19205       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
19206   // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
19207   // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
19208   // uses semantics of argument handles by value, but it should be passed by
19209   // reference. C lang does not support references, so pass all parameters as
19210   // pointers.
19211   // Create 'T omp_orig;' variable.
19212   VarDecl *OmpOrigParm =
19213       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
19214   if (S != nullptr) {
19215     PushOnScopeChains(OmpPrivParm, S);
19216     PushOnScopeChains(OmpOrigParm, S);
19217   } else {
19218     DRD->addDecl(OmpPrivParm);
19219     DRD->addDecl(OmpOrigParm);
19220   }
19221   Expr *OrigE =
19222       ::buildDeclRefExpr(*this, OmpOrigParm, ReductionType, D->getLocation());
19223   Expr *PrivE =
19224       ::buildDeclRefExpr(*this, OmpPrivParm, ReductionType, D->getLocation());
19225   DRD->setInitializerData(OrigE, PrivE);
19226   return OmpPrivParm;
19227 }
19228 
19229 void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
19230                                                      VarDecl *OmpPrivParm) {
19231   auto *DRD = cast<OMPDeclareReductionDecl>(D);
19232   DiscardCleanupsInEvaluationContext();
19233   PopExpressionEvaluationContext();
19234 
19235   PopDeclContext();
19236   PopFunctionScopeInfo();
19237 
19238   if (Initializer != nullptr) {
19239     DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit);
19240   } else if (OmpPrivParm->hasInit()) {
19241     DRD->setInitializer(OmpPrivParm->getInit(),
19242                         OmpPrivParm->isDirectInit()
19243                             ? OMPDeclareReductionDecl::DirectInit
19244                             : OMPDeclareReductionDecl::CopyInit);
19245   } else {
19246     DRD->setInvalidDecl();
19247   }
19248 }
19249 
19250 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
19251     Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
19252   for (Decl *D : DeclReductions.get()) {
19253     if (IsValid) {
19254       if (S)
19255         PushOnScopeChains(cast<OMPDeclareReductionDecl>(D), S,
19256                           /*AddToContext=*/false);
19257     } else {
19258       D->setInvalidDecl();
19259     }
19260   }
19261   return DeclReductions;
19262 }
19263 
19264 TypeResult Sema::ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D) {
19265   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
19266   QualType T = TInfo->getType();
19267   if (D.isInvalidType())
19268     return true;
19269 
19270   if (getLangOpts().CPlusPlus) {
19271     // Check that there are no default arguments (C++ only).
19272     CheckExtraCXXDefaultArguments(D);
19273   }
19274 
19275   return CreateParsedType(T, TInfo);
19276 }
19277 
19278 QualType Sema::ActOnOpenMPDeclareMapperType(SourceLocation TyLoc,
19279                                             TypeResult ParsedType) {
19280   assert(ParsedType.isUsable() && "Expect usable parsed mapper type");
19281 
19282   QualType MapperType = GetTypeFromParser(ParsedType.get());
19283   assert(!MapperType.isNull() && "Expect valid mapper type");
19284 
19285   // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
19286   //  The type must be of struct, union or class type in C and C++
19287   if (!MapperType->isStructureOrClassType() && !MapperType->isUnionType()) {
19288     Diag(TyLoc, diag::err_omp_mapper_wrong_type);
19289     return QualType();
19290   }
19291   return MapperType;
19292 }
19293 
19294 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareMapperDirective(
19295     Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType,
19296     SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS,
19297     Expr *MapperVarRef, ArrayRef<OMPClause *> Clauses, Decl *PrevDeclInScope) {
19298   LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPMapperName,
19299                       forRedeclarationInCurContext());
19300   // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
19301   //  A mapper-identifier may not be redeclared in the current scope for the
19302   //  same type or for a type that is compatible according to the base language
19303   //  rules.
19304   llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
19305   OMPDeclareMapperDecl *PrevDMD = nullptr;
19306   bool InCompoundScope = true;
19307   if (S != nullptr) {
19308     // Find previous declaration with the same name not referenced in other
19309     // declarations.
19310     FunctionScopeInfo *ParentFn = getEnclosingFunction();
19311     InCompoundScope =
19312         (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
19313     LookupName(Lookup, S);
19314     FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
19315                          /*AllowInlineNamespace=*/false);
19316     llvm::DenseMap<OMPDeclareMapperDecl *, bool> UsedAsPrevious;
19317     LookupResult::Filter Filter = Lookup.makeFilter();
19318     while (Filter.hasNext()) {
19319       auto *PrevDecl = cast<OMPDeclareMapperDecl>(Filter.next());
19320       if (InCompoundScope) {
19321         auto I = UsedAsPrevious.find(PrevDecl);
19322         if (I == UsedAsPrevious.end())
19323           UsedAsPrevious[PrevDecl] = false;
19324         if (OMPDeclareMapperDecl *D = PrevDecl->getPrevDeclInScope())
19325           UsedAsPrevious[D] = true;
19326       }
19327       PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
19328           PrevDecl->getLocation();
19329     }
19330     Filter.done();
19331     if (InCompoundScope) {
19332       for (const auto &PrevData : UsedAsPrevious) {
19333         if (!PrevData.second) {
19334           PrevDMD = PrevData.first;
19335           break;
19336         }
19337       }
19338     }
19339   } else if (PrevDeclInScope) {
19340     auto *PrevDMDInScope = PrevDMD =
19341         cast<OMPDeclareMapperDecl>(PrevDeclInScope);
19342     do {
19343       PreviousRedeclTypes[PrevDMDInScope->getType().getCanonicalType()] =
19344           PrevDMDInScope->getLocation();
19345       PrevDMDInScope = PrevDMDInScope->getPrevDeclInScope();
19346     } while (PrevDMDInScope != nullptr);
19347   }
19348   const auto I = PreviousRedeclTypes.find(MapperType.getCanonicalType());
19349   bool Invalid = false;
19350   if (I != PreviousRedeclTypes.end()) {
19351     Diag(StartLoc, diag::err_omp_declare_mapper_redefinition)
19352         << MapperType << Name;
19353     Diag(I->second, diag::note_previous_definition);
19354     Invalid = true;
19355   }
19356   // Build expressions for implicit maps of data members with 'default'
19357   // mappers.
19358   SmallVector<OMPClause *, 4> ClausesWithImplicit(Clauses.begin(),
19359                                                   Clauses.end());
19360   if (LangOpts.OpenMP >= 50)
19361     processImplicitMapsWithDefaultMappers(*this, DSAStack, ClausesWithImplicit);
19362   auto *DMD =
19363       OMPDeclareMapperDecl::Create(Context, DC, StartLoc, Name, MapperType, VN,
19364                                    ClausesWithImplicit, PrevDMD);
19365   if (S)
19366     PushOnScopeChains(DMD, S);
19367   else
19368     DC->addDecl(DMD);
19369   DMD->setAccess(AS);
19370   if (Invalid)
19371     DMD->setInvalidDecl();
19372 
19373   auto *VD = cast<DeclRefExpr>(MapperVarRef)->getDecl();
19374   VD->setDeclContext(DMD);
19375   VD->setLexicalDeclContext(DMD);
19376   DMD->addDecl(VD);
19377   DMD->setMapperVarRef(MapperVarRef);
19378 
19379   return DeclGroupPtrTy::make(DeclGroupRef(DMD));
19380 }
19381 
19382 ExprResult
19383 Sema::ActOnOpenMPDeclareMapperDirectiveVarDecl(Scope *S, QualType MapperType,
19384                                                SourceLocation StartLoc,
19385                                                DeclarationName VN) {
19386   TypeSourceInfo *TInfo =
19387       Context.getTrivialTypeSourceInfo(MapperType, StartLoc);
19388   auto *VD = VarDecl::Create(Context, Context.getTranslationUnitDecl(),
19389                              StartLoc, StartLoc, VN.getAsIdentifierInfo(),
19390                              MapperType, TInfo, SC_None);
19391   if (S)
19392     PushOnScopeChains(VD, S, /*AddToContext=*/false);
19393   Expr *E = buildDeclRefExpr(*this, VD, MapperType, StartLoc);
19394   DSAStack->addDeclareMapperVarRef(E);
19395   return E;
19396 }
19397 
19398 bool Sema::isOpenMPDeclareMapperVarDeclAllowed(const VarDecl *VD) const {
19399   assert(LangOpts.OpenMP && "Expected OpenMP mode.");
19400   const Expr *Ref = DSAStack->getDeclareMapperVarRef();
19401   if (const auto *DRE = cast_or_null<DeclRefExpr>(Ref))
19402     return VD->getCanonicalDecl() == DRE->getDecl()->getCanonicalDecl();
19403   return true;
19404 }
19405 
19406 const ValueDecl *Sema::getOpenMPDeclareMapperVarName() const {
19407   assert(LangOpts.OpenMP && "Expected OpenMP mode.");
19408   return cast<DeclRefExpr>(DSAStack->getDeclareMapperVarRef())->getDecl();
19409 }
19410 
19411 OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
19412                                            SourceLocation StartLoc,
19413                                            SourceLocation LParenLoc,
19414                                            SourceLocation EndLoc) {
19415   Expr *ValExpr = NumTeams;
19416   Stmt *HelperValStmt = nullptr;
19417 
19418   // OpenMP [teams Constrcut, Restrictions]
19419   // The num_teams expression must evaluate to a positive integer value.
19420   if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
19421                                  /*StrictlyPositive=*/true))
19422     return nullptr;
19423 
19424   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
19425   OpenMPDirectiveKind CaptureRegion =
19426       getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams, LangOpts.OpenMP);
19427   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
19428     ValExpr = MakeFullExpr(ValExpr).get();
19429     llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
19430     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
19431     HelperValStmt = buildPreInits(Context, Captures);
19432   }
19433 
19434   return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
19435                                          StartLoc, LParenLoc, EndLoc);
19436 }
19437 
19438 OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
19439                                               SourceLocation StartLoc,
19440                                               SourceLocation LParenLoc,
19441                                               SourceLocation EndLoc) {
19442   Expr *ValExpr = ThreadLimit;
19443   Stmt *HelperValStmt = nullptr;
19444 
19445   // OpenMP [teams Constrcut, Restrictions]
19446   // The thread_limit expression must evaluate to a positive integer value.
19447   if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
19448                                  /*StrictlyPositive=*/true))
19449     return nullptr;
19450 
19451   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
19452   OpenMPDirectiveKind CaptureRegion = getOpenMPCaptureRegionForClause(
19453       DKind, OMPC_thread_limit, LangOpts.OpenMP);
19454   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
19455     ValExpr = MakeFullExpr(ValExpr).get();
19456     llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
19457     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
19458     HelperValStmt = buildPreInits(Context, Captures);
19459   }
19460 
19461   return new (Context) OMPThreadLimitClause(
19462       ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
19463 }
19464 
19465 OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
19466                                            SourceLocation StartLoc,
19467                                            SourceLocation LParenLoc,
19468                                            SourceLocation EndLoc) {
19469   Expr *ValExpr = Priority;
19470   Stmt *HelperValStmt = nullptr;
19471   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
19472 
19473   // OpenMP [2.9.1, task Constrcut]
19474   // The priority-value is a non-negative numerical scalar expression.
19475   if (!isNonNegativeIntegerValue(
19476           ValExpr, *this, OMPC_priority,
19477           /*StrictlyPositive=*/false, /*BuildCapture=*/true,
19478           DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt))
19479     return nullptr;
19480 
19481   return new (Context) OMPPriorityClause(ValExpr, HelperValStmt, CaptureRegion,
19482                                          StartLoc, LParenLoc, EndLoc);
19483 }
19484 
19485 OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
19486                                             SourceLocation StartLoc,
19487                                             SourceLocation LParenLoc,
19488                                             SourceLocation EndLoc) {
19489   Expr *ValExpr = Grainsize;
19490   Stmt *HelperValStmt = nullptr;
19491   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
19492 
19493   // OpenMP [2.9.2, taskloop Constrcut]
19494   // The parameter of the grainsize clause must be a positive integer
19495   // expression.
19496   if (!isNonNegativeIntegerValue(
19497           ValExpr, *this, OMPC_grainsize,
19498           /*StrictlyPositive=*/true, /*BuildCapture=*/true,
19499           DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt))
19500     return nullptr;
19501 
19502   return new (Context) OMPGrainsizeClause(ValExpr, HelperValStmt, CaptureRegion,
19503                                           StartLoc, LParenLoc, EndLoc);
19504 }
19505 
19506 OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
19507                                            SourceLocation StartLoc,
19508                                            SourceLocation LParenLoc,
19509                                            SourceLocation EndLoc) {
19510   Expr *ValExpr = NumTasks;
19511   Stmt *HelperValStmt = nullptr;
19512   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
19513 
19514   // OpenMP [2.9.2, taskloop Constrcut]
19515   // The parameter of the num_tasks clause must be a positive integer
19516   // expression.
19517   if (!isNonNegativeIntegerValue(
19518           ValExpr, *this, OMPC_num_tasks,
19519           /*StrictlyPositive=*/true, /*BuildCapture=*/true,
19520           DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt))
19521     return nullptr;
19522 
19523   return new (Context) OMPNumTasksClause(ValExpr, HelperValStmt, CaptureRegion,
19524                                          StartLoc, LParenLoc, EndLoc);
19525 }
19526 
19527 OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
19528                                        SourceLocation LParenLoc,
19529                                        SourceLocation EndLoc) {
19530   // OpenMP [2.13.2, critical construct, Description]
19531   // ... where hint-expression is an integer constant expression that evaluates
19532   // to a valid lock hint.
19533   ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
19534   if (HintExpr.isInvalid())
19535     return nullptr;
19536   return new (Context)
19537       OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
19538 }
19539 
19540 /// Tries to find omp_event_handle_t type.
19541 static bool findOMPEventHandleT(Sema &S, SourceLocation Loc,
19542                                 DSAStackTy *Stack) {
19543   QualType OMPEventHandleT = Stack->getOMPEventHandleT();
19544   if (!OMPEventHandleT.isNull())
19545     return true;
19546   IdentifierInfo *II = &S.PP.getIdentifierTable().get("omp_event_handle_t");
19547   ParsedType PT = S.getTypeName(*II, Loc, S.getCurScope());
19548   if (!PT.getAsOpaquePtr() || PT.get().isNull()) {
19549     S.Diag(Loc, diag::err_omp_implied_type_not_found) << "omp_event_handle_t";
19550     return false;
19551   }
19552   Stack->setOMPEventHandleT(PT.get());
19553   return true;
19554 }
19555 
19556 OMPClause *Sema::ActOnOpenMPDetachClause(Expr *Evt, SourceLocation StartLoc,
19557                                          SourceLocation LParenLoc,
19558                                          SourceLocation EndLoc) {
19559   if (!Evt->isValueDependent() && !Evt->isTypeDependent() &&
19560       !Evt->isInstantiationDependent() &&
19561       !Evt->containsUnexpandedParameterPack()) {
19562     if (!findOMPEventHandleT(*this, Evt->getExprLoc(), DSAStack))
19563       return nullptr;
19564     // OpenMP 5.0, 2.10.1 task Construct.
19565     // event-handle is a variable of the omp_event_handle_t type.
19566     auto *Ref = dyn_cast<DeclRefExpr>(Evt->IgnoreParenImpCasts());
19567     if (!Ref) {
19568       Diag(Evt->getExprLoc(), diag::err_omp_var_expected)
19569           << "omp_event_handle_t" << 0 << Evt->getSourceRange();
19570       return nullptr;
19571     }
19572     auto *VD = dyn_cast_or_null<VarDecl>(Ref->getDecl());
19573     if (!VD) {
19574       Diag(Evt->getExprLoc(), diag::err_omp_var_expected)
19575           << "omp_event_handle_t" << 0 << Evt->getSourceRange();
19576       return nullptr;
19577     }
19578     if (!Context.hasSameUnqualifiedType(DSAStack->getOMPEventHandleT(),
19579                                         VD->getType()) ||
19580         VD->getType().isConstant(Context)) {
19581       Diag(Evt->getExprLoc(), diag::err_omp_var_expected)
19582           << "omp_event_handle_t" << 1 << VD->getType()
19583           << Evt->getSourceRange();
19584       return nullptr;
19585     }
19586     // OpenMP 5.0, 2.10.1 task Construct
19587     // [detach clause]... The event-handle will be considered as if it was
19588     // specified on a firstprivate clause.
19589     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, /*FromParent=*/false);
19590     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
19591         DVar.RefExpr) {
19592       Diag(Evt->getExprLoc(), diag::err_omp_wrong_dsa)
19593           << getOpenMPClauseName(DVar.CKind)
19594           << getOpenMPClauseName(OMPC_firstprivate);
19595       reportOriginalDsa(*this, DSAStack, VD, DVar);
19596       return nullptr;
19597     }
19598   }
19599 
19600   return new (Context) OMPDetachClause(Evt, StartLoc, LParenLoc, EndLoc);
19601 }
19602 
19603 OMPClause *Sema::ActOnOpenMPDistScheduleClause(
19604     OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
19605     SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
19606     SourceLocation EndLoc) {
19607   if (Kind == OMPC_DIST_SCHEDULE_unknown) {
19608     std::string Values;
19609     Values += "'";
19610     Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
19611     Values += "'";
19612     Diag(KindLoc, diag::err_omp_unexpected_clause_value)
19613         << Values << getOpenMPClauseName(OMPC_dist_schedule);
19614     return nullptr;
19615   }
19616   Expr *ValExpr = ChunkSize;
19617   Stmt *HelperValStmt = nullptr;
19618   if (ChunkSize) {
19619     if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
19620         !ChunkSize->isInstantiationDependent() &&
19621         !ChunkSize->containsUnexpandedParameterPack()) {
19622       SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
19623       ExprResult Val =
19624           PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
19625       if (Val.isInvalid())
19626         return nullptr;
19627 
19628       ValExpr = Val.get();
19629 
19630       // OpenMP [2.7.1, Restrictions]
19631       //  chunk_size must be a loop invariant integer expression with a positive
19632       //  value.
19633       if (Optional<llvm::APSInt> Result =
19634               ValExpr->getIntegerConstantExpr(Context)) {
19635         if (Result->isSigned() && !Result->isStrictlyPositive()) {
19636           Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
19637               << "dist_schedule" << ChunkSize->getSourceRange();
19638           return nullptr;
19639         }
19640       } else if (getOpenMPCaptureRegionForClause(
19641                      DSAStack->getCurrentDirective(), OMPC_dist_schedule,
19642                      LangOpts.OpenMP) != OMPD_unknown &&
19643                  !CurContext->isDependentContext()) {
19644         ValExpr = MakeFullExpr(ValExpr).get();
19645         llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
19646         ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
19647         HelperValStmt = buildPreInits(Context, Captures);
19648       }
19649     }
19650   }
19651 
19652   return new (Context)
19653       OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
19654                             Kind, ValExpr, HelperValStmt);
19655 }
19656 
19657 OMPClause *Sema::ActOnOpenMPDefaultmapClause(
19658     OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
19659     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
19660     SourceLocation KindLoc, SourceLocation EndLoc) {
19661   if (getLangOpts().OpenMP < 50) {
19662     if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom ||
19663         Kind != OMPC_DEFAULTMAP_scalar) {
19664       std::string Value;
19665       SourceLocation Loc;
19666       Value += "'";
19667       if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
19668         Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
19669                                                OMPC_DEFAULTMAP_MODIFIER_tofrom);
19670         Loc = MLoc;
19671       } else {
19672         Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
19673                                                OMPC_DEFAULTMAP_scalar);
19674         Loc = KindLoc;
19675       }
19676       Value += "'";
19677       Diag(Loc, diag::err_omp_unexpected_clause_value)
19678           << Value << getOpenMPClauseName(OMPC_defaultmap);
19679       return nullptr;
19680     }
19681   } else {
19682     bool isDefaultmapModifier = (M != OMPC_DEFAULTMAP_MODIFIER_unknown);
19683     bool isDefaultmapKind = (Kind != OMPC_DEFAULTMAP_unknown) ||
19684                             (LangOpts.OpenMP >= 50 && KindLoc.isInvalid());
19685     if (!isDefaultmapKind || !isDefaultmapModifier) {
19686       StringRef KindValue = "'scalar', 'aggregate', 'pointer'";
19687       if (LangOpts.OpenMP == 50) {
19688         StringRef ModifierValue = "'alloc', 'from', 'to', 'tofrom', "
19689                                   "'firstprivate', 'none', 'default'";
19690         if (!isDefaultmapKind && isDefaultmapModifier) {
19691           Diag(KindLoc, diag::err_omp_unexpected_clause_value)
19692               << KindValue << getOpenMPClauseName(OMPC_defaultmap);
19693         } else if (isDefaultmapKind && !isDefaultmapModifier) {
19694           Diag(MLoc, diag::err_omp_unexpected_clause_value)
19695               << ModifierValue << getOpenMPClauseName(OMPC_defaultmap);
19696         } else {
19697           Diag(MLoc, diag::err_omp_unexpected_clause_value)
19698               << ModifierValue << getOpenMPClauseName(OMPC_defaultmap);
19699           Diag(KindLoc, diag::err_omp_unexpected_clause_value)
19700               << KindValue << getOpenMPClauseName(OMPC_defaultmap);
19701         }
19702       } else {
19703         StringRef ModifierValue =
19704             "'alloc', 'from', 'to', 'tofrom', "
19705             "'firstprivate', 'none', 'default', 'present'";
19706         if (!isDefaultmapKind && isDefaultmapModifier) {
19707           Diag(KindLoc, diag::err_omp_unexpected_clause_value)
19708               << KindValue << getOpenMPClauseName(OMPC_defaultmap);
19709         } else if (isDefaultmapKind && !isDefaultmapModifier) {
19710           Diag(MLoc, diag::err_omp_unexpected_clause_value)
19711               << ModifierValue << getOpenMPClauseName(OMPC_defaultmap);
19712         } else {
19713           Diag(MLoc, diag::err_omp_unexpected_clause_value)
19714               << ModifierValue << getOpenMPClauseName(OMPC_defaultmap);
19715           Diag(KindLoc, diag::err_omp_unexpected_clause_value)
19716               << KindValue << getOpenMPClauseName(OMPC_defaultmap);
19717         }
19718       }
19719       return nullptr;
19720     }
19721 
19722     // OpenMP [5.0, 2.12.5, Restrictions, p. 174]
19723     //  At most one defaultmap clause for each category can appear on the
19724     //  directive.
19725     if (DSAStack->checkDefaultmapCategory(Kind)) {
19726       Diag(StartLoc, diag::err_omp_one_defaultmap_each_category);
19727       return nullptr;
19728     }
19729   }
19730   if (Kind == OMPC_DEFAULTMAP_unknown) {
19731     // Variable category is not specified - mark all categories.
19732     DSAStack->setDefaultDMAAttr(M, OMPC_DEFAULTMAP_aggregate, StartLoc);
19733     DSAStack->setDefaultDMAAttr(M, OMPC_DEFAULTMAP_scalar, StartLoc);
19734     DSAStack->setDefaultDMAAttr(M, OMPC_DEFAULTMAP_pointer, StartLoc);
19735   } else {
19736     DSAStack->setDefaultDMAAttr(M, Kind, StartLoc);
19737   }
19738 
19739   return new (Context)
19740       OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
19741 }
19742 
19743 bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
19744   DeclContext *CurLexicalContext = getCurLexicalContext();
19745   if (!CurLexicalContext->isFileContext() &&
19746       !CurLexicalContext->isExternCContext() &&
19747       !CurLexicalContext->isExternCXXContext() &&
19748       !isa<CXXRecordDecl>(CurLexicalContext) &&
19749       !isa<ClassTemplateDecl>(CurLexicalContext) &&
19750       !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) &&
19751       !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) {
19752     Diag(Loc, diag::err_omp_region_not_file_context);
19753     return false;
19754   }
19755   DeclareTargetNesting.push_back(Loc);
19756   return true;
19757 }
19758 
19759 void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
19760   assert(!DeclareTargetNesting.empty() &&
19761          "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
19762   DeclareTargetNesting.pop_back();
19763 }
19764 
19765 NamedDecl *
19766 Sema::lookupOpenMPDeclareTargetName(Scope *CurScope, CXXScopeSpec &ScopeSpec,
19767                                     const DeclarationNameInfo &Id,
19768                                     NamedDeclSetType &SameDirectiveDecls) {
19769   LookupResult Lookup(*this, Id, LookupOrdinaryName);
19770   LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
19771 
19772   if (Lookup.isAmbiguous())
19773     return nullptr;
19774   Lookup.suppressDiagnostics();
19775 
19776   if (!Lookup.isSingleResult()) {
19777     VarOrFuncDeclFilterCCC CCC(*this);
19778     if (TypoCorrection Corrected =
19779             CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC,
19780                         CTK_ErrorRecovery)) {
19781       diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
19782                                   << Id.getName());
19783       checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
19784       return nullptr;
19785     }
19786 
19787     Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
19788     return nullptr;
19789   }
19790 
19791   NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
19792   if (!isa<VarDecl>(ND) && !isa<FunctionDecl>(ND) &&
19793       !isa<FunctionTemplateDecl>(ND)) {
19794     Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
19795     return nullptr;
19796   }
19797   if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
19798     Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
19799   return ND;
19800 }
19801 
19802 void Sema::ActOnOpenMPDeclareTargetName(
19803     NamedDecl *ND, SourceLocation Loc, OMPDeclareTargetDeclAttr::MapTypeTy MT,
19804     OMPDeclareTargetDeclAttr::DevTypeTy DT) {
19805   assert((isa<VarDecl>(ND) || isa<FunctionDecl>(ND) ||
19806           isa<FunctionTemplateDecl>(ND)) &&
19807          "Expected variable, function or function template.");
19808 
19809   // Diagnose marking after use as it may lead to incorrect diagnosis and
19810   // codegen.
19811   if (LangOpts.OpenMP >= 50 &&
19812       (ND->isUsed(/*CheckUsedAttr=*/false) || ND->isReferenced()))
19813     Diag(Loc, diag::warn_omp_declare_target_after_first_use);
19814 
19815   auto *VD = cast<ValueDecl>(ND);
19816   Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
19817       OMPDeclareTargetDeclAttr::getDeviceType(VD);
19818   Optional<SourceLocation> AttrLoc = OMPDeclareTargetDeclAttr::getLocation(VD);
19819   if (DevTy.hasValue() && *DevTy != DT &&
19820       (DeclareTargetNesting.empty() ||
19821        *AttrLoc != DeclareTargetNesting.back())) {
19822     Diag(Loc, diag::err_omp_device_type_mismatch)
19823         << OMPDeclareTargetDeclAttr::ConvertDevTypeTyToStr(DT)
19824         << OMPDeclareTargetDeclAttr::ConvertDevTypeTyToStr(*DevTy);
19825     return;
19826   }
19827   Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
19828       OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
19829   if (!Res || (!DeclareTargetNesting.empty() &&
19830                *AttrLoc == DeclareTargetNesting.back())) {
19831     auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(
19832         Context, MT, DT, DeclareTargetNesting.size() + 1,
19833         SourceRange(Loc, Loc));
19834     ND->addAttr(A);
19835     if (ASTMutationListener *ML = Context.getASTMutationListener())
19836       ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
19837     checkDeclIsAllowedInOpenMPTarget(nullptr, ND, Loc);
19838   } else if (*Res != MT) {
19839     Diag(Loc, diag::err_omp_declare_target_to_and_link) << ND;
19840   }
19841 }
19842 
19843 static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
19844                                      Sema &SemaRef, Decl *D) {
19845   if (!D || !isa<VarDecl>(D))
19846     return;
19847   auto *VD = cast<VarDecl>(D);
19848   Optional<OMPDeclareTargetDeclAttr::MapTypeTy> MapTy =
19849       OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
19850   if (SemaRef.LangOpts.OpenMP >= 50 &&
19851       (SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true) ||
19852        SemaRef.getCurBlock() || SemaRef.getCurCapturedRegion()) &&
19853       VD->hasGlobalStorage()) {
19854     llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> MapTy =
19855         OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
19856     if (!MapTy || *MapTy != OMPDeclareTargetDeclAttr::MT_To) {
19857       // OpenMP 5.0, 2.12.7 declare target Directive, Restrictions
19858       // If a lambda declaration and definition appears between a
19859       // declare target directive and the matching end declare target
19860       // directive, all variables that are captured by the lambda
19861       // expression must also appear in a to clause.
19862       SemaRef.Diag(VD->getLocation(),
19863                    diag::err_omp_lambda_capture_in_declare_target_not_to);
19864       SemaRef.Diag(SL, diag::note_var_explicitly_captured_here)
19865           << VD << 0 << SR;
19866       return;
19867     }
19868   }
19869   if (MapTy.hasValue())
19870     return;
19871   SemaRef.Diag(VD->getLocation(), diag::warn_omp_not_in_target_context);
19872   SemaRef.Diag(SL, diag::note_used_here) << SR;
19873 }
19874 
19875 static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
19876                                    Sema &SemaRef, DSAStackTy *Stack,
19877                                    ValueDecl *VD) {
19878   return OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD) ||
19879          checkTypeMappable(SL, SR, SemaRef, Stack, VD->getType(),
19880                            /*FullCheck=*/false);
19881 }
19882 
19883 void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
19884                                             SourceLocation IdLoc) {
19885   if (!D || D->isInvalidDecl())
19886     return;
19887   SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
19888   SourceLocation SL = E ? E->getBeginLoc() : D->getLocation();
19889   if (auto *VD = dyn_cast<VarDecl>(D)) {
19890     // Only global variables can be marked as declare target.
19891     if (!VD->isFileVarDecl() && !VD->isStaticLocal() &&
19892         !VD->isStaticDataMember())
19893       return;
19894     // 2.10.6: threadprivate variable cannot appear in a declare target
19895     // directive.
19896     if (DSAStack->isThreadPrivate(VD)) {
19897       Diag(SL, diag::err_omp_threadprivate_in_target);
19898       reportOriginalDsa(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
19899       return;
19900     }
19901   }
19902   if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(D))
19903     D = FTD->getTemplatedDecl();
19904   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
19905     llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
19906         OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(FD);
19907     if (IdLoc.isValid() && Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) {
19908       Diag(IdLoc, diag::err_omp_function_in_link_clause);
19909       Diag(FD->getLocation(), diag::note_defined_here) << FD;
19910       return;
19911     }
19912   }
19913   if (auto *VD = dyn_cast<ValueDecl>(D)) {
19914     // Problem if any with var declared with incomplete type will be reported
19915     // as normal, so no need to check it here.
19916     if ((E || !VD->getType()->isIncompleteType()) &&
19917         !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD))
19918       return;
19919     if (!E && !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
19920       // Checking declaration inside declare target region.
19921       if (isa<VarDecl>(D) || isa<FunctionDecl>(D) ||
19922           isa<FunctionTemplateDecl>(D)) {
19923         auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(
19924             Context, OMPDeclareTargetDeclAttr::MT_To,
19925             OMPDeclareTargetDeclAttr::DT_Any, DeclareTargetNesting.size(),
19926             SourceRange(DeclareTargetNesting.back(),
19927                         DeclareTargetNesting.back()));
19928         D->addAttr(A);
19929         if (ASTMutationListener *ML = Context.getASTMutationListener())
19930           ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
19931       }
19932       return;
19933     }
19934   }
19935   if (!E)
19936     return;
19937   checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
19938 }
19939 
19940 OMPClause *Sema::ActOnOpenMPToClause(
19941     ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
19942     ArrayRef<SourceLocation> MotionModifiersLoc,
19943     CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId,
19944     SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
19945     const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) {
19946   OpenMPMotionModifierKind Modifiers[] = {OMPC_MOTION_MODIFIER_unknown,
19947                                           OMPC_MOTION_MODIFIER_unknown};
19948   SourceLocation ModifiersLoc[NumberOfOMPMotionModifiers];
19949 
19950   // Process motion-modifiers, flag errors for duplicate modifiers.
19951   unsigned Count = 0;
19952   for (unsigned I = 0, E = MotionModifiers.size(); I < E; ++I) {
19953     if (MotionModifiers[I] != OMPC_MOTION_MODIFIER_unknown &&
19954         llvm::find(Modifiers, MotionModifiers[I]) != std::end(Modifiers)) {
19955       Diag(MotionModifiersLoc[I], diag::err_omp_duplicate_motion_modifier);
19956       continue;
19957     }
19958     assert(Count < NumberOfOMPMotionModifiers &&
19959            "Modifiers exceed the allowed number of motion modifiers");
19960     Modifiers[Count] = MotionModifiers[I];
19961     ModifiersLoc[Count] = MotionModifiersLoc[I];
19962     ++Count;
19963   }
19964 
19965   MappableVarListInfo MVLI(VarList);
19966   checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, Locs.StartLoc,
19967                               MapperIdScopeSpec, MapperId, UnresolvedMappers);
19968   if (MVLI.ProcessedVarList.empty())
19969     return nullptr;
19970 
19971   return OMPToClause::Create(
19972       Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
19973       MVLI.VarComponents, MVLI.UDMapperList, Modifiers, ModifiersLoc,
19974       MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
19975 }
19976 
19977 OMPClause *Sema::ActOnOpenMPFromClause(
19978     ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
19979     ArrayRef<SourceLocation> MotionModifiersLoc,
19980     CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId,
19981     SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
19982     const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) {
19983   OpenMPMotionModifierKind Modifiers[] = {OMPC_MOTION_MODIFIER_unknown,
19984                                           OMPC_MOTION_MODIFIER_unknown};
19985   SourceLocation ModifiersLoc[NumberOfOMPMotionModifiers];
19986 
19987   // Process motion-modifiers, flag errors for duplicate modifiers.
19988   unsigned Count = 0;
19989   for (unsigned I = 0, E = MotionModifiers.size(); I < E; ++I) {
19990     if (MotionModifiers[I] != OMPC_MOTION_MODIFIER_unknown &&
19991         llvm::find(Modifiers, MotionModifiers[I]) != std::end(Modifiers)) {
19992       Diag(MotionModifiersLoc[I], diag::err_omp_duplicate_motion_modifier);
19993       continue;
19994     }
19995     assert(Count < NumberOfOMPMotionModifiers &&
19996            "Modifiers exceed the allowed number of motion modifiers");
19997     Modifiers[Count] = MotionModifiers[I];
19998     ModifiersLoc[Count] = MotionModifiersLoc[I];
19999     ++Count;
20000   }
20001 
20002   MappableVarListInfo MVLI(VarList);
20003   checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, Locs.StartLoc,
20004                               MapperIdScopeSpec, MapperId, UnresolvedMappers);
20005   if (MVLI.ProcessedVarList.empty())
20006     return nullptr;
20007 
20008   return OMPFromClause::Create(
20009       Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
20010       MVLI.VarComponents, MVLI.UDMapperList, Modifiers, ModifiersLoc,
20011       MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
20012 }
20013 
20014 OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
20015                                                const OMPVarListLocTy &Locs) {
20016   MappableVarListInfo MVLI(VarList);
20017   SmallVector<Expr *, 8> PrivateCopies;
20018   SmallVector<Expr *, 8> Inits;
20019 
20020   for (Expr *RefExpr : VarList) {
20021     assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
20022     SourceLocation ELoc;
20023     SourceRange ERange;
20024     Expr *SimpleRefExpr = RefExpr;
20025     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
20026     if (Res.second) {
20027       // It will be analyzed later.
20028       MVLI.ProcessedVarList.push_back(RefExpr);
20029       PrivateCopies.push_back(nullptr);
20030       Inits.push_back(nullptr);
20031     }
20032     ValueDecl *D = Res.first;
20033     if (!D)
20034       continue;
20035 
20036     QualType Type = D->getType();
20037     Type = Type.getNonReferenceType().getUnqualifiedType();
20038 
20039     auto *VD = dyn_cast<VarDecl>(D);
20040 
20041     // Item should be a pointer or reference to pointer.
20042     if (!Type->isPointerType()) {
20043       Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
20044           << 0 << RefExpr->getSourceRange();
20045       continue;
20046     }
20047 
20048     // Build the private variable and the expression that refers to it.
20049     auto VDPrivate =
20050         buildVarDecl(*this, ELoc, Type, D->getName(),
20051                      D->hasAttrs() ? &D->getAttrs() : nullptr,
20052                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
20053     if (VDPrivate->isInvalidDecl())
20054       continue;
20055 
20056     CurContext->addDecl(VDPrivate);
20057     DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
20058         *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
20059 
20060     // Add temporary variable to initialize the private copy of the pointer.
20061     VarDecl *VDInit =
20062         buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
20063     DeclRefExpr *VDInitRefExpr = buildDeclRefExpr(
20064         *this, VDInit, RefExpr->getType(), RefExpr->getExprLoc());
20065     AddInitializerToDecl(VDPrivate,
20066                          DefaultLvalueConversion(VDInitRefExpr).get(),
20067                          /*DirectInit=*/false);
20068 
20069     // If required, build a capture to implement the privatization initialized
20070     // with the current list item value.
20071     DeclRefExpr *Ref = nullptr;
20072     if (!VD)
20073       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
20074     MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
20075     PrivateCopies.push_back(VDPrivateRefExpr);
20076     Inits.push_back(VDInitRefExpr);
20077 
20078     // We need to add a data sharing attribute for this variable to make sure it
20079     // is correctly captured. A variable that shows up in a use_device_ptr has
20080     // similar properties of a first private variable.
20081     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
20082 
20083     // Create a mappable component for the list item. List items in this clause
20084     // only need a component.
20085     MVLI.VarBaseDeclarations.push_back(D);
20086     MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
20087     MVLI.VarComponents.back().emplace_back(SimpleRefExpr, D,
20088                                            /*IsNonContiguous=*/false);
20089   }
20090 
20091   if (MVLI.ProcessedVarList.empty())
20092     return nullptr;
20093 
20094   return OMPUseDevicePtrClause::Create(
20095       Context, Locs, MVLI.ProcessedVarList, PrivateCopies, Inits,
20096       MVLI.VarBaseDeclarations, MVLI.VarComponents);
20097 }
20098 
20099 OMPClause *Sema::ActOnOpenMPUseDeviceAddrClause(ArrayRef<Expr *> VarList,
20100                                                 const OMPVarListLocTy &Locs) {
20101   MappableVarListInfo MVLI(VarList);
20102 
20103   for (Expr *RefExpr : VarList) {
20104     assert(RefExpr && "NULL expr in OpenMP use_device_addr clause.");
20105     SourceLocation ELoc;
20106     SourceRange ERange;
20107     Expr *SimpleRefExpr = RefExpr;
20108     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
20109                               /*AllowArraySection=*/true);
20110     if (Res.second) {
20111       // It will be analyzed later.
20112       MVLI.ProcessedVarList.push_back(RefExpr);
20113     }
20114     ValueDecl *D = Res.first;
20115     if (!D)
20116       continue;
20117     auto *VD = dyn_cast<VarDecl>(D);
20118 
20119     // If required, build a capture to implement the privatization initialized
20120     // with the current list item value.
20121     DeclRefExpr *Ref = nullptr;
20122     if (!VD)
20123       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
20124     MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
20125 
20126     // We need to add a data sharing attribute for this variable to make sure it
20127     // is correctly captured. A variable that shows up in a use_device_addr has
20128     // similar properties of a first private variable.
20129     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
20130 
20131     // Create a mappable component for the list item. List items in this clause
20132     // only need a component.
20133     MVLI.VarBaseDeclarations.push_back(D);
20134     MVLI.VarComponents.emplace_back();
20135     Expr *Component = SimpleRefExpr;
20136     if (VD && (isa<OMPArraySectionExpr>(RefExpr->IgnoreParenImpCasts()) ||
20137                isa<ArraySubscriptExpr>(RefExpr->IgnoreParenImpCasts())))
20138       Component = DefaultFunctionArrayLvalueConversion(SimpleRefExpr).get();
20139     MVLI.VarComponents.back().emplace_back(Component, D,
20140                                            /*IsNonContiguous=*/false);
20141   }
20142 
20143   if (MVLI.ProcessedVarList.empty())
20144     return nullptr;
20145 
20146   return OMPUseDeviceAddrClause::Create(Context, Locs, MVLI.ProcessedVarList,
20147                                         MVLI.VarBaseDeclarations,
20148                                         MVLI.VarComponents);
20149 }
20150 
20151 OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
20152                                               const OMPVarListLocTy &Locs) {
20153   MappableVarListInfo MVLI(VarList);
20154   for (Expr *RefExpr : VarList) {
20155     assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
20156     SourceLocation ELoc;
20157     SourceRange ERange;
20158     Expr *SimpleRefExpr = RefExpr;
20159     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
20160     if (Res.second) {
20161       // It will be analyzed later.
20162       MVLI.ProcessedVarList.push_back(RefExpr);
20163     }
20164     ValueDecl *D = Res.first;
20165     if (!D)
20166       continue;
20167 
20168     QualType Type = D->getType();
20169     // item should be a pointer or array or reference to pointer or array
20170     if (!Type.getNonReferenceType()->isPointerType() &&
20171         !Type.getNonReferenceType()->isArrayType()) {
20172       Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
20173           << 0 << RefExpr->getSourceRange();
20174       continue;
20175     }
20176 
20177     // Check if the declaration in the clause does not show up in any data
20178     // sharing attribute.
20179     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
20180     if (isOpenMPPrivate(DVar.CKind)) {
20181       Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
20182           << getOpenMPClauseName(DVar.CKind)
20183           << getOpenMPClauseName(OMPC_is_device_ptr)
20184           << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
20185       reportOriginalDsa(*this, DSAStack, D, DVar);
20186       continue;
20187     }
20188 
20189     const Expr *ConflictExpr;
20190     if (DSAStack->checkMappableExprComponentListsForDecl(
20191             D, /*CurrentRegionOnly=*/true,
20192             [&ConflictExpr](
20193                 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
20194                 OpenMPClauseKind) -> bool {
20195               ConflictExpr = R.front().getAssociatedExpression();
20196               return true;
20197             })) {
20198       Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
20199       Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
20200           << ConflictExpr->getSourceRange();
20201       continue;
20202     }
20203 
20204     // Store the components in the stack so that they can be used to check
20205     // against other clauses later on.
20206     OMPClauseMappableExprCommon::MappableComponent MC(
20207         SimpleRefExpr, D, /*IsNonContiguous=*/false);
20208     DSAStack->addMappableExpressionComponents(
20209         D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
20210 
20211     // Record the expression we've just processed.
20212     MVLI.ProcessedVarList.push_back(SimpleRefExpr);
20213 
20214     // Create a mappable component for the list item. List items in this clause
20215     // only need a component. We use a null declaration to signal fields in
20216     // 'this'.
20217     assert((isa<DeclRefExpr>(SimpleRefExpr) ||
20218             isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
20219            "Unexpected device pointer expression!");
20220     MVLI.VarBaseDeclarations.push_back(
20221         isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
20222     MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
20223     MVLI.VarComponents.back().push_back(MC);
20224   }
20225 
20226   if (MVLI.ProcessedVarList.empty())
20227     return nullptr;
20228 
20229   return OMPIsDevicePtrClause::Create(Context, Locs, MVLI.ProcessedVarList,
20230                                       MVLI.VarBaseDeclarations,
20231                                       MVLI.VarComponents);
20232 }
20233 
20234 OMPClause *Sema::ActOnOpenMPAllocateClause(
20235     Expr *Allocator, ArrayRef<Expr *> VarList, SourceLocation StartLoc,
20236     SourceLocation ColonLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
20237   if (Allocator) {
20238     // OpenMP [2.11.4 allocate Clause, Description]
20239     // allocator is an expression of omp_allocator_handle_t type.
20240     if (!findOMPAllocatorHandleT(*this, Allocator->getExprLoc(), DSAStack))
20241       return nullptr;
20242 
20243     ExprResult AllocatorRes = DefaultLvalueConversion(Allocator);
20244     if (AllocatorRes.isInvalid())
20245       return nullptr;
20246     AllocatorRes = PerformImplicitConversion(AllocatorRes.get(),
20247                                              DSAStack->getOMPAllocatorHandleT(),
20248                                              Sema::AA_Initializing,
20249                                              /*AllowExplicit=*/true);
20250     if (AllocatorRes.isInvalid())
20251       return nullptr;
20252     Allocator = AllocatorRes.get();
20253   } else {
20254     // OpenMP 5.0, 2.11.4 allocate Clause, Restrictions.
20255     // allocate clauses that appear on a target construct or on constructs in a
20256     // target region must specify an allocator expression unless a requires
20257     // directive with the dynamic_allocators clause is present in the same
20258     // compilation unit.
20259     if (LangOpts.OpenMPIsDevice &&
20260         !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())
20261       targetDiag(StartLoc, diag::err_expected_allocator_expression);
20262   }
20263   // Analyze and build list of variables.
20264   SmallVector<Expr *, 8> Vars;
20265   for (Expr *RefExpr : VarList) {
20266     assert(RefExpr && "NULL expr in OpenMP private clause.");
20267     SourceLocation ELoc;
20268     SourceRange ERange;
20269     Expr *SimpleRefExpr = RefExpr;
20270     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
20271     if (Res.second) {
20272       // It will be analyzed later.
20273       Vars.push_back(RefExpr);
20274     }
20275     ValueDecl *D = Res.first;
20276     if (!D)
20277       continue;
20278 
20279     auto *VD = dyn_cast<VarDecl>(D);
20280     DeclRefExpr *Ref = nullptr;
20281     if (!VD && !CurContext->isDependentContext())
20282       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
20283     Vars.push_back((VD || CurContext->isDependentContext())
20284                        ? RefExpr->IgnoreParens()
20285                        : Ref);
20286   }
20287 
20288   if (Vars.empty())
20289     return nullptr;
20290 
20291   if (Allocator)
20292     DSAStack->addInnerAllocatorExpr(Allocator);
20293   return OMPAllocateClause::Create(Context, StartLoc, LParenLoc, Allocator,
20294                                    ColonLoc, EndLoc, Vars);
20295 }
20296 
20297 OMPClause *Sema::ActOnOpenMPNontemporalClause(ArrayRef<Expr *> VarList,
20298                                               SourceLocation StartLoc,
20299                                               SourceLocation LParenLoc,
20300                                               SourceLocation EndLoc) {
20301   SmallVector<Expr *, 8> Vars;
20302   for (Expr *RefExpr : VarList) {
20303     assert(RefExpr && "NULL expr in OpenMP nontemporal clause.");
20304     SourceLocation ELoc;
20305     SourceRange ERange;
20306     Expr *SimpleRefExpr = RefExpr;
20307     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
20308     if (Res.second)
20309       // It will be analyzed later.
20310       Vars.push_back(RefExpr);
20311     ValueDecl *D = Res.first;
20312     if (!D)
20313       continue;
20314 
20315     // OpenMP 5.0, 2.9.3.1 simd Construct, Restrictions.
20316     // A list-item cannot appear in more than one nontemporal clause.
20317     if (const Expr *PrevRef =
20318             DSAStack->addUniqueNontemporal(D, SimpleRefExpr)) {
20319       Diag(ELoc, diag::err_omp_used_in_clause_twice)
20320           << 0 << getOpenMPClauseName(OMPC_nontemporal) << ERange;
20321       Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
20322           << getOpenMPClauseName(OMPC_nontemporal);
20323       continue;
20324     }
20325 
20326     Vars.push_back(RefExpr);
20327   }
20328 
20329   if (Vars.empty())
20330     return nullptr;
20331 
20332   return OMPNontemporalClause::Create(Context, StartLoc, LParenLoc, EndLoc,
20333                                       Vars);
20334 }
20335 
20336 OMPClause *Sema::ActOnOpenMPInclusiveClause(ArrayRef<Expr *> VarList,
20337                                             SourceLocation StartLoc,
20338                                             SourceLocation LParenLoc,
20339                                             SourceLocation EndLoc) {
20340   SmallVector<Expr *, 8> Vars;
20341   for (Expr *RefExpr : VarList) {
20342     assert(RefExpr && "NULL expr in OpenMP nontemporal clause.");
20343     SourceLocation ELoc;
20344     SourceRange ERange;
20345     Expr *SimpleRefExpr = RefExpr;
20346     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
20347                               /*AllowArraySection=*/true);
20348     if (Res.second)
20349       // It will be analyzed later.
20350       Vars.push_back(RefExpr);
20351     ValueDecl *D = Res.first;
20352     if (!D)
20353       continue;
20354 
20355     const DSAStackTy::DSAVarData DVar =
20356         DSAStack->getTopDSA(D, /*FromParent=*/true);
20357     // OpenMP 5.0, 2.9.6, scan Directive, Restrictions.
20358     // A list item that appears in the inclusive or exclusive clause must appear
20359     // in a reduction clause with the inscan modifier on the enclosing
20360     // worksharing-loop, worksharing-loop SIMD, or simd construct.
20361     if (DVar.CKind != OMPC_reduction ||
20362         DVar.Modifier != OMPC_REDUCTION_inscan)
20363       Diag(ELoc, diag::err_omp_inclusive_exclusive_not_reduction)
20364           << RefExpr->getSourceRange();
20365 
20366     if (DSAStack->getParentDirective() != OMPD_unknown)
20367       DSAStack->markDeclAsUsedInScanDirective(D);
20368     Vars.push_back(RefExpr);
20369   }
20370 
20371   if (Vars.empty())
20372     return nullptr;
20373 
20374   return OMPInclusiveClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
20375 }
20376 
20377 OMPClause *Sema::ActOnOpenMPExclusiveClause(ArrayRef<Expr *> VarList,
20378                                             SourceLocation StartLoc,
20379                                             SourceLocation LParenLoc,
20380                                             SourceLocation EndLoc) {
20381   SmallVector<Expr *, 8> Vars;
20382   for (Expr *RefExpr : VarList) {
20383     assert(RefExpr && "NULL expr in OpenMP nontemporal clause.");
20384     SourceLocation ELoc;
20385     SourceRange ERange;
20386     Expr *SimpleRefExpr = RefExpr;
20387     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
20388                               /*AllowArraySection=*/true);
20389     if (Res.second)
20390       // It will be analyzed later.
20391       Vars.push_back(RefExpr);
20392     ValueDecl *D = Res.first;
20393     if (!D)
20394       continue;
20395 
20396     OpenMPDirectiveKind ParentDirective = DSAStack->getParentDirective();
20397     DSAStackTy::DSAVarData DVar;
20398     if (ParentDirective != OMPD_unknown)
20399       DVar = DSAStack->getTopDSA(D, /*FromParent=*/true);
20400     // OpenMP 5.0, 2.9.6, scan Directive, Restrictions.
20401     // A list item that appears in the inclusive or exclusive clause must appear
20402     // in a reduction clause with the inscan modifier on the enclosing
20403     // worksharing-loop, worksharing-loop SIMD, or simd construct.
20404     if (ParentDirective == OMPD_unknown || DVar.CKind != OMPC_reduction ||
20405         DVar.Modifier != OMPC_REDUCTION_inscan) {
20406       Diag(ELoc, diag::err_omp_inclusive_exclusive_not_reduction)
20407           << RefExpr->getSourceRange();
20408     } else {
20409       DSAStack->markDeclAsUsedInScanDirective(D);
20410     }
20411     Vars.push_back(RefExpr);
20412   }
20413 
20414   if (Vars.empty())
20415     return nullptr;
20416 
20417   return OMPExclusiveClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
20418 }
20419 
20420 /// Tries to find omp_alloctrait_t type.
20421 static bool findOMPAlloctraitT(Sema &S, SourceLocation Loc, DSAStackTy *Stack) {
20422   QualType OMPAlloctraitT = Stack->getOMPAlloctraitT();
20423   if (!OMPAlloctraitT.isNull())
20424     return true;
20425   IdentifierInfo &II = S.PP.getIdentifierTable().get("omp_alloctrait_t");
20426   ParsedType PT = S.getTypeName(II, Loc, S.getCurScope());
20427   if (!PT.getAsOpaquePtr() || PT.get().isNull()) {
20428     S.Diag(Loc, diag::err_omp_implied_type_not_found) << "omp_alloctrait_t";
20429     return false;
20430   }
20431   Stack->setOMPAlloctraitT(PT.get());
20432   return true;
20433 }
20434 
20435 OMPClause *Sema::ActOnOpenMPUsesAllocatorClause(
20436     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc,
20437     ArrayRef<UsesAllocatorsData> Data) {
20438   // OpenMP [2.12.5, target Construct]
20439   // allocator is an identifier of omp_allocator_handle_t type.
20440   if (!findOMPAllocatorHandleT(*this, StartLoc, DSAStack))
20441     return nullptr;
20442   // OpenMP [2.12.5, target Construct]
20443   // allocator-traits-array is an identifier of const omp_alloctrait_t * type.
20444   if (llvm::any_of(
20445           Data,
20446           [](const UsesAllocatorsData &D) { return D.AllocatorTraits; }) &&
20447       !findOMPAlloctraitT(*this, StartLoc, DSAStack))
20448     return nullptr;
20449   llvm::SmallPtrSet<CanonicalDeclPtr<Decl>, 4> PredefinedAllocators;
20450   for (int I = 0; I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
20451     auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
20452     StringRef Allocator =
20453         OMPAllocateDeclAttr::ConvertAllocatorTypeTyToStr(AllocatorKind);
20454     DeclarationName AllocatorName = &Context.Idents.get(Allocator);
20455     PredefinedAllocators.insert(LookupSingleName(
20456         TUScope, AllocatorName, StartLoc, Sema::LookupAnyName));
20457   }
20458 
20459   SmallVector<OMPUsesAllocatorsClause::Data, 4> NewData;
20460   for (const UsesAllocatorsData &D : Data) {
20461     Expr *AllocatorExpr = nullptr;
20462     // Check allocator expression.
20463     if (D.Allocator->isTypeDependent()) {
20464       AllocatorExpr = D.Allocator;
20465     } else {
20466       // Traits were specified - need to assign new allocator to the specified
20467       // allocator, so it must be an lvalue.
20468       AllocatorExpr = D.Allocator->IgnoreParenImpCasts();
20469       auto *DRE = dyn_cast<DeclRefExpr>(AllocatorExpr);
20470       bool IsPredefinedAllocator = false;
20471       if (DRE)
20472         IsPredefinedAllocator = PredefinedAllocators.count(DRE->getDecl());
20473       if (!DRE ||
20474           !(Context.hasSameUnqualifiedType(
20475                 AllocatorExpr->getType(), DSAStack->getOMPAllocatorHandleT()) ||
20476             Context.typesAreCompatible(AllocatorExpr->getType(),
20477                                        DSAStack->getOMPAllocatorHandleT(),
20478                                        /*CompareUnqualified=*/true)) ||
20479           (!IsPredefinedAllocator &&
20480            (AllocatorExpr->getType().isConstant(Context) ||
20481             !AllocatorExpr->isLValue()))) {
20482         Diag(D.Allocator->getExprLoc(), diag::err_omp_var_expected)
20483             << "omp_allocator_handle_t" << (DRE ? 1 : 0)
20484             << AllocatorExpr->getType() << D.Allocator->getSourceRange();
20485         continue;
20486       }
20487       // OpenMP [2.12.5, target Construct]
20488       // Predefined allocators appearing in a uses_allocators clause cannot have
20489       // traits specified.
20490       if (IsPredefinedAllocator && D.AllocatorTraits) {
20491         Diag(D.AllocatorTraits->getExprLoc(),
20492              diag::err_omp_predefined_allocator_with_traits)
20493             << D.AllocatorTraits->getSourceRange();
20494         Diag(D.Allocator->getExprLoc(), diag::note_omp_predefined_allocator)
20495             << cast<NamedDecl>(DRE->getDecl())->getName()
20496             << D.Allocator->getSourceRange();
20497         continue;
20498       }
20499       // OpenMP [2.12.5, target Construct]
20500       // Non-predefined allocators appearing in a uses_allocators clause must
20501       // have traits specified.
20502       if (!IsPredefinedAllocator && !D.AllocatorTraits) {
20503         Diag(D.Allocator->getExprLoc(),
20504              diag::err_omp_nonpredefined_allocator_without_traits);
20505         continue;
20506       }
20507       // No allocator traits - just convert it to rvalue.
20508       if (!D.AllocatorTraits)
20509         AllocatorExpr = DefaultLvalueConversion(AllocatorExpr).get();
20510       DSAStack->addUsesAllocatorsDecl(
20511           DRE->getDecl(),
20512           IsPredefinedAllocator
20513               ? DSAStackTy::UsesAllocatorsDeclKind::PredefinedAllocator
20514               : DSAStackTy::UsesAllocatorsDeclKind::UserDefinedAllocator);
20515     }
20516     Expr *AllocatorTraitsExpr = nullptr;
20517     if (D.AllocatorTraits) {
20518       if (D.AllocatorTraits->isTypeDependent()) {
20519         AllocatorTraitsExpr = D.AllocatorTraits;
20520       } else {
20521         // OpenMP [2.12.5, target Construct]
20522         // Arrays that contain allocator traits that appear in a uses_allocators
20523         // clause must be constant arrays, have constant values and be defined
20524         // in the same scope as the construct in which the clause appears.
20525         AllocatorTraitsExpr = D.AllocatorTraits->IgnoreParenImpCasts();
20526         // Check that traits expr is a constant array.
20527         QualType TraitTy;
20528         if (const ArrayType *Ty =
20529                 AllocatorTraitsExpr->getType()->getAsArrayTypeUnsafe())
20530           if (const auto *ConstArrayTy = dyn_cast<ConstantArrayType>(Ty))
20531             TraitTy = ConstArrayTy->getElementType();
20532         if (TraitTy.isNull() ||
20533             !(Context.hasSameUnqualifiedType(TraitTy,
20534                                              DSAStack->getOMPAlloctraitT()) ||
20535               Context.typesAreCompatible(TraitTy, DSAStack->getOMPAlloctraitT(),
20536                                          /*CompareUnqualified=*/true))) {
20537           Diag(D.AllocatorTraits->getExprLoc(),
20538                diag::err_omp_expected_array_alloctraits)
20539               << AllocatorTraitsExpr->getType();
20540           continue;
20541         }
20542         // Do not map by default allocator traits if it is a standalone
20543         // variable.
20544         if (auto *DRE = dyn_cast<DeclRefExpr>(AllocatorTraitsExpr))
20545           DSAStack->addUsesAllocatorsDecl(
20546               DRE->getDecl(),
20547               DSAStackTy::UsesAllocatorsDeclKind::AllocatorTrait);
20548       }
20549     }
20550     OMPUsesAllocatorsClause::Data &NewD = NewData.emplace_back();
20551     NewD.Allocator = AllocatorExpr;
20552     NewD.AllocatorTraits = AllocatorTraitsExpr;
20553     NewD.LParenLoc = D.LParenLoc;
20554     NewD.RParenLoc = D.RParenLoc;
20555   }
20556   return OMPUsesAllocatorsClause::Create(Context, StartLoc, LParenLoc, EndLoc,
20557                                          NewData);
20558 }
20559 
20560 OMPClause *Sema::ActOnOpenMPAffinityClause(
20561     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
20562     SourceLocation EndLoc, Expr *Modifier, ArrayRef<Expr *> Locators) {
20563   SmallVector<Expr *, 8> Vars;
20564   for (Expr *RefExpr : Locators) {
20565     assert(RefExpr && "NULL expr in OpenMP shared clause.");
20566     if (isa<DependentScopeDeclRefExpr>(RefExpr) || RefExpr->isTypeDependent()) {
20567       // It will be analyzed later.
20568       Vars.push_back(RefExpr);
20569       continue;
20570     }
20571 
20572     SourceLocation ELoc = RefExpr->getExprLoc();
20573     Expr *SimpleExpr = RefExpr->IgnoreParenImpCasts();
20574 
20575     if (!SimpleExpr->isLValue()) {
20576       Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
20577           << 1 << 0 << RefExpr->getSourceRange();
20578       continue;
20579     }
20580 
20581     ExprResult Res;
20582     {
20583       Sema::TentativeAnalysisScope Trap(*this);
20584       Res = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, SimpleExpr);
20585     }
20586     if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr) &&
20587         !isa<OMPArrayShapingExpr>(SimpleExpr)) {
20588       Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
20589           << 1 << 0 << RefExpr->getSourceRange();
20590       continue;
20591     }
20592     Vars.push_back(SimpleExpr);
20593   }
20594 
20595   return OMPAffinityClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
20596                                    EndLoc, Modifier, Vars);
20597 }
20598