1 //===--- SemaOpenMP.cpp - Semantic Analysis for OpenMP constructs ---------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 /// \file
10 /// This file implements semantic analysis for OpenMP directives and
11 /// clauses.
12 ///
13 //===----------------------------------------------------------------------===//
14 
15 #include "TreeTransform.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTMutationListener.h"
18 #include "clang/AST/CXXInheritance.h"
19 #include "clang/AST/Decl.h"
20 #include "clang/AST/DeclCXX.h"
21 #include "clang/AST/DeclOpenMP.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/OpenMPKinds.h"
27 #include "clang/Sema/Initialization.h"
28 #include "clang/Sema/Lookup.h"
29 #include "clang/Sema/Scope.h"
30 #include "clang/Sema/ScopeInfo.h"
31 #include "clang/Sema/SemaInternal.h"
32 #include "llvm/ADT/PointerEmbeddedInt.h"
33 using namespace clang;
34 
35 //===----------------------------------------------------------------------===//
36 // Stack of data-sharing attributes for variables
37 //===----------------------------------------------------------------------===//
38 
39 static const Expr *checkMapClauseExpressionBase(
40     Sema &SemaRef, Expr *E,
41     OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
42     OpenMPClauseKind CKind, bool NoDiagnose);
43 
44 namespace {
45 /// Default data sharing attributes, which can be applied to directive.
46 enum DefaultDataSharingAttributes {
47   DSA_unspecified = 0, /// Data sharing attribute not specified.
48   DSA_none = 1 << 0,   /// Default data sharing attribute 'none'.
49   DSA_shared = 1 << 1, /// Default data sharing attribute 'shared'.
50 };
51 
52 /// Attributes of the defaultmap clause.
53 enum DefaultMapAttributes {
54   DMA_unspecified,   /// Default mapping is not specified.
55   DMA_tofrom_scalar, /// Default mapping is 'tofrom:scalar'.
56 };
57 
58 /// Stack for tracking declarations used in OpenMP directives and
59 /// clauses and their data-sharing attributes.
60 class DSAStackTy {
61 public:
62   struct DSAVarData {
63     OpenMPDirectiveKind DKind = OMPD_unknown;
64     OpenMPClauseKind CKind = OMPC_unknown;
65     const Expr *RefExpr = nullptr;
66     DeclRefExpr *PrivateCopy = nullptr;
67     SourceLocation ImplicitDSALoc;
68     DSAVarData() = default;
69     DSAVarData(OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
70                const Expr *RefExpr, DeclRefExpr *PrivateCopy,
71                SourceLocation ImplicitDSALoc)
72         : DKind(DKind), CKind(CKind), RefExpr(RefExpr),
73           PrivateCopy(PrivateCopy), ImplicitDSALoc(ImplicitDSALoc) {}
74   };
75   using OperatorOffsetTy =
76       llvm::SmallVector<std::pair<Expr *, OverloadedOperatorKind>, 4>;
77   using DoacrossDependMapTy =
78       llvm::DenseMap<OMPDependClause *, OperatorOffsetTy>;
79 
80 private:
81   struct DSAInfo {
82     OpenMPClauseKind Attributes = OMPC_unknown;
83     /// Pointer to a reference expression and a flag which shows that the
84     /// variable is marked as lastprivate(true) or not (false).
85     llvm::PointerIntPair<const Expr *, 1, bool> RefExpr;
86     DeclRefExpr *PrivateCopy = nullptr;
87   };
88   using DeclSAMapTy = llvm::SmallDenseMap<const ValueDecl *, DSAInfo, 8>;
89   using AlignedMapTy = llvm::SmallDenseMap<const ValueDecl *, const Expr *, 8>;
90   using LCDeclInfo = std::pair<unsigned, VarDecl *>;
91   using LoopControlVariablesMapTy =
92       llvm::SmallDenseMap<const ValueDecl *, LCDeclInfo, 8>;
93   /// Struct that associates a component with the clause kind where they are
94   /// found.
95   struct MappedExprComponentTy {
96     OMPClauseMappableExprCommon::MappableExprComponentLists Components;
97     OpenMPClauseKind Kind = OMPC_unknown;
98   };
99   using MappedExprComponentsTy =
100       llvm::DenseMap<const ValueDecl *, MappedExprComponentTy>;
101   using CriticalsWithHintsTy =
102       llvm::StringMap<std::pair<const OMPCriticalDirective *, llvm::APSInt>>;
103   struct ReductionData {
104     using BOKPtrType = llvm::PointerEmbeddedInt<BinaryOperatorKind, 16>;
105     SourceRange ReductionRange;
106     llvm::PointerUnion<const Expr *, BOKPtrType> ReductionOp;
107     ReductionData() = default;
108     void set(BinaryOperatorKind BO, SourceRange RR) {
109       ReductionRange = RR;
110       ReductionOp = BO;
111     }
112     void set(const Expr *RefExpr, SourceRange RR) {
113       ReductionRange = RR;
114       ReductionOp = RefExpr;
115     }
116   };
117   using DeclReductionMapTy =
118       llvm::SmallDenseMap<const ValueDecl *, ReductionData, 4>;
119 
120   struct SharingMapTy {
121     DeclSAMapTy SharingMap;
122     DeclReductionMapTy ReductionMap;
123     AlignedMapTy AlignedMap;
124     MappedExprComponentsTy MappedExprComponents;
125     LoopControlVariablesMapTy LCVMap;
126     DefaultDataSharingAttributes DefaultAttr = DSA_unspecified;
127     SourceLocation DefaultAttrLoc;
128     DefaultMapAttributes DefaultMapAttr = DMA_unspecified;
129     SourceLocation DefaultMapAttrLoc;
130     OpenMPDirectiveKind Directive = OMPD_unknown;
131     DeclarationNameInfo DirectiveName;
132     Scope *CurScope = nullptr;
133     SourceLocation ConstructLoc;
134     /// Set of 'depend' clauses with 'sink|source' dependence kind. Required to
135     /// get the data (loop counters etc.) about enclosing loop-based construct.
136     /// This data is required during codegen.
137     DoacrossDependMapTy DoacrossDepends;
138     /// first argument (Expr *) contains optional argument of the
139     /// 'ordered' clause, the second one is true if the regions has 'ordered'
140     /// clause, false otherwise.
141     llvm::Optional<std::pair<const Expr *, OMPOrderedClause *>> OrderedRegion;
142     unsigned AssociatedLoops = 1;
143     const Decl *PossiblyLoopCounter = nullptr;
144     bool NowaitRegion = false;
145     bool CancelRegion = false;
146     bool LoopStart = false;
147     SourceLocation InnerTeamsRegionLoc;
148     /// Reference to the taskgroup task_reduction reference expression.
149     Expr *TaskgroupReductionRef = nullptr;
150     llvm::DenseSet<QualType> MappedClassesQualTypes;
151     SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
152                  Scope *CurScope, SourceLocation Loc)
153         : Directive(DKind), DirectiveName(Name), CurScope(CurScope),
154           ConstructLoc(Loc) {}
155     SharingMapTy() = default;
156   };
157 
158   using StackTy = SmallVector<SharingMapTy, 4>;
159 
160   /// Stack of used declaration and their data-sharing attributes.
161   DeclSAMapTy Threadprivates;
162   const FunctionScopeInfo *CurrentNonCapturingFunctionScope = nullptr;
163   SmallVector<std::pair<StackTy, const FunctionScopeInfo *>, 4> Stack;
164   /// true, if check for DSA must be from parent directive, false, if
165   /// from current directive.
166   OpenMPClauseKind ClauseKindMode = OMPC_unknown;
167   Sema &SemaRef;
168   bool ForceCapturing = false;
169   /// true if all the vaiables in the target executable directives must be
170   /// captured by reference.
171   bool ForceCaptureByReferenceInTargetExecutable = false;
172   CriticalsWithHintsTy Criticals;
173 
174   using iterator = StackTy::const_reverse_iterator;
175 
176   DSAVarData getDSA(iterator &Iter, ValueDecl *D) const;
177 
178   /// Checks if the variable is a local for OpenMP region.
179   bool isOpenMPLocal(VarDecl *D, iterator Iter) const;
180 
181   bool isStackEmpty() const {
182     return Stack.empty() ||
183            Stack.back().second != CurrentNonCapturingFunctionScope ||
184            Stack.back().first.empty();
185   }
186 
187   /// Vector of previously declared requires directives
188   SmallVector<const OMPRequiresDecl *, 2> RequiresDecls;
189 
190 public:
191   explicit DSAStackTy(Sema &S) : SemaRef(S) {}
192 
193   bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
194   OpenMPClauseKind getClauseParsingMode() const {
195     assert(isClauseParsingMode() && "Must be in clause parsing mode.");
196     return ClauseKindMode;
197   }
198   void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
199 
200   bool isForceVarCapturing() const { return ForceCapturing; }
201   void setForceVarCapturing(bool V) { ForceCapturing = V; }
202 
203   void setForceCaptureByReferenceInTargetExecutable(bool V) {
204     ForceCaptureByReferenceInTargetExecutable = V;
205   }
206   bool isForceCaptureByReferenceInTargetExecutable() const {
207     return ForceCaptureByReferenceInTargetExecutable;
208   }
209 
210   void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
211             Scope *CurScope, SourceLocation Loc) {
212     if (Stack.empty() ||
213         Stack.back().second != CurrentNonCapturingFunctionScope)
214       Stack.emplace_back(StackTy(), CurrentNonCapturingFunctionScope);
215     Stack.back().first.emplace_back(DKind, DirName, CurScope, Loc);
216     Stack.back().first.back().DefaultAttrLoc = Loc;
217   }
218 
219   void pop() {
220     assert(!Stack.back().first.empty() &&
221            "Data-sharing attributes stack is empty!");
222     Stack.back().first.pop_back();
223   }
224 
225   /// Marks that we're started loop parsing.
226   void loopInit() {
227     assert(isOpenMPLoopDirective(getCurrentDirective()) &&
228            "Expected loop-based directive.");
229     Stack.back().first.back().LoopStart = true;
230   }
231   /// Start capturing of the variables in the loop context.
232   void loopStart() {
233     assert(isOpenMPLoopDirective(getCurrentDirective()) &&
234            "Expected loop-based directive.");
235     Stack.back().first.back().LoopStart = false;
236   }
237   /// true, if variables are captured, false otherwise.
238   bool isLoopStarted() const {
239     assert(isOpenMPLoopDirective(getCurrentDirective()) &&
240            "Expected loop-based directive.");
241     return !Stack.back().first.back().LoopStart;
242   }
243   /// Marks (or clears) declaration as possibly loop counter.
244   void resetPossibleLoopCounter(const Decl *D = nullptr) {
245     Stack.back().first.back().PossiblyLoopCounter =
246         D ? D->getCanonicalDecl() : D;
247   }
248   /// Gets the possible loop counter decl.
249   const Decl *getPossiblyLoopCunter() const {
250     return Stack.back().first.back().PossiblyLoopCounter;
251   }
252   /// Start new OpenMP region stack in new non-capturing function.
253   void pushFunction() {
254     const FunctionScopeInfo *CurFnScope = SemaRef.getCurFunction();
255     assert(!isa<CapturingScopeInfo>(CurFnScope));
256     CurrentNonCapturingFunctionScope = CurFnScope;
257   }
258   /// Pop region stack for non-capturing function.
259   void popFunction(const FunctionScopeInfo *OldFSI) {
260     if (!Stack.empty() && Stack.back().second == OldFSI) {
261       assert(Stack.back().first.empty());
262       Stack.pop_back();
263     }
264     CurrentNonCapturingFunctionScope = nullptr;
265     for (const FunctionScopeInfo *FSI : llvm::reverse(SemaRef.FunctionScopes)) {
266       if (!isa<CapturingScopeInfo>(FSI)) {
267         CurrentNonCapturingFunctionScope = FSI;
268         break;
269       }
270     }
271   }
272 
273   void addCriticalWithHint(const OMPCriticalDirective *D, llvm::APSInt Hint) {
274     Criticals.try_emplace(D->getDirectiveName().getAsString(), D, Hint);
275   }
276   const std::pair<const OMPCriticalDirective *, llvm::APSInt>
277   getCriticalWithHint(const DeclarationNameInfo &Name) const {
278     auto I = Criticals.find(Name.getAsString());
279     if (I != Criticals.end())
280       return I->second;
281     return std::make_pair(nullptr, llvm::APSInt());
282   }
283   /// If 'aligned' declaration for given variable \a D was not seen yet,
284   /// add it and return NULL; otherwise return previous occurrence's expression
285   /// for diagnostics.
286   const Expr *addUniqueAligned(const ValueDecl *D, const Expr *NewDE);
287 
288   /// Register specified variable as loop control variable.
289   void addLoopControlVariable(const ValueDecl *D, VarDecl *Capture);
290   /// Check if the specified variable is a loop control variable for
291   /// current region.
292   /// \return The index of the loop control variable in the list of associated
293   /// for-loops (from outer to inner).
294   const LCDeclInfo isLoopControlVariable(const ValueDecl *D) const;
295   /// Check if the specified variable is a loop control variable for
296   /// parent region.
297   /// \return The index of the loop control variable in the list of associated
298   /// for-loops (from outer to inner).
299   const LCDeclInfo isParentLoopControlVariable(const ValueDecl *D) const;
300   /// Get the loop control variable for the I-th loop (or nullptr) in
301   /// parent directive.
302   const ValueDecl *getParentLoopControlVariable(unsigned I) const;
303 
304   /// Adds explicit data sharing attribute to the specified declaration.
305   void addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
306               DeclRefExpr *PrivateCopy = nullptr);
307 
308   /// Adds additional information for the reduction items with the reduction id
309   /// represented as an operator.
310   void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
311                                  BinaryOperatorKind BOK);
312   /// Adds additional information for the reduction items with the reduction id
313   /// represented as reduction identifier.
314   void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
315                                  const Expr *ReductionRef);
316   /// Returns the location and reduction operation from the innermost parent
317   /// region for the given \p D.
318   const DSAVarData
319   getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
320                                    BinaryOperatorKind &BOK,
321                                    Expr *&TaskgroupDescriptor) const;
322   /// Returns the location and reduction operation from the innermost parent
323   /// region for the given \p D.
324   const DSAVarData
325   getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
326                                    const Expr *&ReductionRef,
327                                    Expr *&TaskgroupDescriptor) const;
328   /// Return reduction reference expression for the current taskgroup.
329   Expr *getTaskgroupReductionRef() const {
330     assert(Stack.back().first.back().Directive == OMPD_taskgroup &&
331            "taskgroup reference expression requested for non taskgroup "
332            "directive.");
333     return Stack.back().first.back().TaskgroupReductionRef;
334   }
335   /// Checks if the given \p VD declaration is actually a taskgroup reduction
336   /// descriptor variable at the \p Level of OpenMP regions.
337   bool isTaskgroupReductionRef(const ValueDecl *VD, unsigned Level) const {
338     return Stack.back().first[Level].TaskgroupReductionRef &&
339            cast<DeclRefExpr>(Stack.back().first[Level].TaskgroupReductionRef)
340                    ->getDecl() == VD;
341   }
342 
343   /// Returns data sharing attributes from top of the stack for the
344   /// specified declaration.
345   const DSAVarData getTopDSA(ValueDecl *D, bool FromParent);
346   /// Returns data-sharing attributes for the specified declaration.
347   const DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent) const;
348   /// Checks if the specified variables has data-sharing attributes which
349   /// match specified \a CPred predicate in any directive which matches \a DPred
350   /// predicate.
351   const DSAVarData
352   hasDSA(ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
353          const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
354          bool FromParent) const;
355   /// Checks if the specified variables has data-sharing attributes which
356   /// match specified \a CPred predicate in any innermost directive which
357   /// matches \a DPred predicate.
358   const DSAVarData
359   hasInnermostDSA(ValueDecl *D,
360                   const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
361                   const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
362                   bool FromParent) const;
363   /// Checks if the specified variables has explicit data-sharing
364   /// attributes which match specified \a CPred predicate at the specified
365   /// OpenMP region.
366   bool hasExplicitDSA(const ValueDecl *D,
367                       const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
368                       unsigned Level, bool NotLastprivate = false) const;
369 
370   /// Returns true if the directive at level \Level matches in the
371   /// specified \a DPred predicate.
372   bool hasExplicitDirective(
373       const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
374       unsigned Level) const;
375 
376   /// Finds a directive which matches specified \a DPred predicate.
377   bool hasDirective(
378       const llvm::function_ref<bool(
379           OpenMPDirectiveKind, const DeclarationNameInfo &, SourceLocation)>
380           DPred,
381       bool FromParent) const;
382 
383   /// Returns currently analyzed directive.
384   OpenMPDirectiveKind getCurrentDirective() const {
385     return isStackEmpty() ? OMPD_unknown : Stack.back().first.back().Directive;
386   }
387   /// Returns directive kind at specified level.
388   OpenMPDirectiveKind getDirective(unsigned Level) const {
389     assert(!isStackEmpty() && "No directive at specified level.");
390     return Stack.back().first[Level].Directive;
391   }
392   /// Returns parent directive.
393   OpenMPDirectiveKind getParentDirective() const {
394     if (isStackEmpty() || Stack.back().first.size() == 1)
395       return OMPD_unknown;
396     return std::next(Stack.back().first.rbegin())->Directive;
397   }
398 
399   /// Add requires decl to internal vector
400   void addRequiresDecl(OMPRequiresDecl *RD) {
401     RequiresDecls.push_back(RD);
402   }
403 
404   /// Checks for a duplicate clause amongst previously declared requires
405   /// directives
406   bool hasDuplicateRequiresClause(ArrayRef<OMPClause *> ClauseList) const {
407     bool IsDuplicate = false;
408     for (OMPClause *CNew : ClauseList) {
409       for (const OMPRequiresDecl *D : RequiresDecls) {
410         for (const OMPClause *CPrev : D->clauselists()) {
411           if (CNew->getClauseKind() == CPrev->getClauseKind()) {
412             SemaRef.Diag(CNew->getBeginLoc(),
413                          diag::err_omp_requires_clause_redeclaration)
414                 << getOpenMPClauseName(CNew->getClauseKind());
415             SemaRef.Diag(CPrev->getBeginLoc(),
416                          diag::note_omp_requires_previous_clause)
417                 << getOpenMPClauseName(CPrev->getClauseKind());
418             IsDuplicate = true;
419           }
420         }
421       }
422     }
423     return IsDuplicate;
424   }
425 
426   /// Set default data sharing attribute to none.
427   void setDefaultDSANone(SourceLocation Loc) {
428     assert(!isStackEmpty());
429     Stack.back().first.back().DefaultAttr = DSA_none;
430     Stack.back().first.back().DefaultAttrLoc = Loc;
431   }
432   /// Set default data sharing attribute to shared.
433   void setDefaultDSAShared(SourceLocation Loc) {
434     assert(!isStackEmpty());
435     Stack.back().first.back().DefaultAttr = DSA_shared;
436     Stack.back().first.back().DefaultAttrLoc = Loc;
437   }
438   /// Set default data mapping attribute to 'tofrom:scalar'.
439   void setDefaultDMAToFromScalar(SourceLocation Loc) {
440     assert(!isStackEmpty());
441     Stack.back().first.back().DefaultMapAttr = DMA_tofrom_scalar;
442     Stack.back().first.back().DefaultMapAttrLoc = Loc;
443   }
444 
445   DefaultDataSharingAttributes getDefaultDSA() const {
446     return isStackEmpty() ? DSA_unspecified
447                           : Stack.back().first.back().DefaultAttr;
448   }
449   SourceLocation getDefaultDSALocation() const {
450     return isStackEmpty() ? SourceLocation()
451                           : Stack.back().first.back().DefaultAttrLoc;
452   }
453   DefaultMapAttributes getDefaultDMA() const {
454     return isStackEmpty() ? DMA_unspecified
455                           : Stack.back().first.back().DefaultMapAttr;
456   }
457   DefaultMapAttributes getDefaultDMAAtLevel(unsigned Level) const {
458     return Stack.back().first[Level].DefaultMapAttr;
459   }
460   SourceLocation getDefaultDMALocation() const {
461     return isStackEmpty() ? SourceLocation()
462                           : Stack.back().first.back().DefaultMapAttrLoc;
463   }
464 
465   /// Checks if the specified variable is a threadprivate.
466   bool isThreadPrivate(VarDecl *D) {
467     const DSAVarData DVar = getTopDSA(D, false);
468     return isOpenMPThreadPrivate(DVar.CKind);
469   }
470 
471   /// Marks current region as ordered (it has an 'ordered' clause).
472   void setOrderedRegion(bool IsOrdered, const Expr *Param,
473                         OMPOrderedClause *Clause) {
474     assert(!isStackEmpty());
475     if (IsOrdered)
476       Stack.back().first.back().OrderedRegion.emplace(Param, Clause);
477     else
478       Stack.back().first.back().OrderedRegion.reset();
479   }
480   /// Returns true, if region is ordered (has associated 'ordered' clause),
481   /// false - otherwise.
482   bool isOrderedRegion() const {
483     if (isStackEmpty())
484       return false;
485     return Stack.back().first.rbegin()->OrderedRegion.hasValue();
486   }
487   /// Returns optional parameter for the ordered region.
488   std::pair<const Expr *, OMPOrderedClause *> getOrderedRegionParam() const {
489     if (isStackEmpty() ||
490         !Stack.back().first.rbegin()->OrderedRegion.hasValue())
491       return std::make_pair(nullptr, nullptr);
492     return Stack.back().first.rbegin()->OrderedRegion.getValue();
493   }
494   /// Returns true, if parent region is ordered (has associated
495   /// 'ordered' clause), false - otherwise.
496   bool isParentOrderedRegion() const {
497     if (isStackEmpty() || Stack.back().first.size() == 1)
498       return false;
499     return std::next(Stack.back().first.rbegin())->OrderedRegion.hasValue();
500   }
501   /// Returns optional parameter for the ordered region.
502   std::pair<const Expr *, OMPOrderedClause *>
503   getParentOrderedRegionParam() const {
504     if (isStackEmpty() || Stack.back().first.size() == 1 ||
505         !std::next(Stack.back().first.rbegin())->OrderedRegion.hasValue())
506       return std::make_pair(nullptr, nullptr);
507     return std::next(Stack.back().first.rbegin())->OrderedRegion.getValue();
508   }
509   /// Marks current region as nowait (it has a 'nowait' clause).
510   void setNowaitRegion(bool IsNowait = true) {
511     assert(!isStackEmpty());
512     Stack.back().first.back().NowaitRegion = IsNowait;
513   }
514   /// Returns true, if parent region is nowait (has associated
515   /// 'nowait' clause), false - otherwise.
516   bool isParentNowaitRegion() const {
517     if (isStackEmpty() || Stack.back().first.size() == 1)
518       return false;
519     return std::next(Stack.back().first.rbegin())->NowaitRegion;
520   }
521   /// Marks parent region as cancel region.
522   void setParentCancelRegion(bool Cancel = true) {
523     if (!isStackEmpty() && Stack.back().first.size() > 1) {
524       auto &StackElemRef = *std::next(Stack.back().first.rbegin());
525       StackElemRef.CancelRegion |= StackElemRef.CancelRegion || Cancel;
526     }
527   }
528   /// Return true if current region has inner cancel construct.
529   bool isCancelRegion() const {
530     return isStackEmpty() ? false : Stack.back().first.back().CancelRegion;
531   }
532 
533   /// Set collapse value for the region.
534   void setAssociatedLoops(unsigned Val) {
535     assert(!isStackEmpty());
536     Stack.back().first.back().AssociatedLoops = Val;
537   }
538   /// Return collapse value for region.
539   unsigned getAssociatedLoops() const {
540     return isStackEmpty() ? 0 : Stack.back().first.back().AssociatedLoops;
541   }
542 
543   /// Marks current target region as one with closely nested teams
544   /// region.
545   void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
546     if (!isStackEmpty() && Stack.back().first.size() > 1) {
547       std::next(Stack.back().first.rbegin())->InnerTeamsRegionLoc =
548           TeamsRegionLoc;
549     }
550   }
551   /// Returns true, if current region has closely nested teams region.
552   bool hasInnerTeamsRegion() const {
553     return getInnerTeamsRegionLoc().isValid();
554   }
555   /// Returns location of the nested teams region (if any).
556   SourceLocation getInnerTeamsRegionLoc() const {
557     return isStackEmpty() ? SourceLocation()
558                           : Stack.back().first.back().InnerTeamsRegionLoc;
559   }
560 
561   Scope *getCurScope() const {
562     return isStackEmpty() ? nullptr : Stack.back().first.back().CurScope;
563   }
564   SourceLocation getConstructLoc() const {
565     return isStackEmpty() ? SourceLocation()
566                           : Stack.back().first.back().ConstructLoc;
567   }
568 
569   /// Do the check specified in \a Check to all component lists and return true
570   /// if any issue is found.
571   bool checkMappableExprComponentListsForDecl(
572       const ValueDecl *VD, bool CurrentRegionOnly,
573       const llvm::function_ref<
574           bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
575                OpenMPClauseKind)>
576           Check) const {
577     if (isStackEmpty())
578       return false;
579     auto SI = Stack.back().first.rbegin();
580     auto SE = Stack.back().first.rend();
581 
582     if (SI == SE)
583       return false;
584 
585     if (CurrentRegionOnly)
586       SE = std::next(SI);
587     else
588       std::advance(SI, 1);
589 
590     for (; SI != SE; ++SI) {
591       auto MI = SI->MappedExprComponents.find(VD);
592       if (MI != SI->MappedExprComponents.end())
593         for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
594              MI->second.Components)
595           if (Check(L, MI->second.Kind))
596             return true;
597     }
598     return false;
599   }
600 
601   /// Do the check specified in \a Check to all component lists at a given level
602   /// and return true if any issue is found.
603   bool checkMappableExprComponentListsForDeclAtLevel(
604       const ValueDecl *VD, unsigned Level,
605       const llvm::function_ref<
606           bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
607                OpenMPClauseKind)>
608           Check) const {
609     if (isStackEmpty())
610       return false;
611 
612     auto StartI = Stack.back().first.begin();
613     auto EndI = Stack.back().first.end();
614     if (std::distance(StartI, EndI) <= (int)Level)
615       return false;
616     std::advance(StartI, Level);
617 
618     auto MI = StartI->MappedExprComponents.find(VD);
619     if (MI != StartI->MappedExprComponents.end())
620       for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
621            MI->second.Components)
622         if (Check(L, MI->second.Kind))
623           return true;
624     return false;
625   }
626 
627   /// Create a new mappable expression component list associated with a given
628   /// declaration and initialize it with the provided list of components.
629   void addMappableExpressionComponents(
630       const ValueDecl *VD,
631       OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
632       OpenMPClauseKind WhereFoundClauseKind) {
633     assert(!isStackEmpty() &&
634            "Not expecting to retrieve components from a empty stack!");
635     MappedExprComponentTy &MEC =
636         Stack.back().first.back().MappedExprComponents[VD];
637     // Create new entry and append the new components there.
638     MEC.Components.resize(MEC.Components.size() + 1);
639     MEC.Components.back().append(Components.begin(), Components.end());
640     MEC.Kind = WhereFoundClauseKind;
641   }
642 
643   unsigned getNestingLevel() const {
644     assert(!isStackEmpty());
645     return Stack.back().first.size() - 1;
646   }
647   void addDoacrossDependClause(OMPDependClause *C,
648                                const OperatorOffsetTy &OpsOffs) {
649     assert(!isStackEmpty() && Stack.back().first.size() > 1);
650     SharingMapTy &StackElem = *std::next(Stack.back().first.rbegin());
651     assert(isOpenMPWorksharingDirective(StackElem.Directive));
652     StackElem.DoacrossDepends.try_emplace(C, OpsOffs);
653   }
654   llvm::iterator_range<DoacrossDependMapTy::const_iterator>
655   getDoacrossDependClauses() const {
656     assert(!isStackEmpty());
657     const SharingMapTy &StackElem = Stack.back().first.back();
658     if (isOpenMPWorksharingDirective(StackElem.Directive)) {
659       const DoacrossDependMapTy &Ref = StackElem.DoacrossDepends;
660       return llvm::make_range(Ref.begin(), Ref.end());
661     }
662     return llvm::make_range(StackElem.DoacrossDepends.end(),
663                             StackElem.DoacrossDepends.end());
664   }
665 
666   // Store types of classes which have been explicitly mapped
667   void addMappedClassesQualTypes(QualType QT) {
668     SharingMapTy &StackElem = Stack.back().first.back();
669     StackElem.MappedClassesQualTypes.insert(QT);
670   }
671 
672   // Return set of mapped classes types
673   bool isClassPreviouslyMapped(QualType QT) const {
674     const SharingMapTy &StackElem = Stack.back().first.back();
675     return StackElem.MappedClassesQualTypes.count(QT) != 0;
676   }
677 
678 };
679 bool isParallelOrTaskRegion(OpenMPDirectiveKind DKind) {
680   return isOpenMPParallelDirective(DKind) || isOpenMPTaskingDirective(DKind) ||
681          isOpenMPTeamsDirective(DKind) || DKind == OMPD_unknown;
682 }
683 
684 } // namespace
685 
686 static const Expr *getExprAsWritten(const Expr *E) {
687   if (const auto *FE = dyn_cast<FullExpr>(E))
688     E = FE->getSubExpr();
689 
690   if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
691     E = MTE->GetTemporaryExpr();
692 
693   while (const auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
694     E = Binder->getSubExpr();
695 
696   if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
697     E = ICE->getSubExprAsWritten();
698   return E->IgnoreParens();
699 }
700 
701 static Expr *getExprAsWritten(Expr *E) {
702   return const_cast<Expr *>(getExprAsWritten(const_cast<const Expr *>(E)));
703 }
704 
705 static const ValueDecl *getCanonicalDecl(const ValueDecl *D) {
706   if (const auto *CED = dyn_cast<OMPCapturedExprDecl>(D))
707     if (const auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
708       D = ME->getMemberDecl();
709   const auto *VD = dyn_cast<VarDecl>(D);
710   const auto *FD = dyn_cast<FieldDecl>(D);
711   if (VD != nullptr) {
712     VD = VD->getCanonicalDecl();
713     D = VD;
714   } else {
715     assert(FD);
716     FD = FD->getCanonicalDecl();
717     D = FD;
718   }
719   return D;
720 }
721 
722 static ValueDecl *getCanonicalDecl(ValueDecl *D) {
723   return const_cast<ValueDecl *>(
724       getCanonicalDecl(const_cast<const ValueDecl *>(D)));
725 }
726 
727 DSAStackTy::DSAVarData DSAStackTy::getDSA(iterator &Iter,
728                                           ValueDecl *D) const {
729   D = getCanonicalDecl(D);
730   auto *VD = dyn_cast<VarDecl>(D);
731   const auto *FD = dyn_cast<FieldDecl>(D);
732   DSAVarData DVar;
733   if (isStackEmpty() || Iter == Stack.back().first.rend()) {
734     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
735     // in a region but not in construct]
736     //  File-scope or namespace-scope variables referenced in called routines
737     //  in the region are shared unless they appear in a threadprivate
738     //  directive.
739     if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(VD))
740       DVar.CKind = OMPC_shared;
741 
742     // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
743     // in a region but not in construct]
744     //  Variables with static storage duration that are declared in called
745     //  routines in the region are shared.
746     if (VD && VD->hasGlobalStorage())
747       DVar.CKind = OMPC_shared;
748 
749     // Non-static data members are shared by default.
750     if (FD)
751       DVar.CKind = OMPC_shared;
752 
753     return DVar;
754   }
755 
756   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
757   // in a Construct, C/C++, predetermined, p.1]
758   // Variables with automatic storage duration that are declared in a scope
759   // inside the construct are private.
760   if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() &&
761       (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) {
762     DVar.CKind = OMPC_private;
763     return DVar;
764   }
765 
766   DVar.DKind = Iter->Directive;
767   // Explicitly specified attributes and local variables with predetermined
768   // attributes.
769   if (Iter->SharingMap.count(D)) {
770     const DSAInfo &Data = Iter->SharingMap.lookup(D);
771     DVar.RefExpr = Data.RefExpr.getPointer();
772     DVar.PrivateCopy = Data.PrivateCopy;
773     DVar.CKind = Data.Attributes;
774     DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
775     return DVar;
776   }
777 
778   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
779   // in a Construct, C/C++, implicitly determined, p.1]
780   //  In a parallel or task construct, the data-sharing attributes of these
781   //  variables are determined by the default clause, if present.
782   switch (Iter->DefaultAttr) {
783   case DSA_shared:
784     DVar.CKind = OMPC_shared;
785     DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
786     return DVar;
787   case DSA_none:
788     return DVar;
789   case DSA_unspecified:
790     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
791     // in a Construct, implicitly determined, p.2]
792     //  In a parallel construct, if no default clause is present, these
793     //  variables are shared.
794     DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
795     if (isOpenMPParallelDirective(DVar.DKind) ||
796         isOpenMPTeamsDirective(DVar.DKind)) {
797       DVar.CKind = OMPC_shared;
798       return DVar;
799     }
800 
801     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
802     // in a Construct, implicitly determined, p.4]
803     //  In a task construct, if no default clause is present, a variable that in
804     //  the enclosing context is determined to be shared by all implicit tasks
805     //  bound to the current team is shared.
806     if (isOpenMPTaskingDirective(DVar.DKind)) {
807       DSAVarData DVarTemp;
808       iterator I = Iter, E = Stack.back().first.rend();
809       do {
810         ++I;
811         // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
812         // Referenced in a Construct, implicitly determined, p.6]
813         //  In a task construct, if no default clause is present, a variable
814         //  whose data-sharing attribute is not determined by the rules above is
815         //  firstprivate.
816         DVarTemp = getDSA(I, D);
817         if (DVarTemp.CKind != OMPC_shared) {
818           DVar.RefExpr = nullptr;
819           DVar.CKind = OMPC_firstprivate;
820           return DVar;
821         }
822       } while (I != E && !isParallelOrTaskRegion(I->Directive));
823       DVar.CKind =
824           (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
825       return DVar;
826     }
827   }
828   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
829   // in a Construct, implicitly determined, p.3]
830   //  For constructs other than task, if no default clause is present, these
831   //  variables inherit their data-sharing attributes from the enclosing
832   //  context.
833   return getDSA(++Iter, D);
834 }
835 
836 const Expr *DSAStackTy::addUniqueAligned(const ValueDecl *D,
837                                          const Expr *NewDE) {
838   assert(!isStackEmpty() && "Data sharing attributes stack is empty");
839   D = getCanonicalDecl(D);
840   SharingMapTy &StackElem = Stack.back().first.back();
841   auto It = StackElem.AlignedMap.find(D);
842   if (It == StackElem.AlignedMap.end()) {
843     assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
844     StackElem.AlignedMap[D] = NewDE;
845     return nullptr;
846   }
847   assert(It->second && "Unexpected nullptr expr in the aligned map");
848   return It->second;
849 }
850 
851 void DSAStackTy::addLoopControlVariable(const ValueDecl *D, VarDecl *Capture) {
852   assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
853   D = getCanonicalDecl(D);
854   SharingMapTy &StackElem = Stack.back().first.back();
855   StackElem.LCVMap.try_emplace(
856       D, LCDeclInfo(StackElem.LCVMap.size() + 1, Capture));
857 }
858 
859 const DSAStackTy::LCDeclInfo
860 DSAStackTy::isLoopControlVariable(const ValueDecl *D) const {
861   assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
862   D = getCanonicalDecl(D);
863   const SharingMapTy &StackElem = Stack.back().first.back();
864   auto It = StackElem.LCVMap.find(D);
865   if (It != StackElem.LCVMap.end())
866     return It->second;
867   return {0, nullptr};
868 }
869 
870 const DSAStackTy::LCDeclInfo
871 DSAStackTy::isParentLoopControlVariable(const ValueDecl *D) const {
872   assert(!isStackEmpty() && Stack.back().first.size() > 1 &&
873          "Data-sharing attributes stack is empty");
874   D = getCanonicalDecl(D);
875   const SharingMapTy &StackElem = *std::next(Stack.back().first.rbegin());
876   auto It = StackElem.LCVMap.find(D);
877   if (It != StackElem.LCVMap.end())
878     return It->second;
879   return {0, nullptr};
880 }
881 
882 const ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) const {
883   assert(!isStackEmpty() && Stack.back().first.size() > 1 &&
884          "Data-sharing attributes stack is empty");
885   const SharingMapTy &StackElem = *std::next(Stack.back().first.rbegin());
886   if (StackElem.LCVMap.size() < I)
887     return nullptr;
888   for (const auto &Pair : StackElem.LCVMap)
889     if (Pair.second.first == I)
890       return Pair.first;
891   return nullptr;
892 }
893 
894 void DSAStackTy::addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
895                         DeclRefExpr *PrivateCopy) {
896   D = getCanonicalDecl(D);
897   if (A == OMPC_threadprivate) {
898     DSAInfo &Data = Threadprivates[D];
899     Data.Attributes = A;
900     Data.RefExpr.setPointer(E);
901     Data.PrivateCopy = nullptr;
902   } else {
903     assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
904     DSAInfo &Data = Stack.back().first.back().SharingMap[D];
905     assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
906            (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) ||
907            (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) ||
908            (isLoopControlVariable(D).first && A == OMPC_private));
909     if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) {
910       Data.RefExpr.setInt(/*IntVal=*/true);
911       return;
912     }
913     const bool IsLastprivate =
914         A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate;
915     Data.Attributes = A;
916     Data.RefExpr.setPointerAndInt(E, IsLastprivate);
917     Data.PrivateCopy = PrivateCopy;
918     if (PrivateCopy) {
919       DSAInfo &Data =
920           Stack.back().first.back().SharingMap[PrivateCopy->getDecl()];
921       Data.Attributes = A;
922       Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate);
923       Data.PrivateCopy = nullptr;
924     }
925   }
926 }
927 
928 /// Build a variable declaration for OpenMP loop iteration variable.
929 static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
930                              StringRef Name, const AttrVec *Attrs = nullptr,
931                              DeclRefExpr *OrigRef = nullptr) {
932   DeclContext *DC = SemaRef.CurContext;
933   IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
934   TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
935   auto *Decl =
936       VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
937   if (Attrs) {
938     for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
939          I != E; ++I)
940       Decl->addAttr(*I);
941   }
942   Decl->setImplicit();
943   if (OrigRef) {
944     Decl->addAttr(
945         OMPReferencedVarAttr::CreateImplicit(SemaRef.Context, OrigRef));
946   }
947   return Decl;
948 }
949 
950 static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
951                                      SourceLocation Loc,
952                                      bool RefersToCapture = false) {
953   D->setReferenced();
954   D->markUsed(S.Context);
955   return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
956                              SourceLocation(), D, RefersToCapture, Loc, Ty,
957                              VK_LValue);
958 }
959 
960 void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
961                                            BinaryOperatorKind BOK) {
962   D = getCanonicalDecl(D);
963   assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
964   assert(
965       Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction &&
966       "Additional reduction info may be specified only for reduction items.");
967   ReductionData &ReductionData = Stack.back().first.back().ReductionMap[D];
968   assert(ReductionData.ReductionRange.isInvalid() &&
969          Stack.back().first.back().Directive == OMPD_taskgroup &&
970          "Additional reduction info may be specified only once for reduction "
971          "items.");
972   ReductionData.set(BOK, SR);
973   Expr *&TaskgroupReductionRef =
974       Stack.back().first.back().TaskgroupReductionRef;
975   if (!TaskgroupReductionRef) {
976     VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
977                                SemaRef.Context.VoidPtrTy, ".task_red.");
978     TaskgroupReductionRef =
979         buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
980   }
981 }
982 
983 void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
984                                            const Expr *ReductionRef) {
985   D = getCanonicalDecl(D);
986   assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
987   assert(
988       Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction &&
989       "Additional reduction info may be specified only for reduction items.");
990   ReductionData &ReductionData = Stack.back().first.back().ReductionMap[D];
991   assert(ReductionData.ReductionRange.isInvalid() &&
992          Stack.back().first.back().Directive == OMPD_taskgroup &&
993          "Additional reduction info may be specified only once for reduction "
994          "items.");
995   ReductionData.set(ReductionRef, SR);
996   Expr *&TaskgroupReductionRef =
997       Stack.back().first.back().TaskgroupReductionRef;
998   if (!TaskgroupReductionRef) {
999     VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
1000                                SemaRef.Context.VoidPtrTy, ".task_red.");
1001     TaskgroupReductionRef =
1002         buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
1003   }
1004 }
1005 
1006 const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
1007     const ValueDecl *D, SourceRange &SR, BinaryOperatorKind &BOK,
1008     Expr *&TaskgroupDescriptor) const {
1009   D = getCanonicalDecl(D);
1010   assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
1011   if (Stack.back().first.empty())
1012       return DSAVarData();
1013   for (iterator I = std::next(Stack.back().first.rbegin(), 1),
1014                 E = Stack.back().first.rend();
1015        I != E; std::advance(I, 1)) {
1016     const DSAInfo &Data = I->SharingMap.lookup(D);
1017     if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
1018       continue;
1019     const ReductionData &ReductionData = I->ReductionMap.lookup(D);
1020     if (!ReductionData.ReductionOp ||
1021         ReductionData.ReductionOp.is<const Expr *>())
1022       return DSAVarData();
1023     SR = ReductionData.ReductionRange;
1024     BOK = ReductionData.ReductionOp.get<ReductionData::BOKPtrType>();
1025     assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
1026                                        "expression for the descriptor is not "
1027                                        "set.");
1028     TaskgroupDescriptor = I->TaskgroupReductionRef;
1029     return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
1030                       Data.PrivateCopy, I->DefaultAttrLoc);
1031   }
1032   return DSAVarData();
1033 }
1034 
1035 const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
1036     const ValueDecl *D, SourceRange &SR, const Expr *&ReductionRef,
1037     Expr *&TaskgroupDescriptor) const {
1038   D = getCanonicalDecl(D);
1039   assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
1040   if (Stack.back().first.empty())
1041       return DSAVarData();
1042   for (iterator I = std::next(Stack.back().first.rbegin(), 1),
1043                 E = Stack.back().first.rend();
1044        I != E; std::advance(I, 1)) {
1045     const DSAInfo &Data = I->SharingMap.lookup(D);
1046     if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
1047       continue;
1048     const ReductionData &ReductionData = I->ReductionMap.lookup(D);
1049     if (!ReductionData.ReductionOp ||
1050         !ReductionData.ReductionOp.is<const Expr *>())
1051       return DSAVarData();
1052     SR = ReductionData.ReductionRange;
1053     ReductionRef = ReductionData.ReductionOp.get<const Expr *>();
1054     assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
1055                                        "expression for the descriptor is not "
1056                                        "set.");
1057     TaskgroupDescriptor = I->TaskgroupReductionRef;
1058     return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
1059                       Data.PrivateCopy, I->DefaultAttrLoc);
1060   }
1061   return DSAVarData();
1062 }
1063 
1064 bool DSAStackTy::isOpenMPLocal(VarDecl *D, iterator Iter) const {
1065   D = D->getCanonicalDecl();
1066   if (!isStackEmpty()) {
1067     iterator I = Iter, E = Stack.back().first.rend();
1068     Scope *TopScope = nullptr;
1069     while (I != E && !isParallelOrTaskRegion(I->Directive) &&
1070            !isOpenMPTargetExecutionDirective(I->Directive))
1071       ++I;
1072     if (I == E)
1073       return false;
1074     TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
1075     Scope *CurScope = getCurScope();
1076     while (CurScope != TopScope && !CurScope->isDeclScope(D))
1077       CurScope = CurScope->getParent();
1078     return CurScope != TopScope;
1079   }
1080   return false;
1081 }
1082 
1083 const DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D,
1084                                                    bool FromParent) {
1085   D = getCanonicalDecl(D);
1086   DSAVarData DVar;
1087 
1088   auto *VD = dyn_cast<VarDecl>(D);
1089   auto TI = Threadprivates.find(D);
1090   if (TI != Threadprivates.end()) {
1091     DVar.RefExpr = TI->getSecond().RefExpr.getPointer();
1092     DVar.CKind = OMPC_threadprivate;
1093     return DVar;
1094   }
1095   if (VD && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
1096     DVar.RefExpr = buildDeclRefExpr(
1097         SemaRef, VD, D->getType().getNonReferenceType(),
1098         VD->getAttr<OMPThreadPrivateDeclAttr>()->getLocation());
1099     DVar.CKind = OMPC_threadprivate;
1100     addDSA(D, DVar.RefExpr, OMPC_threadprivate);
1101     return DVar;
1102   }
1103   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1104   // in a Construct, C/C++, predetermined, p.1]
1105   //  Variables appearing in threadprivate directives are threadprivate.
1106   if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
1107        !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
1108          SemaRef.getLangOpts().OpenMPUseTLS &&
1109          SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
1110       (VD && VD->getStorageClass() == SC_Register &&
1111        VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
1112     DVar.RefExpr = buildDeclRefExpr(
1113         SemaRef, VD, D->getType().getNonReferenceType(), D->getLocation());
1114     DVar.CKind = OMPC_threadprivate;
1115     addDSA(D, DVar.RefExpr, OMPC_threadprivate);
1116     return DVar;
1117   }
1118   if (SemaRef.getLangOpts().OpenMPCUDAMode && VD &&
1119       VD->isLocalVarDeclOrParm() && !isStackEmpty() &&
1120       !isLoopControlVariable(D).first) {
1121     iterator IterTarget =
1122         std::find_if(Stack.back().first.rbegin(), Stack.back().first.rend(),
1123                      [](const SharingMapTy &Data) {
1124                        return isOpenMPTargetExecutionDirective(Data.Directive);
1125                      });
1126     if (IterTarget != Stack.back().first.rend()) {
1127       iterator ParentIterTarget = std::next(IterTarget, 1);
1128       for (iterator Iter = Stack.back().first.rbegin();
1129            Iter != ParentIterTarget; std::advance(Iter, 1)) {
1130         if (isOpenMPLocal(VD, Iter)) {
1131           DVar.RefExpr =
1132               buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
1133                                D->getLocation());
1134           DVar.CKind = OMPC_threadprivate;
1135           return DVar;
1136         }
1137       }
1138       if (!isClauseParsingMode() || IterTarget != Stack.back().first.rbegin()) {
1139         auto DSAIter = IterTarget->SharingMap.find(D);
1140         if (DSAIter != IterTarget->SharingMap.end() &&
1141             isOpenMPPrivate(DSAIter->getSecond().Attributes)) {
1142           DVar.RefExpr = DSAIter->getSecond().RefExpr.getPointer();
1143           DVar.CKind = OMPC_threadprivate;
1144           return DVar;
1145         }
1146         iterator End = Stack.back().first.rend();
1147         if (!SemaRef.isOpenMPCapturedByRef(
1148                 D, std::distance(ParentIterTarget, End))) {
1149           DVar.RefExpr =
1150               buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
1151                                IterTarget->ConstructLoc);
1152           DVar.CKind = OMPC_threadprivate;
1153           return DVar;
1154         }
1155       }
1156     }
1157   }
1158 
1159   if (isStackEmpty())
1160     // Not in OpenMP execution region and top scope was already checked.
1161     return DVar;
1162 
1163   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1164   // in a Construct, C/C++, predetermined, p.4]
1165   //  Static data members are shared.
1166   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1167   // in a Construct, C/C++, predetermined, p.7]
1168   //  Variables with static storage duration that are declared in a scope
1169   //  inside the construct are shared.
1170   auto &&MatchesAlways = [](OpenMPDirectiveKind) { return true; };
1171   if (VD && VD->isStaticDataMember()) {
1172     DSAVarData DVarTemp = hasDSA(D, isOpenMPPrivate, MatchesAlways, FromParent);
1173     if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
1174       return DVar;
1175 
1176     DVar.CKind = OMPC_shared;
1177     return DVar;
1178   }
1179 
1180   QualType Type = D->getType().getNonReferenceType().getCanonicalType();
1181   bool IsConstant = Type.isConstant(SemaRef.getASTContext());
1182   Type = SemaRef.getASTContext().getBaseElementType(Type);
1183   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1184   // in a Construct, C/C++, predetermined, p.6]
1185   //  Variables with const qualified type having no mutable member are
1186   //  shared.
1187   const CXXRecordDecl *RD =
1188       SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
1189   if (const auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
1190     if (const ClassTemplateDecl *CTD = CTSD->getSpecializedTemplate())
1191       RD = CTD->getTemplatedDecl();
1192   if (IsConstant &&
1193       !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasDefinition() &&
1194         RD->hasMutableFields())) {
1195     // Variables with const-qualified type having no mutable member may be
1196     // listed in a firstprivate clause, even if they are static data members.
1197     DSAVarData DVarTemp = hasInnermostDSA(
1198         D,
1199         [](OpenMPClauseKind C) {
1200           return C == OMPC_firstprivate || C == OMPC_shared;
1201         },
1202         MatchesAlways, FromParent);
1203     if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
1204       return DVarTemp;
1205 
1206     DVar.CKind = OMPC_shared;
1207     return DVar;
1208   }
1209 
1210   // Explicitly specified attributes and local variables with predetermined
1211   // attributes.
1212   iterator I = Stack.back().first.rbegin();
1213   iterator EndI = Stack.back().first.rend();
1214   if (FromParent && I != EndI)
1215     std::advance(I, 1);
1216   auto It = I->SharingMap.find(D);
1217   if (It != I->SharingMap.end()) {
1218     const DSAInfo &Data = It->getSecond();
1219     DVar.RefExpr = Data.RefExpr.getPointer();
1220     DVar.PrivateCopy = Data.PrivateCopy;
1221     DVar.CKind = Data.Attributes;
1222     DVar.ImplicitDSALoc = I->DefaultAttrLoc;
1223     DVar.DKind = I->Directive;
1224   }
1225 
1226   return DVar;
1227 }
1228 
1229 const DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
1230                                                         bool FromParent) const {
1231   if (isStackEmpty()) {
1232     iterator I;
1233     return getDSA(I, D);
1234   }
1235   D = getCanonicalDecl(D);
1236   iterator StartI = Stack.back().first.rbegin();
1237   iterator EndI = Stack.back().first.rend();
1238   if (FromParent && StartI != EndI)
1239     std::advance(StartI, 1);
1240   return getDSA(StartI, D);
1241 }
1242 
1243 const DSAStackTy::DSAVarData
1244 DSAStackTy::hasDSA(ValueDecl *D,
1245                    const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
1246                    const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
1247                    bool FromParent) const {
1248   if (isStackEmpty())
1249     return {};
1250   D = getCanonicalDecl(D);
1251   iterator I = Stack.back().first.rbegin();
1252   iterator EndI = Stack.back().first.rend();
1253   if (FromParent && I != EndI)
1254     std::advance(I, 1);
1255   for (; I != EndI; std::advance(I, 1)) {
1256     if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive))
1257       continue;
1258     iterator NewI = I;
1259     DSAVarData DVar = getDSA(NewI, D);
1260     if (I == NewI && CPred(DVar.CKind))
1261       return DVar;
1262   }
1263   return {};
1264 }
1265 
1266 const DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
1267     ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
1268     const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
1269     bool FromParent) const {
1270   if (isStackEmpty())
1271     return {};
1272   D = getCanonicalDecl(D);
1273   iterator StartI = Stack.back().first.rbegin();
1274   iterator EndI = Stack.back().first.rend();
1275   if (FromParent && StartI != EndI)
1276     std::advance(StartI, 1);
1277   if (StartI == EndI || !DPred(StartI->Directive))
1278     return {};
1279   iterator NewI = StartI;
1280   DSAVarData DVar = getDSA(NewI, D);
1281   return (NewI == StartI && CPred(DVar.CKind)) ? DVar : DSAVarData();
1282 }
1283 
1284 bool DSAStackTy::hasExplicitDSA(
1285     const ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
1286     unsigned Level, bool NotLastprivate) const {
1287   if (isStackEmpty())
1288     return false;
1289   D = getCanonicalDecl(D);
1290   auto StartI = Stack.back().first.begin();
1291   auto EndI = Stack.back().first.end();
1292   if (std::distance(StartI, EndI) <= (int)Level)
1293     return false;
1294   std::advance(StartI, Level);
1295   auto I = StartI->SharingMap.find(D);
1296   if ((I != StartI->SharingMap.end()) &&
1297          I->getSecond().RefExpr.getPointer() &&
1298          CPred(I->getSecond().Attributes) &&
1299          (!NotLastprivate || !I->getSecond().RefExpr.getInt()))
1300     return true;
1301   // Check predetermined rules for the loop control variables.
1302   auto LI = StartI->LCVMap.find(D);
1303   if (LI != StartI->LCVMap.end())
1304     return CPred(OMPC_private);
1305   return false;
1306 }
1307 
1308 bool DSAStackTy::hasExplicitDirective(
1309     const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
1310     unsigned Level) const {
1311   if (isStackEmpty())
1312     return false;
1313   auto StartI = Stack.back().first.begin();
1314   auto EndI = Stack.back().first.end();
1315   if (std::distance(StartI, EndI) <= (int)Level)
1316     return false;
1317   std::advance(StartI, Level);
1318   return DPred(StartI->Directive);
1319 }
1320 
1321 bool DSAStackTy::hasDirective(
1322     const llvm::function_ref<bool(OpenMPDirectiveKind,
1323                                   const DeclarationNameInfo &, SourceLocation)>
1324         DPred,
1325     bool FromParent) const {
1326   // We look only in the enclosing region.
1327   if (isStackEmpty())
1328     return false;
1329   auto StartI = std::next(Stack.back().first.rbegin());
1330   auto EndI = Stack.back().first.rend();
1331   if (FromParent && StartI != EndI)
1332     StartI = std::next(StartI);
1333   for (auto I = StartI, EE = EndI; I != EE; ++I) {
1334     if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
1335       return true;
1336   }
1337   return false;
1338 }
1339 
1340 void Sema::InitDataSharingAttributesStack() {
1341   VarDataSharingAttributesStack = new DSAStackTy(*this);
1342 }
1343 
1344 #define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
1345 
1346 void Sema::pushOpenMPFunctionRegion() {
1347   DSAStack->pushFunction();
1348 }
1349 
1350 void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) {
1351   DSAStack->popFunction(OldFSI);
1352 }
1353 
1354 bool Sema::isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level) const {
1355   assert(LangOpts.OpenMP && "OpenMP is not allowed");
1356 
1357   ASTContext &Ctx = getASTContext();
1358   bool IsByRef = true;
1359 
1360   // Find the directive that is associated with the provided scope.
1361   D = cast<ValueDecl>(D->getCanonicalDecl());
1362   QualType Ty = D->getType();
1363 
1364   if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
1365     // This table summarizes how a given variable should be passed to the device
1366     // given its type and the clauses where it appears. This table is based on
1367     // the description in OpenMP 4.5 [2.10.4, target Construct] and
1368     // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
1369     //
1370     // =========================================================================
1371     // | type |  defaultmap   | pvt | first | is_device_ptr |    map   | res.  |
1372     // |      |(tofrom:scalar)|     |  pvt  |               |          |       |
1373     // =========================================================================
1374     // | scl  |               |     |       |       -       |          | bycopy|
1375     // | scl  |               |  -  |   x   |       -       |     -    | bycopy|
1376     // | scl  |               |  x  |   -   |       -       |     -    | null  |
1377     // | scl  |       x       |     |       |       -       |          | byref |
1378     // | scl  |       x       |  -  |   x   |       -       |     -    | bycopy|
1379     // | scl  |       x       |  x  |   -   |       -       |     -    | null  |
1380     // | scl  |               |  -  |   -   |       -       |     x    | byref |
1381     // | scl  |       x       |  -  |   -   |       -       |     x    | byref |
1382     //
1383     // | agg  |      n.a.     |     |       |       -       |          | byref |
1384     // | agg  |      n.a.     |  -  |   x   |       -       |     -    | byref |
1385     // | agg  |      n.a.     |  x  |   -   |       -       |     -    | null  |
1386     // | agg  |      n.a.     |  -  |   -   |       -       |     x    | byref |
1387     // | agg  |      n.a.     |  -  |   -   |       -       |    x[]   | byref |
1388     //
1389     // | ptr  |      n.a.     |     |       |       -       |          | bycopy|
1390     // | ptr  |      n.a.     |  -  |   x   |       -       |     -    | bycopy|
1391     // | ptr  |      n.a.     |  x  |   -   |       -       |     -    | null  |
1392     // | ptr  |      n.a.     |  -  |   -   |       -       |     x    | byref |
1393     // | ptr  |      n.a.     |  -  |   -   |       -       |    x[]   | bycopy|
1394     // | ptr  |      n.a.     |  -  |   -   |       x       |          | bycopy|
1395     // | ptr  |      n.a.     |  -  |   -   |       x       |     x    | bycopy|
1396     // | ptr  |      n.a.     |  -  |   -   |       x       |    x[]   | bycopy|
1397     // =========================================================================
1398     // Legend:
1399     //  scl - scalar
1400     //  ptr - pointer
1401     //  agg - aggregate
1402     //  x - applies
1403     //  - - invalid in this combination
1404     //  [] - mapped with an array section
1405     //  byref - should be mapped by reference
1406     //  byval - should be mapped by value
1407     //  null - initialize a local variable to null on the device
1408     //
1409     // Observations:
1410     //  - All scalar declarations that show up in a map clause have to be passed
1411     //    by reference, because they may have been mapped in the enclosing data
1412     //    environment.
1413     //  - If the scalar value does not fit the size of uintptr, it has to be
1414     //    passed by reference, regardless the result in the table above.
1415     //  - For pointers mapped by value that have either an implicit map or an
1416     //    array section, the runtime library may pass the NULL value to the
1417     //    device instead of the value passed to it by the compiler.
1418 
1419     if (Ty->isReferenceType())
1420       Ty = Ty->castAs<ReferenceType>()->getPointeeType();
1421 
1422     // Locate map clauses and see if the variable being captured is referred to
1423     // in any of those clauses. Here we only care about variables, not fields,
1424     // because fields are part of aggregates.
1425     bool IsVariableUsedInMapClause = false;
1426     bool IsVariableAssociatedWithSection = false;
1427 
1428     DSAStack->checkMappableExprComponentListsForDeclAtLevel(
1429         D, Level,
1430         [&IsVariableUsedInMapClause, &IsVariableAssociatedWithSection, D](
1431             OMPClauseMappableExprCommon::MappableExprComponentListRef
1432                 MapExprComponents,
1433             OpenMPClauseKind WhereFoundClauseKind) {
1434           // Only the map clause information influences how a variable is
1435           // captured. E.g. is_device_ptr does not require changing the default
1436           // behavior.
1437           if (WhereFoundClauseKind != OMPC_map)
1438             return false;
1439 
1440           auto EI = MapExprComponents.rbegin();
1441           auto EE = MapExprComponents.rend();
1442 
1443           assert(EI != EE && "Invalid map expression!");
1444 
1445           if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
1446             IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
1447 
1448           ++EI;
1449           if (EI == EE)
1450             return false;
1451 
1452           if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
1453               isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
1454               isa<MemberExpr>(EI->getAssociatedExpression())) {
1455             IsVariableAssociatedWithSection = true;
1456             // There is nothing more we need to know about this variable.
1457             return true;
1458           }
1459 
1460           // Keep looking for more map info.
1461           return false;
1462         });
1463 
1464     if (IsVariableUsedInMapClause) {
1465       // If variable is identified in a map clause it is always captured by
1466       // reference except if it is a pointer that is dereferenced somehow.
1467       IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
1468     } else {
1469       // By default, all the data that has a scalar type is mapped by copy
1470       // (except for reduction variables).
1471       IsByRef =
1472           (DSAStack->isForceCaptureByReferenceInTargetExecutable() &&
1473            !Ty->isAnyPointerType()) ||
1474           !Ty->isScalarType() ||
1475           DSAStack->getDefaultDMAAtLevel(Level) == DMA_tofrom_scalar ||
1476           DSAStack->hasExplicitDSA(
1477               D, [](OpenMPClauseKind K) { return K == OMPC_reduction; }, Level);
1478     }
1479   }
1480 
1481   if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
1482     IsByRef =
1483         ((DSAStack->isForceCaptureByReferenceInTargetExecutable() &&
1484           !Ty->isAnyPointerType()) ||
1485          !DSAStack->hasExplicitDSA(
1486              D,
1487              [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; },
1488              Level, /*NotLastprivate=*/true)) &&
1489         // If the variable is artificial and must be captured by value - try to
1490         // capture by value.
1491         !(isa<OMPCapturedExprDecl>(D) && !D->hasAttr<OMPCaptureNoInitAttr>() &&
1492           !cast<OMPCapturedExprDecl>(D)->getInit()->isGLValue());
1493   }
1494 
1495   // When passing data by copy, we need to make sure it fits the uintptr size
1496   // and alignment, because the runtime library only deals with uintptr types.
1497   // If it does not fit the uintptr size, we need to pass the data by reference
1498   // instead.
1499   if (!IsByRef &&
1500       (Ctx.getTypeSizeInChars(Ty) >
1501            Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
1502        Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
1503     IsByRef = true;
1504   }
1505 
1506   return IsByRef;
1507 }
1508 
1509 unsigned Sema::getOpenMPNestingLevel() const {
1510   assert(getLangOpts().OpenMP);
1511   return DSAStack->getNestingLevel();
1512 }
1513 
1514 bool Sema::isInOpenMPTargetExecutionDirective() const {
1515   return (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) &&
1516           !DSAStack->isClauseParsingMode()) ||
1517          DSAStack->hasDirective(
1518              [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
1519                 SourceLocation) -> bool {
1520                return isOpenMPTargetExecutionDirective(K);
1521              },
1522              false);
1523 }
1524 
1525 VarDecl *Sema::isOpenMPCapturedDecl(ValueDecl *D) {
1526   assert(LangOpts.OpenMP && "OpenMP is not allowed");
1527   D = getCanonicalDecl(D);
1528 
1529   // If we are attempting to capture a global variable in a directive with
1530   // 'target' we return true so that this global is also mapped to the device.
1531   //
1532   auto *VD = dyn_cast<VarDecl>(D);
1533   if (VD && !VD->hasLocalStorage()) {
1534     if (isInOpenMPDeclareTargetContext() &&
1535         (getCurCapturedRegion() || getCurBlock() || getCurLambda())) {
1536       // Try to mark variable as declare target if it is used in capturing
1537       // regions.
1538       if (!OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
1539         checkDeclIsAllowedInOpenMPTarget(nullptr, VD);
1540       return nullptr;
1541     } else if (isInOpenMPTargetExecutionDirective()) {
1542       // If the declaration is enclosed in a 'declare target' directive,
1543       // then it should not be captured.
1544       //
1545       if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
1546         return nullptr;
1547       return VD;
1548     }
1549   }
1550   // Capture variables captured by reference in lambdas for target-based
1551   // directives.
1552   if (VD && !DSAStack->isClauseParsingMode()) {
1553     if (const auto *RD = VD->getType()
1554                              .getCanonicalType()
1555                              .getNonReferenceType()
1556                              ->getAsCXXRecordDecl()) {
1557       bool SavedForceCaptureByReferenceInTargetExecutable =
1558           DSAStack->isForceCaptureByReferenceInTargetExecutable();
1559       DSAStack->setForceCaptureByReferenceInTargetExecutable(/*V=*/true);
1560       if (RD->isLambda()) {
1561         llvm::DenseMap<const VarDecl *, FieldDecl *> Captures;
1562         FieldDecl *ThisCapture;
1563         RD->getCaptureFields(Captures, ThisCapture);
1564         for (const LambdaCapture &LC : RD->captures()) {
1565           if (LC.getCaptureKind() == LCK_ByRef) {
1566             VarDecl *VD = LC.getCapturedVar();
1567             DeclContext *VDC = VD->getDeclContext();
1568             if (!VDC->Encloses(CurContext))
1569               continue;
1570             DSAStackTy::DSAVarData DVarPrivate =
1571                 DSAStack->getTopDSA(VD, /*FromParent=*/false);
1572             // Do not capture already captured variables.
1573             if (!OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD) &&
1574                 DVarPrivate.CKind == OMPC_unknown &&
1575                 !DSAStack->checkMappableExprComponentListsForDecl(
1576                     D, /*CurrentRegionOnly=*/true,
1577                     [](OMPClauseMappableExprCommon::
1578                            MappableExprComponentListRef,
1579                        OpenMPClauseKind) { return true; }))
1580               MarkVariableReferenced(LC.getLocation(), LC.getCapturedVar());
1581           } else if (LC.getCaptureKind() == LCK_This) {
1582             QualType ThisTy = getCurrentThisType();
1583             if (!ThisTy.isNull() &&
1584                 Context.typesAreCompatible(ThisTy, ThisCapture->getType()))
1585               CheckCXXThisCapture(LC.getLocation());
1586           }
1587         }
1588       }
1589       DSAStack->setForceCaptureByReferenceInTargetExecutable(
1590           SavedForceCaptureByReferenceInTargetExecutable);
1591     }
1592   }
1593 
1594   if (DSAStack->getCurrentDirective() != OMPD_unknown &&
1595       (!DSAStack->isClauseParsingMode() ||
1596        DSAStack->getParentDirective() != OMPD_unknown)) {
1597     auto &&Info = DSAStack->isLoopControlVariable(D);
1598     if (Info.first ||
1599         (VD && VD->hasLocalStorage() &&
1600          isParallelOrTaskRegion(DSAStack->getCurrentDirective())) ||
1601         (VD && DSAStack->isForceVarCapturing()))
1602       return VD ? VD : Info.second;
1603     DSAStackTy::DSAVarData DVarPrivate =
1604         DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
1605     if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
1606       return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
1607     DVarPrivate = DSAStack->hasDSA(D, isOpenMPPrivate,
1608                                    [](OpenMPDirectiveKind) { return true; },
1609                                    DSAStack->isClauseParsingMode());
1610     if (DVarPrivate.CKind != OMPC_unknown)
1611       return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
1612   }
1613   return nullptr;
1614 }
1615 
1616 void Sema::adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex,
1617                                         unsigned Level) const {
1618   SmallVector<OpenMPDirectiveKind, 4> Regions;
1619   getOpenMPCaptureRegions(Regions, DSAStack->getDirective(Level));
1620   FunctionScopesIndex -= Regions.size();
1621 }
1622 
1623 void Sema::startOpenMPLoop() {
1624   assert(LangOpts.OpenMP && "OpenMP must be enabled.");
1625   if (isOpenMPLoopDirective(DSAStack->getCurrentDirective()))
1626     DSAStack->loopInit();
1627 }
1628 
1629 bool Sema::isOpenMPPrivateDecl(const ValueDecl *D, unsigned Level) const {
1630   assert(LangOpts.OpenMP && "OpenMP is not allowed");
1631   if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
1632     if (DSAStack->getAssociatedLoops() > 0 &&
1633         !DSAStack->isLoopStarted()) {
1634       DSAStack->resetPossibleLoopCounter(D);
1635       DSAStack->loopStart();
1636       return true;
1637     }
1638     if ((DSAStack->getPossiblyLoopCunter() == D->getCanonicalDecl() ||
1639          DSAStack->isLoopControlVariable(D).first) &&
1640         !DSAStack->hasExplicitDSA(
1641             D, [](OpenMPClauseKind K) { return K != OMPC_private; }, Level) &&
1642         !isOpenMPSimdDirective(DSAStack->getCurrentDirective()))
1643       return true;
1644   }
1645   return DSAStack->hasExplicitDSA(
1646              D, [](OpenMPClauseKind K) { return K == OMPC_private; }, Level) ||
1647          (DSAStack->isClauseParsingMode() &&
1648           DSAStack->getClauseParsingMode() == OMPC_private) ||
1649          // Consider taskgroup reduction descriptor variable a private to avoid
1650          // possible capture in the region.
1651          (DSAStack->hasExplicitDirective(
1652               [](OpenMPDirectiveKind K) { return K == OMPD_taskgroup; },
1653               Level) &&
1654           DSAStack->isTaskgroupReductionRef(D, Level));
1655 }
1656 
1657 void Sema::setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D,
1658                                 unsigned Level) {
1659   assert(LangOpts.OpenMP && "OpenMP is not allowed");
1660   D = getCanonicalDecl(D);
1661   OpenMPClauseKind OMPC = OMPC_unknown;
1662   for (unsigned I = DSAStack->getNestingLevel() + 1; I > Level; --I) {
1663     const unsigned NewLevel = I - 1;
1664     if (DSAStack->hasExplicitDSA(D,
1665                                  [&OMPC](const OpenMPClauseKind K) {
1666                                    if (isOpenMPPrivate(K)) {
1667                                      OMPC = K;
1668                                      return true;
1669                                    }
1670                                    return false;
1671                                  },
1672                                  NewLevel))
1673       break;
1674     if (DSAStack->checkMappableExprComponentListsForDeclAtLevel(
1675             D, NewLevel,
1676             [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
1677                OpenMPClauseKind) { return true; })) {
1678       OMPC = OMPC_map;
1679       break;
1680     }
1681     if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
1682                                        NewLevel)) {
1683       OMPC = OMPC_map;
1684       if (D->getType()->isScalarType() &&
1685           DSAStack->getDefaultDMAAtLevel(NewLevel) !=
1686               DefaultMapAttributes::DMA_tofrom_scalar)
1687         OMPC = OMPC_firstprivate;
1688       break;
1689     }
1690   }
1691   if (OMPC != OMPC_unknown)
1692     FD->addAttr(OMPCaptureKindAttr::CreateImplicit(Context, OMPC));
1693 }
1694 
1695 bool Sema::isOpenMPTargetCapturedDecl(const ValueDecl *D,
1696                                       unsigned Level) const {
1697   assert(LangOpts.OpenMP && "OpenMP is not allowed");
1698   // Return true if the current level is no longer enclosed in a target region.
1699 
1700   const auto *VD = dyn_cast<VarDecl>(D);
1701   return VD && !VD->hasLocalStorage() &&
1702          DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
1703                                         Level);
1704 }
1705 
1706 void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
1707 
1708 void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
1709                                const DeclarationNameInfo &DirName,
1710                                Scope *CurScope, SourceLocation Loc) {
1711   DSAStack->push(DKind, DirName, CurScope, Loc);
1712   PushExpressionEvaluationContext(
1713       ExpressionEvaluationContext::PotentiallyEvaluated);
1714 }
1715 
1716 void Sema::StartOpenMPClause(OpenMPClauseKind K) {
1717   DSAStack->setClauseParsingMode(K);
1718 }
1719 
1720 void Sema::EndOpenMPClause() {
1721   DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
1722 }
1723 
1724 void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
1725   // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
1726   //  A variable of class type (or array thereof) that appears in a lastprivate
1727   //  clause requires an accessible, unambiguous default constructor for the
1728   //  class type, unless the list item is also specified in a firstprivate
1729   //  clause.
1730   if (const auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
1731     for (OMPClause *C : D->clauses()) {
1732       if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
1733         SmallVector<Expr *, 8> PrivateCopies;
1734         for (Expr *DE : Clause->varlists()) {
1735           if (DE->isValueDependent() || DE->isTypeDependent()) {
1736             PrivateCopies.push_back(nullptr);
1737             continue;
1738           }
1739           auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
1740           auto *VD = cast<VarDecl>(DRE->getDecl());
1741           QualType Type = VD->getType().getNonReferenceType();
1742           const DSAStackTy::DSAVarData DVar =
1743               DSAStack->getTopDSA(VD, /*FromParent=*/false);
1744           if (DVar.CKind == OMPC_lastprivate) {
1745             // Generate helper private variable and initialize it with the
1746             // default value. The address of the original variable is replaced
1747             // by the address of the new private variable in CodeGen. This new
1748             // variable is not added to IdResolver, so the code in the OpenMP
1749             // region uses original variable for proper diagnostics.
1750             VarDecl *VDPrivate = buildVarDecl(
1751                 *this, DE->getExprLoc(), Type.getUnqualifiedType(),
1752                 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr, DRE);
1753             ActOnUninitializedDecl(VDPrivate);
1754             if (VDPrivate->isInvalidDecl())
1755               continue;
1756             PrivateCopies.push_back(buildDeclRefExpr(
1757                 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
1758           } else {
1759             // The variable is also a firstprivate, so initialization sequence
1760             // for private copy is generated already.
1761             PrivateCopies.push_back(nullptr);
1762           }
1763         }
1764         // Set initializers to private copies if no errors were found.
1765         if (PrivateCopies.size() == Clause->varlist_size())
1766           Clause->setPrivateCopies(PrivateCopies);
1767       }
1768     }
1769   }
1770 
1771   DSAStack->pop();
1772   DiscardCleanupsInEvaluationContext();
1773   PopExpressionEvaluationContext();
1774 }
1775 
1776 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
1777                                      Expr *NumIterations, Sema &SemaRef,
1778                                      Scope *S, DSAStackTy *Stack);
1779 
1780 namespace {
1781 
1782 class VarDeclFilterCCC final : public CorrectionCandidateCallback {
1783 private:
1784   Sema &SemaRef;
1785 
1786 public:
1787   explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
1788   bool ValidateCandidate(const TypoCorrection &Candidate) override {
1789     NamedDecl *ND = Candidate.getCorrectionDecl();
1790     if (const auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
1791       return VD->hasGlobalStorage() &&
1792              SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1793                                    SemaRef.getCurScope());
1794     }
1795     return false;
1796   }
1797 };
1798 
1799 class VarOrFuncDeclFilterCCC final : public CorrectionCandidateCallback {
1800 private:
1801   Sema &SemaRef;
1802 
1803 public:
1804   explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
1805   bool ValidateCandidate(const TypoCorrection &Candidate) override {
1806     NamedDecl *ND = Candidate.getCorrectionDecl();
1807     if (ND && (isa<VarDecl>(ND) || isa<FunctionDecl>(ND))) {
1808       return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1809                                    SemaRef.getCurScope());
1810     }
1811     return false;
1812   }
1813 };
1814 
1815 } // namespace
1816 
1817 ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
1818                                          CXXScopeSpec &ScopeSpec,
1819                                          const DeclarationNameInfo &Id) {
1820   LookupResult Lookup(*this, Id, LookupOrdinaryName);
1821   LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
1822 
1823   if (Lookup.isAmbiguous())
1824     return ExprError();
1825 
1826   VarDecl *VD;
1827   if (!Lookup.isSingleResult()) {
1828     if (TypoCorrection Corrected = CorrectTypo(
1829             Id, LookupOrdinaryName, CurScope, nullptr,
1830             llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) {
1831       diagnoseTypo(Corrected,
1832                    PDiag(Lookup.empty()
1833                              ? diag::err_undeclared_var_use_suggest
1834                              : diag::err_omp_expected_var_arg_suggest)
1835                        << Id.getName());
1836       VD = Corrected.getCorrectionDeclAs<VarDecl>();
1837     } else {
1838       Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
1839                                        : diag::err_omp_expected_var_arg)
1840           << Id.getName();
1841       return ExprError();
1842     }
1843   } else if (!(VD = Lookup.getAsSingle<VarDecl>())) {
1844     Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
1845     Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
1846     return ExprError();
1847   }
1848   Lookup.suppressDiagnostics();
1849 
1850   // OpenMP [2.9.2, Syntax, C/C++]
1851   //   Variables must be file-scope, namespace-scope, or static block-scope.
1852   if (!VD->hasGlobalStorage()) {
1853     Diag(Id.getLoc(), diag::err_omp_global_var_arg)
1854         << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal();
1855     bool IsDecl =
1856         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1857     Diag(VD->getLocation(),
1858          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1859         << VD;
1860     return ExprError();
1861   }
1862 
1863   VarDecl *CanonicalVD = VD->getCanonicalDecl();
1864   NamedDecl *ND = CanonicalVD;
1865   // OpenMP [2.9.2, Restrictions, C/C++, p.2]
1866   //   A threadprivate directive for file-scope variables must appear outside
1867   //   any definition or declaration.
1868   if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
1869       !getCurLexicalContext()->isTranslationUnit()) {
1870     Diag(Id.getLoc(), diag::err_omp_var_scope)
1871         << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1872     bool IsDecl =
1873         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1874     Diag(VD->getLocation(),
1875          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1876         << VD;
1877     return ExprError();
1878   }
1879   // OpenMP [2.9.2, Restrictions, C/C++, p.3]
1880   //   A threadprivate directive for static class member variables must appear
1881   //   in the class definition, in the same scope in which the member
1882   //   variables are declared.
1883   if (CanonicalVD->isStaticDataMember() &&
1884       !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
1885     Diag(Id.getLoc(), diag::err_omp_var_scope)
1886         << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1887     bool IsDecl =
1888         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1889     Diag(VD->getLocation(),
1890          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1891         << VD;
1892     return ExprError();
1893   }
1894   // OpenMP [2.9.2, Restrictions, C/C++, p.4]
1895   //   A threadprivate directive for namespace-scope variables must appear
1896   //   outside any definition or declaration other than the namespace
1897   //   definition itself.
1898   if (CanonicalVD->getDeclContext()->isNamespace() &&
1899       (!getCurLexicalContext()->isFileContext() ||
1900        !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
1901     Diag(Id.getLoc(), diag::err_omp_var_scope)
1902         << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1903     bool IsDecl =
1904         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1905     Diag(VD->getLocation(),
1906          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1907         << VD;
1908     return ExprError();
1909   }
1910   // OpenMP [2.9.2, Restrictions, C/C++, p.6]
1911   //   A threadprivate directive for static block-scope variables must appear
1912   //   in the scope of the variable and not in a nested scope.
1913   if (CanonicalVD->isStaticLocal() && CurScope &&
1914       !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
1915     Diag(Id.getLoc(), diag::err_omp_var_scope)
1916         << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1917     bool IsDecl =
1918         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1919     Diag(VD->getLocation(),
1920          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1921         << VD;
1922     return ExprError();
1923   }
1924 
1925   // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
1926   //   A threadprivate directive must lexically precede all references to any
1927   //   of the variables in its list.
1928   if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) {
1929     Diag(Id.getLoc(), diag::err_omp_var_used)
1930         << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1931     return ExprError();
1932   }
1933 
1934   QualType ExprType = VD->getType().getNonReferenceType();
1935   return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
1936                              SourceLocation(), VD,
1937                              /*RefersToEnclosingVariableOrCapture=*/false,
1938                              Id.getLoc(), ExprType, VK_LValue);
1939 }
1940 
1941 Sema::DeclGroupPtrTy
1942 Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
1943                                         ArrayRef<Expr *> VarList) {
1944   if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
1945     CurContext->addDecl(D);
1946     return DeclGroupPtrTy::make(DeclGroupRef(D));
1947   }
1948   return nullptr;
1949 }
1950 
1951 namespace {
1952 class LocalVarRefChecker final
1953     : public ConstStmtVisitor<LocalVarRefChecker, bool> {
1954   Sema &SemaRef;
1955 
1956 public:
1957   bool VisitDeclRefExpr(const DeclRefExpr *E) {
1958     if (const auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
1959       if (VD->hasLocalStorage()) {
1960         SemaRef.Diag(E->getBeginLoc(),
1961                      diag::err_omp_local_var_in_threadprivate_init)
1962             << E->getSourceRange();
1963         SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
1964             << VD << VD->getSourceRange();
1965         return true;
1966       }
1967     }
1968     return false;
1969   }
1970   bool VisitStmt(const Stmt *S) {
1971     for (const Stmt *Child : S->children()) {
1972       if (Child && Visit(Child))
1973         return true;
1974     }
1975     return false;
1976   }
1977   explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
1978 };
1979 } // namespace
1980 
1981 OMPThreadPrivateDecl *
1982 Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
1983   SmallVector<Expr *, 8> Vars;
1984   for (Expr *RefExpr : VarList) {
1985     auto *DE = cast<DeclRefExpr>(RefExpr);
1986     auto *VD = cast<VarDecl>(DE->getDecl());
1987     SourceLocation ILoc = DE->getExprLoc();
1988 
1989     // Mark variable as used.
1990     VD->setReferenced();
1991     VD->markUsed(Context);
1992 
1993     QualType QType = VD->getType();
1994     if (QType->isDependentType() || QType->isInstantiationDependentType()) {
1995       // It will be analyzed later.
1996       Vars.push_back(DE);
1997       continue;
1998     }
1999 
2000     // OpenMP [2.9.2, Restrictions, C/C++, p.10]
2001     //   A threadprivate variable must not have an incomplete type.
2002     if (RequireCompleteType(ILoc, VD->getType(),
2003                             diag::err_omp_threadprivate_incomplete_type)) {
2004       continue;
2005     }
2006 
2007     // OpenMP [2.9.2, Restrictions, C/C++, p.10]
2008     //   A threadprivate variable must not have a reference type.
2009     if (VD->getType()->isReferenceType()) {
2010       Diag(ILoc, diag::err_omp_ref_type_arg)
2011           << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
2012       bool IsDecl =
2013           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2014       Diag(VD->getLocation(),
2015            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2016           << VD;
2017       continue;
2018     }
2019 
2020     // Check if this is a TLS variable. If TLS is not being supported, produce
2021     // the corresponding diagnostic.
2022     if ((VD->getTLSKind() != VarDecl::TLS_None &&
2023          !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
2024            getLangOpts().OpenMPUseTLS &&
2025            getASTContext().getTargetInfo().isTLSSupported())) ||
2026         (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
2027          !VD->isLocalVarDecl())) {
2028       Diag(ILoc, diag::err_omp_var_thread_local)
2029           << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
2030       bool IsDecl =
2031           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2032       Diag(VD->getLocation(),
2033            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2034           << VD;
2035       continue;
2036     }
2037 
2038     // Check if initial value of threadprivate variable reference variable with
2039     // local storage (it is not supported by runtime).
2040     if (const Expr *Init = VD->getAnyInitializer()) {
2041       LocalVarRefChecker Checker(*this);
2042       if (Checker.Visit(Init))
2043         continue;
2044     }
2045 
2046     Vars.push_back(RefExpr);
2047     DSAStack->addDSA(VD, DE, OMPC_threadprivate);
2048     VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
2049         Context, SourceRange(Loc, Loc)));
2050     if (ASTMutationListener *ML = Context.getASTMutationListener())
2051       ML->DeclarationMarkedOpenMPThreadPrivate(VD);
2052   }
2053   OMPThreadPrivateDecl *D = nullptr;
2054   if (!Vars.empty()) {
2055     D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
2056                                      Vars);
2057     D->setAccess(AS_public);
2058   }
2059   return D;
2060 }
2061 
2062 Sema::DeclGroupPtrTy
2063 Sema::ActOnOpenMPRequiresDirective(SourceLocation Loc,
2064                                    ArrayRef<OMPClause *> ClauseList) {
2065   OMPRequiresDecl *D = nullptr;
2066   if (!CurContext->isFileContext()) {
2067     Diag(Loc, diag::err_omp_invalid_scope) << "requires";
2068   } else {
2069     D = CheckOMPRequiresDecl(Loc, ClauseList);
2070     if (D) {
2071       CurContext->addDecl(D);
2072       DSAStack->addRequiresDecl(D);
2073     }
2074   }
2075   return DeclGroupPtrTy::make(DeclGroupRef(D));
2076 }
2077 
2078 OMPRequiresDecl *Sema::CheckOMPRequiresDecl(SourceLocation Loc,
2079                                             ArrayRef<OMPClause *> ClauseList) {
2080   if (!DSAStack->hasDuplicateRequiresClause(ClauseList))
2081     return OMPRequiresDecl::Create(Context, getCurLexicalContext(), Loc,
2082                                    ClauseList);
2083   return nullptr;
2084 }
2085 
2086 static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack,
2087                               const ValueDecl *D,
2088                               const DSAStackTy::DSAVarData &DVar,
2089                               bool IsLoopIterVar = false) {
2090   if (DVar.RefExpr) {
2091     SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
2092         << getOpenMPClauseName(DVar.CKind);
2093     return;
2094   }
2095   enum {
2096     PDSA_StaticMemberShared,
2097     PDSA_StaticLocalVarShared,
2098     PDSA_LoopIterVarPrivate,
2099     PDSA_LoopIterVarLinear,
2100     PDSA_LoopIterVarLastprivate,
2101     PDSA_ConstVarShared,
2102     PDSA_GlobalVarShared,
2103     PDSA_TaskVarFirstprivate,
2104     PDSA_LocalVarPrivate,
2105     PDSA_Implicit
2106   } Reason = PDSA_Implicit;
2107   bool ReportHint = false;
2108   auto ReportLoc = D->getLocation();
2109   auto *VD = dyn_cast<VarDecl>(D);
2110   if (IsLoopIterVar) {
2111     if (DVar.CKind == OMPC_private)
2112       Reason = PDSA_LoopIterVarPrivate;
2113     else if (DVar.CKind == OMPC_lastprivate)
2114       Reason = PDSA_LoopIterVarLastprivate;
2115     else
2116       Reason = PDSA_LoopIterVarLinear;
2117   } else if (isOpenMPTaskingDirective(DVar.DKind) &&
2118              DVar.CKind == OMPC_firstprivate) {
2119     Reason = PDSA_TaskVarFirstprivate;
2120     ReportLoc = DVar.ImplicitDSALoc;
2121   } else if (VD && VD->isStaticLocal())
2122     Reason = PDSA_StaticLocalVarShared;
2123   else if (VD && VD->isStaticDataMember())
2124     Reason = PDSA_StaticMemberShared;
2125   else if (VD && VD->isFileVarDecl())
2126     Reason = PDSA_GlobalVarShared;
2127   else if (D->getType().isConstant(SemaRef.getASTContext()))
2128     Reason = PDSA_ConstVarShared;
2129   else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
2130     ReportHint = true;
2131     Reason = PDSA_LocalVarPrivate;
2132   }
2133   if (Reason != PDSA_Implicit) {
2134     SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
2135         << Reason << ReportHint
2136         << getOpenMPDirectiveName(Stack->getCurrentDirective());
2137   } else if (DVar.ImplicitDSALoc.isValid()) {
2138     SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
2139         << getOpenMPClauseName(DVar.CKind);
2140   }
2141 }
2142 
2143 namespace {
2144 class DSAAttrChecker final : public StmtVisitor<DSAAttrChecker, void> {
2145   DSAStackTy *Stack;
2146   Sema &SemaRef;
2147   bool ErrorFound = false;
2148   CapturedStmt *CS = nullptr;
2149   llvm::SmallVector<Expr *, 4> ImplicitFirstprivate;
2150   llvm::SmallVector<Expr *, 4> ImplicitMap;
2151   Sema::VarsWithInheritedDSAType VarsWithInheritedDSA;
2152   llvm::SmallDenseSet<const ValueDecl *, 4> ImplicitDeclarations;
2153 
2154   void VisitSubCaptures(OMPExecutableDirective *S) {
2155     // Check implicitly captured variables.
2156     if (!S->hasAssociatedStmt() || !S->getAssociatedStmt())
2157       return;
2158     for (const CapturedStmt::Capture &Cap :
2159          S->getInnermostCapturedStmt()->captures()) {
2160       if (!Cap.capturesVariable())
2161         continue;
2162       VarDecl *VD = Cap.getCapturedVar();
2163       // Do not try to map the variable if it or its sub-component was mapped
2164       // already.
2165       if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
2166           Stack->checkMappableExprComponentListsForDecl(
2167               VD, /*CurrentRegionOnly=*/true,
2168               [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
2169                  OpenMPClauseKind) { return true; }))
2170         continue;
2171       DeclRefExpr *DRE = buildDeclRefExpr(
2172           SemaRef, VD, VD->getType().getNonLValueExprType(SemaRef.Context),
2173           Cap.getLocation(), /*RefersToCapture=*/true);
2174       Visit(DRE);
2175     }
2176   }
2177 
2178 public:
2179   void VisitDeclRefExpr(DeclRefExpr *E) {
2180     if (E->isTypeDependent() || E->isValueDependent() ||
2181         E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
2182       return;
2183     if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
2184       VD = VD->getCanonicalDecl();
2185       // Skip internally declared variables.
2186       if (VD->hasLocalStorage() && !CS->capturesVariable(VD))
2187         return;
2188 
2189       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
2190       // Check if the variable has explicit DSA set and stop analysis if it so.
2191       if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second)
2192         return;
2193 
2194       // Skip internally declared static variables.
2195       llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
2196           OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
2197       if (VD->hasGlobalStorage() && !CS->capturesVariable(VD) &&
2198           (!Res || *Res != OMPDeclareTargetDeclAttr::MT_Link))
2199         return;
2200 
2201       SourceLocation ELoc = E->getExprLoc();
2202       OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
2203       // The default(none) clause requires that each variable that is referenced
2204       // in the construct, and does not have a predetermined data-sharing
2205       // attribute, must have its data-sharing attribute explicitly determined
2206       // by being listed in a data-sharing attribute clause.
2207       if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
2208           isParallelOrTaskRegion(DKind) &&
2209           VarsWithInheritedDSA.count(VD) == 0) {
2210         VarsWithInheritedDSA[VD] = E;
2211         return;
2212       }
2213 
2214       if (isOpenMPTargetExecutionDirective(DKind) &&
2215           !Stack->isLoopControlVariable(VD).first) {
2216         if (!Stack->checkMappableExprComponentListsForDecl(
2217                 VD, /*CurrentRegionOnly=*/true,
2218                 [](OMPClauseMappableExprCommon::MappableExprComponentListRef
2219                        StackComponents,
2220                    OpenMPClauseKind) {
2221                   // Variable is used if it has been marked as an array, array
2222                   // section or the variable iself.
2223                   return StackComponents.size() == 1 ||
2224                          std::all_of(
2225                              std::next(StackComponents.rbegin()),
2226                              StackComponents.rend(),
2227                              [](const OMPClauseMappableExprCommon::
2228                                     MappableComponent &MC) {
2229                                return MC.getAssociatedDeclaration() ==
2230                                           nullptr &&
2231                                       (isa<OMPArraySectionExpr>(
2232                                            MC.getAssociatedExpression()) ||
2233                                        isa<ArraySubscriptExpr>(
2234                                            MC.getAssociatedExpression()));
2235                              });
2236                 })) {
2237           bool IsFirstprivate = false;
2238           // By default lambdas are captured as firstprivates.
2239           if (const auto *RD =
2240                   VD->getType().getNonReferenceType()->getAsCXXRecordDecl())
2241             IsFirstprivate = RD->isLambda();
2242           IsFirstprivate =
2243               IsFirstprivate ||
2244               (VD->getType().getNonReferenceType()->isScalarType() &&
2245                Stack->getDefaultDMA() != DMA_tofrom_scalar && !Res);
2246           if (IsFirstprivate)
2247             ImplicitFirstprivate.emplace_back(E);
2248           else
2249             ImplicitMap.emplace_back(E);
2250           return;
2251         }
2252       }
2253 
2254       // OpenMP [2.9.3.6, Restrictions, p.2]
2255       //  A list item that appears in a reduction clause of the innermost
2256       //  enclosing worksharing or parallel construct may not be accessed in an
2257       //  explicit task.
2258       DVar = Stack->hasInnermostDSA(
2259           VD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
2260           [](OpenMPDirectiveKind K) {
2261             return isOpenMPParallelDirective(K) ||
2262                    isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
2263           },
2264           /*FromParent=*/true);
2265       if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
2266         ErrorFound = true;
2267         SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
2268         reportOriginalDsa(SemaRef, Stack, VD, DVar);
2269         return;
2270       }
2271 
2272       // Define implicit data-sharing attributes for task.
2273       DVar = Stack->getImplicitDSA(VD, /*FromParent=*/false);
2274       if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
2275           !Stack->isLoopControlVariable(VD).first)
2276         ImplicitFirstprivate.push_back(E);
2277     }
2278   }
2279   void VisitMemberExpr(MemberExpr *E) {
2280     if (E->isTypeDependent() || E->isValueDependent() ||
2281         E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
2282       return;
2283     auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
2284     OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
2285     if (auto *TE = dyn_cast<CXXThisExpr>(E->getBase()->IgnoreParens())) {
2286       if (!FD)
2287         return;
2288       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(FD, /*FromParent=*/false);
2289       // Check if the variable has explicit DSA set and stop analysis if it
2290       // so.
2291       if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second)
2292         return;
2293 
2294       if (isOpenMPTargetExecutionDirective(DKind) &&
2295           !Stack->isLoopControlVariable(FD).first &&
2296           !Stack->checkMappableExprComponentListsForDecl(
2297               FD, /*CurrentRegionOnly=*/true,
2298               [](OMPClauseMappableExprCommon::MappableExprComponentListRef
2299                      StackComponents,
2300                  OpenMPClauseKind) {
2301                 return isa<CXXThisExpr>(
2302                     cast<MemberExpr>(
2303                         StackComponents.back().getAssociatedExpression())
2304                         ->getBase()
2305                         ->IgnoreParens());
2306               })) {
2307         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
2308         //  A bit-field cannot appear in a map clause.
2309         //
2310         if (FD->isBitField())
2311           return;
2312 
2313         // Check to see if the member expression is referencing a class that
2314         // has already been explicitly mapped
2315         if (Stack->isClassPreviouslyMapped(TE->getType()))
2316           return;
2317 
2318         ImplicitMap.emplace_back(E);
2319         return;
2320       }
2321 
2322       SourceLocation ELoc = E->getExprLoc();
2323       // OpenMP [2.9.3.6, Restrictions, p.2]
2324       //  A list item that appears in a reduction clause of the innermost
2325       //  enclosing worksharing or parallel construct may not be accessed in
2326       //  an  explicit task.
2327       DVar = Stack->hasInnermostDSA(
2328           FD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
2329           [](OpenMPDirectiveKind K) {
2330             return isOpenMPParallelDirective(K) ||
2331                    isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
2332           },
2333           /*FromParent=*/true);
2334       if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
2335         ErrorFound = true;
2336         SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
2337         reportOriginalDsa(SemaRef, Stack, FD, DVar);
2338         return;
2339       }
2340 
2341       // Define implicit data-sharing attributes for task.
2342       DVar = Stack->getImplicitDSA(FD, /*FromParent=*/false);
2343       if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
2344           !Stack->isLoopControlVariable(FD).first) {
2345         // Check if there is a captured expression for the current field in the
2346         // region. Do not mark it as firstprivate unless there is no captured
2347         // expression.
2348         // TODO: try to make it firstprivate.
2349         if (DVar.CKind != OMPC_unknown)
2350           ImplicitFirstprivate.push_back(E);
2351       }
2352       return;
2353     }
2354     if (isOpenMPTargetExecutionDirective(DKind)) {
2355       OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
2356       if (!checkMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map,
2357                                         /*NoDiagnose=*/true))
2358         return;
2359       const auto *VD = cast<ValueDecl>(
2360           CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl());
2361       if (!Stack->checkMappableExprComponentListsForDecl(
2362               VD, /*CurrentRegionOnly=*/true,
2363               [&CurComponents](
2364                   OMPClauseMappableExprCommon::MappableExprComponentListRef
2365                       StackComponents,
2366                   OpenMPClauseKind) {
2367                 auto CCI = CurComponents.rbegin();
2368                 auto CCE = CurComponents.rend();
2369                 for (const auto &SC : llvm::reverse(StackComponents)) {
2370                   // Do both expressions have the same kind?
2371                   if (CCI->getAssociatedExpression()->getStmtClass() !=
2372                       SC.getAssociatedExpression()->getStmtClass())
2373                     if (!(isa<OMPArraySectionExpr>(
2374                               SC.getAssociatedExpression()) &&
2375                           isa<ArraySubscriptExpr>(
2376                               CCI->getAssociatedExpression())))
2377                       return false;
2378 
2379                   const Decl *CCD = CCI->getAssociatedDeclaration();
2380                   const Decl *SCD = SC.getAssociatedDeclaration();
2381                   CCD = CCD ? CCD->getCanonicalDecl() : nullptr;
2382                   SCD = SCD ? SCD->getCanonicalDecl() : nullptr;
2383                   if (SCD != CCD)
2384                     return false;
2385                   std::advance(CCI, 1);
2386                   if (CCI == CCE)
2387                     break;
2388                 }
2389                 return true;
2390               })) {
2391         Visit(E->getBase());
2392       }
2393     } else {
2394       Visit(E->getBase());
2395     }
2396   }
2397   void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
2398     for (OMPClause *C : S->clauses()) {
2399       // Skip analysis of arguments of implicitly defined firstprivate clause
2400       // for task|target directives.
2401       // Skip analysis of arguments of implicitly defined map clause for target
2402       // directives.
2403       if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) &&
2404                  C->isImplicit())) {
2405         for (Stmt *CC : C->children()) {
2406           if (CC)
2407             Visit(CC);
2408         }
2409       }
2410     }
2411     // Check implicitly captured variables.
2412     VisitSubCaptures(S);
2413   }
2414   void VisitStmt(Stmt *S) {
2415     for (Stmt *C : S->children()) {
2416       if (C) {
2417         // Check implicitly captured variables in the task-based directives to
2418         // check if they must be firstprivatized.
2419         Visit(C);
2420       }
2421     }
2422   }
2423 
2424   bool isErrorFound() const { return ErrorFound; }
2425   ArrayRef<Expr *> getImplicitFirstprivate() const {
2426     return ImplicitFirstprivate;
2427   }
2428   ArrayRef<Expr *> getImplicitMap() const { return ImplicitMap; }
2429   const Sema::VarsWithInheritedDSAType &getVarsWithInheritedDSA() const {
2430     return VarsWithInheritedDSA;
2431   }
2432 
2433   DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
2434       : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {}
2435 };
2436 } // namespace
2437 
2438 void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
2439   switch (DKind) {
2440   case OMPD_parallel:
2441   case OMPD_parallel_for:
2442   case OMPD_parallel_for_simd:
2443   case OMPD_parallel_sections:
2444   case OMPD_teams:
2445   case OMPD_teams_distribute:
2446   case OMPD_teams_distribute_simd: {
2447     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2448     QualType KmpInt32PtrTy =
2449         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2450     Sema::CapturedParamNameType Params[] = {
2451         std::make_pair(".global_tid.", KmpInt32PtrTy),
2452         std::make_pair(".bound_tid.", KmpInt32PtrTy),
2453         std::make_pair(StringRef(), QualType()) // __context with shared vars
2454     };
2455     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2456                              Params);
2457     break;
2458   }
2459   case OMPD_target_teams:
2460   case OMPD_target_parallel:
2461   case OMPD_target_parallel_for:
2462   case OMPD_target_parallel_for_simd:
2463   case OMPD_target_teams_distribute:
2464   case OMPD_target_teams_distribute_simd: {
2465     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2466     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2467     QualType KmpInt32PtrTy =
2468         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2469     QualType Args[] = {VoidPtrTy};
2470     FunctionProtoType::ExtProtoInfo EPI;
2471     EPI.Variadic = true;
2472     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2473     Sema::CapturedParamNameType Params[] = {
2474         std::make_pair(".global_tid.", KmpInt32Ty),
2475         std::make_pair(".part_id.", KmpInt32PtrTy),
2476         std::make_pair(".privates.", VoidPtrTy),
2477         std::make_pair(
2478             ".copy_fn.",
2479             Context.getPointerType(CopyFnType).withConst().withRestrict()),
2480         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2481         std::make_pair(StringRef(), QualType()) // __context with shared vars
2482     };
2483     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2484                              Params);
2485     // Mark this captured region as inlined, because we don't use outlined
2486     // function directly.
2487     getCurCapturedRegion()->TheCapturedDecl->addAttr(
2488         AlwaysInlineAttr::CreateImplicit(
2489             Context, AlwaysInlineAttr::Keyword_forceinline));
2490     Sema::CapturedParamNameType ParamsTarget[] = {
2491         std::make_pair(StringRef(), QualType()) // __context with shared vars
2492     };
2493     // Start a captured region for 'target' with no implicit parameters.
2494     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2495                              ParamsTarget);
2496     Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
2497         std::make_pair(".global_tid.", KmpInt32PtrTy),
2498         std::make_pair(".bound_tid.", KmpInt32PtrTy),
2499         std::make_pair(StringRef(), QualType()) // __context with shared vars
2500     };
2501     // Start a captured region for 'teams' or 'parallel'.  Both regions have
2502     // the same implicit parameters.
2503     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2504                              ParamsTeamsOrParallel);
2505     break;
2506   }
2507   case OMPD_target:
2508   case OMPD_target_simd: {
2509     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2510     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2511     QualType KmpInt32PtrTy =
2512         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2513     QualType Args[] = {VoidPtrTy};
2514     FunctionProtoType::ExtProtoInfo EPI;
2515     EPI.Variadic = true;
2516     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2517     Sema::CapturedParamNameType Params[] = {
2518         std::make_pair(".global_tid.", KmpInt32Ty),
2519         std::make_pair(".part_id.", KmpInt32PtrTy),
2520         std::make_pair(".privates.", VoidPtrTy),
2521         std::make_pair(
2522             ".copy_fn.",
2523             Context.getPointerType(CopyFnType).withConst().withRestrict()),
2524         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2525         std::make_pair(StringRef(), QualType()) // __context with shared vars
2526     };
2527     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2528                              Params);
2529     // Mark this captured region as inlined, because we don't use outlined
2530     // function directly.
2531     getCurCapturedRegion()->TheCapturedDecl->addAttr(
2532         AlwaysInlineAttr::CreateImplicit(
2533             Context, AlwaysInlineAttr::Keyword_forceinline));
2534     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2535                              std::make_pair(StringRef(), QualType()));
2536     break;
2537   }
2538   case OMPD_simd:
2539   case OMPD_for:
2540   case OMPD_for_simd:
2541   case OMPD_sections:
2542   case OMPD_section:
2543   case OMPD_single:
2544   case OMPD_master:
2545   case OMPD_critical:
2546   case OMPD_taskgroup:
2547   case OMPD_distribute:
2548   case OMPD_distribute_simd:
2549   case OMPD_ordered:
2550   case OMPD_atomic:
2551   case OMPD_target_data: {
2552     Sema::CapturedParamNameType Params[] = {
2553         std::make_pair(StringRef(), QualType()) // __context with shared vars
2554     };
2555     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2556                              Params);
2557     break;
2558   }
2559   case OMPD_task: {
2560     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2561     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2562     QualType KmpInt32PtrTy =
2563         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2564     QualType Args[] = {VoidPtrTy};
2565     FunctionProtoType::ExtProtoInfo EPI;
2566     EPI.Variadic = true;
2567     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2568     Sema::CapturedParamNameType Params[] = {
2569         std::make_pair(".global_tid.", KmpInt32Ty),
2570         std::make_pair(".part_id.", KmpInt32PtrTy),
2571         std::make_pair(".privates.", VoidPtrTy),
2572         std::make_pair(
2573             ".copy_fn.",
2574             Context.getPointerType(CopyFnType).withConst().withRestrict()),
2575         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2576         std::make_pair(StringRef(), QualType()) // __context with shared vars
2577     };
2578     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2579                              Params);
2580     // Mark this captured region as inlined, because we don't use outlined
2581     // function directly.
2582     getCurCapturedRegion()->TheCapturedDecl->addAttr(
2583         AlwaysInlineAttr::CreateImplicit(
2584             Context, AlwaysInlineAttr::Keyword_forceinline));
2585     break;
2586   }
2587   case OMPD_taskloop:
2588   case OMPD_taskloop_simd: {
2589     QualType KmpInt32Ty =
2590         Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1)
2591             .withConst();
2592     QualType KmpUInt64Ty =
2593         Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0)
2594             .withConst();
2595     QualType KmpInt64Ty =
2596         Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1)
2597             .withConst();
2598     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2599     QualType KmpInt32PtrTy =
2600         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2601     QualType Args[] = {VoidPtrTy};
2602     FunctionProtoType::ExtProtoInfo EPI;
2603     EPI.Variadic = true;
2604     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2605     Sema::CapturedParamNameType Params[] = {
2606         std::make_pair(".global_tid.", KmpInt32Ty),
2607         std::make_pair(".part_id.", KmpInt32PtrTy),
2608         std::make_pair(".privates.", VoidPtrTy),
2609         std::make_pair(
2610             ".copy_fn.",
2611             Context.getPointerType(CopyFnType).withConst().withRestrict()),
2612         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2613         std::make_pair(".lb.", KmpUInt64Ty),
2614         std::make_pair(".ub.", KmpUInt64Ty),
2615         std::make_pair(".st.", KmpInt64Ty),
2616         std::make_pair(".liter.", KmpInt32Ty),
2617         std::make_pair(".reductions.", VoidPtrTy),
2618         std::make_pair(StringRef(), QualType()) // __context with shared vars
2619     };
2620     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2621                              Params);
2622     // Mark this captured region as inlined, because we don't use outlined
2623     // function directly.
2624     getCurCapturedRegion()->TheCapturedDecl->addAttr(
2625         AlwaysInlineAttr::CreateImplicit(
2626             Context, AlwaysInlineAttr::Keyword_forceinline));
2627     break;
2628   }
2629   case OMPD_distribute_parallel_for_simd:
2630   case OMPD_distribute_parallel_for: {
2631     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2632     QualType KmpInt32PtrTy =
2633         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2634     Sema::CapturedParamNameType Params[] = {
2635         std::make_pair(".global_tid.", KmpInt32PtrTy),
2636         std::make_pair(".bound_tid.", KmpInt32PtrTy),
2637         std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
2638         std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
2639         std::make_pair(StringRef(), QualType()) // __context with shared vars
2640     };
2641     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2642                              Params);
2643     break;
2644   }
2645   case OMPD_target_teams_distribute_parallel_for:
2646   case OMPD_target_teams_distribute_parallel_for_simd: {
2647     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2648     QualType KmpInt32PtrTy =
2649         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2650     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2651 
2652     QualType Args[] = {VoidPtrTy};
2653     FunctionProtoType::ExtProtoInfo EPI;
2654     EPI.Variadic = true;
2655     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2656     Sema::CapturedParamNameType Params[] = {
2657         std::make_pair(".global_tid.", KmpInt32Ty),
2658         std::make_pair(".part_id.", KmpInt32PtrTy),
2659         std::make_pair(".privates.", VoidPtrTy),
2660         std::make_pair(
2661             ".copy_fn.",
2662             Context.getPointerType(CopyFnType).withConst().withRestrict()),
2663         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2664         std::make_pair(StringRef(), QualType()) // __context with shared vars
2665     };
2666     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2667                              Params);
2668     // Mark this captured region as inlined, because we don't use outlined
2669     // function directly.
2670     getCurCapturedRegion()->TheCapturedDecl->addAttr(
2671         AlwaysInlineAttr::CreateImplicit(
2672             Context, AlwaysInlineAttr::Keyword_forceinline));
2673     Sema::CapturedParamNameType ParamsTarget[] = {
2674         std::make_pair(StringRef(), QualType()) // __context with shared vars
2675     };
2676     // Start a captured region for 'target' with no implicit parameters.
2677     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2678                              ParamsTarget);
2679 
2680     Sema::CapturedParamNameType ParamsTeams[] = {
2681         std::make_pair(".global_tid.", KmpInt32PtrTy),
2682         std::make_pair(".bound_tid.", KmpInt32PtrTy),
2683         std::make_pair(StringRef(), QualType()) // __context with shared vars
2684     };
2685     // Start a captured region for 'target' with no implicit parameters.
2686     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2687                              ParamsTeams);
2688 
2689     Sema::CapturedParamNameType ParamsParallel[] = {
2690         std::make_pair(".global_tid.", KmpInt32PtrTy),
2691         std::make_pair(".bound_tid.", KmpInt32PtrTy),
2692         std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
2693         std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
2694         std::make_pair(StringRef(), QualType()) // __context with shared vars
2695     };
2696     // Start a captured region for 'teams' or 'parallel'.  Both regions have
2697     // the same implicit parameters.
2698     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2699                              ParamsParallel);
2700     break;
2701   }
2702 
2703   case OMPD_teams_distribute_parallel_for:
2704   case OMPD_teams_distribute_parallel_for_simd: {
2705     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2706     QualType KmpInt32PtrTy =
2707         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2708 
2709     Sema::CapturedParamNameType ParamsTeams[] = {
2710         std::make_pair(".global_tid.", KmpInt32PtrTy),
2711         std::make_pair(".bound_tid.", KmpInt32PtrTy),
2712         std::make_pair(StringRef(), QualType()) // __context with shared vars
2713     };
2714     // Start a captured region for 'target' with no implicit parameters.
2715     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2716                              ParamsTeams);
2717 
2718     Sema::CapturedParamNameType ParamsParallel[] = {
2719         std::make_pair(".global_tid.", KmpInt32PtrTy),
2720         std::make_pair(".bound_tid.", KmpInt32PtrTy),
2721         std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
2722         std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
2723         std::make_pair(StringRef(), QualType()) // __context with shared vars
2724     };
2725     // Start a captured region for 'teams' or 'parallel'.  Both regions have
2726     // the same implicit parameters.
2727     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2728                              ParamsParallel);
2729     break;
2730   }
2731   case OMPD_target_update:
2732   case OMPD_target_enter_data:
2733   case OMPD_target_exit_data: {
2734     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2735     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2736     QualType KmpInt32PtrTy =
2737         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2738     QualType Args[] = {VoidPtrTy};
2739     FunctionProtoType::ExtProtoInfo EPI;
2740     EPI.Variadic = true;
2741     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2742     Sema::CapturedParamNameType Params[] = {
2743         std::make_pair(".global_tid.", KmpInt32Ty),
2744         std::make_pair(".part_id.", KmpInt32PtrTy),
2745         std::make_pair(".privates.", VoidPtrTy),
2746         std::make_pair(
2747             ".copy_fn.",
2748             Context.getPointerType(CopyFnType).withConst().withRestrict()),
2749         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2750         std::make_pair(StringRef(), QualType()) // __context with shared vars
2751     };
2752     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2753                              Params);
2754     // Mark this captured region as inlined, because we don't use outlined
2755     // function directly.
2756     getCurCapturedRegion()->TheCapturedDecl->addAttr(
2757         AlwaysInlineAttr::CreateImplicit(
2758             Context, AlwaysInlineAttr::Keyword_forceinline));
2759     break;
2760   }
2761   case OMPD_threadprivate:
2762   case OMPD_taskyield:
2763   case OMPD_barrier:
2764   case OMPD_taskwait:
2765   case OMPD_cancellation_point:
2766   case OMPD_cancel:
2767   case OMPD_flush:
2768   case OMPD_declare_reduction:
2769   case OMPD_declare_simd:
2770   case OMPD_declare_target:
2771   case OMPD_end_declare_target:
2772   case OMPD_requires:
2773     llvm_unreachable("OpenMP Directive is not allowed");
2774   case OMPD_unknown:
2775     llvm_unreachable("Unknown OpenMP directive");
2776   }
2777 }
2778 
2779 int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
2780   SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
2781   getOpenMPCaptureRegions(CaptureRegions, DKind);
2782   return CaptureRegions.size();
2783 }
2784 
2785 static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
2786                                              Expr *CaptureExpr, bool WithInit,
2787                                              bool AsExpression) {
2788   assert(CaptureExpr);
2789   ASTContext &C = S.getASTContext();
2790   Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
2791   QualType Ty = Init->getType();
2792   if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
2793     if (S.getLangOpts().CPlusPlus) {
2794       Ty = C.getLValueReferenceType(Ty);
2795     } else {
2796       Ty = C.getPointerType(Ty);
2797       ExprResult Res =
2798           S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
2799       if (!Res.isUsable())
2800         return nullptr;
2801       Init = Res.get();
2802     }
2803     WithInit = true;
2804   }
2805   auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
2806                                           CaptureExpr->getBeginLoc());
2807   if (!WithInit)
2808     CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C));
2809   S.CurContext->addHiddenDecl(CED);
2810   S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
2811   return CED;
2812 }
2813 
2814 static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
2815                                  bool WithInit) {
2816   OMPCapturedExprDecl *CD;
2817   if (VarDecl *VD = S.isOpenMPCapturedDecl(D))
2818     CD = cast<OMPCapturedExprDecl>(VD);
2819   else
2820     CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
2821                           /*AsExpression=*/false);
2822   return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
2823                           CaptureExpr->getExprLoc());
2824 }
2825 
2826 static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
2827   CaptureExpr = S.DefaultLvalueConversion(CaptureExpr).get();
2828   if (!Ref) {
2829     OMPCapturedExprDecl *CD = buildCaptureDecl(
2830         S, &S.getASTContext().Idents.get(".capture_expr."), CaptureExpr,
2831         /*WithInit=*/true, /*AsExpression=*/true);
2832     Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
2833                            CaptureExpr->getExprLoc());
2834   }
2835   ExprResult Res = Ref;
2836   if (!S.getLangOpts().CPlusPlus &&
2837       CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
2838       Ref->getType()->isPointerType()) {
2839     Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
2840     if (!Res.isUsable())
2841       return ExprError();
2842   }
2843   return S.DefaultLvalueConversion(Res.get());
2844 }
2845 
2846 namespace {
2847 // OpenMP directives parsed in this section are represented as a
2848 // CapturedStatement with an associated statement.  If a syntax error
2849 // is detected during the parsing of the associated statement, the
2850 // compiler must abort processing and close the CapturedStatement.
2851 //
2852 // Combined directives such as 'target parallel' have more than one
2853 // nested CapturedStatements.  This RAII ensures that we unwind out
2854 // of all the nested CapturedStatements when an error is found.
2855 class CaptureRegionUnwinderRAII {
2856 private:
2857   Sema &S;
2858   bool &ErrorFound;
2859   OpenMPDirectiveKind DKind = OMPD_unknown;
2860 
2861 public:
2862   CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
2863                             OpenMPDirectiveKind DKind)
2864       : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
2865   ~CaptureRegionUnwinderRAII() {
2866     if (ErrorFound) {
2867       int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
2868       while (--ThisCaptureLevel >= 0)
2869         S.ActOnCapturedRegionError();
2870     }
2871   }
2872 };
2873 } // namespace
2874 
2875 StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
2876                                       ArrayRef<OMPClause *> Clauses) {
2877   bool ErrorFound = false;
2878   CaptureRegionUnwinderRAII CaptureRegionUnwinder(
2879       *this, ErrorFound, DSAStack->getCurrentDirective());
2880   if (!S.isUsable()) {
2881     ErrorFound = true;
2882     return StmtError();
2883   }
2884 
2885   SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
2886   getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
2887   OMPOrderedClause *OC = nullptr;
2888   OMPScheduleClause *SC = nullptr;
2889   SmallVector<const OMPLinearClause *, 4> LCs;
2890   SmallVector<const OMPClauseWithPreInit *, 4> PICs;
2891   // This is required for proper codegen.
2892   for (OMPClause *Clause : Clauses) {
2893     if (isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) &&
2894         Clause->getClauseKind() == OMPC_in_reduction) {
2895       // Capture taskgroup task_reduction descriptors inside the tasking regions
2896       // with the corresponding in_reduction items.
2897       auto *IRC = cast<OMPInReductionClause>(Clause);
2898       for (Expr *E : IRC->taskgroup_descriptors())
2899         if (E)
2900           MarkDeclarationsReferencedInExpr(E);
2901     }
2902     if (isOpenMPPrivate(Clause->getClauseKind()) ||
2903         Clause->getClauseKind() == OMPC_copyprivate ||
2904         (getLangOpts().OpenMPUseTLS &&
2905          getASTContext().getTargetInfo().isTLSSupported() &&
2906          Clause->getClauseKind() == OMPC_copyin)) {
2907       DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
2908       // Mark all variables in private list clauses as used in inner region.
2909       for (Stmt *VarRef : Clause->children()) {
2910         if (auto *E = cast_or_null<Expr>(VarRef)) {
2911           MarkDeclarationsReferencedInExpr(E);
2912         }
2913       }
2914       DSAStack->setForceVarCapturing(/*V=*/false);
2915     } else if (CaptureRegions.size() > 1 ||
2916                CaptureRegions.back() != OMPD_unknown) {
2917       if (auto *C = OMPClauseWithPreInit::get(Clause))
2918         PICs.push_back(C);
2919       if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
2920         if (Expr *E = C->getPostUpdateExpr())
2921           MarkDeclarationsReferencedInExpr(E);
2922       }
2923     }
2924     if (Clause->getClauseKind() == OMPC_schedule)
2925       SC = cast<OMPScheduleClause>(Clause);
2926     else if (Clause->getClauseKind() == OMPC_ordered)
2927       OC = cast<OMPOrderedClause>(Clause);
2928     else if (Clause->getClauseKind() == OMPC_linear)
2929       LCs.push_back(cast<OMPLinearClause>(Clause));
2930   }
2931   // OpenMP, 2.7.1 Loop Construct, Restrictions
2932   // The nonmonotonic modifier cannot be specified if an ordered clause is
2933   // specified.
2934   if (SC &&
2935       (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
2936        SC->getSecondScheduleModifier() ==
2937            OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
2938       OC) {
2939     Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
2940              ? SC->getFirstScheduleModifierLoc()
2941              : SC->getSecondScheduleModifierLoc(),
2942          diag::err_omp_schedule_nonmonotonic_ordered)
2943         << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
2944     ErrorFound = true;
2945   }
2946   if (!LCs.empty() && OC && OC->getNumForLoops()) {
2947     for (const OMPLinearClause *C : LCs) {
2948       Diag(C->getBeginLoc(), diag::err_omp_linear_ordered)
2949           << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
2950     }
2951     ErrorFound = true;
2952   }
2953   if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
2954       isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
2955       OC->getNumForLoops()) {
2956     Diag(OC->getBeginLoc(), diag::err_omp_ordered_simd)
2957         << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
2958     ErrorFound = true;
2959   }
2960   if (ErrorFound) {
2961     return StmtError();
2962   }
2963   StmtResult SR = S;
2964   for (OpenMPDirectiveKind ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
2965     // Mark all variables in private list clauses as used in inner region.
2966     // Required for proper codegen of combined directives.
2967     // TODO: add processing for other clauses.
2968     if (ThisCaptureRegion != OMPD_unknown) {
2969       for (const clang::OMPClauseWithPreInit *C : PICs) {
2970         OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
2971         // Find the particular capture region for the clause if the
2972         // directive is a combined one with multiple capture regions.
2973         // If the directive is not a combined one, the capture region
2974         // associated with the clause is OMPD_unknown and is generated
2975         // only once.
2976         if (CaptureRegion == ThisCaptureRegion ||
2977             CaptureRegion == OMPD_unknown) {
2978           if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
2979             for (Decl *D : DS->decls())
2980               MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
2981           }
2982         }
2983       }
2984     }
2985     SR = ActOnCapturedRegionEnd(SR.get());
2986   }
2987   return SR;
2988 }
2989 
2990 static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
2991                               OpenMPDirectiveKind CancelRegion,
2992                               SourceLocation StartLoc) {
2993   // CancelRegion is only needed for cancel and cancellation_point.
2994   if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
2995     return false;
2996 
2997   if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
2998       CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
2999     return false;
3000 
3001   SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
3002       << getOpenMPDirectiveName(CancelRegion);
3003   return true;
3004 }
3005 
3006 static bool checkNestingOfRegions(Sema &SemaRef, const DSAStackTy *Stack,
3007                                   OpenMPDirectiveKind CurrentRegion,
3008                                   const DeclarationNameInfo &CurrentName,
3009                                   OpenMPDirectiveKind CancelRegion,
3010                                   SourceLocation StartLoc) {
3011   if (Stack->getCurScope()) {
3012     OpenMPDirectiveKind ParentRegion = Stack->getParentDirective();
3013     OpenMPDirectiveKind OffendingRegion = ParentRegion;
3014     bool NestingProhibited = false;
3015     bool CloseNesting = true;
3016     bool OrphanSeen = false;
3017     enum {
3018       NoRecommend,
3019       ShouldBeInParallelRegion,
3020       ShouldBeInOrderedRegion,
3021       ShouldBeInTargetRegion,
3022       ShouldBeInTeamsRegion
3023     } Recommend = NoRecommend;
3024     if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
3025       // OpenMP [2.16, Nesting of Regions]
3026       // OpenMP constructs may not be nested inside a simd region.
3027       // OpenMP [2.8.1,simd Construct, Restrictions]
3028       // An ordered construct with the simd clause is the only OpenMP
3029       // construct that can appear in the simd region.
3030       // Allowing a SIMD construct nested in another SIMD construct is an
3031       // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
3032       // message.
3033       SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
3034                                  ? diag::err_omp_prohibited_region_simd
3035                                  : diag::warn_omp_nesting_simd);
3036       return CurrentRegion != OMPD_simd;
3037     }
3038     if (ParentRegion == OMPD_atomic) {
3039       // OpenMP [2.16, Nesting of Regions]
3040       // OpenMP constructs may not be nested inside an atomic region.
3041       SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
3042       return true;
3043     }
3044     if (CurrentRegion == OMPD_section) {
3045       // OpenMP [2.7.2, sections Construct, Restrictions]
3046       // Orphaned section directives are prohibited. That is, the section
3047       // directives must appear within the sections construct and must not be
3048       // encountered elsewhere in the sections region.
3049       if (ParentRegion != OMPD_sections &&
3050           ParentRegion != OMPD_parallel_sections) {
3051         SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
3052             << (ParentRegion != OMPD_unknown)
3053             << getOpenMPDirectiveName(ParentRegion);
3054         return true;
3055       }
3056       return false;
3057     }
3058     // Allow some constructs (except teams) to be orphaned (they could be
3059     // used in functions, called from OpenMP regions with the required
3060     // preconditions).
3061     if (ParentRegion == OMPD_unknown &&
3062         !isOpenMPNestingTeamsDirective(CurrentRegion))
3063       return false;
3064     if (CurrentRegion == OMPD_cancellation_point ||
3065         CurrentRegion == OMPD_cancel) {
3066       // OpenMP [2.16, Nesting of Regions]
3067       // A cancellation point construct for which construct-type-clause is
3068       // taskgroup must be nested inside a task construct. A cancellation
3069       // point construct for which construct-type-clause is not taskgroup must
3070       // be closely nested inside an OpenMP construct that matches the type
3071       // specified in construct-type-clause.
3072       // A cancel construct for which construct-type-clause is taskgroup must be
3073       // nested inside a task construct. A cancel construct for which
3074       // construct-type-clause is not taskgroup must be closely nested inside an
3075       // OpenMP construct that matches the type specified in
3076       // construct-type-clause.
3077       NestingProhibited =
3078           !((CancelRegion == OMPD_parallel &&
3079              (ParentRegion == OMPD_parallel ||
3080               ParentRegion == OMPD_target_parallel)) ||
3081             (CancelRegion == OMPD_for &&
3082              (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
3083               ParentRegion == OMPD_target_parallel_for ||
3084               ParentRegion == OMPD_distribute_parallel_for ||
3085               ParentRegion == OMPD_teams_distribute_parallel_for ||
3086               ParentRegion == OMPD_target_teams_distribute_parallel_for)) ||
3087             (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
3088             (CancelRegion == OMPD_sections &&
3089              (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
3090               ParentRegion == OMPD_parallel_sections)));
3091     } else if (CurrentRegion == OMPD_master) {
3092       // OpenMP [2.16, Nesting of Regions]
3093       // A master region may not be closely nested inside a worksharing,
3094       // atomic, or explicit task region.
3095       NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
3096                           isOpenMPTaskingDirective(ParentRegion);
3097     } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
3098       // OpenMP [2.16, Nesting of Regions]
3099       // A critical region may not be nested (closely or otherwise) inside a
3100       // critical region with the same name. Note that this restriction is not
3101       // sufficient to prevent deadlock.
3102       SourceLocation PreviousCriticalLoc;
3103       bool DeadLock = Stack->hasDirective(
3104           [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
3105                                               const DeclarationNameInfo &DNI,
3106                                               SourceLocation Loc) {
3107             if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
3108               PreviousCriticalLoc = Loc;
3109               return true;
3110             }
3111             return false;
3112           },
3113           false /* skip top directive */);
3114       if (DeadLock) {
3115         SemaRef.Diag(StartLoc,
3116                      diag::err_omp_prohibited_region_critical_same_name)
3117             << CurrentName.getName();
3118         if (PreviousCriticalLoc.isValid())
3119           SemaRef.Diag(PreviousCriticalLoc,
3120                        diag::note_omp_previous_critical_region);
3121         return true;
3122       }
3123     } else if (CurrentRegion == OMPD_barrier) {
3124       // OpenMP [2.16, Nesting of Regions]
3125       // A barrier region may not be closely nested inside a worksharing,
3126       // explicit task, critical, ordered, atomic, or master region.
3127       NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
3128                           isOpenMPTaskingDirective(ParentRegion) ||
3129                           ParentRegion == OMPD_master ||
3130                           ParentRegion == OMPD_critical ||
3131                           ParentRegion == OMPD_ordered;
3132     } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
3133                !isOpenMPParallelDirective(CurrentRegion) &&
3134                !isOpenMPTeamsDirective(CurrentRegion)) {
3135       // OpenMP [2.16, Nesting of Regions]
3136       // A worksharing region may not be closely nested inside a worksharing,
3137       // explicit task, critical, ordered, atomic, or master region.
3138       NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
3139                           isOpenMPTaskingDirective(ParentRegion) ||
3140                           ParentRegion == OMPD_master ||
3141                           ParentRegion == OMPD_critical ||
3142                           ParentRegion == OMPD_ordered;
3143       Recommend = ShouldBeInParallelRegion;
3144     } else if (CurrentRegion == OMPD_ordered) {
3145       // OpenMP [2.16, Nesting of Regions]
3146       // An ordered region may not be closely nested inside a critical,
3147       // atomic, or explicit task region.
3148       // An ordered region must be closely nested inside a loop region (or
3149       // parallel loop region) with an ordered clause.
3150       // OpenMP [2.8.1,simd Construct, Restrictions]
3151       // An ordered construct with the simd clause is the only OpenMP construct
3152       // that can appear in the simd region.
3153       NestingProhibited = ParentRegion == OMPD_critical ||
3154                           isOpenMPTaskingDirective(ParentRegion) ||
3155                           !(isOpenMPSimdDirective(ParentRegion) ||
3156                             Stack->isParentOrderedRegion());
3157       Recommend = ShouldBeInOrderedRegion;
3158     } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
3159       // OpenMP [2.16, Nesting of Regions]
3160       // If specified, a teams construct must be contained within a target
3161       // construct.
3162       NestingProhibited = ParentRegion != OMPD_target;
3163       OrphanSeen = ParentRegion == OMPD_unknown;
3164       Recommend = ShouldBeInTargetRegion;
3165     }
3166     if (!NestingProhibited &&
3167         !isOpenMPTargetExecutionDirective(CurrentRegion) &&
3168         !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
3169         (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
3170       // OpenMP [2.16, Nesting of Regions]
3171       // distribute, parallel, parallel sections, parallel workshare, and the
3172       // parallel loop and parallel loop SIMD constructs are the only OpenMP
3173       // constructs that can be closely nested in the teams region.
3174       NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
3175                           !isOpenMPDistributeDirective(CurrentRegion);
3176       Recommend = ShouldBeInParallelRegion;
3177     }
3178     if (!NestingProhibited &&
3179         isOpenMPNestingDistributeDirective(CurrentRegion)) {
3180       // OpenMP 4.5 [2.17 Nesting of Regions]
3181       // The region associated with the distribute construct must be strictly
3182       // nested inside a teams region
3183       NestingProhibited =
3184           (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
3185       Recommend = ShouldBeInTeamsRegion;
3186     }
3187     if (!NestingProhibited &&
3188         (isOpenMPTargetExecutionDirective(CurrentRegion) ||
3189          isOpenMPTargetDataManagementDirective(CurrentRegion))) {
3190       // OpenMP 4.5 [2.17 Nesting of Regions]
3191       // If a target, target update, target data, target enter data, or
3192       // target exit data construct is encountered during execution of a
3193       // target region, the behavior is unspecified.
3194       NestingProhibited = Stack->hasDirective(
3195           [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
3196                              SourceLocation) {
3197             if (isOpenMPTargetExecutionDirective(K)) {
3198               OffendingRegion = K;
3199               return true;
3200             }
3201             return false;
3202           },
3203           false /* don't skip top directive */);
3204       CloseNesting = false;
3205     }
3206     if (NestingProhibited) {
3207       if (OrphanSeen) {
3208         SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
3209             << getOpenMPDirectiveName(CurrentRegion) << Recommend;
3210       } else {
3211         SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
3212             << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
3213             << Recommend << getOpenMPDirectiveName(CurrentRegion);
3214       }
3215       return true;
3216     }
3217   }
3218   return false;
3219 }
3220 
3221 static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
3222                            ArrayRef<OMPClause *> Clauses,
3223                            ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
3224   bool ErrorFound = false;
3225   unsigned NamedModifiersNumber = 0;
3226   SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
3227       OMPD_unknown + 1);
3228   SmallVector<SourceLocation, 4> NameModifierLoc;
3229   for (const OMPClause *C : Clauses) {
3230     if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
3231       // At most one if clause without a directive-name-modifier can appear on
3232       // the directive.
3233       OpenMPDirectiveKind CurNM = IC->getNameModifier();
3234       if (FoundNameModifiers[CurNM]) {
3235         S.Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
3236             << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
3237             << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
3238         ErrorFound = true;
3239       } else if (CurNM != OMPD_unknown) {
3240         NameModifierLoc.push_back(IC->getNameModifierLoc());
3241         ++NamedModifiersNumber;
3242       }
3243       FoundNameModifiers[CurNM] = IC;
3244       if (CurNM == OMPD_unknown)
3245         continue;
3246       // Check if the specified name modifier is allowed for the current
3247       // directive.
3248       // At most one if clause with the particular directive-name-modifier can
3249       // appear on the directive.
3250       bool MatchFound = false;
3251       for (auto NM : AllowedNameModifiers) {
3252         if (CurNM == NM) {
3253           MatchFound = true;
3254           break;
3255         }
3256       }
3257       if (!MatchFound) {
3258         S.Diag(IC->getNameModifierLoc(),
3259                diag::err_omp_wrong_if_directive_name_modifier)
3260             << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
3261         ErrorFound = true;
3262       }
3263     }
3264   }
3265   // If any if clause on the directive includes a directive-name-modifier then
3266   // all if clauses on the directive must include a directive-name-modifier.
3267   if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
3268     if (NamedModifiersNumber == AllowedNameModifiers.size()) {
3269       S.Diag(FoundNameModifiers[OMPD_unknown]->getBeginLoc(),
3270              diag::err_omp_no_more_if_clause);
3271     } else {
3272       std::string Values;
3273       std::string Sep(", ");
3274       unsigned AllowedCnt = 0;
3275       unsigned TotalAllowedNum =
3276           AllowedNameModifiers.size() - NamedModifiersNumber;
3277       for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
3278            ++Cnt) {
3279         OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
3280         if (!FoundNameModifiers[NM]) {
3281           Values += "'";
3282           Values += getOpenMPDirectiveName(NM);
3283           Values += "'";
3284           if (AllowedCnt + 2 == TotalAllowedNum)
3285             Values += " or ";
3286           else if (AllowedCnt + 1 != TotalAllowedNum)
3287             Values += Sep;
3288           ++AllowedCnt;
3289         }
3290       }
3291       S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getBeginLoc(),
3292              diag::err_omp_unnamed_if_clause)
3293           << (TotalAllowedNum > 1) << Values;
3294     }
3295     for (SourceLocation Loc : NameModifierLoc) {
3296       S.Diag(Loc, diag::note_omp_previous_named_if_clause);
3297     }
3298     ErrorFound = true;
3299   }
3300   return ErrorFound;
3301 }
3302 
3303 StmtResult Sema::ActOnOpenMPExecutableDirective(
3304     OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
3305     OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
3306     Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
3307   StmtResult Res = StmtError();
3308   // First check CancelRegion which is then used in checkNestingOfRegions.
3309   if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
3310       checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
3311                             StartLoc))
3312     return StmtError();
3313 
3314   llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
3315   VarsWithInheritedDSAType VarsWithInheritedDSA;
3316   bool ErrorFound = false;
3317   ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
3318   if (AStmt && !CurContext->isDependentContext()) {
3319     assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
3320 
3321     // Check default data sharing attributes for referenced variables.
3322     DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
3323     int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
3324     Stmt *S = AStmt;
3325     while (--ThisCaptureLevel >= 0)
3326       S = cast<CapturedStmt>(S)->getCapturedStmt();
3327     DSAChecker.Visit(S);
3328     if (DSAChecker.isErrorFound())
3329       return StmtError();
3330     // Generate list of implicitly defined firstprivate variables.
3331     VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
3332 
3333     SmallVector<Expr *, 4> ImplicitFirstprivates(
3334         DSAChecker.getImplicitFirstprivate().begin(),
3335         DSAChecker.getImplicitFirstprivate().end());
3336     SmallVector<Expr *, 4> ImplicitMaps(DSAChecker.getImplicitMap().begin(),
3337                                         DSAChecker.getImplicitMap().end());
3338     // Mark taskgroup task_reduction descriptors as implicitly firstprivate.
3339     for (OMPClause *C : Clauses) {
3340       if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) {
3341         for (Expr *E : IRC->taskgroup_descriptors())
3342           if (E)
3343             ImplicitFirstprivates.emplace_back(E);
3344       }
3345     }
3346     if (!ImplicitFirstprivates.empty()) {
3347       if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
3348               ImplicitFirstprivates, SourceLocation(), SourceLocation(),
3349               SourceLocation())) {
3350         ClausesWithImplicit.push_back(Implicit);
3351         ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
3352                      ImplicitFirstprivates.size();
3353       } else {
3354         ErrorFound = true;
3355       }
3356     }
3357     if (!ImplicitMaps.empty()) {
3358       if (OMPClause *Implicit = ActOnOpenMPMapClause(
3359               llvm::None, llvm::None, OMPC_MAP_tofrom,
3360               /*IsMapTypeImplicit=*/true, SourceLocation(), SourceLocation(),
3361               ImplicitMaps, SourceLocation(), SourceLocation(),
3362               SourceLocation())) {
3363         ClausesWithImplicit.emplace_back(Implicit);
3364         ErrorFound |=
3365             cast<OMPMapClause>(Implicit)->varlist_size() != ImplicitMaps.size();
3366       } else {
3367         ErrorFound = true;
3368       }
3369     }
3370   }
3371 
3372   llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
3373   switch (Kind) {
3374   case OMPD_parallel:
3375     Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
3376                                        EndLoc);
3377     AllowedNameModifiers.push_back(OMPD_parallel);
3378     break;
3379   case OMPD_simd:
3380     Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
3381                                    VarsWithInheritedDSA);
3382     break;
3383   case OMPD_for:
3384     Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
3385                                   VarsWithInheritedDSA);
3386     break;
3387   case OMPD_for_simd:
3388     Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3389                                       EndLoc, VarsWithInheritedDSA);
3390     break;
3391   case OMPD_sections:
3392     Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
3393                                        EndLoc);
3394     break;
3395   case OMPD_section:
3396     assert(ClausesWithImplicit.empty() &&
3397            "No clauses are allowed for 'omp section' directive");
3398     Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
3399     break;
3400   case OMPD_single:
3401     Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
3402                                      EndLoc);
3403     break;
3404   case OMPD_master:
3405     assert(ClausesWithImplicit.empty() &&
3406            "No clauses are allowed for 'omp master' directive");
3407     Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
3408     break;
3409   case OMPD_critical:
3410     Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
3411                                        StartLoc, EndLoc);
3412     break;
3413   case OMPD_parallel_for:
3414     Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
3415                                           EndLoc, VarsWithInheritedDSA);
3416     AllowedNameModifiers.push_back(OMPD_parallel);
3417     break;
3418   case OMPD_parallel_for_simd:
3419     Res = ActOnOpenMPParallelForSimdDirective(
3420         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3421     AllowedNameModifiers.push_back(OMPD_parallel);
3422     break;
3423   case OMPD_parallel_sections:
3424     Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
3425                                                StartLoc, EndLoc);
3426     AllowedNameModifiers.push_back(OMPD_parallel);
3427     break;
3428   case OMPD_task:
3429     Res =
3430         ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
3431     AllowedNameModifiers.push_back(OMPD_task);
3432     break;
3433   case OMPD_taskyield:
3434     assert(ClausesWithImplicit.empty() &&
3435            "No clauses are allowed for 'omp taskyield' directive");
3436     assert(AStmt == nullptr &&
3437            "No associated statement allowed for 'omp taskyield' directive");
3438     Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
3439     break;
3440   case OMPD_barrier:
3441     assert(ClausesWithImplicit.empty() &&
3442            "No clauses are allowed for 'omp barrier' directive");
3443     assert(AStmt == nullptr &&
3444            "No associated statement allowed for 'omp barrier' directive");
3445     Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
3446     break;
3447   case OMPD_taskwait:
3448     assert(ClausesWithImplicit.empty() &&
3449            "No clauses are allowed for 'omp taskwait' directive");
3450     assert(AStmt == nullptr &&
3451            "No associated statement allowed for 'omp taskwait' directive");
3452     Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
3453     break;
3454   case OMPD_taskgroup:
3455     Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc,
3456                                         EndLoc);
3457     break;
3458   case OMPD_flush:
3459     assert(AStmt == nullptr &&
3460            "No associated statement allowed for 'omp flush' directive");
3461     Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
3462     break;
3463   case OMPD_ordered:
3464     Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
3465                                       EndLoc);
3466     break;
3467   case OMPD_atomic:
3468     Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
3469                                      EndLoc);
3470     break;
3471   case OMPD_teams:
3472     Res =
3473         ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
3474     break;
3475   case OMPD_target:
3476     Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
3477                                      EndLoc);
3478     AllowedNameModifiers.push_back(OMPD_target);
3479     break;
3480   case OMPD_target_parallel:
3481     Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
3482                                              StartLoc, EndLoc);
3483     AllowedNameModifiers.push_back(OMPD_target);
3484     AllowedNameModifiers.push_back(OMPD_parallel);
3485     break;
3486   case OMPD_target_parallel_for:
3487     Res = ActOnOpenMPTargetParallelForDirective(
3488         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3489     AllowedNameModifiers.push_back(OMPD_target);
3490     AllowedNameModifiers.push_back(OMPD_parallel);
3491     break;
3492   case OMPD_cancellation_point:
3493     assert(ClausesWithImplicit.empty() &&
3494            "No clauses are allowed for 'omp cancellation point' directive");
3495     assert(AStmt == nullptr && "No associated statement allowed for 'omp "
3496                                "cancellation point' directive");
3497     Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
3498     break;
3499   case OMPD_cancel:
3500     assert(AStmt == nullptr &&
3501            "No associated statement allowed for 'omp cancel' directive");
3502     Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
3503                                      CancelRegion);
3504     AllowedNameModifiers.push_back(OMPD_cancel);
3505     break;
3506   case OMPD_target_data:
3507     Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
3508                                          EndLoc);
3509     AllowedNameModifiers.push_back(OMPD_target_data);
3510     break;
3511   case OMPD_target_enter_data:
3512     Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
3513                                               EndLoc, AStmt);
3514     AllowedNameModifiers.push_back(OMPD_target_enter_data);
3515     break;
3516   case OMPD_target_exit_data:
3517     Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
3518                                              EndLoc, AStmt);
3519     AllowedNameModifiers.push_back(OMPD_target_exit_data);
3520     break;
3521   case OMPD_taskloop:
3522     Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
3523                                        EndLoc, VarsWithInheritedDSA);
3524     AllowedNameModifiers.push_back(OMPD_taskloop);
3525     break;
3526   case OMPD_taskloop_simd:
3527     Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3528                                            EndLoc, VarsWithInheritedDSA);
3529     AllowedNameModifiers.push_back(OMPD_taskloop);
3530     break;
3531   case OMPD_distribute:
3532     Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
3533                                          EndLoc, VarsWithInheritedDSA);
3534     break;
3535   case OMPD_target_update:
3536     Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc,
3537                                            EndLoc, AStmt);
3538     AllowedNameModifiers.push_back(OMPD_target_update);
3539     break;
3540   case OMPD_distribute_parallel_for:
3541     Res = ActOnOpenMPDistributeParallelForDirective(
3542         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3543     AllowedNameModifiers.push_back(OMPD_parallel);
3544     break;
3545   case OMPD_distribute_parallel_for_simd:
3546     Res = ActOnOpenMPDistributeParallelForSimdDirective(
3547         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3548     AllowedNameModifiers.push_back(OMPD_parallel);
3549     break;
3550   case OMPD_distribute_simd:
3551     Res = ActOnOpenMPDistributeSimdDirective(
3552         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3553     break;
3554   case OMPD_target_parallel_for_simd:
3555     Res = ActOnOpenMPTargetParallelForSimdDirective(
3556         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3557     AllowedNameModifiers.push_back(OMPD_target);
3558     AllowedNameModifiers.push_back(OMPD_parallel);
3559     break;
3560   case OMPD_target_simd:
3561     Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3562                                          EndLoc, VarsWithInheritedDSA);
3563     AllowedNameModifiers.push_back(OMPD_target);
3564     break;
3565   case OMPD_teams_distribute:
3566     Res = ActOnOpenMPTeamsDistributeDirective(
3567         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3568     break;
3569   case OMPD_teams_distribute_simd:
3570     Res = ActOnOpenMPTeamsDistributeSimdDirective(
3571         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3572     break;
3573   case OMPD_teams_distribute_parallel_for_simd:
3574     Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
3575         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3576     AllowedNameModifiers.push_back(OMPD_parallel);
3577     break;
3578   case OMPD_teams_distribute_parallel_for:
3579     Res = ActOnOpenMPTeamsDistributeParallelForDirective(
3580         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3581     AllowedNameModifiers.push_back(OMPD_parallel);
3582     break;
3583   case OMPD_target_teams:
3584     Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
3585                                           EndLoc);
3586     AllowedNameModifiers.push_back(OMPD_target);
3587     break;
3588   case OMPD_target_teams_distribute:
3589     Res = ActOnOpenMPTargetTeamsDistributeDirective(
3590         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3591     AllowedNameModifiers.push_back(OMPD_target);
3592     break;
3593   case OMPD_target_teams_distribute_parallel_for:
3594     Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
3595         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3596     AllowedNameModifiers.push_back(OMPD_target);
3597     AllowedNameModifiers.push_back(OMPD_parallel);
3598     break;
3599   case OMPD_target_teams_distribute_parallel_for_simd:
3600     Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
3601         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3602     AllowedNameModifiers.push_back(OMPD_target);
3603     AllowedNameModifiers.push_back(OMPD_parallel);
3604     break;
3605   case OMPD_target_teams_distribute_simd:
3606     Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
3607         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3608     AllowedNameModifiers.push_back(OMPD_target);
3609     break;
3610   case OMPD_declare_target:
3611   case OMPD_end_declare_target:
3612   case OMPD_threadprivate:
3613   case OMPD_declare_reduction:
3614   case OMPD_declare_simd:
3615   case OMPD_requires:
3616     llvm_unreachable("OpenMP Directive is not allowed");
3617   case OMPD_unknown:
3618     llvm_unreachable("Unknown OpenMP directive");
3619   }
3620 
3621   for (const auto &P : VarsWithInheritedDSA) {
3622     Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
3623         << P.first << P.second->getSourceRange();
3624   }
3625   ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound;
3626 
3627   if (!AllowedNameModifiers.empty())
3628     ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
3629                  ErrorFound;
3630 
3631   if (ErrorFound)
3632     return StmtError();
3633   return Res;
3634 }
3635 
3636 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
3637     DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
3638     ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
3639     ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
3640     ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
3641   assert(Aligneds.size() == Alignments.size());
3642   assert(Linears.size() == LinModifiers.size());
3643   assert(Linears.size() == Steps.size());
3644   if (!DG || DG.get().isNull())
3645     return DeclGroupPtrTy();
3646 
3647   if (!DG.get().isSingleDecl()) {
3648     Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd);
3649     return DG;
3650   }
3651   Decl *ADecl = DG.get().getSingleDecl();
3652   if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
3653     ADecl = FTD->getTemplatedDecl();
3654 
3655   auto *FD = dyn_cast<FunctionDecl>(ADecl);
3656   if (!FD) {
3657     Diag(ADecl->getLocation(), diag::err_omp_function_expected);
3658     return DeclGroupPtrTy();
3659   }
3660 
3661   // OpenMP [2.8.2, declare simd construct, Description]
3662   // The parameter of the simdlen clause must be a constant positive integer
3663   // expression.
3664   ExprResult SL;
3665   if (Simdlen)
3666     SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
3667   // OpenMP [2.8.2, declare simd construct, Description]
3668   // The special this pointer can be used as if was one of the arguments to the
3669   // function in any of the linear, aligned, or uniform clauses.
3670   // The uniform clause declares one or more arguments to have an invariant
3671   // value for all concurrent invocations of the function in the execution of a
3672   // single SIMD loop.
3673   llvm::DenseMap<const Decl *, const Expr *> UniformedArgs;
3674   const Expr *UniformedLinearThis = nullptr;
3675   for (const Expr *E : Uniforms) {
3676     E = E->IgnoreParenImpCasts();
3677     if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
3678       if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
3679         if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
3680             FD->getParamDecl(PVD->getFunctionScopeIndex())
3681                     ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
3682           UniformedArgs.try_emplace(PVD->getCanonicalDecl(), E);
3683           continue;
3684         }
3685     if (isa<CXXThisExpr>(E)) {
3686       UniformedLinearThis = E;
3687       continue;
3688     }
3689     Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3690         << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
3691   }
3692   // OpenMP [2.8.2, declare simd construct, Description]
3693   // The aligned clause declares that the object to which each list item points
3694   // is aligned to the number of bytes expressed in the optional parameter of
3695   // the aligned clause.
3696   // The special this pointer can be used as if was one of the arguments to the
3697   // function in any of the linear, aligned, or uniform clauses.
3698   // The type of list items appearing in the aligned clause must be array,
3699   // pointer, reference to array, or reference to pointer.
3700   llvm::DenseMap<const Decl *, const Expr *> AlignedArgs;
3701   const Expr *AlignedThis = nullptr;
3702   for (const Expr *E : Aligneds) {
3703     E = E->IgnoreParenImpCasts();
3704     if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
3705       if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3706         const VarDecl *CanonPVD = PVD->getCanonicalDecl();
3707         if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
3708             FD->getParamDecl(PVD->getFunctionScopeIndex())
3709                     ->getCanonicalDecl() == CanonPVD) {
3710           // OpenMP  [2.8.1, simd construct, Restrictions]
3711           // A list-item cannot appear in more than one aligned clause.
3712           if (AlignedArgs.count(CanonPVD) > 0) {
3713             Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
3714                 << 1 << E->getSourceRange();
3715             Diag(AlignedArgs[CanonPVD]->getExprLoc(),
3716                  diag::note_omp_explicit_dsa)
3717                 << getOpenMPClauseName(OMPC_aligned);
3718             continue;
3719           }
3720           AlignedArgs[CanonPVD] = E;
3721           QualType QTy = PVD->getType()
3722                              .getNonReferenceType()
3723                              .getUnqualifiedType()
3724                              .getCanonicalType();
3725           const Type *Ty = QTy.getTypePtrOrNull();
3726           if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
3727             Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
3728                 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
3729             Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
3730           }
3731           continue;
3732         }
3733       }
3734     if (isa<CXXThisExpr>(E)) {
3735       if (AlignedThis) {
3736         Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
3737             << 2 << E->getSourceRange();
3738         Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
3739             << getOpenMPClauseName(OMPC_aligned);
3740       }
3741       AlignedThis = E;
3742       continue;
3743     }
3744     Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3745         << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
3746   }
3747   // The optional parameter of the aligned clause, alignment, must be a constant
3748   // positive integer expression. If no optional parameter is specified,
3749   // implementation-defined default alignments for SIMD instructions on the
3750   // target platforms are assumed.
3751   SmallVector<const Expr *, 4> NewAligns;
3752   for (Expr *E : Alignments) {
3753     ExprResult Align;
3754     if (E)
3755       Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
3756     NewAligns.push_back(Align.get());
3757   }
3758   // OpenMP [2.8.2, declare simd construct, Description]
3759   // The linear clause declares one or more list items to be private to a SIMD
3760   // lane and to have a linear relationship with respect to the iteration space
3761   // of a loop.
3762   // The special this pointer can be used as if was one of the arguments to the
3763   // function in any of the linear, aligned, or uniform clauses.
3764   // When a linear-step expression is specified in a linear clause it must be
3765   // either a constant integer expression or an integer-typed parameter that is
3766   // specified in a uniform clause on the directive.
3767   llvm::DenseMap<const Decl *, const Expr *> LinearArgs;
3768   const bool IsUniformedThis = UniformedLinearThis != nullptr;
3769   auto MI = LinModifiers.begin();
3770   for (const Expr *E : Linears) {
3771     auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
3772     ++MI;
3773     E = E->IgnoreParenImpCasts();
3774     if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
3775       if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3776         const VarDecl *CanonPVD = PVD->getCanonicalDecl();
3777         if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
3778             FD->getParamDecl(PVD->getFunctionScopeIndex())
3779                     ->getCanonicalDecl() == CanonPVD) {
3780           // OpenMP  [2.15.3.7, linear Clause, Restrictions]
3781           // A list-item cannot appear in more than one linear clause.
3782           if (LinearArgs.count(CanonPVD) > 0) {
3783             Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3784                 << getOpenMPClauseName(OMPC_linear)
3785                 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
3786             Diag(LinearArgs[CanonPVD]->getExprLoc(),
3787                  diag::note_omp_explicit_dsa)
3788                 << getOpenMPClauseName(OMPC_linear);
3789             continue;
3790           }
3791           // Each argument can appear in at most one uniform or linear clause.
3792           if (UniformedArgs.count(CanonPVD) > 0) {
3793             Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3794                 << getOpenMPClauseName(OMPC_linear)
3795                 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
3796             Diag(UniformedArgs[CanonPVD]->getExprLoc(),
3797                  diag::note_omp_explicit_dsa)
3798                 << getOpenMPClauseName(OMPC_uniform);
3799             continue;
3800           }
3801           LinearArgs[CanonPVD] = E;
3802           if (E->isValueDependent() || E->isTypeDependent() ||
3803               E->isInstantiationDependent() ||
3804               E->containsUnexpandedParameterPack())
3805             continue;
3806           (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
3807                                       PVD->getOriginalType());
3808           continue;
3809         }
3810       }
3811     if (isa<CXXThisExpr>(E)) {
3812       if (UniformedLinearThis) {
3813         Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3814             << getOpenMPClauseName(OMPC_linear)
3815             << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
3816             << E->getSourceRange();
3817         Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
3818             << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
3819                                                    : OMPC_linear);
3820         continue;
3821       }
3822       UniformedLinearThis = E;
3823       if (E->isValueDependent() || E->isTypeDependent() ||
3824           E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
3825         continue;
3826       (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
3827                                   E->getType());
3828       continue;
3829     }
3830     Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3831         << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
3832   }
3833   Expr *Step = nullptr;
3834   Expr *NewStep = nullptr;
3835   SmallVector<Expr *, 4> NewSteps;
3836   for (Expr *E : Steps) {
3837     // Skip the same step expression, it was checked already.
3838     if (Step == E || !E) {
3839       NewSteps.push_back(E ? NewStep : nullptr);
3840       continue;
3841     }
3842     Step = E;
3843     if (const auto *DRE = dyn_cast<DeclRefExpr>(Step))
3844       if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3845         const VarDecl *CanonPVD = PVD->getCanonicalDecl();
3846         if (UniformedArgs.count(CanonPVD) == 0) {
3847           Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
3848               << Step->getSourceRange();
3849         } else if (E->isValueDependent() || E->isTypeDependent() ||
3850                    E->isInstantiationDependent() ||
3851                    E->containsUnexpandedParameterPack() ||
3852                    CanonPVD->getType()->hasIntegerRepresentation()) {
3853           NewSteps.push_back(Step);
3854         } else {
3855           Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
3856               << Step->getSourceRange();
3857         }
3858         continue;
3859       }
3860     NewStep = Step;
3861     if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
3862         !Step->isInstantiationDependent() &&
3863         !Step->containsUnexpandedParameterPack()) {
3864       NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
3865                     .get();
3866       if (NewStep)
3867         NewStep = VerifyIntegerConstantExpression(NewStep).get();
3868     }
3869     NewSteps.push_back(NewStep);
3870   }
3871   auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
3872       Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
3873       Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
3874       const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
3875       const_cast<Expr **>(Linears.data()), Linears.size(),
3876       const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
3877       NewSteps.data(), NewSteps.size(), SR);
3878   ADecl->addAttr(NewAttr);
3879   return ConvertDeclToDeclGroup(ADecl);
3880 }
3881 
3882 StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
3883                                               Stmt *AStmt,
3884                                               SourceLocation StartLoc,
3885                                               SourceLocation EndLoc) {
3886   if (!AStmt)
3887     return StmtError();
3888 
3889   auto *CS = cast<CapturedStmt>(AStmt);
3890   // 1.2.2 OpenMP Language Terminology
3891   // Structured block - An executable statement with a single entry at the
3892   // top and a single exit at the bottom.
3893   // The point of exit cannot be a branch out of the structured block.
3894   // longjmp() and throw() must not violate the entry/exit criteria.
3895   CS->getCapturedDecl()->setNothrow();
3896 
3897   setFunctionHasBranchProtectedScope();
3898 
3899   return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
3900                                       DSAStack->isCancelRegion());
3901 }
3902 
3903 namespace {
3904 /// Helper class for checking canonical form of the OpenMP loops and
3905 /// extracting iteration space of each loop in the loop nest, that will be used
3906 /// for IR generation.
3907 class OpenMPIterationSpaceChecker {
3908   /// Reference to Sema.
3909   Sema &SemaRef;
3910   /// A location for diagnostics (when there is no some better location).
3911   SourceLocation DefaultLoc;
3912   /// A location for diagnostics (when increment is not compatible).
3913   SourceLocation ConditionLoc;
3914   /// A source location for referring to loop init later.
3915   SourceRange InitSrcRange;
3916   /// A source location for referring to condition later.
3917   SourceRange ConditionSrcRange;
3918   /// A source location for referring to increment later.
3919   SourceRange IncrementSrcRange;
3920   /// Loop variable.
3921   ValueDecl *LCDecl = nullptr;
3922   /// Reference to loop variable.
3923   Expr *LCRef = nullptr;
3924   /// Lower bound (initializer for the var).
3925   Expr *LB = nullptr;
3926   /// Upper bound.
3927   Expr *UB = nullptr;
3928   /// Loop step (increment).
3929   Expr *Step = nullptr;
3930   /// This flag is true when condition is one of:
3931   ///   Var <  UB
3932   ///   Var <= UB
3933   ///   UB  >  Var
3934   ///   UB  >= Var
3935   /// This will have no value when the condition is !=
3936   llvm::Optional<bool> TestIsLessOp;
3937   /// This flag is true when condition is strict ( < or > ).
3938   bool TestIsStrictOp = false;
3939   /// This flag is true when step is subtracted on each iteration.
3940   bool SubtractStep = false;
3941 
3942 public:
3943   OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
3944       : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {}
3945   /// Check init-expr for canonical loop form and save loop counter
3946   /// variable - #Var and its initialization value - #LB.
3947   bool checkAndSetInit(Stmt *S, bool EmitDiags = true);
3948   /// Check test-expr for canonical form, save upper-bound (#UB), flags
3949   /// for less/greater and for strict/non-strict comparison.
3950   bool checkAndSetCond(Expr *S);
3951   /// Check incr-expr for canonical loop form and return true if it
3952   /// does not conform, otherwise save loop step (#Step).
3953   bool checkAndSetInc(Expr *S);
3954   /// Return the loop counter variable.
3955   ValueDecl *getLoopDecl() const { return LCDecl; }
3956   /// Return the reference expression to loop counter variable.
3957   Expr *getLoopDeclRefExpr() const { return LCRef; }
3958   /// Source range of the loop init.
3959   SourceRange getInitSrcRange() const { return InitSrcRange; }
3960   /// Source range of the loop condition.
3961   SourceRange getConditionSrcRange() const { return ConditionSrcRange; }
3962   /// Source range of the loop increment.
3963   SourceRange getIncrementSrcRange() const { return IncrementSrcRange; }
3964   /// True if the step should be subtracted.
3965   bool shouldSubtractStep() const { return SubtractStep; }
3966   /// Build the expression to calculate the number of iterations.
3967   Expr *buildNumIterations(
3968       Scope *S, const bool LimitedType,
3969       llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
3970   /// Build the precondition expression for the loops.
3971   Expr *
3972   buildPreCond(Scope *S, Expr *Cond,
3973                llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
3974   /// Build reference expression to the counter be used for codegen.
3975   DeclRefExpr *
3976   buildCounterVar(llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
3977                   DSAStackTy &DSA) const;
3978   /// Build reference expression to the private counter be used for
3979   /// codegen.
3980   Expr *buildPrivateCounterVar() const;
3981   /// Build initialization of the counter be used for codegen.
3982   Expr *buildCounterInit() const;
3983   /// Build step of the counter be used for codegen.
3984   Expr *buildCounterStep() const;
3985   /// Build loop data with counter value for depend clauses in ordered
3986   /// directives.
3987   Expr *
3988   buildOrderedLoopData(Scope *S, Expr *Counter,
3989                        llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
3990                        SourceLocation Loc, Expr *Inc = nullptr,
3991                        OverloadedOperatorKind OOK = OO_Amp);
3992   /// Return true if any expression is dependent.
3993   bool dependent() const;
3994 
3995 private:
3996   /// Check the right-hand side of an assignment in the increment
3997   /// expression.
3998   bool checkAndSetIncRHS(Expr *RHS);
3999   /// Helper to set loop counter variable and its initializer.
4000   bool setLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB);
4001   /// Helper to set upper bound.
4002   bool setUB(Expr *NewUB, llvm::Optional<bool> LessOp, bool StrictOp,
4003              SourceRange SR, SourceLocation SL);
4004   /// Helper to set loop increment.
4005   bool setStep(Expr *NewStep, bool Subtract);
4006 };
4007 
4008 bool OpenMPIterationSpaceChecker::dependent() const {
4009   if (!LCDecl) {
4010     assert(!LB && !UB && !Step);
4011     return false;
4012   }
4013   return LCDecl->getType()->isDependentType() ||
4014          (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
4015          (Step && Step->isValueDependent());
4016 }
4017 
4018 bool OpenMPIterationSpaceChecker::setLCDeclAndLB(ValueDecl *NewLCDecl,
4019                                                  Expr *NewLCRefExpr,
4020                                                  Expr *NewLB) {
4021   // State consistency checking to ensure correct usage.
4022   assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
4023          UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
4024   if (!NewLCDecl || !NewLB)
4025     return true;
4026   LCDecl = getCanonicalDecl(NewLCDecl);
4027   LCRef = NewLCRefExpr;
4028   if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
4029     if (const CXXConstructorDecl *Ctor = CE->getConstructor())
4030       if ((Ctor->isCopyOrMoveConstructor() ||
4031            Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
4032           CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
4033         NewLB = CE->getArg(0)->IgnoreParenImpCasts();
4034   LB = NewLB;
4035   return false;
4036 }
4037 
4038 bool OpenMPIterationSpaceChecker::setUB(Expr *NewUB, llvm::Optional<bool> LessOp,
4039                                         bool StrictOp, SourceRange SR,
4040                                         SourceLocation SL) {
4041   // State consistency checking to ensure correct usage.
4042   assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
4043          Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
4044   if (!NewUB)
4045     return true;
4046   UB = NewUB;
4047   if (LessOp)
4048     TestIsLessOp = LessOp;
4049   TestIsStrictOp = StrictOp;
4050   ConditionSrcRange = SR;
4051   ConditionLoc = SL;
4052   return false;
4053 }
4054 
4055 bool OpenMPIterationSpaceChecker::setStep(Expr *NewStep, bool Subtract) {
4056   // State consistency checking to ensure correct usage.
4057   assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
4058   if (!NewStep)
4059     return true;
4060   if (!NewStep->isValueDependent()) {
4061     // Check that the step is integer expression.
4062     SourceLocation StepLoc = NewStep->getBeginLoc();
4063     ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion(
4064         StepLoc, getExprAsWritten(NewStep));
4065     if (Val.isInvalid())
4066       return true;
4067     NewStep = Val.get();
4068 
4069     // OpenMP [2.6, Canonical Loop Form, Restrictions]
4070     //  If test-expr is of form var relational-op b and relational-op is < or
4071     //  <= then incr-expr must cause var to increase on each iteration of the
4072     //  loop. If test-expr is of form var relational-op b and relational-op is
4073     //  > or >= then incr-expr must cause var to decrease on each iteration of
4074     //  the loop.
4075     //  If test-expr is of form b relational-op var and relational-op is < or
4076     //  <= then incr-expr must cause var to decrease on each iteration of the
4077     //  loop. If test-expr is of form b relational-op var and relational-op is
4078     //  > or >= then incr-expr must cause var to increase on each iteration of
4079     //  the loop.
4080     llvm::APSInt Result;
4081     bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
4082     bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
4083     bool IsConstNeg =
4084         IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
4085     bool IsConstPos =
4086         IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
4087     bool IsConstZero = IsConstant && !Result.getBoolValue();
4088 
4089     // != with increment is treated as <; != with decrement is treated as >
4090     if (!TestIsLessOp.hasValue())
4091       TestIsLessOp = IsConstPos || (IsUnsigned && !Subtract);
4092     if (UB && (IsConstZero ||
4093                (TestIsLessOp.getValue() ?
4094                   (IsConstNeg || (IsUnsigned && Subtract)) :
4095                   (IsConstPos || (IsUnsigned && !Subtract))))) {
4096       SemaRef.Diag(NewStep->getExprLoc(),
4097                    diag::err_omp_loop_incr_not_compatible)
4098           << LCDecl << TestIsLessOp.getValue() << NewStep->getSourceRange();
4099       SemaRef.Diag(ConditionLoc,
4100                    diag::note_omp_loop_cond_requres_compatible_incr)
4101           << TestIsLessOp.getValue() << ConditionSrcRange;
4102       return true;
4103     }
4104     if (TestIsLessOp.getValue() == Subtract) {
4105       NewStep =
4106           SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
4107               .get();
4108       Subtract = !Subtract;
4109     }
4110   }
4111 
4112   Step = NewStep;
4113   SubtractStep = Subtract;
4114   return false;
4115 }
4116 
4117 bool OpenMPIterationSpaceChecker::checkAndSetInit(Stmt *S, bool EmitDiags) {
4118   // Check init-expr for canonical loop form and save loop counter
4119   // variable - #Var and its initialization value - #LB.
4120   // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
4121   //   var = lb
4122   //   integer-type var = lb
4123   //   random-access-iterator-type var = lb
4124   //   pointer-type var = lb
4125   //
4126   if (!S) {
4127     if (EmitDiags) {
4128       SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
4129     }
4130     return true;
4131   }
4132   if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
4133     if (!ExprTemp->cleanupsHaveSideEffects())
4134       S = ExprTemp->getSubExpr();
4135 
4136   InitSrcRange = S->getSourceRange();
4137   if (Expr *E = dyn_cast<Expr>(S))
4138     S = E->IgnoreParens();
4139   if (auto *BO = dyn_cast<BinaryOperator>(S)) {
4140     if (BO->getOpcode() == BO_Assign) {
4141       Expr *LHS = BO->getLHS()->IgnoreParens();
4142       if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
4143         if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
4144           if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
4145             return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
4146         return setLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS());
4147       }
4148       if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
4149         if (ME->isArrow() &&
4150             isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
4151           return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
4152       }
4153     }
4154   } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
4155     if (DS->isSingleDecl()) {
4156       if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
4157         if (Var->hasInit() && !Var->getType()->isReferenceType()) {
4158           // Accept non-canonical init form here but emit ext. warning.
4159           if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
4160             SemaRef.Diag(S->getBeginLoc(),
4161                          diag::ext_omp_loop_not_canonical_init)
4162                 << S->getSourceRange();
4163           return setLCDeclAndLB(
4164               Var,
4165               buildDeclRefExpr(SemaRef, Var,
4166                                Var->getType().getNonReferenceType(),
4167                                DS->getBeginLoc()),
4168               Var->getInit());
4169         }
4170       }
4171     }
4172   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
4173     if (CE->getOperator() == OO_Equal) {
4174       Expr *LHS = CE->getArg(0);
4175       if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
4176         if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
4177           if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
4178             return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
4179         return setLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1));
4180       }
4181       if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
4182         if (ME->isArrow() &&
4183             isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
4184           return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
4185       }
4186     }
4187   }
4188 
4189   if (dependent() || SemaRef.CurContext->isDependentContext())
4190     return false;
4191   if (EmitDiags) {
4192     SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_init)
4193         << S->getSourceRange();
4194   }
4195   return true;
4196 }
4197 
4198 /// Ignore parenthesizes, implicit casts, copy constructor and return the
4199 /// variable (which may be the loop variable) if possible.
4200 static const ValueDecl *getInitLCDecl(const Expr *E) {
4201   if (!E)
4202     return nullptr;
4203   E = getExprAsWritten(E);
4204   if (const auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
4205     if (const CXXConstructorDecl *Ctor = CE->getConstructor())
4206       if ((Ctor->isCopyOrMoveConstructor() ||
4207            Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
4208           CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
4209         E = CE->getArg(0)->IgnoreParenImpCasts();
4210   if (const auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
4211     if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
4212       return getCanonicalDecl(VD);
4213   }
4214   if (const auto *ME = dyn_cast_or_null<MemberExpr>(E))
4215     if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
4216       return getCanonicalDecl(ME->getMemberDecl());
4217   return nullptr;
4218 }
4219 
4220 bool OpenMPIterationSpaceChecker::checkAndSetCond(Expr *S) {
4221   // Check test-expr for canonical form, save upper-bound UB, flags for
4222   // less/greater and for strict/non-strict comparison.
4223   // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
4224   //   var relational-op b
4225   //   b relational-op var
4226   //
4227   if (!S) {
4228     SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl;
4229     return true;
4230   }
4231   S = getExprAsWritten(S);
4232   SourceLocation CondLoc = S->getBeginLoc();
4233   if (auto *BO = dyn_cast<BinaryOperator>(S)) {
4234     if (BO->isRelationalOp()) {
4235       if (getInitLCDecl(BO->getLHS()) == LCDecl)
4236         return setUB(BO->getRHS(),
4237                      (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
4238                      (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
4239                      BO->getSourceRange(), BO->getOperatorLoc());
4240       if (getInitLCDecl(BO->getRHS()) == LCDecl)
4241         return setUB(BO->getLHS(),
4242                      (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
4243                      (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
4244                      BO->getSourceRange(), BO->getOperatorLoc());
4245     } else if (BO->getOpcode() == BO_NE)
4246         return setUB(getInitLCDecl(BO->getLHS()) == LCDecl ?
4247                        BO->getRHS() : BO->getLHS(),
4248                      /*LessOp=*/llvm::None,
4249                      /*StrictOp=*/true,
4250                      BO->getSourceRange(), BO->getOperatorLoc());
4251   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
4252     if (CE->getNumArgs() == 2) {
4253       auto Op = CE->getOperator();
4254       switch (Op) {
4255       case OO_Greater:
4256       case OO_GreaterEqual:
4257       case OO_Less:
4258       case OO_LessEqual:
4259         if (getInitLCDecl(CE->getArg(0)) == LCDecl)
4260           return setUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
4261                        Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
4262                        CE->getOperatorLoc());
4263         if (getInitLCDecl(CE->getArg(1)) == LCDecl)
4264           return setUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
4265                        Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
4266                        CE->getOperatorLoc());
4267         break;
4268       case OO_ExclaimEqual:
4269         return setUB(getInitLCDecl(CE->getArg(0)) == LCDecl ?
4270                      CE->getArg(1) : CE->getArg(0),
4271                      /*LessOp=*/llvm::None,
4272                      /*StrictOp=*/true,
4273                      CE->getSourceRange(),
4274                      CE->getOperatorLoc());
4275         break;
4276       default:
4277         break;
4278       }
4279     }
4280   }
4281   if (dependent() || SemaRef.CurContext->isDependentContext())
4282     return false;
4283   SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
4284       << S->getSourceRange() << LCDecl;
4285   return true;
4286 }
4287 
4288 bool OpenMPIterationSpaceChecker::checkAndSetIncRHS(Expr *RHS) {
4289   // RHS of canonical loop form increment can be:
4290   //   var + incr
4291   //   incr + var
4292   //   var - incr
4293   //
4294   RHS = RHS->IgnoreParenImpCasts();
4295   if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
4296     if (BO->isAdditiveOp()) {
4297       bool IsAdd = BO->getOpcode() == BO_Add;
4298       if (getInitLCDecl(BO->getLHS()) == LCDecl)
4299         return setStep(BO->getRHS(), !IsAdd);
4300       if (IsAdd && getInitLCDecl(BO->getRHS()) == LCDecl)
4301         return setStep(BO->getLHS(), /*Subtract=*/false);
4302     }
4303   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
4304     bool IsAdd = CE->getOperator() == OO_Plus;
4305     if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
4306       if (getInitLCDecl(CE->getArg(0)) == LCDecl)
4307         return setStep(CE->getArg(1), !IsAdd);
4308       if (IsAdd && getInitLCDecl(CE->getArg(1)) == LCDecl)
4309         return setStep(CE->getArg(0), /*Subtract=*/false);
4310     }
4311   }
4312   if (dependent() || SemaRef.CurContext->isDependentContext())
4313     return false;
4314   SemaRef.Diag(RHS->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
4315       << RHS->getSourceRange() << LCDecl;
4316   return true;
4317 }
4318 
4319 bool OpenMPIterationSpaceChecker::checkAndSetInc(Expr *S) {
4320   // Check incr-expr for canonical loop form and return true if it
4321   // does not conform.
4322   // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
4323   //   ++var
4324   //   var++
4325   //   --var
4326   //   var--
4327   //   var += incr
4328   //   var -= incr
4329   //   var = var + incr
4330   //   var = incr + var
4331   //   var = var - incr
4332   //
4333   if (!S) {
4334     SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
4335     return true;
4336   }
4337   if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
4338     if (!ExprTemp->cleanupsHaveSideEffects())
4339       S = ExprTemp->getSubExpr();
4340 
4341   IncrementSrcRange = S->getSourceRange();
4342   S = S->IgnoreParens();
4343   if (auto *UO = dyn_cast<UnaryOperator>(S)) {
4344     if (UO->isIncrementDecrementOp() &&
4345         getInitLCDecl(UO->getSubExpr()) == LCDecl)
4346       return setStep(SemaRef
4347                          .ActOnIntegerConstant(UO->getBeginLoc(),
4348                                                (UO->isDecrementOp() ? -1 : 1))
4349                          .get(),
4350                      /*Subtract=*/false);
4351   } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
4352     switch (BO->getOpcode()) {
4353     case BO_AddAssign:
4354     case BO_SubAssign:
4355       if (getInitLCDecl(BO->getLHS()) == LCDecl)
4356         return setStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
4357       break;
4358     case BO_Assign:
4359       if (getInitLCDecl(BO->getLHS()) == LCDecl)
4360         return checkAndSetIncRHS(BO->getRHS());
4361       break;
4362     default:
4363       break;
4364     }
4365   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
4366     switch (CE->getOperator()) {
4367     case OO_PlusPlus:
4368     case OO_MinusMinus:
4369       if (getInitLCDecl(CE->getArg(0)) == LCDecl)
4370         return setStep(SemaRef
4371                            .ActOnIntegerConstant(
4372                                CE->getBeginLoc(),
4373                                ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
4374                            .get(),
4375                        /*Subtract=*/false);
4376       break;
4377     case OO_PlusEqual:
4378     case OO_MinusEqual:
4379       if (getInitLCDecl(CE->getArg(0)) == LCDecl)
4380         return setStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
4381       break;
4382     case OO_Equal:
4383       if (getInitLCDecl(CE->getArg(0)) == LCDecl)
4384         return checkAndSetIncRHS(CE->getArg(1));
4385       break;
4386     default:
4387       break;
4388     }
4389   }
4390   if (dependent() || SemaRef.CurContext->isDependentContext())
4391     return false;
4392   SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
4393       << S->getSourceRange() << LCDecl;
4394   return true;
4395 }
4396 
4397 static ExprResult
4398 tryBuildCapture(Sema &SemaRef, Expr *Capture,
4399                 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
4400   if (SemaRef.CurContext->isDependentContext())
4401     return ExprResult(Capture);
4402   if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
4403     return SemaRef.PerformImplicitConversion(
4404         Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
4405         /*AllowExplicit=*/true);
4406   auto I = Captures.find(Capture);
4407   if (I != Captures.end())
4408     return buildCapture(SemaRef, Capture, I->second);
4409   DeclRefExpr *Ref = nullptr;
4410   ExprResult Res = buildCapture(SemaRef, Capture, Ref);
4411   Captures[Capture] = Ref;
4412   return Res;
4413 }
4414 
4415 /// Build the expression to calculate the number of iterations.
4416 Expr *OpenMPIterationSpaceChecker::buildNumIterations(
4417     Scope *S, const bool LimitedType,
4418     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
4419   ExprResult Diff;
4420   QualType VarType = LCDecl->getType().getNonReferenceType();
4421   if (VarType->isIntegerType() || VarType->isPointerType() ||
4422       SemaRef.getLangOpts().CPlusPlus) {
4423     // Upper - Lower
4424     Expr *UBExpr = TestIsLessOp.getValue() ? UB : LB;
4425     Expr *LBExpr = TestIsLessOp.getValue() ? LB : UB;
4426     Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
4427     Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
4428     if (!Upper || !Lower)
4429       return nullptr;
4430 
4431     Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
4432 
4433     if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
4434       // BuildBinOp already emitted error, this one is to point user to upper
4435       // and lower bound, and to tell what is passed to 'operator-'.
4436       SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
4437           << Upper->getSourceRange() << Lower->getSourceRange();
4438       return nullptr;
4439     }
4440   }
4441 
4442   if (!Diff.isUsable())
4443     return nullptr;
4444 
4445   // Upper - Lower [- 1]
4446   if (TestIsStrictOp)
4447     Diff = SemaRef.BuildBinOp(
4448         S, DefaultLoc, BO_Sub, Diff.get(),
4449         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4450   if (!Diff.isUsable())
4451     return nullptr;
4452 
4453   // Upper - Lower [- 1] + Step
4454   ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
4455   if (!NewStep.isUsable())
4456     return nullptr;
4457   Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
4458   if (!Diff.isUsable())
4459     return nullptr;
4460 
4461   // Parentheses (for dumping/debugging purposes only).
4462   Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
4463   if (!Diff.isUsable())
4464     return nullptr;
4465 
4466   // (Upper - Lower [- 1] + Step) / Step
4467   Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
4468   if (!Diff.isUsable())
4469     return nullptr;
4470 
4471   // OpenMP runtime requires 32-bit or 64-bit loop variables.
4472   QualType Type = Diff.get()->getType();
4473   ASTContext &C = SemaRef.Context;
4474   bool UseVarType = VarType->hasIntegerRepresentation() &&
4475                     C.getTypeSize(Type) > C.getTypeSize(VarType);
4476   if (!Type->isIntegerType() || UseVarType) {
4477     unsigned NewSize =
4478         UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
4479     bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
4480                                : Type->hasSignedIntegerRepresentation();
4481     Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
4482     if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
4483       Diff = SemaRef.PerformImplicitConversion(
4484           Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
4485       if (!Diff.isUsable())
4486         return nullptr;
4487     }
4488   }
4489   if (LimitedType) {
4490     unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
4491     if (NewSize != C.getTypeSize(Type)) {
4492       if (NewSize < C.getTypeSize(Type)) {
4493         assert(NewSize == 64 && "incorrect loop var size");
4494         SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
4495             << InitSrcRange << ConditionSrcRange;
4496       }
4497       QualType NewType = C.getIntTypeForBitwidth(
4498           NewSize, Type->hasSignedIntegerRepresentation() ||
4499                        C.getTypeSize(Type) < NewSize);
4500       if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
4501         Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
4502                                                  Sema::AA_Converting, true);
4503         if (!Diff.isUsable())
4504           return nullptr;
4505       }
4506     }
4507   }
4508 
4509   return Diff.get();
4510 }
4511 
4512 Expr *OpenMPIterationSpaceChecker::buildPreCond(
4513     Scope *S, Expr *Cond,
4514     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
4515   // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
4516   bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
4517   SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
4518 
4519   ExprResult NewLB = tryBuildCapture(SemaRef, LB, Captures);
4520   ExprResult NewUB = tryBuildCapture(SemaRef, UB, Captures);
4521   if (!NewLB.isUsable() || !NewUB.isUsable())
4522     return nullptr;
4523 
4524   ExprResult CondExpr =
4525       SemaRef.BuildBinOp(S, DefaultLoc,
4526                          TestIsLessOp.getValue() ?
4527                            (TestIsStrictOp ? BO_LT : BO_LE) :
4528                            (TestIsStrictOp ? BO_GT : BO_GE),
4529                          NewLB.get(), NewUB.get());
4530   if (CondExpr.isUsable()) {
4531     if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
4532                                                 SemaRef.Context.BoolTy))
4533       CondExpr = SemaRef.PerformImplicitConversion(
4534           CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
4535           /*AllowExplicit=*/true);
4536   }
4537   SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
4538   // Otherwise use original loop conditon and evaluate it in runtime.
4539   return CondExpr.isUsable() ? CondExpr.get() : Cond;
4540 }
4541 
4542 /// Build reference expression to the counter be used for codegen.
4543 DeclRefExpr *OpenMPIterationSpaceChecker::buildCounterVar(
4544     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
4545     DSAStackTy &DSA) const {
4546   auto *VD = dyn_cast<VarDecl>(LCDecl);
4547   if (!VD) {
4548     VD = SemaRef.isOpenMPCapturedDecl(LCDecl);
4549     DeclRefExpr *Ref = buildDeclRefExpr(
4550         SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
4551     const DSAStackTy::DSAVarData Data =
4552         DSA.getTopDSA(LCDecl, /*FromParent=*/false);
4553     // If the loop control decl is explicitly marked as private, do not mark it
4554     // as captured again.
4555     if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
4556       Captures.insert(std::make_pair(LCRef, Ref));
4557     return Ref;
4558   }
4559   return buildDeclRefExpr(SemaRef, VD, VD->getType().getNonReferenceType(),
4560                           DefaultLoc);
4561 }
4562 
4563 Expr *OpenMPIterationSpaceChecker::buildPrivateCounterVar() const {
4564   if (LCDecl && !LCDecl->isInvalidDecl()) {
4565     QualType Type = LCDecl->getType().getNonReferenceType();
4566     VarDecl *PrivateVar = buildVarDecl(
4567         SemaRef, DefaultLoc, Type, LCDecl->getName(),
4568         LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr,
4569         isa<VarDecl>(LCDecl)
4570             ? buildDeclRefExpr(SemaRef, cast<VarDecl>(LCDecl), Type, DefaultLoc)
4571             : nullptr);
4572     if (PrivateVar->isInvalidDecl())
4573       return nullptr;
4574     return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
4575   }
4576   return nullptr;
4577 }
4578 
4579 /// Build initialization of the counter to be used for codegen.
4580 Expr *OpenMPIterationSpaceChecker::buildCounterInit() const { return LB; }
4581 
4582 /// Build step of the counter be used for codegen.
4583 Expr *OpenMPIterationSpaceChecker::buildCounterStep() const { return Step; }
4584 
4585 Expr *OpenMPIterationSpaceChecker::buildOrderedLoopData(
4586     Scope *S, Expr *Counter,
4587     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, SourceLocation Loc,
4588     Expr *Inc, OverloadedOperatorKind OOK) {
4589   Expr *Cnt = SemaRef.DefaultLvalueConversion(Counter).get();
4590   if (!Cnt)
4591     return nullptr;
4592   if (Inc) {
4593     assert((OOK == OO_Plus || OOK == OO_Minus) &&
4594            "Expected only + or - operations for depend clauses.");
4595     BinaryOperatorKind BOK = (OOK == OO_Plus) ? BO_Add : BO_Sub;
4596     Cnt = SemaRef.BuildBinOp(S, Loc, BOK, Cnt, Inc).get();
4597     if (!Cnt)
4598       return nullptr;
4599   }
4600   ExprResult Diff;
4601   QualType VarType = LCDecl->getType().getNonReferenceType();
4602   if (VarType->isIntegerType() || VarType->isPointerType() ||
4603       SemaRef.getLangOpts().CPlusPlus) {
4604     // Upper - Lower
4605     Expr *Upper =
4606         TestIsLessOp.getValue() ? Cnt : tryBuildCapture(SemaRef, UB, Captures).get();
4607     Expr *Lower =
4608         TestIsLessOp.getValue() ? tryBuildCapture(SemaRef, LB, Captures).get() : Cnt;
4609     if (!Upper || !Lower)
4610       return nullptr;
4611 
4612     Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
4613 
4614     if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
4615       // BuildBinOp already emitted error, this one is to point user to upper
4616       // and lower bound, and to tell what is passed to 'operator-'.
4617       SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
4618           << Upper->getSourceRange() << Lower->getSourceRange();
4619       return nullptr;
4620     }
4621   }
4622 
4623   if (!Diff.isUsable())
4624     return nullptr;
4625 
4626   // Parentheses (for dumping/debugging purposes only).
4627   Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
4628   if (!Diff.isUsable())
4629     return nullptr;
4630 
4631   ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
4632   if (!NewStep.isUsable())
4633     return nullptr;
4634   // (Upper - Lower) / Step
4635   Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
4636   if (!Diff.isUsable())
4637     return nullptr;
4638 
4639   return Diff.get();
4640 }
4641 
4642 /// Iteration space of a single for loop.
4643 struct LoopIterationSpace final {
4644   /// Condition of the loop.
4645   Expr *PreCond = nullptr;
4646   /// This expression calculates the number of iterations in the loop.
4647   /// It is always possible to calculate it before starting the loop.
4648   Expr *NumIterations = nullptr;
4649   /// The loop counter variable.
4650   Expr *CounterVar = nullptr;
4651   /// Private loop counter variable.
4652   Expr *PrivateCounterVar = nullptr;
4653   /// This is initializer for the initial value of #CounterVar.
4654   Expr *CounterInit = nullptr;
4655   /// This is step for the #CounterVar used to generate its update:
4656   /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
4657   Expr *CounterStep = nullptr;
4658   /// Should step be subtracted?
4659   bool Subtract = false;
4660   /// Source range of the loop init.
4661   SourceRange InitSrcRange;
4662   /// Source range of the loop condition.
4663   SourceRange CondSrcRange;
4664   /// Source range of the loop increment.
4665   SourceRange IncSrcRange;
4666 };
4667 
4668 } // namespace
4669 
4670 void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
4671   assert(getLangOpts().OpenMP && "OpenMP is not active.");
4672   assert(Init && "Expected loop in canonical form.");
4673   unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
4674   if (AssociatedLoops > 0 &&
4675       isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
4676     DSAStack->loopStart();
4677     OpenMPIterationSpaceChecker ISC(*this, ForLoc);
4678     if (!ISC.checkAndSetInit(Init, /*EmitDiags=*/false)) {
4679       if (ValueDecl *D = ISC.getLoopDecl()) {
4680         auto *VD = dyn_cast<VarDecl>(D);
4681         if (!VD) {
4682           if (VarDecl *Private = isOpenMPCapturedDecl(D)) {
4683             VD = Private;
4684           } else {
4685             DeclRefExpr *Ref = buildCapture(*this, D, ISC.getLoopDeclRefExpr(),
4686                                             /*WithInit=*/false);
4687             VD = cast<VarDecl>(Ref->getDecl());
4688           }
4689         }
4690         DSAStack->addLoopControlVariable(D, VD);
4691         const Decl *LD = DSAStack->getPossiblyLoopCunter();
4692         if (LD != D->getCanonicalDecl()) {
4693           DSAStack->resetPossibleLoopCounter();
4694           if (auto *Var = dyn_cast_or_null<VarDecl>(LD))
4695             MarkDeclarationsReferencedInExpr(
4696                 buildDeclRefExpr(*this, const_cast<VarDecl *>(Var),
4697                                  Var->getType().getNonLValueExprType(Context),
4698                                  ForLoc, /*RefersToCapture=*/true));
4699         }
4700       }
4701     }
4702     DSAStack->setAssociatedLoops(AssociatedLoops - 1);
4703   }
4704 }
4705 
4706 /// Called on a for stmt to check and extract its iteration space
4707 /// for further processing (such as collapsing).
4708 static bool checkOpenMPIterationSpace(
4709     OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
4710     unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
4711     unsigned TotalNestedLoopCount, Expr *CollapseLoopCountExpr,
4712     Expr *OrderedLoopCountExpr,
4713     Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
4714     LoopIterationSpace &ResultIterSpace,
4715     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
4716   // OpenMP [2.6, Canonical Loop Form]
4717   //   for (init-expr; test-expr; incr-expr) structured-block
4718   auto *For = dyn_cast_or_null<ForStmt>(S);
4719   if (!For) {
4720     SemaRef.Diag(S->getBeginLoc(), diag::err_omp_not_for)
4721         << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
4722         << getOpenMPDirectiveName(DKind) << TotalNestedLoopCount
4723         << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
4724     if (TotalNestedLoopCount > 1) {
4725       if (CollapseLoopCountExpr && OrderedLoopCountExpr)
4726         SemaRef.Diag(DSA.getConstructLoc(),
4727                      diag::note_omp_collapse_ordered_expr)
4728             << 2 << CollapseLoopCountExpr->getSourceRange()
4729             << OrderedLoopCountExpr->getSourceRange();
4730       else if (CollapseLoopCountExpr)
4731         SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
4732                      diag::note_omp_collapse_ordered_expr)
4733             << 0 << CollapseLoopCountExpr->getSourceRange();
4734       else
4735         SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
4736                      diag::note_omp_collapse_ordered_expr)
4737             << 1 << OrderedLoopCountExpr->getSourceRange();
4738     }
4739     return true;
4740   }
4741   assert(For->getBody());
4742 
4743   OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
4744 
4745   // Check init.
4746   Stmt *Init = For->getInit();
4747   if (ISC.checkAndSetInit(Init))
4748     return true;
4749 
4750   bool HasErrors = false;
4751 
4752   // Check loop variable's type.
4753   if (ValueDecl *LCDecl = ISC.getLoopDecl()) {
4754     Expr *LoopDeclRefExpr = ISC.getLoopDeclRefExpr();
4755 
4756     // OpenMP [2.6, Canonical Loop Form]
4757     // Var is one of the following:
4758     //   A variable of signed or unsigned integer type.
4759     //   For C++, a variable of a random access iterator type.
4760     //   For C, a variable of a pointer type.
4761     QualType VarType = LCDecl->getType().getNonReferenceType();
4762     if (!VarType->isDependentType() && !VarType->isIntegerType() &&
4763         !VarType->isPointerType() &&
4764         !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
4765       SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_variable_type)
4766           << SemaRef.getLangOpts().CPlusPlus;
4767       HasErrors = true;
4768     }
4769 
4770     // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
4771     // a Construct
4772     // The loop iteration variable(s) in the associated for-loop(s) of a for or
4773     // parallel for construct is (are) private.
4774     // The loop iteration variable in the associated for-loop of a simd
4775     // construct with just one associated for-loop is linear with a
4776     // constant-linear-step that is the increment of the associated for-loop.
4777     // Exclude loop var from the list of variables with implicitly defined data
4778     // sharing attributes.
4779     VarsWithImplicitDSA.erase(LCDecl);
4780 
4781     // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
4782     // in a Construct, C/C++].
4783     // The loop iteration variable in the associated for-loop of a simd
4784     // construct with just one associated for-loop may be listed in a linear
4785     // clause with a constant-linear-step that is the increment of the
4786     // associated for-loop.
4787     // The loop iteration variable(s) in the associated for-loop(s) of a for or
4788     // parallel for construct may be listed in a private or lastprivate clause.
4789     DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false);
4790     // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
4791     // declared in the loop and it is predetermined as a private.
4792     OpenMPClauseKind PredeterminedCKind =
4793         isOpenMPSimdDirective(DKind)
4794             ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
4795             : OMPC_private;
4796     if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
4797           DVar.CKind != PredeterminedCKind) ||
4798          ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
4799            isOpenMPDistributeDirective(DKind)) &&
4800           !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
4801           DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
4802         (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
4803       SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_var_dsa)
4804           << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
4805           << getOpenMPClauseName(PredeterminedCKind);
4806       if (DVar.RefExpr == nullptr)
4807         DVar.CKind = PredeterminedCKind;
4808       reportOriginalDsa(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true);
4809       HasErrors = true;
4810     } else if (LoopDeclRefExpr != nullptr) {
4811       // Make the loop iteration variable private (for worksharing constructs),
4812       // linear (for simd directives with the only one associated loop) or
4813       // lastprivate (for simd directives with several collapsed or ordered
4814       // loops).
4815       if (DVar.CKind == OMPC_unknown)
4816         DVar = DSA.hasDSA(LCDecl, isOpenMPPrivate,
4817                           [](OpenMPDirectiveKind) -> bool { return true; },
4818                           /*FromParent=*/false);
4819       DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind);
4820     }
4821 
4822     assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
4823 
4824     // Check test-expr.
4825     HasErrors |= ISC.checkAndSetCond(For->getCond());
4826 
4827     // Check incr-expr.
4828     HasErrors |= ISC.checkAndSetInc(For->getInc());
4829   }
4830 
4831   if (ISC.dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
4832     return HasErrors;
4833 
4834   // Build the loop's iteration space representation.
4835   ResultIterSpace.PreCond =
4836       ISC.buildPreCond(DSA.getCurScope(), For->getCond(), Captures);
4837   ResultIterSpace.NumIterations = ISC.buildNumIterations(
4838       DSA.getCurScope(),
4839       (isOpenMPWorksharingDirective(DKind) ||
4840        isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)),
4841       Captures);
4842   ResultIterSpace.CounterVar = ISC.buildCounterVar(Captures, DSA);
4843   ResultIterSpace.PrivateCounterVar = ISC.buildPrivateCounterVar();
4844   ResultIterSpace.CounterInit = ISC.buildCounterInit();
4845   ResultIterSpace.CounterStep = ISC.buildCounterStep();
4846   ResultIterSpace.InitSrcRange = ISC.getInitSrcRange();
4847   ResultIterSpace.CondSrcRange = ISC.getConditionSrcRange();
4848   ResultIterSpace.IncSrcRange = ISC.getIncrementSrcRange();
4849   ResultIterSpace.Subtract = ISC.shouldSubtractStep();
4850 
4851   HasErrors |= (ResultIterSpace.PreCond == nullptr ||
4852                 ResultIterSpace.NumIterations == nullptr ||
4853                 ResultIterSpace.CounterVar == nullptr ||
4854                 ResultIterSpace.PrivateCounterVar == nullptr ||
4855                 ResultIterSpace.CounterInit == nullptr ||
4856                 ResultIterSpace.CounterStep == nullptr);
4857   if (!HasErrors && DSA.isOrderedRegion()) {
4858     if (DSA.getOrderedRegionParam().second->getNumForLoops()) {
4859       if (CurrentNestedLoopCount <
4860           DSA.getOrderedRegionParam().second->getLoopNumIterations().size()) {
4861         DSA.getOrderedRegionParam().second->setLoopNumIterations(
4862             CurrentNestedLoopCount, ResultIterSpace.NumIterations);
4863         DSA.getOrderedRegionParam().second->setLoopCounter(
4864             CurrentNestedLoopCount, ResultIterSpace.CounterVar);
4865       }
4866     }
4867     for (auto &Pair : DSA.getDoacrossDependClauses()) {
4868       if (CurrentNestedLoopCount >= Pair.first->getNumLoops()) {
4869         // Erroneous case - clause has some problems.
4870         continue;
4871       }
4872       if (Pair.first->getDependencyKind() == OMPC_DEPEND_sink &&
4873           Pair.second.size() <= CurrentNestedLoopCount) {
4874         // Erroneous case - clause has some problems.
4875         Pair.first->setLoopData(CurrentNestedLoopCount, nullptr);
4876         continue;
4877       }
4878       Expr *CntValue;
4879       if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
4880         CntValue = ISC.buildOrderedLoopData(
4881             DSA.getCurScope(), ResultIterSpace.CounterVar, Captures,
4882             Pair.first->getDependencyLoc());
4883       else
4884         CntValue = ISC.buildOrderedLoopData(
4885             DSA.getCurScope(), ResultIterSpace.CounterVar, Captures,
4886             Pair.first->getDependencyLoc(),
4887             Pair.second[CurrentNestedLoopCount].first,
4888             Pair.second[CurrentNestedLoopCount].second);
4889       Pair.first->setLoopData(CurrentNestedLoopCount, CntValue);
4890     }
4891   }
4892 
4893   return HasErrors;
4894 }
4895 
4896 /// Build 'VarRef = Start.
4897 static ExprResult
4898 buildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
4899                  ExprResult Start,
4900                  llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
4901   // Build 'VarRef = Start.
4902   ExprResult NewStart = tryBuildCapture(SemaRef, Start.get(), Captures);
4903   if (!NewStart.isUsable())
4904     return ExprError();
4905   if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
4906                                    VarRef.get()->getType())) {
4907     NewStart = SemaRef.PerformImplicitConversion(
4908         NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
4909         /*AllowExplicit=*/true);
4910     if (!NewStart.isUsable())
4911       return ExprError();
4912   }
4913 
4914   ExprResult Init =
4915       SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
4916   return Init;
4917 }
4918 
4919 /// Build 'VarRef = Start + Iter * Step'.
4920 static ExprResult buildCounterUpdate(
4921     Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
4922     ExprResult Start, ExprResult Iter, ExprResult Step, bool Subtract,
4923     llvm::MapVector<const Expr *, DeclRefExpr *> *Captures = nullptr) {
4924   // Add parentheses (for debugging purposes only).
4925   Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
4926   if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
4927       !Step.isUsable())
4928     return ExprError();
4929 
4930   ExprResult NewStep = Step;
4931   if (Captures)
4932     NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
4933   if (NewStep.isInvalid())
4934     return ExprError();
4935   ExprResult Update =
4936       SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
4937   if (!Update.isUsable())
4938     return ExprError();
4939 
4940   // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
4941   // 'VarRef = Start (+|-) Iter * Step'.
4942   ExprResult NewStart = Start;
4943   if (Captures)
4944     NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
4945   if (NewStart.isInvalid())
4946     return ExprError();
4947 
4948   // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
4949   ExprResult SavedUpdate = Update;
4950   ExprResult UpdateVal;
4951   if (VarRef.get()->getType()->isOverloadableType() ||
4952       NewStart.get()->getType()->isOverloadableType() ||
4953       Update.get()->getType()->isOverloadableType()) {
4954     bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
4955     SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
4956     Update =
4957         SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
4958     if (Update.isUsable()) {
4959       UpdateVal =
4960           SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
4961                              VarRef.get(), SavedUpdate.get());
4962       if (UpdateVal.isUsable()) {
4963         Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
4964                                             UpdateVal.get());
4965       }
4966     }
4967     SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
4968   }
4969 
4970   // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
4971   if (!Update.isUsable() || !UpdateVal.isUsable()) {
4972     Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
4973                                 NewStart.get(), SavedUpdate.get());
4974     if (!Update.isUsable())
4975       return ExprError();
4976 
4977     if (!SemaRef.Context.hasSameType(Update.get()->getType(),
4978                                      VarRef.get()->getType())) {
4979       Update = SemaRef.PerformImplicitConversion(
4980           Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
4981       if (!Update.isUsable())
4982         return ExprError();
4983     }
4984 
4985     Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
4986   }
4987   return Update;
4988 }
4989 
4990 /// Convert integer expression \a E to make it have at least \a Bits
4991 /// bits.
4992 static ExprResult widenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
4993   if (E == nullptr)
4994     return ExprError();
4995   ASTContext &C = SemaRef.Context;
4996   QualType OldType = E->getType();
4997   unsigned HasBits = C.getTypeSize(OldType);
4998   if (HasBits >= Bits)
4999     return ExprResult(E);
5000   // OK to convert to signed, because new type has more bits than old.
5001   QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
5002   return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
5003                                            true);
5004 }
5005 
5006 /// Check if the given expression \a E is a constant integer that fits
5007 /// into \a Bits bits.
5008 static bool fitsInto(unsigned Bits, bool Signed, const Expr *E, Sema &SemaRef) {
5009   if (E == nullptr)
5010     return false;
5011   llvm::APSInt Result;
5012   if (E->isIntegerConstantExpr(Result, SemaRef.Context))
5013     return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
5014   return false;
5015 }
5016 
5017 /// Build preinits statement for the given declarations.
5018 static Stmt *buildPreInits(ASTContext &Context,
5019                            MutableArrayRef<Decl *> PreInits) {
5020   if (!PreInits.empty()) {
5021     return new (Context) DeclStmt(
5022         DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
5023         SourceLocation(), SourceLocation());
5024   }
5025   return nullptr;
5026 }
5027 
5028 /// Build preinits statement for the given declarations.
5029 static Stmt *
5030 buildPreInits(ASTContext &Context,
5031               const llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
5032   if (!Captures.empty()) {
5033     SmallVector<Decl *, 16> PreInits;
5034     for (const auto &Pair : Captures)
5035       PreInits.push_back(Pair.second->getDecl());
5036     return buildPreInits(Context, PreInits);
5037   }
5038   return nullptr;
5039 }
5040 
5041 /// Build postupdate expression for the given list of postupdates expressions.
5042 static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
5043   Expr *PostUpdate = nullptr;
5044   if (!PostUpdates.empty()) {
5045     for (Expr *E : PostUpdates) {
5046       Expr *ConvE = S.BuildCStyleCastExpr(
5047                          E->getExprLoc(),
5048                          S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
5049                          E->getExprLoc(), E)
5050                         .get();
5051       PostUpdate = PostUpdate
5052                        ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
5053                                               PostUpdate, ConvE)
5054                              .get()
5055                        : ConvE;
5056     }
5057   }
5058   return PostUpdate;
5059 }
5060 
5061 /// Called on a for stmt to check itself and nested loops (if any).
5062 /// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
5063 /// number of collapsed loops otherwise.
5064 static unsigned
5065 checkOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
5066                 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
5067                 DSAStackTy &DSA,
5068                 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
5069                 OMPLoopDirective::HelperExprs &Built) {
5070   unsigned NestedLoopCount = 1;
5071   if (CollapseLoopCountExpr) {
5072     // Found 'collapse' clause - calculate collapse number.
5073     Expr::EvalResult Result;
5074     if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
5075       NestedLoopCount = Result.Val.getInt().getLimitedValue();
5076   }
5077   unsigned OrderedLoopCount = 1;
5078   if (OrderedLoopCountExpr) {
5079     // Found 'ordered' clause - calculate collapse number.
5080     Expr::EvalResult EVResult;
5081     if (OrderedLoopCountExpr->EvaluateAsInt(EVResult, SemaRef.getASTContext())) {
5082       llvm::APSInt Result = EVResult.Val.getInt();
5083       if (Result.getLimitedValue() < NestedLoopCount) {
5084         SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
5085                      diag::err_omp_wrong_ordered_loop_count)
5086             << OrderedLoopCountExpr->getSourceRange();
5087         SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
5088                      diag::note_collapse_loop_count)
5089             << CollapseLoopCountExpr->getSourceRange();
5090       }
5091       OrderedLoopCount = Result.getLimitedValue();
5092     }
5093   }
5094   // This is helper routine for loop directives (e.g., 'for', 'simd',
5095   // 'for simd', etc.).
5096   llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
5097   SmallVector<LoopIterationSpace, 4> IterSpaces;
5098   IterSpaces.resize(std::max(OrderedLoopCount, NestedLoopCount));
5099   Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
5100   for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
5101     if (checkOpenMPIterationSpace(
5102             DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
5103             std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
5104             OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces[Cnt],
5105             Captures))
5106       return 0;
5107     // Move on to the next nested for loop, or to the loop body.
5108     // OpenMP [2.8.1, simd construct, Restrictions]
5109     // All loops associated with the construct must be perfectly nested; that
5110     // is, there must be no intervening code nor any OpenMP directive between
5111     // any two loops.
5112     CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
5113   }
5114   for (unsigned Cnt = NestedLoopCount; Cnt < OrderedLoopCount; ++Cnt) {
5115     if (checkOpenMPIterationSpace(
5116             DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
5117             std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
5118             OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces[Cnt],
5119             Captures))
5120       return 0;
5121     if (Cnt > 0 && IterSpaces[Cnt].CounterVar) {
5122       // Handle initialization of captured loop iterator variables.
5123       auto *DRE = cast<DeclRefExpr>(IterSpaces[Cnt].CounterVar);
5124       if (isa<OMPCapturedExprDecl>(DRE->getDecl())) {
5125         Captures[DRE] = DRE;
5126       }
5127     }
5128     // Move on to the next nested for loop, or to the loop body.
5129     // OpenMP [2.8.1, simd construct, Restrictions]
5130     // All loops associated with the construct must be perfectly nested; that
5131     // is, there must be no intervening code nor any OpenMP directive between
5132     // any two loops.
5133     CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
5134   }
5135 
5136   Built.clear(/* size */ NestedLoopCount);
5137 
5138   if (SemaRef.CurContext->isDependentContext())
5139     return NestedLoopCount;
5140 
5141   // An example of what is generated for the following code:
5142   //
5143   //   #pragma omp simd collapse(2) ordered(2)
5144   //   for (i = 0; i < NI; ++i)
5145   //     for (k = 0; k < NK; ++k)
5146   //       for (j = J0; j < NJ; j+=2) {
5147   //         <loop body>
5148   //       }
5149   //
5150   // We generate the code below.
5151   // Note: the loop body may be outlined in CodeGen.
5152   // Note: some counters may be C++ classes, operator- is used to find number of
5153   // iterations and operator+= to calculate counter value.
5154   // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
5155   // or i64 is currently supported).
5156   //
5157   //   #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
5158   //   for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
5159   //     .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
5160   //     .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
5161   //     // similar updates for vars in clauses (e.g. 'linear')
5162   //     <loop body (using local i and j)>
5163   //   }
5164   //   i = NI; // assign final values of counters
5165   //   j = NJ;
5166   //
5167 
5168   // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
5169   // the iteration counts of the collapsed for loops.
5170   // Precondition tests if there is at least one iteration (all conditions are
5171   // true).
5172   auto PreCond = ExprResult(IterSpaces[0].PreCond);
5173   Expr *N0 = IterSpaces[0].NumIterations;
5174   ExprResult LastIteration32 =
5175       widenIterationCount(/*Bits=*/32,
5176                           SemaRef
5177                               .PerformImplicitConversion(
5178                                   N0->IgnoreImpCasts(), N0->getType(),
5179                                   Sema::AA_Converting, /*AllowExplicit=*/true)
5180                               .get(),
5181                           SemaRef);
5182   ExprResult LastIteration64 = widenIterationCount(
5183       /*Bits=*/64,
5184       SemaRef
5185           .PerformImplicitConversion(N0->IgnoreImpCasts(), N0->getType(),
5186                                      Sema::AA_Converting,
5187                                      /*AllowExplicit=*/true)
5188           .get(),
5189       SemaRef);
5190 
5191   if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
5192     return NestedLoopCount;
5193 
5194   ASTContext &C = SemaRef.Context;
5195   bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
5196 
5197   Scope *CurScope = DSA.getCurScope();
5198   for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
5199     if (PreCond.isUsable()) {
5200       PreCond =
5201           SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
5202                              PreCond.get(), IterSpaces[Cnt].PreCond);
5203     }
5204     Expr *N = IterSpaces[Cnt].NumIterations;
5205     SourceLocation Loc = N->getExprLoc();
5206     AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
5207     if (LastIteration32.isUsable())
5208       LastIteration32 = SemaRef.BuildBinOp(
5209           CurScope, Loc, BO_Mul, LastIteration32.get(),
5210           SemaRef
5211               .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
5212                                          Sema::AA_Converting,
5213                                          /*AllowExplicit=*/true)
5214               .get());
5215     if (LastIteration64.isUsable())
5216       LastIteration64 = SemaRef.BuildBinOp(
5217           CurScope, Loc, BO_Mul, LastIteration64.get(),
5218           SemaRef
5219               .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
5220                                          Sema::AA_Converting,
5221                                          /*AllowExplicit=*/true)
5222               .get());
5223   }
5224 
5225   // Choose either the 32-bit or 64-bit version.
5226   ExprResult LastIteration = LastIteration64;
5227   if (LastIteration32.isUsable() &&
5228       C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
5229       (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
5230        fitsInto(
5231            /*Bits=*/32,
5232            LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
5233            LastIteration64.get(), SemaRef)))
5234     LastIteration = LastIteration32;
5235   QualType VType = LastIteration.get()->getType();
5236   QualType RealVType = VType;
5237   QualType StrideVType = VType;
5238   if (isOpenMPTaskLoopDirective(DKind)) {
5239     VType =
5240         SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
5241     StrideVType =
5242         SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
5243   }
5244 
5245   if (!LastIteration.isUsable())
5246     return 0;
5247 
5248   // Save the number of iterations.
5249   ExprResult NumIterations = LastIteration;
5250   {
5251     LastIteration = SemaRef.BuildBinOp(
5252         CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
5253         LastIteration.get(),
5254         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
5255     if (!LastIteration.isUsable())
5256       return 0;
5257   }
5258 
5259   // Calculate the last iteration number beforehand instead of doing this on
5260   // each iteration. Do not do this if the number of iterations may be kfold-ed.
5261   llvm::APSInt Result;
5262   bool IsConstant =
5263       LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
5264   ExprResult CalcLastIteration;
5265   if (!IsConstant) {
5266     ExprResult SaveRef =
5267         tryBuildCapture(SemaRef, LastIteration.get(), Captures);
5268     LastIteration = SaveRef;
5269 
5270     // Prepare SaveRef + 1.
5271     NumIterations = SemaRef.BuildBinOp(
5272         CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
5273         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
5274     if (!NumIterations.isUsable())
5275       return 0;
5276   }
5277 
5278   SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
5279 
5280   // Build variables passed into runtime, necessary for worksharing directives.
5281   ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
5282   if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
5283       isOpenMPDistributeDirective(DKind)) {
5284     // Lower bound variable, initialized with zero.
5285     VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
5286     LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
5287     SemaRef.AddInitializerToDecl(LBDecl,
5288                                  SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
5289                                  /*DirectInit*/ false);
5290 
5291     // Upper bound variable, initialized with last iteration number.
5292     VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
5293     UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
5294     SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
5295                                  /*DirectInit*/ false);
5296 
5297     // A 32-bit variable-flag where runtime returns 1 for the last iteration.
5298     // This will be used to implement clause 'lastprivate'.
5299     QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
5300     VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
5301     IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
5302     SemaRef.AddInitializerToDecl(ILDecl,
5303                                  SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
5304                                  /*DirectInit*/ false);
5305 
5306     // Stride variable returned by runtime (we initialize it to 1 by default).
5307     VarDecl *STDecl =
5308         buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
5309     ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
5310     SemaRef.AddInitializerToDecl(STDecl,
5311                                  SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
5312                                  /*DirectInit*/ false);
5313 
5314     // Build expression: UB = min(UB, LastIteration)
5315     // It is necessary for CodeGen of directives with static scheduling.
5316     ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
5317                                                 UB.get(), LastIteration.get());
5318     ExprResult CondOp = SemaRef.ActOnConditionalOp(
5319         LastIteration.get()->getExprLoc(), InitLoc, IsUBGreater.get(),
5320         LastIteration.get(), UB.get());
5321     EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
5322                              CondOp.get());
5323     EUB = SemaRef.ActOnFinishFullExpr(EUB.get(), /*DiscardedValue*/ false);
5324 
5325     // If we have a combined directive that combines 'distribute', 'for' or
5326     // 'simd' we need to be able to access the bounds of the schedule of the
5327     // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
5328     // by scheduling 'distribute' have to be passed to the schedule of 'for'.
5329     if (isOpenMPLoopBoundSharingDirective(DKind)) {
5330       // Lower bound variable, initialized with zero.
5331       VarDecl *CombLBDecl =
5332           buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
5333       CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
5334       SemaRef.AddInitializerToDecl(
5335           CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
5336           /*DirectInit*/ false);
5337 
5338       // Upper bound variable, initialized with last iteration number.
5339       VarDecl *CombUBDecl =
5340           buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
5341       CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
5342       SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
5343                                    /*DirectInit*/ false);
5344 
5345       ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
5346           CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
5347       ExprResult CombCondOp =
5348           SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
5349                                      LastIteration.get(), CombUB.get());
5350       CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
5351                                    CombCondOp.get());
5352       CombEUB =
5353           SemaRef.ActOnFinishFullExpr(CombEUB.get(), /*DiscardedValue*/ false);
5354 
5355       const CapturedDecl *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
5356       // We expect to have at least 2 more parameters than the 'parallel'
5357       // directive does - the lower and upper bounds of the previous schedule.
5358       assert(CD->getNumParams() >= 4 &&
5359              "Unexpected number of parameters in loop combined directive");
5360 
5361       // Set the proper type for the bounds given what we learned from the
5362       // enclosed loops.
5363       ImplicitParamDecl *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
5364       ImplicitParamDecl *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
5365 
5366       // Previous lower and upper bounds are obtained from the region
5367       // parameters.
5368       PrevLB =
5369           buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
5370       PrevUB =
5371           buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
5372     }
5373   }
5374 
5375   // Build the iteration variable and its initialization before loop.
5376   ExprResult IV;
5377   ExprResult Init, CombInit;
5378   {
5379     VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
5380     IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
5381     Expr *RHS =
5382         (isOpenMPWorksharingDirective(DKind) ||
5383          isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
5384             ? LB.get()
5385             : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
5386     Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
5387     Init = SemaRef.ActOnFinishFullExpr(Init.get(), /*DiscardedValue*/ false);
5388 
5389     if (isOpenMPLoopBoundSharingDirective(DKind)) {
5390       Expr *CombRHS =
5391           (isOpenMPWorksharingDirective(DKind) ||
5392            isOpenMPTaskLoopDirective(DKind) ||
5393            isOpenMPDistributeDirective(DKind))
5394               ? CombLB.get()
5395               : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
5396       CombInit =
5397           SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
5398       CombInit =
5399           SemaRef.ActOnFinishFullExpr(CombInit.get(), /*DiscardedValue*/ false);
5400     }
5401   }
5402 
5403   // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops.
5404   SourceLocation CondLoc = AStmt->getBeginLoc();
5405   ExprResult Cond =
5406       (isOpenMPWorksharingDirective(DKind) ||
5407        isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
5408           ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get())
5409           : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
5410                                NumIterations.get());
5411   ExprResult CombDistCond;
5412   if (isOpenMPLoopBoundSharingDirective(DKind)) {
5413     CombDistCond =
5414         SemaRef.BuildBinOp(
5415             CurScope, CondLoc, BO_LT, IV.get(), NumIterations.get());
5416   }
5417 
5418   ExprResult CombCond;
5419   if (isOpenMPLoopBoundSharingDirective(DKind)) {
5420     CombCond =
5421         SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), CombUB.get());
5422   }
5423   // Loop increment (IV = IV + 1)
5424   SourceLocation IncLoc = AStmt->getBeginLoc();
5425   ExprResult Inc =
5426       SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
5427                          SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
5428   if (!Inc.isUsable())
5429     return 0;
5430   Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
5431   Inc = SemaRef.ActOnFinishFullExpr(Inc.get(), /*DiscardedValue*/ false);
5432   if (!Inc.isUsable())
5433     return 0;
5434 
5435   // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
5436   // Used for directives with static scheduling.
5437   // In combined construct, add combined version that use CombLB and CombUB
5438   // base variables for the update
5439   ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
5440   if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
5441       isOpenMPDistributeDirective(DKind)) {
5442     // LB + ST
5443     NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
5444     if (!NextLB.isUsable())
5445       return 0;
5446     // LB = LB + ST
5447     NextLB =
5448         SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
5449     NextLB =
5450         SemaRef.ActOnFinishFullExpr(NextLB.get(), /*DiscardedValue*/ false);
5451     if (!NextLB.isUsable())
5452       return 0;
5453     // UB + ST
5454     NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
5455     if (!NextUB.isUsable())
5456       return 0;
5457     // UB = UB + ST
5458     NextUB =
5459         SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
5460     NextUB =
5461         SemaRef.ActOnFinishFullExpr(NextUB.get(), /*DiscardedValue*/ false);
5462     if (!NextUB.isUsable())
5463       return 0;
5464     if (isOpenMPLoopBoundSharingDirective(DKind)) {
5465       CombNextLB =
5466           SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
5467       if (!NextLB.isUsable())
5468         return 0;
5469       // LB = LB + ST
5470       CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
5471                                       CombNextLB.get());
5472       CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get(),
5473                                                /*DiscardedValue*/ false);
5474       if (!CombNextLB.isUsable())
5475         return 0;
5476       // UB + ST
5477       CombNextUB =
5478           SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
5479       if (!CombNextUB.isUsable())
5480         return 0;
5481       // UB = UB + ST
5482       CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
5483                                       CombNextUB.get());
5484       CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get(),
5485                                                /*DiscardedValue*/ false);
5486       if (!CombNextUB.isUsable())
5487         return 0;
5488     }
5489   }
5490 
5491   // Create increment expression for distribute loop when combined in a same
5492   // directive with for as IV = IV + ST; ensure upper bound expression based
5493   // on PrevUB instead of NumIterations - used to implement 'for' when found
5494   // in combination with 'distribute', like in 'distribute parallel for'
5495   SourceLocation DistIncLoc = AStmt->getBeginLoc();
5496   ExprResult DistCond, DistInc, PrevEUB, ParForInDistCond;
5497   if (isOpenMPLoopBoundSharingDirective(DKind)) {
5498     DistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get());
5499     assert(DistCond.isUsable() && "distribute cond expr was not built");
5500 
5501     DistInc =
5502         SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
5503     assert(DistInc.isUsable() && "distribute inc expr was not built");
5504     DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
5505                                  DistInc.get());
5506     DistInc =
5507         SemaRef.ActOnFinishFullExpr(DistInc.get(), /*DiscardedValue*/ false);
5508     assert(DistInc.isUsable() && "distribute inc expr was not built");
5509 
5510     // Build expression: UB = min(UB, prevUB) for #for in composite or combined
5511     // construct
5512     SourceLocation DistEUBLoc = AStmt->getBeginLoc();
5513     ExprResult IsUBGreater =
5514         SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get());
5515     ExprResult CondOp = SemaRef.ActOnConditionalOp(
5516         DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get());
5517     PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
5518                                  CondOp.get());
5519     PrevEUB =
5520         SemaRef.ActOnFinishFullExpr(PrevEUB.get(), /*DiscardedValue*/ false);
5521 
5522     // Build IV <= PrevUB to be used in parallel for is in combination with
5523     // a distribute directive with schedule(static, 1)
5524     ParForInDistCond =
5525         SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), PrevUB.get());
5526   }
5527 
5528   // Build updates and final values of the loop counters.
5529   bool HasErrors = false;
5530   Built.Counters.resize(NestedLoopCount);
5531   Built.Inits.resize(NestedLoopCount);
5532   Built.Updates.resize(NestedLoopCount);
5533   Built.Finals.resize(NestedLoopCount);
5534   {
5535     ExprResult Div;
5536     // Go from inner nested loop to outer.
5537     for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
5538       LoopIterationSpace &IS = IterSpaces[Cnt];
5539       SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
5540       // Build: Iter = (IV / Div) % IS.NumIters
5541       // where Div is product of previous iterations' IS.NumIters.
5542       ExprResult Iter;
5543       if (Div.isUsable()) {
5544         Iter =
5545             SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get());
5546       } else {
5547         Iter = IV;
5548         assert((Cnt == (int)NestedLoopCount - 1) &&
5549                "unusable div expected on first iteration only");
5550       }
5551 
5552       if (Cnt != 0 && Iter.isUsable())
5553         Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(),
5554                                   IS.NumIterations);
5555       if (!Iter.isUsable()) {
5556         HasErrors = true;
5557         break;
5558       }
5559 
5560       // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
5561       auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
5562       DeclRefExpr *CounterVar = buildDeclRefExpr(
5563           SemaRef, VD, IS.CounterVar->getType(), IS.CounterVar->getExprLoc(),
5564           /*RefersToCapture=*/true);
5565       ExprResult Init = buildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
5566                                          IS.CounterInit, Captures);
5567       if (!Init.isUsable()) {
5568         HasErrors = true;
5569         break;
5570       }
5571       ExprResult Update = buildCounterUpdate(
5572           SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
5573           IS.CounterStep, IS.Subtract, &Captures);
5574       if (!Update.isUsable()) {
5575         HasErrors = true;
5576         break;
5577       }
5578 
5579       // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
5580       ExprResult Final = buildCounterUpdate(
5581           SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
5582           IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures);
5583       if (!Final.isUsable()) {
5584         HasErrors = true;
5585         break;
5586       }
5587 
5588       // Build Div for the next iteration: Div <- Div * IS.NumIters
5589       if (Cnt != 0) {
5590         if (Div.isUnset())
5591           Div = IS.NumIterations;
5592         else
5593           Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(),
5594                                    IS.NumIterations);
5595 
5596         // Add parentheses (for debugging purposes only).
5597         if (Div.isUsable())
5598           Div = tryBuildCapture(SemaRef, Div.get(), Captures);
5599         if (!Div.isUsable()) {
5600           HasErrors = true;
5601           break;
5602         }
5603       }
5604       if (!Update.isUsable() || !Final.isUsable()) {
5605         HasErrors = true;
5606         break;
5607       }
5608       // Save results
5609       Built.Counters[Cnt] = IS.CounterVar;
5610       Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
5611       Built.Inits[Cnt] = Init.get();
5612       Built.Updates[Cnt] = Update.get();
5613       Built.Finals[Cnt] = Final.get();
5614     }
5615   }
5616 
5617   if (HasErrors)
5618     return 0;
5619 
5620   // Save results
5621   Built.IterationVarRef = IV.get();
5622   Built.LastIteration = LastIteration.get();
5623   Built.NumIterations = NumIterations.get();
5624   Built.CalcLastIteration = SemaRef
5625                                 .ActOnFinishFullExpr(CalcLastIteration.get(),
5626                                                      /*DiscardedValue*/ false)
5627                                 .get();
5628   Built.PreCond = PreCond.get();
5629   Built.PreInits = buildPreInits(C, Captures);
5630   Built.Cond = Cond.get();
5631   Built.Init = Init.get();
5632   Built.Inc = Inc.get();
5633   Built.LB = LB.get();
5634   Built.UB = UB.get();
5635   Built.IL = IL.get();
5636   Built.ST = ST.get();
5637   Built.EUB = EUB.get();
5638   Built.NLB = NextLB.get();
5639   Built.NUB = NextUB.get();
5640   Built.PrevLB = PrevLB.get();
5641   Built.PrevUB = PrevUB.get();
5642   Built.DistInc = DistInc.get();
5643   Built.PrevEUB = PrevEUB.get();
5644   Built.DistCombinedFields.LB = CombLB.get();
5645   Built.DistCombinedFields.UB = CombUB.get();
5646   Built.DistCombinedFields.EUB = CombEUB.get();
5647   Built.DistCombinedFields.Init = CombInit.get();
5648   Built.DistCombinedFields.Cond = CombCond.get();
5649   Built.DistCombinedFields.NLB = CombNextLB.get();
5650   Built.DistCombinedFields.NUB = CombNextUB.get();
5651   Built.DistCombinedFields.DistCond = CombDistCond.get();
5652   Built.DistCombinedFields.ParForInDistCond = ParForInDistCond.get();
5653 
5654   return NestedLoopCount;
5655 }
5656 
5657 static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
5658   auto CollapseClauses =
5659       OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
5660   if (CollapseClauses.begin() != CollapseClauses.end())
5661     return (*CollapseClauses.begin())->getNumForLoops();
5662   return nullptr;
5663 }
5664 
5665 static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
5666   auto OrderedClauses =
5667       OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
5668   if (OrderedClauses.begin() != OrderedClauses.end())
5669     return (*OrderedClauses.begin())->getNumForLoops();
5670   return nullptr;
5671 }
5672 
5673 static bool checkSimdlenSafelenSpecified(Sema &S,
5674                                          const ArrayRef<OMPClause *> Clauses) {
5675   const OMPSafelenClause *Safelen = nullptr;
5676   const OMPSimdlenClause *Simdlen = nullptr;
5677 
5678   for (const OMPClause *Clause : Clauses) {
5679     if (Clause->getClauseKind() == OMPC_safelen)
5680       Safelen = cast<OMPSafelenClause>(Clause);
5681     else if (Clause->getClauseKind() == OMPC_simdlen)
5682       Simdlen = cast<OMPSimdlenClause>(Clause);
5683     if (Safelen && Simdlen)
5684       break;
5685   }
5686 
5687   if (Simdlen && Safelen) {
5688     const Expr *SimdlenLength = Simdlen->getSimdlen();
5689     const Expr *SafelenLength = Safelen->getSafelen();
5690     if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
5691         SimdlenLength->isInstantiationDependent() ||
5692         SimdlenLength->containsUnexpandedParameterPack())
5693       return false;
5694     if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
5695         SafelenLength->isInstantiationDependent() ||
5696         SafelenLength->containsUnexpandedParameterPack())
5697       return false;
5698     Expr::EvalResult SimdlenResult, SafelenResult;
5699     SimdlenLength->EvaluateAsInt(SimdlenResult, S.Context);
5700     SafelenLength->EvaluateAsInt(SafelenResult, S.Context);
5701     llvm::APSInt SimdlenRes = SimdlenResult.Val.getInt();
5702     llvm::APSInt SafelenRes = SafelenResult.Val.getInt();
5703     // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
5704     // If both simdlen and safelen clauses are specified, the value of the
5705     // simdlen parameter must be less than or equal to the value of the safelen
5706     // parameter.
5707     if (SimdlenRes > SafelenRes) {
5708       S.Diag(SimdlenLength->getExprLoc(),
5709              diag::err_omp_wrong_simdlen_safelen_values)
5710           << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
5711       return true;
5712     }
5713   }
5714   return false;
5715 }
5716 
5717 StmtResult
5718 Sema::ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
5719                                SourceLocation StartLoc, SourceLocation EndLoc,
5720                                VarsWithInheritedDSAType &VarsWithImplicitDSA) {
5721   if (!AStmt)
5722     return StmtError();
5723 
5724   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5725   OMPLoopDirective::HelperExprs B;
5726   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5727   // define the nested loops number.
5728   unsigned NestedLoopCount = checkOpenMPLoop(
5729       OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
5730       AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
5731   if (NestedLoopCount == 0)
5732     return StmtError();
5733 
5734   assert((CurContext->isDependentContext() || B.builtAll()) &&
5735          "omp simd loop exprs were not built");
5736 
5737   if (!CurContext->isDependentContext()) {
5738     // Finalize the clauses that need pre-built expressions for CodeGen.
5739     for (OMPClause *C : Clauses) {
5740       if (auto *LC = dyn_cast<OMPLinearClause>(C))
5741         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
5742                                      B.NumIterations, *this, CurScope,
5743                                      DSAStack))
5744           return StmtError();
5745     }
5746   }
5747 
5748   if (checkSimdlenSafelenSpecified(*this, Clauses))
5749     return StmtError();
5750 
5751   setFunctionHasBranchProtectedScope();
5752   return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
5753                                   Clauses, AStmt, B);
5754 }
5755 
5756 StmtResult
5757 Sema::ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
5758                               SourceLocation StartLoc, SourceLocation EndLoc,
5759                               VarsWithInheritedDSAType &VarsWithImplicitDSA) {
5760   if (!AStmt)
5761     return StmtError();
5762 
5763   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5764   OMPLoopDirective::HelperExprs B;
5765   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5766   // define the nested loops number.
5767   unsigned NestedLoopCount = checkOpenMPLoop(
5768       OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
5769       AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
5770   if (NestedLoopCount == 0)
5771     return StmtError();
5772 
5773   assert((CurContext->isDependentContext() || B.builtAll()) &&
5774          "omp for loop exprs were not built");
5775 
5776   if (!CurContext->isDependentContext()) {
5777     // Finalize the clauses that need pre-built expressions for CodeGen.
5778     for (OMPClause *C : Clauses) {
5779       if (auto *LC = dyn_cast<OMPLinearClause>(C))
5780         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
5781                                      B.NumIterations, *this, CurScope,
5782                                      DSAStack))
5783           return StmtError();
5784     }
5785   }
5786 
5787   setFunctionHasBranchProtectedScope();
5788   return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
5789                                  Clauses, AStmt, B, DSAStack->isCancelRegion());
5790 }
5791 
5792 StmtResult Sema::ActOnOpenMPForSimdDirective(
5793     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5794     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
5795   if (!AStmt)
5796     return StmtError();
5797 
5798   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5799   OMPLoopDirective::HelperExprs B;
5800   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5801   // define the nested loops number.
5802   unsigned NestedLoopCount =
5803       checkOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
5804                       getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5805                       VarsWithImplicitDSA, B);
5806   if (NestedLoopCount == 0)
5807     return StmtError();
5808 
5809   assert((CurContext->isDependentContext() || B.builtAll()) &&
5810          "omp for simd loop exprs were not built");
5811 
5812   if (!CurContext->isDependentContext()) {
5813     // Finalize the clauses that need pre-built expressions for CodeGen.
5814     for (OMPClause *C : Clauses) {
5815       if (auto *LC = dyn_cast<OMPLinearClause>(C))
5816         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
5817                                      B.NumIterations, *this, CurScope,
5818                                      DSAStack))
5819           return StmtError();
5820     }
5821   }
5822 
5823   if (checkSimdlenSafelenSpecified(*this, Clauses))
5824     return StmtError();
5825 
5826   setFunctionHasBranchProtectedScope();
5827   return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
5828                                      Clauses, AStmt, B);
5829 }
5830 
5831 StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
5832                                               Stmt *AStmt,
5833                                               SourceLocation StartLoc,
5834                                               SourceLocation EndLoc) {
5835   if (!AStmt)
5836     return StmtError();
5837 
5838   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5839   auto BaseStmt = AStmt;
5840   while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
5841     BaseStmt = CS->getCapturedStmt();
5842   if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
5843     auto S = C->children();
5844     if (S.begin() == S.end())
5845       return StmtError();
5846     // All associated statements must be '#pragma omp section' except for
5847     // the first one.
5848     for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
5849       if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
5850         if (SectionStmt)
5851           Diag(SectionStmt->getBeginLoc(),
5852                diag::err_omp_sections_substmt_not_section);
5853         return StmtError();
5854       }
5855       cast<OMPSectionDirective>(SectionStmt)
5856           ->setHasCancel(DSAStack->isCancelRegion());
5857     }
5858   } else {
5859     Diag(AStmt->getBeginLoc(), diag::err_omp_sections_not_compound_stmt);
5860     return StmtError();
5861   }
5862 
5863   setFunctionHasBranchProtectedScope();
5864 
5865   return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
5866                                       DSAStack->isCancelRegion());
5867 }
5868 
5869 StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
5870                                              SourceLocation StartLoc,
5871                                              SourceLocation EndLoc) {
5872   if (!AStmt)
5873     return StmtError();
5874 
5875   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5876 
5877   setFunctionHasBranchProtectedScope();
5878   DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
5879 
5880   return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
5881                                      DSAStack->isCancelRegion());
5882 }
5883 
5884 StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
5885                                             Stmt *AStmt,
5886                                             SourceLocation StartLoc,
5887                                             SourceLocation EndLoc) {
5888   if (!AStmt)
5889     return StmtError();
5890 
5891   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5892 
5893   setFunctionHasBranchProtectedScope();
5894 
5895   // OpenMP [2.7.3, single Construct, Restrictions]
5896   // The copyprivate clause must not be used with the nowait clause.
5897   const OMPClause *Nowait = nullptr;
5898   const OMPClause *Copyprivate = nullptr;
5899   for (const OMPClause *Clause : Clauses) {
5900     if (Clause->getClauseKind() == OMPC_nowait)
5901       Nowait = Clause;
5902     else if (Clause->getClauseKind() == OMPC_copyprivate)
5903       Copyprivate = Clause;
5904     if (Copyprivate && Nowait) {
5905       Diag(Copyprivate->getBeginLoc(),
5906            diag::err_omp_single_copyprivate_with_nowait);
5907       Diag(Nowait->getBeginLoc(), diag::note_omp_nowait_clause_here);
5908       return StmtError();
5909     }
5910   }
5911 
5912   return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
5913 }
5914 
5915 StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
5916                                             SourceLocation StartLoc,
5917                                             SourceLocation EndLoc) {
5918   if (!AStmt)
5919     return StmtError();
5920 
5921   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5922 
5923   setFunctionHasBranchProtectedScope();
5924 
5925   return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
5926 }
5927 
5928 StmtResult Sema::ActOnOpenMPCriticalDirective(
5929     const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
5930     Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
5931   if (!AStmt)
5932     return StmtError();
5933 
5934   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5935 
5936   bool ErrorFound = false;
5937   llvm::APSInt Hint;
5938   SourceLocation HintLoc;
5939   bool DependentHint = false;
5940   for (const OMPClause *C : Clauses) {
5941     if (C->getClauseKind() == OMPC_hint) {
5942       if (!DirName.getName()) {
5943         Diag(C->getBeginLoc(), diag::err_omp_hint_clause_no_name);
5944         ErrorFound = true;
5945       }
5946       Expr *E = cast<OMPHintClause>(C)->getHint();
5947       if (E->isTypeDependent() || E->isValueDependent() ||
5948           E->isInstantiationDependent()) {
5949         DependentHint = true;
5950       } else {
5951         Hint = E->EvaluateKnownConstInt(Context);
5952         HintLoc = C->getBeginLoc();
5953       }
5954     }
5955   }
5956   if (ErrorFound)
5957     return StmtError();
5958   const auto Pair = DSAStack->getCriticalWithHint(DirName);
5959   if (Pair.first && DirName.getName() && !DependentHint) {
5960     if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
5961       Diag(StartLoc, diag::err_omp_critical_with_hint);
5962       if (HintLoc.isValid())
5963         Diag(HintLoc, diag::note_omp_critical_hint_here)
5964             << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
5965       else
5966         Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
5967       if (const auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
5968         Diag(C->getBeginLoc(), diag::note_omp_critical_hint_here)
5969             << 1
5970             << C->getHint()->EvaluateKnownConstInt(Context).toString(
5971                    /*Radix=*/10, /*Signed=*/false);
5972       } else {
5973         Diag(Pair.first->getBeginLoc(), diag::note_omp_critical_no_hint) << 1;
5974       }
5975     }
5976   }
5977 
5978   setFunctionHasBranchProtectedScope();
5979 
5980   auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
5981                                            Clauses, AStmt);
5982   if (!Pair.first && DirName.getName() && !DependentHint)
5983     DSAStack->addCriticalWithHint(Dir, Hint);
5984   return Dir;
5985 }
5986 
5987 StmtResult Sema::ActOnOpenMPParallelForDirective(
5988     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5989     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
5990   if (!AStmt)
5991     return StmtError();
5992 
5993   auto *CS = cast<CapturedStmt>(AStmt);
5994   // 1.2.2 OpenMP Language Terminology
5995   // Structured block - An executable statement with a single entry at the
5996   // top and a single exit at the bottom.
5997   // The point of exit cannot be a branch out of the structured block.
5998   // longjmp() and throw() must not violate the entry/exit criteria.
5999   CS->getCapturedDecl()->setNothrow();
6000 
6001   OMPLoopDirective::HelperExprs B;
6002   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6003   // define the nested loops number.
6004   unsigned NestedLoopCount =
6005       checkOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
6006                       getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6007                       VarsWithImplicitDSA, B);
6008   if (NestedLoopCount == 0)
6009     return StmtError();
6010 
6011   assert((CurContext->isDependentContext() || B.builtAll()) &&
6012          "omp parallel for loop exprs were not built");
6013 
6014   if (!CurContext->isDependentContext()) {
6015     // Finalize the clauses that need pre-built expressions for CodeGen.
6016     for (OMPClause *C : Clauses) {
6017       if (auto *LC = dyn_cast<OMPLinearClause>(C))
6018         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6019                                      B.NumIterations, *this, CurScope,
6020                                      DSAStack))
6021           return StmtError();
6022     }
6023   }
6024 
6025   setFunctionHasBranchProtectedScope();
6026   return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
6027                                          NestedLoopCount, Clauses, AStmt, B,
6028                                          DSAStack->isCancelRegion());
6029 }
6030 
6031 StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
6032     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6033     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
6034   if (!AStmt)
6035     return StmtError();
6036 
6037   auto *CS = cast<CapturedStmt>(AStmt);
6038   // 1.2.2 OpenMP Language Terminology
6039   // Structured block - An executable statement with a single entry at the
6040   // top and a single exit at the bottom.
6041   // The point of exit cannot be a branch out of the structured block.
6042   // longjmp() and throw() must not violate the entry/exit criteria.
6043   CS->getCapturedDecl()->setNothrow();
6044 
6045   OMPLoopDirective::HelperExprs B;
6046   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6047   // define the nested loops number.
6048   unsigned NestedLoopCount =
6049       checkOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
6050                       getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6051                       VarsWithImplicitDSA, B);
6052   if (NestedLoopCount == 0)
6053     return StmtError();
6054 
6055   if (!CurContext->isDependentContext()) {
6056     // Finalize the clauses that need pre-built expressions for CodeGen.
6057     for (OMPClause *C : Clauses) {
6058       if (auto *LC = dyn_cast<OMPLinearClause>(C))
6059         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6060                                      B.NumIterations, *this, CurScope,
6061                                      DSAStack))
6062           return StmtError();
6063     }
6064   }
6065 
6066   if (checkSimdlenSafelenSpecified(*this, Clauses))
6067     return StmtError();
6068 
6069   setFunctionHasBranchProtectedScope();
6070   return OMPParallelForSimdDirective::Create(
6071       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6072 }
6073 
6074 StmtResult
6075 Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
6076                                            Stmt *AStmt, SourceLocation StartLoc,
6077                                            SourceLocation EndLoc) {
6078   if (!AStmt)
6079     return StmtError();
6080 
6081   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6082   auto BaseStmt = AStmt;
6083   while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
6084     BaseStmt = CS->getCapturedStmt();
6085   if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
6086     auto S = C->children();
6087     if (S.begin() == S.end())
6088       return StmtError();
6089     // All associated statements must be '#pragma omp section' except for
6090     // the first one.
6091     for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
6092       if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
6093         if (SectionStmt)
6094           Diag(SectionStmt->getBeginLoc(),
6095                diag::err_omp_parallel_sections_substmt_not_section);
6096         return StmtError();
6097       }
6098       cast<OMPSectionDirective>(SectionStmt)
6099           ->setHasCancel(DSAStack->isCancelRegion());
6100     }
6101   } else {
6102     Diag(AStmt->getBeginLoc(),
6103          diag::err_omp_parallel_sections_not_compound_stmt);
6104     return StmtError();
6105   }
6106 
6107   setFunctionHasBranchProtectedScope();
6108 
6109   return OMPParallelSectionsDirective::Create(
6110       Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
6111 }
6112 
6113 StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
6114                                           Stmt *AStmt, SourceLocation StartLoc,
6115                                           SourceLocation EndLoc) {
6116   if (!AStmt)
6117     return StmtError();
6118 
6119   auto *CS = cast<CapturedStmt>(AStmt);
6120   // 1.2.2 OpenMP Language Terminology
6121   // Structured block - An executable statement with a single entry at the
6122   // top and a single exit at the bottom.
6123   // The point of exit cannot be a branch out of the structured block.
6124   // longjmp() and throw() must not violate the entry/exit criteria.
6125   CS->getCapturedDecl()->setNothrow();
6126 
6127   setFunctionHasBranchProtectedScope();
6128 
6129   return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
6130                                   DSAStack->isCancelRegion());
6131 }
6132 
6133 StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
6134                                                SourceLocation EndLoc) {
6135   return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
6136 }
6137 
6138 StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
6139                                              SourceLocation EndLoc) {
6140   return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
6141 }
6142 
6143 StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
6144                                               SourceLocation EndLoc) {
6145   return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
6146 }
6147 
6148 StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
6149                                                Stmt *AStmt,
6150                                                SourceLocation StartLoc,
6151                                                SourceLocation EndLoc) {
6152   if (!AStmt)
6153     return StmtError();
6154 
6155   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6156 
6157   setFunctionHasBranchProtectedScope();
6158 
6159   return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses,
6160                                        AStmt,
6161                                        DSAStack->getTaskgroupReductionRef());
6162 }
6163 
6164 StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
6165                                            SourceLocation StartLoc,
6166                                            SourceLocation EndLoc) {
6167   assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
6168   return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
6169 }
6170 
6171 StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
6172                                              Stmt *AStmt,
6173                                              SourceLocation StartLoc,
6174                                              SourceLocation EndLoc) {
6175   const OMPClause *DependFound = nullptr;
6176   const OMPClause *DependSourceClause = nullptr;
6177   const OMPClause *DependSinkClause = nullptr;
6178   bool ErrorFound = false;
6179   const OMPThreadsClause *TC = nullptr;
6180   const OMPSIMDClause *SC = nullptr;
6181   for (const OMPClause *C : Clauses) {
6182     if (auto *DC = dyn_cast<OMPDependClause>(C)) {
6183       DependFound = C;
6184       if (DC->getDependencyKind() == OMPC_DEPEND_source) {
6185         if (DependSourceClause) {
6186           Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
6187               << getOpenMPDirectiveName(OMPD_ordered)
6188               << getOpenMPClauseName(OMPC_depend) << 2;
6189           ErrorFound = true;
6190         } else {
6191           DependSourceClause = C;
6192         }
6193         if (DependSinkClause) {
6194           Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
6195               << 0;
6196           ErrorFound = true;
6197         }
6198       } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
6199         if (DependSourceClause) {
6200           Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
6201               << 1;
6202           ErrorFound = true;
6203         }
6204         DependSinkClause = C;
6205       }
6206     } else if (C->getClauseKind() == OMPC_threads) {
6207       TC = cast<OMPThreadsClause>(C);
6208     } else if (C->getClauseKind() == OMPC_simd) {
6209       SC = cast<OMPSIMDClause>(C);
6210     }
6211   }
6212   if (!ErrorFound && !SC &&
6213       isOpenMPSimdDirective(DSAStack->getParentDirective())) {
6214     // OpenMP [2.8.1,simd Construct, Restrictions]
6215     // An ordered construct with the simd clause is the only OpenMP construct
6216     // that can appear in the simd region.
6217     Diag(StartLoc, diag::err_omp_prohibited_region_simd);
6218     ErrorFound = true;
6219   } else if (DependFound && (TC || SC)) {
6220     Diag(DependFound->getBeginLoc(), diag::err_omp_depend_clause_thread_simd)
6221         << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
6222     ErrorFound = true;
6223   } else if (DependFound && !DSAStack->getParentOrderedRegionParam().first) {
6224     Diag(DependFound->getBeginLoc(),
6225          diag::err_omp_ordered_directive_without_param);
6226     ErrorFound = true;
6227   } else if (TC || Clauses.empty()) {
6228     if (const Expr *Param = DSAStack->getParentOrderedRegionParam().first) {
6229       SourceLocation ErrLoc = TC ? TC->getBeginLoc() : StartLoc;
6230       Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
6231           << (TC != nullptr);
6232       Diag(Param->getBeginLoc(), diag::note_omp_ordered_param);
6233       ErrorFound = true;
6234     }
6235   }
6236   if ((!AStmt && !DependFound) || ErrorFound)
6237     return StmtError();
6238 
6239   if (AStmt) {
6240     assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6241 
6242     setFunctionHasBranchProtectedScope();
6243   }
6244 
6245   return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
6246 }
6247 
6248 namespace {
6249 /// Helper class for checking expression in 'omp atomic [update]'
6250 /// construct.
6251 class OpenMPAtomicUpdateChecker {
6252   /// Error results for atomic update expressions.
6253   enum ExprAnalysisErrorCode {
6254     /// A statement is not an expression statement.
6255     NotAnExpression,
6256     /// Expression is not builtin binary or unary operation.
6257     NotABinaryOrUnaryExpression,
6258     /// Unary operation is not post-/pre- increment/decrement operation.
6259     NotAnUnaryIncDecExpression,
6260     /// An expression is not of scalar type.
6261     NotAScalarType,
6262     /// A binary operation is not an assignment operation.
6263     NotAnAssignmentOp,
6264     /// RHS part of the binary operation is not a binary expression.
6265     NotABinaryExpression,
6266     /// RHS part is not additive/multiplicative/shift/biwise binary
6267     /// expression.
6268     NotABinaryOperator,
6269     /// RHS binary operation does not have reference to the updated LHS
6270     /// part.
6271     NotAnUpdateExpression,
6272     /// No errors is found.
6273     NoError
6274   };
6275   /// Reference to Sema.
6276   Sema &SemaRef;
6277   /// A location for note diagnostics (when error is found).
6278   SourceLocation NoteLoc;
6279   /// 'x' lvalue part of the source atomic expression.
6280   Expr *X;
6281   /// 'expr' rvalue part of the source atomic expression.
6282   Expr *E;
6283   /// Helper expression of the form
6284   /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
6285   /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
6286   Expr *UpdateExpr;
6287   /// Is 'x' a LHS in a RHS part of full update expression. It is
6288   /// important for non-associative operations.
6289   bool IsXLHSInRHSPart;
6290   BinaryOperatorKind Op;
6291   SourceLocation OpLoc;
6292   /// true if the source expression is a postfix unary operation, false
6293   /// if it is a prefix unary operation.
6294   bool IsPostfixUpdate;
6295 
6296 public:
6297   OpenMPAtomicUpdateChecker(Sema &SemaRef)
6298       : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
6299         IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
6300   /// Check specified statement that it is suitable for 'atomic update'
6301   /// constructs and extract 'x', 'expr' and Operation from the original
6302   /// expression. If DiagId and NoteId == 0, then only check is performed
6303   /// without error notification.
6304   /// \param DiagId Diagnostic which should be emitted if error is found.
6305   /// \param NoteId Diagnostic note for the main error message.
6306   /// \return true if statement is not an update expression, false otherwise.
6307   bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
6308   /// Return the 'x' lvalue part of the source atomic expression.
6309   Expr *getX() const { return X; }
6310   /// Return the 'expr' rvalue part of the source atomic expression.
6311   Expr *getExpr() const { return E; }
6312   /// Return the update expression used in calculation of the updated
6313   /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
6314   /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
6315   Expr *getUpdateExpr() const { return UpdateExpr; }
6316   /// Return true if 'x' is LHS in RHS part of full update expression,
6317   /// false otherwise.
6318   bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
6319 
6320   /// true if the source expression is a postfix unary operation, false
6321   /// if it is a prefix unary operation.
6322   bool isPostfixUpdate() const { return IsPostfixUpdate; }
6323 
6324 private:
6325   bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
6326                             unsigned NoteId = 0);
6327 };
6328 } // namespace
6329 
6330 bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
6331     BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
6332   ExprAnalysisErrorCode ErrorFound = NoError;
6333   SourceLocation ErrorLoc, NoteLoc;
6334   SourceRange ErrorRange, NoteRange;
6335   // Allowed constructs are:
6336   //  x = x binop expr;
6337   //  x = expr binop x;
6338   if (AtomicBinOp->getOpcode() == BO_Assign) {
6339     X = AtomicBinOp->getLHS();
6340     if (const auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
6341             AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
6342       if (AtomicInnerBinOp->isMultiplicativeOp() ||
6343           AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
6344           AtomicInnerBinOp->isBitwiseOp()) {
6345         Op = AtomicInnerBinOp->getOpcode();
6346         OpLoc = AtomicInnerBinOp->getOperatorLoc();
6347         Expr *LHS = AtomicInnerBinOp->getLHS();
6348         Expr *RHS = AtomicInnerBinOp->getRHS();
6349         llvm::FoldingSetNodeID XId, LHSId, RHSId;
6350         X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
6351                                           /*Canonical=*/true);
6352         LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
6353                                             /*Canonical=*/true);
6354         RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
6355                                             /*Canonical=*/true);
6356         if (XId == LHSId) {
6357           E = RHS;
6358           IsXLHSInRHSPart = true;
6359         } else if (XId == RHSId) {
6360           E = LHS;
6361           IsXLHSInRHSPart = false;
6362         } else {
6363           ErrorLoc = AtomicInnerBinOp->getExprLoc();
6364           ErrorRange = AtomicInnerBinOp->getSourceRange();
6365           NoteLoc = X->getExprLoc();
6366           NoteRange = X->getSourceRange();
6367           ErrorFound = NotAnUpdateExpression;
6368         }
6369       } else {
6370         ErrorLoc = AtomicInnerBinOp->getExprLoc();
6371         ErrorRange = AtomicInnerBinOp->getSourceRange();
6372         NoteLoc = AtomicInnerBinOp->getOperatorLoc();
6373         NoteRange = SourceRange(NoteLoc, NoteLoc);
6374         ErrorFound = NotABinaryOperator;
6375       }
6376     } else {
6377       NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
6378       NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
6379       ErrorFound = NotABinaryExpression;
6380     }
6381   } else {
6382     ErrorLoc = AtomicBinOp->getExprLoc();
6383     ErrorRange = AtomicBinOp->getSourceRange();
6384     NoteLoc = AtomicBinOp->getOperatorLoc();
6385     NoteRange = SourceRange(NoteLoc, NoteLoc);
6386     ErrorFound = NotAnAssignmentOp;
6387   }
6388   if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
6389     SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
6390     SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
6391     return true;
6392   }
6393   if (SemaRef.CurContext->isDependentContext())
6394     E = X = UpdateExpr = nullptr;
6395   return ErrorFound != NoError;
6396 }
6397 
6398 bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
6399                                                unsigned NoteId) {
6400   ExprAnalysisErrorCode ErrorFound = NoError;
6401   SourceLocation ErrorLoc, NoteLoc;
6402   SourceRange ErrorRange, NoteRange;
6403   // Allowed constructs are:
6404   //  x++;
6405   //  x--;
6406   //  ++x;
6407   //  --x;
6408   //  x binop= expr;
6409   //  x = x binop expr;
6410   //  x = expr binop x;
6411   if (auto *AtomicBody = dyn_cast<Expr>(S)) {
6412     AtomicBody = AtomicBody->IgnoreParenImpCasts();
6413     if (AtomicBody->getType()->isScalarType() ||
6414         AtomicBody->isInstantiationDependent()) {
6415       if (const auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
6416               AtomicBody->IgnoreParenImpCasts())) {
6417         // Check for Compound Assignment Operation
6418         Op = BinaryOperator::getOpForCompoundAssignment(
6419             AtomicCompAssignOp->getOpcode());
6420         OpLoc = AtomicCompAssignOp->getOperatorLoc();
6421         E = AtomicCompAssignOp->getRHS();
6422         X = AtomicCompAssignOp->getLHS()->IgnoreParens();
6423         IsXLHSInRHSPart = true;
6424       } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
6425                      AtomicBody->IgnoreParenImpCasts())) {
6426         // Check for Binary Operation
6427         if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
6428           return true;
6429       } else if (const auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
6430                      AtomicBody->IgnoreParenImpCasts())) {
6431         // Check for Unary Operation
6432         if (AtomicUnaryOp->isIncrementDecrementOp()) {
6433           IsPostfixUpdate = AtomicUnaryOp->isPostfix();
6434           Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
6435           OpLoc = AtomicUnaryOp->getOperatorLoc();
6436           X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
6437           E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
6438           IsXLHSInRHSPart = true;
6439         } else {
6440           ErrorFound = NotAnUnaryIncDecExpression;
6441           ErrorLoc = AtomicUnaryOp->getExprLoc();
6442           ErrorRange = AtomicUnaryOp->getSourceRange();
6443           NoteLoc = AtomicUnaryOp->getOperatorLoc();
6444           NoteRange = SourceRange(NoteLoc, NoteLoc);
6445         }
6446       } else if (!AtomicBody->isInstantiationDependent()) {
6447         ErrorFound = NotABinaryOrUnaryExpression;
6448         NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
6449         NoteRange = ErrorRange = AtomicBody->getSourceRange();
6450       }
6451     } else {
6452       ErrorFound = NotAScalarType;
6453       NoteLoc = ErrorLoc = AtomicBody->getBeginLoc();
6454       NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
6455     }
6456   } else {
6457     ErrorFound = NotAnExpression;
6458     NoteLoc = ErrorLoc = S->getBeginLoc();
6459     NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
6460   }
6461   if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
6462     SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
6463     SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
6464     return true;
6465   }
6466   if (SemaRef.CurContext->isDependentContext())
6467     E = X = UpdateExpr = nullptr;
6468   if (ErrorFound == NoError && E && X) {
6469     // Build an update expression of form 'OpaqueValueExpr(x) binop
6470     // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
6471     // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
6472     auto *OVEX = new (SemaRef.getASTContext())
6473         OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
6474     auto *OVEExpr = new (SemaRef.getASTContext())
6475         OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
6476     ExprResult Update =
6477         SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
6478                                    IsXLHSInRHSPart ? OVEExpr : OVEX);
6479     if (Update.isInvalid())
6480       return true;
6481     Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
6482                                                Sema::AA_Casting);
6483     if (Update.isInvalid())
6484       return true;
6485     UpdateExpr = Update.get();
6486   }
6487   return ErrorFound != NoError;
6488 }
6489 
6490 StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
6491                                             Stmt *AStmt,
6492                                             SourceLocation StartLoc,
6493                                             SourceLocation EndLoc) {
6494   if (!AStmt)
6495     return StmtError();
6496 
6497   auto *CS = cast<CapturedStmt>(AStmt);
6498   // 1.2.2 OpenMP Language Terminology
6499   // Structured block - An executable statement with a single entry at the
6500   // top and a single exit at the bottom.
6501   // The point of exit cannot be a branch out of the structured block.
6502   // longjmp() and throw() must not violate the entry/exit criteria.
6503   OpenMPClauseKind AtomicKind = OMPC_unknown;
6504   SourceLocation AtomicKindLoc;
6505   for (const OMPClause *C : Clauses) {
6506     if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
6507         C->getClauseKind() == OMPC_update ||
6508         C->getClauseKind() == OMPC_capture) {
6509       if (AtomicKind != OMPC_unknown) {
6510         Diag(C->getBeginLoc(), diag::err_omp_atomic_several_clauses)
6511             << SourceRange(C->getBeginLoc(), C->getEndLoc());
6512         Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
6513             << getOpenMPClauseName(AtomicKind);
6514       } else {
6515         AtomicKind = C->getClauseKind();
6516         AtomicKindLoc = C->getBeginLoc();
6517       }
6518     }
6519   }
6520 
6521   Stmt *Body = CS->getCapturedStmt();
6522   if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
6523     Body = EWC->getSubExpr();
6524 
6525   Expr *X = nullptr;
6526   Expr *V = nullptr;
6527   Expr *E = nullptr;
6528   Expr *UE = nullptr;
6529   bool IsXLHSInRHSPart = false;
6530   bool IsPostfixUpdate = false;
6531   // OpenMP [2.12.6, atomic Construct]
6532   // In the next expressions:
6533   // * x and v (as applicable) are both l-value expressions with scalar type.
6534   // * During the execution of an atomic region, multiple syntactic
6535   // occurrences of x must designate the same storage location.
6536   // * Neither of v and expr (as applicable) may access the storage location
6537   // designated by x.
6538   // * Neither of x and expr (as applicable) may access the storage location
6539   // designated by v.
6540   // * expr is an expression with scalar type.
6541   // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
6542   // * binop, binop=, ++, and -- are not overloaded operators.
6543   // * The expression x binop expr must be numerically equivalent to x binop
6544   // (expr). This requirement is satisfied if the operators in expr have
6545   // precedence greater than binop, or by using parentheses around expr or
6546   // subexpressions of expr.
6547   // * The expression expr binop x must be numerically equivalent to (expr)
6548   // binop x. This requirement is satisfied if the operators in expr have
6549   // precedence equal to or greater than binop, or by using parentheses around
6550   // expr or subexpressions of expr.
6551   // * For forms that allow multiple occurrences of x, the number of times
6552   // that x is evaluated is unspecified.
6553   if (AtomicKind == OMPC_read) {
6554     enum {
6555       NotAnExpression,
6556       NotAnAssignmentOp,
6557       NotAScalarType,
6558       NotAnLValue,
6559       NoError
6560     } ErrorFound = NoError;
6561     SourceLocation ErrorLoc, NoteLoc;
6562     SourceRange ErrorRange, NoteRange;
6563     // If clause is read:
6564     //  v = x;
6565     if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
6566       const auto *AtomicBinOp =
6567           dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
6568       if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
6569         X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
6570         V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
6571         if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
6572             (V->isInstantiationDependent() || V->getType()->isScalarType())) {
6573           if (!X->isLValue() || !V->isLValue()) {
6574             const Expr *NotLValueExpr = X->isLValue() ? V : X;
6575             ErrorFound = NotAnLValue;
6576             ErrorLoc = AtomicBinOp->getExprLoc();
6577             ErrorRange = AtomicBinOp->getSourceRange();
6578             NoteLoc = NotLValueExpr->getExprLoc();
6579             NoteRange = NotLValueExpr->getSourceRange();
6580           }
6581         } else if (!X->isInstantiationDependent() ||
6582                    !V->isInstantiationDependent()) {
6583           const Expr *NotScalarExpr =
6584               (X->isInstantiationDependent() || X->getType()->isScalarType())
6585                   ? V
6586                   : X;
6587           ErrorFound = NotAScalarType;
6588           ErrorLoc = AtomicBinOp->getExprLoc();
6589           ErrorRange = AtomicBinOp->getSourceRange();
6590           NoteLoc = NotScalarExpr->getExprLoc();
6591           NoteRange = NotScalarExpr->getSourceRange();
6592         }
6593       } else if (!AtomicBody->isInstantiationDependent()) {
6594         ErrorFound = NotAnAssignmentOp;
6595         ErrorLoc = AtomicBody->getExprLoc();
6596         ErrorRange = AtomicBody->getSourceRange();
6597         NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
6598                               : AtomicBody->getExprLoc();
6599         NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
6600                                 : AtomicBody->getSourceRange();
6601       }
6602     } else {
6603       ErrorFound = NotAnExpression;
6604       NoteLoc = ErrorLoc = Body->getBeginLoc();
6605       NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
6606     }
6607     if (ErrorFound != NoError) {
6608       Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
6609           << ErrorRange;
6610       Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
6611                                                       << NoteRange;
6612       return StmtError();
6613     }
6614     if (CurContext->isDependentContext())
6615       V = X = nullptr;
6616   } else if (AtomicKind == OMPC_write) {
6617     enum {
6618       NotAnExpression,
6619       NotAnAssignmentOp,
6620       NotAScalarType,
6621       NotAnLValue,
6622       NoError
6623     } ErrorFound = NoError;
6624     SourceLocation ErrorLoc, NoteLoc;
6625     SourceRange ErrorRange, NoteRange;
6626     // If clause is write:
6627     //  x = expr;
6628     if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
6629       const auto *AtomicBinOp =
6630           dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
6631       if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
6632         X = AtomicBinOp->getLHS();
6633         E = AtomicBinOp->getRHS();
6634         if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
6635             (E->isInstantiationDependent() || E->getType()->isScalarType())) {
6636           if (!X->isLValue()) {
6637             ErrorFound = NotAnLValue;
6638             ErrorLoc = AtomicBinOp->getExprLoc();
6639             ErrorRange = AtomicBinOp->getSourceRange();
6640             NoteLoc = X->getExprLoc();
6641             NoteRange = X->getSourceRange();
6642           }
6643         } else if (!X->isInstantiationDependent() ||
6644                    !E->isInstantiationDependent()) {
6645           const Expr *NotScalarExpr =
6646               (X->isInstantiationDependent() || X->getType()->isScalarType())
6647                   ? E
6648                   : X;
6649           ErrorFound = NotAScalarType;
6650           ErrorLoc = AtomicBinOp->getExprLoc();
6651           ErrorRange = AtomicBinOp->getSourceRange();
6652           NoteLoc = NotScalarExpr->getExprLoc();
6653           NoteRange = NotScalarExpr->getSourceRange();
6654         }
6655       } else if (!AtomicBody->isInstantiationDependent()) {
6656         ErrorFound = NotAnAssignmentOp;
6657         ErrorLoc = AtomicBody->getExprLoc();
6658         ErrorRange = AtomicBody->getSourceRange();
6659         NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
6660                               : AtomicBody->getExprLoc();
6661         NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
6662                                 : AtomicBody->getSourceRange();
6663       }
6664     } else {
6665       ErrorFound = NotAnExpression;
6666       NoteLoc = ErrorLoc = Body->getBeginLoc();
6667       NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
6668     }
6669     if (ErrorFound != NoError) {
6670       Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
6671           << ErrorRange;
6672       Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
6673                                                       << NoteRange;
6674       return StmtError();
6675     }
6676     if (CurContext->isDependentContext())
6677       E = X = nullptr;
6678   } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
6679     // If clause is update:
6680     //  x++;
6681     //  x--;
6682     //  ++x;
6683     //  --x;
6684     //  x binop= expr;
6685     //  x = x binop expr;
6686     //  x = expr binop x;
6687     OpenMPAtomicUpdateChecker Checker(*this);
6688     if (Checker.checkStatement(
6689             Body, (AtomicKind == OMPC_update)
6690                       ? diag::err_omp_atomic_update_not_expression_statement
6691                       : diag::err_omp_atomic_not_expression_statement,
6692             diag::note_omp_atomic_update))
6693       return StmtError();
6694     if (!CurContext->isDependentContext()) {
6695       E = Checker.getExpr();
6696       X = Checker.getX();
6697       UE = Checker.getUpdateExpr();
6698       IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
6699     }
6700   } else if (AtomicKind == OMPC_capture) {
6701     enum {
6702       NotAnAssignmentOp,
6703       NotACompoundStatement,
6704       NotTwoSubstatements,
6705       NotASpecificExpression,
6706       NoError
6707     } ErrorFound = NoError;
6708     SourceLocation ErrorLoc, NoteLoc;
6709     SourceRange ErrorRange, NoteRange;
6710     if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
6711       // If clause is a capture:
6712       //  v = x++;
6713       //  v = x--;
6714       //  v = ++x;
6715       //  v = --x;
6716       //  v = x binop= expr;
6717       //  v = x = x binop expr;
6718       //  v = x = expr binop x;
6719       const auto *AtomicBinOp =
6720           dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
6721       if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
6722         V = AtomicBinOp->getLHS();
6723         Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
6724         OpenMPAtomicUpdateChecker Checker(*this);
6725         if (Checker.checkStatement(
6726                 Body, diag::err_omp_atomic_capture_not_expression_statement,
6727                 diag::note_omp_atomic_update))
6728           return StmtError();
6729         E = Checker.getExpr();
6730         X = Checker.getX();
6731         UE = Checker.getUpdateExpr();
6732         IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
6733         IsPostfixUpdate = Checker.isPostfixUpdate();
6734       } else if (!AtomicBody->isInstantiationDependent()) {
6735         ErrorLoc = AtomicBody->getExprLoc();
6736         ErrorRange = AtomicBody->getSourceRange();
6737         NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
6738                               : AtomicBody->getExprLoc();
6739         NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
6740                                 : AtomicBody->getSourceRange();
6741         ErrorFound = NotAnAssignmentOp;
6742       }
6743       if (ErrorFound != NoError) {
6744         Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
6745             << ErrorRange;
6746         Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
6747         return StmtError();
6748       }
6749       if (CurContext->isDependentContext())
6750         UE = V = E = X = nullptr;
6751     } else {
6752       // If clause is a capture:
6753       //  { v = x; x = expr; }
6754       //  { v = x; x++; }
6755       //  { v = x; x--; }
6756       //  { v = x; ++x; }
6757       //  { v = x; --x; }
6758       //  { v = x; x binop= expr; }
6759       //  { v = x; x = x binop expr; }
6760       //  { v = x; x = expr binop x; }
6761       //  { x++; v = x; }
6762       //  { x--; v = x; }
6763       //  { ++x; v = x; }
6764       //  { --x; v = x; }
6765       //  { x binop= expr; v = x; }
6766       //  { x = x binop expr; v = x; }
6767       //  { x = expr binop x; v = x; }
6768       if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
6769         // Check that this is { expr1; expr2; }
6770         if (CS->size() == 2) {
6771           Stmt *First = CS->body_front();
6772           Stmt *Second = CS->body_back();
6773           if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
6774             First = EWC->getSubExpr()->IgnoreParenImpCasts();
6775           if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
6776             Second = EWC->getSubExpr()->IgnoreParenImpCasts();
6777           // Need to find what subexpression is 'v' and what is 'x'.
6778           OpenMPAtomicUpdateChecker Checker(*this);
6779           bool IsUpdateExprFound = !Checker.checkStatement(Second);
6780           BinaryOperator *BinOp = nullptr;
6781           if (IsUpdateExprFound) {
6782             BinOp = dyn_cast<BinaryOperator>(First);
6783             IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
6784           }
6785           if (IsUpdateExprFound && !CurContext->isDependentContext()) {
6786             //  { v = x; x++; }
6787             //  { v = x; x--; }
6788             //  { v = x; ++x; }
6789             //  { v = x; --x; }
6790             //  { v = x; x binop= expr; }
6791             //  { v = x; x = x binop expr; }
6792             //  { v = x; x = expr binop x; }
6793             // Check that the first expression has form v = x.
6794             Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
6795             llvm::FoldingSetNodeID XId, PossibleXId;
6796             Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
6797             PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
6798             IsUpdateExprFound = XId == PossibleXId;
6799             if (IsUpdateExprFound) {
6800               V = BinOp->getLHS();
6801               X = Checker.getX();
6802               E = Checker.getExpr();
6803               UE = Checker.getUpdateExpr();
6804               IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
6805               IsPostfixUpdate = true;
6806             }
6807           }
6808           if (!IsUpdateExprFound) {
6809             IsUpdateExprFound = !Checker.checkStatement(First);
6810             BinOp = nullptr;
6811             if (IsUpdateExprFound) {
6812               BinOp = dyn_cast<BinaryOperator>(Second);
6813               IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
6814             }
6815             if (IsUpdateExprFound && !CurContext->isDependentContext()) {
6816               //  { x++; v = x; }
6817               //  { x--; v = x; }
6818               //  { ++x; v = x; }
6819               //  { --x; v = x; }
6820               //  { x binop= expr; v = x; }
6821               //  { x = x binop expr; v = x; }
6822               //  { x = expr binop x; v = x; }
6823               // Check that the second expression has form v = x.
6824               Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
6825               llvm::FoldingSetNodeID XId, PossibleXId;
6826               Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
6827               PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
6828               IsUpdateExprFound = XId == PossibleXId;
6829               if (IsUpdateExprFound) {
6830                 V = BinOp->getLHS();
6831                 X = Checker.getX();
6832                 E = Checker.getExpr();
6833                 UE = Checker.getUpdateExpr();
6834                 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
6835                 IsPostfixUpdate = false;
6836               }
6837             }
6838           }
6839           if (!IsUpdateExprFound) {
6840             //  { v = x; x = expr; }
6841             auto *FirstExpr = dyn_cast<Expr>(First);
6842             auto *SecondExpr = dyn_cast<Expr>(Second);
6843             if (!FirstExpr || !SecondExpr ||
6844                 !(FirstExpr->isInstantiationDependent() ||
6845                   SecondExpr->isInstantiationDependent())) {
6846               auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
6847               if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
6848                 ErrorFound = NotAnAssignmentOp;
6849                 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
6850                                                 : First->getBeginLoc();
6851                 NoteRange = ErrorRange = FirstBinOp
6852                                              ? FirstBinOp->getSourceRange()
6853                                              : SourceRange(ErrorLoc, ErrorLoc);
6854               } else {
6855                 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
6856                 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
6857                   ErrorFound = NotAnAssignmentOp;
6858                   NoteLoc = ErrorLoc = SecondBinOp
6859                                            ? SecondBinOp->getOperatorLoc()
6860                                            : Second->getBeginLoc();
6861                   NoteRange = ErrorRange =
6862                       SecondBinOp ? SecondBinOp->getSourceRange()
6863                                   : SourceRange(ErrorLoc, ErrorLoc);
6864                 } else {
6865                   Expr *PossibleXRHSInFirst =
6866                       FirstBinOp->getRHS()->IgnoreParenImpCasts();
6867                   Expr *PossibleXLHSInSecond =
6868                       SecondBinOp->getLHS()->IgnoreParenImpCasts();
6869                   llvm::FoldingSetNodeID X1Id, X2Id;
6870                   PossibleXRHSInFirst->Profile(X1Id, Context,
6871                                                /*Canonical=*/true);
6872                   PossibleXLHSInSecond->Profile(X2Id, Context,
6873                                                 /*Canonical=*/true);
6874                   IsUpdateExprFound = X1Id == X2Id;
6875                   if (IsUpdateExprFound) {
6876                     V = FirstBinOp->getLHS();
6877                     X = SecondBinOp->getLHS();
6878                     E = SecondBinOp->getRHS();
6879                     UE = nullptr;
6880                     IsXLHSInRHSPart = false;
6881                     IsPostfixUpdate = true;
6882                   } else {
6883                     ErrorFound = NotASpecificExpression;
6884                     ErrorLoc = FirstBinOp->getExprLoc();
6885                     ErrorRange = FirstBinOp->getSourceRange();
6886                     NoteLoc = SecondBinOp->getLHS()->getExprLoc();
6887                     NoteRange = SecondBinOp->getRHS()->getSourceRange();
6888                   }
6889                 }
6890               }
6891             }
6892           }
6893         } else {
6894           NoteLoc = ErrorLoc = Body->getBeginLoc();
6895           NoteRange = ErrorRange =
6896               SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
6897           ErrorFound = NotTwoSubstatements;
6898         }
6899       } else {
6900         NoteLoc = ErrorLoc = Body->getBeginLoc();
6901         NoteRange = ErrorRange =
6902             SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
6903         ErrorFound = NotACompoundStatement;
6904       }
6905       if (ErrorFound != NoError) {
6906         Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
6907             << ErrorRange;
6908         Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
6909         return StmtError();
6910       }
6911       if (CurContext->isDependentContext())
6912         UE = V = E = X = nullptr;
6913     }
6914   }
6915 
6916   setFunctionHasBranchProtectedScope();
6917 
6918   return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
6919                                     X, V, E, UE, IsXLHSInRHSPart,
6920                                     IsPostfixUpdate);
6921 }
6922 
6923 StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
6924                                             Stmt *AStmt,
6925                                             SourceLocation StartLoc,
6926                                             SourceLocation EndLoc) {
6927   if (!AStmt)
6928     return StmtError();
6929 
6930   auto *CS = cast<CapturedStmt>(AStmt);
6931   // 1.2.2 OpenMP Language Terminology
6932   // Structured block - An executable statement with a single entry at the
6933   // top and a single exit at the bottom.
6934   // The point of exit cannot be a branch out of the structured block.
6935   // longjmp() and throw() must not violate the entry/exit criteria.
6936   CS->getCapturedDecl()->setNothrow();
6937   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target);
6938        ThisCaptureLevel > 1; --ThisCaptureLevel) {
6939     CS = cast<CapturedStmt>(CS->getCapturedStmt());
6940     // 1.2.2 OpenMP Language Terminology
6941     // Structured block - An executable statement with a single entry at the
6942     // top and a single exit at the bottom.
6943     // The point of exit cannot be a branch out of the structured block.
6944     // longjmp() and throw() must not violate the entry/exit criteria.
6945     CS->getCapturedDecl()->setNothrow();
6946   }
6947 
6948   // OpenMP [2.16, Nesting of Regions]
6949   // If specified, a teams construct must be contained within a target
6950   // construct. That target construct must contain no statements or directives
6951   // outside of the teams construct.
6952   if (DSAStack->hasInnerTeamsRegion()) {
6953     const Stmt *S = CS->IgnoreContainers(/*IgnoreCaptured=*/true);
6954     bool OMPTeamsFound = true;
6955     if (const auto *CS = dyn_cast<CompoundStmt>(S)) {
6956       auto I = CS->body_begin();
6957       while (I != CS->body_end()) {
6958         const auto *OED = dyn_cast<OMPExecutableDirective>(*I);
6959         if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) {
6960           OMPTeamsFound = false;
6961           break;
6962         }
6963         ++I;
6964       }
6965       assert(I != CS->body_end() && "Not found statement");
6966       S = *I;
6967     } else {
6968       const auto *OED = dyn_cast<OMPExecutableDirective>(S);
6969       OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
6970     }
6971     if (!OMPTeamsFound) {
6972       Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
6973       Diag(DSAStack->getInnerTeamsRegionLoc(),
6974            diag::note_omp_nested_teams_construct_here);
6975       Diag(S->getBeginLoc(), diag::note_omp_nested_statement_here)
6976           << isa<OMPExecutableDirective>(S);
6977       return StmtError();
6978     }
6979   }
6980 
6981   setFunctionHasBranchProtectedScope();
6982 
6983   return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
6984 }
6985 
6986 StmtResult
6987 Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
6988                                          Stmt *AStmt, SourceLocation StartLoc,
6989                                          SourceLocation EndLoc) {
6990   if (!AStmt)
6991     return StmtError();
6992 
6993   auto *CS = cast<CapturedStmt>(AStmt);
6994   // 1.2.2 OpenMP Language Terminology
6995   // Structured block - An executable statement with a single entry at the
6996   // top and a single exit at the bottom.
6997   // The point of exit cannot be a branch out of the structured block.
6998   // longjmp() and throw() must not violate the entry/exit criteria.
6999   CS->getCapturedDecl()->setNothrow();
7000   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel);
7001        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7002     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7003     // 1.2.2 OpenMP Language Terminology
7004     // Structured block - An executable statement with a single entry at the
7005     // top and a single exit at the bottom.
7006     // The point of exit cannot be a branch out of the structured block.
7007     // longjmp() and throw() must not violate the entry/exit criteria.
7008     CS->getCapturedDecl()->setNothrow();
7009   }
7010 
7011   setFunctionHasBranchProtectedScope();
7012 
7013   return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
7014                                             AStmt);
7015 }
7016 
7017 StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
7018     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7019     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
7020   if (!AStmt)
7021     return StmtError();
7022 
7023   auto *CS = cast<CapturedStmt>(AStmt);
7024   // 1.2.2 OpenMP Language Terminology
7025   // Structured block - An executable statement with a single entry at the
7026   // top and a single exit at the bottom.
7027   // The point of exit cannot be a branch out of the structured block.
7028   // longjmp() and throw() must not violate the entry/exit criteria.
7029   CS->getCapturedDecl()->setNothrow();
7030   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
7031        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7032     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7033     // 1.2.2 OpenMP Language Terminology
7034     // Structured block - An executable statement with a single entry at the
7035     // top and a single exit at the bottom.
7036     // The point of exit cannot be a branch out of the structured block.
7037     // longjmp() and throw() must not violate the entry/exit criteria.
7038     CS->getCapturedDecl()->setNothrow();
7039   }
7040 
7041   OMPLoopDirective::HelperExprs B;
7042   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7043   // define the nested loops number.
7044   unsigned NestedLoopCount =
7045       checkOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
7046                       getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
7047                       VarsWithImplicitDSA, B);
7048   if (NestedLoopCount == 0)
7049     return StmtError();
7050 
7051   assert((CurContext->isDependentContext() || B.builtAll()) &&
7052          "omp target parallel for loop exprs were not built");
7053 
7054   if (!CurContext->isDependentContext()) {
7055     // Finalize the clauses that need pre-built expressions for CodeGen.
7056     for (OMPClause *C : Clauses) {
7057       if (auto *LC = dyn_cast<OMPLinearClause>(C))
7058         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7059                                      B.NumIterations, *this, CurScope,
7060                                      DSAStack))
7061           return StmtError();
7062     }
7063   }
7064 
7065   setFunctionHasBranchProtectedScope();
7066   return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
7067                                                NestedLoopCount, Clauses, AStmt,
7068                                                B, DSAStack->isCancelRegion());
7069 }
7070 
7071 /// Check for existence of a map clause in the list of clauses.
7072 static bool hasClauses(ArrayRef<OMPClause *> Clauses,
7073                        const OpenMPClauseKind K) {
7074   return llvm::any_of(
7075       Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; });
7076 }
7077 
7078 template <typename... Params>
7079 static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K,
7080                        const Params... ClauseTypes) {
7081   return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...);
7082 }
7083 
7084 StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
7085                                                 Stmt *AStmt,
7086                                                 SourceLocation StartLoc,
7087                                                 SourceLocation EndLoc) {
7088   if (!AStmt)
7089     return StmtError();
7090 
7091   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
7092 
7093   // OpenMP [2.10.1, Restrictions, p. 97]
7094   // At least one map clause must appear on the directive.
7095   if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr)) {
7096     Diag(StartLoc, diag::err_omp_no_clause_for_directive)
7097         << "'map' or 'use_device_ptr'"
7098         << getOpenMPDirectiveName(OMPD_target_data);
7099     return StmtError();
7100   }
7101 
7102   setFunctionHasBranchProtectedScope();
7103 
7104   return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
7105                                         AStmt);
7106 }
7107 
7108 StmtResult
7109 Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
7110                                           SourceLocation StartLoc,
7111                                           SourceLocation EndLoc, Stmt *AStmt) {
7112   if (!AStmt)
7113     return StmtError();
7114 
7115   auto *CS = cast<CapturedStmt>(AStmt);
7116   // 1.2.2 OpenMP Language Terminology
7117   // Structured block - An executable statement with a single entry at the
7118   // top and a single exit at the bottom.
7119   // The point of exit cannot be a branch out of the structured block.
7120   // longjmp() and throw() must not violate the entry/exit criteria.
7121   CS->getCapturedDecl()->setNothrow();
7122   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_enter_data);
7123        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7124     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7125     // 1.2.2 OpenMP Language Terminology
7126     // Structured block - An executable statement with a single entry at the
7127     // top and a single exit at the bottom.
7128     // The point of exit cannot be a branch out of the structured block.
7129     // longjmp() and throw() must not violate the entry/exit criteria.
7130     CS->getCapturedDecl()->setNothrow();
7131   }
7132 
7133   // OpenMP [2.10.2, Restrictions, p. 99]
7134   // At least one map clause must appear on the directive.
7135   if (!hasClauses(Clauses, OMPC_map)) {
7136     Diag(StartLoc, diag::err_omp_no_clause_for_directive)
7137         << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data);
7138     return StmtError();
7139   }
7140 
7141   return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
7142                                              AStmt);
7143 }
7144 
7145 StmtResult
7146 Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
7147                                          SourceLocation StartLoc,
7148                                          SourceLocation EndLoc, Stmt *AStmt) {
7149   if (!AStmt)
7150     return StmtError();
7151 
7152   auto *CS = cast<CapturedStmt>(AStmt);
7153   // 1.2.2 OpenMP Language Terminology
7154   // Structured block - An executable statement with a single entry at the
7155   // top and a single exit at the bottom.
7156   // The point of exit cannot be a branch out of the structured block.
7157   // longjmp() and throw() must not violate the entry/exit criteria.
7158   CS->getCapturedDecl()->setNothrow();
7159   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_exit_data);
7160        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7161     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7162     // 1.2.2 OpenMP Language Terminology
7163     // Structured block - An executable statement with a single entry at the
7164     // top and a single exit at the bottom.
7165     // The point of exit cannot be a branch out of the structured block.
7166     // longjmp() and throw() must not violate the entry/exit criteria.
7167     CS->getCapturedDecl()->setNothrow();
7168   }
7169 
7170   // OpenMP [2.10.3, Restrictions, p. 102]
7171   // At least one map clause must appear on the directive.
7172   if (!hasClauses(Clauses, OMPC_map)) {
7173     Diag(StartLoc, diag::err_omp_no_clause_for_directive)
7174         << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data);
7175     return StmtError();
7176   }
7177 
7178   return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
7179                                             AStmt);
7180 }
7181 
7182 StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
7183                                                   SourceLocation StartLoc,
7184                                                   SourceLocation EndLoc,
7185                                                   Stmt *AStmt) {
7186   if (!AStmt)
7187     return StmtError();
7188 
7189   auto *CS = cast<CapturedStmt>(AStmt);
7190   // 1.2.2 OpenMP Language Terminology
7191   // Structured block - An executable statement with a single entry at the
7192   // top and a single exit at the bottom.
7193   // The point of exit cannot be a branch out of the structured block.
7194   // longjmp() and throw() must not violate the entry/exit criteria.
7195   CS->getCapturedDecl()->setNothrow();
7196   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_update);
7197        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7198     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7199     // 1.2.2 OpenMP Language Terminology
7200     // Structured block - An executable statement with a single entry at the
7201     // top and a single exit at the bottom.
7202     // The point of exit cannot be a branch out of the structured block.
7203     // longjmp() and throw() must not violate the entry/exit criteria.
7204     CS->getCapturedDecl()->setNothrow();
7205   }
7206 
7207   if (!hasClauses(Clauses, OMPC_to, OMPC_from)) {
7208     Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
7209     return StmtError();
7210   }
7211   return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses,
7212                                           AStmt);
7213 }
7214 
7215 StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
7216                                            Stmt *AStmt, SourceLocation StartLoc,
7217                                            SourceLocation EndLoc) {
7218   if (!AStmt)
7219     return StmtError();
7220 
7221   auto *CS = cast<CapturedStmt>(AStmt);
7222   // 1.2.2 OpenMP Language Terminology
7223   // Structured block - An executable statement with a single entry at the
7224   // top and a single exit at the bottom.
7225   // The point of exit cannot be a branch out of the structured block.
7226   // longjmp() and throw() must not violate the entry/exit criteria.
7227   CS->getCapturedDecl()->setNothrow();
7228 
7229   setFunctionHasBranchProtectedScope();
7230 
7231   DSAStack->setParentTeamsRegionLoc(StartLoc);
7232 
7233   return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
7234 }
7235 
7236 StmtResult
7237 Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
7238                                             SourceLocation EndLoc,
7239                                             OpenMPDirectiveKind CancelRegion) {
7240   if (DSAStack->isParentNowaitRegion()) {
7241     Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
7242     return StmtError();
7243   }
7244   if (DSAStack->isParentOrderedRegion()) {
7245     Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
7246     return StmtError();
7247   }
7248   return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
7249                                                CancelRegion);
7250 }
7251 
7252 StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
7253                                             SourceLocation StartLoc,
7254                                             SourceLocation EndLoc,
7255                                             OpenMPDirectiveKind CancelRegion) {
7256   if (DSAStack->isParentNowaitRegion()) {
7257     Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
7258     return StmtError();
7259   }
7260   if (DSAStack->isParentOrderedRegion()) {
7261     Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
7262     return StmtError();
7263   }
7264   DSAStack->setParentCancelRegion(/*Cancel=*/true);
7265   return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
7266                                     CancelRegion);
7267 }
7268 
7269 static bool checkGrainsizeNumTasksClauses(Sema &S,
7270                                           ArrayRef<OMPClause *> Clauses) {
7271   const OMPClause *PrevClause = nullptr;
7272   bool ErrorFound = false;
7273   for (const OMPClause *C : Clauses) {
7274     if (C->getClauseKind() == OMPC_grainsize ||
7275         C->getClauseKind() == OMPC_num_tasks) {
7276       if (!PrevClause)
7277         PrevClause = C;
7278       else if (PrevClause->getClauseKind() != C->getClauseKind()) {
7279         S.Diag(C->getBeginLoc(),
7280                diag::err_omp_grainsize_num_tasks_mutually_exclusive)
7281             << getOpenMPClauseName(C->getClauseKind())
7282             << getOpenMPClauseName(PrevClause->getClauseKind());
7283         S.Diag(PrevClause->getBeginLoc(),
7284                diag::note_omp_previous_grainsize_num_tasks)
7285             << getOpenMPClauseName(PrevClause->getClauseKind());
7286         ErrorFound = true;
7287       }
7288     }
7289   }
7290   return ErrorFound;
7291 }
7292 
7293 static bool checkReductionClauseWithNogroup(Sema &S,
7294                                             ArrayRef<OMPClause *> Clauses) {
7295   const OMPClause *ReductionClause = nullptr;
7296   const OMPClause *NogroupClause = nullptr;
7297   for (const OMPClause *C : Clauses) {
7298     if (C->getClauseKind() == OMPC_reduction) {
7299       ReductionClause = C;
7300       if (NogroupClause)
7301         break;
7302       continue;
7303     }
7304     if (C->getClauseKind() == OMPC_nogroup) {
7305       NogroupClause = C;
7306       if (ReductionClause)
7307         break;
7308       continue;
7309     }
7310   }
7311   if (ReductionClause && NogroupClause) {
7312     S.Diag(ReductionClause->getBeginLoc(), diag::err_omp_reduction_with_nogroup)
7313         << SourceRange(NogroupClause->getBeginLoc(),
7314                        NogroupClause->getEndLoc());
7315     return true;
7316   }
7317   return false;
7318 }
7319 
7320 StmtResult Sema::ActOnOpenMPTaskLoopDirective(
7321     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7322     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
7323   if (!AStmt)
7324     return StmtError();
7325 
7326   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
7327   OMPLoopDirective::HelperExprs B;
7328   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7329   // define the nested loops number.
7330   unsigned NestedLoopCount =
7331       checkOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
7332                       /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
7333                       VarsWithImplicitDSA, B);
7334   if (NestedLoopCount == 0)
7335     return StmtError();
7336 
7337   assert((CurContext->isDependentContext() || B.builtAll()) &&
7338          "omp for loop exprs were not built");
7339 
7340   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
7341   // The grainsize clause and num_tasks clause are mutually exclusive and may
7342   // not appear on the same taskloop directive.
7343   if (checkGrainsizeNumTasksClauses(*this, Clauses))
7344     return StmtError();
7345   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
7346   // If a reduction clause is present on the taskloop directive, the nogroup
7347   // clause must not be specified.
7348   if (checkReductionClauseWithNogroup(*this, Clauses))
7349     return StmtError();
7350 
7351   setFunctionHasBranchProtectedScope();
7352   return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
7353                                       NestedLoopCount, Clauses, AStmt, B);
7354 }
7355 
7356 StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
7357     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7358     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
7359   if (!AStmt)
7360     return StmtError();
7361 
7362   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
7363   OMPLoopDirective::HelperExprs B;
7364   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7365   // define the nested loops number.
7366   unsigned NestedLoopCount =
7367       checkOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
7368                       /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
7369                       VarsWithImplicitDSA, B);
7370   if (NestedLoopCount == 0)
7371     return StmtError();
7372 
7373   assert((CurContext->isDependentContext() || B.builtAll()) &&
7374          "omp for loop exprs were not built");
7375 
7376   if (!CurContext->isDependentContext()) {
7377     // Finalize the clauses that need pre-built expressions for CodeGen.
7378     for (OMPClause *C : Clauses) {
7379       if (auto *LC = dyn_cast<OMPLinearClause>(C))
7380         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7381                                      B.NumIterations, *this, CurScope,
7382                                      DSAStack))
7383           return StmtError();
7384     }
7385   }
7386 
7387   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
7388   // The grainsize clause and num_tasks clause are mutually exclusive and may
7389   // not appear on the same taskloop directive.
7390   if (checkGrainsizeNumTasksClauses(*this, Clauses))
7391     return StmtError();
7392   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
7393   // If a reduction clause is present on the taskloop directive, the nogroup
7394   // clause must not be specified.
7395   if (checkReductionClauseWithNogroup(*this, Clauses))
7396     return StmtError();
7397   if (checkSimdlenSafelenSpecified(*this, Clauses))
7398     return StmtError();
7399 
7400   setFunctionHasBranchProtectedScope();
7401   return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
7402                                           NestedLoopCount, Clauses, AStmt, B);
7403 }
7404 
7405 StmtResult Sema::ActOnOpenMPDistributeDirective(
7406     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7407     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
7408   if (!AStmt)
7409     return StmtError();
7410 
7411   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
7412   OMPLoopDirective::HelperExprs B;
7413   // In presence of clause 'collapse' with number of loops, it will
7414   // define the nested loops number.
7415   unsigned NestedLoopCount =
7416       checkOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
7417                       nullptr /*ordered not a clause on distribute*/, AStmt,
7418                       *this, *DSAStack, VarsWithImplicitDSA, B);
7419   if (NestedLoopCount == 0)
7420     return StmtError();
7421 
7422   assert((CurContext->isDependentContext() || B.builtAll()) &&
7423          "omp for loop exprs were not built");
7424 
7425   setFunctionHasBranchProtectedScope();
7426   return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
7427                                         NestedLoopCount, Clauses, AStmt, B);
7428 }
7429 
7430 StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
7431     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7432     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
7433   if (!AStmt)
7434     return StmtError();
7435 
7436   auto *CS = cast<CapturedStmt>(AStmt);
7437   // 1.2.2 OpenMP Language Terminology
7438   // Structured block - An executable statement with a single entry at the
7439   // top and a single exit at the bottom.
7440   // The point of exit cannot be a branch out of the structured block.
7441   // longjmp() and throw() must not violate the entry/exit criteria.
7442   CS->getCapturedDecl()->setNothrow();
7443   for (int ThisCaptureLevel =
7444            getOpenMPCaptureLevels(OMPD_distribute_parallel_for);
7445        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7446     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7447     // 1.2.2 OpenMP Language Terminology
7448     // Structured block - An executable statement with a single entry at the
7449     // top and a single exit at the bottom.
7450     // The point of exit cannot be a branch out of the structured block.
7451     // longjmp() and throw() must not violate the entry/exit criteria.
7452     CS->getCapturedDecl()->setNothrow();
7453   }
7454 
7455   OMPLoopDirective::HelperExprs B;
7456   // In presence of clause 'collapse' with number of loops, it will
7457   // define the nested loops number.
7458   unsigned NestedLoopCount = checkOpenMPLoop(
7459       OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
7460       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
7461       VarsWithImplicitDSA, B);
7462   if (NestedLoopCount == 0)
7463     return StmtError();
7464 
7465   assert((CurContext->isDependentContext() || B.builtAll()) &&
7466          "omp for loop exprs were not built");
7467 
7468   setFunctionHasBranchProtectedScope();
7469   return OMPDistributeParallelForDirective::Create(
7470       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
7471       DSAStack->isCancelRegion());
7472 }
7473 
7474 StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
7475     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7476     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
7477   if (!AStmt)
7478     return StmtError();
7479 
7480   auto *CS = cast<CapturedStmt>(AStmt);
7481   // 1.2.2 OpenMP Language Terminology
7482   // Structured block - An executable statement with a single entry at the
7483   // top and a single exit at the bottom.
7484   // The point of exit cannot be a branch out of the structured block.
7485   // longjmp() and throw() must not violate the entry/exit criteria.
7486   CS->getCapturedDecl()->setNothrow();
7487   for (int ThisCaptureLevel =
7488            getOpenMPCaptureLevels(OMPD_distribute_parallel_for_simd);
7489        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7490     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7491     // 1.2.2 OpenMP Language Terminology
7492     // Structured block - An executable statement with a single entry at the
7493     // top and a single exit at the bottom.
7494     // The point of exit cannot be a branch out of the structured block.
7495     // longjmp() and throw() must not violate the entry/exit criteria.
7496     CS->getCapturedDecl()->setNothrow();
7497   }
7498 
7499   OMPLoopDirective::HelperExprs B;
7500   // In presence of clause 'collapse' with number of loops, it will
7501   // define the nested loops number.
7502   unsigned NestedLoopCount = checkOpenMPLoop(
7503       OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
7504       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
7505       VarsWithImplicitDSA, B);
7506   if (NestedLoopCount == 0)
7507     return StmtError();
7508 
7509   assert((CurContext->isDependentContext() || B.builtAll()) &&
7510          "omp for loop exprs were not built");
7511 
7512   if (!CurContext->isDependentContext()) {
7513     // Finalize the clauses that need pre-built expressions for CodeGen.
7514     for (OMPClause *C : Clauses) {
7515       if (auto *LC = dyn_cast<OMPLinearClause>(C))
7516         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7517                                      B.NumIterations, *this, CurScope,
7518                                      DSAStack))
7519           return StmtError();
7520     }
7521   }
7522 
7523   if (checkSimdlenSafelenSpecified(*this, Clauses))
7524     return StmtError();
7525 
7526   setFunctionHasBranchProtectedScope();
7527   return OMPDistributeParallelForSimdDirective::Create(
7528       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7529 }
7530 
7531 StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
7532     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7533     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
7534   if (!AStmt)
7535     return StmtError();
7536 
7537   auto *CS = cast<CapturedStmt>(AStmt);
7538   // 1.2.2 OpenMP Language Terminology
7539   // Structured block - An executable statement with a single entry at the
7540   // top and a single exit at the bottom.
7541   // The point of exit cannot be a branch out of the structured block.
7542   // longjmp() and throw() must not violate the entry/exit criteria.
7543   CS->getCapturedDecl()->setNothrow();
7544   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_distribute_simd);
7545        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7546     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7547     // 1.2.2 OpenMP Language Terminology
7548     // Structured block - An executable statement with a single entry at the
7549     // top and a single exit at the bottom.
7550     // The point of exit cannot be a branch out of the structured block.
7551     // longjmp() and throw() must not violate the entry/exit criteria.
7552     CS->getCapturedDecl()->setNothrow();
7553   }
7554 
7555   OMPLoopDirective::HelperExprs B;
7556   // In presence of clause 'collapse' with number of loops, it will
7557   // define the nested loops number.
7558   unsigned NestedLoopCount =
7559       checkOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
7560                       nullptr /*ordered not a clause on distribute*/, CS, *this,
7561                       *DSAStack, VarsWithImplicitDSA, B);
7562   if (NestedLoopCount == 0)
7563     return StmtError();
7564 
7565   assert((CurContext->isDependentContext() || B.builtAll()) &&
7566          "omp for loop exprs were not built");
7567 
7568   if (!CurContext->isDependentContext()) {
7569     // Finalize the clauses that need pre-built expressions for CodeGen.
7570     for (OMPClause *C : Clauses) {
7571       if (auto *LC = dyn_cast<OMPLinearClause>(C))
7572         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7573                                      B.NumIterations, *this, CurScope,
7574                                      DSAStack))
7575           return StmtError();
7576     }
7577   }
7578 
7579   if (checkSimdlenSafelenSpecified(*this, Clauses))
7580     return StmtError();
7581 
7582   setFunctionHasBranchProtectedScope();
7583   return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
7584                                             NestedLoopCount, Clauses, AStmt, B);
7585 }
7586 
7587 StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
7588     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7589     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
7590   if (!AStmt)
7591     return StmtError();
7592 
7593   auto *CS = cast<CapturedStmt>(AStmt);
7594   // 1.2.2 OpenMP Language Terminology
7595   // Structured block - An executable statement with a single entry at the
7596   // top and a single exit at the bottom.
7597   // The point of exit cannot be a branch out of the structured block.
7598   // longjmp() and throw() must not violate the entry/exit criteria.
7599   CS->getCapturedDecl()->setNothrow();
7600   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
7601        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7602     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7603     // 1.2.2 OpenMP Language Terminology
7604     // Structured block - An executable statement with a single entry at the
7605     // top and a single exit at the bottom.
7606     // The point of exit cannot be a branch out of the structured block.
7607     // longjmp() and throw() must not violate the entry/exit criteria.
7608     CS->getCapturedDecl()->setNothrow();
7609   }
7610 
7611   OMPLoopDirective::HelperExprs B;
7612   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7613   // define the nested loops number.
7614   unsigned NestedLoopCount = checkOpenMPLoop(
7615       OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
7616       getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
7617       VarsWithImplicitDSA, B);
7618   if (NestedLoopCount == 0)
7619     return StmtError();
7620 
7621   assert((CurContext->isDependentContext() || B.builtAll()) &&
7622          "omp target parallel for simd loop exprs were not built");
7623 
7624   if (!CurContext->isDependentContext()) {
7625     // Finalize the clauses that need pre-built expressions for CodeGen.
7626     for (OMPClause *C : Clauses) {
7627       if (auto *LC = dyn_cast<OMPLinearClause>(C))
7628         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7629                                      B.NumIterations, *this, CurScope,
7630                                      DSAStack))
7631           return StmtError();
7632     }
7633   }
7634   if (checkSimdlenSafelenSpecified(*this, Clauses))
7635     return StmtError();
7636 
7637   setFunctionHasBranchProtectedScope();
7638   return OMPTargetParallelForSimdDirective::Create(
7639       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7640 }
7641 
7642 StmtResult Sema::ActOnOpenMPTargetSimdDirective(
7643     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7644     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
7645   if (!AStmt)
7646     return StmtError();
7647 
7648   auto *CS = cast<CapturedStmt>(AStmt);
7649   // 1.2.2 OpenMP Language Terminology
7650   // Structured block - An executable statement with a single entry at the
7651   // top and a single exit at the bottom.
7652   // The point of exit cannot be a branch out of the structured block.
7653   // longjmp() and throw() must not violate the entry/exit criteria.
7654   CS->getCapturedDecl()->setNothrow();
7655   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_simd);
7656        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7657     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7658     // 1.2.2 OpenMP Language Terminology
7659     // Structured block - An executable statement with a single entry at the
7660     // top and a single exit at the bottom.
7661     // The point of exit cannot be a branch out of the structured block.
7662     // longjmp() and throw() must not violate the entry/exit criteria.
7663     CS->getCapturedDecl()->setNothrow();
7664   }
7665 
7666   OMPLoopDirective::HelperExprs B;
7667   // In presence of clause 'collapse' with number of loops, it will define the
7668   // nested loops number.
7669   unsigned NestedLoopCount =
7670       checkOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
7671                       getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
7672                       VarsWithImplicitDSA, B);
7673   if (NestedLoopCount == 0)
7674     return StmtError();
7675 
7676   assert((CurContext->isDependentContext() || B.builtAll()) &&
7677          "omp target simd loop exprs were not built");
7678 
7679   if (!CurContext->isDependentContext()) {
7680     // Finalize the clauses that need pre-built expressions for CodeGen.
7681     for (OMPClause *C : Clauses) {
7682       if (auto *LC = dyn_cast<OMPLinearClause>(C))
7683         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7684                                      B.NumIterations, *this, CurScope,
7685                                      DSAStack))
7686           return StmtError();
7687     }
7688   }
7689 
7690   if (checkSimdlenSafelenSpecified(*this, Clauses))
7691     return StmtError();
7692 
7693   setFunctionHasBranchProtectedScope();
7694   return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
7695                                         NestedLoopCount, Clauses, AStmt, B);
7696 }
7697 
7698 StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
7699     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7700     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
7701   if (!AStmt)
7702     return StmtError();
7703 
7704   auto *CS = cast<CapturedStmt>(AStmt);
7705   // 1.2.2 OpenMP Language Terminology
7706   // Structured block - An executable statement with a single entry at the
7707   // top and a single exit at the bottom.
7708   // The point of exit cannot be a branch out of the structured block.
7709   // longjmp() and throw() must not violate the entry/exit criteria.
7710   CS->getCapturedDecl()->setNothrow();
7711   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_teams_distribute);
7712        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7713     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7714     // 1.2.2 OpenMP Language Terminology
7715     // Structured block - An executable statement with a single entry at the
7716     // top and a single exit at the bottom.
7717     // The point of exit cannot be a branch out of the structured block.
7718     // longjmp() and throw() must not violate the entry/exit criteria.
7719     CS->getCapturedDecl()->setNothrow();
7720   }
7721 
7722   OMPLoopDirective::HelperExprs B;
7723   // In presence of clause 'collapse' with number of loops, it will
7724   // define the nested loops number.
7725   unsigned NestedLoopCount =
7726       checkOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
7727                       nullptr /*ordered not a clause on distribute*/, CS, *this,
7728                       *DSAStack, VarsWithImplicitDSA, B);
7729   if (NestedLoopCount == 0)
7730     return StmtError();
7731 
7732   assert((CurContext->isDependentContext() || B.builtAll()) &&
7733          "omp teams distribute loop exprs were not built");
7734 
7735   setFunctionHasBranchProtectedScope();
7736 
7737   DSAStack->setParentTeamsRegionLoc(StartLoc);
7738 
7739   return OMPTeamsDistributeDirective::Create(
7740       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7741 }
7742 
7743 StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
7744     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7745     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
7746   if (!AStmt)
7747     return StmtError();
7748 
7749   auto *CS = cast<CapturedStmt>(AStmt);
7750   // 1.2.2 OpenMP Language Terminology
7751   // Structured block - An executable statement with a single entry at the
7752   // top and a single exit at the bottom.
7753   // The point of exit cannot be a branch out of the structured block.
7754   // longjmp() and throw() must not violate the entry/exit criteria.
7755   CS->getCapturedDecl()->setNothrow();
7756   for (int ThisCaptureLevel =
7757            getOpenMPCaptureLevels(OMPD_teams_distribute_simd);
7758        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7759     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7760     // 1.2.2 OpenMP Language Terminology
7761     // Structured block - An executable statement with a single entry at the
7762     // top and a single exit at the bottom.
7763     // The point of exit cannot be a branch out of the structured block.
7764     // longjmp() and throw() must not violate the entry/exit criteria.
7765     CS->getCapturedDecl()->setNothrow();
7766   }
7767 
7768 
7769   OMPLoopDirective::HelperExprs B;
7770   // In presence of clause 'collapse' with number of loops, it will
7771   // define the nested loops number.
7772   unsigned NestedLoopCount = checkOpenMPLoop(
7773       OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
7774       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
7775       VarsWithImplicitDSA, B);
7776 
7777   if (NestedLoopCount == 0)
7778     return StmtError();
7779 
7780   assert((CurContext->isDependentContext() || B.builtAll()) &&
7781          "omp teams distribute simd loop exprs were not built");
7782 
7783   if (!CurContext->isDependentContext()) {
7784     // Finalize the clauses that need pre-built expressions for CodeGen.
7785     for (OMPClause *C : Clauses) {
7786       if (auto *LC = dyn_cast<OMPLinearClause>(C))
7787         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7788                                      B.NumIterations, *this, CurScope,
7789                                      DSAStack))
7790           return StmtError();
7791     }
7792   }
7793 
7794   if (checkSimdlenSafelenSpecified(*this, Clauses))
7795     return StmtError();
7796 
7797   setFunctionHasBranchProtectedScope();
7798 
7799   DSAStack->setParentTeamsRegionLoc(StartLoc);
7800 
7801   return OMPTeamsDistributeSimdDirective::Create(
7802       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7803 }
7804 
7805 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
7806     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7807     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
7808   if (!AStmt)
7809     return StmtError();
7810 
7811   auto *CS = cast<CapturedStmt>(AStmt);
7812   // 1.2.2 OpenMP Language Terminology
7813   // Structured block - An executable statement with a single entry at the
7814   // top and a single exit at the bottom.
7815   // The point of exit cannot be a branch out of the structured block.
7816   // longjmp() and throw() must not violate the entry/exit criteria.
7817   CS->getCapturedDecl()->setNothrow();
7818 
7819   for (int ThisCaptureLevel =
7820            getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for_simd);
7821        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7822     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7823     // 1.2.2 OpenMP Language Terminology
7824     // Structured block - An executable statement with a single entry at the
7825     // top and a single exit at the bottom.
7826     // The point of exit cannot be a branch out of the structured block.
7827     // longjmp() and throw() must not violate the entry/exit criteria.
7828     CS->getCapturedDecl()->setNothrow();
7829   }
7830 
7831   OMPLoopDirective::HelperExprs B;
7832   // In presence of clause 'collapse' with number of loops, it will
7833   // define the nested loops number.
7834   unsigned NestedLoopCount = checkOpenMPLoop(
7835       OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
7836       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
7837       VarsWithImplicitDSA, B);
7838 
7839   if (NestedLoopCount == 0)
7840     return StmtError();
7841 
7842   assert((CurContext->isDependentContext() || B.builtAll()) &&
7843          "omp for loop exprs were not built");
7844 
7845   if (!CurContext->isDependentContext()) {
7846     // Finalize the clauses that need pre-built expressions for CodeGen.
7847     for (OMPClause *C : Clauses) {
7848       if (auto *LC = dyn_cast<OMPLinearClause>(C))
7849         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7850                                      B.NumIterations, *this, CurScope,
7851                                      DSAStack))
7852           return StmtError();
7853     }
7854   }
7855 
7856   if (checkSimdlenSafelenSpecified(*this, Clauses))
7857     return StmtError();
7858 
7859   setFunctionHasBranchProtectedScope();
7860 
7861   DSAStack->setParentTeamsRegionLoc(StartLoc);
7862 
7863   return OMPTeamsDistributeParallelForSimdDirective::Create(
7864       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7865 }
7866 
7867 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
7868     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7869     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
7870   if (!AStmt)
7871     return StmtError();
7872 
7873   auto *CS = cast<CapturedStmt>(AStmt);
7874   // 1.2.2 OpenMP Language Terminology
7875   // Structured block - An executable statement with a single entry at the
7876   // top and a single exit at the bottom.
7877   // The point of exit cannot be a branch out of the structured block.
7878   // longjmp() and throw() must not violate the entry/exit criteria.
7879   CS->getCapturedDecl()->setNothrow();
7880 
7881   for (int ThisCaptureLevel =
7882            getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for);
7883        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7884     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7885     // 1.2.2 OpenMP Language Terminology
7886     // Structured block - An executable statement with a single entry at the
7887     // top and a single exit at the bottom.
7888     // The point of exit cannot be a branch out of the structured block.
7889     // longjmp() and throw() must not violate the entry/exit criteria.
7890     CS->getCapturedDecl()->setNothrow();
7891   }
7892 
7893   OMPLoopDirective::HelperExprs B;
7894   // In presence of clause 'collapse' with number of loops, it will
7895   // define the nested loops number.
7896   unsigned NestedLoopCount = checkOpenMPLoop(
7897       OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
7898       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
7899       VarsWithImplicitDSA, B);
7900 
7901   if (NestedLoopCount == 0)
7902     return StmtError();
7903 
7904   assert((CurContext->isDependentContext() || B.builtAll()) &&
7905          "omp for loop exprs were not built");
7906 
7907   setFunctionHasBranchProtectedScope();
7908 
7909   DSAStack->setParentTeamsRegionLoc(StartLoc);
7910 
7911   return OMPTeamsDistributeParallelForDirective::Create(
7912       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
7913       DSAStack->isCancelRegion());
7914 }
7915 
7916 StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
7917                                                  Stmt *AStmt,
7918                                                  SourceLocation StartLoc,
7919                                                  SourceLocation EndLoc) {
7920   if (!AStmt)
7921     return StmtError();
7922 
7923   auto *CS = cast<CapturedStmt>(AStmt);
7924   // 1.2.2 OpenMP Language Terminology
7925   // Structured block - An executable statement with a single entry at the
7926   // top and a single exit at the bottom.
7927   // The point of exit cannot be a branch out of the structured block.
7928   // longjmp() and throw() must not violate the entry/exit criteria.
7929   CS->getCapturedDecl()->setNothrow();
7930 
7931   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams);
7932        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7933     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7934     // 1.2.2 OpenMP Language Terminology
7935     // Structured block - An executable statement with a single entry at the
7936     // top and a single exit at the bottom.
7937     // The point of exit cannot be a branch out of the structured block.
7938     // longjmp() and throw() must not violate the entry/exit criteria.
7939     CS->getCapturedDecl()->setNothrow();
7940   }
7941   setFunctionHasBranchProtectedScope();
7942 
7943   return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
7944                                          AStmt);
7945 }
7946 
7947 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
7948     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7949     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
7950   if (!AStmt)
7951     return StmtError();
7952 
7953   auto *CS = cast<CapturedStmt>(AStmt);
7954   // 1.2.2 OpenMP Language Terminology
7955   // Structured block - An executable statement with a single entry at the
7956   // top and a single exit at the bottom.
7957   // The point of exit cannot be a branch out of the structured block.
7958   // longjmp() and throw() must not violate the entry/exit criteria.
7959   CS->getCapturedDecl()->setNothrow();
7960   for (int ThisCaptureLevel =
7961            getOpenMPCaptureLevels(OMPD_target_teams_distribute);
7962        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7963     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7964     // 1.2.2 OpenMP Language Terminology
7965     // Structured block - An executable statement with a single entry at the
7966     // top and a single exit at the bottom.
7967     // The point of exit cannot be a branch out of the structured block.
7968     // longjmp() and throw() must not violate the entry/exit criteria.
7969     CS->getCapturedDecl()->setNothrow();
7970   }
7971 
7972   OMPLoopDirective::HelperExprs B;
7973   // In presence of clause 'collapse' with number of loops, it will
7974   // define the nested loops number.
7975   unsigned NestedLoopCount = checkOpenMPLoop(
7976       OMPD_target_teams_distribute, getCollapseNumberExpr(Clauses),
7977       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
7978       VarsWithImplicitDSA, B);
7979   if (NestedLoopCount == 0)
7980     return StmtError();
7981 
7982   assert((CurContext->isDependentContext() || B.builtAll()) &&
7983          "omp target teams distribute loop exprs were not built");
7984 
7985   setFunctionHasBranchProtectedScope();
7986   return OMPTargetTeamsDistributeDirective::Create(
7987       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7988 }
7989 
7990 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
7991     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7992     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
7993   if (!AStmt)
7994     return StmtError();
7995 
7996   auto *CS = cast<CapturedStmt>(AStmt);
7997   // 1.2.2 OpenMP Language Terminology
7998   // Structured block - An executable statement with a single entry at the
7999   // top and a single exit at the bottom.
8000   // The point of exit cannot be a branch out of the structured block.
8001   // longjmp() and throw() must not violate the entry/exit criteria.
8002   CS->getCapturedDecl()->setNothrow();
8003   for (int ThisCaptureLevel =
8004            getOpenMPCaptureLevels(OMPD_target_teams_distribute_parallel_for);
8005        ThisCaptureLevel > 1; --ThisCaptureLevel) {
8006     CS = cast<CapturedStmt>(CS->getCapturedStmt());
8007     // 1.2.2 OpenMP Language Terminology
8008     // Structured block - An executable statement with a single entry at the
8009     // top and a single exit at the bottom.
8010     // The point of exit cannot be a branch out of the structured block.
8011     // longjmp() and throw() must not violate the entry/exit criteria.
8012     CS->getCapturedDecl()->setNothrow();
8013   }
8014 
8015   OMPLoopDirective::HelperExprs B;
8016   // In presence of clause 'collapse' with number of loops, it will
8017   // define the nested loops number.
8018   unsigned NestedLoopCount = checkOpenMPLoop(
8019       OMPD_target_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
8020       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
8021       VarsWithImplicitDSA, B);
8022   if (NestedLoopCount == 0)
8023     return StmtError();
8024 
8025   assert((CurContext->isDependentContext() || B.builtAll()) &&
8026          "omp target teams distribute parallel for loop exprs were not built");
8027 
8028   if (!CurContext->isDependentContext()) {
8029     // Finalize the clauses that need pre-built expressions for CodeGen.
8030     for (OMPClause *C : Clauses) {
8031       if (auto *LC = dyn_cast<OMPLinearClause>(C))
8032         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8033                                      B.NumIterations, *this, CurScope,
8034                                      DSAStack))
8035           return StmtError();
8036     }
8037   }
8038 
8039   setFunctionHasBranchProtectedScope();
8040   return OMPTargetTeamsDistributeParallelForDirective::Create(
8041       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
8042       DSAStack->isCancelRegion());
8043 }
8044 
8045 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
8046     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8047     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
8048   if (!AStmt)
8049     return StmtError();
8050 
8051   auto *CS = cast<CapturedStmt>(AStmt);
8052   // 1.2.2 OpenMP Language Terminology
8053   // Structured block - An executable statement with a single entry at the
8054   // top and a single exit at the bottom.
8055   // The point of exit cannot be a branch out of the structured block.
8056   // longjmp() and throw() must not violate the entry/exit criteria.
8057   CS->getCapturedDecl()->setNothrow();
8058   for (int ThisCaptureLevel = getOpenMPCaptureLevels(
8059            OMPD_target_teams_distribute_parallel_for_simd);
8060        ThisCaptureLevel > 1; --ThisCaptureLevel) {
8061     CS = cast<CapturedStmt>(CS->getCapturedStmt());
8062     // 1.2.2 OpenMP Language Terminology
8063     // Structured block - An executable statement with a single entry at the
8064     // top and a single exit at the bottom.
8065     // The point of exit cannot be a branch out of the structured block.
8066     // longjmp() and throw() must not violate the entry/exit criteria.
8067     CS->getCapturedDecl()->setNothrow();
8068   }
8069 
8070   OMPLoopDirective::HelperExprs B;
8071   // In presence of clause 'collapse' with number of loops, it will
8072   // define the nested loops number.
8073   unsigned NestedLoopCount =
8074       checkOpenMPLoop(OMPD_target_teams_distribute_parallel_for_simd,
8075                       getCollapseNumberExpr(Clauses),
8076                       nullptr /*ordered not a clause on distribute*/, CS, *this,
8077                       *DSAStack, VarsWithImplicitDSA, B);
8078   if (NestedLoopCount == 0)
8079     return StmtError();
8080 
8081   assert((CurContext->isDependentContext() || B.builtAll()) &&
8082          "omp target teams distribute parallel for simd loop exprs were not "
8083          "built");
8084 
8085   if (!CurContext->isDependentContext()) {
8086     // Finalize the clauses that need pre-built expressions for CodeGen.
8087     for (OMPClause *C : Clauses) {
8088       if (auto *LC = dyn_cast<OMPLinearClause>(C))
8089         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8090                                      B.NumIterations, *this, CurScope,
8091                                      DSAStack))
8092           return StmtError();
8093     }
8094   }
8095 
8096   if (checkSimdlenSafelenSpecified(*this, Clauses))
8097     return StmtError();
8098 
8099   setFunctionHasBranchProtectedScope();
8100   return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
8101       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8102 }
8103 
8104 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
8105     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8106     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
8107   if (!AStmt)
8108     return StmtError();
8109 
8110   auto *CS = cast<CapturedStmt>(AStmt);
8111   // 1.2.2 OpenMP Language Terminology
8112   // Structured block - An executable statement with a single entry at the
8113   // top and a single exit at the bottom.
8114   // The point of exit cannot be a branch out of the structured block.
8115   // longjmp() and throw() must not violate the entry/exit criteria.
8116   CS->getCapturedDecl()->setNothrow();
8117   for (int ThisCaptureLevel =
8118            getOpenMPCaptureLevels(OMPD_target_teams_distribute_simd);
8119        ThisCaptureLevel > 1; --ThisCaptureLevel) {
8120     CS = cast<CapturedStmt>(CS->getCapturedStmt());
8121     // 1.2.2 OpenMP Language Terminology
8122     // Structured block - An executable statement with a single entry at the
8123     // top and a single exit at the bottom.
8124     // The point of exit cannot be a branch out of the structured block.
8125     // longjmp() and throw() must not violate the entry/exit criteria.
8126     CS->getCapturedDecl()->setNothrow();
8127   }
8128 
8129   OMPLoopDirective::HelperExprs B;
8130   // In presence of clause 'collapse' with number of loops, it will
8131   // define the nested loops number.
8132   unsigned NestedLoopCount = checkOpenMPLoop(
8133       OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
8134       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
8135       VarsWithImplicitDSA, B);
8136   if (NestedLoopCount == 0)
8137     return StmtError();
8138 
8139   assert((CurContext->isDependentContext() || B.builtAll()) &&
8140          "omp target teams distribute simd loop exprs were not built");
8141 
8142   if (!CurContext->isDependentContext()) {
8143     // Finalize the clauses that need pre-built expressions for CodeGen.
8144     for (OMPClause *C : Clauses) {
8145       if (auto *LC = dyn_cast<OMPLinearClause>(C))
8146         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8147                                      B.NumIterations, *this, CurScope,
8148                                      DSAStack))
8149           return StmtError();
8150     }
8151   }
8152 
8153   if (checkSimdlenSafelenSpecified(*this, Clauses))
8154     return StmtError();
8155 
8156   setFunctionHasBranchProtectedScope();
8157   return OMPTargetTeamsDistributeSimdDirective::Create(
8158       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8159 }
8160 
8161 OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
8162                                              SourceLocation StartLoc,
8163                                              SourceLocation LParenLoc,
8164                                              SourceLocation EndLoc) {
8165   OMPClause *Res = nullptr;
8166   switch (Kind) {
8167   case OMPC_final:
8168     Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
8169     break;
8170   case OMPC_num_threads:
8171     Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
8172     break;
8173   case OMPC_safelen:
8174     Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
8175     break;
8176   case OMPC_simdlen:
8177     Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
8178     break;
8179   case OMPC_collapse:
8180     Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
8181     break;
8182   case OMPC_ordered:
8183     Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
8184     break;
8185   case OMPC_device:
8186     Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
8187     break;
8188   case OMPC_num_teams:
8189     Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
8190     break;
8191   case OMPC_thread_limit:
8192     Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
8193     break;
8194   case OMPC_priority:
8195     Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
8196     break;
8197   case OMPC_grainsize:
8198     Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
8199     break;
8200   case OMPC_num_tasks:
8201     Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
8202     break;
8203   case OMPC_hint:
8204     Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
8205     break;
8206   case OMPC_if:
8207   case OMPC_default:
8208   case OMPC_proc_bind:
8209   case OMPC_schedule:
8210   case OMPC_private:
8211   case OMPC_firstprivate:
8212   case OMPC_lastprivate:
8213   case OMPC_shared:
8214   case OMPC_reduction:
8215   case OMPC_task_reduction:
8216   case OMPC_in_reduction:
8217   case OMPC_linear:
8218   case OMPC_aligned:
8219   case OMPC_copyin:
8220   case OMPC_copyprivate:
8221   case OMPC_nowait:
8222   case OMPC_untied:
8223   case OMPC_mergeable:
8224   case OMPC_threadprivate:
8225   case OMPC_flush:
8226   case OMPC_read:
8227   case OMPC_write:
8228   case OMPC_update:
8229   case OMPC_capture:
8230   case OMPC_seq_cst:
8231   case OMPC_depend:
8232   case OMPC_threads:
8233   case OMPC_simd:
8234   case OMPC_map:
8235   case OMPC_nogroup:
8236   case OMPC_dist_schedule:
8237   case OMPC_defaultmap:
8238   case OMPC_unknown:
8239   case OMPC_uniform:
8240   case OMPC_to:
8241   case OMPC_from:
8242   case OMPC_use_device_ptr:
8243   case OMPC_is_device_ptr:
8244   case OMPC_unified_address:
8245   case OMPC_unified_shared_memory:
8246   case OMPC_reverse_offload:
8247   case OMPC_dynamic_allocators:
8248   case OMPC_atomic_default_mem_order:
8249     llvm_unreachable("Clause is not allowed.");
8250   }
8251   return Res;
8252 }
8253 
8254 // An OpenMP directive such as 'target parallel' has two captured regions:
8255 // for the 'target' and 'parallel' respectively.  This function returns
8256 // the region in which to capture expressions associated with a clause.
8257 // A return value of OMPD_unknown signifies that the expression should not
8258 // be captured.
8259 static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
8260     OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
8261     OpenMPDirectiveKind NameModifier = OMPD_unknown) {
8262   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
8263   switch (CKind) {
8264   case OMPC_if:
8265     switch (DKind) {
8266     case OMPD_target_parallel:
8267     case OMPD_target_parallel_for:
8268     case OMPD_target_parallel_for_simd:
8269       // If this clause applies to the nested 'parallel' region, capture within
8270       // the 'target' region, otherwise do not capture.
8271       if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
8272         CaptureRegion = OMPD_target;
8273       break;
8274     case OMPD_target_teams_distribute_parallel_for:
8275     case OMPD_target_teams_distribute_parallel_for_simd:
8276       // If this clause applies to the nested 'parallel' region, capture within
8277       // the 'teams' region, otherwise do not capture.
8278       if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
8279         CaptureRegion = OMPD_teams;
8280       break;
8281     case OMPD_teams_distribute_parallel_for:
8282     case OMPD_teams_distribute_parallel_for_simd:
8283       CaptureRegion = OMPD_teams;
8284       break;
8285     case OMPD_target_update:
8286     case OMPD_target_enter_data:
8287     case OMPD_target_exit_data:
8288       CaptureRegion = OMPD_task;
8289       break;
8290     case OMPD_cancel:
8291     case OMPD_parallel:
8292     case OMPD_parallel_sections:
8293     case OMPD_parallel_for:
8294     case OMPD_parallel_for_simd:
8295     case OMPD_target:
8296     case OMPD_target_simd:
8297     case OMPD_target_teams:
8298     case OMPD_target_teams_distribute:
8299     case OMPD_target_teams_distribute_simd:
8300     case OMPD_distribute_parallel_for:
8301     case OMPD_distribute_parallel_for_simd:
8302     case OMPD_task:
8303     case OMPD_taskloop:
8304     case OMPD_taskloop_simd:
8305     case OMPD_target_data:
8306       // Do not capture if-clause expressions.
8307       break;
8308     case OMPD_threadprivate:
8309     case OMPD_taskyield:
8310     case OMPD_barrier:
8311     case OMPD_taskwait:
8312     case OMPD_cancellation_point:
8313     case OMPD_flush:
8314     case OMPD_declare_reduction:
8315     case OMPD_declare_simd:
8316     case OMPD_declare_target:
8317     case OMPD_end_declare_target:
8318     case OMPD_teams:
8319     case OMPD_simd:
8320     case OMPD_for:
8321     case OMPD_for_simd:
8322     case OMPD_sections:
8323     case OMPD_section:
8324     case OMPD_single:
8325     case OMPD_master:
8326     case OMPD_critical:
8327     case OMPD_taskgroup:
8328     case OMPD_distribute:
8329     case OMPD_ordered:
8330     case OMPD_atomic:
8331     case OMPD_distribute_simd:
8332     case OMPD_teams_distribute:
8333     case OMPD_teams_distribute_simd:
8334     case OMPD_requires:
8335       llvm_unreachable("Unexpected OpenMP directive with if-clause");
8336     case OMPD_unknown:
8337       llvm_unreachable("Unknown OpenMP directive");
8338     }
8339     break;
8340   case OMPC_num_threads:
8341     switch (DKind) {
8342     case OMPD_target_parallel:
8343     case OMPD_target_parallel_for:
8344     case OMPD_target_parallel_for_simd:
8345       CaptureRegion = OMPD_target;
8346       break;
8347     case OMPD_teams_distribute_parallel_for:
8348     case OMPD_teams_distribute_parallel_for_simd:
8349     case OMPD_target_teams_distribute_parallel_for:
8350     case OMPD_target_teams_distribute_parallel_for_simd:
8351       CaptureRegion = OMPD_teams;
8352       break;
8353     case OMPD_parallel:
8354     case OMPD_parallel_sections:
8355     case OMPD_parallel_for:
8356     case OMPD_parallel_for_simd:
8357     case OMPD_distribute_parallel_for:
8358     case OMPD_distribute_parallel_for_simd:
8359       // Do not capture num_threads-clause expressions.
8360       break;
8361     case OMPD_target_data:
8362     case OMPD_target_enter_data:
8363     case OMPD_target_exit_data:
8364     case OMPD_target_update:
8365     case OMPD_target:
8366     case OMPD_target_simd:
8367     case OMPD_target_teams:
8368     case OMPD_target_teams_distribute:
8369     case OMPD_target_teams_distribute_simd:
8370     case OMPD_cancel:
8371     case OMPD_task:
8372     case OMPD_taskloop:
8373     case OMPD_taskloop_simd:
8374     case OMPD_threadprivate:
8375     case OMPD_taskyield:
8376     case OMPD_barrier:
8377     case OMPD_taskwait:
8378     case OMPD_cancellation_point:
8379     case OMPD_flush:
8380     case OMPD_declare_reduction:
8381     case OMPD_declare_simd:
8382     case OMPD_declare_target:
8383     case OMPD_end_declare_target:
8384     case OMPD_teams:
8385     case OMPD_simd:
8386     case OMPD_for:
8387     case OMPD_for_simd:
8388     case OMPD_sections:
8389     case OMPD_section:
8390     case OMPD_single:
8391     case OMPD_master:
8392     case OMPD_critical:
8393     case OMPD_taskgroup:
8394     case OMPD_distribute:
8395     case OMPD_ordered:
8396     case OMPD_atomic:
8397     case OMPD_distribute_simd:
8398     case OMPD_teams_distribute:
8399     case OMPD_teams_distribute_simd:
8400     case OMPD_requires:
8401       llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
8402     case OMPD_unknown:
8403       llvm_unreachable("Unknown OpenMP directive");
8404     }
8405     break;
8406   case OMPC_num_teams:
8407     switch (DKind) {
8408     case OMPD_target_teams:
8409     case OMPD_target_teams_distribute:
8410     case OMPD_target_teams_distribute_simd:
8411     case OMPD_target_teams_distribute_parallel_for:
8412     case OMPD_target_teams_distribute_parallel_for_simd:
8413       CaptureRegion = OMPD_target;
8414       break;
8415     case OMPD_teams_distribute_parallel_for:
8416     case OMPD_teams_distribute_parallel_for_simd:
8417     case OMPD_teams:
8418     case OMPD_teams_distribute:
8419     case OMPD_teams_distribute_simd:
8420       // Do not capture num_teams-clause expressions.
8421       break;
8422     case OMPD_distribute_parallel_for:
8423     case OMPD_distribute_parallel_for_simd:
8424     case OMPD_task:
8425     case OMPD_taskloop:
8426     case OMPD_taskloop_simd:
8427     case OMPD_target_data:
8428     case OMPD_target_enter_data:
8429     case OMPD_target_exit_data:
8430     case OMPD_target_update:
8431     case OMPD_cancel:
8432     case OMPD_parallel:
8433     case OMPD_parallel_sections:
8434     case OMPD_parallel_for:
8435     case OMPD_parallel_for_simd:
8436     case OMPD_target:
8437     case OMPD_target_simd:
8438     case OMPD_target_parallel:
8439     case OMPD_target_parallel_for:
8440     case OMPD_target_parallel_for_simd:
8441     case OMPD_threadprivate:
8442     case OMPD_taskyield:
8443     case OMPD_barrier:
8444     case OMPD_taskwait:
8445     case OMPD_cancellation_point:
8446     case OMPD_flush:
8447     case OMPD_declare_reduction:
8448     case OMPD_declare_simd:
8449     case OMPD_declare_target:
8450     case OMPD_end_declare_target:
8451     case OMPD_simd:
8452     case OMPD_for:
8453     case OMPD_for_simd:
8454     case OMPD_sections:
8455     case OMPD_section:
8456     case OMPD_single:
8457     case OMPD_master:
8458     case OMPD_critical:
8459     case OMPD_taskgroup:
8460     case OMPD_distribute:
8461     case OMPD_ordered:
8462     case OMPD_atomic:
8463     case OMPD_distribute_simd:
8464     case OMPD_requires:
8465       llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
8466     case OMPD_unknown:
8467       llvm_unreachable("Unknown OpenMP directive");
8468     }
8469     break;
8470   case OMPC_thread_limit:
8471     switch (DKind) {
8472     case OMPD_target_teams:
8473     case OMPD_target_teams_distribute:
8474     case OMPD_target_teams_distribute_simd:
8475     case OMPD_target_teams_distribute_parallel_for:
8476     case OMPD_target_teams_distribute_parallel_for_simd:
8477       CaptureRegion = OMPD_target;
8478       break;
8479     case OMPD_teams_distribute_parallel_for:
8480     case OMPD_teams_distribute_parallel_for_simd:
8481     case OMPD_teams:
8482     case OMPD_teams_distribute:
8483     case OMPD_teams_distribute_simd:
8484       // Do not capture thread_limit-clause expressions.
8485       break;
8486     case OMPD_distribute_parallel_for:
8487     case OMPD_distribute_parallel_for_simd:
8488     case OMPD_task:
8489     case OMPD_taskloop:
8490     case OMPD_taskloop_simd:
8491     case OMPD_target_data:
8492     case OMPD_target_enter_data:
8493     case OMPD_target_exit_data:
8494     case OMPD_target_update:
8495     case OMPD_cancel:
8496     case OMPD_parallel:
8497     case OMPD_parallel_sections:
8498     case OMPD_parallel_for:
8499     case OMPD_parallel_for_simd:
8500     case OMPD_target:
8501     case OMPD_target_simd:
8502     case OMPD_target_parallel:
8503     case OMPD_target_parallel_for:
8504     case OMPD_target_parallel_for_simd:
8505     case OMPD_threadprivate:
8506     case OMPD_taskyield:
8507     case OMPD_barrier:
8508     case OMPD_taskwait:
8509     case OMPD_cancellation_point:
8510     case OMPD_flush:
8511     case OMPD_declare_reduction:
8512     case OMPD_declare_simd:
8513     case OMPD_declare_target:
8514     case OMPD_end_declare_target:
8515     case OMPD_simd:
8516     case OMPD_for:
8517     case OMPD_for_simd:
8518     case OMPD_sections:
8519     case OMPD_section:
8520     case OMPD_single:
8521     case OMPD_master:
8522     case OMPD_critical:
8523     case OMPD_taskgroup:
8524     case OMPD_distribute:
8525     case OMPD_ordered:
8526     case OMPD_atomic:
8527     case OMPD_distribute_simd:
8528     case OMPD_requires:
8529       llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
8530     case OMPD_unknown:
8531       llvm_unreachable("Unknown OpenMP directive");
8532     }
8533     break;
8534   case OMPC_schedule:
8535     switch (DKind) {
8536     case OMPD_parallel_for:
8537     case OMPD_parallel_for_simd:
8538     case OMPD_distribute_parallel_for:
8539     case OMPD_distribute_parallel_for_simd:
8540     case OMPD_teams_distribute_parallel_for:
8541     case OMPD_teams_distribute_parallel_for_simd:
8542     case OMPD_target_parallel_for:
8543     case OMPD_target_parallel_for_simd:
8544     case OMPD_target_teams_distribute_parallel_for:
8545     case OMPD_target_teams_distribute_parallel_for_simd:
8546       CaptureRegion = OMPD_parallel;
8547       break;
8548     case OMPD_for:
8549     case OMPD_for_simd:
8550       // Do not capture schedule-clause expressions.
8551       break;
8552     case OMPD_task:
8553     case OMPD_taskloop:
8554     case OMPD_taskloop_simd:
8555     case OMPD_target_data:
8556     case OMPD_target_enter_data:
8557     case OMPD_target_exit_data:
8558     case OMPD_target_update:
8559     case OMPD_teams:
8560     case OMPD_teams_distribute:
8561     case OMPD_teams_distribute_simd:
8562     case OMPD_target_teams_distribute:
8563     case OMPD_target_teams_distribute_simd:
8564     case OMPD_target:
8565     case OMPD_target_simd:
8566     case OMPD_target_parallel:
8567     case OMPD_cancel:
8568     case OMPD_parallel:
8569     case OMPD_parallel_sections:
8570     case OMPD_threadprivate:
8571     case OMPD_taskyield:
8572     case OMPD_barrier:
8573     case OMPD_taskwait:
8574     case OMPD_cancellation_point:
8575     case OMPD_flush:
8576     case OMPD_declare_reduction:
8577     case OMPD_declare_simd:
8578     case OMPD_declare_target:
8579     case OMPD_end_declare_target:
8580     case OMPD_simd:
8581     case OMPD_sections:
8582     case OMPD_section:
8583     case OMPD_single:
8584     case OMPD_master:
8585     case OMPD_critical:
8586     case OMPD_taskgroup:
8587     case OMPD_distribute:
8588     case OMPD_ordered:
8589     case OMPD_atomic:
8590     case OMPD_distribute_simd:
8591     case OMPD_target_teams:
8592     case OMPD_requires:
8593       llvm_unreachable("Unexpected OpenMP directive with schedule clause");
8594     case OMPD_unknown:
8595       llvm_unreachable("Unknown OpenMP directive");
8596     }
8597     break;
8598   case OMPC_dist_schedule:
8599     switch (DKind) {
8600     case OMPD_teams_distribute_parallel_for:
8601     case OMPD_teams_distribute_parallel_for_simd:
8602     case OMPD_teams_distribute:
8603     case OMPD_teams_distribute_simd:
8604     case OMPD_target_teams_distribute_parallel_for:
8605     case OMPD_target_teams_distribute_parallel_for_simd:
8606     case OMPD_target_teams_distribute:
8607     case OMPD_target_teams_distribute_simd:
8608       CaptureRegion = OMPD_teams;
8609       break;
8610     case OMPD_distribute_parallel_for:
8611     case OMPD_distribute_parallel_for_simd:
8612     case OMPD_distribute:
8613     case OMPD_distribute_simd:
8614       // Do not capture thread_limit-clause expressions.
8615       break;
8616     case OMPD_parallel_for:
8617     case OMPD_parallel_for_simd:
8618     case OMPD_target_parallel_for_simd:
8619     case OMPD_target_parallel_for:
8620     case OMPD_task:
8621     case OMPD_taskloop:
8622     case OMPD_taskloop_simd:
8623     case OMPD_target_data:
8624     case OMPD_target_enter_data:
8625     case OMPD_target_exit_data:
8626     case OMPD_target_update:
8627     case OMPD_teams:
8628     case OMPD_target:
8629     case OMPD_target_simd:
8630     case OMPD_target_parallel:
8631     case OMPD_cancel:
8632     case OMPD_parallel:
8633     case OMPD_parallel_sections:
8634     case OMPD_threadprivate:
8635     case OMPD_taskyield:
8636     case OMPD_barrier:
8637     case OMPD_taskwait:
8638     case OMPD_cancellation_point:
8639     case OMPD_flush:
8640     case OMPD_declare_reduction:
8641     case OMPD_declare_simd:
8642     case OMPD_declare_target:
8643     case OMPD_end_declare_target:
8644     case OMPD_simd:
8645     case OMPD_for:
8646     case OMPD_for_simd:
8647     case OMPD_sections:
8648     case OMPD_section:
8649     case OMPD_single:
8650     case OMPD_master:
8651     case OMPD_critical:
8652     case OMPD_taskgroup:
8653     case OMPD_ordered:
8654     case OMPD_atomic:
8655     case OMPD_target_teams:
8656     case OMPD_requires:
8657       llvm_unreachable("Unexpected OpenMP directive with schedule clause");
8658     case OMPD_unknown:
8659       llvm_unreachable("Unknown OpenMP directive");
8660     }
8661     break;
8662   case OMPC_device:
8663     switch (DKind) {
8664     case OMPD_target_update:
8665     case OMPD_target_enter_data:
8666     case OMPD_target_exit_data:
8667     case OMPD_target:
8668     case OMPD_target_simd:
8669     case OMPD_target_teams:
8670     case OMPD_target_parallel:
8671     case OMPD_target_teams_distribute:
8672     case OMPD_target_teams_distribute_simd:
8673     case OMPD_target_parallel_for:
8674     case OMPD_target_parallel_for_simd:
8675     case OMPD_target_teams_distribute_parallel_for:
8676     case OMPD_target_teams_distribute_parallel_for_simd:
8677       CaptureRegion = OMPD_task;
8678       break;
8679     case OMPD_target_data:
8680       // Do not capture device-clause expressions.
8681       break;
8682     case OMPD_teams_distribute_parallel_for:
8683     case OMPD_teams_distribute_parallel_for_simd:
8684     case OMPD_teams:
8685     case OMPD_teams_distribute:
8686     case OMPD_teams_distribute_simd:
8687     case OMPD_distribute_parallel_for:
8688     case OMPD_distribute_parallel_for_simd:
8689     case OMPD_task:
8690     case OMPD_taskloop:
8691     case OMPD_taskloop_simd:
8692     case OMPD_cancel:
8693     case OMPD_parallel:
8694     case OMPD_parallel_sections:
8695     case OMPD_parallel_for:
8696     case OMPD_parallel_for_simd:
8697     case OMPD_threadprivate:
8698     case OMPD_taskyield:
8699     case OMPD_barrier:
8700     case OMPD_taskwait:
8701     case OMPD_cancellation_point:
8702     case OMPD_flush:
8703     case OMPD_declare_reduction:
8704     case OMPD_declare_simd:
8705     case OMPD_declare_target:
8706     case OMPD_end_declare_target:
8707     case OMPD_simd:
8708     case OMPD_for:
8709     case OMPD_for_simd:
8710     case OMPD_sections:
8711     case OMPD_section:
8712     case OMPD_single:
8713     case OMPD_master:
8714     case OMPD_critical:
8715     case OMPD_taskgroup:
8716     case OMPD_distribute:
8717     case OMPD_ordered:
8718     case OMPD_atomic:
8719     case OMPD_distribute_simd:
8720     case OMPD_requires:
8721       llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
8722     case OMPD_unknown:
8723       llvm_unreachable("Unknown OpenMP directive");
8724     }
8725     break;
8726   case OMPC_firstprivate:
8727   case OMPC_lastprivate:
8728   case OMPC_reduction:
8729   case OMPC_task_reduction:
8730   case OMPC_in_reduction:
8731   case OMPC_linear:
8732   case OMPC_default:
8733   case OMPC_proc_bind:
8734   case OMPC_final:
8735   case OMPC_safelen:
8736   case OMPC_simdlen:
8737   case OMPC_collapse:
8738   case OMPC_private:
8739   case OMPC_shared:
8740   case OMPC_aligned:
8741   case OMPC_copyin:
8742   case OMPC_copyprivate:
8743   case OMPC_ordered:
8744   case OMPC_nowait:
8745   case OMPC_untied:
8746   case OMPC_mergeable:
8747   case OMPC_threadprivate:
8748   case OMPC_flush:
8749   case OMPC_read:
8750   case OMPC_write:
8751   case OMPC_update:
8752   case OMPC_capture:
8753   case OMPC_seq_cst:
8754   case OMPC_depend:
8755   case OMPC_threads:
8756   case OMPC_simd:
8757   case OMPC_map:
8758   case OMPC_priority:
8759   case OMPC_grainsize:
8760   case OMPC_nogroup:
8761   case OMPC_num_tasks:
8762   case OMPC_hint:
8763   case OMPC_defaultmap:
8764   case OMPC_unknown:
8765   case OMPC_uniform:
8766   case OMPC_to:
8767   case OMPC_from:
8768   case OMPC_use_device_ptr:
8769   case OMPC_is_device_ptr:
8770   case OMPC_unified_address:
8771   case OMPC_unified_shared_memory:
8772   case OMPC_reverse_offload:
8773   case OMPC_dynamic_allocators:
8774   case OMPC_atomic_default_mem_order:
8775     llvm_unreachable("Unexpected OpenMP clause.");
8776   }
8777   return CaptureRegion;
8778 }
8779 
8780 OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
8781                                      Expr *Condition, SourceLocation StartLoc,
8782                                      SourceLocation LParenLoc,
8783                                      SourceLocation NameModifierLoc,
8784                                      SourceLocation ColonLoc,
8785                                      SourceLocation EndLoc) {
8786   Expr *ValExpr = Condition;
8787   Stmt *HelperValStmt = nullptr;
8788   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
8789   if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
8790       !Condition->isInstantiationDependent() &&
8791       !Condition->containsUnexpandedParameterPack()) {
8792     ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
8793     if (Val.isInvalid())
8794       return nullptr;
8795 
8796     ValExpr = Val.get();
8797 
8798     OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
8799     CaptureRegion =
8800         getOpenMPCaptureRegionForClause(DKind, OMPC_if, NameModifier);
8801     if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
8802       ValExpr = MakeFullExpr(ValExpr).get();
8803       llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
8804       ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
8805       HelperValStmt = buildPreInits(Context, Captures);
8806     }
8807   }
8808 
8809   return new (Context)
8810       OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
8811                   LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
8812 }
8813 
8814 OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
8815                                         SourceLocation StartLoc,
8816                                         SourceLocation LParenLoc,
8817                                         SourceLocation EndLoc) {
8818   Expr *ValExpr = Condition;
8819   if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
8820       !Condition->isInstantiationDependent() &&
8821       !Condition->containsUnexpandedParameterPack()) {
8822     ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
8823     if (Val.isInvalid())
8824       return nullptr;
8825 
8826     ValExpr = MakeFullExpr(Val.get()).get();
8827   }
8828 
8829   return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
8830 }
8831 ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
8832                                                         Expr *Op) {
8833   if (!Op)
8834     return ExprError();
8835 
8836   class IntConvertDiagnoser : public ICEConvertDiagnoser {
8837   public:
8838     IntConvertDiagnoser()
8839         : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
8840     SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
8841                                          QualType T) override {
8842       return S.Diag(Loc, diag::err_omp_not_integral) << T;
8843     }
8844     SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
8845                                              QualType T) override {
8846       return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
8847     }
8848     SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
8849                                                QualType T,
8850                                                QualType ConvTy) override {
8851       return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
8852     }
8853     SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
8854                                            QualType ConvTy) override {
8855       return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
8856              << ConvTy->isEnumeralType() << ConvTy;
8857     }
8858     SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
8859                                             QualType T) override {
8860       return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
8861     }
8862     SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
8863                                         QualType ConvTy) override {
8864       return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
8865              << ConvTy->isEnumeralType() << ConvTy;
8866     }
8867     SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
8868                                              QualType) override {
8869       llvm_unreachable("conversion functions are permitted");
8870     }
8871   } ConvertDiagnoser;
8872   return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
8873 }
8874 
8875 static bool isNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
8876                                       OpenMPClauseKind CKind,
8877                                       bool StrictlyPositive) {
8878   if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
8879       !ValExpr->isInstantiationDependent()) {
8880     SourceLocation Loc = ValExpr->getExprLoc();
8881     ExprResult Value =
8882         SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
8883     if (Value.isInvalid())
8884       return false;
8885 
8886     ValExpr = Value.get();
8887     // The expression must evaluate to a non-negative integer value.
8888     llvm::APSInt Result;
8889     if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
8890         Result.isSigned() &&
8891         !((!StrictlyPositive && Result.isNonNegative()) ||
8892           (StrictlyPositive && Result.isStrictlyPositive()))) {
8893       SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
8894           << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
8895           << ValExpr->getSourceRange();
8896       return false;
8897     }
8898   }
8899   return true;
8900 }
8901 
8902 OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
8903                                              SourceLocation StartLoc,
8904                                              SourceLocation LParenLoc,
8905                                              SourceLocation EndLoc) {
8906   Expr *ValExpr = NumThreads;
8907   Stmt *HelperValStmt = nullptr;
8908 
8909   // OpenMP [2.5, Restrictions]
8910   //  The num_threads expression must evaluate to a positive integer value.
8911   if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
8912                                  /*StrictlyPositive=*/true))
8913     return nullptr;
8914 
8915   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
8916   OpenMPDirectiveKind CaptureRegion =
8917       getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads);
8918   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
8919     ValExpr = MakeFullExpr(ValExpr).get();
8920     llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
8921     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
8922     HelperValStmt = buildPreInits(Context, Captures);
8923   }
8924 
8925   return new (Context) OMPNumThreadsClause(
8926       ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
8927 }
8928 
8929 ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
8930                                                        OpenMPClauseKind CKind,
8931                                                        bool StrictlyPositive) {
8932   if (!E)
8933     return ExprError();
8934   if (E->isValueDependent() || E->isTypeDependent() ||
8935       E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
8936     return E;
8937   llvm::APSInt Result;
8938   ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
8939   if (ICE.isInvalid())
8940     return ExprError();
8941   if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
8942       (!StrictlyPositive && !Result.isNonNegative())) {
8943     Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
8944         << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
8945         << E->getSourceRange();
8946     return ExprError();
8947   }
8948   if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
8949     Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
8950         << E->getSourceRange();
8951     return ExprError();
8952   }
8953   if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
8954     DSAStack->setAssociatedLoops(Result.getExtValue());
8955   else if (CKind == OMPC_ordered)
8956     DSAStack->setAssociatedLoops(Result.getExtValue());
8957   return ICE;
8958 }
8959 
8960 OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
8961                                           SourceLocation LParenLoc,
8962                                           SourceLocation EndLoc) {
8963   // OpenMP [2.8.1, simd construct, Description]
8964   // The parameter of the safelen clause must be a constant
8965   // positive integer expression.
8966   ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
8967   if (Safelen.isInvalid())
8968     return nullptr;
8969   return new (Context)
8970       OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
8971 }
8972 
8973 OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
8974                                           SourceLocation LParenLoc,
8975                                           SourceLocation EndLoc) {
8976   // OpenMP [2.8.1, simd construct, Description]
8977   // The parameter of the simdlen clause must be a constant
8978   // positive integer expression.
8979   ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
8980   if (Simdlen.isInvalid())
8981     return nullptr;
8982   return new (Context)
8983       OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
8984 }
8985 
8986 OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
8987                                            SourceLocation StartLoc,
8988                                            SourceLocation LParenLoc,
8989                                            SourceLocation EndLoc) {
8990   // OpenMP [2.7.1, loop construct, Description]
8991   // OpenMP [2.8.1, simd construct, Description]
8992   // OpenMP [2.9.6, distribute construct, Description]
8993   // The parameter of the collapse clause must be a constant
8994   // positive integer expression.
8995   ExprResult NumForLoopsResult =
8996       VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
8997   if (NumForLoopsResult.isInvalid())
8998     return nullptr;
8999   return new (Context)
9000       OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
9001 }
9002 
9003 OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
9004                                           SourceLocation EndLoc,
9005                                           SourceLocation LParenLoc,
9006                                           Expr *NumForLoops) {
9007   // OpenMP [2.7.1, loop construct, Description]
9008   // OpenMP [2.8.1, simd construct, Description]
9009   // OpenMP [2.9.6, distribute construct, Description]
9010   // The parameter of the ordered clause must be a constant
9011   // positive integer expression if any.
9012   if (NumForLoops && LParenLoc.isValid()) {
9013     ExprResult NumForLoopsResult =
9014         VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
9015     if (NumForLoopsResult.isInvalid())
9016       return nullptr;
9017     NumForLoops = NumForLoopsResult.get();
9018   } else {
9019     NumForLoops = nullptr;
9020   }
9021   auto *Clause = OMPOrderedClause::Create(
9022       Context, NumForLoops, NumForLoops ? DSAStack->getAssociatedLoops() : 0,
9023       StartLoc, LParenLoc, EndLoc);
9024   DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops, Clause);
9025   return Clause;
9026 }
9027 
9028 OMPClause *Sema::ActOnOpenMPSimpleClause(
9029     OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
9030     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
9031   OMPClause *Res = nullptr;
9032   switch (Kind) {
9033   case OMPC_default:
9034     Res =
9035         ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
9036                                  ArgumentLoc, StartLoc, LParenLoc, EndLoc);
9037     break;
9038   case OMPC_proc_bind:
9039     Res = ActOnOpenMPProcBindClause(
9040         static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
9041         LParenLoc, EndLoc);
9042     break;
9043   case OMPC_atomic_default_mem_order:
9044     Res = ActOnOpenMPAtomicDefaultMemOrderClause(
9045         static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Argument),
9046         ArgumentLoc, StartLoc, LParenLoc, EndLoc);
9047     break;
9048   case OMPC_if:
9049   case OMPC_final:
9050   case OMPC_num_threads:
9051   case OMPC_safelen:
9052   case OMPC_simdlen:
9053   case OMPC_collapse:
9054   case OMPC_schedule:
9055   case OMPC_private:
9056   case OMPC_firstprivate:
9057   case OMPC_lastprivate:
9058   case OMPC_shared:
9059   case OMPC_reduction:
9060   case OMPC_task_reduction:
9061   case OMPC_in_reduction:
9062   case OMPC_linear:
9063   case OMPC_aligned:
9064   case OMPC_copyin:
9065   case OMPC_copyprivate:
9066   case OMPC_ordered:
9067   case OMPC_nowait:
9068   case OMPC_untied:
9069   case OMPC_mergeable:
9070   case OMPC_threadprivate:
9071   case OMPC_flush:
9072   case OMPC_read:
9073   case OMPC_write:
9074   case OMPC_update:
9075   case OMPC_capture:
9076   case OMPC_seq_cst:
9077   case OMPC_depend:
9078   case OMPC_device:
9079   case OMPC_threads:
9080   case OMPC_simd:
9081   case OMPC_map:
9082   case OMPC_num_teams:
9083   case OMPC_thread_limit:
9084   case OMPC_priority:
9085   case OMPC_grainsize:
9086   case OMPC_nogroup:
9087   case OMPC_num_tasks:
9088   case OMPC_hint:
9089   case OMPC_dist_schedule:
9090   case OMPC_defaultmap:
9091   case OMPC_unknown:
9092   case OMPC_uniform:
9093   case OMPC_to:
9094   case OMPC_from:
9095   case OMPC_use_device_ptr:
9096   case OMPC_is_device_ptr:
9097   case OMPC_unified_address:
9098   case OMPC_unified_shared_memory:
9099   case OMPC_reverse_offload:
9100   case OMPC_dynamic_allocators:
9101     llvm_unreachable("Clause is not allowed.");
9102   }
9103   return Res;
9104 }
9105 
9106 static std::string
9107 getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
9108                         ArrayRef<unsigned> Exclude = llvm::None) {
9109   SmallString<256> Buffer;
9110   llvm::raw_svector_ostream Out(Buffer);
9111   unsigned Bound = Last >= 2 ? Last - 2 : 0;
9112   unsigned Skipped = Exclude.size();
9113   auto S = Exclude.begin(), E = Exclude.end();
9114   for (unsigned I = First; I < Last; ++I) {
9115     if (std::find(S, E, I) != E) {
9116       --Skipped;
9117       continue;
9118     }
9119     Out << "'" << getOpenMPSimpleClauseTypeName(K, I) << "'";
9120     if (I == Bound - Skipped)
9121       Out << " or ";
9122     else if (I != Bound + 1 - Skipped)
9123       Out << ", ";
9124   }
9125   return Out.str();
9126 }
9127 
9128 OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
9129                                           SourceLocation KindKwLoc,
9130                                           SourceLocation StartLoc,
9131                                           SourceLocation LParenLoc,
9132                                           SourceLocation EndLoc) {
9133   if (Kind == OMPC_DEFAULT_unknown) {
9134     static_assert(OMPC_DEFAULT_unknown > 0,
9135                   "OMPC_DEFAULT_unknown not greater than 0");
9136     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
9137         << getListOfPossibleValues(OMPC_default, /*First=*/0,
9138                                    /*Last=*/OMPC_DEFAULT_unknown)
9139         << getOpenMPClauseName(OMPC_default);
9140     return nullptr;
9141   }
9142   switch (Kind) {
9143   case OMPC_DEFAULT_none:
9144     DSAStack->setDefaultDSANone(KindKwLoc);
9145     break;
9146   case OMPC_DEFAULT_shared:
9147     DSAStack->setDefaultDSAShared(KindKwLoc);
9148     break;
9149   case OMPC_DEFAULT_unknown:
9150     llvm_unreachable("Clause kind is not allowed.");
9151     break;
9152   }
9153   return new (Context)
9154       OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
9155 }
9156 
9157 OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
9158                                            SourceLocation KindKwLoc,
9159                                            SourceLocation StartLoc,
9160                                            SourceLocation LParenLoc,
9161                                            SourceLocation EndLoc) {
9162   if (Kind == OMPC_PROC_BIND_unknown) {
9163     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
9164         << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
9165                                    /*Last=*/OMPC_PROC_BIND_unknown)
9166         << getOpenMPClauseName(OMPC_proc_bind);
9167     return nullptr;
9168   }
9169   return new (Context)
9170       OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
9171 }
9172 
9173 OMPClause *Sema::ActOnOpenMPAtomicDefaultMemOrderClause(
9174     OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindKwLoc,
9175     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
9176   if (Kind == OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown) {
9177     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
9178         << getListOfPossibleValues(
9179                OMPC_atomic_default_mem_order, /*First=*/0,
9180                /*Last=*/OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown)
9181         << getOpenMPClauseName(OMPC_atomic_default_mem_order);
9182     return nullptr;
9183   }
9184   return new (Context) OMPAtomicDefaultMemOrderClause(Kind, KindKwLoc, StartLoc,
9185                                                       LParenLoc, EndLoc);
9186 }
9187 
9188 OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
9189     OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
9190     SourceLocation StartLoc, SourceLocation LParenLoc,
9191     ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
9192     SourceLocation EndLoc) {
9193   OMPClause *Res = nullptr;
9194   switch (Kind) {
9195   case OMPC_schedule:
9196     enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
9197     assert(Argument.size() == NumberOfElements &&
9198            ArgumentLoc.size() == NumberOfElements);
9199     Res = ActOnOpenMPScheduleClause(
9200         static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
9201         static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
9202         static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
9203         StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
9204         ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
9205     break;
9206   case OMPC_if:
9207     assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
9208     Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
9209                               Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
9210                               DelimLoc, EndLoc);
9211     break;
9212   case OMPC_dist_schedule:
9213     Res = ActOnOpenMPDistScheduleClause(
9214         static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
9215         StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
9216     break;
9217   case OMPC_defaultmap:
9218     enum { Modifier, DefaultmapKind };
9219     Res = ActOnOpenMPDefaultmapClause(
9220         static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
9221         static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
9222         StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
9223         EndLoc);
9224     break;
9225   case OMPC_final:
9226   case OMPC_num_threads:
9227   case OMPC_safelen:
9228   case OMPC_simdlen:
9229   case OMPC_collapse:
9230   case OMPC_default:
9231   case OMPC_proc_bind:
9232   case OMPC_private:
9233   case OMPC_firstprivate:
9234   case OMPC_lastprivate:
9235   case OMPC_shared:
9236   case OMPC_reduction:
9237   case OMPC_task_reduction:
9238   case OMPC_in_reduction:
9239   case OMPC_linear:
9240   case OMPC_aligned:
9241   case OMPC_copyin:
9242   case OMPC_copyprivate:
9243   case OMPC_ordered:
9244   case OMPC_nowait:
9245   case OMPC_untied:
9246   case OMPC_mergeable:
9247   case OMPC_threadprivate:
9248   case OMPC_flush:
9249   case OMPC_read:
9250   case OMPC_write:
9251   case OMPC_update:
9252   case OMPC_capture:
9253   case OMPC_seq_cst:
9254   case OMPC_depend:
9255   case OMPC_device:
9256   case OMPC_threads:
9257   case OMPC_simd:
9258   case OMPC_map:
9259   case OMPC_num_teams:
9260   case OMPC_thread_limit:
9261   case OMPC_priority:
9262   case OMPC_grainsize:
9263   case OMPC_nogroup:
9264   case OMPC_num_tasks:
9265   case OMPC_hint:
9266   case OMPC_unknown:
9267   case OMPC_uniform:
9268   case OMPC_to:
9269   case OMPC_from:
9270   case OMPC_use_device_ptr:
9271   case OMPC_is_device_ptr:
9272   case OMPC_unified_address:
9273   case OMPC_unified_shared_memory:
9274   case OMPC_reverse_offload:
9275   case OMPC_dynamic_allocators:
9276   case OMPC_atomic_default_mem_order:
9277     llvm_unreachable("Clause is not allowed.");
9278   }
9279   return Res;
9280 }
9281 
9282 static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
9283                                    OpenMPScheduleClauseModifier M2,
9284                                    SourceLocation M1Loc, SourceLocation M2Loc) {
9285   if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
9286     SmallVector<unsigned, 2> Excluded;
9287     if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
9288       Excluded.push_back(M2);
9289     if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
9290       Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
9291     if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
9292       Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
9293     S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
9294         << getListOfPossibleValues(OMPC_schedule,
9295                                    /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
9296                                    /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
9297                                    Excluded)
9298         << getOpenMPClauseName(OMPC_schedule);
9299     return true;
9300   }
9301   return false;
9302 }
9303 
9304 OMPClause *Sema::ActOnOpenMPScheduleClause(
9305     OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
9306     OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
9307     SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
9308     SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
9309   if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
9310       checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
9311     return nullptr;
9312   // OpenMP, 2.7.1, Loop Construct, Restrictions
9313   // Either the monotonic modifier or the nonmonotonic modifier can be specified
9314   // but not both.
9315   if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
9316       (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
9317        M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
9318       (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
9319        M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
9320     Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
9321         << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
9322         << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
9323     return nullptr;
9324   }
9325   if (Kind == OMPC_SCHEDULE_unknown) {
9326     std::string Values;
9327     if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
9328       unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
9329       Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
9330                                        /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
9331                                        Exclude);
9332     } else {
9333       Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
9334                                        /*Last=*/OMPC_SCHEDULE_unknown);
9335     }
9336     Diag(KindLoc, diag::err_omp_unexpected_clause_value)
9337         << Values << getOpenMPClauseName(OMPC_schedule);
9338     return nullptr;
9339   }
9340   // OpenMP, 2.7.1, Loop Construct, Restrictions
9341   // The nonmonotonic modifier can only be specified with schedule(dynamic) or
9342   // schedule(guided).
9343   if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
9344        M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
9345       Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
9346     Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
9347          diag::err_omp_schedule_nonmonotonic_static);
9348     return nullptr;
9349   }
9350   Expr *ValExpr = ChunkSize;
9351   Stmt *HelperValStmt = nullptr;
9352   if (ChunkSize) {
9353     if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
9354         !ChunkSize->isInstantiationDependent() &&
9355         !ChunkSize->containsUnexpandedParameterPack()) {
9356       SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
9357       ExprResult Val =
9358           PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
9359       if (Val.isInvalid())
9360         return nullptr;
9361 
9362       ValExpr = Val.get();
9363 
9364       // OpenMP [2.7.1, Restrictions]
9365       //  chunk_size must be a loop invariant integer expression with a positive
9366       //  value.
9367       llvm::APSInt Result;
9368       if (ValExpr->isIntegerConstantExpr(Result, Context)) {
9369         if (Result.isSigned() && !Result.isStrictlyPositive()) {
9370           Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
9371               << "schedule" << 1 << ChunkSize->getSourceRange();
9372           return nullptr;
9373         }
9374       } else if (getOpenMPCaptureRegionForClause(
9375                      DSAStack->getCurrentDirective(), OMPC_schedule) !=
9376                      OMPD_unknown &&
9377                  !CurContext->isDependentContext()) {
9378         ValExpr = MakeFullExpr(ValExpr).get();
9379         llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
9380         ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
9381         HelperValStmt = buildPreInits(Context, Captures);
9382       }
9383     }
9384   }
9385 
9386   return new (Context)
9387       OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
9388                         ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
9389 }
9390 
9391 OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
9392                                    SourceLocation StartLoc,
9393                                    SourceLocation EndLoc) {
9394   OMPClause *Res = nullptr;
9395   switch (Kind) {
9396   case OMPC_ordered:
9397     Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
9398     break;
9399   case OMPC_nowait:
9400     Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
9401     break;
9402   case OMPC_untied:
9403     Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
9404     break;
9405   case OMPC_mergeable:
9406     Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
9407     break;
9408   case OMPC_read:
9409     Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
9410     break;
9411   case OMPC_write:
9412     Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
9413     break;
9414   case OMPC_update:
9415     Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
9416     break;
9417   case OMPC_capture:
9418     Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
9419     break;
9420   case OMPC_seq_cst:
9421     Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
9422     break;
9423   case OMPC_threads:
9424     Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
9425     break;
9426   case OMPC_simd:
9427     Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
9428     break;
9429   case OMPC_nogroup:
9430     Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
9431     break;
9432   case OMPC_unified_address:
9433     Res = ActOnOpenMPUnifiedAddressClause(StartLoc, EndLoc);
9434     break;
9435   case OMPC_unified_shared_memory:
9436     Res = ActOnOpenMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
9437     break;
9438   case OMPC_reverse_offload:
9439     Res = ActOnOpenMPReverseOffloadClause(StartLoc, EndLoc);
9440     break;
9441   case OMPC_dynamic_allocators:
9442     Res = ActOnOpenMPDynamicAllocatorsClause(StartLoc, EndLoc);
9443     break;
9444   case OMPC_if:
9445   case OMPC_final:
9446   case OMPC_num_threads:
9447   case OMPC_safelen:
9448   case OMPC_simdlen:
9449   case OMPC_collapse:
9450   case OMPC_schedule:
9451   case OMPC_private:
9452   case OMPC_firstprivate:
9453   case OMPC_lastprivate:
9454   case OMPC_shared:
9455   case OMPC_reduction:
9456   case OMPC_task_reduction:
9457   case OMPC_in_reduction:
9458   case OMPC_linear:
9459   case OMPC_aligned:
9460   case OMPC_copyin:
9461   case OMPC_copyprivate:
9462   case OMPC_default:
9463   case OMPC_proc_bind:
9464   case OMPC_threadprivate:
9465   case OMPC_flush:
9466   case OMPC_depend:
9467   case OMPC_device:
9468   case OMPC_map:
9469   case OMPC_num_teams:
9470   case OMPC_thread_limit:
9471   case OMPC_priority:
9472   case OMPC_grainsize:
9473   case OMPC_num_tasks:
9474   case OMPC_hint:
9475   case OMPC_dist_schedule:
9476   case OMPC_defaultmap:
9477   case OMPC_unknown:
9478   case OMPC_uniform:
9479   case OMPC_to:
9480   case OMPC_from:
9481   case OMPC_use_device_ptr:
9482   case OMPC_is_device_ptr:
9483   case OMPC_atomic_default_mem_order:
9484     llvm_unreachable("Clause is not allowed.");
9485   }
9486   return Res;
9487 }
9488 
9489 OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
9490                                          SourceLocation EndLoc) {
9491   DSAStack->setNowaitRegion();
9492   return new (Context) OMPNowaitClause(StartLoc, EndLoc);
9493 }
9494 
9495 OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
9496                                          SourceLocation EndLoc) {
9497   return new (Context) OMPUntiedClause(StartLoc, EndLoc);
9498 }
9499 
9500 OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
9501                                             SourceLocation EndLoc) {
9502   return new (Context) OMPMergeableClause(StartLoc, EndLoc);
9503 }
9504 
9505 OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
9506                                        SourceLocation EndLoc) {
9507   return new (Context) OMPReadClause(StartLoc, EndLoc);
9508 }
9509 
9510 OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
9511                                         SourceLocation EndLoc) {
9512   return new (Context) OMPWriteClause(StartLoc, EndLoc);
9513 }
9514 
9515 OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
9516                                          SourceLocation EndLoc) {
9517   return new (Context) OMPUpdateClause(StartLoc, EndLoc);
9518 }
9519 
9520 OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
9521                                           SourceLocation EndLoc) {
9522   return new (Context) OMPCaptureClause(StartLoc, EndLoc);
9523 }
9524 
9525 OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
9526                                          SourceLocation EndLoc) {
9527   return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
9528 }
9529 
9530 OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
9531                                           SourceLocation EndLoc) {
9532   return new (Context) OMPThreadsClause(StartLoc, EndLoc);
9533 }
9534 
9535 OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
9536                                        SourceLocation EndLoc) {
9537   return new (Context) OMPSIMDClause(StartLoc, EndLoc);
9538 }
9539 
9540 OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
9541                                           SourceLocation EndLoc) {
9542   return new (Context) OMPNogroupClause(StartLoc, EndLoc);
9543 }
9544 
9545 OMPClause *Sema::ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc,
9546                                                  SourceLocation EndLoc) {
9547   return new (Context) OMPUnifiedAddressClause(StartLoc, EndLoc);
9548 }
9549 
9550 OMPClause *Sema::ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc,
9551                                                       SourceLocation EndLoc) {
9552   return new (Context) OMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
9553 }
9554 
9555 OMPClause *Sema::ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc,
9556                                                  SourceLocation EndLoc) {
9557   return new (Context) OMPReverseOffloadClause(StartLoc, EndLoc);
9558 }
9559 
9560 OMPClause *Sema::ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc,
9561                                                     SourceLocation EndLoc) {
9562   return new (Context) OMPDynamicAllocatorsClause(StartLoc, EndLoc);
9563 }
9564 
9565 OMPClause *Sema::ActOnOpenMPVarListClause(
9566     OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
9567     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
9568     SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
9569     const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
9570     OpenMPLinearClauseKind LinKind,
9571     ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
9572     ArrayRef<SourceLocation> MapTypeModifiersLoc,
9573     OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
9574     SourceLocation DepLinMapLoc) {
9575   OMPClause *Res = nullptr;
9576   switch (Kind) {
9577   case OMPC_private:
9578     Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
9579     break;
9580   case OMPC_firstprivate:
9581     Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
9582     break;
9583   case OMPC_lastprivate:
9584     Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
9585     break;
9586   case OMPC_shared:
9587     Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
9588     break;
9589   case OMPC_reduction:
9590     Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
9591                                      EndLoc, ReductionIdScopeSpec, ReductionId);
9592     break;
9593   case OMPC_task_reduction:
9594     Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
9595                                          EndLoc, ReductionIdScopeSpec,
9596                                          ReductionId);
9597     break;
9598   case OMPC_in_reduction:
9599     Res =
9600         ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
9601                                      EndLoc, ReductionIdScopeSpec, ReductionId);
9602     break;
9603   case OMPC_linear:
9604     Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
9605                                   LinKind, DepLinMapLoc, ColonLoc, EndLoc);
9606     break;
9607   case OMPC_aligned:
9608     Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
9609                                    ColonLoc, EndLoc);
9610     break;
9611   case OMPC_copyin:
9612     Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
9613     break;
9614   case OMPC_copyprivate:
9615     Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
9616     break;
9617   case OMPC_flush:
9618     Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
9619     break;
9620   case OMPC_depend:
9621     Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
9622                                   StartLoc, LParenLoc, EndLoc);
9623     break;
9624   case OMPC_map:
9625     Res = ActOnOpenMPMapClause(MapTypeModifiers, MapTypeModifiersLoc, MapType,
9626                                IsMapTypeImplicit, DepLinMapLoc, ColonLoc,
9627                                VarList, StartLoc, LParenLoc, EndLoc);
9628     break;
9629   case OMPC_to:
9630     Res = ActOnOpenMPToClause(VarList, StartLoc, LParenLoc, EndLoc);
9631     break;
9632   case OMPC_from:
9633     Res = ActOnOpenMPFromClause(VarList, StartLoc, LParenLoc, EndLoc);
9634     break;
9635   case OMPC_use_device_ptr:
9636     Res = ActOnOpenMPUseDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
9637     break;
9638   case OMPC_is_device_ptr:
9639     Res = ActOnOpenMPIsDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
9640     break;
9641   case OMPC_if:
9642   case OMPC_final:
9643   case OMPC_num_threads:
9644   case OMPC_safelen:
9645   case OMPC_simdlen:
9646   case OMPC_collapse:
9647   case OMPC_default:
9648   case OMPC_proc_bind:
9649   case OMPC_schedule:
9650   case OMPC_ordered:
9651   case OMPC_nowait:
9652   case OMPC_untied:
9653   case OMPC_mergeable:
9654   case OMPC_threadprivate:
9655   case OMPC_read:
9656   case OMPC_write:
9657   case OMPC_update:
9658   case OMPC_capture:
9659   case OMPC_seq_cst:
9660   case OMPC_device:
9661   case OMPC_threads:
9662   case OMPC_simd:
9663   case OMPC_num_teams:
9664   case OMPC_thread_limit:
9665   case OMPC_priority:
9666   case OMPC_grainsize:
9667   case OMPC_nogroup:
9668   case OMPC_num_tasks:
9669   case OMPC_hint:
9670   case OMPC_dist_schedule:
9671   case OMPC_defaultmap:
9672   case OMPC_unknown:
9673   case OMPC_uniform:
9674   case OMPC_unified_address:
9675   case OMPC_unified_shared_memory:
9676   case OMPC_reverse_offload:
9677   case OMPC_dynamic_allocators:
9678   case OMPC_atomic_default_mem_order:
9679     llvm_unreachable("Clause is not allowed.");
9680   }
9681   return Res;
9682 }
9683 
9684 ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
9685                                        ExprObjectKind OK, SourceLocation Loc) {
9686   ExprResult Res = BuildDeclRefExpr(
9687       Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
9688   if (!Res.isUsable())
9689     return ExprError();
9690   if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
9691     Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
9692     if (!Res.isUsable())
9693       return ExprError();
9694   }
9695   if (VK != VK_LValue && Res.get()->isGLValue()) {
9696     Res = DefaultLvalueConversion(Res.get());
9697     if (!Res.isUsable())
9698       return ExprError();
9699   }
9700   return Res;
9701 }
9702 
9703 static std::pair<ValueDecl *, bool>
9704 getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
9705                SourceRange &ERange, bool AllowArraySection = false) {
9706   if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
9707       RefExpr->containsUnexpandedParameterPack())
9708     return std::make_pair(nullptr, true);
9709 
9710   // OpenMP [3.1, C/C++]
9711   //  A list item is a variable name.
9712   // OpenMP  [2.9.3.3, Restrictions, p.1]
9713   //  A variable that is part of another variable (as an array or
9714   //  structure element) cannot appear in a private clause.
9715   RefExpr = RefExpr->IgnoreParens();
9716   enum {
9717     NoArrayExpr = -1,
9718     ArraySubscript = 0,
9719     OMPArraySection = 1
9720   } IsArrayExpr = NoArrayExpr;
9721   if (AllowArraySection) {
9722     if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
9723       Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
9724       while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
9725         Base = TempASE->getBase()->IgnoreParenImpCasts();
9726       RefExpr = Base;
9727       IsArrayExpr = ArraySubscript;
9728     } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
9729       Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
9730       while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
9731         Base = TempOASE->getBase()->IgnoreParenImpCasts();
9732       while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
9733         Base = TempASE->getBase()->IgnoreParenImpCasts();
9734       RefExpr = Base;
9735       IsArrayExpr = OMPArraySection;
9736     }
9737   }
9738   ELoc = RefExpr->getExprLoc();
9739   ERange = RefExpr->getSourceRange();
9740   RefExpr = RefExpr->IgnoreParenImpCasts();
9741   auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
9742   auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
9743   if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
9744       (S.getCurrentThisType().isNull() || !ME ||
9745        !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
9746        !isa<FieldDecl>(ME->getMemberDecl()))) {
9747     if (IsArrayExpr != NoArrayExpr) {
9748       S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
9749                                                          << ERange;
9750     } else {
9751       S.Diag(ELoc,
9752              AllowArraySection
9753                  ? diag::err_omp_expected_var_name_member_expr_or_array_item
9754                  : diag::err_omp_expected_var_name_member_expr)
9755           << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
9756     }
9757     return std::make_pair(nullptr, false);
9758   }
9759   return std::make_pair(
9760       getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false);
9761 }
9762 
9763 OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
9764                                           SourceLocation StartLoc,
9765                                           SourceLocation LParenLoc,
9766                                           SourceLocation EndLoc) {
9767   SmallVector<Expr *, 8> Vars;
9768   SmallVector<Expr *, 8> PrivateCopies;
9769   for (Expr *RefExpr : VarList) {
9770     assert(RefExpr && "NULL expr in OpenMP private clause.");
9771     SourceLocation ELoc;
9772     SourceRange ERange;
9773     Expr *SimpleRefExpr = RefExpr;
9774     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
9775     if (Res.second) {
9776       // It will be analyzed later.
9777       Vars.push_back(RefExpr);
9778       PrivateCopies.push_back(nullptr);
9779     }
9780     ValueDecl *D = Res.first;
9781     if (!D)
9782       continue;
9783 
9784     QualType Type = D->getType();
9785     auto *VD = dyn_cast<VarDecl>(D);
9786 
9787     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
9788     //  A variable that appears in a private clause must not have an incomplete
9789     //  type or a reference type.
9790     if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
9791       continue;
9792     Type = Type.getNonReferenceType();
9793 
9794     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
9795     // in a Construct]
9796     //  Variables with the predetermined data-sharing attributes may not be
9797     //  listed in data-sharing attributes clauses, except for the cases
9798     //  listed below. For these exceptions only, listing a predetermined
9799     //  variable in a data-sharing attribute clause is allowed and overrides
9800     //  the variable's predetermined data-sharing attributes.
9801     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
9802     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
9803       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
9804                                           << getOpenMPClauseName(OMPC_private);
9805       reportOriginalDsa(*this, DSAStack, D, DVar);
9806       continue;
9807     }
9808 
9809     OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
9810     // Variably modified types are not supported for tasks.
9811     if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
9812         isOpenMPTaskingDirective(CurrDir)) {
9813       Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
9814           << getOpenMPClauseName(OMPC_private) << Type
9815           << getOpenMPDirectiveName(CurrDir);
9816       bool IsDecl =
9817           !VD ||
9818           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
9819       Diag(D->getLocation(),
9820            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
9821           << D;
9822       continue;
9823     }
9824 
9825     // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
9826     // A list item cannot appear in both a map clause and a data-sharing
9827     // attribute clause on the same construct
9828     if (isOpenMPTargetExecutionDirective(CurrDir)) {
9829       OpenMPClauseKind ConflictKind;
9830       if (DSAStack->checkMappableExprComponentListsForDecl(
9831               VD, /*CurrentRegionOnly=*/true,
9832               [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
9833                   OpenMPClauseKind WhereFoundClauseKind) -> bool {
9834                 ConflictKind = WhereFoundClauseKind;
9835                 return true;
9836               })) {
9837         Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
9838             << getOpenMPClauseName(OMPC_private)
9839             << getOpenMPClauseName(ConflictKind)
9840             << getOpenMPDirectiveName(CurrDir);
9841         reportOriginalDsa(*this, DSAStack, D, DVar);
9842         continue;
9843       }
9844     }
9845 
9846     // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
9847     //  A variable of class type (or array thereof) that appears in a private
9848     //  clause requires an accessible, unambiguous default constructor for the
9849     //  class type.
9850     // Generate helper private variable and initialize it with the default
9851     // value. The address of the original variable is replaced by the address of
9852     // the new private variable in CodeGen. This new variable is not added to
9853     // IdResolver, so the code in the OpenMP region uses original variable for
9854     // proper diagnostics.
9855     Type = Type.getUnqualifiedType();
9856     VarDecl *VDPrivate =
9857         buildVarDecl(*this, ELoc, Type, D->getName(),
9858                      D->hasAttrs() ? &D->getAttrs() : nullptr,
9859                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
9860     ActOnUninitializedDecl(VDPrivate);
9861     if (VDPrivate->isInvalidDecl())
9862       continue;
9863     DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
9864         *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
9865 
9866     DeclRefExpr *Ref = nullptr;
9867     if (!VD && !CurContext->isDependentContext())
9868       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
9869     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
9870     Vars.push_back((VD || CurContext->isDependentContext())
9871                        ? RefExpr->IgnoreParens()
9872                        : Ref);
9873     PrivateCopies.push_back(VDPrivateRefExpr);
9874   }
9875 
9876   if (Vars.empty())
9877     return nullptr;
9878 
9879   return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
9880                                   PrivateCopies);
9881 }
9882 
9883 namespace {
9884 class DiagsUninitializedSeveretyRAII {
9885 private:
9886   DiagnosticsEngine &Diags;
9887   SourceLocation SavedLoc;
9888   bool IsIgnored = false;
9889 
9890 public:
9891   DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
9892                                  bool IsIgnored)
9893       : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
9894     if (!IsIgnored) {
9895       Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
9896                         /*Map*/ diag::Severity::Ignored, Loc);
9897     }
9898   }
9899   ~DiagsUninitializedSeveretyRAII() {
9900     if (!IsIgnored)
9901       Diags.popMappings(SavedLoc);
9902   }
9903 };
9904 }
9905 
9906 OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
9907                                                SourceLocation StartLoc,
9908                                                SourceLocation LParenLoc,
9909                                                SourceLocation EndLoc) {
9910   SmallVector<Expr *, 8> Vars;
9911   SmallVector<Expr *, 8> PrivateCopies;
9912   SmallVector<Expr *, 8> Inits;
9913   SmallVector<Decl *, 4> ExprCaptures;
9914   bool IsImplicitClause =
9915       StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
9916   SourceLocation ImplicitClauseLoc = DSAStack->getConstructLoc();
9917 
9918   for (Expr *RefExpr : VarList) {
9919     assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
9920     SourceLocation ELoc;
9921     SourceRange ERange;
9922     Expr *SimpleRefExpr = RefExpr;
9923     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
9924     if (Res.second) {
9925       // It will be analyzed later.
9926       Vars.push_back(RefExpr);
9927       PrivateCopies.push_back(nullptr);
9928       Inits.push_back(nullptr);
9929     }
9930     ValueDecl *D = Res.first;
9931     if (!D)
9932       continue;
9933 
9934     ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
9935     QualType Type = D->getType();
9936     auto *VD = dyn_cast<VarDecl>(D);
9937 
9938     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
9939     //  A variable that appears in a private clause must not have an incomplete
9940     //  type or a reference type.
9941     if (RequireCompleteType(ELoc, Type,
9942                             diag::err_omp_firstprivate_incomplete_type))
9943       continue;
9944     Type = Type.getNonReferenceType();
9945 
9946     // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
9947     //  A variable of class type (or array thereof) that appears in a private
9948     //  clause requires an accessible, unambiguous copy constructor for the
9949     //  class type.
9950     QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
9951 
9952     // If an implicit firstprivate variable found it was checked already.
9953     DSAStackTy::DSAVarData TopDVar;
9954     if (!IsImplicitClause) {
9955       DSAStackTy::DSAVarData DVar =
9956           DSAStack->getTopDSA(D, /*FromParent=*/false);
9957       TopDVar = DVar;
9958       OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
9959       bool IsConstant = ElemType.isConstant(Context);
9960       // OpenMP [2.4.13, Data-sharing Attribute Clauses]
9961       //  A list item that specifies a given variable may not appear in more
9962       // than one clause on the same directive, except that a variable may be
9963       //  specified in both firstprivate and lastprivate clauses.
9964       // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
9965       // A list item may appear in a firstprivate or lastprivate clause but not
9966       // both.
9967       if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
9968           (isOpenMPDistributeDirective(CurrDir) ||
9969            DVar.CKind != OMPC_lastprivate) &&
9970           DVar.RefExpr) {
9971         Diag(ELoc, diag::err_omp_wrong_dsa)
9972             << getOpenMPClauseName(DVar.CKind)
9973             << getOpenMPClauseName(OMPC_firstprivate);
9974         reportOriginalDsa(*this, DSAStack, D, DVar);
9975         continue;
9976       }
9977 
9978       // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
9979       // in a Construct]
9980       //  Variables with the predetermined data-sharing attributes may not be
9981       //  listed in data-sharing attributes clauses, except for the cases
9982       //  listed below. For these exceptions only, listing a predetermined
9983       //  variable in a data-sharing attribute clause is allowed and overrides
9984       //  the variable's predetermined data-sharing attributes.
9985       // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
9986       // in a Construct, C/C++, p.2]
9987       //  Variables with const-qualified type having no mutable member may be
9988       //  listed in a firstprivate clause, even if they are static data members.
9989       if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
9990           DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
9991         Diag(ELoc, diag::err_omp_wrong_dsa)
9992             << getOpenMPClauseName(DVar.CKind)
9993             << getOpenMPClauseName(OMPC_firstprivate);
9994         reportOriginalDsa(*this, DSAStack, D, DVar);
9995         continue;
9996       }
9997 
9998       // OpenMP [2.9.3.4, Restrictions, p.2]
9999       //  A list item that is private within a parallel region must not appear
10000       //  in a firstprivate clause on a worksharing construct if any of the
10001       //  worksharing regions arising from the worksharing construct ever bind
10002       //  to any of the parallel regions arising from the parallel construct.
10003       // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
10004       // A list item that is private within a teams region must not appear in a
10005       // firstprivate clause on a distribute construct if any of the distribute
10006       // regions arising from the distribute construct ever bind to any of the
10007       // teams regions arising from the teams construct.
10008       // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
10009       // A list item that appears in a reduction clause of a teams construct
10010       // must not appear in a firstprivate clause on a distribute construct if
10011       // any of the distribute regions arising from the distribute construct
10012       // ever bind to any of the teams regions arising from the teams construct.
10013       if ((isOpenMPWorksharingDirective(CurrDir) ||
10014            isOpenMPDistributeDirective(CurrDir)) &&
10015           !isOpenMPParallelDirective(CurrDir) &&
10016           !isOpenMPTeamsDirective(CurrDir)) {
10017         DVar = DSAStack->getImplicitDSA(D, true);
10018         if (DVar.CKind != OMPC_shared &&
10019             (isOpenMPParallelDirective(DVar.DKind) ||
10020              isOpenMPTeamsDirective(DVar.DKind) ||
10021              DVar.DKind == OMPD_unknown)) {
10022           Diag(ELoc, diag::err_omp_required_access)
10023               << getOpenMPClauseName(OMPC_firstprivate)
10024               << getOpenMPClauseName(OMPC_shared);
10025           reportOriginalDsa(*this, DSAStack, D, DVar);
10026           continue;
10027         }
10028       }
10029       // OpenMP [2.9.3.4, Restrictions, p.3]
10030       //  A list item that appears in a reduction clause of a parallel construct
10031       //  must not appear in a firstprivate clause on a worksharing or task
10032       //  construct if any of the worksharing or task regions arising from the
10033       //  worksharing or task construct ever bind to any of the parallel regions
10034       //  arising from the parallel construct.
10035       // OpenMP [2.9.3.4, Restrictions, p.4]
10036       //  A list item that appears in a reduction clause in worksharing
10037       //  construct must not appear in a firstprivate clause in a task construct
10038       //  encountered during execution of any of the worksharing regions arising
10039       //  from the worksharing construct.
10040       if (isOpenMPTaskingDirective(CurrDir)) {
10041         DVar = DSAStack->hasInnermostDSA(
10042             D, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
10043             [](OpenMPDirectiveKind K) {
10044               return isOpenMPParallelDirective(K) ||
10045                      isOpenMPWorksharingDirective(K) ||
10046                      isOpenMPTeamsDirective(K);
10047             },
10048             /*FromParent=*/true);
10049         if (DVar.CKind == OMPC_reduction &&
10050             (isOpenMPParallelDirective(DVar.DKind) ||
10051              isOpenMPWorksharingDirective(DVar.DKind) ||
10052              isOpenMPTeamsDirective(DVar.DKind))) {
10053           Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
10054               << getOpenMPDirectiveName(DVar.DKind);
10055           reportOriginalDsa(*this, DSAStack, D, DVar);
10056           continue;
10057         }
10058       }
10059 
10060       // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
10061       // A list item cannot appear in both a map clause and a data-sharing
10062       // attribute clause on the same construct
10063       if (isOpenMPTargetExecutionDirective(CurrDir)) {
10064         OpenMPClauseKind ConflictKind;
10065         if (DSAStack->checkMappableExprComponentListsForDecl(
10066                 VD, /*CurrentRegionOnly=*/true,
10067                 [&ConflictKind](
10068                     OMPClauseMappableExprCommon::MappableExprComponentListRef,
10069                     OpenMPClauseKind WhereFoundClauseKind) {
10070                   ConflictKind = WhereFoundClauseKind;
10071                   return true;
10072                 })) {
10073           Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
10074               << getOpenMPClauseName(OMPC_firstprivate)
10075               << getOpenMPClauseName(ConflictKind)
10076               << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
10077           reportOriginalDsa(*this, DSAStack, D, DVar);
10078           continue;
10079         }
10080       }
10081     }
10082 
10083     // Variably modified types are not supported for tasks.
10084     if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
10085         isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
10086       Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
10087           << getOpenMPClauseName(OMPC_firstprivate) << Type
10088           << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
10089       bool IsDecl =
10090           !VD ||
10091           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
10092       Diag(D->getLocation(),
10093            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
10094           << D;
10095       continue;
10096     }
10097 
10098     Type = Type.getUnqualifiedType();
10099     VarDecl *VDPrivate =
10100         buildVarDecl(*this, ELoc, Type, D->getName(),
10101                      D->hasAttrs() ? &D->getAttrs() : nullptr,
10102                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
10103     // Generate helper private variable and initialize it with the value of the
10104     // original variable. The address of the original variable is replaced by
10105     // the address of the new private variable in the CodeGen. This new variable
10106     // is not added to IdResolver, so the code in the OpenMP region uses
10107     // original variable for proper diagnostics and variable capturing.
10108     Expr *VDInitRefExpr = nullptr;
10109     // For arrays generate initializer for single element and replace it by the
10110     // original array element in CodeGen.
10111     if (Type->isArrayType()) {
10112       VarDecl *VDInit =
10113           buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
10114       VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
10115       Expr *Init = DefaultLvalueConversion(VDInitRefExpr).get();
10116       ElemType = ElemType.getUnqualifiedType();
10117       VarDecl *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
10118                                          ".firstprivate.temp");
10119       InitializedEntity Entity =
10120           InitializedEntity::InitializeVariable(VDInitTemp);
10121       InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
10122 
10123       InitializationSequence InitSeq(*this, Entity, Kind, Init);
10124       ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
10125       if (Result.isInvalid())
10126         VDPrivate->setInvalidDecl();
10127       else
10128         VDPrivate->setInit(Result.getAs<Expr>());
10129       // Remove temp variable declaration.
10130       Context.Deallocate(VDInitTemp);
10131     } else {
10132       VarDecl *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
10133                                      ".firstprivate.temp");
10134       VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
10135                                        RefExpr->getExprLoc());
10136       AddInitializerToDecl(VDPrivate,
10137                            DefaultLvalueConversion(VDInitRefExpr).get(),
10138                            /*DirectInit=*/false);
10139     }
10140     if (VDPrivate->isInvalidDecl()) {
10141       if (IsImplicitClause) {
10142         Diag(RefExpr->getExprLoc(),
10143              diag::note_omp_task_predetermined_firstprivate_here);
10144       }
10145       continue;
10146     }
10147     CurContext->addDecl(VDPrivate);
10148     DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
10149         *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
10150         RefExpr->getExprLoc());
10151     DeclRefExpr *Ref = nullptr;
10152     if (!VD && !CurContext->isDependentContext()) {
10153       if (TopDVar.CKind == OMPC_lastprivate) {
10154         Ref = TopDVar.PrivateCopy;
10155       } else {
10156         Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
10157         if (!isOpenMPCapturedDecl(D))
10158           ExprCaptures.push_back(Ref->getDecl());
10159       }
10160     }
10161     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
10162     Vars.push_back((VD || CurContext->isDependentContext())
10163                        ? RefExpr->IgnoreParens()
10164                        : Ref);
10165     PrivateCopies.push_back(VDPrivateRefExpr);
10166     Inits.push_back(VDInitRefExpr);
10167   }
10168 
10169   if (Vars.empty())
10170     return nullptr;
10171 
10172   return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
10173                                        Vars, PrivateCopies, Inits,
10174                                        buildPreInits(Context, ExprCaptures));
10175 }
10176 
10177 OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
10178                                               SourceLocation StartLoc,
10179                                               SourceLocation LParenLoc,
10180                                               SourceLocation EndLoc) {
10181   SmallVector<Expr *, 8> Vars;
10182   SmallVector<Expr *, 8> SrcExprs;
10183   SmallVector<Expr *, 8> DstExprs;
10184   SmallVector<Expr *, 8> AssignmentOps;
10185   SmallVector<Decl *, 4> ExprCaptures;
10186   SmallVector<Expr *, 4> ExprPostUpdates;
10187   for (Expr *RefExpr : VarList) {
10188     assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
10189     SourceLocation ELoc;
10190     SourceRange ERange;
10191     Expr *SimpleRefExpr = RefExpr;
10192     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
10193     if (Res.second) {
10194       // It will be analyzed later.
10195       Vars.push_back(RefExpr);
10196       SrcExprs.push_back(nullptr);
10197       DstExprs.push_back(nullptr);
10198       AssignmentOps.push_back(nullptr);
10199     }
10200     ValueDecl *D = Res.first;
10201     if (!D)
10202       continue;
10203 
10204     QualType Type = D->getType();
10205     auto *VD = dyn_cast<VarDecl>(D);
10206 
10207     // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
10208     //  A variable that appears in a lastprivate clause must not have an
10209     //  incomplete type or a reference type.
10210     if (RequireCompleteType(ELoc, Type,
10211                             diag::err_omp_lastprivate_incomplete_type))
10212       continue;
10213     Type = Type.getNonReferenceType();
10214 
10215     OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
10216     // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
10217     // in a Construct]
10218     //  Variables with the predetermined data-sharing attributes may not be
10219     //  listed in data-sharing attributes clauses, except for the cases
10220     //  listed below.
10221     // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
10222     // A list item may appear in a firstprivate or lastprivate clause but not
10223     // both.
10224     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
10225     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
10226         (isOpenMPDistributeDirective(CurrDir) ||
10227          DVar.CKind != OMPC_firstprivate) &&
10228         (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
10229       Diag(ELoc, diag::err_omp_wrong_dsa)
10230           << getOpenMPClauseName(DVar.CKind)
10231           << getOpenMPClauseName(OMPC_lastprivate);
10232       reportOriginalDsa(*this, DSAStack, D, DVar);
10233       continue;
10234     }
10235 
10236     // OpenMP [2.14.3.5, Restrictions, p.2]
10237     // A list item that is private within a parallel region, or that appears in
10238     // the reduction clause of a parallel construct, must not appear in a
10239     // lastprivate clause on a worksharing construct if any of the corresponding
10240     // worksharing regions ever binds to any of the corresponding parallel
10241     // regions.
10242     DSAStackTy::DSAVarData TopDVar = DVar;
10243     if (isOpenMPWorksharingDirective(CurrDir) &&
10244         !isOpenMPParallelDirective(CurrDir) &&
10245         !isOpenMPTeamsDirective(CurrDir)) {
10246       DVar = DSAStack->getImplicitDSA(D, true);
10247       if (DVar.CKind != OMPC_shared) {
10248         Diag(ELoc, diag::err_omp_required_access)
10249             << getOpenMPClauseName(OMPC_lastprivate)
10250             << getOpenMPClauseName(OMPC_shared);
10251         reportOriginalDsa(*this, DSAStack, D, DVar);
10252         continue;
10253       }
10254     }
10255 
10256     // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
10257     //  A variable of class type (or array thereof) that appears in a
10258     //  lastprivate clause requires an accessible, unambiguous default
10259     //  constructor for the class type, unless the list item is also specified
10260     //  in a firstprivate clause.
10261     //  A variable of class type (or array thereof) that appears in a
10262     //  lastprivate clause requires an accessible, unambiguous copy assignment
10263     //  operator for the class type.
10264     Type = Context.getBaseElementType(Type).getNonReferenceType();
10265     VarDecl *SrcVD = buildVarDecl(*this, ERange.getBegin(),
10266                                   Type.getUnqualifiedType(), ".lastprivate.src",
10267                                   D->hasAttrs() ? &D->getAttrs() : nullptr);
10268     DeclRefExpr *PseudoSrcExpr =
10269         buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
10270     VarDecl *DstVD =
10271         buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
10272                      D->hasAttrs() ? &D->getAttrs() : nullptr);
10273     DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
10274     // For arrays generate assignment operation for single element and replace
10275     // it by the original array element in CodeGen.
10276     ExprResult AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
10277                                          PseudoDstExpr, PseudoSrcExpr);
10278     if (AssignmentOp.isInvalid())
10279       continue;
10280     AssignmentOp =
10281         ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
10282     if (AssignmentOp.isInvalid())
10283       continue;
10284 
10285     DeclRefExpr *Ref = nullptr;
10286     if (!VD && !CurContext->isDependentContext()) {
10287       if (TopDVar.CKind == OMPC_firstprivate) {
10288         Ref = TopDVar.PrivateCopy;
10289       } else {
10290         Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
10291         if (!isOpenMPCapturedDecl(D))
10292           ExprCaptures.push_back(Ref->getDecl());
10293       }
10294       if (TopDVar.CKind == OMPC_firstprivate ||
10295           (!isOpenMPCapturedDecl(D) &&
10296            Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
10297         ExprResult RefRes = DefaultLvalueConversion(Ref);
10298         if (!RefRes.isUsable())
10299           continue;
10300         ExprResult PostUpdateRes =
10301             BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
10302                        RefRes.get());
10303         if (!PostUpdateRes.isUsable())
10304           continue;
10305         ExprPostUpdates.push_back(
10306             IgnoredValueConversions(PostUpdateRes.get()).get());
10307       }
10308     }
10309     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
10310     Vars.push_back((VD || CurContext->isDependentContext())
10311                        ? RefExpr->IgnoreParens()
10312                        : Ref);
10313     SrcExprs.push_back(PseudoSrcExpr);
10314     DstExprs.push_back(PseudoDstExpr);
10315     AssignmentOps.push_back(AssignmentOp.get());
10316   }
10317 
10318   if (Vars.empty())
10319     return nullptr;
10320 
10321   return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
10322                                       Vars, SrcExprs, DstExprs, AssignmentOps,
10323                                       buildPreInits(Context, ExprCaptures),
10324                                       buildPostUpdate(*this, ExprPostUpdates));
10325 }
10326 
10327 OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
10328                                          SourceLocation StartLoc,
10329                                          SourceLocation LParenLoc,
10330                                          SourceLocation EndLoc) {
10331   SmallVector<Expr *, 8> Vars;
10332   for (Expr *RefExpr : VarList) {
10333     assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
10334     SourceLocation ELoc;
10335     SourceRange ERange;
10336     Expr *SimpleRefExpr = RefExpr;
10337     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
10338     if (Res.second) {
10339       // It will be analyzed later.
10340       Vars.push_back(RefExpr);
10341     }
10342     ValueDecl *D = Res.first;
10343     if (!D)
10344       continue;
10345 
10346     auto *VD = dyn_cast<VarDecl>(D);
10347     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
10348     // in a Construct]
10349     //  Variables with the predetermined data-sharing attributes may not be
10350     //  listed in data-sharing attributes clauses, except for the cases
10351     //  listed below. For these exceptions only, listing a predetermined
10352     //  variable in a data-sharing attribute clause is allowed and overrides
10353     //  the variable's predetermined data-sharing attributes.
10354     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
10355     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
10356         DVar.RefExpr) {
10357       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
10358                                           << getOpenMPClauseName(OMPC_shared);
10359       reportOriginalDsa(*this, DSAStack, D, DVar);
10360       continue;
10361     }
10362 
10363     DeclRefExpr *Ref = nullptr;
10364     if (!VD && isOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
10365       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
10366     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
10367     Vars.push_back((VD || !Ref || CurContext->isDependentContext())
10368                        ? RefExpr->IgnoreParens()
10369                        : Ref);
10370   }
10371 
10372   if (Vars.empty())
10373     return nullptr;
10374 
10375   return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
10376 }
10377 
10378 namespace {
10379 class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
10380   DSAStackTy *Stack;
10381 
10382 public:
10383   bool VisitDeclRefExpr(DeclRefExpr *E) {
10384     if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
10385       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
10386       if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
10387         return false;
10388       if (DVar.CKind != OMPC_unknown)
10389         return true;
10390       DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
10391           VD, isOpenMPPrivate, [](OpenMPDirectiveKind) { return true; },
10392           /*FromParent=*/true);
10393       return DVarPrivate.CKind != OMPC_unknown;
10394     }
10395     return false;
10396   }
10397   bool VisitStmt(Stmt *S) {
10398     for (Stmt *Child : S->children()) {
10399       if (Child && Visit(Child))
10400         return true;
10401     }
10402     return false;
10403   }
10404   explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
10405 };
10406 } // namespace
10407 
10408 namespace {
10409 // Transform MemberExpression for specified FieldDecl of current class to
10410 // DeclRefExpr to specified OMPCapturedExprDecl.
10411 class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
10412   typedef TreeTransform<TransformExprToCaptures> BaseTransform;
10413   ValueDecl *Field = nullptr;
10414   DeclRefExpr *CapturedExpr = nullptr;
10415 
10416 public:
10417   TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
10418       : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
10419 
10420   ExprResult TransformMemberExpr(MemberExpr *E) {
10421     if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
10422         E->getMemberDecl() == Field) {
10423       CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
10424       return CapturedExpr;
10425     }
10426     return BaseTransform::TransformMemberExpr(E);
10427   }
10428   DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
10429 };
10430 } // namespace
10431 
10432 template <typename T, typename U>
10433 static T filterLookupForUDR(SmallVectorImpl<U> &Lookups,
10434                             const llvm::function_ref<T(ValueDecl *)> Gen) {
10435   for (U &Set : Lookups) {
10436     for (auto *D : Set) {
10437       if (T Res = Gen(cast<ValueDecl>(D)))
10438         return Res;
10439     }
10440   }
10441   return T();
10442 }
10443 
10444 static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) {
10445   assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case");
10446 
10447   for (auto RD : D->redecls()) {
10448     // Don't bother with extra checks if we already know this one isn't visible.
10449     if (RD == D)
10450       continue;
10451 
10452     auto ND = cast<NamedDecl>(RD);
10453     if (LookupResult::isVisible(SemaRef, ND))
10454       return ND;
10455   }
10456 
10457   return nullptr;
10458 }
10459 
10460 static void
10461 argumentDependentLookup(Sema &SemaRef, const DeclarationNameInfo &ReductionId,
10462                         SourceLocation Loc, QualType Ty,
10463                         SmallVectorImpl<UnresolvedSet<8>> &Lookups) {
10464   // Find all of the associated namespaces and classes based on the
10465   // arguments we have.
10466   Sema::AssociatedNamespaceSet AssociatedNamespaces;
10467   Sema::AssociatedClassSet AssociatedClasses;
10468   OpaqueValueExpr OVE(Loc, Ty, VK_LValue);
10469   SemaRef.FindAssociatedClassesAndNamespaces(Loc, &OVE, AssociatedNamespaces,
10470                                              AssociatedClasses);
10471 
10472   // C++ [basic.lookup.argdep]p3:
10473   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
10474   //   and let Y be the lookup set produced by argument dependent
10475   //   lookup (defined as follows). If X contains [...] then Y is
10476   //   empty. Otherwise Y is the set of declarations found in the
10477   //   namespaces associated with the argument types as described
10478   //   below. The set of declarations found by the lookup of the name
10479   //   is the union of X and Y.
10480   //
10481   // Here, we compute Y and add its members to the overloaded
10482   // candidate set.
10483   for (auto *NS : AssociatedNamespaces) {
10484     //   When considering an associated namespace, the lookup is the
10485     //   same as the lookup performed when the associated namespace is
10486     //   used as a qualifier (3.4.3.2) except that:
10487     //
10488     //     -- Any using-directives in the associated namespace are
10489     //        ignored.
10490     //
10491     //     -- Any namespace-scope friend functions declared in
10492     //        associated classes are visible within their respective
10493     //        namespaces even if they are not visible during an ordinary
10494     //        lookup (11.4).
10495     DeclContext::lookup_result R = NS->lookup(ReductionId.getName());
10496     for (auto *D : R) {
10497       auto *Underlying = D;
10498       if (auto *USD = dyn_cast<UsingShadowDecl>(D))
10499         Underlying = USD->getTargetDecl();
10500 
10501       if (!isa<OMPDeclareReductionDecl>(Underlying))
10502         continue;
10503 
10504       if (!SemaRef.isVisible(D)) {
10505         D = findAcceptableDecl(SemaRef, D);
10506         if (!D)
10507           continue;
10508         if (auto *USD = dyn_cast<UsingShadowDecl>(D))
10509           Underlying = USD->getTargetDecl();
10510       }
10511       Lookups.emplace_back();
10512       Lookups.back().addDecl(Underlying);
10513     }
10514   }
10515 }
10516 
10517 static ExprResult
10518 buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
10519                          Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
10520                          const DeclarationNameInfo &ReductionId, QualType Ty,
10521                          CXXCastPath &BasePath, Expr *UnresolvedReduction) {
10522   if (ReductionIdScopeSpec.isInvalid())
10523     return ExprError();
10524   SmallVector<UnresolvedSet<8>, 4> Lookups;
10525   if (S) {
10526     LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
10527     Lookup.suppressDiagnostics();
10528     while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
10529       NamedDecl *D = Lookup.getRepresentativeDecl();
10530       do {
10531         S = S->getParent();
10532       } while (S && !S->isDeclScope(D));
10533       if (S)
10534         S = S->getParent();
10535       Lookups.emplace_back();
10536       Lookups.back().append(Lookup.begin(), Lookup.end());
10537       Lookup.clear();
10538     }
10539   } else if (auto *ULE =
10540                  cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
10541     Lookups.push_back(UnresolvedSet<8>());
10542     Decl *PrevD = nullptr;
10543     for (NamedDecl *D : ULE->decls()) {
10544       if (D == PrevD)
10545         Lookups.push_back(UnresolvedSet<8>());
10546       else if (auto *DRD = cast<OMPDeclareReductionDecl>(D))
10547         Lookups.back().addDecl(DRD);
10548       PrevD = D;
10549     }
10550   }
10551   if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() ||
10552       Ty->isInstantiationDependentType() ||
10553       Ty->containsUnexpandedParameterPack() ||
10554       filterLookupForUDR<bool>(Lookups, [](ValueDecl *D) {
10555         return !D->isInvalidDecl() &&
10556                (D->getType()->isDependentType() ||
10557                 D->getType()->isInstantiationDependentType() ||
10558                 D->getType()->containsUnexpandedParameterPack());
10559       })) {
10560     UnresolvedSet<8> ResSet;
10561     for (const UnresolvedSet<8> &Set : Lookups) {
10562       if (Set.empty())
10563         continue;
10564       ResSet.append(Set.begin(), Set.end());
10565       // The last item marks the end of all declarations at the specified scope.
10566       ResSet.addDecl(Set[Set.size() - 1]);
10567     }
10568     return UnresolvedLookupExpr::Create(
10569         SemaRef.Context, /*NamingClass=*/nullptr,
10570         ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
10571         /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
10572   }
10573   // Lookup inside the classes.
10574   // C++ [over.match.oper]p3:
10575   //   For a unary operator @ with an operand of a type whose
10576   //   cv-unqualified version is T1, and for a binary operator @ with
10577   //   a left operand of a type whose cv-unqualified version is T1 and
10578   //   a right operand of a type whose cv-unqualified version is T2,
10579   //   three sets of candidate functions, designated member
10580   //   candidates, non-member candidates and built-in candidates, are
10581   //   constructed as follows:
10582   //     -- If T1 is a complete class type or a class currently being
10583   //        defined, the set of member candidates is the result of the
10584   //        qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
10585   //        the set of member candidates is empty.
10586   LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
10587   Lookup.suppressDiagnostics();
10588   if (const auto *TyRec = Ty->getAs<RecordType>()) {
10589     // Complete the type if it can be completed.
10590     // If the type is neither complete nor being defined, bail out now.
10591     if (SemaRef.isCompleteType(Loc, Ty) || TyRec->isBeingDefined() ||
10592         TyRec->getDecl()->getDefinition()) {
10593       Lookup.clear();
10594       SemaRef.LookupQualifiedName(Lookup, TyRec->getDecl());
10595       if (Lookup.empty()) {
10596         Lookups.emplace_back();
10597         Lookups.back().append(Lookup.begin(), Lookup.end());
10598       }
10599     }
10600   }
10601   // Perform ADL.
10602   argumentDependentLookup(SemaRef, ReductionId, Loc, Ty, Lookups);
10603   if (auto *VD = filterLookupForUDR<ValueDecl *>(
10604           Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
10605             if (!D->isInvalidDecl() &&
10606                 SemaRef.Context.hasSameType(D->getType(), Ty))
10607               return D;
10608             return nullptr;
10609           }))
10610     return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
10611   if (auto *VD = filterLookupForUDR<ValueDecl *>(
10612           Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
10613             if (!D->isInvalidDecl() &&
10614                 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
10615                 !Ty.isMoreQualifiedThan(D->getType()))
10616               return D;
10617             return nullptr;
10618           })) {
10619     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
10620                        /*DetectVirtual=*/false);
10621     if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
10622       if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
10623               VD->getType().getUnqualifiedType()))) {
10624         if (SemaRef.CheckBaseClassAccess(Loc, VD->getType(), Ty, Paths.front(),
10625                                          /*DiagID=*/0) !=
10626             Sema::AR_inaccessible) {
10627           SemaRef.BuildBasePathArray(Paths, BasePath);
10628           return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
10629         }
10630       }
10631     }
10632   }
10633   if (ReductionIdScopeSpec.isSet()) {
10634     SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
10635     return ExprError();
10636   }
10637   return ExprEmpty();
10638 }
10639 
10640 namespace {
10641 /// Data for the reduction-based clauses.
10642 struct ReductionData {
10643   /// List of original reduction items.
10644   SmallVector<Expr *, 8> Vars;
10645   /// List of private copies of the reduction items.
10646   SmallVector<Expr *, 8> Privates;
10647   /// LHS expressions for the reduction_op expressions.
10648   SmallVector<Expr *, 8> LHSs;
10649   /// RHS expressions for the reduction_op expressions.
10650   SmallVector<Expr *, 8> RHSs;
10651   /// Reduction operation expression.
10652   SmallVector<Expr *, 8> ReductionOps;
10653   /// Taskgroup descriptors for the corresponding reduction items in
10654   /// in_reduction clauses.
10655   SmallVector<Expr *, 8> TaskgroupDescriptors;
10656   /// List of captures for clause.
10657   SmallVector<Decl *, 4> ExprCaptures;
10658   /// List of postupdate expressions.
10659   SmallVector<Expr *, 4> ExprPostUpdates;
10660   ReductionData() = delete;
10661   /// Reserves required memory for the reduction data.
10662   ReductionData(unsigned Size) {
10663     Vars.reserve(Size);
10664     Privates.reserve(Size);
10665     LHSs.reserve(Size);
10666     RHSs.reserve(Size);
10667     ReductionOps.reserve(Size);
10668     TaskgroupDescriptors.reserve(Size);
10669     ExprCaptures.reserve(Size);
10670     ExprPostUpdates.reserve(Size);
10671   }
10672   /// Stores reduction item and reduction operation only (required for dependent
10673   /// reduction item).
10674   void push(Expr *Item, Expr *ReductionOp) {
10675     Vars.emplace_back(Item);
10676     Privates.emplace_back(nullptr);
10677     LHSs.emplace_back(nullptr);
10678     RHSs.emplace_back(nullptr);
10679     ReductionOps.emplace_back(ReductionOp);
10680     TaskgroupDescriptors.emplace_back(nullptr);
10681   }
10682   /// Stores reduction data.
10683   void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp,
10684             Expr *TaskgroupDescriptor) {
10685     Vars.emplace_back(Item);
10686     Privates.emplace_back(Private);
10687     LHSs.emplace_back(LHS);
10688     RHSs.emplace_back(RHS);
10689     ReductionOps.emplace_back(ReductionOp);
10690     TaskgroupDescriptors.emplace_back(TaskgroupDescriptor);
10691   }
10692 };
10693 } // namespace
10694 
10695 static bool checkOMPArraySectionConstantForReduction(
10696     ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement,
10697     SmallVectorImpl<llvm::APSInt> &ArraySizes) {
10698   const Expr *Length = OASE->getLength();
10699   if (Length == nullptr) {
10700     // For array sections of the form [1:] or [:], we would need to analyze
10701     // the lower bound...
10702     if (OASE->getColonLoc().isValid())
10703       return false;
10704 
10705     // This is an array subscript which has implicit length 1!
10706     SingleElement = true;
10707     ArraySizes.push_back(llvm::APSInt::get(1));
10708   } else {
10709     Expr::EvalResult Result;
10710     if (!Length->EvaluateAsInt(Result, Context))
10711       return false;
10712 
10713     llvm::APSInt ConstantLengthValue = Result.Val.getInt();
10714     SingleElement = (ConstantLengthValue.getSExtValue() == 1);
10715     ArraySizes.push_back(ConstantLengthValue);
10716   }
10717 
10718   // Get the base of this array section and walk up from there.
10719   const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
10720 
10721   // We require length = 1 for all array sections except the right-most to
10722   // guarantee that the memory region is contiguous and has no holes in it.
10723   while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) {
10724     Length = TempOASE->getLength();
10725     if (Length == nullptr) {
10726       // For array sections of the form [1:] or [:], we would need to analyze
10727       // the lower bound...
10728       if (OASE->getColonLoc().isValid())
10729         return false;
10730 
10731       // This is an array subscript which has implicit length 1!
10732       ArraySizes.push_back(llvm::APSInt::get(1));
10733     } else {
10734       Expr::EvalResult Result;
10735       if (!Length->EvaluateAsInt(Result, Context))
10736         return false;
10737 
10738       llvm::APSInt ConstantLengthValue = Result.Val.getInt();
10739       if (ConstantLengthValue.getSExtValue() != 1)
10740         return false;
10741 
10742       ArraySizes.push_back(ConstantLengthValue);
10743     }
10744     Base = TempOASE->getBase()->IgnoreParenImpCasts();
10745   }
10746 
10747   // If we have a single element, we don't need to add the implicit lengths.
10748   if (!SingleElement) {
10749     while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) {
10750       // Has implicit length 1!
10751       ArraySizes.push_back(llvm::APSInt::get(1));
10752       Base = TempASE->getBase()->IgnoreParenImpCasts();
10753     }
10754   }
10755 
10756   // This array section can be privatized as a single value or as a constant
10757   // sized array.
10758   return true;
10759 }
10760 
10761 static bool actOnOMPReductionKindClause(
10762     Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind,
10763     ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
10764     SourceLocation ColonLoc, SourceLocation EndLoc,
10765     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
10766     ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) {
10767   DeclarationName DN = ReductionId.getName();
10768   OverloadedOperatorKind OOK = DN.getCXXOverloadedOperator();
10769   BinaryOperatorKind BOK = BO_Comma;
10770 
10771   ASTContext &Context = S.Context;
10772   // OpenMP [2.14.3.6, reduction clause]
10773   // C
10774   // reduction-identifier is either an identifier or one of the following
10775   // operators: +, -, *,  &, |, ^, && and ||
10776   // C++
10777   // reduction-identifier is either an id-expression or one of the following
10778   // operators: +, -, *, &, |, ^, && and ||
10779   switch (OOK) {
10780   case OO_Plus:
10781   case OO_Minus:
10782     BOK = BO_Add;
10783     break;
10784   case OO_Star:
10785     BOK = BO_Mul;
10786     break;
10787   case OO_Amp:
10788     BOK = BO_And;
10789     break;
10790   case OO_Pipe:
10791     BOK = BO_Or;
10792     break;
10793   case OO_Caret:
10794     BOK = BO_Xor;
10795     break;
10796   case OO_AmpAmp:
10797     BOK = BO_LAnd;
10798     break;
10799   case OO_PipePipe:
10800     BOK = BO_LOr;
10801     break;
10802   case OO_New:
10803   case OO_Delete:
10804   case OO_Array_New:
10805   case OO_Array_Delete:
10806   case OO_Slash:
10807   case OO_Percent:
10808   case OO_Tilde:
10809   case OO_Exclaim:
10810   case OO_Equal:
10811   case OO_Less:
10812   case OO_Greater:
10813   case OO_LessEqual:
10814   case OO_GreaterEqual:
10815   case OO_PlusEqual:
10816   case OO_MinusEqual:
10817   case OO_StarEqual:
10818   case OO_SlashEqual:
10819   case OO_PercentEqual:
10820   case OO_CaretEqual:
10821   case OO_AmpEqual:
10822   case OO_PipeEqual:
10823   case OO_LessLess:
10824   case OO_GreaterGreater:
10825   case OO_LessLessEqual:
10826   case OO_GreaterGreaterEqual:
10827   case OO_EqualEqual:
10828   case OO_ExclaimEqual:
10829   case OO_Spaceship:
10830   case OO_PlusPlus:
10831   case OO_MinusMinus:
10832   case OO_Comma:
10833   case OO_ArrowStar:
10834   case OO_Arrow:
10835   case OO_Call:
10836   case OO_Subscript:
10837   case OO_Conditional:
10838   case OO_Coawait:
10839   case NUM_OVERLOADED_OPERATORS:
10840     llvm_unreachable("Unexpected reduction identifier");
10841   case OO_None:
10842     if (IdentifierInfo *II = DN.getAsIdentifierInfo()) {
10843       if (II->isStr("max"))
10844         BOK = BO_GT;
10845       else if (II->isStr("min"))
10846         BOK = BO_LT;
10847     }
10848     break;
10849   }
10850   SourceRange ReductionIdRange;
10851   if (ReductionIdScopeSpec.isValid())
10852     ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
10853   else
10854     ReductionIdRange.setBegin(ReductionId.getBeginLoc());
10855   ReductionIdRange.setEnd(ReductionId.getEndLoc());
10856 
10857   auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
10858   bool FirstIter = true;
10859   for (Expr *RefExpr : VarList) {
10860     assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
10861     // OpenMP [2.1, C/C++]
10862     //  A list item is a variable or array section, subject to the restrictions
10863     //  specified in Section 2.4 on page 42 and in each of the sections
10864     // describing clauses and directives for which a list appears.
10865     // OpenMP  [2.14.3.3, Restrictions, p.1]
10866     //  A variable that is part of another variable (as an array or
10867     //  structure element) cannot appear in a private clause.
10868     if (!FirstIter && IR != ER)
10869       ++IR;
10870     FirstIter = false;
10871     SourceLocation ELoc;
10872     SourceRange ERange;
10873     Expr *SimpleRefExpr = RefExpr;
10874     auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
10875                               /*AllowArraySection=*/true);
10876     if (Res.second) {
10877       // Try to find 'declare reduction' corresponding construct before using
10878       // builtin/overloaded operators.
10879       QualType Type = Context.DependentTy;
10880       CXXCastPath BasePath;
10881       ExprResult DeclareReductionRef = buildDeclareReductionRef(
10882           S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
10883           ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
10884       Expr *ReductionOp = nullptr;
10885       if (S.CurContext->isDependentContext() &&
10886           (DeclareReductionRef.isUnset() ||
10887            isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
10888         ReductionOp = DeclareReductionRef.get();
10889       // It will be analyzed later.
10890       RD.push(RefExpr, ReductionOp);
10891     }
10892     ValueDecl *D = Res.first;
10893     if (!D)
10894       continue;
10895 
10896     Expr *TaskgroupDescriptor = nullptr;
10897     QualType Type;
10898     auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
10899     auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
10900     if (ASE) {
10901       Type = ASE->getType().getNonReferenceType();
10902     } else if (OASE) {
10903       QualType BaseType =
10904           OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
10905       if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
10906         Type = ATy->getElementType();
10907       else
10908         Type = BaseType->getPointeeType();
10909       Type = Type.getNonReferenceType();
10910     } else {
10911       Type = Context.getBaseElementType(D->getType().getNonReferenceType());
10912     }
10913     auto *VD = dyn_cast<VarDecl>(D);
10914 
10915     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
10916     //  A variable that appears in a private clause must not have an incomplete
10917     //  type or a reference type.
10918     if (S.RequireCompleteType(ELoc, D->getType(),
10919                               diag::err_omp_reduction_incomplete_type))
10920       continue;
10921     // OpenMP [2.14.3.6, reduction clause, Restrictions]
10922     // A list item that appears in a reduction clause must not be
10923     // const-qualified.
10924     if (Type.getNonReferenceType().isConstant(Context)) {
10925       S.Diag(ELoc, diag::err_omp_const_reduction_list_item) << ERange;
10926       if (!ASE && !OASE) {
10927         bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
10928                                  VarDecl::DeclarationOnly;
10929         S.Diag(D->getLocation(),
10930                IsDecl ? diag::note_previous_decl : diag::note_defined_here)
10931             << D;
10932       }
10933       continue;
10934     }
10935 
10936     OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective();
10937     // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
10938     //  If a list-item is a reference type then it must bind to the same object
10939     //  for all threads of the team.
10940     if (!ASE && !OASE) {
10941       if (VD) {
10942         VarDecl *VDDef = VD->getDefinition();
10943         if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
10944           DSARefChecker Check(Stack);
10945           if (Check.Visit(VDDef->getInit())) {
10946             S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg)
10947                 << getOpenMPClauseName(ClauseKind) << ERange;
10948             S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
10949             continue;
10950           }
10951         }
10952       }
10953 
10954       // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
10955       // in a Construct]
10956       //  Variables with the predetermined data-sharing attributes may not be
10957       //  listed in data-sharing attributes clauses, except for the cases
10958       //  listed below. For these exceptions only, listing a predetermined
10959       //  variable in a data-sharing attribute clause is allowed and overrides
10960       //  the variable's predetermined data-sharing attributes.
10961       // OpenMP [2.14.3.6, Restrictions, p.3]
10962       //  Any number of reduction clauses can be specified on the directive,
10963       //  but a list item can appear only once in the reduction clauses for that
10964       //  directive.
10965       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false);
10966       if (DVar.CKind == OMPC_reduction) {
10967         S.Diag(ELoc, diag::err_omp_once_referenced)
10968             << getOpenMPClauseName(ClauseKind);
10969         if (DVar.RefExpr)
10970           S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
10971         continue;
10972       }
10973       if (DVar.CKind != OMPC_unknown) {
10974         S.Diag(ELoc, diag::err_omp_wrong_dsa)
10975             << getOpenMPClauseName(DVar.CKind)
10976             << getOpenMPClauseName(OMPC_reduction);
10977         reportOriginalDsa(S, Stack, D, DVar);
10978         continue;
10979       }
10980 
10981       // OpenMP [2.14.3.6, Restrictions, p.1]
10982       //  A list item that appears in a reduction clause of a worksharing
10983       //  construct must be shared in the parallel regions to which any of the
10984       //  worksharing regions arising from the worksharing construct bind.
10985       if (isOpenMPWorksharingDirective(CurrDir) &&
10986           !isOpenMPParallelDirective(CurrDir) &&
10987           !isOpenMPTeamsDirective(CurrDir)) {
10988         DVar = Stack->getImplicitDSA(D, true);
10989         if (DVar.CKind != OMPC_shared) {
10990           S.Diag(ELoc, diag::err_omp_required_access)
10991               << getOpenMPClauseName(OMPC_reduction)
10992               << getOpenMPClauseName(OMPC_shared);
10993           reportOriginalDsa(S, Stack, D, DVar);
10994           continue;
10995         }
10996       }
10997     }
10998 
10999     // Try to find 'declare reduction' corresponding construct before using
11000     // builtin/overloaded operators.
11001     CXXCastPath BasePath;
11002     ExprResult DeclareReductionRef = buildDeclareReductionRef(
11003         S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
11004         ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
11005     if (DeclareReductionRef.isInvalid())
11006       continue;
11007     if (S.CurContext->isDependentContext() &&
11008         (DeclareReductionRef.isUnset() ||
11009          isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
11010       RD.push(RefExpr, DeclareReductionRef.get());
11011       continue;
11012     }
11013     if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
11014       // Not allowed reduction identifier is found.
11015       S.Diag(ReductionId.getBeginLoc(),
11016              diag::err_omp_unknown_reduction_identifier)
11017           << Type << ReductionIdRange;
11018       continue;
11019     }
11020 
11021     // OpenMP [2.14.3.6, reduction clause, Restrictions]
11022     // The type of a list item that appears in a reduction clause must be valid
11023     // for the reduction-identifier. For a max or min reduction in C, the type
11024     // of the list item must be an allowed arithmetic data type: char, int,
11025     // float, double, or _Bool, possibly modified with long, short, signed, or
11026     // unsigned. For a max or min reduction in C++, the type of the list item
11027     // must be an allowed arithmetic data type: char, wchar_t, int, float,
11028     // double, or bool, possibly modified with long, short, signed, or unsigned.
11029     if (DeclareReductionRef.isUnset()) {
11030       if ((BOK == BO_GT || BOK == BO_LT) &&
11031           !(Type->isScalarType() ||
11032             (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
11033         S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
11034             << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus;
11035         if (!ASE && !OASE) {
11036           bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
11037                                    VarDecl::DeclarationOnly;
11038           S.Diag(D->getLocation(),
11039                  IsDecl ? diag::note_previous_decl : diag::note_defined_here)
11040               << D;
11041         }
11042         continue;
11043       }
11044       if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
11045           !S.getLangOpts().CPlusPlus && Type->isFloatingType()) {
11046         S.Diag(ELoc, diag::err_omp_clause_floating_type_arg)
11047             << getOpenMPClauseName(ClauseKind);
11048         if (!ASE && !OASE) {
11049           bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
11050                                    VarDecl::DeclarationOnly;
11051           S.Diag(D->getLocation(),
11052                  IsDecl ? diag::note_previous_decl : diag::note_defined_here)
11053               << D;
11054         }
11055         continue;
11056       }
11057     }
11058 
11059     Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
11060     VarDecl *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs",
11061                                   D->hasAttrs() ? &D->getAttrs() : nullptr);
11062     VarDecl *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(),
11063                                   D->hasAttrs() ? &D->getAttrs() : nullptr);
11064     QualType PrivateTy = Type;
11065 
11066     // Try if we can determine constant lengths for all array sections and avoid
11067     // the VLA.
11068     bool ConstantLengthOASE = false;
11069     if (OASE) {
11070       bool SingleElement;
11071       llvm::SmallVector<llvm::APSInt, 4> ArraySizes;
11072       ConstantLengthOASE = checkOMPArraySectionConstantForReduction(
11073           Context, OASE, SingleElement, ArraySizes);
11074 
11075       // If we don't have a single element, we must emit a constant array type.
11076       if (ConstantLengthOASE && !SingleElement) {
11077         for (llvm::APSInt &Size : ArraySizes)
11078           PrivateTy = Context.getConstantArrayType(
11079               PrivateTy, Size, ArrayType::Normal, /*IndexTypeQuals=*/0);
11080       }
11081     }
11082 
11083     if ((OASE && !ConstantLengthOASE) ||
11084         (!OASE && !ASE &&
11085          D->getType().getNonReferenceType()->isVariablyModifiedType())) {
11086       if (!Context.getTargetInfo().isVLASupported() &&
11087           S.shouldDiagnoseTargetSupportFromOpenMP()) {
11088         S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
11089         S.Diag(ELoc, diag::note_vla_unsupported);
11090         continue;
11091       }
11092       // For arrays/array sections only:
11093       // Create pseudo array type for private copy. The size for this array will
11094       // be generated during codegen.
11095       // For array subscripts or single variables Private Ty is the same as Type
11096       // (type of the variable or single array element).
11097       PrivateTy = Context.getVariableArrayType(
11098           Type,
11099           new (Context) OpaqueValueExpr(ELoc, Context.getSizeType(), VK_RValue),
11100           ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
11101     } else if (!ASE && !OASE &&
11102                Context.getAsArrayType(D->getType().getNonReferenceType())) {
11103       PrivateTy = D->getType().getNonReferenceType();
11104     }
11105     // Private copy.
11106     VarDecl *PrivateVD =
11107         buildVarDecl(S, ELoc, PrivateTy, D->getName(),
11108                      D->hasAttrs() ? &D->getAttrs() : nullptr,
11109                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
11110     // Add initializer for private variable.
11111     Expr *Init = nullptr;
11112     DeclRefExpr *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc);
11113     DeclRefExpr *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc);
11114     if (DeclareReductionRef.isUsable()) {
11115       auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
11116       auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
11117       if (DRD->getInitializer()) {
11118         Init = DRDRef;
11119         RHSVD->setInit(DRDRef);
11120         RHSVD->setInitStyle(VarDecl::CallInit);
11121       }
11122     } else {
11123       switch (BOK) {
11124       case BO_Add:
11125       case BO_Xor:
11126       case BO_Or:
11127       case BO_LOr:
11128         // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
11129         if (Type->isScalarType() || Type->isAnyComplexType())
11130           Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get();
11131         break;
11132       case BO_Mul:
11133       case BO_LAnd:
11134         if (Type->isScalarType() || Type->isAnyComplexType()) {
11135           // '*' and '&&' reduction ops - initializer is '1'.
11136           Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get();
11137         }
11138         break;
11139       case BO_And: {
11140         // '&' reduction op - initializer is '~0'.
11141         QualType OrigType = Type;
11142         if (auto *ComplexTy = OrigType->getAs<ComplexType>())
11143           Type = ComplexTy->getElementType();
11144         if (Type->isRealFloatingType()) {
11145           llvm::APFloat InitValue =
11146               llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
11147                                              /*isIEEE=*/true);
11148           Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
11149                                          Type, ELoc);
11150         } else if (Type->isScalarType()) {
11151           uint64_t Size = Context.getTypeSize(Type);
11152           QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
11153           llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
11154           Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
11155         }
11156         if (Init && OrigType->isAnyComplexType()) {
11157           // Init = 0xFFFF + 0xFFFFi;
11158           auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
11159           Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
11160         }
11161         Type = OrigType;
11162         break;
11163       }
11164       case BO_LT:
11165       case BO_GT: {
11166         // 'min' reduction op - initializer is 'Largest representable number in
11167         // the reduction list item type'.
11168         // 'max' reduction op - initializer is 'Least representable number in
11169         // the reduction list item type'.
11170         if (Type->isIntegerType() || Type->isPointerType()) {
11171           bool IsSigned = Type->hasSignedIntegerRepresentation();
11172           uint64_t Size = Context.getTypeSize(Type);
11173           QualType IntTy =
11174               Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
11175           llvm::APInt InitValue =
11176               (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
11177                                         : llvm::APInt::getMinValue(Size)
11178                              : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
11179                                         : llvm::APInt::getMaxValue(Size);
11180           Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
11181           if (Type->isPointerType()) {
11182             // Cast to pointer type.
11183             ExprResult CastExpr = S.BuildCStyleCastExpr(
11184                 ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init);
11185             if (CastExpr.isInvalid())
11186               continue;
11187             Init = CastExpr.get();
11188           }
11189         } else if (Type->isRealFloatingType()) {
11190           llvm::APFloat InitValue = llvm::APFloat::getLargest(
11191               Context.getFloatTypeSemantics(Type), BOK != BO_LT);
11192           Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
11193                                          Type, ELoc);
11194         }
11195         break;
11196       }
11197       case BO_PtrMemD:
11198       case BO_PtrMemI:
11199       case BO_MulAssign:
11200       case BO_Div:
11201       case BO_Rem:
11202       case BO_Sub:
11203       case BO_Shl:
11204       case BO_Shr:
11205       case BO_LE:
11206       case BO_GE:
11207       case BO_EQ:
11208       case BO_NE:
11209       case BO_Cmp:
11210       case BO_AndAssign:
11211       case BO_XorAssign:
11212       case BO_OrAssign:
11213       case BO_Assign:
11214       case BO_AddAssign:
11215       case BO_SubAssign:
11216       case BO_DivAssign:
11217       case BO_RemAssign:
11218       case BO_ShlAssign:
11219       case BO_ShrAssign:
11220       case BO_Comma:
11221         llvm_unreachable("Unexpected reduction operation");
11222       }
11223     }
11224     if (Init && DeclareReductionRef.isUnset())
11225       S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
11226     else if (!Init)
11227       S.ActOnUninitializedDecl(RHSVD);
11228     if (RHSVD->isInvalidDecl())
11229       continue;
11230     if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) {
11231       S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible)
11232           << Type << ReductionIdRange;
11233       bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
11234                                VarDecl::DeclarationOnly;
11235       S.Diag(D->getLocation(),
11236              IsDecl ? diag::note_previous_decl : diag::note_defined_here)
11237           << D;
11238       continue;
11239     }
11240     // Store initializer for single element in private copy. Will be used during
11241     // codegen.
11242     PrivateVD->setInit(RHSVD->getInit());
11243     PrivateVD->setInitStyle(RHSVD->getInitStyle());
11244     DeclRefExpr *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc);
11245     ExprResult ReductionOp;
11246     if (DeclareReductionRef.isUsable()) {
11247       QualType RedTy = DeclareReductionRef.get()->getType();
11248       QualType PtrRedTy = Context.getPointerType(RedTy);
11249       ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
11250       ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
11251       if (!BasePath.empty()) {
11252         LHS = S.DefaultLvalueConversion(LHS.get());
11253         RHS = S.DefaultLvalueConversion(RHS.get());
11254         LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
11255                                        CK_UncheckedDerivedToBase, LHS.get(),
11256                                        &BasePath, LHS.get()->getValueKind());
11257         RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
11258                                        CK_UncheckedDerivedToBase, RHS.get(),
11259                                        &BasePath, RHS.get()->getValueKind());
11260       }
11261       FunctionProtoType::ExtProtoInfo EPI;
11262       QualType Params[] = {PtrRedTy, PtrRedTy};
11263       QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
11264       auto *OVE = new (Context) OpaqueValueExpr(
11265           ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
11266           S.DefaultLvalueConversion(DeclareReductionRef.get()).get());
11267       Expr *Args[] = {LHS.get(), RHS.get()};
11268       ReductionOp =
11269           CallExpr::Create(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
11270     } else {
11271       ReductionOp = S.BuildBinOp(
11272           Stack->getCurScope(), ReductionId.getBeginLoc(), BOK, LHSDRE, RHSDRE);
11273       if (ReductionOp.isUsable()) {
11274         if (BOK != BO_LT && BOK != BO_GT) {
11275           ReductionOp =
11276               S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
11277                            BO_Assign, LHSDRE, ReductionOp.get());
11278         } else {
11279           auto *ConditionalOp = new (Context)
11280               ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc, RHSDRE,
11281                                   Type, VK_LValue, OK_Ordinary);
11282           ReductionOp =
11283               S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
11284                            BO_Assign, LHSDRE, ConditionalOp);
11285         }
11286         if (ReductionOp.isUsable())
11287           ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get(),
11288                                               /*DiscardedValue*/ false);
11289       }
11290       if (!ReductionOp.isUsable())
11291         continue;
11292     }
11293 
11294     // OpenMP [2.15.4.6, Restrictions, p.2]
11295     // A list item that appears in an in_reduction clause of a task construct
11296     // must appear in a task_reduction clause of a construct associated with a
11297     // taskgroup region that includes the participating task in its taskgroup
11298     // set. The construct associated with the innermost region that meets this
11299     // condition must specify the same reduction-identifier as the in_reduction
11300     // clause.
11301     if (ClauseKind == OMPC_in_reduction) {
11302       SourceRange ParentSR;
11303       BinaryOperatorKind ParentBOK;
11304       const Expr *ParentReductionOp;
11305       Expr *ParentBOKTD, *ParentReductionOpTD;
11306       DSAStackTy::DSAVarData ParentBOKDSA =
11307           Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK,
11308                                                   ParentBOKTD);
11309       DSAStackTy::DSAVarData ParentReductionOpDSA =
11310           Stack->getTopMostTaskgroupReductionData(
11311               D, ParentSR, ParentReductionOp, ParentReductionOpTD);
11312       bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown;
11313       bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown;
11314       if (!IsParentBOK && !IsParentReductionOp) {
11315         S.Diag(ELoc, diag::err_omp_in_reduction_not_task_reduction);
11316         continue;
11317       }
11318       if ((DeclareReductionRef.isUnset() && IsParentReductionOp) ||
11319           (DeclareReductionRef.isUsable() && IsParentBOK) || BOK != ParentBOK ||
11320           IsParentReductionOp) {
11321         bool EmitError = true;
11322         if (IsParentReductionOp && DeclareReductionRef.isUsable()) {
11323           llvm::FoldingSetNodeID RedId, ParentRedId;
11324           ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true);
11325           DeclareReductionRef.get()->Profile(RedId, Context,
11326                                              /*Canonical=*/true);
11327           EmitError = RedId != ParentRedId;
11328         }
11329         if (EmitError) {
11330           S.Diag(ReductionId.getBeginLoc(),
11331                  diag::err_omp_reduction_identifier_mismatch)
11332               << ReductionIdRange << RefExpr->getSourceRange();
11333           S.Diag(ParentSR.getBegin(),
11334                  diag::note_omp_previous_reduction_identifier)
11335               << ParentSR
11336               << (IsParentBOK ? ParentBOKDSA.RefExpr
11337                               : ParentReductionOpDSA.RefExpr)
11338                      ->getSourceRange();
11339           continue;
11340         }
11341       }
11342       TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD;
11343       assert(TaskgroupDescriptor && "Taskgroup descriptor must be defined.");
11344     }
11345 
11346     DeclRefExpr *Ref = nullptr;
11347     Expr *VarsExpr = RefExpr->IgnoreParens();
11348     if (!VD && !S.CurContext->isDependentContext()) {
11349       if (ASE || OASE) {
11350         TransformExprToCaptures RebuildToCapture(S, D);
11351         VarsExpr =
11352             RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
11353         Ref = RebuildToCapture.getCapturedExpr();
11354       } else {
11355         VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false);
11356       }
11357       if (!S.isOpenMPCapturedDecl(D)) {
11358         RD.ExprCaptures.emplace_back(Ref->getDecl());
11359         if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
11360           ExprResult RefRes = S.DefaultLvalueConversion(Ref);
11361           if (!RefRes.isUsable())
11362             continue;
11363           ExprResult PostUpdateRes =
11364               S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
11365                            RefRes.get());
11366           if (!PostUpdateRes.isUsable())
11367             continue;
11368           if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
11369               Stack->getCurrentDirective() == OMPD_taskgroup) {
11370             S.Diag(RefExpr->getExprLoc(),
11371                    diag::err_omp_reduction_non_addressable_expression)
11372                 << RefExpr->getSourceRange();
11373             continue;
11374           }
11375           RD.ExprPostUpdates.emplace_back(
11376               S.IgnoredValueConversions(PostUpdateRes.get()).get());
11377         }
11378       }
11379     }
11380     // All reduction items are still marked as reduction (to do not increase
11381     // code base size).
11382     Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
11383     if (CurrDir == OMPD_taskgroup) {
11384       if (DeclareReductionRef.isUsable())
11385         Stack->addTaskgroupReductionData(D, ReductionIdRange,
11386                                          DeclareReductionRef.get());
11387       else
11388         Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK);
11389     }
11390     RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(),
11391             TaskgroupDescriptor);
11392   }
11393   return RD.Vars.empty();
11394 }
11395 
11396 OMPClause *Sema::ActOnOpenMPReductionClause(
11397     ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
11398     SourceLocation ColonLoc, SourceLocation EndLoc,
11399     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
11400     ArrayRef<Expr *> UnresolvedReductions) {
11401   ReductionData RD(VarList.size());
11402   if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList,
11403                                   StartLoc, LParenLoc, ColonLoc, EndLoc,
11404                                   ReductionIdScopeSpec, ReductionId,
11405                                   UnresolvedReductions, RD))
11406     return nullptr;
11407 
11408   return OMPReductionClause::Create(
11409       Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
11410       ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
11411       RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
11412       buildPreInits(Context, RD.ExprCaptures),
11413       buildPostUpdate(*this, RD.ExprPostUpdates));
11414 }
11415 
11416 OMPClause *Sema::ActOnOpenMPTaskReductionClause(
11417     ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
11418     SourceLocation ColonLoc, SourceLocation EndLoc,
11419     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
11420     ArrayRef<Expr *> UnresolvedReductions) {
11421   ReductionData RD(VarList.size());
11422   if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction, VarList,
11423                                   StartLoc, LParenLoc, ColonLoc, EndLoc,
11424                                   ReductionIdScopeSpec, ReductionId,
11425                                   UnresolvedReductions, RD))
11426     return nullptr;
11427 
11428   return OMPTaskReductionClause::Create(
11429       Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
11430       ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
11431       RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
11432       buildPreInits(Context, RD.ExprCaptures),
11433       buildPostUpdate(*this, RD.ExprPostUpdates));
11434 }
11435 
11436 OMPClause *Sema::ActOnOpenMPInReductionClause(
11437     ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
11438     SourceLocation ColonLoc, SourceLocation EndLoc,
11439     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
11440     ArrayRef<Expr *> UnresolvedReductions) {
11441   ReductionData RD(VarList.size());
11442   if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList,
11443                                   StartLoc, LParenLoc, ColonLoc, EndLoc,
11444                                   ReductionIdScopeSpec, ReductionId,
11445                                   UnresolvedReductions, RD))
11446     return nullptr;
11447 
11448   return OMPInReductionClause::Create(
11449       Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
11450       ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
11451       RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors,
11452       buildPreInits(Context, RD.ExprCaptures),
11453       buildPostUpdate(*this, RD.ExprPostUpdates));
11454 }
11455 
11456 bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
11457                                      SourceLocation LinLoc) {
11458   if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
11459       LinKind == OMPC_LINEAR_unknown) {
11460     Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
11461     return true;
11462   }
11463   return false;
11464 }
11465 
11466 bool Sema::CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc,
11467                                  OpenMPLinearClauseKind LinKind,
11468                                  QualType Type) {
11469   const auto *VD = dyn_cast_or_null<VarDecl>(D);
11470   // A variable must not have an incomplete type or a reference type.
11471   if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
11472     return true;
11473   if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
11474       !Type->isReferenceType()) {
11475     Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
11476         << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
11477     return true;
11478   }
11479   Type = Type.getNonReferenceType();
11480 
11481   // A list item must not be const-qualified.
11482   if (Type.isConstant(Context)) {
11483     Diag(ELoc, diag::err_omp_const_variable)
11484         << getOpenMPClauseName(OMPC_linear);
11485     if (D) {
11486       bool IsDecl =
11487           !VD ||
11488           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
11489       Diag(D->getLocation(),
11490            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
11491           << D;
11492     }
11493     return true;
11494   }
11495 
11496   // A list item must be of integral or pointer type.
11497   Type = Type.getUnqualifiedType().getCanonicalType();
11498   const auto *Ty = Type.getTypePtrOrNull();
11499   if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
11500               !Ty->isPointerType())) {
11501     Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
11502     if (D) {
11503       bool IsDecl =
11504           !VD ||
11505           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
11506       Diag(D->getLocation(),
11507            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
11508           << D;
11509     }
11510     return true;
11511   }
11512   return false;
11513 }
11514 
11515 OMPClause *Sema::ActOnOpenMPLinearClause(
11516     ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
11517     SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
11518     SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
11519   SmallVector<Expr *, 8> Vars;
11520   SmallVector<Expr *, 8> Privates;
11521   SmallVector<Expr *, 8> Inits;
11522   SmallVector<Decl *, 4> ExprCaptures;
11523   SmallVector<Expr *, 4> ExprPostUpdates;
11524   if (CheckOpenMPLinearModifier(LinKind, LinLoc))
11525     LinKind = OMPC_LINEAR_val;
11526   for (Expr *RefExpr : VarList) {
11527     assert(RefExpr && "NULL expr in OpenMP linear clause.");
11528     SourceLocation ELoc;
11529     SourceRange ERange;
11530     Expr *SimpleRefExpr = RefExpr;
11531     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
11532     if (Res.second) {
11533       // It will be analyzed later.
11534       Vars.push_back(RefExpr);
11535       Privates.push_back(nullptr);
11536       Inits.push_back(nullptr);
11537     }
11538     ValueDecl *D = Res.first;
11539     if (!D)
11540       continue;
11541 
11542     QualType Type = D->getType();
11543     auto *VD = dyn_cast<VarDecl>(D);
11544 
11545     // OpenMP [2.14.3.7, linear clause]
11546     //  A list-item cannot appear in more than one linear clause.
11547     //  A list-item that appears in a linear clause cannot appear in any
11548     //  other data-sharing attribute clause.
11549     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
11550     if (DVar.RefExpr) {
11551       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
11552                                           << getOpenMPClauseName(OMPC_linear);
11553       reportOriginalDsa(*this, DSAStack, D, DVar);
11554       continue;
11555     }
11556 
11557     if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
11558       continue;
11559     Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
11560 
11561     // Build private copy of original var.
11562     VarDecl *Private =
11563         buildVarDecl(*this, ELoc, Type, D->getName(),
11564                      D->hasAttrs() ? &D->getAttrs() : nullptr,
11565                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
11566     DeclRefExpr *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
11567     // Build var to save initial value.
11568     VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
11569     Expr *InitExpr;
11570     DeclRefExpr *Ref = nullptr;
11571     if (!VD && !CurContext->isDependentContext()) {
11572       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
11573       if (!isOpenMPCapturedDecl(D)) {
11574         ExprCaptures.push_back(Ref->getDecl());
11575         if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
11576           ExprResult RefRes = DefaultLvalueConversion(Ref);
11577           if (!RefRes.isUsable())
11578             continue;
11579           ExprResult PostUpdateRes =
11580               BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
11581                          SimpleRefExpr, RefRes.get());
11582           if (!PostUpdateRes.isUsable())
11583             continue;
11584           ExprPostUpdates.push_back(
11585               IgnoredValueConversions(PostUpdateRes.get()).get());
11586         }
11587       }
11588     }
11589     if (LinKind == OMPC_LINEAR_uval)
11590       InitExpr = VD ? VD->getInit() : SimpleRefExpr;
11591     else
11592       InitExpr = VD ? SimpleRefExpr : Ref;
11593     AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
11594                          /*DirectInit=*/false);
11595     DeclRefExpr *InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
11596 
11597     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
11598     Vars.push_back((VD || CurContext->isDependentContext())
11599                        ? RefExpr->IgnoreParens()
11600                        : Ref);
11601     Privates.push_back(PrivateRef);
11602     Inits.push_back(InitRef);
11603   }
11604 
11605   if (Vars.empty())
11606     return nullptr;
11607 
11608   Expr *StepExpr = Step;
11609   Expr *CalcStepExpr = nullptr;
11610   if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
11611       !Step->isInstantiationDependent() &&
11612       !Step->containsUnexpandedParameterPack()) {
11613     SourceLocation StepLoc = Step->getBeginLoc();
11614     ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
11615     if (Val.isInvalid())
11616       return nullptr;
11617     StepExpr = Val.get();
11618 
11619     // Build var to save the step value.
11620     VarDecl *SaveVar =
11621         buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
11622     ExprResult SaveRef =
11623         buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
11624     ExprResult CalcStep =
11625         BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
11626     CalcStep = ActOnFinishFullExpr(CalcStep.get(), /*DiscardedValue*/ false);
11627 
11628     // Warn about zero linear step (it would be probably better specified as
11629     // making corresponding variables 'const').
11630     llvm::APSInt Result;
11631     bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
11632     if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
11633       Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
11634                                                      << (Vars.size() > 1);
11635     if (!IsConstant && CalcStep.isUsable()) {
11636       // Calculate the step beforehand instead of doing this on each iteration.
11637       // (This is not used if the number of iterations may be kfold-ed).
11638       CalcStepExpr = CalcStep.get();
11639     }
11640   }
11641 
11642   return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
11643                                  ColonLoc, EndLoc, Vars, Privates, Inits,
11644                                  StepExpr, CalcStepExpr,
11645                                  buildPreInits(Context, ExprCaptures),
11646                                  buildPostUpdate(*this, ExprPostUpdates));
11647 }
11648 
11649 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
11650                                      Expr *NumIterations, Sema &SemaRef,
11651                                      Scope *S, DSAStackTy *Stack) {
11652   // Walk the vars and build update/final expressions for the CodeGen.
11653   SmallVector<Expr *, 8> Updates;
11654   SmallVector<Expr *, 8> Finals;
11655   Expr *Step = Clause.getStep();
11656   Expr *CalcStep = Clause.getCalcStep();
11657   // OpenMP [2.14.3.7, linear clause]
11658   // If linear-step is not specified it is assumed to be 1.
11659   if (!Step)
11660     Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
11661   else if (CalcStep)
11662     Step = cast<BinaryOperator>(CalcStep)->getLHS();
11663   bool HasErrors = false;
11664   auto CurInit = Clause.inits().begin();
11665   auto CurPrivate = Clause.privates().begin();
11666   OpenMPLinearClauseKind LinKind = Clause.getModifier();
11667   for (Expr *RefExpr : Clause.varlists()) {
11668     SourceLocation ELoc;
11669     SourceRange ERange;
11670     Expr *SimpleRefExpr = RefExpr;
11671     auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange);
11672     ValueDecl *D = Res.first;
11673     if (Res.second || !D) {
11674       Updates.push_back(nullptr);
11675       Finals.push_back(nullptr);
11676       HasErrors = true;
11677       continue;
11678     }
11679     auto &&Info = Stack->isLoopControlVariable(D);
11680     // OpenMP [2.15.11, distribute simd Construct]
11681     // A list item may not appear in a linear clause, unless it is the loop
11682     // iteration variable.
11683     if (isOpenMPDistributeDirective(Stack->getCurrentDirective()) &&
11684         isOpenMPSimdDirective(Stack->getCurrentDirective()) && !Info.first) {
11685       SemaRef.Diag(ELoc,
11686                    diag::err_omp_linear_distribute_var_non_loop_iteration);
11687       Updates.push_back(nullptr);
11688       Finals.push_back(nullptr);
11689       HasErrors = true;
11690       continue;
11691     }
11692     Expr *InitExpr = *CurInit;
11693 
11694     // Build privatized reference to the current linear var.
11695     auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
11696     Expr *CapturedRef;
11697     if (LinKind == OMPC_LINEAR_uval)
11698       CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
11699     else
11700       CapturedRef =
11701           buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
11702                            DE->getType().getUnqualifiedType(), DE->getExprLoc(),
11703                            /*RefersToCapture=*/true);
11704 
11705     // Build update: Var = InitExpr + IV * Step
11706     ExprResult Update;
11707     if (!Info.first)
11708       Update =
11709           buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate,
11710                              InitExpr, IV, Step, /* Subtract */ false);
11711     else
11712       Update = *CurPrivate;
11713     Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getBeginLoc(),
11714                                          /*DiscardedValue*/ false);
11715 
11716     // Build final: Var = InitExpr + NumIterations * Step
11717     ExprResult Final;
11718     if (!Info.first)
11719       Final =
11720           buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
11721                              InitExpr, NumIterations, Step, /*Subtract=*/false);
11722     else
11723       Final = *CurPrivate;
11724     Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getBeginLoc(),
11725                                         /*DiscardedValue*/ false);
11726 
11727     if (!Update.isUsable() || !Final.isUsable()) {
11728       Updates.push_back(nullptr);
11729       Finals.push_back(nullptr);
11730       HasErrors = true;
11731     } else {
11732       Updates.push_back(Update.get());
11733       Finals.push_back(Final.get());
11734     }
11735     ++CurInit;
11736     ++CurPrivate;
11737   }
11738   Clause.setUpdates(Updates);
11739   Clause.setFinals(Finals);
11740   return HasErrors;
11741 }
11742 
11743 OMPClause *Sema::ActOnOpenMPAlignedClause(
11744     ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
11745     SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
11746   SmallVector<Expr *, 8> Vars;
11747   for (Expr *RefExpr : VarList) {
11748     assert(RefExpr && "NULL expr in OpenMP linear clause.");
11749     SourceLocation ELoc;
11750     SourceRange ERange;
11751     Expr *SimpleRefExpr = RefExpr;
11752     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
11753     if (Res.second) {
11754       // It will be analyzed later.
11755       Vars.push_back(RefExpr);
11756     }
11757     ValueDecl *D = Res.first;
11758     if (!D)
11759       continue;
11760 
11761     QualType QType = D->getType();
11762     auto *VD = dyn_cast<VarDecl>(D);
11763 
11764     // OpenMP  [2.8.1, simd construct, Restrictions]
11765     // The type of list items appearing in the aligned clause must be
11766     // array, pointer, reference to array, or reference to pointer.
11767     QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
11768     const Type *Ty = QType.getTypePtrOrNull();
11769     if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
11770       Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
11771           << QType << getLangOpts().CPlusPlus << ERange;
11772       bool IsDecl =
11773           !VD ||
11774           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
11775       Diag(D->getLocation(),
11776            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
11777           << D;
11778       continue;
11779     }
11780 
11781     // OpenMP  [2.8.1, simd construct, Restrictions]
11782     // A list-item cannot appear in more than one aligned clause.
11783     if (const Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
11784       Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
11785       Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
11786           << getOpenMPClauseName(OMPC_aligned);
11787       continue;
11788     }
11789 
11790     DeclRefExpr *Ref = nullptr;
11791     if (!VD && isOpenMPCapturedDecl(D))
11792       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
11793     Vars.push_back(DefaultFunctionArrayConversion(
11794                        (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
11795                        .get());
11796   }
11797 
11798   // OpenMP [2.8.1, simd construct, Description]
11799   // The parameter of the aligned clause, alignment, must be a constant
11800   // positive integer expression.
11801   // If no optional parameter is specified, implementation-defined default
11802   // alignments for SIMD instructions on the target platforms are assumed.
11803   if (Alignment != nullptr) {
11804     ExprResult AlignResult =
11805         VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
11806     if (AlignResult.isInvalid())
11807       return nullptr;
11808     Alignment = AlignResult.get();
11809   }
11810   if (Vars.empty())
11811     return nullptr;
11812 
11813   return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
11814                                   EndLoc, Vars, Alignment);
11815 }
11816 
11817 OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
11818                                          SourceLocation StartLoc,
11819                                          SourceLocation LParenLoc,
11820                                          SourceLocation EndLoc) {
11821   SmallVector<Expr *, 8> Vars;
11822   SmallVector<Expr *, 8> SrcExprs;
11823   SmallVector<Expr *, 8> DstExprs;
11824   SmallVector<Expr *, 8> AssignmentOps;
11825   for (Expr *RefExpr : VarList) {
11826     assert(RefExpr && "NULL expr in OpenMP copyin clause.");
11827     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
11828       // It will be analyzed later.
11829       Vars.push_back(RefExpr);
11830       SrcExprs.push_back(nullptr);
11831       DstExprs.push_back(nullptr);
11832       AssignmentOps.push_back(nullptr);
11833       continue;
11834     }
11835 
11836     SourceLocation ELoc = RefExpr->getExprLoc();
11837     // OpenMP [2.1, C/C++]
11838     //  A list item is a variable name.
11839     // OpenMP  [2.14.4.1, Restrictions, p.1]
11840     //  A list item that appears in a copyin clause must be threadprivate.
11841     auto *DE = dyn_cast<DeclRefExpr>(RefExpr);
11842     if (!DE || !isa<VarDecl>(DE->getDecl())) {
11843       Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
11844           << 0 << RefExpr->getSourceRange();
11845       continue;
11846     }
11847 
11848     Decl *D = DE->getDecl();
11849     auto *VD = cast<VarDecl>(D);
11850 
11851     QualType Type = VD->getType();
11852     if (Type->isDependentType() || Type->isInstantiationDependentType()) {
11853       // It will be analyzed later.
11854       Vars.push_back(DE);
11855       SrcExprs.push_back(nullptr);
11856       DstExprs.push_back(nullptr);
11857       AssignmentOps.push_back(nullptr);
11858       continue;
11859     }
11860 
11861     // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
11862     //  A list item that appears in a copyin clause must be threadprivate.
11863     if (!DSAStack->isThreadPrivate(VD)) {
11864       Diag(ELoc, diag::err_omp_required_access)
11865           << getOpenMPClauseName(OMPC_copyin)
11866           << getOpenMPDirectiveName(OMPD_threadprivate);
11867       continue;
11868     }
11869 
11870     // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
11871     //  A variable of class type (or array thereof) that appears in a
11872     //  copyin clause requires an accessible, unambiguous copy assignment
11873     //  operator for the class type.
11874     QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
11875     VarDecl *SrcVD =
11876         buildVarDecl(*this, DE->getBeginLoc(), ElemType.getUnqualifiedType(),
11877                      ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
11878     DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(
11879         *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
11880     VarDecl *DstVD =
11881         buildVarDecl(*this, DE->getBeginLoc(), ElemType, ".copyin.dst",
11882                      VD->hasAttrs() ? &VD->getAttrs() : nullptr);
11883     DeclRefExpr *PseudoDstExpr =
11884         buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
11885     // For arrays generate assignment operation for single element and replace
11886     // it by the original array element in CodeGen.
11887     ExprResult AssignmentOp =
11888         BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign, PseudoDstExpr,
11889                    PseudoSrcExpr);
11890     if (AssignmentOp.isInvalid())
11891       continue;
11892     AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
11893                                        /*DiscardedValue*/ false);
11894     if (AssignmentOp.isInvalid())
11895       continue;
11896 
11897     DSAStack->addDSA(VD, DE, OMPC_copyin);
11898     Vars.push_back(DE);
11899     SrcExprs.push_back(PseudoSrcExpr);
11900     DstExprs.push_back(PseudoDstExpr);
11901     AssignmentOps.push_back(AssignmentOp.get());
11902   }
11903 
11904   if (Vars.empty())
11905     return nullptr;
11906 
11907   return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
11908                                  SrcExprs, DstExprs, AssignmentOps);
11909 }
11910 
11911 OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
11912                                               SourceLocation StartLoc,
11913                                               SourceLocation LParenLoc,
11914                                               SourceLocation EndLoc) {
11915   SmallVector<Expr *, 8> Vars;
11916   SmallVector<Expr *, 8> SrcExprs;
11917   SmallVector<Expr *, 8> DstExprs;
11918   SmallVector<Expr *, 8> AssignmentOps;
11919   for (Expr *RefExpr : VarList) {
11920     assert(RefExpr && "NULL expr in OpenMP linear clause.");
11921     SourceLocation ELoc;
11922     SourceRange ERange;
11923     Expr *SimpleRefExpr = RefExpr;
11924     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
11925     if (Res.second) {
11926       // It will be analyzed later.
11927       Vars.push_back(RefExpr);
11928       SrcExprs.push_back(nullptr);
11929       DstExprs.push_back(nullptr);
11930       AssignmentOps.push_back(nullptr);
11931     }
11932     ValueDecl *D = Res.first;
11933     if (!D)
11934       continue;
11935 
11936     QualType Type = D->getType();
11937     auto *VD = dyn_cast<VarDecl>(D);
11938 
11939     // OpenMP [2.14.4.2, Restrictions, p.2]
11940     //  A list item that appears in a copyprivate clause may not appear in a
11941     //  private or firstprivate clause on the single construct.
11942     if (!VD || !DSAStack->isThreadPrivate(VD)) {
11943       DSAStackTy::DSAVarData DVar =
11944           DSAStack->getTopDSA(D, /*FromParent=*/false);
11945       if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
11946           DVar.RefExpr) {
11947         Diag(ELoc, diag::err_omp_wrong_dsa)
11948             << getOpenMPClauseName(DVar.CKind)
11949             << getOpenMPClauseName(OMPC_copyprivate);
11950         reportOriginalDsa(*this, DSAStack, D, DVar);
11951         continue;
11952       }
11953 
11954       // OpenMP [2.11.4.2, Restrictions, p.1]
11955       //  All list items that appear in a copyprivate clause must be either
11956       //  threadprivate or private in the enclosing context.
11957       if (DVar.CKind == OMPC_unknown) {
11958         DVar = DSAStack->getImplicitDSA(D, false);
11959         if (DVar.CKind == OMPC_shared) {
11960           Diag(ELoc, diag::err_omp_required_access)
11961               << getOpenMPClauseName(OMPC_copyprivate)
11962               << "threadprivate or private in the enclosing context";
11963           reportOriginalDsa(*this, DSAStack, D, DVar);
11964           continue;
11965         }
11966       }
11967     }
11968 
11969     // Variably modified types are not supported.
11970     if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
11971       Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
11972           << getOpenMPClauseName(OMPC_copyprivate) << Type
11973           << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
11974       bool IsDecl =
11975           !VD ||
11976           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
11977       Diag(D->getLocation(),
11978            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
11979           << D;
11980       continue;
11981     }
11982 
11983     // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
11984     //  A variable of class type (or array thereof) that appears in a
11985     //  copyin clause requires an accessible, unambiguous copy assignment
11986     //  operator for the class type.
11987     Type = Context.getBaseElementType(Type.getNonReferenceType())
11988                .getUnqualifiedType();
11989     VarDecl *SrcVD =
11990         buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.src",
11991                      D->hasAttrs() ? &D->getAttrs() : nullptr);
11992     DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
11993     VarDecl *DstVD =
11994         buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.dst",
11995                      D->hasAttrs() ? &D->getAttrs() : nullptr);
11996     DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
11997     ExprResult AssignmentOp = BuildBinOp(
11998         DSAStack->getCurScope(), ELoc, BO_Assign, PseudoDstExpr, PseudoSrcExpr);
11999     if (AssignmentOp.isInvalid())
12000       continue;
12001     AssignmentOp =
12002         ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
12003     if (AssignmentOp.isInvalid())
12004       continue;
12005 
12006     // No need to mark vars as copyprivate, they are already threadprivate or
12007     // implicitly private.
12008     assert(VD || isOpenMPCapturedDecl(D));
12009     Vars.push_back(
12010         VD ? RefExpr->IgnoreParens()
12011            : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
12012     SrcExprs.push_back(PseudoSrcExpr);
12013     DstExprs.push_back(PseudoDstExpr);
12014     AssignmentOps.push_back(AssignmentOp.get());
12015   }
12016 
12017   if (Vars.empty())
12018     return nullptr;
12019 
12020   return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
12021                                       Vars, SrcExprs, DstExprs, AssignmentOps);
12022 }
12023 
12024 OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
12025                                         SourceLocation StartLoc,
12026                                         SourceLocation LParenLoc,
12027                                         SourceLocation EndLoc) {
12028   if (VarList.empty())
12029     return nullptr;
12030 
12031   return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
12032 }
12033 
12034 OMPClause *
12035 Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
12036                               SourceLocation DepLoc, SourceLocation ColonLoc,
12037                               ArrayRef<Expr *> VarList, SourceLocation StartLoc,
12038                               SourceLocation LParenLoc, SourceLocation EndLoc) {
12039   if (DSAStack->getCurrentDirective() == OMPD_ordered &&
12040       DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
12041     Diag(DepLoc, diag::err_omp_unexpected_clause_value)
12042         << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
12043     return nullptr;
12044   }
12045   if (DSAStack->getCurrentDirective() != OMPD_ordered &&
12046       (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
12047        DepKind == OMPC_DEPEND_sink)) {
12048     unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
12049     Diag(DepLoc, diag::err_omp_unexpected_clause_value)
12050         << getListOfPossibleValues(OMPC_depend, /*First=*/0,
12051                                    /*Last=*/OMPC_DEPEND_unknown, Except)
12052         << getOpenMPClauseName(OMPC_depend);
12053     return nullptr;
12054   }
12055   SmallVector<Expr *, 8> Vars;
12056   DSAStackTy::OperatorOffsetTy OpsOffs;
12057   llvm::APSInt DepCounter(/*BitWidth=*/32);
12058   llvm::APSInt TotalDepCount(/*BitWidth=*/32);
12059   if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) {
12060     if (const Expr *OrderedCountExpr =
12061             DSAStack->getParentOrderedRegionParam().first) {
12062       TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
12063       TotalDepCount.setIsUnsigned(/*Val=*/true);
12064     }
12065   }
12066   for (Expr *RefExpr : VarList) {
12067     assert(RefExpr && "NULL expr in OpenMP shared clause.");
12068     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
12069       // It will be analyzed later.
12070       Vars.push_back(RefExpr);
12071       continue;
12072     }
12073 
12074     SourceLocation ELoc = RefExpr->getExprLoc();
12075     Expr *SimpleExpr = RefExpr->IgnoreParenCasts();
12076     if (DepKind == OMPC_DEPEND_sink) {
12077       if (DSAStack->getParentOrderedRegionParam().first &&
12078           DepCounter >= TotalDepCount) {
12079         Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
12080         continue;
12081       }
12082       ++DepCounter;
12083       // OpenMP  [2.13.9, Summary]
12084       // depend(dependence-type : vec), where dependence-type is:
12085       // 'sink' and where vec is the iteration vector, which has the form:
12086       //  x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
12087       // where n is the value specified by the ordered clause in the loop
12088       // directive, xi denotes the loop iteration variable of the i-th nested
12089       // loop associated with the loop directive, and di is a constant
12090       // non-negative integer.
12091       if (CurContext->isDependentContext()) {
12092         // It will be analyzed later.
12093         Vars.push_back(RefExpr);
12094         continue;
12095       }
12096       SimpleExpr = SimpleExpr->IgnoreImplicit();
12097       OverloadedOperatorKind OOK = OO_None;
12098       SourceLocation OOLoc;
12099       Expr *LHS = SimpleExpr;
12100       Expr *RHS = nullptr;
12101       if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
12102         OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
12103         OOLoc = BO->getOperatorLoc();
12104         LHS = BO->getLHS()->IgnoreParenImpCasts();
12105         RHS = BO->getRHS()->IgnoreParenImpCasts();
12106       } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
12107         OOK = OCE->getOperator();
12108         OOLoc = OCE->getOperatorLoc();
12109         LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
12110         RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
12111       } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
12112         OOK = MCE->getMethodDecl()
12113                   ->getNameInfo()
12114                   .getName()
12115                   .getCXXOverloadedOperator();
12116         OOLoc = MCE->getCallee()->getExprLoc();
12117         LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
12118         RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
12119       }
12120       SourceLocation ELoc;
12121       SourceRange ERange;
12122       auto Res = getPrivateItem(*this, LHS, ELoc, ERange);
12123       if (Res.second) {
12124         // It will be analyzed later.
12125         Vars.push_back(RefExpr);
12126       }
12127       ValueDecl *D = Res.first;
12128       if (!D)
12129         continue;
12130 
12131       if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
12132         Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
12133         continue;
12134       }
12135       if (RHS) {
12136         ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
12137             RHS, OMPC_depend, /*StrictlyPositive=*/false);
12138         if (RHSRes.isInvalid())
12139           continue;
12140       }
12141       if (!CurContext->isDependentContext() &&
12142           DSAStack->getParentOrderedRegionParam().first &&
12143           DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
12144         const ValueDecl *VD =
12145             DSAStack->getParentLoopControlVariable(DepCounter.getZExtValue());
12146         if (VD)
12147           Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
12148               << 1 << VD;
12149         else
12150           Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0;
12151         continue;
12152       }
12153       OpsOffs.emplace_back(RHS, OOK);
12154     } else {
12155       auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
12156       if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
12157           (ASE &&
12158            !ASE->getBase()->getType().getNonReferenceType()->isPointerType() &&
12159            !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
12160         Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
12161             << RefExpr->getSourceRange();
12162         continue;
12163       }
12164       bool Suppress = getDiagnostics().getSuppressAllDiagnostics();
12165       getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
12166       ExprResult Res =
12167           CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RefExpr->IgnoreParenImpCasts());
12168       getDiagnostics().setSuppressAllDiagnostics(Suppress);
12169       if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr)) {
12170         Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
12171             << RefExpr->getSourceRange();
12172         continue;
12173       }
12174     }
12175     Vars.push_back(RefExpr->IgnoreParenImpCasts());
12176   }
12177 
12178   if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
12179       TotalDepCount > VarList.size() &&
12180       DSAStack->getParentOrderedRegionParam().first &&
12181       DSAStack->getParentLoopControlVariable(VarList.size() + 1)) {
12182     Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
12183         << 1 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
12184   }
12185   if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
12186       Vars.empty())
12187     return nullptr;
12188 
12189   auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
12190                                     DepKind, DepLoc, ColonLoc, Vars,
12191                                     TotalDepCount.getZExtValue());
12192   if ((DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) &&
12193       DSAStack->isParentOrderedRegion())
12194     DSAStack->addDoacrossDependClause(C, OpsOffs);
12195   return C;
12196 }
12197 
12198 OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
12199                                          SourceLocation LParenLoc,
12200                                          SourceLocation EndLoc) {
12201   Expr *ValExpr = Device;
12202   Stmt *HelperValStmt = nullptr;
12203 
12204   // OpenMP [2.9.1, Restrictions]
12205   // The device expression must evaluate to a non-negative integer value.
12206   if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
12207                                  /*StrictlyPositive=*/false))
12208     return nullptr;
12209 
12210   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
12211   OpenMPDirectiveKind CaptureRegion =
12212       getOpenMPCaptureRegionForClause(DKind, OMPC_device);
12213   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
12214     ValExpr = MakeFullExpr(ValExpr).get();
12215     llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
12216     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
12217     HelperValStmt = buildPreInits(Context, Captures);
12218   }
12219 
12220   return new (Context) OMPDeviceClause(ValExpr, HelperValStmt, CaptureRegion,
12221                                        StartLoc, LParenLoc, EndLoc);
12222 }
12223 
12224 static bool checkTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
12225                               DSAStackTy *Stack, QualType QTy,
12226                               bool FullCheck = true) {
12227   NamedDecl *ND;
12228   if (QTy->isIncompleteType(&ND)) {
12229     SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
12230     return false;
12231   }
12232   if (FullCheck && !SemaRef.CurContext->isDependentContext() &&
12233       !QTy.isTrivialType(SemaRef.Context))
12234     SemaRef.Diag(SL, diag::warn_omp_non_trivial_type_mapped) << QTy << SR;
12235   return true;
12236 }
12237 
12238 /// Return true if it can be proven that the provided array expression
12239 /// (array section or array subscript) does NOT specify the whole size of the
12240 /// array whose base type is \a BaseQTy.
12241 static bool checkArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
12242                                                         const Expr *E,
12243                                                         QualType BaseQTy) {
12244   const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
12245 
12246   // If this is an array subscript, it refers to the whole size if the size of
12247   // the dimension is constant and equals 1. Also, an array section assumes the
12248   // format of an array subscript if no colon is used.
12249   if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
12250     if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
12251       return ATy->getSize().getSExtValue() != 1;
12252     // Size can't be evaluated statically.
12253     return false;
12254   }
12255 
12256   assert(OASE && "Expecting array section if not an array subscript.");
12257   const Expr *LowerBound = OASE->getLowerBound();
12258   const Expr *Length = OASE->getLength();
12259 
12260   // If there is a lower bound that does not evaluates to zero, we are not
12261   // covering the whole dimension.
12262   if (LowerBound) {
12263     Expr::EvalResult Result;
12264     if (!LowerBound->EvaluateAsInt(Result, SemaRef.getASTContext()))
12265       return false; // Can't get the integer value as a constant.
12266 
12267     llvm::APSInt ConstLowerBound = Result.Val.getInt();
12268     if (ConstLowerBound.getSExtValue())
12269       return true;
12270   }
12271 
12272   // If we don't have a length we covering the whole dimension.
12273   if (!Length)
12274     return false;
12275 
12276   // If the base is a pointer, we don't have a way to get the size of the
12277   // pointee.
12278   if (BaseQTy->isPointerType())
12279     return false;
12280 
12281   // We can only check if the length is the same as the size of the dimension
12282   // if we have a constant array.
12283   const auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
12284   if (!CATy)
12285     return false;
12286 
12287   Expr::EvalResult Result;
12288   if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
12289     return false; // Can't get the integer value as a constant.
12290 
12291   llvm::APSInt ConstLength = Result.Val.getInt();
12292   return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
12293 }
12294 
12295 // Return true if it can be proven that the provided array expression (array
12296 // section or array subscript) does NOT specify a single element of the array
12297 // whose base type is \a BaseQTy.
12298 static bool checkArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
12299                                                         const Expr *E,
12300                                                         QualType BaseQTy) {
12301   const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
12302 
12303   // An array subscript always refer to a single element. Also, an array section
12304   // assumes the format of an array subscript if no colon is used.
12305   if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
12306     return false;
12307 
12308   assert(OASE && "Expecting array section if not an array subscript.");
12309   const Expr *Length = OASE->getLength();
12310 
12311   // If we don't have a length we have to check if the array has unitary size
12312   // for this dimension. Also, we should always expect a length if the base type
12313   // is pointer.
12314   if (!Length) {
12315     if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
12316       return ATy->getSize().getSExtValue() != 1;
12317     // We cannot assume anything.
12318     return false;
12319   }
12320 
12321   // Check if the length evaluates to 1.
12322   Expr::EvalResult Result;
12323   if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
12324     return false; // Can't get the integer value as a constant.
12325 
12326   llvm::APSInt ConstLength = Result.Val.getInt();
12327   return ConstLength.getSExtValue() != 1;
12328 }
12329 
12330 // Return the expression of the base of the mappable expression or null if it
12331 // cannot be determined and do all the necessary checks to see if the expression
12332 // is valid as a standalone mappable expression. In the process, record all the
12333 // components of the expression.
12334 static const Expr *checkMapClauseExpressionBase(
12335     Sema &SemaRef, Expr *E,
12336     OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
12337     OpenMPClauseKind CKind, bool NoDiagnose) {
12338   SourceLocation ELoc = E->getExprLoc();
12339   SourceRange ERange = E->getSourceRange();
12340 
12341   // The base of elements of list in a map clause have to be either:
12342   //  - a reference to variable or field.
12343   //  - a member expression.
12344   //  - an array expression.
12345   //
12346   // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
12347   // reference to 'r'.
12348   //
12349   // If we have:
12350   //
12351   // struct SS {
12352   //   Bla S;
12353   //   foo() {
12354   //     #pragma omp target map (S.Arr[:12]);
12355   //   }
12356   // }
12357   //
12358   // We want to retrieve the member expression 'this->S';
12359 
12360   const Expr *RelevantExpr = nullptr;
12361 
12362   // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
12363   //  If a list item is an array section, it must specify contiguous storage.
12364   //
12365   // For this restriction it is sufficient that we make sure only references
12366   // to variables or fields and array expressions, and that no array sections
12367   // exist except in the rightmost expression (unless they cover the whole
12368   // dimension of the array). E.g. these would be invalid:
12369   //
12370   //   r.ArrS[3:5].Arr[6:7]
12371   //
12372   //   r.ArrS[3:5].x
12373   //
12374   // but these would be valid:
12375   //   r.ArrS[3].Arr[6:7]
12376   //
12377   //   r.ArrS[3].x
12378 
12379   bool AllowUnitySizeArraySection = true;
12380   bool AllowWholeSizeArraySection = true;
12381 
12382   while (!RelevantExpr) {
12383     E = E->IgnoreParenImpCasts();
12384 
12385     if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
12386       if (!isa<VarDecl>(CurE->getDecl()))
12387         return nullptr;
12388 
12389       RelevantExpr = CurE;
12390 
12391       // If we got a reference to a declaration, we should not expect any array
12392       // section before that.
12393       AllowUnitySizeArraySection = false;
12394       AllowWholeSizeArraySection = false;
12395 
12396       // Record the component.
12397       CurComponents.emplace_back(CurE, CurE->getDecl());
12398     } else if (auto *CurE = dyn_cast<MemberExpr>(E)) {
12399       Expr *BaseE = CurE->getBase()->IgnoreParenImpCasts();
12400 
12401       if (isa<CXXThisExpr>(BaseE))
12402         // We found a base expression: this->Val.
12403         RelevantExpr = CurE;
12404       else
12405         E = BaseE;
12406 
12407       if (!isa<FieldDecl>(CurE->getMemberDecl())) {
12408         if (!NoDiagnose) {
12409           SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
12410               << CurE->getSourceRange();
12411           return nullptr;
12412         }
12413         if (RelevantExpr)
12414           return nullptr;
12415         continue;
12416       }
12417 
12418       auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
12419 
12420       // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
12421       //  A bit-field cannot appear in a map clause.
12422       //
12423       if (FD->isBitField()) {
12424         if (!NoDiagnose) {
12425           SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
12426               << CurE->getSourceRange() << getOpenMPClauseName(CKind);
12427           return nullptr;
12428         }
12429         if (RelevantExpr)
12430           return nullptr;
12431         continue;
12432       }
12433 
12434       // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
12435       //  If the type of a list item is a reference to a type T then the type
12436       //  will be considered to be T for all purposes of this clause.
12437       QualType CurType = BaseE->getType().getNonReferenceType();
12438 
12439       // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
12440       //  A list item cannot be a variable that is a member of a structure with
12441       //  a union type.
12442       //
12443       if (CurType->isUnionType()) {
12444         if (!NoDiagnose) {
12445           SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
12446               << CurE->getSourceRange();
12447           return nullptr;
12448         }
12449         continue;
12450       }
12451 
12452       // If we got a member expression, we should not expect any array section
12453       // before that:
12454       //
12455       // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
12456       //  If a list item is an element of a structure, only the rightmost symbol
12457       //  of the variable reference can be an array section.
12458       //
12459       AllowUnitySizeArraySection = false;
12460       AllowWholeSizeArraySection = false;
12461 
12462       // Record the component.
12463       CurComponents.emplace_back(CurE, FD);
12464     } else if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
12465       E = CurE->getBase()->IgnoreParenImpCasts();
12466 
12467       if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
12468         if (!NoDiagnose) {
12469           SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
12470               << 0 << CurE->getSourceRange();
12471           return nullptr;
12472         }
12473         continue;
12474       }
12475 
12476       // If we got an array subscript that express the whole dimension we
12477       // can have any array expressions before. If it only expressing part of
12478       // the dimension, we can only have unitary-size array expressions.
12479       if (checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
12480                                                       E->getType()))
12481         AllowWholeSizeArraySection = false;
12482 
12483       if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
12484         Expr::EvalResult Result;
12485         if (CurE->getIdx()->EvaluateAsInt(Result, SemaRef.getASTContext())) {
12486           if (!Result.Val.getInt().isNullValue()) {
12487             SemaRef.Diag(CurE->getIdx()->getExprLoc(),
12488                          diag::err_omp_invalid_map_this_expr);
12489             SemaRef.Diag(CurE->getIdx()->getExprLoc(),
12490                          diag::note_omp_invalid_subscript_on_this_ptr_map);
12491           }
12492         }
12493         RelevantExpr = TE;
12494       }
12495 
12496       // Record the component - we don't have any declaration associated.
12497       CurComponents.emplace_back(CurE, nullptr);
12498     } else if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
12499       assert(!NoDiagnose && "Array sections cannot be implicitly mapped.");
12500       E = CurE->getBase()->IgnoreParenImpCasts();
12501 
12502       QualType CurType =
12503           OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
12504 
12505       // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
12506       //  If the type of a list item is a reference to a type T then the type
12507       //  will be considered to be T for all purposes of this clause.
12508       if (CurType->isReferenceType())
12509         CurType = CurType->getPointeeType();
12510 
12511       bool IsPointer = CurType->isAnyPointerType();
12512 
12513       if (!IsPointer && !CurType->isArrayType()) {
12514         SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
12515             << 0 << CurE->getSourceRange();
12516         return nullptr;
12517       }
12518 
12519       bool NotWhole =
12520           checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
12521       bool NotUnity =
12522           checkArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
12523 
12524       if (AllowWholeSizeArraySection) {
12525         // Any array section is currently allowed. Allowing a whole size array
12526         // section implies allowing a unity array section as well.
12527         //
12528         // If this array section refers to the whole dimension we can still
12529         // accept other array sections before this one, except if the base is a
12530         // pointer. Otherwise, only unitary sections are accepted.
12531         if (NotWhole || IsPointer)
12532           AllowWholeSizeArraySection = false;
12533       } else if (AllowUnitySizeArraySection && NotUnity) {
12534         // A unity or whole array section is not allowed and that is not
12535         // compatible with the properties of the current array section.
12536         SemaRef.Diag(
12537             ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
12538             << CurE->getSourceRange();
12539         return nullptr;
12540       }
12541 
12542       if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
12543         Expr::EvalResult ResultR;
12544         Expr::EvalResult ResultL;
12545         if (CurE->getLength()->EvaluateAsInt(ResultR,
12546                                              SemaRef.getASTContext())) {
12547           if (!ResultR.Val.getInt().isOneValue()) {
12548             SemaRef.Diag(CurE->getLength()->getExprLoc(),
12549                          diag::err_omp_invalid_map_this_expr);
12550             SemaRef.Diag(CurE->getLength()->getExprLoc(),
12551                          diag::note_omp_invalid_length_on_this_ptr_mapping);
12552           }
12553         }
12554         if (CurE->getLowerBound() && CurE->getLowerBound()->EvaluateAsInt(
12555                                         ResultL, SemaRef.getASTContext())) {
12556           if (!ResultL.Val.getInt().isNullValue()) {
12557             SemaRef.Diag(CurE->getLowerBound()->getExprLoc(),
12558                          diag::err_omp_invalid_map_this_expr);
12559             SemaRef.Diag(CurE->getLowerBound()->getExprLoc(),
12560                          diag::note_omp_invalid_lower_bound_on_this_ptr_mapping);
12561           }
12562         }
12563         RelevantExpr = TE;
12564       }
12565 
12566       // Record the component - we don't have any declaration associated.
12567       CurComponents.emplace_back(CurE, nullptr);
12568     } else {
12569       if (!NoDiagnose) {
12570         // If nothing else worked, this is not a valid map clause expression.
12571         SemaRef.Diag(
12572             ELoc, diag::err_omp_expected_named_var_member_or_array_expression)
12573             << ERange;
12574       }
12575       return nullptr;
12576     }
12577   }
12578 
12579   return RelevantExpr;
12580 }
12581 
12582 // Return true if expression E associated with value VD has conflicts with other
12583 // map information.
12584 static bool checkMapConflicts(
12585     Sema &SemaRef, DSAStackTy *DSAS, const ValueDecl *VD, const Expr *E,
12586     bool CurrentRegionOnly,
12587     OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
12588     OpenMPClauseKind CKind) {
12589   assert(VD && E);
12590   SourceLocation ELoc = E->getExprLoc();
12591   SourceRange ERange = E->getSourceRange();
12592 
12593   // In order to easily check the conflicts we need to match each component of
12594   // the expression under test with the components of the expressions that are
12595   // already in the stack.
12596 
12597   assert(!CurComponents.empty() && "Map clause expression with no components!");
12598   assert(CurComponents.back().getAssociatedDeclaration() == VD &&
12599          "Map clause expression with unexpected base!");
12600 
12601   // Variables to help detecting enclosing problems in data environment nests.
12602   bool IsEnclosedByDataEnvironmentExpr = false;
12603   const Expr *EnclosingExpr = nullptr;
12604 
12605   bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
12606       VD, CurrentRegionOnly,
12607       [&IsEnclosedByDataEnvironmentExpr, &SemaRef, VD, CurrentRegionOnly, ELoc,
12608        ERange, CKind, &EnclosingExpr,
12609        CurComponents](OMPClauseMappableExprCommon::MappableExprComponentListRef
12610                           StackComponents,
12611                       OpenMPClauseKind) {
12612         assert(!StackComponents.empty() &&
12613                "Map clause expression with no components!");
12614         assert(StackComponents.back().getAssociatedDeclaration() == VD &&
12615                "Map clause expression with unexpected base!");
12616         (void)VD;
12617 
12618         // The whole expression in the stack.
12619         const Expr *RE = StackComponents.front().getAssociatedExpression();
12620 
12621         // Expressions must start from the same base. Here we detect at which
12622         // point both expressions diverge from each other and see if we can
12623         // detect if the memory referred to both expressions is contiguous and
12624         // do not overlap.
12625         auto CI = CurComponents.rbegin();
12626         auto CE = CurComponents.rend();
12627         auto SI = StackComponents.rbegin();
12628         auto SE = StackComponents.rend();
12629         for (; CI != CE && SI != SE; ++CI, ++SI) {
12630 
12631           // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
12632           //  At most one list item can be an array item derived from a given
12633           //  variable in map clauses of the same construct.
12634           if (CurrentRegionOnly &&
12635               (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
12636                isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
12637               (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
12638                isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
12639             SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
12640                          diag::err_omp_multiple_array_items_in_map_clause)
12641                 << CI->getAssociatedExpression()->getSourceRange();
12642             SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
12643                          diag::note_used_here)
12644                 << SI->getAssociatedExpression()->getSourceRange();
12645             return true;
12646           }
12647 
12648           // Do both expressions have the same kind?
12649           if (CI->getAssociatedExpression()->getStmtClass() !=
12650               SI->getAssociatedExpression()->getStmtClass())
12651             break;
12652 
12653           // Are we dealing with different variables/fields?
12654           if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
12655             break;
12656         }
12657         // Check if the extra components of the expressions in the enclosing
12658         // data environment are redundant for the current base declaration.
12659         // If they are, the maps completely overlap, which is legal.
12660         for (; SI != SE; ++SI) {
12661           QualType Type;
12662           if (const auto *ASE =
12663                   dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
12664             Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
12665           } else if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(
12666                          SI->getAssociatedExpression())) {
12667             const Expr *E = OASE->getBase()->IgnoreParenImpCasts();
12668             Type =
12669                 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
12670           }
12671           if (Type.isNull() || Type->isAnyPointerType() ||
12672               checkArrayExpressionDoesNotReferToWholeSize(
12673                   SemaRef, SI->getAssociatedExpression(), Type))
12674             break;
12675         }
12676 
12677         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
12678         //  List items of map clauses in the same construct must not share
12679         //  original storage.
12680         //
12681         // If the expressions are exactly the same or one is a subset of the
12682         // other, it means they are sharing storage.
12683         if (CI == CE && SI == SE) {
12684           if (CurrentRegionOnly) {
12685             if (CKind == OMPC_map) {
12686               SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
12687             } else {
12688               assert(CKind == OMPC_to || CKind == OMPC_from);
12689               SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
12690                   << ERange;
12691             }
12692             SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
12693                 << RE->getSourceRange();
12694             return true;
12695           }
12696           // If we find the same expression in the enclosing data environment,
12697           // that is legal.
12698           IsEnclosedByDataEnvironmentExpr = true;
12699           return false;
12700         }
12701 
12702         QualType DerivedType =
12703             std::prev(CI)->getAssociatedDeclaration()->getType();
12704         SourceLocation DerivedLoc =
12705             std::prev(CI)->getAssociatedExpression()->getExprLoc();
12706 
12707         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
12708         //  If the type of a list item is a reference to a type T then the type
12709         //  will be considered to be T for all purposes of this clause.
12710         DerivedType = DerivedType.getNonReferenceType();
12711 
12712         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
12713         //  A variable for which the type is pointer and an array section
12714         //  derived from that variable must not appear as list items of map
12715         //  clauses of the same construct.
12716         //
12717         // Also, cover one of the cases in:
12718         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
12719         //  If any part of the original storage of a list item has corresponding
12720         //  storage in the device data environment, all of the original storage
12721         //  must have corresponding storage in the device data environment.
12722         //
12723         if (DerivedType->isAnyPointerType()) {
12724           if (CI == CE || SI == SE) {
12725             SemaRef.Diag(
12726                 DerivedLoc,
12727                 diag::err_omp_pointer_mapped_along_with_derived_section)
12728                 << DerivedLoc;
12729             SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
12730                 << RE->getSourceRange();
12731             return true;
12732           }
12733           if (CI->getAssociatedExpression()->getStmtClass() !=
12734                          SI->getAssociatedExpression()->getStmtClass() ||
12735                      CI->getAssociatedDeclaration()->getCanonicalDecl() ==
12736                          SI->getAssociatedDeclaration()->getCanonicalDecl()) {
12737             assert(CI != CE && SI != SE);
12738             SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_dereferenced)
12739                 << DerivedLoc;
12740             SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
12741                 << RE->getSourceRange();
12742             return true;
12743           }
12744         }
12745 
12746         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
12747         //  List items of map clauses in the same construct must not share
12748         //  original storage.
12749         //
12750         // An expression is a subset of the other.
12751         if (CurrentRegionOnly && (CI == CE || SI == SE)) {
12752           if (CKind == OMPC_map) {
12753             if (CI != CE || SI != SE) {
12754               // Allow constructs like this: map(s, s.ptr[0:1]), where s.ptr is
12755               // a pointer.
12756               auto Begin =
12757                   CI != CE ? CurComponents.begin() : StackComponents.begin();
12758               auto End = CI != CE ? CurComponents.end() : StackComponents.end();
12759               auto It = Begin;
12760               while (It != End && !It->getAssociatedDeclaration())
12761                 std::advance(It, 1);
12762               assert(It != End &&
12763                      "Expected at least one component with the declaration.");
12764               if (It != Begin && It->getAssociatedDeclaration()
12765                                      ->getType()
12766                                      .getCanonicalType()
12767                                      ->isAnyPointerType()) {
12768                 IsEnclosedByDataEnvironmentExpr = false;
12769                 EnclosingExpr = nullptr;
12770                 return false;
12771               }
12772             }
12773             SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
12774           } else {
12775             assert(CKind == OMPC_to || CKind == OMPC_from);
12776             SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
12777                 << ERange;
12778           }
12779           SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
12780               << RE->getSourceRange();
12781           return true;
12782         }
12783 
12784         // The current expression uses the same base as other expression in the
12785         // data environment but does not contain it completely.
12786         if (!CurrentRegionOnly && SI != SE)
12787           EnclosingExpr = RE;
12788 
12789         // The current expression is a subset of the expression in the data
12790         // environment.
12791         IsEnclosedByDataEnvironmentExpr |=
12792             (!CurrentRegionOnly && CI != CE && SI == SE);
12793 
12794         return false;
12795       });
12796 
12797   if (CurrentRegionOnly)
12798     return FoundError;
12799 
12800   // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
12801   //  If any part of the original storage of a list item has corresponding
12802   //  storage in the device data environment, all of the original storage must
12803   //  have corresponding storage in the device data environment.
12804   // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
12805   //  If a list item is an element of a structure, and a different element of
12806   //  the structure has a corresponding list item in the device data environment
12807   //  prior to a task encountering the construct associated with the map clause,
12808   //  then the list item must also have a corresponding list item in the device
12809   //  data environment prior to the task encountering the construct.
12810   //
12811   if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
12812     SemaRef.Diag(ELoc,
12813                  diag::err_omp_original_storage_is_shared_and_does_not_contain)
12814         << ERange;
12815     SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
12816         << EnclosingExpr->getSourceRange();
12817     return true;
12818   }
12819 
12820   return FoundError;
12821 }
12822 
12823 namespace {
12824 // Utility struct that gathers all the related lists associated with a mappable
12825 // expression.
12826 struct MappableVarListInfo {
12827   // The list of expressions.
12828   ArrayRef<Expr *> VarList;
12829   // The list of processed expressions.
12830   SmallVector<Expr *, 16> ProcessedVarList;
12831   // The mappble components for each expression.
12832   OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
12833   // The base declaration of the variable.
12834   SmallVector<ValueDecl *, 16> VarBaseDeclarations;
12835 
12836   MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
12837     // We have a list of components and base declarations for each entry in the
12838     // variable list.
12839     VarComponents.reserve(VarList.size());
12840     VarBaseDeclarations.reserve(VarList.size());
12841   }
12842 };
12843 }
12844 
12845 // Check the validity of the provided variable list for the provided clause kind
12846 // \a CKind. In the check process the valid expressions, and mappable expression
12847 // components and variables are extracted and used to fill \a Vars,
12848 // \a ClauseComponents, and \a ClauseBaseDeclarations. \a MapType and
12849 // \a IsMapTypeImplicit are expected to be valid if the clause kind is 'map'.
12850 static void
12851 checkMappableExpressionList(Sema &SemaRef, DSAStackTy *DSAS,
12852                             OpenMPClauseKind CKind, MappableVarListInfo &MVLI,
12853                             SourceLocation StartLoc,
12854                             OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
12855                             bool IsMapTypeImplicit = false) {
12856   // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
12857   assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
12858          "Unexpected clause kind with mappable expressions!");
12859 
12860   // Keep track of the mappable components and base declarations in this clause.
12861   // Each entry in the list is going to have a list of components associated. We
12862   // record each set of the components so that we can build the clause later on.
12863   // In the end we should have the same amount of declarations and component
12864   // lists.
12865 
12866   for (Expr *RE : MVLI.VarList) {
12867     assert(RE && "Null expr in omp to/from/map clause");
12868     SourceLocation ELoc = RE->getExprLoc();
12869 
12870     const Expr *VE = RE->IgnoreParenLValueCasts();
12871 
12872     if (VE->isValueDependent() || VE->isTypeDependent() ||
12873         VE->isInstantiationDependent() ||
12874         VE->containsUnexpandedParameterPack()) {
12875       // We can only analyze this information once the missing information is
12876       // resolved.
12877       MVLI.ProcessedVarList.push_back(RE);
12878       continue;
12879     }
12880 
12881     Expr *SimpleExpr = RE->IgnoreParenCasts();
12882 
12883     if (!RE->IgnoreParenImpCasts()->isLValue()) {
12884       SemaRef.Diag(ELoc,
12885                    diag::err_omp_expected_named_var_member_or_array_expression)
12886           << RE->getSourceRange();
12887       continue;
12888     }
12889 
12890     OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
12891     ValueDecl *CurDeclaration = nullptr;
12892 
12893     // Obtain the array or member expression bases if required. Also, fill the
12894     // components array with all the components identified in the process.
12895     const Expr *BE = checkMapClauseExpressionBase(
12896         SemaRef, SimpleExpr, CurComponents, CKind, /*NoDiagnose=*/false);
12897     if (!BE)
12898       continue;
12899 
12900     assert(!CurComponents.empty() &&
12901            "Invalid mappable expression information.");
12902 
12903     if (const auto *TE = dyn_cast<CXXThisExpr>(BE)) {
12904       // Add store "this" pointer to class in DSAStackTy for future checking
12905       DSAS->addMappedClassesQualTypes(TE->getType());
12906       // Skip restriction checking for variable or field declarations
12907       MVLI.ProcessedVarList.push_back(RE);
12908       MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
12909       MVLI.VarComponents.back().append(CurComponents.begin(),
12910                                        CurComponents.end());
12911       MVLI.VarBaseDeclarations.push_back(nullptr);
12912       continue;
12913     }
12914 
12915     // For the following checks, we rely on the base declaration which is
12916     // expected to be associated with the last component. The declaration is
12917     // expected to be a variable or a field (if 'this' is being mapped).
12918     CurDeclaration = CurComponents.back().getAssociatedDeclaration();
12919     assert(CurDeclaration && "Null decl on map clause.");
12920     assert(
12921         CurDeclaration->isCanonicalDecl() &&
12922         "Expecting components to have associated only canonical declarations.");
12923 
12924     auto *VD = dyn_cast<VarDecl>(CurDeclaration);
12925     const auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
12926 
12927     assert((VD || FD) && "Only variables or fields are expected here!");
12928     (void)FD;
12929 
12930     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
12931     // threadprivate variables cannot appear in a map clause.
12932     // OpenMP 4.5 [2.10.5, target update Construct]
12933     // threadprivate variables cannot appear in a from clause.
12934     if (VD && DSAS->isThreadPrivate(VD)) {
12935       DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
12936       SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
12937           << getOpenMPClauseName(CKind);
12938       reportOriginalDsa(SemaRef, DSAS, VD, DVar);
12939       continue;
12940     }
12941 
12942     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
12943     //  A list item cannot appear in both a map clause and a data-sharing
12944     //  attribute clause on the same construct.
12945 
12946     // Check conflicts with other map clause expressions. We check the conflicts
12947     // with the current construct separately from the enclosing data
12948     // environment, because the restrictions are different. We only have to
12949     // check conflicts across regions for the map clauses.
12950     if (checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
12951                           /*CurrentRegionOnly=*/true, CurComponents, CKind))
12952       break;
12953     if (CKind == OMPC_map &&
12954         checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
12955                           /*CurrentRegionOnly=*/false, CurComponents, CKind))
12956       break;
12957 
12958     // OpenMP 4.5 [2.10.5, target update Construct]
12959     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
12960     //  If the type of a list item is a reference to a type T then the type will
12961     //  be considered to be T for all purposes of this clause.
12962     auto I = llvm::find_if(
12963         CurComponents,
12964         [](const OMPClauseMappableExprCommon::MappableComponent &MC) {
12965           return MC.getAssociatedDeclaration();
12966         });
12967     assert(I != CurComponents.end() && "Null decl on map clause.");
12968     QualType Type =
12969         I->getAssociatedDeclaration()->getType().getNonReferenceType();
12970 
12971     // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
12972     // A list item in a to or from clause must have a mappable type.
12973     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
12974     //  A list item must have a mappable type.
12975     if (!checkTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
12976                            DSAS, Type))
12977       continue;
12978 
12979     if (CKind == OMPC_map) {
12980       // target enter data
12981       // OpenMP [2.10.2, Restrictions, p. 99]
12982       // A map-type must be specified in all map clauses and must be either
12983       // to or alloc.
12984       OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
12985       if (DKind == OMPD_target_enter_data &&
12986           !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
12987         SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
12988             << (IsMapTypeImplicit ? 1 : 0)
12989             << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
12990             << getOpenMPDirectiveName(DKind);
12991         continue;
12992       }
12993 
12994       // target exit_data
12995       // OpenMP [2.10.3, Restrictions, p. 102]
12996       // A map-type must be specified in all map clauses and must be either
12997       // from, release, or delete.
12998       if (DKind == OMPD_target_exit_data &&
12999           !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
13000             MapType == OMPC_MAP_delete)) {
13001         SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
13002             << (IsMapTypeImplicit ? 1 : 0)
13003             << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
13004             << getOpenMPDirectiveName(DKind);
13005         continue;
13006       }
13007 
13008       // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
13009       // A list item cannot appear in both a map clause and a data-sharing
13010       // attribute clause on the same construct
13011       if (VD && isOpenMPTargetExecutionDirective(DKind)) {
13012         DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
13013         if (isOpenMPPrivate(DVar.CKind)) {
13014           SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
13015               << getOpenMPClauseName(DVar.CKind)
13016               << getOpenMPClauseName(OMPC_map)
13017               << getOpenMPDirectiveName(DSAS->getCurrentDirective());
13018           reportOriginalDsa(SemaRef, DSAS, CurDeclaration, DVar);
13019           continue;
13020         }
13021       }
13022     }
13023 
13024     // Save the current expression.
13025     MVLI.ProcessedVarList.push_back(RE);
13026 
13027     // Store the components in the stack so that they can be used to check
13028     // against other clauses later on.
13029     DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
13030                                           /*WhereFoundClauseKind=*/OMPC_map);
13031 
13032     // Save the components and declaration to create the clause. For purposes of
13033     // the clause creation, any component list that has has base 'this' uses
13034     // null as base declaration.
13035     MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
13036     MVLI.VarComponents.back().append(CurComponents.begin(),
13037                                      CurComponents.end());
13038     MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
13039                                                            : CurDeclaration);
13040   }
13041 }
13042 
13043 OMPClause *
13044 Sema::ActOnOpenMPMapClause(ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
13045                            ArrayRef<SourceLocation> MapTypeModifiersLoc,
13046                            OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
13047                            SourceLocation MapLoc, SourceLocation ColonLoc,
13048                            ArrayRef<Expr *> VarList, SourceLocation StartLoc,
13049                            SourceLocation LParenLoc, SourceLocation EndLoc) {
13050   MappableVarListInfo MVLI(VarList);
13051   checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, StartLoc,
13052                               MapType, IsMapTypeImplicit);
13053 
13054   OpenMPMapModifierKind Modifiers[] = { OMPC_MAP_MODIFIER_unknown,
13055                                         OMPC_MAP_MODIFIER_unknown };
13056   SourceLocation ModifiersLoc[OMPMapClause::NumberOfModifiers];
13057 
13058   // Process map-type-modifiers, flag errors for duplicate modifiers.
13059   unsigned Count = 0;
13060   for (unsigned I = 0, E = MapTypeModifiers.size(); I < E; ++I) {
13061     if (MapTypeModifiers[I] != OMPC_MAP_MODIFIER_unknown &&
13062         llvm::find(Modifiers, MapTypeModifiers[I]) != std::end(Modifiers)) {
13063       Diag(MapTypeModifiersLoc[I], diag::err_omp_duplicate_map_type_modifier);
13064       continue;
13065     }
13066     assert(Count < OMPMapClause::NumberOfModifiers &&
13067            "Modifiers exceed the allowed number of map type modifiers");
13068     Modifiers[Count] = MapTypeModifiers[I];
13069     ModifiersLoc[Count] = MapTypeModifiersLoc[I];
13070     ++Count;
13071   }
13072 
13073   // We need to produce a map clause even if we don't have variables so that
13074   // other diagnostics related with non-existing map clauses are accurate.
13075   return OMPMapClause::Create(Context, StartLoc, LParenLoc, EndLoc,
13076                               MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
13077                               MVLI.VarComponents, Modifiers, ModifiersLoc,
13078                               MapType, IsMapTypeImplicit, MapLoc);
13079 }
13080 
13081 QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
13082                                                TypeResult ParsedType) {
13083   assert(ParsedType.isUsable());
13084 
13085   QualType ReductionType = GetTypeFromParser(ParsedType.get());
13086   if (ReductionType.isNull())
13087     return QualType();
13088 
13089   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
13090   // A type name in a declare reduction directive cannot be a function type, an
13091   // array type, a reference type, or a type qualified with const, volatile or
13092   // restrict.
13093   if (ReductionType.hasQualifiers()) {
13094     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
13095     return QualType();
13096   }
13097 
13098   if (ReductionType->isFunctionType()) {
13099     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
13100     return QualType();
13101   }
13102   if (ReductionType->isReferenceType()) {
13103     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
13104     return QualType();
13105   }
13106   if (ReductionType->isArrayType()) {
13107     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
13108     return QualType();
13109   }
13110   return ReductionType;
13111 }
13112 
13113 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
13114     Scope *S, DeclContext *DC, DeclarationName Name,
13115     ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
13116     AccessSpecifier AS, Decl *PrevDeclInScope) {
13117   SmallVector<Decl *, 8> Decls;
13118   Decls.reserve(ReductionTypes.size());
13119 
13120   LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
13121                       forRedeclarationInCurContext());
13122   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
13123   // A reduction-identifier may not be re-declared in the current scope for the
13124   // same type or for a type that is compatible according to the base language
13125   // rules.
13126   llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
13127   OMPDeclareReductionDecl *PrevDRD = nullptr;
13128   bool InCompoundScope = true;
13129   if (S != nullptr) {
13130     // Find previous declaration with the same name not referenced in other
13131     // declarations.
13132     FunctionScopeInfo *ParentFn = getEnclosingFunction();
13133     InCompoundScope =
13134         (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
13135     LookupName(Lookup, S);
13136     FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
13137                          /*AllowInlineNamespace=*/false);
13138     llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
13139     LookupResult::Filter Filter = Lookup.makeFilter();
13140     while (Filter.hasNext()) {
13141       auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
13142       if (InCompoundScope) {
13143         auto I = UsedAsPrevious.find(PrevDecl);
13144         if (I == UsedAsPrevious.end())
13145           UsedAsPrevious[PrevDecl] = false;
13146         if (OMPDeclareReductionDecl *D = PrevDecl->getPrevDeclInScope())
13147           UsedAsPrevious[D] = true;
13148       }
13149       PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
13150           PrevDecl->getLocation();
13151     }
13152     Filter.done();
13153     if (InCompoundScope) {
13154       for (const auto &PrevData : UsedAsPrevious) {
13155         if (!PrevData.second) {
13156           PrevDRD = PrevData.first;
13157           break;
13158         }
13159       }
13160     }
13161   } else if (PrevDeclInScope != nullptr) {
13162     auto *PrevDRDInScope = PrevDRD =
13163         cast<OMPDeclareReductionDecl>(PrevDeclInScope);
13164     do {
13165       PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
13166           PrevDRDInScope->getLocation();
13167       PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
13168     } while (PrevDRDInScope != nullptr);
13169   }
13170   for (const auto &TyData : ReductionTypes) {
13171     const auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
13172     bool Invalid = false;
13173     if (I != PreviousRedeclTypes.end()) {
13174       Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
13175           << TyData.first;
13176       Diag(I->second, diag::note_previous_definition);
13177       Invalid = true;
13178     }
13179     PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
13180     auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
13181                                                 Name, TyData.first, PrevDRD);
13182     DC->addDecl(DRD);
13183     DRD->setAccess(AS);
13184     Decls.push_back(DRD);
13185     if (Invalid)
13186       DRD->setInvalidDecl();
13187     else
13188       PrevDRD = DRD;
13189   }
13190 
13191   return DeclGroupPtrTy::make(
13192       DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
13193 }
13194 
13195 void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
13196   auto *DRD = cast<OMPDeclareReductionDecl>(D);
13197 
13198   // Enter new function scope.
13199   PushFunctionScope();
13200   setFunctionHasBranchProtectedScope();
13201   getCurFunction()->setHasOMPDeclareReductionCombiner();
13202 
13203   if (S != nullptr)
13204     PushDeclContext(S, DRD);
13205   else
13206     CurContext = DRD;
13207 
13208   PushExpressionEvaluationContext(
13209       ExpressionEvaluationContext::PotentiallyEvaluated);
13210 
13211   QualType ReductionType = DRD->getType();
13212   // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
13213   // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
13214   // uses semantics of argument handles by value, but it should be passed by
13215   // reference. C lang does not support references, so pass all parameters as
13216   // pointers.
13217   // Create 'T omp_in;' variable.
13218   VarDecl *OmpInParm =
13219       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
13220   // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
13221   // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
13222   // uses semantics of argument handles by value, but it should be passed by
13223   // reference. C lang does not support references, so pass all parameters as
13224   // pointers.
13225   // Create 'T omp_out;' variable.
13226   VarDecl *OmpOutParm =
13227       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
13228   if (S != nullptr) {
13229     PushOnScopeChains(OmpInParm, S);
13230     PushOnScopeChains(OmpOutParm, S);
13231   } else {
13232     DRD->addDecl(OmpInParm);
13233     DRD->addDecl(OmpOutParm);
13234   }
13235   Expr *InE =
13236       ::buildDeclRefExpr(*this, OmpInParm, ReductionType, D->getLocation());
13237   Expr *OutE =
13238       ::buildDeclRefExpr(*this, OmpOutParm, ReductionType, D->getLocation());
13239   DRD->setCombinerData(InE, OutE);
13240 }
13241 
13242 void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
13243   auto *DRD = cast<OMPDeclareReductionDecl>(D);
13244   DiscardCleanupsInEvaluationContext();
13245   PopExpressionEvaluationContext();
13246 
13247   PopDeclContext();
13248   PopFunctionScopeInfo();
13249 
13250   if (Combiner != nullptr)
13251     DRD->setCombiner(Combiner);
13252   else
13253     DRD->setInvalidDecl();
13254 }
13255 
13256 VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
13257   auto *DRD = cast<OMPDeclareReductionDecl>(D);
13258 
13259   // Enter new function scope.
13260   PushFunctionScope();
13261   setFunctionHasBranchProtectedScope();
13262 
13263   if (S != nullptr)
13264     PushDeclContext(S, DRD);
13265   else
13266     CurContext = DRD;
13267 
13268   PushExpressionEvaluationContext(
13269       ExpressionEvaluationContext::PotentiallyEvaluated);
13270 
13271   QualType ReductionType = DRD->getType();
13272   // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
13273   // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
13274   // uses semantics of argument handles by value, but it should be passed by
13275   // reference. C lang does not support references, so pass all parameters as
13276   // pointers.
13277   // Create 'T omp_priv;' variable.
13278   VarDecl *OmpPrivParm =
13279       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
13280   // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
13281   // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
13282   // uses semantics of argument handles by value, but it should be passed by
13283   // reference. C lang does not support references, so pass all parameters as
13284   // pointers.
13285   // Create 'T omp_orig;' variable.
13286   VarDecl *OmpOrigParm =
13287       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
13288   if (S != nullptr) {
13289     PushOnScopeChains(OmpPrivParm, S);
13290     PushOnScopeChains(OmpOrigParm, S);
13291   } else {
13292     DRD->addDecl(OmpPrivParm);
13293     DRD->addDecl(OmpOrigParm);
13294   }
13295   Expr *OrigE =
13296       ::buildDeclRefExpr(*this, OmpOrigParm, ReductionType, D->getLocation());
13297   Expr *PrivE =
13298       ::buildDeclRefExpr(*this, OmpPrivParm, ReductionType, D->getLocation());
13299   DRD->setInitializerData(OrigE, PrivE);
13300   return OmpPrivParm;
13301 }
13302 
13303 void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
13304                                                      VarDecl *OmpPrivParm) {
13305   auto *DRD = cast<OMPDeclareReductionDecl>(D);
13306   DiscardCleanupsInEvaluationContext();
13307   PopExpressionEvaluationContext();
13308 
13309   PopDeclContext();
13310   PopFunctionScopeInfo();
13311 
13312   if (Initializer != nullptr) {
13313     DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit);
13314   } else if (OmpPrivParm->hasInit()) {
13315     DRD->setInitializer(OmpPrivParm->getInit(),
13316                         OmpPrivParm->isDirectInit()
13317                             ? OMPDeclareReductionDecl::DirectInit
13318                             : OMPDeclareReductionDecl::CopyInit);
13319   } else {
13320     DRD->setInvalidDecl();
13321   }
13322 }
13323 
13324 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
13325     Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
13326   for (Decl *D : DeclReductions.get()) {
13327     if (IsValid) {
13328       if (S)
13329         PushOnScopeChains(cast<OMPDeclareReductionDecl>(D), S,
13330                           /*AddToContext=*/false);
13331     } else {
13332       D->setInvalidDecl();
13333     }
13334   }
13335   return DeclReductions;
13336 }
13337 
13338 OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
13339                                            SourceLocation StartLoc,
13340                                            SourceLocation LParenLoc,
13341                                            SourceLocation EndLoc) {
13342   Expr *ValExpr = NumTeams;
13343   Stmt *HelperValStmt = nullptr;
13344 
13345   // OpenMP [teams Constrcut, Restrictions]
13346   // The num_teams expression must evaluate to a positive integer value.
13347   if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
13348                                  /*StrictlyPositive=*/true))
13349     return nullptr;
13350 
13351   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
13352   OpenMPDirectiveKind CaptureRegion =
13353       getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams);
13354   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
13355     ValExpr = MakeFullExpr(ValExpr).get();
13356     llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
13357     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
13358     HelperValStmt = buildPreInits(Context, Captures);
13359   }
13360 
13361   return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
13362                                          StartLoc, LParenLoc, EndLoc);
13363 }
13364 
13365 OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
13366                                               SourceLocation StartLoc,
13367                                               SourceLocation LParenLoc,
13368                                               SourceLocation EndLoc) {
13369   Expr *ValExpr = ThreadLimit;
13370   Stmt *HelperValStmt = nullptr;
13371 
13372   // OpenMP [teams Constrcut, Restrictions]
13373   // The thread_limit expression must evaluate to a positive integer value.
13374   if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
13375                                  /*StrictlyPositive=*/true))
13376     return nullptr;
13377 
13378   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
13379   OpenMPDirectiveKind CaptureRegion =
13380       getOpenMPCaptureRegionForClause(DKind, OMPC_thread_limit);
13381   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
13382     ValExpr = MakeFullExpr(ValExpr).get();
13383     llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
13384     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
13385     HelperValStmt = buildPreInits(Context, Captures);
13386   }
13387 
13388   return new (Context) OMPThreadLimitClause(
13389       ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
13390 }
13391 
13392 OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
13393                                            SourceLocation StartLoc,
13394                                            SourceLocation LParenLoc,
13395                                            SourceLocation EndLoc) {
13396   Expr *ValExpr = Priority;
13397 
13398   // OpenMP [2.9.1, task Constrcut]
13399   // The priority-value is a non-negative numerical scalar expression.
13400   if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_priority,
13401                                  /*StrictlyPositive=*/false))
13402     return nullptr;
13403 
13404   return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc);
13405 }
13406 
13407 OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
13408                                             SourceLocation StartLoc,
13409                                             SourceLocation LParenLoc,
13410                                             SourceLocation EndLoc) {
13411   Expr *ValExpr = Grainsize;
13412 
13413   // OpenMP [2.9.2, taskloop Constrcut]
13414   // The parameter of the grainsize clause must be a positive integer
13415   // expression.
13416   if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize,
13417                                  /*StrictlyPositive=*/true))
13418     return nullptr;
13419 
13420   return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc);
13421 }
13422 
13423 OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
13424                                            SourceLocation StartLoc,
13425                                            SourceLocation LParenLoc,
13426                                            SourceLocation EndLoc) {
13427   Expr *ValExpr = NumTasks;
13428 
13429   // OpenMP [2.9.2, taskloop Constrcut]
13430   // The parameter of the num_tasks clause must be a positive integer
13431   // expression.
13432   if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks,
13433                                  /*StrictlyPositive=*/true))
13434     return nullptr;
13435 
13436   return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc);
13437 }
13438 
13439 OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
13440                                        SourceLocation LParenLoc,
13441                                        SourceLocation EndLoc) {
13442   // OpenMP [2.13.2, critical construct, Description]
13443   // ... where hint-expression is an integer constant expression that evaluates
13444   // to a valid lock hint.
13445   ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
13446   if (HintExpr.isInvalid())
13447     return nullptr;
13448   return new (Context)
13449       OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
13450 }
13451 
13452 OMPClause *Sema::ActOnOpenMPDistScheduleClause(
13453     OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
13454     SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
13455     SourceLocation EndLoc) {
13456   if (Kind == OMPC_DIST_SCHEDULE_unknown) {
13457     std::string Values;
13458     Values += "'";
13459     Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
13460     Values += "'";
13461     Diag(KindLoc, diag::err_omp_unexpected_clause_value)
13462         << Values << getOpenMPClauseName(OMPC_dist_schedule);
13463     return nullptr;
13464   }
13465   Expr *ValExpr = ChunkSize;
13466   Stmt *HelperValStmt = nullptr;
13467   if (ChunkSize) {
13468     if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
13469         !ChunkSize->isInstantiationDependent() &&
13470         !ChunkSize->containsUnexpandedParameterPack()) {
13471       SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
13472       ExprResult Val =
13473           PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
13474       if (Val.isInvalid())
13475         return nullptr;
13476 
13477       ValExpr = Val.get();
13478 
13479       // OpenMP [2.7.1, Restrictions]
13480       //  chunk_size must be a loop invariant integer expression with a positive
13481       //  value.
13482       llvm::APSInt Result;
13483       if (ValExpr->isIntegerConstantExpr(Result, Context)) {
13484         if (Result.isSigned() && !Result.isStrictlyPositive()) {
13485           Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
13486               << "dist_schedule" << ChunkSize->getSourceRange();
13487           return nullptr;
13488         }
13489       } else if (getOpenMPCaptureRegionForClause(
13490                      DSAStack->getCurrentDirective(), OMPC_dist_schedule) !=
13491                      OMPD_unknown &&
13492                  !CurContext->isDependentContext()) {
13493         ValExpr = MakeFullExpr(ValExpr).get();
13494         llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
13495         ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
13496         HelperValStmt = buildPreInits(Context, Captures);
13497       }
13498     }
13499   }
13500 
13501   return new (Context)
13502       OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
13503                             Kind, ValExpr, HelperValStmt);
13504 }
13505 
13506 OMPClause *Sema::ActOnOpenMPDefaultmapClause(
13507     OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
13508     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
13509     SourceLocation KindLoc, SourceLocation EndLoc) {
13510   // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)'
13511   if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) {
13512     std::string Value;
13513     SourceLocation Loc;
13514     Value += "'";
13515     if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
13516       Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
13517                                              OMPC_DEFAULTMAP_MODIFIER_tofrom);
13518       Loc = MLoc;
13519     } else {
13520       Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
13521                                              OMPC_DEFAULTMAP_scalar);
13522       Loc = KindLoc;
13523     }
13524     Value += "'";
13525     Diag(Loc, diag::err_omp_unexpected_clause_value)
13526         << Value << getOpenMPClauseName(OMPC_defaultmap);
13527     return nullptr;
13528   }
13529   DSAStack->setDefaultDMAToFromScalar(StartLoc);
13530 
13531   return new (Context)
13532       OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
13533 }
13534 
13535 bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
13536   DeclContext *CurLexicalContext = getCurLexicalContext();
13537   if (!CurLexicalContext->isFileContext() &&
13538       !CurLexicalContext->isExternCContext() &&
13539       !CurLexicalContext->isExternCXXContext() &&
13540       !isa<CXXRecordDecl>(CurLexicalContext) &&
13541       !isa<ClassTemplateDecl>(CurLexicalContext) &&
13542       !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) &&
13543       !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) {
13544     Diag(Loc, diag::err_omp_region_not_file_context);
13545     return false;
13546   }
13547   ++DeclareTargetNestingLevel;
13548   return true;
13549 }
13550 
13551 void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
13552   assert(DeclareTargetNestingLevel > 0 &&
13553          "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
13554   --DeclareTargetNestingLevel;
13555 }
13556 
13557 void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope,
13558                                         CXXScopeSpec &ScopeSpec,
13559                                         const DeclarationNameInfo &Id,
13560                                         OMPDeclareTargetDeclAttr::MapTypeTy MT,
13561                                         NamedDeclSetType &SameDirectiveDecls) {
13562   LookupResult Lookup(*this, Id, LookupOrdinaryName);
13563   LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
13564 
13565   if (Lookup.isAmbiguous())
13566     return;
13567   Lookup.suppressDiagnostics();
13568 
13569   if (!Lookup.isSingleResult()) {
13570     if (TypoCorrection Corrected =
13571             CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr,
13572                         llvm::make_unique<VarOrFuncDeclFilterCCC>(*this),
13573                         CTK_ErrorRecovery)) {
13574       diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
13575                                   << Id.getName());
13576       checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
13577       return;
13578     }
13579 
13580     Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
13581     return;
13582   }
13583 
13584   NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
13585   if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND) ||
13586       isa<FunctionTemplateDecl>(ND)) {
13587     if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
13588       Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
13589     llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
13590         OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
13591             cast<ValueDecl>(ND));
13592     if (!Res) {
13593       auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT);
13594       ND->addAttr(A);
13595       if (ASTMutationListener *ML = Context.getASTMutationListener())
13596         ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
13597       checkDeclIsAllowedInOpenMPTarget(nullptr, ND, Id.getLoc());
13598     } else if (*Res != MT) {
13599       Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link)
13600           << Id.getName();
13601     }
13602   } else {
13603     Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
13604   }
13605 }
13606 
13607 static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
13608                                      Sema &SemaRef, Decl *D) {
13609   if (!D || !isa<VarDecl>(D))
13610     return;
13611   auto *VD = cast<VarDecl>(D);
13612   if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
13613     return;
13614   SemaRef.Diag(VD->getLocation(), diag::warn_omp_not_in_target_context);
13615   SemaRef.Diag(SL, diag::note_used_here) << SR;
13616 }
13617 
13618 static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
13619                                    Sema &SemaRef, DSAStackTy *Stack,
13620                                    ValueDecl *VD) {
13621   return VD->hasAttr<OMPDeclareTargetDeclAttr>() ||
13622          checkTypeMappable(SL, SR, SemaRef, Stack, VD->getType(),
13623                            /*FullCheck=*/false);
13624 }
13625 
13626 void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
13627                                             SourceLocation IdLoc) {
13628   if (!D || D->isInvalidDecl())
13629     return;
13630   SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
13631   SourceLocation SL = E ? E->getBeginLoc() : D->getLocation();
13632   if (auto *VD = dyn_cast<VarDecl>(D)) {
13633     // Only global variables can be marked as declare target.
13634     if (!VD->isFileVarDecl() && !VD->isStaticLocal() &&
13635         !VD->isStaticDataMember())
13636       return;
13637     // 2.10.6: threadprivate variable cannot appear in a declare target
13638     // directive.
13639     if (DSAStack->isThreadPrivate(VD)) {
13640       Diag(SL, diag::err_omp_threadprivate_in_target);
13641       reportOriginalDsa(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
13642       return;
13643     }
13644   }
13645   if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(D))
13646     D = FTD->getTemplatedDecl();
13647   if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
13648     llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
13649         OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(FD);
13650     if (Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) {
13651       assert(IdLoc.isValid() && "Source location is expected");
13652       Diag(IdLoc, diag::err_omp_function_in_link_clause);
13653       Diag(FD->getLocation(), diag::note_defined_here) << FD;
13654       return;
13655     }
13656   }
13657   if (auto *VD = dyn_cast<ValueDecl>(D)) {
13658     // Problem if any with var declared with incomplete type will be reported
13659     // as normal, so no need to check it here.
13660     if ((E || !VD->getType()->isIncompleteType()) &&
13661         !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD))
13662       return;
13663     if (!E && !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
13664       // Checking declaration inside declare target region.
13665       if (isa<VarDecl>(D) || isa<FunctionDecl>(D) ||
13666           isa<FunctionTemplateDecl>(D)) {
13667         auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(
13668             Context, OMPDeclareTargetDeclAttr::MT_To);
13669         D->addAttr(A);
13670         if (ASTMutationListener *ML = Context.getASTMutationListener())
13671           ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
13672       }
13673       return;
13674     }
13675   }
13676   if (!E)
13677     return;
13678   checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
13679 }
13680 
13681 OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
13682                                      SourceLocation StartLoc,
13683                                      SourceLocation LParenLoc,
13684                                      SourceLocation EndLoc) {
13685   MappableVarListInfo MVLI(VarList);
13686   checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, StartLoc);
13687   if (MVLI.ProcessedVarList.empty())
13688     return nullptr;
13689 
13690   return OMPToClause::Create(Context, StartLoc, LParenLoc, EndLoc,
13691                              MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
13692                              MVLI.VarComponents);
13693 }
13694 
13695 OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
13696                                        SourceLocation StartLoc,
13697                                        SourceLocation LParenLoc,
13698                                        SourceLocation EndLoc) {
13699   MappableVarListInfo MVLI(VarList);
13700   checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, StartLoc);
13701   if (MVLI.ProcessedVarList.empty())
13702     return nullptr;
13703 
13704   return OMPFromClause::Create(Context, StartLoc, LParenLoc, EndLoc,
13705                                MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
13706                                MVLI.VarComponents);
13707 }
13708 
13709 OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
13710                                                SourceLocation StartLoc,
13711                                                SourceLocation LParenLoc,
13712                                                SourceLocation EndLoc) {
13713   MappableVarListInfo MVLI(VarList);
13714   SmallVector<Expr *, 8> PrivateCopies;
13715   SmallVector<Expr *, 8> Inits;
13716 
13717   for (Expr *RefExpr : VarList) {
13718     assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
13719     SourceLocation ELoc;
13720     SourceRange ERange;
13721     Expr *SimpleRefExpr = RefExpr;
13722     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
13723     if (Res.second) {
13724       // It will be analyzed later.
13725       MVLI.ProcessedVarList.push_back(RefExpr);
13726       PrivateCopies.push_back(nullptr);
13727       Inits.push_back(nullptr);
13728     }
13729     ValueDecl *D = Res.first;
13730     if (!D)
13731       continue;
13732 
13733     QualType Type = D->getType();
13734     Type = Type.getNonReferenceType().getUnqualifiedType();
13735 
13736     auto *VD = dyn_cast<VarDecl>(D);
13737 
13738     // Item should be a pointer or reference to pointer.
13739     if (!Type->isPointerType()) {
13740       Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
13741           << 0 << RefExpr->getSourceRange();
13742       continue;
13743     }
13744 
13745     // Build the private variable and the expression that refers to it.
13746     auto VDPrivate =
13747         buildVarDecl(*this, ELoc, Type, D->getName(),
13748                      D->hasAttrs() ? &D->getAttrs() : nullptr,
13749                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
13750     if (VDPrivate->isInvalidDecl())
13751       continue;
13752 
13753     CurContext->addDecl(VDPrivate);
13754     DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
13755         *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
13756 
13757     // Add temporary variable to initialize the private copy of the pointer.
13758     VarDecl *VDInit =
13759         buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
13760     DeclRefExpr *VDInitRefExpr = buildDeclRefExpr(
13761         *this, VDInit, RefExpr->getType(), RefExpr->getExprLoc());
13762     AddInitializerToDecl(VDPrivate,
13763                          DefaultLvalueConversion(VDInitRefExpr).get(),
13764                          /*DirectInit=*/false);
13765 
13766     // If required, build a capture to implement the privatization initialized
13767     // with the current list item value.
13768     DeclRefExpr *Ref = nullptr;
13769     if (!VD)
13770       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
13771     MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
13772     PrivateCopies.push_back(VDPrivateRefExpr);
13773     Inits.push_back(VDInitRefExpr);
13774 
13775     // We need to add a data sharing attribute for this variable to make sure it
13776     // is correctly captured. A variable that shows up in a use_device_ptr has
13777     // similar properties of a first private variable.
13778     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
13779 
13780     // Create a mappable component for the list item. List items in this clause
13781     // only need a component.
13782     MVLI.VarBaseDeclarations.push_back(D);
13783     MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
13784     MVLI.VarComponents.back().push_back(
13785         OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
13786   }
13787 
13788   if (MVLI.ProcessedVarList.empty())
13789     return nullptr;
13790 
13791   return OMPUseDevicePtrClause::Create(
13792       Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
13793       PrivateCopies, Inits, MVLI.VarBaseDeclarations, MVLI.VarComponents);
13794 }
13795 
13796 OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
13797                                               SourceLocation StartLoc,
13798                                               SourceLocation LParenLoc,
13799                                               SourceLocation EndLoc) {
13800   MappableVarListInfo MVLI(VarList);
13801   for (Expr *RefExpr : VarList) {
13802     assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
13803     SourceLocation ELoc;
13804     SourceRange ERange;
13805     Expr *SimpleRefExpr = RefExpr;
13806     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
13807     if (Res.second) {
13808       // It will be analyzed later.
13809       MVLI.ProcessedVarList.push_back(RefExpr);
13810     }
13811     ValueDecl *D = Res.first;
13812     if (!D)
13813       continue;
13814 
13815     QualType Type = D->getType();
13816     // item should be a pointer or array or reference to pointer or array
13817     if (!Type.getNonReferenceType()->isPointerType() &&
13818         !Type.getNonReferenceType()->isArrayType()) {
13819       Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
13820           << 0 << RefExpr->getSourceRange();
13821       continue;
13822     }
13823 
13824     // Check if the declaration in the clause does not show up in any data
13825     // sharing attribute.
13826     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
13827     if (isOpenMPPrivate(DVar.CKind)) {
13828       Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
13829           << getOpenMPClauseName(DVar.CKind)
13830           << getOpenMPClauseName(OMPC_is_device_ptr)
13831           << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
13832       reportOriginalDsa(*this, DSAStack, D, DVar);
13833       continue;
13834     }
13835 
13836     const Expr *ConflictExpr;
13837     if (DSAStack->checkMappableExprComponentListsForDecl(
13838             D, /*CurrentRegionOnly=*/true,
13839             [&ConflictExpr](
13840                 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
13841                 OpenMPClauseKind) -> bool {
13842               ConflictExpr = R.front().getAssociatedExpression();
13843               return true;
13844             })) {
13845       Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
13846       Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
13847           << ConflictExpr->getSourceRange();
13848       continue;
13849     }
13850 
13851     // Store the components in the stack so that they can be used to check
13852     // against other clauses later on.
13853     OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
13854     DSAStack->addMappableExpressionComponents(
13855         D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
13856 
13857     // Record the expression we've just processed.
13858     MVLI.ProcessedVarList.push_back(SimpleRefExpr);
13859 
13860     // Create a mappable component for the list item. List items in this clause
13861     // only need a component. We use a null declaration to signal fields in
13862     // 'this'.
13863     assert((isa<DeclRefExpr>(SimpleRefExpr) ||
13864             isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
13865            "Unexpected device pointer expression!");
13866     MVLI.VarBaseDeclarations.push_back(
13867         isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
13868     MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
13869     MVLI.VarComponents.back().push_back(MC);
13870   }
13871 
13872   if (MVLI.ProcessedVarList.empty())
13873     return nullptr;
13874 
13875   return OMPIsDevicePtrClause::Create(
13876       Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
13877       MVLI.VarBaseDeclarations, MVLI.VarComponents);
13878 }
13879