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/OMPAssume.h"
40 #include "llvm/Frontend/OpenMP/OMPConstants.h"
41 #include <set>
42 
43 using namespace clang;
44 using namespace llvm::omp;
45 
46 //===----------------------------------------------------------------------===//
47 // Stack of data-sharing attributes for variables
48 //===----------------------------------------------------------------------===//
49 
50 static const Expr *checkMapClauseExpressionBase(
51     Sema &SemaRef, Expr *E,
52     OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
53     OpenMPClauseKind CKind, OpenMPDirectiveKind DKind, bool NoDiagnose);
54 
55 namespace {
56 /// Default data sharing attributes, which can be applied to directive.
57 enum DefaultDataSharingAttributes {
58   DSA_unspecified = 0,       /// Data sharing attribute not specified.
59   DSA_none = 1 << 0,         /// Default data sharing attribute 'none'.
60   DSA_shared = 1 << 1,       /// Default data sharing attribute 'shared'.
61   DSA_firstprivate = 1 << 2, /// Default data sharing attribute 'firstprivate'.
62 };
63 
64 /// Stack for tracking declarations used in OpenMP directives and
65 /// clauses and their data-sharing attributes.
66 class DSAStackTy {
67 public:
68   struct DSAVarData {
69     OpenMPDirectiveKind DKind = OMPD_unknown;
70     OpenMPClauseKind CKind = OMPC_unknown;
71     unsigned Modifier = 0;
72     const Expr *RefExpr = nullptr;
73     DeclRefExpr *PrivateCopy = nullptr;
74     SourceLocation ImplicitDSALoc;
75     bool AppliedToPointee = false;
76     DSAVarData() = default;
77     DSAVarData(OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
78                const Expr *RefExpr, DeclRefExpr *PrivateCopy,
79                SourceLocation ImplicitDSALoc, unsigned Modifier,
80                bool AppliedToPointee)
81         : DKind(DKind), CKind(CKind), Modifier(Modifier), RefExpr(RefExpr),
82           PrivateCopy(PrivateCopy), ImplicitDSALoc(ImplicitDSALoc),
83           AppliedToPointee(AppliedToPointee) {}
84   };
85   using OperatorOffsetTy =
86       llvm::SmallVector<std::pair<Expr *, OverloadedOperatorKind>, 4>;
87   using DoacrossDependMapTy =
88       llvm::DenseMap<OMPDependClause *, OperatorOffsetTy>;
89   /// Kind of the declaration used in the uses_allocators clauses.
90   enum class UsesAllocatorsDeclKind {
91     /// Predefined allocator
92     PredefinedAllocator,
93     /// User-defined allocator
94     UserDefinedAllocator,
95     /// The declaration that represent allocator trait
96     AllocatorTrait,
97   };
98 
99 private:
100   struct DSAInfo {
101     OpenMPClauseKind Attributes = OMPC_unknown;
102     unsigned Modifier = 0;
103     /// Pointer to a reference expression and a flag which shows that the
104     /// variable is marked as lastprivate(true) or not (false).
105     llvm::PointerIntPair<const Expr *, 1, bool> RefExpr;
106     DeclRefExpr *PrivateCopy = nullptr;
107     /// true if the attribute is applied to the pointee, not the variable
108     /// itself.
109     bool AppliedToPointee = false;
110   };
111   using DeclSAMapTy = llvm::SmallDenseMap<const ValueDecl *, DSAInfo, 8>;
112   using UsedRefMapTy = llvm::SmallDenseMap<const ValueDecl *, const Expr *, 8>;
113   using LCDeclInfo = std::pair<unsigned, VarDecl *>;
114   using LoopControlVariablesMapTy =
115       llvm::SmallDenseMap<const ValueDecl *, LCDeclInfo, 8>;
116   /// Struct that associates a component with the clause kind where they are
117   /// found.
118   struct MappedExprComponentTy {
119     OMPClauseMappableExprCommon::MappableExprComponentLists Components;
120     OpenMPClauseKind Kind = OMPC_unknown;
121   };
122   using MappedExprComponentsTy =
123       llvm::DenseMap<const ValueDecl *, MappedExprComponentTy>;
124   using CriticalsWithHintsTy =
125       llvm::StringMap<std::pair<const OMPCriticalDirective *, llvm::APSInt>>;
126   struct ReductionData {
127     using BOKPtrType = llvm::PointerEmbeddedInt<BinaryOperatorKind, 16>;
128     SourceRange ReductionRange;
129     llvm::PointerUnion<const Expr *, BOKPtrType> ReductionOp;
130     ReductionData() = default;
131     void set(BinaryOperatorKind BO, SourceRange RR) {
132       ReductionRange = RR;
133       ReductionOp = BO;
134     }
135     void set(const Expr *RefExpr, SourceRange RR) {
136       ReductionRange = RR;
137       ReductionOp = RefExpr;
138     }
139   };
140   using DeclReductionMapTy =
141       llvm::SmallDenseMap<const ValueDecl *, ReductionData, 4>;
142   struct DefaultmapInfo {
143     OpenMPDefaultmapClauseModifier ImplicitBehavior =
144         OMPC_DEFAULTMAP_MODIFIER_unknown;
145     SourceLocation SLoc;
146     DefaultmapInfo() = default;
147     DefaultmapInfo(OpenMPDefaultmapClauseModifier M, SourceLocation Loc)
148         : ImplicitBehavior(M), SLoc(Loc) {}
149   };
150 
151   struct SharingMapTy {
152     DeclSAMapTy SharingMap;
153     DeclReductionMapTy ReductionMap;
154     UsedRefMapTy AlignedMap;
155     UsedRefMapTy NontemporalMap;
156     MappedExprComponentsTy MappedExprComponents;
157     LoopControlVariablesMapTy LCVMap;
158     DefaultDataSharingAttributes DefaultAttr = DSA_unspecified;
159     SourceLocation DefaultAttrLoc;
160     DefaultmapInfo DefaultmapMap[OMPC_DEFAULTMAP_unknown];
161     OpenMPDirectiveKind Directive = OMPD_unknown;
162     DeclarationNameInfo DirectiveName;
163     Scope *CurScope = nullptr;
164     DeclContext *Context = nullptr;
165     SourceLocation ConstructLoc;
166     /// Set of 'depend' clauses with 'sink|source' dependence kind. Required to
167     /// get the data (loop counters etc.) about enclosing loop-based construct.
168     /// This data is required during codegen.
169     DoacrossDependMapTy DoacrossDepends;
170     /// First argument (Expr *) contains optional argument of the
171     /// 'ordered' clause, the second one is true if the regions has 'ordered'
172     /// clause, false otherwise.
173     llvm::Optional<std::pair<const Expr *, OMPOrderedClause *>> OrderedRegion;
174     unsigned AssociatedLoops = 1;
175     bool HasMutipleLoops = false;
176     const Decl *PossiblyLoopCounter = nullptr;
177     bool NowaitRegion = false;
178     bool CancelRegion = false;
179     bool LoopStart = false;
180     bool BodyComplete = false;
181     SourceLocation PrevScanLocation;
182     SourceLocation PrevOrderedLocation;
183     SourceLocation InnerTeamsRegionLoc;
184     /// Reference to the taskgroup task_reduction reference expression.
185     Expr *TaskgroupReductionRef = nullptr;
186     llvm::DenseSet<QualType> MappedClassesQualTypes;
187     SmallVector<Expr *, 4> InnerUsedAllocators;
188     llvm::DenseSet<CanonicalDeclPtr<Decl>> ImplicitTaskFirstprivates;
189     /// List of globals marked as declare target link in this target region
190     /// (isOpenMPTargetExecutionDirective(Directive) == true).
191     llvm::SmallVector<DeclRefExpr *, 4> DeclareTargetLinkVarDecls;
192     /// List of decls used in inclusive/exclusive clauses of the scan directive.
193     llvm::DenseSet<CanonicalDeclPtr<Decl>> UsedInScanDirective;
194     llvm::DenseMap<CanonicalDeclPtr<const Decl>, UsesAllocatorsDeclKind>
195         UsesAllocatorsDecls;
196     Expr *DeclareMapperVar = nullptr;
197     SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
198                  Scope *CurScope, SourceLocation Loc)
199         : Directive(DKind), DirectiveName(Name), CurScope(CurScope),
200           ConstructLoc(Loc) {}
201     SharingMapTy() = default;
202   };
203 
204   using StackTy = SmallVector<SharingMapTy, 4>;
205 
206   /// Stack of used declaration and their data-sharing attributes.
207   DeclSAMapTy Threadprivates;
208   const FunctionScopeInfo *CurrentNonCapturingFunctionScope = nullptr;
209   SmallVector<std::pair<StackTy, const FunctionScopeInfo *>, 4> Stack;
210   /// true, if check for DSA must be from parent directive, false, if
211   /// from current directive.
212   OpenMPClauseKind ClauseKindMode = OMPC_unknown;
213   Sema &SemaRef;
214   bool ForceCapturing = false;
215   /// true if all the variables in the target executable directives must be
216   /// captured by reference.
217   bool ForceCaptureByReferenceInTargetExecutable = false;
218   CriticalsWithHintsTy Criticals;
219   unsigned IgnoredStackElements = 0;
220 
221   /// Iterators over the stack iterate in order from innermost to outermost
222   /// directive.
223   using const_iterator = StackTy::const_reverse_iterator;
224   const_iterator begin() const {
225     return Stack.empty() ? const_iterator()
226                          : Stack.back().first.rbegin() + IgnoredStackElements;
227   }
228   const_iterator end() const {
229     return Stack.empty() ? const_iterator() : Stack.back().first.rend();
230   }
231   using iterator = StackTy::reverse_iterator;
232   iterator begin() {
233     return Stack.empty() ? iterator()
234                          : Stack.back().first.rbegin() + IgnoredStackElements;
235   }
236   iterator end() {
237     return Stack.empty() ? iterator() : Stack.back().first.rend();
238   }
239 
240   // Convenience operations to get at the elements of the stack.
241 
242   bool isStackEmpty() const {
243     return Stack.empty() ||
244            Stack.back().second != CurrentNonCapturingFunctionScope ||
245            Stack.back().first.size() <= IgnoredStackElements;
246   }
247   size_t getStackSize() const {
248     return isStackEmpty() ? 0
249                           : Stack.back().first.size() - IgnoredStackElements;
250   }
251 
252   SharingMapTy *getTopOfStackOrNull() {
253     size_t Size = getStackSize();
254     if (Size == 0)
255       return nullptr;
256     return &Stack.back().first[Size - 1];
257   }
258   const SharingMapTy *getTopOfStackOrNull() const {
259     return const_cast<DSAStackTy &>(*this).getTopOfStackOrNull();
260   }
261   SharingMapTy &getTopOfStack() {
262     assert(!isStackEmpty() && "no current directive");
263     return *getTopOfStackOrNull();
264   }
265   const SharingMapTy &getTopOfStack() const {
266     return const_cast<DSAStackTy &>(*this).getTopOfStack();
267   }
268 
269   SharingMapTy *getSecondOnStackOrNull() {
270     size_t Size = getStackSize();
271     if (Size <= 1)
272       return nullptr;
273     return &Stack.back().first[Size - 2];
274   }
275   const SharingMapTy *getSecondOnStackOrNull() const {
276     return const_cast<DSAStackTy &>(*this).getSecondOnStackOrNull();
277   }
278 
279   /// Get the stack element at a certain level (previously returned by
280   /// \c getNestingLevel).
281   ///
282   /// Note that nesting levels count from outermost to innermost, and this is
283   /// the reverse of our iteration order where new inner levels are pushed at
284   /// the front of the stack.
285   SharingMapTy &getStackElemAtLevel(unsigned Level) {
286     assert(Level < getStackSize() && "no such stack element");
287     return Stack.back().first[Level];
288   }
289   const SharingMapTy &getStackElemAtLevel(unsigned Level) const {
290     return const_cast<DSAStackTy &>(*this).getStackElemAtLevel(Level);
291   }
292 
293   DSAVarData getDSA(const_iterator &Iter, ValueDecl *D) const;
294 
295   /// Checks if the variable is a local for OpenMP region.
296   bool isOpenMPLocal(VarDecl *D, const_iterator Iter) const;
297 
298   /// Vector of previously declared requires directives
299   SmallVector<const OMPRequiresDecl *, 2> RequiresDecls;
300   /// omp_allocator_handle_t type.
301   QualType OMPAllocatorHandleT;
302   /// omp_depend_t type.
303   QualType OMPDependT;
304   /// omp_event_handle_t type.
305   QualType OMPEventHandleT;
306   /// omp_alloctrait_t type.
307   QualType OMPAlloctraitT;
308   /// Expression for the predefined allocators.
309   Expr *OMPPredefinedAllocators[OMPAllocateDeclAttr::OMPUserDefinedMemAlloc] = {
310       nullptr};
311   /// Vector of previously encountered target directives
312   SmallVector<SourceLocation, 2> TargetLocations;
313   SourceLocation AtomicLocation;
314   /// Vector of declare variant construct traits.
315   SmallVector<llvm::omp::TraitProperty, 8> ConstructTraits;
316 
317 public:
318   explicit DSAStackTy(Sema &S) : SemaRef(S) {}
319 
320   /// Sets omp_allocator_handle_t type.
321   void setOMPAllocatorHandleT(QualType Ty) { OMPAllocatorHandleT = Ty; }
322   /// Gets omp_allocator_handle_t type.
323   QualType getOMPAllocatorHandleT() const { return OMPAllocatorHandleT; }
324   /// Sets omp_alloctrait_t type.
325   void setOMPAlloctraitT(QualType Ty) { OMPAlloctraitT = Ty; }
326   /// Gets omp_alloctrait_t type.
327   QualType getOMPAlloctraitT() const { return OMPAlloctraitT; }
328   /// Sets the given default allocator.
329   void setAllocator(OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind,
330                     Expr *Allocator) {
331     OMPPredefinedAllocators[AllocatorKind] = Allocator;
332   }
333   /// Returns the specified default allocator.
334   Expr *getAllocator(OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind) const {
335     return OMPPredefinedAllocators[AllocatorKind];
336   }
337   /// Sets omp_depend_t type.
338   void setOMPDependT(QualType Ty) { OMPDependT = Ty; }
339   /// Gets omp_depend_t type.
340   QualType getOMPDependT() const { return OMPDependT; }
341 
342   /// Sets omp_event_handle_t type.
343   void setOMPEventHandleT(QualType Ty) { OMPEventHandleT = Ty; }
344   /// Gets omp_event_handle_t type.
345   QualType getOMPEventHandleT() const { return OMPEventHandleT; }
346 
347   bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
348   OpenMPClauseKind getClauseParsingMode() const {
349     assert(isClauseParsingMode() && "Must be in clause parsing mode.");
350     return ClauseKindMode;
351   }
352   void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
353 
354   bool isBodyComplete() const {
355     const SharingMapTy *Top = getTopOfStackOrNull();
356     return Top && Top->BodyComplete;
357   }
358   void setBodyComplete() { getTopOfStack().BodyComplete = true; }
359 
360   bool isForceVarCapturing() const { return ForceCapturing; }
361   void setForceVarCapturing(bool V) { ForceCapturing = V; }
362 
363   void setForceCaptureByReferenceInTargetExecutable(bool V) {
364     ForceCaptureByReferenceInTargetExecutable = V;
365   }
366   bool isForceCaptureByReferenceInTargetExecutable() const {
367     return ForceCaptureByReferenceInTargetExecutable;
368   }
369 
370   void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
371             Scope *CurScope, SourceLocation Loc) {
372     assert(!IgnoredStackElements &&
373            "cannot change stack while ignoring elements");
374     if (Stack.empty() ||
375         Stack.back().second != CurrentNonCapturingFunctionScope)
376       Stack.emplace_back(StackTy(), CurrentNonCapturingFunctionScope);
377     Stack.back().first.emplace_back(DKind, DirName, CurScope, Loc);
378     Stack.back().first.back().DefaultAttrLoc = Loc;
379   }
380 
381   void pop() {
382     assert(!IgnoredStackElements &&
383            "cannot change stack while ignoring elements");
384     assert(!Stack.back().first.empty() &&
385            "Data-sharing attributes stack is empty!");
386     Stack.back().first.pop_back();
387   }
388 
389   /// RAII object to temporarily leave the scope of a directive when we want to
390   /// logically operate in its parent.
391   class ParentDirectiveScope {
392     DSAStackTy &Self;
393     bool Active;
394 
395   public:
396     ParentDirectiveScope(DSAStackTy &Self, bool Activate)
397         : Self(Self), Active(false) {
398       if (Activate)
399         enable();
400     }
401     ~ParentDirectiveScope() { disable(); }
402     void disable() {
403       if (Active) {
404         --Self.IgnoredStackElements;
405         Active = false;
406       }
407     }
408     void enable() {
409       if (!Active) {
410         ++Self.IgnoredStackElements;
411         Active = true;
412       }
413     }
414   };
415 
416   /// Marks that we're started loop parsing.
417   void loopInit() {
418     assert(isOpenMPLoopDirective(getCurrentDirective()) &&
419            "Expected loop-based directive.");
420     getTopOfStack().LoopStart = true;
421   }
422   /// Start capturing of the variables in the loop context.
423   void loopStart() {
424     assert(isOpenMPLoopDirective(getCurrentDirective()) &&
425            "Expected loop-based directive.");
426     getTopOfStack().LoopStart = false;
427   }
428   /// true, if variables are captured, false otherwise.
429   bool isLoopStarted() const {
430     assert(isOpenMPLoopDirective(getCurrentDirective()) &&
431            "Expected loop-based directive.");
432     return !getTopOfStack().LoopStart;
433   }
434   /// Marks (or clears) declaration as possibly loop counter.
435   void resetPossibleLoopCounter(const Decl *D = nullptr) {
436     getTopOfStack().PossiblyLoopCounter = D ? D->getCanonicalDecl() : D;
437   }
438   /// Gets the possible loop counter decl.
439   const Decl *getPossiblyLoopCunter() const {
440     return getTopOfStack().PossiblyLoopCounter;
441   }
442   /// Start new OpenMP region stack in new non-capturing function.
443   void pushFunction() {
444     assert(!IgnoredStackElements &&
445            "cannot change stack while ignoring elements");
446     const FunctionScopeInfo *CurFnScope = SemaRef.getCurFunction();
447     assert(!isa<CapturingScopeInfo>(CurFnScope));
448     CurrentNonCapturingFunctionScope = CurFnScope;
449   }
450   /// Pop region stack for non-capturing function.
451   void popFunction(const FunctionScopeInfo *OldFSI) {
452     assert(!IgnoredStackElements &&
453            "cannot change stack while ignoring elements");
454     if (!Stack.empty() && Stack.back().second == OldFSI) {
455       assert(Stack.back().first.empty());
456       Stack.pop_back();
457     }
458     CurrentNonCapturingFunctionScope = nullptr;
459     for (const FunctionScopeInfo *FSI : llvm::reverse(SemaRef.FunctionScopes)) {
460       if (!isa<CapturingScopeInfo>(FSI)) {
461         CurrentNonCapturingFunctionScope = FSI;
462         break;
463       }
464     }
465   }
466 
467   void addCriticalWithHint(const OMPCriticalDirective *D, llvm::APSInt Hint) {
468     Criticals.try_emplace(D->getDirectiveName().getAsString(), D, Hint);
469   }
470   const std::pair<const OMPCriticalDirective *, llvm::APSInt>
471   getCriticalWithHint(const DeclarationNameInfo &Name) const {
472     auto I = Criticals.find(Name.getAsString());
473     if (I != Criticals.end())
474       return I->second;
475     return std::make_pair(nullptr, llvm::APSInt());
476   }
477   /// If 'aligned' declaration for given variable \a D was not seen yet,
478   /// add it and return NULL; otherwise return previous occurrence's expression
479   /// for diagnostics.
480   const Expr *addUniqueAligned(const ValueDecl *D, const Expr *NewDE);
481   /// If 'nontemporal' declaration for given variable \a D was not seen yet,
482   /// add it and return NULL; otherwise return previous occurrence's expression
483   /// for diagnostics.
484   const Expr *addUniqueNontemporal(const ValueDecl *D, const Expr *NewDE);
485 
486   /// Register specified variable as loop control variable.
487   void addLoopControlVariable(const ValueDecl *D, VarDecl *Capture);
488   /// Check if the specified variable is a loop control variable for
489   /// current region.
490   /// \return The index of the loop control variable in the list of associated
491   /// for-loops (from outer to inner).
492   const LCDeclInfo isLoopControlVariable(const ValueDecl *D) const;
493   /// Check if the specified variable is a loop control variable for
494   /// parent region.
495   /// \return The index of the loop control variable in the list of associated
496   /// for-loops (from outer to inner).
497   const LCDeclInfo isParentLoopControlVariable(const ValueDecl *D) const;
498   /// Check if the specified variable is a loop control variable for
499   /// current region.
500   /// \return The index of the loop control variable in the list of associated
501   /// for-loops (from outer to inner).
502   const LCDeclInfo isLoopControlVariable(const ValueDecl *D,
503                                          unsigned Level) const;
504   /// Get the loop control variable for the I-th loop (or nullptr) in
505   /// parent directive.
506   const ValueDecl *getParentLoopControlVariable(unsigned I) const;
507 
508   /// Marks the specified decl \p D as used in scan directive.
509   void markDeclAsUsedInScanDirective(ValueDecl *D) {
510     if (SharingMapTy *Stack = getSecondOnStackOrNull())
511       Stack->UsedInScanDirective.insert(D);
512   }
513 
514   /// Checks if the specified declaration was used in the inner scan directive.
515   bool isUsedInScanDirective(ValueDecl *D) const {
516     if (const SharingMapTy *Stack = getTopOfStackOrNull())
517       return Stack->UsedInScanDirective.contains(D);
518     return false;
519   }
520 
521   /// Adds explicit data sharing attribute to the specified declaration.
522   void addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
523               DeclRefExpr *PrivateCopy = nullptr, unsigned Modifier = 0,
524               bool AppliedToPointee = false);
525 
526   /// Adds additional information for the reduction items with the reduction id
527   /// represented as an operator.
528   void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
529                                  BinaryOperatorKind BOK);
530   /// Adds additional information for the reduction items with the reduction id
531   /// represented as reduction identifier.
532   void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
533                                  const Expr *ReductionRef);
534   /// Returns the location and reduction operation from the innermost parent
535   /// region for the given \p D.
536   const DSAVarData
537   getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
538                                    BinaryOperatorKind &BOK,
539                                    Expr *&TaskgroupDescriptor) const;
540   /// Returns the location and reduction operation from the innermost parent
541   /// region for the given \p D.
542   const DSAVarData
543   getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
544                                    const Expr *&ReductionRef,
545                                    Expr *&TaskgroupDescriptor) const;
546   /// Return reduction reference expression for the current taskgroup or
547   /// parallel/worksharing directives with task reductions.
548   Expr *getTaskgroupReductionRef() const {
549     assert((getTopOfStack().Directive == OMPD_taskgroup ||
550             ((isOpenMPParallelDirective(getTopOfStack().Directive) ||
551               isOpenMPWorksharingDirective(getTopOfStack().Directive)) &&
552              !isOpenMPSimdDirective(getTopOfStack().Directive))) &&
553            "taskgroup reference expression requested for non taskgroup or "
554            "parallel/worksharing directive.");
555     return getTopOfStack().TaskgroupReductionRef;
556   }
557   /// Checks if the given \p VD declaration is actually a taskgroup reduction
558   /// descriptor variable at the \p Level of OpenMP regions.
559   bool isTaskgroupReductionRef(const ValueDecl *VD, unsigned Level) const {
560     return getStackElemAtLevel(Level).TaskgroupReductionRef &&
561            cast<DeclRefExpr>(getStackElemAtLevel(Level).TaskgroupReductionRef)
562                    ->getDecl() == VD;
563   }
564 
565   /// Returns data sharing attributes from top of the stack for the
566   /// specified declaration.
567   const DSAVarData getTopDSA(ValueDecl *D, bool FromParent);
568   /// Returns data-sharing attributes for the specified declaration.
569   const DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent) const;
570   /// Returns data-sharing attributes for the specified declaration.
571   const DSAVarData getImplicitDSA(ValueDecl *D, unsigned Level) const;
572   /// Checks if the specified variables has data-sharing attributes which
573   /// match specified \a CPred predicate in any directive which matches \a DPred
574   /// predicate.
575   const DSAVarData
576   hasDSA(ValueDecl *D,
577          const llvm::function_ref<bool(OpenMPClauseKind, bool)> CPred,
578          const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
579          bool FromParent) const;
580   /// Checks if the specified variables has data-sharing attributes which
581   /// match specified \a CPred predicate in any innermost directive which
582   /// matches \a DPred predicate.
583   const DSAVarData
584   hasInnermostDSA(ValueDecl *D,
585                   const llvm::function_ref<bool(OpenMPClauseKind, bool)> CPred,
586                   const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
587                   bool FromParent) const;
588   /// Checks if the specified variables has explicit data-sharing
589   /// attributes which match specified \a CPred predicate at the specified
590   /// OpenMP region.
591   bool
592   hasExplicitDSA(const ValueDecl *D,
593                  const llvm::function_ref<bool(OpenMPClauseKind, bool)> CPred,
594                  unsigned Level, bool NotLastprivate = false) const;
595 
596   /// Returns true if the directive at level \Level matches in the
597   /// specified \a DPred predicate.
598   bool hasExplicitDirective(
599       const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
600       unsigned Level) const;
601 
602   /// Finds a directive which matches specified \a DPred predicate.
603   bool hasDirective(
604       const llvm::function_ref<bool(
605           OpenMPDirectiveKind, const DeclarationNameInfo &, SourceLocation)>
606           DPred,
607       bool FromParent) const;
608 
609   /// Returns currently analyzed directive.
610   OpenMPDirectiveKind getCurrentDirective() const {
611     const SharingMapTy *Top = getTopOfStackOrNull();
612     return Top ? Top->Directive : OMPD_unknown;
613   }
614   /// Returns directive kind at specified level.
615   OpenMPDirectiveKind getDirective(unsigned Level) const {
616     assert(!isStackEmpty() && "No directive at specified level.");
617     return getStackElemAtLevel(Level).Directive;
618   }
619   /// Returns the capture region at the specified level.
620   OpenMPDirectiveKind getCaptureRegion(unsigned Level,
621                                        unsigned OpenMPCaptureLevel) const {
622     SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
623     getOpenMPCaptureRegions(CaptureRegions, getDirective(Level));
624     return CaptureRegions[OpenMPCaptureLevel];
625   }
626   /// Returns parent directive.
627   OpenMPDirectiveKind getParentDirective() const {
628     const SharingMapTy *Parent = getSecondOnStackOrNull();
629     return Parent ? Parent->Directive : OMPD_unknown;
630   }
631 
632   /// Add requires decl to internal vector
633   void addRequiresDecl(OMPRequiresDecl *RD) { RequiresDecls.push_back(RD); }
634 
635   /// Checks if the defined 'requires' directive has specified type of clause.
636   template <typename ClauseType> bool hasRequiresDeclWithClause() const {
637     return llvm::any_of(RequiresDecls, [](const OMPRequiresDecl *D) {
638       return llvm::any_of(D->clauselists(), [](const OMPClause *C) {
639         return isa<ClauseType>(C);
640       });
641     });
642   }
643 
644   /// Checks for a duplicate clause amongst previously declared requires
645   /// directives
646   bool hasDuplicateRequiresClause(ArrayRef<OMPClause *> ClauseList) const {
647     bool IsDuplicate = false;
648     for (OMPClause *CNew : ClauseList) {
649       for (const OMPRequiresDecl *D : RequiresDecls) {
650         for (const OMPClause *CPrev : D->clauselists()) {
651           if (CNew->getClauseKind() == CPrev->getClauseKind()) {
652             SemaRef.Diag(CNew->getBeginLoc(),
653                          diag::err_omp_requires_clause_redeclaration)
654                 << getOpenMPClauseName(CNew->getClauseKind());
655             SemaRef.Diag(CPrev->getBeginLoc(),
656                          diag::note_omp_requires_previous_clause)
657                 << getOpenMPClauseName(CPrev->getClauseKind());
658             IsDuplicate = true;
659           }
660         }
661       }
662     }
663     return IsDuplicate;
664   }
665 
666   /// Add location of previously encountered target to internal vector
667   void addTargetDirLocation(SourceLocation LocStart) {
668     TargetLocations.push_back(LocStart);
669   }
670 
671   /// Add location for the first encountered atomicc directive.
672   void addAtomicDirectiveLoc(SourceLocation Loc) {
673     if (AtomicLocation.isInvalid())
674       AtomicLocation = Loc;
675   }
676 
677   /// Returns the location of the first encountered atomic directive in the
678   /// module.
679   SourceLocation getAtomicDirectiveLoc() const { return AtomicLocation; }
680 
681   // Return previously encountered target region locations.
682   ArrayRef<SourceLocation> getEncounteredTargetLocs() const {
683     return TargetLocations;
684   }
685 
686   /// Set default data sharing attribute to none.
687   void setDefaultDSANone(SourceLocation Loc) {
688     getTopOfStack().DefaultAttr = DSA_none;
689     getTopOfStack().DefaultAttrLoc = Loc;
690   }
691   /// Set default data sharing attribute to shared.
692   void setDefaultDSAShared(SourceLocation Loc) {
693     getTopOfStack().DefaultAttr = DSA_shared;
694     getTopOfStack().DefaultAttrLoc = Loc;
695   }
696   /// Set default data sharing attribute to firstprivate.
697   void setDefaultDSAFirstPrivate(SourceLocation Loc) {
698     getTopOfStack().DefaultAttr = DSA_firstprivate;
699     getTopOfStack().DefaultAttrLoc = Loc;
700   }
701   /// Set default data mapping attribute to Modifier:Kind
702   void setDefaultDMAAttr(OpenMPDefaultmapClauseModifier M,
703                          OpenMPDefaultmapClauseKind Kind, SourceLocation Loc) {
704     DefaultmapInfo &DMI = getTopOfStack().DefaultmapMap[Kind];
705     DMI.ImplicitBehavior = M;
706     DMI.SLoc = Loc;
707   }
708   /// Check whether the implicit-behavior has been set in defaultmap
709   bool checkDefaultmapCategory(OpenMPDefaultmapClauseKind VariableCategory) {
710     if (VariableCategory == OMPC_DEFAULTMAP_unknown)
711       return getTopOfStack()
712                      .DefaultmapMap[OMPC_DEFAULTMAP_aggregate]
713                      .ImplicitBehavior != OMPC_DEFAULTMAP_MODIFIER_unknown ||
714              getTopOfStack()
715                      .DefaultmapMap[OMPC_DEFAULTMAP_scalar]
716                      .ImplicitBehavior != OMPC_DEFAULTMAP_MODIFIER_unknown ||
717              getTopOfStack()
718                      .DefaultmapMap[OMPC_DEFAULTMAP_pointer]
719                      .ImplicitBehavior != OMPC_DEFAULTMAP_MODIFIER_unknown;
720     return getTopOfStack().DefaultmapMap[VariableCategory].ImplicitBehavior !=
721            OMPC_DEFAULTMAP_MODIFIER_unknown;
722   }
723 
724   ArrayRef<llvm::omp::TraitProperty> getConstructTraits() {
725     return ConstructTraits;
726   }
727   void handleConstructTrait(ArrayRef<llvm::omp::TraitProperty> Traits,
728                             bool ScopeEntry) {
729     if (ScopeEntry)
730       ConstructTraits.append(Traits.begin(), Traits.end());
731     else
732       for (llvm::omp::TraitProperty Trait : llvm::reverse(Traits)) {
733         llvm::omp::TraitProperty Top = ConstructTraits.pop_back_val();
734         assert(Top == Trait && "Something left a trait on the stack!");
735         (void)Trait;
736         (void)Top;
737       }
738   }
739 
740   DefaultDataSharingAttributes getDefaultDSA(unsigned Level) const {
741     return getStackSize() <= Level ? DSA_unspecified
742                                    : getStackElemAtLevel(Level).DefaultAttr;
743   }
744   DefaultDataSharingAttributes getDefaultDSA() const {
745     return isStackEmpty() ? DSA_unspecified : getTopOfStack().DefaultAttr;
746   }
747   SourceLocation getDefaultDSALocation() const {
748     return isStackEmpty() ? SourceLocation() : getTopOfStack().DefaultAttrLoc;
749   }
750   OpenMPDefaultmapClauseModifier
751   getDefaultmapModifier(OpenMPDefaultmapClauseKind Kind) const {
752     return isStackEmpty()
753                ? OMPC_DEFAULTMAP_MODIFIER_unknown
754                : getTopOfStack().DefaultmapMap[Kind].ImplicitBehavior;
755   }
756   OpenMPDefaultmapClauseModifier
757   getDefaultmapModifierAtLevel(unsigned Level,
758                                OpenMPDefaultmapClauseKind Kind) const {
759     return getStackElemAtLevel(Level).DefaultmapMap[Kind].ImplicitBehavior;
760   }
761   bool isDefaultmapCapturedByRef(unsigned Level,
762                                  OpenMPDefaultmapClauseKind Kind) const {
763     OpenMPDefaultmapClauseModifier M =
764         getDefaultmapModifierAtLevel(Level, Kind);
765     if (Kind == OMPC_DEFAULTMAP_scalar || Kind == OMPC_DEFAULTMAP_pointer) {
766       return (M == OMPC_DEFAULTMAP_MODIFIER_alloc) ||
767              (M == OMPC_DEFAULTMAP_MODIFIER_to) ||
768              (M == OMPC_DEFAULTMAP_MODIFIER_from) ||
769              (M == OMPC_DEFAULTMAP_MODIFIER_tofrom);
770     }
771     return true;
772   }
773   static bool mustBeFirstprivateBase(OpenMPDefaultmapClauseModifier M,
774                                      OpenMPDefaultmapClauseKind Kind) {
775     switch (Kind) {
776     case OMPC_DEFAULTMAP_scalar:
777     case OMPC_DEFAULTMAP_pointer:
778       return (M == OMPC_DEFAULTMAP_MODIFIER_unknown) ||
779              (M == OMPC_DEFAULTMAP_MODIFIER_firstprivate) ||
780              (M == OMPC_DEFAULTMAP_MODIFIER_default);
781     case OMPC_DEFAULTMAP_aggregate:
782       return M == OMPC_DEFAULTMAP_MODIFIER_firstprivate;
783     default:
784       break;
785     }
786     llvm_unreachable("Unexpected OpenMPDefaultmapClauseKind enum");
787   }
788   bool mustBeFirstprivateAtLevel(unsigned Level,
789                                  OpenMPDefaultmapClauseKind Kind) const {
790     OpenMPDefaultmapClauseModifier M =
791         getDefaultmapModifierAtLevel(Level, Kind);
792     return mustBeFirstprivateBase(M, Kind);
793   }
794   bool mustBeFirstprivate(OpenMPDefaultmapClauseKind Kind) const {
795     OpenMPDefaultmapClauseModifier M = getDefaultmapModifier(Kind);
796     return mustBeFirstprivateBase(M, Kind);
797   }
798 
799   /// Checks if the specified variable is a threadprivate.
800   bool isThreadPrivate(VarDecl *D) {
801     const DSAVarData DVar = getTopDSA(D, false);
802     return isOpenMPThreadPrivate(DVar.CKind);
803   }
804 
805   /// Marks current region as ordered (it has an 'ordered' clause).
806   void setOrderedRegion(bool IsOrdered, const Expr *Param,
807                         OMPOrderedClause *Clause) {
808     if (IsOrdered)
809       getTopOfStack().OrderedRegion.emplace(Param, Clause);
810     else
811       getTopOfStack().OrderedRegion.reset();
812   }
813   /// Returns true, if region is ordered (has associated 'ordered' clause),
814   /// false - otherwise.
815   bool isOrderedRegion() const {
816     if (const SharingMapTy *Top = getTopOfStackOrNull())
817       return Top->OrderedRegion.hasValue();
818     return false;
819   }
820   /// Returns optional parameter for the ordered region.
821   std::pair<const Expr *, OMPOrderedClause *> getOrderedRegionParam() const {
822     if (const SharingMapTy *Top = getTopOfStackOrNull())
823       if (Top->OrderedRegion.hasValue())
824         return Top->OrderedRegion.getValue();
825     return std::make_pair(nullptr, nullptr);
826   }
827   /// Returns true, if parent region is ordered (has associated
828   /// 'ordered' clause), false - otherwise.
829   bool isParentOrderedRegion() const {
830     if (const SharingMapTy *Parent = getSecondOnStackOrNull())
831       return Parent->OrderedRegion.hasValue();
832     return false;
833   }
834   /// Returns optional parameter for the ordered region.
835   std::pair<const Expr *, OMPOrderedClause *>
836   getParentOrderedRegionParam() const {
837     if (const SharingMapTy *Parent = getSecondOnStackOrNull())
838       if (Parent->OrderedRegion.hasValue())
839         return Parent->OrderedRegion.getValue();
840     return std::make_pair(nullptr, nullptr);
841   }
842   /// Marks current region as nowait (it has a 'nowait' clause).
843   void setNowaitRegion(bool IsNowait = true) {
844     getTopOfStack().NowaitRegion = IsNowait;
845   }
846   /// Returns true, if parent region is nowait (has associated
847   /// 'nowait' clause), false - otherwise.
848   bool isParentNowaitRegion() const {
849     if (const SharingMapTy *Parent = getSecondOnStackOrNull())
850       return Parent->NowaitRegion;
851     return false;
852   }
853   /// Marks parent region as cancel region.
854   void setParentCancelRegion(bool Cancel = true) {
855     if (SharingMapTy *Parent = getSecondOnStackOrNull())
856       Parent->CancelRegion |= Cancel;
857   }
858   /// Return true if current region has inner cancel construct.
859   bool isCancelRegion() const {
860     const SharingMapTy *Top = getTopOfStackOrNull();
861     return Top ? Top->CancelRegion : false;
862   }
863 
864   /// Mark that parent region already has scan directive.
865   void setParentHasScanDirective(SourceLocation Loc) {
866     if (SharingMapTy *Parent = getSecondOnStackOrNull())
867       Parent->PrevScanLocation = Loc;
868   }
869   /// Return true if current region has inner cancel construct.
870   bool doesParentHasScanDirective() const {
871     const SharingMapTy *Top = getSecondOnStackOrNull();
872     return Top ? Top->PrevScanLocation.isValid() : false;
873   }
874   /// Return true if current region has inner cancel construct.
875   SourceLocation getParentScanDirectiveLoc() const {
876     const SharingMapTy *Top = getSecondOnStackOrNull();
877     return Top ? Top->PrevScanLocation : SourceLocation();
878   }
879   /// Mark that parent region already has ordered directive.
880   void setParentHasOrderedDirective(SourceLocation Loc) {
881     if (SharingMapTy *Parent = getSecondOnStackOrNull())
882       Parent->PrevOrderedLocation = Loc;
883   }
884   /// Return true if current region has inner ordered construct.
885   bool doesParentHasOrderedDirective() const {
886     const SharingMapTy *Top = getSecondOnStackOrNull();
887     return Top ? Top->PrevOrderedLocation.isValid() : false;
888   }
889   /// Returns the location of the previously specified ordered directive.
890   SourceLocation getParentOrderedDirectiveLoc() const {
891     const SharingMapTy *Top = getSecondOnStackOrNull();
892     return Top ? Top->PrevOrderedLocation : SourceLocation();
893   }
894 
895   /// Set collapse value for the region.
896   void setAssociatedLoops(unsigned Val) {
897     getTopOfStack().AssociatedLoops = Val;
898     if (Val > 1)
899       getTopOfStack().HasMutipleLoops = true;
900   }
901   /// Return collapse value for region.
902   unsigned getAssociatedLoops() const {
903     const SharingMapTy *Top = getTopOfStackOrNull();
904     return Top ? Top->AssociatedLoops : 0;
905   }
906   /// Returns true if the construct is associated with multiple loops.
907   bool hasMutipleLoops() const {
908     const SharingMapTy *Top = getTopOfStackOrNull();
909     return Top ? Top->HasMutipleLoops : false;
910   }
911 
912   /// Marks current target region as one with closely nested teams
913   /// region.
914   void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
915     if (SharingMapTy *Parent = getSecondOnStackOrNull())
916       Parent->InnerTeamsRegionLoc = TeamsRegionLoc;
917   }
918   /// Returns true, if current region has closely nested teams region.
919   bool hasInnerTeamsRegion() const {
920     return getInnerTeamsRegionLoc().isValid();
921   }
922   /// Returns location of the nested teams region (if any).
923   SourceLocation getInnerTeamsRegionLoc() const {
924     const SharingMapTy *Top = getTopOfStackOrNull();
925     return Top ? Top->InnerTeamsRegionLoc : SourceLocation();
926   }
927 
928   Scope *getCurScope() const {
929     const SharingMapTy *Top = getTopOfStackOrNull();
930     return Top ? Top->CurScope : nullptr;
931   }
932   void setContext(DeclContext *DC) { getTopOfStack().Context = DC; }
933   SourceLocation getConstructLoc() const {
934     const SharingMapTy *Top = getTopOfStackOrNull();
935     return Top ? Top->ConstructLoc : SourceLocation();
936   }
937 
938   /// Do the check specified in \a Check to all component lists and return true
939   /// if any issue is found.
940   bool checkMappableExprComponentListsForDecl(
941       const ValueDecl *VD, bool CurrentRegionOnly,
942       const llvm::function_ref<
943           bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
944                OpenMPClauseKind)>
945           Check) const {
946     if (isStackEmpty())
947       return false;
948     auto SI = begin();
949     auto SE = end();
950 
951     if (SI == SE)
952       return false;
953 
954     if (CurrentRegionOnly)
955       SE = std::next(SI);
956     else
957       std::advance(SI, 1);
958 
959     for (; SI != SE; ++SI) {
960       auto MI = SI->MappedExprComponents.find(VD);
961       if (MI != SI->MappedExprComponents.end())
962         for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
963              MI->second.Components)
964           if (Check(L, MI->second.Kind))
965             return true;
966     }
967     return false;
968   }
969 
970   /// Do the check specified in \a Check to all component lists at a given level
971   /// and return true if any issue is found.
972   bool checkMappableExprComponentListsForDeclAtLevel(
973       const ValueDecl *VD, unsigned Level,
974       const llvm::function_ref<
975           bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
976                OpenMPClauseKind)>
977           Check) const {
978     if (getStackSize() <= Level)
979       return false;
980 
981     const SharingMapTy &StackElem = getStackElemAtLevel(Level);
982     auto MI = StackElem.MappedExprComponents.find(VD);
983     if (MI != StackElem.MappedExprComponents.end())
984       for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
985            MI->second.Components)
986         if (Check(L, MI->second.Kind))
987           return true;
988     return false;
989   }
990 
991   /// Create a new mappable expression component list associated with a given
992   /// declaration and initialize it with the provided list of components.
993   void addMappableExpressionComponents(
994       const ValueDecl *VD,
995       OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
996       OpenMPClauseKind WhereFoundClauseKind) {
997     MappedExprComponentTy &MEC = getTopOfStack().MappedExprComponents[VD];
998     // Create new entry and append the new components there.
999     MEC.Components.resize(MEC.Components.size() + 1);
1000     MEC.Components.back().append(Components.begin(), Components.end());
1001     MEC.Kind = WhereFoundClauseKind;
1002   }
1003 
1004   unsigned getNestingLevel() const {
1005     assert(!isStackEmpty());
1006     return getStackSize() - 1;
1007   }
1008   void addDoacrossDependClause(OMPDependClause *C,
1009                                const OperatorOffsetTy &OpsOffs) {
1010     SharingMapTy *Parent = getSecondOnStackOrNull();
1011     assert(Parent && isOpenMPWorksharingDirective(Parent->Directive));
1012     Parent->DoacrossDepends.try_emplace(C, OpsOffs);
1013   }
1014   llvm::iterator_range<DoacrossDependMapTy::const_iterator>
1015   getDoacrossDependClauses() const {
1016     const SharingMapTy &StackElem = getTopOfStack();
1017     if (isOpenMPWorksharingDirective(StackElem.Directive)) {
1018       const DoacrossDependMapTy &Ref = StackElem.DoacrossDepends;
1019       return llvm::make_range(Ref.begin(), Ref.end());
1020     }
1021     return llvm::make_range(StackElem.DoacrossDepends.end(),
1022                             StackElem.DoacrossDepends.end());
1023   }
1024 
1025   // Store types of classes which have been explicitly mapped
1026   void addMappedClassesQualTypes(QualType QT) {
1027     SharingMapTy &StackElem = getTopOfStack();
1028     StackElem.MappedClassesQualTypes.insert(QT);
1029   }
1030 
1031   // Return set of mapped classes types
1032   bool isClassPreviouslyMapped(QualType QT) const {
1033     const SharingMapTy &StackElem = getTopOfStack();
1034     return StackElem.MappedClassesQualTypes.contains(QT);
1035   }
1036 
1037   /// Adds global declare target to the parent target region.
1038   void addToParentTargetRegionLinkGlobals(DeclRefExpr *E) {
1039     assert(*OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
1040                E->getDecl()) == OMPDeclareTargetDeclAttr::MT_Link &&
1041            "Expected declare target link global.");
1042     for (auto &Elem : *this) {
1043       if (isOpenMPTargetExecutionDirective(Elem.Directive)) {
1044         Elem.DeclareTargetLinkVarDecls.push_back(E);
1045         return;
1046       }
1047     }
1048   }
1049 
1050   /// Returns the list of globals with declare target link if current directive
1051   /// is target.
1052   ArrayRef<DeclRefExpr *> getLinkGlobals() const {
1053     assert(isOpenMPTargetExecutionDirective(getCurrentDirective()) &&
1054            "Expected target executable directive.");
1055     return getTopOfStack().DeclareTargetLinkVarDecls;
1056   }
1057 
1058   /// Adds list of allocators expressions.
1059   void addInnerAllocatorExpr(Expr *E) {
1060     getTopOfStack().InnerUsedAllocators.push_back(E);
1061   }
1062   /// Return list of used allocators.
1063   ArrayRef<Expr *> getInnerAllocators() const {
1064     return getTopOfStack().InnerUsedAllocators;
1065   }
1066   /// Marks the declaration as implicitly firstprivate nin the task-based
1067   /// regions.
1068   void addImplicitTaskFirstprivate(unsigned Level, Decl *D) {
1069     getStackElemAtLevel(Level).ImplicitTaskFirstprivates.insert(D);
1070   }
1071   /// Checks if the decl is implicitly firstprivate in the task-based region.
1072   bool isImplicitTaskFirstprivate(Decl *D) const {
1073     return getTopOfStack().ImplicitTaskFirstprivates.contains(D);
1074   }
1075 
1076   /// Marks decl as used in uses_allocators clause as the allocator.
1077   void addUsesAllocatorsDecl(const Decl *D, UsesAllocatorsDeclKind Kind) {
1078     getTopOfStack().UsesAllocatorsDecls.try_emplace(D, Kind);
1079   }
1080   /// Checks if specified decl is used in uses allocator clause as the
1081   /// allocator.
1082   Optional<UsesAllocatorsDeclKind> isUsesAllocatorsDecl(unsigned Level,
1083                                                         const Decl *D) const {
1084     const SharingMapTy &StackElem = getTopOfStack();
1085     auto I = StackElem.UsesAllocatorsDecls.find(D);
1086     if (I == StackElem.UsesAllocatorsDecls.end())
1087       return None;
1088     return I->getSecond();
1089   }
1090   Optional<UsesAllocatorsDeclKind> isUsesAllocatorsDecl(const Decl *D) const {
1091     const SharingMapTy &StackElem = getTopOfStack();
1092     auto I = StackElem.UsesAllocatorsDecls.find(D);
1093     if (I == StackElem.UsesAllocatorsDecls.end())
1094       return None;
1095     return I->getSecond();
1096   }
1097 
1098   void addDeclareMapperVarRef(Expr *Ref) {
1099     SharingMapTy &StackElem = getTopOfStack();
1100     StackElem.DeclareMapperVar = Ref;
1101   }
1102   const Expr *getDeclareMapperVarRef() const {
1103     const SharingMapTy *Top = getTopOfStackOrNull();
1104     return Top ? Top->DeclareMapperVar : nullptr;
1105   }
1106 };
1107 
1108 bool isImplicitTaskingRegion(OpenMPDirectiveKind DKind) {
1109   return isOpenMPParallelDirective(DKind) || isOpenMPTeamsDirective(DKind);
1110 }
1111 
1112 bool isImplicitOrExplicitTaskingRegion(OpenMPDirectiveKind DKind) {
1113   return isImplicitTaskingRegion(DKind) || isOpenMPTaskingDirective(DKind) ||
1114          DKind == OMPD_unknown;
1115 }
1116 
1117 } // namespace
1118 
1119 static const Expr *getExprAsWritten(const Expr *E) {
1120   if (const auto *FE = dyn_cast<FullExpr>(E))
1121     E = FE->getSubExpr();
1122 
1123   if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
1124     E = MTE->getSubExpr();
1125 
1126   while (const auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
1127     E = Binder->getSubExpr();
1128 
1129   if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
1130     E = ICE->getSubExprAsWritten();
1131   return E->IgnoreParens();
1132 }
1133 
1134 static Expr *getExprAsWritten(Expr *E) {
1135   return const_cast<Expr *>(getExprAsWritten(const_cast<const Expr *>(E)));
1136 }
1137 
1138 static const ValueDecl *getCanonicalDecl(const ValueDecl *D) {
1139   if (const auto *CED = dyn_cast<OMPCapturedExprDecl>(D))
1140     if (const auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
1141       D = ME->getMemberDecl();
1142   const auto *VD = dyn_cast<VarDecl>(D);
1143   const auto *FD = dyn_cast<FieldDecl>(D);
1144   if (VD != nullptr) {
1145     VD = VD->getCanonicalDecl();
1146     D = VD;
1147   } else {
1148     assert(FD);
1149     FD = FD->getCanonicalDecl();
1150     D = FD;
1151   }
1152   return D;
1153 }
1154 
1155 static ValueDecl *getCanonicalDecl(ValueDecl *D) {
1156   return const_cast<ValueDecl *>(
1157       getCanonicalDecl(const_cast<const ValueDecl *>(D)));
1158 }
1159 
1160 DSAStackTy::DSAVarData DSAStackTy::getDSA(const_iterator &Iter,
1161                                           ValueDecl *D) const {
1162   D = getCanonicalDecl(D);
1163   auto *VD = dyn_cast<VarDecl>(D);
1164   const auto *FD = dyn_cast<FieldDecl>(D);
1165   DSAVarData DVar;
1166   if (Iter == end()) {
1167     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1168     // in a region but not in construct]
1169     //  File-scope or namespace-scope variables referenced in called routines
1170     //  in the region are shared unless they appear in a threadprivate
1171     //  directive.
1172     if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(VD))
1173       DVar.CKind = OMPC_shared;
1174 
1175     // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
1176     // in a region but not in construct]
1177     //  Variables with static storage duration that are declared in called
1178     //  routines in the region are shared.
1179     if (VD && VD->hasGlobalStorage())
1180       DVar.CKind = OMPC_shared;
1181 
1182     // Non-static data members are shared by default.
1183     if (FD)
1184       DVar.CKind = OMPC_shared;
1185 
1186     return DVar;
1187   }
1188 
1189   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1190   // in a Construct, C/C++, predetermined, p.1]
1191   // Variables with automatic storage duration that are declared in a scope
1192   // inside the construct are private.
1193   if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() &&
1194       (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) {
1195     DVar.CKind = OMPC_private;
1196     return DVar;
1197   }
1198 
1199   DVar.DKind = Iter->Directive;
1200   // Explicitly specified attributes and local variables with predetermined
1201   // attributes.
1202   if (Iter->SharingMap.count(D)) {
1203     const DSAInfo &Data = Iter->SharingMap.lookup(D);
1204     DVar.RefExpr = Data.RefExpr.getPointer();
1205     DVar.PrivateCopy = Data.PrivateCopy;
1206     DVar.CKind = Data.Attributes;
1207     DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
1208     DVar.Modifier = Data.Modifier;
1209     DVar.AppliedToPointee = Data.AppliedToPointee;
1210     return DVar;
1211   }
1212 
1213   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1214   // in a Construct, C/C++, implicitly determined, p.1]
1215   //  In a parallel or task construct, the data-sharing attributes of these
1216   //  variables are determined by the default clause, if present.
1217   switch (Iter->DefaultAttr) {
1218   case DSA_shared:
1219     DVar.CKind = OMPC_shared;
1220     DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
1221     return DVar;
1222   case DSA_none:
1223     return DVar;
1224   case DSA_firstprivate:
1225     if (VD->getStorageDuration() == SD_Static &&
1226         VD->getDeclContext()->isFileContext()) {
1227       DVar.CKind = OMPC_unknown;
1228     } else {
1229       DVar.CKind = OMPC_firstprivate;
1230     }
1231     DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
1232     return DVar;
1233   case DSA_unspecified:
1234     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1235     // in a Construct, implicitly determined, p.2]
1236     //  In a parallel construct, if no default clause is present, these
1237     //  variables are shared.
1238     DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
1239     if ((isOpenMPParallelDirective(DVar.DKind) &&
1240          !isOpenMPTaskLoopDirective(DVar.DKind)) ||
1241         isOpenMPTeamsDirective(DVar.DKind)) {
1242       DVar.CKind = OMPC_shared;
1243       return DVar;
1244     }
1245 
1246     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1247     // in a Construct, implicitly determined, p.4]
1248     //  In a task construct, if no default clause is present, a variable that in
1249     //  the enclosing context is determined to be shared by all implicit tasks
1250     //  bound to the current team is shared.
1251     if (isOpenMPTaskingDirective(DVar.DKind)) {
1252       DSAVarData DVarTemp;
1253       const_iterator I = Iter, E = end();
1254       do {
1255         ++I;
1256         // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
1257         // Referenced in a Construct, implicitly determined, p.6]
1258         //  In a task construct, if no default clause is present, a variable
1259         //  whose data-sharing attribute is not determined by the rules above is
1260         //  firstprivate.
1261         DVarTemp = getDSA(I, D);
1262         if (DVarTemp.CKind != OMPC_shared) {
1263           DVar.RefExpr = nullptr;
1264           DVar.CKind = OMPC_firstprivate;
1265           return DVar;
1266         }
1267       } while (I != E && !isImplicitTaskingRegion(I->Directive));
1268       DVar.CKind =
1269           (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
1270       return DVar;
1271     }
1272   }
1273   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1274   // in a Construct, implicitly determined, p.3]
1275   //  For constructs other than task, if no default clause is present, these
1276   //  variables inherit their data-sharing attributes from the enclosing
1277   //  context.
1278   return getDSA(++Iter, D);
1279 }
1280 
1281 const Expr *DSAStackTy::addUniqueAligned(const ValueDecl *D,
1282                                          const Expr *NewDE) {
1283   assert(!isStackEmpty() && "Data sharing attributes stack is empty");
1284   D = getCanonicalDecl(D);
1285   SharingMapTy &StackElem = getTopOfStack();
1286   auto It = StackElem.AlignedMap.find(D);
1287   if (It == StackElem.AlignedMap.end()) {
1288     assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
1289     StackElem.AlignedMap[D] = NewDE;
1290     return nullptr;
1291   }
1292   assert(It->second && "Unexpected nullptr expr in the aligned map");
1293   return It->second;
1294 }
1295 
1296 const Expr *DSAStackTy::addUniqueNontemporal(const ValueDecl *D,
1297                                              const Expr *NewDE) {
1298   assert(!isStackEmpty() && "Data sharing attributes stack is empty");
1299   D = getCanonicalDecl(D);
1300   SharingMapTy &StackElem = getTopOfStack();
1301   auto It = StackElem.NontemporalMap.find(D);
1302   if (It == StackElem.NontemporalMap.end()) {
1303     assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
1304     StackElem.NontemporalMap[D] = NewDE;
1305     return nullptr;
1306   }
1307   assert(It->second && "Unexpected nullptr expr in the aligned map");
1308   return It->second;
1309 }
1310 
1311 void DSAStackTy::addLoopControlVariable(const ValueDecl *D, VarDecl *Capture) {
1312   assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
1313   D = getCanonicalDecl(D);
1314   SharingMapTy &StackElem = getTopOfStack();
1315   StackElem.LCVMap.try_emplace(
1316       D, LCDeclInfo(StackElem.LCVMap.size() + 1, Capture));
1317 }
1318 
1319 const DSAStackTy::LCDeclInfo
1320 DSAStackTy::isLoopControlVariable(const ValueDecl *D) const {
1321   assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
1322   D = getCanonicalDecl(D);
1323   const SharingMapTy &StackElem = getTopOfStack();
1324   auto It = StackElem.LCVMap.find(D);
1325   if (It != StackElem.LCVMap.end())
1326     return It->second;
1327   return {0, nullptr};
1328 }
1329 
1330 const DSAStackTy::LCDeclInfo
1331 DSAStackTy::isLoopControlVariable(const ValueDecl *D, unsigned Level) const {
1332   assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
1333   D = getCanonicalDecl(D);
1334   for (unsigned I = Level + 1; I > 0; --I) {
1335     const SharingMapTy &StackElem = getStackElemAtLevel(I - 1);
1336     auto It = StackElem.LCVMap.find(D);
1337     if (It != StackElem.LCVMap.end())
1338       return It->second;
1339   }
1340   return {0, nullptr};
1341 }
1342 
1343 const DSAStackTy::LCDeclInfo
1344 DSAStackTy::isParentLoopControlVariable(const ValueDecl *D) const {
1345   const SharingMapTy *Parent = getSecondOnStackOrNull();
1346   assert(Parent && "Data-sharing attributes stack is empty");
1347   D = getCanonicalDecl(D);
1348   auto It = Parent->LCVMap.find(D);
1349   if (It != Parent->LCVMap.end())
1350     return It->second;
1351   return {0, nullptr};
1352 }
1353 
1354 const ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) const {
1355   const SharingMapTy *Parent = getSecondOnStackOrNull();
1356   assert(Parent && "Data-sharing attributes stack is empty");
1357   if (Parent->LCVMap.size() < I)
1358     return nullptr;
1359   for (const auto &Pair : Parent->LCVMap)
1360     if (Pair.second.first == I)
1361       return Pair.first;
1362   return nullptr;
1363 }
1364 
1365 void DSAStackTy::addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
1366                         DeclRefExpr *PrivateCopy, unsigned Modifier,
1367                         bool AppliedToPointee) {
1368   D = getCanonicalDecl(D);
1369   if (A == OMPC_threadprivate) {
1370     DSAInfo &Data = Threadprivates[D];
1371     Data.Attributes = A;
1372     Data.RefExpr.setPointer(E);
1373     Data.PrivateCopy = nullptr;
1374     Data.Modifier = Modifier;
1375   } else {
1376     DSAInfo &Data = getTopOfStack().SharingMap[D];
1377     assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
1378            (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) ||
1379            (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) ||
1380            (isLoopControlVariable(D).first && A == OMPC_private));
1381     Data.Modifier = Modifier;
1382     if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) {
1383       Data.RefExpr.setInt(/*IntVal=*/true);
1384       return;
1385     }
1386     const bool IsLastprivate =
1387         A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate;
1388     Data.Attributes = A;
1389     Data.RefExpr.setPointerAndInt(E, IsLastprivate);
1390     Data.PrivateCopy = PrivateCopy;
1391     Data.AppliedToPointee = AppliedToPointee;
1392     if (PrivateCopy) {
1393       DSAInfo &Data = getTopOfStack().SharingMap[PrivateCopy->getDecl()];
1394       Data.Modifier = Modifier;
1395       Data.Attributes = A;
1396       Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate);
1397       Data.PrivateCopy = nullptr;
1398       Data.AppliedToPointee = AppliedToPointee;
1399     }
1400   }
1401 }
1402 
1403 /// Build a variable declaration for OpenMP loop iteration variable.
1404 static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
1405                              StringRef Name, const AttrVec *Attrs = nullptr,
1406                              DeclRefExpr *OrigRef = nullptr) {
1407   DeclContext *DC = SemaRef.CurContext;
1408   IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
1409   TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
1410   auto *Decl =
1411       VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
1412   if (Attrs) {
1413     for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
1414          I != E; ++I)
1415       Decl->addAttr(*I);
1416   }
1417   Decl->setImplicit();
1418   if (OrigRef) {
1419     Decl->addAttr(
1420         OMPReferencedVarAttr::CreateImplicit(SemaRef.Context, OrigRef));
1421   }
1422   return Decl;
1423 }
1424 
1425 static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
1426                                      SourceLocation Loc,
1427                                      bool RefersToCapture = false) {
1428   D->setReferenced();
1429   D->markUsed(S.Context);
1430   return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
1431                              SourceLocation(), D, RefersToCapture, Loc, Ty,
1432                              VK_LValue);
1433 }
1434 
1435 void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
1436                                            BinaryOperatorKind BOK) {
1437   D = getCanonicalDecl(D);
1438   assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
1439   assert(
1440       getTopOfStack().SharingMap[D].Attributes == OMPC_reduction &&
1441       "Additional reduction info may be specified only for reduction items.");
1442   ReductionData &ReductionData = getTopOfStack().ReductionMap[D];
1443   assert(ReductionData.ReductionRange.isInvalid() &&
1444          (getTopOfStack().Directive == OMPD_taskgroup ||
1445           ((isOpenMPParallelDirective(getTopOfStack().Directive) ||
1446             isOpenMPWorksharingDirective(getTopOfStack().Directive)) &&
1447            !isOpenMPSimdDirective(getTopOfStack().Directive))) &&
1448          "Additional reduction info may be specified only once for reduction "
1449          "items.");
1450   ReductionData.set(BOK, SR);
1451   Expr *&TaskgroupReductionRef = getTopOfStack().TaskgroupReductionRef;
1452   if (!TaskgroupReductionRef) {
1453     VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
1454                                SemaRef.Context.VoidPtrTy, ".task_red.");
1455     TaskgroupReductionRef =
1456         buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
1457   }
1458 }
1459 
1460 void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
1461                                            const Expr *ReductionRef) {
1462   D = getCanonicalDecl(D);
1463   assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
1464   assert(
1465       getTopOfStack().SharingMap[D].Attributes == OMPC_reduction &&
1466       "Additional reduction info may be specified only for reduction items.");
1467   ReductionData &ReductionData = getTopOfStack().ReductionMap[D];
1468   assert(ReductionData.ReductionRange.isInvalid() &&
1469          (getTopOfStack().Directive == OMPD_taskgroup ||
1470           ((isOpenMPParallelDirective(getTopOfStack().Directive) ||
1471             isOpenMPWorksharingDirective(getTopOfStack().Directive)) &&
1472            !isOpenMPSimdDirective(getTopOfStack().Directive))) &&
1473          "Additional reduction info may be specified only once for reduction "
1474          "items.");
1475   ReductionData.set(ReductionRef, SR);
1476   Expr *&TaskgroupReductionRef = getTopOfStack().TaskgroupReductionRef;
1477   if (!TaskgroupReductionRef) {
1478     VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
1479                                SemaRef.Context.VoidPtrTy, ".task_red.");
1480     TaskgroupReductionRef =
1481         buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
1482   }
1483 }
1484 
1485 const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
1486     const ValueDecl *D, SourceRange &SR, BinaryOperatorKind &BOK,
1487     Expr *&TaskgroupDescriptor) const {
1488   D = getCanonicalDecl(D);
1489   assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
1490   for (const_iterator I = begin() + 1, E = end(); I != E; ++I) {
1491     const DSAInfo &Data = I->SharingMap.lookup(D);
1492     if (Data.Attributes != OMPC_reduction ||
1493         Data.Modifier != OMPC_REDUCTION_task)
1494       continue;
1495     const ReductionData &ReductionData = I->ReductionMap.lookup(D);
1496     if (!ReductionData.ReductionOp ||
1497         ReductionData.ReductionOp.is<const Expr *>())
1498       return DSAVarData();
1499     SR = ReductionData.ReductionRange;
1500     BOK = ReductionData.ReductionOp.get<ReductionData::BOKPtrType>();
1501     assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
1502                                        "expression for the descriptor is not "
1503                                        "set.");
1504     TaskgroupDescriptor = I->TaskgroupReductionRef;
1505     return DSAVarData(I->Directive, OMPC_reduction, Data.RefExpr.getPointer(),
1506                       Data.PrivateCopy, I->DefaultAttrLoc, OMPC_REDUCTION_task,
1507                       /*AppliedToPointee=*/false);
1508   }
1509   return DSAVarData();
1510 }
1511 
1512 const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
1513     const ValueDecl *D, SourceRange &SR, const Expr *&ReductionRef,
1514     Expr *&TaskgroupDescriptor) const {
1515   D = getCanonicalDecl(D);
1516   assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
1517   for (const_iterator I = begin() + 1, E = end(); I != E; ++I) {
1518     const DSAInfo &Data = I->SharingMap.lookup(D);
1519     if (Data.Attributes != OMPC_reduction ||
1520         Data.Modifier != OMPC_REDUCTION_task)
1521       continue;
1522     const ReductionData &ReductionData = I->ReductionMap.lookup(D);
1523     if (!ReductionData.ReductionOp ||
1524         !ReductionData.ReductionOp.is<const Expr *>())
1525       return DSAVarData();
1526     SR = ReductionData.ReductionRange;
1527     ReductionRef = ReductionData.ReductionOp.get<const Expr *>();
1528     assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
1529                                        "expression for the descriptor is not "
1530                                        "set.");
1531     TaskgroupDescriptor = I->TaskgroupReductionRef;
1532     return DSAVarData(I->Directive, OMPC_reduction, Data.RefExpr.getPointer(),
1533                       Data.PrivateCopy, I->DefaultAttrLoc, OMPC_REDUCTION_task,
1534                       /*AppliedToPointee=*/false);
1535   }
1536   return DSAVarData();
1537 }
1538 
1539 bool DSAStackTy::isOpenMPLocal(VarDecl *D, const_iterator I) const {
1540   D = D->getCanonicalDecl();
1541   for (const_iterator E = end(); I != E; ++I) {
1542     if (isImplicitOrExplicitTaskingRegion(I->Directive) ||
1543         isOpenMPTargetExecutionDirective(I->Directive)) {
1544       if (I->CurScope) {
1545         Scope *TopScope = I->CurScope->getParent();
1546         Scope *CurScope = getCurScope();
1547         while (CurScope && CurScope != TopScope && !CurScope->isDeclScope(D))
1548           CurScope = CurScope->getParent();
1549         return CurScope != TopScope;
1550       }
1551       for (DeclContext *DC = D->getDeclContext(); DC; DC = DC->getParent())
1552         if (I->Context == DC)
1553           return true;
1554       return false;
1555     }
1556   }
1557   return false;
1558 }
1559 
1560 static bool isConstNotMutableType(Sema &SemaRef, QualType Type,
1561                                   bool AcceptIfMutable = true,
1562                                   bool *IsClassType = nullptr) {
1563   ASTContext &Context = SemaRef.getASTContext();
1564   Type = Type.getNonReferenceType().getCanonicalType();
1565   bool IsConstant = Type.isConstant(Context);
1566   Type = Context.getBaseElementType(Type);
1567   const CXXRecordDecl *RD = AcceptIfMutable && SemaRef.getLangOpts().CPlusPlus
1568                                 ? Type->getAsCXXRecordDecl()
1569                                 : nullptr;
1570   if (const auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
1571     if (const ClassTemplateDecl *CTD = CTSD->getSpecializedTemplate())
1572       RD = CTD->getTemplatedDecl();
1573   if (IsClassType)
1574     *IsClassType = RD;
1575   return IsConstant && !(SemaRef.getLangOpts().CPlusPlus && RD &&
1576                          RD->hasDefinition() && RD->hasMutableFields());
1577 }
1578 
1579 static bool rejectConstNotMutableType(Sema &SemaRef, const ValueDecl *D,
1580                                       QualType Type, OpenMPClauseKind CKind,
1581                                       SourceLocation ELoc,
1582                                       bool AcceptIfMutable = true,
1583                                       bool ListItemNotVar = false) {
1584   ASTContext &Context = SemaRef.getASTContext();
1585   bool IsClassType;
1586   if (isConstNotMutableType(SemaRef, Type, AcceptIfMutable, &IsClassType)) {
1587     unsigned Diag = ListItemNotVar ? diag::err_omp_const_list_item
1588                     : IsClassType  ? diag::err_omp_const_not_mutable_variable
1589                                    : diag::err_omp_const_variable;
1590     SemaRef.Diag(ELoc, Diag) << getOpenMPClauseName(CKind);
1591     if (!ListItemNotVar && D) {
1592       const VarDecl *VD = dyn_cast<VarDecl>(D);
1593       bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
1594                                VarDecl::DeclarationOnly;
1595       SemaRef.Diag(D->getLocation(),
1596                    IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1597           << D;
1598     }
1599     return true;
1600   }
1601   return false;
1602 }
1603 
1604 const DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D,
1605                                                    bool FromParent) {
1606   D = getCanonicalDecl(D);
1607   DSAVarData DVar;
1608 
1609   auto *VD = dyn_cast<VarDecl>(D);
1610   auto TI = Threadprivates.find(D);
1611   if (TI != Threadprivates.end()) {
1612     DVar.RefExpr = TI->getSecond().RefExpr.getPointer();
1613     DVar.CKind = OMPC_threadprivate;
1614     DVar.Modifier = TI->getSecond().Modifier;
1615     return DVar;
1616   }
1617   if (VD && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
1618     DVar.RefExpr = buildDeclRefExpr(
1619         SemaRef, VD, D->getType().getNonReferenceType(),
1620         VD->getAttr<OMPThreadPrivateDeclAttr>()->getLocation());
1621     DVar.CKind = OMPC_threadprivate;
1622     addDSA(D, DVar.RefExpr, OMPC_threadprivate);
1623     return DVar;
1624   }
1625   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1626   // in a Construct, C/C++, predetermined, p.1]
1627   //  Variables appearing in threadprivate directives are threadprivate.
1628   if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
1629        !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
1630          SemaRef.getLangOpts().OpenMPUseTLS &&
1631          SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
1632       (VD && VD->getStorageClass() == SC_Register &&
1633        VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
1634     DVar.RefExpr = buildDeclRefExpr(
1635         SemaRef, VD, D->getType().getNonReferenceType(), D->getLocation());
1636     DVar.CKind = OMPC_threadprivate;
1637     addDSA(D, DVar.RefExpr, OMPC_threadprivate);
1638     return DVar;
1639   }
1640   if (SemaRef.getLangOpts().OpenMPCUDAMode && VD &&
1641       VD->isLocalVarDeclOrParm() && !isStackEmpty() &&
1642       !isLoopControlVariable(D).first) {
1643     const_iterator IterTarget =
1644         std::find_if(begin(), end(), [](const SharingMapTy &Data) {
1645           return isOpenMPTargetExecutionDirective(Data.Directive);
1646         });
1647     if (IterTarget != end()) {
1648       const_iterator ParentIterTarget = IterTarget + 1;
1649       for (const_iterator Iter = begin(); Iter != ParentIterTarget; ++Iter) {
1650         if (isOpenMPLocal(VD, Iter)) {
1651           DVar.RefExpr =
1652               buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
1653                                D->getLocation());
1654           DVar.CKind = OMPC_threadprivate;
1655           return DVar;
1656         }
1657       }
1658       if (!isClauseParsingMode() || IterTarget != begin()) {
1659         auto DSAIter = IterTarget->SharingMap.find(D);
1660         if (DSAIter != IterTarget->SharingMap.end() &&
1661             isOpenMPPrivate(DSAIter->getSecond().Attributes)) {
1662           DVar.RefExpr = DSAIter->getSecond().RefExpr.getPointer();
1663           DVar.CKind = OMPC_threadprivate;
1664           return DVar;
1665         }
1666         const_iterator End = end();
1667         if (!SemaRef.isOpenMPCapturedByRef(D,
1668                                            std::distance(ParentIterTarget, End),
1669                                            /*OpenMPCaptureLevel=*/0)) {
1670           DVar.RefExpr =
1671               buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
1672                                IterTarget->ConstructLoc);
1673           DVar.CKind = OMPC_threadprivate;
1674           return DVar;
1675         }
1676       }
1677     }
1678   }
1679 
1680   if (isStackEmpty())
1681     // Not in OpenMP execution region and top scope was already checked.
1682     return DVar;
1683 
1684   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1685   // in a Construct, C/C++, predetermined, p.4]
1686   //  Static data members are shared.
1687   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1688   // in a Construct, C/C++, predetermined, p.7]
1689   //  Variables with static storage duration that are declared in a scope
1690   //  inside the construct are shared.
1691   if (VD && VD->isStaticDataMember()) {
1692     // Check for explicitly specified attributes.
1693     const_iterator I = begin();
1694     const_iterator EndI = end();
1695     if (FromParent && I != EndI)
1696       ++I;
1697     if (I != EndI) {
1698       auto It = I->SharingMap.find(D);
1699       if (It != I->SharingMap.end()) {
1700         const DSAInfo &Data = It->getSecond();
1701         DVar.RefExpr = Data.RefExpr.getPointer();
1702         DVar.PrivateCopy = Data.PrivateCopy;
1703         DVar.CKind = Data.Attributes;
1704         DVar.ImplicitDSALoc = I->DefaultAttrLoc;
1705         DVar.DKind = I->Directive;
1706         DVar.Modifier = Data.Modifier;
1707         DVar.AppliedToPointee = Data.AppliedToPointee;
1708         return DVar;
1709       }
1710     }
1711 
1712     DVar.CKind = OMPC_shared;
1713     return DVar;
1714   }
1715 
1716   auto &&MatchesAlways = [](OpenMPDirectiveKind) { return true; };
1717   // The predetermined shared attribute for const-qualified types having no
1718   // mutable members was removed after OpenMP 3.1.
1719   if (SemaRef.LangOpts.OpenMP <= 31) {
1720     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1721     // in a Construct, C/C++, predetermined, p.6]
1722     //  Variables with const qualified type having no mutable member are
1723     //  shared.
1724     if (isConstNotMutableType(SemaRef, D->getType())) {
1725       // Variables with const-qualified type having no mutable member may be
1726       // listed in a firstprivate clause, even if they are static data members.
1727       DSAVarData DVarTemp = hasInnermostDSA(
1728           D,
1729           [](OpenMPClauseKind C, bool) {
1730             return C == OMPC_firstprivate || C == OMPC_shared;
1731           },
1732           MatchesAlways, FromParent);
1733       if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
1734         return DVarTemp;
1735 
1736       DVar.CKind = OMPC_shared;
1737       return DVar;
1738     }
1739   }
1740 
1741   // Explicitly specified attributes and local variables with predetermined
1742   // attributes.
1743   const_iterator I = begin();
1744   const_iterator EndI = end();
1745   if (FromParent && I != EndI)
1746     ++I;
1747   if (I == EndI)
1748     return DVar;
1749   auto It = I->SharingMap.find(D);
1750   if (It != I->SharingMap.end()) {
1751     const DSAInfo &Data = It->getSecond();
1752     DVar.RefExpr = Data.RefExpr.getPointer();
1753     DVar.PrivateCopy = Data.PrivateCopy;
1754     DVar.CKind = Data.Attributes;
1755     DVar.ImplicitDSALoc = I->DefaultAttrLoc;
1756     DVar.DKind = I->Directive;
1757     DVar.Modifier = Data.Modifier;
1758     DVar.AppliedToPointee = Data.AppliedToPointee;
1759   }
1760 
1761   return DVar;
1762 }
1763 
1764 const DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
1765                                                         bool FromParent) const {
1766   if (isStackEmpty()) {
1767     const_iterator I;
1768     return getDSA(I, D);
1769   }
1770   D = getCanonicalDecl(D);
1771   const_iterator StartI = begin();
1772   const_iterator EndI = end();
1773   if (FromParent && StartI != EndI)
1774     ++StartI;
1775   return getDSA(StartI, D);
1776 }
1777 
1778 const DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
1779                                                         unsigned Level) const {
1780   if (getStackSize() <= Level)
1781     return DSAVarData();
1782   D = getCanonicalDecl(D);
1783   const_iterator StartI = std::next(begin(), getStackSize() - 1 - Level);
1784   return getDSA(StartI, D);
1785 }
1786 
1787 const DSAStackTy::DSAVarData
1788 DSAStackTy::hasDSA(ValueDecl *D,
1789                    const llvm::function_ref<bool(OpenMPClauseKind, bool)> CPred,
1790                    const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
1791                    bool FromParent) const {
1792   if (isStackEmpty())
1793     return {};
1794   D = getCanonicalDecl(D);
1795   const_iterator I = begin();
1796   const_iterator EndI = end();
1797   if (FromParent && I != EndI)
1798     ++I;
1799   for (; I != EndI; ++I) {
1800     if (!DPred(I->Directive) &&
1801         !isImplicitOrExplicitTaskingRegion(I->Directive))
1802       continue;
1803     const_iterator NewI = I;
1804     DSAVarData DVar = getDSA(NewI, D);
1805     if (I == NewI && CPred(DVar.CKind, DVar.AppliedToPointee))
1806       return DVar;
1807   }
1808   return {};
1809 }
1810 
1811 const DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
1812     ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind, bool)> CPred,
1813     const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
1814     bool FromParent) const {
1815   if (isStackEmpty())
1816     return {};
1817   D = getCanonicalDecl(D);
1818   const_iterator StartI = begin();
1819   const_iterator EndI = end();
1820   if (FromParent && StartI != EndI)
1821     ++StartI;
1822   if (StartI == EndI || !DPred(StartI->Directive))
1823     return {};
1824   const_iterator NewI = StartI;
1825   DSAVarData DVar = getDSA(NewI, D);
1826   return (NewI == StartI && CPred(DVar.CKind, DVar.AppliedToPointee))
1827              ? DVar
1828              : DSAVarData();
1829 }
1830 
1831 bool DSAStackTy::hasExplicitDSA(
1832     const ValueDecl *D,
1833     const llvm::function_ref<bool(OpenMPClauseKind, bool)> CPred,
1834     unsigned Level, bool NotLastprivate) const {
1835   if (getStackSize() <= Level)
1836     return false;
1837   D = getCanonicalDecl(D);
1838   const SharingMapTy &StackElem = getStackElemAtLevel(Level);
1839   auto I = StackElem.SharingMap.find(D);
1840   if (I != StackElem.SharingMap.end() && I->getSecond().RefExpr.getPointer() &&
1841       CPred(I->getSecond().Attributes, I->getSecond().AppliedToPointee) &&
1842       (!NotLastprivate || !I->getSecond().RefExpr.getInt()))
1843     return true;
1844   // Check predetermined rules for the loop control variables.
1845   auto LI = StackElem.LCVMap.find(D);
1846   if (LI != StackElem.LCVMap.end())
1847     return CPred(OMPC_private, /*AppliedToPointee=*/false);
1848   return false;
1849 }
1850 
1851 bool DSAStackTy::hasExplicitDirective(
1852     const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
1853     unsigned Level) const {
1854   if (getStackSize() <= Level)
1855     return false;
1856   const SharingMapTy &StackElem = getStackElemAtLevel(Level);
1857   return DPred(StackElem.Directive);
1858 }
1859 
1860 bool DSAStackTy::hasDirective(
1861     const llvm::function_ref<bool(OpenMPDirectiveKind,
1862                                   const DeclarationNameInfo &, SourceLocation)>
1863         DPred,
1864     bool FromParent) const {
1865   // We look only in the enclosing region.
1866   size_t Skip = FromParent ? 2 : 1;
1867   for (const_iterator I = begin() + std::min(Skip, getStackSize()), E = end();
1868        I != E; ++I) {
1869     if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
1870       return true;
1871   }
1872   return false;
1873 }
1874 
1875 void Sema::InitDataSharingAttributesStack() {
1876   VarDataSharingAttributesStack = new DSAStackTy(*this);
1877 }
1878 
1879 #define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
1880 
1881 void Sema::pushOpenMPFunctionRegion() { DSAStack->pushFunction(); }
1882 
1883 void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) {
1884   DSAStack->popFunction(OldFSI);
1885 }
1886 
1887 static bool isOpenMPDeviceDelayedContext(Sema &S) {
1888   assert(S.LangOpts.OpenMP && S.LangOpts.OpenMPIsDevice &&
1889          "Expected OpenMP device compilation.");
1890   return !S.isInOpenMPTargetExecutionDirective();
1891 }
1892 
1893 namespace {
1894 /// Status of the function emission on the host/device.
1895 enum class FunctionEmissionStatus {
1896   Emitted,
1897   Discarded,
1898   Unknown,
1899 };
1900 } // anonymous namespace
1901 
1902 Sema::SemaDiagnosticBuilder Sema::diagIfOpenMPDeviceCode(SourceLocation Loc,
1903                                                          unsigned DiagID,
1904                                                          FunctionDecl *FD) {
1905   assert(LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
1906          "Expected OpenMP device compilation.");
1907 
1908   SemaDiagnosticBuilder::Kind Kind = SemaDiagnosticBuilder::K_Nop;
1909   if (FD) {
1910     FunctionEmissionStatus FES = getEmissionStatus(FD);
1911     switch (FES) {
1912     case FunctionEmissionStatus::Emitted:
1913       Kind = SemaDiagnosticBuilder::K_Immediate;
1914       break;
1915     case FunctionEmissionStatus::Unknown:
1916       // TODO: We should always delay diagnostics here in case a target
1917       //       region is in a function we do not emit. However, as the
1918       //       current diagnostics are associated with the function containing
1919       //       the target region and we do not emit that one, we would miss out
1920       //       on diagnostics for the target region itself. We need to anchor
1921       //       the diagnostics with the new generated function *or* ensure we
1922       //       emit diagnostics associated with the surrounding function.
1923       Kind = isOpenMPDeviceDelayedContext(*this)
1924                  ? SemaDiagnosticBuilder::K_Deferred
1925                  : SemaDiagnosticBuilder::K_Immediate;
1926       break;
1927     case FunctionEmissionStatus::TemplateDiscarded:
1928     case FunctionEmissionStatus::OMPDiscarded:
1929       Kind = SemaDiagnosticBuilder::K_Nop;
1930       break;
1931     case FunctionEmissionStatus::CUDADiscarded:
1932       llvm_unreachable("CUDADiscarded unexpected in OpenMP device compilation");
1933       break;
1934     }
1935   }
1936 
1937   return SemaDiagnosticBuilder(Kind, Loc, DiagID, FD, *this);
1938 }
1939 
1940 Sema::SemaDiagnosticBuilder Sema::diagIfOpenMPHostCode(SourceLocation Loc,
1941                                                        unsigned DiagID,
1942                                                        FunctionDecl *FD) {
1943   assert(LangOpts.OpenMP && !LangOpts.OpenMPIsDevice &&
1944          "Expected OpenMP host compilation.");
1945 
1946   SemaDiagnosticBuilder::Kind Kind = SemaDiagnosticBuilder::K_Nop;
1947   if (FD) {
1948     FunctionEmissionStatus FES = getEmissionStatus(FD);
1949     switch (FES) {
1950     case FunctionEmissionStatus::Emitted:
1951       Kind = SemaDiagnosticBuilder::K_Immediate;
1952       break;
1953     case FunctionEmissionStatus::Unknown:
1954       Kind = SemaDiagnosticBuilder::K_Deferred;
1955       break;
1956     case FunctionEmissionStatus::TemplateDiscarded:
1957     case FunctionEmissionStatus::OMPDiscarded:
1958     case FunctionEmissionStatus::CUDADiscarded:
1959       Kind = SemaDiagnosticBuilder::K_Nop;
1960       break;
1961     }
1962   }
1963 
1964   return SemaDiagnosticBuilder(Kind, Loc, DiagID, FD, *this);
1965 }
1966 
1967 static OpenMPDefaultmapClauseKind
1968 getVariableCategoryFromDecl(const LangOptions &LO, const ValueDecl *VD) {
1969   if (LO.OpenMP <= 45) {
1970     if (VD->getType().getNonReferenceType()->isScalarType())
1971       return OMPC_DEFAULTMAP_scalar;
1972     return OMPC_DEFAULTMAP_aggregate;
1973   }
1974   if (VD->getType().getNonReferenceType()->isAnyPointerType())
1975     return OMPC_DEFAULTMAP_pointer;
1976   if (VD->getType().getNonReferenceType()->isScalarType())
1977     return OMPC_DEFAULTMAP_scalar;
1978   return OMPC_DEFAULTMAP_aggregate;
1979 }
1980 
1981 bool Sema::isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level,
1982                                  unsigned OpenMPCaptureLevel) const {
1983   assert(LangOpts.OpenMP && "OpenMP is not allowed");
1984 
1985   ASTContext &Ctx = getASTContext();
1986   bool IsByRef = true;
1987 
1988   // Find the directive that is associated with the provided scope.
1989   D = cast<ValueDecl>(D->getCanonicalDecl());
1990   QualType Ty = D->getType();
1991 
1992   bool IsVariableUsedInMapClause = false;
1993   if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
1994     // This table summarizes how a given variable should be passed to the device
1995     // given its type and the clauses where it appears. This table is based on
1996     // the description in OpenMP 4.5 [2.10.4, target Construct] and
1997     // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
1998     //
1999     // =========================================================================
2000     // | type |  defaultmap   | pvt | first | is_device_ptr |    map   | res.  |
2001     // |      |(tofrom:scalar)|     |  pvt  |               |          |       |
2002     // =========================================================================
2003     // | scl  |               |     |       |       -       |          | bycopy|
2004     // | scl  |               |  -  |   x   |       -       |     -    | bycopy|
2005     // | scl  |               |  x  |   -   |       -       |     -    | null  |
2006     // | scl  |       x       |     |       |       -       |          | byref |
2007     // | scl  |       x       |  -  |   x   |       -       |     -    | bycopy|
2008     // | scl  |       x       |  x  |   -   |       -       |     -    | null  |
2009     // | scl  |               |  -  |   -   |       -       |     x    | byref |
2010     // | scl  |       x       |  -  |   -   |       -       |     x    | byref |
2011     //
2012     // | agg  |      n.a.     |     |       |       -       |          | byref |
2013     // | agg  |      n.a.     |  -  |   x   |       -       |     -    | byref |
2014     // | agg  |      n.a.     |  x  |   -   |       -       |     -    | null  |
2015     // | agg  |      n.a.     |  -  |   -   |       -       |     x    | byref |
2016     // | agg  |      n.a.     |  -  |   -   |       -       |    x[]   | byref |
2017     //
2018     // | ptr  |      n.a.     |     |       |       -       |          | bycopy|
2019     // | ptr  |      n.a.     |  -  |   x   |       -       |     -    | bycopy|
2020     // | ptr  |      n.a.     |  x  |   -   |       -       |     -    | null  |
2021     // | ptr  |      n.a.     |  -  |   -   |       -       |     x    | byref |
2022     // | ptr  |      n.a.     |  -  |   -   |       -       |    x[]   | bycopy|
2023     // | ptr  |      n.a.     |  -  |   -   |       x       |          | bycopy|
2024     // | ptr  |      n.a.     |  -  |   -   |       x       |     x    | bycopy|
2025     // | ptr  |      n.a.     |  -  |   -   |       x       |    x[]   | bycopy|
2026     // =========================================================================
2027     // Legend:
2028     //  scl - scalar
2029     //  ptr - pointer
2030     //  agg - aggregate
2031     //  x - applies
2032     //  - - invalid in this combination
2033     //  [] - mapped with an array section
2034     //  byref - should be mapped by reference
2035     //  byval - should be mapped by value
2036     //  null - initialize a local variable to null on the device
2037     //
2038     // Observations:
2039     //  - All scalar declarations that show up in a map clause have to be passed
2040     //    by reference, because they may have been mapped in the enclosing data
2041     //    environment.
2042     //  - If the scalar value does not fit the size of uintptr, it has to be
2043     //    passed by reference, regardless the result in the table above.
2044     //  - For pointers mapped by value that have either an implicit map or an
2045     //    array section, the runtime library may pass the NULL value to the
2046     //    device instead of the value passed to it by the compiler.
2047 
2048     if (Ty->isReferenceType())
2049       Ty = Ty->castAs<ReferenceType>()->getPointeeType();
2050 
2051     // Locate map clauses and see if the variable being captured is referred to
2052     // in any of those clauses. Here we only care about variables, not fields,
2053     // because fields are part of aggregates.
2054     bool IsVariableAssociatedWithSection = false;
2055 
2056     DSAStack->checkMappableExprComponentListsForDeclAtLevel(
2057         D, Level,
2058         [&IsVariableUsedInMapClause, &IsVariableAssociatedWithSection,
2059          D](OMPClauseMappableExprCommon::MappableExprComponentListRef
2060                 MapExprComponents,
2061             OpenMPClauseKind WhereFoundClauseKind) {
2062           // Only the map clause information influences how a variable is
2063           // captured. E.g. is_device_ptr does not require changing the default
2064           // behavior.
2065           if (WhereFoundClauseKind != OMPC_map)
2066             return false;
2067 
2068           auto EI = MapExprComponents.rbegin();
2069           auto EE = MapExprComponents.rend();
2070 
2071           assert(EI != EE && "Invalid map expression!");
2072 
2073           if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
2074             IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
2075 
2076           ++EI;
2077           if (EI == EE)
2078             return false;
2079 
2080           if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
2081               isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
2082               isa<MemberExpr>(EI->getAssociatedExpression()) ||
2083               isa<OMPArrayShapingExpr>(EI->getAssociatedExpression())) {
2084             IsVariableAssociatedWithSection = true;
2085             // There is nothing more we need to know about this variable.
2086             return true;
2087           }
2088 
2089           // Keep looking for more map info.
2090           return false;
2091         });
2092 
2093     if (IsVariableUsedInMapClause) {
2094       // If variable is identified in a map clause it is always captured by
2095       // reference except if it is a pointer that is dereferenced somehow.
2096       IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
2097     } else {
2098       // By default, all the data that has a scalar type is mapped by copy
2099       // (except for reduction variables).
2100       // Defaultmap scalar is mutual exclusive to defaultmap pointer
2101       IsByRef = (DSAStack->isForceCaptureByReferenceInTargetExecutable() &&
2102                  !Ty->isAnyPointerType()) ||
2103                 !Ty->isScalarType() ||
2104                 DSAStack->isDefaultmapCapturedByRef(
2105                     Level, getVariableCategoryFromDecl(LangOpts, D)) ||
2106                 DSAStack->hasExplicitDSA(
2107                     D,
2108                     [](OpenMPClauseKind K, bool AppliedToPointee) {
2109                       return K == OMPC_reduction && !AppliedToPointee;
2110                     },
2111                     Level);
2112     }
2113   }
2114 
2115   if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
2116     IsByRef =
2117         ((IsVariableUsedInMapClause &&
2118           DSAStack->getCaptureRegion(Level, OpenMPCaptureLevel) ==
2119               OMPD_target) ||
2120          !(DSAStack->hasExplicitDSA(
2121                D,
2122                [](OpenMPClauseKind K, bool AppliedToPointee) -> bool {
2123                  return K == OMPC_firstprivate ||
2124                         (K == OMPC_reduction && AppliedToPointee);
2125                },
2126                Level, /*NotLastprivate=*/true) ||
2127            DSAStack->isUsesAllocatorsDecl(Level, D))) &&
2128         // If the variable is artificial and must be captured by value - try to
2129         // capture by value.
2130         !(isa<OMPCapturedExprDecl>(D) && !D->hasAttr<OMPCaptureNoInitAttr>() &&
2131           !cast<OMPCapturedExprDecl>(D)->getInit()->isGLValue()) &&
2132         // If the variable is implicitly firstprivate and scalar - capture by
2133         // copy
2134         !(DSAStack->getDefaultDSA() == DSA_firstprivate &&
2135           !DSAStack->hasExplicitDSA(
2136               D, [](OpenMPClauseKind K, bool) { return K != OMPC_unknown; },
2137               Level) &&
2138           !DSAStack->isLoopControlVariable(D, Level).first);
2139   }
2140 
2141   // When passing data by copy, we need to make sure it fits the uintptr size
2142   // and alignment, because the runtime library only deals with uintptr types.
2143   // If it does not fit the uintptr size, we need to pass the data by reference
2144   // instead.
2145   if (!IsByRef &&
2146       (Ctx.getTypeSizeInChars(Ty) >
2147            Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
2148        Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
2149     IsByRef = true;
2150   }
2151 
2152   return IsByRef;
2153 }
2154 
2155 unsigned Sema::getOpenMPNestingLevel() const {
2156   assert(getLangOpts().OpenMP);
2157   return DSAStack->getNestingLevel();
2158 }
2159 
2160 bool Sema::isInOpenMPTargetExecutionDirective() const {
2161   return (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) &&
2162           !DSAStack->isClauseParsingMode()) ||
2163          DSAStack->hasDirective(
2164              [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
2165                 SourceLocation) -> bool {
2166                return isOpenMPTargetExecutionDirective(K);
2167              },
2168              false);
2169 }
2170 
2171 VarDecl *Sema::isOpenMPCapturedDecl(ValueDecl *D, bool CheckScopeInfo,
2172                                     unsigned StopAt) {
2173   assert(LangOpts.OpenMP && "OpenMP is not allowed");
2174   D = getCanonicalDecl(D);
2175 
2176   auto *VD = dyn_cast<VarDecl>(D);
2177   // Do not capture constexpr variables.
2178   if (VD && VD->isConstexpr())
2179     return nullptr;
2180 
2181   // If we want to determine whether the variable should be captured from the
2182   // perspective of the current capturing scope, and we've already left all the
2183   // capturing scopes of the top directive on the stack, check from the
2184   // perspective of its parent directive (if any) instead.
2185   DSAStackTy::ParentDirectiveScope InParentDirectiveRAII(
2186       *DSAStack, CheckScopeInfo && DSAStack->isBodyComplete());
2187 
2188   // If we are attempting to capture a global variable in a directive with
2189   // 'target' we return true so that this global is also mapped to the device.
2190   //
2191   if (VD && !VD->hasLocalStorage() &&
2192       (getCurCapturedRegion() || getCurBlock() || getCurLambda())) {
2193     if (isInOpenMPTargetExecutionDirective()) {
2194       DSAStackTy::DSAVarData DVarTop =
2195           DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
2196       if (DVarTop.CKind != OMPC_unknown && DVarTop.RefExpr)
2197         return VD;
2198       // If the declaration is enclosed in a 'declare target' directive,
2199       // then it should not be captured.
2200       //
2201       if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
2202         return nullptr;
2203       CapturedRegionScopeInfo *CSI = nullptr;
2204       for (FunctionScopeInfo *FSI : llvm::drop_begin(
2205                llvm::reverse(FunctionScopes),
2206                CheckScopeInfo ? (FunctionScopes.size() - (StopAt + 1)) : 0)) {
2207         if (!isa<CapturingScopeInfo>(FSI))
2208           return nullptr;
2209         if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(FSI))
2210           if (RSI->CapRegionKind == CR_OpenMP) {
2211             CSI = RSI;
2212             break;
2213           }
2214       }
2215       assert(CSI && "Failed to find CapturedRegionScopeInfo");
2216       SmallVector<OpenMPDirectiveKind, 4> Regions;
2217       getOpenMPCaptureRegions(Regions,
2218                               DSAStack->getDirective(CSI->OpenMPLevel));
2219       if (Regions[CSI->OpenMPCaptureLevel] != OMPD_task)
2220         return VD;
2221     }
2222     if (isInOpenMPDeclareTargetContext()) {
2223       // Try to mark variable as declare target if it is used in capturing
2224       // regions.
2225       if (LangOpts.OpenMP <= 45 &&
2226           !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
2227         checkDeclIsAllowedInOpenMPTarget(nullptr, VD);
2228       return nullptr;
2229     }
2230   }
2231 
2232   if (CheckScopeInfo) {
2233     bool OpenMPFound = false;
2234     for (unsigned I = StopAt + 1; I > 0; --I) {
2235       FunctionScopeInfo *FSI = FunctionScopes[I - 1];
2236       if (!isa<CapturingScopeInfo>(FSI))
2237         return nullptr;
2238       if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(FSI))
2239         if (RSI->CapRegionKind == CR_OpenMP) {
2240           OpenMPFound = true;
2241           break;
2242         }
2243     }
2244     if (!OpenMPFound)
2245       return nullptr;
2246   }
2247 
2248   if (DSAStack->getCurrentDirective() != OMPD_unknown &&
2249       (!DSAStack->isClauseParsingMode() ||
2250        DSAStack->getParentDirective() != OMPD_unknown)) {
2251     auto &&Info = DSAStack->isLoopControlVariable(D);
2252     if (Info.first ||
2253         (VD && VD->hasLocalStorage() &&
2254          isImplicitOrExplicitTaskingRegion(DSAStack->getCurrentDirective())) ||
2255         (VD && DSAStack->isForceVarCapturing()))
2256       return VD ? VD : Info.second;
2257     DSAStackTy::DSAVarData DVarTop =
2258         DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
2259     if (DVarTop.CKind != OMPC_unknown && isOpenMPPrivate(DVarTop.CKind) &&
2260         (!VD || VD->hasLocalStorage() || !DVarTop.AppliedToPointee))
2261       return VD ? VD : cast<VarDecl>(DVarTop.PrivateCopy->getDecl());
2262     // Threadprivate variables must not be captured.
2263     if (isOpenMPThreadPrivate(DVarTop.CKind))
2264       return nullptr;
2265     // The variable is not private or it is the variable in the directive with
2266     // default(none) clause and not used in any clause.
2267     DSAStackTy::DSAVarData DVarPrivate = DSAStack->hasDSA(
2268         D,
2269         [](OpenMPClauseKind C, bool AppliedToPointee) {
2270           return isOpenMPPrivate(C) && !AppliedToPointee;
2271         },
2272         [](OpenMPDirectiveKind) { return true; },
2273         DSAStack->isClauseParsingMode());
2274     // Global shared must not be captured.
2275     if (VD && !VD->hasLocalStorage() && DVarPrivate.CKind == OMPC_unknown &&
2276         ((DSAStack->getDefaultDSA() != DSA_none &&
2277           DSAStack->getDefaultDSA() != DSA_firstprivate) ||
2278          DVarTop.CKind == OMPC_shared))
2279       return nullptr;
2280     if (DVarPrivate.CKind != OMPC_unknown ||
2281         (VD && (DSAStack->getDefaultDSA() == DSA_none ||
2282                 DSAStack->getDefaultDSA() == DSA_firstprivate)))
2283       return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
2284   }
2285   return nullptr;
2286 }
2287 
2288 void Sema::adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex,
2289                                         unsigned Level) const {
2290   FunctionScopesIndex -= getOpenMPCaptureLevels(DSAStack->getDirective(Level));
2291 }
2292 
2293 void Sema::startOpenMPLoop() {
2294   assert(LangOpts.OpenMP && "OpenMP must be enabled.");
2295   if (isOpenMPLoopDirective(DSAStack->getCurrentDirective()))
2296     DSAStack->loopInit();
2297 }
2298 
2299 void Sema::startOpenMPCXXRangeFor() {
2300   assert(LangOpts.OpenMP && "OpenMP must be enabled.");
2301   if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
2302     DSAStack->resetPossibleLoopCounter();
2303     DSAStack->loopStart();
2304   }
2305 }
2306 
2307 OpenMPClauseKind Sema::isOpenMPPrivateDecl(ValueDecl *D, unsigned Level,
2308                                            unsigned CapLevel) const {
2309   assert(LangOpts.OpenMP && "OpenMP is not allowed");
2310   if (DSAStack->hasExplicitDirective(isOpenMPTaskingDirective, Level)) {
2311     bool IsTriviallyCopyable =
2312         D->getType().getNonReferenceType().isTriviallyCopyableType(Context) &&
2313         !D->getType()
2314              .getNonReferenceType()
2315              .getCanonicalType()
2316              ->getAsCXXRecordDecl();
2317     OpenMPDirectiveKind DKind = DSAStack->getDirective(Level);
2318     SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
2319     getOpenMPCaptureRegions(CaptureRegions, DKind);
2320     if (isOpenMPTaskingDirective(CaptureRegions[CapLevel]) &&
2321         (IsTriviallyCopyable ||
2322          !isOpenMPTaskLoopDirective(CaptureRegions[CapLevel]))) {
2323       if (DSAStack->hasExplicitDSA(
2324               D,
2325               [](OpenMPClauseKind K, bool) { return K == OMPC_firstprivate; },
2326               Level, /*NotLastprivate=*/true))
2327         return OMPC_firstprivate;
2328       DSAStackTy::DSAVarData DVar = DSAStack->getImplicitDSA(D, Level);
2329       if (DVar.CKind != OMPC_shared &&
2330           !DSAStack->isLoopControlVariable(D, Level).first && !DVar.RefExpr) {
2331         DSAStack->addImplicitTaskFirstprivate(Level, D);
2332         return OMPC_firstprivate;
2333       }
2334     }
2335   }
2336   if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
2337     if (DSAStack->getAssociatedLoops() > 0 && !DSAStack->isLoopStarted()) {
2338       DSAStack->resetPossibleLoopCounter(D);
2339       DSAStack->loopStart();
2340       return OMPC_private;
2341     }
2342     if ((DSAStack->getPossiblyLoopCunter() == D->getCanonicalDecl() ||
2343          DSAStack->isLoopControlVariable(D).first) &&
2344         !DSAStack->hasExplicitDSA(
2345             D, [](OpenMPClauseKind K, bool) { return K != OMPC_private; },
2346             Level) &&
2347         !isOpenMPSimdDirective(DSAStack->getCurrentDirective()))
2348       return OMPC_private;
2349   }
2350   if (const auto *VD = dyn_cast<VarDecl>(D)) {
2351     if (DSAStack->isThreadPrivate(const_cast<VarDecl *>(VD)) &&
2352         DSAStack->isForceVarCapturing() &&
2353         !DSAStack->hasExplicitDSA(
2354             D, [](OpenMPClauseKind K, bool) { return K == OMPC_copyin; },
2355             Level))
2356       return OMPC_private;
2357   }
2358   // User-defined allocators are private since they must be defined in the
2359   // context of target region.
2360   if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level) &&
2361       DSAStack->isUsesAllocatorsDecl(Level, D).getValueOr(
2362           DSAStackTy::UsesAllocatorsDeclKind::AllocatorTrait) ==
2363           DSAStackTy::UsesAllocatorsDeclKind::UserDefinedAllocator)
2364     return OMPC_private;
2365   return (DSAStack->hasExplicitDSA(
2366               D, [](OpenMPClauseKind K, bool) { return K == OMPC_private; },
2367               Level) ||
2368           (DSAStack->isClauseParsingMode() &&
2369            DSAStack->getClauseParsingMode() == OMPC_private) ||
2370           // Consider taskgroup reduction descriptor variable a private
2371           // to avoid possible capture in the region.
2372           (DSAStack->hasExplicitDirective(
2373                [](OpenMPDirectiveKind K) {
2374                  return K == OMPD_taskgroup ||
2375                         ((isOpenMPParallelDirective(K) ||
2376                           isOpenMPWorksharingDirective(K)) &&
2377                          !isOpenMPSimdDirective(K));
2378                },
2379                Level) &&
2380            DSAStack->isTaskgroupReductionRef(D, Level)))
2381              ? OMPC_private
2382              : OMPC_unknown;
2383 }
2384 
2385 void Sema::setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D,
2386                                 unsigned Level) {
2387   assert(LangOpts.OpenMP && "OpenMP is not allowed");
2388   D = getCanonicalDecl(D);
2389   OpenMPClauseKind OMPC = OMPC_unknown;
2390   for (unsigned I = DSAStack->getNestingLevel() + 1; I > Level; --I) {
2391     const unsigned NewLevel = I - 1;
2392     if (DSAStack->hasExplicitDSA(
2393             D,
2394             [&OMPC](const OpenMPClauseKind K, bool AppliedToPointee) {
2395               if (isOpenMPPrivate(K) && !AppliedToPointee) {
2396                 OMPC = K;
2397                 return true;
2398               }
2399               return false;
2400             },
2401             NewLevel))
2402       break;
2403     if (DSAStack->checkMappableExprComponentListsForDeclAtLevel(
2404             D, NewLevel,
2405             [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
2406                OpenMPClauseKind) { return true; })) {
2407       OMPC = OMPC_map;
2408       break;
2409     }
2410     if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
2411                                        NewLevel)) {
2412       OMPC = OMPC_map;
2413       if (DSAStack->mustBeFirstprivateAtLevel(
2414               NewLevel, getVariableCategoryFromDecl(LangOpts, D)))
2415         OMPC = OMPC_firstprivate;
2416       break;
2417     }
2418   }
2419   if (OMPC != OMPC_unknown)
2420     FD->addAttr(OMPCaptureKindAttr::CreateImplicit(Context, unsigned(OMPC)));
2421 }
2422 
2423 bool Sema::isOpenMPTargetCapturedDecl(const ValueDecl *D, unsigned Level,
2424                                       unsigned CaptureLevel) const {
2425   assert(LangOpts.OpenMP && "OpenMP is not allowed");
2426   // Return true if the current level is no longer enclosed in a target region.
2427 
2428   SmallVector<OpenMPDirectiveKind, 4> Regions;
2429   getOpenMPCaptureRegions(Regions, DSAStack->getDirective(Level));
2430   const auto *VD = dyn_cast<VarDecl>(D);
2431   return VD && !VD->hasLocalStorage() &&
2432          DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
2433                                         Level) &&
2434          Regions[CaptureLevel] != OMPD_task;
2435 }
2436 
2437 bool Sema::isOpenMPGlobalCapturedDecl(ValueDecl *D, unsigned Level,
2438                                       unsigned CaptureLevel) const {
2439   assert(LangOpts.OpenMP && "OpenMP is not allowed");
2440   // Return true if the current level is no longer enclosed in a target region.
2441 
2442   if (const auto *VD = dyn_cast<VarDecl>(D)) {
2443     if (!VD->hasLocalStorage()) {
2444       if (isInOpenMPTargetExecutionDirective())
2445         return true;
2446       DSAStackTy::DSAVarData TopDVar =
2447           DSAStack->getTopDSA(D, /*FromParent=*/false);
2448       unsigned NumLevels =
2449           getOpenMPCaptureLevels(DSAStack->getDirective(Level));
2450       if (Level == 0)
2451         return (NumLevels == CaptureLevel + 1) && TopDVar.CKind != OMPC_shared;
2452       do {
2453         --Level;
2454         DSAStackTy::DSAVarData DVar = DSAStack->getImplicitDSA(D, Level);
2455         if (DVar.CKind != OMPC_shared)
2456           return true;
2457       } while (Level > 0);
2458     }
2459   }
2460   return true;
2461 }
2462 
2463 void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
2464 
2465 void Sema::ActOnOpenMPBeginDeclareVariant(SourceLocation Loc,
2466                                           OMPTraitInfo &TI) {
2467   OMPDeclareVariantScopes.push_back(OMPDeclareVariantScope(TI));
2468 }
2469 
2470 void Sema::ActOnOpenMPEndDeclareVariant() {
2471   assert(isInOpenMPDeclareVariantScope() &&
2472          "Not in OpenMP declare variant scope!");
2473 
2474   OMPDeclareVariantScopes.pop_back();
2475 }
2476 
2477 void Sema::finalizeOpenMPDelayedAnalysis(const FunctionDecl *Caller,
2478                                          const FunctionDecl *Callee,
2479                                          SourceLocation Loc) {
2480   assert(LangOpts.OpenMP && "Expected OpenMP compilation mode.");
2481   Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
2482       OMPDeclareTargetDeclAttr::getDeviceType(Caller->getMostRecentDecl());
2483   // Ignore host functions during device analyzis.
2484   if (LangOpts.OpenMPIsDevice &&
2485       (!DevTy || *DevTy == OMPDeclareTargetDeclAttr::DT_Host))
2486     return;
2487   // Ignore nohost functions during host analyzis.
2488   if (!LangOpts.OpenMPIsDevice && DevTy &&
2489       *DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
2490     return;
2491   const FunctionDecl *FD = Callee->getMostRecentDecl();
2492   DevTy = OMPDeclareTargetDeclAttr::getDeviceType(FD);
2493   if (LangOpts.OpenMPIsDevice && DevTy &&
2494       *DevTy == OMPDeclareTargetDeclAttr::DT_Host) {
2495     // Diagnose host function called during device codegen.
2496     StringRef HostDevTy =
2497         getOpenMPSimpleClauseTypeName(OMPC_device_type, OMPC_DEVICE_TYPE_host);
2498     Diag(Loc, diag::err_omp_wrong_device_function_call) << HostDevTy << 0;
2499     Diag(*OMPDeclareTargetDeclAttr::getLocation(FD),
2500          diag::note_omp_marked_device_type_here)
2501         << HostDevTy;
2502     return;
2503   }
2504   if (!LangOpts.OpenMPIsDevice && DevTy &&
2505       *DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) {
2506     // Diagnose nohost function called during host codegen.
2507     StringRef NoHostDevTy = getOpenMPSimpleClauseTypeName(
2508         OMPC_device_type, OMPC_DEVICE_TYPE_nohost);
2509     Diag(Loc, diag::err_omp_wrong_device_function_call) << NoHostDevTy << 1;
2510     Diag(*OMPDeclareTargetDeclAttr::getLocation(FD),
2511          diag::note_omp_marked_device_type_here)
2512         << NoHostDevTy;
2513   }
2514 }
2515 
2516 void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
2517                                const DeclarationNameInfo &DirName,
2518                                Scope *CurScope, SourceLocation Loc) {
2519   DSAStack->push(DKind, DirName, CurScope, Loc);
2520   PushExpressionEvaluationContext(
2521       ExpressionEvaluationContext::PotentiallyEvaluated);
2522 }
2523 
2524 void Sema::StartOpenMPClause(OpenMPClauseKind K) {
2525   DSAStack->setClauseParsingMode(K);
2526 }
2527 
2528 void Sema::EndOpenMPClause() {
2529   DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
2530   CleanupVarDeclMarking();
2531 }
2532 
2533 static std::pair<ValueDecl *, bool>
2534 getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
2535                SourceRange &ERange, bool AllowArraySection = false);
2536 
2537 /// Check consistency of the reduction clauses.
2538 static void checkReductionClauses(Sema &S, DSAStackTy *Stack,
2539                                   ArrayRef<OMPClause *> Clauses) {
2540   bool InscanFound = false;
2541   SourceLocation InscanLoc;
2542   // OpenMP 5.0, 2.19.5.4 reduction Clause, Restrictions.
2543   // A reduction clause without the inscan reduction-modifier may not appear on
2544   // a construct on which a reduction clause with the inscan reduction-modifier
2545   // appears.
2546   for (OMPClause *C : Clauses) {
2547     if (C->getClauseKind() != OMPC_reduction)
2548       continue;
2549     auto *RC = cast<OMPReductionClause>(C);
2550     if (RC->getModifier() == OMPC_REDUCTION_inscan) {
2551       InscanFound = true;
2552       InscanLoc = RC->getModifierLoc();
2553       continue;
2554     }
2555     if (RC->getModifier() == OMPC_REDUCTION_task) {
2556       // OpenMP 5.0, 2.19.5.4 reduction Clause.
2557       // A reduction clause with the task reduction-modifier may only appear on
2558       // a parallel construct, a worksharing construct or a combined or
2559       // composite construct for which any of the aforementioned constructs is a
2560       // constituent construct and simd or loop are not constituent constructs.
2561       OpenMPDirectiveKind CurDir = Stack->getCurrentDirective();
2562       if (!(isOpenMPParallelDirective(CurDir) ||
2563             isOpenMPWorksharingDirective(CurDir)) ||
2564           isOpenMPSimdDirective(CurDir))
2565         S.Diag(RC->getModifierLoc(),
2566                diag::err_omp_reduction_task_not_parallel_or_worksharing);
2567       continue;
2568     }
2569   }
2570   if (InscanFound) {
2571     for (OMPClause *C : Clauses) {
2572       if (C->getClauseKind() != OMPC_reduction)
2573         continue;
2574       auto *RC = cast<OMPReductionClause>(C);
2575       if (RC->getModifier() != OMPC_REDUCTION_inscan) {
2576         S.Diag(RC->getModifier() == OMPC_REDUCTION_unknown
2577                    ? RC->getBeginLoc()
2578                    : RC->getModifierLoc(),
2579                diag::err_omp_inscan_reduction_expected);
2580         S.Diag(InscanLoc, diag::note_omp_previous_inscan_reduction);
2581         continue;
2582       }
2583       for (Expr *Ref : RC->varlists()) {
2584         assert(Ref && "NULL expr in OpenMP nontemporal clause.");
2585         SourceLocation ELoc;
2586         SourceRange ERange;
2587         Expr *SimpleRefExpr = Ref;
2588         auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
2589                                   /*AllowArraySection=*/true);
2590         ValueDecl *D = Res.first;
2591         if (!D)
2592           continue;
2593         if (!Stack->isUsedInScanDirective(getCanonicalDecl(D))) {
2594           S.Diag(Ref->getExprLoc(),
2595                  diag::err_omp_reduction_not_inclusive_exclusive)
2596               << Ref->getSourceRange();
2597         }
2598       }
2599     }
2600   }
2601 }
2602 
2603 static void checkAllocateClauses(Sema &S, DSAStackTy *Stack,
2604                                  ArrayRef<OMPClause *> Clauses);
2605 static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
2606                                  bool WithInit);
2607 
2608 static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack,
2609                               const ValueDecl *D,
2610                               const DSAStackTy::DSAVarData &DVar,
2611                               bool IsLoopIterVar = false);
2612 
2613 void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
2614   // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
2615   //  A variable of class type (or array thereof) that appears in a lastprivate
2616   //  clause requires an accessible, unambiguous default constructor for the
2617   //  class type, unless the list item is also specified in a firstprivate
2618   //  clause.
2619   if (const auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
2620     for (OMPClause *C : D->clauses()) {
2621       if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
2622         SmallVector<Expr *, 8> PrivateCopies;
2623         for (Expr *DE : Clause->varlists()) {
2624           if (DE->isValueDependent() || DE->isTypeDependent()) {
2625             PrivateCopies.push_back(nullptr);
2626             continue;
2627           }
2628           auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
2629           auto *VD = cast<VarDecl>(DRE->getDecl());
2630           QualType Type = VD->getType().getNonReferenceType();
2631           const DSAStackTy::DSAVarData DVar =
2632               DSAStack->getTopDSA(VD, /*FromParent=*/false);
2633           if (DVar.CKind == OMPC_lastprivate) {
2634             // Generate helper private variable and initialize it with the
2635             // default value. The address of the original variable is replaced
2636             // by the address of the new private variable in CodeGen. This new
2637             // variable is not added to IdResolver, so the code in the OpenMP
2638             // region uses original variable for proper diagnostics.
2639             VarDecl *VDPrivate = buildVarDecl(
2640                 *this, DE->getExprLoc(), Type.getUnqualifiedType(),
2641                 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr, DRE);
2642             ActOnUninitializedDecl(VDPrivate);
2643             if (VDPrivate->isInvalidDecl()) {
2644               PrivateCopies.push_back(nullptr);
2645               continue;
2646             }
2647             PrivateCopies.push_back(buildDeclRefExpr(
2648                 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
2649           } else {
2650             // The variable is also a firstprivate, so initialization sequence
2651             // for private copy is generated already.
2652             PrivateCopies.push_back(nullptr);
2653           }
2654         }
2655         Clause->setPrivateCopies(PrivateCopies);
2656         continue;
2657       }
2658       // Finalize nontemporal clause by handling private copies, if any.
2659       if (auto *Clause = dyn_cast<OMPNontemporalClause>(C)) {
2660         SmallVector<Expr *, 8> PrivateRefs;
2661         for (Expr *RefExpr : Clause->varlists()) {
2662           assert(RefExpr && "NULL expr in OpenMP nontemporal clause.");
2663           SourceLocation ELoc;
2664           SourceRange ERange;
2665           Expr *SimpleRefExpr = RefExpr;
2666           auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
2667           if (Res.second)
2668             // It will be analyzed later.
2669             PrivateRefs.push_back(RefExpr);
2670           ValueDecl *D = Res.first;
2671           if (!D)
2672             continue;
2673 
2674           const DSAStackTy::DSAVarData DVar =
2675               DSAStack->getTopDSA(D, /*FromParent=*/false);
2676           PrivateRefs.push_back(DVar.PrivateCopy ? DVar.PrivateCopy
2677                                                  : SimpleRefExpr);
2678         }
2679         Clause->setPrivateRefs(PrivateRefs);
2680         continue;
2681       }
2682       if (auto *Clause = dyn_cast<OMPUsesAllocatorsClause>(C)) {
2683         for (unsigned I = 0, E = Clause->getNumberOfAllocators(); I < E; ++I) {
2684           OMPUsesAllocatorsClause::Data D = Clause->getAllocatorData(I);
2685           auto *DRE = dyn_cast<DeclRefExpr>(D.Allocator->IgnoreParenImpCasts());
2686           if (!DRE)
2687             continue;
2688           ValueDecl *VD = DRE->getDecl();
2689           if (!VD || !isa<VarDecl>(VD))
2690             continue;
2691           DSAStackTy::DSAVarData DVar =
2692               DSAStack->getTopDSA(VD, /*FromParent=*/false);
2693           // OpenMP [2.12.5, target Construct]
2694           // Memory allocators that appear in a uses_allocators clause cannot
2695           // appear in other data-sharing attribute clauses or data-mapping
2696           // attribute clauses in the same construct.
2697           Expr *MapExpr = nullptr;
2698           if (DVar.RefExpr ||
2699               DSAStack->checkMappableExprComponentListsForDecl(
2700                   VD, /*CurrentRegionOnly=*/true,
2701                   [VD, &MapExpr](
2702                       OMPClauseMappableExprCommon::MappableExprComponentListRef
2703                           MapExprComponents,
2704                       OpenMPClauseKind C) {
2705                     auto MI = MapExprComponents.rbegin();
2706                     auto ME = MapExprComponents.rend();
2707                     if (MI != ME &&
2708                         MI->getAssociatedDeclaration()->getCanonicalDecl() ==
2709                             VD->getCanonicalDecl()) {
2710                       MapExpr = MI->getAssociatedExpression();
2711                       return true;
2712                     }
2713                     return false;
2714                   })) {
2715             Diag(D.Allocator->getExprLoc(),
2716                  diag::err_omp_allocator_used_in_clauses)
2717                 << D.Allocator->getSourceRange();
2718             if (DVar.RefExpr)
2719               reportOriginalDsa(*this, DSAStack, VD, DVar);
2720             else
2721               Diag(MapExpr->getExprLoc(), diag::note_used_here)
2722                   << MapExpr->getSourceRange();
2723           }
2724         }
2725         continue;
2726       }
2727     }
2728     // Check allocate clauses.
2729     if (!CurContext->isDependentContext())
2730       checkAllocateClauses(*this, DSAStack, D->clauses());
2731     checkReductionClauses(*this, DSAStack, D->clauses());
2732   }
2733 
2734   DSAStack->pop();
2735   DiscardCleanupsInEvaluationContext();
2736   PopExpressionEvaluationContext();
2737 }
2738 
2739 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
2740                                      Expr *NumIterations, Sema &SemaRef,
2741                                      Scope *S, DSAStackTy *Stack);
2742 
2743 namespace {
2744 
2745 class VarDeclFilterCCC final : public CorrectionCandidateCallback {
2746 private:
2747   Sema &SemaRef;
2748 
2749 public:
2750   explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
2751   bool ValidateCandidate(const TypoCorrection &Candidate) override {
2752     NamedDecl *ND = Candidate.getCorrectionDecl();
2753     if (const auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
2754       return VD->hasGlobalStorage() &&
2755              SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
2756                                    SemaRef.getCurScope());
2757     }
2758     return false;
2759   }
2760 
2761   std::unique_ptr<CorrectionCandidateCallback> clone() override {
2762     return std::make_unique<VarDeclFilterCCC>(*this);
2763   }
2764 };
2765 
2766 class VarOrFuncDeclFilterCCC final : public CorrectionCandidateCallback {
2767 private:
2768   Sema &SemaRef;
2769 
2770 public:
2771   explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
2772   bool ValidateCandidate(const TypoCorrection &Candidate) override {
2773     NamedDecl *ND = Candidate.getCorrectionDecl();
2774     if (ND && ((isa<VarDecl>(ND) && ND->getKind() == Decl::Var) ||
2775                isa<FunctionDecl>(ND))) {
2776       return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
2777                                    SemaRef.getCurScope());
2778     }
2779     return false;
2780   }
2781 
2782   std::unique_ptr<CorrectionCandidateCallback> clone() override {
2783     return std::make_unique<VarOrFuncDeclFilterCCC>(*this);
2784   }
2785 };
2786 
2787 } // namespace
2788 
2789 ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
2790                                          CXXScopeSpec &ScopeSpec,
2791                                          const DeclarationNameInfo &Id,
2792                                          OpenMPDirectiveKind Kind) {
2793   LookupResult Lookup(*this, Id, LookupOrdinaryName);
2794   LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
2795 
2796   if (Lookup.isAmbiguous())
2797     return ExprError();
2798 
2799   VarDecl *VD;
2800   if (!Lookup.isSingleResult()) {
2801     VarDeclFilterCCC CCC(*this);
2802     if (TypoCorrection Corrected =
2803             CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC,
2804                         CTK_ErrorRecovery)) {
2805       diagnoseTypo(Corrected,
2806                    PDiag(Lookup.empty()
2807                              ? diag::err_undeclared_var_use_suggest
2808                              : diag::err_omp_expected_var_arg_suggest)
2809                        << Id.getName());
2810       VD = Corrected.getCorrectionDeclAs<VarDecl>();
2811     } else {
2812       Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
2813                                        : diag::err_omp_expected_var_arg)
2814           << Id.getName();
2815       return ExprError();
2816     }
2817   } else if (!(VD = Lookup.getAsSingle<VarDecl>())) {
2818     Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
2819     Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
2820     return ExprError();
2821   }
2822   Lookup.suppressDiagnostics();
2823 
2824   // OpenMP [2.9.2, Syntax, C/C++]
2825   //   Variables must be file-scope, namespace-scope, or static block-scope.
2826   if (Kind == OMPD_threadprivate && !VD->hasGlobalStorage()) {
2827     Diag(Id.getLoc(), diag::err_omp_global_var_arg)
2828         << getOpenMPDirectiveName(Kind) << !VD->isStaticLocal();
2829     bool IsDecl =
2830         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2831     Diag(VD->getLocation(),
2832          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2833         << VD;
2834     return ExprError();
2835   }
2836 
2837   VarDecl *CanonicalVD = VD->getCanonicalDecl();
2838   NamedDecl *ND = CanonicalVD;
2839   // OpenMP [2.9.2, Restrictions, C/C++, p.2]
2840   //   A threadprivate directive for file-scope variables must appear outside
2841   //   any definition or declaration.
2842   if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
2843       !getCurLexicalContext()->isTranslationUnit()) {
2844     Diag(Id.getLoc(), diag::err_omp_var_scope)
2845         << getOpenMPDirectiveName(Kind) << VD;
2846     bool IsDecl =
2847         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2848     Diag(VD->getLocation(),
2849          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2850         << VD;
2851     return ExprError();
2852   }
2853   // OpenMP [2.9.2, Restrictions, C/C++, p.3]
2854   //   A threadprivate directive for static class member variables must appear
2855   //   in the class definition, in the same scope in which the member
2856   //   variables are declared.
2857   if (CanonicalVD->isStaticDataMember() &&
2858       !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
2859     Diag(Id.getLoc(), diag::err_omp_var_scope)
2860         << getOpenMPDirectiveName(Kind) << VD;
2861     bool IsDecl =
2862         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2863     Diag(VD->getLocation(),
2864          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2865         << VD;
2866     return ExprError();
2867   }
2868   // OpenMP [2.9.2, Restrictions, C/C++, p.4]
2869   //   A threadprivate directive for namespace-scope variables must appear
2870   //   outside any definition or declaration other than the namespace
2871   //   definition itself.
2872   if (CanonicalVD->getDeclContext()->isNamespace() &&
2873       (!getCurLexicalContext()->isFileContext() ||
2874        !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
2875     Diag(Id.getLoc(), diag::err_omp_var_scope)
2876         << getOpenMPDirectiveName(Kind) << VD;
2877     bool IsDecl =
2878         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2879     Diag(VD->getLocation(),
2880          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2881         << VD;
2882     return ExprError();
2883   }
2884   // OpenMP [2.9.2, Restrictions, C/C++, p.6]
2885   //   A threadprivate directive for static block-scope variables must appear
2886   //   in the scope of the variable and not in a nested scope.
2887   if (CanonicalVD->isLocalVarDecl() && CurScope &&
2888       !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
2889     Diag(Id.getLoc(), diag::err_omp_var_scope)
2890         << getOpenMPDirectiveName(Kind) << VD;
2891     bool IsDecl =
2892         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2893     Diag(VD->getLocation(),
2894          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2895         << VD;
2896     return ExprError();
2897   }
2898 
2899   // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
2900   //   A threadprivate directive must lexically precede all references to any
2901   //   of the variables in its list.
2902   if (Kind == OMPD_threadprivate && VD->isUsed() &&
2903       !DSAStack->isThreadPrivate(VD)) {
2904     Diag(Id.getLoc(), diag::err_omp_var_used)
2905         << getOpenMPDirectiveName(Kind) << VD;
2906     return ExprError();
2907   }
2908 
2909   QualType ExprType = VD->getType().getNonReferenceType();
2910   return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
2911                              SourceLocation(), VD,
2912                              /*RefersToEnclosingVariableOrCapture=*/false,
2913                              Id.getLoc(), ExprType, VK_LValue);
2914 }
2915 
2916 Sema::DeclGroupPtrTy
2917 Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
2918                                         ArrayRef<Expr *> VarList) {
2919   if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
2920     CurContext->addDecl(D);
2921     return DeclGroupPtrTy::make(DeclGroupRef(D));
2922   }
2923   return nullptr;
2924 }
2925 
2926 namespace {
2927 class LocalVarRefChecker final
2928     : public ConstStmtVisitor<LocalVarRefChecker, bool> {
2929   Sema &SemaRef;
2930 
2931 public:
2932   bool VisitDeclRefExpr(const DeclRefExpr *E) {
2933     if (const auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
2934       if (VD->hasLocalStorage()) {
2935         SemaRef.Diag(E->getBeginLoc(),
2936                      diag::err_omp_local_var_in_threadprivate_init)
2937             << E->getSourceRange();
2938         SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
2939             << VD << VD->getSourceRange();
2940         return true;
2941       }
2942     }
2943     return false;
2944   }
2945   bool VisitStmt(const Stmt *S) {
2946     for (const Stmt *Child : S->children()) {
2947       if (Child && Visit(Child))
2948         return true;
2949     }
2950     return false;
2951   }
2952   explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
2953 };
2954 } // namespace
2955 
2956 OMPThreadPrivateDecl *
2957 Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
2958   SmallVector<Expr *, 8> Vars;
2959   for (Expr *RefExpr : VarList) {
2960     auto *DE = cast<DeclRefExpr>(RefExpr);
2961     auto *VD = cast<VarDecl>(DE->getDecl());
2962     SourceLocation ILoc = DE->getExprLoc();
2963 
2964     // Mark variable as used.
2965     VD->setReferenced();
2966     VD->markUsed(Context);
2967 
2968     QualType QType = VD->getType();
2969     if (QType->isDependentType() || QType->isInstantiationDependentType()) {
2970       // It will be analyzed later.
2971       Vars.push_back(DE);
2972       continue;
2973     }
2974 
2975     // OpenMP [2.9.2, Restrictions, C/C++, p.10]
2976     //   A threadprivate variable must not have an incomplete type.
2977     if (RequireCompleteType(ILoc, VD->getType(),
2978                             diag::err_omp_threadprivate_incomplete_type)) {
2979       continue;
2980     }
2981 
2982     // OpenMP [2.9.2, Restrictions, C/C++, p.10]
2983     //   A threadprivate variable must not have a reference type.
2984     if (VD->getType()->isReferenceType()) {
2985       Diag(ILoc, diag::err_omp_ref_type_arg)
2986           << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
2987       bool IsDecl =
2988           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2989       Diag(VD->getLocation(),
2990            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2991           << VD;
2992       continue;
2993     }
2994 
2995     // Check if this is a TLS variable. If TLS is not being supported, produce
2996     // the corresponding diagnostic.
2997     if ((VD->getTLSKind() != VarDecl::TLS_None &&
2998          !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
2999            getLangOpts().OpenMPUseTLS &&
3000            getASTContext().getTargetInfo().isTLSSupported())) ||
3001         (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
3002          !VD->isLocalVarDecl())) {
3003       Diag(ILoc, diag::err_omp_var_thread_local)
3004           << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
3005       bool IsDecl =
3006           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
3007       Diag(VD->getLocation(),
3008            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
3009           << VD;
3010       continue;
3011     }
3012 
3013     // Check if initial value of threadprivate variable reference variable with
3014     // local storage (it is not supported by runtime).
3015     if (const Expr *Init = VD->getAnyInitializer()) {
3016       LocalVarRefChecker Checker(*this);
3017       if (Checker.Visit(Init))
3018         continue;
3019     }
3020 
3021     Vars.push_back(RefExpr);
3022     DSAStack->addDSA(VD, DE, OMPC_threadprivate);
3023     VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
3024         Context, SourceRange(Loc, Loc)));
3025     if (ASTMutationListener *ML = Context.getASTMutationListener())
3026       ML->DeclarationMarkedOpenMPThreadPrivate(VD);
3027   }
3028   OMPThreadPrivateDecl *D = nullptr;
3029   if (!Vars.empty()) {
3030     D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
3031                                      Vars);
3032     D->setAccess(AS_public);
3033   }
3034   return D;
3035 }
3036 
3037 static OMPAllocateDeclAttr::AllocatorTypeTy
3038 getAllocatorKind(Sema &S, DSAStackTy *Stack, Expr *Allocator) {
3039   if (!Allocator)
3040     return OMPAllocateDeclAttr::OMPNullMemAlloc;
3041   if (Allocator->isTypeDependent() || Allocator->isValueDependent() ||
3042       Allocator->isInstantiationDependent() ||
3043       Allocator->containsUnexpandedParameterPack())
3044     return OMPAllocateDeclAttr::OMPUserDefinedMemAlloc;
3045   auto AllocatorKindRes = OMPAllocateDeclAttr::OMPUserDefinedMemAlloc;
3046   const Expr *AE = Allocator->IgnoreParenImpCasts();
3047   for (int I = 0; I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
3048     auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
3049     const Expr *DefAllocator = Stack->getAllocator(AllocatorKind);
3050     llvm::FoldingSetNodeID AEId, DAEId;
3051     AE->Profile(AEId, S.getASTContext(), /*Canonical=*/true);
3052     DefAllocator->Profile(DAEId, S.getASTContext(), /*Canonical=*/true);
3053     if (AEId == DAEId) {
3054       AllocatorKindRes = AllocatorKind;
3055       break;
3056     }
3057   }
3058   return AllocatorKindRes;
3059 }
3060 
3061 static bool checkPreviousOMPAllocateAttribute(
3062     Sema &S, DSAStackTy *Stack, Expr *RefExpr, VarDecl *VD,
3063     OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind, Expr *Allocator) {
3064   if (!VD->hasAttr<OMPAllocateDeclAttr>())
3065     return false;
3066   const auto *A = VD->getAttr<OMPAllocateDeclAttr>();
3067   Expr *PrevAllocator = A->getAllocator();
3068   OMPAllocateDeclAttr::AllocatorTypeTy PrevAllocatorKind =
3069       getAllocatorKind(S, Stack, PrevAllocator);
3070   bool AllocatorsMatch = AllocatorKind == PrevAllocatorKind;
3071   if (AllocatorsMatch &&
3072       AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc &&
3073       Allocator && PrevAllocator) {
3074     const Expr *AE = Allocator->IgnoreParenImpCasts();
3075     const Expr *PAE = PrevAllocator->IgnoreParenImpCasts();
3076     llvm::FoldingSetNodeID AEId, PAEId;
3077     AE->Profile(AEId, S.Context, /*Canonical=*/true);
3078     PAE->Profile(PAEId, S.Context, /*Canonical=*/true);
3079     AllocatorsMatch = AEId == PAEId;
3080   }
3081   if (!AllocatorsMatch) {
3082     SmallString<256> AllocatorBuffer;
3083     llvm::raw_svector_ostream AllocatorStream(AllocatorBuffer);
3084     if (Allocator)
3085       Allocator->printPretty(AllocatorStream, nullptr, S.getPrintingPolicy());
3086     SmallString<256> PrevAllocatorBuffer;
3087     llvm::raw_svector_ostream PrevAllocatorStream(PrevAllocatorBuffer);
3088     if (PrevAllocator)
3089       PrevAllocator->printPretty(PrevAllocatorStream, nullptr,
3090                                  S.getPrintingPolicy());
3091 
3092     SourceLocation AllocatorLoc =
3093         Allocator ? Allocator->getExprLoc() : RefExpr->getExprLoc();
3094     SourceRange AllocatorRange =
3095         Allocator ? Allocator->getSourceRange() : RefExpr->getSourceRange();
3096     SourceLocation PrevAllocatorLoc =
3097         PrevAllocator ? PrevAllocator->getExprLoc() : A->getLocation();
3098     SourceRange PrevAllocatorRange =
3099         PrevAllocator ? PrevAllocator->getSourceRange() : A->getRange();
3100     S.Diag(AllocatorLoc, diag::warn_omp_used_different_allocator)
3101         << (Allocator ? 1 : 0) << AllocatorStream.str()
3102         << (PrevAllocator ? 1 : 0) << PrevAllocatorStream.str()
3103         << AllocatorRange;
3104     S.Diag(PrevAllocatorLoc, diag::note_omp_previous_allocator)
3105         << PrevAllocatorRange;
3106     return true;
3107   }
3108   return false;
3109 }
3110 
3111 static void
3112 applyOMPAllocateAttribute(Sema &S, VarDecl *VD,
3113                           OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind,
3114                           Expr *Allocator, Expr *Alignment, SourceRange SR) {
3115   if (VD->hasAttr<OMPAllocateDeclAttr>())
3116     return;
3117   if (Alignment &&
3118       (Alignment->isTypeDependent() || Alignment->isValueDependent() ||
3119        Alignment->isInstantiationDependent() ||
3120        Alignment->containsUnexpandedParameterPack()))
3121     // Apply later when we have a usable value.
3122     return;
3123   if (Allocator &&
3124       (Allocator->isTypeDependent() || Allocator->isValueDependent() ||
3125        Allocator->isInstantiationDependent() ||
3126        Allocator->containsUnexpandedParameterPack()))
3127     return;
3128   auto *A = OMPAllocateDeclAttr::CreateImplicit(S.Context, AllocatorKind,
3129                                                 Allocator, Alignment, SR);
3130   VD->addAttr(A);
3131   if (ASTMutationListener *ML = S.Context.getASTMutationListener())
3132     ML->DeclarationMarkedOpenMPAllocate(VD, A);
3133 }
3134 
3135 Sema::DeclGroupPtrTy
3136 Sema::ActOnOpenMPAllocateDirective(SourceLocation Loc, ArrayRef<Expr *> VarList,
3137                                    ArrayRef<OMPClause *> Clauses,
3138                                    DeclContext *Owner) {
3139   assert(Clauses.size() <= 2 && "Expected at most two clauses.");
3140   Expr *Alignment = nullptr;
3141   Expr *Allocator = nullptr;
3142   if (Clauses.empty()) {
3143     // OpenMP 5.0, 2.11.3 allocate Directive, Restrictions.
3144     // allocate directives that appear in a target region must specify an
3145     // allocator clause unless a requires directive with the dynamic_allocators
3146     // clause is present in the same compilation unit.
3147     if (LangOpts.OpenMPIsDevice &&
3148         !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())
3149       targetDiag(Loc, diag::err_expected_allocator_clause);
3150   } else {
3151     for (const OMPClause *C : Clauses)
3152       if (const auto *AC = dyn_cast<OMPAllocatorClause>(C))
3153         Allocator = AC->getAllocator();
3154       else if (const auto *AC = dyn_cast<OMPAlignClause>(C))
3155         Alignment = AC->getAlignment();
3156       else
3157         llvm_unreachable("Unexpected clause on allocate directive");
3158   }
3159   OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind =
3160       getAllocatorKind(*this, DSAStack, Allocator);
3161   SmallVector<Expr *, 8> Vars;
3162   for (Expr *RefExpr : VarList) {
3163     auto *DE = cast<DeclRefExpr>(RefExpr);
3164     auto *VD = cast<VarDecl>(DE->getDecl());
3165 
3166     // Check if this is a TLS variable or global register.
3167     if (VD->getTLSKind() != VarDecl::TLS_None ||
3168         VD->hasAttr<OMPThreadPrivateDeclAttr>() ||
3169         (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
3170          !VD->isLocalVarDecl()))
3171       continue;
3172 
3173     // If the used several times in the allocate directive, the same allocator
3174     // must be used.
3175     if (checkPreviousOMPAllocateAttribute(*this, DSAStack, RefExpr, VD,
3176                                           AllocatorKind, Allocator))
3177       continue;
3178 
3179     // OpenMP, 2.11.3 allocate Directive, Restrictions, C / C++
3180     // If a list item has a static storage type, the allocator expression in the
3181     // allocator clause must be a constant expression that evaluates to one of
3182     // the predefined memory allocator values.
3183     if (Allocator && VD->hasGlobalStorage()) {
3184       if (AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc) {
3185         Diag(Allocator->getExprLoc(),
3186              diag::err_omp_expected_predefined_allocator)
3187             << Allocator->getSourceRange();
3188         bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
3189                       VarDecl::DeclarationOnly;
3190         Diag(VD->getLocation(),
3191              IsDecl ? diag::note_previous_decl : diag::note_defined_here)
3192             << VD;
3193         continue;
3194       }
3195     }
3196 
3197     Vars.push_back(RefExpr);
3198     applyOMPAllocateAttribute(*this, VD, AllocatorKind, Allocator, Alignment,
3199                               DE->getSourceRange());
3200   }
3201   if (Vars.empty())
3202     return nullptr;
3203   if (!Owner)
3204     Owner = getCurLexicalContext();
3205   auto *D = OMPAllocateDecl::Create(Context, Owner, Loc, Vars, Clauses);
3206   D->setAccess(AS_public);
3207   Owner->addDecl(D);
3208   return DeclGroupPtrTy::make(DeclGroupRef(D));
3209 }
3210 
3211 Sema::DeclGroupPtrTy
3212 Sema::ActOnOpenMPRequiresDirective(SourceLocation Loc,
3213                                    ArrayRef<OMPClause *> ClauseList) {
3214   OMPRequiresDecl *D = nullptr;
3215   if (!CurContext->isFileContext()) {
3216     Diag(Loc, diag::err_omp_invalid_scope) << "requires";
3217   } else {
3218     D = CheckOMPRequiresDecl(Loc, ClauseList);
3219     if (D) {
3220       CurContext->addDecl(D);
3221       DSAStack->addRequiresDecl(D);
3222     }
3223   }
3224   return DeclGroupPtrTy::make(DeclGroupRef(D));
3225 }
3226 
3227 void Sema::ActOnOpenMPAssumesDirective(SourceLocation Loc,
3228                                        OpenMPDirectiveKind DKind,
3229                                        ArrayRef<std::string> Assumptions,
3230                                        bool SkippedClauses) {
3231   if (!SkippedClauses && Assumptions.empty())
3232     Diag(Loc, diag::err_omp_no_clause_for_directive)
3233         << llvm::omp::getAllAssumeClauseOptions()
3234         << llvm::omp::getOpenMPDirectiveName(DKind);
3235 
3236   auto *AA = AssumptionAttr::Create(Context, llvm::join(Assumptions, ","), Loc);
3237   if (DKind == llvm::omp::Directive::OMPD_begin_assumes) {
3238     OMPAssumeScoped.push_back(AA);
3239     return;
3240   }
3241 
3242   // Global assumes without assumption clauses are ignored.
3243   if (Assumptions.empty())
3244     return;
3245 
3246   assert(DKind == llvm::omp::Directive::OMPD_assumes &&
3247          "Unexpected omp assumption directive!");
3248   OMPAssumeGlobal.push_back(AA);
3249 
3250   // The OMPAssumeGlobal scope above will take care of new declarations but
3251   // we also want to apply the assumption to existing ones, e.g., to
3252   // declarations in included headers. To this end, we traverse all existing
3253   // declaration contexts and annotate function declarations here.
3254   SmallVector<DeclContext *, 8> DeclContexts;
3255   auto *Ctx = CurContext;
3256   while (Ctx->getLexicalParent())
3257     Ctx = Ctx->getLexicalParent();
3258   DeclContexts.push_back(Ctx);
3259   while (!DeclContexts.empty()) {
3260     DeclContext *DC = DeclContexts.pop_back_val();
3261     for (auto *SubDC : DC->decls()) {
3262       if (SubDC->isInvalidDecl())
3263         continue;
3264       if (auto *CTD = dyn_cast<ClassTemplateDecl>(SubDC)) {
3265         DeclContexts.push_back(CTD->getTemplatedDecl());
3266         for (auto *S : CTD->specializations())
3267           DeclContexts.push_back(S);
3268         continue;
3269       }
3270       if (auto *DC = dyn_cast<DeclContext>(SubDC))
3271         DeclContexts.push_back(DC);
3272       if (auto *F = dyn_cast<FunctionDecl>(SubDC)) {
3273         F->addAttr(AA);
3274         continue;
3275       }
3276     }
3277   }
3278 }
3279 
3280 void Sema::ActOnOpenMPEndAssumesDirective() {
3281   assert(isInOpenMPAssumeScope() && "Not in OpenMP assumes scope!");
3282   OMPAssumeScoped.pop_back();
3283 }
3284 
3285 OMPRequiresDecl *Sema::CheckOMPRequiresDecl(SourceLocation Loc,
3286                                             ArrayRef<OMPClause *> ClauseList) {
3287   /// For target specific clauses, the requires directive cannot be
3288   /// specified after the handling of any of the target regions in the
3289   /// current compilation unit.
3290   ArrayRef<SourceLocation> TargetLocations =
3291       DSAStack->getEncounteredTargetLocs();
3292   SourceLocation AtomicLoc = DSAStack->getAtomicDirectiveLoc();
3293   if (!TargetLocations.empty() || !AtomicLoc.isInvalid()) {
3294     for (const OMPClause *CNew : ClauseList) {
3295       // Check if any of the requires clauses affect target regions.
3296       if (isa<OMPUnifiedSharedMemoryClause>(CNew) ||
3297           isa<OMPUnifiedAddressClause>(CNew) ||
3298           isa<OMPReverseOffloadClause>(CNew) ||
3299           isa<OMPDynamicAllocatorsClause>(CNew)) {
3300         Diag(Loc, diag::err_omp_directive_before_requires)
3301             << "target" << getOpenMPClauseName(CNew->getClauseKind());
3302         for (SourceLocation TargetLoc : TargetLocations) {
3303           Diag(TargetLoc, diag::note_omp_requires_encountered_directive)
3304               << "target";
3305         }
3306       } else if (!AtomicLoc.isInvalid() &&
3307                  isa<OMPAtomicDefaultMemOrderClause>(CNew)) {
3308         Diag(Loc, diag::err_omp_directive_before_requires)
3309             << "atomic" << getOpenMPClauseName(CNew->getClauseKind());
3310         Diag(AtomicLoc, diag::note_omp_requires_encountered_directive)
3311             << "atomic";
3312       }
3313     }
3314   }
3315 
3316   if (!DSAStack->hasDuplicateRequiresClause(ClauseList))
3317     return OMPRequiresDecl::Create(Context, getCurLexicalContext(), Loc,
3318                                    ClauseList);
3319   return nullptr;
3320 }
3321 
3322 static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack,
3323                               const ValueDecl *D,
3324                               const DSAStackTy::DSAVarData &DVar,
3325                               bool IsLoopIterVar) {
3326   if (DVar.RefExpr) {
3327     SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
3328         << getOpenMPClauseName(DVar.CKind);
3329     return;
3330   }
3331   enum {
3332     PDSA_StaticMemberShared,
3333     PDSA_StaticLocalVarShared,
3334     PDSA_LoopIterVarPrivate,
3335     PDSA_LoopIterVarLinear,
3336     PDSA_LoopIterVarLastprivate,
3337     PDSA_ConstVarShared,
3338     PDSA_GlobalVarShared,
3339     PDSA_TaskVarFirstprivate,
3340     PDSA_LocalVarPrivate,
3341     PDSA_Implicit
3342   } Reason = PDSA_Implicit;
3343   bool ReportHint = false;
3344   auto ReportLoc = D->getLocation();
3345   auto *VD = dyn_cast<VarDecl>(D);
3346   if (IsLoopIterVar) {
3347     if (DVar.CKind == OMPC_private)
3348       Reason = PDSA_LoopIterVarPrivate;
3349     else if (DVar.CKind == OMPC_lastprivate)
3350       Reason = PDSA_LoopIterVarLastprivate;
3351     else
3352       Reason = PDSA_LoopIterVarLinear;
3353   } else if (isOpenMPTaskingDirective(DVar.DKind) &&
3354              DVar.CKind == OMPC_firstprivate) {
3355     Reason = PDSA_TaskVarFirstprivate;
3356     ReportLoc = DVar.ImplicitDSALoc;
3357   } else if (VD && VD->isStaticLocal())
3358     Reason = PDSA_StaticLocalVarShared;
3359   else if (VD && VD->isStaticDataMember())
3360     Reason = PDSA_StaticMemberShared;
3361   else if (VD && VD->isFileVarDecl())
3362     Reason = PDSA_GlobalVarShared;
3363   else if (D->getType().isConstant(SemaRef.getASTContext()))
3364     Reason = PDSA_ConstVarShared;
3365   else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
3366     ReportHint = true;
3367     Reason = PDSA_LocalVarPrivate;
3368   }
3369   if (Reason != PDSA_Implicit) {
3370     SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
3371         << Reason << ReportHint
3372         << getOpenMPDirectiveName(Stack->getCurrentDirective());
3373   } else if (DVar.ImplicitDSALoc.isValid()) {
3374     SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
3375         << getOpenMPClauseName(DVar.CKind);
3376   }
3377 }
3378 
3379 static OpenMPMapClauseKind
3380 getMapClauseKindFromModifier(OpenMPDefaultmapClauseModifier M,
3381                              bool IsAggregateOrDeclareTarget) {
3382   OpenMPMapClauseKind Kind = OMPC_MAP_unknown;
3383   switch (M) {
3384   case OMPC_DEFAULTMAP_MODIFIER_alloc:
3385     Kind = OMPC_MAP_alloc;
3386     break;
3387   case OMPC_DEFAULTMAP_MODIFIER_to:
3388     Kind = OMPC_MAP_to;
3389     break;
3390   case OMPC_DEFAULTMAP_MODIFIER_from:
3391     Kind = OMPC_MAP_from;
3392     break;
3393   case OMPC_DEFAULTMAP_MODIFIER_tofrom:
3394     Kind = OMPC_MAP_tofrom;
3395     break;
3396   case OMPC_DEFAULTMAP_MODIFIER_present:
3397     // OpenMP 5.1 [2.21.7.3] defaultmap clause, Description]
3398     // If implicit-behavior is present, each variable referenced in the
3399     // construct in the category specified by variable-category is treated as if
3400     // it had been listed in a map clause with the map-type of alloc and
3401     // map-type-modifier of present.
3402     Kind = OMPC_MAP_alloc;
3403     break;
3404   case OMPC_DEFAULTMAP_MODIFIER_firstprivate:
3405   case OMPC_DEFAULTMAP_MODIFIER_last:
3406     llvm_unreachable("Unexpected defaultmap implicit behavior");
3407   case OMPC_DEFAULTMAP_MODIFIER_none:
3408   case OMPC_DEFAULTMAP_MODIFIER_default:
3409   case OMPC_DEFAULTMAP_MODIFIER_unknown:
3410     // IsAggregateOrDeclareTarget could be true if:
3411     // 1. the implicit behavior for aggregate is tofrom
3412     // 2. it's a declare target link
3413     if (IsAggregateOrDeclareTarget) {
3414       Kind = OMPC_MAP_tofrom;
3415       break;
3416     }
3417     llvm_unreachable("Unexpected defaultmap implicit behavior");
3418   }
3419   assert(Kind != OMPC_MAP_unknown && "Expect map kind to be known");
3420   return Kind;
3421 }
3422 
3423 namespace {
3424 class DSAAttrChecker final : public StmtVisitor<DSAAttrChecker, void> {
3425   DSAStackTy *Stack;
3426   Sema &SemaRef;
3427   bool ErrorFound = false;
3428   bool TryCaptureCXXThisMembers = false;
3429   CapturedStmt *CS = nullptr;
3430   const static unsigned DefaultmapKindNum = OMPC_DEFAULTMAP_pointer + 1;
3431   llvm::SmallVector<Expr *, 4> ImplicitFirstprivate;
3432   llvm::SmallVector<Expr *, 4> ImplicitMap[DefaultmapKindNum][OMPC_MAP_delete];
3433   llvm::SmallVector<OpenMPMapModifierKind, NumberOfOMPMapClauseModifiers>
3434       ImplicitMapModifier[DefaultmapKindNum];
3435   Sema::VarsWithInheritedDSAType VarsWithInheritedDSA;
3436   llvm::SmallDenseSet<const ValueDecl *, 4> ImplicitDeclarations;
3437 
3438   void VisitSubCaptures(OMPExecutableDirective *S) {
3439     // Check implicitly captured variables.
3440     if (!S->hasAssociatedStmt() || !S->getAssociatedStmt())
3441       return;
3442     if (S->getDirectiveKind() == OMPD_atomic ||
3443         S->getDirectiveKind() == OMPD_critical ||
3444         S->getDirectiveKind() == OMPD_section ||
3445         S->getDirectiveKind() == OMPD_master ||
3446         S->getDirectiveKind() == OMPD_masked ||
3447         isOpenMPLoopTransformationDirective(S->getDirectiveKind())) {
3448       Visit(S->getAssociatedStmt());
3449       return;
3450     }
3451     visitSubCaptures(S->getInnermostCapturedStmt());
3452     // Try to capture inner this->member references to generate correct mappings
3453     // and diagnostics.
3454     if (TryCaptureCXXThisMembers ||
3455         (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
3456          llvm::any_of(S->getInnermostCapturedStmt()->captures(),
3457                       [](const CapturedStmt::Capture &C) {
3458                         return C.capturesThis();
3459                       }))) {
3460       bool SavedTryCaptureCXXThisMembers = TryCaptureCXXThisMembers;
3461       TryCaptureCXXThisMembers = true;
3462       Visit(S->getInnermostCapturedStmt()->getCapturedStmt());
3463       TryCaptureCXXThisMembers = SavedTryCaptureCXXThisMembers;
3464     }
3465     // In tasks firstprivates are not captured anymore, need to analyze them
3466     // explicitly.
3467     if (isOpenMPTaskingDirective(S->getDirectiveKind()) &&
3468         !isOpenMPTaskLoopDirective(S->getDirectiveKind())) {
3469       for (OMPClause *C : S->clauses())
3470         if (auto *FC = dyn_cast<OMPFirstprivateClause>(C)) {
3471           for (Expr *Ref : FC->varlists())
3472             Visit(Ref);
3473         }
3474     }
3475   }
3476 
3477 public:
3478   void VisitDeclRefExpr(DeclRefExpr *E) {
3479     if (TryCaptureCXXThisMembers || E->isTypeDependent() ||
3480         E->isValueDependent() || E->containsUnexpandedParameterPack() ||
3481         E->isInstantiationDependent())
3482       return;
3483     if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
3484       // Check the datasharing rules for the expressions in the clauses.
3485       if (!CS || (isa<OMPCapturedExprDecl>(VD) && !CS->capturesVariable(VD) &&
3486                   !Stack->getTopDSA(VD, /*FromParent=*/false).RefExpr)) {
3487         if (auto *CED = dyn_cast<OMPCapturedExprDecl>(VD))
3488           if (!CED->hasAttr<OMPCaptureNoInitAttr>()) {
3489             Visit(CED->getInit());
3490             return;
3491           }
3492       } else if (VD->isImplicit() || isa<OMPCapturedExprDecl>(VD))
3493         // Do not analyze internal variables and do not enclose them into
3494         // implicit clauses.
3495         return;
3496       VD = VD->getCanonicalDecl();
3497       // Skip internally declared variables.
3498       if (VD->hasLocalStorage() && CS && !CS->capturesVariable(VD) &&
3499           !Stack->isImplicitTaskFirstprivate(VD))
3500         return;
3501       // Skip allocators in uses_allocators clauses.
3502       if (Stack->isUsesAllocatorsDecl(VD).hasValue())
3503         return;
3504 
3505       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
3506       // Check if the variable has explicit DSA set and stop analysis if it so.
3507       if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second)
3508         return;
3509 
3510       // Skip internally declared static variables.
3511       llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
3512           OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
3513       if (VD->hasGlobalStorage() && CS && !CS->capturesVariable(VD) &&
3514           (Stack->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() ||
3515            !Res || *Res != OMPDeclareTargetDeclAttr::MT_Link) &&
3516           !Stack->isImplicitTaskFirstprivate(VD))
3517         return;
3518 
3519       SourceLocation ELoc = E->getExprLoc();
3520       OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
3521       // The default(none) clause requires that each variable that is referenced
3522       // in the construct, and does not have a predetermined data-sharing
3523       // attribute, must have its data-sharing attribute explicitly determined
3524       // by being listed in a data-sharing attribute clause.
3525       if (DVar.CKind == OMPC_unknown &&
3526           (Stack->getDefaultDSA() == DSA_none ||
3527            Stack->getDefaultDSA() == DSA_firstprivate) &&
3528           isImplicitOrExplicitTaskingRegion(DKind) &&
3529           VarsWithInheritedDSA.count(VD) == 0) {
3530         bool InheritedDSA = Stack->getDefaultDSA() == DSA_none;
3531         if (!InheritedDSA && Stack->getDefaultDSA() == DSA_firstprivate) {
3532           DSAStackTy::DSAVarData DVar =
3533               Stack->getImplicitDSA(VD, /*FromParent=*/false);
3534           InheritedDSA = DVar.CKind == OMPC_unknown;
3535         }
3536         if (InheritedDSA)
3537           VarsWithInheritedDSA[VD] = E;
3538         return;
3539       }
3540 
3541       // OpenMP 5.0 [2.19.7.2, defaultmap clause, Description]
3542       // If implicit-behavior is none, each variable referenced in the
3543       // construct that does not have a predetermined data-sharing attribute
3544       // and does not appear in a to or link clause on a declare target
3545       // directive must be listed in a data-mapping attribute clause, a
3546       // data-haring attribute clause (including a data-sharing attribute
3547       // clause on a combined construct where target. is one of the
3548       // constituent constructs), or an is_device_ptr clause.
3549       OpenMPDefaultmapClauseKind ClauseKind =
3550           getVariableCategoryFromDecl(SemaRef.getLangOpts(), VD);
3551       if (SemaRef.getLangOpts().OpenMP >= 50) {
3552         bool IsModifierNone = Stack->getDefaultmapModifier(ClauseKind) ==
3553                               OMPC_DEFAULTMAP_MODIFIER_none;
3554         if (DVar.CKind == OMPC_unknown && IsModifierNone &&
3555             VarsWithInheritedDSA.count(VD) == 0 && !Res) {
3556           // Only check for data-mapping attribute and is_device_ptr here
3557           // since we have already make sure that the declaration does not
3558           // have a data-sharing attribute above
3559           if (!Stack->checkMappableExprComponentListsForDecl(
3560                   VD, /*CurrentRegionOnly=*/true,
3561                   [VD](OMPClauseMappableExprCommon::MappableExprComponentListRef
3562                            MapExprComponents,
3563                        OpenMPClauseKind) {
3564                     auto MI = MapExprComponents.rbegin();
3565                     auto ME = MapExprComponents.rend();
3566                     return MI != ME && MI->getAssociatedDeclaration() == VD;
3567                   })) {
3568             VarsWithInheritedDSA[VD] = E;
3569             return;
3570           }
3571         }
3572       }
3573       if (SemaRef.getLangOpts().OpenMP > 50) {
3574         bool IsModifierPresent = Stack->getDefaultmapModifier(ClauseKind) ==
3575                                  OMPC_DEFAULTMAP_MODIFIER_present;
3576         if (IsModifierPresent) {
3577           if (llvm::find(ImplicitMapModifier[ClauseKind],
3578                          OMPC_MAP_MODIFIER_present) ==
3579               std::end(ImplicitMapModifier[ClauseKind])) {
3580             ImplicitMapModifier[ClauseKind].push_back(
3581                 OMPC_MAP_MODIFIER_present);
3582           }
3583         }
3584       }
3585 
3586       if (isOpenMPTargetExecutionDirective(DKind) &&
3587           !Stack->isLoopControlVariable(VD).first) {
3588         if (!Stack->checkMappableExprComponentListsForDecl(
3589                 VD, /*CurrentRegionOnly=*/true,
3590                 [this](OMPClauseMappableExprCommon::MappableExprComponentListRef
3591                            StackComponents,
3592                        OpenMPClauseKind) {
3593                   if (SemaRef.LangOpts.OpenMP >= 50)
3594                     return !StackComponents.empty();
3595                   // Variable is used if it has been marked as an array, array
3596                   // section, array shaping or the variable iself.
3597                   return StackComponents.size() == 1 ||
3598                          std::all_of(
3599                              std::next(StackComponents.rbegin()),
3600                              StackComponents.rend(),
3601                              [](const OMPClauseMappableExprCommon::
3602                                     MappableComponent &MC) {
3603                                return MC.getAssociatedDeclaration() ==
3604                                           nullptr &&
3605                                       (isa<OMPArraySectionExpr>(
3606                                            MC.getAssociatedExpression()) ||
3607                                        isa<OMPArrayShapingExpr>(
3608                                            MC.getAssociatedExpression()) ||
3609                                        isa<ArraySubscriptExpr>(
3610                                            MC.getAssociatedExpression()));
3611                              });
3612                 })) {
3613           bool IsFirstprivate = false;
3614           // By default lambdas are captured as firstprivates.
3615           if (const auto *RD =
3616                   VD->getType().getNonReferenceType()->getAsCXXRecordDecl())
3617             IsFirstprivate = RD->isLambda();
3618           IsFirstprivate =
3619               IsFirstprivate || (Stack->mustBeFirstprivate(ClauseKind) && !Res);
3620           if (IsFirstprivate) {
3621             ImplicitFirstprivate.emplace_back(E);
3622           } else {
3623             OpenMPDefaultmapClauseModifier M =
3624                 Stack->getDefaultmapModifier(ClauseKind);
3625             OpenMPMapClauseKind Kind = getMapClauseKindFromModifier(
3626                 M, ClauseKind == OMPC_DEFAULTMAP_aggregate || Res);
3627             ImplicitMap[ClauseKind][Kind].emplace_back(E);
3628           }
3629           return;
3630         }
3631       }
3632 
3633       // OpenMP [2.9.3.6, Restrictions, p.2]
3634       //  A list item that appears in a reduction clause of the innermost
3635       //  enclosing worksharing or parallel construct may not be accessed in an
3636       //  explicit task.
3637       DVar = Stack->hasInnermostDSA(
3638           VD,
3639           [](OpenMPClauseKind C, bool AppliedToPointee) {
3640             return C == OMPC_reduction && !AppliedToPointee;
3641           },
3642           [](OpenMPDirectiveKind K) {
3643             return isOpenMPParallelDirective(K) ||
3644                    isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
3645           },
3646           /*FromParent=*/true);
3647       if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
3648         ErrorFound = true;
3649         SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
3650         reportOriginalDsa(SemaRef, Stack, VD, DVar);
3651         return;
3652       }
3653 
3654       // Define implicit data-sharing attributes for task.
3655       DVar = Stack->getImplicitDSA(VD, /*FromParent=*/false);
3656       if (((isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared) ||
3657            (Stack->getDefaultDSA() == DSA_firstprivate &&
3658             DVar.CKind == OMPC_firstprivate && !DVar.RefExpr)) &&
3659           !Stack->isLoopControlVariable(VD).first) {
3660         ImplicitFirstprivate.push_back(E);
3661         return;
3662       }
3663 
3664       // Store implicitly used globals with declare target link for parent
3665       // target.
3666       if (!isOpenMPTargetExecutionDirective(DKind) && Res &&
3667           *Res == OMPDeclareTargetDeclAttr::MT_Link) {
3668         Stack->addToParentTargetRegionLinkGlobals(E);
3669         return;
3670       }
3671     }
3672   }
3673   void VisitMemberExpr(MemberExpr *E) {
3674     if (E->isTypeDependent() || E->isValueDependent() ||
3675         E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
3676       return;
3677     auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
3678     OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
3679     if (auto *TE = dyn_cast<CXXThisExpr>(E->getBase()->IgnoreParenCasts())) {
3680       if (!FD)
3681         return;
3682       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(FD, /*FromParent=*/false);
3683       // Check if the variable has explicit DSA set and stop analysis if it
3684       // so.
3685       if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second)
3686         return;
3687 
3688       if (isOpenMPTargetExecutionDirective(DKind) &&
3689           !Stack->isLoopControlVariable(FD).first &&
3690           !Stack->checkMappableExprComponentListsForDecl(
3691               FD, /*CurrentRegionOnly=*/true,
3692               [](OMPClauseMappableExprCommon::MappableExprComponentListRef
3693                      StackComponents,
3694                  OpenMPClauseKind) {
3695                 return isa<CXXThisExpr>(
3696                     cast<MemberExpr>(
3697                         StackComponents.back().getAssociatedExpression())
3698                         ->getBase()
3699                         ->IgnoreParens());
3700               })) {
3701         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
3702         //  A bit-field cannot appear in a map clause.
3703         //
3704         if (FD->isBitField())
3705           return;
3706 
3707         // Check to see if the member expression is referencing a class that
3708         // has already been explicitly mapped
3709         if (Stack->isClassPreviouslyMapped(TE->getType()))
3710           return;
3711 
3712         OpenMPDefaultmapClauseModifier Modifier =
3713             Stack->getDefaultmapModifier(OMPC_DEFAULTMAP_aggregate);
3714         OpenMPDefaultmapClauseKind ClauseKind =
3715             getVariableCategoryFromDecl(SemaRef.getLangOpts(), FD);
3716         OpenMPMapClauseKind Kind = getMapClauseKindFromModifier(
3717             Modifier, /*IsAggregateOrDeclareTarget*/ true);
3718         ImplicitMap[ClauseKind][Kind].emplace_back(E);
3719         return;
3720       }
3721 
3722       SourceLocation ELoc = E->getExprLoc();
3723       // OpenMP [2.9.3.6, Restrictions, p.2]
3724       //  A list item that appears in a reduction clause of the innermost
3725       //  enclosing worksharing or parallel construct may not be accessed in
3726       //  an  explicit task.
3727       DVar = Stack->hasInnermostDSA(
3728           FD,
3729           [](OpenMPClauseKind C, bool AppliedToPointee) {
3730             return C == OMPC_reduction && !AppliedToPointee;
3731           },
3732           [](OpenMPDirectiveKind K) {
3733             return isOpenMPParallelDirective(K) ||
3734                    isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
3735           },
3736           /*FromParent=*/true);
3737       if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
3738         ErrorFound = true;
3739         SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
3740         reportOriginalDsa(SemaRef, Stack, FD, DVar);
3741         return;
3742       }
3743 
3744       // Define implicit data-sharing attributes for task.
3745       DVar = Stack->getImplicitDSA(FD, /*FromParent=*/false);
3746       if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
3747           !Stack->isLoopControlVariable(FD).first) {
3748         // Check if there is a captured expression for the current field in the
3749         // region. Do not mark it as firstprivate unless there is no captured
3750         // expression.
3751         // TODO: try to make it firstprivate.
3752         if (DVar.CKind != OMPC_unknown)
3753           ImplicitFirstprivate.push_back(E);
3754       }
3755       return;
3756     }
3757     if (isOpenMPTargetExecutionDirective(DKind)) {
3758       OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
3759       if (!checkMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map,
3760                                         Stack->getCurrentDirective(),
3761                                         /*NoDiagnose=*/true))
3762         return;
3763       const auto *VD = cast<ValueDecl>(
3764           CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl());
3765       if (!Stack->checkMappableExprComponentListsForDecl(
3766               VD, /*CurrentRegionOnly=*/true,
3767               [&CurComponents](
3768                   OMPClauseMappableExprCommon::MappableExprComponentListRef
3769                       StackComponents,
3770                   OpenMPClauseKind) {
3771                 auto CCI = CurComponents.rbegin();
3772                 auto CCE = CurComponents.rend();
3773                 for (const auto &SC : llvm::reverse(StackComponents)) {
3774                   // Do both expressions have the same kind?
3775                   if (CCI->getAssociatedExpression()->getStmtClass() !=
3776                       SC.getAssociatedExpression()->getStmtClass())
3777                     if (!((isa<OMPArraySectionExpr>(
3778                                SC.getAssociatedExpression()) ||
3779                            isa<OMPArrayShapingExpr>(
3780                                SC.getAssociatedExpression())) &&
3781                           isa<ArraySubscriptExpr>(
3782                               CCI->getAssociatedExpression())))
3783                       return false;
3784 
3785                   const Decl *CCD = CCI->getAssociatedDeclaration();
3786                   const Decl *SCD = SC.getAssociatedDeclaration();
3787                   CCD = CCD ? CCD->getCanonicalDecl() : nullptr;
3788                   SCD = SCD ? SCD->getCanonicalDecl() : nullptr;
3789                   if (SCD != CCD)
3790                     return false;
3791                   std::advance(CCI, 1);
3792                   if (CCI == CCE)
3793                     break;
3794                 }
3795                 return true;
3796               })) {
3797         Visit(E->getBase());
3798       }
3799     } else if (!TryCaptureCXXThisMembers) {
3800       Visit(E->getBase());
3801     }
3802   }
3803   void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
3804     for (OMPClause *C : S->clauses()) {
3805       // Skip analysis of arguments of private clauses for task|target
3806       // directives.
3807       if (isa_and_nonnull<OMPPrivateClause>(C))
3808         continue;
3809       // Skip analysis of arguments of implicitly defined firstprivate clause
3810       // for task|target directives.
3811       // Skip analysis of arguments of implicitly defined map clause for target
3812       // directives.
3813       if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) &&
3814                  C->isImplicit() &&
3815                  !isOpenMPTaskingDirective(Stack->getCurrentDirective()))) {
3816         for (Stmt *CC : C->children()) {
3817           if (CC)
3818             Visit(CC);
3819         }
3820       }
3821     }
3822     // Check implicitly captured variables.
3823     VisitSubCaptures(S);
3824   }
3825 
3826   void VisitOMPLoopTransformationDirective(OMPLoopTransformationDirective *S) {
3827     // Loop transformation directives do not introduce data sharing
3828     VisitStmt(S);
3829   }
3830 
3831   void VisitCallExpr(CallExpr *S) {
3832     for (Stmt *C : S->arguments()) {
3833       if (C) {
3834         // Check implicitly captured variables in the task-based directives to
3835         // check if they must be firstprivatized.
3836         Visit(C);
3837       }
3838     }
3839     if (Expr *Callee = S->getCallee())
3840       if (auto *CE = dyn_cast<MemberExpr>(Callee->IgnoreParenImpCasts()))
3841         Visit(CE->getBase());
3842   }
3843   void VisitStmt(Stmt *S) {
3844     for (Stmt *C : S->children()) {
3845       if (C) {
3846         // Check implicitly captured variables in the task-based directives to
3847         // check if they must be firstprivatized.
3848         Visit(C);
3849       }
3850     }
3851   }
3852 
3853   void visitSubCaptures(CapturedStmt *S) {
3854     for (const CapturedStmt::Capture &Cap : S->captures()) {
3855       if (!Cap.capturesVariable() && !Cap.capturesVariableByCopy())
3856         continue;
3857       VarDecl *VD = Cap.getCapturedVar();
3858       // Do not try to map the variable if it or its sub-component was mapped
3859       // already.
3860       if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
3861           Stack->checkMappableExprComponentListsForDecl(
3862               VD, /*CurrentRegionOnly=*/true,
3863               [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
3864                  OpenMPClauseKind) { return true; }))
3865         continue;
3866       DeclRefExpr *DRE = buildDeclRefExpr(
3867           SemaRef, VD, VD->getType().getNonLValueExprType(SemaRef.Context),
3868           Cap.getLocation(), /*RefersToCapture=*/true);
3869       Visit(DRE);
3870     }
3871   }
3872   bool isErrorFound() const { return ErrorFound; }
3873   ArrayRef<Expr *> getImplicitFirstprivate() const {
3874     return ImplicitFirstprivate;
3875   }
3876   ArrayRef<Expr *> getImplicitMap(OpenMPDefaultmapClauseKind DK,
3877                                   OpenMPMapClauseKind MK) const {
3878     return ImplicitMap[DK][MK];
3879   }
3880   ArrayRef<OpenMPMapModifierKind>
3881   getImplicitMapModifier(OpenMPDefaultmapClauseKind Kind) const {
3882     return ImplicitMapModifier[Kind];
3883   }
3884   const Sema::VarsWithInheritedDSAType &getVarsWithInheritedDSA() const {
3885     return VarsWithInheritedDSA;
3886   }
3887 
3888   DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
3889       : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {
3890     // Process declare target link variables for the target directives.
3891     if (isOpenMPTargetExecutionDirective(S->getCurrentDirective())) {
3892       for (DeclRefExpr *E : Stack->getLinkGlobals())
3893         Visit(E);
3894     }
3895   }
3896 };
3897 } // namespace
3898 
3899 static void handleDeclareVariantConstructTrait(DSAStackTy *Stack,
3900                                                OpenMPDirectiveKind DKind,
3901                                                bool ScopeEntry) {
3902   SmallVector<llvm::omp::TraitProperty, 8> Traits;
3903   if (isOpenMPTargetExecutionDirective(DKind))
3904     Traits.emplace_back(llvm::omp::TraitProperty::construct_target_target);
3905   if (isOpenMPTeamsDirective(DKind))
3906     Traits.emplace_back(llvm::omp::TraitProperty::construct_teams_teams);
3907   if (isOpenMPParallelDirective(DKind))
3908     Traits.emplace_back(llvm::omp::TraitProperty::construct_parallel_parallel);
3909   if (isOpenMPWorksharingDirective(DKind))
3910     Traits.emplace_back(llvm::omp::TraitProperty::construct_for_for);
3911   if (isOpenMPSimdDirective(DKind))
3912     Traits.emplace_back(llvm::omp::TraitProperty::construct_simd_simd);
3913   Stack->handleConstructTrait(Traits, ScopeEntry);
3914 }
3915 
3916 void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
3917   switch (DKind) {
3918   case OMPD_parallel:
3919   case OMPD_parallel_for:
3920   case OMPD_parallel_for_simd:
3921   case OMPD_parallel_sections:
3922   case OMPD_parallel_master:
3923   case OMPD_teams:
3924   case OMPD_teams_distribute:
3925   case OMPD_teams_distribute_simd: {
3926     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3927     QualType KmpInt32PtrTy =
3928         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3929     Sema::CapturedParamNameType Params[] = {
3930         std::make_pair(".global_tid.", KmpInt32PtrTy),
3931         std::make_pair(".bound_tid.", KmpInt32PtrTy),
3932         std::make_pair(StringRef(), QualType()) // __context with shared vars
3933     };
3934     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3935                              Params);
3936     break;
3937   }
3938   case OMPD_target_teams:
3939   case OMPD_target_parallel:
3940   case OMPD_target_parallel_for:
3941   case OMPD_target_parallel_for_simd:
3942   case OMPD_target_teams_distribute:
3943   case OMPD_target_teams_distribute_simd: {
3944     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3945     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3946     QualType KmpInt32PtrTy =
3947         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3948     QualType Args[] = {VoidPtrTy};
3949     FunctionProtoType::ExtProtoInfo EPI;
3950     EPI.Variadic = true;
3951     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3952     Sema::CapturedParamNameType Params[] = {
3953         std::make_pair(".global_tid.", KmpInt32Ty),
3954         std::make_pair(".part_id.", KmpInt32PtrTy),
3955         std::make_pair(".privates.", VoidPtrTy),
3956         std::make_pair(
3957             ".copy_fn.",
3958             Context.getPointerType(CopyFnType).withConst().withRestrict()),
3959         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3960         std::make_pair(StringRef(), QualType()) // __context with shared vars
3961     };
3962     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3963                              Params, /*OpenMPCaptureLevel=*/0);
3964     // Mark this captured region as inlined, because we don't use outlined
3965     // function directly.
3966     getCurCapturedRegion()->TheCapturedDecl->addAttr(
3967         AlwaysInlineAttr::CreateImplicit(
3968             Context, {}, AttributeCommonInfo::AS_Keyword,
3969             AlwaysInlineAttr::Keyword_forceinline));
3970     Sema::CapturedParamNameType ParamsTarget[] = {
3971         std::make_pair(StringRef(), QualType()) // __context with shared vars
3972     };
3973     // Start a captured region for 'target' with no implicit parameters.
3974     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3975                              ParamsTarget, /*OpenMPCaptureLevel=*/1);
3976     Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
3977         std::make_pair(".global_tid.", KmpInt32PtrTy),
3978         std::make_pair(".bound_tid.", KmpInt32PtrTy),
3979         std::make_pair(StringRef(), QualType()) // __context with shared vars
3980     };
3981     // Start a captured region for 'teams' or 'parallel'.  Both regions have
3982     // the same implicit parameters.
3983     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3984                              ParamsTeamsOrParallel, /*OpenMPCaptureLevel=*/2);
3985     break;
3986   }
3987   case OMPD_target:
3988   case OMPD_target_simd: {
3989     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3990     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3991     QualType KmpInt32PtrTy =
3992         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3993     QualType Args[] = {VoidPtrTy};
3994     FunctionProtoType::ExtProtoInfo EPI;
3995     EPI.Variadic = true;
3996     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3997     Sema::CapturedParamNameType Params[] = {
3998         std::make_pair(".global_tid.", KmpInt32Ty),
3999         std::make_pair(".part_id.", KmpInt32PtrTy),
4000         std::make_pair(".privates.", VoidPtrTy),
4001         std::make_pair(
4002             ".copy_fn.",
4003             Context.getPointerType(CopyFnType).withConst().withRestrict()),
4004         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
4005         std::make_pair(StringRef(), QualType()) // __context with shared vars
4006     };
4007     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4008                              Params, /*OpenMPCaptureLevel=*/0);
4009     // Mark this captured region as inlined, because we don't use outlined
4010     // function directly.
4011     getCurCapturedRegion()->TheCapturedDecl->addAttr(
4012         AlwaysInlineAttr::CreateImplicit(
4013             Context, {}, AttributeCommonInfo::AS_Keyword,
4014             AlwaysInlineAttr::Keyword_forceinline));
4015     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4016                              std::make_pair(StringRef(), QualType()),
4017                              /*OpenMPCaptureLevel=*/1);
4018     break;
4019   }
4020   case OMPD_atomic:
4021   case OMPD_critical:
4022   case OMPD_section:
4023   case OMPD_master:
4024   case OMPD_masked:
4025   case OMPD_tile:
4026   case OMPD_unroll:
4027     break;
4028   case OMPD_loop:
4029     // TODO: 'loop' may require additional parameters depending on the binding.
4030     // Treat similar to OMPD_simd/OMPD_for for now.
4031   case OMPD_simd:
4032   case OMPD_for:
4033   case OMPD_for_simd:
4034   case OMPD_sections:
4035   case OMPD_single:
4036   case OMPD_taskgroup:
4037   case OMPD_distribute:
4038   case OMPD_distribute_simd:
4039   case OMPD_ordered:
4040   case OMPD_target_data:
4041   case OMPD_dispatch: {
4042     Sema::CapturedParamNameType Params[] = {
4043         std::make_pair(StringRef(), QualType()) // __context with shared vars
4044     };
4045     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4046                              Params);
4047     break;
4048   }
4049   case OMPD_task: {
4050     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
4051     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
4052     QualType KmpInt32PtrTy =
4053         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
4054     QualType Args[] = {VoidPtrTy};
4055     FunctionProtoType::ExtProtoInfo EPI;
4056     EPI.Variadic = true;
4057     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
4058     Sema::CapturedParamNameType Params[] = {
4059         std::make_pair(".global_tid.", KmpInt32Ty),
4060         std::make_pair(".part_id.", KmpInt32PtrTy),
4061         std::make_pair(".privates.", VoidPtrTy),
4062         std::make_pair(
4063             ".copy_fn.",
4064             Context.getPointerType(CopyFnType).withConst().withRestrict()),
4065         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
4066         std::make_pair(StringRef(), QualType()) // __context with shared vars
4067     };
4068     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4069                              Params);
4070     // Mark this captured region as inlined, because we don't use outlined
4071     // function directly.
4072     getCurCapturedRegion()->TheCapturedDecl->addAttr(
4073         AlwaysInlineAttr::CreateImplicit(
4074             Context, {}, AttributeCommonInfo::AS_Keyword,
4075             AlwaysInlineAttr::Keyword_forceinline));
4076     break;
4077   }
4078   case OMPD_taskloop:
4079   case OMPD_taskloop_simd:
4080   case OMPD_master_taskloop:
4081   case OMPD_master_taskloop_simd: {
4082     QualType KmpInt32Ty =
4083         Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1)
4084             .withConst();
4085     QualType KmpUInt64Ty =
4086         Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0)
4087             .withConst();
4088     QualType KmpInt64Ty =
4089         Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1)
4090             .withConst();
4091     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
4092     QualType KmpInt32PtrTy =
4093         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
4094     QualType Args[] = {VoidPtrTy};
4095     FunctionProtoType::ExtProtoInfo EPI;
4096     EPI.Variadic = true;
4097     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
4098     Sema::CapturedParamNameType Params[] = {
4099         std::make_pair(".global_tid.", KmpInt32Ty),
4100         std::make_pair(".part_id.", KmpInt32PtrTy),
4101         std::make_pair(".privates.", VoidPtrTy),
4102         std::make_pair(
4103             ".copy_fn.",
4104             Context.getPointerType(CopyFnType).withConst().withRestrict()),
4105         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
4106         std::make_pair(".lb.", KmpUInt64Ty),
4107         std::make_pair(".ub.", KmpUInt64Ty),
4108         std::make_pair(".st.", KmpInt64Ty),
4109         std::make_pair(".liter.", KmpInt32Ty),
4110         std::make_pair(".reductions.", VoidPtrTy),
4111         std::make_pair(StringRef(), QualType()) // __context with shared vars
4112     };
4113     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4114                              Params);
4115     // Mark this captured region as inlined, because we don't use outlined
4116     // function directly.
4117     getCurCapturedRegion()->TheCapturedDecl->addAttr(
4118         AlwaysInlineAttr::CreateImplicit(
4119             Context, {}, AttributeCommonInfo::AS_Keyword,
4120             AlwaysInlineAttr::Keyword_forceinline));
4121     break;
4122   }
4123   case OMPD_parallel_master_taskloop:
4124   case OMPD_parallel_master_taskloop_simd: {
4125     QualType KmpInt32Ty =
4126         Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1)
4127             .withConst();
4128     QualType KmpUInt64Ty =
4129         Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0)
4130             .withConst();
4131     QualType KmpInt64Ty =
4132         Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1)
4133             .withConst();
4134     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
4135     QualType KmpInt32PtrTy =
4136         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
4137     Sema::CapturedParamNameType ParamsParallel[] = {
4138         std::make_pair(".global_tid.", KmpInt32PtrTy),
4139         std::make_pair(".bound_tid.", KmpInt32PtrTy),
4140         std::make_pair(StringRef(), QualType()) // __context with shared vars
4141     };
4142     // Start a captured region for 'parallel'.
4143     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4144                              ParamsParallel, /*OpenMPCaptureLevel=*/0);
4145     QualType Args[] = {VoidPtrTy};
4146     FunctionProtoType::ExtProtoInfo EPI;
4147     EPI.Variadic = true;
4148     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
4149     Sema::CapturedParamNameType Params[] = {
4150         std::make_pair(".global_tid.", KmpInt32Ty),
4151         std::make_pair(".part_id.", KmpInt32PtrTy),
4152         std::make_pair(".privates.", VoidPtrTy),
4153         std::make_pair(
4154             ".copy_fn.",
4155             Context.getPointerType(CopyFnType).withConst().withRestrict()),
4156         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
4157         std::make_pair(".lb.", KmpUInt64Ty),
4158         std::make_pair(".ub.", KmpUInt64Ty),
4159         std::make_pair(".st.", KmpInt64Ty),
4160         std::make_pair(".liter.", KmpInt32Ty),
4161         std::make_pair(".reductions.", VoidPtrTy),
4162         std::make_pair(StringRef(), QualType()) // __context with shared vars
4163     };
4164     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4165                              Params, /*OpenMPCaptureLevel=*/1);
4166     // Mark this captured region as inlined, because we don't use outlined
4167     // function directly.
4168     getCurCapturedRegion()->TheCapturedDecl->addAttr(
4169         AlwaysInlineAttr::CreateImplicit(
4170             Context, {}, AttributeCommonInfo::AS_Keyword,
4171             AlwaysInlineAttr::Keyword_forceinline));
4172     break;
4173   }
4174   case OMPD_distribute_parallel_for_simd:
4175   case OMPD_distribute_parallel_for: {
4176     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
4177     QualType KmpInt32PtrTy =
4178         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
4179     Sema::CapturedParamNameType Params[] = {
4180         std::make_pair(".global_tid.", KmpInt32PtrTy),
4181         std::make_pair(".bound_tid.", KmpInt32PtrTy),
4182         std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
4183         std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
4184         std::make_pair(StringRef(), QualType()) // __context with shared vars
4185     };
4186     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4187                              Params);
4188     break;
4189   }
4190   case OMPD_target_teams_distribute_parallel_for:
4191   case OMPD_target_teams_distribute_parallel_for_simd: {
4192     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
4193     QualType KmpInt32PtrTy =
4194         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
4195     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
4196 
4197     QualType Args[] = {VoidPtrTy};
4198     FunctionProtoType::ExtProtoInfo EPI;
4199     EPI.Variadic = true;
4200     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
4201     Sema::CapturedParamNameType Params[] = {
4202         std::make_pair(".global_tid.", KmpInt32Ty),
4203         std::make_pair(".part_id.", KmpInt32PtrTy),
4204         std::make_pair(".privates.", VoidPtrTy),
4205         std::make_pair(
4206             ".copy_fn.",
4207             Context.getPointerType(CopyFnType).withConst().withRestrict()),
4208         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
4209         std::make_pair(StringRef(), QualType()) // __context with shared vars
4210     };
4211     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4212                              Params, /*OpenMPCaptureLevel=*/0);
4213     // Mark this captured region as inlined, because we don't use outlined
4214     // function directly.
4215     getCurCapturedRegion()->TheCapturedDecl->addAttr(
4216         AlwaysInlineAttr::CreateImplicit(
4217             Context, {}, AttributeCommonInfo::AS_Keyword,
4218             AlwaysInlineAttr::Keyword_forceinline));
4219     Sema::CapturedParamNameType ParamsTarget[] = {
4220         std::make_pair(StringRef(), QualType()) // __context with shared vars
4221     };
4222     // Start a captured region for 'target' with no implicit parameters.
4223     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4224                              ParamsTarget, /*OpenMPCaptureLevel=*/1);
4225 
4226     Sema::CapturedParamNameType ParamsTeams[] = {
4227         std::make_pair(".global_tid.", KmpInt32PtrTy),
4228         std::make_pair(".bound_tid.", KmpInt32PtrTy),
4229         std::make_pair(StringRef(), QualType()) // __context with shared vars
4230     };
4231     // Start a captured region for 'target' with no implicit parameters.
4232     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4233                              ParamsTeams, /*OpenMPCaptureLevel=*/2);
4234 
4235     Sema::CapturedParamNameType ParamsParallel[] = {
4236         std::make_pair(".global_tid.", KmpInt32PtrTy),
4237         std::make_pair(".bound_tid.", KmpInt32PtrTy),
4238         std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
4239         std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
4240         std::make_pair(StringRef(), QualType()) // __context with shared vars
4241     };
4242     // Start a captured region for 'teams' or 'parallel'.  Both regions have
4243     // the same implicit parameters.
4244     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4245                              ParamsParallel, /*OpenMPCaptureLevel=*/3);
4246     break;
4247   }
4248 
4249   case OMPD_teams_distribute_parallel_for:
4250   case OMPD_teams_distribute_parallel_for_simd: {
4251     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
4252     QualType KmpInt32PtrTy =
4253         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
4254 
4255     Sema::CapturedParamNameType ParamsTeams[] = {
4256         std::make_pair(".global_tid.", KmpInt32PtrTy),
4257         std::make_pair(".bound_tid.", KmpInt32PtrTy),
4258         std::make_pair(StringRef(), QualType()) // __context with shared vars
4259     };
4260     // Start a captured region for 'target' with no implicit parameters.
4261     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4262                              ParamsTeams, /*OpenMPCaptureLevel=*/0);
4263 
4264     Sema::CapturedParamNameType ParamsParallel[] = {
4265         std::make_pair(".global_tid.", KmpInt32PtrTy),
4266         std::make_pair(".bound_tid.", KmpInt32PtrTy),
4267         std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
4268         std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
4269         std::make_pair(StringRef(), QualType()) // __context with shared vars
4270     };
4271     // Start a captured region for 'teams' or 'parallel'.  Both regions have
4272     // the same implicit parameters.
4273     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4274                              ParamsParallel, /*OpenMPCaptureLevel=*/1);
4275     break;
4276   }
4277   case OMPD_target_update:
4278   case OMPD_target_enter_data:
4279   case OMPD_target_exit_data: {
4280     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
4281     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
4282     QualType KmpInt32PtrTy =
4283         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
4284     QualType Args[] = {VoidPtrTy};
4285     FunctionProtoType::ExtProtoInfo EPI;
4286     EPI.Variadic = true;
4287     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
4288     Sema::CapturedParamNameType Params[] = {
4289         std::make_pair(".global_tid.", KmpInt32Ty),
4290         std::make_pair(".part_id.", KmpInt32PtrTy),
4291         std::make_pair(".privates.", VoidPtrTy),
4292         std::make_pair(
4293             ".copy_fn.",
4294             Context.getPointerType(CopyFnType).withConst().withRestrict()),
4295         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
4296         std::make_pair(StringRef(), QualType()) // __context with shared vars
4297     };
4298     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
4299                              Params);
4300     // Mark this captured region as inlined, because we don't use outlined
4301     // function directly.
4302     getCurCapturedRegion()->TheCapturedDecl->addAttr(
4303         AlwaysInlineAttr::CreateImplicit(
4304             Context, {}, AttributeCommonInfo::AS_Keyword,
4305             AlwaysInlineAttr::Keyword_forceinline));
4306     break;
4307   }
4308   case OMPD_threadprivate:
4309   case OMPD_allocate:
4310   case OMPD_taskyield:
4311   case OMPD_barrier:
4312   case OMPD_taskwait:
4313   case OMPD_cancellation_point:
4314   case OMPD_cancel:
4315   case OMPD_flush:
4316   case OMPD_depobj:
4317   case OMPD_scan:
4318   case OMPD_declare_reduction:
4319   case OMPD_declare_mapper:
4320   case OMPD_declare_simd:
4321   case OMPD_declare_target:
4322   case OMPD_end_declare_target:
4323   case OMPD_requires:
4324   case OMPD_declare_variant:
4325   case OMPD_begin_declare_variant:
4326   case OMPD_end_declare_variant:
4327   case OMPD_metadirective:
4328     llvm_unreachable("OpenMP Directive is not allowed");
4329   case OMPD_unknown:
4330   default:
4331     llvm_unreachable("Unknown OpenMP directive");
4332   }
4333   DSAStack->setContext(CurContext);
4334   handleDeclareVariantConstructTrait(DSAStack, DKind, /* ScopeEntry */ true);
4335 }
4336 
4337 int Sema::getNumberOfConstructScopes(unsigned Level) const {
4338   return getOpenMPCaptureLevels(DSAStack->getDirective(Level));
4339 }
4340 
4341 int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
4342   SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
4343   getOpenMPCaptureRegions(CaptureRegions, DKind);
4344   return CaptureRegions.size();
4345 }
4346 
4347 static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
4348                                              Expr *CaptureExpr, bool WithInit,
4349                                              bool AsExpression) {
4350   assert(CaptureExpr);
4351   ASTContext &C = S.getASTContext();
4352   Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
4353   QualType Ty = Init->getType();
4354   if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
4355     if (S.getLangOpts().CPlusPlus) {
4356       Ty = C.getLValueReferenceType(Ty);
4357     } else {
4358       Ty = C.getPointerType(Ty);
4359       ExprResult Res =
4360           S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
4361       if (!Res.isUsable())
4362         return nullptr;
4363       Init = Res.get();
4364     }
4365     WithInit = true;
4366   }
4367   auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
4368                                           CaptureExpr->getBeginLoc());
4369   if (!WithInit)
4370     CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C));
4371   S.CurContext->addHiddenDecl(CED);
4372   Sema::TentativeAnalysisScope Trap(S);
4373   S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
4374   return CED;
4375 }
4376 
4377 static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
4378                                  bool WithInit) {
4379   OMPCapturedExprDecl *CD;
4380   if (VarDecl *VD = S.isOpenMPCapturedDecl(D))
4381     CD = cast<OMPCapturedExprDecl>(VD);
4382   else
4383     CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
4384                           /*AsExpression=*/false);
4385   return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
4386                           CaptureExpr->getExprLoc());
4387 }
4388 
4389 static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
4390   CaptureExpr = S.DefaultLvalueConversion(CaptureExpr).get();
4391   if (!Ref) {
4392     OMPCapturedExprDecl *CD = buildCaptureDecl(
4393         S, &S.getASTContext().Idents.get(".capture_expr."), CaptureExpr,
4394         /*WithInit=*/true, /*AsExpression=*/true);
4395     Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
4396                            CaptureExpr->getExprLoc());
4397   }
4398   ExprResult Res = Ref;
4399   if (!S.getLangOpts().CPlusPlus &&
4400       CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
4401       Ref->getType()->isPointerType()) {
4402     Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
4403     if (!Res.isUsable())
4404       return ExprError();
4405   }
4406   return S.DefaultLvalueConversion(Res.get());
4407 }
4408 
4409 namespace {
4410 // OpenMP directives parsed in this section are represented as a
4411 // CapturedStatement with an associated statement.  If a syntax error
4412 // is detected during the parsing of the associated statement, the
4413 // compiler must abort processing and close the CapturedStatement.
4414 //
4415 // Combined directives such as 'target parallel' have more than one
4416 // nested CapturedStatements.  This RAII ensures that we unwind out
4417 // of all the nested CapturedStatements when an error is found.
4418 class CaptureRegionUnwinderRAII {
4419 private:
4420   Sema &S;
4421   bool &ErrorFound;
4422   OpenMPDirectiveKind DKind = OMPD_unknown;
4423 
4424 public:
4425   CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
4426                             OpenMPDirectiveKind DKind)
4427       : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
4428   ~CaptureRegionUnwinderRAII() {
4429     if (ErrorFound) {
4430       int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
4431       while (--ThisCaptureLevel >= 0)
4432         S.ActOnCapturedRegionError();
4433     }
4434   }
4435 };
4436 } // namespace
4437 
4438 void Sema::tryCaptureOpenMPLambdas(ValueDecl *V) {
4439   // Capture variables captured by reference in lambdas for target-based
4440   // directives.
4441   if (!CurContext->isDependentContext() &&
4442       (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) ||
4443        isOpenMPTargetDataManagementDirective(
4444            DSAStack->getCurrentDirective()))) {
4445     QualType Type = V->getType();
4446     if (const auto *RD = Type.getCanonicalType()
4447                              .getNonReferenceType()
4448                              ->getAsCXXRecordDecl()) {
4449       bool SavedForceCaptureByReferenceInTargetExecutable =
4450           DSAStack->isForceCaptureByReferenceInTargetExecutable();
4451       DSAStack->setForceCaptureByReferenceInTargetExecutable(
4452           /*V=*/true);
4453       if (RD->isLambda()) {
4454         llvm::DenseMap<const VarDecl *, FieldDecl *> Captures;
4455         FieldDecl *ThisCapture;
4456         RD->getCaptureFields(Captures, ThisCapture);
4457         for (const LambdaCapture &LC : RD->captures()) {
4458           if (LC.getCaptureKind() == LCK_ByRef) {
4459             VarDecl *VD = LC.getCapturedVar();
4460             DeclContext *VDC = VD->getDeclContext();
4461             if (!VDC->Encloses(CurContext))
4462               continue;
4463             MarkVariableReferenced(LC.getLocation(), VD);
4464           } else if (LC.getCaptureKind() == LCK_This) {
4465             QualType ThisTy = getCurrentThisType();
4466             if (!ThisTy.isNull() &&
4467                 Context.typesAreCompatible(ThisTy, ThisCapture->getType()))
4468               CheckCXXThisCapture(LC.getLocation());
4469           }
4470         }
4471       }
4472       DSAStack->setForceCaptureByReferenceInTargetExecutable(
4473           SavedForceCaptureByReferenceInTargetExecutable);
4474     }
4475   }
4476 }
4477 
4478 static bool checkOrderedOrderSpecified(Sema &S,
4479                                        const ArrayRef<OMPClause *> Clauses) {
4480   const OMPOrderedClause *Ordered = nullptr;
4481   const OMPOrderClause *Order = nullptr;
4482 
4483   for (const OMPClause *Clause : Clauses) {
4484     if (Clause->getClauseKind() == OMPC_ordered)
4485       Ordered = cast<OMPOrderedClause>(Clause);
4486     else if (Clause->getClauseKind() == OMPC_order) {
4487       Order = cast<OMPOrderClause>(Clause);
4488       if (Order->getKind() != OMPC_ORDER_concurrent)
4489         Order = nullptr;
4490     }
4491     if (Ordered && Order)
4492       break;
4493   }
4494 
4495   if (Ordered && Order) {
4496     S.Diag(Order->getKindKwLoc(),
4497            diag::err_omp_simple_clause_incompatible_with_ordered)
4498         << getOpenMPClauseName(OMPC_order)
4499         << getOpenMPSimpleClauseTypeName(OMPC_order, OMPC_ORDER_concurrent)
4500         << SourceRange(Order->getBeginLoc(), Order->getEndLoc());
4501     S.Diag(Ordered->getBeginLoc(), diag::note_omp_ordered_param)
4502         << 0 << SourceRange(Ordered->getBeginLoc(), Ordered->getEndLoc());
4503     return true;
4504   }
4505   return false;
4506 }
4507 
4508 StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
4509                                       ArrayRef<OMPClause *> Clauses) {
4510   handleDeclareVariantConstructTrait(DSAStack, DSAStack->getCurrentDirective(),
4511                                      /* ScopeEntry */ false);
4512   if (DSAStack->getCurrentDirective() == OMPD_atomic ||
4513       DSAStack->getCurrentDirective() == OMPD_critical ||
4514       DSAStack->getCurrentDirective() == OMPD_section ||
4515       DSAStack->getCurrentDirective() == OMPD_master ||
4516       DSAStack->getCurrentDirective() == OMPD_masked)
4517     return S;
4518 
4519   bool ErrorFound = false;
4520   CaptureRegionUnwinderRAII CaptureRegionUnwinder(
4521       *this, ErrorFound, DSAStack->getCurrentDirective());
4522   if (!S.isUsable()) {
4523     ErrorFound = true;
4524     return StmtError();
4525   }
4526 
4527   SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
4528   getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
4529   OMPOrderedClause *OC = nullptr;
4530   OMPScheduleClause *SC = nullptr;
4531   SmallVector<const OMPLinearClause *, 4> LCs;
4532   SmallVector<const OMPClauseWithPreInit *, 4> PICs;
4533   // This is required for proper codegen.
4534   for (OMPClause *Clause : Clauses) {
4535     if (!LangOpts.OpenMPSimd &&
4536         isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) &&
4537         Clause->getClauseKind() == OMPC_in_reduction) {
4538       // Capture taskgroup task_reduction descriptors inside the tasking regions
4539       // with the corresponding in_reduction items.
4540       auto *IRC = cast<OMPInReductionClause>(Clause);
4541       for (Expr *E : IRC->taskgroup_descriptors())
4542         if (E)
4543           MarkDeclarationsReferencedInExpr(E);
4544     }
4545     if (isOpenMPPrivate(Clause->getClauseKind()) ||
4546         Clause->getClauseKind() == OMPC_copyprivate ||
4547         (getLangOpts().OpenMPUseTLS &&
4548          getASTContext().getTargetInfo().isTLSSupported() &&
4549          Clause->getClauseKind() == OMPC_copyin)) {
4550       DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
4551       // Mark all variables in private list clauses as used in inner region.
4552       for (Stmt *VarRef : Clause->children()) {
4553         if (auto *E = cast_or_null<Expr>(VarRef)) {
4554           MarkDeclarationsReferencedInExpr(E);
4555         }
4556       }
4557       DSAStack->setForceVarCapturing(/*V=*/false);
4558     } else if (isOpenMPLoopTransformationDirective(
4559                    DSAStack->getCurrentDirective())) {
4560       assert(CaptureRegions.empty() &&
4561              "No captured regions in loop transformation directives.");
4562     } else if (CaptureRegions.size() > 1 ||
4563                CaptureRegions.back() != OMPD_unknown) {
4564       if (auto *C = OMPClauseWithPreInit::get(Clause))
4565         PICs.push_back(C);
4566       if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
4567         if (Expr *E = C->getPostUpdateExpr())
4568           MarkDeclarationsReferencedInExpr(E);
4569       }
4570     }
4571     if (Clause->getClauseKind() == OMPC_schedule)
4572       SC = cast<OMPScheduleClause>(Clause);
4573     else if (Clause->getClauseKind() == OMPC_ordered)
4574       OC = cast<OMPOrderedClause>(Clause);
4575     else if (Clause->getClauseKind() == OMPC_linear)
4576       LCs.push_back(cast<OMPLinearClause>(Clause));
4577   }
4578   // Capture allocator expressions if used.
4579   for (Expr *E : DSAStack->getInnerAllocators())
4580     MarkDeclarationsReferencedInExpr(E);
4581   // OpenMP, 2.7.1 Loop Construct, Restrictions
4582   // The nonmonotonic modifier cannot be specified if an ordered clause is
4583   // specified.
4584   if (SC &&
4585       (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
4586        SC->getSecondScheduleModifier() ==
4587            OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
4588       OC) {
4589     Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
4590              ? SC->getFirstScheduleModifierLoc()
4591              : SC->getSecondScheduleModifierLoc(),
4592          diag::err_omp_simple_clause_incompatible_with_ordered)
4593         << getOpenMPClauseName(OMPC_schedule)
4594         << getOpenMPSimpleClauseTypeName(OMPC_schedule,
4595                                          OMPC_SCHEDULE_MODIFIER_nonmonotonic)
4596         << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
4597     ErrorFound = true;
4598   }
4599   // OpenMP 5.0, 2.9.2 Worksharing-Loop Construct, Restrictions.
4600   // If an order(concurrent) clause is present, an ordered clause may not appear
4601   // on the same directive.
4602   if (checkOrderedOrderSpecified(*this, Clauses))
4603     ErrorFound = true;
4604   if (!LCs.empty() && OC && OC->getNumForLoops()) {
4605     for (const OMPLinearClause *C : LCs) {
4606       Diag(C->getBeginLoc(), diag::err_omp_linear_ordered)
4607           << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
4608     }
4609     ErrorFound = true;
4610   }
4611   if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
4612       isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
4613       OC->getNumForLoops()) {
4614     Diag(OC->getBeginLoc(), diag::err_omp_ordered_simd)
4615         << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
4616     ErrorFound = true;
4617   }
4618   if (ErrorFound) {
4619     return StmtError();
4620   }
4621   StmtResult SR = S;
4622   unsigned CompletedRegions = 0;
4623   for (OpenMPDirectiveKind ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
4624     // Mark all variables in private list clauses as used in inner region.
4625     // Required for proper codegen of combined directives.
4626     // TODO: add processing for other clauses.
4627     if (ThisCaptureRegion != OMPD_unknown) {
4628       for (const clang::OMPClauseWithPreInit *C : PICs) {
4629         OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
4630         // Find the particular capture region for the clause if the
4631         // directive is a combined one with multiple capture regions.
4632         // If the directive is not a combined one, the capture region
4633         // associated with the clause is OMPD_unknown and is generated
4634         // only once.
4635         if (CaptureRegion == ThisCaptureRegion ||
4636             CaptureRegion == OMPD_unknown) {
4637           if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
4638             for (Decl *D : DS->decls())
4639               MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
4640           }
4641         }
4642       }
4643     }
4644     if (ThisCaptureRegion == OMPD_target) {
4645       // Capture allocator traits in the target region. They are used implicitly
4646       // and, thus, are not captured by default.
4647       for (OMPClause *C : Clauses) {
4648         if (const auto *UAC = dyn_cast<OMPUsesAllocatorsClause>(C)) {
4649           for (unsigned I = 0, End = UAC->getNumberOfAllocators(); I < End;
4650                ++I) {
4651             OMPUsesAllocatorsClause::Data D = UAC->getAllocatorData(I);
4652             if (Expr *E = D.AllocatorTraits)
4653               MarkDeclarationsReferencedInExpr(E);
4654           }
4655           continue;
4656         }
4657       }
4658     }
4659     if (ThisCaptureRegion == OMPD_parallel) {
4660       // Capture temp arrays for inscan reductions and locals in aligned
4661       // clauses.
4662       for (OMPClause *C : Clauses) {
4663         if (auto *RC = dyn_cast<OMPReductionClause>(C)) {
4664           if (RC->getModifier() != OMPC_REDUCTION_inscan)
4665             continue;
4666           for (Expr *E : RC->copy_array_temps())
4667             MarkDeclarationsReferencedInExpr(E);
4668         }
4669         if (auto *AC = dyn_cast<OMPAlignedClause>(C)) {
4670           for (Expr *E : AC->varlists())
4671             MarkDeclarationsReferencedInExpr(E);
4672         }
4673       }
4674     }
4675     if (++CompletedRegions == CaptureRegions.size())
4676       DSAStack->setBodyComplete();
4677     SR = ActOnCapturedRegionEnd(SR.get());
4678   }
4679   return SR;
4680 }
4681 
4682 static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
4683                               OpenMPDirectiveKind CancelRegion,
4684                               SourceLocation StartLoc) {
4685   // CancelRegion is only needed for cancel and cancellation_point.
4686   if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
4687     return false;
4688 
4689   if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
4690       CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
4691     return false;
4692 
4693   SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
4694       << getOpenMPDirectiveName(CancelRegion);
4695   return true;
4696 }
4697 
4698 static bool checkNestingOfRegions(Sema &SemaRef, const DSAStackTy *Stack,
4699                                   OpenMPDirectiveKind CurrentRegion,
4700                                   const DeclarationNameInfo &CurrentName,
4701                                   OpenMPDirectiveKind CancelRegion,
4702                                   OpenMPBindClauseKind BindKind,
4703                                   SourceLocation StartLoc) {
4704   if (Stack->getCurScope()) {
4705     OpenMPDirectiveKind ParentRegion = Stack->getParentDirective();
4706     OpenMPDirectiveKind OffendingRegion = ParentRegion;
4707     bool NestingProhibited = false;
4708     bool CloseNesting = true;
4709     bool OrphanSeen = false;
4710     enum {
4711       NoRecommend,
4712       ShouldBeInParallelRegion,
4713       ShouldBeInOrderedRegion,
4714       ShouldBeInTargetRegion,
4715       ShouldBeInTeamsRegion,
4716       ShouldBeInLoopSimdRegion,
4717     } Recommend = NoRecommend;
4718     if (isOpenMPSimdDirective(ParentRegion) &&
4719         ((SemaRef.LangOpts.OpenMP <= 45 && CurrentRegion != OMPD_ordered) ||
4720          (SemaRef.LangOpts.OpenMP >= 50 && CurrentRegion != OMPD_ordered &&
4721           CurrentRegion != OMPD_simd && CurrentRegion != OMPD_atomic &&
4722           CurrentRegion != OMPD_scan))) {
4723       // OpenMP [2.16, Nesting of Regions]
4724       // OpenMP constructs may not be nested inside a simd region.
4725       // OpenMP [2.8.1,simd Construct, Restrictions]
4726       // An ordered construct with the simd clause is the only OpenMP
4727       // construct that can appear in the simd region.
4728       // Allowing a SIMD construct nested in another SIMD construct is an
4729       // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
4730       // message.
4731       // OpenMP 5.0 [2.9.3.1, simd Construct, Restrictions]
4732       // The only OpenMP constructs that can be encountered during execution of
4733       // a simd region are the atomic construct, the loop construct, the simd
4734       // construct and the ordered construct with the simd clause.
4735       SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
4736                                  ? diag::err_omp_prohibited_region_simd
4737                                  : diag::warn_omp_nesting_simd)
4738           << (SemaRef.LangOpts.OpenMP >= 50 ? 1 : 0);
4739       return CurrentRegion != OMPD_simd;
4740     }
4741     if (ParentRegion == OMPD_atomic) {
4742       // OpenMP [2.16, Nesting of Regions]
4743       // OpenMP constructs may not be nested inside an atomic region.
4744       SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
4745       return true;
4746     }
4747     if (CurrentRegion == OMPD_section) {
4748       // OpenMP [2.7.2, sections Construct, Restrictions]
4749       // Orphaned section directives are prohibited. That is, the section
4750       // directives must appear within the sections construct and must not be
4751       // encountered elsewhere in the sections region.
4752       if (ParentRegion != OMPD_sections &&
4753           ParentRegion != OMPD_parallel_sections) {
4754         SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
4755             << (ParentRegion != OMPD_unknown)
4756             << getOpenMPDirectiveName(ParentRegion);
4757         return true;
4758       }
4759       return false;
4760     }
4761     // Allow some constructs (except teams and cancellation constructs) to be
4762     // orphaned (they could be used in functions, called from OpenMP regions
4763     // with the required preconditions).
4764     if (ParentRegion == OMPD_unknown &&
4765         !isOpenMPNestingTeamsDirective(CurrentRegion) &&
4766         CurrentRegion != OMPD_cancellation_point &&
4767         CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_scan)
4768       return false;
4769     if (CurrentRegion == OMPD_cancellation_point ||
4770         CurrentRegion == OMPD_cancel) {
4771       // OpenMP [2.16, Nesting of Regions]
4772       // A cancellation point construct for which construct-type-clause is
4773       // taskgroup must be nested inside a task construct. A cancellation
4774       // point construct for which construct-type-clause is not taskgroup must
4775       // be closely nested inside an OpenMP construct that matches the type
4776       // specified in construct-type-clause.
4777       // A cancel construct for which construct-type-clause is taskgroup must be
4778       // nested inside a task construct. A cancel construct for which
4779       // construct-type-clause is not taskgroup must be closely nested inside an
4780       // OpenMP construct that matches the type specified in
4781       // construct-type-clause.
4782       NestingProhibited =
4783           !((CancelRegion == OMPD_parallel &&
4784              (ParentRegion == OMPD_parallel ||
4785               ParentRegion == OMPD_target_parallel)) ||
4786             (CancelRegion == OMPD_for &&
4787              (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
4788               ParentRegion == OMPD_target_parallel_for ||
4789               ParentRegion == OMPD_distribute_parallel_for ||
4790               ParentRegion == OMPD_teams_distribute_parallel_for ||
4791               ParentRegion == OMPD_target_teams_distribute_parallel_for)) ||
4792             (CancelRegion == OMPD_taskgroup &&
4793              (ParentRegion == OMPD_task ||
4794               (SemaRef.getLangOpts().OpenMP >= 50 &&
4795                (ParentRegion == OMPD_taskloop ||
4796                 ParentRegion == OMPD_master_taskloop ||
4797                 ParentRegion == OMPD_parallel_master_taskloop)))) ||
4798             (CancelRegion == OMPD_sections &&
4799              (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
4800               ParentRegion == OMPD_parallel_sections)));
4801       OrphanSeen = ParentRegion == OMPD_unknown;
4802     } else if (CurrentRegion == OMPD_master || CurrentRegion == OMPD_masked) {
4803       // OpenMP 5.1 [2.22, Nesting of Regions]
4804       // A masked region may not be closely nested inside a worksharing, loop,
4805       // atomic, task, or taskloop region.
4806       NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
4807                           isOpenMPGenericLoopDirective(ParentRegion) ||
4808                           isOpenMPTaskingDirective(ParentRegion);
4809     } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
4810       // OpenMP [2.16, Nesting of Regions]
4811       // A critical region may not be nested (closely or otherwise) inside a
4812       // critical region with the same name. Note that this restriction is not
4813       // sufficient to prevent deadlock.
4814       SourceLocation PreviousCriticalLoc;
4815       bool DeadLock = Stack->hasDirective(
4816           [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
4817                                               const DeclarationNameInfo &DNI,
4818                                               SourceLocation Loc) {
4819             if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
4820               PreviousCriticalLoc = Loc;
4821               return true;
4822             }
4823             return false;
4824           },
4825           false /* skip top directive */);
4826       if (DeadLock) {
4827         SemaRef.Diag(StartLoc,
4828                      diag::err_omp_prohibited_region_critical_same_name)
4829             << CurrentName.getName();
4830         if (PreviousCriticalLoc.isValid())
4831           SemaRef.Diag(PreviousCriticalLoc,
4832                        diag::note_omp_previous_critical_region);
4833         return true;
4834       }
4835     } else if (CurrentRegion == OMPD_barrier) {
4836       // OpenMP 5.1 [2.22, Nesting of Regions]
4837       // A barrier region may not be closely nested inside a worksharing, loop,
4838       // task, taskloop, critical, ordered, atomic, or masked region.
4839       NestingProhibited =
4840           isOpenMPWorksharingDirective(ParentRegion) ||
4841           isOpenMPGenericLoopDirective(ParentRegion) ||
4842           isOpenMPTaskingDirective(ParentRegion) ||
4843           ParentRegion == OMPD_master || ParentRegion == OMPD_masked ||
4844           ParentRegion == OMPD_parallel_master ||
4845           ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered;
4846     } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
4847                !isOpenMPParallelDirective(CurrentRegion) &&
4848                !isOpenMPTeamsDirective(CurrentRegion)) {
4849       // OpenMP 5.1 [2.22, Nesting of Regions]
4850       // A loop region that binds to a parallel region or a worksharing region
4851       // may not be closely nested inside a worksharing, loop, task, taskloop,
4852       // critical, ordered, atomic, or masked region.
4853       NestingProhibited =
4854           isOpenMPWorksharingDirective(ParentRegion) ||
4855           isOpenMPGenericLoopDirective(ParentRegion) ||
4856           isOpenMPTaskingDirective(ParentRegion) ||
4857           ParentRegion == OMPD_master || ParentRegion == OMPD_masked ||
4858           ParentRegion == OMPD_parallel_master ||
4859           ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered;
4860       Recommend = ShouldBeInParallelRegion;
4861     } else if (CurrentRegion == OMPD_ordered) {
4862       // OpenMP [2.16, Nesting of Regions]
4863       // An ordered region may not be closely nested inside a critical,
4864       // atomic, or explicit task region.
4865       // An ordered region must be closely nested inside a loop region (or
4866       // parallel loop region) with an ordered clause.
4867       // OpenMP [2.8.1,simd Construct, Restrictions]
4868       // An ordered construct with the simd clause is the only OpenMP construct
4869       // that can appear in the simd region.
4870       NestingProhibited = ParentRegion == OMPD_critical ||
4871                           isOpenMPTaskingDirective(ParentRegion) ||
4872                           !(isOpenMPSimdDirective(ParentRegion) ||
4873                             Stack->isParentOrderedRegion());
4874       Recommend = ShouldBeInOrderedRegion;
4875     } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
4876       // OpenMP [2.16, Nesting of Regions]
4877       // If specified, a teams construct must be contained within a target
4878       // construct.
4879       NestingProhibited =
4880           (SemaRef.LangOpts.OpenMP <= 45 && ParentRegion != OMPD_target) ||
4881           (SemaRef.LangOpts.OpenMP >= 50 && ParentRegion != OMPD_unknown &&
4882            ParentRegion != OMPD_target);
4883       OrphanSeen = ParentRegion == OMPD_unknown;
4884       Recommend = ShouldBeInTargetRegion;
4885     } else if (CurrentRegion == OMPD_scan) {
4886       // OpenMP [2.16, Nesting of Regions]
4887       // If specified, a teams construct must be contained within a target
4888       // construct.
4889       NestingProhibited =
4890           SemaRef.LangOpts.OpenMP < 50 ||
4891           (ParentRegion != OMPD_simd && ParentRegion != OMPD_for &&
4892            ParentRegion != OMPD_for_simd && ParentRegion != OMPD_parallel_for &&
4893            ParentRegion != OMPD_parallel_for_simd);
4894       OrphanSeen = ParentRegion == OMPD_unknown;
4895       Recommend = ShouldBeInLoopSimdRegion;
4896     }
4897     if (!NestingProhibited &&
4898         !isOpenMPTargetExecutionDirective(CurrentRegion) &&
4899         !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
4900         (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
4901       // OpenMP [5.1, 2.22, Nesting of Regions]
4902       // distribute, distribute simd, distribute parallel worksharing-loop,
4903       // distribute parallel worksharing-loop SIMD, loop, parallel regions,
4904       // including any parallel regions arising from combined constructs,
4905       // omp_get_num_teams() regions, and omp_get_team_num() regions are the
4906       // only OpenMP regions that may be strictly nested inside the teams
4907       // region.
4908       NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
4909                           !isOpenMPDistributeDirective(CurrentRegion) &&
4910                           CurrentRegion != OMPD_loop;
4911       Recommend = ShouldBeInParallelRegion;
4912     }
4913     if (!NestingProhibited && CurrentRegion == OMPD_loop) {
4914       // OpenMP [5.1, 2.11.7, loop Construct, Restrictions]
4915       // If the bind clause is present on the loop construct and binding is
4916       // teams then the corresponding loop region must be strictly nested inside
4917       // a teams region.
4918       NestingProhibited = BindKind == OMPC_BIND_teams &&
4919                           ParentRegion != OMPD_teams &&
4920                           ParentRegion != OMPD_target_teams;
4921       Recommend = ShouldBeInTeamsRegion;
4922     }
4923     if (!NestingProhibited &&
4924         isOpenMPNestingDistributeDirective(CurrentRegion)) {
4925       // OpenMP 4.5 [2.17 Nesting of Regions]
4926       // The region associated with the distribute construct must be strictly
4927       // nested inside a teams region
4928       NestingProhibited =
4929           (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
4930       Recommend = ShouldBeInTeamsRegion;
4931     }
4932     if (!NestingProhibited &&
4933         (isOpenMPTargetExecutionDirective(CurrentRegion) ||
4934          isOpenMPTargetDataManagementDirective(CurrentRegion))) {
4935       // OpenMP 4.5 [2.17 Nesting of Regions]
4936       // If a target, target update, target data, target enter data, or
4937       // target exit data construct is encountered during execution of a
4938       // target region, the behavior is unspecified.
4939       NestingProhibited = Stack->hasDirective(
4940           [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
4941                              SourceLocation) {
4942             if (isOpenMPTargetExecutionDirective(K)) {
4943               OffendingRegion = K;
4944               return true;
4945             }
4946             return false;
4947           },
4948           false /* don't skip top directive */);
4949       CloseNesting = false;
4950     }
4951     if (NestingProhibited) {
4952       if (OrphanSeen) {
4953         SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
4954             << getOpenMPDirectiveName(CurrentRegion) << Recommend;
4955       } else {
4956         SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
4957             << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
4958             << Recommend << getOpenMPDirectiveName(CurrentRegion);
4959       }
4960       return true;
4961     }
4962   }
4963   return false;
4964 }
4965 
4966 struct Kind2Unsigned {
4967   using argument_type = OpenMPDirectiveKind;
4968   unsigned operator()(argument_type DK) { return unsigned(DK); }
4969 };
4970 static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
4971                            ArrayRef<OMPClause *> Clauses,
4972                            ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
4973   bool ErrorFound = false;
4974   unsigned NamedModifiersNumber = 0;
4975   llvm::IndexedMap<const OMPIfClause *, Kind2Unsigned> FoundNameModifiers;
4976   FoundNameModifiers.resize(llvm::omp::Directive_enumSize + 1);
4977   SmallVector<SourceLocation, 4> NameModifierLoc;
4978   for (const OMPClause *C : Clauses) {
4979     if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
4980       // At most one if clause without a directive-name-modifier can appear on
4981       // the directive.
4982       OpenMPDirectiveKind CurNM = IC->getNameModifier();
4983       if (FoundNameModifiers[CurNM]) {
4984         S.Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
4985             << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
4986             << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
4987         ErrorFound = true;
4988       } else if (CurNM != OMPD_unknown) {
4989         NameModifierLoc.push_back(IC->getNameModifierLoc());
4990         ++NamedModifiersNumber;
4991       }
4992       FoundNameModifiers[CurNM] = IC;
4993       if (CurNM == OMPD_unknown)
4994         continue;
4995       // Check if the specified name modifier is allowed for the current
4996       // directive.
4997       // At most one if clause with the particular directive-name-modifier can
4998       // appear on the directive.
4999       if (!llvm::is_contained(AllowedNameModifiers, CurNM)) {
5000         S.Diag(IC->getNameModifierLoc(),
5001                diag::err_omp_wrong_if_directive_name_modifier)
5002             << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
5003         ErrorFound = true;
5004       }
5005     }
5006   }
5007   // If any if clause on the directive includes a directive-name-modifier then
5008   // all if clauses on the directive must include a directive-name-modifier.
5009   if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
5010     if (NamedModifiersNumber == AllowedNameModifiers.size()) {
5011       S.Diag(FoundNameModifiers[OMPD_unknown]->getBeginLoc(),
5012              diag::err_omp_no_more_if_clause);
5013     } else {
5014       std::string Values;
5015       std::string Sep(", ");
5016       unsigned AllowedCnt = 0;
5017       unsigned TotalAllowedNum =
5018           AllowedNameModifiers.size() - NamedModifiersNumber;
5019       for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
5020            ++Cnt) {
5021         OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
5022         if (!FoundNameModifiers[NM]) {
5023           Values += "'";
5024           Values += getOpenMPDirectiveName(NM);
5025           Values += "'";
5026           if (AllowedCnt + 2 == TotalAllowedNum)
5027             Values += " or ";
5028           else if (AllowedCnt + 1 != TotalAllowedNum)
5029             Values += Sep;
5030           ++AllowedCnt;
5031         }
5032       }
5033       S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getBeginLoc(),
5034              diag::err_omp_unnamed_if_clause)
5035           << (TotalAllowedNum > 1) << Values;
5036     }
5037     for (SourceLocation Loc : NameModifierLoc) {
5038       S.Diag(Loc, diag::note_omp_previous_named_if_clause);
5039     }
5040     ErrorFound = true;
5041   }
5042   return ErrorFound;
5043 }
5044 
5045 static std::pair<ValueDecl *, bool> getPrivateItem(Sema &S, Expr *&RefExpr,
5046                                                    SourceLocation &ELoc,
5047                                                    SourceRange &ERange,
5048                                                    bool AllowArraySection) {
5049   if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
5050       RefExpr->containsUnexpandedParameterPack())
5051     return std::make_pair(nullptr, true);
5052 
5053   // OpenMP [3.1, C/C++]
5054   //  A list item is a variable name.
5055   // OpenMP  [2.9.3.3, Restrictions, p.1]
5056   //  A variable that is part of another variable (as an array or
5057   //  structure element) cannot appear in a private clause.
5058   RefExpr = RefExpr->IgnoreParens();
5059   enum {
5060     NoArrayExpr = -1,
5061     ArraySubscript = 0,
5062     OMPArraySection = 1
5063   } IsArrayExpr = NoArrayExpr;
5064   if (AllowArraySection) {
5065     if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
5066       Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
5067       while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
5068         Base = TempASE->getBase()->IgnoreParenImpCasts();
5069       RefExpr = Base;
5070       IsArrayExpr = ArraySubscript;
5071     } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
5072       Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
5073       while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
5074         Base = TempOASE->getBase()->IgnoreParenImpCasts();
5075       while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
5076         Base = TempASE->getBase()->IgnoreParenImpCasts();
5077       RefExpr = Base;
5078       IsArrayExpr = OMPArraySection;
5079     }
5080   }
5081   ELoc = RefExpr->getExprLoc();
5082   ERange = RefExpr->getSourceRange();
5083   RefExpr = RefExpr->IgnoreParenImpCasts();
5084   auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
5085   auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
5086   if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
5087       (S.getCurrentThisType().isNull() || !ME ||
5088        !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
5089        !isa<FieldDecl>(ME->getMemberDecl()))) {
5090     if (IsArrayExpr != NoArrayExpr) {
5091       S.Diag(ELoc, diag::err_omp_expected_base_var_name)
5092           << IsArrayExpr << ERange;
5093     } else {
5094       S.Diag(ELoc,
5095              AllowArraySection
5096                  ? diag::err_omp_expected_var_name_member_expr_or_array_item
5097                  : diag::err_omp_expected_var_name_member_expr)
5098           << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
5099     }
5100     return std::make_pair(nullptr, false);
5101   }
5102   return std::make_pair(
5103       getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false);
5104 }
5105 
5106 namespace {
5107 /// Checks if the allocator is used in uses_allocators clause to be allowed in
5108 /// target regions.
5109 class AllocatorChecker final : public ConstStmtVisitor<AllocatorChecker, bool> {
5110   DSAStackTy *S = nullptr;
5111 
5112 public:
5113   bool VisitDeclRefExpr(const DeclRefExpr *E) {
5114     return S->isUsesAllocatorsDecl(E->getDecl())
5115                .getValueOr(
5116                    DSAStackTy::UsesAllocatorsDeclKind::AllocatorTrait) ==
5117            DSAStackTy::UsesAllocatorsDeclKind::AllocatorTrait;
5118   }
5119   bool VisitStmt(const Stmt *S) {
5120     for (const Stmt *Child : S->children()) {
5121       if (Child && Visit(Child))
5122         return true;
5123     }
5124     return false;
5125   }
5126   explicit AllocatorChecker(DSAStackTy *S) : S(S) {}
5127 };
5128 } // namespace
5129 
5130 static void checkAllocateClauses(Sema &S, DSAStackTy *Stack,
5131                                  ArrayRef<OMPClause *> Clauses) {
5132   assert(!S.CurContext->isDependentContext() &&
5133          "Expected non-dependent context.");
5134   auto AllocateRange =
5135       llvm::make_filter_range(Clauses, OMPAllocateClause::classof);
5136   llvm::DenseMap<CanonicalDeclPtr<Decl>, CanonicalDeclPtr<VarDecl>> DeclToCopy;
5137   auto PrivateRange = llvm::make_filter_range(Clauses, [](const OMPClause *C) {
5138     return isOpenMPPrivate(C->getClauseKind());
5139   });
5140   for (OMPClause *Cl : PrivateRange) {
5141     MutableArrayRef<Expr *>::iterator I, It, Et;
5142     if (Cl->getClauseKind() == OMPC_private) {
5143       auto *PC = cast<OMPPrivateClause>(Cl);
5144       I = PC->private_copies().begin();
5145       It = PC->varlist_begin();
5146       Et = PC->varlist_end();
5147     } else if (Cl->getClauseKind() == OMPC_firstprivate) {
5148       auto *PC = cast<OMPFirstprivateClause>(Cl);
5149       I = PC->private_copies().begin();
5150       It = PC->varlist_begin();
5151       Et = PC->varlist_end();
5152     } else if (Cl->getClauseKind() == OMPC_lastprivate) {
5153       auto *PC = cast<OMPLastprivateClause>(Cl);
5154       I = PC->private_copies().begin();
5155       It = PC->varlist_begin();
5156       Et = PC->varlist_end();
5157     } else if (Cl->getClauseKind() == OMPC_linear) {
5158       auto *PC = cast<OMPLinearClause>(Cl);
5159       I = PC->privates().begin();
5160       It = PC->varlist_begin();
5161       Et = PC->varlist_end();
5162     } else if (Cl->getClauseKind() == OMPC_reduction) {
5163       auto *PC = cast<OMPReductionClause>(Cl);
5164       I = PC->privates().begin();
5165       It = PC->varlist_begin();
5166       Et = PC->varlist_end();
5167     } else if (Cl->getClauseKind() == OMPC_task_reduction) {
5168       auto *PC = cast<OMPTaskReductionClause>(Cl);
5169       I = PC->privates().begin();
5170       It = PC->varlist_begin();
5171       Et = PC->varlist_end();
5172     } else if (Cl->getClauseKind() == OMPC_in_reduction) {
5173       auto *PC = cast<OMPInReductionClause>(Cl);
5174       I = PC->privates().begin();
5175       It = PC->varlist_begin();
5176       Et = PC->varlist_end();
5177     } else {
5178       llvm_unreachable("Expected private clause.");
5179     }
5180     for (Expr *E : llvm::make_range(It, Et)) {
5181       if (!*I) {
5182         ++I;
5183         continue;
5184       }
5185       SourceLocation ELoc;
5186       SourceRange ERange;
5187       Expr *SimpleRefExpr = E;
5188       auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
5189                                 /*AllowArraySection=*/true);
5190       DeclToCopy.try_emplace(Res.first,
5191                              cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()));
5192       ++I;
5193     }
5194   }
5195   for (OMPClause *C : AllocateRange) {
5196     auto *AC = cast<OMPAllocateClause>(C);
5197     if (S.getLangOpts().OpenMP >= 50 &&
5198         !Stack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>() &&
5199         isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
5200         AC->getAllocator()) {
5201       Expr *Allocator = AC->getAllocator();
5202       // OpenMP, 2.12.5 target Construct
5203       // Memory allocators that do not appear in a uses_allocators clause cannot
5204       // appear as an allocator in an allocate clause or be used in the target
5205       // region unless a requires directive with the dynamic_allocators clause
5206       // is present in the same compilation unit.
5207       AllocatorChecker Checker(Stack);
5208       if (Checker.Visit(Allocator))
5209         S.Diag(Allocator->getExprLoc(),
5210                diag::err_omp_allocator_not_in_uses_allocators)
5211             << Allocator->getSourceRange();
5212     }
5213     OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind =
5214         getAllocatorKind(S, Stack, AC->getAllocator());
5215     // OpenMP, 2.11.4 allocate Clause, Restrictions.
5216     // For task, taskloop or target directives, allocation requests to memory
5217     // allocators with the trait access set to thread result in unspecified
5218     // behavior.
5219     if (AllocatorKind == OMPAllocateDeclAttr::OMPThreadMemAlloc &&
5220         (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
5221          isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()))) {
5222       S.Diag(AC->getAllocator()->getExprLoc(),
5223              diag::warn_omp_allocate_thread_on_task_target_directive)
5224           << getOpenMPDirectiveName(Stack->getCurrentDirective());
5225     }
5226     for (Expr *E : AC->varlists()) {
5227       SourceLocation ELoc;
5228       SourceRange ERange;
5229       Expr *SimpleRefExpr = E;
5230       auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange);
5231       ValueDecl *VD = Res.first;
5232       DSAStackTy::DSAVarData Data = Stack->getTopDSA(VD, /*FromParent=*/false);
5233       if (!isOpenMPPrivate(Data.CKind)) {
5234         S.Diag(E->getExprLoc(),
5235                diag::err_omp_expected_private_copy_for_allocate);
5236         continue;
5237       }
5238       VarDecl *PrivateVD = DeclToCopy[VD];
5239       if (checkPreviousOMPAllocateAttribute(S, Stack, E, PrivateVD,
5240                                             AllocatorKind, AC->getAllocator()))
5241         continue;
5242       // Placeholder until allocate clause supports align modifier.
5243       Expr *Alignment = nullptr;
5244       applyOMPAllocateAttribute(S, PrivateVD, AllocatorKind, AC->getAllocator(),
5245                                 Alignment, E->getSourceRange());
5246     }
5247   }
5248 }
5249 
5250 namespace {
5251 /// Rewrite statements and expressions for Sema \p Actions CurContext.
5252 ///
5253 /// Used to wrap already parsed statements/expressions into a new CapturedStmt
5254 /// context. DeclRefExpr used inside the new context are changed to refer to the
5255 /// captured variable instead.
5256 class CaptureVars : public TreeTransform<CaptureVars> {
5257   using BaseTransform = TreeTransform<CaptureVars>;
5258 
5259 public:
5260   CaptureVars(Sema &Actions) : BaseTransform(Actions) {}
5261 
5262   bool AlwaysRebuild() { return true; }
5263 };
5264 } // namespace
5265 
5266 static VarDecl *precomputeExpr(Sema &Actions,
5267                                SmallVectorImpl<Stmt *> &BodyStmts, Expr *E,
5268                                StringRef Name) {
5269   Expr *NewE = AssertSuccess(CaptureVars(Actions).TransformExpr(E));
5270   VarDecl *NewVar = buildVarDecl(Actions, {}, NewE->getType(), Name, nullptr,
5271                                  dyn_cast<DeclRefExpr>(E->IgnoreImplicit()));
5272   auto *NewDeclStmt = cast<DeclStmt>(AssertSuccess(
5273       Actions.ActOnDeclStmt(Actions.ConvertDeclToDeclGroup(NewVar), {}, {})));
5274   Actions.AddInitializerToDecl(NewDeclStmt->getSingleDecl(), NewE, false);
5275   BodyStmts.push_back(NewDeclStmt);
5276   return NewVar;
5277 }
5278 
5279 /// Create a closure that computes the number of iterations of a loop.
5280 ///
5281 /// \param Actions   The Sema object.
5282 /// \param LogicalTy Type for the logical iteration number.
5283 /// \param Rel       Comparison operator of the loop condition.
5284 /// \param StartExpr Value of the loop counter at the first iteration.
5285 /// \param StopExpr  Expression the loop counter is compared against in the loop
5286 /// condition. \param StepExpr      Amount of increment after each iteration.
5287 ///
5288 /// \return Closure (CapturedStmt) of the distance calculation.
5289 static CapturedStmt *buildDistanceFunc(Sema &Actions, QualType LogicalTy,
5290                                        BinaryOperator::Opcode Rel,
5291                                        Expr *StartExpr, Expr *StopExpr,
5292                                        Expr *StepExpr) {
5293   ASTContext &Ctx = Actions.getASTContext();
5294   TypeSourceInfo *LogicalTSI = Ctx.getTrivialTypeSourceInfo(LogicalTy);
5295 
5296   // Captured regions currently don't support return values, we use an
5297   // out-parameter instead. All inputs are implicit captures.
5298   // TODO: Instead of capturing each DeclRefExpr occurring in
5299   // StartExpr/StopExpr/Step, these could also be passed as a value capture.
5300   QualType ResultTy = Ctx.getLValueReferenceType(LogicalTy);
5301   Sema::CapturedParamNameType Params[] = {{"Distance", ResultTy},
5302                                           {StringRef(), QualType()}};
5303   Actions.ActOnCapturedRegionStart({}, nullptr, CR_Default, Params);
5304 
5305   Stmt *Body;
5306   {
5307     Sema::CompoundScopeRAII CompoundScope(Actions);
5308     CapturedDecl *CS = cast<CapturedDecl>(Actions.CurContext);
5309 
5310     // Get the LValue expression for the result.
5311     ImplicitParamDecl *DistParam = CS->getParam(0);
5312     DeclRefExpr *DistRef = Actions.BuildDeclRefExpr(
5313         DistParam, LogicalTy, VK_LValue, {}, nullptr, nullptr, {}, nullptr);
5314 
5315     SmallVector<Stmt *, 4> BodyStmts;
5316 
5317     // Capture all referenced variable references.
5318     // TODO: Instead of computing NewStart/NewStop/NewStep inside the
5319     // CapturedStmt, we could compute them before and capture the result, to be
5320     // used jointly with the LoopVar function.
5321     VarDecl *NewStart = precomputeExpr(Actions, BodyStmts, StartExpr, ".start");
5322     VarDecl *NewStop = precomputeExpr(Actions, BodyStmts, StopExpr, ".stop");
5323     VarDecl *NewStep = precomputeExpr(Actions, BodyStmts, StepExpr, ".step");
5324     auto BuildVarRef = [&](VarDecl *VD) {
5325       return buildDeclRefExpr(Actions, VD, VD->getType(), {});
5326     };
5327 
5328     IntegerLiteral *Zero = IntegerLiteral::Create(
5329         Ctx, llvm::APInt(Ctx.getIntWidth(LogicalTy), 0), LogicalTy, {});
5330     Expr *Dist;
5331     if (Rel == BO_NE) {
5332       // When using a != comparison, the increment can be +1 or -1. This can be
5333       // dynamic at runtime, so we need to check for the direction.
5334       Expr *IsNegStep = AssertSuccess(
5335           Actions.BuildBinOp(nullptr, {}, BO_LT, BuildVarRef(NewStep), Zero));
5336 
5337       // Positive increment.
5338       Expr *ForwardRange = AssertSuccess(Actions.BuildBinOp(
5339           nullptr, {}, BO_Sub, BuildVarRef(NewStop), BuildVarRef(NewStart)));
5340       ForwardRange = AssertSuccess(
5341           Actions.BuildCStyleCastExpr({}, LogicalTSI, {}, ForwardRange));
5342       Expr *ForwardDist = AssertSuccess(Actions.BuildBinOp(
5343           nullptr, {}, BO_Div, ForwardRange, BuildVarRef(NewStep)));
5344 
5345       // Negative increment.
5346       Expr *BackwardRange = AssertSuccess(Actions.BuildBinOp(
5347           nullptr, {}, BO_Sub, BuildVarRef(NewStart), BuildVarRef(NewStop)));
5348       BackwardRange = AssertSuccess(
5349           Actions.BuildCStyleCastExpr({}, LogicalTSI, {}, BackwardRange));
5350       Expr *NegIncAmount = AssertSuccess(
5351           Actions.BuildUnaryOp(nullptr, {}, UO_Minus, BuildVarRef(NewStep)));
5352       Expr *BackwardDist = AssertSuccess(
5353           Actions.BuildBinOp(nullptr, {}, BO_Div, BackwardRange, NegIncAmount));
5354 
5355       // Use the appropriate case.
5356       Dist = AssertSuccess(Actions.ActOnConditionalOp(
5357           {}, {}, IsNegStep, BackwardDist, ForwardDist));
5358     } else {
5359       assert((Rel == BO_LT || Rel == BO_LE || Rel == BO_GE || Rel == BO_GT) &&
5360              "Expected one of these relational operators");
5361 
5362       // We can derive the direction from any other comparison operator. It is
5363       // non well-formed OpenMP if Step increments/decrements in the other
5364       // directions. Whether at least the first iteration passes the loop
5365       // condition.
5366       Expr *HasAnyIteration = AssertSuccess(Actions.BuildBinOp(
5367           nullptr, {}, Rel, BuildVarRef(NewStart), BuildVarRef(NewStop)));
5368 
5369       // Compute the range between first and last counter value.
5370       Expr *Range;
5371       if (Rel == BO_GE || Rel == BO_GT)
5372         Range = AssertSuccess(Actions.BuildBinOp(
5373             nullptr, {}, BO_Sub, BuildVarRef(NewStart), BuildVarRef(NewStop)));
5374       else
5375         Range = AssertSuccess(Actions.BuildBinOp(
5376             nullptr, {}, BO_Sub, BuildVarRef(NewStop), BuildVarRef(NewStart)));
5377 
5378       // Ensure unsigned range space.
5379       Range =
5380           AssertSuccess(Actions.BuildCStyleCastExpr({}, LogicalTSI, {}, Range));
5381 
5382       if (Rel == BO_LE || Rel == BO_GE) {
5383         // Add one to the range if the relational operator is inclusive.
5384         Range = AssertSuccess(Actions.BuildBinOp(
5385             nullptr, {}, BO_Add, Range,
5386             Actions.ActOnIntegerConstant(SourceLocation(), 1).get()));
5387       }
5388 
5389       // Divide by the absolute step amount.
5390       Expr *Divisor = BuildVarRef(NewStep);
5391       if (Rel == BO_GE || Rel == BO_GT)
5392         Divisor =
5393             AssertSuccess(Actions.BuildUnaryOp(nullptr, {}, UO_Minus, Divisor));
5394       Dist = AssertSuccess(
5395           Actions.BuildBinOp(nullptr, {}, BO_Div, Range, Divisor));
5396 
5397       // If there is not at least one iteration, the range contains garbage. Fix
5398       // to zero in this case.
5399       Dist = AssertSuccess(
5400           Actions.ActOnConditionalOp({}, {}, HasAnyIteration, Dist, Zero));
5401     }
5402 
5403     // Assign the result to the out-parameter.
5404     Stmt *ResultAssign = AssertSuccess(Actions.BuildBinOp(
5405         Actions.getCurScope(), {}, BO_Assign, DistRef, Dist));
5406     BodyStmts.push_back(ResultAssign);
5407 
5408     Body = AssertSuccess(Actions.ActOnCompoundStmt({}, {}, BodyStmts, false));
5409   }
5410 
5411   return cast<CapturedStmt>(
5412       AssertSuccess(Actions.ActOnCapturedRegionEnd(Body)));
5413 }
5414 
5415 /// Create a closure that computes the loop variable from the logical iteration
5416 /// number.
5417 ///
5418 /// \param Actions   The Sema object.
5419 /// \param LoopVarTy Type for the loop variable used for result value.
5420 /// \param LogicalTy Type for the logical iteration number.
5421 /// \param StartExpr Value of the loop counter at the first iteration.
5422 /// \param Step      Amount of increment after each iteration.
5423 /// \param Deref     Whether the loop variable is a dereference of the loop
5424 /// counter variable.
5425 ///
5426 /// \return Closure (CapturedStmt) of the loop value calculation.
5427 static CapturedStmt *buildLoopVarFunc(Sema &Actions, QualType LoopVarTy,
5428                                       QualType LogicalTy,
5429                                       DeclRefExpr *StartExpr, Expr *Step,
5430                                       bool Deref) {
5431   ASTContext &Ctx = Actions.getASTContext();
5432 
5433   // Pass the result as an out-parameter. Passing as return value would require
5434   // the OpenMPIRBuilder to know additional C/C++ semantics, such as how to
5435   // invoke a copy constructor.
5436   QualType TargetParamTy = Ctx.getLValueReferenceType(LoopVarTy);
5437   Sema::CapturedParamNameType Params[] = {{"LoopVar", TargetParamTy},
5438                                           {"Logical", LogicalTy},
5439                                           {StringRef(), QualType()}};
5440   Actions.ActOnCapturedRegionStart({}, nullptr, CR_Default, Params);
5441 
5442   // Capture the initial iterator which represents the LoopVar value at the
5443   // zero's logical iteration. Since the original ForStmt/CXXForRangeStmt update
5444   // it in every iteration, capture it by value before it is modified.
5445   VarDecl *StartVar = cast<VarDecl>(StartExpr->getDecl());
5446   bool Invalid = Actions.tryCaptureVariable(StartVar, {},
5447                                             Sema::TryCapture_ExplicitByVal, {});
5448   (void)Invalid;
5449   assert(!Invalid && "Expecting capture-by-value to work.");
5450 
5451   Expr *Body;
5452   {
5453     Sema::CompoundScopeRAII CompoundScope(Actions);
5454     auto *CS = cast<CapturedDecl>(Actions.CurContext);
5455 
5456     ImplicitParamDecl *TargetParam = CS->getParam(0);
5457     DeclRefExpr *TargetRef = Actions.BuildDeclRefExpr(
5458         TargetParam, LoopVarTy, VK_LValue, {}, nullptr, nullptr, {}, nullptr);
5459     ImplicitParamDecl *IndvarParam = CS->getParam(1);
5460     DeclRefExpr *LogicalRef = Actions.BuildDeclRefExpr(
5461         IndvarParam, LogicalTy, VK_LValue, {}, nullptr, nullptr, {}, nullptr);
5462 
5463     // Capture the Start expression.
5464     CaptureVars Recap(Actions);
5465     Expr *NewStart = AssertSuccess(Recap.TransformExpr(StartExpr));
5466     Expr *NewStep = AssertSuccess(Recap.TransformExpr(Step));
5467 
5468     Expr *Skip = AssertSuccess(
5469         Actions.BuildBinOp(nullptr, {}, BO_Mul, NewStep, LogicalRef));
5470     // TODO: Explicitly cast to the iterator's difference_type instead of
5471     // relying on implicit conversion.
5472     Expr *Advanced =
5473         AssertSuccess(Actions.BuildBinOp(nullptr, {}, BO_Add, NewStart, Skip));
5474 
5475     if (Deref) {
5476       // For range-based for-loops convert the loop counter value to a concrete
5477       // loop variable value by dereferencing the iterator.
5478       Advanced =
5479           AssertSuccess(Actions.BuildUnaryOp(nullptr, {}, UO_Deref, Advanced));
5480     }
5481 
5482     // Assign the result to the output parameter.
5483     Body = AssertSuccess(Actions.BuildBinOp(Actions.getCurScope(), {},
5484                                             BO_Assign, TargetRef, Advanced));
5485   }
5486   return cast<CapturedStmt>(
5487       AssertSuccess(Actions.ActOnCapturedRegionEnd(Body)));
5488 }
5489 
5490 StmtResult Sema::ActOnOpenMPCanonicalLoop(Stmt *AStmt) {
5491   ASTContext &Ctx = getASTContext();
5492 
5493   // Extract the common elements of ForStmt and CXXForRangeStmt:
5494   // Loop variable, repeat condition, increment
5495   Expr *Cond, *Inc;
5496   VarDecl *LIVDecl, *LUVDecl;
5497   if (auto *For = dyn_cast<ForStmt>(AStmt)) {
5498     Stmt *Init = For->getInit();
5499     if (auto *LCVarDeclStmt = dyn_cast<DeclStmt>(Init)) {
5500       // For statement declares loop variable.
5501       LIVDecl = cast<VarDecl>(LCVarDeclStmt->getSingleDecl());
5502     } else if (auto *LCAssign = dyn_cast<BinaryOperator>(Init)) {
5503       // For statement reuses variable.
5504       assert(LCAssign->getOpcode() == BO_Assign &&
5505              "init part must be a loop variable assignment");
5506       auto *CounterRef = cast<DeclRefExpr>(LCAssign->getLHS());
5507       LIVDecl = cast<VarDecl>(CounterRef->getDecl());
5508     } else
5509       llvm_unreachable("Cannot determine loop variable");
5510     LUVDecl = LIVDecl;
5511 
5512     Cond = For->getCond();
5513     Inc = For->getInc();
5514   } else if (auto *RangeFor = dyn_cast<CXXForRangeStmt>(AStmt)) {
5515     DeclStmt *BeginStmt = RangeFor->getBeginStmt();
5516     LIVDecl = cast<VarDecl>(BeginStmt->getSingleDecl());
5517     LUVDecl = RangeFor->getLoopVariable();
5518 
5519     Cond = RangeFor->getCond();
5520     Inc = RangeFor->getInc();
5521   } else
5522     llvm_unreachable("unhandled kind of loop");
5523 
5524   QualType CounterTy = LIVDecl->getType();
5525   QualType LVTy = LUVDecl->getType();
5526 
5527   // Analyze the loop condition.
5528   Expr *LHS, *RHS;
5529   BinaryOperator::Opcode CondRel;
5530   Cond = Cond->IgnoreImplicit();
5531   if (auto *CondBinExpr = dyn_cast<BinaryOperator>(Cond)) {
5532     LHS = CondBinExpr->getLHS();
5533     RHS = CondBinExpr->getRHS();
5534     CondRel = CondBinExpr->getOpcode();
5535   } else if (auto *CondCXXOp = dyn_cast<CXXOperatorCallExpr>(Cond)) {
5536     assert(CondCXXOp->getNumArgs() == 2 && "Comparison should have 2 operands");
5537     LHS = CondCXXOp->getArg(0);
5538     RHS = CondCXXOp->getArg(1);
5539     switch (CondCXXOp->getOperator()) {
5540     case OO_ExclaimEqual:
5541       CondRel = BO_NE;
5542       break;
5543     case OO_Less:
5544       CondRel = BO_LT;
5545       break;
5546     case OO_LessEqual:
5547       CondRel = BO_LE;
5548       break;
5549     case OO_Greater:
5550       CondRel = BO_GT;
5551       break;
5552     case OO_GreaterEqual:
5553       CondRel = BO_GE;
5554       break;
5555     default:
5556       llvm_unreachable("unexpected iterator operator");
5557     }
5558   } else
5559     llvm_unreachable("unexpected loop condition");
5560 
5561   // Normalize such that the loop counter is on the LHS.
5562   if (!isa<DeclRefExpr>(LHS->IgnoreImplicit()) ||
5563       cast<DeclRefExpr>(LHS->IgnoreImplicit())->getDecl() != LIVDecl) {
5564     std::swap(LHS, RHS);
5565     CondRel = BinaryOperator::reverseComparisonOp(CondRel);
5566   }
5567   auto *CounterRef = cast<DeclRefExpr>(LHS->IgnoreImplicit());
5568 
5569   // Decide the bit width for the logical iteration counter. By default use the
5570   // unsigned ptrdiff_t integer size (for iterators and pointers).
5571   // TODO: For iterators, use iterator::difference_type,
5572   // std::iterator_traits<>::difference_type or decltype(it - end).
5573   QualType LogicalTy = Ctx.getUnsignedPointerDiffType();
5574   if (CounterTy->isIntegerType()) {
5575     unsigned BitWidth = Ctx.getIntWidth(CounterTy);
5576     LogicalTy = Ctx.getIntTypeForBitwidth(BitWidth, false);
5577   }
5578 
5579   // Analyze the loop increment.
5580   Expr *Step;
5581   if (auto *IncUn = dyn_cast<UnaryOperator>(Inc)) {
5582     int Direction;
5583     switch (IncUn->getOpcode()) {
5584     case UO_PreInc:
5585     case UO_PostInc:
5586       Direction = 1;
5587       break;
5588     case UO_PreDec:
5589     case UO_PostDec:
5590       Direction = -1;
5591       break;
5592     default:
5593       llvm_unreachable("unhandled unary increment operator");
5594     }
5595     Step = IntegerLiteral::Create(
5596         Ctx, llvm::APInt(Ctx.getIntWidth(LogicalTy), Direction), LogicalTy, {});
5597   } else if (auto *IncBin = dyn_cast<BinaryOperator>(Inc)) {
5598     if (IncBin->getOpcode() == BO_AddAssign) {
5599       Step = IncBin->getRHS();
5600     } else if (IncBin->getOpcode() == BO_SubAssign) {
5601       Step =
5602           AssertSuccess(BuildUnaryOp(nullptr, {}, UO_Minus, IncBin->getRHS()));
5603     } else
5604       llvm_unreachable("unhandled binary increment operator");
5605   } else if (auto *CondCXXOp = dyn_cast<CXXOperatorCallExpr>(Inc)) {
5606     switch (CondCXXOp->getOperator()) {
5607     case OO_PlusPlus:
5608       Step = IntegerLiteral::Create(
5609           Ctx, llvm::APInt(Ctx.getIntWidth(LogicalTy), 1), LogicalTy, {});
5610       break;
5611     case OO_MinusMinus:
5612       Step = IntegerLiteral::Create(
5613           Ctx, llvm::APInt(Ctx.getIntWidth(LogicalTy), -1), LogicalTy, {});
5614       break;
5615     case OO_PlusEqual:
5616       Step = CondCXXOp->getArg(1);
5617       break;
5618     case OO_MinusEqual:
5619       Step = AssertSuccess(
5620           BuildUnaryOp(nullptr, {}, UO_Minus, CondCXXOp->getArg(1)));
5621       break;
5622     default:
5623       llvm_unreachable("unhandled overloaded increment operator");
5624     }
5625   } else
5626     llvm_unreachable("unknown increment expression");
5627 
5628   CapturedStmt *DistanceFunc =
5629       buildDistanceFunc(*this, LogicalTy, CondRel, LHS, RHS, Step);
5630   CapturedStmt *LoopVarFunc = buildLoopVarFunc(
5631       *this, LVTy, LogicalTy, CounterRef, Step, isa<CXXForRangeStmt>(AStmt));
5632   DeclRefExpr *LVRef = BuildDeclRefExpr(LUVDecl, LUVDecl->getType(), VK_LValue,
5633                                         {}, nullptr, nullptr, {}, nullptr);
5634   return OMPCanonicalLoop::create(getASTContext(), AStmt, DistanceFunc,
5635                                   LoopVarFunc, LVRef);
5636 }
5637 
5638 StmtResult Sema::ActOnOpenMPLoopnest(Stmt *AStmt) {
5639   // Handle a literal loop.
5640   if (isa<ForStmt>(AStmt) || isa<CXXForRangeStmt>(AStmt))
5641     return ActOnOpenMPCanonicalLoop(AStmt);
5642 
5643   // If not a literal loop, it must be the result of a loop transformation.
5644   OMPExecutableDirective *LoopTransform = cast<OMPExecutableDirective>(AStmt);
5645   assert(
5646       isOpenMPLoopTransformationDirective(LoopTransform->getDirectiveKind()) &&
5647       "Loop transformation directive expected");
5648   return LoopTransform;
5649 }
5650 
5651 static ExprResult buildUserDefinedMapperRef(Sema &SemaRef, Scope *S,
5652                                             CXXScopeSpec &MapperIdScopeSpec,
5653                                             const DeclarationNameInfo &MapperId,
5654                                             QualType Type,
5655                                             Expr *UnresolvedMapper);
5656 
5657 /// Perform DFS through the structure/class data members trying to find
5658 /// member(s) with user-defined 'default' mapper and generate implicit map
5659 /// clauses for such members with the found 'default' mapper.
5660 static void
5661 processImplicitMapsWithDefaultMappers(Sema &S, DSAStackTy *Stack,
5662                                       SmallVectorImpl<OMPClause *> &Clauses) {
5663   // Check for the deault mapper for data members.
5664   if (S.getLangOpts().OpenMP < 50)
5665     return;
5666   SmallVector<OMPClause *, 4> ImplicitMaps;
5667   for (int Cnt = 0, EndCnt = Clauses.size(); Cnt < EndCnt; ++Cnt) {
5668     auto *C = dyn_cast<OMPMapClause>(Clauses[Cnt]);
5669     if (!C)
5670       continue;
5671     SmallVector<Expr *, 4> SubExprs;
5672     auto *MI = C->mapperlist_begin();
5673     for (auto I = C->varlist_begin(), End = C->varlist_end(); I != End;
5674          ++I, ++MI) {
5675       // Expression is mapped using mapper - skip it.
5676       if (*MI)
5677         continue;
5678       Expr *E = *I;
5679       // Expression is dependent - skip it, build the mapper when it gets
5680       // instantiated.
5681       if (E->isTypeDependent() || E->isValueDependent() ||
5682           E->containsUnexpandedParameterPack())
5683         continue;
5684       // Array section - need to check for the mapping of the array section
5685       // element.
5686       QualType CanonType = E->getType().getCanonicalType();
5687       if (CanonType->isSpecificBuiltinType(BuiltinType::OMPArraySection)) {
5688         const auto *OASE = cast<OMPArraySectionExpr>(E->IgnoreParenImpCasts());
5689         QualType BaseType =
5690             OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
5691         QualType ElemType;
5692         if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
5693           ElemType = ATy->getElementType();
5694         else
5695           ElemType = BaseType->getPointeeType();
5696         CanonType = ElemType;
5697       }
5698 
5699       // DFS over data members in structures/classes.
5700       SmallVector<std::pair<QualType, FieldDecl *>, 4> Types(
5701           1, {CanonType, nullptr});
5702       llvm::DenseMap<const Type *, Expr *> Visited;
5703       SmallVector<std::pair<FieldDecl *, unsigned>, 4> ParentChain(
5704           1, {nullptr, 1});
5705       while (!Types.empty()) {
5706         QualType BaseType;
5707         FieldDecl *CurFD;
5708         std::tie(BaseType, CurFD) = Types.pop_back_val();
5709         while (ParentChain.back().second == 0)
5710           ParentChain.pop_back();
5711         --ParentChain.back().second;
5712         if (BaseType.isNull())
5713           continue;
5714         // Only structs/classes are allowed to have mappers.
5715         const RecordDecl *RD = BaseType.getCanonicalType()->getAsRecordDecl();
5716         if (!RD)
5717           continue;
5718         auto It = Visited.find(BaseType.getTypePtr());
5719         if (It == Visited.end()) {
5720           // Try to find the associated user-defined mapper.
5721           CXXScopeSpec MapperIdScopeSpec;
5722           DeclarationNameInfo DefaultMapperId;
5723           DefaultMapperId.setName(S.Context.DeclarationNames.getIdentifier(
5724               &S.Context.Idents.get("default")));
5725           DefaultMapperId.setLoc(E->getExprLoc());
5726           ExprResult ER = buildUserDefinedMapperRef(
5727               S, Stack->getCurScope(), MapperIdScopeSpec, DefaultMapperId,
5728               BaseType, /*UnresolvedMapper=*/nullptr);
5729           if (ER.isInvalid())
5730             continue;
5731           It = Visited.try_emplace(BaseType.getTypePtr(), ER.get()).first;
5732         }
5733         // Found default mapper.
5734         if (It->second) {
5735           auto *OE = new (S.Context) OpaqueValueExpr(E->getExprLoc(), CanonType,
5736                                                      VK_LValue, OK_Ordinary, E);
5737           OE->setIsUnique(/*V=*/true);
5738           Expr *BaseExpr = OE;
5739           for (const auto &P : ParentChain) {
5740             if (P.first) {
5741               BaseExpr = S.BuildMemberExpr(
5742                   BaseExpr, /*IsArrow=*/false, E->getExprLoc(),
5743                   NestedNameSpecifierLoc(), SourceLocation(), P.first,
5744                   DeclAccessPair::make(P.first, P.first->getAccess()),
5745                   /*HadMultipleCandidates=*/false, DeclarationNameInfo(),
5746                   P.first->getType(), VK_LValue, OK_Ordinary);
5747               BaseExpr = S.DefaultLvalueConversion(BaseExpr).get();
5748             }
5749           }
5750           if (CurFD)
5751             BaseExpr = S.BuildMemberExpr(
5752                 BaseExpr, /*IsArrow=*/false, E->getExprLoc(),
5753                 NestedNameSpecifierLoc(), SourceLocation(), CurFD,
5754                 DeclAccessPair::make(CurFD, CurFD->getAccess()),
5755                 /*HadMultipleCandidates=*/false, DeclarationNameInfo(),
5756                 CurFD->getType(), VK_LValue, OK_Ordinary);
5757           SubExprs.push_back(BaseExpr);
5758           continue;
5759         }
5760         // Check for the "default" mapper for data members.
5761         bool FirstIter = true;
5762         for (FieldDecl *FD : RD->fields()) {
5763           if (!FD)
5764             continue;
5765           QualType FieldTy = FD->getType();
5766           if (FieldTy.isNull() ||
5767               !(FieldTy->isStructureOrClassType() || FieldTy->isUnionType()))
5768             continue;
5769           if (FirstIter) {
5770             FirstIter = false;
5771             ParentChain.emplace_back(CurFD, 1);
5772           } else {
5773             ++ParentChain.back().second;
5774           }
5775           Types.emplace_back(FieldTy, FD);
5776         }
5777       }
5778     }
5779     if (SubExprs.empty())
5780       continue;
5781     CXXScopeSpec MapperIdScopeSpec;
5782     DeclarationNameInfo MapperId;
5783     if (OMPClause *NewClause = S.ActOnOpenMPMapClause(
5784             C->getMapTypeModifiers(), C->getMapTypeModifiersLoc(),
5785             MapperIdScopeSpec, MapperId, C->getMapType(),
5786             /*IsMapTypeImplicit=*/true, SourceLocation(), SourceLocation(),
5787             SubExprs, OMPVarListLocTy()))
5788       Clauses.push_back(NewClause);
5789   }
5790 }
5791 
5792 StmtResult Sema::ActOnOpenMPExecutableDirective(
5793     OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
5794     OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
5795     Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
5796   StmtResult Res = StmtError();
5797   OpenMPBindClauseKind BindKind = OMPC_BIND_unknown;
5798   if (const OMPBindClause *BC =
5799           OMPExecutableDirective::getSingleClause<OMPBindClause>(Clauses))
5800     BindKind = BC->getBindKind();
5801   // First check CancelRegion which is then used in checkNestingOfRegions.
5802   if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
5803       checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
5804                             BindKind, StartLoc))
5805     return StmtError();
5806 
5807   llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
5808   VarsWithInheritedDSAType VarsWithInheritedDSA;
5809   bool ErrorFound = false;
5810   ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
5811   if (AStmt && !CurContext->isDependentContext() && Kind != OMPD_atomic &&
5812       Kind != OMPD_critical && Kind != OMPD_section && Kind != OMPD_master &&
5813       Kind != OMPD_masked && !isOpenMPLoopTransformationDirective(Kind)) {
5814     assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5815 
5816     // Check default data sharing attributes for referenced variables.
5817     DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
5818     int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
5819     Stmt *S = AStmt;
5820     while (--ThisCaptureLevel >= 0)
5821       S = cast<CapturedStmt>(S)->getCapturedStmt();
5822     DSAChecker.Visit(S);
5823     if (!isOpenMPTargetDataManagementDirective(Kind) &&
5824         !isOpenMPTaskingDirective(Kind)) {
5825       // Visit subcaptures to generate implicit clauses for captured vars.
5826       auto *CS = cast<CapturedStmt>(AStmt);
5827       SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
5828       getOpenMPCaptureRegions(CaptureRegions, Kind);
5829       // Ignore outer tasking regions for target directives.
5830       if (CaptureRegions.size() > 1 && CaptureRegions.front() == OMPD_task)
5831         CS = cast<CapturedStmt>(CS->getCapturedStmt());
5832       DSAChecker.visitSubCaptures(CS);
5833     }
5834     if (DSAChecker.isErrorFound())
5835       return StmtError();
5836     // Generate list of implicitly defined firstprivate variables.
5837     VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
5838 
5839     SmallVector<Expr *, 4> ImplicitFirstprivates(
5840         DSAChecker.getImplicitFirstprivate().begin(),
5841         DSAChecker.getImplicitFirstprivate().end());
5842     const unsigned DefaultmapKindNum = OMPC_DEFAULTMAP_pointer + 1;
5843     SmallVector<Expr *, 4> ImplicitMaps[DefaultmapKindNum][OMPC_MAP_delete];
5844     SmallVector<OpenMPMapModifierKind, NumberOfOMPMapClauseModifiers>
5845         ImplicitMapModifiers[DefaultmapKindNum];
5846     SmallVector<SourceLocation, NumberOfOMPMapClauseModifiers>
5847         ImplicitMapModifiersLoc[DefaultmapKindNum];
5848     // Get the original location of present modifier from Defaultmap clause.
5849     SourceLocation PresentModifierLocs[DefaultmapKindNum];
5850     for (OMPClause *C : Clauses) {
5851       if (auto *DMC = dyn_cast<OMPDefaultmapClause>(C))
5852         if (DMC->getDefaultmapModifier() == OMPC_DEFAULTMAP_MODIFIER_present)
5853           PresentModifierLocs[DMC->getDefaultmapKind()] =
5854               DMC->getDefaultmapModifierLoc();
5855     }
5856     for (unsigned VC = 0; VC < DefaultmapKindNum; ++VC) {
5857       auto Kind = static_cast<OpenMPDefaultmapClauseKind>(VC);
5858       for (unsigned I = 0; I < OMPC_MAP_delete; ++I) {
5859         ArrayRef<Expr *> ImplicitMap = DSAChecker.getImplicitMap(
5860             Kind, static_cast<OpenMPMapClauseKind>(I));
5861         ImplicitMaps[VC][I].append(ImplicitMap.begin(), ImplicitMap.end());
5862       }
5863       ArrayRef<OpenMPMapModifierKind> ImplicitModifier =
5864           DSAChecker.getImplicitMapModifier(Kind);
5865       ImplicitMapModifiers[VC].append(ImplicitModifier.begin(),
5866                                       ImplicitModifier.end());
5867       std::fill_n(std::back_inserter(ImplicitMapModifiersLoc[VC]),
5868                   ImplicitModifier.size(), PresentModifierLocs[VC]);
5869     }
5870     // Mark taskgroup task_reduction descriptors as implicitly firstprivate.
5871     for (OMPClause *C : Clauses) {
5872       if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) {
5873         for (Expr *E : IRC->taskgroup_descriptors())
5874           if (E)
5875             ImplicitFirstprivates.emplace_back(E);
5876       }
5877       // OpenMP 5.0, 2.10.1 task Construct
5878       // [detach clause]... The event-handle will be considered as if it was
5879       // specified on a firstprivate clause.
5880       if (auto *DC = dyn_cast<OMPDetachClause>(C))
5881         ImplicitFirstprivates.push_back(DC->getEventHandler());
5882     }
5883     if (!ImplicitFirstprivates.empty()) {
5884       if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
5885               ImplicitFirstprivates, SourceLocation(), SourceLocation(),
5886               SourceLocation())) {
5887         ClausesWithImplicit.push_back(Implicit);
5888         ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
5889                      ImplicitFirstprivates.size();
5890       } else {
5891         ErrorFound = true;
5892       }
5893     }
5894     // OpenMP 5.0 [2.19.7]
5895     // If a list item appears in a reduction, lastprivate or linear
5896     // clause on a combined target construct then it is treated as
5897     // if it also appears in a map clause with a map-type of tofrom
5898     if (getLangOpts().OpenMP >= 50 && Kind != OMPD_target &&
5899         isOpenMPTargetExecutionDirective(Kind)) {
5900       SmallVector<Expr *, 4> ImplicitExprs;
5901       for (OMPClause *C : Clauses) {
5902         if (auto *RC = dyn_cast<OMPReductionClause>(C))
5903           for (Expr *E : RC->varlists())
5904             if (!isa<DeclRefExpr>(E->IgnoreParenImpCasts()))
5905               ImplicitExprs.emplace_back(E);
5906       }
5907       if (!ImplicitExprs.empty()) {
5908         ArrayRef<Expr *> Exprs = ImplicitExprs;
5909         CXXScopeSpec MapperIdScopeSpec;
5910         DeclarationNameInfo MapperId;
5911         if (OMPClause *Implicit = ActOnOpenMPMapClause(
5912                 OMPC_MAP_MODIFIER_unknown, SourceLocation(), MapperIdScopeSpec,
5913                 MapperId, OMPC_MAP_tofrom,
5914                 /*IsMapTypeImplicit=*/true, SourceLocation(), SourceLocation(),
5915                 Exprs, OMPVarListLocTy(), /*NoDiagnose=*/true))
5916           ClausesWithImplicit.emplace_back(Implicit);
5917       }
5918     }
5919     for (unsigned I = 0, E = DefaultmapKindNum; I < E; ++I) {
5920       int ClauseKindCnt = -1;
5921       for (ArrayRef<Expr *> ImplicitMap : ImplicitMaps[I]) {
5922         ++ClauseKindCnt;
5923         if (ImplicitMap.empty())
5924           continue;
5925         CXXScopeSpec MapperIdScopeSpec;
5926         DeclarationNameInfo MapperId;
5927         auto Kind = static_cast<OpenMPMapClauseKind>(ClauseKindCnt);
5928         if (OMPClause *Implicit = ActOnOpenMPMapClause(
5929                 ImplicitMapModifiers[I], ImplicitMapModifiersLoc[I],
5930                 MapperIdScopeSpec, MapperId, Kind, /*IsMapTypeImplicit=*/true,
5931                 SourceLocation(), SourceLocation(), ImplicitMap,
5932                 OMPVarListLocTy())) {
5933           ClausesWithImplicit.emplace_back(Implicit);
5934           ErrorFound |= cast<OMPMapClause>(Implicit)->varlist_size() !=
5935                         ImplicitMap.size();
5936         } else {
5937           ErrorFound = true;
5938         }
5939       }
5940     }
5941     // Build expressions for implicit maps of data members with 'default'
5942     // mappers.
5943     if (LangOpts.OpenMP >= 50)
5944       processImplicitMapsWithDefaultMappers(*this, DSAStack,
5945                                             ClausesWithImplicit);
5946   }
5947 
5948   llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
5949   switch (Kind) {
5950   case OMPD_parallel:
5951     Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
5952                                        EndLoc);
5953     AllowedNameModifiers.push_back(OMPD_parallel);
5954     break;
5955   case OMPD_simd:
5956     Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
5957                                    VarsWithInheritedDSA);
5958     if (LangOpts.OpenMP >= 50)
5959       AllowedNameModifiers.push_back(OMPD_simd);
5960     break;
5961   case OMPD_tile:
5962     Res =
5963         ActOnOpenMPTileDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
5964     break;
5965   case OMPD_unroll:
5966     Res = ActOnOpenMPUnrollDirective(ClausesWithImplicit, AStmt, StartLoc,
5967                                      EndLoc);
5968     break;
5969   case OMPD_for:
5970     Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
5971                                   VarsWithInheritedDSA);
5972     break;
5973   case OMPD_for_simd:
5974     Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
5975                                       EndLoc, VarsWithInheritedDSA);
5976     if (LangOpts.OpenMP >= 50)
5977       AllowedNameModifiers.push_back(OMPD_simd);
5978     break;
5979   case OMPD_sections:
5980     Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
5981                                        EndLoc);
5982     break;
5983   case OMPD_section:
5984     assert(ClausesWithImplicit.empty() &&
5985            "No clauses are allowed for 'omp section' directive");
5986     Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
5987     break;
5988   case OMPD_single:
5989     Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
5990                                      EndLoc);
5991     break;
5992   case OMPD_master:
5993     assert(ClausesWithImplicit.empty() &&
5994            "No clauses are allowed for 'omp master' directive");
5995     Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
5996     break;
5997   case OMPD_masked:
5998     Res = ActOnOpenMPMaskedDirective(ClausesWithImplicit, AStmt, StartLoc,
5999                                      EndLoc);
6000     break;
6001   case OMPD_critical:
6002     Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
6003                                        StartLoc, EndLoc);
6004     break;
6005   case OMPD_parallel_for:
6006     Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
6007                                           EndLoc, VarsWithInheritedDSA);
6008     AllowedNameModifiers.push_back(OMPD_parallel);
6009     break;
6010   case OMPD_parallel_for_simd:
6011     Res = ActOnOpenMPParallelForSimdDirective(
6012         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6013     AllowedNameModifiers.push_back(OMPD_parallel);
6014     if (LangOpts.OpenMP >= 50)
6015       AllowedNameModifiers.push_back(OMPD_simd);
6016     break;
6017   case OMPD_parallel_master:
6018     Res = ActOnOpenMPParallelMasterDirective(ClausesWithImplicit, AStmt,
6019                                              StartLoc, EndLoc);
6020     AllowedNameModifiers.push_back(OMPD_parallel);
6021     break;
6022   case OMPD_parallel_sections:
6023     Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
6024                                                StartLoc, EndLoc);
6025     AllowedNameModifiers.push_back(OMPD_parallel);
6026     break;
6027   case OMPD_task:
6028     Res =
6029         ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
6030     AllowedNameModifiers.push_back(OMPD_task);
6031     break;
6032   case OMPD_taskyield:
6033     assert(ClausesWithImplicit.empty() &&
6034            "No clauses are allowed for 'omp taskyield' directive");
6035     assert(AStmt == nullptr &&
6036            "No associated statement allowed for 'omp taskyield' directive");
6037     Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
6038     break;
6039   case OMPD_barrier:
6040     assert(ClausesWithImplicit.empty() &&
6041            "No clauses are allowed for 'omp barrier' directive");
6042     assert(AStmt == nullptr &&
6043            "No associated statement allowed for 'omp barrier' directive");
6044     Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
6045     break;
6046   case OMPD_taskwait:
6047     assert(AStmt == nullptr &&
6048            "No associated statement allowed for 'omp taskwait' directive");
6049     Res = ActOnOpenMPTaskwaitDirective(ClausesWithImplicit, StartLoc, EndLoc);
6050     break;
6051   case OMPD_taskgroup:
6052     Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc,
6053                                         EndLoc);
6054     break;
6055   case OMPD_flush:
6056     assert(AStmt == nullptr &&
6057            "No associated statement allowed for 'omp flush' directive");
6058     Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
6059     break;
6060   case OMPD_depobj:
6061     assert(AStmt == nullptr &&
6062            "No associated statement allowed for 'omp depobj' directive");
6063     Res = ActOnOpenMPDepobjDirective(ClausesWithImplicit, StartLoc, EndLoc);
6064     break;
6065   case OMPD_scan:
6066     assert(AStmt == nullptr &&
6067            "No associated statement allowed for 'omp scan' directive");
6068     Res = ActOnOpenMPScanDirective(ClausesWithImplicit, StartLoc, EndLoc);
6069     break;
6070   case OMPD_ordered:
6071     Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
6072                                       EndLoc);
6073     break;
6074   case OMPD_atomic:
6075     Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
6076                                      EndLoc);
6077     break;
6078   case OMPD_teams:
6079     Res =
6080         ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
6081     break;
6082   case OMPD_target:
6083     Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
6084                                      EndLoc);
6085     AllowedNameModifiers.push_back(OMPD_target);
6086     break;
6087   case OMPD_target_parallel:
6088     Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
6089                                              StartLoc, EndLoc);
6090     AllowedNameModifiers.push_back(OMPD_target);
6091     AllowedNameModifiers.push_back(OMPD_parallel);
6092     break;
6093   case OMPD_target_parallel_for:
6094     Res = ActOnOpenMPTargetParallelForDirective(
6095         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6096     AllowedNameModifiers.push_back(OMPD_target);
6097     AllowedNameModifiers.push_back(OMPD_parallel);
6098     break;
6099   case OMPD_cancellation_point:
6100     assert(ClausesWithImplicit.empty() &&
6101            "No clauses are allowed for 'omp cancellation point' directive");
6102     assert(AStmt == nullptr && "No associated statement allowed for 'omp "
6103                                "cancellation point' directive");
6104     Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
6105     break;
6106   case OMPD_cancel:
6107     assert(AStmt == nullptr &&
6108            "No associated statement allowed for 'omp cancel' directive");
6109     Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
6110                                      CancelRegion);
6111     AllowedNameModifiers.push_back(OMPD_cancel);
6112     break;
6113   case OMPD_target_data:
6114     Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
6115                                          EndLoc);
6116     AllowedNameModifiers.push_back(OMPD_target_data);
6117     break;
6118   case OMPD_target_enter_data:
6119     Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
6120                                               EndLoc, AStmt);
6121     AllowedNameModifiers.push_back(OMPD_target_enter_data);
6122     break;
6123   case OMPD_target_exit_data:
6124     Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
6125                                              EndLoc, AStmt);
6126     AllowedNameModifiers.push_back(OMPD_target_exit_data);
6127     break;
6128   case OMPD_taskloop:
6129     Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
6130                                        EndLoc, VarsWithInheritedDSA);
6131     AllowedNameModifiers.push_back(OMPD_taskloop);
6132     break;
6133   case OMPD_taskloop_simd:
6134     Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
6135                                            EndLoc, VarsWithInheritedDSA);
6136     AllowedNameModifiers.push_back(OMPD_taskloop);
6137     if (LangOpts.OpenMP >= 50)
6138       AllowedNameModifiers.push_back(OMPD_simd);
6139     break;
6140   case OMPD_master_taskloop:
6141     Res = ActOnOpenMPMasterTaskLoopDirective(
6142         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6143     AllowedNameModifiers.push_back(OMPD_taskloop);
6144     break;
6145   case OMPD_master_taskloop_simd:
6146     Res = ActOnOpenMPMasterTaskLoopSimdDirective(
6147         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6148     AllowedNameModifiers.push_back(OMPD_taskloop);
6149     if (LangOpts.OpenMP >= 50)
6150       AllowedNameModifiers.push_back(OMPD_simd);
6151     break;
6152   case OMPD_parallel_master_taskloop:
6153     Res = ActOnOpenMPParallelMasterTaskLoopDirective(
6154         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6155     AllowedNameModifiers.push_back(OMPD_taskloop);
6156     AllowedNameModifiers.push_back(OMPD_parallel);
6157     break;
6158   case OMPD_parallel_master_taskloop_simd:
6159     Res = ActOnOpenMPParallelMasterTaskLoopSimdDirective(
6160         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6161     AllowedNameModifiers.push_back(OMPD_taskloop);
6162     AllowedNameModifiers.push_back(OMPD_parallel);
6163     if (LangOpts.OpenMP >= 50)
6164       AllowedNameModifiers.push_back(OMPD_simd);
6165     break;
6166   case OMPD_distribute:
6167     Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
6168                                          EndLoc, VarsWithInheritedDSA);
6169     break;
6170   case OMPD_target_update:
6171     Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc,
6172                                            EndLoc, AStmt);
6173     AllowedNameModifiers.push_back(OMPD_target_update);
6174     break;
6175   case OMPD_distribute_parallel_for:
6176     Res = ActOnOpenMPDistributeParallelForDirective(
6177         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6178     AllowedNameModifiers.push_back(OMPD_parallel);
6179     break;
6180   case OMPD_distribute_parallel_for_simd:
6181     Res = ActOnOpenMPDistributeParallelForSimdDirective(
6182         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6183     AllowedNameModifiers.push_back(OMPD_parallel);
6184     if (LangOpts.OpenMP >= 50)
6185       AllowedNameModifiers.push_back(OMPD_simd);
6186     break;
6187   case OMPD_distribute_simd:
6188     Res = ActOnOpenMPDistributeSimdDirective(
6189         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6190     if (LangOpts.OpenMP >= 50)
6191       AllowedNameModifiers.push_back(OMPD_simd);
6192     break;
6193   case OMPD_target_parallel_for_simd:
6194     Res = ActOnOpenMPTargetParallelForSimdDirective(
6195         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6196     AllowedNameModifiers.push_back(OMPD_target);
6197     AllowedNameModifiers.push_back(OMPD_parallel);
6198     if (LangOpts.OpenMP >= 50)
6199       AllowedNameModifiers.push_back(OMPD_simd);
6200     break;
6201   case OMPD_target_simd:
6202     Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
6203                                          EndLoc, VarsWithInheritedDSA);
6204     AllowedNameModifiers.push_back(OMPD_target);
6205     if (LangOpts.OpenMP >= 50)
6206       AllowedNameModifiers.push_back(OMPD_simd);
6207     break;
6208   case OMPD_teams_distribute:
6209     Res = ActOnOpenMPTeamsDistributeDirective(
6210         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6211     break;
6212   case OMPD_teams_distribute_simd:
6213     Res = ActOnOpenMPTeamsDistributeSimdDirective(
6214         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6215     if (LangOpts.OpenMP >= 50)
6216       AllowedNameModifiers.push_back(OMPD_simd);
6217     break;
6218   case OMPD_teams_distribute_parallel_for_simd:
6219     Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
6220         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6221     AllowedNameModifiers.push_back(OMPD_parallel);
6222     if (LangOpts.OpenMP >= 50)
6223       AllowedNameModifiers.push_back(OMPD_simd);
6224     break;
6225   case OMPD_teams_distribute_parallel_for:
6226     Res = ActOnOpenMPTeamsDistributeParallelForDirective(
6227         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6228     AllowedNameModifiers.push_back(OMPD_parallel);
6229     break;
6230   case OMPD_target_teams:
6231     Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
6232                                           EndLoc);
6233     AllowedNameModifiers.push_back(OMPD_target);
6234     break;
6235   case OMPD_target_teams_distribute:
6236     Res = ActOnOpenMPTargetTeamsDistributeDirective(
6237         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6238     AllowedNameModifiers.push_back(OMPD_target);
6239     break;
6240   case OMPD_target_teams_distribute_parallel_for:
6241     Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
6242         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6243     AllowedNameModifiers.push_back(OMPD_target);
6244     AllowedNameModifiers.push_back(OMPD_parallel);
6245     break;
6246   case OMPD_target_teams_distribute_parallel_for_simd:
6247     Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
6248         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6249     AllowedNameModifiers.push_back(OMPD_target);
6250     AllowedNameModifiers.push_back(OMPD_parallel);
6251     if (LangOpts.OpenMP >= 50)
6252       AllowedNameModifiers.push_back(OMPD_simd);
6253     break;
6254   case OMPD_target_teams_distribute_simd:
6255     Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
6256         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
6257     AllowedNameModifiers.push_back(OMPD_target);
6258     if (LangOpts.OpenMP >= 50)
6259       AllowedNameModifiers.push_back(OMPD_simd);
6260     break;
6261   case OMPD_interop:
6262     assert(AStmt == nullptr &&
6263            "No associated statement allowed for 'omp interop' directive");
6264     Res = ActOnOpenMPInteropDirective(ClausesWithImplicit, StartLoc, EndLoc);
6265     break;
6266   case OMPD_dispatch:
6267     Res = ActOnOpenMPDispatchDirective(ClausesWithImplicit, AStmt, StartLoc,
6268                                        EndLoc);
6269     break;
6270   case OMPD_loop:
6271     Res = ActOnOpenMPGenericLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
6272                                           EndLoc, VarsWithInheritedDSA);
6273     break;
6274   case OMPD_declare_target:
6275   case OMPD_end_declare_target:
6276   case OMPD_threadprivate:
6277   case OMPD_allocate:
6278   case OMPD_declare_reduction:
6279   case OMPD_declare_mapper:
6280   case OMPD_declare_simd:
6281   case OMPD_requires:
6282   case OMPD_declare_variant:
6283   case OMPD_begin_declare_variant:
6284   case OMPD_end_declare_variant:
6285     llvm_unreachable("OpenMP Directive is not allowed");
6286   case OMPD_unknown:
6287   default:
6288     llvm_unreachable("Unknown OpenMP directive");
6289   }
6290 
6291   ErrorFound = Res.isInvalid() || ErrorFound;
6292 
6293   // Check variables in the clauses if default(none) or
6294   // default(firstprivate) was specified.
6295   if (DSAStack->getDefaultDSA() == DSA_none ||
6296       DSAStack->getDefaultDSA() == DSA_firstprivate) {
6297     DSAAttrChecker DSAChecker(DSAStack, *this, nullptr);
6298     for (OMPClause *C : Clauses) {
6299       switch (C->getClauseKind()) {
6300       case OMPC_num_threads:
6301       case OMPC_dist_schedule:
6302         // Do not analyse if no parent teams directive.
6303         if (isOpenMPTeamsDirective(Kind))
6304           break;
6305         continue;
6306       case OMPC_if:
6307         if (isOpenMPTeamsDirective(Kind) &&
6308             cast<OMPIfClause>(C)->getNameModifier() != OMPD_target)
6309           break;
6310         if (isOpenMPParallelDirective(Kind) &&
6311             isOpenMPTaskLoopDirective(Kind) &&
6312             cast<OMPIfClause>(C)->getNameModifier() != OMPD_parallel)
6313           break;
6314         continue;
6315       case OMPC_schedule:
6316       case OMPC_detach:
6317         break;
6318       case OMPC_grainsize:
6319       case OMPC_num_tasks:
6320       case OMPC_final:
6321       case OMPC_priority:
6322       case OMPC_novariants:
6323       case OMPC_nocontext:
6324         // Do not analyze if no parent parallel directive.
6325         if (isOpenMPParallelDirective(Kind))
6326           break;
6327         continue;
6328       case OMPC_ordered:
6329       case OMPC_device:
6330       case OMPC_num_teams:
6331       case OMPC_thread_limit:
6332       case OMPC_hint:
6333       case OMPC_collapse:
6334       case OMPC_safelen:
6335       case OMPC_simdlen:
6336       case OMPC_sizes:
6337       case OMPC_default:
6338       case OMPC_proc_bind:
6339       case OMPC_private:
6340       case OMPC_firstprivate:
6341       case OMPC_lastprivate:
6342       case OMPC_shared:
6343       case OMPC_reduction:
6344       case OMPC_task_reduction:
6345       case OMPC_in_reduction:
6346       case OMPC_linear:
6347       case OMPC_aligned:
6348       case OMPC_copyin:
6349       case OMPC_copyprivate:
6350       case OMPC_nowait:
6351       case OMPC_untied:
6352       case OMPC_mergeable:
6353       case OMPC_allocate:
6354       case OMPC_read:
6355       case OMPC_write:
6356       case OMPC_update:
6357       case OMPC_capture:
6358       case OMPC_compare:
6359       case OMPC_seq_cst:
6360       case OMPC_acq_rel:
6361       case OMPC_acquire:
6362       case OMPC_release:
6363       case OMPC_relaxed:
6364       case OMPC_depend:
6365       case OMPC_threads:
6366       case OMPC_simd:
6367       case OMPC_map:
6368       case OMPC_nogroup:
6369       case OMPC_defaultmap:
6370       case OMPC_to:
6371       case OMPC_from:
6372       case OMPC_use_device_ptr:
6373       case OMPC_use_device_addr:
6374       case OMPC_is_device_ptr:
6375       case OMPC_nontemporal:
6376       case OMPC_order:
6377       case OMPC_destroy:
6378       case OMPC_inclusive:
6379       case OMPC_exclusive:
6380       case OMPC_uses_allocators:
6381       case OMPC_affinity:
6382       case OMPC_bind:
6383         continue;
6384       case OMPC_allocator:
6385       case OMPC_flush:
6386       case OMPC_depobj:
6387       case OMPC_threadprivate:
6388       case OMPC_uniform:
6389       case OMPC_unknown:
6390       case OMPC_unified_address:
6391       case OMPC_unified_shared_memory:
6392       case OMPC_reverse_offload:
6393       case OMPC_dynamic_allocators:
6394       case OMPC_atomic_default_mem_order:
6395       case OMPC_device_type:
6396       case OMPC_match:
6397       case OMPC_when:
6398       default:
6399         llvm_unreachable("Unexpected clause");
6400       }
6401       for (Stmt *CC : C->children()) {
6402         if (CC)
6403           DSAChecker.Visit(CC);
6404       }
6405     }
6406     for (const auto &P : DSAChecker.getVarsWithInheritedDSA())
6407       VarsWithInheritedDSA[P.getFirst()] = P.getSecond();
6408   }
6409   for (const auto &P : VarsWithInheritedDSA) {
6410     if (P.getFirst()->isImplicit() || isa<OMPCapturedExprDecl>(P.getFirst()))
6411       continue;
6412     ErrorFound = true;
6413     if (DSAStack->getDefaultDSA() == DSA_none ||
6414         DSAStack->getDefaultDSA() == DSA_firstprivate) {
6415       Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
6416           << P.first << P.second->getSourceRange();
6417       Diag(DSAStack->getDefaultDSALocation(), diag::note_omp_default_dsa_none);
6418     } else if (getLangOpts().OpenMP >= 50) {
6419       Diag(P.second->getExprLoc(),
6420            diag::err_omp_defaultmap_no_attr_for_variable)
6421           << P.first << P.second->getSourceRange();
6422       Diag(DSAStack->getDefaultDSALocation(),
6423            diag::note_omp_defaultmap_attr_none);
6424     }
6425   }
6426 
6427   if (!AllowedNameModifiers.empty())
6428     ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
6429                  ErrorFound;
6430 
6431   if (ErrorFound)
6432     return StmtError();
6433 
6434   if (!CurContext->isDependentContext() &&
6435       isOpenMPTargetExecutionDirective(Kind) &&
6436       !(DSAStack->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() ||
6437         DSAStack->hasRequiresDeclWithClause<OMPUnifiedAddressClause>() ||
6438         DSAStack->hasRequiresDeclWithClause<OMPReverseOffloadClause>() ||
6439         DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())) {
6440     // Register target to DSA Stack.
6441     DSAStack->addTargetDirLocation(StartLoc);
6442   }
6443 
6444   return Res;
6445 }
6446 
6447 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
6448     DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
6449     ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
6450     ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
6451     ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
6452   assert(Aligneds.size() == Alignments.size());
6453   assert(Linears.size() == LinModifiers.size());
6454   assert(Linears.size() == Steps.size());
6455   if (!DG || DG.get().isNull())
6456     return DeclGroupPtrTy();
6457 
6458   const int SimdId = 0;
6459   if (!DG.get().isSingleDecl()) {
6460     Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd_variant)
6461         << SimdId;
6462     return DG;
6463   }
6464   Decl *ADecl = DG.get().getSingleDecl();
6465   if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
6466     ADecl = FTD->getTemplatedDecl();
6467 
6468   auto *FD = dyn_cast<FunctionDecl>(ADecl);
6469   if (!FD) {
6470     Diag(ADecl->getLocation(), diag::err_omp_function_expected) << SimdId;
6471     return DeclGroupPtrTy();
6472   }
6473 
6474   // OpenMP [2.8.2, declare simd construct, Description]
6475   // The parameter of the simdlen clause must be a constant positive integer
6476   // expression.
6477   ExprResult SL;
6478   if (Simdlen)
6479     SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
6480   // OpenMP [2.8.2, declare simd construct, Description]
6481   // The special this pointer can be used as if was one of the arguments to the
6482   // function in any of the linear, aligned, or uniform clauses.
6483   // The uniform clause declares one or more arguments to have an invariant
6484   // value for all concurrent invocations of the function in the execution of a
6485   // single SIMD loop.
6486   llvm::DenseMap<const Decl *, const Expr *> UniformedArgs;
6487   const Expr *UniformedLinearThis = nullptr;
6488   for (const Expr *E : Uniforms) {
6489     E = E->IgnoreParenImpCasts();
6490     if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
6491       if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
6492         if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
6493             FD->getParamDecl(PVD->getFunctionScopeIndex())
6494                     ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
6495           UniformedArgs.try_emplace(PVD->getCanonicalDecl(), E);
6496           continue;
6497         }
6498     if (isa<CXXThisExpr>(E)) {
6499       UniformedLinearThis = E;
6500       continue;
6501     }
6502     Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
6503         << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
6504   }
6505   // OpenMP [2.8.2, declare simd construct, Description]
6506   // The aligned clause declares that the object to which each list item points
6507   // is aligned to the number of bytes expressed in the optional parameter of
6508   // the aligned clause.
6509   // The special this pointer can be used as if was one of the arguments to the
6510   // function in any of the linear, aligned, or uniform clauses.
6511   // The type of list items appearing in the aligned clause must be array,
6512   // pointer, reference to array, or reference to pointer.
6513   llvm::DenseMap<const Decl *, const Expr *> AlignedArgs;
6514   const Expr *AlignedThis = nullptr;
6515   for (const Expr *E : Aligneds) {
6516     E = E->IgnoreParenImpCasts();
6517     if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
6518       if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
6519         const VarDecl *CanonPVD = PVD->getCanonicalDecl();
6520         if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
6521             FD->getParamDecl(PVD->getFunctionScopeIndex())
6522                     ->getCanonicalDecl() == CanonPVD) {
6523           // OpenMP  [2.8.1, simd construct, Restrictions]
6524           // A list-item cannot appear in more than one aligned clause.
6525           if (AlignedArgs.count(CanonPVD) > 0) {
6526             Diag(E->getExprLoc(), diag::err_omp_used_in_clause_twice)
6527                 << 1 << getOpenMPClauseName(OMPC_aligned)
6528                 << E->getSourceRange();
6529             Diag(AlignedArgs[CanonPVD]->getExprLoc(),
6530                  diag::note_omp_explicit_dsa)
6531                 << getOpenMPClauseName(OMPC_aligned);
6532             continue;
6533           }
6534           AlignedArgs[CanonPVD] = E;
6535           QualType QTy = PVD->getType()
6536                              .getNonReferenceType()
6537                              .getUnqualifiedType()
6538                              .getCanonicalType();
6539           const Type *Ty = QTy.getTypePtrOrNull();
6540           if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
6541             Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
6542                 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
6543             Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
6544           }
6545           continue;
6546         }
6547       }
6548     if (isa<CXXThisExpr>(E)) {
6549       if (AlignedThis) {
6550         Diag(E->getExprLoc(), diag::err_omp_used_in_clause_twice)
6551             << 2 << getOpenMPClauseName(OMPC_aligned) << E->getSourceRange();
6552         Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
6553             << getOpenMPClauseName(OMPC_aligned);
6554       }
6555       AlignedThis = E;
6556       continue;
6557     }
6558     Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
6559         << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
6560   }
6561   // The optional parameter of the aligned clause, alignment, must be a constant
6562   // positive integer expression. If no optional parameter is specified,
6563   // implementation-defined default alignments for SIMD instructions on the
6564   // target platforms are assumed.
6565   SmallVector<const Expr *, 4> NewAligns;
6566   for (Expr *E : Alignments) {
6567     ExprResult Align;
6568     if (E)
6569       Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
6570     NewAligns.push_back(Align.get());
6571   }
6572   // OpenMP [2.8.2, declare simd construct, Description]
6573   // The linear clause declares one or more list items to be private to a SIMD
6574   // lane and to have a linear relationship with respect to the iteration space
6575   // of a loop.
6576   // The special this pointer can be used as if was one of the arguments to the
6577   // function in any of the linear, aligned, or uniform clauses.
6578   // When a linear-step expression is specified in a linear clause it must be
6579   // either a constant integer expression or an integer-typed parameter that is
6580   // specified in a uniform clause on the directive.
6581   llvm::DenseMap<const Decl *, const Expr *> LinearArgs;
6582   const bool IsUniformedThis = UniformedLinearThis != nullptr;
6583   auto MI = LinModifiers.begin();
6584   for (const Expr *E : Linears) {
6585     auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
6586     ++MI;
6587     E = E->IgnoreParenImpCasts();
6588     if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
6589       if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
6590         const VarDecl *CanonPVD = PVD->getCanonicalDecl();
6591         if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
6592             FD->getParamDecl(PVD->getFunctionScopeIndex())
6593                     ->getCanonicalDecl() == CanonPVD) {
6594           // OpenMP  [2.15.3.7, linear Clause, Restrictions]
6595           // A list-item cannot appear in more than one linear clause.
6596           if (LinearArgs.count(CanonPVD) > 0) {
6597             Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
6598                 << getOpenMPClauseName(OMPC_linear)
6599                 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
6600             Diag(LinearArgs[CanonPVD]->getExprLoc(),
6601                  diag::note_omp_explicit_dsa)
6602                 << getOpenMPClauseName(OMPC_linear);
6603             continue;
6604           }
6605           // Each argument can appear in at most one uniform or linear clause.
6606           if (UniformedArgs.count(CanonPVD) > 0) {
6607             Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
6608                 << getOpenMPClauseName(OMPC_linear)
6609                 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
6610             Diag(UniformedArgs[CanonPVD]->getExprLoc(),
6611                  diag::note_omp_explicit_dsa)
6612                 << getOpenMPClauseName(OMPC_uniform);
6613             continue;
6614           }
6615           LinearArgs[CanonPVD] = E;
6616           if (E->isValueDependent() || E->isTypeDependent() ||
6617               E->isInstantiationDependent() ||
6618               E->containsUnexpandedParameterPack())
6619             continue;
6620           (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
6621                                       PVD->getOriginalType(),
6622                                       /*IsDeclareSimd=*/true);
6623           continue;
6624         }
6625       }
6626     if (isa<CXXThisExpr>(E)) {
6627       if (UniformedLinearThis) {
6628         Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
6629             << getOpenMPClauseName(OMPC_linear)
6630             << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
6631             << E->getSourceRange();
6632         Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
6633             << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
6634                                                    : OMPC_linear);
6635         continue;
6636       }
6637       UniformedLinearThis = E;
6638       if (E->isValueDependent() || E->isTypeDependent() ||
6639           E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
6640         continue;
6641       (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
6642                                   E->getType(), /*IsDeclareSimd=*/true);
6643       continue;
6644     }
6645     Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
6646         << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
6647   }
6648   Expr *Step = nullptr;
6649   Expr *NewStep = nullptr;
6650   SmallVector<Expr *, 4> NewSteps;
6651   for (Expr *E : Steps) {
6652     // Skip the same step expression, it was checked already.
6653     if (Step == E || !E) {
6654       NewSteps.push_back(E ? NewStep : nullptr);
6655       continue;
6656     }
6657     Step = E;
6658     if (const auto *DRE = dyn_cast<DeclRefExpr>(Step))
6659       if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
6660         const VarDecl *CanonPVD = PVD->getCanonicalDecl();
6661         if (UniformedArgs.count(CanonPVD) == 0) {
6662           Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
6663               << Step->getSourceRange();
6664         } else if (E->isValueDependent() || E->isTypeDependent() ||
6665                    E->isInstantiationDependent() ||
6666                    E->containsUnexpandedParameterPack() ||
6667                    CanonPVD->getType()->hasIntegerRepresentation()) {
6668           NewSteps.push_back(Step);
6669         } else {
6670           Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
6671               << Step->getSourceRange();
6672         }
6673         continue;
6674       }
6675     NewStep = Step;
6676     if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
6677         !Step->isInstantiationDependent() &&
6678         !Step->containsUnexpandedParameterPack()) {
6679       NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
6680                     .get();
6681       if (NewStep)
6682         NewStep =
6683             VerifyIntegerConstantExpression(NewStep, /*FIXME*/ AllowFold).get();
6684     }
6685     NewSteps.push_back(NewStep);
6686   }
6687   auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
6688       Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
6689       Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
6690       const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
6691       const_cast<Expr **>(Linears.data()), Linears.size(),
6692       const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
6693       NewSteps.data(), NewSteps.size(), SR);
6694   ADecl->addAttr(NewAttr);
6695   return DG;
6696 }
6697 
6698 static void setPrototype(Sema &S, FunctionDecl *FD, FunctionDecl *FDWithProto,
6699                          QualType NewType) {
6700   assert(NewType->isFunctionProtoType() &&
6701          "Expected function type with prototype.");
6702   assert(FD->getType()->isFunctionNoProtoType() &&
6703          "Expected function with type with no prototype.");
6704   assert(FDWithProto->getType()->isFunctionProtoType() &&
6705          "Expected function with prototype.");
6706   // Synthesize parameters with the same types.
6707   FD->setType(NewType);
6708   SmallVector<ParmVarDecl *, 16> Params;
6709   for (const ParmVarDecl *P : FDWithProto->parameters()) {
6710     auto *Param = ParmVarDecl::Create(S.getASTContext(), FD, SourceLocation(),
6711                                       SourceLocation(), nullptr, P->getType(),
6712                                       /*TInfo=*/nullptr, SC_None, nullptr);
6713     Param->setScopeInfo(0, Params.size());
6714     Param->setImplicit();
6715     Params.push_back(Param);
6716   }
6717 
6718   FD->setParams(Params);
6719 }
6720 
6721 void Sema::ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(Decl *D) {
6722   if (D->isInvalidDecl())
6723     return;
6724   FunctionDecl *FD = nullptr;
6725   if (auto *UTemplDecl = dyn_cast<FunctionTemplateDecl>(D))
6726     FD = UTemplDecl->getTemplatedDecl();
6727   else
6728     FD = cast<FunctionDecl>(D);
6729   assert(FD && "Expected a function declaration!");
6730 
6731   // If we are instantiating templates we do *not* apply scoped assumptions but
6732   // only global ones. We apply scoped assumption to the template definition
6733   // though.
6734   if (!inTemplateInstantiation()) {
6735     for (AssumptionAttr *AA : OMPAssumeScoped)
6736       FD->addAttr(AA);
6737   }
6738   for (AssumptionAttr *AA : OMPAssumeGlobal)
6739     FD->addAttr(AA);
6740 }
6741 
6742 Sema::OMPDeclareVariantScope::OMPDeclareVariantScope(OMPTraitInfo &TI)
6743     : TI(&TI), NameSuffix(TI.getMangledName()) {}
6744 
6745 void Sema::ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
6746     Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists,
6747     SmallVectorImpl<FunctionDecl *> &Bases) {
6748   if (!D.getIdentifier())
6749     return;
6750 
6751   OMPDeclareVariantScope &DVScope = OMPDeclareVariantScopes.back();
6752 
6753   // Template specialization is an extension, check if we do it.
6754   bool IsTemplated = !TemplateParamLists.empty();
6755   if (IsTemplated &
6756       !DVScope.TI->isExtensionActive(
6757           llvm::omp::TraitProperty::implementation_extension_allow_templates))
6758     return;
6759 
6760   IdentifierInfo *BaseII = D.getIdentifier();
6761   LookupResult Lookup(*this, DeclarationName(BaseII), D.getIdentifierLoc(),
6762                       LookupOrdinaryName);
6763   LookupParsedName(Lookup, S, &D.getCXXScopeSpec());
6764 
6765   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6766   QualType FType = TInfo->getType();
6767 
6768   bool IsConstexpr =
6769       D.getDeclSpec().getConstexprSpecifier() == ConstexprSpecKind::Constexpr;
6770   bool IsConsteval =
6771       D.getDeclSpec().getConstexprSpecifier() == ConstexprSpecKind::Consteval;
6772 
6773   for (auto *Candidate : Lookup) {
6774     auto *CandidateDecl = Candidate->getUnderlyingDecl();
6775     FunctionDecl *UDecl = nullptr;
6776     if (IsTemplated && isa<FunctionTemplateDecl>(CandidateDecl)) {
6777       auto *FTD = cast<FunctionTemplateDecl>(CandidateDecl);
6778       if (FTD->getTemplateParameters()->size() == TemplateParamLists.size())
6779         UDecl = FTD->getTemplatedDecl();
6780     } else if (!IsTemplated)
6781       UDecl = dyn_cast<FunctionDecl>(CandidateDecl);
6782     if (!UDecl)
6783       continue;
6784 
6785     // Don't specialize constexpr/consteval functions with
6786     // non-constexpr/consteval functions.
6787     if (UDecl->isConstexpr() && !IsConstexpr)
6788       continue;
6789     if (UDecl->isConsteval() && !IsConsteval)
6790       continue;
6791 
6792     QualType UDeclTy = UDecl->getType();
6793     if (!UDeclTy->isDependentType()) {
6794       QualType NewType = Context.mergeFunctionTypes(
6795           FType, UDeclTy, /* OfBlockPointer */ false,
6796           /* Unqualified */ false, /* AllowCXX */ true);
6797       if (NewType.isNull())
6798         continue;
6799     }
6800 
6801     // Found a base!
6802     Bases.push_back(UDecl);
6803   }
6804 
6805   bool UseImplicitBase = !DVScope.TI->isExtensionActive(
6806       llvm::omp::TraitProperty::implementation_extension_disable_implicit_base);
6807   // If no base was found we create a declaration that we use as base.
6808   if (Bases.empty() && UseImplicitBase) {
6809     D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration);
6810     Decl *BaseD = HandleDeclarator(S, D, TemplateParamLists);
6811     BaseD->setImplicit(true);
6812     if (auto *BaseTemplD = dyn_cast<FunctionTemplateDecl>(BaseD))
6813       Bases.push_back(BaseTemplD->getTemplatedDecl());
6814     else
6815       Bases.push_back(cast<FunctionDecl>(BaseD));
6816   }
6817 
6818   std::string MangledName;
6819   MangledName += D.getIdentifier()->getName();
6820   MangledName += getOpenMPVariantManglingSeparatorStr();
6821   MangledName += DVScope.NameSuffix;
6822   IdentifierInfo &VariantII = Context.Idents.get(MangledName);
6823 
6824   VariantII.setMangledOpenMPVariantName(true);
6825   D.SetIdentifier(&VariantII, D.getBeginLoc());
6826 }
6827 
6828 void Sema::ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(
6829     Decl *D, SmallVectorImpl<FunctionDecl *> &Bases) {
6830   // Do not mark function as is used to prevent its emission if this is the
6831   // only place where it is used.
6832   EnterExpressionEvaluationContext Unevaluated(
6833       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6834 
6835   FunctionDecl *FD = nullptr;
6836   if (auto *UTemplDecl = dyn_cast<FunctionTemplateDecl>(D))
6837     FD = UTemplDecl->getTemplatedDecl();
6838   else
6839     FD = cast<FunctionDecl>(D);
6840   auto *VariantFuncRef = DeclRefExpr::Create(
6841       Context, NestedNameSpecifierLoc(), SourceLocation(), FD,
6842       /* RefersToEnclosingVariableOrCapture */ false,
6843       /* NameLoc */ FD->getLocation(), FD->getType(),
6844       ExprValueKind::VK_PRValue);
6845 
6846   OMPDeclareVariantScope &DVScope = OMPDeclareVariantScopes.back();
6847   auto *OMPDeclareVariantA = OMPDeclareVariantAttr::CreateImplicit(
6848       Context, VariantFuncRef, DVScope.TI,
6849       /*NothingArgs=*/nullptr, /*NothingArgsSize=*/0,
6850       /*NeedDevicePtrArgs=*/nullptr, /*NeedDevicePtrArgsSize=*/0,
6851       /*AppendArgs=*/nullptr, /*AppendArgsSize=*/0);
6852   for (FunctionDecl *BaseFD : Bases)
6853     BaseFD->addAttr(OMPDeclareVariantA);
6854 }
6855 
6856 ExprResult Sema::ActOnOpenMPCall(ExprResult Call, Scope *Scope,
6857                                  SourceLocation LParenLoc,
6858                                  MultiExprArg ArgExprs,
6859                                  SourceLocation RParenLoc, Expr *ExecConfig) {
6860   // The common case is a regular call we do not want to specialize at all. Try
6861   // to make that case fast by bailing early.
6862   CallExpr *CE = dyn_cast<CallExpr>(Call.get());
6863   if (!CE)
6864     return Call;
6865 
6866   FunctionDecl *CalleeFnDecl = CE->getDirectCallee();
6867   if (!CalleeFnDecl)
6868     return Call;
6869 
6870   if (!CalleeFnDecl->hasAttr<OMPDeclareVariantAttr>())
6871     return Call;
6872 
6873   ASTContext &Context = getASTContext();
6874   std::function<void(StringRef)> DiagUnknownTrait = [this,
6875                                                      CE](StringRef ISATrait) {
6876     // TODO Track the selector locations in a way that is accessible here to
6877     // improve the diagnostic location.
6878     Diag(CE->getBeginLoc(), diag::warn_unknown_declare_variant_isa_trait)
6879         << ISATrait;
6880   };
6881   TargetOMPContext OMPCtx(Context, std::move(DiagUnknownTrait),
6882                           getCurFunctionDecl(), DSAStack->getConstructTraits());
6883 
6884   QualType CalleeFnType = CalleeFnDecl->getType();
6885 
6886   SmallVector<Expr *, 4> Exprs;
6887   SmallVector<VariantMatchInfo, 4> VMIs;
6888   while (CalleeFnDecl) {
6889     for (OMPDeclareVariantAttr *A :
6890          CalleeFnDecl->specific_attrs<OMPDeclareVariantAttr>()) {
6891       Expr *VariantRef = A->getVariantFuncRef();
6892 
6893       VariantMatchInfo VMI;
6894       OMPTraitInfo &TI = A->getTraitInfo();
6895       TI.getAsVariantMatchInfo(Context, VMI);
6896       if (!isVariantApplicableInContext(VMI, OMPCtx,
6897                                         /* DeviceSetOnly */ false))
6898         continue;
6899 
6900       VMIs.push_back(VMI);
6901       Exprs.push_back(VariantRef);
6902     }
6903 
6904     CalleeFnDecl = CalleeFnDecl->getPreviousDecl();
6905   }
6906 
6907   ExprResult NewCall;
6908   do {
6909     int BestIdx = getBestVariantMatchForContext(VMIs, OMPCtx);
6910     if (BestIdx < 0)
6911       return Call;
6912     Expr *BestExpr = cast<DeclRefExpr>(Exprs[BestIdx]);
6913     Decl *BestDecl = cast<DeclRefExpr>(BestExpr)->getDecl();
6914 
6915     {
6916       // Try to build a (member) call expression for the current best applicable
6917       // variant expression. We allow this to fail in which case we continue
6918       // with the next best variant expression. The fail case is part of the
6919       // implementation defined behavior in the OpenMP standard when it talks
6920       // about what differences in the function prototypes: "Any differences
6921       // that the specific OpenMP context requires in the prototype of the
6922       // variant from the base function prototype are implementation defined."
6923       // This wording is there to allow the specialized variant to have a
6924       // different type than the base function. This is intended and OK but if
6925       // we cannot create a call the difference is not in the "implementation
6926       // defined range" we allow.
6927       Sema::TentativeAnalysisScope Trap(*this);
6928 
6929       if (auto *SpecializedMethod = dyn_cast<CXXMethodDecl>(BestDecl)) {
6930         auto *MemberCall = dyn_cast<CXXMemberCallExpr>(CE);
6931         BestExpr = MemberExpr::CreateImplicit(
6932             Context, MemberCall->getImplicitObjectArgument(),
6933             /* IsArrow */ false, SpecializedMethod, Context.BoundMemberTy,
6934             MemberCall->getValueKind(), MemberCall->getObjectKind());
6935       }
6936       NewCall = BuildCallExpr(Scope, BestExpr, LParenLoc, ArgExprs, RParenLoc,
6937                               ExecConfig);
6938       if (NewCall.isUsable()) {
6939         if (CallExpr *NCE = dyn_cast<CallExpr>(NewCall.get())) {
6940           FunctionDecl *NewCalleeFnDecl = NCE->getDirectCallee();
6941           QualType NewType = Context.mergeFunctionTypes(
6942               CalleeFnType, NewCalleeFnDecl->getType(),
6943               /* OfBlockPointer */ false,
6944               /* Unqualified */ false, /* AllowCXX */ true);
6945           if (!NewType.isNull())
6946             break;
6947           // Don't use the call if the function type was not compatible.
6948           NewCall = nullptr;
6949         }
6950       }
6951     }
6952 
6953     VMIs.erase(VMIs.begin() + BestIdx);
6954     Exprs.erase(Exprs.begin() + BestIdx);
6955   } while (!VMIs.empty());
6956 
6957   if (!NewCall.isUsable())
6958     return Call;
6959   return PseudoObjectExpr::Create(Context, CE, {NewCall.get()}, 0);
6960 }
6961 
6962 Optional<std::pair<FunctionDecl *, Expr *>>
6963 Sema::checkOpenMPDeclareVariantFunction(Sema::DeclGroupPtrTy DG,
6964                                         Expr *VariantRef, OMPTraitInfo &TI,
6965                                         unsigned NumAppendArgs,
6966                                         SourceRange SR) {
6967   if (!DG || DG.get().isNull())
6968     return None;
6969 
6970   const int VariantId = 1;
6971   // Must be applied only to single decl.
6972   if (!DG.get().isSingleDecl()) {
6973     Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd_variant)
6974         << VariantId << SR;
6975     return None;
6976   }
6977   Decl *ADecl = DG.get().getSingleDecl();
6978   if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
6979     ADecl = FTD->getTemplatedDecl();
6980 
6981   // Decl must be a function.
6982   auto *FD = dyn_cast<FunctionDecl>(ADecl);
6983   if (!FD) {
6984     Diag(ADecl->getLocation(), diag::err_omp_function_expected)
6985         << VariantId << SR;
6986     return None;
6987   }
6988 
6989   auto &&HasMultiVersionAttributes = [](const FunctionDecl *FD) {
6990     return FD->hasAttrs() &&
6991            (FD->hasAttr<CPUDispatchAttr>() || FD->hasAttr<CPUSpecificAttr>() ||
6992             FD->hasAttr<TargetAttr>());
6993   };
6994   // OpenMP is not compatible with CPU-specific attributes.
6995   if (HasMultiVersionAttributes(FD)) {
6996     Diag(FD->getLocation(), diag::err_omp_declare_variant_incompat_attributes)
6997         << SR;
6998     return None;
6999   }
7000 
7001   // Allow #pragma omp declare variant only if the function is not used.
7002   if (FD->isUsed(false))
7003     Diag(SR.getBegin(), diag::warn_omp_declare_variant_after_used)
7004         << FD->getLocation();
7005 
7006   // Check if the function was emitted already.
7007   const FunctionDecl *Definition;
7008   if (!FD->isThisDeclarationADefinition() && FD->isDefined(Definition) &&
7009       (LangOpts.EmitAllDecls || Context.DeclMustBeEmitted(Definition)))
7010     Diag(SR.getBegin(), diag::warn_omp_declare_variant_after_emitted)
7011         << FD->getLocation();
7012 
7013   // The VariantRef must point to function.
7014   if (!VariantRef) {
7015     Diag(SR.getBegin(), diag::err_omp_function_expected) << VariantId;
7016     return None;
7017   }
7018 
7019   auto ShouldDelayChecks = [](Expr *&E, bool) {
7020     return E && (E->isTypeDependent() || E->isValueDependent() ||
7021                  E->containsUnexpandedParameterPack() ||
7022                  E->isInstantiationDependent());
7023   };
7024   // Do not check templates, wait until instantiation.
7025   if (FD->isDependentContext() || ShouldDelayChecks(VariantRef, false) ||
7026       TI.anyScoreOrCondition(ShouldDelayChecks))
7027     return std::make_pair(FD, VariantRef);
7028 
7029   // Deal with non-constant score and user condition expressions.
7030   auto HandleNonConstantScoresAndConditions = [this](Expr *&E,
7031                                                      bool IsScore) -> bool {
7032     if (!E || E->isIntegerConstantExpr(Context))
7033       return false;
7034 
7035     if (IsScore) {
7036       // We warn on non-constant scores and pretend they were not present.
7037       Diag(E->getExprLoc(), diag::warn_omp_declare_variant_score_not_constant)
7038           << E;
7039       E = nullptr;
7040     } else {
7041       // We could replace a non-constant user condition with "false" but we
7042       // will soon need to handle these anyway for the dynamic version of
7043       // OpenMP context selectors.
7044       Diag(E->getExprLoc(),
7045            diag::err_omp_declare_variant_user_condition_not_constant)
7046           << E;
7047     }
7048     return true;
7049   };
7050   if (TI.anyScoreOrCondition(HandleNonConstantScoresAndConditions))
7051     return None;
7052 
7053   QualType AdjustedFnType = FD->getType();
7054   if (NumAppendArgs) {
7055     const auto *PTy = AdjustedFnType->getAsAdjusted<FunctionProtoType>();
7056     if (!PTy) {
7057       Diag(FD->getLocation(), diag::err_omp_declare_variant_prototype_required)
7058           << SR;
7059       return None;
7060     }
7061     // Adjust the function type to account for an extra omp_interop_t for each
7062     // specified in the append_args clause.
7063     const TypeDecl *TD = nullptr;
7064     LookupResult Result(*this, &Context.Idents.get("omp_interop_t"),
7065                         SR.getBegin(), Sema::LookupOrdinaryName);
7066     if (LookupName(Result, getCurScope())) {
7067       NamedDecl *ND = Result.getFoundDecl();
7068       TD = dyn_cast_or_null<TypeDecl>(ND);
7069     }
7070     if (!TD) {
7071       Diag(SR.getBegin(), diag::err_omp_interop_type_not_found) << SR;
7072       return None;
7073     }
7074     QualType InteropType = Context.getTypeDeclType(TD);
7075     if (PTy->isVariadic()) {
7076       Diag(FD->getLocation(), diag::err_omp_append_args_with_varargs) << SR;
7077       return None;
7078     }
7079     llvm::SmallVector<QualType, 8> Params;
7080     Params.append(PTy->param_type_begin(), PTy->param_type_end());
7081     Params.insert(Params.end(), NumAppendArgs, InteropType);
7082     AdjustedFnType = Context.getFunctionType(PTy->getReturnType(), Params,
7083                                              PTy->getExtProtoInfo());
7084   }
7085 
7086   // Convert VariantRef expression to the type of the original function to
7087   // resolve possible conflicts.
7088   ExprResult VariantRefCast = VariantRef;
7089   if (LangOpts.CPlusPlus) {
7090     QualType FnPtrType;
7091     auto *Method = dyn_cast<CXXMethodDecl>(FD);
7092     if (Method && !Method->isStatic()) {
7093       const Type *ClassType =
7094           Context.getTypeDeclType(Method->getParent()).getTypePtr();
7095       FnPtrType = Context.getMemberPointerType(AdjustedFnType, ClassType);
7096       ExprResult ER;
7097       {
7098         // Build adrr_of unary op to correctly handle type checks for member
7099         // functions.
7100         Sema::TentativeAnalysisScope Trap(*this);
7101         ER = CreateBuiltinUnaryOp(VariantRef->getBeginLoc(), UO_AddrOf,
7102                                   VariantRef);
7103       }
7104       if (!ER.isUsable()) {
7105         Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
7106             << VariantId << VariantRef->getSourceRange();
7107         return None;
7108       }
7109       VariantRef = ER.get();
7110     } else {
7111       FnPtrType = Context.getPointerType(AdjustedFnType);
7112     }
7113     QualType VarianPtrType = Context.getPointerType(VariantRef->getType());
7114     if (VarianPtrType.getUnqualifiedType() != FnPtrType.getUnqualifiedType()) {
7115       ImplicitConversionSequence ICS = TryImplicitConversion(
7116           VariantRef, FnPtrType.getUnqualifiedType(),
7117           /*SuppressUserConversions=*/false, AllowedExplicit::None,
7118           /*InOverloadResolution=*/false,
7119           /*CStyle=*/false,
7120           /*AllowObjCWritebackConversion=*/false);
7121       if (ICS.isFailure()) {
7122         Diag(VariantRef->getExprLoc(),
7123              diag::err_omp_declare_variant_incompat_types)
7124             << VariantRef->getType()
7125             << ((Method && !Method->isStatic()) ? FnPtrType : FD->getType())
7126             << (NumAppendArgs ? 1 : 0) << VariantRef->getSourceRange();
7127         return None;
7128       }
7129       VariantRefCast = PerformImplicitConversion(
7130           VariantRef, FnPtrType.getUnqualifiedType(), AA_Converting);
7131       if (!VariantRefCast.isUsable())
7132         return None;
7133     }
7134     // Drop previously built artificial addr_of unary op for member functions.
7135     if (Method && !Method->isStatic()) {
7136       Expr *PossibleAddrOfVariantRef = VariantRefCast.get();
7137       if (auto *UO = dyn_cast<UnaryOperator>(
7138               PossibleAddrOfVariantRef->IgnoreImplicit()))
7139         VariantRefCast = UO->getSubExpr();
7140     }
7141   }
7142 
7143   ExprResult ER = CheckPlaceholderExpr(VariantRefCast.get());
7144   if (!ER.isUsable() ||
7145       !ER.get()->IgnoreParenImpCasts()->getType()->isFunctionType()) {
7146     Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
7147         << VariantId << VariantRef->getSourceRange();
7148     return None;
7149   }
7150 
7151   // The VariantRef must point to function.
7152   auto *DRE = dyn_cast<DeclRefExpr>(ER.get()->IgnoreParenImpCasts());
7153   if (!DRE) {
7154     Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
7155         << VariantId << VariantRef->getSourceRange();
7156     return None;
7157   }
7158   auto *NewFD = dyn_cast_or_null<FunctionDecl>(DRE->getDecl());
7159   if (!NewFD) {
7160     Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
7161         << VariantId << VariantRef->getSourceRange();
7162     return None;
7163   }
7164 
7165   // Check if function types are compatible in C.
7166   if (!LangOpts.CPlusPlus) {
7167     QualType NewType =
7168         Context.mergeFunctionTypes(AdjustedFnType, NewFD->getType());
7169     if (NewType.isNull()) {
7170       Diag(VariantRef->getExprLoc(),
7171            diag::err_omp_declare_variant_incompat_types)
7172           << NewFD->getType() << FD->getType() << (NumAppendArgs ? 1 : 0)
7173           << VariantRef->getSourceRange();
7174       return None;
7175     }
7176     if (NewType->isFunctionProtoType()) {
7177       if (FD->getType()->isFunctionNoProtoType())
7178         setPrototype(*this, FD, NewFD, NewType);
7179       else if (NewFD->getType()->isFunctionNoProtoType())
7180         setPrototype(*this, NewFD, FD, NewType);
7181     }
7182   }
7183 
7184   // Check if variant function is not marked with declare variant directive.
7185   if (NewFD->hasAttrs() && NewFD->hasAttr<OMPDeclareVariantAttr>()) {
7186     Diag(VariantRef->getExprLoc(),
7187          diag::warn_omp_declare_variant_marked_as_declare_variant)
7188         << VariantRef->getSourceRange();
7189     SourceRange SR =
7190         NewFD->specific_attr_begin<OMPDeclareVariantAttr>()->getRange();
7191     Diag(SR.getBegin(), diag::note_omp_marked_declare_variant_here) << SR;
7192     return None;
7193   }
7194 
7195   enum DoesntSupport {
7196     VirtFuncs = 1,
7197     Constructors = 3,
7198     Destructors = 4,
7199     DeletedFuncs = 5,
7200     DefaultedFuncs = 6,
7201     ConstexprFuncs = 7,
7202     ConstevalFuncs = 8,
7203   };
7204   if (const auto *CXXFD = dyn_cast<CXXMethodDecl>(FD)) {
7205     if (CXXFD->isVirtual()) {
7206       Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
7207           << VirtFuncs;
7208       return None;
7209     }
7210 
7211     if (isa<CXXConstructorDecl>(FD)) {
7212       Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
7213           << Constructors;
7214       return None;
7215     }
7216 
7217     if (isa<CXXDestructorDecl>(FD)) {
7218       Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
7219           << Destructors;
7220       return None;
7221     }
7222   }
7223 
7224   if (FD->isDeleted()) {
7225     Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
7226         << DeletedFuncs;
7227     return None;
7228   }
7229 
7230   if (FD->isDefaulted()) {
7231     Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
7232         << DefaultedFuncs;
7233     return None;
7234   }
7235 
7236   if (FD->isConstexpr()) {
7237     Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
7238         << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
7239     return None;
7240   }
7241 
7242   // Check general compatibility.
7243   if (areMultiversionVariantFunctionsCompatible(
7244           FD, NewFD, PartialDiagnostic::NullDiagnostic(),
7245           PartialDiagnosticAt(SourceLocation(),
7246                               PartialDiagnostic::NullDiagnostic()),
7247           PartialDiagnosticAt(
7248               VariantRef->getExprLoc(),
7249               PDiag(diag::err_omp_declare_variant_doesnt_support)),
7250           PartialDiagnosticAt(VariantRef->getExprLoc(),
7251                               PDiag(diag::err_omp_declare_variant_diff)
7252                                   << FD->getLocation()),
7253           /*TemplatesSupported=*/true, /*ConstexprSupported=*/false,
7254           /*CLinkageMayDiffer=*/true))
7255     return None;
7256   return std::make_pair(FD, cast<Expr>(DRE));
7257 }
7258 
7259 void Sema::ActOnOpenMPDeclareVariantDirective(
7260     FunctionDecl *FD, Expr *VariantRef, OMPTraitInfo &TI,
7261     ArrayRef<Expr *> AdjustArgsNothing,
7262     ArrayRef<Expr *> AdjustArgsNeedDevicePtr,
7263     ArrayRef<OMPDeclareVariantAttr::InteropType> AppendArgs,
7264     SourceLocation AdjustArgsLoc, SourceLocation AppendArgsLoc,
7265     SourceRange SR) {
7266 
7267   // OpenMP 5.1 [2.3.5, declare variant directive, Restrictions]
7268   // An adjust_args clause or append_args clause can only be specified if the
7269   // dispatch selector of the construct selector set appears in the match
7270   // clause.
7271 
7272   SmallVector<Expr *, 8> AllAdjustArgs;
7273   llvm::append_range(AllAdjustArgs, AdjustArgsNothing);
7274   llvm::append_range(AllAdjustArgs, AdjustArgsNeedDevicePtr);
7275 
7276   if (!AllAdjustArgs.empty() || !AppendArgs.empty()) {
7277     VariantMatchInfo VMI;
7278     TI.getAsVariantMatchInfo(Context, VMI);
7279     if (!llvm::is_contained(
7280             VMI.ConstructTraits,
7281             llvm::omp::TraitProperty::construct_dispatch_dispatch)) {
7282       if (!AllAdjustArgs.empty())
7283         Diag(AdjustArgsLoc, diag::err_omp_clause_requires_dispatch_construct)
7284             << getOpenMPClauseName(OMPC_adjust_args);
7285       if (!AppendArgs.empty())
7286         Diag(AppendArgsLoc, diag::err_omp_clause_requires_dispatch_construct)
7287             << getOpenMPClauseName(OMPC_append_args);
7288       return;
7289     }
7290   }
7291 
7292   // OpenMP 5.1 [2.3.5, declare variant directive, Restrictions]
7293   // Each argument can only appear in a single adjust_args clause for each
7294   // declare variant directive.
7295   llvm::SmallPtrSet<const VarDecl *, 4> AdjustVars;
7296 
7297   for (Expr *E : AllAdjustArgs) {
7298     E = E->IgnoreParenImpCasts();
7299     if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) {
7300       if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
7301         const VarDecl *CanonPVD = PVD->getCanonicalDecl();
7302         if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
7303             FD->getParamDecl(PVD->getFunctionScopeIndex())
7304                     ->getCanonicalDecl() == CanonPVD) {
7305           // It's a parameter of the function, check duplicates.
7306           if (!AdjustVars.insert(CanonPVD).second) {
7307             Diag(DRE->getLocation(), diag::err_omp_adjust_arg_multiple_clauses)
7308                 << PVD;
7309             return;
7310           }
7311           continue;
7312         }
7313       }
7314     }
7315     // Anything that is not a function parameter is an error.
7316     Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause) << FD << 0;
7317     return;
7318   }
7319 
7320   auto *NewAttr = OMPDeclareVariantAttr::CreateImplicit(
7321       Context, VariantRef, &TI, const_cast<Expr **>(AdjustArgsNothing.data()),
7322       AdjustArgsNothing.size(),
7323       const_cast<Expr **>(AdjustArgsNeedDevicePtr.data()),
7324       AdjustArgsNeedDevicePtr.size(),
7325       const_cast<OMPDeclareVariantAttr::InteropType *>(AppendArgs.data()),
7326       AppendArgs.size(), SR);
7327   FD->addAttr(NewAttr);
7328 }
7329 
7330 StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
7331                                               Stmt *AStmt,
7332                                               SourceLocation StartLoc,
7333                                               SourceLocation EndLoc) {
7334   if (!AStmt)
7335     return StmtError();
7336 
7337   auto *CS = cast<CapturedStmt>(AStmt);
7338   // 1.2.2 OpenMP Language Terminology
7339   // Structured block - An executable statement with a single entry at the
7340   // top and a single exit at the bottom.
7341   // The point of exit cannot be a branch out of the structured block.
7342   // longjmp() and throw() must not violate the entry/exit criteria.
7343   CS->getCapturedDecl()->setNothrow();
7344 
7345   setFunctionHasBranchProtectedScope();
7346 
7347   return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
7348                                       DSAStack->getTaskgroupReductionRef(),
7349                                       DSAStack->isCancelRegion());
7350 }
7351 
7352 namespace {
7353 /// Iteration space of a single for loop.
7354 struct LoopIterationSpace final {
7355   /// True if the condition operator is the strict compare operator (<, > or
7356   /// !=).
7357   bool IsStrictCompare = false;
7358   /// Condition of the loop.
7359   Expr *PreCond = nullptr;
7360   /// This expression calculates the number of iterations in the loop.
7361   /// It is always possible to calculate it before starting the loop.
7362   Expr *NumIterations = nullptr;
7363   /// The loop counter variable.
7364   Expr *CounterVar = nullptr;
7365   /// Private loop counter variable.
7366   Expr *PrivateCounterVar = nullptr;
7367   /// This is initializer for the initial value of #CounterVar.
7368   Expr *CounterInit = nullptr;
7369   /// This is step for the #CounterVar used to generate its update:
7370   /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
7371   Expr *CounterStep = nullptr;
7372   /// Should step be subtracted?
7373   bool Subtract = false;
7374   /// Source range of the loop init.
7375   SourceRange InitSrcRange;
7376   /// Source range of the loop condition.
7377   SourceRange CondSrcRange;
7378   /// Source range of the loop increment.
7379   SourceRange IncSrcRange;
7380   /// Minimum value that can have the loop control variable. Used to support
7381   /// non-rectangular loops. Applied only for LCV with the non-iterator types,
7382   /// since only such variables can be used in non-loop invariant expressions.
7383   Expr *MinValue = nullptr;
7384   /// Maximum value that can have the loop control variable. Used to support
7385   /// non-rectangular loops. Applied only for LCV with the non-iterator type,
7386   /// since only such variables can be used in non-loop invariant expressions.
7387   Expr *MaxValue = nullptr;
7388   /// true, if the lower bound depends on the outer loop control var.
7389   bool IsNonRectangularLB = false;
7390   /// true, if the upper bound depends on the outer loop control var.
7391   bool IsNonRectangularUB = false;
7392   /// Index of the loop this loop depends on and forms non-rectangular loop
7393   /// nest.
7394   unsigned LoopDependentIdx = 0;
7395   /// Final condition for the non-rectangular loop nest support. It is used to
7396   /// check that the number of iterations for this particular counter must be
7397   /// finished.
7398   Expr *FinalCondition = nullptr;
7399 };
7400 
7401 /// Helper class for checking canonical form of the OpenMP loops and
7402 /// extracting iteration space of each loop in the loop nest, that will be used
7403 /// for IR generation.
7404 class OpenMPIterationSpaceChecker {
7405   /// Reference to Sema.
7406   Sema &SemaRef;
7407   /// Does the loop associated directive support non-rectangular loops?
7408   bool SupportsNonRectangular;
7409   /// Data-sharing stack.
7410   DSAStackTy &Stack;
7411   /// A location for diagnostics (when there is no some better location).
7412   SourceLocation DefaultLoc;
7413   /// A location for diagnostics (when increment is not compatible).
7414   SourceLocation ConditionLoc;
7415   /// A source location for referring to loop init later.
7416   SourceRange InitSrcRange;
7417   /// A source location for referring to condition later.
7418   SourceRange ConditionSrcRange;
7419   /// A source location for referring to increment later.
7420   SourceRange IncrementSrcRange;
7421   /// Loop variable.
7422   ValueDecl *LCDecl = nullptr;
7423   /// Reference to loop variable.
7424   Expr *LCRef = nullptr;
7425   /// Lower bound (initializer for the var).
7426   Expr *LB = nullptr;
7427   /// Upper bound.
7428   Expr *UB = nullptr;
7429   /// Loop step (increment).
7430   Expr *Step = nullptr;
7431   /// This flag is true when condition is one of:
7432   ///   Var <  UB
7433   ///   Var <= UB
7434   ///   UB  >  Var
7435   ///   UB  >= Var
7436   /// This will have no value when the condition is !=
7437   llvm::Optional<bool> TestIsLessOp;
7438   /// This flag is true when condition is strict ( < or > ).
7439   bool TestIsStrictOp = false;
7440   /// This flag is true when step is subtracted on each iteration.
7441   bool SubtractStep = false;
7442   /// The outer loop counter this loop depends on (if any).
7443   const ValueDecl *DepDecl = nullptr;
7444   /// Contains number of loop (starts from 1) on which loop counter init
7445   /// expression of this loop depends on.
7446   Optional<unsigned> InitDependOnLC;
7447   /// Contains number of loop (starts from 1) on which loop counter condition
7448   /// expression of this loop depends on.
7449   Optional<unsigned> CondDependOnLC;
7450   /// Checks if the provide statement depends on the loop counter.
7451   Optional<unsigned> doesDependOnLoopCounter(const Stmt *S, bool IsInitializer);
7452   /// Original condition required for checking of the exit condition for
7453   /// non-rectangular loop.
7454   Expr *Condition = nullptr;
7455 
7456 public:
7457   OpenMPIterationSpaceChecker(Sema &SemaRef, bool SupportsNonRectangular,
7458                               DSAStackTy &Stack, SourceLocation DefaultLoc)
7459       : SemaRef(SemaRef), SupportsNonRectangular(SupportsNonRectangular),
7460         Stack(Stack), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {}
7461   /// Check init-expr for canonical loop form and save loop counter
7462   /// variable - #Var and its initialization value - #LB.
7463   bool checkAndSetInit(Stmt *S, bool EmitDiags = true);
7464   /// Check test-expr for canonical form, save upper-bound (#UB), flags
7465   /// for less/greater and for strict/non-strict comparison.
7466   bool checkAndSetCond(Expr *S);
7467   /// Check incr-expr for canonical loop form and return true if it
7468   /// does not conform, otherwise save loop step (#Step).
7469   bool checkAndSetInc(Expr *S);
7470   /// Return the loop counter variable.
7471   ValueDecl *getLoopDecl() const { return LCDecl; }
7472   /// Return the reference expression to loop counter variable.
7473   Expr *getLoopDeclRefExpr() const { return LCRef; }
7474   /// Source range of the loop init.
7475   SourceRange getInitSrcRange() const { return InitSrcRange; }
7476   /// Source range of the loop condition.
7477   SourceRange getConditionSrcRange() const { return ConditionSrcRange; }
7478   /// Source range of the loop increment.
7479   SourceRange getIncrementSrcRange() const { return IncrementSrcRange; }
7480   /// True if the step should be subtracted.
7481   bool shouldSubtractStep() const { return SubtractStep; }
7482   /// True, if the compare operator is strict (<, > or !=).
7483   bool isStrictTestOp() const { return TestIsStrictOp; }
7484   /// Build the expression to calculate the number of iterations.
7485   Expr *buildNumIterations(
7486       Scope *S, ArrayRef<LoopIterationSpace> ResultIterSpaces, bool LimitedType,
7487       llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
7488   /// Build the precondition expression for the loops.
7489   Expr *
7490   buildPreCond(Scope *S, Expr *Cond,
7491                llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
7492   /// Build reference expression to the counter be used for codegen.
7493   DeclRefExpr *
7494   buildCounterVar(llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
7495                   DSAStackTy &DSA) const;
7496   /// Build reference expression to the private counter be used for
7497   /// codegen.
7498   Expr *buildPrivateCounterVar() const;
7499   /// Build initialization of the counter be used for codegen.
7500   Expr *buildCounterInit() const;
7501   /// Build step of the counter be used for codegen.
7502   Expr *buildCounterStep() const;
7503   /// Build loop data with counter value for depend clauses in ordered
7504   /// directives.
7505   Expr *
7506   buildOrderedLoopData(Scope *S, Expr *Counter,
7507                        llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
7508                        SourceLocation Loc, Expr *Inc = nullptr,
7509                        OverloadedOperatorKind OOK = OO_Amp);
7510   /// Builds the minimum value for the loop counter.
7511   std::pair<Expr *, Expr *> buildMinMaxValues(
7512       Scope *S, llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
7513   /// Builds final condition for the non-rectangular loops.
7514   Expr *buildFinalCondition(Scope *S) const;
7515   /// Return true if any expression is dependent.
7516   bool dependent() const;
7517   /// Returns true if the initializer forms non-rectangular loop.
7518   bool doesInitDependOnLC() const { return InitDependOnLC.hasValue(); }
7519   /// Returns true if the condition forms non-rectangular loop.
7520   bool doesCondDependOnLC() const { return CondDependOnLC.hasValue(); }
7521   /// Returns index of the loop we depend on (starting from 1), or 0 otherwise.
7522   unsigned getLoopDependentIdx() const {
7523     return InitDependOnLC.getValueOr(CondDependOnLC.getValueOr(0));
7524   }
7525 
7526 private:
7527   /// Check the right-hand side of an assignment in the increment
7528   /// expression.
7529   bool checkAndSetIncRHS(Expr *RHS);
7530   /// Helper to set loop counter variable and its initializer.
7531   bool setLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB,
7532                       bool EmitDiags);
7533   /// Helper to set upper bound.
7534   bool setUB(Expr *NewUB, llvm::Optional<bool> LessOp, bool StrictOp,
7535              SourceRange SR, SourceLocation SL);
7536   /// Helper to set loop increment.
7537   bool setStep(Expr *NewStep, bool Subtract);
7538 };
7539 
7540 bool OpenMPIterationSpaceChecker::dependent() const {
7541   if (!LCDecl) {
7542     assert(!LB && !UB && !Step);
7543     return false;
7544   }
7545   return LCDecl->getType()->isDependentType() ||
7546          (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
7547          (Step && Step->isValueDependent());
7548 }
7549 
7550 bool OpenMPIterationSpaceChecker::setLCDeclAndLB(ValueDecl *NewLCDecl,
7551                                                  Expr *NewLCRefExpr,
7552                                                  Expr *NewLB, bool EmitDiags) {
7553   // State consistency checking to ensure correct usage.
7554   assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
7555          UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
7556   if (!NewLCDecl || !NewLB || NewLB->containsErrors())
7557     return true;
7558   LCDecl = getCanonicalDecl(NewLCDecl);
7559   LCRef = NewLCRefExpr;
7560   if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
7561     if (const CXXConstructorDecl *Ctor = CE->getConstructor())
7562       if ((Ctor->isCopyOrMoveConstructor() ||
7563            Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
7564           CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
7565         NewLB = CE->getArg(0)->IgnoreParenImpCasts();
7566   LB = NewLB;
7567   if (EmitDiags)
7568     InitDependOnLC = doesDependOnLoopCounter(LB, /*IsInitializer=*/true);
7569   return false;
7570 }
7571 
7572 bool OpenMPIterationSpaceChecker::setUB(Expr *NewUB,
7573                                         llvm::Optional<bool> LessOp,
7574                                         bool StrictOp, SourceRange SR,
7575                                         SourceLocation SL) {
7576   // State consistency checking to ensure correct usage.
7577   assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
7578          Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
7579   if (!NewUB || NewUB->containsErrors())
7580     return true;
7581   UB = NewUB;
7582   if (LessOp)
7583     TestIsLessOp = LessOp;
7584   TestIsStrictOp = StrictOp;
7585   ConditionSrcRange = SR;
7586   ConditionLoc = SL;
7587   CondDependOnLC = doesDependOnLoopCounter(UB, /*IsInitializer=*/false);
7588   return false;
7589 }
7590 
7591 bool OpenMPIterationSpaceChecker::setStep(Expr *NewStep, bool Subtract) {
7592   // State consistency checking to ensure correct usage.
7593   assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
7594   if (!NewStep || NewStep->containsErrors())
7595     return true;
7596   if (!NewStep->isValueDependent()) {
7597     // Check that the step is integer expression.
7598     SourceLocation StepLoc = NewStep->getBeginLoc();
7599     ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion(
7600         StepLoc, getExprAsWritten(NewStep));
7601     if (Val.isInvalid())
7602       return true;
7603     NewStep = Val.get();
7604 
7605     // OpenMP [2.6, Canonical Loop Form, Restrictions]
7606     //  If test-expr is of form var relational-op b and relational-op is < or
7607     //  <= then incr-expr must cause var to increase on each iteration of the
7608     //  loop. If test-expr is of form var relational-op b and relational-op is
7609     //  > or >= then incr-expr must cause var to decrease on each iteration of
7610     //  the loop.
7611     //  If test-expr is of form b relational-op var and relational-op is < or
7612     //  <= then incr-expr must cause var to decrease on each iteration of the
7613     //  loop. If test-expr is of form b relational-op var and relational-op is
7614     //  > or >= then incr-expr must cause var to increase on each iteration of
7615     //  the loop.
7616     Optional<llvm::APSInt> Result =
7617         NewStep->getIntegerConstantExpr(SemaRef.Context);
7618     bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
7619     bool IsConstNeg =
7620         Result && Result->isSigned() && (Subtract != Result->isNegative());
7621     bool IsConstPos =
7622         Result && Result->isSigned() && (Subtract == Result->isNegative());
7623     bool IsConstZero = Result && !Result->getBoolValue();
7624 
7625     // != with increment is treated as <; != with decrement is treated as >
7626     if (!TestIsLessOp.hasValue())
7627       TestIsLessOp = IsConstPos || (IsUnsigned && !Subtract);
7628     if (UB &&
7629         (IsConstZero || (TestIsLessOp.getValue()
7630                              ? (IsConstNeg || (IsUnsigned && Subtract))
7631                              : (IsConstPos || (IsUnsigned && !Subtract))))) {
7632       SemaRef.Diag(NewStep->getExprLoc(),
7633                    diag::err_omp_loop_incr_not_compatible)
7634           << LCDecl << TestIsLessOp.getValue() << NewStep->getSourceRange();
7635       SemaRef.Diag(ConditionLoc,
7636                    diag::note_omp_loop_cond_requres_compatible_incr)
7637           << TestIsLessOp.getValue() << ConditionSrcRange;
7638       return true;
7639     }
7640     if (TestIsLessOp.getValue() == Subtract) {
7641       NewStep =
7642           SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
7643               .get();
7644       Subtract = !Subtract;
7645     }
7646   }
7647 
7648   Step = NewStep;
7649   SubtractStep = Subtract;
7650   return false;
7651 }
7652 
7653 namespace {
7654 /// Checker for the non-rectangular loops. Checks if the initializer or
7655 /// condition expression references loop counter variable.
7656 class LoopCounterRefChecker final
7657     : public ConstStmtVisitor<LoopCounterRefChecker, bool> {
7658   Sema &SemaRef;
7659   DSAStackTy &Stack;
7660   const ValueDecl *CurLCDecl = nullptr;
7661   const ValueDecl *DepDecl = nullptr;
7662   const ValueDecl *PrevDepDecl = nullptr;
7663   bool IsInitializer = true;
7664   bool SupportsNonRectangular;
7665   unsigned BaseLoopId = 0;
7666   bool checkDecl(const Expr *E, const ValueDecl *VD) {
7667     if (getCanonicalDecl(VD) == getCanonicalDecl(CurLCDecl)) {
7668       SemaRef.Diag(E->getExprLoc(), diag::err_omp_stmt_depends_on_loop_counter)
7669           << (IsInitializer ? 0 : 1);
7670       return false;
7671     }
7672     const auto &&Data = Stack.isLoopControlVariable(VD);
7673     // OpenMP, 2.9.1 Canonical Loop Form, Restrictions.
7674     // The type of the loop iterator on which we depend may not have a random
7675     // access iterator type.
7676     if (Data.first && VD->getType()->isRecordType()) {
7677       SmallString<128> Name;
7678       llvm::raw_svector_ostream OS(Name);
7679       VD->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(),
7680                                /*Qualified=*/true);
7681       SemaRef.Diag(E->getExprLoc(),
7682                    diag::err_omp_wrong_dependency_iterator_type)
7683           << OS.str();
7684       SemaRef.Diag(VD->getLocation(), diag::note_previous_decl) << VD;
7685       return false;
7686     }
7687     if (Data.first && !SupportsNonRectangular) {
7688       SemaRef.Diag(E->getExprLoc(), diag::err_omp_invariant_dependency);
7689       return false;
7690     }
7691     if (Data.first &&
7692         (DepDecl || (PrevDepDecl &&
7693                      getCanonicalDecl(VD) != getCanonicalDecl(PrevDepDecl)))) {
7694       if (!DepDecl && PrevDepDecl)
7695         DepDecl = PrevDepDecl;
7696       SmallString<128> Name;
7697       llvm::raw_svector_ostream OS(Name);
7698       DepDecl->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(),
7699                                     /*Qualified=*/true);
7700       SemaRef.Diag(E->getExprLoc(),
7701                    diag::err_omp_invariant_or_linear_dependency)
7702           << OS.str();
7703       return false;
7704     }
7705     if (Data.first) {
7706       DepDecl = VD;
7707       BaseLoopId = Data.first;
7708     }
7709     return Data.first;
7710   }
7711 
7712 public:
7713   bool VisitDeclRefExpr(const DeclRefExpr *E) {
7714     const ValueDecl *VD = E->getDecl();
7715     if (isa<VarDecl>(VD))
7716       return checkDecl(E, VD);
7717     return false;
7718   }
7719   bool VisitMemberExpr(const MemberExpr *E) {
7720     if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
7721       const ValueDecl *VD = E->getMemberDecl();
7722       if (isa<VarDecl>(VD) || isa<FieldDecl>(VD))
7723         return checkDecl(E, VD);
7724     }
7725     return false;
7726   }
7727   bool VisitStmt(const Stmt *S) {
7728     bool Res = false;
7729     for (const Stmt *Child : S->children())
7730       Res = (Child && Visit(Child)) || Res;
7731     return Res;
7732   }
7733   explicit LoopCounterRefChecker(Sema &SemaRef, DSAStackTy &Stack,
7734                                  const ValueDecl *CurLCDecl, bool IsInitializer,
7735                                  const ValueDecl *PrevDepDecl = nullptr,
7736                                  bool SupportsNonRectangular = true)
7737       : SemaRef(SemaRef), Stack(Stack), CurLCDecl(CurLCDecl),
7738         PrevDepDecl(PrevDepDecl), IsInitializer(IsInitializer),
7739         SupportsNonRectangular(SupportsNonRectangular) {}
7740   unsigned getBaseLoopId() const {
7741     assert(CurLCDecl && "Expected loop dependency.");
7742     return BaseLoopId;
7743   }
7744   const ValueDecl *getDepDecl() const {
7745     assert(CurLCDecl && "Expected loop dependency.");
7746     return DepDecl;
7747   }
7748 };
7749 } // namespace
7750 
7751 Optional<unsigned>
7752 OpenMPIterationSpaceChecker::doesDependOnLoopCounter(const Stmt *S,
7753                                                      bool IsInitializer) {
7754   // Check for the non-rectangular loops.
7755   LoopCounterRefChecker LoopStmtChecker(SemaRef, Stack, LCDecl, IsInitializer,
7756                                         DepDecl, SupportsNonRectangular);
7757   if (LoopStmtChecker.Visit(S)) {
7758     DepDecl = LoopStmtChecker.getDepDecl();
7759     return LoopStmtChecker.getBaseLoopId();
7760   }
7761   return llvm::None;
7762 }
7763 
7764 bool OpenMPIterationSpaceChecker::checkAndSetInit(Stmt *S, bool EmitDiags) {
7765   // Check init-expr for canonical loop form and save loop counter
7766   // variable - #Var and its initialization value - #LB.
7767   // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
7768   //   var = lb
7769   //   integer-type var = lb
7770   //   random-access-iterator-type var = lb
7771   //   pointer-type var = lb
7772   //
7773   if (!S) {
7774     if (EmitDiags) {
7775       SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
7776     }
7777     return true;
7778   }
7779   if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
7780     if (!ExprTemp->cleanupsHaveSideEffects())
7781       S = ExprTemp->getSubExpr();
7782 
7783   InitSrcRange = S->getSourceRange();
7784   if (Expr *E = dyn_cast<Expr>(S))
7785     S = E->IgnoreParens();
7786   if (auto *BO = dyn_cast<BinaryOperator>(S)) {
7787     if (BO->getOpcode() == BO_Assign) {
7788       Expr *LHS = BO->getLHS()->IgnoreParens();
7789       if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
7790         if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
7791           if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
7792             return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
7793                                   EmitDiags);
7794         return setLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS(), EmitDiags);
7795       }
7796       if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
7797         if (ME->isArrow() &&
7798             isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
7799           return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
7800                                 EmitDiags);
7801       }
7802     }
7803   } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
7804     if (DS->isSingleDecl()) {
7805       if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
7806         if (Var->hasInit() && !Var->getType()->isReferenceType()) {
7807           // Accept non-canonical init form here but emit ext. warning.
7808           if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
7809             SemaRef.Diag(S->getBeginLoc(),
7810                          diag::ext_omp_loop_not_canonical_init)
7811                 << S->getSourceRange();
7812           return setLCDeclAndLB(
7813               Var,
7814               buildDeclRefExpr(SemaRef, Var,
7815                                Var->getType().getNonReferenceType(),
7816                                DS->getBeginLoc()),
7817               Var->getInit(), EmitDiags);
7818         }
7819       }
7820     }
7821   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
7822     if (CE->getOperator() == OO_Equal) {
7823       Expr *LHS = CE->getArg(0);
7824       if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
7825         if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
7826           if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
7827             return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
7828                                   EmitDiags);
7829         return setLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1), EmitDiags);
7830       }
7831       if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
7832         if (ME->isArrow() &&
7833             isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
7834           return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
7835                                 EmitDiags);
7836       }
7837     }
7838   }
7839 
7840   if (dependent() || SemaRef.CurContext->isDependentContext())
7841     return false;
7842   if (EmitDiags) {
7843     SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_init)
7844         << S->getSourceRange();
7845   }
7846   return true;
7847 }
7848 
7849 /// Ignore parenthesizes, implicit casts, copy constructor and return the
7850 /// variable (which may be the loop variable) if possible.
7851 static const ValueDecl *getInitLCDecl(const Expr *E) {
7852   if (!E)
7853     return nullptr;
7854   E = getExprAsWritten(E);
7855   if (const auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
7856     if (const CXXConstructorDecl *Ctor = CE->getConstructor())
7857       if ((Ctor->isCopyOrMoveConstructor() ||
7858            Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
7859           CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
7860         E = CE->getArg(0)->IgnoreParenImpCasts();
7861   if (const auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
7862     if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
7863       return getCanonicalDecl(VD);
7864   }
7865   if (const auto *ME = dyn_cast_or_null<MemberExpr>(E))
7866     if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
7867       return getCanonicalDecl(ME->getMemberDecl());
7868   return nullptr;
7869 }
7870 
7871 bool OpenMPIterationSpaceChecker::checkAndSetCond(Expr *S) {
7872   // Check test-expr for canonical form, save upper-bound UB, flags for
7873   // less/greater and for strict/non-strict comparison.
7874   // OpenMP [2.9] Canonical loop form. Test-expr may be one of the following:
7875   //   var relational-op b
7876   //   b relational-op var
7877   //
7878   bool IneqCondIsCanonical = SemaRef.getLangOpts().OpenMP >= 50;
7879   if (!S) {
7880     SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond)
7881         << (IneqCondIsCanonical ? 1 : 0) << LCDecl;
7882     return true;
7883   }
7884   Condition = S;
7885   S = getExprAsWritten(S);
7886   SourceLocation CondLoc = S->getBeginLoc();
7887   auto &&CheckAndSetCond = [this, IneqCondIsCanonical](
7888                                BinaryOperatorKind Opcode, const Expr *LHS,
7889                                const Expr *RHS, SourceRange SR,
7890                                SourceLocation OpLoc) -> llvm::Optional<bool> {
7891     if (BinaryOperator::isRelationalOp(Opcode)) {
7892       if (getInitLCDecl(LHS) == LCDecl)
7893         return setUB(const_cast<Expr *>(RHS),
7894                      (Opcode == BO_LT || Opcode == BO_LE),
7895                      (Opcode == BO_LT || Opcode == BO_GT), SR, OpLoc);
7896       if (getInitLCDecl(RHS) == LCDecl)
7897         return setUB(const_cast<Expr *>(LHS),
7898                      (Opcode == BO_GT || Opcode == BO_GE),
7899                      (Opcode == BO_LT || Opcode == BO_GT), SR, OpLoc);
7900     } else if (IneqCondIsCanonical && Opcode == BO_NE) {
7901       return setUB(const_cast<Expr *>(getInitLCDecl(LHS) == LCDecl ? RHS : LHS),
7902                    /*LessOp=*/llvm::None,
7903                    /*StrictOp=*/true, SR, OpLoc);
7904     }
7905     return llvm::None;
7906   };
7907   llvm::Optional<bool> Res;
7908   if (auto *RBO = dyn_cast<CXXRewrittenBinaryOperator>(S)) {
7909     CXXRewrittenBinaryOperator::DecomposedForm DF = RBO->getDecomposedForm();
7910     Res = CheckAndSetCond(DF.Opcode, DF.LHS, DF.RHS, RBO->getSourceRange(),
7911                           RBO->getOperatorLoc());
7912   } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
7913     Res = CheckAndSetCond(BO->getOpcode(), BO->getLHS(), BO->getRHS(),
7914                           BO->getSourceRange(), BO->getOperatorLoc());
7915   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
7916     if (CE->getNumArgs() == 2) {
7917       Res = CheckAndSetCond(
7918           BinaryOperator::getOverloadedOpcode(CE->getOperator()), CE->getArg(0),
7919           CE->getArg(1), CE->getSourceRange(), CE->getOperatorLoc());
7920     }
7921   }
7922   if (Res.hasValue())
7923     return *Res;
7924   if (dependent() || SemaRef.CurContext->isDependentContext())
7925     return false;
7926   SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
7927       << (IneqCondIsCanonical ? 1 : 0) << S->getSourceRange() << LCDecl;
7928   return true;
7929 }
7930 
7931 bool OpenMPIterationSpaceChecker::checkAndSetIncRHS(Expr *RHS) {
7932   // RHS of canonical loop form increment can be:
7933   //   var + incr
7934   //   incr + var
7935   //   var - incr
7936   //
7937   RHS = RHS->IgnoreParenImpCasts();
7938   if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
7939     if (BO->isAdditiveOp()) {
7940       bool IsAdd = BO->getOpcode() == BO_Add;
7941       if (getInitLCDecl(BO->getLHS()) == LCDecl)
7942         return setStep(BO->getRHS(), !IsAdd);
7943       if (IsAdd && getInitLCDecl(BO->getRHS()) == LCDecl)
7944         return setStep(BO->getLHS(), /*Subtract=*/false);
7945     }
7946   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
7947     bool IsAdd = CE->getOperator() == OO_Plus;
7948     if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
7949       if (getInitLCDecl(CE->getArg(0)) == LCDecl)
7950         return setStep(CE->getArg(1), !IsAdd);
7951       if (IsAdd && getInitLCDecl(CE->getArg(1)) == LCDecl)
7952         return setStep(CE->getArg(0), /*Subtract=*/false);
7953     }
7954   }
7955   if (dependent() || SemaRef.CurContext->isDependentContext())
7956     return false;
7957   SemaRef.Diag(RHS->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
7958       << RHS->getSourceRange() << LCDecl;
7959   return true;
7960 }
7961 
7962 bool OpenMPIterationSpaceChecker::checkAndSetInc(Expr *S) {
7963   // Check incr-expr for canonical loop form and return true if it
7964   // does not conform.
7965   // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
7966   //   ++var
7967   //   var++
7968   //   --var
7969   //   var--
7970   //   var += incr
7971   //   var -= incr
7972   //   var = var + incr
7973   //   var = incr + var
7974   //   var = var - incr
7975   //
7976   if (!S) {
7977     SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
7978     return true;
7979   }
7980   if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
7981     if (!ExprTemp->cleanupsHaveSideEffects())
7982       S = ExprTemp->getSubExpr();
7983 
7984   IncrementSrcRange = S->getSourceRange();
7985   S = S->IgnoreParens();
7986   if (auto *UO = dyn_cast<UnaryOperator>(S)) {
7987     if (UO->isIncrementDecrementOp() &&
7988         getInitLCDecl(UO->getSubExpr()) == LCDecl)
7989       return setStep(SemaRef
7990                          .ActOnIntegerConstant(UO->getBeginLoc(),
7991                                                (UO->isDecrementOp() ? -1 : 1))
7992                          .get(),
7993                      /*Subtract=*/false);
7994   } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
7995     switch (BO->getOpcode()) {
7996     case BO_AddAssign:
7997     case BO_SubAssign:
7998       if (getInitLCDecl(BO->getLHS()) == LCDecl)
7999         return setStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
8000       break;
8001     case BO_Assign:
8002       if (getInitLCDecl(BO->getLHS()) == LCDecl)
8003         return checkAndSetIncRHS(BO->getRHS());
8004       break;
8005     default:
8006       break;
8007     }
8008   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
8009     switch (CE->getOperator()) {
8010     case OO_PlusPlus:
8011     case OO_MinusMinus:
8012       if (getInitLCDecl(CE->getArg(0)) == LCDecl)
8013         return setStep(SemaRef
8014                            .ActOnIntegerConstant(
8015                                CE->getBeginLoc(),
8016                                ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
8017                            .get(),
8018                        /*Subtract=*/false);
8019       break;
8020     case OO_PlusEqual:
8021     case OO_MinusEqual:
8022       if (getInitLCDecl(CE->getArg(0)) == LCDecl)
8023         return setStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
8024       break;
8025     case OO_Equal:
8026       if (getInitLCDecl(CE->getArg(0)) == LCDecl)
8027         return checkAndSetIncRHS(CE->getArg(1));
8028       break;
8029     default:
8030       break;
8031     }
8032   }
8033   if (dependent() || SemaRef.CurContext->isDependentContext())
8034     return false;
8035   SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
8036       << S->getSourceRange() << LCDecl;
8037   return true;
8038 }
8039 
8040 static ExprResult
8041 tryBuildCapture(Sema &SemaRef, Expr *Capture,
8042                 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
8043   if (SemaRef.CurContext->isDependentContext() || Capture->containsErrors())
8044     return Capture;
8045   if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
8046     return SemaRef.PerformImplicitConversion(
8047         Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
8048         /*AllowExplicit=*/true);
8049   auto I = Captures.find(Capture);
8050   if (I != Captures.end())
8051     return buildCapture(SemaRef, Capture, I->second);
8052   DeclRefExpr *Ref = nullptr;
8053   ExprResult Res = buildCapture(SemaRef, Capture, Ref);
8054   Captures[Capture] = Ref;
8055   return Res;
8056 }
8057 
8058 /// Calculate number of iterations, transforming to unsigned, if number of
8059 /// iterations may be larger than the original type.
8060 static Expr *
8061 calculateNumIters(Sema &SemaRef, Scope *S, SourceLocation DefaultLoc,
8062                   Expr *Lower, Expr *Upper, Expr *Step, QualType LCTy,
8063                   bool TestIsStrictOp, bool RoundToStep,
8064                   llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
8065   ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
8066   if (!NewStep.isUsable())
8067     return nullptr;
8068   llvm::APSInt LRes, SRes;
8069   bool IsLowerConst = false, IsStepConst = false;
8070   if (Optional<llvm::APSInt> Res =
8071           Lower->getIntegerConstantExpr(SemaRef.Context)) {
8072     LRes = *Res;
8073     IsLowerConst = true;
8074   }
8075   if (Optional<llvm::APSInt> Res =
8076           Step->getIntegerConstantExpr(SemaRef.Context)) {
8077     SRes = *Res;
8078     IsStepConst = true;
8079   }
8080   bool NoNeedToConvert = IsLowerConst && !RoundToStep &&
8081                          ((!TestIsStrictOp && LRes.isNonNegative()) ||
8082                           (TestIsStrictOp && LRes.isStrictlyPositive()));
8083   bool NeedToReorganize = false;
8084   // Check if any subexpressions in Lower -Step [+ 1] lead to overflow.
8085   if (!NoNeedToConvert && IsLowerConst &&
8086       (TestIsStrictOp || (RoundToStep && IsStepConst))) {
8087     NoNeedToConvert = true;
8088     if (RoundToStep) {
8089       unsigned BW = LRes.getBitWidth() > SRes.getBitWidth()
8090                         ? LRes.getBitWidth()
8091                         : SRes.getBitWidth();
8092       LRes = LRes.extend(BW + 1);
8093       LRes.setIsSigned(true);
8094       SRes = SRes.extend(BW + 1);
8095       SRes.setIsSigned(true);
8096       LRes -= SRes;
8097       NoNeedToConvert = LRes.trunc(BW).extend(BW + 1) == LRes;
8098       LRes = LRes.trunc(BW);
8099     }
8100     if (TestIsStrictOp) {
8101       unsigned BW = LRes.getBitWidth();
8102       LRes = LRes.extend(BW + 1);
8103       LRes.setIsSigned(true);
8104       ++LRes;
8105       NoNeedToConvert =
8106           NoNeedToConvert && LRes.trunc(BW).extend(BW + 1) == LRes;
8107       // truncate to the original bitwidth.
8108       LRes = LRes.trunc(BW);
8109     }
8110     NeedToReorganize = NoNeedToConvert;
8111   }
8112   llvm::APSInt URes;
8113   bool IsUpperConst = false;
8114   if (Optional<llvm::APSInt> Res =
8115           Upper->getIntegerConstantExpr(SemaRef.Context)) {
8116     URes = *Res;
8117     IsUpperConst = true;
8118   }
8119   if (NoNeedToConvert && IsLowerConst && IsUpperConst &&
8120       (!RoundToStep || IsStepConst)) {
8121     unsigned BW = LRes.getBitWidth() > URes.getBitWidth() ? LRes.getBitWidth()
8122                                                           : URes.getBitWidth();
8123     LRes = LRes.extend(BW + 1);
8124     LRes.setIsSigned(true);
8125     URes = URes.extend(BW + 1);
8126     URes.setIsSigned(true);
8127     URes -= LRes;
8128     NoNeedToConvert = URes.trunc(BW).extend(BW + 1) == URes;
8129     NeedToReorganize = NoNeedToConvert;
8130   }
8131   // If the boundaries are not constant or (Lower - Step [+ 1]) is not constant
8132   // or less than zero (Upper - (Lower - Step [+ 1]) may overflow) - promote to
8133   // unsigned.
8134   if ((!NoNeedToConvert || (LRes.isNegative() && !IsUpperConst)) &&
8135       !LCTy->isDependentType() && LCTy->isIntegerType()) {
8136     QualType LowerTy = Lower->getType();
8137     QualType UpperTy = Upper->getType();
8138     uint64_t LowerSize = SemaRef.Context.getTypeSize(LowerTy);
8139     uint64_t UpperSize = SemaRef.Context.getTypeSize(UpperTy);
8140     if ((LowerSize <= UpperSize && UpperTy->hasSignedIntegerRepresentation()) ||
8141         (LowerSize > UpperSize && LowerTy->hasSignedIntegerRepresentation())) {
8142       QualType CastType = SemaRef.Context.getIntTypeForBitwidth(
8143           LowerSize > UpperSize ? LowerSize : UpperSize, /*Signed=*/0);
8144       Upper =
8145           SemaRef
8146               .PerformImplicitConversion(
8147                   SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Upper).get(),
8148                   CastType, Sema::AA_Converting)
8149               .get();
8150       Lower = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Lower).get();
8151       NewStep = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, NewStep.get());
8152     }
8153   }
8154   if (!Lower || !Upper || NewStep.isInvalid())
8155     return nullptr;
8156 
8157   ExprResult Diff;
8158   // If need to reorganize, then calculate the form as Upper - (Lower - Step [+
8159   // 1]).
8160   if (NeedToReorganize) {
8161     Diff = Lower;
8162 
8163     if (RoundToStep) {
8164       // Lower - Step
8165       Diff =
8166           SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Diff.get(), NewStep.get());
8167       if (!Diff.isUsable())
8168         return nullptr;
8169     }
8170 
8171     // Lower - Step [+ 1]
8172     if (TestIsStrictOp)
8173       Diff = SemaRef.BuildBinOp(
8174           S, DefaultLoc, BO_Add, Diff.get(),
8175           SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
8176     if (!Diff.isUsable())
8177       return nullptr;
8178 
8179     Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
8180     if (!Diff.isUsable())
8181       return nullptr;
8182 
8183     // Upper - (Lower - Step [+ 1]).
8184     Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Diff.get());
8185     if (!Diff.isUsable())
8186       return nullptr;
8187   } else {
8188     Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
8189 
8190     if (!Diff.isUsable() && LCTy->getAsCXXRecordDecl()) {
8191       // BuildBinOp already emitted error, this one is to point user to upper
8192       // and lower bound, and to tell what is passed to 'operator-'.
8193       SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
8194           << Upper->getSourceRange() << Lower->getSourceRange();
8195       return nullptr;
8196     }
8197 
8198     if (!Diff.isUsable())
8199       return nullptr;
8200 
8201     // Upper - Lower [- 1]
8202     if (TestIsStrictOp)
8203       Diff = SemaRef.BuildBinOp(
8204           S, DefaultLoc, BO_Sub, Diff.get(),
8205           SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
8206     if (!Diff.isUsable())
8207       return nullptr;
8208 
8209     if (RoundToStep) {
8210       // Upper - Lower [- 1] + Step
8211       Diff =
8212           SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
8213       if (!Diff.isUsable())
8214         return nullptr;
8215     }
8216   }
8217 
8218   // Parentheses (for dumping/debugging purposes only).
8219   Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
8220   if (!Diff.isUsable())
8221     return nullptr;
8222 
8223   // (Upper - Lower [- 1] + Step) / Step or (Upper - Lower) / Step
8224   Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
8225   if (!Diff.isUsable())
8226     return nullptr;
8227 
8228   return Diff.get();
8229 }
8230 
8231 /// Build the expression to calculate the number of iterations.
8232 Expr *OpenMPIterationSpaceChecker::buildNumIterations(
8233     Scope *S, ArrayRef<LoopIterationSpace> ResultIterSpaces, bool LimitedType,
8234     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
8235   QualType VarType = LCDecl->getType().getNonReferenceType();
8236   if (!VarType->isIntegerType() && !VarType->isPointerType() &&
8237       !SemaRef.getLangOpts().CPlusPlus)
8238     return nullptr;
8239   Expr *LBVal = LB;
8240   Expr *UBVal = UB;
8241   // LB = TestIsLessOp.getValue() ? min(LB(MinVal), LB(MaxVal)) :
8242   // max(LB(MinVal), LB(MaxVal))
8243   if (InitDependOnLC) {
8244     const LoopIterationSpace &IS = ResultIterSpaces[*InitDependOnLC - 1];
8245     if (!IS.MinValue || !IS.MaxValue)
8246       return nullptr;
8247     // OuterVar = Min
8248     ExprResult MinValue =
8249         SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MinValue);
8250     if (!MinValue.isUsable())
8251       return nullptr;
8252 
8253     ExprResult LBMinVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
8254                                              IS.CounterVar, MinValue.get());
8255     if (!LBMinVal.isUsable())
8256       return nullptr;
8257     // OuterVar = Min, LBVal
8258     LBMinVal =
8259         SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, LBMinVal.get(), LBVal);
8260     if (!LBMinVal.isUsable())
8261       return nullptr;
8262     // (OuterVar = Min, LBVal)
8263     LBMinVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, LBMinVal.get());
8264     if (!LBMinVal.isUsable())
8265       return nullptr;
8266 
8267     // OuterVar = Max
8268     ExprResult MaxValue =
8269         SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MaxValue);
8270     if (!MaxValue.isUsable())
8271       return nullptr;
8272 
8273     ExprResult LBMaxVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
8274                                              IS.CounterVar, MaxValue.get());
8275     if (!LBMaxVal.isUsable())
8276       return nullptr;
8277     // OuterVar = Max, LBVal
8278     LBMaxVal =
8279         SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, LBMaxVal.get(), LBVal);
8280     if (!LBMaxVal.isUsable())
8281       return nullptr;
8282     // (OuterVar = Max, LBVal)
8283     LBMaxVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, LBMaxVal.get());
8284     if (!LBMaxVal.isUsable())
8285       return nullptr;
8286 
8287     Expr *LBMin = tryBuildCapture(SemaRef, LBMinVal.get(), Captures).get();
8288     Expr *LBMax = tryBuildCapture(SemaRef, LBMaxVal.get(), Captures).get();
8289     if (!LBMin || !LBMax)
8290       return nullptr;
8291     // LB(MinVal) < LB(MaxVal)
8292     ExprResult MinLessMaxRes =
8293         SemaRef.BuildBinOp(S, DefaultLoc, BO_LT, LBMin, LBMax);
8294     if (!MinLessMaxRes.isUsable())
8295       return nullptr;
8296     Expr *MinLessMax =
8297         tryBuildCapture(SemaRef, MinLessMaxRes.get(), Captures).get();
8298     if (!MinLessMax)
8299       return nullptr;
8300     if (TestIsLessOp.getValue()) {
8301       // LB(MinVal) < LB(MaxVal) ? LB(MinVal) : LB(MaxVal) - min(LB(MinVal),
8302       // LB(MaxVal))
8303       ExprResult MinLB = SemaRef.ActOnConditionalOp(DefaultLoc, DefaultLoc,
8304                                                     MinLessMax, LBMin, LBMax);
8305       if (!MinLB.isUsable())
8306         return nullptr;
8307       LBVal = MinLB.get();
8308     } else {
8309       // LB(MinVal) < LB(MaxVal) ? LB(MaxVal) : LB(MinVal) - max(LB(MinVal),
8310       // LB(MaxVal))
8311       ExprResult MaxLB = SemaRef.ActOnConditionalOp(DefaultLoc, DefaultLoc,
8312                                                     MinLessMax, LBMax, LBMin);
8313       if (!MaxLB.isUsable())
8314         return nullptr;
8315       LBVal = MaxLB.get();
8316     }
8317   }
8318   // UB = TestIsLessOp.getValue() ? max(UB(MinVal), UB(MaxVal)) :
8319   // min(UB(MinVal), UB(MaxVal))
8320   if (CondDependOnLC) {
8321     const LoopIterationSpace &IS = ResultIterSpaces[*CondDependOnLC - 1];
8322     if (!IS.MinValue || !IS.MaxValue)
8323       return nullptr;
8324     // OuterVar = Min
8325     ExprResult MinValue =
8326         SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MinValue);
8327     if (!MinValue.isUsable())
8328       return nullptr;
8329 
8330     ExprResult UBMinVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
8331                                              IS.CounterVar, MinValue.get());
8332     if (!UBMinVal.isUsable())
8333       return nullptr;
8334     // OuterVar = Min, UBVal
8335     UBMinVal =
8336         SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, UBMinVal.get(), UBVal);
8337     if (!UBMinVal.isUsable())
8338       return nullptr;
8339     // (OuterVar = Min, UBVal)
8340     UBMinVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, UBMinVal.get());
8341     if (!UBMinVal.isUsable())
8342       return nullptr;
8343 
8344     // OuterVar = Max
8345     ExprResult MaxValue =
8346         SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MaxValue);
8347     if (!MaxValue.isUsable())
8348       return nullptr;
8349 
8350     ExprResult UBMaxVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
8351                                              IS.CounterVar, MaxValue.get());
8352     if (!UBMaxVal.isUsable())
8353       return nullptr;
8354     // OuterVar = Max, UBVal
8355     UBMaxVal =
8356         SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, UBMaxVal.get(), UBVal);
8357     if (!UBMaxVal.isUsable())
8358       return nullptr;
8359     // (OuterVar = Max, UBVal)
8360     UBMaxVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, UBMaxVal.get());
8361     if (!UBMaxVal.isUsable())
8362       return nullptr;
8363 
8364     Expr *UBMin = tryBuildCapture(SemaRef, UBMinVal.get(), Captures).get();
8365     Expr *UBMax = tryBuildCapture(SemaRef, UBMaxVal.get(), Captures).get();
8366     if (!UBMin || !UBMax)
8367       return nullptr;
8368     // UB(MinVal) > UB(MaxVal)
8369     ExprResult MinGreaterMaxRes =
8370         SemaRef.BuildBinOp(S, DefaultLoc, BO_GT, UBMin, UBMax);
8371     if (!MinGreaterMaxRes.isUsable())
8372       return nullptr;
8373     Expr *MinGreaterMax =
8374         tryBuildCapture(SemaRef, MinGreaterMaxRes.get(), Captures).get();
8375     if (!MinGreaterMax)
8376       return nullptr;
8377     if (TestIsLessOp.getValue()) {
8378       // UB(MinVal) > UB(MaxVal) ? UB(MinVal) : UB(MaxVal) - max(UB(MinVal),
8379       // UB(MaxVal))
8380       ExprResult MaxUB = SemaRef.ActOnConditionalOp(
8381           DefaultLoc, DefaultLoc, MinGreaterMax, UBMin, UBMax);
8382       if (!MaxUB.isUsable())
8383         return nullptr;
8384       UBVal = MaxUB.get();
8385     } else {
8386       // UB(MinVal) > UB(MaxVal) ? UB(MaxVal) : UB(MinVal) - min(UB(MinVal),
8387       // UB(MaxVal))
8388       ExprResult MinUB = SemaRef.ActOnConditionalOp(
8389           DefaultLoc, DefaultLoc, MinGreaterMax, UBMax, UBMin);
8390       if (!MinUB.isUsable())
8391         return nullptr;
8392       UBVal = MinUB.get();
8393     }
8394   }
8395   Expr *UBExpr = TestIsLessOp.getValue() ? UBVal : LBVal;
8396   Expr *LBExpr = TestIsLessOp.getValue() ? LBVal : UBVal;
8397   Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
8398   Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
8399   if (!Upper || !Lower)
8400     return nullptr;
8401 
8402   ExprResult Diff = calculateNumIters(SemaRef, S, DefaultLoc, Lower, Upper,
8403                                       Step, VarType, TestIsStrictOp,
8404                                       /*RoundToStep=*/true, Captures);
8405   if (!Diff.isUsable())
8406     return nullptr;
8407 
8408   // OpenMP runtime requires 32-bit or 64-bit loop variables.
8409   QualType Type = Diff.get()->getType();
8410   ASTContext &C = SemaRef.Context;
8411   bool UseVarType = VarType->hasIntegerRepresentation() &&
8412                     C.getTypeSize(Type) > C.getTypeSize(VarType);
8413   if (!Type->isIntegerType() || UseVarType) {
8414     unsigned NewSize =
8415         UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
8416     bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
8417                                : Type->hasSignedIntegerRepresentation();
8418     Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
8419     if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
8420       Diff = SemaRef.PerformImplicitConversion(
8421           Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
8422       if (!Diff.isUsable())
8423         return nullptr;
8424     }
8425   }
8426   if (LimitedType) {
8427     unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
8428     if (NewSize != C.getTypeSize(Type)) {
8429       if (NewSize < C.getTypeSize(Type)) {
8430         assert(NewSize == 64 && "incorrect loop var size");
8431         SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
8432             << InitSrcRange << ConditionSrcRange;
8433       }
8434       QualType NewType = C.getIntTypeForBitwidth(
8435           NewSize, Type->hasSignedIntegerRepresentation() ||
8436                        C.getTypeSize(Type) < NewSize);
8437       if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
8438         Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
8439                                                  Sema::AA_Converting, true);
8440         if (!Diff.isUsable())
8441           return nullptr;
8442       }
8443     }
8444   }
8445 
8446   return Diff.get();
8447 }
8448 
8449 std::pair<Expr *, Expr *> OpenMPIterationSpaceChecker::buildMinMaxValues(
8450     Scope *S, llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
8451   // Do not build for iterators, they cannot be used in non-rectangular loop
8452   // nests.
8453   if (LCDecl->getType()->isRecordType())
8454     return std::make_pair(nullptr, nullptr);
8455   // If we subtract, the min is in the condition, otherwise the min is in the
8456   // init value.
8457   Expr *MinExpr = nullptr;
8458   Expr *MaxExpr = nullptr;
8459   Expr *LBExpr = TestIsLessOp.getValue() ? LB : UB;
8460   Expr *UBExpr = TestIsLessOp.getValue() ? UB : LB;
8461   bool LBNonRect = TestIsLessOp.getValue() ? InitDependOnLC.hasValue()
8462                                            : CondDependOnLC.hasValue();
8463   bool UBNonRect = TestIsLessOp.getValue() ? CondDependOnLC.hasValue()
8464                                            : InitDependOnLC.hasValue();
8465   Expr *Lower =
8466       LBNonRect ? LBExpr : tryBuildCapture(SemaRef, LBExpr, Captures).get();
8467   Expr *Upper =
8468       UBNonRect ? UBExpr : tryBuildCapture(SemaRef, UBExpr, Captures).get();
8469   if (!Upper || !Lower)
8470     return std::make_pair(nullptr, nullptr);
8471 
8472   if (TestIsLessOp.getValue())
8473     MinExpr = Lower;
8474   else
8475     MaxExpr = Upper;
8476 
8477   // Build minimum/maximum value based on number of iterations.
8478   QualType VarType = LCDecl->getType().getNonReferenceType();
8479 
8480   ExprResult Diff = calculateNumIters(SemaRef, S, DefaultLoc, Lower, Upper,
8481                                       Step, VarType, TestIsStrictOp,
8482                                       /*RoundToStep=*/false, Captures);
8483   if (!Diff.isUsable())
8484     return std::make_pair(nullptr, nullptr);
8485 
8486   // ((Upper - Lower [- 1]) / Step) * Step
8487   // Parentheses (for dumping/debugging purposes only).
8488   Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
8489   if (!Diff.isUsable())
8490     return std::make_pair(nullptr, nullptr);
8491 
8492   ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
8493   if (!NewStep.isUsable())
8494     return std::make_pair(nullptr, nullptr);
8495   Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Mul, Diff.get(), NewStep.get());
8496   if (!Diff.isUsable())
8497     return std::make_pair(nullptr, nullptr);
8498 
8499   // Parentheses (for dumping/debugging purposes only).
8500   Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
8501   if (!Diff.isUsable())
8502     return std::make_pair(nullptr, nullptr);
8503 
8504   // Convert to the ptrdiff_t, if original type is pointer.
8505   if (VarType->isAnyPointerType() &&
8506       !SemaRef.Context.hasSameType(
8507           Diff.get()->getType(),
8508           SemaRef.Context.getUnsignedPointerDiffType())) {
8509     Diff = SemaRef.PerformImplicitConversion(
8510         Diff.get(), SemaRef.Context.getUnsignedPointerDiffType(),
8511         Sema::AA_Converting, /*AllowExplicit=*/true);
8512   }
8513   if (!Diff.isUsable())
8514     return std::make_pair(nullptr, nullptr);
8515 
8516   if (TestIsLessOp.getValue()) {
8517     // MinExpr = Lower;
8518     // MaxExpr = Lower + (((Upper - Lower [- 1]) / Step) * Step)
8519     Diff = SemaRef.BuildBinOp(
8520         S, DefaultLoc, BO_Add,
8521         SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Lower).get(),
8522         Diff.get());
8523     if (!Diff.isUsable())
8524       return std::make_pair(nullptr, nullptr);
8525   } else {
8526     // MaxExpr = Upper;
8527     // MinExpr = Upper - (((Upper - Lower [- 1]) / Step) * Step)
8528     Diff = SemaRef.BuildBinOp(
8529         S, DefaultLoc, BO_Sub,
8530         SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Upper).get(),
8531         Diff.get());
8532     if (!Diff.isUsable())
8533       return std::make_pair(nullptr, nullptr);
8534   }
8535 
8536   // Convert to the original type.
8537   if (SemaRef.Context.hasSameType(Diff.get()->getType(), VarType))
8538     Diff = SemaRef.PerformImplicitConversion(Diff.get(), VarType,
8539                                              Sema::AA_Converting,
8540                                              /*AllowExplicit=*/true);
8541   if (!Diff.isUsable())
8542     return std::make_pair(nullptr, nullptr);
8543 
8544   Sema::TentativeAnalysisScope Trap(SemaRef);
8545   Diff = SemaRef.ActOnFinishFullExpr(Diff.get(), /*DiscardedValue=*/false);
8546   if (!Diff.isUsable())
8547     return std::make_pair(nullptr, nullptr);
8548 
8549   if (TestIsLessOp.getValue())
8550     MaxExpr = Diff.get();
8551   else
8552     MinExpr = Diff.get();
8553 
8554   return std::make_pair(MinExpr, MaxExpr);
8555 }
8556 
8557 Expr *OpenMPIterationSpaceChecker::buildFinalCondition(Scope *S) const {
8558   if (InitDependOnLC || CondDependOnLC)
8559     return Condition;
8560   return nullptr;
8561 }
8562 
8563 Expr *OpenMPIterationSpaceChecker::buildPreCond(
8564     Scope *S, Expr *Cond,
8565     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
8566   // Do not build a precondition when the condition/initialization is dependent
8567   // to prevent pessimistic early loop exit.
8568   // TODO: this can be improved by calculating min/max values but not sure that
8569   // it will be very effective.
8570   if (CondDependOnLC || InitDependOnLC)
8571     return SemaRef
8572         .PerformImplicitConversion(
8573             SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get(),
8574             SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
8575             /*AllowExplicit=*/true)
8576         .get();
8577 
8578   // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
8579   Sema::TentativeAnalysisScope Trap(SemaRef);
8580 
8581   ExprResult NewLB = tryBuildCapture(SemaRef, LB, Captures);
8582   ExprResult NewUB = tryBuildCapture(SemaRef, UB, Captures);
8583   if (!NewLB.isUsable() || !NewUB.isUsable())
8584     return nullptr;
8585 
8586   ExprResult CondExpr = SemaRef.BuildBinOp(
8587       S, DefaultLoc,
8588       TestIsLessOp.getValue() ? (TestIsStrictOp ? BO_LT : BO_LE)
8589                               : (TestIsStrictOp ? BO_GT : BO_GE),
8590       NewLB.get(), NewUB.get());
8591   if (CondExpr.isUsable()) {
8592     if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
8593                                                 SemaRef.Context.BoolTy))
8594       CondExpr = SemaRef.PerformImplicitConversion(
8595           CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
8596           /*AllowExplicit=*/true);
8597   }
8598 
8599   // Otherwise use original loop condition and evaluate it in runtime.
8600   return CondExpr.isUsable() ? CondExpr.get() : Cond;
8601 }
8602 
8603 /// Build reference expression to the counter be used for codegen.
8604 DeclRefExpr *OpenMPIterationSpaceChecker::buildCounterVar(
8605     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
8606     DSAStackTy &DSA) const {
8607   auto *VD = dyn_cast<VarDecl>(LCDecl);
8608   if (!VD) {
8609     VD = SemaRef.isOpenMPCapturedDecl(LCDecl);
8610     DeclRefExpr *Ref = buildDeclRefExpr(
8611         SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
8612     const DSAStackTy::DSAVarData Data =
8613         DSA.getTopDSA(LCDecl, /*FromParent=*/false);
8614     // If the loop control decl is explicitly marked as private, do not mark it
8615     // as captured again.
8616     if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
8617       Captures.insert(std::make_pair(LCRef, Ref));
8618     return Ref;
8619   }
8620   return cast<DeclRefExpr>(LCRef);
8621 }
8622 
8623 Expr *OpenMPIterationSpaceChecker::buildPrivateCounterVar() const {
8624   if (LCDecl && !LCDecl->isInvalidDecl()) {
8625     QualType Type = LCDecl->getType().getNonReferenceType();
8626     VarDecl *PrivateVar = buildVarDecl(
8627         SemaRef, DefaultLoc, Type, LCDecl->getName(),
8628         LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr,
8629         isa<VarDecl>(LCDecl)
8630             ? buildDeclRefExpr(SemaRef, cast<VarDecl>(LCDecl), Type, DefaultLoc)
8631             : nullptr);
8632     if (PrivateVar->isInvalidDecl())
8633       return nullptr;
8634     return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
8635   }
8636   return nullptr;
8637 }
8638 
8639 /// Build initialization of the counter to be used for codegen.
8640 Expr *OpenMPIterationSpaceChecker::buildCounterInit() const { return LB; }
8641 
8642 /// Build step of the counter be used for codegen.
8643 Expr *OpenMPIterationSpaceChecker::buildCounterStep() const { return Step; }
8644 
8645 Expr *OpenMPIterationSpaceChecker::buildOrderedLoopData(
8646     Scope *S, Expr *Counter,
8647     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, SourceLocation Loc,
8648     Expr *Inc, OverloadedOperatorKind OOK) {
8649   Expr *Cnt = SemaRef.DefaultLvalueConversion(Counter).get();
8650   if (!Cnt)
8651     return nullptr;
8652   if (Inc) {
8653     assert((OOK == OO_Plus || OOK == OO_Minus) &&
8654            "Expected only + or - operations for depend clauses.");
8655     BinaryOperatorKind BOK = (OOK == OO_Plus) ? BO_Add : BO_Sub;
8656     Cnt = SemaRef.BuildBinOp(S, Loc, BOK, Cnt, Inc).get();
8657     if (!Cnt)
8658       return nullptr;
8659   }
8660   QualType VarType = LCDecl->getType().getNonReferenceType();
8661   if (!VarType->isIntegerType() && !VarType->isPointerType() &&
8662       !SemaRef.getLangOpts().CPlusPlus)
8663     return nullptr;
8664   // Upper - Lower
8665   Expr *Upper = TestIsLessOp.getValue()
8666                     ? Cnt
8667                     : tryBuildCapture(SemaRef, LB, Captures).get();
8668   Expr *Lower = TestIsLessOp.getValue()
8669                     ? tryBuildCapture(SemaRef, LB, Captures).get()
8670                     : Cnt;
8671   if (!Upper || !Lower)
8672     return nullptr;
8673 
8674   ExprResult Diff = calculateNumIters(
8675       SemaRef, S, DefaultLoc, Lower, Upper, Step, VarType,
8676       /*TestIsStrictOp=*/false, /*RoundToStep=*/false, Captures);
8677   if (!Diff.isUsable())
8678     return nullptr;
8679 
8680   return Diff.get();
8681 }
8682 } // namespace
8683 
8684 void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
8685   assert(getLangOpts().OpenMP && "OpenMP is not active.");
8686   assert(Init && "Expected loop in canonical form.");
8687   unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
8688   if (AssociatedLoops > 0 &&
8689       isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
8690     DSAStack->loopStart();
8691     OpenMPIterationSpaceChecker ISC(*this, /*SupportsNonRectangular=*/true,
8692                                     *DSAStack, ForLoc);
8693     if (!ISC.checkAndSetInit(Init, /*EmitDiags=*/false)) {
8694       if (ValueDecl *D = ISC.getLoopDecl()) {
8695         auto *VD = dyn_cast<VarDecl>(D);
8696         DeclRefExpr *PrivateRef = nullptr;
8697         if (!VD) {
8698           if (VarDecl *Private = isOpenMPCapturedDecl(D)) {
8699             VD = Private;
8700           } else {
8701             PrivateRef = buildCapture(*this, D, ISC.getLoopDeclRefExpr(),
8702                                       /*WithInit=*/false);
8703             VD = cast<VarDecl>(PrivateRef->getDecl());
8704           }
8705         }
8706         DSAStack->addLoopControlVariable(D, VD);
8707         const Decl *LD = DSAStack->getPossiblyLoopCunter();
8708         if (LD != D->getCanonicalDecl()) {
8709           DSAStack->resetPossibleLoopCounter();
8710           if (auto *Var = dyn_cast_or_null<VarDecl>(LD))
8711             MarkDeclarationsReferencedInExpr(
8712                 buildDeclRefExpr(*this, const_cast<VarDecl *>(Var),
8713                                  Var->getType().getNonLValueExprType(Context),
8714                                  ForLoc, /*RefersToCapture=*/true));
8715         }
8716         OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
8717         // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables
8718         // Referenced in a Construct, C/C++]. The loop iteration variable in the
8719         // associated for-loop of a simd construct with just one associated
8720         // for-loop may be listed in a linear clause with a constant-linear-step
8721         // that is the increment of the associated for-loop. The loop iteration
8722         // variable(s) in the associated for-loop(s) of a for or parallel for
8723         // construct may be listed in a private or lastprivate clause.
8724         DSAStackTy::DSAVarData DVar =
8725             DSAStack->getTopDSA(D, /*FromParent=*/false);
8726         // If LoopVarRefExpr is nullptr it means the corresponding loop variable
8727         // is declared in the loop and it is predetermined as a private.
8728         Expr *LoopDeclRefExpr = ISC.getLoopDeclRefExpr();
8729         OpenMPClauseKind PredeterminedCKind =
8730             isOpenMPSimdDirective(DKind)
8731                 ? (DSAStack->hasMutipleLoops() ? OMPC_lastprivate : OMPC_linear)
8732                 : OMPC_private;
8733         if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
8734               DVar.CKind != PredeterminedCKind && DVar.RefExpr &&
8735               (LangOpts.OpenMP <= 45 || (DVar.CKind != OMPC_lastprivate &&
8736                                          DVar.CKind != OMPC_private))) ||
8737              ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
8738                DKind == OMPD_master_taskloop ||
8739                DKind == OMPD_parallel_master_taskloop ||
8740                isOpenMPDistributeDirective(DKind)) &&
8741               !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
8742               DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
8743             (DVar.CKind != OMPC_private || DVar.RefExpr)) {
8744           Diag(Init->getBeginLoc(), diag::err_omp_loop_var_dsa)
8745               << getOpenMPClauseName(DVar.CKind)
8746               << getOpenMPDirectiveName(DKind)
8747               << getOpenMPClauseName(PredeterminedCKind);
8748           if (DVar.RefExpr == nullptr)
8749             DVar.CKind = PredeterminedCKind;
8750           reportOriginalDsa(*this, DSAStack, D, DVar,
8751                             /*IsLoopIterVar=*/true);
8752         } else if (LoopDeclRefExpr) {
8753           // Make the loop iteration variable private (for worksharing
8754           // constructs), linear (for simd directives with the only one
8755           // associated loop) or lastprivate (for simd directives with several
8756           // collapsed or ordered loops).
8757           if (DVar.CKind == OMPC_unknown)
8758             DSAStack->addDSA(D, LoopDeclRefExpr, PredeterminedCKind,
8759                              PrivateRef);
8760         }
8761       }
8762     }
8763     DSAStack->setAssociatedLoops(AssociatedLoops - 1);
8764   }
8765 }
8766 
8767 /// Called on a for stmt to check and extract its iteration space
8768 /// for further processing (such as collapsing).
8769 static bool checkOpenMPIterationSpace(
8770     OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
8771     unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
8772     unsigned TotalNestedLoopCount, Expr *CollapseLoopCountExpr,
8773     Expr *OrderedLoopCountExpr,
8774     Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
8775     llvm::MutableArrayRef<LoopIterationSpace> ResultIterSpaces,
8776     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
8777   bool SupportsNonRectangular = !isOpenMPLoopTransformationDirective(DKind);
8778   // OpenMP [2.9.1, Canonical Loop Form]
8779   //   for (init-expr; test-expr; incr-expr) structured-block
8780   //   for (range-decl: range-expr) structured-block
8781   if (auto *CanonLoop = dyn_cast_or_null<OMPCanonicalLoop>(S))
8782     S = CanonLoop->getLoopStmt();
8783   auto *For = dyn_cast_or_null<ForStmt>(S);
8784   auto *CXXFor = dyn_cast_or_null<CXXForRangeStmt>(S);
8785   // Ranged for is supported only in OpenMP 5.0.
8786   if (!For && (SemaRef.LangOpts.OpenMP <= 45 || !CXXFor)) {
8787     SemaRef.Diag(S->getBeginLoc(), diag::err_omp_not_for)
8788         << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
8789         << getOpenMPDirectiveName(DKind) << TotalNestedLoopCount
8790         << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
8791     if (TotalNestedLoopCount > 1) {
8792       if (CollapseLoopCountExpr && OrderedLoopCountExpr)
8793         SemaRef.Diag(DSA.getConstructLoc(),
8794                      diag::note_omp_collapse_ordered_expr)
8795             << 2 << CollapseLoopCountExpr->getSourceRange()
8796             << OrderedLoopCountExpr->getSourceRange();
8797       else if (CollapseLoopCountExpr)
8798         SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
8799                      diag::note_omp_collapse_ordered_expr)
8800             << 0 << CollapseLoopCountExpr->getSourceRange();
8801       else
8802         SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
8803                      diag::note_omp_collapse_ordered_expr)
8804             << 1 << OrderedLoopCountExpr->getSourceRange();
8805     }
8806     return true;
8807   }
8808   assert(((For && For->getBody()) || (CXXFor && CXXFor->getBody())) &&
8809          "No loop body.");
8810   // Postpone analysis in dependent contexts for ranged for loops.
8811   if (CXXFor && SemaRef.CurContext->isDependentContext())
8812     return false;
8813 
8814   OpenMPIterationSpaceChecker ISC(SemaRef, SupportsNonRectangular, DSA,
8815                                   For ? For->getForLoc() : CXXFor->getForLoc());
8816 
8817   // Check init.
8818   Stmt *Init = For ? For->getInit() : CXXFor->getBeginStmt();
8819   if (ISC.checkAndSetInit(Init))
8820     return true;
8821 
8822   bool HasErrors = false;
8823 
8824   // Check loop variable's type.
8825   if (ValueDecl *LCDecl = ISC.getLoopDecl()) {
8826     // OpenMP [2.6, Canonical Loop Form]
8827     // Var is one of the following:
8828     //   A variable of signed or unsigned integer type.
8829     //   For C++, a variable of a random access iterator type.
8830     //   For C, a variable of a pointer type.
8831     QualType VarType = LCDecl->getType().getNonReferenceType();
8832     if (!VarType->isDependentType() && !VarType->isIntegerType() &&
8833         !VarType->isPointerType() &&
8834         !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
8835       SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_variable_type)
8836           << SemaRef.getLangOpts().CPlusPlus;
8837       HasErrors = true;
8838     }
8839 
8840     // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
8841     // a Construct
8842     // The loop iteration variable(s) in the associated for-loop(s) of a for or
8843     // parallel for construct is (are) private.
8844     // The loop iteration variable in the associated for-loop of a simd
8845     // construct with just one associated for-loop is linear with a
8846     // constant-linear-step that is the increment of the associated for-loop.
8847     // Exclude loop var from the list of variables with implicitly defined data
8848     // sharing attributes.
8849     VarsWithImplicitDSA.erase(LCDecl);
8850 
8851     assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
8852 
8853     // Check test-expr.
8854     HasErrors |= ISC.checkAndSetCond(For ? For->getCond() : CXXFor->getCond());
8855 
8856     // Check incr-expr.
8857     HasErrors |= ISC.checkAndSetInc(For ? For->getInc() : CXXFor->getInc());
8858   }
8859 
8860   if (ISC.dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
8861     return HasErrors;
8862 
8863   // Build the loop's iteration space representation.
8864   ResultIterSpaces[CurrentNestedLoopCount].PreCond = ISC.buildPreCond(
8865       DSA.getCurScope(), For ? For->getCond() : CXXFor->getCond(), Captures);
8866   ResultIterSpaces[CurrentNestedLoopCount].NumIterations =
8867       ISC.buildNumIterations(DSA.getCurScope(), ResultIterSpaces,
8868                              (isOpenMPWorksharingDirective(DKind) ||
8869                               isOpenMPGenericLoopDirective(DKind) ||
8870                               isOpenMPTaskLoopDirective(DKind) ||
8871                               isOpenMPDistributeDirective(DKind) ||
8872                               isOpenMPLoopTransformationDirective(DKind)),
8873                              Captures);
8874   ResultIterSpaces[CurrentNestedLoopCount].CounterVar =
8875       ISC.buildCounterVar(Captures, DSA);
8876   ResultIterSpaces[CurrentNestedLoopCount].PrivateCounterVar =
8877       ISC.buildPrivateCounterVar();
8878   ResultIterSpaces[CurrentNestedLoopCount].CounterInit = ISC.buildCounterInit();
8879   ResultIterSpaces[CurrentNestedLoopCount].CounterStep = ISC.buildCounterStep();
8880   ResultIterSpaces[CurrentNestedLoopCount].InitSrcRange = ISC.getInitSrcRange();
8881   ResultIterSpaces[CurrentNestedLoopCount].CondSrcRange =
8882       ISC.getConditionSrcRange();
8883   ResultIterSpaces[CurrentNestedLoopCount].IncSrcRange =
8884       ISC.getIncrementSrcRange();
8885   ResultIterSpaces[CurrentNestedLoopCount].Subtract = ISC.shouldSubtractStep();
8886   ResultIterSpaces[CurrentNestedLoopCount].IsStrictCompare =
8887       ISC.isStrictTestOp();
8888   std::tie(ResultIterSpaces[CurrentNestedLoopCount].MinValue,
8889            ResultIterSpaces[CurrentNestedLoopCount].MaxValue) =
8890       ISC.buildMinMaxValues(DSA.getCurScope(), Captures);
8891   ResultIterSpaces[CurrentNestedLoopCount].FinalCondition =
8892       ISC.buildFinalCondition(DSA.getCurScope());
8893   ResultIterSpaces[CurrentNestedLoopCount].IsNonRectangularLB =
8894       ISC.doesInitDependOnLC();
8895   ResultIterSpaces[CurrentNestedLoopCount].IsNonRectangularUB =
8896       ISC.doesCondDependOnLC();
8897   ResultIterSpaces[CurrentNestedLoopCount].LoopDependentIdx =
8898       ISC.getLoopDependentIdx();
8899 
8900   HasErrors |=
8901       (ResultIterSpaces[CurrentNestedLoopCount].PreCond == nullptr ||
8902        ResultIterSpaces[CurrentNestedLoopCount].NumIterations == nullptr ||
8903        ResultIterSpaces[CurrentNestedLoopCount].CounterVar == nullptr ||
8904        ResultIterSpaces[CurrentNestedLoopCount].PrivateCounterVar == nullptr ||
8905        ResultIterSpaces[CurrentNestedLoopCount].CounterInit == nullptr ||
8906        ResultIterSpaces[CurrentNestedLoopCount].CounterStep == nullptr);
8907   if (!HasErrors && DSA.isOrderedRegion()) {
8908     if (DSA.getOrderedRegionParam().second->getNumForLoops()) {
8909       if (CurrentNestedLoopCount <
8910           DSA.getOrderedRegionParam().second->getLoopNumIterations().size()) {
8911         DSA.getOrderedRegionParam().second->setLoopNumIterations(
8912             CurrentNestedLoopCount,
8913             ResultIterSpaces[CurrentNestedLoopCount].NumIterations);
8914         DSA.getOrderedRegionParam().second->setLoopCounter(
8915             CurrentNestedLoopCount,
8916             ResultIterSpaces[CurrentNestedLoopCount].CounterVar);
8917       }
8918     }
8919     for (auto &Pair : DSA.getDoacrossDependClauses()) {
8920       if (CurrentNestedLoopCount >= Pair.first->getNumLoops()) {
8921         // Erroneous case - clause has some problems.
8922         continue;
8923       }
8924       if (Pair.first->getDependencyKind() == OMPC_DEPEND_sink &&
8925           Pair.second.size() <= CurrentNestedLoopCount) {
8926         // Erroneous case - clause has some problems.
8927         Pair.first->setLoopData(CurrentNestedLoopCount, nullptr);
8928         continue;
8929       }
8930       Expr *CntValue;
8931       if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
8932         CntValue = ISC.buildOrderedLoopData(
8933             DSA.getCurScope(),
8934             ResultIterSpaces[CurrentNestedLoopCount].CounterVar, Captures,
8935             Pair.first->getDependencyLoc());
8936       else
8937         CntValue = ISC.buildOrderedLoopData(
8938             DSA.getCurScope(),
8939             ResultIterSpaces[CurrentNestedLoopCount].CounterVar, Captures,
8940             Pair.first->getDependencyLoc(),
8941             Pair.second[CurrentNestedLoopCount].first,
8942             Pair.second[CurrentNestedLoopCount].second);
8943       Pair.first->setLoopData(CurrentNestedLoopCount, CntValue);
8944     }
8945   }
8946 
8947   return HasErrors;
8948 }
8949 
8950 /// Build 'VarRef = Start.
8951 static ExprResult
8952 buildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
8953                  ExprResult Start, bool IsNonRectangularLB,
8954                  llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
8955   // Build 'VarRef = Start.
8956   ExprResult NewStart = IsNonRectangularLB
8957                             ? Start.get()
8958                             : tryBuildCapture(SemaRef, Start.get(), Captures);
8959   if (!NewStart.isUsable())
8960     return ExprError();
8961   if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
8962                                    VarRef.get()->getType())) {
8963     NewStart = SemaRef.PerformImplicitConversion(
8964         NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
8965         /*AllowExplicit=*/true);
8966     if (!NewStart.isUsable())
8967       return ExprError();
8968   }
8969 
8970   ExprResult Init =
8971       SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
8972   return Init;
8973 }
8974 
8975 /// Build 'VarRef = Start + Iter * Step'.
8976 static ExprResult buildCounterUpdate(
8977     Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
8978     ExprResult Start, ExprResult Iter, ExprResult Step, bool Subtract,
8979     bool IsNonRectangularLB,
8980     llvm::MapVector<const Expr *, DeclRefExpr *> *Captures = nullptr) {
8981   // Add parentheses (for debugging purposes only).
8982   Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
8983   if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
8984       !Step.isUsable())
8985     return ExprError();
8986 
8987   ExprResult NewStep = Step;
8988   if (Captures)
8989     NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
8990   if (NewStep.isInvalid())
8991     return ExprError();
8992   ExprResult Update =
8993       SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
8994   if (!Update.isUsable())
8995     return ExprError();
8996 
8997   // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
8998   // 'VarRef = Start (+|-) Iter * Step'.
8999   if (!Start.isUsable())
9000     return ExprError();
9001   ExprResult NewStart = SemaRef.ActOnParenExpr(Loc, Loc, Start.get());
9002   if (!NewStart.isUsable())
9003     return ExprError();
9004   if (Captures && !IsNonRectangularLB)
9005     NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
9006   if (NewStart.isInvalid())
9007     return ExprError();
9008 
9009   // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
9010   ExprResult SavedUpdate = Update;
9011   ExprResult UpdateVal;
9012   if (VarRef.get()->getType()->isOverloadableType() ||
9013       NewStart.get()->getType()->isOverloadableType() ||
9014       Update.get()->getType()->isOverloadableType()) {
9015     Sema::TentativeAnalysisScope Trap(SemaRef);
9016 
9017     Update =
9018         SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
9019     if (Update.isUsable()) {
9020       UpdateVal =
9021           SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
9022                              VarRef.get(), SavedUpdate.get());
9023       if (UpdateVal.isUsable()) {
9024         Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
9025                                             UpdateVal.get());
9026       }
9027     }
9028   }
9029 
9030   // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
9031   if (!Update.isUsable() || !UpdateVal.isUsable()) {
9032     Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
9033                                 NewStart.get(), SavedUpdate.get());
9034     if (!Update.isUsable())
9035       return ExprError();
9036 
9037     if (!SemaRef.Context.hasSameType(Update.get()->getType(),
9038                                      VarRef.get()->getType())) {
9039       Update = SemaRef.PerformImplicitConversion(
9040           Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
9041       if (!Update.isUsable())
9042         return ExprError();
9043     }
9044 
9045     Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
9046   }
9047   return Update;
9048 }
9049 
9050 /// Convert integer expression \a E to make it have at least \a Bits
9051 /// bits.
9052 static ExprResult widenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
9053   if (E == nullptr)
9054     return ExprError();
9055   ASTContext &C = SemaRef.Context;
9056   QualType OldType = E->getType();
9057   unsigned HasBits = C.getTypeSize(OldType);
9058   if (HasBits >= Bits)
9059     return ExprResult(E);
9060   // OK to convert to signed, because new type has more bits than old.
9061   QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
9062   return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
9063                                            true);
9064 }
9065 
9066 /// Check if the given expression \a E is a constant integer that fits
9067 /// into \a Bits bits.
9068 static bool fitsInto(unsigned Bits, bool Signed, const Expr *E, Sema &SemaRef) {
9069   if (E == nullptr)
9070     return false;
9071   if (Optional<llvm::APSInt> Result =
9072           E->getIntegerConstantExpr(SemaRef.Context))
9073     return Signed ? Result->isSignedIntN(Bits) : Result->isIntN(Bits);
9074   return false;
9075 }
9076 
9077 /// Build preinits statement for the given declarations.
9078 static Stmt *buildPreInits(ASTContext &Context,
9079                            MutableArrayRef<Decl *> PreInits) {
9080   if (!PreInits.empty()) {
9081     return new (Context) DeclStmt(
9082         DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
9083         SourceLocation(), SourceLocation());
9084   }
9085   return nullptr;
9086 }
9087 
9088 /// Build preinits statement for the given declarations.
9089 static Stmt *
9090 buildPreInits(ASTContext &Context,
9091               const llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
9092   if (!Captures.empty()) {
9093     SmallVector<Decl *, 16> PreInits;
9094     for (const auto &Pair : Captures)
9095       PreInits.push_back(Pair.second->getDecl());
9096     return buildPreInits(Context, PreInits);
9097   }
9098   return nullptr;
9099 }
9100 
9101 /// Build postupdate expression for the given list of postupdates expressions.
9102 static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
9103   Expr *PostUpdate = nullptr;
9104   if (!PostUpdates.empty()) {
9105     for (Expr *E : PostUpdates) {
9106       Expr *ConvE = S.BuildCStyleCastExpr(
9107                          E->getExprLoc(),
9108                          S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
9109                          E->getExprLoc(), E)
9110                         .get();
9111       PostUpdate = PostUpdate
9112                        ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
9113                                               PostUpdate, ConvE)
9114                              .get()
9115                        : ConvE;
9116     }
9117   }
9118   return PostUpdate;
9119 }
9120 
9121 /// Called on a for stmt to check itself and nested loops (if any).
9122 /// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
9123 /// number of collapsed loops otherwise.
9124 static unsigned
9125 checkOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
9126                 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
9127                 DSAStackTy &DSA,
9128                 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
9129                 OMPLoopBasedDirective::HelperExprs &Built) {
9130   unsigned NestedLoopCount = 1;
9131   bool SupportsNonPerfectlyNested = (SemaRef.LangOpts.OpenMP >= 50) &&
9132                                     !isOpenMPLoopTransformationDirective(DKind);
9133 
9134   if (CollapseLoopCountExpr) {
9135     // Found 'collapse' clause - calculate collapse number.
9136     Expr::EvalResult Result;
9137     if (!CollapseLoopCountExpr->isValueDependent() &&
9138         CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
9139       NestedLoopCount = Result.Val.getInt().getLimitedValue();
9140     } else {
9141       Built.clear(/*Size=*/1);
9142       return 1;
9143     }
9144   }
9145   unsigned OrderedLoopCount = 1;
9146   if (OrderedLoopCountExpr) {
9147     // Found 'ordered' clause - calculate collapse number.
9148     Expr::EvalResult EVResult;
9149     if (!OrderedLoopCountExpr->isValueDependent() &&
9150         OrderedLoopCountExpr->EvaluateAsInt(EVResult,
9151                                             SemaRef.getASTContext())) {
9152       llvm::APSInt Result = EVResult.Val.getInt();
9153       if (Result.getLimitedValue() < NestedLoopCount) {
9154         SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
9155                      diag::err_omp_wrong_ordered_loop_count)
9156             << OrderedLoopCountExpr->getSourceRange();
9157         SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
9158                      diag::note_collapse_loop_count)
9159             << CollapseLoopCountExpr->getSourceRange();
9160       }
9161       OrderedLoopCount = Result.getLimitedValue();
9162     } else {
9163       Built.clear(/*Size=*/1);
9164       return 1;
9165     }
9166   }
9167   // This is helper routine for loop directives (e.g., 'for', 'simd',
9168   // 'for simd', etc.).
9169   llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
9170   unsigned NumLoops = std::max(OrderedLoopCount, NestedLoopCount);
9171   SmallVector<LoopIterationSpace, 4> IterSpaces(NumLoops);
9172   if (!OMPLoopBasedDirective::doForAllLoops(
9173           AStmt->IgnoreContainers(!isOpenMPLoopTransformationDirective(DKind)),
9174           SupportsNonPerfectlyNested, NumLoops,
9175           [DKind, &SemaRef, &DSA, NumLoops, NestedLoopCount,
9176            CollapseLoopCountExpr, OrderedLoopCountExpr, &VarsWithImplicitDSA,
9177            &IterSpaces, &Captures](unsigned Cnt, Stmt *CurStmt) {
9178             if (checkOpenMPIterationSpace(
9179                     DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
9180                     NumLoops, CollapseLoopCountExpr, OrderedLoopCountExpr,
9181                     VarsWithImplicitDSA, IterSpaces, Captures))
9182               return true;
9183             if (Cnt > 0 && Cnt >= NestedLoopCount &&
9184                 IterSpaces[Cnt].CounterVar) {
9185               // Handle initialization of captured loop iterator variables.
9186               auto *DRE = cast<DeclRefExpr>(IterSpaces[Cnt].CounterVar);
9187               if (isa<OMPCapturedExprDecl>(DRE->getDecl())) {
9188                 Captures[DRE] = DRE;
9189               }
9190             }
9191             return false;
9192           },
9193           [&SemaRef, &Captures](OMPLoopTransformationDirective *Transform) {
9194             Stmt *DependentPreInits = Transform->getPreInits();
9195             if (!DependentPreInits)
9196               return;
9197             for (Decl *C : cast<DeclStmt>(DependentPreInits)->getDeclGroup()) {
9198               auto *D = cast<VarDecl>(C);
9199               DeclRefExpr *Ref = buildDeclRefExpr(SemaRef, D, D->getType(),
9200                                                   Transform->getBeginLoc());
9201               Captures[Ref] = Ref;
9202             }
9203           }))
9204     return 0;
9205 
9206   Built.clear(/* size */ NestedLoopCount);
9207 
9208   if (SemaRef.CurContext->isDependentContext())
9209     return NestedLoopCount;
9210 
9211   // An example of what is generated for the following code:
9212   //
9213   //   #pragma omp simd collapse(2) ordered(2)
9214   //   for (i = 0; i < NI; ++i)
9215   //     for (k = 0; k < NK; ++k)
9216   //       for (j = J0; j < NJ; j+=2) {
9217   //         <loop body>
9218   //       }
9219   //
9220   // We generate the code below.
9221   // Note: the loop body may be outlined in CodeGen.
9222   // Note: some counters may be C++ classes, operator- is used to find number of
9223   // iterations and operator+= to calculate counter value.
9224   // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
9225   // or i64 is currently supported).
9226   //
9227   //   #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
9228   //   for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
9229   //     .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
9230   //     .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
9231   //     // similar updates for vars in clauses (e.g. 'linear')
9232   //     <loop body (using local i and j)>
9233   //   }
9234   //   i = NI; // assign final values of counters
9235   //   j = NJ;
9236   //
9237 
9238   // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
9239   // the iteration counts of the collapsed for loops.
9240   // Precondition tests if there is at least one iteration (all conditions are
9241   // true).
9242   auto PreCond = ExprResult(IterSpaces[0].PreCond);
9243   Expr *N0 = IterSpaces[0].NumIterations;
9244   ExprResult LastIteration32 =
9245       widenIterationCount(/*Bits=*/32,
9246                           SemaRef
9247                               .PerformImplicitConversion(
9248                                   N0->IgnoreImpCasts(), N0->getType(),
9249                                   Sema::AA_Converting, /*AllowExplicit=*/true)
9250                               .get(),
9251                           SemaRef);
9252   ExprResult LastIteration64 = widenIterationCount(
9253       /*Bits=*/64,
9254       SemaRef
9255           .PerformImplicitConversion(N0->IgnoreImpCasts(), N0->getType(),
9256                                      Sema::AA_Converting,
9257                                      /*AllowExplicit=*/true)
9258           .get(),
9259       SemaRef);
9260 
9261   if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
9262     return NestedLoopCount;
9263 
9264   ASTContext &C = SemaRef.Context;
9265   bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
9266 
9267   Scope *CurScope = DSA.getCurScope();
9268   for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
9269     if (PreCond.isUsable()) {
9270       PreCond =
9271           SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
9272                              PreCond.get(), IterSpaces[Cnt].PreCond);
9273     }
9274     Expr *N = IterSpaces[Cnt].NumIterations;
9275     SourceLocation Loc = N->getExprLoc();
9276     AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
9277     if (LastIteration32.isUsable())
9278       LastIteration32 = SemaRef.BuildBinOp(
9279           CurScope, Loc, BO_Mul, LastIteration32.get(),
9280           SemaRef
9281               .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
9282                                          Sema::AA_Converting,
9283                                          /*AllowExplicit=*/true)
9284               .get());
9285     if (LastIteration64.isUsable())
9286       LastIteration64 = SemaRef.BuildBinOp(
9287           CurScope, Loc, BO_Mul, LastIteration64.get(),
9288           SemaRef
9289               .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
9290                                          Sema::AA_Converting,
9291                                          /*AllowExplicit=*/true)
9292               .get());
9293   }
9294 
9295   // Choose either the 32-bit or 64-bit version.
9296   ExprResult LastIteration = LastIteration64;
9297   if (SemaRef.getLangOpts().OpenMPOptimisticCollapse ||
9298       (LastIteration32.isUsable() &&
9299        C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
9300        (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
9301         fitsInto(
9302             /*Bits=*/32,
9303             LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
9304             LastIteration64.get(), SemaRef))))
9305     LastIteration = LastIteration32;
9306   QualType VType = LastIteration.get()->getType();
9307   QualType RealVType = VType;
9308   QualType StrideVType = VType;
9309   if (isOpenMPTaskLoopDirective(DKind)) {
9310     VType =
9311         SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
9312     StrideVType =
9313         SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
9314   }
9315 
9316   if (!LastIteration.isUsable())
9317     return 0;
9318 
9319   // Save the number of iterations.
9320   ExprResult NumIterations = LastIteration;
9321   {
9322     LastIteration = SemaRef.BuildBinOp(
9323         CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
9324         LastIteration.get(),
9325         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
9326     if (!LastIteration.isUsable())
9327       return 0;
9328   }
9329 
9330   // Calculate the last iteration number beforehand instead of doing this on
9331   // each iteration. Do not do this if the number of iterations may be kfold-ed.
9332   bool IsConstant = LastIteration.get()->isIntegerConstantExpr(SemaRef.Context);
9333   ExprResult CalcLastIteration;
9334   if (!IsConstant) {
9335     ExprResult SaveRef =
9336         tryBuildCapture(SemaRef, LastIteration.get(), Captures);
9337     LastIteration = SaveRef;
9338 
9339     // Prepare SaveRef + 1.
9340     NumIterations = SemaRef.BuildBinOp(
9341         CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
9342         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
9343     if (!NumIterations.isUsable())
9344       return 0;
9345   }
9346 
9347   SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
9348 
9349   // Build variables passed into runtime, necessary for worksharing directives.
9350   ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
9351   if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
9352       isOpenMPDistributeDirective(DKind) ||
9353       isOpenMPGenericLoopDirective(DKind) ||
9354       isOpenMPLoopTransformationDirective(DKind)) {
9355     // Lower bound variable, initialized with zero.
9356     VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
9357     LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
9358     SemaRef.AddInitializerToDecl(LBDecl,
9359                                  SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
9360                                  /*DirectInit*/ false);
9361 
9362     // Upper bound variable, initialized with last iteration number.
9363     VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
9364     UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
9365     SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
9366                                  /*DirectInit*/ false);
9367 
9368     // A 32-bit variable-flag where runtime returns 1 for the last iteration.
9369     // This will be used to implement clause 'lastprivate'.
9370     QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
9371     VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
9372     IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
9373     SemaRef.AddInitializerToDecl(ILDecl,
9374                                  SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
9375                                  /*DirectInit*/ false);
9376 
9377     // Stride variable returned by runtime (we initialize it to 1 by default).
9378     VarDecl *STDecl =
9379         buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
9380     ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
9381     SemaRef.AddInitializerToDecl(STDecl,
9382                                  SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
9383                                  /*DirectInit*/ false);
9384 
9385     // Build expression: UB = min(UB, LastIteration)
9386     // It is necessary for CodeGen of directives with static scheduling.
9387     ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
9388                                                 UB.get(), LastIteration.get());
9389     ExprResult CondOp = SemaRef.ActOnConditionalOp(
9390         LastIteration.get()->getExprLoc(), InitLoc, IsUBGreater.get(),
9391         LastIteration.get(), UB.get());
9392     EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
9393                              CondOp.get());
9394     EUB = SemaRef.ActOnFinishFullExpr(EUB.get(), /*DiscardedValue*/ false);
9395 
9396     // If we have a combined directive that combines 'distribute', 'for' or
9397     // 'simd' we need to be able to access the bounds of the schedule of the
9398     // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
9399     // by scheduling 'distribute' have to be passed to the schedule of 'for'.
9400     if (isOpenMPLoopBoundSharingDirective(DKind)) {
9401       // Lower bound variable, initialized with zero.
9402       VarDecl *CombLBDecl =
9403           buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
9404       CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
9405       SemaRef.AddInitializerToDecl(
9406           CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
9407           /*DirectInit*/ false);
9408 
9409       // Upper bound variable, initialized with last iteration number.
9410       VarDecl *CombUBDecl =
9411           buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
9412       CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
9413       SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
9414                                    /*DirectInit*/ false);
9415 
9416       ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
9417           CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
9418       ExprResult CombCondOp =
9419           SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
9420                                      LastIteration.get(), CombUB.get());
9421       CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
9422                                    CombCondOp.get());
9423       CombEUB =
9424           SemaRef.ActOnFinishFullExpr(CombEUB.get(), /*DiscardedValue*/ false);
9425 
9426       const CapturedDecl *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
9427       // We expect to have at least 2 more parameters than the 'parallel'
9428       // directive does - the lower and upper bounds of the previous schedule.
9429       assert(CD->getNumParams() >= 4 &&
9430              "Unexpected number of parameters in loop combined directive");
9431 
9432       // Set the proper type for the bounds given what we learned from the
9433       // enclosed loops.
9434       ImplicitParamDecl *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
9435       ImplicitParamDecl *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
9436 
9437       // Previous lower and upper bounds are obtained from the region
9438       // parameters.
9439       PrevLB =
9440           buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
9441       PrevUB =
9442           buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
9443     }
9444   }
9445 
9446   // Build the iteration variable and its initialization before loop.
9447   ExprResult IV;
9448   ExprResult Init, CombInit;
9449   {
9450     VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
9451     IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
9452     Expr *RHS = (isOpenMPWorksharingDirective(DKind) ||
9453                  isOpenMPGenericLoopDirective(DKind) ||
9454                  isOpenMPTaskLoopDirective(DKind) ||
9455                  isOpenMPDistributeDirective(DKind) ||
9456                  isOpenMPLoopTransformationDirective(DKind))
9457                     ? LB.get()
9458                     : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
9459     Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
9460     Init = SemaRef.ActOnFinishFullExpr(Init.get(), /*DiscardedValue*/ false);
9461 
9462     if (isOpenMPLoopBoundSharingDirective(DKind)) {
9463       Expr *CombRHS =
9464           (isOpenMPWorksharingDirective(DKind) ||
9465            isOpenMPGenericLoopDirective(DKind) ||
9466            isOpenMPTaskLoopDirective(DKind) ||
9467            isOpenMPDistributeDirective(DKind))
9468               ? CombLB.get()
9469               : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
9470       CombInit =
9471           SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
9472       CombInit =
9473           SemaRef.ActOnFinishFullExpr(CombInit.get(), /*DiscardedValue*/ false);
9474     }
9475   }
9476 
9477   bool UseStrictCompare =
9478       RealVType->hasUnsignedIntegerRepresentation() &&
9479       llvm::all_of(IterSpaces, [](const LoopIterationSpace &LIS) {
9480         return LIS.IsStrictCompare;
9481       });
9482   // Loop condition (IV < NumIterations) or (IV <= UB or IV < UB + 1 (for
9483   // unsigned IV)) for worksharing loops.
9484   SourceLocation CondLoc = AStmt->getBeginLoc();
9485   Expr *BoundUB = UB.get();
9486   if (UseStrictCompare) {
9487     BoundUB =
9488         SemaRef
9489             .BuildBinOp(CurScope, CondLoc, BO_Add, BoundUB,
9490                         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
9491             .get();
9492     BoundUB =
9493         SemaRef.ActOnFinishFullExpr(BoundUB, /*DiscardedValue*/ false).get();
9494   }
9495   ExprResult Cond =
9496       (isOpenMPWorksharingDirective(DKind) ||
9497        isOpenMPGenericLoopDirective(DKind) ||
9498        isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind) ||
9499        isOpenMPLoopTransformationDirective(DKind))
9500           ? SemaRef.BuildBinOp(CurScope, CondLoc,
9501                                UseStrictCompare ? BO_LT : BO_LE, IV.get(),
9502                                BoundUB)
9503           : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
9504                                NumIterations.get());
9505   ExprResult CombDistCond;
9506   if (isOpenMPLoopBoundSharingDirective(DKind)) {
9507     CombDistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
9508                                       NumIterations.get());
9509   }
9510 
9511   ExprResult CombCond;
9512   if (isOpenMPLoopBoundSharingDirective(DKind)) {
9513     Expr *BoundCombUB = CombUB.get();
9514     if (UseStrictCompare) {
9515       BoundCombUB =
9516           SemaRef
9517               .BuildBinOp(
9518                   CurScope, CondLoc, BO_Add, BoundCombUB,
9519                   SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
9520               .get();
9521       BoundCombUB =
9522           SemaRef.ActOnFinishFullExpr(BoundCombUB, /*DiscardedValue*/ false)
9523               .get();
9524     }
9525     CombCond =
9526         SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
9527                            IV.get(), BoundCombUB);
9528   }
9529   // Loop increment (IV = IV + 1)
9530   SourceLocation IncLoc = AStmt->getBeginLoc();
9531   ExprResult Inc =
9532       SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
9533                          SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
9534   if (!Inc.isUsable())
9535     return 0;
9536   Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
9537   Inc = SemaRef.ActOnFinishFullExpr(Inc.get(), /*DiscardedValue*/ false);
9538   if (!Inc.isUsable())
9539     return 0;
9540 
9541   // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
9542   // Used for directives with static scheduling.
9543   // In combined construct, add combined version that use CombLB and CombUB
9544   // base variables for the update
9545   ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
9546   if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
9547       isOpenMPGenericLoopDirective(DKind) ||
9548       isOpenMPDistributeDirective(DKind) ||
9549       isOpenMPLoopTransformationDirective(DKind)) {
9550     // LB + ST
9551     NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
9552     if (!NextLB.isUsable())
9553       return 0;
9554     // LB = LB + ST
9555     NextLB =
9556         SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
9557     NextLB =
9558         SemaRef.ActOnFinishFullExpr(NextLB.get(), /*DiscardedValue*/ false);
9559     if (!NextLB.isUsable())
9560       return 0;
9561     // UB + ST
9562     NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
9563     if (!NextUB.isUsable())
9564       return 0;
9565     // UB = UB + ST
9566     NextUB =
9567         SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
9568     NextUB =
9569         SemaRef.ActOnFinishFullExpr(NextUB.get(), /*DiscardedValue*/ false);
9570     if (!NextUB.isUsable())
9571       return 0;
9572     if (isOpenMPLoopBoundSharingDirective(DKind)) {
9573       CombNextLB =
9574           SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
9575       if (!NextLB.isUsable())
9576         return 0;
9577       // LB = LB + ST
9578       CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
9579                                       CombNextLB.get());
9580       CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get(),
9581                                                /*DiscardedValue*/ false);
9582       if (!CombNextLB.isUsable())
9583         return 0;
9584       // UB + ST
9585       CombNextUB =
9586           SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
9587       if (!CombNextUB.isUsable())
9588         return 0;
9589       // UB = UB + ST
9590       CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
9591                                       CombNextUB.get());
9592       CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get(),
9593                                                /*DiscardedValue*/ false);
9594       if (!CombNextUB.isUsable())
9595         return 0;
9596     }
9597   }
9598 
9599   // Create increment expression for distribute loop when combined in a same
9600   // directive with for as IV = IV + ST; ensure upper bound expression based
9601   // on PrevUB instead of NumIterations - used to implement 'for' when found
9602   // in combination with 'distribute', like in 'distribute parallel for'
9603   SourceLocation DistIncLoc = AStmt->getBeginLoc();
9604   ExprResult DistCond, DistInc, PrevEUB, ParForInDistCond;
9605   if (isOpenMPLoopBoundSharingDirective(DKind)) {
9606     DistCond = SemaRef.BuildBinOp(
9607         CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE, IV.get(), BoundUB);
9608     assert(DistCond.isUsable() && "distribute cond expr was not built");
9609 
9610     DistInc =
9611         SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
9612     assert(DistInc.isUsable() && "distribute inc expr was not built");
9613     DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
9614                                  DistInc.get());
9615     DistInc =
9616         SemaRef.ActOnFinishFullExpr(DistInc.get(), /*DiscardedValue*/ false);
9617     assert(DistInc.isUsable() && "distribute inc expr was not built");
9618 
9619     // Build expression: UB = min(UB, prevUB) for #for in composite or combined
9620     // construct
9621     ExprResult NewPrevUB = PrevUB;
9622     SourceLocation DistEUBLoc = AStmt->getBeginLoc();
9623     if (!SemaRef.Context.hasSameType(UB.get()->getType(),
9624                                      PrevUB.get()->getType())) {
9625       NewPrevUB = SemaRef.BuildCStyleCastExpr(
9626           DistEUBLoc,
9627           SemaRef.Context.getTrivialTypeSourceInfo(UB.get()->getType()),
9628           DistEUBLoc, NewPrevUB.get());
9629       if (!NewPrevUB.isUsable())
9630         return 0;
9631     }
9632     ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT,
9633                                                 UB.get(), NewPrevUB.get());
9634     ExprResult CondOp = SemaRef.ActOnConditionalOp(
9635         DistEUBLoc, DistEUBLoc, IsUBGreater.get(), NewPrevUB.get(), UB.get());
9636     PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
9637                                  CondOp.get());
9638     PrevEUB =
9639         SemaRef.ActOnFinishFullExpr(PrevEUB.get(), /*DiscardedValue*/ false);
9640 
9641     // Build IV <= PrevUB or IV < PrevUB + 1 for unsigned IV to be used in
9642     // parallel for is in combination with a distribute directive with
9643     // schedule(static, 1)
9644     Expr *BoundPrevUB = PrevUB.get();
9645     if (UseStrictCompare) {
9646       BoundPrevUB =
9647           SemaRef
9648               .BuildBinOp(
9649                   CurScope, CondLoc, BO_Add, BoundPrevUB,
9650                   SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
9651               .get();
9652       BoundPrevUB =
9653           SemaRef.ActOnFinishFullExpr(BoundPrevUB, /*DiscardedValue*/ false)
9654               .get();
9655     }
9656     ParForInDistCond =
9657         SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
9658                            IV.get(), BoundPrevUB);
9659   }
9660 
9661   // Build updates and final values of the loop counters.
9662   bool HasErrors = false;
9663   Built.Counters.resize(NestedLoopCount);
9664   Built.Inits.resize(NestedLoopCount);
9665   Built.Updates.resize(NestedLoopCount);
9666   Built.Finals.resize(NestedLoopCount);
9667   Built.DependentCounters.resize(NestedLoopCount);
9668   Built.DependentInits.resize(NestedLoopCount);
9669   Built.FinalsConditions.resize(NestedLoopCount);
9670   {
9671     // We implement the following algorithm for obtaining the
9672     // original loop iteration variable values based on the
9673     // value of the collapsed loop iteration variable IV.
9674     //
9675     // Let n+1 be the number of collapsed loops in the nest.
9676     // Iteration variables (I0, I1, .... In)
9677     // Iteration counts (N0, N1, ... Nn)
9678     //
9679     // Acc = IV;
9680     //
9681     // To compute Ik for loop k, 0 <= k <= n, generate:
9682     //    Prod = N(k+1) * N(k+2) * ... * Nn;
9683     //    Ik = Acc / Prod;
9684     //    Acc -= Ik * Prod;
9685     //
9686     ExprResult Acc = IV;
9687     for (unsigned int Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
9688       LoopIterationSpace &IS = IterSpaces[Cnt];
9689       SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
9690       ExprResult Iter;
9691 
9692       // Compute prod
9693       ExprResult Prod = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
9694       for (unsigned int K = Cnt + 1; K < NestedLoopCount; ++K)
9695         Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Prod.get(),
9696                                   IterSpaces[K].NumIterations);
9697 
9698       // Iter = Acc / Prod
9699       // If there is at least one more inner loop to avoid
9700       // multiplication by 1.
9701       if (Cnt + 1 < NestedLoopCount)
9702         Iter =
9703             SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, Acc.get(), Prod.get());
9704       else
9705         Iter = Acc;
9706       if (!Iter.isUsable()) {
9707         HasErrors = true;
9708         break;
9709       }
9710 
9711       // Update Acc:
9712       // Acc -= Iter * Prod
9713       // Check if there is at least one more inner loop to avoid
9714       // multiplication by 1.
9715       if (Cnt + 1 < NestedLoopCount)
9716         Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Iter.get(),
9717                                   Prod.get());
9718       else
9719         Prod = Iter;
9720       Acc = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Sub, Acc.get(), Prod.get());
9721 
9722       // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
9723       auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
9724       DeclRefExpr *CounterVar = buildDeclRefExpr(
9725           SemaRef, VD, IS.CounterVar->getType(), IS.CounterVar->getExprLoc(),
9726           /*RefersToCapture=*/true);
9727       ExprResult Init =
9728           buildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
9729                            IS.CounterInit, IS.IsNonRectangularLB, Captures);
9730       if (!Init.isUsable()) {
9731         HasErrors = true;
9732         break;
9733       }
9734       ExprResult Update = buildCounterUpdate(
9735           SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
9736           IS.CounterStep, IS.Subtract, IS.IsNonRectangularLB, &Captures);
9737       if (!Update.isUsable()) {
9738         HasErrors = true;
9739         break;
9740       }
9741 
9742       // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
9743       ExprResult Final =
9744           buildCounterUpdate(SemaRef, CurScope, UpdLoc, CounterVar,
9745                              IS.CounterInit, IS.NumIterations, IS.CounterStep,
9746                              IS.Subtract, IS.IsNonRectangularLB, &Captures);
9747       if (!Final.isUsable()) {
9748         HasErrors = true;
9749         break;
9750       }
9751 
9752       if (!Update.isUsable() || !Final.isUsable()) {
9753         HasErrors = true;
9754         break;
9755       }
9756       // Save results
9757       Built.Counters[Cnt] = IS.CounterVar;
9758       Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
9759       Built.Inits[Cnt] = Init.get();
9760       Built.Updates[Cnt] = Update.get();
9761       Built.Finals[Cnt] = Final.get();
9762       Built.DependentCounters[Cnt] = nullptr;
9763       Built.DependentInits[Cnt] = nullptr;
9764       Built.FinalsConditions[Cnt] = nullptr;
9765       if (IS.IsNonRectangularLB || IS.IsNonRectangularUB) {
9766         Built.DependentCounters[Cnt] =
9767             Built.Counters[NestedLoopCount - 1 - IS.LoopDependentIdx];
9768         Built.DependentInits[Cnt] =
9769             Built.Inits[NestedLoopCount - 1 - IS.LoopDependentIdx];
9770         Built.FinalsConditions[Cnt] = IS.FinalCondition;
9771       }
9772     }
9773   }
9774 
9775   if (HasErrors)
9776     return 0;
9777 
9778   // Save results
9779   Built.IterationVarRef = IV.get();
9780   Built.LastIteration = LastIteration.get();
9781   Built.NumIterations = NumIterations.get();
9782   Built.CalcLastIteration = SemaRef
9783                                 .ActOnFinishFullExpr(CalcLastIteration.get(),
9784                                                      /*DiscardedValue=*/false)
9785                                 .get();
9786   Built.PreCond = PreCond.get();
9787   Built.PreInits = buildPreInits(C, Captures);
9788   Built.Cond = Cond.get();
9789   Built.Init = Init.get();
9790   Built.Inc = Inc.get();
9791   Built.LB = LB.get();
9792   Built.UB = UB.get();
9793   Built.IL = IL.get();
9794   Built.ST = ST.get();
9795   Built.EUB = EUB.get();
9796   Built.NLB = NextLB.get();
9797   Built.NUB = NextUB.get();
9798   Built.PrevLB = PrevLB.get();
9799   Built.PrevUB = PrevUB.get();
9800   Built.DistInc = DistInc.get();
9801   Built.PrevEUB = PrevEUB.get();
9802   Built.DistCombinedFields.LB = CombLB.get();
9803   Built.DistCombinedFields.UB = CombUB.get();
9804   Built.DistCombinedFields.EUB = CombEUB.get();
9805   Built.DistCombinedFields.Init = CombInit.get();
9806   Built.DistCombinedFields.Cond = CombCond.get();
9807   Built.DistCombinedFields.NLB = CombNextLB.get();
9808   Built.DistCombinedFields.NUB = CombNextUB.get();
9809   Built.DistCombinedFields.DistCond = CombDistCond.get();
9810   Built.DistCombinedFields.ParForInDistCond = ParForInDistCond.get();
9811 
9812   return NestedLoopCount;
9813 }
9814 
9815 static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
9816   auto CollapseClauses =
9817       OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
9818   if (CollapseClauses.begin() != CollapseClauses.end())
9819     return (*CollapseClauses.begin())->getNumForLoops();
9820   return nullptr;
9821 }
9822 
9823 static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
9824   auto OrderedClauses =
9825       OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
9826   if (OrderedClauses.begin() != OrderedClauses.end())
9827     return (*OrderedClauses.begin())->getNumForLoops();
9828   return nullptr;
9829 }
9830 
9831 static bool checkSimdlenSafelenSpecified(Sema &S,
9832                                          const ArrayRef<OMPClause *> Clauses) {
9833   const OMPSafelenClause *Safelen = nullptr;
9834   const OMPSimdlenClause *Simdlen = nullptr;
9835 
9836   for (const OMPClause *Clause : Clauses) {
9837     if (Clause->getClauseKind() == OMPC_safelen)
9838       Safelen = cast<OMPSafelenClause>(Clause);
9839     else if (Clause->getClauseKind() == OMPC_simdlen)
9840       Simdlen = cast<OMPSimdlenClause>(Clause);
9841     if (Safelen && Simdlen)
9842       break;
9843   }
9844 
9845   if (Simdlen && Safelen) {
9846     const Expr *SimdlenLength = Simdlen->getSimdlen();
9847     const Expr *SafelenLength = Safelen->getSafelen();
9848     if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
9849         SimdlenLength->isInstantiationDependent() ||
9850         SimdlenLength->containsUnexpandedParameterPack())
9851       return false;
9852     if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
9853         SafelenLength->isInstantiationDependent() ||
9854         SafelenLength->containsUnexpandedParameterPack())
9855       return false;
9856     Expr::EvalResult SimdlenResult, SafelenResult;
9857     SimdlenLength->EvaluateAsInt(SimdlenResult, S.Context);
9858     SafelenLength->EvaluateAsInt(SafelenResult, S.Context);
9859     llvm::APSInt SimdlenRes = SimdlenResult.Val.getInt();
9860     llvm::APSInt SafelenRes = SafelenResult.Val.getInt();
9861     // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
9862     // If both simdlen and safelen clauses are specified, the value of the
9863     // simdlen parameter must be less than or equal to the value of the safelen
9864     // parameter.
9865     if (SimdlenRes > SafelenRes) {
9866       S.Diag(SimdlenLength->getExprLoc(),
9867              diag::err_omp_wrong_simdlen_safelen_values)
9868           << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
9869       return true;
9870     }
9871   }
9872   return false;
9873 }
9874 
9875 StmtResult
9876 Sema::ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
9877                                SourceLocation StartLoc, SourceLocation EndLoc,
9878                                VarsWithInheritedDSAType &VarsWithImplicitDSA) {
9879   if (!AStmt)
9880     return StmtError();
9881 
9882   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9883   OMPLoopBasedDirective::HelperExprs B;
9884   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9885   // define the nested loops number.
9886   unsigned NestedLoopCount = checkOpenMPLoop(
9887       OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
9888       AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
9889   if (NestedLoopCount == 0)
9890     return StmtError();
9891 
9892   assert((CurContext->isDependentContext() || B.builtAll()) &&
9893          "omp simd loop exprs were not built");
9894 
9895   if (!CurContext->isDependentContext()) {
9896     // Finalize the clauses that need pre-built expressions for CodeGen.
9897     for (OMPClause *C : Clauses) {
9898       if (auto *LC = dyn_cast<OMPLinearClause>(C))
9899         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9900                                      B.NumIterations, *this, CurScope,
9901                                      DSAStack))
9902           return StmtError();
9903     }
9904   }
9905 
9906   if (checkSimdlenSafelenSpecified(*this, Clauses))
9907     return StmtError();
9908 
9909   setFunctionHasBranchProtectedScope();
9910   return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
9911                                   Clauses, AStmt, B);
9912 }
9913 
9914 StmtResult
9915 Sema::ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
9916                               SourceLocation StartLoc, SourceLocation EndLoc,
9917                               VarsWithInheritedDSAType &VarsWithImplicitDSA) {
9918   if (!AStmt)
9919     return StmtError();
9920 
9921   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9922   OMPLoopBasedDirective::HelperExprs B;
9923   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9924   // define the nested loops number.
9925   unsigned NestedLoopCount = checkOpenMPLoop(
9926       OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
9927       AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
9928   if (NestedLoopCount == 0)
9929     return StmtError();
9930 
9931   assert((CurContext->isDependentContext() || B.builtAll()) &&
9932          "omp for loop exprs were not built");
9933 
9934   if (!CurContext->isDependentContext()) {
9935     // Finalize the clauses that need pre-built expressions for CodeGen.
9936     for (OMPClause *C : Clauses) {
9937       if (auto *LC = dyn_cast<OMPLinearClause>(C))
9938         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9939                                      B.NumIterations, *this, CurScope,
9940                                      DSAStack))
9941           return StmtError();
9942     }
9943   }
9944 
9945   setFunctionHasBranchProtectedScope();
9946   return OMPForDirective::Create(
9947       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
9948       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
9949 }
9950 
9951 StmtResult Sema::ActOnOpenMPForSimdDirective(
9952     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9953     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
9954   if (!AStmt)
9955     return StmtError();
9956 
9957   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9958   OMPLoopBasedDirective::HelperExprs B;
9959   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9960   // define the nested loops number.
9961   unsigned NestedLoopCount =
9962       checkOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
9963                       getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
9964                       VarsWithImplicitDSA, B);
9965   if (NestedLoopCount == 0)
9966     return StmtError();
9967 
9968   assert((CurContext->isDependentContext() || B.builtAll()) &&
9969          "omp for simd loop exprs were not built");
9970 
9971   if (!CurContext->isDependentContext()) {
9972     // Finalize the clauses that need pre-built expressions for CodeGen.
9973     for (OMPClause *C : Clauses) {
9974       if (auto *LC = dyn_cast<OMPLinearClause>(C))
9975         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9976                                      B.NumIterations, *this, CurScope,
9977                                      DSAStack))
9978           return StmtError();
9979     }
9980   }
9981 
9982   if (checkSimdlenSafelenSpecified(*this, Clauses))
9983     return StmtError();
9984 
9985   setFunctionHasBranchProtectedScope();
9986   return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
9987                                      Clauses, AStmt, B);
9988 }
9989 
9990 StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
9991                                               Stmt *AStmt,
9992                                               SourceLocation StartLoc,
9993                                               SourceLocation EndLoc) {
9994   if (!AStmt)
9995     return StmtError();
9996 
9997   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9998   auto BaseStmt = AStmt;
9999   while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
10000     BaseStmt = CS->getCapturedStmt();
10001   if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
10002     auto S = C->children();
10003     if (S.begin() == S.end())
10004       return StmtError();
10005     // All associated statements must be '#pragma omp section' except for
10006     // the first one.
10007     for (Stmt *SectionStmt : llvm::drop_begin(S)) {
10008       if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
10009         if (SectionStmt)
10010           Diag(SectionStmt->getBeginLoc(),
10011                diag::err_omp_sections_substmt_not_section);
10012         return StmtError();
10013       }
10014       cast<OMPSectionDirective>(SectionStmt)
10015           ->setHasCancel(DSAStack->isCancelRegion());
10016     }
10017   } else {
10018     Diag(AStmt->getBeginLoc(), diag::err_omp_sections_not_compound_stmt);
10019     return StmtError();
10020   }
10021 
10022   setFunctionHasBranchProtectedScope();
10023 
10024   return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
10025                                       DSAStack->getTaskgroupReductionRef(),
10026                                       DSAStack->isCancelRegion());
10027 }
10028 
10029 StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
10030                                              SourceLocation StartLoc,
10031                                              SourceLocation EndLoc) {
10032   if (!AStmt)
10033     return StmtError();
10034 
10035   setFunctionHasBranchProtectedScope();
10036   DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
10037 
10038   return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
10039                                      DSAStack->isCancelRegion());
10040 }
10041 
10042 static Expr *getDirectCallExpr(Expr *E) {
10043   E = E->IgnoreParenCasts()->IgnoreImplicit();
10044   if (auto *CE = dyn_cast<CallExpr>(E))
10045     if (CE->getDirectCallee())
10046       return E;
10047   return nullptr;
10048 }
10049 
10050 StmtResult Sema::ActOnOpenMPDispatchDirective(ArrayRef<OMPClause *> Clauses,
10051                                               Stmt *AStmt,
10052                                               SourceLocation StartLoc,
10053                                               SourceLocation EndLoc) {
10054   if (!AStmt)
10055     return StmtError();
10056 
10057   Stmt *S = cast<CapturedStmt>(AStmt)->getCapturedStmt();
10058 
10059   // 5.1 OpenMP
10060   // expression-stmt : an expression statement with one of the following forms:
10061   //   expression = target-call ( [expression-list] );
10062   //   target-call ( [expression-list] );
10063 
10064   SourceLocation TargetCallLoc;
10065 
10066   if (!CurContext->isDependentContext()) {
10067     Expr *TargetCall = nullptr;
10068 
10069     auto *E = dyn_cast<Expr>(S);
10070     if (!E) {
10071       Diag(S->getBeginLoc(), diag::err_omp_dispatch_statement_call);
10072       return StmtError();
10073     }
10074 
10075     E = E->IgnoreParenCasts()->IgnoreImplicit();
10076 
10077     if (auto *BO = dyn_cast<BinaryOperator>(E)) {
10078       if (BO->getOpcode() == BO_Assign)
10079         TargetCall = getDirectCallExpr(BO->getRHS());
10080     } else {
10081       if (auto *COCE = dyn_cast<CXXOperatorCallExpr>(E))
10082         if (COCE->getOperator() == OO_Equal)
10083           TargetCall = getDirectCallExpr(COCE->getArg(1));
10084       if (!TargetCall)
10085         TargetCall = getDirectCallExpr(E);
10086     }
10087     if (!TargetCall) {
10088       Diag(E->getBeginLoc(), diag::err_omp_dispatch_statement_call);
10089       return StmtError();
10090     }
10091     TargetCallLoc = TargetCall->getExprLoc();
10092   }
10093 
10094   setFunctionHasBranchProtectedScope();
10095 
10096   return OMPDispatchDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
10097                                       TargetCallLoc);
10098 }
10099 
10100 StmtResult Sema::ActOnOpenMPGenericLoopDirective(
10101     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10102     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
10103   if (!AStmt)
10104     return StmtError();
10105 
10106   // OpenMP 5.1 [2.11.7, loop construct]
10107   // A list item may not appear in a lastprivate clause unless it is the
10108   // loop iteration variable of a loop that is associated with the construct.
10109   for (OMPClause *C : Clauses) {
10110     if (auto *LPC = dyn_cast<OMPLastprivateClause>(C)) {
10111       for (Expr *RefExpr : LPC->varlists()) {
10112         SourceLocation ELoc;
10113         SourceRange ERange;
10114         Expr *SimpleRefExpr = RefExpr;
10115         auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
10116         if (ValueDecl *D = Res.first) {
10117           auto &&Info = DSAStack->isLoopControlVariable(D);
10118           if (!Info.first) {
10119             Diag(ELoc, diag::err_omp_lastprivate_loop_var_non_loop_iteration);
10120             return StmtError();
10121           }
10122         }
10123       }
10124     }
10125   }
10126 
10127   auto *CS = cast<CapturedStmt>(AStmt);
10128   // 1.2.2 OpenMP Language Terminology
10129   // Structured block - An executable statement with a single entry at the
10130   // top and a single exit at the bottom.
10131   // The point of exit cannot be a branch out of the structured block.
10132   // longjmp() and throw() must not violate the entry/exit criteria.
10133   CS->getCapturedDecl()->setNothrow();
10134 
10135   OMPLoopDirective::HelperExprs B;
10136   // In presence of clause 'collapse', it will define the nested loops number.
10137   unsigned NestedLoopCount = checkOpenMPLoop(
10138       OMPD_loop, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
10139       AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
10140   if (NestedLoopCount == 0)
10141     return StmtError();
10142 
10143   assert((CurContext->isDependentContext() || B.builtAll()) &&
10144          "omp loop exprs were not built");
10145 
10146   setFunctionHasBranchProtectedScope();
10147   return OMPGenericLoopDirective::Create(Context, StartLoc, EndLoc,
10148                                          NestedLoopCount, Clauses, AStmt, B);
10149 }
10150 
10151 StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
10152                                             Stmt *AStmt,
10153                                             SourceLocation StartLoc,
10154                                             SourceLocation EndLoc) {
10155   if (!AStmt)
10156     return StmtError();
10157 
10158   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
10159 
10160   setFunctionHasBranchProtectedScope();
10161 
10162   // OpenMP [2.7.3, single Construct, Restrictions]
10163   // The copyprivate clause must not be used with the nowait clause.
10164   const OMPClause *Nowait = nullptr;
10165   const OMPClause *Copyprivate = nullptr;
10166   for (const OMPClause *Clause : Clauses) {
10167     if (Clause->getClauseKind() == OMPC_nowait)
10168       Nowait = Clause;
10169     else if (Clause->getClauseKind() == OMPC_copyprivate)
10170       Copyprivate = Clause;
10171     if (Copyprivate && Nowait) {
10172       Diag(Copyprivate->getBeginLoc(),
10173            diag::err_omp_single_copyprivate_with_nowait);
10174       Diag(Nowait->getBeginLoc(), diag::note_omp_nowait_clause_here);
10175       return StmtError();
10176     }
10177   }
10178 
10179   return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
10180 }
10181 
10182 StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
10183                                             SourceLocation StartLoc,
10184                                             SourceLocation EndLoc) {
10185   if (!AStmt)
10186     return StmtError();
10187 
10188   setFunctionHasBranchProtectedScope();
10189 
10190   return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
10191 }
10192 
10193 StmtResult Sema::ActOnOpenMPMaskedDirective(ArrayRef<OMPClause *> Clauses,
10194                                             Stmt *AStmt,
10195                                             SourceLocation StartLoc,
10196                                             SourceLocation EndLoc) {
10197   if (!AStmt)
10198     return StmtError();
10199 
10200   setFunctionHasBranchProtectedScope();
10201 
10202   return OMPMaskedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
10203 }
10204 
10205 StmtResult Sema::ActOnOpenMPCriticalDirective(
10206     const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
10207     Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
10208   if (!AStmt)
10209     return StmtError();
10210 
10211   bool ErrorFound = false;
10212   llvm::APSInt Hint;
10213   SourceLocation HintLoc;
10214   bool DependentHint = false;
10215   for (const OMPClause *C : Clauses) {
10216     if (C->getClauseKind() == OMPC_hint) {
10217       if (!DirName.getName()) {
10218         Diag(C->getBeginLoc(), diag::err_omp_hint_clause_no_name);
10219         ErrorFound = true;
10220       }
10221       Expr *E = cast<OMPHintClause>(C)->getHint();
10222       if (E->isTypeDependent() || E->isValueDependent() ||
10223           E->isInstantiationDependent()) {
10224         DependentHint = true;
10225       } else {
10226         Hint = E->EvaluateKnownConstInt(Context);
10227         HintLoc = C->getBeginLoc();
10228       }
10229     }
10230   }
10231   if (ErrorFound)
10232     return StmtError();
10233   const auto Pair = DSAStack->getCriticalWithHint(DirName);
10234   if (Pair.first && DirName.getName() && !DependentHint) {
10235     if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
10236       Diag(StartLoc, diag::err_omp_critical_with_hint);
10237       if (HintLoc.isValid())
10238         Diag(HintLoc, diag::note_omp_critical_hint_here)
10239             << 0 << toString(Hint, /*Radix=*/10, /*Signed=*/false);
10240       else
10241         Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
10242       if (const auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
10243         Diag(C->getBeginLoc(), diag::note_omp_critical_hint_here)
10244             << 1
10245             << toString(C->getHint()->EvaluateKnownConstInt(Context),
10246                         /*Radix=*/10, /*Signed=*/false);
10247       } else {
10248         Diag(Pair.first->getBeginLoc(), diag::note_omp_critical_no_hint) << 1;
10249       }
10250     }
10251   }
10252 
10253   setFunctionHasBranchProtectedScope();
10254 
10255   auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
10256                                            Clauses, AStmt);
10257   if (!Pair.first && DirName.getName() && !DependentHint)
10258     DSAStack->addCriticalWithHint(Dir, Hint);
10259   return Dir;
10260 }
10261 
10262 StmtResult Sema::ActOnOpenMPParallelForDirective(
10263     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10264     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
10265   if (!AStmt)
10266     return StmtError();
10267 
10268   auto *CS = cast<CapturedStmt>(AStmt);
10269   // 1.2.2 OpenMP Language Terminology
10270   // Structured block - An executable statement with a single entry at the
10271   // top and a single exit at the bottom.
10272   // The point of exit cannot be a branch out of the structured block.
10273   // longjmp() and throw() must not violate the entry/exit criteria.
10274   CS->getCapturedDecl()->setNothrow();
10275 
10276   OMPLoopBasedDirective::HelperExprs B;
10277   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
10278   // define the nested loops number.
10279   unsigned NestedLoopCount =
10280       checkOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
10281                       getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
10282                       VarsWithImplicitDSA, B);
10283   if (NestedLoopCount == 0)
10284     return StmtError();
10285 
10286   assert((CurContext->isDependentContext() || B.builtAll()) &&
10287          "omp parallel for loop exprs were not built");
10288 
10289   if (!CurContext->isDependentContext()) {
10290     // Finalize the clauses that need pre-built expressions for CodeGen.
10291     for (OMPClause *C : Clauses) {
10292       if (auto *LC = dyn_cast<OMPLinearClause>(C))
10293         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10294                                      B.NumIterations, *this, CurScope,
10295                                      DSAStack))
10296           return StmtError();
10297     }
10298   }
10299 
10300   setFunctionHasBranchProtectedScope();
10301   return OMPParallelForDirective::Create(
10302       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
10303       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
10304 }
10305 
10306 StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
10307     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10308     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
10309   if (!AStmt)
10310     return StmtError();
10311 
10312   auto *CS = cast<CapturedStmt>(AStmt);
10313   // 1.2.2 OpenMP Language Terminology
10314   // Structured block - An executable statement with a single entry at the
10315   // top and a single exit at the bottom.
10316   // The point of exit cannot be a branch out of the structured block.
10317   // longjmp() and throw() must not violate the entry/exit criteria.
10318   CS->getCapturedDecl()->setNothrow();
10319 
10320   OMPLoopBasedDirective::HelperExprs B;
10321   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
10322   // define the nested loops number.
10323   unsigned NestedLoopCount =
10324       checkOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
10325                       getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
10326                       VarsWithImplicitDSA, B);
10327   if (NestedLoopCount == 0)
10328     return StmtError();
10329 
10330   if (!CurContext->isDependentContext()) {
10331     // Finalize the clauses that need pre-built expressions for CodeGen.
10332     for (OMPClause *C : Clauses) {
10333       if (auto *LC = dyn_cast<OMPLinearClause>(C))
10334         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10335                                      B.NumIterations, *this, CurScope,
10336                                      DSAStack))
10337           return StmtError();
10338     }
10339   }
10340 
10341   if (checkSimdlenSafelenSpecified(*this, Clauses))
10342     return StmtError();
10343 
10344   setFunctionHasBranchProtectedScope();
10345   return OMPParallelForSimdDirective::Create(
10346       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10347 }
10348 
10349 StmtResult
10350 Sema::ActOnOpenMPParallelMasterDirective(ArrayRef<OMPClause *> Clauses,
10351                                          Stmt *AStmt, SourceLocation StartLoc,
10352                                          SourceLocation EndLoc) {
10353   if (!AStmt)
10354     return StmtError();
10355 
10356   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
10357   auto *CS = cast<CapturedStmt>(AStmt);
10358   // 1.2.2 OpenMP Language Terminology
10359   // Structured block - An executable statement with a single entry at the
10360   // top and a single exit at the bottom.
10361   // The point of exit cannot be a branch out of the structured block.
10362   // longjmp() and throw() must not violate the entry/exit criteria.
10363   CS->getCapturedDecl()->setNothrow();
10364 
10365   setFunctionHasBranchProtectedScope();
10366 
10367   return OMPParallelMasterDirective::Create(
10368       Context, StartLoc, EndLoc, Clauses, AStmt,
10369       DSAStack->getTaskgroupReductionRef());
10370 }
10371 
10372 StmtResult
10373 Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
10374                                            Stmt *AStmt, SourceLocation StartLoc,
10375                                            SourceLocation EndLoc) {
10376   if (!AStmt)
10377     return StmtError();
10378 
10379   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
10380   auto BaseStmt = AStmt;
10381   while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
10382     BaseStmt = CS->getCapturedStmt();
10383   if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
10384     auto S = C->children();
10385     if (S.begin() == S.end())
10386       return StmtError();
10387     // All associated statements must be '#pragma omp section' except for
10388     // the first one.
10389     for (Stmt *SectionStmt : llvm::drop_begin(S)) {
10390       if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
10391         if (SectionStmt)
10392           Diag(SectionStmt->getBeginLoc(),
10393                diag::err_omp_parallel_sections_substmt_not_section);
10394         return StmtError();
10395       }
10396       cast<OMPSectionDirective>(SectionStmt)
10397           ->setHasCancel(DSAStack->isCancelRegion());
10398     }
10399   } else {
10400     Diag(AStmt->getBeginLoc(),
10401          diag::err_omp_parallel_sections_not_compound_stmt);
10402     return StmtError();
10403   }
10404 
10405   setFunctionHasBranchProtectedScope();
10406 
10407   return OMPParallelSectionsDirective::Create(
10408       Context, StartLoc, EndLoc, Clauses, AStmt,
10409       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
10410 }
10411 
10412 /// Find and diagnose mutually exclusive clause kinds.
10413 static bool checkMutuallyExclusiveClauses(
10414     Sema &S, ArrayRef<OMPClause *> Clauses,
10415     ArrayRef<OpenMPClauseKind> MutuallyExclusiveClauses) {
10416   const OMPClause *PrevClause = nullptr;
10417   bool ErrorFound = false;
10418   for (const OMPClause *C : Clauses) {
10419     if (llvm::is_contained(MutuallyExclusiveClauses, C->getClauseKind())) {
10420       if (!PrevClause) {
10421         PrevClause = C;
10422       } else if (PrevClause->getClauseKind() != C->getClauseKind()) {
10423         S.Diag(C->getBeginLoc(), diag::err_omp_clauses_mutually_exclusive)
10424             << getOpenMPClauseName(C->getClauseKind())
10425             << getOpenMPClauseName(PrevClause->getClauseKind());
10426         S.Diag(PrevClause->getBeginLoc(), diag::note_omp_previous_clause)
10427             << getOpenMPClauseName(PrevClause->getClauseKind());
10428         ErrorFound = true;
10429       }
10430     }
10431   }
10432   return ErrorFound;
10433 }
10434 
10435 StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
10436                                           Stmt *AStmt, SourceLocation StartLoc,
10437                                           SourceLocation EndLoc) {
10438   if (!AStmt)
10439     return StmtError();
10440 
10441   // OpenMP 5.0, 2.10.1 task Construct
10442   // If a detach clause appears on the directive, then a mergeable clause cannot
10443   // appear on the same directive.
10444   if (checkMutuallyExclusiveClauses(*this, Clauses,
10445                                     {OMPC_detach, OMPC_mergeable}))
10446     return StmtError();
10447 
10448   auto *CS = cast<CapturedStmt>(AStmt);
10449   // 1.2.2 OpenMP Language Terminology
10450   // Structured block - An executable statement with a single entry at the
10451   // top and a single exit at the bottom.
10452   // The point of exit cannot be a branch out of the structured block.
10453   // longjmp() and throw() must not violate the entry/exit criteria.
10454   CS->getCapturedDecl()->setNothrow();
10455 
10456   setFunctionHasBranchProtectedScope();
10457 
10458   return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
10459                                   DSAStack->isCancelRegion());
10460 }
10461 
10462 StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
10463                                                SourceLocation EndLoc) {
10464   return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
10465 }
10466 
10467 StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
10468                                              SourceLocation EndLoc) {
10469   return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
10470 }
10471 
10472 StmtResult Sema::ActOnOpenMPTaskwaitDirective(ArrayRef<OMPClause *> Clauses,
10473                                               SourceLocation StartLoc,
10474                                               SourceLocation EndLoc) {
10475   return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc, Clauses);
10476 }
10477 
10478 StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
10479                                                Stmt *AStmt,
10480                                                SourceLocation StartLoc,
10481                                                SourceLocation EndLoc) {
10482   if (!AStmt)
10483     return StmtError();
10484 
10485   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
10486 
10487   setFunctionHasBranchProtectedScope();
10488 
10489   return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses,
10490                                        AStmt,
10491                                        DSAStack->getTaskgroupReductionRef());
10492 }
10493 
10494 StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
10495                                            SourceLocation StartLoc,
10496                                            SourceLocation EndLoc) {
10497   OMPFlushClause *FC = nullptr;
10498   OMPClause *OrderClause = nullptr;
10499   for (OMPClause *C : Clauses) {
10500     if (C->getClauseKind() == OMPC_flush)
10501       FC = cast<OMPFlushClause>(C);
10502     else
10503       OrderClause = C;
10504   }
10505   OpenMPClauseKind MemOrderKind = OMPC_unknown;
10506   SourceLocation MemOrderLoc;
10507   for (const OMPClause *C : Clauses) {
10508     if (C->getClauseKind() == OMPC_acq_rel ||
10509         C->getClauseKind() == OMPC_acquire ||
10510         C->getClauseKind() == OMPC_release) {
10511       if (MemOrderKind != OMPC_unknown) {
10512         Diag(C->getBeginLoc(), diag::err_omp_several_mem_order_clauses)
10513             << getOpenMPDirectiveName(OMPD_flush) << 1
10514             << SourceRange(C->getBeginLoc(), C->getEndLoc());
10515         Diag(MemOrderLoc, diag::note_omp_previous_mem_order_clause)
10516             << getOpenMPClauseName(MemOrderKind);
10517       } else {
10518         MemOrderKind = C->getClauseKind();
10519         MemOrderLoc = C->getBeginLoc();
10520       }
10521     }
10522   }
10523   if (FC && OrderClause) {
10524     Diag(FC->getLParenLoc(), diag::err_omp_flush_order_clause_and_list)
10525         << getOpenMPClauseName(OrderClause->getClauseKind());
10526     Diag(OrderClause->getBeginLoc(), diag::note_omp_flush_order_clause_here)
10527         << getOpenMPClauseName(OrderClause->getClauseKind());
10528     return StmtError();
10529   }
10530   return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
10531 }
10532 
10533 StmtResult Sema::ActOnOpenMPDepobjDirective(ArrayRef<OMPClause *> Clauses,
10534                                             SourceLocation StartLoc,
10535                                             SourceLocation EndLoc) {
10536   if (Clauses.empty()) {
10537     Diag(StartLoc, diag::err_omp_depobj_expected);
10538     return StmtError();
10539   } else if (Clauses[0]->getClauseKind() != OMPC_depobj) {
10540     Diag(Clauses[0]->getBeginLoc(), diag::err_omp_depobj_expected);
10541     return StmtError();
10542   }
10543   // Only depobj expression and another single clause is allowed.
10544   if (Clauses.size() > 2) {
10545     Diag(Clauses[2]->getBeginLoc(),
10546          diag::err_omp_depobj_single_clause_expected);
10547     return StmtError();
10548   } else if (Clauses.size() < 1) {
10549     Diag(Clauses[0]->getEndLoc(), diag::err_omp_depobj_single_clause_expected);
10550     return StmtError();
10551   }
10552   return OMPDepobjDirective::Create(Context, StartLoc, EndLoc, Clauses);
10553 }
10554 
10555 StmtResult Sema::ActOnOpenMPScanDirective(ArrayRef<OMPClause *> Clauses,
10556                                           SourceLocation StartLoc,
10557                                           SourceLocation EndLoc) {
10558   // Check that exactly one clause is specified.
10559   if (Clauses.size() != 1) {
10560     Diag(Clauses.empty() ? EndLoc : Clauses[1]->getBeginLoc(),
10561          diag::err_omp_scan_single_clause_expected);
10562     return StmtError();
10563   }
10564   // Check that scan directive is used in the scopeof the OpenMP loop body.
10565   if (Scope *S = DSAStack->getCurScope()) {
10566     Scope *ParentS = S->getParent();
10567     if (!ParentS || ParentS->getParent() != ParentS->getBreakParent() ||
10568         !ParentS->getBreakParent()->isOpenMPLoopScope())
10569       return StmtError(Diag(StartLoc, diag::err_omp_orphaned_device_directive)
10570                        << getOpenMPDirectiveName(OMPD_scan) << 5);
10571   }
10572   // Check that only one instance of scan directives is used in the same outer
10573   // region.
10574   if (DSAStack->doesParentHasScanDirective()) {
10575     Diag(StartLoc, diag::err_omp_several_directives_in_region) << "scan";
10576     Diag(DSAStack->getParentScanDirectiveLoc(),
10577          diag::note_omp_previous_directive)
10578         << "scan";
10579     return StmtError();
10580   }
10581   DSAStack->setParentHasScanDirective(StartLoc);
10582   return OMPScanDirective::Create(Context, StartLoc, EndLoc, Clauses);
10583 }
10584 
10585 StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
10586                                              Stmt *AStmt,
10587                                              SourceLocation StartLoc,
10588                                              SourceLocation EndLoc) {
10589   const OMPClause *DependFound = nullptr;
10590   const OMPClause *DependSourceClause = nullptr;
10591   const OMPClause *DependSinkClause = nullptr;
10592   bool ErrorFound = false;
10593   const OMPThreadsClause *TC = nullptr;
10594   const OMPSIMDClause *SC = nullptr;
10595   for (const OMPClause *C : Clauses) {
10596     if (auto *DC = dyn_cast<OMPDependClause>(C)) {
10597       DependFound = C;
10598       if (DC->getDependencyKind() == OMPC_DEPEND_source) {
10599         if (DependSourceClause) {
10600           Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
10601               << getOpenMPDirectiveName(OMPD_ordered)
10602               << getOpenMPClauseName(OMPC_depend) << 2;
10603           ErrorFound = true;
10604         } else {
10605           DependSourceClause = C;
10606         }
10607         if (DependSinkClause) {
10608           Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
10609               << 0;
10610           ErrorFound = true;
10611         }
10612       } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
10613         if (DependSourceClause) {
10614           Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
10615               << 1;
10616           ErrorFound = true;
10617         }
10618         DependSinkClause = C;
10619       }
10620     } else if (C->getClauseKind() == OMPC_threads) {
10621       TC = cast<OMPThreadsClause>(C);
10622     } else if (C->getClauseKind() == OMPC_simd) {
10623       SC = cast<OMPSIMDClause>(C);
10624     }
10625   }
10626   if (!ErrorFound && !SC &&
10627       isOpenMPSimdDirective(DSAStack->getParentDirective())) {
10628     // OpenMP [2.8.1,simd Construct, Restrictions]
10629     // An ordered construct with the simd clause is the only OpenMP construct
10630     // that can appear in the simd region.
10631     Diag(StartLoc, diag::err_omp_prohibited_region_simd)
10632         << (LangOpts.OpenMP >= 50 ? 1 : 0);
10633     ErrorFound = true;
10634   } else if (DependFound && (TC || SC)) {
10635     Diag(DependFound->getBeginLoc(), diag::err_omp_depend_clause_thread_simd)
10636         << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
10637     ErrorFound = true;
10638   } else if (DependFound && !DSAStack->getParentOrderedRegionParam().first) {
10639     Diag(DependFound->getBeginLoc(),
10640          diag::err_omp_ordered_directive_without_param);
10641     ErrorFound = true;
10642   } else if (TC || Clauses.empty()) {
10643     if (const Expr *Param = DSAStack->getParentOrderedRegionParam().first) {
10644       SourceLocation ErrLoc = TC ? TC->getBeginLoc() : StartLoc;
10645       Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
10646           << (TC != nullptr);
10647       Diag(Param->getBeginLoc(), diag::note_omp_ordered_param) << 1;
10648       ErrorFound = true;
10649     }
10650   }
10651   if ((!AStmt && !DependFound) || ErrorFound)
10652     return StmtError();
10653 
10654   // OpenMP 5.0, 2.17.9, ordered Construct, Restrictions.
10655   // During execution of an iteration of a worksharing-loop or a loop nest
10656   // within a worksharing-loop, simd, or worksharing-loop SIMD region, a thread
10657   // must not execute more than one ordered region corresponding to an ordered
10658   // construct without a depend clause.
10659   if (!DependFound) {
10660     if (DSAStack->doesParentHasOrderedDirective()) {
10661       Diag(StartLoc, diag::err_omp_several_directives_in_region) << "ordered";
10662       Diag(DSAStack->getParentOrderedDirectiveLoc(),
10663            diag::note_omp_previous_directive)
10664           << "ordered";
10665       return StmtError();
10666     }
10667     DSAStack->setParentHasOrderedDirective(StartLoc);
10668   }
10669 
10670   if (AStmt) {
10671     assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
10672 
10673     setFunctionHasBranchProtectedScope();
10674   }
10675 
10676   return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
10677 }
10678 
10679 namespace {
10680 /// Helper class for checking expression in 'omp atomic [update]'
10681 /// construct.
10682 class OpenMPAtomicUpdateChecker {
10683   /// Error results for atomic update expressions.
10684   enum ExprAnalysisErrorCode {
10685     /// A statement is not an expression statement.
10686     NotAnExpression,
10687     /// Expression is not builtin binary or unary operation.
10688     NotABinaryOrUnaryExpression,
10689     /// Unary operation is not post-/pre- increment/decrement operation.
10690     NotAnUnaryIncDecExpression,
10691     /// An expression is not of scalar type.
10692     NotAScalarType,
10693     /// A binary operation is not an assignment operation.
10694     NotAnAssignmentOp,
10695     /// RHS part of the binary operation is not a binary expression.
10696     NotABinaryExpression,
10697     /// RHS part is not additive/multiplicative/shift/biwise binary
10698     /// expression.
10699     NotABinaryOperator,
10700     /// RHS binary operation does not have reference to the updated LHS
10701     /// part.
10702     NotAnUpdateExpression,
10703     /// No errors is found.
10704     NoError
10705   };
10706   /// Reference to Sema.
10707   Sema &SemaRef;
10708   /// A location for note diagnostics (when error is found).
10709   SourceLocation NoteLoc;
10710   /// 'x' lvalue part of the source atomic expression.
10711   Expr *X;
10712   /// 'expr' rvalue part of the source atomic expression.
10713   Expr *E;
10714   /// Helper expression of the form
10715   /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
10716   /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
10717   Expr *UpdateExpr;
10718   /// Is 'x' a LHS in a RHS part of full update expression. It is
10719   /// important for non-associative operations.
10720   bool IsXLHSInRHSPart;
10721   BinaryOperatorKind Op;
10722   SourceLocation OpLoc;
10723   /// true if the source expression is a postfix unary operation, false
10724   /// if it is a prefix unary operation.
10725   bool IsPostfixUpdate;
10726 
10727 public:
10728   OpenMPAtomicUpdateChecker(Sema &SemaRef)
10729       : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
10730         IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
10731   /// Check specified statement that it is suitable for 'atomic update'
10732   /// constructs and extract 'x', 'expr' and Operation from the original
10733   /// expression. If DiagId and NoteId == 0, then only check is performed
10734   /// without error notification.
10735   /// \param DiagId Diagnostic which should be emitted if error is found.
10736   /// \param NoteId Diagnostic note for the main error message.
10737   /// \return true if statement is not an update expression, false otherwise.
10738   bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
10739   /// Return the 'x' lvalue part of the source atomic expression.
10740   Expr *getX() const { return X; }
10741   /// Return the 'expr' rvalue part of the source atomic expression.
10742   Expr *getExpr() const { return E; }
10743   /// Return the update expression used in calculation of the updated
10744   /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
10745   /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
10746   Expr *getUpdateExpr() const { return UpdateExpr; }
10747   /// Return true if 'x' is LHS in RHS part of full update expression,
10748   /// false otherwise.
10749   bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
10750 
10751   /// true if the source expression is a postfix unary operation, false
10752   /// if it is a prefix unary operation.
10753   bool isPostfixUpdate() const { return IsPostfixUpdate; }
10754 
10755 private:
10756   bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
10757                             unsigned NoteId = 0);
10758 };
10759 
10760 bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
10761     BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
10762   ExprAnalysisErrorCode ErrorFound = NoError;
10763   SourceLocation ErrorLoc, NoteLoc;
10764   SourceRange ErrorRange, NoteRange;
10765   // Allowed constructs are:
10766   //  x = x binop expr;
10767   //  x = expr binop x;
10768   if (AtomicBinOp->getOpcode() == BO_Assign) {
10769     X = AtomicBinOp->getLHS();
10770     if (const auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
10771             AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
10772       if (AtomicInnerBinOp->isMultiplicativeOp() ||
10773           AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
10774           AtomicInnerBinOp->isBitwiseOp()) {
10775         Op = AtomicInnerBinOp->getOpcode();
10776         OpLoc = AtomicInnerBinOp->getOperatorLoc();
10777         Expr *LHS = AtomicInnerBinOp->getLHS();
10778         Expr *RHS = AtomicInnerBinOp->getRHS();
10779         llvm::FoldingSetNodeID XId, LHSId, RHSId;
10780         X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
10781                                           /*Canonical=*/true);
10782         LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
10783                                             /*Canonical=*/true);
10784         RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
10785                                             /*Canonical=*/true);
10786         if (XId == LHSId) {
10787           E = RHS;
10788           IsXLHSInRHSPart = true;
10789         } else if (XId == RHSId) {
10790           E = LHS;
10791           IsXLHSInRHSPart = false;
10792         } else {
10793           ErrorLoc = AtomicInnerBinOp->getExprLoc();
10794           ErrorRange = AtomicInnerBinOp->getSourceRange();
10795           NoteLoc = X->getExprLoc();
10796           NoteRange = X->getSourceRange();
10797           ErrorFound = NotAnUpdateExpression;
10798         }
10799       } else {
10800         ErrorLoc = AtomicInnerBinOp->getExprLoc();
10801         ErrorRange = AtomicInnerBinOp->getSourceRange();
10802         NoteLoc = AtomicInnerBinOp->getOperatorLoc();
10803         NoteRange = SourceRange(NoteLoc, NoteLoc);
10804         ErrorFound = NotABinaryOperator;
10805       }
10806     } else {
10807       NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
10808       NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
10809       ErrorFound = NotABinaryExpression;
10810     }
10811   } else {
10812     ErrorLoc = AtomicBinOp->getExprLoc();
10813     ErrorRange = AtomicBinOp->getSourceRange();
10814     NoteLoc = AtomicBinOp->getOperatorLoc();
10815     NoteRange = SourceRange(NoteLoc, NoteLoc);
10816     ErrorFound = NotAnAssignmentOp;
10817   }
10818   if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
10819     SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
10820     SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
10821     return true;
10822   }
10823   if (SemaRef.CurContext->isDependentContext())
10824     E = X = UpdateExpr = nullptr;
10825   return ErrorFound != NoError;
10826 }
10827 
10828 bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
10829                                                unsigned NoteId) {
10830   ExprAnalysisErrorCode ErrorFound = NoError;
10831   SourceLocation ErrorLoc, NoteLoc;
10832   SourceRange ErrorRange, NoteRange;
10833   // Allowed constructs are:
10834   //  x++;
10835   //  x--;
10836   //  ++x;
10837   //  --x;
10838   //  x binop= expr;
10839   //  x = x binop expr;
10840   //  x = expr binop x;
10841   if (auto *AtomicBody = dyn_cast<Expr>(S)) {
10842     AtomicBody = AtomicBody->IgnoreParenImpCasts();
10843     if (AtomicBody->getType()->isScalarType() ||
10844         AtomicBody->isInstantiationDependent()) {
10845       if (const auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
10846               AtomicBody->IgnoreParenImpCasts())) {
10847         // Check for Compound Assignment Operation
10848         Op = BinaryOperator::getOpForCompoundAssignment(
10849             AtomicCompAssignOp->getOpcode());
10850         OpLoc = AtomicCompAssignOp->getOperatorLoc();
10851         E = AtomicCompAssignOp->getRHS();
10852         X = AtomicCompAssignOp->getLHS()->IgnoreParens();
10853         IsXLHSInRHSPart = true;
10854       } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
10855                      AtomicBody->IgnoreParenImpCasts())) {
10856         // Check for Binary Operation
10857         if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
10858           return true;
10859       } else if (const auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
10860                      AtomicBody->IgnoreParenImpCasts())) {
10861         // Check for Unary Operation
10862         if (AtomicUnaryOp->isIncrementDecrementOp()) {
10863           IsPostfixUpdate = AtomicUnaryOp->isPostfix();
10864           Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
10865           OpLoc = AtomicUnaryOp->getOperatorLoc();
10866           X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
10867           E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
10868           IsXLHSInRHSPart = true;
10869         } else {
10870           ErrorFound = NotAnUnaryIncDecExpression;
10871           ErrorLoc = AtomicUnaryOp->getExprLoc();
10872           ErrorRange = AtomicUnaryOp->getSourceRange();
10873           NoteLoc = AtomicUnaryOp->getOperatorLoc();
10874           NoteRange = SourceRange(NoteLoc, NoteLoc);
10875         }
10876       } else if (!AtomicBody->isInstantiationDependent()) {
10877         ErrorFound = NotABinaryOrUnaryExpression;
10878         NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
10879         NoteRange = ErrorRange = AtomicBody->getSourceRange();
10880       }
10881     } else {
10882       ErrorFound = NotAScalarType;
10883       NoteLoc = ErrorLoc = AtomicBody->getBeginLoc();
10884       NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
10885     }
10886   } else {
10887     ErrorFound = NotAnExpression;
10888     NoteLoc = ErrorLoc = S->getBeginLoc();
10889     NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
10890   }
10891   if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
10892     SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
10893     SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
10894     return true;
10895   }
10896   if (SemaRef.CurContext->isDependentContext())
10897     E = X = UpdateExpr = nullptr;
10898   if (ErrorFound == NoError && E && X) {
10899     // Build an update expression of form 'OpaqueValueExpr(x) binop
10900     // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
10901     // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
10902     auto *OVEX = new (SemaRef.getASTContext())
10903         OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_PRValue);
10904     auto *OVEExpr = new (SemaRef.getASTContext())
10905         OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_PRValue);
10906     ExprResult Update =
10907         SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
10908                                    IsXLHSInRHSPart ? OVEExpr : OVEX);
10909     if (Update.isInvalid())
10910       return true;
10911     Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
10912                                                Sema::AA_Casting);
10913     if (Update.isInvalid())
10914       return true;
10915     UpdateExpr = Update.get();
10916   }
10917   return ErrorFound != NoError;
10918 }
10919 } // namespace
10920 
10921 StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
10922                                             Stmt *AStmt,
10923                                             SourceLocation StartLoc,
10924                                             SourceLocation EndLoc) {
10925   // Register location of the first atomic directive.
10926   DSAStack->addAtomicDirectiveLoc(StartLoc);
10927   if (!AStmt)
10928     return StmtError();
10929 
10930   // 1.2.2 OpenMP Language Terminology
10931   // Structured block - An executable statement with a single entry at the
10932   // top and a single exit at the bottom.
10933   // The point of exit cannot be a branch out of the structured block.
10934   // longjmp() and throw() must not violate the entry/exit criteria.
10935   OpenMPClauseKind AtomicKind = OMPC_unknown;
10936   SourceLocation AtomicKindLoc;
10937   OpenMPClauseKind MemOrderKind = OMPC_unknown;
10938   SourceLocation MemOrderLoc;
10939   for (const OMPClause *C : Clauses) {
10940     switch (C->getClauseKind()) {
10941     case OMPC_read:
10942     case OMPC_write:
10943     case OMPC_update:
10944     case OMPC_capture:
10945     case OMPC_compare: {
10946       if (AtomicKind != OMPC_unknown) {
10947         Diag(C->getBeginLoc(), diag::err_omp_atomic_several_clauses)
10948             << SourceRange(C->getBeginLoc(), C->getEndLoc());
10949         Diag(AtomicKindLoc, diag::note_omp_previous_mem_order_clause)
10950             << getOpenMPClauseName(AtomicKind);
10951       } else {
10952         AtomicKind = C->getClauseKind();
10953         AtomicKindLoc = C->getBeginLoc();
10954       }
10955       break;
10956     }
10957     case OMPC_seq_cst:
10958     case OMPC_acq_rel:
10959     case OMPC_acquire:
10960     case OMPC_release:
10961     case OMPC_relaxed: {
10962       if (MemOrderKind != OMPC_unknown) {
10963         Diag(C->getBeginLoc(), diag::err_omp_several_mem_order_clauses)
10964             << getOpenMPDirectiveName(OMPD_atomic) << 0
10965             << SourceRange(C->getBeginLoc(), C->getEndLoc());
10966         Diag(MemOrderLoc, diag::note_omp_previous_mem_order_clause)
10967             << getOpenMPClauseName(MemOrderKind);
10968       } else {
10969         MemOrderKind = C->getClauseKind();
10970         MemOrderLoc = C->getBeginLoc();
10971       }
10972       break;
10973     }
10974     // The following clauses are allowed, but we don't need to do anything here.
10975     case OMPC_hint:
10976       break;
10977     default:
10978       llvm_unreachable("unknown clause is encountered");
10979     }
10980   }
10981   // OpenMP 5.0, 2.17.7 atomic Construct, Restrictions
10982   // If atomic-clause is read then memory-order-clause must not be acq_rel or
10983   // release.
10984   // If atomic-clause is write then memory-order-clause must not be acq_rel or
10985   // acquire.
10986   // If atomic-clause is update or not present then memory-order-clause must not
10987   // be acq_rel or acquire.
10988   if ((AtomicKind == OMPC_read &&
10989        (MemOrderKind == OMPC_acq_rel || MemOrderKind == OMPC_release)) ||
10990       ((AtomicKind == OMPC_write || AtomicKind == OMPC_update ||
10991         AtomicKind == OMPC_unknown) &&
10992        (MemOrderKind == OMPC_acq_rel || MemOrderKind == OMPC_acquire))) {
10993     SourceLocation Loc = AtomicKindLoc;
10994     if (AtomicKind == OMPC_unknown)
10995       Loc = StartLoc;
10996     Diag(Loc, diag::err_omp_atomic_incompatible_mem_order_clause)
10997         << getOpenMPClauseName(AtomicKind)
10998         << (AtomicKind == OMPC_unknown ? 1 : 0)
10999         << getOpenMPClauseName(MemOrderKind);
11000     Diag(MemOrderLoc, diag::note_omp_previous_mem_order_clause)
11001         << getOpenMPClauseName(MemOrderKind);
11002   }
11003 
11004   Stmt *Body = AStmt;
11005   if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
11006     Body = EWC->getSubExpr();
11007 
11008   Expr *X = nullptr;
11009   Expr *V = nullptr;
11010   Expr *E = nullptr;
11011   Expr *UE = nullptr;
11012   bool IsXLHSInRHSPart = false;
11013   bool IsPostfixUpdate = false;
11014   // OpenMP [2.12.6, atomic Construct]
11015   // In the next expressions:
11016   // * x and v (as applicable) are both l-value expressions with scalar type.
11017   // * During the execution of an atomic region, multiple syntactic
11018   // occurrences of x must designate the same storage location.
11019   // * Neither of v and expr (as applicable) may access the storage location
11020   // designated by x.
11021   // * Neither of x and expr (as applicable) may access the storage location
11022   // designated by v.
11023   // * expr is an expression with scalar type.
11024   // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
11025   // * binop, binop=, ++, and -- are not overloaded operators.
11026   // * The expression x binop expr must be numerically equivalent to x binop
11027   // (expr). This requirement is satisfied if the operators in expr have
11028   // precedence greater than binop, or by using parentheses around expr or
11029   // subexpressions of expr.
11030   // * The expression expr binop x must be numerically equivalent to (expr)
11031   // binop x. This requirement is satisfied if the operators in expr have
11032   // precedence equal to or greater than binop, or by using parentheses around
11033   // expr or subexpressions of expr.
11034   // * For forms that allow multiple occurrences of x, the number of times
11035   // that x is evaluated is unspecified.
11036   if (AtomicKind == OMPC_read) {
11037     enum {
11038       NotAnExpression,
11039       NotAnAssignmentOp,
11040       NotAScalarType,
11041       NotAnLValue,
11042       NoError
11043     } ErrorFound = NoError;
11044     SourceLocation ErrorLoc, NoteLoc;
11045     SourceRange ErrorRange, NoteRange;
11046     // If clause is read:
11047     //  v = x;
11048     if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
11049       const auto *AtomicBinOp =
11050           dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
11051       if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
11052         X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
11053         V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
11054         if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
11055             (V->isInstantiationDependent() || V->getType()->isScalarType())) {
11056           if (!X->isLValue() || !V->isLValue()) {
11057             const Expr *NotLValueExpr = X->isLValue() ? V : X;
11058             ErrorFound = NotAnLValue;
11059             ErrorLoc = AtomicBinOp->getExprLoc();
11060             ErrorRange = AtomicBinOp->getSourceRange();
11061             NoteLoc = NotLValueExpr->getExprLoc();
11062             NoteRange = NotLValueExpr->getSourceRange();
11063           }
11064         } else if (!X->isInstantiationDependent() ||
11065                    !V->isInstantiationDependent()) {
11066           const Expr *NotScalarExpr =
11067               (X->isInstantiationDependent() || X->getType()->isScalarType())
11068                   ? V
11069                   : X;
11070           ErrorFound = NotAScalarType;
11071           ErrorLoc = AtomicBinOp->getExprLoc();
11072           ErrorRange = AtomicBinOp->getSourceRange();
11073           NoteLoc = NotScalarExpr->getExprLoc();
11074           NoteRange = NotScalarExpr->getSourceRange();
11075         }
11076       } else if (!AtomicBody->isInstantiationDependent()) {
11077         ErrorFound = NotAnAssignmentOp;
11078         ErrorLoc = AtomicBody->getExprLoc();
11079         ErrorRange = AtomicBody->getSourceRange();
11080         NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
11081                               : AtomicBody->getExprLoc();
11082         NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
11083                                 : AtomicBody->getSourceRange();
11084       }
11085     } else {
11086       ErrorFound = NotAnExpression;
11087       NoteLoc = ErrorLoc = Body->getBeginLoc();
11088       NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
11089     }
11090     if (ErrorFound != NoError) {
11091       Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
11092           << ErrorRange;
11093       Diag(NoteLoc, diag::note_omp_atomic_read_write)
11094           << ErrorFound << NoteRange;
11095       return StmtError();
11096     }
11097     if (CurContext->isDependentContext())
11098       V = X = nullptr;
11099   } else if (AtomicKind == OMPC_write) {
11100     enum {
11101       NotAnExpression,
11102       NotAnAssignmentOp,
11103       NotAScalarType,
11104       NotAnLValue,
11105       NoError
11106     } ErrorFound = NoError;
11107     SourceLocation ErrorLoc, NoteLoc;
11108     SourceRange ErrorRange, NoteRange;
11109     // If clause is write:
11110     //  x = expr;
11111     if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
11112       const auto *AtomicBinOp =
11113           dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
11114       if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
11115         X = AtomicBinOp->getLHS();
11116         E = AtomicBinOp->getRHS();
11117         if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
11118             (E->isInstantiationDependent() || E->getType()->isScalarType())) {
11119           if (!X->isLValue()) {
11120             ErrorFound = NotAnLValue;
11121             ErrorLoc = AtomicBinOp->getExprLoc();
11122             ErrorRange = AtomicBinOp->getSourceRange();
11123             NoteLoc = X->getExprLoc();
11124             NoteRange = X->getSourceRange();
11125           }
11126         } else if (!X->isInstantiationDependent() ||
11127                    !E->isInstantiationDependent()) {
11128           const Expr *NotScalarExpr =
11129               (X->isInstantiationDependent() || X->getType()->isScalarType())
11130                   ? E
11131                   : X;
11132           ErrorFound = NotAScalarType;
11133           ErrorLoc = AtomicBinOp->getExprLoc();
11134           ErrorRange = AtomicBinOp->getSourceRange();
11135           NoteLoc = NotScalarExpr->getExprLoc();
11136           NoteRange = NotScalarExpr->getSourceRange();
11137         }
11138       } else if (!AtomicBody->isInstantiationDependent()) {
11139         ErrorFound = NotAnAssignmentOp;
11140         ErrorLoc = AtomicBody->getExprLoc();
11141         ErrorRange = AtomicBody->getSourceRange();
11142         NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
11143                               : AtomicBody->getExprLoc();
11144         NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
11145                                 : AtomicBody->getSourceRange();
11146       }
11147     } else {
11148       ErrorFound = NotAnExpression;
11149       NoteLoc = ErrorLoc = Body->getBeginLoc();
11150       NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
11151     }
11152     if (ErrorFound != NoError) {
11153       Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
11154           << ErrorRange;
11155       Diag(NoteLoc, diag::note_omp_atomic_read_write)
11156           << ErrorFound << NoteRange;
11157       return StmtError();
11158     }
11159     if (CurContext->isDependentContext())
11160       E = X = nullptr;
11161   } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
11162     // If clause is update:
11163     //  x++;
11164     //  x--;
11165     //  ++x;
11166     //  --x;
11167     //  x binop= expr;
11168     //  x = x binop expr;
11169     //  x = expr binop x;
11170     OpenMPAtomicUpdateChecker Checker(*this);
11171     if (Checker.checkStatement(
11172             Body,
11173             (AtomicKind == OMPC_update)
11174                 ? diag::err_omp_atomic_update_not_expression_statement
11175                 : diag::err_omp_atomic_not_expression_statement,
11176             diag::note_omp_atomic_update))
11177       return StmtError();
11178     if (!CurContext->isDependentContext()) {
11179       E = Checker.getExpr();
11180       X = Checker.getX();
11181       UE = Checker.getUpdateExpr();
11182       IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
11183     }
11184   } else if (AtomicKind == OMPC_capture) {
11185     enum {
11186       NotAnAssignmentOp,
11187       NotACompoundStatement,
11188       NotTwoSubstatements,
11189       NotASpecificExpression,
11190       NoError
11191     } ErrorFound = NoError;
11192     SourceLocation ErrorLoc, NoteLoc;
11193     SourceRange ErrorRange, NoteRange;
11194     if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
11195       // If clause is a capture:
11196       //  v = x++;
11197       //  v = x--;
11198       //  v = ++x;
11199       //  v = --x;
11200       //  v = x binop= expr;
11201       //  v = x = x binop expr;
11202       //  v = x = expr binop x;
11203       const auto *AtomicBinOp =
11204           dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
11205       if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
11206         V = AtomicBinOp->getLHS();
11207         Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
11208         OpenMPAtomicUpdateChecker Checker(*this);
11209         if (Checker.checkStatement(
11210                 Body, diag::err_omp_atomic_capture_not_expression_statement,
11211                 diag::note_omp_atomic_update))
11212           return StmtError();
11213         E = Checker.getExpr();
11214         X = Checker.getX();
11215         UE = Checker.getUpdateExpr();
11216         IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
11217         IsPostfixUpdate = Checker.isPostfixUpdate();
11218       } else if (!AtomicBody->isInstantiationDependent()) {
11219         ErrorLoc = AtomicBody->getExprLoc();
11220         ErrorRange = AtomicBody->getSourceRange();
11221         NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
11222                               : AtomicBody->getExprLoc();
11223         NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
11224                                 : AtomicBody->getSourceRange();
11225         ErrorFound = NotAnAssignmentOp;
11226       }
11227       if (ErrorFound != NoError) {
11228         Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
11229             << ErrorRange;
11230         Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
11231         return StmtError();
11232       }
11233       if (CurContext->isDependentContext())
11234         UE = V = E = X = nullptr;
11235     } else {
11236       // If clause is a capture:
11237       //  { v = x; x = expr; }
11238       //  { v = x; x++; }
11239       //  { v = x; x--; }
11240       //  { v = x; ++x; }
11241       //  { v = x; --x; }
11242       //  { v = x; x binop= expr; }
11243       //  { v = x; x = x binop expr; }
11244       //  { v = x; x = expr binop x; }
11245       //  { x++; v = x; }
11246       //  { x--; v = x; }
11247       //  { ++x; v = x; }
11248       //  { --x; v = x; }
11249       //  { x binop= expr; v = x; }
11250       //  { x = x binop expr; v = x; }
11251       //  { x = expr binop x; v = x; }
11252       if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
11253         // Check that this is { expr1; expr2; }
11254         if (CS->size() == 2) {
11255           Stmt *First = CS->body_front();
11256           Stmt *Second = CS->body_back();
11257           if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
11258             First = EWC->getSubExpr()->IgnoreParenImpCasts();
11259           if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
11260             Second = EWC->getSubExpr()->IgnoreParenImpCasts();
11261           // Need to find what subexpression is 'v' and what is 'x'.
11262           OpenMPAtomicUpdateChecker Checker(*this);
11263           bool IsUpdateExprFound = !Checker.checkStatement(Second);
11264           BinaryOperator *BinOp = nullptr;
11265           if (IsUpdateExprFound) {
11266             BinOp = dyn_cast<BinaryOperator>(First);
11267             IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
11268           }
11269           if (IsUpdateExprFound && !CurContext->isDependentContext()) {
11270             //  { v = x; x++; }
11271             //  { v = x; x--; }
11272             //  { v = x; ++x; }
11273             //  { v = x; --x; }
11274             //  { v = x; x binop= expr; }
11275             //  { v = x; x = x binop expr; }
11276             //  { v = x; x = expr binop x; }
11277             // Check that the first expression has form v = x.
11278             Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
11279             llvm::FoldingSetNodeID XId, PossibleXId;
11280             Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
11281             PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
11282             IsUpdateExprFound = XId == PossibleXId;
11283             if (IsUpdateExprFound) {
11284               V = BinOp->getLHS();
11285               X = Checker.getX();
11286               E = Checker.getExpr();
11287               UE = Checker.getUpdateExpr();
11288               IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
11289               IsPostfixUpdate = true;
11290             }
11291           }
11292           if (!IsUpdateExprFound) {
11293             IsUpdateExprFound = !Checker.checkStatement(First);
11294             BinOp = nullptr;
11295             if (IsUpdateExprFound) {
11296               BinOp = dyn_cast<BinaryOperator>(Second);
11297               IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
11298             }
11299             if (IsUpdateExprFound && !CurContext->isDependentContext()) {
11300               //  { x++; v = x; }
11301               //  { x--; v = x; }
11302               //  { ++x; v = x; }
11303               //  { --x; v = x; }
11304               //  { x binop= expr; v = x; }
11305               //  { x = x binop expr; v = x; }
11306               //  { x = expr binop x; v = x; }
11307               // Check that the second expression has form v = x.
11308               Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
11309               llvm::FoldingSetNodeID XId, PossibleXId;
11310               Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
11311               PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
11312               IsUpdateExprFound = XId == PossibleXId;
11313               if (IsUpdateExprFound) {
11314                 V = BinOp->getLHS();
11315                 X = Checker.getX();
11316                 E = Checker.getExpr();
11317                 UE = Checker.getUpdateExpr();
11318                 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
11319                 IsPostfixUpdate = false;
11320               }
11321             }
11322           }
11323           if (!IsUpdateExprFound) {
11324             //  { v = x; x = expr; }
11325             auto *FirstExpr = dyn_cast<Expr>(First);
11326             auto *SecondExpr = dyn_cast<Expr>(Second);
11327             if (!FirstExpr || !SecondExpr ||
11328                 !(FirstExpr->isInstantiationDependent() ||
11329                   SecondExpr->isInstantiationDependent())) {
11330               auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
11331               if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
11332                 ErrorFound = NotAnAssignmentOp;
11333                 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
11334                                                 : First->getBeginLoc();
11335                 NoteRange = ErrorRange = FirstBinOp
11336                                              ? FirstBinOp->getSourceRange()
11337                                              : SourceRange(ErrorLoc, ErrorLoc);
11338               } else {
11339                 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
11340                 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
11341                   ErrorFound = NotAnAssignmentOp;
11342                   NoteLoc = ErrorLoc = SecondBinOp
11343                                            ? SecondBinOp->getOperatorLoc()
11344                                            : Second->getBeginLoc();
11345                   NoteRange = ErrorRange =
11346                       SecondBinOp ? SecondBinOp->getSourceRange()
11347                                   : SourceRange(ErrorLoc, ErrorLoc);
11348                 } else {
11349                   Expr *PossibleXRHSInFirst =
11350                       FirstBinOp->getRHS()->IgnoreParenImpCasts();
11351                   Expr *PossibleXLHSInSecond =
11352                       SecondBinOp->getLHS()->IgnoreParenImpCasts();
11353                   llvm::FoldingSetNodeID X1Id, X2Id;
11354                   PossibleXRHSInFirst->Profile(X1Id, Context,
11355                                                /*Canonical=*/true);
11356                   PossibleXLHSInSecond->Profile(X2Id, Context,
11357                                                 /*Canonical=*/true);
11358                   IsUpdateExprFound = X1Id == X2Id;
11359                   if (IsUpdateExprFound) {
11360                     V = FirstBinOp->getLHS();
11361                     X = SecondBinOp->getLHS();
11362                     E = SecondBinOp->getRHS();
11363                     UE = nullptr;
11364                     IsXLHSInRHSPart = false;
11365                     IsPostfixUpdate = true;
11366                   } else {
11367                     ErrorFound = NotASpecificExpression;
11368                     ErrorLoc = FirstBinOp->getExprLoc();
11369                     ErrorRange = FirstBinOp->getSourceRange();
11370                     NoteLoc = SecondBinOp->getLHS()->getExprLoc();
11371                     NoteRange = SecondBinOp->getRHS()->getSourceRange();
11372                   }
11373                 }
11374               }
11375             }
11376           }
11377         } else {
11378           NoteLoc = ErrorLoc = Body->getBeginLoc();
11379           NoteRange = ErrorRange =
11380               SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
11381           ErrorFound = NotTwoSubstatements;
11382         }
11383       } else {
11384         NoteLoc = ErrorLoc = Body->getBeginLoc();
11385         NoteRange = ErrorRange =
11386             SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
11387         ErrorFound = NotACompoundStatement;
11388       }
11389     }
11390     if (ErrorFound != NoError) {
11391       Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
11392           << ErrorRange;
11393       Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
11394       return StmtError();
11395     }
11396     if (CurContext->isDependentContext())
11397       UE = V = E = X = nullptr;
11398   } else if (AtomicKind == OMPC_compare) {
11399     // TODO: For now we emit an error here and in emitOMPAtomicExpr we ignore
11400     // code gen.
11401     unsigned DiagID = Diags.getCustomDiagID(
11402         DiagnosticsEngine::Error, "atomic compare is not supported for now");
11403     Diag(AtomicKindLoc, DiagID);
11404   }
11405 
11406   setFunctionHasBranchProtectedScope();
11407 
11408   return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
11409                                     X, V, E, UE, IsXLHSInRHSPart,
11410                                     IsPostfixUpdate);
11411 }
11412 
11413 StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
11414                                             Stmt *AStmt,
11415                                             SourceLocation StartLoc,
11416                                             SourceLocation EndLoc) {
11417   if (!AStmt)
11418     return StmtError();
11419 
11420   auto *CS = cast<CapturedStmt>(AStmt);
11421   // 1.2.2 OpenMP Language Terminology
11422   // Structured block - An executable statement with a single entry at the
11423   // top and a single exit at the bottom.
11424   // The point of exit cannot be a branch out of the structured block.
11425   // longjmp() and throw() must not violate the entry/exit criteria.
11426   CS->getCapturedDecl()->setNothrow();
11427   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target);
11428        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11429     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11430     // 1.2.2 OpenMP Language Terminology
11431     // Structured block - An executable statement with a single entry at the
11432     // top and a single exit at the bottom.
11433     // The point of exit cannot be a branch out of the structured block.
11434     // longjmp() and throw() must not violate the entry/exit criteria.
11435     CS->getCapturedDecl()->setNothrow();
11436   }
11437 
11438   // OpenMP [2.16, Nesting of Regions]
11439   // If specified, a teams construct must be contained within a target
11440   // construct. That target construct must contain no statements or directives
11441   // outside of the teams construct.
11442   if (DSAStack->hasInnerTeamsRegion()) {
11443     const Stmt *S = CS->IgnoreContainers(/*IgnoreCaptured=*/true);
11444     bool OMPTeamsFound = true;
11445     if (const auto *CS = dyn_cast<CompoundStmt>(S)) {
11446       auto I = CS->body_begin();
11447       while (I != CS->body_end()) {
11448         const auto *OED = dyn_cast<OMPExecutableDirective>(*I);
11449         if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind()) ||
11450             OMPTeamsFound) {
11451 
11452           OMPTeamsFound = false;
11453           break;
11454         }
11455         ++I;
11456       }
11457       assert(I != CS->body_end() && "Not found statement");
11458       S = *I;
11459     } else {
11460       const auto *OED = dyn_cast<OMPExecutableDirective>(S);
11461       OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
11462     }
11463     if (!OMPTeamsFound) {
11464       Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
11465       Diag(DSAStack->getInnerTeamsRegionLoc(),
11466            diag::note_omp_nested_teams_construct_here);
11467       Diag(S->getBeginLoc(), diag::note_omp_nested_statement_here)
11468           << isa<OMPExecutableDirective>(S);
11469       return StmtError();
11470     }
11471   }
11472 
11473   setFunctionHasBranchProtectedScope();
11474 
11475   return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
11476 }
11477 
11478 StmtResult
11479 Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
11480                                          Stmt *AStmt, SourceLocation StartLoc,
11481                                          SourceLocation EndLoc) {
11482   if (!AStmt)
11483     return StmtError();
11484 
11485   auto *CS = cast<CapturedStmt>(AStmt);
11486   // 1.2.2 OpenMP Language Terminology
11487   // Structured block - An executable statement with a single entry at the
11488   // top and a single exit at the bottom.
11489   // The point of exit cannot be a branch out of the structured block.
11490   // longjmp() and throw() must not violate the entry/exit criteria.
11491   CS->getCapturedDecl()->setNothrow();
11492   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel);
11493        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11494     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11495     // 1.2.2 OpenMP Language Terminology
11496     // Structured block - An executable statement with a single entry at the
11497     // top and a single exit at the bottom.
11498     // The point of exit cannot be a branch out of the structured block.
11499     // longjmp() and throw() must not violate the entry/exit criteria.
11500     CS->getCapturedDecl()->setNothrow();
11501   }
11502 
11503   setFunctionHasBranchProtectedScope();
11504 
11505   return OMPTargetParallelDirective::Create(
11506       Context, StartLoc, EndLoc, Clauses, AStmt,
11507       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
11508 }
11509 
11510 StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
11511     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11512     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11513   if (!AStmt)
11514     return StmtError();
11515 
11516   auto *CS = cast<CapturedStmt>(AStmt);
11517   // 1.2.2 OpenMP Language Terminology
11518   // Structured block - An executable statement with a single entry at the
11519   // top and a single exit at the bottom.
11520   // The point of exit cannot be a branch out of the structured block.
11521   // longjmp() and throw() must not violate the entry/exit criteria.
11522   CS->getCapturedDecl()->setNothrow();
11523   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
11524        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11525     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11526     // 1.2.2 OpenMP Language Terminology
11527     // Structured block - An executable statement with a single entry at the
11528     // top and a single exit at the bottom.
11529     // The point of exit cannot be a branch out of the structured block.
11530     // longjmp() and throw() must not violate the entry/exit criteria.
11531     CS->getCapturedDecl()->setNothrow();
11532   }
11533 
11534   OMPLoopBasedDirective::HelperExprs B;
11535   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
11536   // define the nested loops number.
11537   unsigned NestedLoopCount =
11538       checkOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
11539                       getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
11540                       VarsWithImplicitDSA, B);
11541   if (NestedLoopCount == 0)
11542     return StmtError();
11543 
11544   assert((CurContext->isDependentContext() || B.builtAll()) &&
11545          "omp target parallel for loop exprs were not built");
11546 
11547   if (!CurContext->isDependentContext()) {
11548     // Finalize the clauses that need pre-built expressions for CodeGen.
11549     for (OMPClause *C : Clauses) {
11550       if (auto *LC = dyn_cast<OMPLinearClause>(C))
11551         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
11552                                      B.NumIterations, *this, CurScope,
11553                                      DSAStack))
11554           return StmtError();
11555     }
11556   }
11557 
11558   setFunctionHasBranchProtectedScope();
11559   return OMPTargetParallelForDirective::Create(
11560       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
11561       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
11562 }
11563 
11564 /// Check for existence of a map clause in the list of clauses.
11565 static bool hasClauses(ArrayRef<OMPClause *> Clauses,
11566                        const OpenMPClauseKind K) {
11567   return llvm::any_of(
11568       Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; });
11569 }
11570 
11571 template <typename... Params>
11572 static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K,
11573                        const Params... ClauseTypes) {
11574   return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...);
11575 }
11576 
11577 StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
11578                                                 Stmt *AStmt,
11579                                                 SourceLocation StartLoc,
11580                                                 SourceLocation EndLoc) {
11581   if (!AStmt)
11582     return StmtError();
11583 
11584   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
11585 
11586   // OpenMP [2.12.2, target data Construct, Restrictions]
11587   // At least one map, use_device_addr or use_device_ptr clause must appear on
11588   // the directive.
11589   if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr) &&
11590       (LangOpts.OpenMP < 50 || !hasClauses(Clauses, OMPC_use_device_addr))) {
11591     StringRef Expected;
11592     if (LangOpts.OpenMP < 50)
11593       Expected = "'map' or 'use_device_ptr'";
11594     else
11595       Expected = "'map', 'use_device_ptr', or 'use_device_addr'";
11596     Diag(StartLoc, diag::err_omp_no_clause_for_directive)
11597         << Expected << getOpenMPDirectiveName(OMPD_target_data);
11598     return StmtError();
11599   }
11600 
11601   setFunctionHasBranchProtectedScope();
11602 
11603   return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
11604                                         AStmt);
11605 }
11606 
11607 StmtResult
11608 Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
11609                                           SourceLocation StartLoc,
11610                                           SourceLocation EndLoc, Stmt *AStmt) {
11611   if (!AStmt)
11612     return StmtError();
11613 
11614   auto *CS = cast<CapturedStmt>(AStmt);
11615   // 1.2.2 OpenMP Language Terminology
11616   // Structured block - An executable statement with a single entry at the
11617   // top and a single exit at the bottom.
11618   // The point of exit cannot be a branch out of the structured block.
11619   // longjmp() and throw() must not violate the entry/exit criteria.
11620   CS->getCapturedDecl()->setNothrow();
11621   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_enter_data);
11622        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11623     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11624     // 1.2.2 OpenMP Language Terminology
11625     // Structured block - An executable statement with a single entry at the
11626     // top and a single exit at the bottom.
11627     // The point of exit cannot be a branch out of the structured block.
11628     // longjmp() and throw() must not violate the entry/exit criteria.
11629     CS->getCapturedDecl()->setNothrow();
11630   }
11631 
11632   // OpenMP [2.10.2, Restrictions, p. 99]
11633   // At least one map clause must appear on the directive.
11634   if (!hasClauses(Clauses, OMPC_map)) {
11635     Diag(StartLoc, diag::err_omp_no_clause_for_directive)
11636         << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data);
11637     return StmtError();
11638   }
11639 
11640   return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
11641                                              AStmt);
11642 }
11643 
11644 StmtResult
11645 Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
11646                                          SourceLocation StartLoc,
11647                                          SourceLocation EndLoc, Stmt *AStmt) {
11648   if (!AStmt)
11649     return StmtError();
11650 
11651   auto *CS = cast<CapturedStmt>(AStmt);
11652   // 1.2.2 OpenMP Language Terminology
11653   // Structured block - An executable statement with a single entry at the
11654   // top and a single exit at the bottom.
11655   // The point of exit cannot be a branch out of the structured block.
11656   // longjmp() and throw() must not violate the entry/exit criteria.
11657   CS->getCapturedDecl()->setNothrow();
11658   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_exit_data);
11659        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11660     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11661     // 1.2.2 OpenMP Language Terminology
11662     // Structured block - An executable statement with a single entry at the
11663     // top and a single exit at the bottom.
11664     // The point of exit cannot be a branch out of the structured block.
11665     // longjmp() and throw() must not violate the entry/exit criteria.
11666     CS->getCapturedDecl()->setNothrow();
11667   }
11668 
11669   // OpenMP [2.10.3, Restrictions, p. 102]
11670   // At least one map clause must appear on the directive.
11671   if (!hasClauses(Clauses, OMPC_map)) {
11672     Diag(StartLoc, diag::err_omp_no_clause_for_directive)
11673         << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data);
11674     return StmtError();
11675   }
11676 
11677   return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
11678                                             AStmt);
11679 }
11680 
11681 StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
11682                                                   SourceLocation StartLoc,
11683                                                   SourceLocation EndLoc,
11684                                                   Stmt *AStmt) {
11685   if (!AStmt)
11686     return StmtError();
11687 
11688   auto *CS = cast<CapturedStmt>(AStmt);
11689   // 1.2.2 OpenMP Language Terminology
11690   // Structured block - An executable statement with a single entry at the
11691   // top and a single exit at the bottom.
11692   // The point of exit cannot be a branch out of the structured block.
11693   // longjmp() and throw() must not violate the entry/exit criteria.
11694   CS->getCapturedDecl()->setNothrow();
11695   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_update);
11696        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11697     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11698     // 1.2.2 OpenMP Language Terminology
11699     // Structured block - An executable statement with a single entry at the
11700     // top and a single exit at the bottom.
11701     // The point of exit cannot be a branch out of the structured block.
11702     // longjmp() and throw() must not violate the entry/exit criteria.
11703     CS->getCapturedDecl()->setNothrow();
11704   }
11705 
11706   if (!hasClauses(Clauses, OMPC_to, OMPC_from)) {
11707     Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
11708     return StmtError();
11709   }
11710   return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses,
11711                                           AStmt);
11712 }
11713 
11714 StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
11715                                            Stmt *AStmt, SourceLocation StartLoc,
11716                                            SourceLocation EndLoc) {
11717   if (!AStmt)
11718     return StmtError();
11719 
11720   auto *CS = cast<CapturedStmt>(AStmt);
11721   // 1.2.2 OpenMP Language Terminology
11722   // Structured block - An executable statement with a single entry at the
11723   // top and a single exit at the bottom.
11724   // The point of exit cannot be a branch out of the structured block.
11725   // longjmp() and throw() must not violate the entry/exit criteria.
11726   CS->getCapturedDecl()->setNothrow();
11727 
11728   setFunctionHasBranchProtectedScope();
11729 
11730   DSAStack->setParentTeamsRegionLoc(StartLoc);
11731 
11732   return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
11733 }
11734 
11735 StmtResult
11736 Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
11737                                             SourceLocation EndLoc,
11738                                             OpenMPDirectiveKind CancelRegion) {
11739   if (DSAStack->isParentNowaitRegion()) {
11740     Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
11741     return StmtError();
11742   }
11743   if (DSAStack->isParentOrderedRegion()) {
11744     Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
11745     return StmtError();
11746   }
11747   return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
11748                                                CancelRegion);
11749 }
11750 
11751 StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
11752                                             SourceLocation StartLoc,
11753                                             SourceLocation EndLoc,
11754                                             OpenMPDirectiveKind CancelRegion) {
11755   if (DSAStack->isParentNowaitRegion()) {
11756     Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
11757     return StmtError();
11758   }
11759   if (DSAStack->isParentOrderedRegion()) {
11760     Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
11761     return StmtError();
11762   }
11763   DSAStack->setParentCancelRegion(/*Cancel=*/true);
11764   return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
11765                                     CancelRegion);
11766 }
11767 
11768 static bool checkReductionClauseWithNogroup(Sema &S,
11769                                             ArrayRef<OMPClause *> Clauses) {
11770   const OMPClause *ReductionClause = nullptr;
11771   const OMPClause *NogroupClause = nullptr;
11772   for (const OMPClause *C : Clauses) {
11773     if (C->getClauseKind() == OMPC_reduction) {
11774       ReductionClause = C;
11775       if (NogroupClause)
11776         break;
11777       continue;
11778     }
11779     if (C->getClauseKind() == OMPC_nogroup) {
11780       NogroupClause = C;
11781       if (ReductionClause)
11782         break;
11783       continue;
11784     }
11785   }
11786   if (ReductionClause && NogroupClause) {
11787     S.Diag(ReductionClause->getBeginLoc(), diag::err_omp_reduction_with_nogroup)
11788         << SourceRange(NogroupClause->getBeginLoc(),
11789                        NogroupClause->getEndLoc());
11790     return true;
11791   }
11792   return false;
11793 }
11794 
11795 StmtResult Sema::ActOnOpenMPTaskLoopDirective(
11796     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11797     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11798   if (!AStmt)
11799     return StmtError();
11800 
11801   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
11802   OMPLoopBasedDirective::HelperExprs B;
11803   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
11804   // define the nested loops number.
11805   unsigned NestedLoopCount =
11806       checkOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
11807                       /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
11808                       VarsWithImplicitDSA, B);
11809   if (NestedLoopCount == 0)
11810     return StmtError();
11811 
11812   assert((CurContext->isDependentContext() || B.builtAll()) &&
11813          "omp for loop exprs were not built");
11814 
11815   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
11816   // The grainsize clause and num_tasks clause are mutually exclusive and may
11817   // not appear on the same taskloop directive.
11818   if (checkMutuallyExclusiveClauses(*this, Clauses,
11819                                     {OMPC_grainsize, OMPC_num_tasks}))
11820     return StmtError();
11821   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
11822   // If a reduction clause is present on the taskloop directive, the nogroup
11823   // clause must not be specified.
11824   if (checkReductionClauseWithNogroup(*this, Clauses))
11825     return StmtError();
11826 
11827   setFunctionHasBranchProtectedScope();
11828   return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
11829                                       NestedLoopCount, Clauses, AStmt, B,
11830                                       DSAStack->isCancelRegion());
11831 }
11832 
11833 StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
11834     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11835     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11836   if (!AStmt)
11837     return StmtError();
11838 
11839   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
11840   OMPLoopBasedDirective::HelperExprs B;
11841   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
11842   // define the nested loops number.
11843   unsigned NestedLoopCount =
11844       checkOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
11845                       /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
11846                       VarsWithImplicitDSA, B);
11847   if (NestedLoopCount == 0)
11848     return StmtError();
11849 
11850   assert((CurContext->isDependentContext() || B.builtAll()) &&
11851          "omp for loop exprs were not built");
11852 
11853   if (!CurContext->isDependentContext()) {
11854     // Finalize the clauses that need pre-built expressions for CodeGen.
11855     for (OMPClause *C : Clauses) {
11856       if (auto *LC = dyn_cast<OMPLinearClause>(C))
11857         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
11858                                      B.NumIterations, *this, CurScope,
11859                                      DSAStack))
11860           return StmtError();
11861     }
11862   }
11863 
11864   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
11865   // The grainsize clause and num_tasks clause are mutually exclusive and may
11866   // not appear on the same taskloop directive.
11867   if (checkMutuallyExclusiveClauses(*this, Clauses,
11868                                     {OMPC_grainsize, OMPC_num_tasks}))
11869     return StmtError();
11870   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
11871   // If a reduction clause is present on the taskloop directive, the nogroup
11872   // clause must not be specified.
11873   if (checkReductionClauseWithNogroup(*this, Clauses))
11874     return StmtError();
11875   if (checkSimdlenSafelenSpecified(*this, Clauses))
11876     return StmtError();
11877 
11878   setFunctionHasBranchProtectedScope();
11879   return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
11880                                           NestedLoopCount, Clauses, AStmt, B);
11881 }
11882 
11883 StmtResult Sema::ActOnOpenMPMasterTaskLoopDirective(
11884     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11885     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11886   if (!AStmt)
11887     return StmtError();
11888 
11889   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
11890   OMPLoopBasedDirective::HelperExprs B;
11891   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
11892   // define the nested loops number.
11893   unsigned NestedLoopCount =
11894       checkOpenMPLoop(OMPD_master_taskloop, getCollapseNumberExpr(Clauses),
11895                       /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
11896                       VarsWithImplicitDSA, B);
11897   if (NestedLoopCount == 0)
11898     return StmtError();
11899 
11900   assert((CurContext->isDependentContext() || B.builtAll()) &&
11901          "omp for loop exprs were not built");
11902 
11903   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
11904   // The grainsize clause and num_tasks clause are mutually exclusive and may
11905   // not appear on the same taskloop directive.
11906   if (checkMutuallyExclusiveClauses(*this, Clauses,
11907                                     {OMPC_grainsize, OMPC_num_tasks}))
11908     return StmtError();
11909   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
11910   // If a reduction clause is present on the taskloop directive, the nogroup
11911   // clause must not be specified.
11912   if (checkReductionClauseWithNogroup(*this, Clauses))
11913     return StmtError();
11914 
11915   setFunctionHasBranchProtectedScope();
11916   return OMPMasterTaskLoopDirective::Create(Context, StartLoc, EndLoc,
11917                                             NestedLoopCount, Clauses, AStmt, B,
11918                                             DSAStack->isCancelRegion());
11919 }
11920 
11921 StmtResult Sema::ActOnOpenMPMasterTaskLoopSimdDirective(
11922     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11923     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11924   if (!AStmt)
11925     return StmtError();
11926 
11927   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
11928   OMPLoopBasedDirective::HelperExprs B;
11929   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
11930   // define the nested loops number.
11931   unsigned NestedLoopCount =
11932       checkOpenMPLoop(OMPD_master_taskloop_simd, getCollapseNumberExpr(Clauses),
11933                       /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
11934                       VarsWithImplicitDSA, B);
11935   if (NestedLoopCount == 0)
11936     return StmtError();
11937 
11938   assert((CurContext->isDependentContext() || B.builtAll()) &&
11939          "omp for loop exprs were not built");
11940 
11941   if (!CurContext->isDependentContext()) {
11942     // Finalize the clauses that need pre-built expressions for CodeGen.
11943     for (OMPClause *C : Clauses) {
11944       if (auto *LC = dyn_cast<OMPLinearClause>(C))
11945         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
11946                                      B.NumIterations, *this, CurScope,
11947                                      DSAStack))
11948           return StmtError();
11949     }
11950   }
11951 
11952   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
11953   // The grainsize clause and num_tasks clause are mutually exclusive and may
11954   // not appear on the same taskloop directive.
11955   if (checkMutuallyExclusiveClauses(*this, Clauses,
11956                                     {OMPC_grainsize, OMPC_num_tasks}))
11957     return StmtError();
11958   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
11959   // If a reduction clause is present on the taskloop directive, the nogroup
11960   // clause must not be specified.
11961   if (checkReductionClauseWithNogroup(*this, Clauses))
11962     return StmtError();
11963   if (checkSimdlenSafelenSpecified(*this, Clauses))
11964     return StmtError();
11965 
11966   setFunctionHasBranchProtectedScope();
11967   return OMPMasterTaskLoopSimdDirective::Create(
11968       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
11969 }
11970 
11971 StmtResult Sema::ActOnOpenMPParallelMasterTaskLoopDirective(
11972     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11973     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11974   if (!AStmt)
11975     return StmtError();
11976 
11977   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
11978   auto *CS = cast<CapturedStmt>(AStmt);
11979   // 1.2.2 OpenMP Language Terminology
11980   // Structured block - An executable statement with a single entry at the
11981   // top and a single exit at the bottom.
11982   // The point of exit cannot be a branch out of the structured block.
11983   // longjmp() and throw() must not violate the entry/exit criteria.
11984   CS->getCapturedDecl()->setNothrow();
11985   for (int ThisCaptureLevel =
11986            getOpenMPCaptureLevels(OMPD_parallel_master_taskloop);
11987        ThisCaptureLevel > 1; --ThisCaptureLevel) {
11988     CS = cast<CapturedStmt>(CS->getCapturedStmt());
11989     // 1.2.2 OpenMP Language Terminology
11990     // Structured block - An executable statement with a single entry at the
11991     // top and a single exit at the bottom.
11992     // The point of exit cannot be a branch out of the structured block.
11993     // longjmp() and throw() must not violate the entry/exit criteria.
11994     CS->getCapturedDecl()->setNothrow();
11995   }
11996 
11997   OMPLoopBasedDirective::HelperExprs B;
11998   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
11999   // define the nested loops number.
12000   unsigned NestedLoopCount = checkOpenMPLoop(
12001       OMPD_parallel_master_taskloop, getCollapseNumberExpr(Clauses),
12002       /*OrderedLoopCountExpr=*/nullptr, CS, *this, *DSAStack,
12003       VarsWithImplicitDSA, B);
12004   if (NestedLoopCount == 0)
12005     return StmtError();
12006 
12007   assert((CurContext->isDependentContext() || B.builtAll()) &&
12008          "omp for loop exprs were not built");
12009 
12010   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
12011   // The grainsize clause and num_tasks clause are mutually exclusive and may
12012   // not appear on the same taskloop directive.
12013   if (checkMutuallyExclusiveClauses(*this, Clauses,
12014                                     {OMPC_grainsize, OMPC_num_tasks}))
12015     return StmtError();
12016   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
12017   // If a reduction clause is present on the taskloop directive, the nogroup
12018   // clause must not be specified.
12019   if (checkReductionClauseWithNogroup(*this, Clauses))
12020     return StmtError();
12021 
12022   setFunctionHasBranchProtectedScope();
12023   return OMPParallelMasterTaskLoopDirective::Create(
12024       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
12025       DSAStack->isCancelRegion());
12026 }
12027 
12028 StmtResult Sema::ActOnOpenMPParallelMasterTaskLoopSimdDirective(
12029     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12030     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12031   if (!AStmt)
12032     return StmtError();
12033 
12034   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
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_parallel_master_taskloop_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' or 'ordered' with number of loops, it will
12056   // define the nested loops number.
12057   unsigned NestedLoopCount = checkOpenMPLoop(
12058       OMPD_parallel_master_taskloop_simd, getCollapseNumberExpr(Clauses),
12059       /*OrderedLoopCountExpr=*/nullptr, CS, *this, *DSAStack,
12060       VarsWithImplicitDSA, B);
12061   if (NestedLoopCount == 0)
12062     return StmtError();
12063 
12064   assert((CurContext->isDependentContext() || B.builtAll()) &&
12065          "omp for loop exprs were not built");
12066 
12067   if (!CurContext->isDependentContext()) {
12068     // Finalize the clauses that need pre-built expressions for CodeGen.
12069     for (OMPClause *C : Clauses) {
12070       if (auto *LC = dyn_cast<OMPLinearClause>(C))
12071         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
12072                                      B.NumIterations, *this, CurScope,
12073                                      DSAStack))
12074           return StmtError();
12075     }
12076   }
12077 
12078   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
12079   // The grainsize clause and num_tasks clause are mutually exclusive and may
12080   // not appear on the same taskloop directive.
12081   if (checkMutuallyExclusiveClauses(*this, Clauses,
12082                                     {OMPC_grainsize, OMPC_num_tasks}))
12083     return StmtError();
12084   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
12085   // If a reduction clause is present on the taskloop directive, the nogroup
12086   // clause must not be specified.
12087   if (checkReductionClauseWithNogroup(*this, Clauses))
12088     return StmtError();
12089   if (checkSimdlenSafelenSpecified(*this, Clauses))
12090     return StmtError();
12091 
12092   setFunctionHasBranchProtectedScope();
12093   return OMPParallelMasterTaskLoopSimdDirective::Create(
12094       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
12095 }
12096 
12097 StmtResult Sema::ActOnOpenMPDistributeDirective(
12098     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12099     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12100   if (!AStmt)
12101     return StmtError();
12102 
12103   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
12104   OMPLoopBasedDirective::HelperExprs B;
12105   // In presence of clause 'collapse' with number of loops, it will
12106   // define the nested loops number.
12107   unsigned NestedLoopCount =
12108       checkOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
12109                       nullptr /*ordered not a clause on distribute*/, AStmt,
12110                       *this, *DSAStack, VarsWithImplicitDSA, B);
12111   if (NestedLoopCount == 0)
12112     return StmtError();
12113 
12114   assert((CurContext->isDependentContext() || B.builtAll()) &&
12115          "omp for loop exprs were not built");
12116 
12117   setFunctionHasBranchProtectedScope();
12118   return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
12119                                         NestedLoopCount, Clauses, AStmt, B);
12120 }
12121 
12122 StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
12123     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12124     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12125   if (!AStmt)
12126     return StmtError();
12127 
12128   auto *CS = cast<CapturedStmt>(AStmt);
12129   // 1.2.2 OpenMP Language Terminology
12130   // Structured block - An executable statement with a single entry at the
12131   // top and a single exit at the bottom.
12132   // The point of exit cannot be a branch out of the structured block.
12133   // longjmp() and throw() must not violate the entry/exit criteria.
12134   CS->getCapturedDecl()->setNothrow();
12135   for (int ThisCaptureLevel =
12136            getOpenMPCaptureLevels(OMPD_distribute_parallel_for);
12137        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12138     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12139     // 1.2.2 OpenMP Language Terminology
12140     // Structured block - An executable statement with a single entry at the
12141     // top and a single exit at the bottom.
12142     // The point of exit cannot be a branch out of the structured block.
12143     // longjmp() and throw() must not violate the entry/exit criteria.
12144     CS->getCapturedDecl()->setNothrow();
12145   }
12146 
12147   OMPLoopBasedDirective::HelperExprs B;
12148   // In presence of clause 'collapse' with number of loops, it will
12149   // define the nested loops number.
12150   unsigned NestedLoopCount = checkOpenMPLoop(
12151       OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
12152       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
12153       VarsWithImplicitDSA, B);
12154   if (NestedLoopCount == 0)
12155     return StmtError();
12156 
12157   assert((CurContext->isDependentContext() || B.builtAll()) &&
12158          "omp for loop exprs were not built");
12159 
12160   setFunctionHasBranchProtectedScope();
12161   return OMPDistributeParallelForDirective::Create(
12162       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
12163       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
12164 }
12165 
12166 StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
12167     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12168     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12169   if (!AStmt)
12170     return StmtError();
12171 
12172   auto *CS = cast<CapturedStmt>(AStmt);
12173   // 1.2.2 OpenMP Language Terminology
12174   // Structured block - An executable statement with a single entry at the
12175   // top and a single exit at the bottom.
12176   // The point of exit cannot be a branch out of the structured block.
12177   // longjmp() and throw() must not violate the entry/exit criteria.
12178   CS->getCapturedDecl()->setNothrow();
12179   for (int ThisCaptureLevel =
12180            getOpenMPCaptureLevels(OMPD_distribute_parallel_for_simd);
12181        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12182     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12183     // 1.2.2 OpenMP Language Terminology
12184     // Structured block - An executable statement with a single entry at the
12185     // top and a single exit at the bottom.
12186     // The point of exit cannot be a branch out of the structured block.
12187     // longjmp() and throw() must not violate the entry/exit criteria.
12188     CS->getCapturedDecl()->setNothrow();
12189   }
12190 
12191   OMPLoopBasedDirective::HelperExprs B;
12192   // In presence of clause 'collapse' with number of loops, it will
12193   // define the nested loops number.
12194   unsigned NestedLoopCount = checkOpenMPLoop(
12195       OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
12196       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
12197       VarsWithImplicitDSA, B);
12198   if (NestedLoopCount == 0)
12199     return StmtError();
12200 
12201   assert((CurContext->isDependentContext() || B.builtAll()) &&
12202          "omp for loop exprs were not built");
12203 
12204   if (!CurContext->isDependentContext()) {
12205     // Finalize the clauses that need pre-built expressions for CodeGen.
12206     for (OMPClause *C : Clauses) {
12207       if (auto *LC = dyn_cast<OMPLinearClause>(C))
12208         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
12209                                      B.NumIterations, *this, CurScope,
12210                                      DSAStack))
12211           return StmtError();
12212     }
12213   }
12214 
12215   if (checkSimdlenSafelenSpecified(*this, Clauses))
12216     return StmtError();
12217 
12218   setFunctionHasBranchProtectedScope();
12219   return OMPDistributeParallelForSimdDirective::Create(
12220       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
12221 }
12222 
12223 StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
12224     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12225     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12226   if (!AStmt)
12227     return StmtError();
12228 
12229   auto *CS = cast<CapturedStmt>(AStmt);
12230   // 1.2.2 OpenMP Language Terminology
12231   // Structured block - An executable statement with a single entry at the
12232   // top and a single exit at the bottom.
12233   // The point of exit cannot be a branch out of the structured block.
12234   // longjmp() and throw() must not violate the entry/exit criteria.
12235   CS->getCapturedDecl()->setNothrow();
12236   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_distribute_simd);
12237        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12238     CS = cast<CapturedStmt>(CS->getCapturedStmt());
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   }
12246 
12247   OMPLoopBasedDirective::HelperExprs B;
12248   // In presence of clause 'collapse' with number of loops, it will
12249   // define the nested loops number.
12250   unsigned NestedLoopCount =
12251       checkOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
12252                       nullptr /*ordered not a clause on distribute*/, CS, *this,
12253                       *DSAStack, VarsWithImplicitDSA, B);
12254   if (NestedLoopCount == 0)
12255     return StmtError();
12256 
12257   assert((CurContext->isDependentContext() || B.builtAll()) &&
12258          "omp for loop exprs were not built");
12259 
12260   if (!CurContext->isDependentContext()) {
12261     // Finalize the clauses that need pre-built expressions for CodeGen.
12262     for (OMPClause *C : Clauses) {
12263       if (auto *LC = dyn_cast<OMPLinearClause>(C))
12264         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
12265                                      B.NumIterations, *this, CurScope,
12266                                      DSAStack))
12267           return StmtError();
12268     }
12269   }
12270 
12271   if (checkSimdlenSafelenSpecified(*this, Clauses))
12272     return StmtError();
12273 
12274   setFunctionHasBranchProtectedScope();
12275   return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
12276                                             NestedLoopCount, Clauses, AStmt, B);
12277 }
12278 
12279 StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
12280     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12281     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12282   if (!AStmt)
12283     return StmtError();
12284 
12285   auto *CS = cast<CapturedStmt>(AStmt);
12286   // 1.2.2 OpenMP Language Terminology
12287   // Structured block - An executable statement with a single entry at the
12288   // top and a single exit at the bottom.
12289   // The point of exit cannot be a branch out of the structured block.
12290   // longjmp() and throw() must not violate the entry/exit criteria.
12291   CS->getCapturedDecl()->setNothrow();
12292   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
12293        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12294     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12295     // 1.2.2 OpenMP Language Terminology
12296     // Structured block - An executable statement with a single entry at the
12297     // top and a single exit at the bottom.
12298     // The point of exit cannot be a branch out of the structured block.
12299     // longjmp() and throw() must not violate the entry/exit criteria.
12300     CS->getCapturedDecl()->setNothrow();
12301   }
12302 
12303   OMPLoopBasedDirective::HelperExprs B;
12304   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
12305   // define the nested loops number.
12306   unsigned NestedLoopCount = checkOpenMPLoop(
12307       OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
12308       getOrderedNumberExpr(Clauses), CS, *this, *DSAStack, VarsWithImplicitDSA,
12309       B);
12310   if (NestedLoopCount == 0)
12311     return StmtError();
12312 
12313   assert((CurContext->isDependentContext() || B.builtAll()) &&
12314          "omp target parallel for simd loop exprs were not built");
12315 
12316   if (!CurContext->isDependentContext()) {
12317     // Finalize the clauses that need pre-built expressions for CodeGen.
12318     for (OMPClause *C : Clauses) {
12319       if (auto *LC = dyn_cast<OMPLinearClause>(C))
12320         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
12321                                      B.NumIterations, *this, CurScope,
12322                                      DSAStack))
12323           return StmtError();
12324     }
12325   }
12326   if (checkSimdlenSafelenSpecified(*this, Clauses))
12327     return StmtError();
12328 
12329   setFunctionHasBranchProtectedScope();
12330   return OMPTargetParallelForSimdDirective::Create(
12331       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
12332 }
12333 
12334 StmtResult Sema::ActOnOpenMPTargetSimdDirective(
12335     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12336     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12337   if (!AStmt)
12338     return StmtError();
12339 
12340   auto *CS = cast<CapturedStmt>(AStmt);
12341   // 1.2.2 OpenMP Language Terminology
12342   // Structured block - An executable statement with a single entry at the
12343   // top and a single exit at the bottom.
12344   // The point of exit cannot be a branch out of the structured block.
12345   // longjmp() and throw() must not violate the entry/exit criteria.
12346   CS->getCapturedDecl()->setNothrow();
12347   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_simd);
12348        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12349     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12350     // 1.2.2 OpenMP Language Terminology
12351     // Structured block - An executable statement with a single entry at the
12352     // top and a single exit at the bottom.
12353     // The point of exit cannot be a branch out of the structured block.
12354     // longjmp() and throw() must not violate the entry/exit criteria.
12355     CS->getCapturedDecl()->setNothrow();
12356   }
12357 
12358   OMPLoopBasedDirective::HelperExprs B;
12359   // In presence of clause 'collapse' with number of loops, it will define the
12360   // nested loops number.
12361   unsigned NestedLoopCount =
12362       checkOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
12363                       getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
12364                       VarsWithImplicitDSA, B);
12365   if (NestedLoopCount == 0)
12366     return StmtError();
12367 
12368   assert((CurContext->isDependentContext() || B.builtAll()) &&
12369          "omp target simd loop exprs were not built");
12370 
12371   if (!CurContext->isDependentContext()) {
12372     // Finalize the clauses that need pre-built expressions for CodeGen.
12373     for (OMPClause *C : Clauses) {
12374       if (auto *LC = dyn_cast<OMPLinearClause>(C))
12375         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
12376                                      B.NumIterations, *this, CurScope,
12377                                      DSAStack))
12378           return StmtError();
12379     }
12380   }
12381 
12382   if (checkSimdlenSafelenSpecified(*this, Clauses))
12383     return StmtError();
12384 
12385   setFunctionHasBranchProtectedScope();
12386   return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
12387                                         NestedLoopCount, Clauses, AStmt, B);
12388 }
12389 
12390 StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
12391     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12392     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12393   if (!AStmt)
12394     return StmtError();
12395 
12396   auto *CS = cast<CapturedStmt>(AStmt);
12397   // 1.2.2 OpenMP Language Terminology
12398   // Structured block - An executable statement with a single entry at the
12399   // top and a single exit at the bottom.
12400   // The point of exit cannot be a branch out of the structured block.
12401   // longjmp() and throw() must not violate the entry/exit criteria.
12402   CS->getCapturedDecl()->setNothrow();
12403   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_teams_distribute);
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 =
12418       checkOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
12419                       nullptr /*ordered not a clause on distribute*/, CS, *this,
12420                       *DSAStack, VarsWithImplicitDSA, B);
12421   if (NestedLoopCount == 0)
12422     return StmtError();
12423 
12424   assert((CurContext->isDependentContext() || B.builtAll()) &&
12425          "omp teams distribute loop exprs were not built");
12426 
12427   setFunctionHasBranchProtectedScope();
12428 
12429   DSAStack->setParentTeamsRegionLoc(StartLoc);
12430 
12431   return OMPTeamsDistributeDirective::Create(
12432       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
12433 }
12434 
12435 StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
12436     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12437     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12438   if (!AStmt)
12439     return StmtError();
12440 
12441   auto *CS = cast<CapturedStmt>(AStmt);
12442   // 1.2.2 OpenMP Language Terminology
12443   // Structured block - An executable statement with a single entry at the
12444   // top and a single exit at the bottom.
12445   // The point of exit cannot be a branch out of the structured block.
12446   // longjmp() and throw() must not violate the entry/exit criteria.
12447   CS->getCapturedDecl()->setNothrow();
12448   for (int ThisCaptureLevel =
12449            getOpenMPCaptureLevels(OMPD_teams_distribute_simd);
12450        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12451     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12452     // 1.2.2 OpenMP Language Terminology
12453     // Structured block - An executable statement with a single entry at the
12454     // top and a single exit at the bottom.
12455     // The point of exit cannot be a branch out of the structured block.
12456     // longjmp() and throw() must not violate the entry/exit criteria.
12457     CS->getCapturedDecl()->setNothrow();
12458   }
12459 
12460   OMPLoopBasedDirective::HelperExprs B;
12461   // In presence of clause 'collapse' with number of loops, it will
12462   // define the nested loops number.
12463   unsigned NestedLoopCount = checkOpenMPLoop(
12464       OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
12465       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
12466       VarsWithImplicitDSA, B);
12467 
12468   if (NestedLoopCount == 0)
12469     return StmtError();
12470 
12471   assert((CurContext->isDependentContext() || B.builtAll()) &&
12472          "omp teams distribute simd loop exprs were not built");
12473 
12474   if (!CurContext->isDependentContext()) {
12475     // Finalize the clauses that need pre-built expressions for CodeGen.
12476     for (OMPClause *C : Clauses) {
12477       if (auto *LC = dyn_cast<OMPLinearClause>(C))
12478         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
12479                                      B.NumIterations, *this, CurScope,
12480                                      DSAStack))
12481           return StmtError();
12482     }
12483   }
12484 
12485   if (checkSimdlenSafelenSpecified(*this, Clauses))
12486     return StmtError();
12487 
12488   setFunctionHasBranchProtectedScope();
12489 
12490   DSAStack->setParentTeamsRegionLoc(StartLoc);
12491 
12492   return OMPTeamsDistributeSimdDirective::Create(
12493       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
12494 }
12495 
12496 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
12497     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12498     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12499   if (!AStmt)
12500     return StmtError();
12501 
12502   auto *CS = cast<CapturedStmt>(AStmt);
12503   // 1.2.2 OpenMP Language Terminology
12504   // Structured block - An executable statement with a single entry at the
12505   // top and a single exit at the bottom.
12506   // The point of exit cannot be a branch out of the structured block.
12507   // longjmp() and throw() must not violate the entry/exit criteria.
12508   CS->getCapturedDecl()->setNothrow();
12509 
12510   for (int ThisCaptureLevel =
12511            getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for_simd);
12512        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12513     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12514     // 1.2.2 OpenMP Language Terminology
12515     // Structured block - An executable statement with a single entry at the
12516     // top and a single exit at the bottom.
12517     // The point of exit cannot be a branch out of the structured block.
12518     // longjmp() and throw() must not violate the entry/exit criteria.
12519     CS->getCapturedDecl()->setNothrow();
12520   }
12521 
12522   OMPLoopBasedDirective::HelperExprs B;
12523   // In presence of clause 'collapse' with number of loops, it will
12524   // define the nested loops number.
12525   unsigned NestedLoopCount = checkOpenMPLoop(
12526       OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
12527       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
12528       VarsWithImplicitDSA, B);
12529 
12530   if (NestedLoopCount == 0)
12531     return StmtError();
12532 
12533   assert((CurContext->isDependentContext() || B.builtAll()) &&
12534          "omp for loop exprs were not built");
12535 
12536   if (!CurContext->isDependentContext()) {
12537     // Finalize the clauses that need pre-built expressions for CodeGen.
12538     for (OMPClause *C : Clauses) {
12539       if (auto *LC = dyn_cast<OMPLinearClause>(C))
12540         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
12541                                      B.NumIterations, *this, CurScope,
12542                                      DSAStack))
12543           return StmtError();
12544     }
12545   }
12546 
12547   if (checkSimdlenSafelenSpecified(*this, Clauses))
12548     return StmtError();
12549 
12550   setFunctionHasBranchProtectedScope();
12551 
12552   DSAStack->setParentTeamsRegionLoc(StartLoc);
12553 
12554   return OMPTeamsDistributeParallelForSimdDirective::Create(
12555       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
12556 }
12557 
12558 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
12559     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12560     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12561   if (!AStmt)
12562     return StmtError();
12563 
12564   auto *CS = cast<CapturedStmt>(AStmt);
12565   // 1.2.2 OpenMP Language Terminology
12566   // Structured block - An executable statement with a single entry at the
12567   // top and a single exit at the bottom.
12568   // The point of exit cannot be a branch out of the structured block.
12569   // longjmp() and throw() must not violate the entry/exit criteria.
12570   CS->getCapturedDecl()->setNothrow();
12571 
12572   for (int ThisCaptureLevel =
12573            getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for);
12574        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12575     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12576     // 1.2.2 OpenMP Language Terminology
12577     // Structured block - An executable statement with a single entry at the
12578     // top and a single exit at the bottom.
12579     // The point of exit cannot be a branch out of the structured block.
12580     // longjmp() and throw() must not violate the entry/exit criteria.
12581     CS->getCapturedDecl()->setNothrow();
12582   }
12583 
12584   OMPLoopBasedDirective::HelperExprs B;
12585   // In presence of clause 'collapse' with number of loops, it will
12586   // define the nested loops number.
12587   unsigned NestedLoopCount = checkOpenMPLoop(
12588       OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
12589       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
12590       VarsWithImplicitDSA, B);
12591 
12592   if (NestedLoopCount == 0)
12593     return StmtError();
12594 
12595   assert((CurContext->isDependentContext() || B.builtAll()) &&
12596          "omp for loop exprs were not built");
12597 
12598   setFunctionHasBranchProtectedScope();
12599 
12600   DSAStack->setParentTeamsRegionLoc(StartLoc);
12601 
12602   return OMPTeamsDistributeParallelForDirective::Create(
12603       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
12604       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
12605 }
12606 
12607 StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
12608                                                  Stmt *AStmt,
12609                                                  SourceLocation StartLoc,
12610                                                  SourceLocation EndLoc) {
12611   if (!AStmt)
12612     return StmtError();
12613 
12614   auto *CS = cast<CapturedStmt>(AStmt);
12615   // 1.2.2 OpenMP Language Terminology
12616   // Structured block - An executable statement with a single entry at the
12617   // top and a single exit at the bottom.
12618   // The point of exit cannot be a branch out of the structured block.
12619   // longjmp() and throw() must not violate the entry/exit criteria.
12620   CS->getCapturedDecl()->setNothrow();
12621 
12622   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams);
12623        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12624     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12625     // 1.2.2 OpenMP Language Terminology
12626     // Structured block - An executable statement with a single entry at the
12627     // top and a single exit at the bottom.
12628     // The point of exit cannot be a branch out of the structured block.
12629     // longjmp() and throw() must not violate the entry/exit criteria.
12630     CS->getCapturedDecl()->setNothrow();
12631   }
12632   setFunctionHasBranchProtectedScope();
12633 
12634   return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
12635                                          AStmt);
12636 }
12637 
12638 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
12639     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12640     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12641   if (!AStmt)
12642     return StmtError();
12643 
12644   auto *CS = cast<CapturedStmt>(AStmt);
12645   // 1.2.2 OpenMP Language Terminology
12646   // Structured block - An executable statement with a single entry at the
12647   // top and a single exit at the bottom.
12648   // The point of exit cannot be a branch out of the structured block.
12649   // longjmp() and throw() must not violate the entry/exit criteria.
12650   CS->getCapturedDecl()->setNothrow();
12651   for (int ThisCaptureLevel =
12652            getOpenMPCaptureLevels(OMPD_target_teams_distribute);
12653        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12654     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12655     // 1.2.2 OpenMP Language Terminology
12656     // Structured block - An executable statement with a single entry at the
12657     // top and a single exit at the bottom.
12658     // The point of exit cannot be a branch out of the structured block.
12659     // longjmp() and throw() must not violate the entry/exit criteria.
12660     CS->getCapturedDecl()->setNothrow();
12661   }
12662 
12663   OMPLoopBasedDirective::HelperExprs B;
12664   // In presence of clause 'collapse' with number of loops, it will
12665   // define the nested loops number.
12666   unsigned NestedLoopCount = checkOpenMPLoop(
12667       OMPD_target_teams_distribute, getCollapseNumberExpr(Clauses),
12668       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
12669       VarsWithImplicitDSA, B);
12670   if (NestedLoopCount == 0)
12671     return StmtError();
12672 
12673   assert((CurContext->isDependentContext() || B.builtAll()) &&
12674          "omp target teams distribute loop exprs were not built");
12675 
12676   setFunctionHasBranchProtectedScope();
12677   return OMPTargetTeamsDistributeDirective::Create(
12678       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
12679 }
12680 
12681 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
12682     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12683     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12684   if (!AStmt)
12685     return StmtError();
12686 
12687   auto *CS = cast<CapturedStmt>(AStmt);
12688   // 1.2.2 OpenMP Language Terminology
12689   // Structured block - An executable statement with a single entry at the
12690   // top and a single exit at the bottom.
12691   // The point of exit cannot be a branch out of the structured block.
12692   // longjmp() and throw() must not violate the entry/exit criteria.
12693   CS->getCapturedDecl()->setNothrow();
12694   for (int ThisCaptureLevel =
12695            getOpenMPCaptureLevels(OMPD_target_teams_distribute_parallel_for);
12696        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12697     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12698     // 1.2.2 OpenMP Language Terminology
12699     // Structured block - An executable statement with a single entry at the
12700     // top and a single exit at the bottom.
12701     // The point of exit cannot be a branch out of the structured block.
12702     // longjmp() and throw() must not violate the entry/exit criteria.
12703     CS->getCapturedDecl()->setNothrow();
12704   }
12705 
12706   OMPLoopBasedDirective::HelperExprs B;
12707   // In presence of clause 'collapse' with number of loops, it will
12708   // define the nested loops number.
12709   unsigned NestedLoopCount = checkOpenMPLoop(
12710       OMPD_target_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
12711       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
12712       VarsWithImplicitDSA, B);
12713   if (NestedLoopCount == 0)
12714     return StmtError();
12715 
12716   assert((CurContext->isDependentContext() || B.builtAll()) &&
12717          "omp target teams distribute parallel for loop exprs were not built");
12718 
12719   if (!CurContext->isDependentContext()) {
12720     // Finalize the clauses that need pre-built expressions for CodeGen.
12721     for (OMPClause *C : Clauses) {
12722       if (auto *LC = dyn_cast<OMPLinearClause>(C))
12723         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
12724                                      B.NumIterations, *this, CurScope,
12725                                      DSAStack))
12726           return StmtError();
12727     }
12728   }
12729 
12730   setFunctionHasBranchProtectedScope();
12731   return OMPTargetTeamsDistributeParallelForDirective::Create(
12732       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
12733       DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
12734 }
12735 
12736 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
12737     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12738     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12739   if (!AStmt)
12740     return StmtError();
12741 
12742   auto *CS = cast<CapturedStmt>(AStmt);
12743   // 1.2.2 OpenMP Language Terminology
12744   // Structured block - An executable statement with a single entry at the
12745   // top and a single exit at the bottom.
12746   // The point of exit cannot be a branch out of the structured block.
12747   // longjmp() and throw() must not violate the entry/exit criteria.
12748   CS->getCapturedDecl()->setNothrow();
12749   for (int ThisCaptureLevel = getOpenMPCaptureLevels(
12750            OMPD_target_teams_distribute_parallel_for_simd);
12751        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12752     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12753     // 1.2.2 OpenMP Language Terminology
12754     // Structured block - An executable statement with a single entry at the
12755     // top and a single exit at the bottom.
12756     // The point of exit cannot be a branch out of the structured block.
12757     // longjmp() and throw() must not violate the entry/exit criteria.
12758     CS->getCapturedDecl()->setNothrow();
12759   }
12760 
12761   OMPLoopBasedDirective::HelperExprs B;
12762   // In presence of clause 'collapse' with number of loops, it will
12763   // define the nested loops number.
12764   unsigned NestedLoopCount =
12765       checkOpenMPLoop(OMPD_target_teams_distribute_parallel_for_simd,
12766                       getCollapseNumberExpr(Clauses),
12767                       nullptr /*ordered not a clause on distribute*/, CS, *this,
12768                       *DSAStack, VarsWithImplicitDSA, B);
12769   if (NestedLoopCount == 0)
12770     return StmtError();
12771 
12772   assert((CurContext->isDependentContext() || B.builtAll()) &&
12773          "omp target teams distribute parallel for simd loop exprs were not "
12774          "built");
12775 
12776   if (!CurContext->isDependentContext()) {
12777     // Finalize the clauses that need pre-built expressions for CodeGen.
12778     for (OMPClause *C : Clauses) {
12779       if (auto *LC = dyn_cast<OMPLinearClause>(C))
12780         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
12781                                      B.NumIterations, *this, CurScope,
12782                                      DSAStack))
12783           return StmtError();
12784     }
12785   }
12786 
12787   if (checkSimdlenSafelenSpecified(*this, Clauses))
12788     return StmtError();
12789 
12790   setFunctionHasBranchProtectedScope();
12791   return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
12792       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
12793 }
12794 
12795 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
12796     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12797     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12798   if (!AStmt)
12799     return StmtError();
12800 
12801   auto *CS = cast<CapturedStmt>(AStmt);
12802   // 1.2.2 OpenMP Language Terminology
12803   // Structured block - An executable statement with a single entry at the
12804   // top and a single exit at the bottom.
12805   // The point of exit cannot be a branch out of the structured block.
12806   // longjmp() and throw() must not violate the entry/exit criteria.
12807   CS->getCapturedDecl()->setNothrow();
12808   for (int ThisCaptureLevel =
12809            getOpenMPCaptureLevels(OMPD_target_teams_distribute_simd);
12810        ThisCaptureLevel > 1; --ThisCaptureLevel) {
12811     CS = cast<CapturedStmt>(CS->getCapturedStmt());
12812     // 1.2.2 OpenMP Language Terminology
12813     // Structured block - An executable statement with a single entry at the
12814     // top and a single exit at the bottom.
12815     // The point of exit cannot be a branch out of the structured block.
12816     // longjmp() and throw() must not violate the entry/exit criteria.
12817     CS->getCapturedDecl()->setNothrow();
12818   }
12819 
12820   OMPLoopBasedDirective::HelperExprs B;
12821   // In presence of clause 'collapse' with number of loops, it will
12822   // define the nested loops number.
12823   unsigned NestedLoopCount = checkOpenMPLoop(
12824       OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
12825       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
12826       VarsWithImplicitDSA, B);
12827   if (NestedLoopCount == 0)
12828     return StmtError();
12829 
12830   assert((CurContext->isDependentContext() || B.builtAll()) &&
12831          "omp target teams distribute simd loop exprs were not built");
12832 
12833   if (!CurContext->isDependentContext()) {
12834     // Finalize the clauses that need pre-built expressions for CodeGen.
12835     for (OMPClause *C : Clauses) {
12836       if (auto *LC = dyn_cast<OMPLinearClause>(C))
12837         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
12838                                      B.NumIterations, *this, CurScope,
12839                                      DSAStack))
12840           return StmtError();
12841     }
12842   }
12843 
12844   if (checkSimdlenSafelenSpecified(*this, Clauses))
12845     return StmtError();
12846 
12847   setFunctionHasBranchProtectedScope();
12848   return OMPTargetTeamsDistributeSimdDirective::Create(
12849       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
12850 }
12851 
12852 bool Sema::checkTransformableLoopNest(
12853     OpenMPDirectiveKind Kind, Stmt *AStmt, int NumLoops,
12854     SmallVectorImpl<OMPLoopBasedDirective::HelperExprs> &LoopHelpers,
12855     Stmt *&Body,
12856     SmallVectorImpl<SmallVector<llvm::PointerUnion<Stmt *, Decl *>, 0>>
12857         &OriginalInits) {
12858   OriginalInits.emplace_back();
12859   bool Result = OMPLoopBasedDirective::doForAllLoops(
12860       AStmt->IgnoreContainers(), /*TryImperfectlyNestedLoops=*/false, NumLoops,
12861       [this, &LoopHelpers, &Body, &OriginalInits, Kind](unsigned Cnt,
12862                                                         Stmt *CurStmt) {
12863         VarsWithInheritedDSAType TmpDSA;
12864         unsigned SingleNumLoops =
12865             checkOpenMPLoop(Kind, nullptr, nullptr, CurStmt, *this, *DSAStack,
12866                             TmpDSA, LoopHelpers[Cnt]);
12867         if (SingleNumLoops == 0)
12868           return true;
12869         assert(SingleNumLoops == 1 && "Expect single loop iteration space");
12870         if (auto *For = dyn_cast<ForStmt>(CurStmt)) {
12871           OriginalInits.back().push_back(For->getInit());
12872           Body = For->getBody();
12873         } else {
12874           assert(isa<CXXForRangeStmt>(CurStmt) &&
12875                  "Expected canonical for or range-based for loops.");
12876           auto *CXXFor = cast<CXXForRangeStmt>(CurStmt);
12877           OriginalInits.back().push_back(CXXFor->getBeginStmt());
12878           Body = CXXFor->getBody();
12879         }
12880         OriginalInits.emplace_back();
12881         return false;
12882       },
12883       [&OriginalInits](OMPLoopBasedDirective *Transform) {
12884         Stmt *DependentPreInits;
12885         if (auto *Dir = dyn_cast<OMPTileDirective>(Transform))
12886           DependentPreInits = Dir->getPreInits();
12887         else if (auto *Dir = dyn_cast<OMPUnrollDirective>(Transform))
12888           DependentPreInits = Dir->getPreInits();
12889         else
12890           llvm_unreachable("Unhandled loop transformation");
12891         if (!DependentPreInits)
12892           return;
12893         for (Decl *C : cast<DeclStmt>(DependentPreInits)->getDeclGroup())
12894           OriginalInits.back().push_back(C);
12895       });
12896   assert(OriginalInits.back().empty() && "No preinit after innermost loop");
12897   OriginalInits.pop_back();
12898   return Result;
12899 }
12900 
12901 StmtResult Sema::ActOnOpenMPTileDirective(ArrayRef<OMPClause *> Clauses,
12902                                           Stmt *AStmt, SourceLocation StartLoc,
12903                                           SourceLocation EndLoc) {
12904   auto SizesClauses =
12905       OMPExecutableDirective::getClausesOfKind<OMPSizesClause>(Clauses);
12906   if (SizesClauses.empty()) {
12907     // A missing 'sizes' clause is already reported by the parser.
12908     return StmtError();
12909   }
12910   const OMPSizesClause *SizesClause = *SizesClauses.begin();
12911   unsigned NumLoops = SizesClause->getNumSizes();
12912 
12913   // Empty statement should only be possible if there already was an error.
12914   if (!AStmt)
12915     return StmtError();
12916 
12917   // Verify and diagnose loop nest.
12918   SmallVector<OMPLoopBasedDirective::HelperExprs, 4> LoopHelpers(NumLoops);
12919   Stmt *Body = nullptr;
12920   SmallVector<SmallVector<llvm::PointerUnion<Stmt *, Decl *>, 0>, 4>
12921       OriginalInits;
12922   if (!checkTransformableLoopNest(OMPD_tile, AStmt, NumLoops, LoopHelpers, Body,
12923                                   OriginalInits))
12924     return StmtError();
12925 
12926   // Delay tiling to when template is completely instantiated.
12927   if (CurContext->isDependentContext())
12928     return OMPTileDirective::Create(Context, StartLoc, EndLoc, Clauses,
12929                                     NumLoops, AStmt, nullptr, nullptr);
12930 
12931   SmallVector<Decl *, 4> PreInits;
12932 
12933   // Create iteration variables for the generated loops.
12934   SmallVector<VarDecl *, 4> FloorIndVars;
12935   SmallVector<VarDecl *, 4> TileIndVars;
12936   FloorIndVars.resize(NumLoops);
12937   TileIndVars.resize(NumLoops);
12938   for (unsigned I = 0; I < NumLoops; ++I) {
12939     OMPLoopBasedDirective::HelperExprs &LoopHelper = LoopHelpers[I];
12940 
12941     assert(LoopHelper.Counters.size() == 1 &&
12942            "Expect single-dimensional loop iteration space");
12943     auto *OrigCntVar = cast<DeclRefExpr>(LoopHelper.Counters.front());
12944     std::string OrigVarName = OrigCntVar->getNameInfo().getAsString();
12945     DeclRefExpr *IterVarRef = cast<DeclRefExpr>(LoopHelper.IterationVarRef);
12946     QualType CntTy = IterVarRef->getType();
12947 
12948     // Iteration variable for the floor (i.e. outer) loop.
12949     {
12950       std::string FloorCntName =
12951           (Twine(".floor_") + llvm::utostr(I) + ".iv." + OrigVarName).str();
12952       VarDecl *FloorCntDecl =
12953           buildVarDecl(*this, {}, CntTy, FloorCntName, nullptr, OrigCntVar);
12954       FloorIndVars[I] = FloorCntDecl;
12955     }
12956 
12957     // Iteration variable for the tile (i.e. inner) loop.
12958     {
12959       std::string TileCntName =
12960           (Twine(".tile_") + llvm::utostr(I) + ".iv." + OrigVarName).str();
12961 
12962       // Reuse the iteration variable created by checkOpenMPLoop. It is also
12963       // used by the expressions to derive the original iteration variable's
12964       // value from the logical iteration number.
12965       auto *TileCntDecl = cast<VarDecl>(IterVarRef->getDecl());
12966       TileCntDecl->setDeclName(&PP.getIdentifierTable().get(TileCntName));
12967       TileIndVars[I] = TileCntDecl;
12968     }
12969     for (auto &P : OriginalInits[I]) {
12970       if (auto *D = P.dyn_cast<Decl *>())
12971         PreInits.push_back(D);
12972       else if (auto *PI = dyn_cast_or_null<DeclStmt>(P.dyn_cast<Stmt *>()))
12973         PreInits.append(PI->decl_begin(), PI->decl_end());
12974     }
12975     if (auto *PI = cast_or_null<DeclStmt>(LoopHelper.PreInits))
12976       PreInits.append(PI->decl_begin(), PI->decl_end());
12977     // Gather declarations for the data members used as counters.
12978     for (Expr *CounterRef : LoopHelper.Counters) {
12979       auto *CounterDecl = cast<DeclRefExpr>(CounterRef)->getDecl();
12980       if (isa<OMPCapturedExprDecl>(CounterDecl))
12981         PreInits.push_back(CounterDecl);
12982     }
12983   }
12984 
12985   // Once the original iteration values are set, append the innermost body.
12986   Stmt *Inner = Body;
12987 
12988   // Create tile loops from the inside to the outside.
12989   for (int I = NumLoops - 1; I >= 0; --I) {
12990     OMPLoopBasedDirective::HelperExprs &LoopHelper = LoopHelpers[I];
12991     Expr *NumIterations = LoopHelper.NumIterations;
12992     auto *OrigCntVar = cast<DeclRefExpr>(LoopHelper.Counters[0]);
12993     QualType CntTy = OrigCntVar->getType();
12994     Expr *DimTileSize = SizesClause->getSizesRefs()[I];
12995     Scope *CurScope = getCurScope();
12996 
12997     // Commonly used variables.
12998     DeclRefExpr *TileIV = buildDeclRefExpr(*this, TileIndVars[I], CntTy,
12999                                            OrigCntVar->getExprLoc());
13000     DeclRefExpr *FloorIV = buildDeclRefExpr(*this, FloorIndVars[I], CntTy,
13001                                             OrigCntVar->getExprLoc());
13002 
13003     // For init-statement: auto .tile.iv = .floor.iv
13004     AddInitializerToDecl(TileIndVars[I], DefaultLvalueConversion(FloorIV).get(),
13005                          /*DirectInit=*/false);
13006     Decl *CounterDecl = TileIndVars[I];
13007     StmtResult InitStmt = new (Context)
13008         DeclStmt(DeclGroupRef::Create(Context, &CounterDecl, 1),
13009                  OrigCntVar->getBeginLoc(), OrigCntVar->getEndLoc());
13010     if (!InitStmt.isUsable())
13011       return StmtError();
13012 
13013     // For cond-expression: .tile.iv < min(.floor.iv + DimTileSize,
13014     // NumIterations)
13015     ExprResult EndOfTile = BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(),
13016                                       BO_Add, FloorIV, DimTileSize);
13017     if (!EndOfTile.isUsable())
13018       return StmtError();
13019     ExprResult IsPartialTile =
13020         BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), BO_LT,
13021                    NumIterations, EndOfTile.get());
13022     if (!IsPartialTile.isUsable())
13023       return StmtError();
13024     ExprResult MinTileAndIterSpace = ActOnConditionalOp(
13025         LoopHelper.Cond->getBeginLoc(), LoopHelper.Cond->getEndLoc(),
13026         IsPartialTile.get(), NumIterations, EndOfTile.get());
13027     if (!MinTileAndIterSpace.isUsable())
13028       return StmtError();
13029     ExprResult CondExpr = BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(),
13030                                      BO_LT, TileIV, MinTileAndIterSpace.get());
13031     if (!CondExpr.isUsable())
13032       return StmtError();
13033 
13034     // For incr-statement: ++.tile.iv
13035     ExprResult IncrStmt =
13036         BuildUnaryOp(CurScope, LoopHelper.Inc->getExprLoc(), UO_PreInc, TileIV);
13037     if (!IncrStmt.isUsable())
13038       return StmtError();
13039 
13040     // Statements to set the original iteration variable's value from the
13041     // logical iteration number.
13042     // Generated for loop is:
13043     // Original_for_init;
13044     // for (auto .tile.iv = .floor.iv; .tile.iv < min(.floor.iv + DimTileSize,
13045     // NumIterations); ++.tile.iv) {
13046     //   Original_Body;
13047     //   Original_counter_update;
13048     // }
13049     // FIXME: If the innermost body is an loop itself, inserting these
13050     // statements stops it being recognized  as a perfectly nested loop (e.g.
13051     // for applying tiling again). If this is the case, sink the expressions
13052     // further into the inner loop.
13053     SmallVector<Stmt *, 4> BodyParts;
13054     BodyParts.append(LoopHelper.Updates.begin(), LoopHelper.Updates.end());
13055     BodyParts.push_back(Inner);
13056     Inner = CompoundStmt::Create(Context, BodyParts, Inner->getBeginLoc(),
13057                                  Inner->getEndLoc());
13058     Inner = new (Context)
13059         ForStmt(Context, InitStmt.get(), CondExpr.get(), nullptr,
13060                 IncrStmt.get(), Inner, LoopHelper.Init->getBeginLoc(),
13061                 LoopHelper.Init->getBeginLoc(), LoopHelper.Inc->getEndLoc());
13062   }
13063 
13064   // Create floor loops from the inside to the outside.
13065   for (int I = NumLoops - 1; I >= 0; --I) {
13066     auto &LoopHelper = LoopHelpers[I];
13067     Expr *NumIterations = LoopHelper.NumIterations;
13068     DeclRefExpr *OrigCntVar = cast<DeclRefExpr>(LoopHelper.Counters[0]);
13069     QualType CntTy = OrigCntVar->getType();
13070     Expr *DimTileSize = SizesClause->getSizesRefs()[I];
13071     Scope *CurScope = getCurScope();
13072 
13073     // Commonly used variables.
13074     DeclRefExpr *FloorIV = buildDeclRefExpr(*this, FloorIndVars[I], CntTy,
13075                                             OrigCntVar->getExprLoc());
13076 
13077     // For init-statement: auto .floor.iv = 0
13078     AddInitializerToDecl(
13079         FloorIndVars[I],
13080         ActOnIntegerConstant(LoopHelper.Init->getExprLoc(), 0).get(),
13081         /*DirectInit=*/false);
13082     Decl *CounterDecl = FloorIndVars[I];
13083     StmtResult InitStmt = new (Context)
13084         DeclStmt(DeclGroupRef::Create(Context, &CounterDecl, 1),
13085                  OrigCntVar->getBeginLoc(), OrigCntVar->getEndLoc());
13086     if (!InitStmt.isUsable())
13087       return StmtError();
13088 
13089     // For cond-expression: .floor.iv < NumIterations
13090     ExprResult CondExpr = BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(),
13091                                      BO_LT, FloorIV, NumIterations);
13092     if (!CondExpr.isUsable())
13093       return StmtError();
13094 
13095     // For incr-statement: .floor.iv += DimTileSize
13096     ExprResult IncrStmt = BuildBinOp(CurScope, LoopHelper.Inc->getExprLoc(),
13097                                      BO_AddAssign, FloorIV, DimTileSize);
13098     if (!IncrStmt.isUsable())
13099       return StmtError();
13100 
13101     Inner = new (Context)
13102         ForStmt(Context, InitStmt.get(), CondExpr.get(), nullptr,
13103                 IncrStmt.get(), Inner, LoopHelper.Init->getBeginLoc(),
13104                 LoopHelper.Init->getBeginLoc(), LoopHelper.Inc->getEndLoc());
13105   }
13106 
13107   return OMPTileDirective::Create(Context, StartLoc, EndLoc, Clauses, NumLoops,
13108                                   AStmt, Inner,
13109                                   buildPreInits(Context, PreInits));
13110 }
13111 
13112 StmtResult Sema::ActOnOpenMPUnrollDirective(ArrayRef<OMPClause *> Clauses,
13113                                             Stmt *AStmt,
13114                                             SourceLocation StartLoc,
13115                                             SourceLocation EndLoc) {
13116   // Empty statement should only be possible if there already was an error.
13117   if (!AStmt)
13118     return StmtError();
13119 
13120   if (checkMutuallyExclusiveClauses(*this, Clauses, {OMPC_partial, OMPC_full}))
13121     return StmtError();
13122 
13123   const OMPFullClause *FullClause =
13124       OMPExecutableDirective::getSingleClause<OMPFullClause>(Clauses);
13125   const OMPPartialClause *PartialClause =
13126       OMPExecutableDirective::getSingleClause<OMPPartialClause>(Clauses);
13127   assert(!(FullClause && PartialClause) &&
13128          "mutual exclusivity must have been checked before");
13129 
13130   constexpr unsigned NumLoops = 1;
13131   Stmt *Body = nullptr;
13132   SmallVector<OMPLoopBasedDirective::HelperExprs, NumLoops> LoopHelpers(
13133       NumLoops);
13134   SmallVector<SmallVector<llvm::PointerUnion<Stmt *, Decl *>, 0>, NumLoops + 1>
13135       OriginalInits;
13136   if (!checkTransformableLoopNest(OMPD_unroll, AStmt, NumLoops, LoopHelpers,
13137                                   Body, OriginalInits))
13138     return StmtError();
13139 
13140   unsigned NumGeneratedLoops = PartialClause ? 1 : 0;
13141 
13142   // Delay unrolling to when template is completely instantiated.
13143   if (CurContext->isDependentContext())
13144     return OMPUnrollDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
13145                                       NumGeneratedLoops, nullptr, nullptr);
13146 
13147   OMPLoopBasedDirective::HelperExprs &LoopHelper = LoopHelpers.front();
13148 
13149   if (FullClause) {
13150     if (!VerifyPositiveIntegerConstantInClause(
13151              LoopHelper.NumIterations, OMPC_full, /*StrictlyPositive=*/false,
13152              /*SuppressExprDiags=*/true)
13153              .isUsable()) {
13154       Diag(AStmt->getBeginLoc(), diag::err_omp_unroll_full_variable_trip_count);
13155       Diag(FullClause->getBeginLoc(), diag::note_omp_directive_here)
13156           << "#pragma omp unroll full";
13157       return StmtError();
13158     }
13159   }
13160 
13161   // The generated loop may only be passed to other loop-associated directive
13162   // when a partial clause is specified. Without the requirement it is
13163   // sufficient to generate loop unroll metadata at code-generation.
13164   if (NumGeneratedLoops == 0)
13165     return OMPUnrollDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
13166                                       NumGeneratedLoops, nullptr, nullptr);
13167 
13168   // Otherwise, we need to provide a de-sugared/transformed AST that can be
13169   // associated with another loop directive.
13170   //
13171   // The canonical loop analysis return by checkTransformableLoopNest assumes
13172   // the following structure to be the same loop without transformations or
13173   // directives applied: \code OriginalInits; LoopHelper.PreInits;
13174   // LoopHelper.Counters;
13175   // for (; IV < LoopHelper.NumIterations; ++IV) {
13176   //   LoopHelper.Updates;
13177   //   Body;
13178   // }
13179   // \endcode
13180   // where IV is a variable declared and initialized to 0 in LoopHelper.PreInits
13181   // and referenced by LoopHelper.IterationVarRef.
13182   //
13183   // The unrolling directive transforms this into the following loop:
13184   // \code
13185   // OriginalInits;         \
13186   // LoopHelper.PreInits;    > NewPreInits
13187   // LoopHelper.Counters;   /
13188   // for (auto UIV = 0; UIV < LoopHelper.NumIterations; UIV+=Factor) {
13189   //   #pragma clang loop unroll_count(Factor)
13190   //   for (IV = UIV; IV < UIV + Factor && UIV < LoopHelper.NumIterations; ++IV)
13191   //   {
13192   //     LoopHelper.Updates;
13193   //     Body;
13194   //   }
13195   // }
13196   // \endcode
13197   // where UIV is a new logical iteration counter. IV must be the same VarDecl
13198   // as the original LoopHelper.IterationVarRef because LoopHelper.Updates
13199   // references it. If the partially unrolled loop is associated with another
13200   // loop directive (like an OMPForDirective), it will use checkOpenMPLoop to
13201   // analyze this loop, i.e. the outer loop must fulfill the constraints of an
13202   // OpenMP canonical loop. The inner loop is not an associable canonical loop
13203   // and only exists to defer its unrolling to LLVM's LoopUnroll instead of
13204   // doing it in the frontend (by adding loop metadata). NewPreInits becomes a
13205   // property of the OMPLoopBasedDirective instead of statements in
13206   // CompoundStatement. This is to allow the loop to become a non-outermost loop
13207   // of a canonical loop nest where these PreInits are emitted before the
13208   // outermost directive.
13209 
13210   // Determine the PreInit declarations.
13211   SmallVector<Decl *, 4> PreInits;
13212   assert(OriginalInits.size() == 1 &&
13213          "Expecting a single-dimensional loop iteration space");
13214   for (auto &P : OriginalInits[0]) {
13215     if (auto *D = P.dyn_cast<Decl *>())
13216       PreInits.push_back(D);
13217     else if (auto *PI = dyn_cast_or_null<DeclStmt>(P.dyn_cast<Stmt *>()))
13218       PreInits.append(PI->decl_begin(), PI->decl_end());
13219   }
13220   if (auto *PI = cast_or_null<DeclStmt>(LoopHelper.PreInits))
13221     PreInits.append(PI->decl_begin(), PI->decl_end());
13222   // Gather declarations for the data members used as counters.
13223   for (Expr *CounterRef : LoopHelper.Counters) {
13224     auto *CounterDecl = cast<DeclRefExpr>(CounterRef)->getDecl();
13225     if (isa<OMPCapturedExprDecl>(CounterDecl))
13226       PreInits.push_back(CounterDecl);
13227   }
13228 
13229   auto *IterationVarRef = cast<DeclRefExpr>(LoopHelper.IterationVarRef);
13230   QualType IVTy = IterationVarRef->getType();
13231   assert(LoopHelper.Counters.size() == 1 &&
13232          "Expecting a single-dimensional loop iteration space");
13233   auto *OrigVar = cast<DeclRefExpr>(LoopHelper.Counters.front());
13234 
13235   // Determine the unroll factor.
13236   uint64_t Factor;
13237   SourceLocation FactorLoc;
13238   if (Expr *FactorVal = PartialClause->getFactor()) {
13239     Factor =
13240         FactorVal->getIntegerConstantExpr(Context).getValue().getZExtValue();
13241     FactorLoc = FactorVal->getExprLoc();
13242   } else {
13243     // TODO: Use a better profitability model.
13244     Factor = 2;
13245   }
13246   assert(Factor > 0 && "Expected positive unroll factor");
13247   auto MakeFactorExpr = [this, Factor, IVTy, FactorLoc]() {
13248     return IntegerLiteral::Create(
13249         Context, llvm::APInt(Context.getIntWidth(IVTy), Factor), IVTy,
13250         FactorLoc);
13251   };
13252 
13253   // Iteration variable SourceLocations.
13254   SourceLocation OrigVarLoc = OrigVar->getExprLoc();
13255   SourceLocation OrigVarLocBegin = OrigVar->getBeginLoc();
13256   SourceLocation OrigVarLocEnd = OrigVar->getEndLoc();
13257 
13258   // Internal variable names.
13259   std::string OrigVarName = OrigVar->getNameInfo().getAsString();
13260   std::string OuterIVName = (Twine(".unrolled.iv.") + OrigVarName).str();
13261   std::string InnerIVName = (Twine(".unroll_inner.iv.") + OrigVarName).str();
13262   std::string InnerTripCountName =
13263       (Twine(".unroll_inner.tripcount.") + OrigVarName).str();
13264 
13265   // Create the iteration variable for the unrolled loop.
13266   VarDecl *OuterIVDecl =
13267       buildVarDecl(*this, {}, IVTy, OuterIVName, nullptr, OrigVar);
13268   auto MakeOuterRef = [this, OuterIVDecl, IVTy, OrigVarLoc]() {
13269     return buildDeclRefExpr(*this, OuterIVDecl, IVTy, OrigVarLoc);
13270   };
13271 
13272   // Iteration variable for the inner loop: Reuse the iteration variable created
13273   // by checkOpenMPLoop.
13274   auto *InnerIVDecl = cast<VarDecl>(IterationVarRef->getDecl());
13275   InnerIVDecl->setDeclName(&PP.getIdentifierTable().get(InnerIVName));
13276   auto MakeInnerRef = [this, InnerIVDecl, IVTy, OrigVarLoc]() {
13277     return buildDeclRefExpr(*this, InnerIVDecl, IVTy, OrigVarLoc);
13278   };
13279 
13280   // Make a copy of the NumIterations expression for each use: By the AST
13281   // constraints, every expression object in a DeclContext must be unique.
13282   CaptureVars CopyTransformer(*this);
13283   auto MakeNumIterations = [&CopyTransformer, &LoopHelper]() -> Expr * {
13284     return AssertSuccess(
13285         CopyTransformer.TransformExpr(LoopHelper.NumIterations));
13286   };
13287 
13288   // Inner For init-statement: auto .unroll_inner.iv = .unrolled.iv
13289   ExprResult LValueConv = DefaultLvalueConversion(MakeOuterRef());
13290   AddInitializerToDecl(InnerIVDecl, LValueConv.get(), /*DirectInit=*/false);
13291   StmtResult InnerInit = new (Context)
13292       DeclStmt(DeclGroupRef(InnerIVDecl), OrigVarLocBegin, OrigVarLocEnd);
13293   if (!InnerInit.isUsable())
13294     return StmtError();
13295 
13296   // Inner For cond-expression:
13297   // \code
13298   //   .unroll_inner.iv < .unrolled.iv + Factor &&
13299   //   .unroll_inner.iv < NumIterations
13300   // \endcode
13301   // This conjunction of two conditions allows ScalarEvolution to derive the
13302   // maximum trip count of the inner loop.
13303   ExprResult EndOfTile = BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(),
13304                                     BO_Add, MakeOuterRef(), MakeFactorExpr());
13305   if (!EndOfTile.isUsable())
13306     return StmtError();
13307   ExprResult InnerCond1 = BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(),
13308                                      BO_LE, MakeInnerRef(), EndOfTile.get());
13309   if (!InnerCond1.isUsable())
13310     return StmtError();
13311   ExprResult InnerCond2 =
13312       BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), BO_LE, MakeInnerRef(),
13313                  MakeNumIterations());
13314   if (!InnerCond2.isUsable())
13315     return StmtError();
13316   ExprResult InnerCond =
13317       BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), BO_LAnd,
13318                  InnerCond1.get(), InnerCond2.get());
13319   if (!InnerCond.isUsable())
13320     return StmtError();
13321 
13322   // Inner For incr-statement: ++.unroll_inner.iv
13323   ExprResult InnerIncr = BuildUnaryOp(CurScope, LoopHelper.Inc->getExprLoc(),
13324                                       UO_PreInc, MakeInnerRef());
13325   if (!InnerIncr.isUsable())
13326     return StmtError();
13327 
13328   // Inner For statement.
13329   SmallVector<Stmt *> InnerBodyStmts;
13330   InnerBodyStmts.append(LoopHelper.Updates.begin(), LoopHelper.Updates.end());
13331   InnerBodyStmts.push_back(Body);
13332   CompoundStmt *InnerBody = CompoundStmt::Create(
13333       Context, InnerBodyStmts, Body->getBeginLoc(), Body->getEndLoc());
13334   ForStmt *InnerFor = new (Context)
13335       ForStmt(Context, InnerInit.get(), InnerCond.get(), nullptr,
13336               InnerIncr.get(), InnerBody, LoopHelper.Init->getBeginLoc(),
13337               LoopHelper.Init->getBeginLoc(), LoopHelper.Inc->getEndLoc());
13338 
13339   // Unroll metadata for the inner loop.
13340   // This needs to take into account the remainder portion of the unrolled loop,
13341   // hence `unroll(full)` does not apply here, even though the LoopUnroll pass
13342   // supports multiple loop exits. Instead, unroll using a factor equivalent to
13343   // the maximum trip count, which will also generate a remainder loop. Just
13344   // `unroll(enable)` (which could have been useful if the user has not
13345   // specified a concrete factor; even though the outer loop cannot be
13346   // influenced anymore, would avoid more code bloat than necessary) will refuse
13347   // the loop because "Won't unroll; remainder loop could not be generated when
13348   // assuming runtime trip count". Even if it did work, it must not choose a
13349   // larger unroll factor than the maximum loop length, or it would always just
13350   // execute the remainder loop.
13351   LoopHintAttr *UnrollHintAttr =
13352       LoopHintAttr::CreateImplicit(Context, LoopHintAttr::UnrollCount,
13353                                    LoopHintAttr::Numeric, MakeFactorExpr());
13354   AttributedStmt *InnerUnrolled =
13355       AttributedStmt::Create(Context, StartLoc, {UnrollHintAttr}, InnerFor);
13356 
13357   // Outer For init-statement: auto .unrolled.iv = 0
13358   AddInitializerToDecl(
13359       OuterIVDecl, ActOnIntegerConstant(LoopHelper.Init->getExprLoc(), 0).get(),
13360       /*DirectInit=*/false);
13361   StmtResult OuterInit = new (Context)
13362       DeclStmt(DeclGroupRef(OuterIVDecl), OrigVarLocBegin, OrigVarLocEnd);
13363   if (!OuterInit.isUsable())
13364     return StmtError();
13365 
13366   // Outer For cond-expression: .unrolled.iv < NumIterations
13367   ExprResult OuterConde =
13368       BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), BO_LT, MakeOuterRef(),
13369                  MakeNumIterations());
13370   if (!OuterConde.isUsable())
13371     return StmtError();
13372 
13373   // Outer For incr-statement: .unrolled.iv += Factor
13374   ExprResult OuterIncr =
13375       BuildBinOp(CurScope, LoopHelper.Inc->getExprLoc(), BO_AddAssign,
13376                  MakeOuterRef(), MakeFactorExpr());
13377   if (!OuterIncr.isUsable())
13378     return StmtError();
13379 
13380   // Outer For statement.
13381   ForStmt *OuterFor = new (Context)
13382       ForStmt(Context, OuterInit.get(), OuterConde.get(), nullptr,
13383               OuterIncr.get(), InnerUnrolled, LoopHelper.Init->getBeginLoc(),
13384               LoopHelper.Init->getBeginLoc(), LoopHelper.Inc->getEndLoc());
13385 
13386   return OMPUnrollDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
13387                                     NumGeneratedLoops, OuterFor,
13388                                     buildPreInits(Context, PreInits));
13389 }
13390 
13391 OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
13392                                              SourceLocation StartLoc,
13393                                              SourceLocation LParenLoc,
13394                                              SourceLocation EndLoc) {
13395   OMPClause *Res = nullptr;
13396   switch (Kind) {
13397   case OMPC_final:
13398     Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
13399     break;
13400   case OMPC_num_threads:
13401     Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
13402     break;
13403   case OMPC_safelen:
13404     Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
13405     break;
13406   case OMPC_simdlen:
13407     Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
13408     break;
13409   case OMPC_allocator:
13410     Res = ActOnOpenMPAllocatorClause(Expr, StartLoc, LParenLoc, EndLoc);
13411     break;
13412   case OMPC_collapse:
13413     Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
13414     break;
13415   case OMPC_ordered:
13416     Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
13417     break;
13418   case OMPC_num_teams:
13419     Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
13420     break;
13421   case OMPC_thread_limit:
13422     Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
13423     break;
13424   case OMPC_priority:
13425     Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
13426     break;
13427   case OMPC_grainsize:
13428     Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
13429     break;
13430   case OMPC_num_tasks:
13431     Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
13432     break;
13433   case OMPC_hint:
13434     Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
13435     break;
13436   case OMPC_depobj:
13437     Res = ActOnOpenMPDepobjClause(Expr, StartLoc, LParenLoc, EndLoc);
13438     break;
13439   case OMPC_detach:
13440     Res = ActOnOpenMPDetachClause(Expr, StartLoc, LParenLoc, EndLoc);
13441     break;
13442   case OMPC_novariants:
13443     Res = ActOnOpenMPNovariantsClause(Expr, StartLoc, LParenLoc, EndLoc);
13444     break;
13445   case OMPC_nocontext:
13446     Res = ActOnOpenMPNocontextClause(Expr, StartLoc, LParenLoc, EndLoc);
13447     break;
13448   case OMPC_filter:
13449     Res = ActOnOpenMPFilterClause(Expr, StartLoc, LParenLoc, EndLoc);
13450     break;
13451   case OMPC_partial:
13452     Res = ActOnOpenMPPartialClause(Expr, StartLoc, LParenLoc, EndLoc);
13453     break;
13454   case OMPC_align:
13455     Res = ActOnOpenMPAlignClause(Expr, StartLoc, LParenLoc, EndLoc);
13456     break;
13457   case OMPC_device:
13458   case OMPC_if:
13459   case OMPC_default:
13460   case OMPC_proc_bind:
13461   case OMPC_schedule:
13462   case OMPC_private:
13463   case OMPC_firstprivate:
13464   case OMPC_lastprivate:
13465   case OMPC_shared:
13466   case OMPC_reduction:
13467   case OMPC_task_reduction:
13468   case OMPC_in_reduction:
13469   case OMPC_linear:
13470   case OMPC_aligned:
13471   case OMPC_copyin:
13472   case OMPC_copyprivate:
13473   case OMPC_nowait:
13474   case OMPC_untied:
13475   case OMPC_mergeable:
13476   case OMPC_threadprivate:
13477   case OMPC_sizes:
13478   case OMPC_allocate:
13479   case OMPC_flush:
13480   case OMPC_read:
13481   case OMPC_write:
13482   case OMPC_update:
13483   case OMPC_capture:
13484   case OMPC_compare:
13485   case OMPC_seq_cst:
13486   case OMPC_acq_rel:
13487   case OMPC_acquire:
13488   case OMPC_release:
13489   case OMPC_relaxed:
13490   case OMPC_depend:
13491   case OMPC_threads:
13492   case OMPC_simd:
13493   case OMPC_map:
13494   case OMPC_nogroup:
13495   case OMPC_dist_schedule:
13496   case OMPC_defaultmap:
13497   case OMPC_unknown:
13498   case OMPC_uniform:
13499   case OMPC_to:
13500   case OMPC_from:
13501   case OMPC_use_device_ptr:
13502   case OMPC_use_device_addr:
13503   case OMPC_is_device_ptr:
13504   case OMPC_unified_address:
13505   case OMPC_unified_shared_memory:
13506   case OMPC_reverse_offload:
13507   case OMPC_dynamic_allocators:
13508   case OMPC_atomic_default_mem_order:
13509   case OMPC_device_type:
13510   case OMPC_match:
13511   case OMPC_nontemporal:
13512   case OMPC_order:
13513   case OMPC_destroy:
13514   case OMPC_inclusive:
13515   case OMPC_exclusive:
13516   case OMPC_uses_allocators:
13517   case OMPC_affinity:
13518   case OMPC_when:
13519   case OMPC_bind:
13520   default:
13521     llvm_unreachable("Clause is not allowed.");
13522   }
13523   return Res;
13524 }
13525 
13526 // An OpenMP directive such as 'target parallel' has two captured regions:
13527 // for the 'target' and 'parallel' respectively.  This function returns
13528 // the region in which to capture expressions associated with a clause.
13529 // A return value of OMPD_unknown signifies that the expression should not
13530 // be captured.
13531 static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
13532     OpenMPDirectiveKind DKind, OpenMPClauseKind CKind, unsigned OpenMPVersion,
13533     OpenMPDirectiveKind NameModifier = OMPD_unknown) {
13534   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
13535   switch (CKind) {
13536   case OMPC_if:
13537     switch (DKind) {
13538     case OMPD_target_parallel_for_simd:
13539       if (OpenMPVersion >= 50 &&
13540           (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) {
13541         CaptureRegion = OMPD_parallel;
13542         break;
13543       }
13544       LLVM_FALLTHROUGH;
13545     case OMPD_target_parallel:
13546     case OMPD_target_parallel_for:
13547       // If this clause applies to the nested 'parallel' region, capture within
13548       // the 'target' region, otherwise do not capture.
13549       if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
13550         CaptureRegion = OMPD_target;
13551       break;
13552     case OMPD_target_teams_distribute_parallel_for_simd:
13553       if (OpenMPVersion >= 50 &&
13554           (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) {
13555         CaptureRegion = OMPD_parallel;
13556         break;
13557       }
13558       LLVM_FALLTHROUGH;
13559     case OMPD_target_teams_distribute_parallel_for:
13560       // If this clause applies to the nested 'parallel' region, capture within
13561       // the 'teams' region, otherwise do not capture.
13562       if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
13563         CaptureRegion = OMPD_teams;
13564       break;
13565     case OMPD_teams_distribute_parallel_for_simd:
13566       if (OpenMPVersion >= 50 &&
13567           (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) {
13568         CaptureRegion = OMPD_parallel;
13569         break;
13570       }
13571       LLVM_FALLTHROUGH;
13572     case OMPD_teams_distribute_parallel_for:
13573       CaptureRegion = OMPD_teams;
13574       break;
13575     case OMPD_target_update:
13576     case OMPD_target_enter_data:
13577     case OMPD_target_exit_data:
13578       CaptureRegion = OMPD_task;
13579       break;
13580     case OMPD_parallel_master_taskloop:
13581       if (NameModifier == OMPD_unknown || NameModifier == OMPD_taskloop)
13582         CaptureRegion = OMPD_parallel;
13583       break;
13584     case OMPD_parallel_master_taskloop_simd:
13585       if ((OpenMPVersion <= 45 && NameModifier == OMPD_unknown) ||
13586           NameModifier == OMPD_taskloop) {
13587         CaptureRegion = OMPD_parallel;
13588         break;
13589       }
13590       if (OpenMPVersion <= 45)
13591         break;
13592       if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)
13593         CaptureRegion = OMPD_taskloop;
13594       break;
13595     case OMPD_parallel_for_simd:
13596       if (OpenMPVersion <= 45)
13597         break;
13598       if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)
13599         CaptureRegion = OMPD_parallel;
13600       break;
13601     case OMPD_taskloop_simd:
13602     case OMPD_master_taskloop_simd:
13603       if (OpenMPVersion <= 45)
13604         break;
13605       if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)
13606         CaptureRegion = OMPD_taskloop;
13607       break;
13608     case OMPD_distribute_parallel_for_simd:
13609       if (OpenMPVersion <= 45)
13610         break;
13611       if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)
13612         CaptureRegion = OMPD_parallel;
13613       break;
13614     case OMPD_target_simd:
13615       if (OpenMPVersion >= 50 &&
13616           (NameModifier == OMPD_unknown || NameModifier == OMPD_simd))
13617         CaptureRegion = OMPD_target;
13618       break;
13619     case OMPD_teams_distribute_simd:
13620     case OMPD_target_teams_distribute_simd:
13621       if (OpenMPVersion >= 50 &&
13622           (NameModifier == OMPD_unknown || NameModifier == OMPD_simd))
13623         CaptureRegion = OMPD_teams;
13624       break;
13625     case OMPD_cancel:
13626     case OMPD_parallel:
13627     case OMPD_parallel_master:
13628     case OMPD_parallel_sections:
13629     case OMPD_parallel_for:
13630     case OMPD_target:
13631     case OMPD_target_teams:
13632     case OMPD_target_teams_distribute:
13633     case OMPD_distribute_parallel_for:
13634     case OMPD_task:
13635     case OMPD_taskloop:
13636     case OMPD_master_taskloop:
13637     case OMPD_target_data:
13638     case OMPD_simd:
13639     case OMPD_for_simd:
13640     case OMPD_distribute_simd:
13641       // Do not capture if-clause expressions.
13642       break;
13643     case OMPD_threadprivate:
13644     case OMPD_allocate:
13645     case OMPD_taskyield:
13646     case OMPD_barrier:
13647     case OMPD_taskwait:
13648     case OMPD_cancellation_point:
13649     case OMPD_flush:
13650     case OMPD_depobj:
13651     case OMPD_scan:
13652     case OMPD_declare_reduction:
13653     case OMPD_declare_mapper:
13654     case OMPD_declare_simd:
13655     case OMPD_declare_variant:
13656     case OMPD_begin_declare_variant:
13657     case OMPD_end_declare_variant:
13658     case OMPD_declare_target:
13659     case OMPD_end_declare_target:
13660     case OMPD_loop:
13661     case OMPD_teams:
13662     case OMPD_tile:
13663     case OMPD_unroll:
13664     case OMPD_for:
13665     case OMPD_sections:
13666     case OMPD_section:
13667     case OMPD_single:
13668     case OMPD_master:
13669     case OMPD_masked:
13670     case OMPD_critical:
13671     case OMPD_taskgroup:
13672     case OMPD_distribute:
13673     case OMPD_ordered:
13674     case OMPD_atomic:
13675     case OMPD_teams_distribute:
13676     case OMPD_requires:
13677     case OMPD_metadirective:
13678       llvm_unreachable("Unexpected OpenMP directive with if-clause");
13679     case OMPD_unknown:
13680     default:
13681       llvm_unreachable("Unknown OpenMP directive");
13682     }
13683     break;
13684   case OMPC_num_threads:
13685     switch (DKind) {
13686     case OMPD_target_parallel:
13687     case OMPD_target_parallel_for:
13688     case OMPD_target_parallel_for_simd:
13689       CaptureRegion = OMPD_target;
13690       break;
13691     case OMPD_teams_distribute_parallel_for:
13692     case OMPD_teams_distribute_parallel_for_simd:
13693     case OMPD_target_teams_distribute_parallel_for:
13694     case OMPD_target_teams_distribute_parallel_for_simd:
13695       CaptureRegion = OMPD_teams;
13696       break;
13697     case OMPD_parallel:
13698     case OMPD_parallel_master:
13699     case OMPD_parallel_sections:
13700     case OMPD_parallel_for:
13701     case OMPD_parallel_for_simd:
13702     case OMPD_distribute_parallel_for:
13703     case OMPD_distribute_parallel_for_simd:
13704     case OMPD_parallel_master_taskloop:
13705     case OMPD_parallel_master_taskloop_simd:
13706       // Do not capture num_threads-clause expressions.
13707       break;
13708     case OMPD_target_data:
13709     case OMPD_target_enter_data:
13710     case OMPD_target_exit_data:
13711     case OMPD_target_update:
13712     case OMPD_target:
13713     case OMPD_target_simd:
13714     case OMPD_target_teams:
13715     case OMPD_target_teams_distribute:
13716     case OMPD_target_teams_distribute_simd:
13717     case OMPD_cancel:
13718     case OMPD_task:
13719     case OMPD_taskloop:
13720     case OMPD_taskloop_simd:
13721     case OMPD_master_taskloop:
13722     case OMPD_master_taskloop_simd:
13723     case OMPD_threadprivate:
13724     case OMPD_allocate:
13725     case OMPD_taskyield:
13726     case OMPD_barrier:
13727     case OMPD_taskwait:
13728     case OMPD_cancellation_point:
13729     case OMPD_flush:
13730     case OMPD_depobj:
13731     case OMPD_scan:
13732     case OMPD_declare_reduction:
13733     case OMPD_declare_mapper:
13734     case OMPD_declare_simd:
13735     case OMPD_declare_variant:
13736     case OMPD_begin_declare_variant:
13737     case OMPD_end_declare_variant:
13738     case OMPD_declare_target:
13739     case OMPD_end_declare_target:
13740     case OMPD_loop:
13741     case OMPD_teams:
13742     case OMPD_simd:
13743     case OMPD_tile:
13744     case OMPD_unroll:
13745     case OMPD_for:
13746     case OMPD_for_simd:
13747     case OMPD_sections:
13748     case OMPD_section:
13749     case OMPD_single:
13750     case OMPD_master:
13751     case OMPD_masked:
13752     case OMPD_critical:
13753     case OMPD_taskgroup:
13754     case OMPD_distribute:
13755     case OMPD_ordered:
13756     case OMPD_atomic:
13757     case OMPD_distribute_simd:
13758     case OMPD_teams_distribute:
13759     case OMPD_teams_distribute_simd:
13760     case OMPD_requires:
13761     case OMPD_metadirective:
13762       llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
13763     case OMPD_unknown:
13764     default:
13765       llvm_unreachable("Unknown OpenMP directive");
13766     }
13767     break;
13768   case OMPC_num_teams:
13769     switch (DKind) {
13770     case OMPD_target_teams:
13771     case OMPD_target_teams_distribute:
13772     case OMPD_target_teams_distribute_simd:
13773     case OMPD_target_teams_distribute_parallel_for:
13774     case OMPD_target_teams_distribute_parallel_for_simd:
13775       CaptureRegion = OMPD_target;
13776       break;
13777     case OMPD_teams_distribute_parallel_for:
13778     case OMPD_teams_distribute_parallel_for_simd:
13779     case OMPD_teams:
13780     case OMPD_teams_distribute:
13781     case OMPD_teams_distribute_simd:
13782       // Do not capture num_teams-clause expressions.
13783       break;
13784     case OMPD_distribute_parallel_for:
13785     case OMPD_distribute_parallel_for_simd:
13786     case OMPD_task:
13787     case OMPD_taskloop:
13788     case OMPD_taskloop_simd:
13789     case OMPD_master_taskloop:
13790     case OMPD_master_taskloop_simd:
13791     case OMPD_parallel_master_taskloop:
13792     case OMPD_parallel_master_taskloop_simd:
13793     case OMPD_target_data:
13794     case OMPD_target_enter_data:
13795     case OMPD_target_exit_data:
13796     case OMPD_target_update:
13797     case OMPD_cancel:
13798     case OMPD_parallel:
13799     case OMPD_parallel_master:
13800     case OMPD_parallel_sections:
13801     case OMPD_parallel_for:
13802     case OMPD_parallel_for_simd:
13803     case OMPD_target:
13804     case OMPD_target_simd:
13805     case OMPD_target_parallel:
13806     case OMPD_target_parallel_for:
13807     case OMPD_target_parallel_for_simd:
13808     case OMPD_threadprivate:
13809     case OMPD_allocate:
13810     case OMPD_taskyield:
13811     case OMPD_barrier:
13812     case OMPD_taskwait:
13813     case OMPD_cancellation_point:
13814     case OMPD_flush:
13815     case OMPD_depobj:
13816     case OMPD_scan:
13817     case OMPD_declare_reduction:
13818     case OMPD_declare_mapper:
13819     case OMPD_declare_simd:
13820     case OMPD_declare_variant:
13821     case OMPD_begin_declare_variant:
13822     case OMPD_end_declare_variant:
13823     case OMPD_declare_target:
13824     case OMPD_end_declare_target:
13825     case OMPD_loop:
13826     case OMPD_simd:
13827     case OMPD_tile:
13828     case OMPD_unroll:
13829     case OMPD_for:
13830     case OMPD_for_simd:
13831     case OMPD_sections:
13832     case OMPD_section:
13833     case OMPD_single:
13834     case OMPD_master:
13835     case OMPD_masked:
13836     case OMPD_critical:
13837     case OMPD_taskgroup:
13838     case OMPD_distribute:
13839     case OMPD_ordered:
13840     case OMPD_atomic:
13841     case OMPD_distribute_simd:
13842     case OMPD_requires:
13843     case OMPD_metadirective:
13844       llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
13845     case OMPD_unknown:
13846     default:
13847       llvm_unreachable("Unknown OpenMP directive");
13848     }
13849     break;
13850   case OMPC_thread_limit:
13851     switch (DKind) {
13852     case OMPD_target_teams:
13853     case OMPD_target_teams_distribute:
13854     case OMPD_target_teams_distribute_simd:
13855     case OMPD_target_teams_distribute_parallel_for:
13856     case OMPD_target_teams_distribute_parallel_for_simd:
13857       CaptureRegion = OMPD_target;
13858       break;
13859     case OMPD_teams_distribute_parallel_for:
13860     case OMPD_teams_distribute_parallel_for_simd:
13861     case OMPD_teams:
13862     case OMPD_teams_distribute:
13863     case OMPD_teams_distribute_simd:
13864       // Do not capture thread_limit-clause expressions.
13865       break;
13866     case OMPD_distribute_parallel_for:
13867     case OMPD_distribute_parallel_for_simd:
13868     case OMPD_task:
13869     case OMPD_taskloop:
13870     case OMPD_taskloop_simd:
13871     case OMPD_master_taskloop:
13872     case OMPD_master_taskloop_simd:
13873     case OMPD_parallel_master_taskloop:
13874     case OMPD_parallel_master_taskloop_simd:
13875     case OMPD_target_data:
13876     case OMPD_target_enter_data:
13877     case OMPD_target_exit_data:
13878     case OMPD_target_update:
13879     case OMPD_cancel:
13880     case OMPD_parallel:
13881     case OMPD_parallel_master:
13882     case OMPD_parallel_sections:
13883     case OMPD_parallel_for:
13884     case OMPD_parallel_for_simd:
13885     case OMPD_target:
13886     case OMPD_target_simd:
13887     case OMPD_target_parallel:
13888     case OMPD_target_parallel_for:
13889     case OMPD_target_parallel_for_simd:
13890     case OMPD_threadprivate:
13891     case OMPD_allocate:
13892     case OMPD_taskyield:
13893     case OMPD_barrier:
13894     case OMPD_taskwait:
13895     case OMPD_cancellation_point:
13896     case OMPD_flush:
13897     case OMPD_depobj:
13898     case OMPD_scan:
13899     case OMPD_declare_reduction:
13900     case OMPD_declare_mapper:
13901     case OMPD_declare_simd:
13902     case OMPD_declare_variant:
13903     case OMPD_begin_declare_variant:
13904     case OMPD_end_declare_variant:
13905     case OMPD_declare_target:
13906     case OMPD_end_declare_target:
13907     case OMPD_loop:
13908     case OMPD_simd:
13909     case OMPD_tile:
13910     case OMPD_unroll:
13911     case OMPD_for:
13912     case OMPD_for_simd:
13913     case OMPD_sections:
13914     case OMPD_section:
13915     case OMPD_single:
13916     case OMPD_master:
13917     case OMPD_masked:
13918     case OMPD_critical:
13919     case OMPD_taskgroup:
13920     case OMPD_distribute:
13921     case OMPD_ordered:
13922     case OMPD_atomic:
13923     case OMPD_distribute_simd:
13924     case OMPD_requires:
13925     case OMPD_metadirective:
13926       llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
13927     case OMPD_unknown:
13928     default:
13929       llvm_unreachable("Unknown OpenMP directive");
13930     }
13931     break;
13932   case OMPC_schedule:
13933     switch (DKind) {
13934     case OMPD_parallel_for:
13935     case OMPD_parallel_for_simd:
13936     case OMPD_distribute_parallel_for:
13937     case OMPD_distribute_parallel_for_simd:
13938     case OMPD_teams_distribute_parallel_for:
13939     case OMPD_teams_distribute_parallel_for_simd:
13940     case OMPD_target_parallel_for:
13941     case OMPD_target_parallel_for_simd:
13942     case OMPD_target_teams_distribute_parallel_for:
13943     case OMPD_target_teams_distribute_parallel_for_simd:
13944       CaptureRegion = OMPD_parallel;
13945       break;
13946     case OMPD_for:
13947     case OMPD_for_simd:
13948       // Do not capture schedule-clause expressions.
13949       break;
13950     case OMPD_task:
13951     case OMPD_taskloop:
13952     case OMPD_taskloop_simd:
13953     case OMPD_master_taskloop:
13954     case OMPD_master_taskloop_simd:
13955     case OMPD_parallel_master_taskloop:
13956     case OMPD_parallel_master_taskloop_simd:
13957     case OMPD_target_data:
13958     case OMPD_target_enter_data:
13959     case OMPD_target_exit_data:
13960     case OMPD_target_update:
13961     case OMPD_teams:
13962     case OMPD_teams_distribute:
13963     case OMPD_teams_distribute_simd:
13964     case OMPD_target_teams_distribute:
13965     case OMPD_target_teams_distribute_simd:
13966     case OMPD_target:
13967     case OMPD_target_simd:
13968     case OMPD_target_parallel:
13969     case OMPD_cancel:
13970     case OMPD_parallel:
13971     case OMPD_parallel_master:
13972     case OMPD_parallel_sections:
13973     case OMPD_threadprivate:
13974     case OMPD_allocate:
13975     case OMPD_taskyield:
13976     case OMPD_barrier:
13977     case OMPD_taskwait:
13978     case OMPD_cancellation_point:
13979     case OMPD_flush:
13980     case OMPD_depobj:
13981     case OMPD_scan:
13982     case OMPD_declare_reduction:
13983     case OMPD_declare_mapper:
13984     case OMPD_declare_simd:
13985     case OMPD_declare_variant:
13986     case OMPD_begin_declare_variant:
13987     case OMPD_end_declare_variant:
13988     case OMPD_declare_target:
13989     case OMPD_end_declare_target:
13990     case OMPD_loop:
13991     case OMPD_simd:
13992     case OMPD_tile:
13993     case OMPD_unroll:
13994     case OMPD_sections:
13995     case OMPD_section:
13996     case OMPD_single:
13997     case OMPD_master:
13998     case OMPD_masked:
13999     case OMPD_critical:
14000     case OMPD_taskgroup:
14001     case OMPD_distribute:
14002     case OMPD_ordered:
14003     case OMPD_atomic:
14004     case OMPD_distribute_simd:
14005     case OMPD_target_teams:
14006     case OMPD_requires:
14007     case OMPD_metadirective:
14008       llvm_unreachable("Unexpected OpenMP directive with schedule clause");
14009     case OMPD_unknown:
14010     default:
14011       llvm_unreachable("Unknown OpenMP directive");
14012     }
14013     break;
14014   case OMPC_dist_schedule:
14015     switch (DKind) {
14016     case OMPD_teams_distribute_parallel_for:
14017     case OMPD_teams_distribute_parallel_for_simd:
14018     case OMPD_teams_distribute:
14019     case OMPD_teams_distribute_simd:
14020     case OMPD_target_teams_distribute_parallel_for:
14021     case OMPD_target_teams_distribute_parallel_for_simd:
14022     case OMPD_target_teams_distribute:
14023     case OMPD_target_teams_distribute_simd:
14024       CaptureRegion = OMPD_teams;
14025       break;
14026     case OMPD_distribute_parallel_for:
14027     case OMPD_distribute_parallel_for_simd:
14028     case OMPD_distribute:
14029     case OMPD_distribute_simd:
14030       // Do not capture dist_schedule-clause expressions.
14031       break;
14032     case OMPD_parallel_for:
14033     case OMPD_parallel_for_simd:
14034     case OMPD_target_parallel_for_simd:
14035     case OMPD_target_parallel_for:
14036     case OMPD_task:
14037     case OMPD_taskloop:
14038     case OMPD_taskloop_simd:
14039     case OMPD_master_taskloop:
14040     case OMPD_master_taskloop_simd:
14041     case OMPD_parallel_master_taskloop:
14042     case OMPD_parallel_master_taskloop_simd:
14043     case OMPD_target_data:
14044     case OMPD_target_enter_data:
14045     case OMPD_target_exit_data:
14046     case OMPD_target_update:
14047     case OMPD_teams:
14048     case OMPD_target:
14049     case OMPD_target_simd:
14050     case OMPD_target_parallel:
14051     case OMPD_cancel:
14052     case OMPD_parallel:
14053     case OMPD_parallel_master:
14054     case OMPD_parallel_sections:
14055     case OMPD_threadprivate:
14056     case OMPD_allocate:
14057     case OMPD_taskyield:
14058     case OMPD_barrier:
14059     case OMPD_taskwait:
14060     case OMPD_cancellation_point:
14061     case OMPD_flush:
14062     case OMPD_depobj:
14063     case OMPD_scan:
14064     case OMPD_declare_reduction:
14065     case OMPD_declare_mapper:
14066     case OMPD_declare_simd:
14067     case OMPD_declare_variant:
14068     case OMPD_begin_declare_variant:
14069     case OMPD_end_declare_variant:
14070     case OMPD_declare_target:
14071     case OMPD_end_declare_target:
14072     case OMPD_loop:
14073     case OMPD_simd:
14074     case OMPD_tile:
14075     case OMPD_unroll:
14076     case OMPD_for:
14077     case OMPD_for_simd:
14078     case OMPD_sections:
14079     case OMPD_section:
14080     case OMPD_single:
14081     case OMPD_master:
14082     case OMPD_masked:
14083     case OMPD_critical:
14084     case OMPD_taskgroup:
14085     case OMPD_ordered:
14086     case OMPD_atomic:
14087     case OMPD_target_teams:
14088     case OMPD_requires:
14089     case OMPD_metadirective:
14090       llvm_unreachable("Unexpected OpenMP directive with dist_schedule clause");
14091     case OMPD_unknown:
14092     default:
14093       llvm_unreachable("Unknown OpenMP directive");
14094     }
14095     break;
14096   case OMPC_device:
14097     switch (DKind) {
14098     case OMPD_target_update:
14099     case OMPD_target_enter_data:
14100     case OMPD_target_exit_data:
14101     case OMPD_target:
14102     case OMPD_target_simd:
14103     case OMPD_target_teams:
14104     case OMPD_target_parallel:
14105     case OMPD_target_teams_distribute:
14106     case OMPD_target_teams_distribute_simd:
14107     case OMPD_target_parallel_for:
14108     case OMPD_target_parallel_for_simd:
14109     case OMPD_target_teams_distribute_parallel_for:
14110     case OMPD_target_teams_distribute_parallel_for_simd:
14111     case OMPD_dispatch:
14112       CaptureRegion = OMPD_task;
14113       break;
14114     case OMPD_target_data:
14115     case OMPD_interop:
14116       // Do not capture device-clause expressions.
14117       break;
14118     case OMPD_teams_distribute_parallel_for:
14119     case OMPD_teams_distribute_parallel_for_simd:
14120     case OMPD_teams:
14121     case OMPD_teams_distribute:
14122     case OMPD_teams_distribute_simd:
14123     case OMPD_distribute_parallel_for:
14124     case OMPD_distribute_parallel_for_simd:
14125     case OMPD_task:
14126     case OMPD_taskloop:
14127     case OMPD_taskloop_simd:
14128     case OMPD_master_taskloop:
14129     case OMPD_master_taskloop_simd:
14130     case OMPD_parallel_master_taskloop:
14131     case OMPD_parallel_master_taskloop_simd:
14132     case OMPD_cancel:
14133     case OMPD_parallel:
14134     case OMPD_parallel_master:
14135     case OMPD_parallel_sections:
14136     case OMPD_parallel_for:
14137     case OMPD_parallel_for_simd:
14138     case OMPD_threadprivate:
14139     case OMPD_allocate:
14140     case OMPD_taskyield:
14141     case OMPD_barrier:
14142     case OMPD_taskwait:
14143     case OMPD_cancellation_point:
14144     case OMPD_flush:
14145     case OMPD_depobj:
14146     case OMPD_scan:
14147     case OMPD_declare_reduction:
14148     case OMPD_declare_mapper:
14149     case OMPD_declare_simd:
14150     case OMPD_declare_variant:
14151     case OMPD_begin_declare_variant:
14152     case OMPD_end_declare_variant:
14153     case OMPD_declare_target:
14154     case OMPD_end_declare_target:
14155     case OMPD_loop:
14156     case OMPD_simd:
14157     case OMPD_tile:
14158     case OMPD_unroll:
14159     case OMPD_for:
14160     case OMPD_for_simd:
14161     case OMPD_sections:
14162     case OMPD_section:
14163     case OMPD_single:
14164     case OMPD_master:
14165     case OMPD_masked:
14166     case OMPD_critical:
14167     case OMPD_taskgroup:
14168     case OMPD_distribute:
14169     case OMPD_ordered:
14170     case OMPD_atomic:
14171     case OMPD_distribute_simd:
14172     case OMPD_requires:
14173     case OMPD_metadirective:
14174       llvm_unreachable("Unexpected OpenMP directive with device-clause");
14175     case OMPD_unknown:
14176     default:
14177       llvm_unreachable("Unknown OpenMP directive");
14178     }
14179     break;
14180   case OMPC_grainsize:
14181   case OMPC_num_tasks:
14182   case OMPC_final:
14183   case OMPC_priority:
14184     switch (DKind) {
14185     case OMPD_task:
14186     case OMPD_taskloop:
14187     case OMPD_taskloop_simd:
14188     case OMPD_master_taskloop:
14189     case OMPD_master_taskloop_simd:
14190       break;
14191     case OMPD_parallel_master_taskloop:
14192     case OMPD_parallel_master_taskloop_simd:
14193       CaptureRegion = OMPD_parallel;
14194       break;
14195     case OMPD_target_update:
14196     case OMPD_target_enter_data:
14197     case OMPD_target_exit_data:
14198     case OMPD_target:
14199     case OMPD_target_simd:
14200     case OMPD_target_teams:
14201     case OMPD_target_parallel:
14202     case OMPD_target_teams_distribute:
14203     case OMPD_target_teams_distribute_simd:
14204     case OMPD_target_parallel_for:
14205     case OMPD_target_parallel_for_simd:
14206     case OMPD_target_teams_distribute_parallel_for:
14207     case OMPD_target_teams_distribute_parallel_for_simd:
14208     case OMPD_target_data:
14209     case OMPD_teams_distribute_parallel_for:
14210     case OMPD_teams_distribute_parallel_for_simd:
14211     case OMPD_teams:
14212     case OMPD_teams_distribute:
14213     case OMPD_teams_distribute_simd:
14214     case OMPD_distribute_parallel_for:
14215     case OMPD_distribute_parallel_for_simd:
14216     case OMPD_cancel:
14217     case OMPD_parallel:
14218     case OMPD_parallel_master:
14219     case OMPD_parallel_sections:
14220     case OMPD_parallel_for:
14221     case OMPD_parallel_for_simd:
14222     case OMPD_threadprivate:
14223     case OMPD_allocate:
14224     case OMPD_taskyield:
14225     case OMPD_barrier:
14226     case OMPD_taskwait:
14227     case OMPD_cancellation_point:
14228     case OMPD_flush:
14229     case OMPD_depobj:
14230     case OMPD_scan:
14231     case OMPD_declare_reduction:
14232     case OMPD_declare_mapper:
14233     case OMPD_declare_simd:
14234     case OMPD_declare_variant:
14235     case OMPD_begin_declare_variant:
14236     case OMPD_end_declare_variant:
14237     case OMPD_declare_target:
14238     case OMPD_end_declare_target:
14239     case OMPD_loop:
14240     case OMPD_simd:
14241     case OMPD_tile:
14242     case OMPD_unroll:
14243     case OMPD_for:
14244     case OMPD_for_simd:
14245     case OMPD_sections:
14246     case OMPD_section:
14247     case OMPD_single:
14248     case OMPD_master:
14249     case OMPD_masked:
14250     case OMPD_critical:
14251     case OMPD_taskgroup:
14252     case OMPD_distribute:
14253     case OMPD_ordered:
14254     case OMPD_atomic:
14255     case OMPD_distribute_simd:
14256     case OMPD_requires:
14257     case OMPD_metadirective:
14258       llvm_unreachable("Unexpected OpenMP directive with grainsize-clause");
14259     case OMPD_unknown:
14260     default:
14261       llvm_unreachable("Unknown OpenMP directive");
14262     }
14263     break;
14264   case OMPC_novariants:
14265   case OMPC_nocontext:
14266     switch (DKind) {
14267     case OMPD_dispatch:
14268       CaptureRegion = OMPD_task;
14269       break;
14270     default:
14271       llvm_unreachable("Unexpected OpenMP directive");
14272     }
14273     break;
14274   case OMPC_filter:
14275     // Do not capture filter-clause expressions.
14276     break;
14277   case OMPC_when:
14278     if (DKind == OMPD_metadirective) {
14279       CaptureRegion = OMPD_metadirective;
14280     } else if (DKind == OMPD_unknown) {
14281       llvm_unreachable("Unknown OpenMP directive");
14282     } else {
14283       llvm_unreachable("Unexpected OpenMP directive with when clause");
14284     }
14285     break;
14286   case OMPC_firstprivate:
14287   case OMPC_lastprivate:
14288   case OMPC_reduction:
14289   case OMPC_task_reduction:
14290   case OMPC_in_reduction:
14291   case OMPC_linear:
14292   case OMPC_default:
14293   case OMPC_proc_bind:
14294   case OMPC_safelen:
14295   case OMPC_simdlen:
14296   case OMPC_sizes:
14297   case OMPC_allocator:
14298   case OMPC_collapse:
14299   case OMPC_private:
14300   case OMPC_shared:
14301   case OMPC_aligned:
14302   case OMPC_copyin:
14303   case OMPC_copyprivate:
14304   case OMPC_ordered:
14305   case OMPC_nowait:
14306   case OMPC_untied:
14307   case OMPC_mergeable:
14308   case OMPC_threadprivate:
14309   case OMPC_allocate:
14310   case OMPC_flush:
14311   case OMPC_depobj:
14312   case OMPC_read:
14313   case OMPC_write:
14314   case OMPC_update:
14315   case OMPC_capture:
14316   case OMPC_compare:
14317   case OMPC_seq_cst:
14318   case OMPC_acq_rel:
14319   case OMPC_acquire:
14320   case OMPC_release:
14321   case OMPC_relaxed:
14322   case OMPC_depend:
14323   case OMPC_threads:
14324   case OMPC_simd:
14325   case OMPC_map:
14326   case OMPC_nogroup:
14327   case OMPC_hint:
14328   case OMPC_defaultmap:
14329   case OMPC_unknown:
14330   case OMPC_uniform:
14331   case OMPC_to:
14332   case OMPC_from:
14333   case OMPC_use_device_ptr:
14334   case OMPC_use_device_addr:
14335   case OMPC_is_device_ptr:
14336   case OMPC_unified_address:
14337   case OMPC_unified_shared_memory:
14338   case OMPC_reverse_offload:
14339   case OMPC_dynamic_allocators:
14340   case OMPC_atomic_default_mem_order:
14341   case OMPC_device_type:
14342   case OMPC_match:
14343   case OMPC_nontemporal:
14344   case OMPC_order:
14345   case OMPC_destroy:
14346   case OMPC_detach:
14347   case OMPC_inclusive:
14348   case OMPC_exclusive:
14349   case OMPC_uses_allocators:
14350   case OMPC_affinity:
14351   case OMPC_bind:
14352   default:
14353     llvm_unreachable("Unexpected OpenMP clause.");
14354   }
14355   return CaptureRegion;
14356 }
14357 
14358 OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
14359                                      Expr *Condition, SourceLocation StartLoc,
14360                                      SourceLocation LParenLoc,
14361                                      SourceLocation NameModifierLoc,
14362                                      SourceLocation ColonLoc,
14363                                      SourceLocation EndLoc) {
14364   Expr *ValExpr = Condition;
14365   Stmt *HelperValStmt = nullptr;
14366   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
14367   if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
14368       !Condition->isInstantiationDependent() &&
14369       !Condition->containsUnexpandedParameterPack()) {
14370     ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
14371     if (Val.isInvalid())
14372       return nullptr;
14373 
14374     ValExpr = Val.get();
14375 
14376     OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
14377     CaptureRegion = getOpenMPCaptureRegionForClause(
14378         DKind, OMPC_if, LangOpts.OpenMP, NameModifier);
14379     if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
14380       ValExpr = MakeFullExpr(ValExpr).get();
14381       llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
14382       ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
14383       HelperValStmt = buildPreInits(Context, Captures);
14384     }
14385   }
14386 
14387   return new (Context)
14388       OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
14389                   LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
14390 }
14391 
14392 OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
14393                                         SourceLocation StartLoc,
14394                                         SourceLocation LParenLoc,
14395                                         SourceLocation EndLoc) {
14396   Expr *ValExpr = Condition;
14397   Stmt *HelperValStmt = nullptr;
14398   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
14399   if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
14400       !Condition->isInstantiationDependent() &&
14401       !Condition->containsUnexpandedParameterPack()) {
14402     ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
14403     if (Val.isInvalid())
14404       return nullptr;
14405 
14406     ValExpr = MakeFullExpr(Val.get()).get();
14407 
14408     OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
14409     CaptureRegion =
14410         getOpenMPCaptureRegionForClause(DKind, OMPC_final, LangOpts.OpenMP);
14411     if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
14412       ValExpr = MakeFullExpr(ValExpr).get();
14413       llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
14414       ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
14415       HelperValStmt = buildPreInits(Context, Captures);
14416     }
14417   }
14418 
14419   return new (Context) OMPFinalClause(ValExpr, HelperValStmt, CaptureRegion,
14420                                       StartLoc, LParenLoc, EndLoc);
14421 }
14422 
14423 ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
14424                                                         Expr *Op) {
14425   if (!Op)
14426     return ExprError();
14427 
14428   class IntConvertDiagnoser : public ICEConvertDiagnoser {
14429   public:
14430     IntConvertDiagnoser()
14431         : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
14432     SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
14433                                          QualType T) override {
14434       return S.Diag(Loc, diag::err_omp_not_integral) << T;
14435     }
14436     SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
14437                                              QualType T) override {
14438       return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
14439     }
14440     SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
14441                                                QualType T,
14442                                                QualType ConvTy) override {
14443       return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
14444     }
14445     SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
14446                                            QualType ConvTy) override {
14447       return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
14448              << ConvTy->isEnumeralType() << ConvTy;
14449     }
14450     SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
14451                                             QualType T) override {
14452       return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
14453     }
14454     SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
14455                                         QualType ConvTy) override {
14456       return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
14457              << ConvTy->isEnumeralType() << ConvTy;
14458     }
14459     SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
14460                                              QualType) override {
14461       llvm_unreachable("conversion functions are permitted");
14462     }
14463   } ConvertDiagnoser;
14464   return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
14465 }
14466 
14467 static bool
14468 isNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef, OpenMPClauseKind CKind,
14469                           bool StrictlyPositive, bool BuildCapture = false,
14470                           OpenMPDirectiveKind DKind = OMPD_unknown,
14471                           OpenMPDirectiveKind *CaptureRegion = nullptr,
14472                           Stmt **HelperValStmt = nullptr) {
14473   if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
14474       !ValExpr->isInstantiationDependent()) {
14475     SourceLocation Loc = ValExpr->getExprLoc();
14476     ExprResult Value =
14477         SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
14478     if (Value.isInvalid())
14479       return false;
14480 
14481     ValExpr = Value.get();
14482     // The expression must evaluate to a non-negative integer value.
14483     if (Optional<llvm::APSInt> Result =
14484             ValExpr->getIntegerConstantExpr(SemaRef.Context)) {
14485       if (Result->isSigned() &&
14486           !((!StrictlyPositive && Result->isNonNegative()) ||
14487             (StrictlyPositive && Result->isStrictlyPositive()))) {
14488         SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
14489             << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
14490             << ValExpr->getSourceRange();
14491         return false;
14492       }
14493     }
14494     if (!BuildCapture)
14495       return true;
14496     *CaptureRegion =
14497         getOpenMPCaptureRegionForClause(DKind, CKind, SemaRef.LangOpts.OpenMP);
14498     if (*CaptureRegion != OMPD_unknown &&
14499         !SemaRef.CurContext->isDependentContext()) {
14500       ValExpr = SemaRef.MakeFullExpr(ValExpr).get();
14501       llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
14502       ValExpr = tryBuildCapture(SemaRef, ValExpr, Captures).get();
14503       *HelperValStmt = buildPreInits(SemaRef.Context, Captures);
14504     }
14505   }
14506   return true;
14507 }
14508 
14509 OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
14510                                              SourceLocation StartLoc,
14511                                              SourceLocation LParenLoc,
14512                                              SourceLocation EndLoc) {
14513   Expr *ValExpr = NumThreads;
14514   Stmt *HelperValStmt = nullptr;
14515 
14516   // OpenMP [2.5, Restrictions]
14517   //  The num_threads expression must evaluate to a positive integer value.
14518   if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
14519                                  /*StrictlyPositive=*/true))
14520     return nullptr;
14521 
14522   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
14523   OpenMPDirectiveKind CaptureRegion =
14524       getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads, LangOpts.OpenMP);
14525   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
14526     ValExpr = MakeFullExpr(ValExpr).get();
14527     llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
14528     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
14529     HelperValStmt = buildPreInits(Context, Captures);
14530   }
14531 
14532   return new (Context) OMPNumThreadsClause(
14533       ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
14534 }
14535 
14536 ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
14537                                                        OpenMPClauseKind CKind,
14538                                                        bool StrictlyPositive,
14539                                                        bool SuppressExprDiags) {
14540   if (!E)
14541     return ExprError();
14542   if (E->isValueDependent() || E->isTypeDependent() ||
14543       E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
14544     return E;
14545 
14546   llvm::APSInt Result;
14547   ExprResult ICE;
14548   if (SuppressExprDiags) {
14549     // Use a custom diagnoser that suppresses 'note' diagnostics about the
14550     // expression.
14551     struct SuppressedDiagnoser : public Sema::VerifyICEDiagnoser {
14552       SuppressedDiagnoser() : VerifyICEDiagnoser(/*Suppress=*/true) {}
14553       Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
14554                                                  SourceLocation Loc) override {
14555         llvm_unreachable("Diagnostic suppressed");
14556       }
14557     } Diagnoser;
14558     ICE = VerifyIntegerConstantExpression(E, &Result, Diagnoser, AllowFold);
14559   } else {
14560     ICE = VerifyIntegerConstantExpression(E, &Result, /*FIXME*/ AllowFold);
14561   }
14562   if (ICE.isInvalid())
14563     return ExprError();
14564 
14565   if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
14566       (!StrictlyPositive && !Result.isNonNegative())) {
14567     Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
14568         << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
14569         << E->getSourceRange();
14570     return ExprError();
14571   }
14572   if ((CKind == OMPC_aligned || CKind == OMPC_align) && !Result.isPowerOf2()) {
14573     Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
14574         << E->getSourceRange();
14575     return ExprError();
14576   }
14577   if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
14578     DSAStack->setAssociatedLoops(Result.getExtValue());
14579   else if (CKind == OMPC_ordered)
14580     DSAStack->setAssociatedLoops(Result.getExtValue());
14581   return ICE;
14582 }
14583 
14584 OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
14585                                           SourceLocation LParenLoc,
14586                                           SourceLocation EndLoc) {
14587   // OpenMP [2.8.1, simd construct, Description]
14588   // The parameter of the safelen clause must be a constant
14589   // positive integer expression.
14590   ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
14591   if (Safelen.isInvalid())
14592     return nullptr;
14593   return new (Context)
14594       OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
14595 }
14596 
14597 OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
14598                                           SourceLocation LParenLoc,
14599                                           SourceLocation EndLoc) {
14600   // OpenMP [2.8.1, simd construct, Description]
14601   // The parameter of the simdlen clause must be a constant
14602   // positive integer expression.
14603   ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
14604   if (Simdlen.isInvalid())
14605     return nullptr;
14606   return new (Context)
14607       OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
14608 }
14609 
14610 /// Tries to find omp_allocator_handle_t type.
14611 static bool findOMPAllocatorHandleT(Sema &S, SourceLocation Loc,
14612                                     DSAStackTy *Stack) {
14613   QualType OMPAllocatorHandleT = Stack->getOMPAllocatorHandleT();
14614   if (!OMPAllocatorHandleT.isNull())
14615     return true;
14616   // Build the predefined allocator expressions.
14617   bool ErrorFound = false;
14618   for (int I = 0; I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
14619     auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
14620     StringRef Allocator =
14621         OMPAllocateDeclAttr::ConvertAllocatorTypeTyToStr(AllocatorKind);
14622     DeclarationName AllocatorName = &S.getASTContext().Idents.get(Allocator);
14623     auto *VD = dyn_cast_or_null<ValueDecl>(
14624         S.LookupSingleName(S.TUScope, AllocatorName, Loc, Sema::LookupAnyName));
14625     if (!VD) {
14626       ErrorFound = true;
14627       break;
14628     }
14629     QualType AllocatorType =
14630         VD->getType().getNonLValueExprType(S.getASTContext());
14631     ExprResult Res = S.BuildDeclRefExpr(VD, AllocatorType, VK_LValue, Loc);
14632     if (!Res.isUsable()) {
14633       ErrorFound = true;
14634       break;
14635     }
14636     if (OMPAllocatorHandleT.isNull())
14637       OMPAllocatorHandleT = AllocatorType;
14638     if (!S.getASTContext().hasSameType(OMPAllocatorHandleT, AllocatorType)) {
14639       ErrorFound = true;
14640       break;
14641     }
14642     Stack->setAllocator(AllocatorKind, Res.get());
14643   }
14644   if (ErrorFound) {
14645     S.Diag(Loc, diag::err_omp_implied_type_not_found)
14646         << "omp_allocator_handle_t";
14647     return false;
14648   }
14649   OMPAllocatorHandleT.addConst();
14650   Stack->setOMPAllocatorHandleT(OMPAllocatorHandleT);
14651   return true;
14652 }
14653 
14654 OMPClause *Sema::ActOnOpenMPAllocatorClause(Expr *A, SourceLocation StartLoc,
14655                                             SourceLocation LParenLoc,
14656                                             SourceLocation EndLoc) {
14657   // OpenMP [2.11.3, allocate Directive, Description]
14658   // allocator is an expression of omp_allocator_handle_t type.
14659   if (!findOMPAllocatorHandleT(*this, A->getExprLoc(), DSAStack))
14660     return nullptr;
14661 
14662   ExprResult Allocator = DefaultLvalueConversion(A);
14663   if (Allocator.isInvalid())
14664     return nullptr;
14665   Allocator = PerformImplicitConversion(Allocator.get(),
14666                                         DSAStack->getOMPAllocatorHandleT(),
14667                                         Sema::AA_Initializing,
14668                                         /*AllowExplicit=*/true);
14669   if (Allocator.isInvalid())
14670     return nullptr;
14671   return new (Context)
14672       OMPAllocatorClause(Allocator.get(), StartLoc, LParenLoc, EndLoc);
14673 }
14674 
14675 OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
14676                                            SourceLocation StartLoc,
14677                                            SourceLocation LParenLoc,
14678                                            SourceLocation EndLoc) {
14679   // OpenMP [2.7.1, loop construct, Description]
14680   // OpenMP [2.8.1, simd construct, Description]
14681   // OpenMP [2.9.6, distribute construct, Description]
14682   // The parameter of the collapse clause must be a constant
14683   // positive integer expression.
14684   ExprResult NumForLoopsResult =
14685       VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
14686   if (NumForLoopsResult.isInvalid())
14687     return nullptr;
14688   return new (Context)
14689       OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
14690 }
14691 
14692 OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
14693                                           SourceLocation EndLoc,
14694                                           SourceLocation LParenLoc,
14695                                           Expr *NumForLoops) {
14696   // OpenMP [2.7.1, loop construct, Description]
14697   // OpenMP [2.8.1, simd construct, Description]
14698   // OpenMP [2.9.6, distribute construct, Description]
14699   // The parameter of the ordered clause must be a constant
14700   // positive integer expression if any.
14701   if (NumForLoops && LParenLoc.isValid()) {
14702     ExprResult NumForLoopsResult =
14703         VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
14704     if (NumForLoopsResult.isInvalid())
14705       return nullptr;
14706     NumForLoops = NumForLoopsResult.get();
14707   } else {
14708     NumForLoops = nullptr;
14709   }
14710   auto *Clause = OMPOrderedClause::Create(
14711       Context, NumForLoops, NumForLoops ? DSAStack->getAssociatedLoops() : 0,
14712       StartLoc, LParenLoc, EndLoc);
14713   DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops, Clause);
14714   return Clause;
14715 }
14716 
14717 OMPClause *Sema::ActOnOpenMPSimpleClause(
14718     OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
14719     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
14720   OMPClause *Res = nullptr;
14721   switch (Kind) {
14722   case OMPC_default:
14723     Res = ActOnOpenMPDefaultClause(static_cast<DefaultKind>(Argument),
14724                                    ArgumentLoc, StartLoc, LParenLoc, EndLoc);
14725     break;
14726   case OMPC_proc_bind:
14727     Res = ActOnOpenMPProcBindClause(static_cast<ProcBindKind>(Argument),
14728                                     ArgumentLoc, StartLoc, LParenLoc, EndLoc);
14729     break;
14730   case OMPC_atomic_default_mem_order:
14731     Res = ActOnOpenMPAtomicDefaultMemOrderClause(
14732         static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Argument),
14733         ArgumentLoc, StartLoc, LParenLoc, EndLoc);
14734     break;
14735   case OMPC_order:
14736     Res = ActOnOpenMPOrderClause(static_cast<OpenMPOrderClauseKind>(Argument),
14737                                  ArgumentLoc, StartLoc, LParenLoc, EndLoc);
14738     break;
14739   case OMPC_update:
14740     Res = ActOnOpenMPUpdateClause(static_cast<OpenMPDependClauseKind>(Argument),
14741                                   ArgumentLoc, StartLoc, LParenLoc, EndLoc);
14742     break;
14743   case OMPC_bind:
14744     Res = ActOnOpenMPBindClause(static_cast<OpenMPBindClauseKind>(Argument),
14745                                 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
14746     break;
14747   case OMPC_if:
14748   case OMPC_final:
14749   case OMPC_num_threads:
14750   case OMPC_safelen:
14751   case OMPC_simdlen:
14752   case OMPC_sizes:
14753   case OMPC_allocator:
14754   case OMPC_collapse:
14755   case OMPC_schedule:
14756   case OMPC_private:
14757   case OMPC_firstprivate:
14758   case OMPC_lastprivate:
14759   case OMPC_shared:
14760   case OMPC_reduction:
14761   case OMPC_task_reduction:
14762   case OMPC_in_reduction:
14763   case OMPC_linear:
14764   case OMPC_aligned:
14765   case OMPC_copyin:
14766   case OMPC_copyprivate:
14767   case OMPC_ordered:
14768   case OMPC_nowait:
14769   case OMPC_untied:
14770   case OMPC_mergeable:
14771   case OMPC_threadprivate:
14772   case OMPC_allocate:
14773   case OMPC_flush:
14774   case OMPC_depobj:
14775   case OMPC_read:
14776   case OMPC_write:
14777   case OMPC_capture:
14778   case OMPC_compare:
14779   case OMPC_seq_cst:
14780   case OMPC_acq_rel:
14781   case OMPC_acquire:
14782   case OMPC_release:
14783   case OMPC_relaxed:
14784   case OMPC_depend:
14785   case OMPC_device:
14786   case OMPC_threads:
14787   case OMPC_simd:
14788   case OMPC_map:
14789   case OMPC_num_teams:
14790   case OMPC_thread_limit:
14791   case OMPC_priority:
14792   case OMPC_grainsize:
14793   case OMPC_nogroup:
14794   case OMPC_num_tasks:
14795   case OMPC_hint:
14796   case OMPC_dist_schedule:
14797   case OMPC_defaultmap:
14798   case OMPC_unknown:
14799   case OMPC_uniform:
14800   case OMPC_to:
14801   case OMPC_from:
14802   case OMPC_use_device_ptr:
14803   case OMPC_use_device_addr:
14804   case OMPC_is_device_ptr:
14805   case OMPC_unified_address:
14806   case OMPC_unified_shared_memory:
14807   case OMPC_reverse_offload:
14808   case OMPC_dynamic_allocators:
14809   case OMPC_device_type:
14810   case OMPC_match:
14811   case OMPC_nontemporal:
14812   case OMPC_destroy:
14813   case OMPC_novariants:
14814   case OMPC_nocontext:
14815   case OMPC_detach:
14816   case OMPC_inclusive:
14817   case OMPC_exclusive:
14818   case OMPC_uses_allocators:
14819   case OMPC_affinity:
14820   case OMPC_when:
14821   default:
14822     llvm_unreachable("Clause is not allowed.");
14823   }
14824   return Res;
14825 }
14826 
14827 static std::string
14828 getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
14829                         ArrayRef<unsigned> Exclude = llvm::None) {
14830   SmallString<256> Buffer;
14831   llvm::raw_svector_ostream Out(Buffer);
14832   unsigned Skipped = Exclude.size();
14833   auto S = Exclude.begin(), E = Exclude.end();
14834   for (unsigned I = First; I < Last; ++I) {
14835     if (std::find(S, E, I) != E) {
14836       --Skipped;
14837       continue;
14838     }
14839     Out << "'" << getOpenMPSimpleClauseTypeName(K, I) << "'";
14840     if (I + Skipped + 2 == Last)
14841       Out << " or ";
14842     else if (I + Skipped + 1 != Last)
14843       Out << ", ";
14844   }
14845   return std::string(Out.str());
14846 }
14847 
14848 OMPClause *Sema::ActOnOpenMPDefaultClause(DefaultKind Kind,
14849                                           SourceLocation KindKwLoc,
14850                                           SourceLocation StartLoc,
14851                                           SourceLocation LParenLoc,
14852                                           SourceLocation EndLoc) {
14853   if (Kind == OMP_DEFAULT_unknown) {
14854     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
14855         << getListOfPossibleValues(OMPC_default, /*First=*/0,
14856                                    /*Last=*/unsigned(OMP_DEFAULT_unknown))
14857         << getOpenMPClauseName(OMPC_default);
14858     return nullptr;
14859   }
14860 
14861   switch (Kind) {
14862   case OMP_DEFAULT_none:
14863     DSAStack->setDefaultDSANone(KindKwLoc);
14864     break;
14865   case OMP_DEFAULT_shared:
14866     DSAStack->setDefaultDSAShared(KindKwLoc);
14867     break;
14868   case OMP_DEFAULT_firstprivate:
14869     DSAStack->setDefaultDSAFirstPrivate(KindKwLoc);
14870     break;
14871   default:
14872     llvm_unreachable("DSA unexpected in OpenMP default clause");
14873   }
14874 
14875   return new (Context)
14876       OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
14877 }
14878 
14879 OMPClause *Sema::ActOnOpenMPProcBindClause(ProcBindKind Kind,
14880                                            SourceLocation KindKwLoc,
14881                                            SourceLocation StartLoc,
14882                                            SourceLocation LParenLoc,
14883                                            SourceLocation EndLoc) {
14884   if (Kind == OMP_PROC_BIND_unknown) {
14885     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
14886         << getListOfPossibleValues(OMPC_proc_bind,
14887                                    /*First=*/unsigned(OMP_PROC_BIND_master),
14888                                    /*Last=*/
14889                                    unsigned(LangOpts.OpenMP > 50
14890                                                 ? OMP_PROC_BIND_primary
14891                                                 : OMP_PROC_BIND_spread) +
14892                                        1)
14893         << getOpenMPClauseName(OMPC_proc_bind);
14894     return nullptr;
14895   }
14896   if (Kind == OMP_PROC_BIND_primary && LangOpts.OpenMP < 51)
14897     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
14898         << getListOfPossibleValues(OMPC_proc_bind,
14899                                    /*First=*/unsigned(OMP_PROC_BIND_master),
14900                                    /*Last=*/
14901                                    unsigned(OMP_PROC_BIND_spread) + 1)
14902         << getOpenMPClauseName(OMPC_proc_bind);
14903   return new (Context)
14904       OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
14905 }
14906 
14907 OMPClause *Sema::ActOnOpenMPAtomicDefaultMemOrderClause(
14908     OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindKwLoc,
14909     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
14910   if (Kind == OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown) {
14911     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
14912         << getListOfPossibleValues(
14913                OMPC_atomic_default_mem_order, /*First=*/0,
14914                /*Last=*/OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown)
14915         << getOpenMPClauseName(OMPC_atomic_default_mem_order);
14916     return nullptr;
14917   }
14918   return new (Context) OMPAtomicDefaultMemOrderClause(Kind, KindKwLoc, StartLoc,
14919                                                       LParenLoc, EndLoc);
14920 }
14921 
14922 OMPClause *Sema::ActOnOpenMPOrderClause(OpenMPOrderClauseKind Kind,
14923                                         SourceLocation KindKwLoc,
14924                                         SourceLocation StartLoc,
14925                                         SourceLocation LParenLoc,
14926                                         SourceLocation EndLoc) {
14927   if (Kind == OMPC_ORDER_unknown) {
14928     static_assert(OMPC_ORDER_unknown > 0,
14929                   "OMPC_ORDER_unknown not greater than 0");
14930     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
14931         << getListOfPossibleValues(OMPC_order, /*First=*/0,
14932                                    /*Last=*/OMPC_ORDER_unknown)
14933         << getOpenMPClauseName(OMPC_order);
14934     return nullptr;
14935   }
14936   return new (Context)
14937       OMPOrderClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
14938 }
14939 
14940 OMPClause *Sema::ActOnOpenMPUpdateClause(OpenMPDependClauseKind Kind,
14941                                          SourceLocation KindKwLoc,
14942                                          SourceLocation StartLoc,
14943                                          SourceLocation LParenLoc,
14944                                          SourceLocation EndLoc) {
14945   if (Kind == OMPC_DEPEND_unknown || Kind == OMPC_DEPEND_source ||
14946       Kind == OMPC_DEPEND_sink || Kind == OMPC_DEPEND_depobj) {
14947     unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink,
14948                          OMPC_DEPEND_depobj};
14949     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
14950         << getListOfPossibleValues(OMPC_depend, /*First=*/0,
14951                                    /*Last=*/OMPC_DEPEND_unknown, Except)
14952         << getOpenMPClauseName(OMPC_update);
14953     return nullptr;
14954   }
14955   return OMPUpdateClause::Create(Context, StartLoc, LParenLoc, KindKwLoc, Kind,
14956                                  EndLoc);
14957 }
14958 
14959 OMPClause *Sema::ActOnOpenMPSizesClause(ArrayRef<Expr *> SizeExprs,
14960                                         SourceLocation StartLoc,
14961                                         SourceLocation LParenLoc,
14962                                         SourceLocation EndLoc) {
14963   for (Expr *SizeExpr : SizeExprs) {
14964     ExprResult NumForLoopsResult = VerifyPositiveIntegerConstantInClause(
14965         SizeExpr, OMPC_sizes, /*StrictlyPositive=*/true);
14966     if (!NumForLoopsResult.isUsable())
14967       return nullptr;
14968   }
14969 
14970   DSAStack->setAssociatedLoops(SizeExprs.size());
14971   return OMPSizesClause::Create(Context, StartLoc, LParenLoc, EndLoc,
14972                                 SizeExprs);
14973 }
14974 
14975 OMPClause *Sema::ActOnOpenMPFullClause(SourceLocation StartLoc,
14976                                        SourceLocation EndLoc) {
14977   return OMPFullClause::Create(Context, StartLoc, EndLoc);
14978 }
14979 
14980 OMPClause *Sema::ActOnOpenMPPartialClause(Expr *FactorExpr,
14981                                           SourceLocation StartLoc,
14982                                           SourceLocation LParenLoc,
14983                                           SourceLocation EndLoc) {
14984   if (FactorExpr) {
14985     // If an argument is specified, it must be a constant (or an unevaluated
14986     // template expression).
14987     ExprResult FactorResult = VerifyPositiveIntegerConstantInClause(
14988         FactorExpr, OMPC_partial, /*StrictlyPositive=*/true);
14989     if (FactorResult.isInvalid())
14990       return nullptr;
14991     FactorExpr = FactorResult.get();
14992   }
14993 
14994   return OMPPartialClause::Create(Context, StartLoc, LParenLoc, EndLoc,
14995                                   FactorExpr);
14996 }
14997 
14998 OMPClause *Sema::ActOnOpenMPAlignClause(Expr *A, SourceLocation StartLoc,
14999                                         SourceLocation LParenLoc,
15000                                         SourceLocation EndLoc) {
15001   ExprResult AlignVal;
15002   AlignVal = VerifyPositiveIntegerConstantInClause(A, OMPC_align);
15003   if (AlignVal.isInvalid())
15004     return nullptr;
15005   return OMPAlignClause::Create(Context, AlignVal.get(), StartLoc, LParenLoc,
15006                                 EndLoc);
15007 }
15008 
15009 OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
15010     OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
15011     SourceLocation StartLoc, SourceLocation LParenLoc,
15012     ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
15013     SourceLocation EndLoc) {
15014   OMPClause *Res = nullptr;
15015   switch (Kind) {
15016   case OMPC_schedule:
15017     enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
15018     assert(Argument.size() == NumberOfElements &&
15019            ArgumentLoc.size() == NumberOfElements);
15020     Res = ActOnOpenMPScheduleClause(
15021         static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
15022         static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
15023         static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
15024         StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
15025         ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
15026     break;
15027   case OMPC_if:
15028     assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
15029     Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
15030                               Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
15031                               DelimLoc, EndLoc);
15032     break;
15033   case OMPC_dist_schedule:
15034     Res = ActOnOpenMPDistScheduleClause(
15035         static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
15036         StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
15037     break;
15038   case OMPC_defaultmap:
15039     enum { Modifier, DefaultmapKind };
15040     Res = ActOnOpenMPDefaultmapClause(
15041         static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
15042         static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
15043         StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
15044         EndLoc);
15045     break;
15046   case OMPC_device:
15047     assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
15048     Res = ActOnOpenMPDeviceClause(
15049         static_cast<OpenMPDeviceClauseModifier>(Argument.back()), Expr,
15050         StartLoc, LParenLoc, ArgumentLoc.back(), EndLoc);
15051     break;
15052   case OMPC_final:
15053   case OMPC_num_threads:
15054   case OMPC_safelen:
15055   case OMPC_simdlen:
15056   case OMPC_sizes:
15057   case OMPC_allocator:
15058   case OMPC_collapse:
15059   case OMPC_default:
15060   case OMPC_proc_bind:
15061   case OMPC_private:
15062   case OMPC_firstprivate:
15063   case OMPC_lastprivate:
15064   case OMPC_shared:
15065   case OMPC_reduction:
15066   case OMPC_task_reduction:
15067   case OMPC_in_reduction:
15068   case OMPC_linear:
15069   case OMPC_aligned:
15070   case OMPC_copyin:
15071   case OMPC_copyprivate:
15072   case OMPC_ordered:
15073   case OMPC_nowait:
15074   case OMPC_untied:
15075   case OMPC_mergeable:
15076   case OMPC_threadprivate:
15077   case OMPC_allocate:
15078   case OMPC_flush:
15079   case OMPC_depobj:
15080   case OMPC_read:
15081   case OMPC_write:
15082   case OMPC_update:
15083   case OMPC_capture:
15084   case OMPC_compare:
15085   case OMPC_seq_cst:
15086   case OMPC_acq_rel:
15087   case OMPC_acquire:
15088   case OMPC_release:
15089   case OMPC_relaxed:
15090   case OMPC_depend:
15091   case OMPC_threads:
15092   case OMPC_simd:
15093   case OMPC_map:
15094   case OMPC_num_teams:
15095   case OMPC_thread_limit:
15096   case OMPC_priority:
15097   case OMPC_grainsize:
15098   case OMPC_nogroup:
15099   case OMPC_num_tasks:
15100   case OMPC_hint:
15101   case OMPC_unknown:
15102   case OMPC_uniform:
15103   case OMPC_to:
15104   case OMPC_from:
15105   case OMPC_use_device_ptr:
15106   case OMPC_use_device_addr:
15107   case OMPC_is_device_ptr:
15108   case OMPC_unified_address:
15109   case OMPC_unified_shared_memory:
15110   case OMPC_reverse_offload:
15111   case OMPC_dynamic_allocators:
15112   case OMPC_atomic_default_mem_order:
15113   case OMPC_device_type:
15114   case OMPC_match:
15115   case OMPC_nontemporal:
15116   case OMPC_order:
15117   case OMPC_destroy:
15118   case OMPC_novariants:
15119   case OMPC_nocontext:
15120   case OMPC_detach:
15121   case OMPC_inclusive:
15122   case OMPC_exclusive:
15123   case OMPC_uses_allocators:
15124   case OMPC_affinity:
15125   case OMPC_when:
15126   case OMPC_bind:
15127   default:
15128     llvm_unreachable("Clause is not allowed.");
15129   }
15130   return Res;
15131 }
15132 
15133 static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
15134                                    OpenMPScheduleClauseModifier M2,
15135                                    SourceLocation M1Loc, SourceLocation M2Loc) {
15136   if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
15137     SmallVector<unsigned, 2> Excluded;
15138     if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
15139       Excluded.push_back(M2);
15140     if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
15141       Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
15142     if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
15143       Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
15144     S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
15145         << getListOfPossibleValues(OMPC_schedule,
15146                                    /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
15147                                    /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
15148                                    Excluded)
15149         << getOpenMPClauseName(OMPC_schedule);
15150     return true;
15151   }
15152   return false;
15153 }
15154 
15155 OMPClause *Sema::ActOnOpenMPScheduleClause(
15156     OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
15157     OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
15158     SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
15159     SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
15160   if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
15161       checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
15162     return nullptr;
15163   // OpenMP, 2.7.1, Loop Construct, Restrictions
15164   // Either the monotonic modifier or the nonmonotonic modifier can be specified
15165   // but not both.
15166   if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
15167       (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
15168        M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
15169       (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
15170        M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
15171     Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
15172         << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
15173         << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
15174     return nullptr;
15175   }
15176   if (Kind == OMPC_SCHEDULE_unknown) {
15177     std::string Values;
15178     if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
15179       unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
15180       Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
15181                                        /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
15182                                        Exclude);
15183     } else {
15184       Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
15185                                        /*Last=*/OMPC_SCHEDULE_unknown);
15186     }
15187     Diag(KindLoc, diag::err_omp_unexpected_clause_value)
15188         << Values << getOpenMPClauseName(OMPC_schedule);
15189     return nullptr;
15190   }
15191   // OpenMP, 2.7.1, Loop Construct, Restrictions
15192   // The nonmonotonic modifier can only be specified with schedule(dynamic) or
15193   // schedule(guided).
15194   // OpenMP 5.0 does not have this restriction.
15195   if (LangOpts.OpenMP < 50 &&
15196       (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
15197        M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
15198       Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
15199     Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
15200          diag::err_omp_schedule_nonmonotonic_static);
15201     return nullptr;
15202   }
15203   Expr *ValExpr = ChunkSize;
15204   Stmt *HelperValStmt = nullptr;
15205   if (ChunkSize) {
15206     if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
15207         !ChunkSize->isInstantiationDependent() &&
15208         !ChunkSize->containsUnexpandedParameterPack()) {
15209       SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
15210       ExprResult Val =
15211           PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
15212       if (Val.isInvalid())
15213         return nullptr;
15214 
15215       ValExpr = Val.get();
15216 
15217       // OpenMP [2.7.1, Restrictions]
15218       //  chunk_size must be a loop invariant integer expression with a positive
15219       //  value.
15220       if (Optional<llvm::APSInt> Result =
15221               ValExpr->getIntegerConstantExpr(Context)) {
15222         if (Result->isSigned() && !Result->isStrictlyPositive()) {
15223           Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
15224               << "schedule" << 1 << ChunkSize->getSourceRange();
15225           return nullptr;
15226         }
15227       } else if (getOpenMPCaptureRegionForClause(
15228                      DSAStack->getCurrentDirective(), OMPC_schedule,
15229                      LangOpts.OpenMP) != OMPD_unknown &&
15230                  !CurContext->isDependentContext()) {
15231         ValExpr = MakeFullExpr(ValExpr).get();
15232         llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
15233         ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
15234         HelperValStmt = buildPreInits(Context, Captures);
15235       }
15236     }
15237   }
15238 
15239   return new (Context)
15240       OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
15241                         ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
15242 }
15243 
15244 OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
15245                                    SourceLocation StartLoc,
15246                                    SourceLocation EndLoc) {
15247   OMPClause *Res = nullptr;
15248   switch (Kind) {
15249   case OMPC_ordered:
15250     Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
15251     break;
15252   case OMPC_nowait:
15253     Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
15254     break;
15255   case OMPC_untied:
15256     Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
15257     break;
15258   case OMPC_mergeable:
15259     Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
15260     break;
15261   case OMPC_read:
15262     Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
15263     break;
15264   case OMPC_write:
15265     Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
15266     break;
15267   case OMPC_update:
15268     Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
15269     break;
15270   case OMPC_capture:
15271     Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
15272     break;
15273   case OMPC_compare:
15274     Res = ActOnOpenMPCompareClause(StartLoc, EndLoc);
15275     break;
15276   case OMPC_seq_cst:
15277     Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
15278     break;
15279   case OMPC_acq_rel:
15280     Res = ActOnOpenMPAcqRelClause(StartLoc, EndLoc);
15281     break;
15282   case OMPC_acquire:
15283     Res = ActOnOpenMPAcquireClause(StartLoc, EndLoc);
15284     break;
15285   case OMPC_release:
15286     Res = ActOnOpenMPReleaseClause(StartLoc, EndLoc);
15287     break;
15288   case OMPC_relaxed:
15289     Res = ActOnOpenMPRelaxedClause(StartLoc, EndLoc);
15290     break;
15291   case OMPC_threads:
15292     Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
15293     break;
15294   case OMPC_simd:
15295     Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
15296     break;
15297   case OMPC_nogroup:
15298     Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
15299     break;
15300   case OMPC_unified_address:
15301     Res = ActOnOpenMPUnifiedAddressClause(StartLoc, EndLoc);
15302     break;
15303   case OMPC_unified_shared_memory:
15304     Res = ActOnOpenMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
15305     break;
15306   case OMPC_reverse_offload:
15307     Res = ActOnOpenMPReverseOffloadClause(StartLoc, EndLoc);
15308     break;
15309   case OMPC_dynamic_allocators:
15310     Res = ActOnOpenMPDynamicAllocatorsClause(StartLoc, EndLoc);
15311     break;
15312   case OMPC_destroy:
15313     Res = ActOnOpenMPDestroyClause(/*InteropVar=*/nullptr, StartLoc,
15314                                    /*LParenLoc=*/SourceLocation(),
15315                                    /*VarLoc=*/SourceLocation(), EndLoc);
15316     break;
15317   case OMPC_full:
15318     Res = ActOnOpenMPFullClause(StartLoc, EndLoc);
15319     break;
15320   case OMPC_partial:
15321     Res = ActOnOpenMPPartialClause(nullptr, StartLoc, /*LParenLoc=*/{}, EndLoc);
15322     break;
15323   case OMPC_if:
15324   case OMPC_final:
15325   case OMPC_num_threads:
15326   case OMPC_safelen:
15327   case OMPC_simdlen:
15328   case OMPC_sizes:
15329   case OMPC_allocator:
15330   case OMPC_collapse:
15331   case OMPC_schedule:
15332   case OMPC_private:
15333   case OMPC_firstprivate:
15334   case OMPC_lastprivate:
15335   case OMPC_shared:
15336   case OMPC_reduction:
15337   case OMPC_task_reduction:
15338   case OMPC_in_reduction:
15339   case OMPC_linear:
15340   case OMPC_aligned:
15341   case OMPC_copyin:
15342   case OMPC_copyprivate:
15343   case OMPC_default:
15344   case OMPC_proc_bind:
15345   case OMPC_threadprivate:
15346   case OMPC_allocate:
15347   case OMPC_flush:
15348   case OMPC_depobj:
15349   case OMPC_depend:
15350   case OMPC_device:
15351   case OMPC_map:
15352   case OMPC_num_teams:
15353   case OMPC_thread_limit:
15354   case OMPC_priority:
15355   case OMPC_grainsize:
15356   case OMPC_num_tasks:
15357   case OMPC_hint:
15358   case OMPC_dist_schedule:
15359   case OMPC_defaultmap:
15360   case OMPC_unknown:
15361   case OMPC_uniform:
15362   case OMPC_to:
15363   case OMPC_from:
15364   case OMPC_use_device_ptr:
15365   case OMPC_use_device_addr:
15366   case OMPC_is_device_ptr:
15367   case OMPC_atomic_default_mem_order:
15368   case OMPC_device_type:
15369   case OMPC_match:
15370   case OMPC_nontemporal:
15371   case OMPC_order:
15372   case OMPC_novariants:
15373   case OMPC_nocontext:
15374   case OMPC_detach:
15375   case OMPC_inclusive:
15376   case OMPC_exclusive:
15377   case OMPC_uses_allocators:
15378   case OMPC_affinity:
15379   case OMPC_when:
15380   default:
15381     llvm_unreachable("Clause is not allowed.");
15382   }
15383   return Res;
15384 }
15385 
15386 OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
15387                                          SourceLocation EndLoc) {
15388   DSAStack->setNowaitRegion();
15389   return new (Context) OMPNowaitClause(StartLoc, EndLoc);
15390 }
15391 
15392 OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
15393                                          SourceLocation EndLoc) {
15394   return new (Context) OMPUntiedClause(StartLoc, EndLoc);
15395 }
15396 
15397 OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
15398                                             SourceLocation EndLoc) {
15399   return new (Context) OMPMergeableClause(StartLoc, EndLoc);
15400 }
15401 
15402 OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
15403                                        SourceLocation EndLoc) {
15404   return new (Context) OMPReadClause(StartLoc, EndLoc);
15405 }
15406 
15407 OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
15408                                         SourceLocation EndLoc) {
15409   return new (Context) OMPWriteClause(StartLoc, EndLoc);
15410 }
15411 
15412 OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
15413                                          SourceLocation EndLoc) {
15414   return OMPUpdateClause::Create(Context, StartLoc, EndLoc);
15415 }
15416 
15417 OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
15418                                           SourceLocation EndLoc) {
15419   return new (Context) OMPCaptureClause(StartLoc, EndLoc);
15420 }
15421 
15422 OMPClause *Sema::ActOnOpenMPCompareClause(SourceLocation StartLoc,
15423                                           SourceLocation EndLoc) {
15424   return new (Context) OMPCompareClause(StartLoc, EndLoc);
15425 }
15426 
15427 OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
15428                                          SourceLocation EndLoc) {
15429   return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
15430 }
15431 
15432 OMPClause *Sema::ActOnOpenMPAcqRelClause(SourceLocation StartLoc,
15433                                          SourceLocation EndLoc) {
15434   return new (Context) OMPAcqRelClause(StartLoc, EndLoc);
15435 }
15436 
15437 OMPClause *Sema::ActOnOpenMPAcquireClause(SourceLocation StartLoc,
15438                                           SourceLocation EndLoc) {
15439   return new (Context) OMPAcquireClause(StartLoc, EndLoc);
15440 }
15441 
15442 OMPClause *Sema::ActOnOpenMPReleaseClause(SourceLocation StartLoc,
15443                                           SourceLocation EndLoc) {
15444   return new (Context) OMPReleaseClause(StartLoc, EndLoc);
15445 }
15446 
15447 OMPClause *Sema::ActOnOpenMPRelaxedClause(SourceLocation StartLoc,
15448                                           SourceLocation EndLoc) {
15449   return new (Context) OMPRelaxedClause(StartLoc, EndLoc);
15450 }
15451 
15452 OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
15453                                           SourceLocation EndLoc) {
15454   return new (Context) OMPThreadsClause(StartLoc, EndLoc);
15455 }
15456 
15457 OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
15458                                        SourceLocation EndLoc) {
15459   return new (Context) OMPSIMDClause(StartLoc, EndLoc);
15460 }
15461 
15462 OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
15463                                           SourceLocation EndLoc) {
15464   return new (Context) OMPNogroupClause(StartLoc, EndLoc);
15465 }
15466 
15467 OMPClause *Sema::ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc,
15468                                                  SourceLocation EndLoc) {
15469   return new (Context) OMPUnifiedAddressClause(StartLoc, EndLoc);
15470 }
15471 
15472 OMPClause *Sema::ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc,
15473                                                       SourceLocation EndLoc) {
15474   return new (Context) OMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
15475 }
15476 
15477 OMPClause *Sema::ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc,
15478                                                  SourceLocation EndLoc) {
15479   return new (Context) OMPReverseOffloadClause(StartLoc, EndLoc);
15480 }
15481 
15482 OMPClause *Sema::ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc,
15483                                                     SourceLocation EndLoc) {
15484   return new (Context) OMPDynamicAllocatorsClause(StartLoc, EndLoc);
15485 }
15486 
15487 StmtResult Sema::ActOnOpenMPInteropDirective(ArrayRef<OMPClause *> Clauses,
15488                                              SourceLocation StartLoc,
15489                                              SourceLocation EndLoc) {
15490 
15491   // OpenMP 5.1 [2.15.1, interop Construct, Restrictions]
15492   // At least one action-clause must appear on a directive.
15493   if (!hasClauses(Clauses, OMPC_init, OMPC_use, OMPC_destroy, OMPC_nowait)) {
15494     StringRef Expected = "'init', 'use', 'destroy', or 'nowait'";
15495     Diag(StartLoc, diag::err_omp_no_clause_for_directive)
15496         << Expected << getOpenMPDirectiveName(OMPD_interop);
15497     return StmtError();
15498   }
15499 
15500   // OpenMP 5.1 [2.15.1, interop Construct, Restrictions]
15501   // A depend clause can only appear on the directive if a targetsync
15502   // interop-type is present or the interop-var was initialized with
15503   // the targetsync interop-type.
15504 
15505   // If there is any 'init' clause diagnose if there is no 'init' clause with
15506   // interop-type of 'targetsync'. Cases involving other directives cannot be
15507   // diagnosed.
15508   const OMPDependClause *DependClause = nullptr;
15509   bool HasInitClause = false;
15510   bool IsTargetSync = false;
15511   for (const OMPClause *C : Clauses) {
15512     if (IsTargetSync)
15513       break;
15514     if (const auto *InitClause = dyn_cast<OMPInitClause>(C)) {
15515       HasInitClause = true;
15516       if (InitClause->getIsTargetSync())
15517         IsTargetSync = true;
15518     } else if (const auto *DC = dyn_cast<OMPDependClause>(C)) {
15519       DependClause = DC;
15520     }
15521   }
15522   if (DependClause && HasInitClause && !IsTargetSync) {
15523     Diag(DependClause->getBeginLoc(), diag::err_omp_interop_bad_depend_clause);
15524     return StmtError();
15525   }
15526 
15527   // OpenMP 5.1 [2.15.1, interop Construct, Restrictions]
15528   // Each interop-var may be specified for at most one action-clause of each
15529   // interop construct.
15530   llvm::SmallPtrSet<const VarDecl *, 4> InteropVars;
15531   for (const OMPClause *C : Clauses) {
15532     OpenMPClauseKind ClauseKind = C->getClauseKind();
15533     const DeclRefExpr *DRE = nullptr;
15534     SourceLocation VarLoc;
15535 
15536     if (ClauseKind == OMPC_init) {
15537       const auto *IC = cast<OMPInitClause>(C);
15538       VarLoc = IC->getVarLoc();
15539       DRE = dyn_cast_or_null<DeclRefExpr>(IC->getInteropVar());
15540     } else if (ClauseKind == OMPC_use) {
15541       const auto *UC = cast<OMPUseClause>(C);
15542       VarLoc = UC->getVarLoc();
15543       DRE = dyn_cast_or_null<DeclRefExpr>(UC->getInteropVar());
15544     } else if (ClauseKind == OMPC_destroy) {
15545       const auto *DC = cast<OMPDestroyClause>(C);
15546       VarLoc = DC->getVarLoc();
15547       DRE = dyn_cast_or_null<DeclRefExpr>(DC->getInteropVar());
15548     }
15549 
15550     if (!DRE)
15551       continue;
15552 
15553     if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
15554       if (!InteropVars.insert(VD->getCanonicalDecl()).second) {
15555         Diag(VarLoc, diag::err_omp_interop_var_multiple_actions) << VD;
15556         return StmtError();
15557       }
15558     }
15559   }
15560 
15561   return OMPInteropDirective::Create(Context, StartLoc, EndLoc, Clauses);
15562 }
15563 
15564 static bool isValidInteropVariable(Sema &SemaRef, Expr *InteropVarExpr,
15565                                    SourceLocation VarLoc,
15566                                    OpenMPClauseKind Kind) {
15567   if (InteropVarExpr->isValueDependent() || InteropVarExpr->isTypeDependent() ||
15568       InteropVarExpr->isInstantiationDependent() ||
15569       InteropVarExpr->containsUnexpandedParameterPack())
15570     return true;
15571 
15572   const auto *DRE = dyn_cast<DeclRefExpr>(InteropVarExpr);
15573   if (!DRE || !isa<VarDecl>(DRE->getDecl())) {
15574     SemaRef.Diag(VarLoc, diag::err_omp_interop_variable_expected) << 0;
15575     return false;
15576   }
15577 
15578   // Interop variable should be of type omp_interop_t.
15579   bool HasError = false;
15580   QualType InteropType;
15581   LookupResult Result(SemaRef, &SemaRef.Context.Idents.get("omp_interop_t"),
15582                       VarLoc, Sema::LookupOrdinaryName);
15583   if (SemaRef.LookupName(Result, SemaRef.getCurScope())) {
15584     NamedDecl *ND = Result.getFoundDecl();
15585     if (const auto *TD = dyn_cast<TypeDecl>(ND)) {
15586       InteropType = QualType(TD->getTypeForDecl(), 0);
15587     } else {
15588       HasError = true;
15589     }
15590   } else {
15591     HasError = true;
15592   }
15593 
15594   if (HasError) {
15595     SemaRef.Diag(VarLoc, diag::err_omp_implied_type_not_found)
15596         << "omp_interop_t";
15597     return false;
15598   }
15599 
15600   QualType VarType = InteropVarExpr->getType().getUnqualifiedType();
15601   if (!SemaRef.Context.hasSameType(InteropType, VarType)) {
15602     SemaRef.Diag(VarLoc, diag::err_omp_interop_variable_wrong_type);
15603     return false;
15604   }
15605 
15606   // OpenMP 5.1 [2.15.1, interop Construct, Restrictions]
15607   // The interop-var passed to init or destroy must be non-const.
15608   if ((Kind == OMPC_init || Kind == OMPC_destroy) &&
15609       isConstNotMutableType(SemaRef, InteropVarExpr->getType())) {
15610     SemaRef.Diag(VarLoc, diag::err_omp_interop_variable_expected)
15611         << /*non-const*/ 1;
15612     return false;
15613   }
15614   return true;
15615 }
15616 
15617 OMPClause *
15618 Sema::ActOnOpenMPInitClause(Expr *InteropVar, ArrayRef<Expr *> PrefExprs,
15619                             bool IsTarget, bool IsTargetSync,
15620                             SourceLocation StartLoc, SourceLocation LParenLoc,
15621                             SourceLocation VarLoc, SourceLocation EndLoc) {
15622 
15623   if (!isValidInteropVariable(*this, InteropVar, VarLoc, OMPC_init))
15624     return nullptr;
15625 
15626   // Check prefer_type values.  These foreign-runtime-id values are either
15627   // string literals or constant integral expressions.
15628   for (const Expr *E : PrefExprs) {
15629     if (E->isValueDependent() || E->isTypeDependent() ||
15630         E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
15631       continue;
15632     if (E->isIntegerConstantExpr(Context))
15633       continue;
15634     if (isa<StringLiteral>(E))
15635       continue;
15636     Diag(E->getExprLoc(), diag::err_omp_interop_prefer_type);
15637     return nullptr;
15638   }
15639 
15640   return OMPInitClause::Create(Context, InteropVar, PrefExprs, IsTarget,
15641                                IsTargetSync, StartLoc, LParenLoc, VarLoc,
15642                                EndLoc);
15643 }
15644 
15645 OMPClause *Sema::ActOnOpenMPUseClause(Expr *InteropVar, SourceLocation StartLoc,
15646                                       SourceLocation LParenLoc,
15647                                       SourceLocation VarLoc,
15648                                       SourceLocation EndLoc) {
15649 
15650   if (!isValidInteropVariable(*this, InteropVar, VarLoc, OMPC_use))
15651     return nullptr;
15652 
15653   return new (Context)
15654       OMPUseClause(InteropVar, StartLoc, LParenLoc, VarLoc, EndLoc);
15655 }
15656 
15657 OMPClause *Sema::ActOnOpenMPDestroyClause(Expr *InteropVar,
15658                                           SourceLocation StartLoc,
15659                                           SourceLocation LParenLoc,
15660                                           SourceLocation VarLoc,
15661                                           SourceLocation EndLoc) {
15662   if (InteropVar &&
15663       !isValidInteropVariable(*this, InteropVar, VarLoc, OMPC_destroy))
15664     return nullptr;
15665 
15666   return new (Context)
15667       OMPDestroyClause(InteropVar, StartLoc, LParenLoc, VarLoc, EndLoc);
15668 }
15669 
15670 OMPClause *Sema::ActOnOpenMPNovariantsClause(Expr *Condition,
15671                                              SourceLocation StartLoc,
15672                                              SourceLocation LParenLoc,
15673                                              SourceLocation EndLoc) {
15674   Expr *ValExpr = Condition;
15675   Stmt *HelperValStmt = nullptr;
15676   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
15677   if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
15678       !Condition->isInstantiationDependent() &&
15679       !Condition->containsUnexpandedParameterPack()) {
15680     ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
15681     if (Val.isInvalid())
15682       return nullptr;
15683 
15684     ValExpr = MakeFullExpr(Val.get()).get();
15685 
15686     OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
15687     CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_novariants,
15688                                                     LangOpts.OpenMP);
15689     if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
15690       ValExpr = MakeFullExpr(ValExpr).get();
15691       llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
15692       ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
15693       HelperValStmt = buildPreInits(Context, Captures);
15694     }
15695   }
15696 
15697   return new (Context) OMPNovariantsClause(
15698       ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
15699 }
15700 
15701 OMPClause *Sema::ActOnOpenMPNocontextClause(Expr *Condition,
15702                                             SourceLocation StartLoc,
15703                                             SourceLocation LParenLoc,
15704                                             SourceLocation EndLoc) {
15705   Expr *ValExpr = Condition;
15706   Stmt *HelperValStmt = nullptr;
15707   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
15708   if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
15709       !Condition->isInstantiationDependent() &&
15710       !Condition->containsUnexpandedParameterPack()) {
15711     ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
15712     if (Val.isInvalid())
15713       return nullptr;
15714 
15715     ValExpr = MakeFullExpr(Val.get()).get();
15716 
15717     OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
15718     CaptureRegion =
15719         getOpenMPCaptureRegionForClause(DKind, OMPC_nocontext, LangOpts.OpenMP);
15720     if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
15721       ValExpr = MakeFullExpr(ValExpr).get();
15722       llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
15723       ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
15724       HelperValStmt = buildPreInits(Context, Captures);
15725     }
15726   }
15727 
15728   return new (Context) OMPNocontextClause(ValExpr, HelperValStmt, CaptureRegion,
15729                                           StartLoc, LParenLoc, EndLoc);
15730 }
15731 
15732 OMPClause *Sema::ActOnOpenMPFilterClause(Expr *ThreadID,
15733                                          SourceLocation StartLoc,
15734                                          SourceLocation LParenLoc,
15735                                          SourceLocation EndLoc) {
15736   Expr *ValExpr = ThreadID;
15737   Stmt *HelperValStmt = nullptr;
15738 
15739   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
15740   OpenMPDirectiveKind CaptureRegion =
15741       getOpenMPCaptureRegionForClause(DKind, OMPC_filter, LangOpts.OpenMP);
15742   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
15743     ValExpr = MakeFullExpr(ValExpr).get();
15744     llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
15745     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
15746     HelperValStmt = buildPreInits(Context, Captures);
15747   }
15748 
15749   return new (Context) OMPFilterClause(ValExpr, HelperValStmt, CaptureRegion,
15750                                        StartLoc, LParenLoc, EndLoc);
15751 }
15752 
15753 OMPClause *Sema::ActOnOpenMPVarListClause(
15754     OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *DepModOrTailExpr,
15755     const OMPVarListLocTy &Locs, SourceLocation ColonLoc,
15756     CXXScopeSpec &ReductionOrMapperIdScopeSpec,
15757     DeclarationNameInfo &ReductionOrMapperId, int ExtraModifier,
15758     ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
15759     ArrayRef<SourceLocation> MapTypeModifiersLoc, bool IsMapTypeImplicit,
15760     SourceLocation ExtraModifierLoc,
15761     ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
15762     ArrayRef<SourceLocation> MotionModifiersLoc) {
15763   SourceLocation StartLoc = Locs.StartLoc;
15764   SourceLocation LParenLoc = Locs.LParenLoc;
15765   SourceLocation EndLoc = Locs.EndLoc;
15766   OMPClause *Res = nullptr;
15767   switch (Kind) {
15768   case OMPC_private:
15769     Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
15770     break;
15771   case OMPC_firstprivate:
15772     Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
15773     break;
15774   case OMPC_lastprivate:
15775     assert(0 <= ExtraModifier && ExtraModifier <= OMPC_LASTPRIVATE_unknown &&
15776            "Unexpected lastprivate modifier.");
15777     Res = ActOnOpenMPLastprivateClause(
15778         VarList, static_cast<OpenMPLastprivateModifier>(ExtraModifier),
15779         ExtraModifierLoc, ColonLoc, StartLoc, LParenLoc, EndLoc);
15780     break;
15781   case OMPC_shared:
15782     Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
15783     break;
15784   case OMPC_reduction:
15785     assert(0 <= ExtraModifier && ExtraModifier <= OMPC_REDUCTION_unknown &&
15786            "Unexpected lastprivate modifier.");
15787     Res = ActOnOpenMPReductionClause(
15788         VarList, static_cast<OpenMPReductionClauseModifier>(ExtraModifier),
15789         StartLoc, LParenLoc, ExtraModifierLoc, ColonLoc, EndLoc,
15790         ReductionOrMapperIdScopeSpec, ReductionOrMapperId);
15791     break;
15792   case OMPC_task_reduction:
15793     Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
15794                                          EndLoc, ReductionOrMapperIdScopeSpec,
15795                                          ReductionOrMapperId);
15796     break;
15797   case OMPC_in_reduction:
15798     Res = ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
15799                                        EndLoc, ReductionOrMapperIdScopeSpec,
15800                                        ReductionOrMapperId);
15801     break;
15802   case OMPC_linear:
15803     assert(0 <= ExtraModifier && ExtraModifier <= OMPC_LINEAR_unknown &&
15804            "Unexpected linear modifier.");
15805     Res = ActOnOpenMPLinearClause(
15806         VarList, DepModOrTailExpr, StartLoc, LParenLoc,
15807         static_cast<OpenMPLinearClauseKind>(ExtraModifier), ExtraModifierLoc,
15808         ColonLoc, EndLoc);
15809     break;
15810   case OMPC_aligned:
15811     Res = ActOnOpenMPAlignedClause(VarList, DepModOrTailExpr, StartLoc,
15812                                    LParenLoc, ColonLoc, EndLoc);
15813     break;
15814   case OMPC_copyin:
15815     Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
15816     break;
15817   case OMPC_copyprivate:
15818     Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
15819     break;
15820   case OMPC_flush:
15821     Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
15822     break;
15823   case OMPC_depend:
15824     assert(0 <= ExtraModifier && ExtraModifier <= OMPC_DEPEND_unknown &&
15825            "Unexpected depend modifier.");
15826     Res = ActOnOpenMPDependClause(
15827         DepModOrTailExpr, static_cast<OpenMPDependClauseKind>(ExtraModifier),
15828         ExtraModifierLoc, ColonLoc, VarList, StartLoc, LParenLoc, EndLoc);
15829     break;
15830   case OMPC_map:
15831     assert(0 <= ExtraModifier && ExtraModifier <= OMPC_MAP_unknown &&
15832            "Unexpected map modifier.");
15833     Res = ActOnOpenMPMapClause(
15834         MapTypeModifiers, MapTypeModifiersLoc, ReductionOrMapperIdScopeSpec,
15835         ReductionOrMapperId, static_cast<OpenMPMapClauseKind>(ExtraModifier),
15836         IsMapTypeImplicit, ExtraModifierLoc, ColonLoc, VarList, Locs);
15837     break;
15838   case OMPC_to:
15839     Res = ActOnOpenMPToClause(MotionModifiers, MotionModifiersLoc,
15840                               ReductionOrMapperIdScopeSpec, ReductionOrMapperId,
15841                               ColonLoc, VarList, Locs);
15842     break;
15843   case OMPC_from:
15844     Res = ActOnOpenMPFromClause(MotionModifiers, MotionModifiersLoc,
15845                                 ReductionOrMapperIdScopeSpec,
15846                                 ReductionOrMapperId, ColonLoc, VarList, Locs);
15847     break;
15848   case OMPC_use_device_ptr:
15849     Res = ActOnOpenMPUseDevicePtrClause(VarList, Locs);
15850     break;
15851   case OMPC_use_device_addr:
15852     Res = ActOnOpenMPUseDeviceAddrClause(VarList, Locs);
15853     break;
15854   case OMPC_is_device_ptr:
15855     Res = ActOnOpenMPIsDevicePtrClause(VarList, Locs);
15856     break;
15857   case OMPC_allocate:
15858     Res = ActOnOpenMPAllocateClause(DepModOrTailExpr, VarList, StartLoc,
15859                                     LParenLoc, ColonLoc, EndLoc);
15860     break;
15861   case OMPC_nontemporal:
15862     Res = ActOnOpenMPNontemporalClause(VarList, StartLoc, LParenLoc, EndLoc);
15863     break;
15864   case OMPC_inclusive:
15865     Res = ActOnOpenMPInclusiveClause(VarList, StartLoc, LParenLoc, EndLoc);
15866     break;
15867   case OMPC_exclusive:
15868     Res = ActOnOpenMPExclusiveClause(VarList, StartLoc, LParenLoc, EndLoc);
15869     break;
15870   case OMPC_affinity:
15871     Res = ActOnOpenMPAffinityClause(StartLoc, LParenLoc, ColonLoc, EndLoc,
15872                                     DepModOrTailExpr, VarList);
15873     break;
15874   case OMPC_if:
15875   case OMPC_depobj:
15876   case OMPC_final:
15877   case OMPC_num_threads:
15878   case OMPC_safelen:
15879   case OMPC_simdlen:
15880   case OMPC_sizes:
15881   case OMPC_allocator:
15882   case OMPC_collapse:
15883   case OMPC_default:
15884   case OMPC_proc_bind:
15885   case OMPC_schedule:
15886   case OMPC_ordered:
15887   case OMPC_nowait:
15888   case OMPC_untied:
15889   case OMPC_mergeable:
15890   case OMPC_threadprivate:
15891   case OMPC_read:
15892   case OMPC_write:
15893   case OMPC_update:
15894   case OMPC_capture:
15895   case OMPC_compare:
15896   case OMPC_seq_cst:
15897   case OMPC_acq_rel:
15898   case OMPC_acquire:
15899   case OMPC_release:
15900   case OMPC_relaxed:
15901   case OMPC_device:
15902   case OMPC_threads:
15903   case OMPC_simd:
15904   case OMPC_num_teams:
15905   case OMPC_thread_limit:
15906   case OMPC_priority:
15907   case OMPC_grainsize:
15908   case OMPC_nogroup:
15909   case OMPC_num_tasks:
15910   case OMPC_hint:
15911   case OMPC_dist_schedule:
15912   case OMPC_defaultmap:
15913   case OMPC_unknown:
15914   case OMPC_uniform:
15915   case OMPC_unified_address:
15916   case OMPC_unified_shared_memory:
15917   case OMPC_reverse_offload:
15918   case OMPC_dynamic_allocators:
15919   case OMPC_atomic_default_mem_order:
15920   case OMPC_device_type:
15921   case OMPC_match:
15922   case OMPC_order:
15923   case OMPC_destroy:
15924   case OMPC_novariants:
15925   case OMPC_nocontext:
15926   case OMPC_detach:
15927   case OMPC_uses_allocators:
15928   case OMPC_when:
15929   case OMPC_bind:
15930   default:
15931     llvm_unreachable("Clause is not allowed.");
15932   }
15933   return Res;
15934 }
15935 
15936 ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
15937                                        ExprObjectKind OK, SourceLocation Loc) {
15938   ExprResult Res = BuildDeclRefExpr(
15939       Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
15940   if (!Res.isUsable())
15941     return ExprError();
15942   if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
15943     Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
15944     if (!Res.isUsable())
15945       return ExprError();
15946   }
15947   if (VK != VK_LValue && Res.get()->isGLValue()) {
15948     Res = DefaultLvalueConversion(Res.get());
15949     if (!Res.isUsable())
15950       return ExprError();
15951   }
15952   return Res;
15953 }
15954 
15955 OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
15956                                           SourceLocation StartLoc,
15957                                           SourceLocation LParenLoc,
15958                                           SourceLocation EndLoc) {
15959   SmallVector<Expr *, 8> Vars;
15960   SmallVector<Expr *, 8> PrivateCopies;
15961   for (Expr *RefExpr : VarList) {
15962     assert(RefExpr && "NULL expr in OpenMP private clause.");
15963     SourceLocation ELoc;
15964     SourceRange ERange;
15965     Expr *SimpleRefExpr = RefExpr;
15966     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
15967     if (Res.second) {
15968       // It will be analyzed later.
15969       Vars.push_back(RefExpr);
15970       PrivateCopies.push_back(nullptr);
15971     }
15972     ValueDecl *D = Res.first;
15973     if (!D)
15974       continue;
15975 
15976     QualType Type = D->getType();
15977     auto *VD = dyn_cast<VarDecl>(D);
15978 
15979     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
15980     //  A variable that appears in a private clause must not have an incomplete
15981     //  type or a reference type.
15982     if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
15983       continue;
15984     Type = Type.getNonReferenceType();
15985 
15986     // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
15987     // A variable that is privatized must not have a const-qualified type
15988     // unless it is of class type with a mutable member. This restriction does
15989     // not apply to the firstprivate clause.
15990     //
15991     // OpenMP 3.1 [2.9.3.3, private clause, Restrictions]
15992     // A variable that appears in a private clause must not have a
15993     // const-qualified type unless it is of class type with a mutable member.
15994     if (rejectConstNotMutableType(*this, D, Type, OMPC_private, ELoc))
15995       continue;
15996 
15997     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
15998     // in a Construct]
15999     //  Variables with the predetermined data-sharing attributes may not be
16000     //  listed in data-sharing attributes clauses, except for the cases
16001     //  listed below. For these exceptions only, listing a predetermined
16002     //  variable in a data-sharing attribute clause is allowed and overrides
16003     //  the variable's predetermined data-sharing attributes.
16004     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
16005     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
16006       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
16007                                           << getOpenMPClauseName(OMPC_private);
16008       reportOriginalDsa(*this, DSAStack, D, DVar);
16009       continue;
16010     }
16011 
16012     OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
16013     // Variably modified types are not supported for tasks.
16014     if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
16015         isOpenMPTaskingDirective(CurrDir)) {
16016       Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
16017           << getOpenMPClauseName(OMPC_private) << Type
16018           << getOpenMPDirectiveName(CurrDir);
16019       bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
16020                                VarDecl::DeclarationOnly;
16021       Diag(D->getLocation(),
16022            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
16023           << D;
16024       continue;
16025     }
16026 
16027     // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
16028     // A list item cannot appear in both a map clause and a data-sharing
16029     // attribute clause on the same construct
16030     //
16031     // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
16032     // A list item cannot appear in both a map clause and a data-sharing
16033     // attribute clause on the same construct unless the construct is a
16034     // combined construct.
16035     if ((LangOpts.OpenMP <= 45 && isOpenMPTargetExecutionDirective(CurrDir)) ||
16036         CurrDir == OMPD_target) {
16037       OpenMPClauseKind ConflictKind;
16038       if (DSAStack->checkMappableExprComponentListsForDecl(
16039               VD, /*CurrentRegionOnly=*/true,
16040               [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
16041                   OpenMPClauseKind WhereFoundClauseKind) -> bool {
16042                 ConflictKind = WhereFoundClauseKind;
16043                 return true;
16044               })) {
16045         Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
16046             << getOpenMPClauseName(OMPC_private)
16047             << getOpenMPClauseName(ConflictKind)
16048             << getOpenMPDirectiveName(CurrDir);
16049         reportOriginalDsa(*this, DSAStack, D, DVar);
16050         continue;
16051       }
16052     }
16053 
16054     // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
16055     //  A variable of class type (or array thereof) that appears in a private
16056     //  clause requires an accessible, unambiguous default constructor for the
16057     //  class type.
16058     // Generate helper private variable and initialize it with the default
16059     // value. The address of the original variable is replaced by the address of
16060     // the new private variable in CodeGen. This new variable is not added to
16061     // IdResolver, so the code in the OpenMP region uses original variable for
16062     // proper diagnostics.
16063     Type = Type.getUnqualifiedType();
16064     VarDecl *VDPrivate =
16065         buildVarDecl(*this, ELoc, Type, D->getName(),
16066                      D->hasAttrs() ? &D->getAttrs() : nullptr,
16067                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
16068     ActOnUninitializedDecl(VDPrivate);
16069     if (VDPrivate->isInvalidDecl())
16070       continue;
16071     DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
16072         *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
16073 
16074     DeclRefExpr *Ref = nullptr;
16075     if (!VD && !CurContext->isDependentContext())
16076       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
16077     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
16078     Vars.push_back((VD || CurContext->isDependentContext())
16079                        ? RefExpr->IgnoreParens()
16080                        : Ref);
16081     PrivateCopies.push_back(VDPrivateRefExpr);
16082   }
16083 
16084   if (Vars.empty())
16085     return nullptr;
16086 
16087   return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
16088                                   PrivateCopies);
16089 }
16090 
16091 OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
16092                                                SourceLocation StartLoc,
16093                                                SourceLocation LParenLoc,
16094                                                SourceLocation EndLoc) {
16095   SmallVector<Expr *, 8> Vars;
16096   SmallVector<Expr *, 8> PrivateCopies;
16097   SmallVector<Expr *, 8> Inits;
16098   SmallVector<Decl *, 4> ExprCaptures;
16099   bool IsImplicitClause =
16100       StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
16101   SourceLocation ImplicitClauseLoc = DSAStack->getConstructLoc();
16102 
16103   for (Expr *RefExpr : VarList) {
16104     assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
16105     SourceLocation ELoc;
16106     SourceRange ERange;
16107     Expr *SimpleRefExpr = RefExpr;
16108     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
16109     if (Res.second) {
16110       // It will be analyzed later.
16111       Vars.push_back(RefExpr);
16112       PrivateCopies.push_back(nullptr);
16113       Inits.push_back(nullptr);
16114     }
16115     ValueDecl *D = Res.first;
16116     if (!D)
16117       continue;
16118 
16119     ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
16120     QualType Type = D->getType();
16121     auto *VD = dyn_cast<VarDecl>(D);
16122 
16123     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
16124     //  A variable that appears in a private clause must not have an incomplete
16125     //  type or a reference type.
16126     if (RequireCompleteType(ELoc, Type,
16127                             diag::err_omp_firstprivate_incomplete_type))
16128       continue;
16129     Type = Type.getNonReferenceType();
16130 
16131     // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
16132     //  A variable of class type (or array thereof) that appears in a private
16133     //  clause requires an accessible, unambiguous copy constructor for the
16134     //  class type.
16135     QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
16136 
16137     // If an implicit firstprivate variable found it was checked already.
16138     DSAStackTy::DSAVarData TopDVar;
16139     if (!IsImplicitClause) {
16140       DSAStackTy::DSAVarData DVar =
16141           DSAStack->getTopDSA(D, /*FromParent=*/false);
16142       TopDVar = DVar;
16143       OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
16144       bool IsConstant = ElemType.isConstant(Context);
16145       // OpenMP [2.4.13, Data-sharing Attribute Clauses]
16146       //  A list item that specifies a given variable may not appear in more
16147       // than one clause on the same directive, except that a variable may be
16148       //  specified in both firstprivate and lastprivate clauses.
16149       // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
16150       // A list item may appear in a firstprivate or lastprivate clause but not
16151       // both.
16152       if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
16153           (isOpenMPDistributeDirective(CurrDir) ||
16154            DVar.CKind != OMPC_lastprivate) &&
16155           DVar.RefExpr) {
16156         Diag(ELoc, diag::err_omp_wrong_dsa)
16157             << getOpenMPClauseName(DVar.CKind)
16158             << getOpenMPClauseName(OMPC_firstprivate);
16159         reportOriginalDsa(*this, DSAStack, D, DVar);
16160         continue;
16161       }
16162 
16163       // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
16164       // in a Construct]
16165       //  Variables with the predetermined data-sharing attributes may not be
16166       //  listed in data-sharing attributes clauses, except for the cases
16167       //  listed below. For these exceptions only, listing a predetermined
16168       //  variable in a data-sharing attribute clause is allowed and overrides
16169       //  the variable's predetermined data-sharing attributes.
16170       // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
16171       // in a Construct, C/C++, p.2]
16172       //  Variables with const-qualified type having no mutable member may be
16173       //  listed in a firstprivate clause, even if they are static data members.
16174       if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
16175           DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
16176         Diag(ELoc, diag::err_omp_wrong_dsa)
16177             << getOpenMPClauseName(DVar.CKind)
16178             << getOpenMPClauseName(OMPC_firstprivate);
16179         reportOriginalDsa(*this, DSAStack, D, DVar);
16180         continue;
16181       }
16182 
16183       // OpenMP [2.9.3.4, Restrictions, p.2]
16184       //  A list item that is private within a parallel region must not appear
16185       //  in a firstprivate clause on a worksharing construct if any of the
16186       //  worksharing regions arising from the worksharing construct ever bind
16187       //  to any of the parallel regions arising from the parallel construct.
16188       // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
16189       // A list item that is private within a teams region must not appear in a
16190       // firstprivate clause on a distribute construct if any of the distribute
16191       // regions arising from the distribute construct ever bind to any of the
16192       // teams regions arising from the teams construct.
16193       // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
16194       // A list item that appears in a reduction clause of a teams construct
16195       // must not appear in a firstprivate clause on a distribute construct if
16196       // any of the distribute regions arising from the distribute construct
16197       // ever bind to any of the teams regions arising from the teams construct.
16198       if ((isOpenMPWorksharingDirective(CurrDir) ||
16199            isOpenMPDistributeDirective(CurrDir)) &&
16200           !isOpenMPParallelDirective(CurrDir) &&
16201           !isOpenMPTeamsDirective(CurrDir)) {
16202         DVar = DSAStack->getImplicitDSA(D, true);
16203         if (DVar.CKind != OMPC_shared &&
16204             (isOpenMPParallelDirective(DVar.DKind) ||
16205              isOpenMPTeamsDirective(DVar.DKind) ||
16206              DVar.DKind == OMPD_unknown)) {
16207           Diag(ELoc, diag::err_omp_required_access)
16208               << getOpenMPClauseName(OMPC_firstprivate)
16209               << getOpenMPClauseName(OMPC_shared);
16210           reportOriginalDsa(*this, DSAStack, D, DVar);
16211           continue;
16212         }
16213       }
16214       // OpenMP [2.9.3.4, Restrictions, p.3]
16215       //  A list item that appears in a reduction clause of a parallel construct
16216       //  must not appear in a firstprivate clause on a worksharing or task
16217       //  construct if any of the worksharing or task regions arising from the
16218       //  worksharing or task construct ever bind to any of the parallel regions
16219       //  arising from the parallel construct.
16220       // OpenMP [2.9.3.4, Restrictions, p.4]
16221       //  A list item that appears in a reduction clause in worksharing
16222       //  construct must not appear in a firstprivate clause in a task construct
16223       //  encountered during execution of any of the worksharing regions arising
16224       //  from the worksharing construct.
16225       if (isOpenMPTaskingDirective(CurrDir)) {
16226         DVar = DSAStack->hasInnermostDSA(
16227             D,
16228             [](OpenMPClauseKind C, bool AppliedToPointee) {
16229               return C == OMPC_reduction && !AppliedToPointee;
16230             },
16231             [](OpenMPDirectiveKind K) {
16232               return isOpenMPParallelDirective(K) ||
16233                      isOpenMPWorksharingDirective(K) ||
16234                      isOpenMPTeamsDirective(K);
16235             },
16236             /*FromParent=*/true);
16237         if (DVar.CKind == OMPC_reduction &&
16238             (isOpenMPParallelDirective(DVar.DKind) ||
16239              isOpenMPWorksharingDirective(DVar.DKind) ||
16240              isOpenMPTeamsDirective(DVar.DKind))) {
16241           Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
16242               << getOpenMPDirectiveName(DVar.DKind);
16243           reportOriginalDsa(*this, DSAStack, D, DVar);
16244           continue;
16245         }
16246       }
16247 
16248       // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
16249       // A list item cannot appear in both a map clause and a data-sharing
16250       // attribute clause on the same construct
16251       //
16252       // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
16253       // A list item cannot appear in both a map clause and a data-sharing
16254       // attribute clause on the same construct unless the construct is a
16255       // combined construct.
16256       if ((LangOpts.OpenMP <= 45 &&
16257            isOpenMPTargetExecutionDirective(CurrDir)) ||
16258           CurrDir == OMPD_target) {
16259         OpenMPClauseKind ConflictKind;
16260         if (DSAStack->checkMappableExprComponentListsForDecl(
16261                 VD, /*CurrentRegionOnly=*/true,
16262                 [&ConflictKind](
16263                     OMPClauseMappableExprCommon::MappableExprComponentListRef,
16264                     OpenMPClauseKind WhereFoundClauseKind) {
16265                   ConflictKind = WhereFoundClauseKind;
16266                   return true;
16267                 })) {
16268           Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
16269               << getOpenMPClauseName(OMPC_firstprivate)
16270               << getOpenMPClauseName(ConflictKind)
16271               << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
16272           reportOriginalDsa(*this, DSAStack, D, DVar);
16273           continue;
16274         }
16275       }
16276     }
16277 
16278     // Variably modified types are not supported for tasks.
16279     if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
16280         isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
16281       Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
16282           << getOpenMPClauseName(OMPC_firstprivate) << Type
16283           << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
16284       bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
16285                                VarDecl::DeclarationOnly;
16286       Diag(D->getLocation(),
16287            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
16288           << D;
16289       continue;
16290     }
16291 
16292     Type = Type.getUnqualifiedType();
16293     VarDecl *VDPrivate =
16294         buildVarDecl(*this, ELoc, Type, D->getName(),
16295                      D->hasAttrs() ? &D->getAttrs() : nullptr,
16296                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
16297     // Generate helper private variable and initialize it with the value of the
16298     // original variable. The address of the original variable is replaced by
16299     // the address of the new private variable in the CodeGen. This new variable
16300     // is not added to IdResolver, so the code in the OpenMP region uses
16301     // original variable for proper diagnostics and variable capturing.
16302     Expr *VDInitRefExpr = nullptr;
16303     // For arrays generate initializer for single element and replace it by the
16304     // original array element in CodeGen.
16305     if (Type->isArrayType()) {
16306       VarDecl *VDInit =
16307           buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
16308       VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
16309       Expr *Init = DefaultLvalueConversion(VDInitRefExpr).get();
16310       ElemType = ElemType.getUnqualifiedType();
16311       VarDecl *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
16312                                          ".firstprivate.temp");
16313       InitializedEntity Entity =
16314           InitializedEntity::InitializeVariable(VDInitTemp);
16315       InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
16316 
16317       InitializationSequence InitSeq(*this, Entity, Kind, Init);
16318       ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
16319       if (Result.isInvalid())
16320         VDPrivate->setInvalidDecl();
16321       else
16322         VDPrivate->setInit(Result.getAs<Expr>());
16323       // Remove temp variable declaration.
16324       Context.Deallocate(VDInitTemp);
16325     } else {
16326       VarDecl *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
16327                                      ".firstprivate.temp");
16328       VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
16329                                        RefExpr->getExprLoc());
16330       AddInitializerToDecl(VDPrivate,
16331                            DefaultLvalueConversion(VDInitRefExpr).get(),
16332                            /*DirectInit=*/false);
16333     }
16334     if (VDPrivate->isInvalidDecl()) {
16335       if (IsImplicitClause) {
16336         Diag(RefExpr->getExprLoc(),
16337              diag::note_omp_task_predetermined_firstprivate_here);
16338       }
16339       continue;
16340     }
16341     CurContext->addDecl(VDPrivate);
16342     DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
16343         *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
16344         RefExpr->getExprLoc());
16345     DeclRefExpr *Ref = nullptr;
16346     if (!VD && !CurContext->isDependentContext()) {
16347       if (TopDVar.CKind == OMPC_lastprivate) {
16348         Ref = TopDVar.PrivateCopy;
16349       } else {
16350         Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
16351         if (!isOpenMPCapturedDecl(D))
16352           ExprCaptures.push_back(Ref->getDecl());
16353       }
16354     }
16355     if (!IsImplicitClause)
16356       DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
16357     Vars.push_back((VD || CurContext->isDependentContext())
16358                        ? RefExpr->IgnoreParens()
16359                        : Ref);
16360     PrivateCopies.push_back(VDPrivateRefExpr);
16361     Inits.push_back(VDInitRefExpr);
16362   }
16363 
16364   if (Vars.empty())
16365     return nullptr;
16366 
16367   return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
16368                                        Vars, PrivateCopies, Inits,
16369                                        buildPreInits(Context, ExprCaptures));
16370 }
16371 
16372 OMPClause *Sema::ActOnOpenMPLastprivateClause(
16373     ArrayRef<Expr *> VarList, OpenMPLastprivateModifier LPKind,
16374     SourceLocation LPKindLoc, SourceLocation ColonLoc, SourceLocation StartLoc,
16375     SourceLocation LParenLoc, SourceLocation EndLoc) {
16376   if (LPKind == OMPC_LASTPRIVATE_unknown && LPKindLoc.isValid()) {
16377     assert(ColonLoc.isValid() && "Colon location must be valid.");
16378     Diag(LPKindLoc, diag::err_omp_unexpected_clause_value)
16379         << getListOfPossibleValues(OMPC_lastprivate, /*First=*/0,
16380                                    /*Last=*/OMPC_LASTPRIVATE_unknown)
16381         << getOpenMPClauseName(OMPC_lastprivate);
16382     return nullptr;
16383   }
16384 
16385   SmallVector<Expr *, 8> Vars;
16386   SmallVector<Expr *, 8> SrcExprs;
16387   SmallVector<Expr *, 8> DstExprs;
16388   SmallVector<Expr *, 8> AssignmentOps;
16389   SmallVector<Decl *, 4> ExprCaptures;
16390   SmallVector<Expr *, 4> ExprPostUpdates;
16391   for (Expr *RefExpr : VarList) {
16392     assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
16393     SourceLocation ELoc;
16394     SourceRange ERange;
16395     Expr *SimpleRefExpr = RefExpr;
16396     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
16397     if (Res.second) {
16398       // It will be analyzed later.
16399       Vars.push_back(RefExpr);
16400       SrcExprs.push_back(nullptr);
16401       DstExprs.push_back(nullptr);
16402       AssignmentOps.push_back(nullptr);
16403     }
16404     ValueDecl *D = Res.first;
16405     if (!D)
16406       continue;
16407 
16408     QualType Type = D->getType();
16409     auto *VD = dyn_cast<VarDecl>(D);
16410 
16411     // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
16412     //  A variable that appears in a lastprivate clause must not have an
16413     //  incomplete type or a reference type.
16414     if (RequireCompleteType(ELoc, Type,
16415                             diag::err_omp_lastprivate_incomplete_type))
16416       continue;
16417     Type = Type.getNonReferenceType();
16418 
16419     // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
16420     // A variable that is privatized must not have a const-qualified type
16421     // unless it is of class type with a mutable member. This restriction does
16422     // not apply to the firstprivate clause.
16423     //
16424     // OpenMP 3.1 [2.9.3.5, lastprivate clause, Restrictions]
16425     // A variable that appears in a lastprivate clause must not have a
16426     // const-qualified type unless it is of class type with a mutable member.
16427     if (rejectConstNotMutableType(*this, D, Type, OMPC_lastprivate, ELoc))
16428       continue;
16429 
16430     // OpenMP 5.0 [2.19.4.5 lastprivate Clause, Restrictions]
16431     // A list item that appears in a lastprivate clause with the conditional
16432     // modifier must be a scalar variable.
16433     if (LPKind == OMPC_LASTPRIVATE_conditional && !Type->isScalarType()) {
16434       Diag(ELoc, diag::err_omp_lastprivate_conditional_non_scalar);
16435       bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
16436                                VarDecl::DeclarationOnly;
16437       Diag(D->getLocation(),
16438            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
16439           << D;
16440       continue;
16441     }
16442 
16443     OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
16444     // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
16445     // in a Construct]
16446     //  Variables with the predetermined data-sharing attributes may not be
16447     //  listed in data-sharing attributes clauses, except for the cases
16448     //  listed below.
16449     // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
16450     // A list item may appear in a firstprivate or lastprivate clause but not
16451     // both.
16452     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
16453     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
16454         (isOpenMPDistributeDirective(CurrDir) ||
16455          DVar.CKind != OMPC_firstprivate) &&
16456         (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
16457       Diag(ELoc, diag::err_omp_wrong_dsa)
16458           << getOpenMPClauseName(DVar.CKind)
16459           << getOpenMPClauseName(OMPC_lastprivate);
16460       reportOriginalDsa(*this, DSAStack, D, DVar);
16461       continue;
16462     }
16463 
16464     // OpenMP [2.14.3.5, Restrictions, p.2]
16465     // A list item that is private within a parallel region, or that appears in
16466     // the reduction clause of a parallel construct, must not appear in a
16467     // lastprivate clause on a worksharing construct if any of the corresponding
16468     // worksharing regions ever binds to any of the corresponding parallel
16469     // regions.
16470     DSAStackTy::DSAVarData TopDVar = DVar;
16471     if (isOpenMPWorksharingDirective(CurrDir) &&
16472         !isOpenMPParallelDirective(CurrDir) &&
16473         !isOpenMPTeamsDirective(CurrDir)) {
16474       DVar = DSAStack->getImplicitDSA(D, true);
16475       if (DVar.CKind != OMPC_shared) {
16476         Diag(ELoc, diag::err_omp_required_access)
16477             << getOpenMPClauseName(OMPC_lastprivate)
16478             << getOpenMPClauseName(OMPC_shared);
16479         reportOriginalDsa(*this, DSAStack, D, DVar);
16480         continue;
16481       }
16482     }
16483 
16484     // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
16485     //  A variable of class type (or array thereof) that appears in a
16486     //  lastprivate clause requires an accessible, unambiguous default
16487     //  constructor for the class type, unless the list item is also specified
16488     //  in a firstprivate clause.
16489     //  A variable of class type (or array thereof) that appears in a
16490     //  lastprivate clause requires an accessible, unambiguous copy assignment
16491     //  operator for the class type.
16492     Type = Context.getBaseElementType(Type).getNonReferenceType();
16493     VarDecl *SrcVD = buildVarDecl(*this, ERange.getBegin(),
16494                                   Type.getUnqualifiedType(), ".lastprivate.src",
16495                                   D->hasAttrs() ? &D->getAttrs() : nullptr);
16496     DeclRefExpr *PseudoSrcExpr =
16497         buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
16498     VarDecl *DstVD =
16499         buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
16500                      D->hasAttrs() ? &D->getAttrs() : nullptr);
16501     DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
16502     // For arrays generate assignment operation for single element and replace
16503     // it by the original array element in CodeGen.
16504     ExprResult AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
16505                                          PseudoDstExpr, PseudoSrcExpr);
16506     if (AssignmentOp.isInvalid())
16507       continue;
16508     AssignmentOp =
16509         ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
16510     if (AssignmentOp.isInvalid())
16511       continue;
16512 
16513     DeclRefExpr *Ref = nullptr;
16514     if (!VD && !CurContext->isDependentContext()) {
16515       if (TopDVar.CKind == OMPC_firstprivate) {
16516         Ref = TopDVar.PrivateCopy;
16517       } else {
16518         Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
16519         if (!isOpenMPCapturedDecl(D))
16520           ExprCaptures.push_back(Ref->getDecl());
16521       }
16522       if ((TopDVar.CKind == OMPC_firstprivate && !TopDVar.PrivateCopy) ||
16523           (!isOpenMPCapturedDecl(D) &&
16524            Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
16525         ExprResult RefRes = DefaultLvalueConversion(Ref);
16526         if (!RefRes.isUsable())
16527           continue;
16528         ExprResult PostUpdateRes =
16529             BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
16530                        RefRes.get());
16531         if (!PostUpdateRes.isUsable())
16532           continue;
16533         ExprPostUpdates.push_back(
16534             IgnoredValueConversions(PostUpdateRes.get()).get());
16535       }
16536     }
16537     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
16538     Vars.push_back((VD || CurContext->isDependentContext())
16539                        ? RefExpr->IgnoreParens()
16540                        : Ref);
16541     SrcExprs.push_back(PseudoSrcExpr);
16542     DstExprs.push_back(PseudoDstExpr);
16543     AssignmentOps.push_back(AssignmentOp.get());
16544   }
16545 
16546   if (Vars.empty())
16547     return nullptr;
16548 
16549   return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
16550                                       Vars, SrcExprs, DstExprs, AssignmentOps,
16551                                       LPKind, LPKindLoc, ColonLoc,
16552                                       buildPreInits(Context, ExprCaptures),
16553                                       buildPostUpdate(*this, ExprPostUpdates));
16554 }
16555 
16556 OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
16557                                          SourceLocation StartLoc,
16558                                          SourceLocation LParenLoc,
16559                                          SourceLocation EndLoc) {
16560   SmallVector<Expr *, 8> Vars;
16561   for (Expr *RefExpr : VarList) {
16562     assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
16563     SourceLocation ELoc;
16564     SourceRange ERange;
16565     Expr *SimpleRefExpr = RefExpr;
16566     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
16567     if (Res.second) {
16568       // It will be analyzed later.
16569       Vars.push_back(RefExpr);
16570     }
16571     ValueDecl *D = Res.first;
16572     if (!D)
16573       continue;
16574 
16575     auto *VD = dyn_cast<VarDecl>(D);
16576     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
16577     // in a Construct]
16578     //  Variables with the predetermined data-sharing attributes may not be
16579     //  listed in data-sharing attributes clauses, except for the cases
16580     //  listed below. For these exceptions only, listing a predetermined
16581     //  variable in a data-sharing attribute clause is allowed and overrides
16582     //  the variable's predetermined data-sharing attributes.
16583     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
16584     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
16585         DVar.RefExpr) {
16586       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
16587                                           << getOpenMPClauseName(OMPC_shared);
16588       reportOriginalDsa(*this, DSAStack, D, DVar);
16589       continue;
16590     }
16591 
16592     DeclRefExpr *Ref = nullptr;
16593     if (!VD && isOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
16594       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
16595     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
16596     Vars.push_back((VD || !Ref || CurContext->isDependentContext())
16597                        ? RefExpr->IgnoreParens()
16598                        : Ref);
16599   }
16600 
16601   if (Vars.empty())
16602     return nullptr;
16603 
16604   return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
16605 }
16606 
16607 namespace {
16608 class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
16609   DSAStackTy *Stack;
16610 
16611 public:
16612   bool VisitDeclRefExpr(DeclRefExpr *E) {
16613     if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
16614       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
16615       if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
16616         return false;
16617       if (DVar.CKind != OMPC_unknown)
16618         return true;
16619       DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
16620           VD,
16621           [](OpenMPClauseKind C, bool AppliedToPointee) {
16622             return isOpenMPPrivate(C) && !AppliedToPointee;
16623           },
16624           [](OpenMPDirectiveKind) { return true; },
16625           /*FromParent=*/true);
16626       return DVarPrivate.CKind != OMPC_unknown;
16627     }
16628     return false;
16629   }
16630   bool VisitStmt(Stmt *S) {
16631     for (Stmt *Child : S->children()) {
16632       if (Child && Visit(Child))
16633         return true;
16634     }
16635     return false;
16636   }
16637   explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
16638 };
16639 } // namespace
16640 
16641 namespace {
16642 // Transform MemberExpression for specified FieldDecl of current class to
16643 // DeclRefExpr to specified OMPCapturedExprDecl.
16644 class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
16645   typedef TreeTransform<TransformExprToCaptures> BaseTransform;
16646   ValueDecl *Field = nullptr;
16647   DeclRefExpr *CapturedExpr = nullptr;
16648 
16649 public:
16650   TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
16651       : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
16652 
16653   ExprResult TransformMemberExpr(MemberExpr *E) {
16654     if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
16655         E->getMemberDecl() == Field) {
16656       CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
16657       return CapturedExpr;
16658     }
16659     return BaseTransform::TransformMemberExpr(E);
16660   }
16661   DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
16662 };
16663 } // namespace
16664 
16665 template <typename T, typename U>
16666 static T filterLookupForUDReductionAndMapper(
16667     SmallVectorImpl<U> &Lookups, const llvm::function_ref<T(ValueDecl *)> Gen) {
16668   for (U &Set : Lookups) {
16669     for (auto *D : Set) {
16670       if (T Res = Gen(cast<ValueDecl>(D)))
16671         return Res;
16672     }
16673   }
16674   return T();
16675 }
16676 
16677 static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) {
16678   assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case");
16679 
16680   for (auto RD : D->redecls()) {
16681     // Don't bother with extra checks if we already know this one isn't visible.
16682     if (RD == D)
16683       continue;
16684 
16685     auto ND = cast<NamedDecl>(RD);
16686     if (LookupResult::isVisible(SemaRef, ND))
16687       return ND;
16688   }
16689 
16690   return nullptr;
16691 }
16692 
16693 static void
16694 argumentDependentLookup(Sema &SemaRef, const DeclarationNameInfo &Id,
16695                         SourceLocation Loc, QualType Ty,
16696                         SmallVectorImpl<UnresolvedSet<8>> &Lookups) {
16697   // Find all of the associated namespaces and classes based on the
16698   // arguments we have.
16699   Sema::AssociatedNamespaceSet AssociatedNamespaces;
16700   Sema::AssociatedClassSet AssociatedClasses;
16701   OpaqueValueExpr OVE(Loc, Ty, VK_LValue);
16702   SemaRef.FindAssociatedClassesAndNamespaces(Loc, &OVE, AssociatedNamespaces,
16703                                              AssociatedClasses);
16704 
16705   // C++ [basic.lookup.argdep]p3:
16706   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
16707   //   and let Y be the lookup set produced by argument dependent
16708   //   lookup (defined as follows). If X contains [...] then Y is
16709   //   empty. Otherwise Y is the set of declarations found in the
16710   //   namespaces associated with the argument types as described
16711   //   below. The set of declarations found by the lookup of the name
16712   //   is the union of X and Y.
16713   //
16714   // Here, we compute Y and add its members to the overloaded
16715   // candidate set.
16716   for (auto *NS : AssociatedNamespaces) {
16717     //   When considering an associated namespace, the lookup is the
16718     //   same as the lookup performed when the associated namespace is
16719     //   used as a qualifier (3.4.3.2) except that:
16720     //
16721     //     -- Any using-directives in the associated namespace are
16722     //        ignored.
16723     //
16724     //     -- Any namespace-scope friend functions declared in
16725     //        associated classes are visible within their respective
16726     //        namespaces even if they are not visible during an ordinary
16727     //        lookup (11.4).
16728     DeclContext::lookup_result R = NS->lookup(Id.getName());
16729     for (auto *D : R) {
16730       auto *Underlying = D;
16731       if (auto *USD = dyn_cast<UsingShadowDecl>(D))
16732         Underlying = USD->getTargetDecl();
16733 
16734       if (!isa<OMPDeclareReductionDecl>(Underlying) &&
16735           !isa<OMPDeclareMapperDecl>(Underlying))
16736         continue;
16737 
16738       if (!SemaRef.isVisible(D)) {
16739         D = findAcceptableDecl(SemaRef, D);
16740         if (!D)
16741           continue;
16742         if (auto *USD = dyn_cast<UsingShadowDecl>(D))
16743           Underlying = USD->getTargetDecl();
16744       }
16745       Lookups.emplace_back();
16746       Lookups.back().addDecl(Underlying);
16747     }
16748   }
16749 }
16750 
16751 static ExprResult
16752 buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
16753                          Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
16754                          const DeclarationNameInfo &ReductionId, QualType Ty,
16755                          CXXCastPath &BasePath, Expr *UnresolvedReduction) {
16756   if (ReductionIdScopeSpec.isInvalid())
16757     return ExprError();
16758   SmallVector<UnresolvedSet<8>, 4> Lookups;
16759   if (S) {
16760     LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
16761     Lookup.suppressDiagnostics();
16762     while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
16763       NamedDecl *D = Lookup.getRepresentativeDecl();
16764       do {
16765         S = S->getParent();
16766       } while (S && !S->isDeclScope(D));
16767       if (S)
16768         S = S->getParent();
16769       Lookups.emplace_back();
16770       Lookups.back().append(Lookup.begin(), Lookup.end());
16771       Lookup.clear();
16772     }
16773   } else if (auto *ULE =
16774                  cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
16775     Lookups.push_back(UnresolvedSet<8>());
16776     Decl *PrevD = nullptr;
16777     for (NamedDecl *D : ULE->decls()) {
16778       if (D == PrevD)
16779         Lookups.push_back(UnresolvedSet<8>());
16780       else if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(D))
16781         Lookups.back().addDecl(DRD);
16782       PrevD = D;
16783     }
16784   }
16785   if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() ||
16786       Ty->isInstantiationDependentType() ||
16787       Ty->containsUnexpandedParameterPack() ||
16788       filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
16789         return !D->isInvalidDecl() &&
16790                (D->getType()->isDependentType() ||
16791                 D->getType()->isInstantiationDependentType() ||
16792                 D->getType()->containsUnexpandedParameterPack());
16793       })) {
16794     UnresolvedSet<8> ResSet;
16795     for (const UnresolvedSet<8> &Set : Lookups) {
16796       if (Set.empty())
16797         continue;
16798       ResSet.append(Set.begin(), Set.end());
16799       // The last item marks the end of all declarations at the specified scope.
16800       ResSet.addDecl(Set[Set.size() - 1]);
16801     }
16802     return UnresolvedLookupExpr::Create(
16803         SemaRef.Context, /*NamingClass=*/nullptr,
16804         ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
16805         /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
16806   }
16807   // Lookup inside the classes.
16808   // C++ [over.match.oper]p3:
16809   //   For a unary operator @ with an operand of a type whose
16810   //   cv-unqualified version is T1, and for a binary operator @ with
16811   //   a left operand of a type whose cv-unqualified version is T1 and
16812   //   a right operand of a type whose cv-unqualified version is T2,
16813   //   three sets of candidate functions, designated member
16814   //   candidates, non-member candidates and built-in candidates, are
16815   //   constructed as follows:
16816   //     -- If T1 is a complete class type or a class currently being
16817   //        defined, the set of member candidates is the result of the
16818   //        qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
16819   //        the set of member candidates is empty.
16820   LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
16821   Lookup.suppressDiagnostics();
16822   if (const auto *TyRec = Ty->getAs<RecordType>()) {
16823     // Complete the type if it can be completed.
16824     // If the type is neither complete nor being defined, bail out now.
16825     if (SemaRef.isCompleteType(Loc, Ty) || TyRec->isBeingDefined() ||
16826         TyRec->getDecl()->getDefinition()) {
16827       Lookup.clear();
16828       SemaRef.LookupQualifiedName(Lookup, TyRec->getDecl());
16829       if (Lookup.empty()) {
16830         Lookups.emplace_back();
16831         Lookups.back().append(Lookup.begin(), Lookup.end());
16832       }
16833     }
16834   }
16835   // Perform ADL.
16836   if (SemaRef.getLangOpts().CPlusPlus)
16837     argumentDependentLookup(SemaRef, ReductionId, Loc, Ty, Lookups);
16838   if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
16839           Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
16840             if (!D->isInvalidDecl() &&
16841                 SemaRef.Context.hasSameType(D->getType(), Ty))
16842               return D;
16843             return nullptr;
16844           }))
16845     return SemaRef.BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(),
16846                                     VK_LValue, Loc);
16847   if (SemaRef.getLangOpts().CPlusPlus) {
16848     if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
16849             Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
16850               if (!D->isInvalidDecl() &&
16851                   SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
16852                   !Ty.isMoreQualifiedThan(D->getType()))
16853                 return D;
16854               return nullptr;
16855             })) {
16856       CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
16857                          /*DetectVirtual=*/false);
16858       if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
16859         if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
16860                 VD->getType().getUnqualifiedType()))) {
16861           if (SemaRef.CheckBaseClassAccess(
16862                   Loc, VD->getType(), Ty, Paths.front(),
16863                   /*DiagID=*/0) != Sema::AR_inaccessible) {
16864             SemaRef.BuildBasePathArray(Paths, BasePath);
16865             return SemaRef.BuildDeclRefExpr(
16866                 VD, VD->getType().getNonReferenceType(), VK_LValue, Loc);
16867           }
16868         }
16869       }
16870     }
16871   }
16872   if (ReductionIdScopeSpec.isSet()) {
16873     SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier)
16874         << Ty << Range;
16875     return ExprError();
16876   }
16877   return ExprEmpty();
16878 }
16879 
16880 namespace {
16881 /// Data for the reduction-based clauses.
16882 struct ReductionData {
16883   /// List of original reduction items.
16884   SmallVector<Expr *, 8> Vars;
16885   /// List of private copies of the reduction items.
16886   SmallVector<Expr *, 8> Privates;
16887   /// LHS expressions for the reduction_op expressions.
16888   SmallVector<Expr *, 8> LHSs;
16889   /// RHS expressions for the reduction_op expressions.
16890   SmallVector<Expr *, 8> RHSs;
16891   /// Reduction operation expression.
16892   SmallVector<Expr *, 8> ReductionOps;
16893   /// inscan copy operation expressions.
16894   SmallVector<Expr *, 8> InscanCopyOps;
16895   /// inscan copy temp array expressions for prefix sums.
16896   SmallVector<Expr *, 8> InscanCopyArrayTemps;
16897   /// inscan copy temp array element expressions for prefix sums.
16898   SmallVector<Expr *, 8> InscanCopyArrayElems;
16899   /// Taskgroup descriptors for the corresponding reduction items in
16900   /// in_reduction clauses.
16901   SmallVector<Expr *, 8> TaskgroupDescriptors;
16902   /// List of captures for clause.
16903   SmallVector<Decl *, 4> ExprCaptures;
16904   /// List of postupdate expressions.
16905   SmallVector<Expr *, 4> ExprPostUpdates;
16906   /// Reduction modifier.
16907   unsigned RedModifier = 0;
16908   ReductionData() = delete;
16909   /// Reserves required memory for the reduction data.
16910   ReductionData(unsigned Size, unsigned Modifier = 0) : RedModifier(Modifier) {
16911     Vars.reserve(Size);
16912     Privates.reserve(Size);
16913     LHSs.reserve(Size);
16914     RHSs.reserve(Size);
16915     ReductionOps.reserve(Size);
16916     if (RedModifier == OMPC_REDUCTION_inscan) {
16917       InscanCopyOps.reserve(Size);
16918       InscanCopyArrayTemps.reserve(Size);
16919       InscanCopyArrayElems.reserve(Size);
16920     }
16921     TaskgroupDescriptors.reserve(Size);
16922     ExprCaptures.reserve(Size);
16923     ExprPostUpdates.reserve(Size);
16924   }
16925   /// Stores reduction item and reduction operation only (required for dependent
16926   /// reduction item).
16927   void push(Expr *Item, Expr *ReductionOp) {
16928     Vars.emplace_back(Item);
16929     Privates.emplace_back(nullptr);
16930     LHSs.emplace_back(nullptr);
16931     RHSs.emplace_back(nullptr);
16932     ReductionOps.emplace_back(ReductionOp);
16933     TaskgroupDescriptors.emplace_back(nullptr);
16934     if (RedModifier == OMPC_REDUCTION_inscan) {
16935       InscanCopyOps.push_back(nullptr);
16936       InscanCopyArrayTemps.push_back(nullptr);
16937       InscanCopyArrayElems.push_back(nullptr);
16938     }
16939   }
16940   /// Stores reduction data.
16941   void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp,
16942             Expr *TaskgroupDescriptor, Expr *CopyOp, Expr *CopyArrayTemp,
16943             Expr *CopyArrayElem) {
16944     Vars.emplace_back(Item);
16945     Privates.emplace_back(Private);
16946     LHSs.emplace_back(LHS);
16947     RHSs.emplace_back(RHS);
16948     ReductionOps.emplace_back(ReductionOp);
16949     TaskgroupDescriptors.emplace_back(TaskgroupDescriptor);
16950     if (RedModifier == OMPC_REDUCTION_inscan) {
16951       InscanCopyOps.push_back(CopyOp);
16952       InscanCopyArrayTemps.push_back(CopyArrayTemp);
16953       InscanCopyArrayElems.push_back(CopyArrayElem);
16954     } else {
16955       assert(CopyOp == nullptr && CopyArrayTemp == nullptr &&
16956              CopyArrayElem == nullptr &&
16957              "Copy operation must be used for inscan reductions only.");
16958     }
16959   }
16960 };
16961 } // namespace
16962 
16963 static bool checkOMPArraySectionConstantForReduction(
16964     ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement,
16965     SmallVectorImpl<llvm::APSInt> &ArraySizes) {
16966   const Expr *Length = OASE->getLength();
16967   if (Length == nullptr) {
16968     // For array sections of the form [1:] or [:], we would need to analyze
16969     // the lower bound...
16970     if (OASE->getColonLocFirst().isValid())
16971       return false;
16972 
16973     // This is an array subscript which has implicit length 1!
16974     SingleElement = true;
16975     ArraySizes.push_back(llvm::APSInt::get(1));
16976   } else {
16977     Expr::EvalResult Result;
16978     if (!Length->EvaluateAsInt(Result, Context))
16979       return false;
16980 
16981     llvm::APSInt ConstantLengthValue = Result.Val.getInt();
16982     SingleElement = (ConstantLengthValue.getSExtValue() == 1);
16983     ArraySizes.push_back(ConstantLengthValue);
16984   }
16985 
16986   // Get the base of this array section and walk up from there.
16987   const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
16988 
16989   // We require length = 1 for all array sections except the right-most to
16990   // guarantee that the memory region is contiguous and has no holes in it.
16991   while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) {
16992     Length = TempOASE->getLength();
16993     if (Length == nullptr) {
16994       // For array sections of the form [1:] or [:], we would need to analyze
16995       // the lower bound...
16996       if (OASE->getColonLocFirst().isValid())
16997         return false;
16998 
16999       // This is an array subscript which has implicit length 1!
17000       ArraySizes.push_back(llvm::APSInt::get(1));
17001     } else {
17002       Expr::EvalResult Result;
17003       if (!Length->EvaluateAsInt(Result, Context))
17004         return false;
17005 
17006       llvm::APSInt ConstantLengthValue = Result.Val.getInt();
17007       if (ConstantLengthValue.getSExtValue() != 1)
17008         return false;
17009 
17010       ArraySizes.push_back(ConstantLengthValue);
17011     }
17012     Base = TempOASE->getBase()->IgnoreParenImpCasts();
17013   }
17014 
17015   // If we have a single element, we don't need to add the implicit lengths.
17016   if (!SingleElement) {
17017     while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) {
17018       // Has implicit length 1!
17019       ArraySizes.push_back(llvm::APSInt::get(1));
17020       Base = TempASE->getBase()->IgnoreParenImpCasts();
17021     }
17022   }
17023 
17024   // This array section can be privatized as a single value or as a constant
17025   // sized array.
17026   return true;
17027 }
17028 
17029 static BinaryOperatorKind
17030 getRelatedCompoundReductionOp(BinaryOperatorKind BOK) {
17031   if (BOK == BO_Add)
17032     return BO_AddAssign;
17033   if (BOK == BO_Mul)
17034     return BO_MulAssign;
17035   if (BOK == BO_And)
17036     return BO_AndAssign;
17037   if (BOK == BO_Or)
17038     return BO_OrAssign;
17039   if (BOK == BO_Xor)
17040     return BO_XorAssign;
17041   return BOK;
17042 }
17043 
17044 static bool actOnOMPReductionKindClause(
17045     Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind,
17046     ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
17047     SourceLocation ColonLoc, SourceLocation EndLoc,
17048     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
17049     ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) {
17050   DeclarationName DN = ReductionId.getName();
17051   OverloadedOperatorKind OOK = DN.getCXXOverloadedOperator();
17052   BinaryOperatorKind BOK = BO_Comma;
17053 
17054   ASTContext &Context = S.Context;
17055   // OpenMP [2.14.3.6, reduction clause]
17056   // C
17057   // reduction-identifier is either an identifier or one of the following
17058   // operators: +, -, *,  &, |, ^, && and ||
17059   // C++
17060   // reduction-identifier is either an id-expression or one of the following
17061   // operators: +, -, *, &, |, ^, && and ||
17062   switch (OOK) {
17063   case OO_Plus:
17064   case OO_Minus:
17065     BOK = BO_Add;
17066     break;
17067   case OO_Star:
17068     BOK = BO_Mul;
17069     break;
17070   case OO_Amp:
17071     BOK = BO_And;
17072     break;
17073   case OO_Pipe:
17074     BOK = BO_Or;
17075     break;
17076   case OO_Caret:
17077     BOK = BO_Xor;
17078     break;
17079   case OO_AmpAmp:
17080     BOK = BO_LAnd;
17081     break;
17082   case OO_PipePipe:
17083     BOK = BO_LOr;
17084     break;
17085   case OO_New:
17086   case OO_Delete:
17087   case OO_Array_New:
17088   case OO_Array_Delete:
17089   case OO_Slash:
17090   case OO_Percent:
17091   case OO_Tilde:
17092   case OO_Exclaim:
17093   case OO_Equal:
17094   case OO_Less:
17095   case OO_Greater:
17096   case OO_LessEqual:
17097   case OO_GreaterEqual:
17098   case OO_PlusEqual:
17099   case OO_MinusEqual:
17100   case OO_StarEqual:
17101   case OO_SlashEqual:
17102   case OO_PercentEqual:
17103   case OO_CaretEqual:
17104   case OO_AmpEqual:
17105   case OO_PipeEqual:
17106   case OO_LessLess:
17107   case OO_GreaterGreater:
17108   case OO_LessLessEqual:
17109   case OO_GreaterGreaterEqual:
17110   case OO_EqualEqual:
17111   case OO_ExclaimEqual:
17112   case OO_Spaceship:
17113   case OO_PlusPlus:
17114   case OO_MinusMinus:
17115   case OO_Comma:
17116   case OO_ArrowStar:
17117   case OO_Arrow:
17118   case OO_Call:
17119   case OO_Subscript:
17120   case OO_Conditional:
17121   case OO_Coawait:
17122   case NUM_OVERLOADED_OPERATORS:
17123     llvm_unreachable("Unexpected reduction identifier");
17124   case OO_None:
17125     if (IdentifierInfo *II = DN.getAsIdentifierInfo()) {
17126       if (II->isStr("max"))
17127         BOK = BO_GT;
17128       else if (II->isStr("min"))
17129         BOK = BO_LT;
17130     }
17131     break;
17132   }
17133   SourceRange ReductionIdRange;
17134   if (ReductionIdScopeSpec.isValid())
17135     ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
17136   else
17137     ReductionIdRange.setBegin(ReductionId.getBeginLoc());
17138   ReductionIdRange.setEnd(ReductionId.getEndLoc());
17139 
17140   auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
17141   bool FirstIter = true;
17142   for (Expr *RefExpr : VarList) {
17143     assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
17144     // OpenMP [2.1, C/C++]
17145     //  A list item is a variable or array section, subject to the restrictions
17146     //  specified in Section 2.4 on page 42 and in each of the sections
17147     // describing clauses and directives for which a list appears.
17148     // OpenMP  [2.14.3.3, Restrictions, p.1]
17149     //  A variable that is part of another variable (as an array or
17150     //  structure element) cannot appear in a private clause.
17151     if (!FirstIter && IR != ER)
17152       ++IR;
17153     FirstIter = false;
17154     SourceLocation ELoc;
17155     SourceRange ERange;
17156     Expr *SimpleRefExpr = RefExpr;
17157     auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
17158                               /*AllowArraySection=*/true);
17159     if (Res.second) {
17160       // Try to find 'declare reduction' corresponding construct before using
17161       // builtin/overloaded operators.
17162       QualType Type = Context.DependentTy;
17163       CXXCastPath BasePath;
17164       ExprResult DeclareReductionRef = buildDeclareReductionRef(
17165           S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
17166           ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
17167       Expr *ReductionOp = nullptr;
17168       if (S.CurContext->isDependentContext() &&
17169           (DeclareReductionRef.isUnset() ||
17170            isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
17171         ReductionOp = DeclareReductionRef.get();
17172       // It will be analyzed later.
17173       RD.push(RefExpr, ReductionOp);
17174     }
17175     ValueDecl *D = Res.first;
17176     if (!D)
17177       continue;
17178 
17179     Expr *TaskgroupDescriptor = nullptr;
17180     QualType Type;
17181     auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
17182     auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
17183     if (ASE) {
17184       Type = ASE->getType().getNonReferenceType();
17185     } else if (OASE) {
17186       QualType BaseType =
17187           OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
17188       if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
17189         Type = ATy->getElementType();
17190       else
17191         Type = BaseType->getPointeeType();
17192       Type = Type.getNonReferenceType();
17193     } else {
17194       Type = Context.getBaseElementType(D->getType().getNonReferenceType());
17195     }
17196     auto *VD = dyn_cast<VarDecl>(D);
17197 
17198     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
17199     //  A variable that appears in a private clause must not have an incomplete
17200     //  type or a reference type.
17201     if (S.RequireCompleteType(ELoc, D->getType(),
17202                               diag::err_omp_reduction_incomplete_type))
17203       continue;
17204     // OpenMP [2.14.3.6, reduction clause, Restrictions]
17205     // A list item that appears in a reduction clause must not be
17206     // const-qualified.
17207     if (rejectConstNotMutableType(S, D, Type, ClauseKind, ELoc,
17208                                   /*AcceptIfMutable*/ false, ASE || OASE))
17209       continue;
17210 
17211     OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective();
17212     // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
17213     //  If a list-item is a reference type then it must bind to the same object
17214     //  for all threads of the team.
17215     if (!ASE && !OASE) {
17216       if (VD) {
17217         VarDecl *VDDef = VD->getDefinition();
17218         if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
17219           DSARefChecker Check(Stack);
17220           if (Check.Visit(VDDef->getInit())) {
17221             S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg)
17222                 << getOpenMPClauseName(ClauseKind) << ERange;
17223             S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
17224             continue;
17225           }
17226         }
17227       }
17228 
17229       // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
17230       // in a Construct]
17231       //  Variables with the predetermined data-sharing attributes may not be
17232       //  listed in data-sharing attributes clauses, except for the cases
17233       //  listed below. For these exceptions only, listing a predetermined
17234       //  variable in a data-sharing attribute clause is allowed and overrides
17235       //  the variable's predetermined data-sharing attributes.
17236       // OpenMP [2.14.3.6, Restrictions, p.3]
17237       //  Any number of reduction clauses can be specified on the directive,
17238       //  but a list item can appear only once in the reduction clauses for that
17239       //  directive.
17240       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false);
17241       if (DVar.CKind == OMPC_reduction) {
17242         S.Diag(ELoc, diag::err_omp_once_referenced)
17243             << getOpenMPClauseName(ClauseKind);
17244         if (DVar.RefExpr)
17245           S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
17246         continue;
17247       }
17248       if (DVar.CKind != OMPC_unknown) {
17249         S.Diag(ELoc, diag::err_omp_wrong_dsa)
17250             << getOpenMPClauseName(DVar.CKind)
17251             << getOpenMPClauseName(OMPC_reduction);
17252         reportOriginalDsa(S, Stack, D, DVar);
17253         continue;
17254       }
17255 
17256       // OpenMP [2.14.3.6, Restrictions, p.1]
17257       //  A list item that appears in a reduction clause of a worksharing
17258       //  construct must be shared in the parallel regions to which any of the
17259       //  worksharing regions arising from the worksharing construct bind.
17260       if (isOpenMPWorksharingDirective(CurrDir) &&
17261           !isOpenMPParallelDirective(CurrDir) &&
17262           !isOpenMPTeamsDirective(CurrDir)) {
17263         DVar = Stack->getImplicitDSA(D, true);
17264         if (DVar.CKind != OMPC_shared) {
17265           S.Diag(ELoc, diag::err_omp_required_access)
17266               << getOpenMPClauseName(OMPC_reduction)
17267               << getOpenMPClauseName(OMPC_shared);
17268           reportOriginalDsa(S, Stack, D, DVar);
17269           continue;
17270         }
17271       }
17272     } else {
17273       // Threadprivates cannot be shared between threads, so dignose if the base
17274       // is a threadprivate variable.
17275       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false);
17276       if (DVar.CKind == OMPC_threadprivate) {
17277         S.Diag(ELoc, diag::err_omp_wrong_dsa)
17278             << getOpenMPClauseName(DVar.CKind)
17279             << getOpenMPClauseName(OMPC_reduction);
17280         reportOriginalDsa(S, Stack, D, DVar);
17281         continue;
17282       }
17283     }
17284 
17285     // Try to find 'declare reduction' corresponding construct before using
17286     // builtin/overloaded operators.
17287     CXXCastPath BasePath;
17288     ExprResult DeclareReductionRef = buildDeclareReductionRef(
17289         S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
17290         ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
17291     if (DeclareReductionRef.isInvalid())
17292       continue;
17293     if (S.CurContext->isDependentContext() &&
17294         (DeclareReductionRef.isUnset() ||
17295          isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
17296       RD.push(RefExpr, DeclareReductionRef.get());
17297       continue;
17298     }
17299     if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
17300       // Not allowed reduction identifier is found.
17301       S.Diag(ReductionId.getBeginLoc(),
17302              diag::err_omp_unknown_reduction_identifier)
17303           << Type << ReductionIdRange;
17304       continue;
17305     }
17306 
17307     // OpenMP [2.14.3.6, reduction clause, Restrictions]
17308     // The type of a list item that appears in a reduction clause must be valid
17309     // for the reduction-identifier. For a max or min reduction in C, the type
17310     // of the list item must be an allowed arithmetic data type: char, int,
17311     // float, double, or _Bool, possibly modified with long, short, signed, or
17312     // unsigned. For a max or min reduction in C++, the type of the list item
17313     // must be an allowed arithmetic data type: char, wchar_t, int, float,
17314     // double, or bool, possibly modified with long, short, signed, or unsigned.
17315     if (DeclareReductionRef.isUnset()) {
17316       if ((BOK == BO_GT || BOK == BO_LT) &&
17317           !(Type->isScalarType() ||
17318             (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
17319         S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
17320             << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus;
17321         if (!ASE && !OASE) {
17322           bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
17323                                    VarDecl::DeclarationOnly;
17324           S.Diag(D->getLocation(),
17325                  IsDecl ? diag::note_previous_decl : diag::note_defined_here)
17326               << D;
17327         }
17328         continue;
17329       }
17330       if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
17331           !S.getLangOpts().CPlusPlus && Type->isFloatingType()) {
17332         S.Diag(ELoc, diag::err_omp_clause_floating_type_arg)
17333             << getOpenMPClauseName(ClauseKind);
17334         if (!ASE && !OASE) {
17335           bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
17336                                    VarDecl::DeclarationOnly;
17337           S.Diag(D->getLocation(),
17338                  IsDecl ? diag::note_previous_decl : diag::note_defined_here)
17339               << D;
17340         }
17341         continue;
17342       }
17343     }
17344 
17345     Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
17346     VarDecl *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs",
17347                                   D->hasAttrs() ? &D->getAttrs() : nullptr);
17348     VarDecl *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(),
17349                                   D->hasAttrs() ? &D->getAttrs() : nullptr);
17350     QualType PrivateTy = Type;
17351 
17352     // Try if we can determine constant lengths for all array sections and avoid
17353     // the VLA.
17354     bool ConstantLengthOASE = false;
17355     if (OASE) {
17356       bool SingleElement;
17357       llvm::SmallVector<llvm::APSInt, 4> ArraySizes;
17358       ConstantLengthOASE = checkOMPArraySectionConstantForReduction(
17359           Context, OASE, SingleElement, ArraySizes);
17360 
17361       // If we don't have a single element, we must emit a constant array type.
17362       if (ConstantLengthOASE && !SingleElement) {
17363         for (llvm::APSInt &Size : ArraySizes)
17364           PrivateTy = Context.getConstantArrayType(PrivateTy, Size, nullptr,
17365                                                    ArrayType::Normal,
17366                                                    /*IndexTypeQuals=*/0);
17367       }
17368     }
17369 
17370     if ((OASE && !ConstantLengthOASE) ||
17371         (!OASE && !ASE &&
17372          D->getType().getNonReferenceType()->isVariablyModifiedType())) {
17373       if (!Context.getTargetInfo().isVLASupported()) {
17374         if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective())) {
17375           S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
17376           S.Diag(ELoc, diag::note_vla_unsupported);
17377           continue;
17378         } else {
17379           S.targetDiag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
17380           S.targetDiag(ELoc, diag::note_vla_unsupported);
17381         }
17382       }
17383       // For arrays/array sections only:
17384       // Create pseudo array type for private copy. The size for this array will
17385       // be generated during codegen.
17386       // For array subscripts or single variables Private Ty is the same as Type
17387       // (type of the variable or single array element).
17388       PrivateTy = Context.getVariableArrayType(
17389           Type,
17390           new (Context)
17391               OpaqueValueExpr(ELoc, Context.getSizeType(), VK_PRValue),
17392           ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
17393     } else if (!ASE && !OASE &&
17394                Context.getAsArrayType(D->getType().getNonReferenceType())) {
17395       PrivateTy = D->getType().getNonReferenceType();
17396     }
17397     // Private copy.
17398     VarDecl *PrivateVD =
17399         buildVarDecl(S, ELoc, PrivateTy, D->getName(),
17400                      D->hasAttrs() ? &D->getAttrs() : nullptr,
17401                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
17402     // Add initializer for private variable.
17403     Expr *Init = nullptr;
17404     DeclRefExpr *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc);
17405     DeclRefExpr *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc);
17406     if (DeclareReductionRef.isUsable()) {
17407       auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
17408       auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
17409       if (DRD->getInitializer()) {
17410         Init = DRDRef;
17411         RHSVD->setInit(DRDRef);
17412         RHSVD->setInitStyle(VarDecl::CallInit);
17413       }
17414     } else {
17415       switch (BOK) {
17416       case BO_Add:
17417       case BO_Xor:
17418       case BO_Or:
17419       case BO_LOr:
17420         // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
17421         if (Type->isScalarType() || Type->isAnyComplexType())
17422           Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get();
17423         break;
17424       case BO_Mul:
17425       case BO_LAnd:
17426         if (Type->isScalarType() || Type->isAnyComplexType()) {
17427           // '*' and '&&' reduction ops - initializer is '1'.
17428           Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get();
17429         }
17430         break;
17431       case BO_And: {
17432         // '&' reduction op - initializer is '~0'.
17433         QualType OrigType = Type;
17434         if (auto *ComplexTy = OrigType->getAs<ComplexType>())
17435           Type = ComplexTy->getElementType();
17436         if (Type->isRealFloatingType()) {
17437           llvm::APFloat InitValue = llvm::APFloat::getAllOnesValue(
17438               Context.getFloatTypeSemantics(Type));
17439           Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
17440                                          Type, ELoc);
17441         } else if (Type->isScalarType()) {
17442           uint64_t Size = Context.getTypeSize(Type);
17443           QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
17444           llvm::APInt InitValue = llvm::APInt::getAllOnes(Size);
17445           Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
17446         }
17447         if (Init && OrigType->isAnyComplexType()) {
17448           // Init = 0xFFFF + 0xFFFFi;
17449           auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
17450           Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
17451         }
17452         Type = OrigType;
17453         break;
17454       }
17455       case BO_LT:
17456       case BO_GT: {
17457         // 'min' reduction op - initializer is 'Largest representable number in
17458         // the reduction list item type'.
17459         // 'max' reduction op - initializer is 'Least representable number in
17460         // the reduction list item type'.
17461         if (Type->isIntegerType() || Type->isPointerType()) {
17462           bool IsSigned = Type->hasSignedIntegerRepresentation();
17463           uint64_t Size = Context.getTypeSize(Type);
17464           QualType IntTy =
17465               Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
17466           llvm::APInt InitValue =
17467               (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
17468                                         : llvm::APInt::getMinValue(Size)
17469               : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
17470                              : llvm::APInt::getMaxValue(Size);
17471           Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
17472           if (Type->isPointerType()) {
17473             // Cast to pointer type.
17474             ExprResult CastExpr = S.BuildCStyleCastExpr(
17475                 ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init);
17476             if (CastExpr.isInvalid())
17477               continue;
17478             Init = CastExpr.get();
17479           }
17480         } else if (Type->isRealFloatingType()) {
17481           llvm::APFloat InitValue = llvm::APFloat::getLargest(
17482               Context.getFloatTypeSemantics(Type), BOK != BO_LT);
17483           Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
17484                                          Type, ELoc);
17485         }
17486         break;
17487       }
17488       case BO_PtrMemD:
17489       case BO_PtrMemI:
17490       case BO_MulAssign:
17491       case BO_Div:
17492       case BO_Rem:
17493       case BO_Sub:
17494       case BO_Shl:
17495       case BO_Shr:
17496       case BO_LE:
17497       case BO_GE:
17498       case BO_EQ:
17499       case BO_NE:
17500       case BO_Cmp:
17501       case BO_AndAssign:
17502       case BO_XorAssign:
17503       case BO_OrAssign:
17504       case BO_Assign:
17505       case BO_AddAssign:
17506       case BO_SubAssign:
17507       case BO_DivAssign:
17508       case BO_RemAssign:
17509       case BO_ShlAssign:
17510       case BO_ShrAssign:
17511       case BO_Comma:
17512         llvm_unreachable("Unexpected reduction operation");
17513       }
17514     }
17515     if (Init && DeclareReductionRef.isUnset()) {
17516       S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
17517       // Store initializer for single element in private copy. Will be used
17518       // during codegen.
17519       PrivateVD->setInit(RHSVD->getInit());
17520       PrivateVD->setInitStyle(RHSVD->getInitStyle());
17521     } else if (!Init) {
17522       S.ActOnUninitializedDecl(RHSVD);
17523       // Store initializer for single element in private copy. Will be used
17524       // during codegen.
17525       PrivateVD->setInit(RHSVD->getInit());
17526       PrivateVD->setInitStyle(RHSVD->getInitStyle());
17527     }
17528     if (RHSVD->isInvalidDecl())
17529       continue;
17530     if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) {
17531       S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible)
17532           << Type << ReductionIdRange;
17533       bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
17534                                VarDecl::DeclarationOnly;
17535       S.Diag(D->getLocation(),
17536              IsDecl ? diag::note_previous_decl : diag::note_defined_here)
17537           << D;
17538       continue;
17539     }
17540     DeclRefExpr *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc);
17541     ExprResult ReductionOp;
17542     if (DeclareReductionRef.isUsable()) {
17543       QualType RedTy = DeclareReductionRef.get()->getType();
17544       QualType PtrRedTy = Context.getPointerType(RedTy);
17545       ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
17546       ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
17547       if (!BasePath.empty()) {
17548         LHS = S.DefaultLvalueConversion(LHS.get());
17549         RHS = S.DefaultLvalueConversion(RHS.get());
17550         LHS = ImplicitCastExpr::Create(
17551             Context, PtrRedTy, CK_UncheckedDerivedToBase, LHS.get(), &BasePath,
17552             LHS.get()->getValueKind(), FPOptionsOverride());
17553         RHS = ImplicitCastExpr::Create(
17554             Context, PtrRedTy, CK_UncheckedDerivedToBase, RHS.get(), &BasePath,
17555             RHS.get()->getValueKind(), FPOptionsOverride());
17556       }
17557       FunctionProtoType::ExtProtoInfo EPI;
17558       QualType Params[] = {PtrRedTy, PtrRedTy};
17559       QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
17560       auto *OVE = new (Context) OpaqueValueExpr(
17561           ELoc, Context.getPointerType(FnTy), VK_PRValue, OK_Ordinary,
17562           S.DefaultLvalueConversion(DeclareReductionRef.get()).get());
17563       Expr *Args[] = {LHS.get(), RHS.get()};
17564       ReductionOp =
17565           CallExpr::Create(Context, OVE, Args, Context.VoidTy, VK_PRValue, ELoc,
17566                            S.CurFPFeatureOverrides());
17567     } else {
17568       BinaryOperatorKind CombBOK = getRelatedCompoundReductionOp(BOK);
17569       if (Type->isRecordType() && CombBOK != BOK) {
17570         Sema::TentativeAnalysisScope Trap(S);
17571         ReductionOp =
17572             S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
17573                          CombBOK, LHSDRE, RHSDRE);
17574       }
17575       if (!ReductionOp.isUsable()) {
17576         ReductionOp =
17577             S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(), BOK,
17578                          LHSDRE, RHSDRE);
17579         if (ReductionOp.isUsable()) {
17580           if (BOK != BO_LT && BOK != BO_GT) {
17581             ReductionOp =
17582                 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
17583                              BO_Assign, LHSDRE, ReductionOp.get());
17584           } else {
17585             auto *ConditionalOp = new (Context)
17586                 ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc,
17587                                     RHSDRE, Type, VK_LValue, OK_Ordinary);
17588             ReductionOp =
17589                 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
17590                              BO_Assign, LHSDRE, ConditionalOp);
17591           }
17592         }
17593       }
17594       if (ReductionOp.isUsable())
17595         ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get(),
17596                                             /*DiscardedValue*/ false);
17597       if (!ReductionOp.isUsable())
17598         continue;
17599     }
17600 
17601     // Add copy operations for inscan reductions.
17602     // LHS = RHS;
17603     ExprResult CopyOpRes, TempArrayRes, TempArrayElem;
17604     if (ClauseKind == OMPC_reduction &&
17605         RD.RedModifier == OMPC_REDUCTION_inscan) {
17606       ExprResult RHS = S.DefaultLvalueConversion(RHSDRE);
17607       CopyOpRes = S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, LHSDRE,
17608                                RHS.get());
17609       if (!CopyOpRes.isUsable())
17610         continue;
17611       CopyOpRes =
17612           S.ActOnFinishFullExpr(CopyOpRes.get(), /*DiscardedValue=*/true);
17613       if (!CopyOpRes.isUsable())
17614         continue;
17615       // For simd directive and simd-based directives in simd mode no need to
17616       // construct temp array, need just a single temp element.
17617       if (Stack->getCurrentDirective() == OMPD_simd ||
17618           (S.getLangOpts().OpenMPSimd &&
17619            isOpenMPSimdDirective(Stack->getCurrentDirective()))) {
17620         VarDecl *TempArrayVD =
17621             buildVarDecl(S, ELoc, PrivateTy, D->getName(),
17622                          D->hasAttrs() ? &D->getAttrs() : nullptr);
17623         // Add a constructor to the temp decl.
17624         S.ActOnUninitializedDecl(TempArrayVD);
17625         TempArrayRes = buildDeclRefExpr(S, TempArrayVD, PrivateTy, ELoc);
17626       } else {
17627         // Build temp array for prefix sum.
17628         auto *Dim = new (S.Context)
17629             OpaqueValueExpr(ELoc, S.Context.getSizeType(), VK_PRValue);
17630         QualType ArrayTy =
17631             S.Context.getVariableArrayType(PrivateTy, Dim, ArrayType::Normal,
17632                                            /*IndexTypeQuals=*/0, {ELoc, ELoc});
17633         VarDecl *TempArrayVD =
17634             buildVarDecl(S, ELoc, ArrayTy, D->getName(),
17635                          D->hasAttrs() ? &D->getAttrs() : nullptr);
17636         // Add a constructor to the temp decl.
17637         S.ActOnUninitializedDecl(TempArrayVD);
17638         TempArrayRes = buildDeclRefExpr(S, TempArrayVD, ArrayTy, ELoc);
17639         TempArrayElem =
17640             S.DefaultFunctionArrayLvalueConversion(TempArrayRes.get());
17641         auto *Idx = new (S.Context)
17642             OpaqueValueExpr(ELoc, S.Context.getSizeType(), VK_PRValue);
17643         TempArrayElem = S.CreateBuiltinArraySubscriptExpr(TempArrayElem.get(),
17644                                                           ELoc, Idx, ELoc);
17645       }
17646     }
17647 
17648     // OpenMP [2.15.4.6, Restrictions, p.2]
17649     // A list item that appears in an in_reduction clause of a task construct
17650     // must appear in a task_reduction clause of a construct associated with a
17651     // taskgroup region that includes the participating task in its taskgroup
17652     // set. The construct associated with the innermost region that meets this
17653     // condition must specify the same reduction-identifier as the in_reduction
17654     // clause.
17655     if (ClauseKind == OMPC_in_reduction) {
17656       SourceRange ParentSR;
17657       BinaryOperatorKind ParentBOK;
17658       const Expr *ParentReductionOp = nullptr;
17659       Expr *ParentBOKTD = nullptr, *ParentReductionOpTD = nullptr;
17660       DSAStackTy::DSAVarData ParentBOKDSA =
17661           Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK,
17662                                                   ParentBOKTD);
17663       DSAStackTy::DSAVarData ParentReductionOpDSA =
17664           Stack->getTopMostTaskgroupReductionData(
17665               D, ParentSR, ParentReductionOp, ParentReductionOpTD);
17666       bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown;
17667       bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown;
17668       if ((DeclareReductionRef.isUnset() && IsParentReductionOp) ||
17669           (DeclareReductionRef.isUsable() && IsParentBOK) ||
17670           (IsParentBOK && BOK != ParentBOK) || IsParentReductionOp) {
17671         bool EmitError = true;
17672         if (IsParentReductionOp && DeclareReductionRef.isUsable()) {
17673           llvm::FoldingSetNodeID RedId, ParentRedId;
17674           ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true);
17675           DeclareReductionRef.get()->Profile(RedId, Context,
17676                                              /*Canonical=*/true);
17677           EmitError = RedId != ParentRedId;
17678         }
17679         if (EmitError) {
17680           S.Diag(ReductionId.getBeginLoc(),
17681                  diag::err_omp_reduction_identifier_mismatch)
17682               << ReductionIdRange << RefExpr->getSourceRange();
17683           S.Diag(ParentSR.getBegin(),
17684                  diag::note_omp_previous_reduction_identifier)
17685               << ParentSR
17686               << (IsParentBOK ? ParentBOKDSA.RefExpr
17687                               : ParentReductionOpDSA.RefExpr)
17688                      ->getSourceRange();
17689           continue;
17690         }
17691       }
17692       TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD;
17693     }
17694 
17695     DeclRefExpr *Ref = nullptr;
17696     Expr *VarsExpr = RefExpr->IgnoreParens();
17697     if (!VD && !S.CurContext->isDependentContext()) {
17698       if (ASE || OASE) {
17699         TransformExprToCaptures RebuildToCapture(S, D);
17700         VarsExpr =
17701             RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
17702         Ref = RebuildToCapture.getCapturedExpr();
17703       } else {
17704         VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false);
17705       }
17706       if (!S.isOpenMPCapturedDecl(D)) {
17707         RD.ExprCaptures.emplace_back(Ref->getDecl());
17708         if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
17709           ExprResult RefRes = S.DefaultLvalueConversion(Ref);
17710           if (!RefRes.isUsable())
17711             continue;
17712           ExprResult PostUpdateRes =
17713               S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
17714                            RefRes.get());
17715           if (!PostUpdateRes.isUsable())
17716             continue;
17717           if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
17718               Stack->getCurrentDirective() == OMPD_taskgroup) {
17719             S.Diag(RefExpr->getExprLoc(),
17720                    diag::err_omp_reduction_non_addressable_expression)
17721                 << RefExpr->getSourceRange();
17722             continue;
17723           }
17724           RD.ExprPostUpdates.emplace_back(
17725               S.IgnoredValueConversions(PostUpdateRes.get()).get());
17726         }
17727       }
17728     }
17729     // All reduction items are still marked as reduction (to do not increase
17730     // code base size).
17731     unsigned Modifier = RD.RedModifier;
17732     // Consider task_reductions as reductions with task modifier. Required for
17733     // correct analysis of in_reduction clauses.
17734     if (CurrDir == OMPD_taskgroup && ClauseKind == OMPC_task_reduction)
17735       Modifier = OMPC_REDUCTION_task;
17736     Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref, Modifier,
17737                   ASE || OASE);
17738     if (Modifier == OMPC_REDUCTION_task &&
17739         (CurrDir == OMPD_taskgroup ||
17740          ((isOpenMPParallelDirective(CurrDir) ||
17741            isOpenMPWorksharingDirective(CurrDir)) &&
17742           !isOpenMPSimdDirective(CurrDir)))) {
17743       if (DeclareReductionRef.isUsable())
17744         Stack->addTaskgroupReductionData(D, ReductionIdRange,
17745                                          DeclareReductionRef.get());
17746       else
17747         Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK);
17748     }
17749     RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(),
17750             TaskgroupDescriptor, CopyOpRes.get(), TempArrayRes.get(),
17751             TempArrayElem.get());
17752   }
17753   return RD.Vars.empty();
17754 }
17755 
17756 OMPClause *Sema::ActOnOpenMPReductionClause(
17757     ArrayRef<Expr *> VarList, OpenMPReductionClauseModifier Modifier,
17758     SourceLocation StartLoc, SourceLocation LParenLoc,
17759     SourceLocation ModifierLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
17760     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
17761     ArrayRef<Expr *> UnresolvedReductions) {
17762   if (ModifierLoc.isValid() && Modifier == OMPC_REDUCTION_unknown) {
17763     Diag(LParenLoc, diag::err_omp_unexpected_clause_value)
17764         << getListOfPossibleValues(OMPC_reduction, /*First=*/0,
17765                                    /*Last=*/OMPC_REDUCTION_unknown)
17766         << getOpenMPClauseName(OMPC_reduction);
17767     return nullptr;
17768   }
17769   // OpenMP 5.0, 2.19.5.4 reduction Clause, Restrictions
17770   // A reduction clause with the inscan reduction-modifier may only appear on a
17771   // worksharing-loop construct, a worksharing-loop SIMD construct, a simd
17772   // construct, a parallel worksharing-loop construct or a parallel
17773   // worksharing-loop SIMD construct.
17774   if (Modifier == OMPC_REDUCTION_inscan &&
17775       (DSAStack->getCurrentDirective() != OMPD_for &&
17776        DSAStack->getCurrentDirective() != OMPD_for_simd &&
17777        DSAStack->getCurrentDirective() != OMPD_simd &&
17778        DSAStack->getCurrentDirective() != OMPD_parallel_for &&
17779        DSAStack->getCurrentDirective() != OMPD_parallel_for_simd)) {
17780     Diag(ModifierLoc, diag::err_omp_wrong_inscan_reduction);
17781     return nullptr;
17782   }
17783 
17784   ReductionData RD(VarList.size(), Modifier);
17785   if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList,
17786                                   StartLoc, LParenLoc, ColonLoc, EndLoc,
17787                                   ReductionIdScopeSpec, ReductionId,
17788                                   UnresolvedReductions, RD))
17789     return nullptr;
17790 
17791   return OMPReductionClause::Create(
17792       Context, StartLoc, LParenLoc, ModifierLoc, ColonLoc, EndLoc, Modifier,
17793       RD.Vars, ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
17794       RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.InscanCopyOps,
17795       RD.InscanCopyArrayTemps, RD.InscanCopyArrayElems,
17796       buildPreInits(Context, RD.ExprCaptures),
17797       buildPostUpdate(*this, RD.ExprPostUpdates));
17798 }
17799 
17800 OMPClause *Sema::ActOnOpenMPTaskReductionClause(
17801     ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
17802     SourceLocation ColonLoc, SourceLocation EndLoc,
17803     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
17804     ArrayRef<Expr *> UnresolvedReductions) {
17805   ReductionData RD(VarList.size());
17806   if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction, VarList,
17807                                   StartLoc, LParenLoc, ColonLoc, EndLoc,
17808                                   ReductionIdScopeSpec, ReductionId,
17809                                   UnresolvedReductions, RD))
17810     return nullptr;
17811 
17812   return OMPTaskReductionClause::Create(
17813       Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
17814       ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
17815       RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
17816       buildPreInits(Context, RD.ExprCaptures),
17817       buildPostUpdate(*this, RD.ExprPostUpdates));
17818 }
17819 
17820 OMPClause *Sema::ActOnOpenMPInReductionClause(
17821     ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
17822     SourceLocation ColonLoc, SourceLocation EndLoc,
17823     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
17824     ArrayRef<Expr *> UnresolvedReductions) {
17825   ReductionData RD(VarList.size());
17826   if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList,
17827                                   StartLoc, LParenLoc, ColonLoc, EndLoc,
17828                                   ReductionIdScopeSpec, ReductionId,
17829                                   UnresolvedReductions, RD))
17830     return nullptr;
17831 
17832   return OMPInReductionClause::Create(
17833       Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
17834       ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
17835       RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors,
17836       buildPreInits(Context, RD.ExprCaptures),
17837       buildPostUpdate(*this, RD.ExprPostUpdates));
17838 }
17839 
17840 bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
17841                                      SourceLocation LinLoc) {
17842   if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
17843       LinKind == OMPC_LINEAR_unknown) {
17844     Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
17845     return true;
17846   }
17847   return false;
17848 }
17849 
17850 bool Sema::CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc,
17851                                  OpenMPLinearClauseKind LinKind, QualType Type,
17852                                  bool IsDeclareSimd) {
17853   const auto *VD = dyn_cast_or_null<VarDecl>(D);
17854   // A variable must not have an incomplete type or a reference type.
17855   if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
17856     return true;
17857   if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
17858       !Type->isReferenceType()) {
17859     Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
17860         << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
17861     return true;
17862   }
17863   Type = Type.getNonReferenceType();
17864 
17865   // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
17866   // A variable that is privatized must not have a const-qualified type
17867   // unless it is of class type with a mutable member. This restriction does
17868   // not apply to the firstprivate clause, nor to the linear clause on
17869   // declarative directives (like declare simd).
17870   if (!IsDeclareSimd &&
17871       rejectConstNotMutableType(*this, D, Type, OMPC_linear, ELoc))
17872     return true;
17873 
17874   // A list item must be of integral or pointer type.
17875   Type = Type.getUnqualifiedType().getCanonicalType();
17876   const auto *Ty = Type.getTypePtrOrNull();
17877   if (!Ty || (LinKind != OMPC_LINEAR_ref && !Ty->isDependentType() &&
17878               !Ty->isIntegralType(Context) && !Ty->isPointerType())) {
17879     Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
17880     if (D) {
17881       bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
17882                                VarDecl::DeclarationOnly;
17883       Diag(D->getLocation(),
17884            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
17885           << D;
17886     }
17887     return true;
17888   }
17889   return false;
17890 }
17891 
17892 OMPClause *Sema::ActOnOpenMPLinearClause(
17893     ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
17894     SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
17895     SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
17896   SmallVector<Expr *, 8> Vars;
17897   SmallVector<Expr *, 8> Privates;
17898   SmallVector<Expr *, 8> Inits;
17899   SmallVector<Decl *, 4> ExprCaptures;
17900   SmallVector<Expr *, 4> ExprPostUpdates;
17901   if (CheckOpenMPLinearModifier(LinKind, LinLoc))
17902     LinKind = OMPC_LINEAR_val;
17903   for (Expr *RefExpr : VarList) {
17904     assert(RefExpr && "NULL expr in OpenMP linear clause.");
17905     SourceLocation ELoc;
17906     SourceRange ERange;
17907     Expr *SimpleRefExpr = RefExpr;
17908     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
17909     if (Res.second) {
17910       // It will be analyzed later.
17911       Vars.push_back(RefExpr);
17912       Privates.push_back(nullptr);
17913       Inits.push_back(nullptr);
17914     }
17915     ValueDecl *D = Res.first;
17916     if (!D)
17917       continue;
17918 
17919     QualType Type = D->getType();
17920     auto *VD = dyn_cast<VarDecl>(D);
17921 
17922     // OpenMP [2.14.3.7, linear clause]
17923     //  A list-item cannot appear in more than one linear clause.
17924     //  A list-item that appears in a linear clause cannot appear in any
17925     //  other data-sharing attribute clause.
17926     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
17927     if (DVar.RefExpr) {
17928       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
17929                                           << getOpenMPClauseName(OMPC_linear);
17930       reportOriginalDsa(*this, DSAStack, D, DVar);
17931       continue;
17932     }
17933 
17934     if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
17935       continue;
17936     Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
17937 
17938     // Build private copy of original var.
17939     VarDecl *Private =
17940         buildVarDecl(*this, ELoc, Type, D->getName(),
17941                      D->hasAttrs() ? &D->getAttrs() : nullptr,
17942                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
17943     DeclRefExpr *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
17944     // Build var to save initial value.
17945     VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
17946     Expr *InitExpr;
17947     DeclRefExpr *Ref = nullptr;
17948     if (!VD && !CurContext->isDependentContext()) {
17949       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
17950       if (!isOpenMPCapturedDecl(D)) {
17951         ExprCaptures.push_back(Ref->getDecl());
17952         if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
17953           ExprResult RefRes = DefaultLvalueConversion(Ref);
17954           if (!RefRes.isUsable())
17955             continue;
17956           ExprResult PostUpdateRes =
17957               BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
17958                          SimpleRefExpr, RefRes.get());
17959           if (!PostUpdateRes.isUsable())
17960             continue;
17961           ExprPostUpdates.push_back(
17962               IgnoredValueConversions(PostUpdateRes.get()).get());
17963         }
17964       }
17965     }
17966     if (LinKind == OMPC_LINEAR_uval)
17967       InitExpr = VD ? VD->getInit() : SimpleRefExpr;
17968     else
17969       InitExpr = VD ? SimpleRefExpr : Ref;
17970     AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
17971                          /*DirectInit=*/false);
17972     DeclRefExpr *InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
17973 
17974     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
17975     Vars.push_back((VD || CurContext->isDependentContext())
17976                        ? RefExpr->IgnoreParens()
17977                        : Ref);
17978     Privates.push_back(PrivateRef);
17979     Inits.push_back(InitRef);
17980   }
17981 
17982   if (Vars.empty())
17983     return nullptr;
17984 
17985   Expr *StepExpr = Step;
17986   Expr *CalcStepExpr = nullptr;
17987   if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
17988       !Step->isInstantiationDependent() &&
17989       !Step->containsUnexpandedParameterPack()) {
17990     SourceLocation StepLoc = Step->getBeginLoc();
17991     ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
17992     if (Val.isInvalid())
17993       return nullptr;
17994     StepExpr = Val.get();
17995 
17996     // Build var to save the step value.
17997     VarDecl *SaveVar =
17998         buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
17999     ExprResult SaveRef =
18000         buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
18001     ExprResult CalcStep =
18002         BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
18003     CalcStep = ActOnFinishFullExpr(CalcStep.get(), /*DiscardedValue*/ false);
18004 
18005     // Warn about zero linear step (it would be probably better specified as
18006     // making corresponding variables 'const').
18007     if (Optional<llvm::APSInt> Result =
18008             StepExpr->getIntegerConstantExpr(Context)) {
18009       if (!Result->isNegative() && !Result->isStrictlyPositive())
18010         Diag(StepLoc, diag::warn_omp_linear_step_zero)
18011             << Vars[0] << (Vars.size() > 1);
18012     } else if (CalcStep.isUsable()) {
18013       // Calculate the step beforehand instead of doing this on each iteration.
18014       // (This is not used if the number of iterations may be kfold-ed).
18015       CalcStepExpr = CalcStep.get();
18016     }
18017   }
18018 
18019   return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
18020                                  ColonLoc, EndLoc, Vars, Privates, Inits,
18021                                  StepExpr, CalcStepExpr,
18022                                  buildPreInits(Context, ExprCaptures),
18023                                  buildPostUpdate(*this, ExprPostUpdates));
18024 }
18025 
18026 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
18027                                      Expr *NumIterations, Sema &SemaRef,
18028                                      Scope *S, DSAStackTy *Stack) {
18029   // Walk the vars and build update/final expressions for the CodeGen.
18030   SmallVector<Expr *, 8> Updates;
18031   SmallVector<Expr *, 8> Finals;
18032   SmallVector<Expr *, 8> UsedExprs;
18033   Expr *Step = Clause.getStep();
18034   Expr *CalcStep = Clause.getCalcStep();
18035   // OpenMP [2.14.3.7, linear clause]
18036   // If linear-step is not specified it is assumed to be 1.
18037   if (!Step)
18038     Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
18039   else if (CalcStep)
18040     Step = cast<BinaryOperator>(CalcStep)->getLHS();
18041   bool HasErrors = false;
18042   auto CurInit = Clause.inits().begin();
18043   auto CurPrivate = Clause.privates().begin();
18044   OpenMPLinearClauseKind LinKind = Clause.getModifier();
18045   for (Expr *RefExpr : Clause.varlists()) {
18046     SourceLocation ELoc;
18047     SourceRange ERange;
18048     Expr *SimpleRefExpr = RefExpr;
18049     auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange);
18050     ValueDecl *D = Res.first;
18051     if (Res.second || !D) {
18052       Updates.push_back(nullptr);
18053       Finals.push_back(nullptr);
18054       HasErrors = true;
18055       continue;
18056     }
18057     auto &&Info = Stack->isLoopControlVariable(D);
18058     // OpenMP [2.15.11, distribute simd Construct]
18059     // A list item may not appear in a linear clause, unless it is the loop
18060     // iteration variable.
18061     if (isOpenMPDistributeDirective(Stack->getCurrentDirective()) &&
18062         isOpenMPSimdDirective(Stack->getCurrentDirective()) && !Info.first) {
18063       SemaRef.Diag(ELoc,
18064                    diag::err_omp_linear_distribute_var_non_loop_iteration);
18065       Updates.push_back(nullptr);
18066       Finals.push_back(nullptr);
18067       HasErrors = true;
18068       continue;
18069     }
18070     Expr *InitExpr = *CurInit;
18071 
18072     // Build privatized reference to the current linear var.
18073     auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
18074     Expr *CapturedRef;
18075     if (LinKind == OMPC_LINEAR_uval)
18076       CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
18077     else
18078       CapturedRef =
18079           buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
18080                            DE->getType().getUnqualifiedType(), DE->getExprLoc(),
18081                            /*RefersToCapture=*/true);
18082 
18083     // Build update: Var = InitExpr + IV * Step
18084     ExprResult Update;
18085     if (!Info.first)
18086       Update = buildCounterUpdate(
18087           SemaRef, S, RefExpr->getExprLoc(), *CurPrivate, InitExpr, IV, Step,
18088           /*Subtract=*/false, /*IsNonRectangularLB=*/false);
18089     else
18090       Update = *CurPrivate;
18091     Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getBeginLoc(),
18092                                          /*DiscardedValue*/ false);
18093 
18094     // Build final: Var = PrivCopy;
18095     ExprResult Final;
18096     if (!Info.first)
18097       Final = SemaRef.BuildBinOp(
18098           S, RefExpr->getExprLoc(), BO_Assign, CapturedRef,
18099           SemaRef.DefaultLvalueConversion(*CurPrivate).get());
18100     else
18101       Final = *CurPrivate;
18102     Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getBeginLoc(),
18103                                         /*DiscardedValue*/ false);
18104 
18105     if (!Update.isUsable() || !Final.isUsable()) {
18106       Updates.push_back(nullptr);
18107       Finals.push_back(nullptr);
18108       UsedExprs.push_back(nullptr);
18109       HasErrors = true;
18110     } else {
18111       Updates.push_back(Update.get());
18112       Finals.push_back(Final.get());
18113       if (!Info.first)
18114         UsedExprs.push_back(SimpleRefExpr);
18115     }
18116     ++CurInit;
18117     ++CurPrivate;
18118   }
18119   if (Expr *S = Clause.getStep())
18120     UsedExprs.push_back(S);
18121   // Fill the remaining part with the nullptr.
18122   UsedExprs.append(Clause.varlist_size() + 1 - UsedExprs.size(), nullptr);
18123   Clause.setUpdates(Updates);
18124   Clause.setFinals(Finals);
18125   Clause.setUsedExprs(UsedExprs);
18126   return HasErrors;
18127 }
18128 
18129 OMPClause *Sema::ActOnOpenMPAlignedClause(
18130     ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
18131     SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
18132   SmallVector<Expr *, 8> Vars;
18133   for (Expr *RefExpr : VarList) {
18134     assert(RefExpr && "NULL expr in OpenMP linear clause.");
18135     SourceLocation ELoc;
18136     SourceRange ERange;
18137     Expr *SimpleRefExpr = RefExpr;
18138     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
18139     if (Res.second) {
18140       // It will be analyzed later.
18141       Vars.push_back(RefExpr);
18142     }
18143     ValueDecl *D = Res.first;
18144     if (!D)
18145       continue;
18146 
18147     QualType QType = D->getType();
18148     auto *VD = dyn_cast<VarDecl>(D);
18149 
18150     // OpenMP  [2.8.1, simd construct, Restrictions]
18151     // The type of list items appearing in the aligned clause must be
18152     // array, pointer, reference to array, or reference to pointer.
18153     QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
18154     const Type *Ty = QType.getTypePtrOrNull();
18155     if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
18156       Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
18157           << QType << getLangOpts().CPlusPlus << ERange;
18158       bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
18159                                VarDecl::DeclarationOnly;
18160       Diag(D->getLocation(),
18161            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
18162           << D;
18163       continue;
18164     }
18165 
18166     // OpenMP  [2.8.1, simd construct, Restrictions]
18167     // A list-item cannot appear in more than one aligned clause.
18168     if (const Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
18169       Diag(ELoc, diag::err_omp_used_in_clause_twice)
18170           << 0 << getOpenMPClauseName(OMPC_aligned) << ERange;
18171       Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
18172           << getOpenMPClauseName(OMPC_aligned);
18173       continue;
18174     }
18175 
18176     DeclRefExpr *Ref = nullptr;
18177     if (!VD && isOpenMPCapturedDecl(D))
18178       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
18179     Vars.push_back(DefaultFunctionArrayConversion(
18180                        (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
18181                        .get());
18182   }
18183 
18184   // OpenMP [2.8.1, simd construct, Description]
18185   // The parameter of the aligned clause, alignment, must be a constant
18186   // positive integer expression.
18187   // If no optional parameter is specified, implementation-defined default
18188   // alignments for SIMD instructions on the target platforms are assumed.
18189   if (Alignment != nullptr) {
18190     ExprResult AlignResult =
18191         VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
18192     if (AlignResult.isInvalid())
18193       return nullptr;
18194     Alignment = AlignResult.get();
18195   }
18196   if (Vars.empty())
18197     return nullptr;
18198 
18199   return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
18200                                   EndLoc, Vars, Alignment);
18201 }
18202 
18203 OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
18204                                          SourceLocation StartLoc,
18205                                          SourceLocation LParenLoc,
18206                                          SourceLocation EndLoc) {
18207   SmallVector<Expr *, 8> Vars;
18208   SmallVector<Expr *, 8> SrcExprs;
18209   SmallVector<Expr *, 8> DstExprs;
18210   SmallVector<Expr *, 8> AssignmentOps;
18211   for (Expr *RefExpr : VarList) {
18212     assert(RefExpr && "NULL expr in OpenMP copyin clause.");
18213     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
18214       // It will be analyzed later.
18215       Vars.push_back(RefExpr);
18216       SrcExprs.push_back(nullptr);
18217       DstExprs.push_back(nullptr);
18218       AssignmentOps.push_back(nullptr);
18219       continue;
18220     }
18221 
18222     SourceLocation ELoc = RefExpr->getExprLoc();
18223     // OpenMP [2.1, C/C++]
18224     //  A list item is a variable name.
18225     // OpenMP  [2.14.4.1, Restrictions, p.1]
18226     //  A list item that appears in a copyin clause must be threadprivate.
18227     auto *DE = dyn_cast<DeclRefExpr>(RefExpr);
18228     if (!DE || !isa<VarDecl>(DE->getDecl())) {
18229       Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
18230           << 0 << RefExpr->getSourceRange();
18231       continue;
18232     }
18233 
18234     Decl *D = DE->getDecl();
18235     auto *VD = cast<VarDecl>(D);
18236 
18237     QualType Type = VD->getType();
18238     if (Type->isDependentType() || Type->isInstantiationDependentType()) {
18239       // It will be analyzed later.
18240       Vars.push_back(DE);
18241       SrcExprs.push_back(nullptr);
18242       DstExprs.push_back(nullptr);
18243       AssignmentOps.push_back(nullptr);
18244       continue;
18245     }
18246 
18247     // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
18248     //  A list item that appears in a copyin clause must be threadprivate.
18249     if (!DSAStack->isThreadPrivate(VD)) {
18250       Diag(ELoc, diag::err_omp_required_access)
18251           << getOpenMPClauseName(OMPC_copyin)
18252           << getOpenMPDirectiveName(OMPD_threadprivate);
18253       continue;
18254     }
18255 
18256     // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
18257     //  A variable of class type (or array thereof) that appears in a
18258     //  copyin clause requires an accessible, unambiguous copy assignment
18259     //  operator for the class type.
18260     QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
18261     VarDecl *SrcVD =
18262         buildVarDecl(*this, DE->getBeginLoc(), ElemType.getUnqualifiedType(),
18263                      ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
18264     DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(
18265         *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
18266     VarDecl *DstVD =
18267         buildVarDecl(*this, DE->getBeginLoc(), ElemType, ".copyin.dst",
18268                      VD->hasAttrs() ? &VD->getAttrs() : nullptr);
18269     DeclRefExpr *PseudoDstExpr =
18270         buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
18271     // For arrays generate assignment operation for single element and replace
18272     // it by the original array element in CodeGen.
18273     ExprResult AssignmentOp =
18274         BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign, PseudoDstExpr,
18275                    PseudoSrcExpr);
18276     if (AssignmentOp.isInvalid())
18277       continue;
18278     AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
18279                                        /*DiscardedValue*/ false);
18280     if (AssignmentOp.isInvalid())
18281       continue;
18282 
18283     DSAStack->addDSA(VD, DE, OMPC_copyin);
18284     Vars.push_back(DE);
18285     SrcExprs.push_back(PseudoSrcExpr);
18286     DstExprs.push_back(PseudoDstExpr);
18287     AssignmentOps.push_back(AssignmentOp.get());
18288   }
18289 
18290   if (Vars.empty())
18291     return nullptr;
18292 
18293   return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
18294                                  SrcExprs, DstExprs, AssignmentOps);
18295 }
18296 
18297 OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
18298                                               SourceLocation StartLoc,
18299                                               SourceLocation LParenLoc,
18300                                               SourceLocation EndLoc) {
18301   SmallVector<Expr *, 8> Vars;
18302   SmallVector<Expr *, 8> SrcExprs;
18303   SmallVector<Expr *, 8> DstExprs;
18304   SmallVector<Expr *, 8> AssignmentOps;
18305   for (Expr *RefExpr : VarList) {
18306     assert(RefExpr && "NULL expr in OpenMP linear clause.");
18307     SourceLocation ELoc;
18308     SourceRange ERange;
18309     Expr *SimpleRefExpr = RefExpr;
18310     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
18311     if (Res.second) {
18312       // It will be analyzed later.
18313       Vars.push_back(RefExpr);
18314       SrcExprs.push_back(nullptr);
18315       DstExprs.push_back(nullptr);
18316       AssignmentOps.push_back(nullptr);
18317     }
18318     ValueDecl *D = Res.first;
18319     if (!D)
18320       continue;
18321 
18322     QualType Type = D->getType();
18323     auto *VD = dyn_cast<VarDecl>(D);
18324 
18325     // OpenMP [2.14.4.2, Restrictions, p.2]
18326     //  A list item that appears in a copyprivate clause may not appear in a
18327     //  private or firstprivate clause on the single construct.
18328     if (!VD || !DSAStack->isThreadPrivate(VD)) {
18329       DSAStackTy::DSAVarData DVar =
18330           DSAStack->getTopDSA(D, /*FromParent=*/false);
18331       if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
18332           DVar.RefExpr) {
18333         Diag(ELoc, diag::err_omp_wrong_dsa)
18334             << getOpenMPClauseName(DVar.CKind)
18335             << getOpenMPClauseName(OMPC_copyprivate);
18336         reportOriginalDsa(*this, DSAStack, D, DVar);
18337         continue;
18338       }
18339 
18340       // OpenMP [2.11.4.2, Restrictions, p.1]
18341       //  All list items that appear in a copyprivate clause must be either
18342       //  threadprivate or private in the enclosing context.
18343       if (DVar.CKind == OMPC_unknown) {
18344         DVar = DSAStack->getImplicitDSA(D, false);
18345         if (DVar.CKind == OMPC_shared) {
18346           Diag(ELoc, diag::err_omp_required_access)
18347               << getOpenMPClauseName(OMPC_copyprivate)
18348               << "threadprivate or private in the enclosing context";
18349           reportOriginalDsa(*this, DSAStack, D, DVar);
18350           continue;
18351         }
18352       }
18353     }
18354 
18355     // Variably modified types are not supported.
18356     if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
18357       Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
18358           << getOpenMPClauseName(OMPC_copyprivate) << Type
18359           << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
18360       bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
18361                                VarDecl::DeclarationOnly;
18362       Diag(D->getLocation(),
18363            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
18364           << D;
18365       continue;
18366     }
18367 
18368     // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
18369     //  A variable of class type (or array thereof) that appears in a
18370     //  copyin clause requires an accessible, unambiguous copy assignment
18371     //  operator for the class type.
18372     Type = Context.getBaseElementType(Type.getNonReferenceType())
18373                .getUnqualifiedType();
18374     VarDecl *SrcVD =
18375         buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.src",
18376                      D->hasAttrs() ? &D->getAttrs() : nullptr);
18377     DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
18378     VarDecl *DstVD =
18379         buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.dst",
18380                      D->hasAttrs() ? &D->getAttrs() : nullptr);
18381     DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
18382     ExprResult AssignmentOp = BuildBinOp(
18383         DSAStack->getCurScope(), ELoc, BO_Assign, PseudoDstExpr, PseudoSrcExpr);
18384     if (AssignmentOp.isInvalid())
18385       continue;
18386     AssignmentOp =
18387         ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
18388     if (AssignmentOp.isInvalid())
18389       continue;
18390 
18391     // No need to mark vars as copyprivate, they are already threadprivate or
18392     // implicitly private.
18393     assert(VD || isOpenMPCapturedDecl(D));
18394     Vars.push_back(
18395         VD ? RefExpr->IgnoreParens()
18396            : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
18397     SrcExprs.push_back(PseudoSrcExpr);
18398     DstExprs.push_back(PseudoDstExpr);
18399     AssignmentOps.push_back(AssignmentOp.get());
18400   }
18401 
18402   if (Vars.empty())
18403     return nullptr;
18404 
18405   return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
18406                                       Vars, SrcExprs, DstExprs, AssignmentOps);
18407 }
18408 
18409 OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
18410                                         SourceLocation StartLoc,
18411                                         SourceLocation LParenLoc,
18412                                         SourceLocation EndLoc) {
18413   if (VarList.empty())
18414     return nullptr;
18415 
18416   return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
18417 }
18418 
18419 /// Tries to find omp_depend_t. type.
18420 static bool findOMPDependT(Sema &S, SourceLocation Loc, DSAStackTy *Stack,
18421                            bool Diagnose = true) {
18422   QualType OMPDependT = Stack->getOMPDependT();
18423   if (!OMPDependT.isNull())
18424     return true;
18425   IdentifierInfo *II = &S.PP.getIdentifierTable().get("omp_depend_t");
18426   ParsedType PT = S.getTypeName(*II, Loc, S.getCurScope());
18427   if (!PT.getAsOpaquePtr() || PT.get().isNull()) {
18428     if (Diagnose)
18429       S.Diag(Loc, diag::err_omp_implied_type_not_found) << "omp_depend_t";
18430     return false;
18431   }
18432   Stack->setOMPDependT(PT.get());
18433   return true;
18434 }
18435 
18436 OMPClause *Sema::ActOnOpenMPDepobjClause(Expr *Depobj, SourceLocation StartLoc,
18437                                          SourceLocation LParenLoc,
18438                                          SourceLocation EndLoc) {
18439   if (!Depobj)
18440     return nullptr;
18441 
18442   bool OMPDependTFound = findOMPDependT(*this, StartLoc, DSAStack);
18443 
18444   // OpenMP 5.0, 2.17.10.1 depobj Construct
18445   // depobj is an lvalue expression of type omp_depend_t.
18446   if (!Depobj->isTypeDependent() && !Depobj->isValueDependent() &&
18447       !Depobj->isInstantiationDependent() &&
18448       !Depobj->containsUnexpandedParameterPack() &&
18449       (OMPDependTFound &&
18450        !Context.typesAreCompatible(DSAStack->getOMPDependT(), Depobj->getType(),
18451                                    /*CompareUnqualified=*/true))) {
18452     Diag(Depobj->getExprLoc(), diag::err_omp_expected_omp_depend_t_lvalue)
18453         << 0 << Depobj->getType() << Depobj->getSourceRange();
18454   }
18455 
18456   if (!Depobj->isLValue()) {
18457     Diag(Depobj->getExprLoc(), diag::err_omp_expected_omp_depend_t_lvalue)
18458         << 1 << Depobj->getSourceRange();
18459   }
18460 
18461   return OMPDepobjClause::Create(Context, StartLoc, LParenLoc, EndLoc, Depobj);
18462 }
18463 
18464 OMPClause *
18465 Sema::ActOnOpenMPDependClause(Expr *DepModifier, OpenMPDependClauseKind DepKind,
18466                               SourceLocation DepLoc, SourceLocation ColonLoc,
18467                               ArrayRef<Expr *> VarList, SourceLocation StartLoc,
18468                               SourceLocation LParenLoc, SourceLocation EndLoc) {
18469   if (DSAStack->getCurrentDirective() == OMPD_ordered &&
18470       DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
18471     Diag(DepLoc, diag::err_omp_unexpected_clause_value)
18472         << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
18473     return nullptr;
18474   }
18475   if (DSAStack->getCurrentDirective() == OMPD_taskwait &&
18476       DepKind == OMPC_DEPEND_mutexinoutset) {
18477     Diag(DepLoc, diag::err_omp_taskwait_depend_mutexinoutset_not_allowed);
18478     return nullptr;
18479   }
18480   if ((DSAStack->getCurrentDirective() != OMPD_ordered ||
18481        DSAStack->getCurrentDirective() == OMPD_depobj) &&
18482       (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
18483        DepKind == OMPC_DEPEND_sink ||
18484        ((LangOpts.OpenMP < 50 ||
18485          DSAStack->getCurrentDirective() == OMPD_depobj) &&
18486         DepKind == OMPC_DEPEND_depobj))) {
18487     SmallVector<unsigned, 3> Except;
18488     Except.push_back(OMPC_DEPEND_source);
18489     Except.push_back(OMPC_DEPEND_sink);
18490     if (LangOpts.OpenMP < 50 || DSAStack->getCurrentDirective() == OMPD_depobj)
18491       Except.push_back(OMPC_DEPEND_depobj);
18492     std::string Expected = (LangOpts.OpenMP >= 50 && !DepModifier)
18493                                ? "depend modifier(iterator) or "
18494                                : "";
18495     Diag(DepLoc, diag::err_omp_unexpected_clause_value)
18496         << Expected + getListOfPossibleValues(OMPC_depend, /*First=*/0,
18497                                               /*Last=*/OMPC_DEPEND_unknown,
18498                                               Except)
18499         << getOpenMPClauseName(OMPC_depend);
18500     return nullptr;
18501   }
18502   if (DepModifier &&
18503       (DepKind == OMPC_DEPEND_source || DepKind == OMPC_DEPEND_sink)) {
18504     Diag(DepModifier->getExprLoc(),
18505          diag::err_omp_depend_sink_source_with_modifier);
18506     return nullptr;
18507   }
18508   if (DepModifier &&
18509       !DepModifier->getType()->isSpecificBuiltinType(BuiltinType::OMPIterator))
18510     Diag(DepModifier->getExprLoc(), diag::err_omp_depend_modifier_not_iterator);
18511 
18512   SmallVector<Expr *, 8> Vars;
18513   DSAStackTy::OperatorOffsetTy OpsOffs;
18514   llvm::APSInt DepCounter(/*BitWidth=*/32);
18515   llvm::APSInt TotalDepCount(/*BitWidth=*/32);
18516   if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) {
18517     if (const Expr *OrderedCountExpr =
18518             DSAStack->getParentOrderedRegionParam().first) {
18519       TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
18520       TotalDepCount.setIsUnsigned(/*Val=*/true);
18521     }
18522   }
18523   for (Expr *RefExpr : VarList) {
18524     assert(RefExpr && "NULL expr in OpenMP shared clause.");
18525     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
18526       // It will be analyzed later.
18527       Vars.push_back(RefExpr);
18528       continue;
18529     }
18530 
18531     SourceLocation ELoc = RefExpr->getExprLoc();
18532     Expr *SimpleExpr = RefExpr->IgnoreParenCasts();
18533     if (DepKind == OMPC_DEPEND_sink) {
18534       if (DSAStack->getParentOrderedRegionParam().first &&
18535           DepCounter >= TotalDepCount) {
18536         Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
18537         continue;
18538       }
18539       ++DepCounter;
18540       // OpenMP  [2.13.9, Summary]
18541       // depend(dependence-type : vec), where dependence-type is:
18542       // 'sink' and where vec is the iteration vector, which has the form:
18543       //  x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
18544       // where n is the value specified by the ordered clause in the loop
18545       // directive, xi denotes the loop iteration variable of the i-th nested
18546       // loop associated with the loop directive, and di is a constant
18547       // non-negative integer.
18548       if (CurContext->isDependentContext()) {
18549         // It will be analyzed later.
18550         Vars.push_back(RefExpr);
18551         continue;
18552       }
18553       SimpleExpr = SimpleExpr->IgnoreImplicit();
18554       OverloadedOperatorKind OOK = OO_None;
18555       SourceLocation OOLoc;
18556       Expr *LHS = SimpleExpr;
18557       Expr *RHS = nullptr;
18558       if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
18559         OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
18560         OOLoc = BO->getOperatorLoc();
18561         LHS = BO->getLHS()->IgnoreParenImpCasts();
18562         RHS = BO->getRHS()->IgnoreParenImpCasts();
18563       } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
18564         OOK = OCE->getOperator();
18565         OOLoc = OCE->getOperatorLoc();
18566         LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
18567         RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
18568       } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
18569         OOK = MCE->getMethodDecl()
18570                   ->getNameInfo()
18571                   .getName()
18572                   .getCXXOverloadedOperator();
18573         OOLoc = MCE->getCallee()->getExprLoc();
18574         LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
18575         RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
18576       }
18577       SourceLocation ELoc;
18578       SourceRange ERange;
18579       auto Res = getPrivateItem(*this, LHS, ELoc, ERange);
18580       if (Res.second) {
18581         // It will be analyzed later.
18582         Vars.push_back(RefExpr);
18583       }
18584       ValueDecl *D = Res.first;
18585       if (!D)
18586         continue;
18587 
18588       if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
18589         Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
18590         continue;
18591       }
18592       if (RHS) {
18593         ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
18594             RHS, OMPC_depend, /*StrictlyPositive=*/false);
18595         if (RHSRes.isInvalid())
18596           continue;
18597       }
18598       if (!CurContext->isDependentContext() &&
18599           DSAStack->getParentOrderedRegionParam().first &&
18600           DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
18601         const ValueDecl *VD =
18602             DSAStack->getParentLoopControlVariable(DepCounter.getZExtValue());
18603         if (VD)
18604           Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
18605               << 1 << VD;
18606         else
18607           Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0;
18608         continue;
18609       }
18610       OpsOffs.emplace_back(RHS, OOK);
18611     } else {
18612       bool OMPDependTFound = LangOpts.OpenMP >= 50;
18613       if (OMPDependTFound)
18614         OMPDependTFound = findOMPDependT(*this, StartLoc, DSAStack,
18615                                          DepKind == OMPC_DEPEND_depobj);
18616       if (DepKind == OMPC_DEPEND_depobj) {
18617         // OpenMP 5.0, 2.17.11 depend Clause, Restrictions, C/C++
18618         // List items used in depend clauses with the depobj dependence type
18619         // must be expressions of the omp_depend_t type.
18620         if (!RefExpr->isValueDependent() && !RefExpr->isTypeDependent() &&
18621             !RefExpr->isInstantiationDependent() &&
18622             !RefExpr->containsUnexpandedParameterPack() &&
18623             (OMPDependTFound &&
18624              !Context.hasSameUnqualifiedType(DSAStack->getOMPDependT(),
18625                                              RefExpr->getType()))) {
18626           Diag(ELoc, diag::err_omp_expected_omp_depend_t_lvalue)
18627               << 0 << RefExpr->getType() << RefExpr->getSourceRange();
18628           continue;
18629         }
18630         if (!RefExpr->isLValue()) {
18631           Diag(ELoc, diag::err_omp_expected_omp_depend_t_lvalue)
18632               << 1 << RefExpr->getType() << RefExpr->getSourceRange();
18633           continue;
18634         }
18635       } else {
18636         // OpenMP 5.0 [2.17.11, Restrictions]
18637         // List items used in depend clauses cannot be zero-length array
18638         // sections.
18639         QualType ExprTy = RefExpr->getType().getNonReferenceType();
18640         const auto *OASE = dyn_cast<OMPArraySectionExpr>(SimpleExpr);
18641         if (OASE) {
18642           QualType BaseType =
18643               OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
18644           if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
18645             ExprTy = ATy->getElementType();
18646           else
18647             ExprTy = BaseType->getPointeeType();
18648           ExprTy = ExprTy.getNonReferenceType();
18649           const Expr *Length = OASE->getLength();
18650           Expr::EvalResult Result;
18651           if (Length && !Length->isValueDependent() &&
18652               Length->EvaluateAsInt(Result, Context) &&
18653               Result.Val.getInt().isZero()) {
18654             Diag(ELoc,
18655                  diag::err_omp_depend_zero_length_array_section_not_allowed)
18656                 << SimpleExpr->getSourceRange();
18657             continue;
18658           }
18659         }
18660 
18661         // OpenMP 5.0, 2.17.11 depend Clause, Restrictions, C/C++
18662         // List items used in depend clauses with the in, out, inout or
18663         // mutexinoutset dependence types cannot be expressions of the
18664         // omp_depend_t type.
18665         if (!RefExpr->isValueDependent() && !RefExpr->isTypeDependent() &&
18666             !RefExpr->isInstantiationDependent() &&
18667             !RefExpr->containsUnexpandedParameterPack() &&
18668             (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
18669              (OMPDependTFound &&
18670               DSAStack->getOMPDependT().getTypePtr() == ExprTy.getTypePtr()))) {
18671           Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
18672               << (LangOpts.OpenMP >= 50 ? 1 : 0)
18673               << (LangOpts.OpenMP >= 50 ? 1 : 0) << RefExpr->getSourceRange();
18674           continue;
18675         }
18676 
18677         auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
18678         if (ASE && !ASE->getBase()->isTypeDependent() &&
18679             !ASE->getBase()->getType().getNonReferenceType()->isPointerType() &&
18680             !ASE->getBase()->getType().getNonReferenceType()->isArrayType()) {
18681           Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
18682               << (LangOpts.OpenMP >= 50 ? 1 : 0)
18683               << (LangOpts.OpenMP >= 50 ? 1 : 0) << RefExpr->getSourceRange();
18684           continue;
18685         }
18686 
18687         ExprResult Res;
18688         {
18689           Sema::TentativeAnalysisScope Trap(*this);
18690           Res = CreateBuiltinUnaryOp(ELoc, UO_AddrOf,
18691                                      RefExpr->IgnoreParenImpCasts());
18692         }
18693         if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr) &&
18694             !isa<OMPArrayShapingExpr>(SimpleExpr)) {
18695           Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
18696               << (LangOpts.OpenMP >= 50 ? 1 : 0)
18697               << (LangOpts.OpenMP >= 50 ? 1 : 0) << RefExpr->getSourceRange();
18698           continue;
18699         }
18700       }
18701     }
18702     Vars.push_back(RefExpr->IgnoreParenImpCasts());
18703   }
18704 
18705   if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
18706       TotalDepCount > VarList.size() &&
18707       DSAStack->getParentOrderedRegionParam().first &&
18708       DSAStack->getParentLoopControlVariable(VarList.size() + 1)) {
18709     Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
18710         << 1 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
18711   }
18712   if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
18713       Vars.empty())
18714     return nullptr;
18715 
18716   auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
18717                                     DepModifier, DepKind, DepLoc, ColonLoc,
18718                                     Vars, TotalDepCount.getZExtValue());
18719   if ((DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) &&
18720       DSAStack->isParentOrderedRegion())
18721     DSAStack->addDoacrossDependClause(C, OpsOffs);
18722   return C;
18723 }
18724 
18725 OMPClause *Sema::ActOnOpenMPDeviceClause(OpenMPDeviceClauseModifier Modifier,
18726                                          Expr *Device, SourceLocation StartLoc,
18727                                          SourceLocation LParenLoc,
18728                                          SourceLocation ModifierLoc,
18729                                          SourceLocation EndLoc) {
18730   assert((ModifierLoc.isInvalid() || LangOpts.OpenMP >= 50) &&
18731          "Unexpected device modifier in OpenMP < 50.");
18732 
18733   bool ErrorFound = false;
18734   if (ModifierLoc.isValid() && Modifier == OMPC_DEVICE_unknown) {
18735     std::string Values =
18736         getListOfPossibleValues(OMPC_device, /*First=*/0, OMPC_DEVICE_unknown);
18737     Diag(ModifierLoc, diag::err_omp_unexpected_clause_value)
18738         << Values << getOpenMPClauseName(OMPC_device);
18739     ErrorFound = true;
18740   }
18741 
18742   Expr *ValExpr = Device;
18743   Stmt *HelperValStmt = nullptr;
18744 
18745   // OpenMP [2.9.1, Restrictions]
18746   // The device expression must evaluate to a non-negative integer value.
18747   ErrorFound = !isNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
18748                                           /*StrictlyPositive=*/false) ||
18749                ErrorFound;
18750   if (ErrorFound)
18751     return nullptr;
18752 
18753   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
18754   OpenMPDirectiveKind CaptureRegion =
18755       getOpenMPCaptureRegionForClause(DKind, OMPC_device, LangOpts.OpenMP);
18756   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
18757     ValExpr = MakeFullExpr(ValExpr).get();
18758     llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
18759     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
18760     HelperValStmt = buildPreInits(Context, Captures);
18761   }
18762 
18763   return new (Context)
18764       OMPDeviceClause(Modifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
18765                       LParenLoc, ModifierLoc, EndLoc);
18766 }
18767 
18768 static bool checkTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
18769                               DSAStackTy *Stack, QualType QTy,
18770                               bool FullCheck = true) {
18771   if (SemaRef.RequireCompleteType(SL, QTy, diag::err_incomplete_type))
18772     return false;
18773   if (FullCheck && !SemaRef.CurContext->isDependentContext() &&
18774       !QTy.isTriviallyCopyableType(SemaRef.Context))
18775     SemaRef.Diag(SL, diag::warn_omp_non_trivial_type_mapped) << QTy << SR;
18776   return true;
18777 }
18778 
18779 /// Return true if it can be proven that the provided array expression
18780 /// (array section or array subscript) does NOT specify the whole size of the
18781 /// array whose base type is \a BaseQTy.
18782 static bool checkArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
18783                                                         const Expr *E,
18784                                                         QualType BaseQTy) {
18785   const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
18786 
18787   // If this is an array subscript, it refers to the whole size if the size of
18788   // the dimension is constant and equals 1. Also, an array section assumes the
18789   // format of an array subscript if no colon is used.
18790   if (isa<ArraySubscriptExpr>(E) ||
18791       (OASE && OASE->getColonLocFirst().isInvalid())) {
18792     if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
18793       return ATy->getSize().getSExtValue() != 1;
18794     // Size can't be evaluated statically.
18795     return false;
18796   }
18797 
18798   assert(OASE && "Expecting array section if not an array subscript.");
18799   const Expr *LowerBound = OASE->getLowerBound();
18800   const Expr *Length = OASE->getLength();
18801 
18802   // If there is a lower bound that does not evaluates to zero, we are not
18803   // covering the whole dimension.
18804   if (LowerBound) {
18805     Expr::EvalResult Result;
18806     if (!LowerBound->EvaluateAsInt(Result, SemaRef.getASTContext()))
18807       return false; // Can't get the integer value as a constant.
18808 
18809     llvm::APSInt ConstLowerBound = Result.Val.getInt();
18810     if (ConstLowerBound.getSExtValue())
18811       return true;
18812   }
18813 
18814   // If we don't have a length we covering the whole dimension.
18815   if (!Length)
18816     return false;
18817 
18818   // If the base is a pointer, we don't have a way to get the size of the
18819   // pointee.
18820   if (BaseQTy->isPointerType())
18821     return false;
18822 
18823   // We can only check if the length is the same as the size of the dimension
18824   // if we have a constant array.
18825   const auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
18826   if (!CATy)
18827     return false;
18828 
18829   Expr::EvalResult Result;
18830   if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
18831     return false; // Can't get the integer value as a constant.
18832 
18833   llvm::APSInt ConstLength = Result.Val.getInt();
18834   return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
18835 }
18836 
18837 // Return true if it can be proven that the provided array expression (array
18838 // section or array subscript) does NOT specify a single element of the array
18839 // whose base type is \a BaseQTy.
18840 static bool checkArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
18841                                                         const Expr *E,
18842                                                         QualType BaseQTy) {
18843   const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
18844 
18845   // An array subscript always refer to a single element. Also, an array section
18846   // assumes the format of an array subscript if no colon is used.
18847   if (isa<ArraySubscriptExpr>(E) ||
18848       (OASE && OASE->getColonLocFirst().isInvalid()))
18849     return false;
18850 
18851   assert(OASE && "Expecting array section if not an array subscript.");
18852   const Expr *Length = OASE->getLength();
18853 
18854   // If we don't have a length we have to check if the array has unitary size
18855   // for this dimension. Also, we should always expect a length if the base type
18856   // is pointer.
18857   if (!Length) {
18858     if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
18859       return ATy->getSize().getSExtValue() != 1;
18860     // We cannot assume anything.
18861     return false;
18862   }
18863 
18864   // Check if the length evaluates to 1.
18865   Expr::EvalResult Result;
18866   if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
18867     return false; // Can't get the integer value as a constant.
18868 
18869   llvm::APSInt ConstLength = Result.Val.getInt();
18870   return ConstLength.getSExtValue() != 1;
18871 }
18872 
18873 // The base of elements of list in a map clause have to be either:
18874 //  - a reference to variable or field.
18875 //  - a member expression.
18876 //  - an array expression.
18877 //
18878 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
18879 // reference to 'r'.
18880 //
18881 // If we have:
18882 //
18883 // struct SS {
18884 //   Bla S;
18885 //   foo() {
18886 //     #pragma omp target map (S.Arr[:12]);
18887 //   }
18888 // }
18889 //
18890 // We want to retrieve the member expression 'this->S';
18891 
18892 // OpenMP 5.0 [2.19.7.1, map Clause, Restrictions, p.2]
18893 //  If a list item is an array section, it must specify contiguous storage.
18894 //
18895 // For this restriction it is sufficient that we make sure only references
18896 // to variables or fields and array expressions, and that no array sections
18897 // exist except in the rightmost expression (unless they cover the whole
18898 // dimension of the array). E.g. these would be invalid:
18899 //
18900 //   r.ArrS[3:5].Arr[6:7]
18901 //
18902 //   r.ArrS[3:5].x
18903 //
18904 // but these would be valid:
18905 //   r.ArrS[3].Arr[6:7]
18906 //
18907 //   r.ArrS[3].x
18908 namespace {
18909 class MapBaseChecker final : public StmtVisitor<MapBaseChecker, bool> {
18910   Sema &SemaRef;
18911   OpenMPClauseKind CKind = OMPC_unknown;
18912   OpenMPDirectiveKind DKind = OMPD_unknown;
18913   OMPClauseMappableExprCommon::MappableExprComponentList &Components;
18914   bool IsNonContiguous = false;
18915   bool NoDiagnose = false;
18916   const Expr *RelevantExpr = nullptr;
18917   bool AllowUnitySizeArraySection = true;
18918   bool AllowWholeSizeArraySection = true;
18919   bool AllowAnotherPtr = true;
18920   SourceLocation ELoc;
18921   SourceRange ERange;
18922 
18923   void emitErrorMsg() {
18924     // If nothing else worked, this is not a valid map clause expression.
18925     if (SemaRef.getLangOpts().OpenMP < 50) {
18926       SemaRef.Diag(ELoc,
18927                    diag::err_omp_expected_named_var_member_or_array_expression)
18928           << ERange;
18929     } else {
18930       SemaRef.Diag(ELoc, diag::err_omp_non_lvalue_in_map_or_motion_clauses)
18931           << getOpenMPClauseName(CKind) << ERange;
18932     }
18933   }
18934 
18935 public:
18936   bool VisitDeclRefExpr(DeclRefExpr *DRE) {
18937     if (!isa<VarDecl>(DRE->getDecl())) {
18938       emitErrorMsg();
18939       return false;
18940     }
18941     assert(!RelevantExpr && "RelevantExpr is expected to be nullptr");
18942     RelevantExpr = DRE;
18943     // Record the component.
18944     Components.emplace_back(DRE, DRE->getDecl(), IsNonContiguous);
18945     return true;
18946   }
18947 
18948   bool VisitMemberExpr(MemberExpr *ME) {
18949     Expr *E = ME;
18950     Expr *BaseE = ME->getBase()->IgnoreParenCasts();
18951 
18952     if (isa<CXXThisExpr>(BaseE)) {
18953       assert(!RelevantExpr && "RelevantExpr is expected to be nullptr");
18954       // We found a base expression: this->Val.
18955       RelevantExpr = ME;
18956     } else {
18957       E = BaseE;
18958     }
18959 
18960     if (!isa<FieldDecl>(ME->getMemberDecl())) {
18961       if (!NoDiagnose) {
18962         SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
18963             << ME->getSourceRange();
18964         return false;
18965       }
18966       if (RelevantExpr)
18967         return false;
18968       return Visit(E);
18969     }
18970 
18971     auto *FD = cast<FieldDecl>(ME->getMemberDecl());
18972 
18973     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
18974     //  A bit-field cannot appear in a map clause.
18975     //
18976     if (FD->isBitField()) {
18977       if (!NoDiagnose) {
18978         SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
18979             << ME->getSourceRange() << getOpenMPClauseName(CKind);
18980         return false;
18981       }
18982       if (RelevantExpr)
18983         return false;
18984       return Visit(E);
18985     }
18986 
18987     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
18988     //  If the type of a list item is a reference to a type T then the type
18989     //  will be considered to be T for all purposes of this clause.
18990     QualType CurType = BaseE->getType().getNonReferenceType();
18991 
18992     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
18993     //  A list item cannot be a variable that is a member of a structure with
18994     //  a union type.
18995     //
18996     if (CurType->isUnionType()) {
18997       if (!NoDiagnose) {
18998         SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
18999             << ME->getSourceRange();
19000         return false;
19001       }
19002       return RelevantExpr || Visit(E);
19003     }
19004 
19005     // If we got a member expression, we should not expect any array section
19006     // before that:
19007     //
19008     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
19009     //  If a list item is an element of a structure, only the rightmost symbol
19010     //  of the variable reference can be an array section.
19011     //
19012     AllowUnitySizeArraySection = false;
19013     AllowWholeSizeArraySection = false;
19014 
19015     // Record the component.
19016     Components.emplace_back(ME, FD, IsNonContiguous);
19017     return RelevantExpr || Visit(E);
19018   }
19019 
19020   bool VisitArraySubscriptExpr(ArraySubscriptExpr *AE) {
19021     Expr *E = AE->getBase()->IgnoreParenImpCasts();
19022 
19023     if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
19024       if (!NoDiagnose) {
19025         SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
19026             << 0 << AE->getSourceRange();
19027         return false;
19028       }
19029       return RelevantExpr || Visit(E);
19030     }
19031 
19032     // If we got an array subscript that express the whole dimension we
19033     // can have any array expressions before. If it only expressing part of
19034     // the dimension, we can only have unitary-size array expressions.
19035     if (checkArrayExpressionDoesNotReferToWholeSize(SemaRef, AE, E->getType()))
19036       AllowWholeSizeArraySection = false;
19037 
19038     if (const auto *TE = dyn_cast<CXXThisExpr>(E->IgnoreParenCasts())) {
19039       Expr::EvalResult Result;
19040       if (!AE->getIdx()->isValueDependent() &&
19041           AE->getIdx()->EvaluateAsInt(Result, SemaRef.getASTContext()) &&
19042           !Result.Val.getInt().isZero()) {
19043         SemaRef.Diag(AE->getIdx()->getExprLoc(),
19044                      diag::err_omp_invalid_map_this_expr);
19045         SemaRef.Diag(AE->getIdx()->getExprLoc(),
19046                      diag::note_omp_invalid_subscript_on_this_ptr_map);
19047       }
19048       assert(!RelevantExpr && "RelevantExpr is expected to be nullptr");
19049       RelevantExpr = TE;
19050     }
19051 
19052     // Record the component - we don't have any declaration associated.
19053     Components.emplace_back(AE, nullptr, IsNonContiguous);
19054 
19055     return RelevantExpr || Visit(E);
19056   }
19057 
19058   bool VisitOMPArraySectionExpr(OMPArraySectionExpr *OASE) {
19059     // After OMP 5.0  Array section in reduction clause will be implicitly
19060     // mapped
19061     assert(!(SemaRef.getLangOpts().OpenMP < 50 && NoDiagnose) &&
19062            "Array sections cannot be implicitly mapped.");
19063     Expr *E = OASE->getBase()->IgnoreParenImpCasts();
19064     QualType CurType =
19065         OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
19066 
19067     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
19068     //  If the type of a list item is a reference to a type T then the type
19069     //  will be considered to be T for all purposes of this clause.
19070     if (CurType->isReferenceType())
19071       CurType = CurType->getPointeeType();
19072 
19073     bool IsPointer = CurType->isAnyPointerType();
19074 
19075     if (!IsPointer && !CurType->isArrayType()) {
19076       SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
19077           << 0 << OASE->getSourceRange();
19078       return false;
19079     }
19080 
19081     bool NotWhole =
19082         checkArrayExpressionDoesNotReferToWholeSize(SemaRef, OASE, CurType);
19083     bool NotUnity =
19084         checkArrayExpressionDoesNotReferToUnitySize(SemaRef, OASE, CurType);
19085 
19086     if (AllowWholeSizeArraySection) {
19087       // Any array section is currently allowed. Allowing a whole size array
19088       // section implies allowing a unity array section as well.
19089       //
19090       // If this array section refers to the whole dimension we can still
19091       // accept other array sections before this one, except if the base is a
19092       // pointer. Otherwise, only unitary sections are accepted.
19093       if (NotWhole || IsPointer)
19094         AllowWholeSizeArraySection = false;
19095     } else if (DKind == OMPD_target_update &&
19096                SemaRef.getLangOpts().OpenMP >= 50) {
19097       if (IsPointer && !AllowAnotherPtr)
19098         SemaRef.Diag(ELoc, diag::err_omp_section_length_undefined)
19099             << /*array of unknown bound */ 1;
19100       else
19101         IsNonContiguous = true;
19102     } else if (AllowUnitySizeArraySection && NotUnity) {
19103       // A unity or whole array section is not allowed and that is not
19104       // compatible with the properties of the current array section.
19105       if (NoDiagnose)
19106         return false;
19107       SemaRef.Diag(ELoc,
19108                    diag::err_array_section_does_not_specify_contiguous_storage)
19109           << OASE->getSourceRange();
19110       return false;
19111     }
19112 
19113     if (IsPointer)
19114       AllowAnotherPtr = false;
19115 
19116     if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
19117       Expr::EvalResult ResultR;
19118       Expr::EvalResult ResultL;
19119       if (!OASE->getLength()->isValueDependent() &&
19120           OASE->getLength()->EvaluateAsInt(ResultR, SemaRef.getASTContext()) &&
19121           !ResultR.Val.getInt().isOne()) {
19122         SemaRef.Diag(OASE->getLength()->getExprLoc(),
19123                      diag::err_omp_invalid_map_this_expr);
19124         SemaRef.Diag(OASE->getLength()->getExprLoc(),
19125                      diag::note_omp_invalid_length_on_this_ptr_mapping);
19126       }
19127       if (OASE->getLowerBound() && !OASE->getLowerBound()->isValueDependent() &&
19128           OASE->getLowerBound()->EvaluateAsInt(ResultL,
19129                                                SemaRef.getASTContext()) &&
19130           !ResultL.Val.getInt().isZero()) {
19131         SemaRef.Diag(OASE->getLowerBound()->getExprLoc(),
19132                      diag::err_omp_invalid_map_this_expr);
19133         SemaRef.Diag(OASE->getLowerBound()->getExprLoc(),
19134                      diag::note_omp_invalid_lower_bound_on_this_ptr_mapping);
19135       }
19136       assert(!RelevantExpr && "RelevantExpr is expected to be nullptr");
19137       RelevantExpr = TE;
19138     }
19139 
19140     // Record the component - we don't have any declaration associated.
19141     Components.emplace_back(OASE, nullptr, /*IsNonContiguous=*/false);
19142     return RelevantExpr || Visit(E);
19143   }
19144   bool VisitOMPArrayShapingExpr(OMPArrayShapingExpr *E) {
19145     Expr *Base = E->getBase();
19146 
19147     // Record the component - we don't have any declaration associated.
19148     Components.emplace_back(E, nullptr, IsNonContiguous);
19149 
19150     return Visit(Base->IgnoreParenImpCasts());
19151   }
19152 
19153   bool VisitUnaryOperator(UnaryOperator *UO) {
19154     if (SemaRef.getLangOpts().OpenMP < 50 || !UO->isLValue() ||
19155         UO->getOpcode() != UO_Deref) {
19156       emitErrorMsg();
19157       return false;
19158     }
19159     if (!RelevantExpr) {
19160       // Record the component if haven't found base decl.
19161       Components.emplace_back(UO, nullptr, /*IsNonContiguous=*/false);
19162     }
19163     return RelevantExpr || Visit(UO->getSubExpr()->IgnoreParenImpCasts());
19164   }
19165   bool VisitBinaryOperator(BinaryOperator *BO) {
19166     if (SemaRef.getLangOpts().OpenMP < 50 || !BO->getType()->isPointerType()) {
19167       emitErrorMsg();
19168       return false;
19169     }
19170 
19171     // Pointer arithmetic is the only thing we expect to happen here so after we
19172     // make sure the binary operator is a pointer type, the we only thing need
19173     // to to is to visit the subtree that has the same type as root (so that we
19174     // know the other subtree is just an offset)
19175     Expr *LE = BO->getLHS()->IgnoreParenImpCasts();
19176     Expr *RE = BO->getRHS()->IgnoreParenImpCasts();
19177     Components.emplace_back(BO, nullptr, false);
19178     assert((LE->getType().getTypePtr() == BO->getType().getTypePtr() ||
19179             RE->getType().getTypePtr() == BO->getType().getTypePtr()) &&
19180            "Either LHS or RHS have base decl inside");
19181     if (BO->getType().getTypePtr() == LE->getType().getTypePtr())
19182       return RelevantExpr || Visit(LE);
19183     return RelevantExpr || Visit(RE);
19184   }
19185   bool VisitCXXThisExpr(CXXThisExpr *CTE) {
19186     assert(!RelevantExpr && "RelevantExpr is expected to be nullptr");
19187     RelevantExpr = CTE;
19188     Components.emplace_back(CTE, nullptr, IsNonContiguous);
19189     return true;
19190   }
19191   bool VisitCXXOperatorCallExpr(CXXOperatorCallExpr *COCE) {
19192     assert(!RelevantExpr && "RelevantExpr is expected to be nullptr");
19193     Components.emplace_back(COCE, nullptr, IsNonContiguous);
19194     return true;
19195   }
19196   bool VisitOpaqueValueExpr(OpaqueValueExpr *E) {
19197     Expr *Source = E->getSourceExpr();
19198     if (!Source) {
19199       emitErrorMsg();
19200       return false;
19201     }
19202     return Visit(Source);
19203   }
19204   bool VisitStmt(Stmt *) {
19205     emitErrorMsg();
19206     return false;
19207   }
19208   const Expr *getFoundBase() const { return RelevantExpr; }
19209   explicit MapBaseChecker(
19210       Sema &SemaRef, OpenMPClauseKind CKind, OpenMPDirectiveKind DKind,
19211       OMPClauseMappableExprCommon::MappableExprComponentList &Components,
19212       bool NoDiagnose, SourceLocation &ELoc, SourceRange &ERange)
19213       : SemaRef(SemaRef), CKind(CKind), DKind(DKind), Components(Components),
19214         NoDiagnose(NoDiagnose), ELoc(ELoc), ERange(ERange) {}
19215 };
19216 } // namespace
19217 
19218 /// Return the expression of the base of the mappable expression or null if it
19219 /// cannot be determined and do all the necessary checks to see if the
19220 /// expression is valid as a standalone mappable expression. In the process,
19221 /// record all the components of the expression.
19222 static const Expr *checkMapClauseExpressionBase(
19223     Sema &SemaRef, Expr *E,
19224     OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
19225     OpenMPClauseKind CKind, OpenMPDirectiveKind DKind, bool NoDiagnose) {
19226   SourceLocation ELoc = E->getExprLoc();
19227   SourceRange ERange = E->getSourceRange();
19228   MapBaseChecker Checker(SemaRef, CKind, DKind, CurComponents, NoDiagnose, ELoc,
19229                          ERange);
19230   if (Checker.Visit(E->IgnoreParens())) {
19231     // Check if the highest dimension array section has length specified
19232     if (SemaRef.getLangOpts().OpenMP >= 50 && !CurComponents.empty() &&
19233         (CKind == OMPC_to || CKind == OMPC_from)) {
19234       auto CI = CurComponents.rbegin();
19235       auto CE = CurComponents.rend();
19236       for (; CI != CE; ++CI) {
19237         const auto *OASE =
19238             dyn_cast<OMPArraySectionExpr>(CI->getAssociatedExpression());
19239         if (!OASE)
19240           continue;
19241         if (OASE && OASE->getLength())
19242           break;
19243         SemaRef.Diag(ELoc, diag::err_array_section_does_not_specify_length)
19244             << ERange;
19245       }
19246     }
19247     return Checker.getFoundBase();
19248   }
19249   return nullptr;
19250 }
19251 
19252 // Return true if expression E associated with value VD has conflicts with other
19253 // map information.
19254 static bool checkMapConflicts(
19255     Sema &SemaRef, DSAStackTy *DSAS, const ValueDecl *VD, const Expr *E,
19256     bool CurrentRegionOnly,
19257     OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
19258     OpenMPClauseKind CKind) {
19259   assert(VD && E);
19260   SourceLocation ELoc = E->getExprLoc();
19261   SourceRange ERange = E->getSourceRange();
19262 
19263   // In order to easily check the conflicts we need to match each component of
19264   // the expression under test with the components of the expressions that are
19265   // already in the stack.
19266 
19267   assert(!CurComponents.empty() && "Map clause expression with no components!");
19268   assert(CurComponents.back().getAssociatedDeclaration() == VD &&
19269          "Map clause expression with unexpected base!");
19270 
19271   // Variables to help detecting enclosing problems in data environment nests.
19272   bool IsEnclosedByDataEnvironmentExpr = false;
19273   const Expr *EnclosingExpr = nullptr;
19274 
19275   bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
19276       VD, CurrentRegionOnly,
19277       [&IsEnclosedByDataEnvironmentExpr, &SemaRef, VD, CurrentRegionOnly, ELoc,
19278        ERange, CKind, &EnclosingExpr,
19279        CurComponents](OMPClauseMappableExprCommon::MappableExprComponentListRef
19280                           StackComponents,
19281                       OpenMPClauseKind Kind) {
19282         if (CKind == Kind && SemaRef.LangOpts.OpenMP >= 50)
19283           return false;
19284         assert(!StackComponents.empty() &&
19285                "Map clause expression with no components!");
19286         assert(StackComponents.back().getAssociatedDeclaration() == VD &&
19287                "Map clause expression with unexpected base!");
19288         (void)VD;
19289 
19290         // The whole expression in the stack.
19291         const Expr *RE = StackComponents.front().getAssociatedExpression();
19292 
19293         // Expressions must start from the same base. Here we detect at which
19294         // point both expressions diverge from each other and see if we can
19295         // detect if the memory referred to both expressions is contiguous and
19296         // do not overlap.
19297         auto CI = CurComponents.rbegin();
19298         auto CE = CurComponents.rend();
19299         auto SI = StackComponents.rbegin();
19300         auto SE = StackComponents.rend();
19301         for (; CI != CE && SI != SE; ++CI, ++SI) {
19302 
19303           // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
19304           //  At most one list item can be an array item derived from a given
19305           //  variable in map clauses of the same construct.
19306           if (CurrentRegionOnly &&
19307               (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
19308                isa<OMPArraySectionExpr>(CI->getAssociatedExpression()) ||
19309                isa<OMPArrayShapingExpr>(CI->getAssociatedExpression())) &&
19310               (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
19311                isa<OMPArraySectionExpr>(SI->getAssociatedExpression()) ||
19312                isa<OMPArrayShapingExpr>(SI->getAssociatedExpression()))) {
19313             SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
19314                          diag::err_omp_multiple_array_items_in_map_clause)
19315                 << CI->getAssociatedExpression()->getSourceRange();
19316             SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
19317                          diag::note_used_here)
19318                 << SI->getAssociatedExpression()->getSourceRange();
19319             return true;
19320           }
19321 
19322           // Do both expressions have the same kind?
19323           if (CI->getAssociatedExpression()->getStmtClass() !=
19324               SI->getAssociatedExpression()->getStmtClass())
19325             break;
19326 
19327           // Are we dealing with different variables/fields?
19328           if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
19329             break;
19330         }
19331         // Check if the extra components of the expressions in the enclosing
19332         // data environment are redundant for the current base declaration.
19333         // If they are, the maps completely overlap, which is legal.
19334         for (; SI != SE; ++SI) {
19335           QualType Type;
19336           if (const auto *ASE =
19337                   dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
19338             Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
19339           } else if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(
19340                          SI->getAssociatedExpression())) {
19341             const Expr *E = OASE->getBase()->IgnoreParenImpCasts();
19342             Type =
19343                 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
19344           } else if (const auto *OASE = dyn_cast<OMPArrayShapingExpr>(
19345                          SI->getAssociatedExpression())) {
19346             Type = OASE->getBase()->getType()->getPointeeType();
19347           }
19348           if (Type.isNull() || Type->isAnyPointerType() ||
19349               checkArrayExpressionDoesNotReferToWholeSize(
19350                   SemaRef, SI->getAssociatedExpression(), Type))
19351             break;
19352         }
19353 
19354         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
19355         //  List items of map clauses in the same construct must not share
19356         //  original storage.
19357         //
19358         // If the expressions are exactly the same or one is a subset of the
19359         // other, it means they are sharing storage.
19360         if (CI == CE && SI == SE) {
19361           if (CurrentRegionOnly) {
19362             if (CKind == OMPC_map) {
19363               SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
19364             } else {
19365               assert(CKind == OMPC_to || CKind == OMPC_from);
19366               SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
19367                   << ERange;
19368             }
19369             SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
19370                 << RE->getSourceRange();
19371             return true;
19372           }
19373           // If we find the same expression in the enclosing data environment,
19374           // that is legal.
19375           IsEnclosedByDataEnvironmentExpr = true;
19376           return false;
19377         }
19378 
19379         QualType DerivedType =
19380             std::prev(CI)->getAssociatedDeclaration()->getType();
19381         SourceLocation DerivedLoc =
19382             std::prev(CI)->getAssociatedExpression()->getExprLoc();
19383 
19384         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
19385         //  If the type of a list item is a reference to a type T then the type
19386         //  will be considered to be T for all purposes of this clause.
19387         DerivedType = DerivedType.getNonReferenceType();
19388 
19389         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
19390         //  A variable for which the type is pointer and an array section
19391         //  derived from that variable must not appear as list items of map
19392         //  clauses of the same construct.
19393         //
19394         // Also, cover one of the cases in:
19395         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
19396         //  If any part of the original storage of a list item has corresponding
19397         //  storage in the device data environment, all of the original storage
19398         //  must have corresponding storage in the device data environment.
19399         //
19400         if (DerivedType->isAnyPointerType()) {
19401           if (CI == CE || SI == SE) {
19402             SemaRef.Diag(
19403                 DerivedLoc,
19404                 diag::err_omp_pointer_mapped_along_with_derived_section)
19405                 << DerivedLoc;
19406             SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
19407                 << RE->getSourceRange();
19408             return true;
19409           }
19410           if (CI->getAssociatedExpression()->getStmtClass() !=
19411                   SI->getAssociatedExpression()->getStmtClass() ||
19412               CI->getAssociatedDeclaration()->getCanonicalDecl() ==
19413                   SI->getAssociatedDeclaration()->getCanonicalDecl()) {
19414             assert(CI != CE && SI != SE);
19415             SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_dereferenced)
19416                 << DerivedLoc;
19417             SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
19418                 << RE->getSourceRange();
19419             return true;
19420           }
19421         }
19422 
19423         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
19424         //  List items of map clauses in the same construct must not share
19425         //  original storage.
19426         //
19427         // An expression is a subset of the other.
19428         if (CurrentRegionOnly && (CI == CE || SI == SE)) {
19429           if (CKind == OMPC_map) {
19430             if (CI != CE || SI != SE) {
19431               // Allow constructs like this: map(s, s.ptr[0:1]), where s.ptr is
19432               // a pointer.
19433               auto Begin =
19434                   CI != CE ? CurComponents.begin() : StackComponents.begin();
19435               auto End = CI != CE ? CurComponents.end() : StackComponents.end();
19436               auto It = Begin;
19437               while (It != End && !It->getAssociatedDeclaration())
19438                 std::advance(It, 1);
19439               assert(It != End &&
19440                      "Expected at least one component with the declaration.");
19441               if (It != Begin && It->getAssociatedDeclaration()
19442                                      ->getType()
19443                                      .getCanonicalType()
19444                                      ->isAnyPointerType()) {
19445                 IsEnclosedByDataEnvironmentExpr = false;
19446                 EnclosingExpr = nullptr;
19447                 return false;
19448               }
19449             }
19450             SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
19451           } else {
19452             assert(CKind == OMPC_to || CKind == OMPC_from);
19453             SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
19454                 << ERange;
19455           }
19456           SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
19457               << RE->getSourceRange();
19458           return true;
19459         }
19460 
19461         // The current expression uses the same base as other expression in the
19462         // data environment but does not contain it completely.
19463         if (!CurrentRegionOnly && SI != SE)
19464           EnclosingExpr = RE;
19465 
19466         // The current expression is a subset of the expression in the data
19467         // environment.
19468         IsEnclosedByDataEnvironmentExpr |=
19469             (!CurrentRegionOnly && CI != CE && SI == SE);
19470 
19471         return false;
19472       });
19473 
19474   if (CurrentRegionOnly)
19475     return FoundError;
19476 
19477   // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
19478   //  If any part of the original storage of a list item has corresponding
19479   //  storage in the device data environment, all of the original storage must
19480   //  have corresponding storage in the device data environment.
19481   // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
19482   //  If a list item is an element of a structure, and a different element of
19483   //  the structure has a corresponding list item in the device data environment
19484   //  prior to a task encountering the construct associated with the map clause,
19485   //  then the list item must also have a corresponding list item in the device
19486   //  data environment prior to the task encountering the construct.
19487   //
19488   if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
19489     SemaRef.Diag(ELoc,
19490                  diag::err_omp_original_storage_is_shared_and_does_not_contain)
19491         << ERange;
19492     SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
19493         << EnclosingExpr->getSourceRange();
19494     return true;
19495   }
19496 
19497   return FoundError;
19498 }
19499 
19500 // Look up the user-defined mapper given the mapper name and mapped type, and
19501 // build a reference to it.
19502 static ExprResult buildUserDefinedMapperRef(Sema &SemaRef, Scope *S,
19503                                             CXXScopeSpec &MapperIdScopeSpec,
19504                                             const DeclarationNameInfo &MapperId,
19505                                             QualType Type,
19506                                             Expr *UnresolvedMapper) {
19507   if (MapperIdScopeSpec.isInvalid())
19508     return ExprError();
19509   // Get the actual type for the array type.
19510   if (Type->isArrayType()) {
19511     assert(Type->getAsArrayTypeUnsafe() && "Expect to get a valid array type");
19512     Type = Type->getAsArrayTypeUnsafe()->getElementType().getCanonicalType();
19513   }
19514   // Find all user-defined mappers with the given MapperId.
19515   SmallVector<UnresolvedSet<8>, 4> Lookups;
19516   LookupResult Lookup(SemaRef, MapperId, Sema::LookupOMPMapperName);
19517   Lookup.suppressDiagnostics();
19518   if (S) {
19519     while (S && SemaRef.LookupParsedName(Lookup, S, &MapperIdScopeSpec)) {
19520       NamedDecl *D = Lookup.getRepresentativeDecl();
19521       while (S && !S->isDeclScope(D))
19522         S = S->getParent();
19523       if (S)
19524         S = S->getParent();
19525       Lookups.emplace_back();
19526       Lookups.back().append(Lookup.begin(), Lookup.end());
19527       Lookup.clear();
19528     }
19529   } else if (auto *ULE = cast_or_null<UnresolvedLookupExpr>(UnresolvedMapper)) {
19530     // Extract the user-defined mappers with the given MapperId.
19531     Lookups.push_back(UnresolvedSet<8>());
19532     for (NamedDecl *D : ULE->decls()) {
19533       auto *DMD = cast<OMPDeclareMapperDecl>(D);
19534       assert(DMD && "Expect valid OMPDeclareMapperDecl during instantiation.");
19535       Lookups.back().addDecl(DMD);
19536     }
19537   }
19538   // Defer the lookup for dependent types. The results will be passed through
19539   // UnresolvedMapper on instantiation.
19540   if (SemaRef.CurContext->isDependentContext() || Type->isDependentType() ||
19541       Type->isInstantiationDependentType() ||
19542       Type->containsUnexpandedParameterPack() ||
19543       filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
19544         return !D->isInvalidDecl() &&
19545                (D->getType()->isDependentType() ||
19546                 D->getType()->isInstantiationDependentType() ||
19547                 D->getType()->containsUnexpandedParameterPack());
19548       })) {
19549     UnresolvedSet<8> URS;
19550     for (const UnresolvedSet<8> &Set : Lookups) {
19551       if (Set.empty())
19552         continue;
19553       URS.append(Set.begin(), Set.end());
19554     }
19555     return UnresolvedLookupExpr::Create(
19556         SemaRef.Context, /*NamingClass=*/nullptr,
19557         MapperIdScopeSpec.getWithLocInContext(SemaRef.Context), MapperId,
19558         /*ADL=*/false, /*Overloaded=*/true, URS.begin(), URS.end());
19559   }
19560   SourceLocation Loc = MapperId.getLoc();
19561   // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
19562   //  The type must be of struct, union or class type in C and C++
19563   if (!Type->isStructureOrClassType() && !Type->isUnionType() &&
19564       (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default")) {
19565     SemaRef.Diag(Loc, diag::err_omp_mapper_wrong_type);
19566     return ExprError();
19567   }
19568   // Perform argument dependent lookup.
19569   if (SemaRef.getLangOpts().CPlusPlus && !MapperIdScopeSpec.isSet())
19570     argumentDependentLookup(SemaRef, MapperId, Loc, Type, Lookups);
19571   // Return the first user-defined mapper with the desired type.
19572   if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
19573           Lookups, [&SemaRef, Type](ValueDecl *D) -> ValueDecl * {
19574             if (!D->isInvalidDecl() &&
19575                 SemaRef.Context.hasSameType(D->getType(), Type))
19576               return D;
19577             return nullptr;
19578           }))
19579     return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
19580   // Find the first user-defined mapper with a type derived from the desired
19581   // type.
19582   if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
19583           Lookups, [&SemaRef, Type, Loc](ValueDecl *D) -> ValueDecl * {
19584             if (!D->isInvalidDecl() &&
19585                 SemaRef.IsDerivedFrom(Loc, Type, D->getType()) &&
19586                 !Type.isMoreQualifiedThan(D->getType()))
19587               return D;
19588             return nullptr;
19589           })) {
19590     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
19591                        /*DetectVirtual=*/false);
19592     if (SemaRef.IsDerivedFrom(Loc, Type, VD->getType(), Paths)) {
19593       if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
19594               VD->getType().getUnqualifiedType()))) {
19595         if (SemaRef.CheckBaseClassAccess(
19596                 Loc, VD->getType(), Type, Paths.front(),
19597                 /*DiagID=*/0) != Sema::AR_inaccessible) {
19598           return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
19599         }
19600       }
19601     }
19602   }
19603   // Report error if a mapper is specified, but cannot be found.
19604   if (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default") {
19605     SemaRef.Diag(Loc, diag::err_omp_invalid_mapper)
19606         << Type << MapperId.getName();
19607     return ExprError();
19608   }
19609   return ExprEmpty();
19610 }
19611 
19612 namespace {
19613 // Utility struct that gathers all the related lists associated with a mappable
19614 // expression.
19615 struct MappableVarListInfo {
19616   // The list of expressions.
19617   ArrayRef<Expr *> VarList;
19618   // The list of processed expressions.
19619   SmallVector<Expr *, 16> ProcessedVarList;
19620   // The mappble components for each expression.
19621   OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
19622   // The base declaration of the variable.
19623   SmallVector<ValueDecl *, 16> VarBaseDeclarations;
19624   // The reference to the user-defined mapper associated with every expression.
19625   SmallVector<Expr *, 16> UDMapperList;
19626 
19627   MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
19628     // We have a list of components and base declarations for each entry in the
19629     // variable list.
19630     VarComponents.reserve(VarList.size());
19631     VarBaseDeclarations.reserve(VarList.size());
19632   }
19633 };
19634 } // namespace
19635 
19636 // Check the validity of the provided variable list for the provided clause kind
19637 // \a CKind. In the check process the valid expressions, mappable expression
19638 // components, variables, and user-defined mappers are extracted and used to
19639 // fill \a ProcessedVarList, \a VarComponents, \a VarBaseDeclarations, and \a
19640 // UDMapperList in MVLI. \a MapType, \a IsMapTypeImplicit, \a MapperIdScopeSpec,
19641 // and \a MapperId are expected to be valid if the clause kind is 'map'.
19642 static void checkMappableExpressionList(
19643     Sema &SemaRef, DSAStackTy *DSAS, OpenMPClauseKind CKind,
19644     MappableVarListInfo &MVLI, SourceLocation StartLoc,
19645     CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo MapperId,
19646     ArrayRef<Expr *> UnresolvedMappers,
19647     OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
19648     ArrayRef<OpenMPMapModifierKind> Modifiers = None,
19649     bool IsMapTypeImplicit = false, bool NoDiagnose = false) {
19650   // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
19651   assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
19652          "Unexpected clause kind with mappable expressions!");
19653 
19654   // If the identifier of user-defined mapper is not specified, it is "default".
19655   // We do not change the actual name in this clause to distinguish whether a
19656   // mapper is specified explicitly, i.e., it is not explicitly specified when
19657   // MapperId.getName() is empty.
19658   if (!MapperId.getName() || MapperId.getName().isEmpty()) {
19659     auto &DeclNames = SemaRef.getASTContext().DeclarationNames;
19660     MapperId.setName(DeclNames.getIdentifier(
19661         &SemaRef.getASTContext().Idents.get("default")));
19662     MapperId.setLoc(StartLoc);
19663   }
19664 
19665   // Iterators to find the current unresolved mapper expression.
19666   auto UMIt = UnresolvedMappers.begin(), UMEnd = UnresolvedMappers.end();
19667   bool UpdateUMIt = false;
19668   Expr *UnresolvedMapper = nullptr;
19669 
19670   bool HasHoldModifier =
19671       llvm::is_contained(Modifiers, OMPC_MAP_MODIFIER_ompx_hold);
19672 
19673   // Keep track of the mappable components and base declarations in this clause.
19674   // Each entry in the list is going to have a list of components associated. We
19675   // record each set of the components so that we can build the clause later on.
19676   // In the end we should have the same amount of declarations and component
19677   // lists.
19678 
19679   for (Expr *RE : MVLI.VarList) {
19680     assert(RE && "Null expr in omp to/from/map clause");
19681     SourceLocation ELoc = RE->getExprLoc();
19682 
19683     // Find the current unresolved mapper expression.
19684     if (UpdateUMIt && UMIt != UMEnd) {
19685       UMIt++;
19686       assert(
19687           UMIt != UMEnd &&
19688           "Expect the size of UnresolvedMappers to match with that of VarList");
19689     }
19690     UpdateUMIt = true;
19691     if (UMIt != UMEnd)
19692       UnresolvedMapper = *UMIt;
19693 
19694     const Expr *VE = RE->IgnoreParenLValueCasts();
19695 
19696     if (VE->isValueDependent() || VE->isTypeDependent() ||
19697         VE->isInstantiationDependent() ||
19698         VE->containsUnexpandedParameterPack()) {
19699       // Try to find the associated user-defined mapper.
19700       ExprResult ER = buildUserDefinedMapperRef(
19701           SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
19702           VE->getType().getCanonicalType(), UnresolvedMapper);
19703       if (ER.isInvalid())
19704         continue;
19705       MVLI.UDMapperList.push_back(ER.get());
19706       // We can only analyze this information once the missing information is
19707       // resolved.
19708       MVLI.ProcessedVarList.push_back(RE);
19709       continue;
19710     }
19711 
19712     Expr *SimpleExpr = RE->IgnoreParenCasts();
19713 
19714     if (!RE->isLValue()) {
19715       if (SemaRef.getLangOpts().OpenMP < 50) {
19716         SemaRef.Diag(
19717             ELoc, diag::err_omp_expected_named_var_member_or_array_expression)
19718             << RE->getSourceRange();
19719       } else {
19720         SemaRef.Diag(ELoc, diag::err_omp_non_lvalue_in_map_or_motion_clauses)
19721             << getOpenMPClauseName(CKind) << RE->getSourceRange();
19722       }
19723       continue;
19724     }
19725 
19726     OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
19727     ValueDecl *CurDeclaration = nullptr;
19728 
19729     // Obtain the array or member expression bases if required. Also, fill the
19730     // components array with all the components identified in the process.
19731     const Expr *BE =
19732         checkMapClauseExpressionBase(SemaRef, SimpleExpr, CurComponents, CKind,
19733                                      DSAS->getCurrentDirective(), NoDiagnose);
19734     if (!BE)
19735       continue;
19736 
19737     assert(!CurComponents.empty() &&
19738            "Invalid mappable expression information.");
19739 
19740     if (const auto *TE = dyn_cast<CXXThisExpr>(BE)) {
19741       // Add store "this" pointer to class in DSAStackTy for future checking
19742       DSAS->addMappedClassesQualTypes(TE->getType());
19743       // Try to find the associated user-defined mapper.
19744       ExprResult ER = buildUserDefinedMapperRef(
19745           SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
19746           VE->getType().getCanonicalType(), UnresolvedMapper);
19747       if (ER.isInvalid())
19748         continue;
19749       MVLI.UDMapperList.push_back(ER.get());
19750       // Skip restriction checking for variable or field declarations
19751       MVLI.ProcessedVarList.push_back(RE);
19752       MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
19753       MVLI.VarComponents.back().append(CurComponents.begin(),
19754                                        CurComponents.end());
19755       MVLI.VarBaseDeclarations.push_back(nullptr);
19756       continue;
19757     }
19758 
19759     // For the following checks, we rely on the base declaration which is
19760     // expected to be associated with the last component. The declaration is
19761     // expected to be a variable or a field (if 'this' is being mapped).
19762     CurDeclaration = CurComponents.back().getAssociatedDeclaration();
19763     assert(CurDeclaration && "Null decl on map clause.");
19764     assert(
19765         CurDeclaration->isCanonicalDecl() &&
19766         "Expecting components to have associated only canonical declarations.");
19767 
19768     auto *VD = dyn_cast<VarDecl>(CurDeclaration);
19769     const auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
19770 
19771     assert((VD || FD) && "Only variables or fields are expected here!");
19772     (void)FD;
19773 
19774     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
19775     // threadprivate variables cannot appear in a map clause.
19776     // OpenMP 4.5 [2.10.5, target update Construct]
19777     // threadprivate variables cannot appear in a from clause.
19778     if (VD && DSAS->isThreadPrivate(VD)) {
19779       if (NoDiagnose)
19780         continue;
19781       DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
19782       SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
19783           << getOpenMPClauseName(CKind);
19784       reportOriginalDsa(SemaRef, DSAS, VD, DVar);
19785       continue;
19786     }
19787 
19788     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
19789     //  A list item cannot appear in both a map clause and a data-sharing
19790     //  attribute clause on the same construct.
19791 
19792     // Check conflicts with other map clause expressions. We check the conflicts
19793     // with the current construct separately from the enclosing data
19794     // environment, because the restrictions are different. We only have to
19795     // check conflicts across regions for the map clauses.
19796     if (checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
19797                           /*CurrentRegionOnly=*/true, CurComponents, CKind))
19798       break;
19799     if (CKind == OMPC_map &&
19800         (SemaRef.getLangOpts().OpenMP <= 45 || StartLoc.isValid()) &&
19801         checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
19802                           /*CurrentRegionOnly=*/false, CurComponents, CKind))
19803       break;
19804 
19805     // OpenMP 4.5 [2.10.5, target update Construct]
19806     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
19807     //  If the type of a list item is a reference to a type T then the type will
19808     //  be considered to be T for all purposes of this clause.
19809     auto I = llvm::find_if(
19810         CurComponents,
19811         [](const OMPClauseMappableExprCommon::MappableComponent &MC) {
19812           return MC.getAssociatedDeclaration();
19813         });
19814     assert(I != CurComponents.end() && "Null decl on map clause.");
19815     (void)I;
19816     QualType Type;
19817     auto *ASE = dyn_cast<ArraySubscriptExpr>(VE->IgnoreParens());
19818     auto *OASE = dyn_cast<OMPArraySectionExpr>(VE->IgnoreParens());
19819     auto *OAShE = dyn_cast<OMPArrayShapingExpr>(VE->IgnoreParens());
19820     if (ASE) {
19821       Type = ASE->getType().getNonReferenceType();
19822     } else if (OASE) {
19823       QualType BaseType =
19824           OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
19825       if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
19826         Type = ATy->getElementType();
19827       else
19828         Type = BaseType->getPointeeType();
19829       Type = Type.getNonReferenceType();
19830     } else if (OAShE) {
19831       Type = OAShE->getBase()->getType()->getPointeeType();
19832     } else {
19833       Type = VE->getType();
19834     }
19835 
19836     // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
19837     // A list item in a to or from clause must have a mappable type.
19838     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
19839     //  A list item must have a mappable type.
19840     if (!checkTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
19841                            DSAS, Type, /*FullCheck=*/true))
19842       continue;
19843 
19844     if (CKind == OMPC_map) {
19845       // target enter data
19846       // OpenMP [2.10.2, Restrictions, p. 99]
19847       // A map-type must be specified in all map clauses and must be either
19848       // to or alloc.
19849       OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
19850       if (DKind == OMPD_target_enter_data &&
19851           !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
19852         SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
19853             << (IsMapTypeImplicit ? 1 : 0)
19854             << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
19855             << getOpenMPDirectiveName(DKind);
19856         continue;
19857       }
19858 
19859       // target exit_data
19860       // OpenMP [2.10.3, Restrictions, p. 102]
19861       // A map-type must be specified in all map clauses and must be either
19862       // from, release, or delete.
19863       if (DKind == OMPD_target_exit_data &&
19864           !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
19865             MapType == OMPC_MAP_delete)) {
19866         SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
19867             << (IsMapTypeImplicit ? 1 : 0)
19868             << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
19869             << getOpenMPDirectiveName(DKind);
19870         continue;
19871       }
19872 
19873       // The 'ompx_hold' modifier is specifically intended to be used on a
19874       // 'target' or 'target data' directive to prevent data from being unmapped
19875       // during the associated statement.  It is not permitted on a 'target
19876       // enter data' or 'target exit data' directive, which have no associated
19877       // statement.
19878       if ((DKind == OMPD_target_enter_data || DKind == OMPD_target_exit_data) &&
19879           HasHoldModifier) {
19880         SemaRef.Diag(StartLoc,
19881                      diag::err_omp_invalid_map_type_modifier_for_directive)
19882             << getOpenMPSimpleClauseTypeName(OMPC_map,
19883                                              OMPC_MAP_MODIFIER_ompx_hold)
19884             << getOpenMPDirectiveName(DKind);
19885         continue;
19886       }
19887 
19888       // target, target data
19889       // OpenMP 5.0 [2.12.2, Restrictions, p. 163]
19890       // OpenMP 5.0 [2.12.5, Restrictions, p. 174]
19891       // A map-type in a map clause must be to, from, tofrom or alloc
19892       if ((DKind == OMPD_target_data ||
19893            isOpenMPTargetExecutionDirective(DKind)) &&
19894           !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_from ||
19895             MapType == OMPC_MAP_tofrom || MapType == OMPC_MAP_alloc)) {
19896         SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
19897             << (IsMapTypeImplicit ? 1 : 0)
19898             << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
19899             << getOpenMPDirectiveName(DKind);
19900         continue;
19901       }
19902 
19903       // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
19904       // A list item cannot appear in both a map clause and a data-sharing
19905       // attribute clause on the same construct
19906       //
19907       // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
19908       // A list item cannot appear in both a map clause and a data-sharing
19909       // attribute clause on the same construct unless the construct is a
19910       // combined construct.
19911       if (VD && ((SemaRef.LangOpts.OpenMP <= 45 &&
19912                   isOpenMPTargetExecutionDirective(DKind)) ||
19913                  DKind == OMPD_target)) {
19914         DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
19915         if (isOpenMPPrivate(DVar.CKind)) {
19916           SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
19917               << getOpenMPClauseName(DVar.CKind)
19918               << getOpenMPClauseName(OMPC_map)
19919               << getOpenMPDirectiveName(DSAS->getCurrentDirective());
19920           reportOriginalDsa(SemaRef, DSAS, CurDeclaration, DVar);
19921           continue;
19922         }
19923       }
19924     }
19925 
19926     // Try to find the associated user-defined mapper.
19927     ExprResult ER = buildUserDefinedMapperRef(
19928         SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
19929         Type.getCanonicalType(), UnresolvedMapper);
19930     if (ER.isInvalid())
19931       continue;
19932     MVLI.UDMapperList.push_back(ER.get());
19933 
19934     // Save the current expression.
19935     MVLI.ProcessedVarList.push_back(RE);
19936 
19937     // Store the components in the stack so that they can be used to check
19938     // against other clauses later on.
19939     DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
19940                                           /*WhereFoundClauseKind=*/OMPC_map);
19941 
19942     // Save the components and declaration to create the clause. For purposes of
19943     // the clause creation, any component list that has has base 'this' uses
19944     // null as base declaration.
19945     MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
19946     MVLI.VarComponents.back().append(CurComponents.begin(),
19947                                      CurComponents.end());
19948     MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
19949                                                            : CurDeclaration);
19950   }
19951 }
19952 
19953 OMPClause *Sema::ActOnOpenMPMapClause(
19954     ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
19955     ArrayRef<SourceLocation> MapTypeModifiersLoc,
19956     CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId,
19957     OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, SourceLocation MapLoc,
19958     SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
19959     const OMPVarListLocTy &Locs, bool NoDiagnose,
19960     ArrayRef<Expr *> UnresolvedMappers) {
19961   OpenMPMapModifierKind Modifiers[] = {
19962       OMPC_MAP_MODIFIER_unknown, OMPC_MAP_MODIFIER_unknown,
19963       OMPC_MAP_MODIFIER_unknown, OMPC_MAP_MODIFIER_unknown,
19964       OMPC_MAP_MODIFIER_unknown};
19965   SourceLocation ModifiersLoc[NumberOfOMPMapClauseModifiers];
19966 
19967   // Process map-type-modifiers, flag errors for duplicate modifiers.
19968   unsigned Count = 0;
19969   for (unsigned I = 0, E = MapTypeModifiers.size(); I < E; ++I) {
19970     if (MapTypeModifiers[I] != OMPC_MAP_MODIFIER_unknown &&
19971         llvm::is_contained(Modifiers, MapTypeModifiers[I])) {
19972       Diag(MapTypeModifiersLoc[I], diag::err_omp_duplicate_map_type_modifier);
19973       continue;
19974     }
19975     assert(Count < NumberOfOMPMapClauseModifiers &&
19976            "Modifiers exceed the allowed number of map type modifiers");
19977     Modifiers[Count] = MapTypeModifiers[I];
19978     ModifiersLoc[Count] = MapTypeModifiersLoc[I];
19979     ++Count;
19980   }
19981 
19982   MappableVarListInfo MVLI(VarList);
19983   checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, Locs.StartLoc,
19984                               MapperIdScopeSpec, MapperId, UnresolvedMappers,
19985                               MapType, Modifiers, IsMapTypeImplicit,
19986                               NoDiagnose);
19987 
19988   // We need to produce a map clause even if we don't have variables so that
19989   // other diagnostics related with non-existing map clauses are accurate.
19990   return OMPMapClause::Create(Context, Locs, MVLI.ProcessedVarList,
19991                               MVLI.VarBaseDeclarations, MVLI.VarComponents,
19992                               MVLI.UDMapperList, Modifiers, ModifiersLoc,
19993                               MapperIdScopeSpec.getWithLocInContext(Context),
19994                               MapperId, MapType, IsMapTypeImplicit, MapLoc);
19995 }
19996 
19997 QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
19998                                                TypeResult ParsedType) {
19999   assert(ParsedType.isUsable());
20000 
20001   QualType ReductionType = GetTypeFromParser(ParsedType.get());
20002   if (ReductionType.isNull())
20003     return QualType();
20004 
20005   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
20006   // A type name in a declare reduction directive cannot be a function type, an
20007   // array type, a reference type, or a type qualified with const, volatile or
20008   // restrict.
20009   if (ReductionType.hasQualifiers()) {
20010     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
20011     return QualType();
20012   }
20013 
20014   if (ReductionType->isFunctionType()) {
20015     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
20016     return QualType();
20017   }
20018   if (ReductionType->isReferenceType()) {
20019     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
20020     return QualType();
20021   }
20022   if (ReductionType->isArrayType()) {
20023     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
20024     return QualType();
20025   }
20026   return ReductionType;
20027 }
20028 
20029 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
20030     Scope *S, DeclContext *DC, DeclarationName Name,
20031     ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
20032     AccessSpecifier AS, Decl *PrevDeclInScope) {
20033   SmallVector<Decl *, 8> Decls;
20034   Decls.reserve(ReductionTypes.size());
20035 
20036   LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
20037                       forRedeclarationInCurContext());
20038   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
20039   // A reduction-identifier may not be re-declared in the current scope for the
20040   // same type or for a type that is compatible according to the base language
20041   // rules.
20042   llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
20043   OMPDeclareReductionDecl *PrevDRD = nullptr;
20044   bool InCompoundScope = true;
20045   if (S != nullptr) {
20046     // Find previous declaration with the same name not referenced in other
20047     // declarations.
20048     FunctionScopeInfo *ParentFn = getEnclosingFunction();
20049     InCompoundScope =
20050         (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
20051     LookupName(Lookup, S);
20052     FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
20053                          /*AllowInlineNamespace=*/false);
20054     llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
20055     LookupResult::Filter Filter = Lookup.makeFilter();
20056     while (Filter.hasNext()) {
20057       auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
20058       if (InCompoundScope) {
20059         auto I = UsedAsPrevious.find(PrevDecl);
20060         if (I == UsedAsPrevious.end())
20061           UsedAsPrevious[PrevDecl] = false;
20062         if (OMPDeclareReductionDecl *D = PrevDecl->getPrevDeclInScope())
20063           UsedAsPrevious[D] = true;
20064       }
20065       PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
20066           PrevDecl->getLocation();
20067     }
20068     Filter.done();
20069     if (InCompoundScope) {
20070       for (const auto &PrevData : UsedAsPrevious) {
20071         if (!PrevData.second) {
20072           PrevDRD = PrevData.first;
20073           break;
20074         }
20075       }
20076     }
20077   } else if (PrevDeclInScope != nullptr) {
20078     auto *PrevDRDInScope = PrevDRD =
20079         cast<OMPDeclareReductionDecl>(PrevDeclInScope);
20080     do {
20081       PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
20082           PrevDRDInScope->getLocation();
20083       PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
20084     } while (PrevDRDInScope != nullptr);
20085   }
20086   for (const auto &TyData : ReductionTypes) {
20087     const auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
20088     bool Invalid = false;
20089     if (I != PreviousRedeclTypes.end()) {
20090       Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
20091           << TyData.first;
20092       Diag(I->second, diag::note_previous_definition);
20093       Invalid = true;
20094     }
20095     PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
20096     auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
20097                                                 Name, TyData.first, PrevDRD);
20098     DC->addDecl(DRD);
20099     DRD->setAccess(AS);
20100     Decls.push_back(DRD);
20101     if (Invalid)
20102       DRD->setInvalidDecl();
20103     else
20104       PrevDRD = DRD;
20105   }
20106 
20107   return DeclGroupPtrTy::make(
20108       DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
20109 }
20110 
20111 void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
20112   auto *DRD = cast<OMPDeclareReductionDecl>(D);
20113 
20114   // Enter new function scope.
20115   PushFunctionScope();
20116   setFunctionHasBranchProtectedScope();
20117   getCurFunction()->setHasOMPDeclareReductionCombiner();
20118 
20119   if (S != nullptr)
20120     PushDeclContext(S, DRD);
20121   else
20122     CurContext = DRD;
20123 
20124   PushExpressionEvaluationContext(
20125       ExpressionEvaluationContext::PotentiallyEvaluated);
20126 
20127   QualType ReductionType = DRD->getType();
20128   // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
20129   // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
20130   // uses semantics of argument handles by value, but it should be passed by
20131   // reference. C lang does not support references, so pass all parameters as
20132   // pointers.
20133   // Create 'T omp_in;' variable.
20134   VarDecl *OmpInParm =
20135       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
20136   // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
20137   // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
20138   // uses semantics of argument handles by value, but it should be passed by
20139   // reference. C lang does not support references, so pass all parameters as
20140   // pointers.
20141   // Create 'T omp_out;' variable.
20142   VarDecl *OmpOutParm =
20143       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
20144   if (S != nullptr) {
20145     PushOnScopeChains(OmpInParm, S);
20146     PushOnScopeChains(OmpOutParm, S);
20147   } else {
20148     DRD->addDecl(OmpInParm);
20149     DRD->addDecl(OmpOutParm);
20150   }
20151   Expr *InE =
20152       ::buildDeclRefExpr(*this, OmpInParm, ReductionType, D->getLocation());
20153   Expr *OutE =
20154       ::buildDeclRefExpr(*this, OmpOutParm, ReductionType, D->getLocation());
20155   DRD->setCombinerData(InE, OutE);
20156 }
20157 
20158 void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
20159   auto *DRD = cast<OMPDeclareReductionDecl>(D);
20160   DiscardCleanupsInEvaluationContext();
20161   PopExpressionEvaluationContext();
20162 
20163   PopDeclContext();
20164   PopFunctionScopeInfo();
20165 
20166   if (Combiner != nullptr)
20167     DRD->setCombiner(Combiner);
20168   else
20169     DRD->setInvalidDecl();
20170 }
20171 
20172 VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
20173   auto *DRD = cast<OMPDeclareReductionDecl>(D);
20174 
20175   // Enter new function scope.
20176   PushFunctionScope();
20177   setFunctionHasBranchProtectedScope();
20178 
20179   if (S != nullptr)
20180     PushDeclContext(S, DRD);
20181   else
20182     CurContext = DRD;
20183 
20184   PushExpressionEvaluationContext(
20185       ExpressionEvaluationContext::PotentiallyEvaluated);
20186 
20187   QualType ReductionType = DRD->getType();
20188   // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
20189   // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
20190   // uses semantics of argument handles by value, but it should be passed by
20191   // reference. C lang does not support references, so pass all parameters as
20192   // pointers.
20193   // Create 'T omp_priv;' variable.
20194   VarDecl *OmpPrivParm =
20195       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
20196   // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
20197   // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
20198   // uses semantics of argument handles by value, but it should be passed by
20199   // reference. C lang does not support references, so pass all parameters as
20200   // pointers.
20201   // Create 'T omp_orig;' variable.
20202   VarDecl *OmpOrigParm =
20203       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
20204   if (S != nullptr) {
20205     PushOnScopeChains(OmpPrivParm, S);
20206     PushOnScopeChains(OmpOrigParm, S);
20207   } else {
20208     DRD->addDecl(OmpPrivParm);
20209     DRD->addDecl(OmpOrigParm);
20210   }
20211   Expr *OrigE =
20212       ::buildDeclRefExpr(*this, OmpOrigParm, ReductionType, D->getLocation());
20213   Expr *PrivE =
20214       ::buildDeclRefExpr(*this, OmpPrivParm, ReductionType, D->getLocation());
20215   DRD->setInitializerData(OrigE, PrivE);
20216   return OmpPrivParm;
20217 }
20218 
20219 void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
20220                                                      VarDecl *OmpPrivParm) {
20221   auto *DRD = cast<OMPDeclareReductionDecl>(D);
20222   DiscardCleanupsInEvaluationContext();
20223   PopExpressionEvaluationContext();
20224 
20225   PopDeclContext();
20226   PopFunctionScopeInfo();
20227 
20228   if (Initializer != nullptr) {
20229     DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit);
20230   } else if (OmpPrivParm->hasInit()) {
20231     DRD->setInitializer(OmpPrivParm->getInit(),
20232                         OmpPrivParm->isDirectInit()
20233                             ? OMPDeclareReductionDecl::DirectInit
20234                             : OMPDeclareReductionDecl::CopyInit);
20235   } else {
20236     DRD->setInvalidDecl();
20237   }
20238 }
20239 
20240 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
20241     Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
20242   for (Decl *D : DeclReductions.get()) {
20243     if (IsValid) {
20244       if (S)
20245         PushOnScopeChains(cast<OMPDeclareReductionDecl>(D), S,
20246                           /*AddToContext=*/false);
20247     } else {
20248       D->setInvalidDecl();
20249     }
20250   }
20251   return DeclReductions;
20252 }
20253 
20254 TypeResult Sema::ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D) {
20255   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
20256   QualType T = TInfo->getType();
20257   if (D.isInvalidType())
20258     return true;
20259 
20260   if (getLangOpts().CPlusPlus) {
20261     // Check that there are no default arguments (C++ only).
20262     CheckExtraCXXDefaultArguments(D);
20263   }
20264 
20265   return CreateParsedType(T, TInfo);
20266 }
20267 
20268 QualType Sema::ActOnOpenMPDeclareMapperType(SourceLocation TyLoc,
20269                                             TypeResult ParsedType) {
20270   assert(ParsedType.isUsable() && "Expect usable parsed mapper type");
20271 
20272   QualType MapperType = GetTypeFromParser(ParsedType.get());
20273   assert(!MapperType.isNull() && "Expect valid mapper type");
20274 
20275   // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
20276   //  The type must be of struct, union or class type in C and C++
20277   if (!MapperType->isStructureOrClassType() && !MapperType->isUnionType()) {
20278     Diag(TyLoc, diag::err_omp_mapper_wrong_type);
20279     return QualType();
20280   }
20281   return MapperType;
20282 }
20283 
20284 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareMapperDirective(
20285     Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType,
20286     SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS,
20287     Expr *MapperVarRef, ArrayRef<OMPClause *> Clauses, Decl *PrevDeclInScope) {
20288   LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPMapperName,
20289                       forRedeclarationInCurContext());
20290   // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
20291   //  A mapper-identifier may not be redeclared in the current scope for the
20292   //  same type or for a type that is compatible according to the base language
20293   //  rules.
20294   llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
20295   OMPDeclareMapperDecl *PrevDMD = nullptr;
20296   bool InCompoundScope = true;
20297   if (S != nullptr) {
20298     // Find previous declaration with the same name not referenced in other
20299     // declarations.
20300     FunctionScopeInfo *ParentFn = getEnclosingFunction();
20301     InCompoundScope =
20302         (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
20303     LookupName(Lookup, S);
20304     FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
20305                          /*AllowInlineNamespace=*/false);
20306     llvm::DenseMap<OMPDeclareMapperDecl *, bool> UsedAsPrevious;
20307     LookupResult::Filter Filter = Lookup.makeFilter();
20308     while (Filter.hasNext()) {
20309       auto *PrevDecl = cast<OMPDeclareMapperDecl>(Filter.next());
20310       if (InCompoundScope) {
20311         auto I = UsedAsPrevious.find(PrevDecl);
20312         if (I == UsedAsPrevious.end())
20313           UsedAsPrevious[PrevDecl] = false;
20314         if (OMPDeclareMapperDecl *D = PrevDecl->getPrevDeclInScope())
20315           UsedAsPrevious[D] = true;
20316       }
20317       PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
20318           PrevDecl->getLocation();
20319     }
20320     Filter.done();
20321     if (InCompoundScope) {
20322       for (const auto &PrevData : UsedAsPrevious) {
20323         if (!PrevData.second) {
20324           PrevDMD = PrevData.first;
20325           break;
20326         }
20327       }
20328     }
20329   } else if (PrevDeclInScope) {
20330     auto *PrevDMDInScope = PrevDMD =
20331         cast<OMPDeclareMapperDecl>(PrevDeclInScope);
20332     do {
20333       PreviousRedeclTypes[PrevDMDInScope->getType().getCanonicalType()] =
20334           PrevDMDInScope->getLocation();
20335       PrevDMDInScope = PrevDMDInScope->getPrevDeclInScope();
20336     } while (PrevDMDInScope != nullptr);
20337   }
20338   const auto I = PreviousRedeclTypes.find(MapperType.getCanonicalType());
20339   bool Invalid = false;
20340   if (I != PreviousRedeclTypes.end()) {
20341     Diag(StartLoc, diag::err_omp_declare_mapper_redefinition)
20342         << MapperType << Name;
20343     Diag(I->second, diag::note_previous_definition);
20344     Invalid = true;
20345   }
20346   // Build expressions for implicit maps of data members with 'default'
20347   // mappers.
20348   SmallVector<OMPClause *, 4> ClausesWithImplicit(Clauses.begin(),
20349                                                   Clauses.end());
20350   if (LangOpts.OpenMP >= 50)
20351     processImplicitMapsWithDefaultMappers(*this, DSAStack, ClausesWithImplicit);
20352   auto *DMD =
20353       OMPDeclareMapperDecl::Create(Context, DC, StartLoc, Name, MapperType, VN,
20354                                    ClausesWithImplicit, PrevDMD);
20355   if (S)
20356     PushOnScopeChains(DMD, S);
20357   else
20358     DC->addDecl(DMD);
20359   DMD->setAccess(AS);
20360   if (Invalid)
20361     DMD->setInvalidDecl();
20362 
20363   auto *VD = cast<DeclRefExpr>(MapperVarRef)->getDecl();
20364   VD->setDeclContext(DMD);
20365   VD->setLexicalDeclContext(DMD);
20366   DMD->addDecl(VD);
20367   DMD->setMapperVarRef(MapperVarRef);
20368 
20369   return DeclGroupPtrTy::make(DeclGroupRef(DMD));
20370 }
20371 
20372 ExprResult
20373 Sema::ActOnOpenMPDeclareMapperDirectiveVarDecl(Scope *S, QualType MapperType,
20374                                                SourceLocation StartLoc,
20375                                                DeclarationName VN) {
20376   TypeSourceInfo *TInfo =
20377       Context.getTrivialTypeSourceInfo(MapperType, StartLoc);
20378   auto *VD = VarDecl::Create(Context, Context.getTranslationUnitDecl(),
20379                              StartLoc, StartLoc, VN.getAsIdentifierInfo(),
20380                              MapperType, TInfo, SC_None);
20381   if (S)
20382     PushOnScopeChains(VD, S, /*AddToContext=*/false);
20383   Expr *E = buildDeclRefExpr(*this, VD, MapperType, StartLoc);
20384   DSAStack->addDeclareMapperVarRef(E);
20385   return E;
20386 }
20387 
20388 bool Sema::isOpenMPDeclareMapperVarDeclAllowed(const VarDecl *VD) const {
20389   assert(LangOpts.OpenMP && "Expected OpenMP mode.");
20390   const Expr *Ref = DSAStack->getDeclareMapperVarRef();
20391   if (const auto *DRE = cast_or_null<DeclRefExpr>(Ref)) {
20392     if (VD->getCanonicalDecl() == DRE->getDecl()->getCanonicalDecl())
20393       return true;
20394     if (VD->isUsableInConstantExpressions(Context))
20395       return true;
20396     return false;
20397   }
20398   return true;
20399 }
20400 
20401 const ValueDecl *Sema::getOpenMPDeclareMapperVarName() const {
20402   assert(LangOpts.OpenMP && "Expected OpenMP mode.");
20403   return cast<DeclRefExpr>(DSAStack->getDeclareMapperVarRef())->getDecl();
20404 }
20405 
20406 OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
20407                                            SourceLocation StartLoc,
20408                                            SourceLocation LParenLoc,
20409                                            SourceLocation EndLoc) {
20410   Expr *ValExpr = NumTeams;
20411   Stmt *HelperValStmt = nullptr;
20412 
20413   // OpenMP [teams Constrcut, Restrictions]
20414   // The num_teams expression must evaluate to a positive integer value.
20415   if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
20416                                  /*StrictlyPositive=*/true))
20417     return nullptr;
20418 
20419   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
20420   OpenMPDirectiveKind CaptureRegion =
20421       getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams, LangOpts.OpenMP);
20422   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
20423     ValExpr = MakeFullExpr(ValExpr).get();
20424     llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
20425     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
20426     HelperValStmt = buildPreInits(Context, Captures);
20427   }
20428 
20429   return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
20430                                          StartLoc, LParenLoc, EndLoc);
20431 }
20432 
20433 OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
20434                                               SourceLocation StartLoc,
20435                                               SourceLocation LParenLoc,
20436                                               SourceLocation EndLoc) {
20437   Expr *ValExpr = ThreadLimit;
20438   Stmt *HelperValStmt = nullptr;
20439 
20440   // OpenMP [teams Constrcut, Restrictions]
20441   // The thread_limit expression must evaluate to a positive integer value.
20442   if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
20443                                  /*StrictlyPositive=*/true))
20444     return nullptr;
20445 
20446   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
20447   OpenMPDirectiveKind CaptureRegion = getOpenMPCaptureRegionForClause(
20448       DKind, OMPC_thread_limit, LangOpts.OpenMP);
20449   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
20450     ValExpr = MakeFullExpr(ValExpr).get();
20451     llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
20452     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
20453     HelperValStmt = buildPreInits(Context, Captures);
20454   }
20455 
20456   return new (Context) OMPThreadLimitClause(
20457       ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
20458 }
20459 
20460 OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
20461                                            SourceLocation StartLoc,
20462                                            SourceLocation LParenLoc,
20463                                            SourceLocation EndLoc) {
20464   Expr *ValExpr = Priority;
20465   Stmt *HelperValStmt = nullptr;
20466   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
20467 
20468   // OpenMP [2.9.1, task Constrcut]
20469   // The priority-value is a non-negative numerical scalar expression.
20470   if (!isNonNegativeIntegerValue(
20471           ValExpr, *this, OMPC_priority,
20472           /*StrictlyPositive=*/false, /*BuildCapture=*/true,
20473           DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt))
20474     return nullptr;
20475 
20476   return new (Context) OMPPriorityClause(ValExpr, HelperValStmt, CaptureRegion,
20477                                          StartLoc, LParenLoc, EndLoc);
20478 }
20479 
20480 OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
20481                                             SourceLocation StartLoc,
20482                                             SourceLocation LParenLoc,
20483                                             SourceLocation EndLoc) {
20484   Expr *ValExpr = Grainsize;
20485   Stmt *HelperValStmt = nullptr;
20486   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
20487 
20488   // OpenMP [2.9.2, taskloop Constrcut]
20489   // The parameter of the grainsize clause must be a positive integer
20490   // expression.
20491   if (!isNonNegativeIntegerValue(
20492           ValExpr, *this, OMPC_grainsize,
20493           /*StrictlyPositive=*/true, /*BuildCapture=*/true,
20494           DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt))
20495     return nullptr;
20496 
20497   return new (Context) OMPGrainsizeClause(ValExpr, HelperValStmt, CaptureRegion,
20498                                           StartLoc, LParenLoc, EndLoc);
20499 }
20500 
20501 OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
20502                                            SourceLocation StartLoc,
20503                                            SourceLocation LParenLoc,
20504                                            SourceLocation EndLoc) {
20505   Expr *ValExpr = NumTasks;
20506   Stmt *HelperValStmt = nullptr;
20507   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
20508 
20509   // OpenMP [2.9.2, taskloop Constrcut]
20510   // The parameter of the num_tasks clause must be a positive integer
20511   // expression.
20512   if (!isNonNegativeIntegerValue(
20513           ValExpr, *this, OMPC_num_tasks,
20514           /*StrictlyPositive=*/true, /*BuildCapture=*/true,
20515           DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt))
20516     return nullptr;
20517 
20518   return new (Context) OMPNumTasksClause(ValExpr, HelperValStmt, CaptureRegion,
20519                                          StartLoc, LParenLoc, EndLoc);
20520 }
20521 
20522 OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
20523                                        SourceLocation LParenLoc,
20524                                        SourceLocation EndLoc) {
20525   // OpenMP [2.13.2, critical construct, Description]
20526   // ... where hint-expression is an integer constant expression that evaluates
20527   // to a valid lock hint.
20528   ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
20529   if (HintExpr.isInvalid())
20530     return nullptr;
20531   return new (Context)
20532       OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
20533 }
20534 
20535 /// Tries to find omp_event_handle_t type.
20536 static bool findOMPEventHandleT(Sema &S, SourceLocation Loc,
20537                                 DSAStackTy *Stack) {
20538   QualType OMPEventHandleT = Stack->getOMPEventHandleT();
20539   if (!OMPEventHandleT.isNull())
20540     return true;
20541   IdentifierInfo *II = &S.PP.getIdentifierTable().get("omp_event_handle_t");
20542   ParsedType PT = S.getTypeName(*II, Loc, S.getCurScope());
20543   if (!PT.getAsOpaquePtr() || PT.get().isNull()) {
20544     S.Diag(Loc, diag::err_omp_implied_type_not_found) << "omp_event_handle_t";
20545     return false;
20546   }
20547   Stack->setOMPEventHandleT(PT.get());
20548   return true;
20549 }
20550 
20551 OMPClause *Sema::ActOnOpenMPDetachClause(Expr *Evt, SourceLocation StartLoc,
20552                                          SourceLocation LParenLoc,
20553                                          SourceLocation EndLoc) {
20554   if (!Evt->isValueDependent() && !Evt->isTypeDependent() &&
20555       !Evt->isInstantiationDependent() &&
20556       !Evt->containsUnexpandedParameterPack()) {
20557     if (!findOMPEventHandleT(*this, Evt->getExprLoc(), DSAStack))
20558       return nullptr;
20559     // OpenMP 5.0, 2.10.1 task Construct.
20560     // event-handle is a variable of the omp_event_handle_t type.
20561     auto *Ref = dyn_cast<DeclRefExpr>(Evt->IgnoreParenImpCasts());
20562     if (!Ref) {
20563       Diag(Evt->getExprLoc(), diag::err_omp_var_expected)
20564           << "omp_event_handle_t" << 0 << Evt->getSourceRange();
20565       return nullptr;
20566     }
20567     auto *VD = dyn_cast_or_null<VarDecl>(Ref->getDecl());
20568     if (!VD) {
20569       Diag(Evt->getExprLoc(), diag::err_omp_var_expected)
20570           << "omp_event_handle_t" << 0 << Evt->getSourceRange();
20571       return nullptr;
20572     }
20573     if (!Context.hasSameUnqualifiedType(DSAStack->getOMPEventHandleT(),
20574                                         VD->getType()) ||
20575         VD->getType().isConstant(Context)) {
20576       Diag(Evt->getExprLoc(), diag::err_omp_var_expected)
20577           << "omp_event_handle_t" << 1 << VD->getType()
20578           << Evt->getSourceRange();
20579       return nullptr;
20580     }
20581     // OpenMP 5.0, 2.10.1 task Construct
20582     // [detach clause]... The event-handle will be considered as if it was
20583     // specified on a firstprivate clause.
20584     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, /*FromParent=*/false);
20585     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
20586         DVar.RefExpr) {
20587       Diag(Evt->getExprLoc(), diag::err_omp_wrong_dsa)
20588           << getOpenMPClauseName(DVar.CKind)
20589           << getOpenMPClauseName(OMPC_firstprivate);
20590       reportOriginalDsa(*this, DSAStack, VD, DVar);
20591       return nullptr;
20592     }
20593   }
20594 
20595   return new (Context) OMPDetachClause(Evt, StartLoc, LParenLoc, EndLoc);
20596 }
20597 
20598 OMPClause *Sema::ActOnOpenMPDistScheduleClause(
20599     OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
20600     SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
20601     SourceLocation EndLoc) {
20602   if (Kind == OMPC_DIST_SCHEDULE_unknown) {
20603     std::string Values;
20604     Values += "'";
20605     Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
20606     Values += "'";
20607     Diag(KindLoc, diag::err_omp_unexpected_clause_value)
20608         << Values << getOpenMPClauseName(OMPC_dist_schedule);
20609     return nullptr;
20610   }
20611   Expr *ValExpr = ChunkSize;
20612   Stmt *HelperValStmt = nullptr;
20613   if (ChunkSize) {
20614     if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
20615         !ChunkSize->isInstantiationDependent() &&
20616         !ChunkSize->containsUnexpandedParameterPack()) {
20617       SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
20618       ExprResult Val =
20619           PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
20620       if (Val.isInvalid())
20621         return nullptr;
20622 
20623       ValExpr = Val.get();
20624 
20625       // OpenMP [2.7.1, Restrictions]
20626       //  chunk_size must be a loop invariant integer expression with a positive
20627       //  value.
20628       if (Optional<llvm::APSInt> Result =
20629               ValExpr->getIntegerConstantExpr(Context)) {
20630         if (Result->isSigned() && !Result->isStrictlyPositive()) {
20631           Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
20632               << "dist_schedule" << ChunkSize->getSourceRange();
20633           return nullptr;
20634         }
20635       } else if (getOpenMPCaptureRegionForClause(
20636                      DSAStack->getCurrentDirective(), OMPC_dist_schedule,
20637                      LangOpts.OpenMP) != OMPD_unknown &&
20638                  !CurContext->isDependentContext()) {
20639         ValExpr = MakeFullExpr(ValExpr).get();
20640         llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
20641         ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
20642         HelperValStmt = buildPreInits(Context, Captures);
20643       }
20644     }
20645   }
20646 
20647   return new (Context)
20648       OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
20649                             Kind, ValExpr, HelperValStmt);
20650 }
20651 
20652 OMPClause *Sema::ActOnOpenMPDefaultmapClause(
20653     OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
20654     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
20655     SourceLocation KindLoc, SourceLocation EndLoc) {
20656   if (getLangOpts().OpenMP < 50) {
20657     if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom ||
20658         Kind != OMPC_DEFAULTMAP_scalar) {
20659       std::string Value;
20660       SourceLocation Loc;
20661       Value += "'";
20662       if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
20663         Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
20664                                                OMPC_DEFAULTMAP_MODIFIER_tofrom);
20665         Loc = MLoc;
20666       } else {
20667         Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
20668                                                OMPC_DEFAULTMAP_scalar);
20669         Loc = KindLoc;
20670       }
20671       Value += "'";
20672       Diag(Loc, diag::err_omp_unexpected_clause_value)
20673           << Value << getOpenMPClauseName(OMPC_defaultmap);
20674       return nullptr;
20675     }
20676   } else {
20677     bool isDefaultmapModifier = (M != OMPC_DEFAULTMAP_MODIFIER_unknown);
20678     bool isDefaultmapKind = (Kind != OMPC_DEFAULTMAP_unknown) ||
20679                             (LangOpts.OpenMP >= 50 && KindLoc.isInvalid());
20680     if (!isDefaultmapKind || !isDefaultmapModifier) {
20681       StringRef KindValue = "'scalar', 'aggregate', 'pointer'";
20682       if (LangOpts.OpenMP == 50) {
20683         StringRef ModifierValue = "'alloc', 'from', 'to', 'tofrom', "
20684                                   "'firstprivate', 'none', 'default'";
20685         if (!isDefaultmapKind && isDefaultmapModifier) {
20686           Diag(KindLoc, diag::err_omp_unexpected_clause_value)
20687               << KindValue << getOpenMPClauseName(OMPC_defaultmap);
20688         } else if (isDefaultmapKind && !isDefaultmapModifier) {
20689           Diag(MLoc, diag::err_omp_unexpected_clause_value)
20690               << ModifierValue << getOpenMPClauseName(OMPC_defaultmap);
20691         } else {
20692           Diag(MLoc, diag::err_omp_unexpected_clause_value)
20693               << ModifierValue << getOpenMPClauseName(OMPC_defaultmap);
20694           Diag(KindLoc, diag::err_omp_unexpected_clause_value)
20695               << KindValue << getOpenMPClauseName(OMPC_defaultmap);
20696         }
20697       } else {
20698         StringRef ModifierValue =
20699             "'alloc', 'from', 'to', 'tofrom', "
20700             "'firstprivate', 'none', 'default', 'present'";
20701         if (!isDefaultmapKind && isDefaultmapModifier) {
20702           Diag(KindLoc, diag::err_omp_unexpected_clause_value)
20703               << KindValue << getOpenMPClauseName(OMPC_defaultmap);
20704         } else if (isDefaultmapKind && !isDefaultmapModifier) {
20705           Diag(MLoc, diag::err_omp_unexpected_clause_value)
20706               << ModifierValue << getOpenMPClauseName(OMPC_defaultmap);
20707         } else {
20708           Diag(MLoc, diag::err_omp_unexpected_clause_value)
20709               << ModifierValue << getOpenMPClauseName(OMPC_defaultmap);
20710           Diag(KindLoc, diag::err_omp_unexpected_clause_value)
20711               << KindValue << getOpenMPClauseName(OMPC_defaultmap);
20712         }
20713       }
20714       return nullptr;
20715     }
20716 
20717     // OpenMP [5.0, 2.12.5, Restrictions, p. 174]
20718     //  At most one defaultmap clause for each category can appear on the
20719     //  directive.
20720     if (DSAStack->checkDefaultmapCategory(Kind)) {
20721       Diag(StartLoc, diag::err_omp_one_defaultmap_each_category);
20722       return nullptr;
20723     }
20724   }
20725   if (Kind == OMPC_DEFAULTMAP_unknown) {
20726     // Variable category is not specified - mark all categories.
20727     DSAStack->setDefaultDMAAttr(M, OMPC_DEFAULTMAP_aggregate, StartLoc);
20728     DSAStack->setDefaultDMAAttr(M, OMPC_DEFAULTMAP_scalar, StartLoc);
20729     DSAStack->setDefaultDMAAttr(M, OMPC_DEFAULTMAP_pointer, StartLoc);
20730   } else {
20731     DSAStack->setDefaultDMAAttr(M, Kind, StartLoc);
20732   }
20733 
20734   return new (Context)
20735       OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
20736 }
20737 
20738 bool Sema::ActOnStartOpenMPDeclareTargetContext(
20739     DeclareTargetContextInfo &DTCI) {
20740   DeclContext *CurLexicalContext = getCurLexicalContext();
20741   if (!CurLexicalContext->isFileContext() &&
20742       !CurLexicalContext->isExternCContext() &&
20743       !CurLexicalContext->isExternCXXContext() &&
20744       !isa<CXXRecordDecl>(CurLexicalContext) &&
20745       !isa<ClassTemplateDecl>(CurLexicalContext) &&
20746       !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) &&
20747       !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) {
20748     Diag(DTCI.Loc, diag::err_omp_region_not_file_context);
20749     return false;
20750   }
20751   DeclareTargetNesting.push_back(DTCI);
20752   return true;
20753 }
20754 
20755 const Sema::DeclareTargetContextInfo
20756 Sema::ActOnOpenMPEndDeclareTargetDirective() {
20757   assert(!DeclareTargetNesting.empty() &&
20758          "check isInOpenMPDeclareTargetContext() first!");
20759   return DeclareTargetNesting.pop_back_val();
20760 }
20761 
20762 void Sema::ActOnFinishedOpenMPDeclareTargetContext(
20763     DeclareTargetContextInfo &DTCI) {
20764   for (auto &It : DTCI.ExplicitlyMapped)
20765     ActOnOpenMPDeclareTargetName(It.first, It.second.Loc, It.second.MT, DTCI);
20766 }
20767 
20768 NamedDecl *Sema::lookupOpenMPDeclareTargetName(Scope *CurScope,
20769                                                CXXScopeSpec &ScopeSpec,
20770                                                const DeclarationNameInfo &Id) {
20771   LookupResult Lookup(*this, Id, LookupOrdinaryName);
20772   LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
20773 
20774   if (Lookup.isAmbiguous())
20775     return nullptr;
20776   Lookup.suppressDiagnostics();
20777 
20778   if (!Lookup.isSingleResult()) {
20779     VarOrFuncDeclFilterCCC CCC(*this);
20780     if (TypoCorrection Corrected =
20781             CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC,
20782                         CTK_ErrorRecovery)) {
20783       diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
20784                                   << Id.getName());
20785       checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
20786       return nullptr;
20787     }
20788 
20789     Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
20790     return nullptr;
20791   }
20792 
20793   NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
20794   if (!isa<VarDecl>(ND) && !isa<FunctionDecl>(ND) &&
20795       !isa<FunctionTemplateDecl>(ND)) {
20796     Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
20797     return nullptr;
20798   }
20799   return ND;
20800 }
20801 
20802 void Sema::ActOnOpenMPDeclareTargetName(NamedDecl *ND, SourceLocation Loc,
20803                                         OMPDeclareTargetDeclAttr::MapTypeTy MT,
20804                                         DeclareTargetContextInfo &DTCI) {
20805   assert((isa<VarDecl>(ND) || isa<FunctionDecl>(ND) ||
20806           isa<FunctionTemplateDecl>(ND)) &&
20807          "Expected variable, function or function template.");
20808 
20809   // Diagnose marking after use as it may lead to incorrect diagnosis and
20810   // codegen.
20811   if (LangOpts.OpenMP >= 50 &&
20812       (ND->isUsed(/*CheckUsedAttr=*/false) || ND->isReferenced()))
20813     Diag(Loc, diag::warn_omp_declare_target_after_first_use);
20814 
20815   // Explicit declare target lists have precedence.
20816   const unsigned Level = -1;
20817 
20818   auto *VD = cast<ValueDecl>(ND);
20819   llvm::Optional<OMPDeclareTargetDeclAttr *> ActiveAttr =
20820       OMPDeclareTargetDeclAttr::getActiveAttr(VD);
20821   if (ActiveAttr.hasValue() && ActiveAttr.getValue()->getDevType() != DTCI.DT &&
20822       ActiveAttr.getValue()->getLevel() == Level) {
20823     Diag(Loc, diag::err_omp_device_type_mismatch)
20824         << OMPDeclareTargetDeclAttr::ConvertDevTypeTyToStr(DTCI.DT)
20825         << OMPDeclareTargetDeclAttr::ConvertDevTypeTyToStr(
20826                ActiveAttr.getValue()->getDevType());
20827     return;
20828   }
20829   if (ActiveAttr.hasValue() && ActiveAttr.getValue()->getMapType() != MT &&
20830       ActiveAttr.getValue()->getLevel() == Level) {
20831     Diag(Loc, diag::err_omp_declare_target_to_and_link) << ND;
20832     return;
20833   }
20834 
20835   if (ActiveAttr.hasValue() && ActiveAttr.getValue()->getLevel() == Level)
20836     return;
20837 
20838   Expr *IndirectE = nullptr;
20839   bool IsIndirect = false;
20840   if (DTCI.Indirect.hasValue()) {
20841     IndirectE = DTCI.Indirect.getValue();
20842     if (!IndirectE)
20843       IsIndirect = true;
20844   }
20845   auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(
20846       Context, MT, DTCI.DT, IndirectE, IsIndirect, Level,
20847       SourceRange(Loc, Loc));
20848   ND->addAttr(A);
20849   if (ASTMutationListener *ML = Context.getASTMutationListener())
20850     ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
20851   checkDeclIsAllowedInOpenMPTarget(nullptr, ND, Loc);
20852 }
20853 
20854 static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
20855                                      Sema &SemaRef, Decl *D) {
20856   if (!D || !isa<VarDecl>(D))
20857     return;
20858   auto *VD = cast<VarDecl>(D);
20859   Optional<OMPDeclareTargetDeclAttr::MapTypeTy> MapTy =
20860       OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
20861   if (SemaRef.LangOpts.OpenMP >= 50 &&
20862       (SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true) ||
20863        SemaRef.getCurBlock() || SemaRef.getCurCapturedRegion()) &&
20864       VD->hasGlobalStorage()) {
20865     if (!MapTy || *MapTy != OMPDeclareTargetDeclAttr::MT_To) {
20866       // OpenMP 5.0, 2.12.7 declare target Directive, Restrictions
20867       // If a lambda declaration and definition appears between a
20868       // declare target directive and the matching end declare target
20869       // directive, all variables that are captured by the lambda
20870       // expression must also appear in a to clause.
20871       SemaRef.Diag(VD->getLocation(),
20872                    diag::err_omp_lambda_capture_in_declare_target_not_to);
20873       SemaRef.Diag(SL, diag::note_var_explicitly_captured_here)
20874           << VD << 0 << SR;
20875       return;
20876     }
20877   }
20878   if (MapTy.hasValue())
20879     return;
20880   SemaRef.Diag(VD->getLocation(), diag::warn_omp_not_in_target_context);
20881   SemaRef.Diag(SL, diag::note_used_here) << SR;
20882 }
20883 
20884 static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
20885                                    Sema &SemaRef, DSAStackTy *Stack,
20886                                    ValueDecl *VD) {
20887   return OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD) ||
20888          checkTypeMappable(SL, SR, SemaRef, Stack, VD->getType(),
20889                            /*FullCheck=*/false);
20890 }
20891 
20892 void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
20893                                             SourceLocation IdLoc) {
20894   if (!D || D->isInvalidDecl())
20895     return;
20896   SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
20897   SourceLocation SL = E ? E->getBeginLoc() : D->getLocation();
20898   if (auto *VD = dyn_cast<VarDecl>(D)) {
20899     // Only global variables can be marked as declare target.
20900     if (!VD->isFileVarDecl() && !VD->isStaticLocal() &&
20901         !VD->isStaticDataMember())
20902       return;
20903     // 2.10.6: threadprivate variable cannot appear in a declare target
20904     // directive.
20905     if (DSAStack->isThreadPrivate(VD)) {
20906       Diag(SL, diag::err_omp_threadprivate_in_target);
20907       reportOriginalDsa(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
20908       return;
20909     }
20910   }
20911   if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(D))
20912     D = FTD->getTemplatedDecl();
20913   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
20914     llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
20915         OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(FD);
20916     if (IdLoc.isValid() && Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) {
20917       Diag(IdLoc, diag::err_omp_function_in_link_clause);
20918       Diag(FD->getLocation(), diag::note_defined_here) << FD;
20919       return;
20920     }
20921   }
20922   if (auto *VD = dyn_cast<ValueDecl>(D)) {
20923     // Problem if any with var declared with incomplete type will be reported
20924     // as normal, so no need to check it here.
20925     if ((E || !VD->getType()->isIncompleteType()) &&
20926         !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD))
20927       return;
20928     if (!E && isInOpenMPDeclareTargetContext()) {
20929       // Checking declaration inside declare target region.
20930       if (isa<VarDecl>(D) || isa<FunctionDecl>(D) ||
20931           isa<FunctionTemplateDecl>(D)) {
20932         llvm::Optional<OMPDeclareTargetDeclAttr *> ActiveAttr =
20933             OMPDeclareTargetDeclAttr::getActiveAttr(VD);
20934         unsigned Level = DeclareTargetNesting.size();
20935         if (ActiveAttr.hasValue() && ActiveAttr.getValue()->getLevel() >= Level)
20936           return;
20937         DeclareTargetContextInfo &DTCI = DeclareTargetNesting.back();
20938         Expr *IndirectE = nullptr;
20939         bool IsIndirect = false;
20940         if (DTCI.Indirect.hasValue()) {
20941           IndirectE = DTCI.Indirect.getValue();
20942           if (!IndirectE)
20943             IsIndirect = true;
20944         }
20945         auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(
20946             Context, OMPDeclareTargetDeclAttr::MT_To, DTCI.DT, IndirectE,
20947             IsIndirect, Level, SourceRange(DTCI.Loc, DTCI.Loc));
20948         D->addAttr(A);
20949         if (ASTMutationListener *ML = Context.getASTMutationListener())
20950           ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
20951       }
20952       return;
20953     }
20954   }
20955   if (!E)
20956     return;
20957   checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
20958 }
20959 
20960 OMPClause *Sema::ActOnOpenMPToClause(
20961     ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
20962     ArrayRef<SourceLocation> MotionModifiersLoc,
20963     CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId,
20964     SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
20965     const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) {
20966   OpenMPMotionModifierKind Modifiers[] = {OMPC_MOTION_MODIFIER_unknown,
20967                                           OMPC_MOTION_MODIFIER_unknown};
20968   SourceLocation ModifiersLoc[NumberOfOMPMotionModifiers];
20969 
20970   // Process motion-modifiers, flag errors for duplicate modifiers.
20971   unsigned Count = 0;
20972   for (unsigned I = 0, E = MotionModifiers.size(); I < E; ++I) {
20973     if (MotionModifiers[I] != OMPC_MOTION_MODIFIER_unknown &&
20974         llvm::is_contained(Modifiers, MotionModifiers[I])) {
20975       Diag(MotionModifiersLoc[I], diag::err_omp_duplicate_motion_modifier);
20976       continue;
20977     }
20978     assert(Count < NumberOfOMPMotionModifiers &&
20979            "Modifiers exceed the allowed number of motion modifiers");
20980     Modifiers[Count] = MotionModifiers[I];
20981     ModifiersLoc[Count] = MotionModifiersLoc[I];
20982     ++Count;
20983   }
20984 
20985   MappableVarListInfo MVLI(VarList);
20986   checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, Locs.StartLoc,
20987                               MapperIdScopeSpec, MapperId, UnresolvedMappers);
20988   if (MVLI.ProcessedVarList.empty())
20989     return nullptr;
20990 
20991   return OMPToClause::Create(
20992       Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
20993       MVLI.VarComponents, MVLI.UDMapperList, Modifiers, ModifiersLoc,
20994       MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
20995 }
20996 
20997 OMPClause *Sema::ActOnOpenMPFromClause(
20998     ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
20999     ArrayRef<SourceLocation> MotionModifiersLoc,
21000     CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId,
21001     SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
21002     const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) {
21003   OpenMPMotionModifierKind Modifiers[] = {OMPC_MOTION_MODIFIER_unknown,
21004                                           OMPC_MOTION_MODIFIER_unknown};
21005   SourceLocation ModifiersLoc[NumberOfOMPMotionModifiers];
21006 
21007   // Process motion-modifiers, flag errors for duplicate modifiers.
21008   unsigned Count = 0;
21009   for (unsigned I = 0, E = MotionModifiers.size(); I < E; ++I) {
21010     if (MotionModifiers[I] != OMPC_MOTION_MODIFIER_unknown &&
21011         llvm::is_contained(Modifiers, MotionModifiers[I])) {
21012       Diag(MotionModifiersLoc[I], diag::err_omp_duplicate_motion_modifier);
21013       continue;
21014     }
21015     assert(Count < NumberOfOMPMotionModifiers &&
21016            "Modifiers exceed the allowed number of motion modifiers");
21017     Modifiers[Count] = MotionModifiers[I];
21018     ModifiersLoc[Count] = MotionModifiersLoc[I];
21019     ++Count;
21020   }
21021 
21022   MappableVarListInfo MVLI(VarList);
21023   checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, Locs.StartLoc,
21024                               MapperIdScopeSpec, MapperId, UnresolvedMappers);
21025   if (MVLI.ProcessedVarList.empty())
21026     return nullptr;
21027 
21028   return OMPFromClause::Create(
21029       Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
21030       MVLI.VarComponents, MVLI.UDMapperList, Modifiers, ModifiersLoc,
21031       MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
21032 }
21033 
21034 OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
21035                                                const OMPVarListLocTy &Locs) {
21036   MappableVarListInfo MVLI(VarList);
21037   SmallVector<Expr *, 8> PrivateCopies;
21038   SmallVector<Expr *, 8> Inits;
21039 
21040   for (Expr *RefExpr : VarList) {
21041     assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
21042     SourceLocation ELoc;
21043     SourceRange ERange;
21044     Expr *SimpleRefExpr = RefExpr;
21045     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
21046     if (Res.second) {
21047       // It will be analyzed later.
21048       MVLI.ProcessedVarList.push_back(RefExpr);
21049       PrivateCopies.push_back(nullptr);
21050       Inits.push_back(nullptr);
21051     }
21052     ValueDecl *D = Res.first;
21053     if (!D)
21054       continue;
21055 
21056     QualType Type = D->getType();
21057     Type = Type.getNonReferenceType().getUnqualifiedType();
21058 
21059     auto *VD = dyn_cast<VarDecl>(D);
21060 
21061     // Item should be a pointer or reference to pointer.
21062     if (!Type->isPointerType()) {
21063       Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
21064           << 0 << RefExpr->getSourceRange();
21065       continue;
21066     }
21067 
21068     // Build the private variable and the expression that refers to it.
21069     auto VDPrivate =
21070         buildVarDecl(*this, ELoc, Type, D->getName(),
21071                      D->hasAttrs() ? &D->getAttrs() : nullptr,
21072                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
21073     if (VDPrivate->isInvalidDecl())
21074       continue;
21075 
21076     CurContext->addDecl(VDPrivate);
21077     DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
21078         *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
21079 
21080     // Add temporary variable to initialize the private copy of the pointer.
21081     VarDecl *VDInit =
21082         buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
21083     DeclRefExpr *VDInitRefExpr = buildDeclRefExpr(
21084         *this, VDInit, RefExpr->getType(), RefExpr->getExprLoc());
21085     AddInitializerToDecl(VDPrivate,
21086                          DefaultLvalueConversion(VDInitRefExpr).get(),
21087                          /*DirectInit=*/false);
21088 
21089     // If required, build a capture to implement the privatization initialized
21090     // with the current list item value.
21091     DeclRefExpr *Ref = nullptr;
21092     if (!VD)
21093       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
21094     MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
21095     PrivateCopies.push_back(VDPrivateRefExpr);
21096     Inits.push_back(VDInitRefExpr);
21097 
21098     // We need to add a data sharing attribute for this variable to make sure it
21099     // is correctly captured. A variable that shows up in a use_device_ptr has
21100     // similar properties of a first private variable.
21101     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
21102 
21103     // Create a mappable component for the list item. List items in this clause
21104     // only need a component.
21105     MVLI.VarBaseDeclarations.push_back(D);
21106     MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
21107     MVLI.VarComponents.back().emplace_back(SimpleRefExpr, D,
21108                                            /*IsNonContiguous=*/false);
21109   }
21110 
21111   if (MVLI.ProcessedVarList.empty())
21112     return nullptr;
21113 
21114   return OMPUseDevicePtrClause::Create(
21115       Context, Locs, MVLI.ProcessedVarList, PrivateCopies, Inits,
21116       MVLI.VarBaseDeclarations, MVLI.VarComponents);
21117 }
21118 
21119 OMPClause *Sema::ActOnOpenMPUseDeviceAddrClause(ArrayRef<Expr *> VarList,
21120                                                 const OMPVarListLocTy &Locs) {
21121   MappableVarListInfo MVLI(VarList);
21122 
21123   for (Expr *RefExpr : VarList) {
21124     assert(RefExpr && "NULL expr in OpenMP use_device_addr clause.");
21125     SourceLocation ELoc;
21126     SourceRange ERange;
21127     Expr *SimpleRefExpr = RefExpr;
21128     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
21129                               /*AllowArraySection=*/true);
21130     if (Res.second) {
21131       // It will be analyzed later.
21132       MVLI.ProcessedVarList.push_back(RefExpr);
21133     }
21134     ValueDecl *D = Res.first;
21135     if (!D)
21136       continue;
21137     auto *VD = dyn_cast<VarDecl>(D);
21138 
21139     // If required, build a capture to implement the privatization initialized
21140     // with the current list item value.
21141     DeclRefExpr *Ref = nullptr;
21142     if (!VD)
21143       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
21144     MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
21145 
21146     // We need to add a data sharing attribute for this variable to make sure it
21147     // is correctly captured. A variable that shows up in a use_device_addr has
21148     // similar properties of a first private variable.
21149     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
21150 
21151     // Create a mappable component for the list item. List items in this clause
21152     // only need a component.
21153     MVLI.VarBaseDeclarations.push_back(D);
21154     MVLI.VarComponents.emplace_back();
21155     Expr *Component = SimpleRefExpr;
21156     if (VD && (isa<OMPArraySectionExpr>(RefExpr->IgnoreParenImpCasts()) ||
21157                isa<ArraySubscriptExpr>(RefExpr->IgnoreParenImpCasts())))
21158       Component = DefaultFunctionArrayLvalueConversion(SimpleRefExpr).get();
21159     MVLI.VarComponents.back().emplace_back(Component, D,
21160                                            /*IsNonContiguous=*/false);
21161   }
21162 
21163   if (MVLI.ProcessedVarList.empty())
21164     return nullptr;
21165 
21166   return OMPUseDeviceAddrClause::Create(Context, Locs, MVLI.ProcessedVarList,
21167                                         MVLI.VarBaseDeclarations,
21168                                         MVLI.VarComponents);
21169 }
21170 
21171 OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
21172                                               const OMPVarListLocTy &Locs) {
21173   MappableVarListInfo MVLI(VarList);
21174   for (Expr *RefExpr : VarList) {
21175     assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
21176     SourceLocation ELoc;
21177     SourceRange ERange;
21178     Expr *SimpleRefExpr = RefExpr;
21179     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
21180     if (Res.second) {
21181       // It will be analyzed later.
21182       MVLI.ProcessedVarList.push_back(RefExpr);
21183     }
21184     ValueDecl *D = Res.first;
21185     if (!D)
21186       continue;
21187 
21188     QualType Type = D->getType();
21189     // item should be a pointer or array or reference to pointer or array
21190     if (!Type.getNonReferenceType()->isPointerType() &&
21191         !Type.getNonReferenceType()->isArrayType()) {
21192       Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
21193           << 0 << RefExpr->getSourceRange();
21194       continue;
21195     }
21196 
21197     // Check if the declaration in the clause does not show up in any data
21198     // sharing attribute.
21199     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
21200     if (isOpenMPPrivate(DVar.CKind)) {
21201       Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
21202           << getOpenMPClauseName(DVar.CKind)
21203           << getOpenMPClauseName(OMPC_is_device_ptr)
21204           << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
21205       reportOriginalDsa(*this, DSAStack, D, DVar);
21206       continue;
21207     }
21208 
21209     const Expr *ConflictExpr;
21210     if (DSAStack->checkMappableExprComponentListsForDecl(
21211             D, /*CurrentRegionOnly=*/true,
21212             [&ConflictExpr](
21213                 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
21214                 OpenMPClauseKind) -> bool {
21215               ConflictExpr = R.front().getAssociatedExpression();
21216               return true;
21217             })) {
21218       Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
21219       Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
21220           << ConflictExpr->getSourceRange();
21221       continue;
21222     }
21223 
21224     // Store the components in the stack so that they can be used to check
21225     // against other clauses later on.
21226     OMPClauseMappableExprCommon::MappableComponent MC(
21227         SimpleRefExpr, D, /*IsNonContiguous=*/false);
21228     DSAStack->addMappableExpressionComponents(
21229         D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
21230 
21231     // Record the expression we've just processed.
21232     MVLI.ProcessedVarList.push_back(SimpleRefExpr);
21233 
21234     // Create a mappable component for the list item. List items in this clause
21235     // only need a component. We use a null declaration to signal fields in
21236     // 'this'.
21237     assert((isa<DeclRefExpr>(SimpleRefExpr) ||
21238             isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
21239            "Unexpected device pointer expression!");
21240     MVLI.VarBaseDeclarations.push_back(
21241         isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
21242     MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
21243     MVLI.VarComponents.back().push_back(MC);
21244   }
21245 
21246   if (MVLI.ProcessedVarList.empty())
21247     return nullptr;
21248 
21249   return OMPIsDevicePtrClause::Create(Context, Locs, MVLI.ProcessedVarList,
21250                                       MVLI.VarBaseDeclarations,
21251                                       MVLI.VarComponents);
21252 }
21253 
21254 OMPClause *Sema::ActOnOpenMPAllocateClause(
21255     Expr *Allocator, ArrayRef<Expr *> VarList, SourceLocation StartLoc,
21256     SourceLocation ColonLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
21257   if (Allocator) {
21258     // OpenMP [2.11.4 allocate Clause, Description]
21259     // allocator is an expression of omp_allocator_handle_t type.
21260     if (!findOMPAllocatorHandleT(*this, Allocator->getExprLoc(), DSAStack))
21261       return nullptr;
21262 
21263     ExprResult AllocatorRes = DefaultLvalueConversion(Allocator);
21264     if (AllocatorRes.isInvalid())
21265       return nullptr;
21266     AllocatorRes = PerformImplicitConversion(AllocatorRes.get(),
21267                                              DSAStack->getOMPAllocatorHandleT(),
21268                                              Sema::AA_Initializing,
21269                                              /*AllowExplicit=*/true);
21270     if (AllocatorRes.isInvalid())
21271       return nullptr;
21272     Allocator = AllocatorRes.get();
21273   } else {
21274     // OpenMP 5.0, 2.11.4 allocate Clause, Restrictions.
21275     // allocate clauses that appear on a target construct or on constructs in a
21276     // target region must specify an allocator expression unless a requires
21277     // directive with the dynamic_allocators clause is present in the same
21278     // compilation unit.
21279     if (LangOpts.OpenMPIsDevice &&
21280         !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())
21281       targetDiag(StartLoc, diag::err_expected_allocator_expression);
21282   }
21283   // Analyze and build list of variables.
21284   SmallVector<Expr *, 8> Vars;
21285   for (Expr *RefExpr : VarList) {
21286     assert(RefExpr && "NULL expr in OpenMP private clause.");
21287     SourceLocation ELoc;
21288     SourceRange ERange;
21289     Expr *SimpleRefExpr = RefExpr;
21290     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
21291     if (Res.second) {
21292       // It will be analyzed later.
21293       Vars.push_back(RefExpr);
21294     }
21295     ValueDecl *D = Res.first;
21296     if (!D)
21297       continue;
21298 
21299     auto *VD = dyn_cast<VarDecl>(D);
21300     DeclRefExpr *Ref = nullptr;
21301     if (!VD && !CurContext->isDependentContext())
21302       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
21303     Vars.push_back((VD || CurContext->isDependentContext())
21304                        ? RefExpr->IgnoreParens()
21305                        : Ref);
21306   }
21307 
21308   if (Vars.empty())
21309     return nullptr;
21310 
21311   if (Allocator)
21312     DSAStack->addInnerAllocatorExpr(Allocator);
21313   return OMPAllocateClause::Create(Context, StartLoc, LParenLoc, Allocator,
21314                                    ColonLoc, EndLoc, Vars);
21315 }
21316 
21317 OMPClause *Sema::ActOnOpenMPNontemporalClause(ArrayRef<Expr *> VarList,
21318                                               SourceLocation StartLoc,
21319                                               SourceLocation LParenLoc,
21320                                               SourceLocation EndLoc) {
21321   SmallVector<Expr *, 8> Vars;
21322   for (Expr *RefExpr : VarList) {
21323     assert(RefExpr && "NULL expr in OpenMP nontemporal clause.");
21324     SourceLocation ELoc;
21325     SourceRange ERange;
21326     Expr *SimpleRefExpr = RefExpr;
21327     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
21328     if (Res.second)
21329       // It will be analyzed later.
21330       Vars.push_back(RefExpr);
21331     ValueDecl *D = Res.first;
21332     if (!D)
21333       continue;
21334 
21335     // OpenMP 5.0, 2.9.3.1 simd Construct, Restrictions.
21336     // A list-item cannot appear in more than one nontemporal clause.
21337     if (const Expr *PrevRef =
21338             DSAStack->addUniqueNontemporal(D, SimpleRefExpr)) {
21339       Diag(ELoc, diag::err_omp_used_in_clause_twice)
21340           << 0 << getOpenMPClauseName(OMPC_nontemporal) << ERange;
21341       Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
21342           << getOpenMPClauseName(OMPC_nontemporal);
21343       continue;
21344     }
21345 
21346     Vars.push_back(RefExpr);
21347   }
21348 
21349   if (Vars.empty())
21350     return nullptr;
21351 
21352   return OMPNontemporalClause::Create(Context, StartLoc, LParenLoc, EndLoc,
21353                                       Vars);
21354 }
21355 
21356 OMPClause *Sema::ActOnOpenMPInclusiveClause(ArrayRef<Expr *> VarList,
21357                                             SourceLocation StartLoc,
21358                                             SourceLocation LParenLoc,
21359                                             SourceLocation EndLoc) {
21360   SmallVector<Expr *, 8> Vars;
21361   for (Expr *RefExpr : VarList) {
21362     assert(RefExpr && "NULL expr in OpenMP nontemporal clause.");
21363     SourceLocation ELoc;
21364     SourceRange ERange;
21365     Expr *SimpleRefExpr = RefExpr;
21366     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
21367                               /*AllowArraySection=*/true);
21368     if (Res.second)
21369       // It will be analyzed later.
21370       Vars.push_back(RefExpr);
21371     ValueDecl *D = Res.first;
21372     if (!D)
21373       continue;
21374 
21375     const DSAStackTy::DSAVarData DVar =
21376         DSAStack->getTopDSA(D, /*FromParent=*/true);
21377     // OpenMP 5.0, 2.9.6, scan Directive, Restrictions.
21378     // A list item that appears in the inclusive or exclusive clause must appear
21379     // in a reduction clause with the inscan modifier on the enclosing
21380     // worksharing-loop, worksharing-loop SIMD, or simd construct.
21381     if (DVar.CKind != OMPC_reduction || DVar.Modifier != OMPC_REDUCTION_inscan)
21382       Diag(ELoc, diag::err_omp_inclusive_exclusive_not_reduction)
21383           << RefExpr->getSourceRange();
21384 
21385     if (DSAStack->getParentDirective() != OMPD_unknown)
21386       DSAStack->markDeclAsUsedInScanDirective(D);
21387     Vars.push_back(RefExpr);
21388   }
21389 
21390   if (Vars.empty())
21391     return nullptr;
21392 
21393   return OMPInclusiveClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
21394 }
21395 
21396 OMPClause *Sema::ActOnOpenMPExclusiveClause(ArrayRef<Expr *> VarList,
21397                                             SourceLocation StartLoc,
21398                                             SourceLocation LParenLoc,
21399                                             SourceLocation EndLoc) {
21400   SmallVector<Expr *, 8> Vars;
21401   for (Expr *RefExpr : VarList) {
21402     assert(RefExpr && "NULL expr in OpenMP nontemporal clause.");
21403     SourceLocation ELoc;
21404     SourceRange ERange;
21405     Expr *SimpleRefExpr = RefExpr;
21406     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
21407                               /*AllowArraySection=*/true);
21408     if (Res.second)
21409       // It will be analyzed later.
21410       Vars.push_back(RefExpr);
21411     ValueDecl *D = Res.first;
21412     if (!D)
21413       continue;
21414 
21415     OpenMPDirectiveKind ParentDirective = DSAStack->getParentDirective();
21416     DSAStackTy::DSAVarData DVar;
21417     if (ParentDirective != OMPD_unknown)
21418       DVar = DSAStack->getTopDSA(D, /*FromParent=*/true);
21419     // OpenMP 5.0, 2.9.6, scan Directive, Restrictions.
21420     // A list item that appears in the inclusive or exclusive clause must appear
21421     // in a reduction clause with the inscan modifier on the enclosing
21422     // worksharing-loop, worksharing-loop SIMD, or simd construct.
21423     if (ParentDirective == OMPD_unknown || DVar.CKind != OMPC_reduction ||
21424         DVar.Modifier != OMPC_REDUCTION_inscan) {
21425       Diag(ELoc, diag::err_omp_inclusive_exclusive_not_reduction)
21426           << RefExpr->getSourceRange();
21427     } else {
21428       DSAStack->markDeclAsUsedInScanDirective(D);
21429     }
21430     Vars.push_back(RefExpr);
21431   }
21432 
21433   if (Vars.empty())
21434     return nullptr;
21435 
21436   return OMPExclusiveClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
21437 }
21438 
21439 /// Tries to find omp_alloctrait_t type.
21440 static bool findOMPAlloctraitT(Sema &S, SourceLocation Loc, DSAStackTy *Stack) {
21441   QualType OMPAlloctraitT = Stack->getOMPAlloctraitT();
21442   if (!OMPAlloctraitT.isNull())
21443     return true;
21444   IdentifierInfo &II = S.PP.getIdentifierTable().get("omp_alloctrait_t");
21445   ParsedType PT = S.getTypeName(II, Loc, S.getCurScope());
21446   if (!PT.getAsOpaquePtr() || PT.get().isNull()) {
21447     S.Diag(Loc, diag::err_omp_implied_type_not_found) << "omp_alloctrait_t";
21448     return false;
21449   }
21450   Stack->setOMPAlloctraitT(PT.get());
21451   return true;
21452 }
21453 
21454 OMPClause *Sema::ActOnOpenMPUsesAllocatorClause(
21455     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc,
21456     ArrayRef<UsesAllocatorsData> Data) {
21457   // OpenMP [2.12.5, target Construct]
21458   // allocator is an identifier of omp_allocator_handle_t type.
21459   if (!findOMPAllocatorHandleT(*this, StartLoc, DSAStack))
21460     return nullptr;
21461   // OpenMP [2.12.5, target Construct]
21462   // allocator-traits-array is an identifier of const omp_alloctrait_t * type.
21463   if (llvm::any_of(
21464           Data,
21465           [](const UsesAllocatorsData &D) { return D.AllocatorTraits; }) &&
21466       !findOMPAlloctraitT(*this, StartLoc, DSAStack))
21467     return nullptr;
21468   llvm::SmallPtrSet<CanonicalDeclPtr<Decl>, 4> PredefinedAllocators;
21469   for (int I = 0; I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
21470     auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
21471     StringRef Allocator =
21472         OMPAllocateDeclAttr::ConvertAllocatorTypeTyToStr(AllocatorKind);
21473     DeclarationName AllocatorName = &Context.Idents.get(Allocator);
21474     PredefinedAllocators.insert(LookupSingleName(
21475         TUScope, AllocatorName, StartLoc, Sema::LookupAnyName));
21476   }
21477 
21478   SmallVector<OMPUsesAllocatorsClause::Data, 4> NewData;
21479   for (const UsesAllocatorsData &D : Data) {
21480     Expr *AllocatorExpr = nullptr;
21481     // Check allocator expression.
21482     if (D.Allocator->isTypeDependent()) {
21483       AllocatorExpr = D.Allocator;
21484     } else {
21485       // Traits were specified - need to assign new allocator to the specified
21486       // allocator, so it must be an lvalue.
21487       AllocatorExpr = D.Allocator->IgnoreParenImpCasts();
21488       auto *DRE = dyn_cast<DeclRefExpr>(AllocatorExpr);
21489       bool IsPredefinedAllocator = false;
21490       if (DRE)
21491         IsPredefinedAllocator = PredefinedAllocators.count(DRE->getDecl());
21492       if (!DRE ||
21493           !(Context.hasSameUnqualifiedType(
21494                 AllocatorExpr->getType(), DSAStack->getOMPAllocatorHandleT()) ||
21495             Context.typesAreCompatible(AllocatorExpr->getType(),
21496                                        DSAStack->getOMPAllocatorHandleT(),
21497                                        /*CompareUnqualified=*/true)) ||
21498           (!IsPredefinedAllocator &&
21499            (AllocatorExpr->getType().isConstant(Context) ||
21500             !AllocatorExpr->isLValue()))) {
21501         Diag(D.Allocator->getExprLoc(), diag::err_omp_var_expected)
21502             << "omp_allocator_handle_t" << (DRE ? 1 : 0)
21503             << AllocatorExpr->getType() << D.Allocator->getSourceRange();
21504         continue;
21505       }
21506       // OpenMP [2.12.5, target Construct]
21507       // Predefined allocators appearing in a uses_allocators clause cannot have
21508       // traits specified.
21509       if (IsPredefinedAllocator && D.AllocatorTraits) {
21510         Diag(D.AllocatorTraits->getExprLoc(),
21511              diag::err_omp_predefined_allocator_with_traits)
21512             << D.AllocatorTraits->getSourceRange();
21513         Diag(D.Allocator->getExprLoc(), diag::note_omp_predefined_allocator)
21514             << cast<NamedDecl>(DRE->getDecl())->getName()
21515             << D.Allocator->getSourceRange();
21516         continue;
21517       }
21518       // OpenMP [2.12.5, target Construct]
21519       // Non-predefined allocators appearing in a uses_allocators clause must
21520       // have traits specified.
21521       if (!IsPredefinedAllocator && !D.AllocatorTraits) {
21522         Diag(D.Allocator->getExprLoc(),
21523              diag::err_omp_nonpredefined_allocator_without_traits);
21524         continue;
21525       }
21526       // No allocator traits - just convert it to rvalue.
21527       if (!D.AllocatorTraits)
21528         AllocatorExpr = DefaultLvalueConversion(AllocatorExpr).get();
21529       DSAStack->addUsesAllocatorsDecl(
21530           DRE->getDecl(),
21531           IsPredefinedAllocator
21532               ? DSAStackTy::UsesAllocatorsDeclKind::PredefinedAllocator
21533               : DSAStackTy::UsesAllocatorsDeclKind::UserDefinedAllocator);
21534     }
21535     Expr *AllocatorTraitsExpr = nullptr;
21536     if (D.AllocatorTraits) {
21537       if (D.AllocatorTraits->isTypeDependent()) {
21538         AllocatorTraitsExpr = D.AllocatorTraits;
21539       } else {
21540         // OpenMP [2.12.5, target Construct]
21541         // Arrays that contain allocator traits that appear in a uses_allocators
21542         // clause must be constant arrays, have constant values and be defined
21543         // in the same scope as the construct in which the clause appears.
21544         AllocatorTraitsExpr = D.AllocatorTraits->IgnoreParenImpCasts();
21545         // Check that traits expr is a constant array.
21546         QualType TraitTy;
21547         if (const ArrayType *Ty =
21548                 AllocatorTraitsExpr->getType()->getAsArrayTypeUnsafe())
21549           if (const auto *ConstArrayTy = dyn_cast<ConstantArrayType>(Ty))
21550             TraitTy = ConstArrayTy->getElementType();
21551         if (TraitTy.isNull() ||
21552             !(Context.hasSameUnqualifiedType(TraitTy,
21553                                              DSAStack->getOMPAlloctraitT()) ||
21554               Context.typesAreCompatible(TraitTy, DSAStack->getOMPAlloctraitT(),
21555                                          /*CompareUnqualified=*/true))) {
21556           Diag(D.AllocatorTraits->getExprLoc(),
21557                diag::err_omp_expected_array_alloctraits)
21558               << AllocatorTraitsExpr->getType();
21559           continue;
21560         }
21561         // Do not map by default allocator traits if it is a standalone
21562         // variable.
21563         if (auto *DRE = dyn_cast<DeclRefExpr>(AllocatorTraitsExpr))
21564           DSAStack->addUsesAllocatorsDecl(
21565               DRE->getDecl(),
21566               DSAStackTy::UsesAllocatorsDeclKind::AllocatorTrait);
21567       }
21568     }
21569     OMPUsesAllocatorsClause::Data &NewD = NewData.emplace_back();
21570     NewD.Allocator = AllocatorExpr;
21571     NewD.AllocatorTraits = AllocatorTraitsExpr;
21572     NewD.LParenLoc = D.LParenLoc;
21573     NewD.RParenLoc = D.RParenLoc;
21574   }
21575   return OMPUsesAllocatorsClause::Create(Context, StartLoc, LParenLoc, EndLoc,
21576                                          NewData);
21577 }
21578 
21579 OMPClause *Sema::ActOnOpenMPAffinityClause(
21580     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
21581     SourceLocation EndLoc, Expr *Modifier, ArrayRef<Expr *> Locators) {
21582   SmallVector<Expr *, 8> Vars;
21583   for (Expr *RefExpr : Locators) {
21584     assert(RefExpr && "NULL expr in OpenMP shared clause.");
21585     if (isa<DependentScopeDeclRefExpr>(RefExpr) || RefExpr->isTypeDependent()) {
21586       // It will be analyzed later.
21587       Vars.push_back(RefExpr);
21588       continue;
21589     }
21590 
21591     SourceLocation ELoc = RefExpr->getExprLoc();
21592     Expr *SimpleExpr = RefExpr->IgnoreParenImpCasts();
21593 
21594     if (!SimpleExpr->isLValue()) {
21595       Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
21596           << 1 << 0 << RefExpr->getSourceRange();
21597       continue;
21598     }
21599 
21600     ExprResult Res;
21601     {
21602       Sema::TentativeAnalysisScope Trap(*this);
21603       Res = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, SimpleExpr);
21604     }
21605     if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr) &&
21606         !isa<OMPArrayShapingExpr>(SimpleExpr)) {
21607       Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
21608           << 1 << 0 << RefExpr->getSourceRange();
21609       continue;
21610     }
21611     Vars.push_back(SimpleExpr);
21612   }
21613 
21614   return OMPAffinityClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
21615                                    EndLoc, Modifier, Vars);
21616 }
21617 
21618 OMPClause *Sema::ActOnOpenMPBindClause(OpenMPBindClauseKind Kind,
21619                                        SourceLocation KindLoc,
21620                                        SourceLocation StartLoc,
21621                                        SourceLocation LParenLoc,
21622                                        SourceLocation EndLoc) {
21623   if (Kind == OMPC_BIND_unknown) {
21624     Diag(KindLoc, diag::err_omp_unexpected_clause_value)
21625         << getListOfPossibleValues(OMPC_bind, /*First=*/0,
21626                                    /*Last=*/unsigned(OMPC_BIND_unknown))
21627         << getOpenMPClauseName(OMPC_bind);
21628     return nullptr;
21629   }
21630 
21631   return OMPBindClause::Create(Context, Kind, KindLoc, StartLoc, LParenLoc,
21632                                EndLoc);
21633 }
21634