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/Basic/OpenMPKinds.h"
26 #include "clang/Sema/Initialization.h"
27 #include "clang/Sema/Lookup.h"
28 #include "clang/Sema/Scope.h"
29 #include "clang/Sema/ScopeInfo.h"
30 #include "clang/Sema/SemaInternal.h"
31 #include "llvm/ADT/PointerEmbeddedInt.h"
32 using namespace clang;
33 
34 //===----------------------------------------------------------------------===//
35 // Stack of data-sharing attributes for variables
36 //===----------------------------------------------------------------------===//
37 
38 static const Expr *checkMapClauseExpressionBase(
39     Sema &SemaRef, Expr *E,
40     OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
41     OpenMPClauseKind CKind, bool NoDiagnose);
42 
43 namespace {
44 /// Default data sharing attributes, which can be applied to directive.
45 enum DefaultDataSharingAttributes {
46   DSA_unspecified = 0, /// Data sharing attribute not specified.
47   DSA_none = 1 << 0,   /// Default data sharing attribute 'none'.
48   DSA_shared = 1 << 1, /// Default data sharing attribute 'shared'.
49 };
50 
51 /// Attributes of the defaultmap clause.
52 enum DefaultMapAttributes {
53   DMA_unspecified,   /// Default mapping is not specified.
54   DMA_tofrom_scalar, /// Default mapping is 'tofrom:scalar'.
55 };
56 
57 /// Stack for tracking declarations used in OpenMP directives and
58 /// clauses and their data-sharing attributes.
59 class DSAStackTy {
60 public:
61   struct DSAVarData {
62     OpenMPDirectiveKind DKind = OMPD_unknown;
63     OpenMPClauseKind CKind = OMPC_unknown;
64     const Expr *RefExpr = nullptr;
65     DeclRefExpr *PrivateCopy = nullptr;
66     SourceLocation ImplicitDSALoc;
67     DSAVarData() = default;
68     DSAVarData(OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
69                const Expr *RefExpr, DeclRefExpr *PrivateCopy,
70                SourceLocation ImplicitDSALoc)
71         : DKind(DKind), CKind(CKind), RefExpr(RefExpr),
72           PrivateCopy(PrivateCopy), ImplicitDSALoc(ImplicitDSALoc) {}
73   };
74   using OperatorOffsetTy =
75       llvm::SmallVector<std::pair<Expr *, OverloadedOperatorKind>, 4>;
76   using DoacrossDependMapTy =
77       llvm::DenseMap<OMPDependClause *, OperatorOffsetTy>;
78 
79 private:
80   struct DSAInfo {
81     OpenMPClauseKind Attributes = OMPC_unknown;
82     /// Pointer to a reference expression and a flag which shows that the
83     /// variable is marked as lastprivate(true) or not (false).
84     llvm::PointerIntPair<const Expr *, 1, bool> RefExpr;
85     DeclRefExpr *PrivateCopy = nullptr;
86   };
87   using DeclSAMapTy = llvm::SmallDenseMap<const ValueDecl *, DSAInfo, 8>;
88   using AlignedMapTy = llvm::SmallDenseMap<const ValueDecl *, const Expr *, 8>;
89   using LCDeclInfo = std::pair<unsigned, VarDecl *>;
90   using LoopControlVariablesMapTy =
91       llvm::SmallDenseMap<const ValueDecl *, LCDeclInfo, 8>;
92   /// Struct that associates a component with the clause kind where they are
93   /// found.
94   struct MappedExprComponentTy {
95     OMPClauseMappableExprCommon::MappableExprComponentLists Components;
96     OpenMPClauseKind Kind = OMPC_unknown;
97   };
98   using MappedExprComponentsTy =
99       llvm::DenseMap<const ValueDecl *, MappedExprComponentTy>;
100   using CriticalsWithHintsTy =
101       llvm::StringMap<std::pair<const OMPCriticalDirective *, llvm::APSInt>>;
102   struct ReductionData {
103     using BOKPtrType = llvm::PointerEmbeddedInt<BinaryOperatorKind, 16>;
104     SourceRange ReductionRange;
105     llvm::PointerUnion<const Expr *, BOKPtrType> ReductionOp;
106     ReductionData() = default;
107     void set(BinaryOperatorKind BO, SourceRange RR) {
108       ReductionRange = RR;
109       ReductionOp = BO;
110     }
111     void set(const Expr *RefExpr, SourceRange RR) {
112       ReductionRange = RR;
113       ReductionOp = RefExpr;
114     }
115   };
116   using DeclReductionMapTy =
117       llvm::SmallDenseMap<const ValueDecl *, ReductionData, 4>;
118 
119   struct SharingMapTy {
120     DeclSAMapTy SharingMap;
121     DeclReductionMapTy ReductionMap;
122     AlignedMapTy AlignedMap;
123     MappedExprComponentsTy MappedExprComponents;
124     LoopControlVariablesMapTy LCVMap;
125     DefaultDataSharingAttributes DefaultAttr = DSA_unspecified;
126     SourceLocation DefaultAttrLoc;
127     DefaultMapAttributes DefaultMapAttr = DMA_unspecified;
128     SourceLocation DefaultMapAttrLoc;
129     OpenMPDirectiveKind Directive = OMPD_unknown;
130     DeclarationNameInfo DirectiveName;
131     Scope *CurScope = nullptr;
132     SourceLocation ConstructLoc;
133     /// Set of 'depend' clauses with 'sink|source' dependence kind. Required to
134     /// get the data (loop counters etc.) about enclosing loop-based construct.
135     /// This data is required during codegen.
136     DoacrossDependMapTy DoacrossDepends;
137     /// first argument (Expr *) contains optional argument of the
138     /// 'ordered' clause, the second one is true if the regions has 'ordered'
139     /// clause, false otherwise.
140     llvm::Optional<std::pair<const Expr *, OMPOrderedClause *>> OrderedRegion;
141     unsigned AssociatedLoops = 1;
142     const Decl *PossiblyLoopCounter = nullptr;
143     bool NowaitRegion = false;
144     bool CancelRegion = false;
145     bool LoopStart = false;
146     SourceLocation InnerTeamsRegionLoc;
147     /// Reference to the taskgroup task_reduction reference expression.
148     Expr *TaskgroupReductionRef = nullptr;
149     SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
150                  Scope *CurScope, SourceLocation Loc)
151         : Directive(DKind), DirectiveName(Name), CurScope(CurScope),
152           ConstructLoc(Loc) {}
153     SharingMapTy() = default;
154   };
155 
156   using StackTy = SmallVector<SharingMapTy, 4>;
157 
158   /// Stack of used declaration and their data-sharing attributes.
159   DeclSAMapTy Threadprivates;
160   const FunctionScopeInfo *CurrentNonCapturingFunctionScope = nullptr;
161   SmallVector<std::pair<StackTy, const FunctionScopeInfo *>, 4> Stack;
162   /// true, if check for DSA must be from parent directive, false, if
163   /// from current directive.
164   OpenMPClauseKind ClauseKindMode = OMPC_unknown;
165   Sema &SemaRef;
166   bool ForceCapturing = false;
167   /// true if all the vaiables in the target executable directives must be
168   /// captured by reference.
169   bool ForceCaptureByReferenceInTargetExecutable = false;
170   CriticalsWithHintsTy Criticals;
171 
172   using iterator = StackTy::const_reverse_iterator;
173 
174   DSAVarData getDSA(iterator &Iter, ValueDecl *D) const;
175 
176   /// Checks if the variable is a local for OpenMP region.
177   bool isOpenMPLocal(VarDecl *D, iterator Iter) const;
178 
179   bool isStackEmpty() const {
180     return Stack.empty() ||
181            Stack.back().second != CurrentNonCapturingFunctionScope ||
182            Stack.back().first.empty();
183   }
184 
185   /// Vector of previously declared requires directives
186   SmallVector<const OMPRequiresDecl *, 2> RequiresDecls;
187 
188 public:
189   explicit DSAStackTy(Sema &S) : SemaRef(S) {}
190 
191   bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
192   OpenMPClauseKind getClauseParsingMode() const {
193     assert(isClauseParsingMode() && "Must be in clause parsing mode.");
194     return ClauseKindMode;
195   }
196   void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
197 
198   bool isForceVarCapturing() const { return ForceCapturing; }
199   void setForceVarCapturing(bool V) { ForceCapturing = V; }
200 
201   void setForceCaptureByReferenceInTargetExecutable(bool V) {
202     ForceCaptureByReferenceInTargetExecutable = V;
203   }
204   bool isForceCaptureByReferenceInTargetExecutable() const {
205     return ForceCaptureByReferenceInTargetExecutable;
206   }
207 
208   void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
209             Scope *CurScope, SourceLocation Loc) {
210     if (Stack.empty() ||
211         Stack.back().second != CurrentNonCapturingFunctionScope)
212       Stack.emplace_back(StackTy(), CurrentNonCapturingFunctionScope);
213     Stack.back().first.emplace_back(DKind, DirName, CurScope, Loc);
214     Stack.back().first.back().DefaultAttrLoc = Loc;
215   }
216 
217   void pop() {
218     assert(!Stack.back().first.empty() &&
219            "Data-sharing attributes stack is empty!");
220     Stack.back().first.pop_back();
221   }
222 
223   /// Marks that we're started loop parsing.
224   void loopInit() {
225     assert(isOpenMPLoopDirective(getCurrentDirective()) &&
226            "Expected loop-based directive.");
227     Stack.back().first.back().LoopStart = true;
228   }
229   /// Start capturing of the variables in the loop context.
230   void loopStart() {
231     assert(isOpenMPLoopDirective(getCurrentDirective()) &&
232            "Expected loop-based directive.");
233     Stack.back().first.back().LoopStart = false;
234   }
235   /// true, if variables are captured, false otherwise.
236   bool isLoopStarted() const {
237     assert(isOpenMPLoopDirective(getCurrentDirective()) &&
238            "Expected loop-based directive.");
239     return !Stack.back().first.back().LoopStart;
240   }
241   /// Marks (or clears) declaration as possibly loop counter.
242   void resetPossibleLoopCounter(const Decl *D = nullptr) {
243     Stack.back().first.back().PossiblyLoopCounter =
244         D ? D->getCanonicalDecl() : D;
245   }
246   /// Gets the possible loop counter decl.
247   const Decl *getPossiblyLoopCunter() const {
248     return Stack.back().first.back().PossiblyLoopCounter;
249   }
250   /// Start new OpenMP region stack in new non-capturing function.
251   void pushFunction() {
252     const FunctionScopeInfo *CurFnScope = SemaRef.getCurFunction();
253     assert(!isa<CapturingScopeInfo>(CurFnScope));
254     CurrentNonCapturingFunctionScope = CurFnScope;
255   }
256   /// Pop region stack for non-capturing function.
257   void popFunction(const FunctionScopeInfo *OldFSI) {
258     if (!Stack.empty() && Stack.back().second == OldFSI) {
259       assert(Stack.back().first.empty());
260       Stack.pop_back();
261     }
262     CurrentNonCapturingFunctionScope = nullptr;
263     for (const FunctionScopeInfo *FSI : llvm::reverse(SemaRef.FunctionScopes)) {
264       if (!isa<CapturingScopeInfo>(FSI)) {
265         CurrentNonCapturingFunctionScope = FSI;
266         break;
267       }
268     }
269   }
270 
271   void addCriticalWithHint(const OMPCriticalDirective *D, llvm::APSInt Hint) {
272     Criticals.try_emplace(D->getDirectiveName().getAsString(), D, Hint);
273   }
274   const std::pair<const OMPCriticalDirective *, llvm::APSInt>
275   getCriticalWithHint(const DeclarationNameInfo &Name) const {
276     auto I = Criticals.find(Name.getAsString());
277     if (I != Criticals.end())
278       return I->second;
279     return std::make_pair(nullptr, llvm::APSInt());
280   }
281   /// If 'aligned' declaration for given variable \a D was not seen yet,
282   /// add it and return NULL; otherwise return previous occurrence's expression
283   /// for diagnostics.
284   const Expr *addUniqueAligned(const ValueDecl *D, const Expr *NewDE);
285 
286   /// Register specified variable as loop control variable.
287   void addLoopControlVariable(const ValueDecl *D, VarDecl *Capture);
288   /// Check if the specified variable is a loop control variable for
289   /// current region.
290   /// \return The index of the loop control variable in the list of associated
291   /// for-loops (from outer to inner).
292   const LCDeclInfo isLoopControlVariable(const ValueDecl *D) const;
293   /// Check if the specified variable is a loop control variable for
294   /// parent region.
295   /// \return The index of the loop control variable in the list of associated
296   /// for-loops (from outer to inner).
297   const LCDeclInfo isParentLoopControlVariable(const ValueDecl *D) const;
298   /// Get the loop control variable for the I-th loop (or nullptr) in
299   /// parent directive.
300   const ValueDecl *getParentLoopControlVariable(unsigned I) const;
301 
302   /// Adds explicit data sharing attribute to the specified declaration.
303   void addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
304               DeclRefExpr *PrivateCopy = nullptr);
305 
306   /// Adds additional information for the reduction items with the reduction id
307   /// represented as an operator.
308   void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
309                                  BinaryOperatorKind BOK);
310   /// Adds additional information for the reduction items with the reduction id
311   /// represented as reduction identifier.
312   void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
313                                  const Expr *ReductionRef);
314   /// Returns the location and reduction operation from the innermost parent
315   /// region for the given \p D.
316   const DSAVarData
317   getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
318                                    BinaryOperatorKind &BOK,
319                                    Expr *&TaskgroupDescriptor) const;
320   /// Returns the location and reduction operation from the innermost parent
321   /// region for the given \p D.
322   const DSAVarData
323   getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
324                                    const Expr *&ReductionRef,
325                                    Expr *&TaskgroupDescriptor) const;
326   /// Return reduction reference expression for the current taskgroup.
327   Expr *getTaskgroupReductionRef() const {
328     assert(Stack.back().first.back().Directive == OMPD_taskgroup &&
329            "taskgroup reference expression requested for non taskgroup "
330            "directive.");
331     return Stack.back().first.back().TaskgroupReductionRef;
332   }
333   /// Checks if the given \p VD declaration is actually a taskgroup reduction
334   /// descriptor variable at the \p Level of OpenMP regions.
335   bool isTaskgroupReductionRef(const ValueDecl *VD, unsigned Level) const {
336     return Stack.back().first[Level].TaskgroupReductionRef &&
337            cast<DeclRefExpr>(Stack.back().first[Level].TaskgroupReductionRef)
338                    ->getDecl() == VD;
339   }
340 
341   /// Returns data sharing attributes from top of the stack for the
342   /// specified declaration.
343   const DSAVarData getTopDSA(ValueDecl *D, bool FromParent);
344   /// Returns data-sharing attributes for the specified declaration.
345   const DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent) const;
346   /// Checks if the specified variables has data-sharing attributes which
347   /// match specified \a CPred predicate in any directive which matches \a DPred
348   /// predicate.
349   const DSAVarData
350   hasDSA(ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
351          const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
352          bool FromParent) const;
353   /// Checks if the specified variables has data-sharing attributes which
354   /// match specified \a CPred predicate in any innermost directive which
355   /// matches \a DPred predicate.
356   const DSAVarData
357   hasInnermostDSA(ValueDecl *D,
358                   const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
359                   const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
360                   bool FromParent) const;
361   /// Checks if the specified variables has explicit data-sharing
362   /// attributes which match specified \a CPred predicate at the specified
363   /// OpenMP region.
364   bool hasExplicitDSA(const ValueDecl *D,
365                       const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
366                       unsigned Level, bool NotLastprivate = false) const;
367 
368   /// Returns true if the directive at level \Level matches in the
369   /// specified \a DPred predicate.
370   bool hasExplicitDirective(
371       const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
372       unsigned Level) const;
373 
374   /// Finds a directive which matches specified \a DPred predicate.
375   bool hasDirective(
376       const llvm::function_ref<bool(
377           OpenMPDirectiveKind, const DeclarationNameInfo &, SourceLocation)>
378           DPred,
379       bool FromParent) const;
380 
381   /// Returns currently analyzed directive.
382   OpenMPDirectiveKind getCurrentDirective() const {
383     return isStackEmpty() ? OMPD_unknown : Stack.back().first.back().Directive;
384   }
385   /// Returns directive kind at specified level.
386   OpenMPDirectiveKind getDirective(unsigned Level) const {
387     assert(!isStackEmpty() && "No directive at specified level.");
388     return Stack.back().first[Level].Directive;
389   }
390   /// Returns parent directive.
391   OpenMPDirectiveKind getParentDirective() const {
392     if (isStackEmpty() || Stack.back().first.size() == 1)
393       return OMPD_unknown;
394     return std::next(Stack.back().first.rbegin())->Directive;
395   }
396 
397   /// Add requires decl to internal vector
398   void addRequiresDecl(OMPRequiresDecl *RD) {
399     RequiresDecls.push_back(RD);
400   }
401 
402   /// Checks for a duplicate clause amongst previously declared requires
403   /// directives
404   bool hasDuplicateRequiresClause(ArrayRef<OMPClause *> ClauseList) const {
405     bool IsDuplicate = false;
406     for (OMPClause *CNew : ClauseList) {
407       for (const OMPRequiresDecl *D : RequiresDecls) {
408         for (const OMPClause *CPrev : D->clauselists()) {
409           if (CNew->getClauseKind() == CPrev->getClauseKind()) {
410             SemaRef.Diag(CNew->getBeginLoc(),
411                          diag::err_omp_requires_clause_redeclaration)
412                 << getOpenMPClauseName(CNew->getClauseKind());
413             SemaRef.Diag(CPrev->getBeginLoc(),
414                          diag::note_omp_requires_previous_clause)
415                 << getOpenMPClauseName(CPrev->getClauseKind());
416             IsDuplicate = true;
417           }
418         }
419       }
420     }
421     return IsDuplicate;
422   }
423 
424   /// Set default data sharing attribute to none.
425   void setDefaultDSANone(SourceLocation Loc) {
426     assert(!isStackEmpty());
427     Stack.back().first.back().DefaultAttr = DSA_none;
428     Stack.back().first.back().DefaultAttrLoc = Loc;
429   }
430   /// Set default data sharing attribute to shared.
431   void setDefaultDSAShared(SourceLocation Loc) {
432     assert(!isStackEmpty());
433     Stack.back().first.back().DefaultAttr = DSA_shared;
434     Stack.back().first.back().DefaultAttrLoc = Loc;
435   }
436   /// Set default data mapping attribute to 'tofrom:scalar'.
437   void setDefaultDMAToFromScalar(SourceLocation Loc) {
438     assert(!isStackEmpty());
439     Stack.back().first.back().DefaultMapAttr = DMA_tofrom_scalar;
440     Stack.back().first.back().DefaultMapAttrLoc = Loc;
441   }
442 
443   DefaultDataSharingAttributes getDefaultDSA() const {
444     return isStackEmpty() ? DSA_unspecified
445                           : Stack.back().first.back().DefaultAttr;
446   }
447   SourceLocation getDefaultDSALocation() const {
448     return isStackEmpty() ? SourceLocation()
449                           : Stack.back().first.back().DefaultAttrLoc;
450   }
451   DefaultMapAttributes getDefaultDMA() const {
452     return isStackEmpty() ? DMA_unspecified
453                           : Stack.back().first.back().DefaultMapAttr;
454   }
455   DefaultMapAttributes getDefaultDMAAtLevel(unsigned Level) const {
456     return Stack.back().first[Level].DefaultMapAttr;
457   }
458   SourceLocation getDefaultDMALocation() const {
459     return isStackEmpty() ? SourceLocation()
460                           : Stack.back().first.back().DefaultMapAttrLoc;
461   }
462 
463   /// Checks if the specified variable is a threadprivate.
464   bool isThreadPrivate(VarDecl *D) {
465     const DSAVarData DVar = getTopDSA(D, false);
466     return isOpenMPThreadPrivate(DVar.CKind);
467   }
468 
469   /// Marks current region as ordered (it has an 'ordered' clause).
470   void setOrderedRegion(bool IsOrdered, const Expr *Param,
471                         OMPOrderedClause *Clause) {
472     assert(!isStackEmpty());
473     if (IsOrdered)
474       Stack.back().first.back().OrderedRegion.emplace(Param, Clause);
475     else
476       Stack.back().first.back().OrderedRegion.reset();
477   }
478   /// Returns true, if region is ordered (has associated 'ordered' clause),
479   /// false - otherwise.
480   bool isOrderedRegion() const {
481     if (isStackEmpty())
482       return false;
483     return Stack.back().first.rbegin()->OrderedRegion.hasValue();
484   }
485   /// Returns optional parameter for the ordered region.
486   std::pair<const Expr *, OMPOrderedClause *> getOrderedRegionParam() const {
487     if (isStackEmpty() ||
488         !Stack.back().first.rbegin()->OrderedRegion.hasValue())
489       return std::make_pair(nullptr, nullptr);
490     return Stack.back().first.rbegin()->OrderedRegion.getValue();
491   }
492   /// Returns true, if parent region is ordered (has associated
493   /// 'ordered' clause), false - otherwise.
494   bool isParentOrderedRegion() const {
495     if (isStackEmpty() || Stack.back().first.size() == 1)
496       return false;
497     return std::next(Stack.back().first.rbegin())->OrderedRegion.hasValue();
498   }
499   /// Returns optional parameter for the ordered region.
500   std::pair<const Expr *, OMPOrderedClause *>
501   getParentOrderedRegionParam() const {
502     if (isStackEmpty() || Stack.back().first.size() == 1 ||
503         !std::next(Stack.back().first.rbegin())->OrderedRegion.hasValue())
504       return std::make_pair(nullptr, nullptr);
505     return std::next(Stack.back().first.rbegin())->OrderedRegion.getValue();
506   }
507   /// Marks current region as nowait (it has a 'nowait' clause).
508   void setNowaitRegion(bool IsNowait = true) {
509     assert(!isStackEmpty());
510     Stack.back().first.back().NowaitRegion = IsNowait;
511   }
512   /// Returns true, if parent region is nowait (has associated
513   /// 'nowait' clause), false - otherwise.
514   bool isParentNowaitRegion() const {
515     if (isStackEmpty() || Stack.back().first.size() == 1)
516       return false;
517     return std::next(Stack.back().first.rbegin())->NowaitRegion;
518   }
519   /// Marks parent region as cancel region.
520   void setParentCancelRegion(bool Cancel = true) {
521     if (!isStackEmpty() && Stack.back().first.size() > 1) {
522       auto &StackElemRef = *std::next(Stack.back().first.rbegin());
523       StackElemRef.CancelRegion |= StackElemRef.CancelRegion || Cancel;
524     }
525   }
526   /// Return true if current region has inner cancel construct.
527   bool isCancelRegion() const {
528     return isStackEmpty() ? false : Stack.back().first.back().CancelRegion;
529   }
530 
531   /// Set collapse value for the region.
532   void setAssociatedLoops(unsigned Val) {
533     assert(!isStackEmpty());
534     Stack.back().first.back().AssociatedLoops = Val;
535   }
536   /// Return collapse value for region.
537   unsigned getAssociatedLoops() const {
538     return isStackEmpty() ? 0 : Stack.back().first.back().AssociatedLoops;
539   }
540 
541   /// Marks current target region as one with closely nested teams
542   /// region.
543   void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
544     if (!isStackEmpty() && Stack.back().first.size() > 1) {
545       std::next(Stack.back().first.rbegin())->InnerTeamsRegionLoc =
546           TeamsRegionLoc;
547     }
548   }
549   /// Returns true, if current region has closely nested teams region.
550   bool hasInnerTeamsRegion() const {
551     return getInnerTeamsRegionLoc().isValid();
552   }
553   /// Returns location of the nested teams region (if any).
554   SourceLocation getInnerTeamsRegionLoc() const {
555     return isStackEmpty() ? SourceLocation()
556                           : Stack.back().first.back().InnerTeamsRegionLoc;
557   }
558 
559   Scope *getCurScope() const {
560     return isStackEmpty() ? nullptr : Stack.back().first.back().CurScope;
561   }
562   SourceLocation getConstructLoc() const {
563     return isStackEmpty() ? SourceLocation()
564                           : Stack.back().first.back().ConstructLoc;
565   }
566 
567   /// Do the check specified in \a Check to all component lists and return true
568   /// if any issue is found.
569   bool checkMappableExprComponentListsForDecl(
570       const ValueDecl *VD, bool CurrentRegionOnly,
571       const llvm::function_ref<
572           bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
573                OpenMPClauseKind)>
574           Check) const {
575     if (isStackEmpty())
576       return false;
577     auto SI = Stack.back().first.rbegin();
578     auto SE = Stack.back().first.rend();
579 
580     if (SI == SE)
581       return false;
582 
583     if (CurrentRegionOnly)
584       SE = std::next(SI);
585     else
586       std::advance(SI, 1);
587 
588     for (; SI != SE; ++SI) {
589       auto MI = SI->MappedExprComponents.find(VD);
590       if (MI != SI->MappedExprComponents.end())
591         for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
592              MI->second.Components)
593           if (Check(L, MI->second.Kind))
594             return true;
595     }
596     return false;
597   }
598 
599   /// Do the check specified in \a Check to all component lists at a given level
600   /// and return true if any issue is found.
601   bool checkMappableExprComponentListsForDeclAtLevel(
602       const ValueDecl *VD, unsigned Level,
603       const llvm::function_ref<
604           bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
605                OpenMPClauseKind)>
606           Check) const {
607     if (isStackEmpty())
608       return false;
609 
610     auto StartI = Stack.back().first.begin();
611     auto EndI = Stack.back().first.end();
612     if (std::distance(StartI, EndI) <= (int)Level)
613       return false;
614     std::advance(StartI, Level);
615 
616     auto MI = StartI->MappedExprComponents.find(VD);
617     if (MI != StartI->MappedExprComponents.end())
618       for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
619            MI->second.Components)
620         if (Check(L, MI->second.Kind))
621           return true;
622     return false;
623   }
624 
625   /// Create a new mappable expression component list associated with a given
626   /// declaration and initialize it with the provided list of components.
627   void addMappableExpressionComponents(
628       const ValueDecl *VD,
629       OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
630       OpenMPClauseKind WhereFoundClauseKind) {
631     assert(!isStackEmpty() &&
632            "Not expecting to retrieve components from a empty stack!");
633     MappedExprComponentTy &MEC =
634         Stack.back().first.back().MappedExprComponents[VD];
635     // Create new entry and append the new components there.
636     MEC.Components.resize(MEC.Components.size() + 1);
637     MEC.Components.back().append(Components.begin(), Components.end());
638     MEC.Kind = WhereFoundClauseKind;
639   }
640 
641   unsigned getNestingLevel() const {
642     assert(!isStackEmpty());
643     return Stack.back().first.size() - 1;
644   }
645   void addDoacrossDependClause(OMPDependClause *C,
646                                const OperatorOffsetTy &OpsOffs) {
647     assert(!isStackEmpty() && Stack.back().first.size() > 1);
648     SharingMapTy &StackElem = *std::next(Stack.back().first.rbegin());
649     assert(isOpenMPWorksharingDirective(StackElem.Directive));
650     StackElem.DoacrossDepends.try_emplace(C, OpsOffs);
651   }
652   llvm::iterator_range<DoacrossDependMapTy::const_iterator>
653   getDoacrossDependClauses() const {
654     assert(!isStackEmpty());
655     const SharingMapTy &StackElem = Stack.back().first.back();
656     if (isOpenMPWorksharingDirective(StackElem.Directive)) {
657       const DoacrossDependMapTy &Ref = StackElem.DoacrossDepends;
658       return llvm::make_range(Ref.begin(), Ref.end());
659     }
660     return llvm::make_range(StackElem.DoacrossDepends.end(),
661                             StackElem.DoacrossDepends.end());
662   }
663 };
664 bool isParallelOrTaskRegion(OpenMPDirectiveKind DKind) {
665   return isOpenMPParallelDirective(DKind) || isOpenMPTaskingDirective(DKind) ||
666          isOpenMPTeamsDirective(DKind) || DKind == OMPD_unknown;
667 }
668 
669 } // namespace
670 
671 static const Expr *getExprAsWritten(const Expr *E) {
672   if (const auto *FE = dyn_cast<FullExpr>(E))
673     E = FE->getSubExpr();
674 
675   if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
676     E = MTE->GetTemporaryExpr();
677 
678   while (const auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
679     E = Binder->getSubExpr();
680 
681   if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
682     E = ICE->getSubExprAsWritten();
683   return E->IgnoreParens();
684 }
685 
686 static Expr *getExprAsWritten(Expr *E) {
687   return const_cast<Expr *>(getExprAsWritten(const_cast<const Expr *>(E)));
688 }
689 
690 static const ValueDecl *getCanonicalDecl(const ValueDecl *D) {
691   if (const auto *CED = dyn_cast<OMPCapturedExprDecl>(D))
692     if (const auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
693       D = ME->getMemberDecl();
694   const auto *VD = dyn_cast<VarDecl>(D);
695   const auto *FD = dyn_cast<FieldDecl>(D);
696   if (VD != nullptr) {
697     VD = VD->getCanonicalDecl();
698     D = VD;
699   } else {
700     assert(FD);
701     FD = FD->getCanonicalDecl();
702     D = FD;
703   }
704   return D;
705 }
706 
707 static ValueDecl *getCanonicalDecl(ValueDecl *D) {
708   return const_cast<ValueDecl *>(
709       getCanonicalDecl(const_cast<const ValueDecl *>(D)));
710 }
711 
712 DSAStackTy::DSAVarData DSAStackTy::getDSA(iterator &Iter,
713                                           ValueDecl *D) const {
714   D = getCanonicalDecl(D);
715   auto *VD = dyn_cast<VarDecl>(D);
716   const auto *FD = dyn_cast<FieldDecl>(D);
717   DSAVarData DVar;
718   if (isStackEmpty() || Iter == Stack.back().first.rend()) {
719     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
720     // in a region but not in construct]
721     //  File-scope or namespace-scope variables referenced in called routines
722     //  in the region are shared unless they appear in a threadprivate
723     //  directive.
724     if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(VD))
725       DVar.CKind = OMPC_shared;
726 
727     // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
728     // in a region but not in construct]
729     //  Variables with static storage duration that are declared in called
730     //  routines in the region are shared.
731     if (VD && VD->hasGlobalStorage())
732       DVar.CKind = OMPC_shared;
733 
734     // Non-static data members are shared by default.
735     if (FD)
736       DVar.CKind = OMPC_shared;
737 
738     return DVar;
739   }
740 
741   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
742   // in a Construct, C/C++, predetermined, p.1]
743   // Variables with automatic storage duration that are declared in a scope
744   // inside the construct are private.
745   if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() &&
746       (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) {
747     DVar.CKind = OMPC_private;
748     return DVar;
749   }
750 
751   DVar.DKind = Iter->Directive;
752   // Explicitly specified attributes and local variables with predetermined
753   // attributes.
754   if (Iter->SharingMap.count(D)) {
755     const DSAInfo &Data = Iter->SharingMap.lookup(D);
756     DVar.RefExpr = Data.RefExpr.getPointer();
757     DVar.PrivateCopy = Data.PrivateCopy;
758     DVar.CKind = Data.Attributes;
759     DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
760     return DVar;
761   }
762 
763   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
764   // in a Construct, C/C++, implicitly determined, p.1]
765   //  In a parallel or task construct, the data-sharing attributes of these
766   //  variables are determined by the default clause, if present.
767   switch (Iter->DefaultAttr) {
768   case DSA_shared:
769     DVar.CKind = OMPC_shared;
770     DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
771     return DVar;
772   case DSA_none:
773     return DVar;
774   case DSA_unspecified:
775     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
776     // in a Construct, implicitly determined, p.2]
777     //  In a parallel construct, if no default clause is present, these
778     //  variables are shared.
779     DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
780     if (isOpenMPParallelDirective(DVar.DKind) ||
781         isOpenMPTeamsDirective(DVar.DKind)) {
782       DVar.CKind = OMPC_shared;
783       return DVar;
784     }
785 
786     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
787     // in a Construct, implicitly determined, p.4]
788     //  In a task construct, if no default clause is present, a variable that in
789     //  the enclosing context is determined to be shared by all implicit tasks
790     //  bound to the current team is shared.
791     if (isOpenMPTaskingDirective(DVar.DKind)) {
792       DSAVarData DVarTemp;
793       iterator I = Iter, E = Stack.back().first.rend();
794       do {
795         ++I;
796         // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
797         // Referenced in a Construct, implicitly determined, p.6]
798         //  In a task construct, if no default clause is present, a variable
799         //  whose data-sharing attribute is not determined by the rules above is
800         //  firstprivate.
801         DVarTemp = getDSA(I, D);
802         if (DVarTemp.CKind != OMPC_shared) {
803           DVar.RefExpr = nullptr;
804           DVar.CKind = OMPC_firstprivate;
805           return DVar;
806         }
807       } while (I != E && !isParallelOrTaskRegion(I->Directive));
808       DVar.CKind =
809           (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
810       return DVar;
811     }
812   }
813   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
814   // in a Construct, implicitly determined, p.3]
815   //  For constructs other than task, if no default clause is present, these
816   //  variables inherit their data-sharing attributes from the enclosing
817   //  context.
818   return getDSA(++Iter, D);
819 }
820 
821 const Expr *DSAStackTy::addUniqueAligned(const ValueDecl *D,
822                                          const Expr *NewDE) {
823   assert(!isStackEmpty() && "Data sharing attributes stack is empty");
824   D = getCanonicalDecl(D);
825   SharingMapTy &StackElem = Stack.back().first.back();
826   auto It = StackElem.AlignedMap.find(D);
827   if (It == StackElem.AlignedMap.end()) {
828     assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
829     StackElem.AlignedMap[D] = NewDE;
830     return nullptr;
831   }
832   assert(It->second && "Unexpected nullptr expr in the aligned map");
833   return It->second;
834 }
835 
836 void DSAStackTy::addLoopControlVariable(const ValueDecl *D, VarDecl *Capture) {
837   assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
838   D = getCanonicalDecl(D);
839   SharingMapTy &StackElem = Stack.back().first.back();
840   StackElem.LCVMap.try_emplace(
841       D, LCDeclInfo(StackElem.LCVMap.size() + 1, Capture));
842 }
843 
844 const DSAStackTy::LCDeclInfo
845 DSAStackTy::isLoopControlVariable(const ValueDecl *D) const {
846   assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
847   D = getCanonicalDecl(D);
848   const SharingMapTy &StackElem = Stack.back().first.back();
849   auto It = StackElem.LCVMap.find(D);
850   if (It != StackElem.LCVMap.end())
851     return It->second;
852   return {0, nullptr};
853 }
854 
855 const DSAStackTy::LCDeclInfo
856 DSAStackTy::isParentLoopControlVariable(const ValueDecl *D) const {
857   assert(!isStackEmpty() && Stack.back().first.size() > 1 &&
858          "Data-sharing attributes stack is empty");
859   D = getCanonicalDecl(D);
860   const SharingMapTy &StackElem = *std::next(Stack.back().first.rbegin());
861   auto It = StackElem.LCVMap.find(D);
862   if (It != StackElem.LCVMap.end())
863     return It->second;
864   return {0, nullptr};
865 }
866 
867 const ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) const {
868   assert(!isStackEmpty() && Stack.back().first.size() > 1 &&
869          "Data-sharing attributes stack is empty");
870   const SharingMapTy &StackElem = *std::next(Stack.back().first.rbegin());
871   if (StackElem.LCVMap.size() < I)
872     return nullptr;
873   for (const auto &Pair : StackElem.LCVMap)
874     if (Pair.second.first == I)
875       return Pair.first;
876   return nullptr;
877 }
878 
879 void DSAStackTy::addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
880                         DeclRefExpr *PrivateCopy) {
881   D = getCanonicalDecl(D);
882   if (A == OMPC_threadprivate) {
883     DSAInfo &Data = Threadprivates[D];
884     Data.Attributes = A;
885     Data.RefExpr.setPointer(E);
886     Data.PrivateCopy = nullptr;
887   } else {
888     assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
889     DSAInfo &Data = Stack.back().first.back().SharingMap[D];
890     assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
891            (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) ||
892            (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) ||
893            (isLoopControlVariable(D).first && A == OMPC_private));
894     if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) {
895       Data.RefExpr.setInt(/*IntVal=*/true);
896       return;
897     }
898     const bool IsLastprivate =
899         A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate;
900     Data.Attributes = A;
901     Data.RefExpr.setPointerAndInt(E, IsLastprivate);
902     Data.PrivateCopy = PrivateCopy;
903     if (PrivateCopy) {
904       DSAInfo &Data =
905           Stack.back().first.back().SharingMap[PrivateCopy->getDecl()];
906       Data.Attributes = A;
907       Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate);
908       Data.PrivateCopy = nullptr;
909     }
910   }
911 }
912 
913 /// Build a variable declaration for OpenMP loop iteration variable.
914 static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
915                              StringRef Name, const AttrVec *Attrs = nullptr,
916                              DeclRefExpr *OrigRef = nullptr) {
917   DeclContext *DC = SemaRef.CurContext;
918   IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
919   TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
920   auto *Decl =
921       VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
922   if (Attrs) {
923     for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
924          I != E; ++I)
925       Decl->addAttr(*I);
926   }
927   Decl->setImplicit();
928   if (OrigRef) {
929     Decl->addAttr(
930         OMPReferencedVarAttr::CreateImplicit(SemaRef.Context, OrigRef));
931   }
932   return Decl;
933 }
934 
935 static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
936                                      SourceLocation Loc,
937                                      bool RefersToCapture = false) {
938   D->setReferenced();
939   D->markUsed(S.Context);
940   return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
941                              SourceLocation(), D, RefersToCapture, Loc, Ty,
942                              VK_LValue);
943 }
944 
945 void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
946                                            BinaryOperatorKind BOK) {
947   D = getCanonicalDecl(D);
948   assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
949   assert(
950       Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction &&
951       "Additional reduction info may be specified only for reduction items.");
952   ReductionData &ReductionData = Stack.back().first.back().ReductionMap[D];
953   assert(ReductionData.ReductionRange.isInvalid() &&
954          Stack.back().first.back().Directive == OMPD_taskgroup &&
955          "Additional reduction info may be specified only once for reduction "
956          "items.");
957   ReductionData.set(BOK, SR);
958   Expr *&TaskgroupReductionRef =
959       Stack.back().first.back().TaskgroupReductionRef;
960   if (!TaskgroupReductionRef) {
961     VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
962                                SemaRef.Context.VoidPtrTy, ".task_red.");
963     TaskgroupReductionRef =
964         buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
965   }
966 }
967 
968 void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
969                                            const Expr *ReductionRef) {
970   D = getCanonicalDecl(D);
971   assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
972   assert(
973       Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction &&
974       "Additional reduction info may be specified only for reduction items.");
975   ReductionData &ReductionData = Stack.back().first.back().ReductionMap[D];
976   assert(ReductionData.ReductionRange.isInvalid() &&
977          Stack.back().first.back().Directive == OMPD_taskgroup &&
978          "Additional reduction info may be specified only once for reduction "
979          "items.");
980   ReductionData.set(ReductionRef, SR);
981   Expr *&TaskgroupReductionRef =
982       Stack.back().first.back().TaskgroupReductionRef;
983   if (!TaskgroupReductionRef) {
984     VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
985                                SemaRef.Context.VoidPtrTy, ".task_red.");
986     TaskgroupReductionRef =
987         buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
988   }
989 }
990 
991 const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
992     const ValueDecl *D, SourceRange &SR, BinaryOperatorKind &BOK,
993     Expr *&TaskgroupDescriptor) const {
994   D = getCanonicalDecl(D);
995   assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
996   if (Stack.back().first.empty())
997       return DSAVarData();
998   for (iterator I = std::next(Stack.back().first.rbegin(), 1),
999                 E = Stack.back().first.rend();
1000        I != E; std::advance(I, 1)) {
1001     const DSAInfo &Data = I->SharingMap.lookup(D);
1002     if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
1003       continue;
1004     const ReductionData &ReductionData = I->ReductionMap.lookup(D);
1005     if (!ReductionData.ReductionOp ||
1006         ReductionData.ReductionOp.is<const Expr *>())
1007       return DSAVarData();
1008     SR = ReductionData.ReductionRange;
1009     BOK = ReductionData.ReductionOp.get<ReductionData::BOKPtrType>();
1010     assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
1011                                        "expression for the descriptor is not "
1012                                        "set.");
1013     TaskgroupDescriptor = I->TaskgroupReductionRef;
1014     return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
1015                       Data.PrivateCopy, I->DefaultAttrLoc);
1016   }
1017   return DSAVarData();
1018 }
1019 
1020 const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
1021     const ValueDecl *D, SourceRange &SR, const Expr *&ReductionRef,
1022     Expr *&TaskgroupDescriptor) const {
1023   D = getCanonicalDecl(D);
1024   assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
1025   if (Stack.back().first.empty())
1026       return DSAVarData();
1027   for (iterator I = std::next(Stack.back().first.rbegin(), 1),
1028                 E = Stack.back().first.rend();
1029        I != E; std::advance(I, 1)) {
1030     const DSAInfo &Data = I->SharingMap.lookup(D);
1031     if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
1032       continue;
1033     const ReductionData &ReductionData = I->ReductionMap.lookup(D);
1034     if (!ReductionData.ReductionOp ||
1035         !ReductionData.ReductionOp.is<const Expr *>())
1036       return DSAVarData();
1037     SR = ReductionData.ReductionRange;
1038     ReductionRef = ReductionData.ReductionOp.get<const Expr *>();
1039     assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
1040                                        "expression for the descriptor is not "
1041                                        "set.");
1042     TaskgroupDescriptor = I->TaskgroupReductionRef;
1043     return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
1044                       Data.PrivateCopy, I->DefaultAttrLoc);
1045   }
1046   return DSAVarData();
1047 }
1048 
1049 bool DSAStackTy::isOpenMPLocal(VarDecl *D, iterator Iter) const {
1050   D = D->getCanonicalDecl();
1051   if (!isStackEmpty()) {
1052     iterator I = Iter, E = Stack.back().first.rend();
1053     Scope *TopScope = nullptr;
1054     while (I != E && !isParallelOrTaskRegion(I->Directive) &&
1055            !isOpenMPTargetExecutionDirective(I->Directive))
1056       ++I;
1057     if (I == E)
1058       return false;
1059     TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
1060     Scope *CurScope = getCurScope();
1061     while (CurScope != TopScope && !CurScope->isDeclScope(D))
1062       CurScope = CurScope->getParent();
1063     return CurScope != TopScope;
1064   }
1065   return false;
1066 }
1067 
1068 const DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D,
1069                                                    bool FromParent) {
1070   D = getCanonicalDecl(D);
1071   DSAVarData DVar;
1072 
1073   auto *VD = dyn_cast<VarDecl>(D);
1074   auto TI = Threadprivates.find(D);
1075   if (TI != Threadprivates.end()) {
1076     DVar.RefExpr = TI->getSecond().RefExpr.getPointer();
1077     DVar.CKind = OMPC_threadprivate;
1078     return DVar;
1079   }
1080   if (VD && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
1081     DVar.RefExpr = buildDeclRefExpr(
1082         SemaRef, VD, D->getType().getNonReferenceType(),
1083         VD->getAttr<OMPThreadPrivateDeclAttr>()->getLocation());
1084     DVar.CKind = OMPC_threadprivate;
1085     addDSA(D, DVar.RefExpr, OMPC_threadprivate);
1086     return DVar;
1087   }
1088   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1089   // in a Construct, C/C++, predetermined, p.1]
1090   //  Variables appearing in threadprivate directives are threadprivate.
1091   if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
1092        !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
1093          SemaRef.getLangOpts().OpenMPUseTLS &&
1094          SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
1095       (VD && VD->getStorageClass() == SC_Register &&
1096        VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
1097     DVar.RefExpr = buildDeclRefExpr(
1098         SemaRef, VD, D->getType().getNonReferenceType(), D->getLocation());
1099     DVar.CKind = OMPC_threadprivate;
1100     addDSA(D, DVar.RefExpr, OMPC_threadprivate);
1101     return DVar;
1102   }
1103   if (SemaRef.getLangOpts().OpenMPCUDAMode && VD &&
1104       VD->isLocalVarDeclOrParm() && !isStackEmpty() &&
1105       !isLoopControlVariable(D).first) {
1106     iterator IterTarget =
1107         std::find_if(Stack.back().first.rbegin(), Stack.back().first.rend(),
1108                      [](const SharingMapTy &Data) {
1109                        return isOpenMPTargetExecutionDirective(Data.Directive);
1110                      });
1111     if (IterTarget != Stack.back().first.rend()) {
1112       iterator ParentIterTarget = std::next(IterTarget, 1);
1113       for (iterator Iter = Stack.back().first.rbegin();
1114            Iter != ParentIterTarget; std::advance(Iter, 1)) {
1115         if (isOpenMPLocal(VD, Iter)) {
1116           DVar.RefExpr =
1117               buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
1118                                D->getLocation());
1119           DVar.CKind = OMPC_threadprivate;
1120           return DVar;
1121         }
1122       }
1123       if (!isClauseParsingMode() || IterTarget != Stack.back().first.rbegin()) {
1124         auto DSAIter = IterTarget->SharingMap.find(D);
1125         if (DSAIter != IterTarget->SharingMap.end() &&
1126             isOpenMPPrivate(DSAIter->getSecond().Attributes)) {
1127           DVar.RefExpr = DSAIter->getSecond().RefExpr.getPointer();
1128           DVar.CKind = OMPC_threadprivate;
1129           return DVar;
1130         }
1131         iterator End = Stack.back().first.rend();
1132         if (!SemaRef.isOpenMPCapturedByRef(
1133                 D, std::distance(ParentIterTarget, End))) {
1134           DVar.RefExpr =
1135               buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
1136                                IterTarget->ConstructLoc);
1137           DVar.CKind = OMPC_threadprivate;
1138           return DVar;
1139         }
1140       }
1141     }
1142   }
1143 
1144   if (isStackEmpty())
1145     // Not in OpenMP execution region and top scope was already checked.
1146     return DVar;
1147 
1148   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1149   // in a Construct, C/C++, predetermined, p.4]
1150   //  Static data members are shared.
1151   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1152   // in a Construct, C/C++, predetermined, p.7]
1153   //  Variables with static storage duration that are declared in a scope
1154   //  inside the construct are shared.
1155   auto &&MatchesAlways = [](OpenMPDirectiveKind) { return true; };
1156   if (VD && VD->isStaticDataMember()) {
1157     DSAVarData DVarTemp = hasDSA(D, isOpenMPPrivate, MatchesAlways, FromParent);
1158     if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
1159       return DVar;
1160 
1161     DVar.CKind = OMPC_shared;
1162     return DVar;
1163   }
1164 
1165   QualType Type = D->getType().getNonReferenceType().getCanonicalType();
1166   bool IsConstant = Type.isConstant(SemaRef.getASTContext());
1167   Type = SemaRef.getASTContext().getBaseElementType(Type);
1168   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1169   // in a Construct, C/C++, predetermined, p.6]
1170   //  Variables with const qualified type having no mutable member are
1171   //  shared.
1172   const CXXRecordDecl *RD =
1173       SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
1174   if (const auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
1175     if (const ClassTemplateDecl *CTD = CTSD->getSpecializedTemplate())
1176       RD = CTD->getTemplatedDecl();
1177   if (IsConstant &&
1178       !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasDefinition() &&
1179         RD->hasMutableFields())) {
1180     // Variables with const-qualified type having no mutable member may be
1181     // listed in a firstprivate clause, even if they are static data members.
1182     DSAVarData DVarTemp =
1183         hasDSA(D, [](OpenMPClauseKind C) { return C == OMPC_firstprivate; },
1184                MatchesAlways, FromParent);
1185     if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr)
1186       return DVarTemp;
1187 
1188     DVar.CKind = OMPC_shared;
1189     return DVar;
1190   }
1191 
1192   // Explicitly specified attributes and local variables with predetermined
1193   // attributes.
1194   iterator I = Stack.back().first.rbegin();
1195   iterator EndI = Stack.back().first.rend();
1196   if (FromParent && I != EndI)
1197     std::advance(I, 1);
1198   auto It = I->SharingMap.find(D);
1199   if (It != I->SharingMap.end()) {
1200     const DSAInfo &Data = It->getSecond();
1201     DVar.RefExpr = Data.RefExpr.getPointer();
1202     DVar.PrivateCopy = Data.PrivateCopy;
1203     DVar.CKind = Data.Attributes;
1204     DVar.ImplicitDSALoc = I->DefaultAttrLoc;
1205     DVar.DKind = I->Directive;
1206   }
1207 
1208   return DVar;
1209 }
1210 
1211 const DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
1212                                                         bool FromParent) const {
1213   if (isStackEmpty()) {
1214     iterator I;
1215     return getDSA(I, D);
1216   }
1217   D = getCanonicalDecl(D);
1218   iterator StartI = Stack.back().first.rbegin();
1219   iterator EndI = Stack.back().first.rend();
1220   if (FromParent && StartI != EndI)
1221     std::advance(StartI, 1);
1222   return getDSA(StartI, D);
1223 }
1224 
1225 const DSAStackTy::DSAVarData
1226 DSAStackTy::hasDSA(ValueDecl *D,
1227                    const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
1228                    const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
1229                    bool FromParent) const {
1230   if (isStackEmpty())
1231     return {};
1232   D = getCanonicalDecl(D);
1233   iterator I = Stack.back().first.rbegin();
1234   iterator EndI = Stack.back().first.rend();
1235   if (FromParent && I != EndI)
1236     std::advance(I, 1);
1237   for (; I != EndI; std::advance(I, 1)) {
1238     if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive))
1239       continue;
1240     iterator NewI = I;
1241     DSAVarData DVar = getDSA(NewI, D);
1242     if (I == NewI && CPred(DVar.CKind))
1243       return DVar;
1244   }
1245   return {};
1246 }
1247 
1248 const DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
1249     ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
1250     const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
1251     bool FromParent) const {
1252   if (isStackEmpty())
1253     return {};
1254   D = getCanonicalDecl(D);
1255   iterator StartI = Stack.back().first.rbegin();
1256   iterator EndI = Stack.back().first.rend();
1257   if (FromParent && StartI != EndI)
1258     std::advance(StartI, 1);
1259   if (StartI == EndI || !DPred(StartI->Directive))
1260     return {};
1261   iterator NewI = StartI;
1262   DSAVarData DVar = getDSA(NewI, D);
1263   return (NewI == StartI && CPred(DVar.CKind)) ? DVar : DSAVarData();
1264 }
1265 
1266 bool DSAStackTy::hasExplicitDSA(
1267     const ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
1268     unsigned Level, bool NotLastprivate) const {
1269   if (isStackEmpty())
1270     return false;
1271   D = getCanonicalDecl(D);
1272   auto StartI = Stack.back().first.begin();
1273   auto EndI = Stack.back().first.end();
1274   if (std::distance(StartI, EndI) <= (int)Level)
1275     return false;
1276   std::advance(StartI, Level);
1277   auto I = StartI->SharingMap.find(D);
1278   if ((I != StartI->SharingMap.end()) &&
1279          I->getSecond().RefExpr.getPointer() &&
1280          CPred(I->getSecond().Attributes) &&
1281          (!NotLastprivate || !I->getSecond().RefExpr.getInt()))
1282     return true;
1283   // Check predetermined rules for the loop control variables.
1284   auto LI = StartI->LCVMap.find(D);
1285   if (LI != StartI->LCVMap.end())
1286     return CPred(OMPC_private);
1287   return false;
1288 }
1289 
1290 bool DSAStackTy::hasExplicitDirective(
1291     const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
1292     unsigned Level) const {
1293   if (isStackEmpty())
1294     return false;
1295   auto StartI = Stack.back().first.begin();
1296   auto EndI = Stack.back().first.end();
1297   if (std::distance(StartI, EndI) <= (int)Level)
1298     return false;
1299   std::advance(StartI, Level);
1300   return DPred(StartI->Directive);
1301 }
1302 
1303 bool DSAStackTy::hasDirective(
1304     const llvm::function_ref<bool(OpenMPDirectiveKind,
1305                                   const DeclarationNameInfo &, SourceLocation)>
1306         DPred,
1307     bool FromParent) const {
1308   // We look only in the enclosing region.
1309   if (isStackEmpty())
1310     return false;
1311   auto StartI = std::next(Stack.back().first.rbegin());
1312   auto EndI = Stack.back().first.rend();
1313   if (FromParent && StartI != EndI)
1314     StartI = std::next(StartI);
1315   for (auto I = StartI, EE = EndI; I != EE; ++I) {
1316     if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
1317       return true;
1318   }
1319   return false;
1320 }
1321 
1322 void Sema::InitDataSharingAttributesStack() {
1323   VarDataSharingAttributesStack = new DSAStackTy(*this);
1324 }
1325 
1326 #define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
1327 
1328 void Sema::pushOpenMPFunctionRegion() {
1329   DSAStack->pushFunction();
1330 }
1331 
1332 void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) {
1333   DSAStack->popFunction(OldFSI);
1334 }
1335 
1336 bool Sema::isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level) const {
1337   assert(LangOpts.OpenMP && "OpenMP is not allowed");
1338 
1339   ASTContext &Ctx = getASTContext();
1340   bool IsByRef = true;
1341 
1342   // Find the directive that is associated with the provided scope.
1343   D = cast<ValueDecl>(D->getCanonicalDecl());
1344   QualType Ty = D->getType();
1345 
1346   if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
1347     // This table summarizes how a given variable should be passed to the device
1348     // given its type and the clauses where it appears. This table is based on
1349     // the description in OpenMP 4.5 [2.10.4, target Construct] and
1350     // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
1351     //
1352     // =========================================================================
1353     // | type |  defaultmap   | pvt | first | is_device_ptr |    map   | res.  |
1354     // |      |(tofrom:scalar)|     |  pvt  |               |          |       |
1355     // =========================================================================
1356     // | scl  |               |     |       |       -       |          | bycopy|
1357     // | scl  |               |  -  |   x   |       -       |     -    | bycopy|
1358     // | scl  |               |  x  |   -   |       -       |     -    | null  |
1359     // | scl  |       x       |     |       |       -       |          | byref |
1360     // | scl  |       x       |  -  |   x   |       -       |     -    | bycopy|
1361     // | scl  |       x       |  x  |   -   |       -       |     -    | null  |
1362     // | scl  |               |  -  |   -   |       -       |     x    | byref |
1363     // | scl  |       x       |  -  |   -   |       -       |     x    | byref |
1364     //
1365     // | agg  |      n.a.     |     |       |       -       |          | byref |
1366     // | agg  |      n.a.     |  -  |   x   |       -       |     -    | byref |
1367     // | agg  |      n.a.     |  x  |   -   |       -       |     -    | null  |
1368     // | agg  |      n.a.     |  -  |   -   |       -       |     x    | byref |
1369     // | agg  |      n.a.     |  -  |   -   |       -       |    x[]   | byref |
1370     //
1371     // | ptr  |      n.a.     |     |       |       -       |          | bycopy|
1372     // | ptr  |      n.a.     |  -  |   x   |       -       |     -    | bycopy|
1373     // | ptr  |      n.a.     |  x  |   -   |       -       |     -    | null  |
1374     // | ptr  |      n.a.     |  -  |   -   |       -       |     x    | byref |
1375     // | ptr  |      n.a.     |  -  |   -   |       -       |    x[]   | bycopy|
1376     // | ptr  |      n.a.     |  -  |   -   |       x       |          | bycopy|
1377     // | ptr  |      n.a.     |  -  |   -   |       x       |     x    | bycopy|
1378     // | ptr  |      n.a.     |  -  |   -   |       x       |    x[]   | bycopy|
1379     // =========================================================================
1380     // Legend:
1381     //  scl - scalar
1382     //  ptr - pointer
1383     //  agg - aggregate
1384     //  x - applies
1385     //  - - invalid in this combination
1386     //  [] - mapped with an array section
1387     //  byref - should be mapped by reference
1388     //  byval - should be mapped by value
1389     //  null - initialize a local variable to null on the device
1390     //
1391     // Observations:
1392     //  - All scalar declarations that show up in a map clause have to be passed
1393     //    by reference, because they may have been mapped in the enclosing data
1394     //    environment.
1395     //  - If the scalar value does not fit the size of uintptr, it has to be
1396     //    passed by reference, regardless the result in the table above.
1397     //  - For pointers mapped by value that have either an implicit map or an
1398     //    array section, the runtime library may pass the NULL value to the
1399     //    device instead of the value passed to it by the compiler.
1400 
1401     if (Ty->isReferenceType())
1402       Ty = Ty->castAs<ReferenceType>()->getPointeeType();
1403 
1404     // Locate map clauses and see if the variable being captured is referred to
1405     // in any of those clauses. Here we only care about variables, not fields,
1406     // because fields are part of aggregates.
1407     bool IsVariableUsedInMapClause = false;
1408     bool IsVariableAssociatedWithSection = false;
1409 
1410     DSAStack->checkMappableExprComponentListsForDeclAtLevel(
1411         D, Level,
1412         [&IsVariableUsedInMapClause, &IsVariableAssociatedWithSection, D](
1413             OMPClauseMappableExprCommon::MappableExprComponentListRef
1414                 MapExprComponents,
1415             OpenMPClauseKind WhereFoundClauseKind) {
1416           // Only the map clause information influences how a variable is
1417           // captured. E.g. is_device_ptr does not require changing the default
1418           // behavior.
1419           if (WhereFoundClauseKind != OMPC_map)
1420             return false;
1421 
1422           auto EI = MapExprComponents.rbegin();
1423           auto EE = MapExprComponents.rend();
1424 
1425           assert(EI != EE && "Invalid map expression!");
1426 
1427           if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
1428             IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
1429 
1430           ++EI;
1431           if (EI == EE)
1432             return false;
1433 
1434           if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
1435               isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
1436               isa<MemberExpr>(EI->getAssociatedExpression())) {
1437             IsVariableAssociatedWithSection = true;
1438             // There is nothing more we need to know about this variable.
1439             return true;
1440           }
1441 
1442           // Keep looking for more map info.
1443           return false;
1444         });
1445 
1446     if (IsVariableUsedInMapClause) {
1447       // If variable is identified in a map clause it is always captured by
1448       // reference except if it is a pointer that is dereferenced somehow.
1449       IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
1450     } else {
1451       // By default, all the data that has a scalar type is mapped by copy
1452       // (except for reduction variables).
1453       IsByRef =
1454           (DSAStack->isForceCaptureByReferenceInTargetExecutable() &&
1455            !Ty->isAnyPointerType()) ||
1456           !Ty->isScalarType() ||
1457           DSAStack->getDefaultDMAAtLevel(Level) == DMA_tofrom_scalar ||
1458           DSAStack->hasExplicitDSA(
1459               D, [](OpenMPClauseKind K) { return K == OMPC_reduction; }, Level);
1460     }
1461   }
1462 
1463   if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
1464     IsByRef =
1465         ((DSAStack->isForceCaptureByReferenceInTargetExecutable() &&
1466           !Ty->isAnyPointerType()) ||
1467          !DSAStack->hasExplicitDSA(
1468              D,
1469              [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; },
1470              Level, /*NotLastprivate=*/true)) &&
1471         // If the variable is artificial and must be captured by value - try to
1472         // capture by value.
1473         !(isa<OMPCapturedExprDecl>(D) && !D->hasAttr<OMPCaptureNoInitAttr>() &&
1474           !cast<OMPCapturedExprDecl>(D)->getInit()->isGLValue());
1475   }
1476 
1477   // When passing data by copy, we need to make sure it fits the uintptr size
1478   // and alignment, because the runtime library only deals with uintptr types.
1479   // If it does not fit the uintptr size, we need to pass the data by reference
1480   // instead.
1481   if (!IsByRef &&
1482       (Ctx.getTypeSizeInChars(Ty) >
1483            Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
1484        Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
1485     IsByRef = true;
1486   }
1487 
1488   return IsByRef;
1489 }
1490 
1491 unsigned Sema::getOpenMPNestingLevel() const {
1492   assert(getLangOpts().OpenMP);
1493   return DSAStack->getNestingLevel();
1494 }
1495 
1496 bool Sema::isInOpenMPTargetExecutionDirective() const {
1497   return (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) &&
1498           !DSAStack->isClauseParsingMode()) ||
1499          DSAStack->hasDirective(
1500              [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
1501                 SourceLocation) -> bool {
1502                return isOpenMPTargetExecutionDirective(K);
1503              },
1504              false);
1505 }
1506 
1507 VarDecl *Sema::isOpenMPCapturedDecl(ValueDecl *D) {
1508   assert(LangOpts.OpenMP && "OpenMP is not allowed");
1509   D = getCanonicalDecl(D);
1510 
1511   // If we are attempting to capture a global variable in a directive with
1512   // 'target' we return true so that this global is also mapped to the device.
1513   //
1514   auto *VD = dyn_cast<VarDecl>(D);
1515   if (VD && !VD->hasLocalStorage()) {
1516     if (isInOpenMPDeclareTargetContext() &&
1517         (getCurCapturedRegion() || getCurBlock() || getCurLambda())) {
1518       // Try to mark variable as declare target if it is used in capturing
1519       // regions.
1520       if (!OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
1521         checkDeclIsAllowedInOpenMPTarget(nullptr, VD);
1522       return nullptr;
1523     } else if (isInOpenMPTargetExecutionDirective()) {
1524       // If the declaration is enclosed in a 'declare target' directive,
1525       // then it should not be captured.
1526       //
1527       if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
1528         return nullptr;
1529       return VD;
1530     }
1531   }
1532   // Capture variables captured by reference in lambdas for target-based
1533   // directives.
1534   if (VD && !DSAStack->isClauseParsingMode()) {
1535     if (const auto *RD = VD->getType()
1536                              .getCanonicalType()
1537                              .getNonReferenceType()
1538                              ->getAsCXXRecordDecl()) {
1539       bool SavedForceCaptureByReferenceInTargetExecutable =
1540           DSAStack->isForceCaptureByReferenceInTargetExecutable();
1541       DSAStack->setForceCaptureByReferenceInTargetExecutable(/*V=*/true);
1542       if (RD->isLambda()) {
1543         llvm::DenseMap<const VarDecl *, FieldDecl *> Captures;
1544         FieldDecl *ThisCapture;
1545         RD->getCaptureFields(Captures, ThisCapture);
1546         for (const LambdaCapture &LC : RD->captures()) {
1547           if (LC.getCaptureKind() == LCK_ByRef) {
1548             VarDecl *VD = LC.getCapturedVar();
1549             DeclContext *VDC = VD->getDeclContext();
1550             if (!VDC->Encloses(CurContext))
1551               continue;
1552             DSAStackTy::DSAVarData DVarPrivate =
1553                 DSAStack->getTopDSA(VD, /*FromParent=*/false);
1554             // Do not capture already captured variables.
1555             if (!OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD) &&
1556                 DVarPrivate.CKind == OMPC_unknown &&
1557                 !DSAStack->checkMappableExprComponentListsForDecl(
1558                     D, /*CurrentRegionOnly=*/true,
1559                     [](OMPClauseMappableExprCommon::
1560                            MappableExprComponentListRef,
1561                        OpenMPClauseKind) { return true; }))
1562               MarkVariableReferenced(LC.getLocation(), LC.getCapturedVar());
1563           } else if (LC.getCaptureKind() == LCK_This) {
1564             QualType ThisTy = getCurrentThisType();
1565             if (!ThisTy.isNull() &&
1566                 Context.typesAreCompatible(ThisTy, ThisCapture->getType()))
1567               CheckCXXThisCapture(LC.getLocation());
1568           }
1569         }
1570       }
1571       DSAStack->setForceCaptureByReferenceInTargetExecutable(
1572           SavedForceCaptureByReferenceInTargetExecutable);
1573     }
1574   }
1575 
1576   if (DSAStack->getCurrentDirective() != OMPD_unknown &&
1577       (!DSAStack->isClauseParsingMode() ||
1578        DSAStack->getParentDirective() != OMPD_unknown)) {
1579     auto &&Info = DSAStack->isLoopControlVariable(D);
1580     if (Info.first ||
1581         (VD && VD->hasLocalStorage() &&
1582          isParallelOrTaskRegion(DSAStack->getCurrentDirective())) ||
1583         (VD && DSAStack->isForceVarCapturing()))
1584       return VD ? VD : Info.second;
1585     DSAStackTy::DSAVarData DVarPrivate =
1586         DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
1587     if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
1588       return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
1589     DVarPrivate = DSAStack->hasDSA(D, isOpenMPPrivate,
1590                                    [](OpenMPDirectiveKind) { return true; },
1591                                    DSAStack->isClauseParsingMode());
1592     if (DVarPrivate.CKind != OMPC_unknown)
1593       return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
1594   }
1595   return nullptr;
1596 }
1597 
1598 void Sema::adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex,
1599                                         unsigned Level) const {
1600   SmallVector<OpenMPDirectiveKind, 4> Regions;
1601   getOpenMPCaptureRegions(Regions, DSAStack->getDirective(Level));
1602   FunctionScopesIndex -= Regions.size();
1603 }
1604 
1605 void Sema::startOpenMPLoop() {
1606   assert(LangOpts.OpenMP && "OpenMP must be enabled.");
1607   if (isOpenMPLoopDirective(DSAStack->getCurrentDirective()))
1608     DSAStack->loopInit();
1609 }
1610 
1611 bool Sema::isOpenMPPrivateDecl(const ValueDecl *D, unsigned Level) const {
1612   assert(LangOpts.OpenMP && "OpenMP is not allowed");
1613   if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
1614     if (DSAStack->getAssociatedLoops() > 0 &&
1615         !DSAStack->isLoopStarted()) {
1616       DSAStack->resetPossibleLoopCounter(D);
1617       DSAStack->loopStart();
1618       return true;
1619     }
1620     if ((DSAStack->getPossiblyLoopCunter() == D->getCanonicalDecl() ||
1621          DSAStack->isLoopControlVariable(D).first) &&
1622         !DSAStack->hasExplicitDSA(
1623             D, [](OpenMPClauseKind K) { return K != OMPC_private; }, Level) &&
1624         !isOpenMPSimdDirective(DSAStack->getCurrentDirective()))
1625       return true;
1626   }
1627   return DSAStack->hasExplicitDSA(
1628              D, [](OpenMPClauseKind K) { return K == OMPC_private; }, Level) ||
1629          (DSAStack->isClauseParsingMode() &&
1630           DSAStack->getClauseParsingMode() == OMPC_private) ||
1631          // Consider taskgroup reduction descriptor variable a private to avoid
1632          // possible capture in the region.
1633          (DSAStack->hasExplicitDirective(
1634               [](OpenMPDirectiveKind K) { return K == OMPD_taskgroup; },
1635               Level) &&
1636           DSAStack->isTaskgroupReductionRef(D, Level));
1637 }
1638 
1639 void Sema::setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D,
1640                                 unsigned Level) {
1641   assert(LangOpts.OpenMP && "OpenMP is not allowed");
1642   D = getCanonicalDecl(D);
1643   OpenMPClauseKind OMPC = OMPC_unknown;
1644   for (unsigned I = DSAStack->getNestingLevel() + 1; I > Level; --I) {
1645     const unsigned NewLevel = I - 1;
1646     if (DSAStack->hasExplicitDSA(D,
1647                                  [&OMPC](const OpenMPClauseKind K) {
1648                                    if (isOpenMPPrivate(K)) {
1649                                      OMPC = K;
1650                                      return true;
1651                                    }
1652                                    return false;
1653                                  },
1654                                  NewLevel))
1655       break;
1656     if (DSAStack->checkMappableExprComponentListsForDeclAtLevel(
1657             D, NewLevel,
1658             [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
1659                OpenMPClauseKind) { return true; })) {
1660       OMPC = OMPC_map;
1661       break;
1662     }
1663     if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
1664                                        NewLevel)) {
1665       OMPC = OMPC_map;
1666       if (D->getType()->isScalarType() &&
1667           DSAStack->getDefaultDMAAtLevel(NewLevel) !=
1668               DefaultMapAttributes::DMA_tofrom_scalar)
1669         OMPC = OMPC_firstprivate;
1670       break;
1671     }
1672   }
1673   if (OMPC != OMPC_unknown)
1674     FD->addAttr(OMPCaptureKindAttr::CreateImplicit(Context, OMPC));
1675 }
1676 
1677 bool Sema::isOpenMPTargetCapturedDecl(const ValueDecl *D,
1678                                       unsigned Level) const {
1679   assert(LangOpts.OpenMP && "OpenMP is not allowed");
1680   // Return true if the current level is no longer enclosed in a target region.
1681 
1682   const auto *VD = dyn_cast<VarDecl>(D);
1683   return VD && !VD->hasLocalStorage() &&
1684          DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
1685                                         Level);
1686 }
1687 
1688 void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
1689 
1690 void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
1691                                const DeclarationNameInfo &DirName,
1692                                Scope *CurScope, SourceLocation Loc) {
1693   DSAStack->push(DKind, DirName, CurScope, Loc);
1694   PushExpressionEvaluationContext(
1695       ExpressionEvaluationContext::PotentiallyEvaluated);
1696 }
1697 
1698 void Sema::StartOpenMPClause(OpenMPClauseKind K) {
1699   DSAStack->setClauseParsingMode(K);
1700 }
1701 
1702 void Sema::EndOpenMPClause() {
1703   DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
1704 }
1705 
1706 void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
1707   // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
1708   //  A variable of class type (or array thereof) that appears in a lastprivate
1709   //  clause requires an accessible, unambiguous default constructor for the
1710   //  class type, unless the list item is also specified in a firstprivate
1711   //  clause.
1712   if (const auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
1713     for (OMPClause *C : D->clauses()) {
1714       if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
1715         SmallVector<Expr *, 8> PrivateCopies;
1716         for (Expr *DE : Clause->varlists()) {
1717           if (DE->isValueDependent() || DE->isTypeDependent()) {
1718             PrivateCopies.push_back(nullptr);
1719             continue;
1720           }
1721           auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
1722           auto *VD = cast<VarDecl>(DRE->getDecl());
1723           QualType Type = VD->getType().getNonReferenceType();
1724           const DSAStackTy::DSAVarData DVar =
1725               DSAStack->getTopDSA(VD, /*FromParent=*/false);
1726           if (DVar.CKind == OMPC_lastprivate) {
1727             // Generate helper private variable and initialize it with the
1728             // default value. The address of the original variable is replaced
1729             // by the address of the new private variable in CodeGen. This new
1730             // variable is not added to IdResolver, so the code in the OpenMP
1731             // region uses original variable for proper diagnostics.
1732             VarDecl *VDPrivate = buildVarDecl(
1733                 *this, DE->getExprLoc(), Type.getUnqualifiedType(),
1734                 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr, DRE);
1735             ActOnUninitializedDecl(VDPrivate);
1736             if (VDPrivate->isInvalidDecl())
1737               continue;
1738             PrivateCopies.push_back(buildDeclRefExpr(
1739                 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
1740           } else {
1741             // The variable is also a firstprivate, so initialization sequence
1742             // for private copy is generated already.
1743             PrivateCopies.push_back(nullptr);
1744           }
1745         }
1746         // Set initializers to private copies if no errors were found.
1747         if (PrivateCopies.size() == Clause->varlist_size())
1748           Clause->setPrivateCopies(PrivateCopies);
1749       }
1750     }
1751   }
1752 
1753   DSAStack->pop();
1754   DiscardCleanupsInEvaluationContext();
1755   PopExpressionEvaluationContext();
1756 }
1757 
1758 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
1759                                      Expr *NumIterations, Sema &SemaRef,
1760                                      Scope *S, DSAStackTy *Stack);
1761 
1762 namespace {
1763 
1764 class VarDeclFilterCCC final : public CorrectionCandidateCallback {
1765 private:
1766   Sema &SemaRef;
1767 
1768 public:
1769   explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
1770   bool ValidateCandidate(const TypoCorrection &Candidate) override {
1771     NamedDecl *ND = Candidate.getCorrectionDecl();
1772     if (const auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
1773       return VD->hasGlobalStorage() &&
1774              SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1775                                    SemaRef.getCurScope());
1776     }
1777     return false;
1778   }
1779 };
1780 
1781 class VarOrFuncDeclFilterCCC final : public CorrectionCandidateCallback {
1782 private:
1783   Sema &SemaRef;
1784 
1785 public:
1786   explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
1787   bool ValidateCandidate(const TypoCorrection &Candidate) override {
1788     NamedDecl *ND = Candidate.getCorrectionDecl();
1789     if (ND && (isa<VarDecl>(ND) || isa<FunctionDecl>(ND))) {
1790       return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1791                                    SemaRef.getCurScope());
1792     }
1793     return false;
1794   }
1795 };
1796 
1797 } // namespace
1798 
1799 ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
1800                                          CXXScopeSpec &ScopeSpec,
1801                                          const DeclarationNameInfo &Id) {
1802   LookupResult Lookup(*this, Id, LookupOrdinaryName);
1803   LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
1804 
1805   if (Lookup.isAmbiguous())
1806     return ExprError();
1807 
1808   VarDecl *VD;
1809   if (!Lookup.isSingleResult()) {
1810     if (TypoCorrection Corrected = CorrectTypo(
1811             Id, LookupOrdinaryName, CurScope, nullptr,
1812             llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) {
1813       diagnoseTypo(Corrected,
1814                    PDiag(Lookup.empty()
1815                              ? diag::err_undeclared_var_use_suggest
1816                              : diag::err_omp_expected_var_arg_suggest)
1817                        << Id.getName());
1818       VD = Corrected.getCorrectionDeclAs<VarDecl>();
1819     } else {
1820       Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
1821                                        : diag::err_omp_expected_var_arg)
1822           << Id.getName();
1823       return ExprError();
1824     }
1825   } else if (!(VD = Lookup.getAsSingle<VarDecl>())) {
1826     Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
1827     Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
1828     return ExprError();
1829   }
1830   Lookup.suppressDiagnostics();
1831 
1832   // OpenMP [2.9.2, Syntax, C/C++]
1833   //   Variables must be file-scope, namespace-scope, or static block-scope.
1834   if (!VD->hasGlobalStorage()) {
1835     Diag(Id.getLoc(), diag::err_omp_global_var_arg)
1836         << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal();
1837     bool IsDecl =
1838         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1839     Diag(VD->getLocation(),
1840          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1841         << VD;
1842     return ExprError();
1843   }
1844 
1845   VarDecl *CanonicalVD = VD->getCanonicalDecl();
1846   NamedDecl *ND = CanonicalVD;
1847   // OpenMP [2.9.2, Restrictions, C/C++, p.2]
1848   //   A threadprivate directive for file-scope variables must appear outside
1849   //   any definition or declaration.
1850   if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
1851       !getCurLexicalContext()->isTranslationUnit()) {
1852     Diag(Id.getLoc(), diag::err_omp_var_scope)
1853         << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1854     bool IsDecl =
1855         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1856     Diag(VD->getLocation(),
1857          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1858         << VD;
1859     return ExprError();
1860   }
1861   // OpenMP [2.9.2, Restrictions, C/C++, p.3]
1862   //   A threadprivate directive for static class member variables must appear
1863   //   in the class definition, in the same scope in which the member
1864   //   variables are declared.
1865   if (CanonicalVD->isStaticDataMember() &&
1866       !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
1867     Diag(Id.getLoc(), diag::err_omp_var_scope)
1868         << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1869     bool IsDecl =
1870         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1871     Diag(VD->getLocation(),
1872          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1873         << VD;
1874     return ExprError();
1875   }
1876   // OpenMP [2.9.2, Restrictions, C/C++, p.4]
1877   //   A threadprivate directive for namespace-scope variables must appear
1878   //   outside any definition or declaration other than the namespace
1879   //   definition itself.
1880   if (CanonicalVD->getDeclContext()->isNamespace() &&
1881       (!getCurLexicalContext()->isFileContext() ||
1882        !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
1883     Diag(Id.getLoc(), diag::err_omp_var_scope)
1884         << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1885     bool IsDecl =
1886         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1887     Diag(VD->getLocation(),
1888          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1889         << VD;
1890     return ExprError();
1891   }
1892   // OpenMP [2.9.2, Restrictions, C/C++, p.6]
1893   //   A threadprivate directive for static block-scope variables must appear
1894   //   in the scope of the variable and not in a nested scope.
1895   if (CanonicalVD->isStaticLocal() && CurScope &&
1896       !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
1897     Diag(Id.getLoc(), diag::err_omp_var_scope)
1898         << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1899     bool IsDecl =
1900         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1901     Diag(VD->getLocation(),
1902          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1903         << VD;
1904     return ExprError();
1905   }
1906 
1907   // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
1908   //   A threadprivate directive must lexically precede all references to any
1909   //   of the variables in its list.
1910   if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) {
1911     Diag(Id.getLoc(), diag::err_omp_var_used)
1912         << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1913     return ExprError();
1914   }
1915 
1916   QualType ExprType = VD->getType().getNonReferenceType();
1917   return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
1918                              SourceLocation(), VD,
1919                              /*RefersToEnclosingVariableOrCapture=*/false,
1920                              Id.getLoc(), ExprType, VK_LValue);
1921 }
1922 
1923 Sema::DeclGroupPtrTy
1924 Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
1925                                         ArrayRef<Expr *> VarList) {
1926   if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
1927     CurContext->addDecl(D);
1928     return DeclGroupPtrTy::make(DeclGroupRef(D));
1929   }
1930   return nullptr;
1931 }
1932 
1933 namespace {
1934 class LocalVarRefChecker final
1935     : public ConstStmtVisitor<LocalVarRefChecker, bool> {
1936   Sema &SemaRef;
1937 
1938 public:
1939   bool VisitDeclRefExpr(const DeclRefExpr *E) {
1940     if (const auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
1941       if (VD->hasLocalStorage()) {
1942         SemaRef.Diag(E->getBeginLoc(),
1943                      diag::err_omp_local_var_in_threadprivate_init)
1944             << E->getSourceRange();
1945         SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
1946             << VD << VD->getSourceRange();
1947         return true;
1948       }
1949     }
1950     return false;
1951   }
1952   bool VisitStmt(const Stmt *S) {
1953     for (const Stmt *Child : S->children()) {
1954       if (Child && Visit(Child))
1955         return true;
1956     }
1957     return false;
1958   }
1959   explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
1960 };
1961 } // namespace
1962 
1963 OMPThreadPrivateDecl *
1964 Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
1965   SmallVector<Expr *, 8> Vars;
1966   for (Expr *RefExpr : VarList) {
1967     auto *DE = cast<DeclRefExpr>(RefExpr);
1968     auto *VD = cast<VarDecl>(DE->getDecl());
1969     SourceLocation ILoc = DE->getExprLoc();
1970 
1971     // Mark variable as used.
1972     VD->setReferenced();
1973     VD->markUsed(Context);
1974 
1975     QualType QType = VD->getType();
1976     if (QType->isDependentType() || QType->isInstantiationDependentType()) {
1977       // It will be analyzed later.
1978       Vars.push_back(DE);
1979       continue;
1980     }
1981 
1982     // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1983     //   A threadprivate variable must not have an incomplete type.
1984     if (RequireCompleteType(ILoc, VD->getType(),
1985                             diag::err_omp_threadprivate_incomplete_type)) {
1986       continue;
1987     }
1988 
1989     // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1990     //   A threadprivate variable must not have a reference type.
1991     if (VD->getType()->isReferenceType()) {
1992       Diag(ILoc, diag::err_omp_ref_type_arg)
1993           << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
1994       bool IsDecl =
1995           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1996       Diag(VD->getLocation(),
1997            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1998           << VD;
1999       continue;
2000     }
2001 
2002     // Check if this is a TLS variable. If TLS is not being supported, produce
2003     // the corresponding diagnostic.
2004     if ((VD->getTLSKind() != VarDecl::TLS_None &&
2005          !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
2006            getLangOpts().OpenMPUseTLS &&
2007            getASTContext().getTargetInfo().isTLSSupported())) ||
2008         (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
2009          !VD->isLocalVarDecl())) {
2010       Diag(ILoc, diag::err_omp_var_thread_local)
2011           << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
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 initial value of threadprivate variable reference variable with
2021     // local storage (it is not supported by runtime).
2022     if (const Expr *Init = VD->getAnyInitializer()) {
2023       LocalVarRefChecker Checker(*this);
2024       if (Checker.Visit(Init))
2025         continue;
2026     }
2027 
2028     Vars.push_back(RefExpr);
2029     DSAStack->addDSA(VD, DE, OMPC_threadprivate);
2030     VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
2031         Context, SourceRange(Loc, Loc)));
2032     if (ASTMutationListener *ML = Context.getASTMutationListener())
2033       ML->DeclarationMarkedOpenMPThreadPrivate(VD);
2034   }
2035   OMPThreadPrivateDecl *D = nullptr;
2036   if (!Vars.empty()) {
2037     D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
2038                                      Vars);
2039     D->setAccess(AS_public);
2040   }
2041   return D;
2042 }
2043 
2044 Sema::DeclGroupPtrTy
2045 Sema::ActOnOpenMPRequiresDirective(SourceLocation Loc,
2046                                    ArrayRef<OMPClause *> ClauseList) {
2047   OMPRequiresDecl *D = nullptr;
2048   if (!CurContext->isFileContext()) {
2049     Diag(Loc, diag::err_omp_invalid_scope) << "requires";
2050   } else {
2051     D = CheckOMPRequiresDecl(Loc, ClauseList);
2052     if (D) {
2053       CurContext->addDecl(D);
2054       DSAStack->addRequiresDecl(D);
2055     }
2056   }
2057   return DeclGroupPtrTy::make(DeclGroupRef(D));
2058 }
2059 
2060 OMPRequiresDecl *Sema::CheckOMPRequiresDecl(SourceLocation Loc,
2061                                             ArrayRef<OMPClause *> ClauseList) {
2062   if (!DSAStack->hasDuplicateRequiresClause(ClauseList))
2063     return OMPRequiresDecl::Create(Context, getCurLexicalContext(), Loc,
2064                                    ClauseList);
2065   return nullptr;
2066 }
2067 
2068 static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack,
2069                               const ValueDecl *D,
2070                               const DSAStackTy::DSAVarData &DVar,
2071                               bool IsLoopIterVar = false) {
2072   if (DVar.RefExpr) {
2073     SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
2074         << getOpenMPClauseName(DVar.CKind);
2075     return;
2076   }
2077   enum {
2078     PDSA_StaticMemberShared,
2079     PDSA_StaticLocalVarShared,
2080     PDSA_LoopIterVarPrivate,
2081     PDSA_LoopIterVarLinear,
2082     PDSA_LoopIterVarLastprivate,
2083     PDSA_ConstVarShared,
2084     PDSA_GlobalVarShared,
2085     PDSA_TaskVarFirstprivate,
2086     PDSA_LocalVarPrivate,
2087     PDSA_Implicit
2088   } Reason = PDSA_Implicit;
2089   bool ReportHint = false;
2090   auto ReportLoc = D->getLocation();
2091   auto *VD = dyn_cast<VarDecl>(D);
2092   if (IsLoopIterVar) {
2093     if (DVar.CKind == OMPC_private)
2094       Reason = PDSA_LoopIterVarPrivate;
2095     else if (DVar.CKind == OMPC_lastprivate)
2096       Reason = PDSA_LoopIterVarLastprivate;
2097     else
2098       Reason = PDSA_LoopIterVarLinear;
2099   } else if (isOpenMPTaskingDirective(DVar.DKind) &&
2100              DVar.CKind == OMPC_firstprivate) {
2101     Reason = PDSA_TaskVarFirstprivate;
2102     ReportLoc = DVar.ImplicitDSALoc;
2103   } else if (VD && VD->isStaticLocal())
2104     Reason = PDSA_StaticLocalVarShared;
2105   else if (VD && VD->isStaticDataMember())
2106     Reason = PDSA_StaticMemberShared;
2107   else if (VD && VD->isFileVarDecl())
2108     Reason = PDSA_GlobalVarShared;
2109   else if (D->getType().isConstant(SemaRef.getASTContext()))
2110     Reason = PDSA_ConstVarShared;
2111   else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
2112     ReportHint = true;
2113     Reason = PDSA_LocalVarPrivate;
2114   }
2115   if (Reason != PDSA_Implicit) {
2116     SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
2117         << Reason << ReportHint
2118         << getOpenMPDirectiveName(Stack->getCurrentDirective());
2119   } else if (DVar.ImplicitDSALoc.isValid()) {
2120     SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
2121         << getOpenMPClauseName(DVar.CKind);
2122   }
2123 }
2124 
2125 namespace {
2126 class DSAAttrChecker final : public StmtVisitor<DSAAttrChecker, void> {
2127   DSAStackTy *Stack;
2128   Sema &SemaRef;
2129   bool ErrorFound = false;
2130   CapturedStmt *CS = nullptr;
2131   llvm::SmallVector<Expr *, 4> ImplicitFirstprivate;
2132   llvm::SmallVector<Expr *, 4> ImplicitMap;
2133   Sema::VarsWithInheritedDSAType VarsWithInheritedDSA;
2134   llvm::SmallDenseSet<const ValueDecl *, 4> ImplicitDeclarations;
2135 
2136   void VisitSubCaptures(OMPExecutableDirective *S) {
2137     // Check implicitly captured variables.
2138     if (!S->hasAssociatedStmt() || !S->getAssociatedStmt())
2139       return;
2140     for (const CapturedStmt::Capture &Cap :
2141          S->getInnermostCapturedStmt()->captures()) {
2142       if (!Cap.capturesVariable())
2143         continue;
2144       VarDecl *VD = Cap.getCapturedVar();
2145       // Do not try to map the variable if it or its sub-component was mapped
2146       // already.
2147       if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
2148           Stack->checkMappableExprComponentListsForDecl(
2149               VD, /*CurrentRegionOnly=*/true,
2150               [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
2151                  OpenMPClauseKind) { return true; }))
2152         continue;
2153       DeclRefExpr *DRE = buildDeclRefExpr(
2154           SemaRef, VD, VD->getType().getNonLValueExprType(SemaRef.Context),
2155           Cap.getLocation(), /*RefersToCapture=*/true);
2156       Visit(DRE);
2157     }
2158   }
2159 
2160 public:
2161   void VisitDeclRefExpr(DeclRefExpr *E) {
2162     if (E->isTypeDependent() || E->isValueDependent() ||
2163         E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
2164       return;
2165     if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
2166       VD = VD->getCanonicalDecl();
2167       // Skip internally declared variables.
2168       if (VD->hasLocalStorage() && !CS->capturesVariable(VD))
2169         return;
2170 
2171       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
2172       // Check if the variable has explicit DSA set and stop analysis if it so.
2173       if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second)
2174         return;
2175 
2176       // Skip internally declared static variables.
2177       llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
2178           OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
2179       if (VD->hasGlobalStorage() && !CS->capturesVariable(VD) &&
2180           (!Res || *Res != OMPDeclareTargetDeclAttr::MT_Link))
2181         return;
2182 
2183       SourceLocation ELoc = E->getExprLoc();
2184       OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
2185       // The default(none) clause requires that each variable that is referenced
2186       // in the construct, and does not have a predetermined data-sharing
2187       // attribute, must have its data-sharing attribute explicitly determined
2188       // by being listed in a data-sharing attribute clause.
2189       if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
2190           isParallelOrTaskRegion(DKind) &&
2191           VarsWithInheritedDSA.count(VD) == 0) {
2192         VarsWithInheritedDSA[VD] = E;
2193         return;
2194       }
2195 
2196       if (isOpenMPTargetExecutionDirective(DKind) &&
2197           !Stack->isLoopControlVariable(VD).first) {
2198         if (!Stack->checkMappableExprComponentListsForDecl(
2199                 VD, /*CurrentRegionOnly=*/true,
2200                 [](OMPClauseMappableExprCommon::MappableExprComponentListRef
2201                        StackComponents,
2202                    OpenMPClauseKind) {
2203                   // Variable is used if it has been marked as an array, array
2204                   // section or the variable iself.
2205                   return StackComponents.size() == 1 ||
2206                          std::all_of(
2207                              std::next(StackComponents.rbegin()),
2208                              StackComponents.rend(),
2209                              [](const OMPClauseMappableExprCommon::
2210                                     MappableComponent &MC) {
2211                                return MC.getAssociatedDeclaration() ==
2212                                           nullptr &&
2213                                       (isa<OMPArraySectionExpr>(
2214                                            MC.getAssociatedExpression()) ||
2215                                        isa<ArraySubscriptExpr>(
2216                                            MC.getAssociatedExpression()));
2217                              });
2218                 })) {
2219           bool IsFirstprivate = false;
2220           // By default lambdas are captured as firstprivates.
2221           if (const auto *RD =
2222                   VD->getType().getNonReferenceType()->getAsCXXRecordDecl())
2223             IsFirstprivate = RD->isLambda();
2224           IsFirstprivate =
2225               IsFirstprivate ||
2226               (VD->getType().getNonReferenceType()->isScalarType() &&
2227                Stack->getDefaultDMA() != DMA_tofrom_scalar && !Res);
2228           if (IsFirstprivate)
2229             ImplicitFirstprivate.emplace_back(E);
2230           else
2231             ImplicitMap.emplace_back(E);
2232           return;
2233         }
2234       }
2235 
2236       // OpenMP [2.9.3.6, Restrictions, p.2]
2237       //  A list item that appears in a reduction clause of the innermost
2238       //  enclosing worksharing or parallel construct may not be accessed in an
2239       //  explicit task.
2240       DVar = Stack->hasInnermostDSA(
2241           VD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
2242           [](OpenMPDirectiveKind K) {
2243             return isOpenMPParallelDirective(K) ||
2244                    isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
2245           },
2246           /*FromParent=*/true);
2247       if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
2248         ErrorFound = true;
2249         SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
2250         reportOriginalDsa(SemaRef, Stack, VD, DVar);
2251         return;
2252       }
2253 
2254       // Define implicit data-sharing attributes for task.
2255       DVar = Stack->getImplicitDSA(VD, /*FromParent=*/false);
2256       if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
2257           !Stack->isLoopControlVariable(VD).first)
2258         ImplicitFirstprivate.push_back(E);
2259     }
2260   }
2261   void VisitMemberExpr(MemberExpr *E) {
2262     if (E->isTypeDependent() || E->isValueDependent() ||
2263         E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
2264       return;
2265     auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
2266     OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
2267     if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
2268       if (!FD)
2269         return;
2270       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(FD, /*FromParent=*/false);
2271       // Check if the variable has explicit DSA set and stop analysis if it
2272       // so.
2273       if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second)
2274         return;
2275 
2276       if (isOpenMPTargetExecutionDirective(DKind) &&
2277           !Stack->isLoopControlVariable(FD).first &&
2278           !Stack->checkMappableExprComponentListsForDecl(
2279               FD, /*CurrentRegionOnly=*/true,
2280               [](OMPClauseMappableExprCommon::MappableExprComponentListRef
2281                      StackComponents,
2282                  OpenMPClauseKind) {
2283                 return isa<CXXThisExpr>(
2284                     cast<MemberExpr>(
2285                         StackComponents.back().getAssociatedExpression())
2286                         ->getBase()
2287                         ->IgnoreParens());
2288               })) {
2289         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
2290         //  A bit-field cannot appear in a map clause.
2291         //
2292         if (FD->isBitField())
2293           return;
2294         ImplicitMap.emplace_back(E);
2295         return;
2296       }
2297 
2298       SourceLocation ELoc = E->getExprLoc();
2299       // OpenMP [2.9.3.6, Restrictions, p.2]
2300       //  A list item that appears in a reduction clause of the innermost
2301       //  enclosing worksharing or parallel construct may not be accessed in
2302       //  an  explicit task.
2303       DVar = Stack->hasInnermostDSA(
2304           FD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
2305           [](OpenMPDirectiveKind K) {
2306             return isOpenMPParallelDirective(K) ||
2307                    isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
2308           },
2309           /*FromParent=*/true);
2310       if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
2311         ErrorFound = true;
2312         SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
2313         reportOriginalDsa(SemaRef, Stack, FD, DVar);
2314         return;
2315       }
2316 
2317       // Define implicit data-sharing attributes for task.
2318       DVar = Stack->getImplicitDSA(FD, /*FromParent=*/false);
2319       if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
2320           !Stack->isLoopControlVariable(FD).first) {
2321         // Check if there is a captured expression for the current field in the
2322         // region. Do not mark it as firstprivate unless there is no captured
2323         // expression.
2324         // TODO: try to make it firstprivate.
2325         if (DVar.CKind != OMPC_unknown)
2326           ImplicitFirstprivate.push_back(E);
2327       }
2328       return;
2329     }
2330     if (isOpenMPTargetExecutionDirective(DKind)) {
2331       OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
2332       if (!checkMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map,
2333                                         /*NoDiagnose=*/true))
2334         return;
2335       const auto *VD = cast<ValueDecl>(
2336           CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl());
2337       if (!Stack->checkMappableExprComponentListsForDecl(
2338               VD, /*CurrentRegionOnly=*/true,
2339               [&CurComponents](
2340                   OMPClauseMappableExprCommon::MappableExprComponentListRef
2341                       StackComponents,
2342                   OpenMPClauseKind) {
2343                 auto CCI = CurComponents.rbegin();
2344                 auto CCE = CurComponents.rend();
2345                 for (const auto &SC : llvm::reverse(StackComponents)) {
2346                   // Do both expressions have the same kind?
2347                   if (CCI->getAssociatedExpression()->getStmtClass() !=
2348                       SC.getAssociatedExpression()->getStmtClass())
2349                     if (!(isa<OMPArraySectionExpr>(
2350                               SC.getAssociatedExpression()) &&
2351                           isa<ArraySubscriptExpr>(
2352                               CCI->getAssociatedExpression())))
2353                       return false;
2354 
2355                   const Decl *CCD = CCI->getAssociatedDeclaration();
2356                   const Decl *SCD = SC.getAssociatedDeclaration();
2357                   CCD = CCD ? CCD->getCanonicalDecl() : nullptr;
2358                   SCD = SCD ? SCD->getCanonicalDecl() : nullptr;
2359                   if (SCD != CCD)
2360                     return false;
2361                   std::advance(CCI, 1);
2362                   if (CCI == CCE)
2363                     break;
2364                 }
2365                 return true;
2366               })) {
2367         Visit(E->getBase());
2368       }
2369     } else {
2370       Visit(E->getBase());
2371     }
2372   }
2373   void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
2374     for (OMPClause *C : S->clauses()) {
2375       // Skip analysis of arguments of implicitly defined firstprivate clause
2376       // for task|target directives.
2377       // Skip analysis of arguments of implicitly defined map clause for target
2378       // directives.
2379       if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) &&
2380                  C->isImplicit())) {
2381         for (Stmt *CC : C->children()) {
2382           if (CC)
2383             Visit(CC);
2384         }
2385       }
2386     }
2387     // Check implicitly captured variables.
2388     VisitSubCaptures(S);
2389   }
2390   void VisitStmt(Stmt *S) {
2391     for (Stmt *C : S->children()) {
2392       if (C) {
2393         if (auto *OED = dyn_cast<OMPExecutableDirective>(C)) {
2394           // Check implicitly captured variables in the task-based directives to
2395           // check if they must be firstprivatized.
2396           VisitSubCaptures(OED);
2397         } else {
2398           Visit(C);
2399         }
2400       }
2401     }
2402   }
2403 
2404   bool isErrorFound() const { return ErrorFound; }
2405   ArrayRef<Expr *> getImplicitFirstprivate() const {
2406     return ImplicitFirstprivate;
2407   }
2408   ArrayRef<Expr *> getImplicitMap() const { return ImplicitMap; }
2409   const Sema::VarsWithInheritedDSAType &getVarsWithInheritedDSA() const {
2410     return VarsWithInheritedDSA;
2411   }
2412 
2413   DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
2414       : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {}
2415 };
2416 } // namespace
2417 
2418 void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
2419   switch (DKind) {
2420   case OMPD_parallel:
2421   case OMPD_parallel_for:
2422   case OMPD_parallel_for_simd:
2423   case OMPD_parallel_sections:
2424   case OMPD_teams:
2425   case OMPD_teams_distribute:
2426   case OMPD_teams_distribute_simd: {
2427     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2428     QualType KmpInt32PtrTy =
2429         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2430     Sema::CapturedParamNameType Params[] = {
2431         std::make_pair(".global_tid.", KmpInt32PtrTy),
2432         std::make_pair(".bound_tid.", KmpInt32PtrTy),
2433         std::make_pair(StringRef(), QualType()) // __context with shared vars
2434     };
2435     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2436                              Params);
2437     break;
2438   }
2439   case OMPD_target_teams:
2440   case OMPD_target_parallel:
2441   case OMPD_target_parallel_for:
2442   case OMPD_target_parallel_for_simd:
2443   case OMPD_target_teams_distribute:
2444   case OMPD_target_teams_distribute_simd: {
2445     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2446     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2447     QualType KmpInt32PtrTy =
2448         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2449     QualType Args[] = {VoidPtrTy};
2450     FunctionProtoType::ExtProtoInfo EPI;
2451     EPI.Variadic = true;
2452     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2453     Sema::CapturedParamNameType Params[] = {
2454         std::make_pair(".global_tid.", KmpInt32Ty),
2455         std::make_pair(".part_id.", KmpInt32PtrTy),
2456         std::make_pair(".privates.", VoidPtrTy),
2457         std::make_pair(
2458             ".copy_fn.",
2459             Context.getPointerType(CopyFnType).withConst().withRestrict()),
2460         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2461         std::make_pair(StringRef(), QualType()) // __context with shared vars
2462     };
2463     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2464                              Params);
2465     // Mark this captured region as inlined, because we don't use outlined
2466     // function directly.
2467     getCurCapturedRegion()->TheCapturedDecl->addAttr(
2468         AlwaysInlineAttr::CreateImplicit(
2469             Context, AlwaysInlineAttr::Keyword_forceinline));
2470     Sema::CapturedParamNameType ParamsTarget[] = {
2471         std::make_pair(StringRef(), QualType()) // __context with shared vars
2472     };
2473     // Start a captured region for 'target' with no implicit parameters.
2474     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2475                              ParamsTarget);
2476     Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
2477         std::make_pair(".global_tid.", KmpInt32PtrTy),
2478         std::make_pair(".bound_tid.", KmpInt32PtrTy),
2479         std::make_pair(StringRef(), QualType()) // __context with shared vars
2480     };
2481     // Start a captured region for 'teams' or 'parallel'.  Both regions have
2482     // the same implicit parameters.
2483     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2484                              ParamsTeamsOrParallel);
2485     break;
2486   }
2487   case OMPD_target:
2488   case OMPD_target_simd: {
2489     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2490     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2491     QualType KmpInt32PtrTy =
2492         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2493     QualType Args[] = {VoidPtrTy};
2494     FunctionProtoType::ExtProtoInfo EPI;
2495     EPI.Variadic = true;
2496     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2497     Sema::CapturedParamNameType Params[] = {
2498         std::make_pair(".global_tid.", KmpInt32Ty),
2499         std::make_pair(".part_id.", KmpInt32PtrTy),
2500         std::make_pair(".privates.", VoidPtrTy),
2501         std::make_pair(
2502             ".copy_fn.",
2503             Context.getPointerType(CopyFnType).withConst().withRestrict()),
2504         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2505         std::make_pair(StringRef(), QualType()) // __context with shared vars
2506     };
2507     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2508                              Params);
2509     // Mark this captured region as inlined, because we don't use outlined
2510     // function directly.
2511     getCurCapturedRegion()->TheCapturedDecl->addAttr(
2512         AlwaysInlineAttr::CreateImplicit(
2513             Context, AlwaysInlineAttr::Keyword_forceinline));
2514     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2515                              std::make_pair(StringRef(), QualType()));
2516     break;
2517   }
2518   case OMPD_simd:
2519   case OMPD_for:
2520   case OMPD_for_simd:
2521   case OMPD_sections:
2522   case OMPD_section:
2523   case OMPD_single:
2524   case OMPD_master:
2525   case OMPD_critical:
2526   case OMPD_taskgroup:
2527   case OMPD_distribute:
2528   case OMPD_distribute_simd:
2529   case OMPD_ordered:
2530   case OMPD_atomic:
2531   case OMPD_target_data: {
2532     Sema::CapturedParamNameType Params[] = {
2533         std::make_pair(StringRef(), QualType()) // __context with shared vars
2534     };
2535     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2536                              Params);
2537     break;
2538   }
2539   case OMPD_task: {
2540     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2541     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2542     QualType KmpInt32PtrTy =
2543         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2544     QualType Args[] = {VoidPtrTy};
2545     FunctionProtoType::ExtProtoInfo EPI;
2546     EPI.Variadic = true;
2547     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2548     Sema::CapturedParamNameType Params[] = {
2549         std::make_pair(".global_tid.", KmpInt32Ty),
2550         std::make_pair(".part_id.", KmpInt32PtrTy),
2551         std::make_pair(".privates.", VoidPtrTy),
2552         std::make_pair(
2553             ".copy_fn.",
2554             Context.getPointerType(CopyFnType).withConst().withRestrict()),
2555         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2556         std::make_pair(StringRef(), QualType()) // __context with shared vars
2557     };
2558     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2559                              Params);
2560     // Mark this captured region as inlined, because we don't use outlined
2561     // function directly.
2562     getCurCapturedRegion()->TheCapturedDecl->addAttr(
2563         AlwaysInlineAttr::CreateImplicit(
2564             Context, AlwaysInlineAttr::Keyword_forceinline));
2565     break;
2566   }
2567   case OMPD_taskloop:
2568   case OMPD_taskloop_simd: {
2569     QualType KmpInt32Ty =
2570         Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1)
2571             .withConst();
2572     QualType KmpUInt64Ty =
2573         Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0)
2574             .withConst();
2575     QualType KmpInt64Ty =
2576         Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1)
2577             .withConst();
2578     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2579     QualType KmpInt32PtrTy =
2580         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2581     QualType Args[] = {VoidPtrTy};
2582     FunctionProtoType::ExtProtoInfo EPI;
2583     EPI.Variadic = true;
2584     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2585     Sema::CapturedParamNameType Params[] = {
2586         std::make_pair(".global_tid.", KmpInt32Ty),
2587         std::make_pair(".part_id.", KmpInt32PtrTy),
2588         std::make_pair(".privates.", VoidPtrTy),
2589         std::make_pair(
2590             ".copy_fn.",
2591             Context.getPointerType(CopyFnType).withConst().withRestrict()),
2592         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2593         std::make_pair(".lb.", KmpUInt64Ty),
2594         std::make_pair(".ub.", KmpUInt64Ty),
2595         std::make_pair(".st.", KmpInt64Ty),
2596         std::make_pair(".liter.", KmpInt32Ty),
2597         std::make_pair(".reductions.", VoidPtrTy),
2598         std::make_pair(StringRef(), QualType()) // __context with shared vars
2599     };
2600     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2601                              Params);
2602     // Mark this captured region as inlined, because we don't use outlined
2603     // function directly.
2604     getCurCapturedRegion()->TheCapturedDecl->addAttr(
2605         AlwaysInlineAttr::CreateImplicit(
2606             Context, AlwaysInlineAttr::Keyword_forceinline));
2607     break;
2608   }
2609   case OMPD_distribute_parallel_for_simd:
2610   case OMPD_distribute_parallel_for: {
2611     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2612     QualType KmpInt32PtrTy =
2613         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2614     Sema::CapturedParamNameType Params[] = {
2615         std::make_pair(".global_tid.", KmpInt32PtrTy),
2616         std::make_pair(".bound_tid.", KmpInt32PtrTy),
2617         std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
2618         std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
2619         std::make_pair(StringRef(), QualType()) // __context with shared vars
2620     };
2621     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2622                              Params);
2623     break;
2624   }
2625   case OMPD_target_teams_distribute_parallel_for:
2626   case OMPD_target_teams_distribute_parallel_for_simd: {
2627     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2628     QualType KmpInt32PtrTy =
2629         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2630     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2631 
2632     QualType Args[] = {VoidPtrTy};
2633     FunctionProtoType::ExtProtoInfo EPI;
2634     EPI.Variadic = true;
2635     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2636     Sema::CapturedParamNameType Params[] = {
2637         std::make_pair(".global_tid.", KmpInt32Ty),
2638         std::make_pair(".part_id.", KmpInt32PtrTy),
2639         std::make_pair(".privates.", VoidPtrTy),
2640         std::make_pair(
2641             ".copy_fn.",
2642             Context.getPointerType(CopyFnType).withConst().withRestrict()),
2643         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2644         std::make_pair(StringRef(), QualType()) // __context with shared vars
2645     };
2646     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2647                              Params);
2648     // Mark this captured region as inlined, because we don't use outlined
2649     // function directly.
2650     getCurCapturedRegion()->TheCapturedDecl->addAttr(
2651         AlwaysInlineAttr::CreateImplicit(
2652             Context, AlwaysInlineAttr::Keyword_forceinline));
2653     Sema::CapturedParamNameType ParamsTarget[] = {
2654         std::make_pair(StringRef(), QualType()) // __context with shared vars
2655     };
2656     // Start a captured region for 'target' with no implicit parameters.
2657     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2658                              ParamsTarget);
2659 
2660     Sema::CapturedParamNameType ParamsTeams[] = {
2661         std::make_pair(".global_tid.", KmpInt32PtrTy),
2662         std::make_pair(".bound_tid.", KmpInt32PtrTy),
2663         std::make_pair(StringRef(), QualType()) // __context with shared vars
2664     };
2665     // Start a captured region for 'target' with no implicit parameters.
2666     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2667                              ParamsTeams);
2668 
2669     Sema::CapturedParamNameType ParamsParallel[] = {
2670         std::make_pair(".global_tid.", KmpInt32PtrTy),
2671         std::make_pair(".bound_tid.", KmpInt32PtrTy),
2672         std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
2673         std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
2674         std::make_pair(StringRef(), QualType()) // __context with shared vars
2675     };
2676     // Start a captured region for 'teams' or 'parallel'.  Both regions have
2677     // the same implicit parameters.
2678     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2679                              ParamsParallel);
2680     break;
2681   }
2682 
2683   case OMPD_teams_distribute_parallel_for:
2684   case OMPD_teams_distribute_parallel_for_simd: {
2685     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2686     QualType KmpInt32PtrTy =
2687         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2688 
2689     Sema::CapturedParamNameType ParamsTeams[] = {
2690         std::make_pair(".global_tid.", KmpInt32PtrTy),
2691         std::make_pair(".bound_tid.", KmpInt32PtrTy),
2692         std::make_pair(StringRef(), QualType()) // __context with shared vars
2693     };
2694     // Start a captured region for 'target' with no implicit parameters.
2695     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2696                              ParamsTeams);
2697 
2698     Sema::CapturedParamNameType ParamsParallel[] = {
2699         std::make_pair(".global_tid.", KmpInt32PtrTy),
2700         std::make_pair(".bound_tid.", KmpInt32PtrTy),
2701         std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
2702         std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
2703         std::make_pair(StringRef(), QualType()) // __context with shared vars
2704     };
2705     // Start a captured region for 'teams' or 'parallel'.  Both regions have
2706     // the same implicit parameters.
2707     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2708                              ParamsParallel);
2709     break;
2710   }
2711   case OMPD_target_update:
2712   case OMPD_target_enter_data:
2713   case OMPD_target_exit_data: {
2714     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2715     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2716     QualType KmpInt32PtrTy =
2717         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2718     QualType Args[] = {VoidPtrTy};
2719     FunctionProtoType::ExtProtoInfo EPI;
2720     EPI.Variadic = true;
2721     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2722     Sema::CapturedParamNameType Params[] = {
2723         std::make_pair(".global_tid.", KmpInt32Ty),
2724         std::make_pair(".part_id.", KmpInt32PtrTy),
2725         std::make_pair(".privates.", VoidPtrTy),
2726         std::make_pair(
2727             ".copy_fn.",
2728             Context.getPointerType(CopyFnType).withConst().withRestrict()),
2729         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2730         std::make_pair(StringRef(), QualType()) // __context with shared vars
2731     };
2732     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2733                              Params);
2734     // Mark this captured region as inlined, because we don't use outlined
2735     // function directly.
2736     getCurCapturedRegion()->TheCapturedDecl->addAttr(
2737         AlwaysInlineAttr::CreateImplicit(
2738             Context, AlwaysInlineAttr::Keyword_forceinline));
2739     break;
2740   }
2741   case OMPD_threadprivate:
2742   case OMPD_taskyield:
2743   case OMPD_barrier:
2744   case OMPD_taskwait:
2745   case OMPD_cancellation_point:
2746   case OMPD_cancel:
2747   case OMPD_flush:
2748   case OMPD_declare_reduction:
2749   case OMPD_declare_simd:
2750   case OMPD_declare_target:
2751   case OMPD_end_declare_target:
2752   case OMPD_requires:
2753     llvm_unreachable("OpenMP Directive is not allowed");
2754   case OMPD_unknown:
2755     llvm_unreachable("Unknown OpenMP directive");
2756   }
2757 }
2758 
2759 int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
2760   SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
2761   getOpenMPCaptureRegions(CaptureRegions, DKind);
2762   return CaptureRegions.size();
2763 }
2764 
2765 static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
2766                                              Expr *CaptureExpr, bool WithInit,
2767                                              bool AsExpression) {
2768   assert(CaptureExpr);
2769   ASTContext &C = S.getASTContext();
2770   Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
2771   QualType Ty = Init->getType();
2772   if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
2773     if (S.getLangOpts().CPlusPlus) {
2774       Ty = C.getLValueReferenceType(Ty);
2775     } else {
2776       Ty = C.getPointerType(Ty);
2777       ExprResult Res =
2778           S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
2779       if (!Res.isUsable())
2780         return nullptr;
2781       Init = Res.get();
2782     }
2783     WithInit = true;
2784   }
2785   auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
2786                                           CaptureExpr->getBeginLoc());
2787   if (!WithInit)
2788     CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C));
2789   S.CurContext->addHiddenDecl(CED);
2790   S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
2791   return CED;
2792 }
2793 
2794 static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
2795                                  bool WithInit) {
2796   OMPCapturedExprDecl *CD;
2797   if (VarDecl *VD = S.isOpenMPCapturedDecl(D))
2798     CD = cast<OMPCapturedExprDecl>(VD);
2799   else
2800     CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
2801                           /*AsExpression=*/false);
2802   return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
2803                           CaptureExpr->getExprLoc());
2804 }
2805 
2806 static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
2807   CaptureExpr = S.DefaultLvalueConversion(CaptureExpr).get();
2808   if (!Ref) {
2809     OMPCapturedExprDecl *CD = buildCaptureDecl(
2810         S, &S.getASTContext().Idents.get(".capture_expr."), CaptureExpr,
2811         /*WithInit=*/true, /*AsExpression=*/true);
2812     Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
2813                            CaptureExpr->getExprLoc());
2814   }
2815   ExprResult Res = Ref;
2816   if (!S.getLangOpts().CPlusPlus &&
2817       CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
2818       Ref->getType()->isPointerType()) {
2819     Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
2820     if (!Res.isUsable())
2821       return ExprError();
2822   }
2823   return S.DefaultLvalueConversion(Res.get());
2824 }
2825 
2826 namespace {
2827 // OpenMP directives parsed in this section are represented as a
2828 // CapturedStatement with an associated statement.  If a syntax error
2829 // is detected during the parsing of the associated statement, the
2830 // compiler must abort processing and close the CapturedStatement.
2831 //
2832 // Combined directives such as 'target parallel' have more than one
2833 // nested CapturedStatements.  This RAII ensures that we unwind out
2834 // of all the nested CapturedStatements when an error is found.
2835 class CaptureRegionUnwinderRAII {
2836 private:
2837   Sema &S;
2838   bool &ErrorFound;
2839   OpenMPDirectiveKind DKind = OMPD_unknown;
2840 
2841 public:
2842   CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
2843                             OpenMPDirectiveKind DKind)
2844       : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
2845   ~CaptureRegionUnwinderRAII() {
2846     if (ErrorFound) {
2847       int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
2848       while (--ThisCaptureLevel >= 0)
2849         S.ActOnCapturedRegionError();
2850     }
2851   }
2852 };
2853 } // namespace
2854 
2855 StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
2856                                       ArrayRef<OMPClause *> Clauses) {
2857   bool ErrorFound = false;
2858   CaptureRegionUnwinderRAII CaptureRegionUnwinder(
2859       *this, ErrorFound, DSAStack->getCurrentDirective());
2860   if (!S.isUsable()) {
2861     ErrorFound = true;
2862     return StmtError();
2863   }
2864 
2865   SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
2866   getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
2867   OMPOrderedClause *OC = nullptr;
2868   OMPScheduleClause *SC = nullptr;
2869   SmallVector<const OMPLinearClause *, 4> LCs;
2870   SmallVector<const OMPClauseWithPreInit *, 4> PICs;
2871   // This is required for proper codegen.
2872   for (OMPClause *Clause : Clauses) {
2873     if (isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) &&
2874         Clause->getClauseKind() == OMPC_in_reduction) {
2875       // Capture taskgroup task_reduction descriptors inside the tasking regions
2876       // with the corresponding in_reduction items.
2877       auto *IRC = cast<OMPInReductionClause>(Clause);
2878       for (Expr *E : IRC->taskgroup_descriptors())
2879         if (E)
2880           MarkDeclarationsReferencedInExpr(E);
2881     }
2882     if (isOpenMPPrivate(Clause->getClauseKind()) ||
2883         Clause->getClauseKind() == OMPC_copyprivate ||
2884         (getLangOpts().OpenMPUseTLS &&
2885          getASTContext().getTargetInfo().isTLSSupported() &&
2886          Clause->getClauseKind() == OMPC_copyin)) {
2887       DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
2888       // Mark all variables in private list clauses as used in inner region.
2889       for (Stmt *VarRef : Clause->children()) {
2890         if (auto *E = cast_or_null<Expr>(VarRef)) {
2891           MarkDeclarationsReferencedInExpr(E);
2892         }
2893       }
2894       DSAStack->setForceVarCapturing(/*V=*/false);
2895     } else if (CaptureRegions.size() > 1 ||
2896                CaptureRegions.back() != OMPD_unknown) {
2897       if (auto *C = OMPClauseWithPreInit::get(Clause))
2898         PICs.push_back(C);
2899       if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
2900         if (Expr *E = C->getPostUpdateExpr())
2901           MarkDeclarationsReferencedInExpr(E);
2902       }
2903     }
2904     if (Clause->getClauseKind() == OMPC_schedule)
2905       SC = cast<OMPScheduleClause>(Clause);
2906     else if (Clause->getClauseKind() == OMPC_ordered)
2907       OC = cast<OMPOrderedClause>(Clause);
2908     else if (Clause->getClauseKind() == OMPC_linear)
2909       LCs.push_back(cast<OMPLinearClause>(Clause));
2910   }
2911   // OpenMP, 2.7.1 Loop Construct, Restrictions
2912   // The nonmonotonic modifier cannot be specified if an ordered clause is
2913   // specified.
2914   if (SC &&
2915       (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
2916        SC->getSecondScheduleModifier() ==
2917            OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
2918       OC) {
2919     Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
2920              ? SC->getFirstScheduleModifierLoc()
2921              : SC->getSecondScheduleModifierLoc(),
2922          diag::err_omp_schedule_nonmonotonic_ordered)
2923         << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
2924     ErrorFound = true;
2925   }
2926   if (!LCs.empty() && OC && OC->getNumForLoops()) {
2927     for (const OMPLinearClause *C : LCs) {
2928       Diag(C->getBeginLoc(), diag::err_omp_linear_ordered)
2929           << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
2930     }
2931     ErrorFound = true;
2932   }
2933   if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
2934       isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
2935       OC->getNumForLoops()) {
2936     Diag(OC->getBeginLoc(), diag::err_omp_ordered_simd)
2937         << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
2938     ErrorFound = true;
2939   }
2940   if (ErrorFound) {
2941     return StmtError();
2942   }
2943   StmtResult SR = S;
2944   for (OpenMPDirectiveKind ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
2945     // Mark all variables in private list clauses as used in inner region.
2946     // Required for proper codegen of combined directives.
2947     // TODO: add processing for other clauses.
2948     if (ThisCaptureRegion != OMPD_unknown) {
2949       for (const clang::OMPClauseWithPreInit *C : PICs) {
2950         OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
2951         // Find the particular capture region for the clause if the
2952         // directive is a combined one with multiple capture regions.
2953         // If the directive is not a combined one, the capture region
2954         // associated with the clause is OMPD_unknown and is generated
2955         // only once.
2956         if (CaptureRegion == ThisCaptureRegion ||
2957             CaptureRegion == OMPD_unknown) {
2958           if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
2959             for (Decl *D : DS->decls())
2960               MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
2961           }
2962         }
2963       }
2964     }
2965     SR = ActOnCapturedRegionEnd(SR.get());
2966   }
2967   return SR;
2968 }
2969 
2970 static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
2971                               OpenMPDirectiveKind CancelRegion,
2972                               SourceLocation StartLoc) {
2973   // CancelRegion is only needed for cancel and cancellation_point.
2974   if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
2975     return false;
2976 
2977   if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
2978       CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
2979     return false;
2980 
2981   SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
2982       << getOpenMPDirectiveName(CancelRegion);
2983   return true;
2984 }
2985 
2986 static bool checkNestingOfRegions(Sema &SemaRef, const DSAStackTy *Stack,
2987                                   OpenMPDirectiveKind CurrentRegion,
2988                                   const DeclarationNameInfo &CurrentName,
2989                                   OpenMPDirectiveKind CancelRegion,
2990                                   SourceLocation StartLoc) {
2991   if (Stack->getCurScope()) {
2992     OpenMPDirectiveKind ParentRegion = Stack->getParentDirective();
2993     OpenMPDirectiveKind OffendingRegion = ParentRegion;
2994     bool NestingProhibited = false;
2995     bool CloseNesting = true;
2996     bool OrphanSeen = false;
2997     enum {
2998       NoRecommend,
2999       ShouldBeInParallelRegion,
3000       ShouldBeInOrderedRegion,
3001       ShouldBeInTargetRegion,
3002       ShouldBeInTeamsRegion
3003     } Recommend = NoRecommend;
3004     if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
3005       // OpenMP [2.16, Nesting of Regions]
3006       // OpenMP constructs may not be nested inside a simd region.
3007       // OpenMP [2.8.1,simd Construct, Restrictions]
3008       // An ordered construct with the simd clause is the only OpenMP
3009       // construct that can appear in the simd region.
3010       // Allowing a SIMD construct nested in another SIMD construct is an
3011       // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
3012       // message.
3013       SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
3014                                  ? diag::err_omp_prohibited_region_simd
3015                                  : diag::warn_omp_nesting_simd);
3016       return CurrentRegion != OMPD_simd;
3017     }
3018     if (ParentRegion == OMPD_atomic) {
3019       // OpenMP [2.16, Nesting of Regions]
3020       // OpenMP constructs may not be nested inside an atomic region.
3021       SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
3022       return true;
3023     }
3024     if (CurrentRegion == OMPD_section) {
3025       // OpenMP [2.7.2, sections Construct, Restrictions]
3026       // Orphaned section directives are prohibited. That is, the section
3027       // directives must appear within the sections construct and must not be
3028       // encountered elsewhere in the sections region.
3029       if (ParentRegion != OMPD_sections &&
3030           ParentRegion != OMPD_parallel_sections) {
3031         SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
3032             << (ParentRegion != OMPD_unknown)
3033             << getOpenMPDirectiveName(ParentRegion);
3034         return true;
3035       }
3036       return false;
3037     }
3038     // Allow some constructs (except teams) to be orphaned (they could be
3039     // used in functions, called from OpenMP regions with the required
3040     // preconditions).
3041     if (ParentRegion == OMPD_unknown &&
3042         !isOpenMPNestingTeamsDirective(CurrentRegion))
3043       return false;
3044     if (CurrentRegion == OMPD_cancellation_point ||
3045         CurrentRegion == OMPD_cancel) {
3046       // OpenMP [2.16, Nesting of Regions]
3047       // A cancellation point construct for which construct-type-clause is
3048       // taskgroup must be nested inside a task construct. A cancellation
3049       // point construct for which construct-type-clause is not taskgroup must
3050       // be closely nested inside an OpenMP construct that matches the type
3051       // specified in construct-type-clause.
3052       // A cancel construct for which construct-type-clause is taskgroup must be
3053       // nested inside a task construct. A cancel construct for which
3054       // construct-type-clause is not taskgroup must be closely nested inside an
3055       // OpenMP construct that matches the type specified in
3056       // construct-type-clause.
3057       NestingProhibited =
3058           !((CancelRegion == OMPD_parallel &&
3059              (ParentRegion == OMPD_parallel ||
3060               ParentRegion == OMPD_target_parallel)) ||
3061             (CancelRegion == OMPD_for &&
3062              (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
3063               ParentRegion == OMPD_target_parallel_for ||
3064               ParentRegion == OMPD_distribute_parallel_for ||
3065               ParentRegion == OMPD_teams_distribute_parallel_for ||
3066               ParentRegion == OMPD_target_teams_distribute_parallel_for)) ||
3067             (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
3068             (CancelRegion == OMPD_sections &&
3069              (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
3070               ParentRegion == OMPD_parallel_sections)));
3071     } else if (CurrentRegion == OMPD_master) {
3072       // OpenMP [2.16, Nesting of Regions]
3073       // A master region may not be closely nested inside a worksharing,
3074       // atomic, or explicit task region.
3075       NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
3076                           isOpenMPTaskingDirective(ParentRegion);
3077     } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
3078       // OpenMP [2.16, Nesting of Regions]
3079       // A critical region may not be nested (closely or otherwise) inside a
3080       // critical region with the same name. Note that this restriction is not
3081       // sufficient to prevent deadlock.
3082       SourceLocation PreviousCriticalLoc;
3083       bool DeadLock = Stack->hasDirective(
3084           [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
3085                                               const DeclarationNameInfo &DNI,
3086                                               SourceLocation Loc) {
3087             if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
3088               PreviousCriticalLoc = Loc;
3089               return true;
3090             }
3091             return false;
3092           },
3093           false /* skip top directive */);
3094       if (DeadLock) {
3095         SemaRef.Diag(StartLoc,
3096                      diag::err_omp_prohibited_region_critical_same_name)
3097             << CurrentName.getName();
3098         if (PreviousCriticalLoc.isValid())
3099           SemaRef.Diag(PreviousCriticalLoc,
3100                        diag::note_omp_previous_critical_region);
3101         return true;
3102       }
3103     } else if (CurrentRegion == OMPD_barrier) {
3104       // OpenMP [2.16, Nesting of Regions]
3105       // A barrier region may not be closely nested inside a worksharing,
3106       // explicit task, critical, ordered, atomic, or master region.
3107       NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
3108                           isOpenMPTaskingDirective(ParentRegion) ||
3109                           ParentRegion == OMPD_master ||
3110                           ParentRegion == OMPD_critical ||
3111                           ParentRegion == OMPD_ordered;
3112     } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
3113                !isOpenMPParallelDirective(CurrentRegion) &&
3114                !isOpenMPTeamsDirective(CurrentRegion)) {
3115       // OpenMP [2.16, Nesting of Regions]
3116       // A worksharing region may not be closely nested inside a worksharing,
3117       // explicit task, critical, ordered, atomic, or master region.
3118       NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
3119                           isOpenMPTaskingDirective(ParentRegion) ||
3120                           ParentRegion == OMPD_master ||
3121                           ParentRegion == OMPD_critical ||
3122                           ParentRegion == OMPD_ordered;
3123       Recommend = ShouldBeInParallelRegion;
3124     } else if (CurrentRegion == OMPD_ordered) {
3125       // OpenMP [2.16, Nesting of Regions]
3126       // An ordered region may not be closely nested inside a critical,
3127       // atomic, or explicit task region.
3128       // An ordered region must be closely nested inside a loop region (or
3129       // parallel loop region) with an ordered clause.
3130       // OpenMP [2.8.1,simd Construct, Restrictions]
3131       // An ordered construct with the simd clause is the only OpenMP construct
3132       // that can appear in the simd region.
3133       NestingProhibited = ParentRegion == OMPD_critical ||
3134                           isOpenMPTaskingDirective(ParentRegion) ||
3135                           !(isOpenMPSimdDirective(ParentRegion) ||
3136                             Stack->isParentOrderedRegion());
3137       Recommend = ShouldBeInOrderedRegion;
3138     } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
3139       // OpenMP [2.16, Nesting of Regions]
3140       // If specified, a teams construct must be contained within a target
3141       // construct.
3142       NestingProhibited = ParentRegion != OMPD_target;
3143       OrphanSeen = ParentRegion == OMPD_unknown;
3144       Recommend = ShouldBeInTargetRegion;
3145     }
3146     if (!NestingProhibited &&
3147         !isOpenMPTargetExecutionDirective(CurrentRegion) &&
3148         !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
3149         (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
3150       // OpenMP [2.16, Nesting of Regions]
3151       // distribute, parallel, parallel sections, parallel workshare, and the
3152       // parallel loop and parallel loop SIMD constructs are the only OpenMP
3153       // constructs that can be closely nested in the teams region.
3154       NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
3155                           !isOpenMPDistributeDirective(CurrentRegion);
3156       Recommend = ShouldBeInParallelRegion;
3157     }
3158     if (!NestingProhibited &&
3159         isOpenMPNestingDistributeDirective(CurrentRegion)) {
3160       // OpenMP 4.5 [2.17 Nesting of Regions]
3161       // The region associated with the distribute construct must be strictly
3162       // nested inside a teams region
3163       NestingProhibited =
3164           (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
3165       Recommend = ShouldBeInTeamsRegion;
3166     }
3167     if (!NestingProhibited &&
3168         (isOpenMPTargetExecutionDirective(CurrentRegion) ||
3169          isOpenMPTargetDataManagementDirective(CurrentRegion))) {
3170       // OpenMP 4.5 [2.17 Nesting of Regions]
3171       // If a target, target update, target data, target enter data, or
3172       // target exit data construct is encountered during execution of a
3173       // target region, the behavior is unspecified.
3174       NestingProhibited = Stack->hasDirective(
3175           [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
3176                              SourceLocation) {
3177             if (isOpenMPTargetExecutionDirective(K)) {
3178               OffendingRegion = K;
3179               return true;
3180             }
3181             return false;
3182           },
3183           false /* don't skip top directive */);
3184       CloseNesting = false;
3185     }
3186     if (NestingProhibited) {
3187       if (OrphanSeen) {
3188         SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
3189             << getOpenMPDirectiveName(CurrentRegion) << Recommend;
3190       } else {
3191         SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
3192             << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
3193             << Recommend << getOpenMPDirectiveName(CurrentRegion);
3194       }
3195       return true;
3196     }
3197   }
3198   return false;
3199 }
3200 
3201 static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
3202                            ArrayRef<OMPClause *> Clauses,
3203                            ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
3204   bool ErrorFound = false;
3205   unsigned NamedModifiersNumber = 0;
3206   SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
3207       OMPD_unknown + 1);
3208   SmallVector<SourceLocation, 4> NameModifierLoc;
3209   for (const OMPClause *C : Clauses) {
3210     if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
3211       // At most one if clause without a directive-name-modifier can appear on
3212       // the directive.
3213       OpenMPDirectiveKind CurNM = IC->getNameModifier();
3214       if (FoundNameModifiers[CurNM]) {
3215         S.Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
3216             << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
3217             << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
3218         ErrorFound = true;
3219       } else if (CurNM != OMPD_unknown) {
3220         NameModifierLoc.push_back(IC->getNameModifierLoc());
3221         ++NamedModifiersNumber;
3222       }
3223       FoundNameModifiers[CurNM] = IC;
3224       if (CurNM == OMPD_unknown)
3225         continue;
3226       // Check if the specified name modifier is allowed for the current
3227       // directive.
3228       // At most one if clause with the particular directive-name-modifier can
3229       // appear on the directive.
3230       bool MatchFound = false;
3231       for (auto NM : AllowedNameModifiers) {
3232         if (CurNM == NM) {
3233           MatchFound = true;
3234           break;
3235         }
3236       }
3237       if (!MatchFound) {
3238         S.Diag(IC->getNameModifierLoc(),
3239                diag::err_omp_wrong_if_directive_name_modifier)
3240             << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
3241         ErrorFound = true;
3242       }
3243     }
3244   }
3245   // If any if clause on the directive includes a directive-name-modifier then
3246   // all if clauses on the directive must include a directive-name-modifier.
3247   if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
3248     if (NamedModifiersNumber == AllowedNameModifiers.size()) {
3249       S.Diag(FoundNameModifiers[OMPD_unknown]->getBeginLoc(),
3250              diag::err_omp_no_more_if_clause);
3251     } else {
3252       std::string Values;
3253       std::string Sep(", ");
3254       unsigned AllowedCnt = 0;
3255       unsigned TotalAllowedNum =
3256           AllowedNameModifiers.size() - NamedModifiersNumber;
3257       for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
3258            ++Cnt) {
3259         OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
3260         if (!FoundNameModifiers[NM]) {
3261           Values += "'";
3262           Values += getOpenMPDirectiveName(NM);
3263           Values += "'";
3264           if (AllowedCnt + 2 == TotalAllowedNum)
3265             Values += " or ";
3266           else if (AllowedCnt + 1 != TotalAllowedNum)
3267             Values += Sep;
3268           ++AllowedCnt;
3269         }
3270       }
3271       S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getBeginLoc(),
3272              diag::err_omp_unnamed_if_clause)
3273           << (TotalAllowedNum > 1) << Values;
3274     }
3275     for (SourceLocation Loc : NameModifierLoc) {
3276       S.Diag(Loc, diag::note_omp_previous_named_if_clause);
3277     }
3278     ErrorFound = true;
3279   }
3280   return ErrorFound;
3281 }
3282 
3283 StmtResult Sema::ActOnOpenMPExecutableDirective(
3284     OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
3285     OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
3286     Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
3287   StmtResult Res = StmtError();
3288   // First check CancelRegion which is then used in checkNestingOfRegions.
3289   if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
3290       checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
3291                             StartLoc))
3292     return StmtError();
3293 
3294   llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
3295   VarsWithInheritedDSAType VarsWithInheritedDSA;
3296   bool ErrorFound = false;
3297   ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
3298   if (AStmt && !CurContext->isDependentContext()) {
3299     assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
3300 
3301     // Check default data sharing attributes for referenced variables.
3302     DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
3303     int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
3304     Stmt *S = AStmt;
3305     while (--ThisCaptureLevel >= 0)
3306       S = cast<CapturedStmt>(S)->getCapturedStmt();
3307     DSAChecker.Visit(S);
3308     if (DSAChecker.isErrorFound())
3309       return StmtError();
3310     // Generate list of implicitly defined firstprivate variables.
3311     VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
3312 
3313     SmallVector<Expr *, 4> ImplicitFirstprivates(
3314         DSAChecker.getImplicitFirstprivate().begin(),
3315         DSAChecker.getImplicitFirstprivate().end());
3316     SmallVector<Expr *, 4> ImplicitMaps(DSAChecker.getImplicitMap().begin(),
3317                                         DSAChecker.getImplicitMap().end());
3318     // Mark taskgroup task_reduction descriptors as implicitly firstprivate.
3319     for (OMPClause *C : Clauses) {
3320       if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) {
3321         for (Expr *E : IRC->taskgroup_descriptors())
3322           if (E)
3323             ImplicitFirstprivates.emplace_back(E);
3324       }
3325     }
3326     if (!ImplicitFirstprivates.empty()) {
3327       if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
3328               ImplicitFirstprivates, SourceLocation(), SourceLocation(),
3329               SourceLocation())) {
3330         ClausesWithImplicit.push_back(Implicit);
3331         ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
3332                      ImplicitFirstprivates.size();
3333       } else {
3334         ErrorFound = true;
3335       }
3336     }
3337     if (!ImplicitMaps.empty()) {
3338       if (OMPClause *Implicit = ActOnOpenMPMapClause(
3339               OMPC_MAP_unknown, OMPC_MAP_tofrom, /*IsMapTypeImplicit=*/true,
3340               SourceLocation(), SourceLocation(), ImplicitMaps,
3341               SourceLocation(), SourceLocation(), SourceLocation())) {
3342         ClausesWithImplicit.emplace_back(Implicit);
3343         ErrorFound |=
3344             cast<OMPMapClause>(Implicit)->varlist_size() != ImplicitMaps.size();
3345       } else {
3346         ErrorFound = true;
3347       }
3348     }
3349   }
3350 
3351   llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
3352   switch (Kind) {
3353   case OMPD_parallel:
3354     Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
3355                                        EndLoc);
3356     AllowedNameModifiers.push_back(OMPD_parallel);
3357     break;
3358   case OMPD_simd:
3359     Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
3360                                    VarsWithInheritedDSA);
3361     break;
3362   case OMPD_for:
3363     Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
3364                                   VarsWithInheritedDSA);
3365     break;
3366   case OMPD_for_simd:
3367     Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3368                                       EndLoc, VarsWithInheritedDSA);
3369     break;
3370   case OMPD_sections:
3371     Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
3372                                        EndLoc);
3373     break;
3374   case OMPD_section:
3375     assert(ClausesWithImplicit.empty() &&
3376            "No clauses are allowed for 'omp section' directive");
3377     Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
3378     break;
3379   case OMPD_single:
3380     Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
3381                                      EndLoc);
3382     break;
3383   case OMPD_master:
3384     assert(ClausesWithImplicit.empty() &&
3385            "No clauses are allowed for 'omp master' directive");
3386     Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
3387     break;
3388   case OMPD_critical:
3389     Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
3390                                        StartLoc, EndLoc);
3391     break;
3392   case OMPD_parallel_for:
3393     Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
3394                                           EndLoc, VarsWithInheritedDSA);
3395     AllowedNameModifiers.push_back(OMPD_parallel);
3396     break;
3397   case OMPD_parallel_for_simd:
3398     Res = ActOnOpenMPParallelForSimdDirective(
3399         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3400     AllowedNameModifiers.push_back(OMPD_parallel);
3401     break;
3402   case OMPD_parallel_sections:
3403     Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
3404                                                StartLoc, EndLoc);
3405     AllowedNameModifiers.push_back(OMPD_parallel);
3406     break;
3407   case OMPD_task:
3408     Res =
3409         ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
3410     AllowedNameModifiers.push_back(OMPD_task);
3411     break;
3412   case OMPD_taskyield:
3413     assert(ClausesWithImplicit.empty() &&
3414            "No clauses are allowed for 'omp taskyield' directive");
3415     assert(AStmt == nullptr &&
3416            "No associated statement allowed for 'omp taskyield' directive");
3417     Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
3418     break;
3419   case OMPD_barrier:
3420     assert(ClausesWithImplicit.empty() &&
3421            "No clauses are allowed for 'omp barrier' directive");
3422     assert(AStmt == nullptr &&
3423            "No associated statement allowed for 'omp barrier' directive");
3424     Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
3425     break;
3426   case OMPD_taskwait:
3427     assert(ClausesWithImplicit.empty() &&
3428            "No clauses are allowed for 'omp taskwait' directive");
3429     assert(AStmt == nullptr &&
3430            "No associated statement allowed for 'omp taskwait' directive");
3431     Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
3432     break;
3433   case OMPD_taskgroup:
3434     Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc,
3435                                         EndLoc);
3436     break;
3437   case OMPD_flush:
3438     assert(AStmt == nullptr &&
3439            "No associated statement allowed for 'omp flush' directive");
3440     Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
3441     break;
3442   case OMPD_ordered:
3443     Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
3444                                       EndLoc);
3445     break;
3446   case OMPD_atomic:
3447     Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
3448                                      EndLoc);
3449     break;
3450   case OMPD_teams:
3451     Res =
3452         ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
3453     break;
3454   case OMPD_target:
3455     Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
3456                                      EndLoc);
3457     AllowedNameModifiers.push_back(OMPD_target);
3458     break;
3459   case OMPD_target_parallel:
3460     Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
3461                                              StartLoc, EndLoc);
3462     AllowedNameModifiers.push_back(OMPD_target);
3463     AllowedNameModifiers.push_back(OMPD_parallel);
3464     break;
3465   case OMPD_target_parallel_for:
3466     Res = ActOnOpenMPTargetParallelForDirective(
3467         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3468     AllowedNameModifiers.push_back(OMPD_target);
3469     AllowedNameModifiers.push_back(OMPD_parallel);
3470     break;
3471   case OMPD_cancellation_point:
3472     assert(ClausesWithImplicit.empty() &&
3473            "No clauses are allowed for 'omp cancellation point' directive");
3474     assert(AStmt == nullptr && "No associated statement allowed for 'omp "
3475                                "cancellation point' directive");
3476     Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
3477     break;
3478   case OMPD_cancel:
3479     assert(AStmt == nullptr &&
3480            "No associated statement allowed for 'omp cancel' directive");
3481     Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
3482                                      CancelRegion);
3483     AllowedNameModifiers.push_back(OMPD_cancel);
3484     break;
3485   case OMPD_target_data:
3486     Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
3487                                          EndLoc);
3488     AllowedNameModifiers.push_back(OMPD_target_data);
3489     break;
3490   case OMPD_target_enter_data:
3491     Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
3492                                               EndLoc, AStmt);
3493     AllowedNameModifiers.push_back(OMPD_target_enter_data);
3494     break;
3495   case OMPD_target_exit_data:
3496     Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
3497                                              EndLoc, AStmt);
3498     AllowedNameModifiers.push_back(OMPD_target_exit_data);
3499     break;
3500   case OMPD_taskloop:
3501     Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
3502                                        EndLoc, VarsWithInheritedDSA);
3503     AllowedNameModifiers.push_back(OMPD_taskloop);
3504     break;
3505   case OMPD_taskloop_simd:
3506     Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3507                                            EndLoc, VarsWithInheritedDSA);
3508     AllowedNameModifiers.push_back(OMPD_taskloop);
3509     break;
3510   case OMPD_distribute:
3511     Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
3512                                          EndLoc, VarsWithInheritedDSA);
3513     break;
3514   case OMPD_target_update:
3515     Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc,
3516                                            EndLoc, AStmt);
3517     AllowedNameModifiers.push_back(OMPD_target_update);
3518     break;
3519   case OMPD_distribute_parallel_for:
3520     Res = ActOnOpenMPDistributeParallelForDirective(
3521         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3522     AllowedNameModifiers.push_back(OMPD_parallel);
3523     break;
3524   case OMPD_distribute_parallel_for_simd:
3525     Res = ActOnOpenMPDistributeParallelForSimdDirective(
3526         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3527     AllowedNameModifiers.push_back(OMPD_parallel);
3528     break;
3529   case OMPD_distribute_simd:
3530     Res = ActOnOpenMPDistributeSimdDirective(
3531         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3532     break;
3533   case OMPD_target_parallel_for_simd:
3534     Res = ActOnOpenMPTargetParallelForSimdDirective(
3535         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3536     AllowedNameModifiers.push_back(OMPD_target);
3537     AllowedNameModifiers.push_back(OMPD_parallel);
3538     break;
3539   case OMPD_target_simd:
3540     Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3541                                          EndLoc, VarsWithInheritedDSA);
3542     AllowedNameModifiers.push_back(OMPD_target);
3543     break;
3544   case OMPD_teams_distribute:
3545     Res = ActOnOpenMPTeamsDistributeDirective(
3546         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3547     break;
3548   case OMPD_teams_distribute_simd:
3549     Res = ActOnOpenMPTeamsDistributeSimdDirective(
3550         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3551     break;
3552   case OMPD_teams_distribute_parallel_for_simd:
3553     Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
3554         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3555     AllowedNameModifiers.push_back(OMPD_parallel);
3556     break;
3557   case OMPD_teams_distribute_parallel_for:
3558     Res = ActOnOpenMPTeamsDistributeParallelForDirective(
3559         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3560     AllowedNameModifiers.push_back(OMPD_parallel);
3561     break;
3562   case OMPD_target_teams:
3563     Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
3564                                           EndLoc);
3565     AllowedNameModifiers.push_back(OMPD_target);
3566     break;
3567   case OMPD_target_teams_distribute:
3568     Res = ActOnOpenMPTargetTeamsDistributeDirective(
3569         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3570     AllowedNameModifiers.push_back(OMPD_target);
3571     break;
3572   case OMPD_target_teams_distribute_parallel_for:
3573     Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
3574         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3575     AllowedNameModifiers.push_back(OMPD_target);
3576     AllowedNameModifiers.push_back(OMPD_parallel);
3577     break;
3578   case OMPD_target_teams_distribute_parallel_for_simd:
3579     Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
3580         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3581     AllowedNameModifiers.push_back(OMPD_target);
3582     AllowedNameModifiers.push_back(OMPD_parallel);
3583     break;
3584   case OMPD_target_teams_distribute_simd:
3585     Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
3586         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3587     AllowedNameModifiers.push_back(OMPD_target);
3588     break;
3589   case OMPD_declare_target:
3590   case OMPD_end_declare_target:
3591   case OMPD_threadprivate:
3592   case OMPD_declare_reduction:
3593   case OMPD_declare_simd:
3594   case OMPD_requires:
3595     llvm_unreachable("OpenMP Directive is not allowed");
3596   case OMPD_unknown:
3597     llvm_unreachable("Unknown OpenMP directive");
3598   }
3599 
3600   for (const auto &P : VarsWithInheritedDSA) {
3601     Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
3602         << P.first << P.second->getSourceRange();
3603   }
3604   ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound;
3605 
3606   if (!AllowedNameModifiers.empty())
3607     ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
3608                  ErrorFound;
3609 
3610   if (ErrorFound)
3611     return StmtError();
3612   return Res;
3613 }
3614 
3615 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
3616     DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
3617     ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
3618     ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
3619     ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
3620   assert(Aligneds.size() == Alignments.size());
3621   assert(Linears.size() == LinModifiers.size());
3622   assert(Linears.size() == Steps.size());
3623   if (!DG || DG.get().isNull())
3624     return DeclGroupPtrTy();
3625 
3626   if (!DG.get().isSingleDecl()) {
3627     Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd);
3628     return DG;
3629   }
3630   Decl *ADecl = DG.get().getSingleDecl();
3631   if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
3632     ADecl = FTD->getTemplatedDecl();
3633 
3634   auto *FD = dyn_cast<FunctionDecl>(ADecl);
3635   if (!FD) {
3636     Diag(ADecl->getLocation(), diag::err_omp_function_expected);
3637     return DeclGroupPtrTy();
3638   }
3639 
3640   // OpenMP [2.8.2, declare simd construct, Description]
3641   // The parameter of the simdlen clause must be a constant positive integer
3642   // expression.
3643   ExprResult SL;
3644   if (Simdlen)
3645     SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
3646   // OpenMP [2.8.2, declare simd construct, Description]
3647   // The special this pointer can be used as if was one of the arguments to the
3648   // function in any of the linear, aligned, or uniform clauses.
3649   // The uniform clause declares one or more arguments to have an invariant
3650   // value for all concurrent invocations of the function in the execution of a
3651   // single SIMD loop.
3652   llvm::DenseMap<const Decl *, const Expr *> UniformedArgs;
3653   const Expr *UniformedLinearThis = nullptr;
3654   for (const Expr *E : Uniforms) {
3655     E = E->IgnoreParenImpCasts();
3656     if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
3657       if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
3658         if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
3659             FD->getParamDecl(PVD->getFunctionScopeIndex())
3660                     ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
3661           UniformedArgs.try_emplace(PVD->getCanonicalDecl(), E);
3662           continue;
3663         }
3664     if (isa<CXXThisExpr>(E)) {
3665       UniformedLinearThis = E;
3666       continue;
3667     }
3668     Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3669         << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
3670   }
3671   // OpenMP [2.8.2, declare simd construct, Description]
3672   // The aligned clause declares that the object to which each list item points
3673   // is aligned to the number of bytes expressed in the optional parameter of
3674   // the aligned clause.
3675   // The special this pointer can be used as if was one of the arguments to the
3676   // function in any of the linear, aligned, or uniform clauses.
3677   // The type of list items appearing in the aligned clause must be array,
3678   // pointer, reference to array, or reference to pointer.
3679   llvm::DenseMap<const Decl *, const Expr *> AlignedArgs;
3680   const Expr *AlignedThis = nullptr;
3681   for (const Expr *E : Aligneds) {
3682     E = E->IgnoreParenImpCasts();
3683     if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
3684       if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3685         const VarDecl *CanonPVD = PVD->getCanonicalDecl();
3686         if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
3687             FD->getParamDecl(PVD->getFunctionScopeIndex())
3688                     ->getCanonicalDecl() == CanonPVD) {
3689           // OpenMP  [2.8.1, simd construct, Restrictions]
3690           // A list-item cannot appear in more than one aligned clause.
3691           if (AlignedArgs.count(CanonPVD) > 0) {
3692             Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
3693                 << 1 << E->getSourceRange();
3694             Diag(AlignedArgs[CanonPVD]->getExprLoc(),
3695                  diag::note_omp_explicit_dsa)
3696                 << getOpenMPClauseName(OMPC_aligned);
3697             continue;
3698           }
3699           AlignedArgs[CanonPVD] = E;
3700           QualType QTy = PVD->getType()
3701                              .getNonReferenceType()
3702                              .getUnqualifiedType()
3703                              .getCanonicalType();
3704           const Type *Ty = QTy.getTypePtrOrNull();
3705           if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
3706             Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
3707                 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
3708             Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
3709           }
3710           continue;
3711         }
3712       }
3713     if (isa<CXXThisExpr>(E)) {
3714       if (AlignedThis) {
3715         Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
3716             << 2 << E->getSourceRange();
3717         Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
3718             << getOpenMPClauseName(OMPC_aligned);
3719       }
3720       AlignedThis = E;
3721       continue;
3722     }
3723     Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3724         << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
3725   }
3726   // The optional parameter of the aligned clause, alignment, must be a constant
3727   // positive integer expression. If no optional parameter is specified,
3728   // implementation-defined default alignments for SIMD instructions on the
3729   // target platforms are assumed.
3730   SmallVector<const Expr *, 4> NewAligns;
3731   for (Expr *E : Alignments) {
3732     ExprResult Align;
3733     if (E)
3734       Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
3735     NewAligns.push_back(Align.get());
3736   }
3737   // OpenMP [2.8.2, declare simd construct, Description]
3738   // The linear clause declares one or more list items to be private to a SIMD
3739   // lane and to have a linear relationship with respect to the iteration space
3740   // of a loop.
3741   // The special this pointer can be used as if was one of the arguments to the
3742   // function in any of the linear, aligned, or uniform clauses.
3743   // When a linear-step expression is specified in a linear clause it must be
3744   // either a constant integer expression or an integer-typed parameter that is
3745   // specified in a uniform clause on the directive.
3746   llvm::DenseMap<const Decl *, const Expr *> LinearArgs;
3747   const bool IsUniformedThis = UniformedLinearThis != nullptr;
3748   auto MI = LinModifiers.begin();
3749   for (const Expr *E : Linears) {
3750     auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
3751     ++MI;
3752     E = E->IgnoreParenImpCasts();
3753     if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
3754       if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3755         const VarDecl *CanonPVD = PVD->getCanonicalDecl();
3756         if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
3757             FD->getParamDecl(PVD->getFunctionScopeIndex())
3758                     ->getCanonicalDecl() == CanonPVD) {
3759           // OpenMP  [2.15.3.7, linear Clause, Restrictions]
3760           // A list-item cannot appear in more than one linear clause.
3761           if (LinearArgs.count(CanonPVD) > 0) {
3762             Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3763                 << getOpenMPClauseName(OMPC_linear)
3764                 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
3765             Diag(LinearArgs[CanonPVD]->getExprLoc(),
3766                  diag::note_omp_explicit_dsa)
3767                 << getOpenMPClauseName(OMPC_linear);
3768             continue;
3769           }
3770           // Each argument can appear in at most one uniform or linear clause.
3771           if (UniformedArgs.count(CanonPVD) > 0) {
3772             Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3773                 << getOpenMPClauseName(OMPC_linear)
3774                 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
3775             Diag(UniformedArgs[CanonPVD]->getExprLoc(),
3776                  diag::note_omp_explicit_dsa)
3777                 << getOpenMPClauseName(OMPC_uniform);
3778             continue;
3779           }
3780           LinearArgs[CanonPVD] = E;
3781           if (E->isValueDependent() || E->isTypeDependent() ||
3782               E->isInstantiationDependent() ||
3783               E->containsUnexpandedParameterPack())
3784             continue;
3785           (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
3786                                       PVD->getOriginalType());
3787           continue;
3788         }
3789       }
3790     if (isa<CXXThisExpr>(E)) {
3791       if (UniformedLinearThis) {
3792         Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3793             << getOpenMPClauseName(OMPC_linear)
3794             << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
3795             << E->getSourceRange();
3796         Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
3797             << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
3798                                                    : OMPC_linear);
3799         continue;
3800       }
3801       UniformedLinearThis = E;
3802       if (E->isValueDependent() || E->isTypeDependent() ||
3803           E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
3804         continue;
3805       (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
3806                                   E->getType());
3807       continue;
3808     }
3809     Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3810         << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
3811   }
3812   Expr *Step = nullptr;
3813   Expr *NewStep = nullptr;
3814   SmallVector<Expr *, 4> NewSteps;
3815   for (Expr *E : Steps) {
3816     // Skip the same step expression, it was checked already.
3817     if (Step == E || !E) {
3818       NewSteps.push_back(E ? NewStep : nullptr);
3819       continue;
3820     }
3821     Step = E;
3822     if (const auto *DRE = dyn_cast<DeclRefExpr>(Step))
3823       if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3824         const VarDecl *CanonPVD = PVD->getCanonicalDecl();
3825         if (UniformedArgs.count(CanonPVD) == 0) {
3826           Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
3827               << Step->getSourceRange();
3828         } else if (E->isValueDependent() || E->isTypeDependent() ||
3829                    E->isInstantiationDependent() ||
3830                    E->containsUnexpandedParameterPack() ||
3831                    CanonPVD->getType()->hasIntegerRepresentation()) {
3832           NewSteps.push_back(Step);
3833         } else {
3834           Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
3835               << Step->getSourceRange();
3836         }
3837         continue;
3838       }
3839     NewStep = Step;
3840     if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
3841         !Step->isInstantiationDependent() &&
3842         !Step->containsUnexpandedParameterPack()) {
3843       NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
3844                     .get();
3845       if (NewStep)
3846         NewStep = VerifyIntegerConstantExpression(NewStep).get();
3847     }
3848     NewSteps.push_back(NewStep);
3849   }
3850   auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
3851       Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
3852       Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
3853       const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
3854       const_cast<Expr **>(Linears.data()), Linears.size(),
3855       const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
3856       NewSteps.data(), NewSteps.size(), SR);
3857   ADecl->addAttr(NewAttr);
3858   return ConvertDeclToDeclGroup(ADecl);
3859 }
3860 
3861 StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
3862                                               Stmt *AStmt,
3863                                               SourceLocation StartLoc,
3864                                               SourceLocation EndLoc) {
3865   if (!AStmt)
3866     return StmtError();
3867 
3868   auto *CS = cast<CapturedStmt>(AStmt);
3869   // 1.2.2 OpenMP Language Terminology
3870   // Structured block - An executable statement with a single entry at the
3871   // top and a single exit at the bottom.
3872   // The point of exit cannot be a branch out of the structured block.
3873   // longjmp() and throw() must not violate the entry/exit criteria.
3874   CS->getCapturedDecl()->setNothrow();
3875 
3876   setFunctionHasBranchProtectedScope();
3877 
3878   return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
3879                                       DSAStack->isCancelRegion());
3880 }
3881 
3882 namespace {
3883 /// Helper class for checking canonical form of the OpenMP loops and
3884 /// extracting iteration space of each loop in the loop nest, that will be used
3885 /// for IR generation.
3886 class OpenMPIterationSpaceChecker {
3887   /// Reference to Sema.
3888   Sema &SemaRef;
3889   /// A location for diagnostics (when there is no some better location).
3890   SourceLocation DefaultLoc;
3891   /// A location for diagnostics (when increment is not compatible).
3892   SourceLocation ConditionLoc;
3893   /// A source location for referring to loop init later.
3894   SourceRange InitSrcRange;
3895   /// A source location for referring to condition later.
3896   SourceRange ConditionSrcRange;
3897   /// A source location for referring to increment later.
3898   SourceRange IncrementSrcRange;
3899   /// Loop variable.
3900   ValueDecl *LCDecl = nullptr;
3901   /// Reference to loop variable.
3902   Expr *LCRef = nullptr;
3903   /// Lower bound (initializer for the var).
3904   Expr *LB = nullptr;
3905   /// Upper bound.
3906   Expr *UB = nullptr;
3907   /// Loop step (increment).
3908   Expr *Step = nullptr;
3909   /// This flag is true when condition is one of:
3910   ///   Var <  UB
3911   ///   Var <= UB
3912   ///   UB  >  Var
3913   ///   UB  >= Var
3914   /// This will have no value when the condition is !=
3915   llvm::Optional<bool> TestIsLessOp;
3916   /// This flag is true when condition is strict ( < or > ).
3917   bool TestIsStrictOp = false;
3918   /// This flag is true when step is subtracted on each iteration.
3919   bool SubtractStep = false;
3920 
3921 public:
3922   OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
3923       : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {}
3924   /// Check init-expr for canonical loop form and save loop counter
3925   /// variable - #Var and its initialization value - #LB.
3926   bool checkAndSetInit(Stmt *S, bool EmitDiags = true);
3927   /// Check test-expr for canonical form, save upper-bound (#UB), flags
3928   /// for less/greater and for strict/non-strict comparison.
3929   bool checkAndSetCond(Expr *S);
3930   /// Check incr-expr for canonical loop form and return true if it
3931   /// does not conform, otherwise save loop step (#Step).
3932   bool checkAndSetInc(Expr *S);
3933   /// Return the loop counter variable.
3934   ValueDecl *getLoopDecl() const { return LCDecl; }
3935   /// Return the reference expression to loop counter variable.
3936   Expr *getLoopDeclRefExpr() const { return LCRef; }
3937   /// Source range of the loop init.
3938   SourceRange getInitSrcRange() const { return InitSrcRange; }
3939   /// Source range of the loop condition.
3940   SourceRange getConditionSrcRange() const { return ConditionSrcRange; }
3941   /// Source range of the loop increment.
3942   SourceRange getIncrementSrcRange() const { return IncrementSrcRange; }
3943   /// True if the step should be subtracted.
3944   bool shouldSubtractStep() const { return SubtractStep; }
3945   /// Build the expression to calculate the number of iterations.
3946   Expr *buildNumIterations(
3947       Scope *S, const bool LimitedType,
3948       llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
3949   /// Build the precondition expression for the loops.
3950   Expr *
3951   buildPreCond(Scope *S, Expr *Cond,
3952                llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
3953   /// Build reference expression to the counter be used for codegen.
3954   DeclRefExpr *
3955   buildCounterVar(llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
3956                   DSAStackTy &DSA) const;
3957   /// Build reference expression to the private counter be used for
3958   /// codegen.
3959   Expr *buildPrivateCounterVar() const;
3960   /// Build initialization of the counter be used for codegen.
3961   Expr *buildCounterInit() const;
3962   /// Build step of the counter be used for codegen.
3963   Expr *buildCounterStep() const;
3964   /// Build loop data with counter value for depend clauses in ordered
3965   /// directives.
3966   Expr *
3967   buildOrderedLoopData(Scope *S, Expr *Counter,
3968                        llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
3969                        SourceLocation Loc, Expr *Inc = nullptr,
3970                        OverloadedOperatorKind OOK = OO_Amp);
3971   /// Return true if any expression is dependent.
3972   bool dependent() const;
3973 
3974 private:
3975   /// Check the right-hand side of an assignment in the increment
3976   /// expression.
3977   bool checkAndSetIncRHS(Expr *RHS);
3978   /// Helper to set loop counter variable and its initializer.
3979   bool setLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB);
3980   /// Helper to set upper bound.
3981   bool setUB(Expr *NewUB, llvm::Optional<bool> LessOp, bool StrictOp,
3982              SourceRange SR, SourceLocation SL);
3983   /// Helper to set loop increment.
3984   bool setStep(Expr *NewStep, bool Subtract);
3985 };
3986 
3987 bool OpenMPIterationSpaceChecker::dependent() const {
3988   if (!LCDecl) {
3989     assert(!LB && !UB && !Step);
3990     return false;
3991   }
3992   return LCDecl->getType()->isDependentType() ||
3993          (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
3994          (Step && Step->isValueDependent());
3995 }
3996 
3997 bool OpenMPIterationSpaceChecker::setLCDeclAndLB(ValueDecl *NewLCDecl,
3998                                                  Expr *NewLCRefExpr,
3999                                                  Expr *NewLB) {
4000   // State consistency checking to ensure correct usage.
4001   assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
4002          UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
4003   if (!NewLCDecl || !NewLB)
4004     return true;
4005   LCDecl = getCanonicalDecl(NewLCDecl);
4006   LCRef = NewLCRefExpr;
4007   if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
4008     if (const CXXConstructorDecl *Ctor = CE->getConstructor())
4009       if ((Ctor->isCopyOrMoveConstructor() ||
4010            Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
4011           CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
4012         NewLB = CE->getArg(0)->IgnoreParenImpCasts();
4013   LB = NewLB;
4014   return false;
4015 }
4016 
4017 bool OpenMPIterationSpaceChecker::setUB(Expr *NewUB, llvm::Optional<bool> LessOp,
4018                                         bool StrictOp, SourceRange SR,
4019                                         SourceLocation SL) {
4020   // State consistency checking to ensure correct usage.
4021   assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
4022          Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
4023   if (!NewUB)
4024     return true;
4025   UB = NewUB;
4026   if (LessOp)
4027     TestIsLessOp = LessOp;
4028   TestIsStrictOp = StrictOp;
4029   ConditionSrcRange = SR;
4030   ConditionLoc = SL;
4031   return false;
4032 }
4033 
4034 bool OpenMPIterationSpaceChecker::setStep(Expr *NewStep, bool Subtract) {
4035   // State consistency checking to ensure correct usage.
4036   assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
4037   if (!NewStep)
4038     return true;
4039   if (!NewStep->isValueDependent()) {
4040     // Check that the step is integer expression.
4041     SourceLocation StepLoc = NewStep->getBeginLoc();
4042     ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion(
4043         StepLoc, getExprAsWritten(NewStep));
4044     if (Val.isInvalid())
4045       return true;
4046     NewStep = Val.get();
4047 
4048     // OpenMP [2.6, Canonical Loop Form, Restrictions]
4049     //  If test-expr is of form var relational-op b and relational-op is < or
4050     //  <= then incr-expr must cause var to increase on each iteration of the
4051     //  loop. If test-expr is of form var relational-op b and relational-op is
4052     //  > or >= then incr-expr must cause var to decrease on each iteration of
4053     //  the loop.
4054     //  If test-expr is of form b relational-op var and relational-op is < or
4055     //  <= then incr-expr must cause var to decrease on each iteration of the
4056     //  loop. If test-expr is of form b relational-op var and relational-op is
4057     //  > or >= then incr-expr must cause var to increase on each iteration of
4058     //  the loop.
4059     llvm::APSInt Result;
4060     bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
4061     bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
4062     bool IsConstNeg =
4063         IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
4064     bool IsConstPos =
4065         IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
4066     bool IsConstZero = IsConstant && !Result.getBoolValue();
4067 
4068     // != with increment is treated as <; != with decrement is treated as >
4069     if (!TestIsLessOp.hasValue())
4070       TestIsLessOp = IsConstPos || (IsUnsigned && !Subtract);
4071     if (UB && (IsConstZero ||
4072                (TestIsLessOp.getValue() ?
4073                   (IsConstNeg || (IsUnsigned && Subtract)) :
4074                   (IsConstPos || (IsUnsigned && !Subtract))))) {
4075       SemaRef.Diag(NewStep->getExprLoc(),
4076                    diag::err_omp_loop_incr_not_compatible)
4077           << LCDecl << TestIsLessOp.getValue() << NewStep->getSourceRange();
4078       SemaRef.Diag(ConditionLoc,
4079                    diag::note_omp_loop_cond_requres_compatible_incr)
4080           << TestIsLessOp.getValue() << ConditionSrcRange;
4081       return true;
4082     }
4083     if (TestIsLessOp.getValue() == Subtract) {
4084       NewStep =
4085           SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
4086               .get();
4087       Subtract = !Subtract;
4088     }
4089   }
4090 
4091   Step = NewStep;
4092   SubtractStep = Subtract;
4093   return false;
4094 }
4095 
4096 bool OpenMPIterationSpaceChecker::checkAndSetInit(Stmt *S, bool EmitDiags) {
4097   // Check init-expr for canonical loop form and save loop counter
4098   // variable - #Var and its initialization value - #LB.
4099   // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
4100   //   var = lb
4101   //   integer-type var = lb
4102   //   random-access-iterator-type var = lb
4103   //   pointer-type var = lb
4104   //
4105   if (!S) {
4106     if (EmitDiags) {
4107       SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
4108     }
4109     return true;
4110   }
4111   if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
4112     if (!ExprTemp->cleanupsHaveSideEffects())
4113       S = ExprTemp->getSubExpr();
4114 
4115   InitSrcRange = S->getSourceRange();
4116   if (Expr *E = dyn_cast<Expr>(S))
4117     S = E->IgnoreParens();
4118   if (auto *BO = dyn_cast<BinaryOperator>(S)) {
4119     if (BO->getOpcode() == BO_Assign) {
4120       Expr *LHS = BO->getLHS()->IgnoreParens();
4121       if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
4122         if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
4123           if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
4124             return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
4125         return setLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS());
4126       }
4127       if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
4128         if (ME->isArrow() &&
4129             isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
4130           return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
4131       }
4132     }
4133   } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
4134     if (DS->isSingleDecl()) {
4135       if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
4136         if (Var->hasInit() && !Var->getType()->isReferenceType()) {
4137           // Accept non-canonical init form here but emit ext. warning.
4138           if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
4139             SemaRef.Diag(S->getBeginLoc(),
4140                          diag::ext_omp_loop_not_canonical_init)
4141                 << S->getSourceRange();
4142           return setLCDeclAndLB(
4143               Var,
4144               buildDeclRefExpr(SemaRef, Var,
4145                                Var->getType().getNonReferenceType(),
4146                                DS->getBeginLoc()),
4147               Var->getInit());
4148         }
4149       }
4150     }
4151   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
4152     if (CE->getOperator() == OO_Equal) {
4153       Expr *LHS = CE->getArg(0);
4154       if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
4155         if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
4156           if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
4157             return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
4158         return setLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1));
4159       }
4160       if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
4161         if (ME->isArrow() &&
4162             isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
4163           return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
4164       }
4165     }
4166   }
4167 
4168   if (dependent() || SemaRef.CurContext->isDependentContext())
4169     return false;
4170   if (EmitDiags) {
4171     SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_init)
4172         << S->getSourceRange();
4173   }
4174   return true;
4175 }
4176 
4177 /// Ignore parenthesizes, implicit casts, copy constructor and return the
4178 /// variable (which may be the loop variable) if possible.
4179 static const ValueDecl *getInitLCDecl(const Expr *E) {
4180   if (!E)
4181     return nullptr;
4182   E = getExprAsWritten(E);
4183   if (const auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
4184     if (const CXXConstructorDecl *Ctor = CE->getConstructor())
4185       if ((Ctor->isCopyOrMoveConstructor() ||
4186            Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
4187           CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
4188         E = CE->getArg(0)->IgnoreParenImpCasts();
4189   if (const auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
4190     if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
4191       return getCanonicalDecl(VD);
4192   }
4193   if (const auto *ME = dyn_cast_or_null<MemberExpr>(E))
4194     if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
4195       return getCanonicalDecl(ME->getMemberDecl());
4196   return nullptr;
4197 }
4198 
4199 bool OpenMPIterationSpaceChecker::checkAndSetCond(Expr *S) {
4200   // Check test-expr for canonical form, save upper-bound UB, flags for
4201   // less/greater and for strict/non-strict comparison.
4202   // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
4203   //   var relational-op b
4204   //   b relational-op var
4205   //
4206   if (!S) {
4207     SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl;
4208     return true;
4209   }
4210   S = getExprAsWritten(S);
4211   SourceLocation CondLoc = S->getBeginLoc();
4212   if (auto *BO = dyn_cast<BinaryOperator>(S)) {
4213     if (BO->isRelationalOp()) {
4214       if (getInitLCDecl(BO->getLHS()) == LCDecl)
4215         return setUB(BO->getRHS(),
4216                      (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
4217                      (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
4218                      BO->getSourceRange(), BO->getOperatorLoc());
4219       if (getInitLCDecl(BO->getRHS()) == LCDecl)
4220         return setUB(BO->getLHS(),
4221                      (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
4222                      (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
4223                      BO->getSourceRange(), BO->getOperatorLoc());
4224     } else if (BO->getOpcode() == BO_NE)
4225         return setUB(getInitLCDecl(BO->getLHS()) == LCDecl ?
4226                        BO->getRHS() : BO->getLHS(),
4227                      /*LessOp=*/llvm::None,
4228                      /*StrictOp=*/true,
4229                      BO->getSourceRange(), BO->getOperatorLoc());
4230   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
4231     if (CE->getNumArgs() == 2) {
4232       auto Op = CE->getOperator();
4233       switch (Op) {
4234       case OO_Greater:
4235       case OO_GreaterEqual:
4236       case OO_Less:
4237       case OO_LessEqual:
4238         if (getInitLCDecl(CE->getArg(0)) == LCDecl)
4239           return setUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
4240                        Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
4241                        CE->getOperatorLoc());
4242         if (getInitLCDecl(CE->getArg(1)) == LCDecl)
4243           return setUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
4244                        Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
4245                        CE->getOperatorLoc());
4246         break;
4247       case OO_ExclaimEqual:
4248         return setUB(getInitLCDecl(CE->getArg(0)) == LCDecl ?
4249                      CE->getArg(1) : CE->getArg(0),
4250                      /*LessOp=*/llvm::None,
4251                      /*StrictOp=*/true,
4252                      CE->getSourceRange(),
4253                      CE->getOperatorLoc());
4254         break;
4255       default:
4256         break;
4257       }
4258     }
4259   }
4260   if (dependent() || SemaRef.CurContext->isDependentContext())
4261     return false;
4262   SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
4263       << S->getSourceRange() << LCDecl;
4264   return true;
4265 }
4266 
4267 bool OpenMPIterationSpaceChecker::checkAndSetIncRHS(Expr *RHS) {
4268   // RHS of canonical loop form increment can be:
4269   //   var + incr
4270   //   incr + var
4271   //   var - incr
4272   //
4273   RHS = RHS->IgnoreParenImpCasts();
4274   if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
4275     if (BO->isAdditiveOp()) {
4276       bool IsAdd = BO->getOpcode() == BO_Add;
4277       if (getInitLCDecl(BO->getLHS()) == LCDecl)
4278         return setStep(BO->getRHS(), !IsAdd);
4279       if (IsAdd && getInitLCDecl(BO->getRHS()) == LCDecl)
4280         return setStep(BO->getLHS(), /*Subtract=*/false);
4281     }
4282   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
4283     bool IsAdd = CE->getOperator() == OO_Plus;
4284     if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
4285       if (getInitLCDecl(CE->getArg(0)) == LCDecl)
4286         return setStep(CE->getArg(1), !IsAdd);
4287       if (IsAdd && getInitLCDecl(CE->getArg(1)) == LCDecl)
4288         return setStep(CE->getArg(0), /*Subtract=*/false);
4289     }
4290   }
4291   if (dependent() || SemaRef.CurContext->isDependentContext())
4292     return false;
4293   SemaRef.Diag(RHS->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
4294       << RHS->getSourceRange() << LCDecl;
4295   return true;
4296 }
4297 
4298 bool OpenMPIterationSpaceChecker::checkAndSetInc(Expr *S) {
4299   // Check incr-expr for canonical loop form and return true if it
4300   // does not conform.
4301   // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
4302   //   ++var
4303   //   var++
4304   //   --var
4305   //   var--
4306   //   var += incr
4307   //   var -= incr
4308   //   var = var + incr
4309   //   var = incr + var
4310   //   var = var - incr
4311   //
4312   if (!S) {
4313     SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
4314     return true;
4315   }
4316   if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
4317     if (!ExprTemp->cleanupsHaveSideEffects())
4318       S = ExprTemp->getSubExpr();
4319 
4320   IncrementSrcRange = S->getSourceRange();
4321   S = S->IgnoreParens();
4322   if (auto *UO = dyn_cast<UnaryOperator>(S)) {
4323     if (UO->isIncrementDecrementOp() &&
4324         getInitLCDecl(UO->getSubExpr()) == LCDecl)
4325       return setStep(SemaRef
4326                          .ActOnIntegerConstant(UO->getBeginLoc(),
4327                                                (UO->isDecrementOp() ? -1 : 1))
4328                          .get(),
4329                      /*Subtract=*/false);
4330   } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
4331     switch (BO->getOpcode()) {
4332     case BO_AddAssign:
4333     case BO_SubAssign:
4334       if (getInitLCDecl(BO->getLHS()) == LCDecl)
4335         return setStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
4336       break;
4337     case BO_Assign:
4338       if (getInitLCDecl(BO->getLHS()) == LCDecl)
4339         return checkAndSetIncRHS(BO->getRHS());
4340       break;
4341     default:
4342       break;
4343     }
4344   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
4345     switch (CE->getOperator()) {
4346     case OO_PlusPlus:
4347     case OO_MinusMinus:
4348       if (getInitLCDecl(CE->getArg(0)) == LCDecl)
4349         return setStep(SemaRef
4350                            .ActOnIntegerConstant(
4351                                CE->getBeginLoc(),
4352                                ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
4353                            .get(),
4354                        /*Subtract=*/false);
4355       break;
4356     case OO_PlusEqual:
4357     case OO_MinusEqual:
4358       if (getInitLCDecl(CE->getArg(0)) == LCDecl)
4359         return setStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
4360       break;
4361     case OO_Equal:
4362       if (getInitLCDecl(CE->getArg(0)) == LCDecl)
4363         return checkAndSetIncRHS(CE->getArg(1));
4364       break;
4365     default:
4366       break;
4367     }
4368   }
4369   if (dependent() || SemaRef.CurContext->isDependentContext())
4370     return false;
4371   SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
4372       << S->getSourceRange() << LCDecl;
4373   return true;
4374 }
4375 
4376 static ExprResult
4377 tryBuildCapture(Sema &SemaRef, Expr *Capture,
4378                 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
4379   if (SemaRef.CurContext->isDependentContext())
4380     return ExprResult(Capture);
4381   if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
4382     return SemaRef.PerformImplicitConversion(
4383         Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
4384         /*AllowExplicit=*/true);
4385   auto I = Captures.find(Capture);
4386   if (I != Captures.end())
4387     return buildCapture(SemaRef, Capture, I->second);
4388   DeclRefExpr *Ref = nullptr;
4389   ExprResult Res = buildCapture(SemaRef, Capture, Ref);
4390   Captures[Capture] = Ref;
4391   return Res;
4392 }
4393 
4394 /// Build the expression to calculate the number of iterations.
4395 Expr *OpenMPIterationSpaceChecker::buildNumIterations(
4396     Scope *S, const bool LimitedType,
4397     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
4398   ExprResult Diff;
4399   QualType VarType = LCDecl->getType().getNonReferenceType();
4400   if (VarType->isIntegerType() || VarType->isPointerType() ||
4401       SemaRef.getLangOpts().CPlusPlus) {
4402     // Upper - Lower
4403     Expr *UBExpr = TestIsLessOp.getValue() ? UB : LB;
4404     Expr *LBExpr = TestIsLessOp.getValue() ? LB : UB;
4405     Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
4406     Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
4407     if (!Upper || !Lower)
4408       return nullptr;
4409 
4410     Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
4411 
4412     if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
4413       // BuildBinOp already emitted error, this one is to point user to upper
4414       // and lower bound, and to tell what is passed to 'operator-'.
4415       SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
4416           << Upper->getSourceRange() << Lower->getSourceRange();
4417       return nullptr;
4418     }
4419   }
4420 
4421   if (!Diff.isUsable())
4422     return nullptr;
4423 
4424   // Upper - Lower [- 1]
4425   if (TestIsStrictOp)
4426     Diff = SemaRef.BuildBinOp(
4427         S, DefaultLoc, BO_Sub, Diff.get(),
4428         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4429   if (!Diff.isUsable())
4430     return nullptr;
4431 
4432   // Upper - Lower [- 1] + Step
4433   ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
4434   if (!NewStep.isUsable())
4435     return nullptr;
4436   Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
4437   if (!Diff.isUsable())
4438     return nullptr;
4439 
4440   // Parentheses (for dumping/debugging purposes only).
4441   Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
4442   if (!Diff.isUsable())
4443     return nullptr;
4444 
4445   // (Upper - Lower [- 1] + Step) / Step
4446   Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
4447   if (!Diff.isUsable())
4448     return nullptr;
4449 
4450   // OpenMP runtime requires 32-bit or 64-bit loop variables.
4451   QualType Type = Diff.get()->getType();
4452   ASTContext &C = SemaRef.Context;
4453   bool UseVarType = VarType->hasIntegerRepresentation() &&
4454                     C.getTypeSize(Type) > C.getTypeSize(VarType);
4455   if (!Type->isIntegerType() || UseVarType) {
4456     unsigned NewSize =
4457         UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
4458     bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
4459                                : Type->hasSignedIntegerRepresentation();
4460     Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
4461     if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
4462       Diff = SemaRef.PerformImplicitConversion(
4463           Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
4464       if (!Diff.isUsable())
4465         return nullptr;
4466     }
4467   }
4468   if (LimitedType) {
4469     unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
4470     if (NewSize != C.getTypeSize(Type)) {
4471       if (NewSize < C.getTypeSize(Type)) {
4472         assert(NewSize == 64 && "incorrect loop var size");
4473         SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
4474             << InitSrcRange << ConditionSrcRange;
4475       }
4476       QualType NewType = C.getIntTypeForBitwidth(
4477           NewSize, Type->hasSignedIntegerRepresentation() ||
4478                        C.getTypeSize(Type) < NewSize);
4479       if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
4480         Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
4481                                                  Sema::AA_Converting, true);
4482         if (!Diff.isUsable())
4483           return nullptr;
4484       }
4485     }
4486   }
4487 
4488   return Diff.get();
4489 }
4490 
4491 Expr *OpenMPIterationSpaceChecker::buildPreCond(
4492     Scope *S, Expr *Cond,
4493     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
4494   // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
4495   bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
4496   SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
4497 
4498   ExprResult NewLB = tryBuildCapture(SemaRef, LB, Captures);
4499   ExprResult NewUB = tryBuildCapture(SemaRef, UB, Captures);
4500   if (!NewLB.isUsable() || !NewUB.isUsable())
4501     return nullptr;
4502 
4503   ExprResult CondExpr =
4504       SemaRef.BuildBinOp(S, DefaultLoc,
4505                          TestIsLessOp.getValue() ?
4506                            (TestIsStrictOp ? BO_LT : BO_LE) :
4507                            (TestIsStrictOp ? BO_GT : BO_GE),
4508                          NewLB.get(), NewUB.get());
4509   if (CondExpr.isUsable()) {
4510     if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
4511                                                 SemaRef.Context.BoolTy))
4512       CondExpr = SemaRef.PerformImplicitConversion(
4513           CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
4514           /*AllowExplicit=*/true);
4515   }
4516   SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
4517   // Otherwise use original loop conditon and evaluate it in runtime.
4518   return CondExpr.isUsable() ? CondExpr.get() : Cond;
4519 }
4520 
4521 /// Build reference expression to the counter be used for codegen.
4522 DeclRefExpr *OpenMPIterationSpaceChecker::buildCounterVar(
4523     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
4524     DSAStackTy &DSA) const {
4525   auto *VD = dyn_cast<VarDecl>(LCDecl);
4526   if (!VD) {
4527     VD = SemaRef.isOpenMPCapturedDecl(LCDecl);
4528     DeclRefExpr *Ref = buildDeclRefExpr(
4529         SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
4530     const DSAStackTy::DSAVarData Data =
4531         DSA.getTopDSA(LCDecl, /*FromParent=*/false);
4532     // If the loop control decl is explicitly marked as private, do not mark it
4533     // as captured again.
4534     if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
4535       Captures.insert(std::make_pair(LCRef, Ref));
4536     return Ref;
4537   }
4538   return buildDeclRefExpr(SemaRef, VD, VD->getType().getNonReferenceType(),
4539                           DefaultLoc);
4540 }
4541 
4542 Expr *OpenMPIterationSpaceChecker::buildPrivateCounterVar() const {
4543   if (LCDecl && !LCDecl->isInvalidDecl()) {
4544     QualType Type = LCDecl->getType().getNonReferenceType();
4545     VarDecl *PrivateVar = buildVarDecl(
4546         SemaRef, DefaultLoc, Type, LCDecl->getName(),
4547         LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr,
4548         isa<VarDecl>(LCDecl)
4549             ? buildDeclRefExpr(SemaRef, cast<VarDecl>(LCDecl), Type, DefaultLoc)
4550             : nullptr);
4551     if (PrivateVar->isInvalidDecl())
4552       return nullptr;
4553     return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
4554   }
4555   return nullptr;
4556 }
4557 
4558 /// Build initialization of the counter to be used for codegen.
4559 Expr *OpenMPIterationSpaceChecker::buildCounterInit() const { return LB; }
4560 
4561 /// Build step of the counter be used for codegen.
4562 Expr *OpenMPIterationSpaceChecker::buildCounterStep() const { return Step; }
4563 
4564 Expr *OpenMPIterationSpaceChecker::buildOrderedLoopData(
4565     Scope *S, Expr *Counter,
4566     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, SourceLocation Loc,
4567     Expr *Inc, OverloadedOperatorKind OOK) {
4568   Expr *Cnt = SemaRef.DefaultLvalueConversion(Counter).get();
4569   if (!Cnt)
4570     return nullptr;
4571   if (Inc) {
4572     assert((OOK == OO_Plus || OOK == OO_Minus) &&
4573            "Expected only + or - operations for depend clauses.");
4574     BinaryOperatorKind BOK = (OOK == OO_Plus) ? BO_Add : BO_Sub;
4575     Cnt = SemaRef.BuildBinOp(S, Loc, BOK, Cnt, Inc).get();
4576     if (!Cnt)
4577       return nullptr;
4578   }
4579   ExprResult Diff;
4580   QualType VarType = LCDecl->getType().getNonReferenceType();
4581   if (VarType->isIntegerType() || VarType->isPointerType() ||
4582       SemaRef.getLangOpts().CPlusPlus) {
4583     // Upper - Lower
4584     Expr *Upper =
4585         TestIsLessOp.getValue() ? Cnt : tryBuildCapture(SemaRef, UB, Captures).get();
4586     Expr *Lower =
4587         TestIsLessOp.getValue() ? tryBuildCapture(SemaRef, LB, Captures).get() : Cnt;
4588     if (!Upper || !Lower)
4589       return nullptr;
4590 
4591     Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
4592 
4593     if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
4594       // BuildBinOp already emitted error, this one is to point user to upper
4595       // and lower bound, and to tell what is passed to 'operator-'.
4596       SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
4597           << Upper->getSourceRange() << Lower->getSourceRange();
4598       return nullptr;
4599     }
4600   }
4601 
4602   if (!Diff.isUsable())
4603     return nullptr;
4604 
4605   // Parentheses (for dumping/debugging purposes only).
4606   Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
4607   if (!Diff.isUsable())
4608     return nullptr;
4609 
4610   ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
4611   if (!NewStep.isUsable())
4612     return nullptr;
4613   // (Upper - Lower) / Step
4614   Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
4615   if (!Diff.isUsable())
4616     return nullptr;
4617 
4618   return Diff.get();
4619 }
4620 
4621 /// Iteration space of a single for loop.
4622 struct LoopIterationSpace final {
4623   /// Condition of the loop.
4624   Expr *PreCond = nullptr;
4625   /// This expression calculates the number of iterations in the loop.
4626   /// It is always possible to calculate it before starting the loop.
4627   Expr *NumIterations = nullptr;
4628   /// The loop counter variable.
4629   Expr *CounterVar = nullptr;
4630   /// Private loop counter variable.
4631   Expr *PrivateCounterVar = nullptr;
4632   /// This is initializer for the initial value of #CounterVar.
4633   Expr *CounterInit = nullptr;
4634   /// This is step for the #CounterVar used to generate its update:
4635   /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
4636   Expr *CounterStep = nullptr;
4637   /// Should step be subtracted?
4638   bool Subtract = false;
4639   /// Source range of the loop init.
4640   SourceRange InitSrcRange;
4641   /// Source range of the loop condition.
4642   SourceRange CondSrcRange;
4643   /// Source range of the loop increment.
4644   SourceRange IncSrcRange;
4645 };
4646 
4647 } // namespace
4648 
4649 void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
4650   assert(getLangOpts().OpenMP && "OpenMP is not active.");
4651   assert(Init && "Expected loop in canonical form.");
4652   unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
4653   if (AssociatedLoops > 0 &&
4654       isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
4655     OpenMPIterationSpaceChecker ISC(*this, ForLoc);
4656     if (!ISC.checkAndSetInit(Init, /*EmitDiags=*/false)) {
4657       if (ValueDecl *D = ISC.getLoopDecl()) {
4658         auto *VD = dyn_cast<VarDecl>(D);
4659         if (!VD) {
4660           if (VarDecl *Private = isOpenMPCapturedDecl(D)) {
4661             VD = Private;
4662           } else {
4663             DeclRefExpr *Ref = buildCapture(*this, D, ISC.getLoopDeclRefExpr(),
4664                                             /*WithInit=*/false);
4665             VD = cast<VarDecl>(Ref->getDecl());
4666           }
4667         }
4668         DSAStack->addLoopControlVariable(D, VD);
4669         const Decl *LD = DSAStack->getPossiblyLoopCunter();
4670         if (LD != D->getCanonicalDecl()) {
4671           DSAStack->resetPossibleLoopCounter();
4672           if (auto *Var = dyn_cast_or_null<VarDecl>(LD))
4673             MarkDeclarationsReferencedInExpr(
4674                 buildDeclRefExpr(*this, const_cast<VarDecl *>(Var),
4675                                  Var->getType().getNonLValueExprType(Context),
4676                                  ForLoc, /*RefersToCapture=*/true));
4677         }
4678       }
4679     }
4680     DSAStack->setAssociatedLoops(AssociatedLoops - 1);
4681   }
4682 }
4683 
4684 /// Called on a for stmt to check and extract its iteration space
4685 /// for further processing (such as collapsing).
4686 static bool checkOpenMPIterationSpace(
4687     OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
4688     unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
4689     unsigned TotalNestedLoopCount, Expr *CollapseLoopCountExpr,
4690     Expr *OrderedLoopCountExpr,
4691     Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
4692     LoopIterationSpace &ResultIterSpace,
4693     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
4694   // OpenMP [2.6, Canonical Loop Form]
4695   //   for (init-expr; test-expr; incr-expr) structured-block
4696   auto *For = dyn_cast_or_null<ForStmt>(S);
4697   if (!For) {
4698     SemaRef.Diag(S->getBeginLoc(), diag::err_omp_not_for)
4699         << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
4700         << getOpenMPDirectiveName(DKind) << TotalNestedLoopCount
4701         << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
4702     if (TotalNestedLoopCount > 1) {
4703       if (CollapseLoopCountExpr && OrderedLoopCountExpr)
4704         SemaRef.Diag(DSA.getConstructLoc(),
4705                      diag::note_omp_collapse_ordered_expr)
4706             << 2 << CollapseLoopCountExpr->getSourceRange()
4707             << OrderedLoopCountExpr->getSourceRange();
4708       else if (CollapseLoopCountExpr)
4709         SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
4710                      diag::note_omp_collapse_ordered_expr)
4711             << 0 << CollapseLoopCountExpr->getSourceRange();
4712       else
4713         SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
4714                      diag::note_omp_collapse_ordered_expr)
4715             << 1 << OrderedLoopCountExpr->getSourceRange();
4716     }
4717     return true;
4718   }
4719   assert(For->getBody());
4720 
4721   OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
4722 
4723   // Check init.
4724   Stmt *Init = For->getInit();
4725   if (ISC.checkAndSetInit(Init))
4726     return true;
4727 
4728   bool HasErrors = false;
4729 
4730   // Check loop variable's type.
4731   if (ValueDecl *LCDecl = ISC.getLoopDecl()) {
4732     Expr *LoopDeclRefExpr = ISC.getLoopDeclRefExpr();
4733 
4734     // OpenMP [2.6, Canonical Loop Form]
4735     // Var is one of the following:
4736     //   A variable of signed or unsigned integer type.
4737     //   For C++, a variable of a random access iterator type.
4738     //   For C, a variable of a pointer type.
4739     QualType VarType = LCDecl->getType().getNonReferenceType();
4740     if (!VarType->isDependentType() && !VarType->isIntegerType() &&
4741         !VarType->isPointerType() &&
4742         !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
4743       SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_variable_type)
4744           << SemaRef.getLangOpts().CPlusPlus;
4745       HasErrors = true;
4746     }
4747 
4748     // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
4749     // a Construct
4750     // The loop iteration variable(s) in the associated for-loop(s) of a for or
4751     // parallel for construct is (are) private.
4752     // The loop iteration variable in the associated for-loop of a simd
4753     // construct with just one associated for-loop is linear with a
4754     // constant-linear-step that is the increment of the associated for-loop.
4755     // Exclude loop var from the list of variables with implicitly defined data
4756     // sharing attributes.
4757     VarsWithImplicitDSA.erase(LCDecl);
4758 
4759     // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
4760     // in a Construct, C/C++].
4761     // The loop iteration variable in the associated for-loop of a simd
4762     // construct with just one associated for-loop may be listed in a linear
4763     // clause with a constant-linear-step that is the increment of the
4764     // associated for-loop.
4765     // The loop iteration variable(s) in the associated for-loop(s) of a for or
4766     // parallel for construct may be listed in a private or lastprivate clause.
4767     DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false);
4768     // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
4769     // declared in the loop and it is predetermined as a private.
4770     OpenMPClauseKind PredeterminedCKind =
4771         isOpenMPSimdDirective(DKind)
4772             ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
4773             : OMPC_private;
4774     if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
4775           DVar.CKind != PredeterminedCKind) ||
4776          ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
4777            isOpenMPDistributeDirective(DKind)) &&
4778           !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
4779           DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
4780         (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
4781       SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_var_dsa)
4782           << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
4783           << getOpenMPClauseName(PredeterminedCKind);
4784       if (DVar.RefExpr == nullptr)
4785         DVar.CKind = PredeterminedCKind;
4786       reportOriginalDsa(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true);
4787       HasErrors = true;
4788     } else if (LoopDeclRefExpr != nullptr) {
4789       // Make the loop iteration variable private (for worksharing constructs),
4790       // linear (for simd directives with the only one associated loop) or
4791       // lastprivate (for simd directives with several collapsed or ordered
4792       // loops).
4793       if (DVar.CKind == OMPC_unknown)
4794         DVar = DSA.hasDSA(LCDecl, isOpenMPPrivate,
4795                           [](OpenMPDirectiveKind) -> bool { return true; },
4796                           /*FromParent=*/false);
4797       DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind);
4798     }
4799 
4800     assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
4801 
4802     // Check test-expr.
4803     HasErrors |= ISC.checkAndSetCond(For->getCond());
4804 
4805     // Check incr-expr.
4806     HasErrors |= ISC.checkAndSetInc(For->getInc());
4807   }
4808 
4809   if (ISC.dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
4810     return HasErrors;
4811 
4812   // Build the loop's iteration space representation.
4813   ResultIterSpace.PreCond =
4814       ISC.buildPreCond(DSA.getCurScope(), For->getCond(), Captures);
4815   ResultIterSpace.NumIterations = ISC.buildNumIterations(
4816       DSA.getCurScope(),
4817       (isOpenMPWorksharingDirective(DKind) ||
4818        isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)),
4819       Captures);
4820   ResultIterSpace.CounterVar = ISC.buildCounterVar(Captures, DSA);
4821   ResultIterSpace.PrivateCounterVar = ISC.buildPrivateCounterVar();
4822   ResultIterSpace.CounterInit = ISC.buildCounterInit();
4823   ResultIterSpace.CounterStep = ISC.buildCounterStep();
4824   ResultIterSpace.InitSrcRange = ISC.getInitSrcRange();
4825   ResultIterSpace.CondSrcRange = ISC.getConditionSrcRange();
4826   ResultIterSpace.IncSrcRange = ISC.getIncrementSrcRange();
4827   ResultIterSpace.Subtract = ISC.shouldSubtractStep();
4828 
4829   HasErrors |= (ResultIterSpace.PreCond == nullptr ||
4830                 ResultIterSpace.NumIterations == nullptr ||
4831                 ResultIterSpace.CounterVar == nullptr ||
4832                 ResultIterSpace.PrivateCounterVar == nullptr ||
4833                 ResultIterSpace.CounterInit == nullptr ||
4834                 ResultIterSpace.CounterStep == nullptr);
4835   if (!HasErrors && DSA.isOrderedRegion()) {
4836     if (DSA.getOrderedRegionParam().second->getNumForLoops()) {
4837       if (CurrentNestedLoopCount <
4838           DSA.getOrderedRegionParam().second->getLoopNumIterations().size()) {
4839         DSA.getOrderedRegionParam().second->setLoopNumIterations(
4840             CurrentNestedLoopCount, ResultIterSpace.NumIterations);
4841         DSA.getOrderedRegionParam().second->setLoopCounter(
4842             CurrentNestedLoopCount, ResultIterSpace.CounterVar);
4843       }
4844     }
4845     for (auto &Pair : DSA.getDoacrossDependClauses()) {
4846       if (CurrentNestedLoopCount >= Pair.first->getNumLoops()) {
4847         // Erroneous case - clause has some problems.
4848         continue;
4849       }
4850       if (Pair.first->getDependencyKind() == OMPC_DEPEND_sink &&
4851           Pair.second.size() <= CurrentNestedLoopCount) {
4852         // Erroneous case - clause has some problems.
4853         Pair.first->setLoopData(CurrentNestedLoopCount, nullptr);
4854         continue;
4855       }
4856       Expr *CntValue;
4857       if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
4858         CntValue = ISC.buildOrderedLoopData(
4859             DSA.getCurScope(), ResultIterSpace.CounterVar, Captures,
4860             Pair.first->getDependencyLoc());
4861       else
4862         CntValue = ISC.buildOrderedLoopData(
4863             DSA.getCurScope(), ResultIterSpace.CounterVar, Captures,
4864             Pair.first->getDependencyLoc(),
4865             Pair.second[CurrentNestedLoopCount].first,
4866             Pair.second[CurrentNestedLoopCount].second);
4867       Pair.first->setLoopData(CurrentNestedLoopCount, CntValue);
4868     }
4869   }
4870 
4871   return HasErrors;
4872 }
4873 
4874 /// Build 'VarRef = Start.
4875 static ExprResult
4876 buildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
4877                  ExprResult Start,
4878                  llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
4879   // Build 'VarRef = Start.
4880   ExprResult NewStart = tryBuildCapture(SemaRef, Start.get(), Captures);
4881   if (!NewStart.isUsable())
4882     return ExprError();
4883   if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
4884                                    VarRef.get()->getType())) {
4885     NewStart = SemaRef.PerformImplicitConversion(
4886         NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
4887         /*AllowExplicit=*/true);
4888     if (!NewStart.isUsable())
4889       return ExprError();
4890   }
4891 
4892   ExprResult Init =
4893       SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
4894   return Init;
4895 }
4896 
4897 /// Build 'VarRef = Start + Iter * Step'.
4898 static ExprResult buildCounterUpdate(
4899     Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
4900     ExprResult Start, ExprResult Iter, ExprResult Step, bool Subtract,
4901     llvm::MapVector<const Expr *, DeclRefExpr *> *Captures = nullptr) {
4902   // Add parentheses (for debugging purposes only).
4903   Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
4904   if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
4905       !Step.isUsable())
4906     return ExprError();
4907 
4908   ExprResult NewStep = Step;
4909   if (Captures)
4910     NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
4911   if (NewStep.isInvalid())
4912     return ExprError();
4913   ExprResult Update =
4914       SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
4915   if (!Update.isUsable())
4916     return ExprError();
4917 
4918   // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
4919   // 'VarRef = Start (+|-) Iter * Step'.
4920   ExprResult NewStart = Start;
4921   if (Captures)
4922     NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
4923   if (NewStart.isInvalid())
4924     return ExprError();
4925 
4926   // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
4927   ExprResult SavedUpdate = Update;
4928   ExprResult UpdateVal;
4929   if (VarRef.get()->getType()->isOverloadableType() ||
4930       NewStart.get()->getType()->isOverloadableType() ||
4931       Update.get()->getType()->isOverloadableType()) {
4932     bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
4933     SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
4934     Update =
4935         SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
4936     if (Update.isUsable()) {
4937       UpdateVal =
4938           SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
4939                              VarRef.get(), SavedUpdate.get());
4940       if (UpdateVal.isUsable()) {
4941         Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
4942                                             UpdateVal.get());
4943       }
4944     }
4945     SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
4946   }
4947 
4948   // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
4949   if (!Update.isUsable() || !UpdateVal.isUsable()) {
4950     Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
4951                                 NewStart.get(), SavedUpdate.get());
4952     if (!Update.isUsable())
4953       return ExprError();
4954 
4955     if (!SemaRef.Context.hasSameType(Update.get()->getType(),
4956                                      VarRef.get()->getType())) {
4957       Update = SemaRef.PerformImplicitConversion(
4958           Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
4959       if (!Update.isUsable())
4960         return ExprError();
4961     }
4962 
4963     Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
4964   }
4965   return Update;
4966 }
4967 
4968 /// Convert integer expression \a E to make it have at least \a Bits
4969 /// bits.
4970 static ExprResult widenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
4971   if (E == nullptr)
4972     return ExprError();
4973   ASTContext &C = SemaRef.Context;
4974   QualType OldType = E->getType();
4975   unsigned HasBits = C.getTypeSize(OldType);
4976   if (HasBits >= Bits)
4977     return ExprResult(E);
4978   // OK to convert to signed, because new type has more bits than old.
4979   QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
4980   return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
4981                                            true);
4982 }
4983 
4984 /// Check if the given expression \a E is a constant integer that fits
4985 /// into \a Bits bits.
4986 static bool fitsInto(unsigned Bits, bool Signed, const Expr *E, Sema &SemaRef) {
4987   if (E == nullptr)
4988     return false;
4989   llvm::APSInt Result;
4990   if (E->isIntegerConstantExpr(Result, SemaRef.Context))
4991     return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
4992   return false;
4993 }
4994 
4995 /// Build preinits statement for the given declarations.
4996 static Stmt *buildPreInits(ASTContext &Context,
4997                            MutableArrayRef<Decl *> PreInits) {
4998   if (!PreInits.empty()) {
4999     return new (Context) DeclStmt(
5000         DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
5001         SourceLocation(), SourceLocation());
5002   }
5003   return nullptr;
5004 }
5005 
5006 /// Build preinits statement for the given declarations.
5007 static Stmt *
5008 buildPreInits(ASTContext &Context,
5009               const llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
5010   if (!Captures.empty()) {
5011     SmallVector<Decl *, 16> PreInits;
5012     for (const auto &Pair : Captures)
5013       PreInits.push_back(Pair.second->getDecl());
5014     return buildPreInits(Context, PreInits);
5015   }
5016   return nullptr;
5017 }
5018 
5019 /// Build postupdate expression for the given list of postupdates expressions.
5020 static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
5021   Expr *PostUpdate = nullptr;
5022   if (!PostUpdates.empty()) {
5023     for (Expr *E : PostUpdates) {
5024       Expr *ConvE = S.BuildCStyleCastExpr(
5025                          E->getExprLoc(),
5026                          S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
5027                          E->getExprLoc(), E)
5028                         .get();
5029       PostUpdate = PostUpdate
5030                        ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
5031                                               PostUpdate, ConvE)
5032                              .get()
5033                        : ConvE;
5034     }
5035   }
5036   return PostUpdate;
5037 }
5038 
5039 /// Called on a for stmt to check itself and nested loops (if any).
5040 /// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
5041 /// number of collapsed loops otherwise.
5042 static unsigned
5043 checkOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
5044                 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
5045                 DSAStackTy &DSA,
5046                 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
5047                 OMPLoopDirective::HelperExprs &Built) {
5048   unsigned NestedLoopCount = 1;
5049   if (CollapseLoopCountExpr) {
5050     // Found 'collapse' clause - calculate collapse number.
5051     Expr::EvalResult Result;
5052     if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
5053       NestedLoopCount = Result.Val.getInt().getLimitedValue();
5054   }
5055   unsigned OrderedLoopCount = 1;
5056   if (OrderedLoopCountExpr) {
5057     // Found 'ordered' clause - calculate collapse number.
5058     Expr::EvalResult EVResult;
5059     if (OrderedLoopCountExpr->EvaluateAsInt(EVResult, SemaRef.getASTContext())) {
5060       llvm::APSInt Result = EVResult.Val.getInt();
5061       if (Result.getLimitedValue() < NestedLoopCount) {
5062         SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
5063                      diag::err_omp_wrong_ordered_loop_count)
5064             << OrderedLoopCountExpr->getSourceRange();
5065         SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
5066                      diag::note_collapse_loop_count)
5067             << CollapseLoopCountExpr->getSourceRange();
5068       }
5069       OrderedLoopCount = Result.getLimitedValue();
5070     }
5071   }
5072   // This is helper routine for loop directives (e.g., 'for', 'simd',
5073   // 'for simd', etc.).
5074   llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
5075   SmallVector<LoopIterationSpace, 4> IterSpaces;
5076   IterSpaces.resize(std::max(OrderedLoopCount, NestedLoopCount));
5077   Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
5078   for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
5079     if (checkOpenMPIterationSpace(
5080             DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
5081             std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
5082             OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces[Cnt],
5083             Captures))
5084       return 0;
5085     // Move on to the next nested for loop, or to the loop body.
5086     // OpenMP [2.8.1, simd construct, Restrictions]
5087     // All loops associated with the construct must be perfectly nested; that
5088     // is, there must be no intervening code nor any OpenMP directive between
5089     // any two loops.
5090     CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
5091   }
5092   for (unsigned Cnt = NestedLoopCount; Cnt < OrderedLoopCount; ++Cnt) {
5093     if (checkOpenMPIterationSpace(
5094             DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
5095             std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
5096             OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces[Cnt],
5097             Captures))
5098       return 0;
5099     if (Cnt > 0 && IterSpaces[Cnt].CounterVar) {
5100       // Handle initialization of captured loop iterator variables.
5101       auto *DRE = cast<DeclRefExpr>(IterSpaces[Cnt].CounterVar);
5102       if (isa<OMPCapturedExprDecl>(DRE->getDecl())) {
5103         Captures[DRE] = DRE;
5104       }
5105     }
5106     // Move on to the next nested for loop, or to the loop body.
5107     // OpenMP [2.8.1, simd construct, Restrictions]
5108     // All loops associated with the construct must be perfectly nested; that
5109     // is, there must be no intervening code nor any OpenMP directive between
5110     // any two loops.
5111     CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
5112   }
5113 
5114   Built.clear(/* size */ NestedLoopCount);
5115 
5116   if (SemaRef.CurContext->isDependentContext())
5117     return NestedLoopCount;
5118 
5119   // An example of what is generated for the following code:
5120   //
5121   //   #pragma omp simd collapse(2) ordered(2)
5122   //   for (i = 0; i < NI; ++i)
5123   //     for (k = 0; k < NK; ++k)
5124   //       for (j = J0; j < NJ; j+=2) {
5125   //         <loop body>
5126   //       }
5127   //
5128   // We generate the code below.
5129   // Note: the loop body may be outlined in CodeGen.
5130   // Note: some counters may be C++ classes, operator- is used to find number of
5131   // iterations and operator+= to calculate counter value.
5132   // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
5133   // or i64 is currently supported).
5134   //
5135   //   #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
5136   //   for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
5137   //     .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
5138   //     .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
5139   //     // similar updates for vars in clauses (e.g. 'linear')
5140   //     <loop body (using local i and j)>
5141   //   }
5142   //   i = NI; // assign final values of counters
5143   //   j = NJ;
5144   //
5145 
5146   // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
5147   // the iteration counts of the collapsed for loops.
5148   // Precondition tests if there is at least one iteration (all conditions are
5149   // true).
5150   auto PreCond = ExprResult(IterSpaces[0].PreCond);
5151   Expr *N0 = IterSpaces[0].NumIterations;
5152   ExprResult LastIteration32 =
5153       widenIterationCount(/*Bits=*/32,
5154                           SemaRef
5155                               .PerformImplicitConversion(
5156                                   N0->IgnoreImpCasts(), N0->getType(),
5157                                   Sema::AA_Converting, /*AllowExplicit=*/true)
5158                               .get(),
5159                           SemaRef);
5160   ExprResult LastIteration64 = widenIterationCount(
5161       /*Bits=*/64,
5162       SemaRef
5163           .PerformImplicitConversion(N0->IgnoreImpCasts(), N0->getType(),
5164                                      Sema::AA_Converting,
5165                                      /*AllowExplicit=*/true)
5166           .get(),
5167       SemaRef);
5168 
5169   if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
5170     return NestedLoopCount;
5171 
5172   ASTContext &C = SemaRef.Context;
5173   bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
5174 
5175   Scope *CurScope = DSA.getCurScope();
5176   for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
5177     if (PreCond.isUsable()) {
5178       PreCond =
5179           SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
5180                              PreCond.get(), IterSpaces[Cnt].PreCond);
5181     }
5182     Expr *N = IterSpaces[Cnt].NumIterations;
5183     SourceLocation Loc = N->getExprLoc();
5184     AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
5185     if (LastIteration32.isUsable())
5186       LastIteration32 = SemaRef.BuildBinOp(
5187           CurScope, Loc, BO_Mul, LastIteration32.get(),
5188           SemaRef
5189               .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
5190                                          Sema::AA_Converting,
5191                                          /*AllowExplicit=*/true)
5192               .get());
5193     if (LastIteration64.isUsable())
5194       LastIteration64 = SemaRef.BuildBinOp(
5195           CurScope, Loc, BO_Mul, LastIteration64.get(),
5196           SemaRef
5197               .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
5198                                          Sema::AA_Converting,
5199                                          /*AllowExplicit=*/true)
5200               .get());
5201   }
5202 
5203   // Choose either the 32-bit or 64-bit version.
5204   ExprResult LastIteration = LastIteration64;
5205   if (LastIteration32.isUsable() &&
5206       C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
5207       (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
5208        fitsInto(
5209            /*Bits=*/32,
5210            LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
5211            LastIteration64.get(), SemaRef)))
5212     LastIteration = LastIteration32;
5213   QualType VType = LastIteration.get()->getType();
5214   QualType RealVType = VType;
5215   QualType StrideVType = VType;
5216   if (isOpenMPTaskLoopDirective(DKind)) {
5217     VType =
5218         SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
5219     StrideVType =
5220         SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
5221   }
5222 
5223   if (!LastIteration.isUsable())
5224     return 0;
5225 
5226   // Save the number of iterations.
5227   ExprResult NumIterations = LastIteration;
5228   {
5229     LastIteration = SemaRef.BuildBinOp(
5230         CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
5231         LastIteration.get(),
5232         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
5233     if (!LastIteration.isUsable())
5234       return 0;
5235   }
5236 
5237   // Calculate the last iteration number beforehand instead of doing this on
5238   // each iteration. Do not do this if the number of iterations may be kfold-ed.
5239   llvm::APSInt Result;
5240   bool IsConstant =
5241       LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
5242   ExprResult CalcLastIteration;
5243   if (!IsConstant) {
5244     ExprResult SaveRef =
5245         tryBuildCapture(SemaRef, LastIteration.get(), Captures);
5246     LastIteration = SaveRef;
5247 
5248     // Prepare SaveRef + 1.
5249     NumIterations = SemaRef.BuildBinOp(
5250         CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
5251         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
5252     if (!NumIterations.isUsable())
5253       return 0;
5254   }
5255 
5256   SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
5257 
5258   // Build variables passed into runtime, necessary for worksharing directives.
5259   ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
5260   if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
5261       isOpenMPDistributeDirective(DKind)) {
5262     // Lower bound variable, initialized with zero.
5263     VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
5264     LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
5265     SemaRef.AddInitializerToDecl(LBDecl,
5266                                  SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
5267                                  /*DirectInit*/ false);
5268 
5269     // Upper bound variable, initialized with last iteration number.
5270     VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
5271     UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
5272     SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
5273                                  /*DirectInit*/ false);
5274 
5275     // A 32-bit variable-flag where runtime returns 1 for the last iteration.
5276     // This will be used to implement clause 'lastprivate'.
5277     QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
5278     VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
5279     IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
5280     SemaRef.AddInitializerToDecl(ILDecl,
5281                                  SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
5282                                  /*DirectInit*/ false);
5283 
5284     // Stride variable returned by runtime (we initialize it to 1 by default).
5285     VarDecl *STDecl =
5286         buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
5287     ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
5288     SemaRef.AddInitializerToDecl(STDecl,
5289                                  SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
5290                                  /*DirectInit*/ false);
5291 
5292     // Build expression: UB = min(UB, LastIteration)
5293     // It is necessary for CodeGen of directives with static scheduling.
5294     ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
5295                                                 UB.get(), LastIteration.get());
5296     ExprResult CondOp = SemaRef.ActOnConditionalOp(
5297         LastIteration.get()->getExprLoc(), InitLoc, IsUBGreater.get(),
5298         LastIteration.get(), UB.get());
5299     EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
5300                              CondOp.get());
5301     EUB = SemaRef.ActOnFinishFullExpr(EUB.get());
5302 
5303     // If we have a combined directive that combines 'distribute', 'for' or
5304     // 'simd' we need to be able to access the bounds of the schedule of the
5305     // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
5306     // by scheduling 'distribute' have to be passed to the schedule of 'for'.
5307     if (isOpenMPLoopBoundSharingDirective(DKind)) {
5308       // Lower bound variable, initialized with zero.
5309       VarDecl *CombLBDecl =
5310           buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
5311       CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
5312       SemaRef.AddInitializerToDecl(
5313           CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
5314           /*DirectInit*/ false);
5315 
5316       // Upper bound variable, initialized with last iteration number.
5317       VarDecl *CombUBDecl =
5318           buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
5319       CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
5320       SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
5321                                    /*DirectInit*/ false);
5322 
5323       ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
5324           CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
5325       ExprResult CombCondOp =
5326           SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
5327                                      LastIteration.get(), CombUB.get());
5328       CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
5329                                    CombCondOp.get());
5330       CombEUB = SemaRef.ActOnFinishFullExpr(CombEUB.get());
5331 
5332       const CapturedDecl *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
5333       // We expect to have at least 2 more parameters than the 'parallel'
5334       // directive does - the lower and upper bounds of the previous schedule.
5335       assert(CD->getNumParams() >= 4 &&
5336              "Unexpected number of parameters in loop combined directive");
5337 
5338       // Set the proper type for the bounds given what we learned from the
5339       // enclosed loops.
5340       ImplicitParamDecl *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
5341       ImplicitParamDecl *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
5342 
5343       // Previous lower and upper bounds are obtained from the region
5344       // parameters.
5345       PrevLB =
5346           buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
5347       PrevUB =
5348           buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
5349     }
5350   }
5351 
5352   // Build the iteration variable and its initialization before loop.
5353   ExprResult IV;
5354   ExprResult Init, CombInit;
5355   {
5356     VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
5357     IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
5358     Expr *RHS =
5359         (isOpenMPWorksharingDirective(DKind) ||
5360          isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
5361             ? LB.get()
5362             : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
5363     Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
5364     Init = SemaRef.ActOnFinishFullExpr(Init.get());
5365 
5366     if (isOpenMPLoopBoundSharingDirective(DKind)) {
5367       Expr *CombRHS =
5368           (isOpenMPWorksharingDirective(DKind) ||
5369            isOpenMPTaskLoopDirective(DKind) ||
5370            isOpenMPDistributeDirective(DKind))
5371               ? CombLB.get()
5372               : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
5373       CombInit =
5374           SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
5375       CombInit = SemaRef.ActOnFinishFullExpr(CombInit.get());
5376     }
5377   }
5378 
5379   // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops.
5380   SourceLocation CondLoc = AStmt->getBeginLoc();
5381   ExprResult Cond =
5382       (isOpenMPWorksharingDirective(DKind) ||
5383        isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
5384           ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get())
5385           : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
5386                                NumIterations.get());
5387   ExprResult CombDistCond;
5388   if (isOpenMPLoopBoundSharingDirective(DKind)) {
5389     CombDistCond =
5390         SemaRef.BuildBinOp(
5391             CurScope, CondLoc, BO_LT, IV.get(), NumIterations.get());
5392   }
5393 
5394   ExprResult CombCond;
5395   if (isOpenMPLoopBoundSharingDirective(DKind)) {
5396     CombCond =
5397         SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), CombUB.get());
5398   }
5399   // Loop increment (IV = IV + 1)
5400   SourceLocation IncLoc = AStmt->getBeginLoc();
5401   ExprResult Inc =
5402       SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
5403                          SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
5404   if (!Inc.isUsable())
5405     return 0;
5406   Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
5407   Inc = SemaRef.ActOnFinishFullExpr(Inc.get());
5408   if (!Inc.isUsable())
5409     return 0;
5410 
5411   // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
5412   // Used for directives with static scheduling.
5413   // In combined construct, add combined version that use CombLB and CombUB
5414   // base variables for the update
5415   ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
5416   if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
5417       isOpenMPDistributeDirective(DKind)) {
5418     // LB + ST
5419     NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
5420     if (!NextLB.isUsable())
5421       return 0;
5422     // LB = LB + ST
5423     NextLB =
5424         SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
5425     NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get());
5426     if (!NextLB.isUsable())
5427       return 0;
5428     // UB + ST
5429     NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
5430     if (!NextUB.isUsable())
5431       return 0;
5432     // UB = UB + ST
5433     NextUB =
5434         SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
5435     NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get());
5436     if (!NextUB.isUsable())
5437       return 0;
5438     if (isOpenMPLoopBoundSharingDirective(DKind)) {
5439       CombNextLB =
5440           SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
5441       if (!NextLB.isUsable())
5442         return 0;
5443       // LB = LB + ST
5444       CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
5445                                       CombNextLB.get());
5446       CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get());
5447       if (!CombNextLB.isUsable())
5448         return 0;
5449       // UB + ST
5450       CombNextUB =
5451           SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
5452       if (!CombNextUB.isUsable())
5453         return 0;
5454       // UB = UB + ST
5455       CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
5456                                       CombNextUB.get());
5457       CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get());
5458       if (!CombNextUB.isUsable())
5459         return 0;
5460     }
5461   }
5462 
5463   // Create increment expression for distribute loop when combined in a same
5464   // directive with for as IV = IV + ST; ensure upper bound expression based
5465   // on PrevUB instead of NumIterations - used to implement 'for' when found
5466   // in combination with 'distribute', like in 'distribute parallel for'
5467   SourceLocation DistIncLoc = AStmt->getBeginLoc();
5468   ExprResult DistCond, DistInc, PrevEUB, ParForInDistCond;
5469   if (isOpenMPLoopBoundSharingDirective(DKind)) {
5470     DistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get());
5471     assert(DistCond.isUsable() && "distribute cond expr was not built");
5472 
5473     DistInc =
5474         SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
5475     assert(DistInc.isUsable() && "distribute inc expr was not built");
5476     DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
5477                                  DistInc.get());
5478     DistInc = SemaRef.ActOnFinishFullExpr(DistInc.get());
5479     assert(DistInc.isUsable() && "distribute inc expr was not built");
5480 
5481     // Build expression: UB = min(UB, prevUB) for #for in composite or combined
5482     // construct
5483     SourceLocation DistEUBLoc = AStmt->getBeginLoc();
5484     ExprResult IsUBGreater =
5485         SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get());
5486     ExprResult CondOp = SemaRef.ActOnConditionalOp(
5487         DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get());
5488     PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
5489                                  CondOp.get());
5490     PrevEUB = SemaRef.ActOnFinishFullExpr(PrevEUB.get());
5491 
5492     // Build IV <= PrevUB to be used in parallel for is in combination with
5493     // a distribute directive with schedule(static, 1)
5494     ParForInDistCond =
5495         SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), PrevUB.get());
5496   }
5497 
5498   // Build updates and final values of the loop counters.
5499   bool HasErrors = false;
5500   Built.Counters.resize(NestedLoopCount);
5501   Built.Inits.resize(NestedLoopCount);
5502   Built.Updates.resize(NestedLoopCount);
5503   Built.Finals.resize(NestedLoopCount);
5504   {
5505     ExprResult Div;
5506     // Go from inner nested loop to outer.
5507     for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
5508       LoopIterationSpace &IS = IterSpaces[Cnt];
5509       SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
5510       // Build: Iter = (IV / Div) % IS.NumIters
5511       // where Div is product of previous iterations' IS.NumIters.
5512       ExprResult Iter;
5513       if (Div.isUsable()) {
5514         Iter =
5515             SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get());
5516       } else {
5517         Iter = IV;
5518         assert((Cnt == (int)NestedLoopCount - 1) &&
5519                "unusable div expected on first iteration only");
5520       }
5521 
5522       if (Cnt != 0 && Iter.isUsable())
5523         Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(),
5524                                   IS.NumIterations);
5525       if (!Iter.isUsable()) {
5526         HasErrors = true;
5527         break;
5528       }
5529 
5530       // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
5531       auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
5532       DeclRefExpr *CounterVar = buildDeclRefExpr(
5533           SemaRef, VD, IS.CounterVar->getType(), IS.CounterVar->getExprLoc(),
5534           /*RefersToCapture=*/true);
5535       ExprResult Init = buildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
5536                                          IS.CounterInit, Captures);
5537       if (!Init.isUsable()) {
5538         HasErrors = true;
5539         break;
5540       }
5541       ExprResult Update = buildCounterUpdate(
5542           SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
5543           IS.CounterStep, IS.Subtract, &Captures);
5544       if (!Update.isUsable()) {
5545         HasErrors = true;
5546         break;
5547       }
5548 
5549       // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
5550       ExprResult Final = buildCounterUpdate(
5551           SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
5552           IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures);
5553       if (!Final.isUsable()) {
5554         HasErrors = true;
5555         break;
5556       }
5557 
5558       // Build Div for the next iteration: Div <- Div * IS.NumIters
5559       if (Cnt != 0) {
5560         if (Div.isUnset())
5561           Div = IS.NumIterations;
5562         else
5563           Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(),
5564                                    IS.NumIterations);
5565 
5566         // Add parentheses (for debugging purposes only).
5567         if (Div.isUsable())
5568           Div = tryBuildCapture(SemaRef, Div.get(), Captures);
5569         if (!Div.isUsable()) {
5570           HasErrors = true;
5571           break;
5572         }
5573       }
5574       if (!Update.isUsable() || !Final.isUsable()) {
5575         HasErrors = true;
5576         break;
5577       }
5578       // Save results
5579       Built.Counters[Cnt] = IS.CounterVar;
5580       Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
5581       Built.Inits[Cnt] = Init.get();
5582       Built.Updates[Cnt] = Update.get();
5583       Built.Finals[Cnt] = Final.get();
5584     }
5585   }
5586 
5587   if (HasErrors)
5588     return 0;
5589 
5590   // Save results
5591   Built.IterationVarRef = IV.get();
5592   Built.LastIteration = LastIteration.get();
5593   Built.NumIterations = NumIterations.get();
5594   Built.CalcLastIteration =
5595       SemaRef.ActOnFinishFullExpr(CalcLastIteration.get()).get();
5596   Built.PreCond = PreCond.get();
5597   Built.PreInits = buildPreInits(C, Captures);
5598   Built.Cond = Cond.get();
5599   Built.Init = Init.get();
5600   Built.Inc = Inc.get();
5601   Built.LB = LB.get();
5602   Built.UB = UB.get();
5603   Built.IL = IL.get();
5604   Built.ST = ST.get();
5605   Built.EUB = EUB.get();
5606   Built.NLB = NextLB.get();
5607   Built.NUB = NextUB.get();
5608   Built.PrevLB = PrevLB.get();
5609   Built.PrevUB = PrevUB.get();
5610   Built.DistInc = DistInc.get();
5611   Built.PrevEUB = PrevEUB.get();
5612   Built.DistCombinedFields.LB = CombLB.get();
5613   Built.DistCombinedFields.UB = CombUB.get();
5614   Built.DistCombinedFields.EUB = CombEUB.get();
5615   Built.DistCombinedFields.Init = CombInit.get();
5616   Built.DistCombinedFields.Cond = CombCond.get();
5617   Built.DistCombinedFields.NLB = CombNextLB.get();
5618   Built.DistCombinedFields.NUB = CombNextUB.get();
5619   Built.DistCombinedFields.DistCond = CombDistCond.get();
5620   Built.DistCombinedFields.ParForInDistCond = ParForInDistCond.get();
5621 
5622   return NestedLoopCount;
5623 }
5624 
5625 static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
5626   auto CollapseClauses =
5627       OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
5628   if (CollapseClauses.begin() != CollapseClauses.end())
5629     return (*CollapseClauses.begin())->getNumForLoops();
5630   return nullptr;
5631 }
5632 
5633 static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
5634   auto OrderedClauses =
5635       OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
5636   if (OrderedClauses.begin() != OrderedClauses.end())
5637     return (*OrderedClauses.begin())->getNumForLoops();
5638   return nullptr;
5639 }
5640 
5641 static bool checkSimdlenSafelenSpecified(Sema &S,
5642                                          const ArrayRef<OMPClause *> Clauses) {
5643   const OMPSafelenClause *Safelen = nullptr;
5644   const OMPSimdlenClause *Simdlen = nullptr;
5645 
5646   for (const OMPClause *Clause : Clauses) {
5647     if (Clause->getClauseKind() == OMPC_safelen)
5648       Safelen = cast<OMPSafelenClause>(Clause);
5649     else if (Clause->getClauseKind() == OMPC_simdlen)
5650       Simdlen = cast<OMPSimdlenClause>(Clause);
5651     if (Safelen && Simdlen)
5652       break;
5653   }
5654 
5655   if (Simdlen && Safelen) {
5656     const Expr *SimdlenLength = Simdlen->getSimdlen();
5657     const Expr *SafelenLength = Safelen->getSafelen();
5658     if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
5659         SimdlenLength->isInstantiationDependent() ||
5660         SimdlenLength->containsUnexpandedParameterPack())
5661       return false;
5662     if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
5663         SafelenLength->isInstantiationDependent() ||
5664         SafelenLength->containsUnexpandedParameterPack())
5665       return false;
5666     Expr::EvalResult SimdlenResult, SafelenResult;
5667     SimdlenLength->EvaluateAsInt(SimdlenResult, S.Context);
5668     SafelenLength->EvaluateAsInt(SafelenResult, S.Context);
5669     llvm::APSInt SimdlenRes = SimdlenResult.Val.getInt();
5670     llvm::APSInt SafelenRes = SafelenResult.Val.getInt();
5671     // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
5672     // If both simdlen and safelen clauses are specified, the value of the
5673     // simdlen parameter must be less than or equal to the value of the safelen
5674     // parameter.
5675     if (SimdlenRes > SafelenRes) {
5676       S.Diag(SimdlenLength->getExprLoc(),
5677              diag::err_omp_wrong_simdlen_safelen_values)
5678           << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
5679       return true;
5680     }
5681   }
5682   return false;
5683 }
5684 
5685 StmtResult
5686 Sema::ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
5687                                SourceLocation StartLoc, SourceLocation EndLoc,
5688                                VarsWithInheritedDSAType &VarsWithImplicitDSA) {
5689   if (!AStmt)
5690     return StmtError();
5691 
5692   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5693   OMPLoopDirective::HelperExprs B;
5694   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5695   // define the nested loops number.
5696   unsigned NestedLoopCount = checkOpenMPLoop(
5697       OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
5698       AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
5699   if (NestedLoopCount == 0)
5700     return StmtError();
5701 
5702   assert((CurContext->isDependentContext() || B.builtAll()) &&
5703          "omp simd loop exprs were not built");
5704 
5705   if (!CurContext->isDependentContext()) {
5706     // Finalize the clauses that need pre-built expressions for CodeGen.
5707     for (OMPClause *C : Clauses) {
5708       if (auto *LC = dyn_cast<OMPLinearClause>(C))
5709         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
5710                                      B.NumIterations, *this, CurScope,
5711                                      DSAStack))
5712           return StmtError();
5713     }
5714   }
5715 
5716   if (checkSimdlenSafelenSpecified(*this, Clauses))
5717     return StmtError();
5718 
5719   setFunctionHasBranchProtectedScope();
5720   return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
5721                                   Clauses, AStmt, B);
5722 }
5723 
5724 StmtResult
5725 Sema::ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
5726                               SourceLocation StartLoc, SourceLocation EndLoc,
5727                               VarsWithInheritedDSAType &VarsWithImplicitDSA) {
5728   if (!AStmt)
5729     return StmtError();
5730 
5731   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5732   OMPLoopDirective::HelperExprs B;
5733   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5734   // define the nested loops number.
5735   unsigned NestedLoopCount = checkOpenMPLoop(
5736       OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
5737       AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
5738   if (NestedLoopCount == 0)
5739     return StmtError();
5740 
5741   assert((CurContext->isDependentContext() || B.builtAll()) &&
5742          "omp for loop exprs were not built");
5743 
5744   if (!CurContext->isDependentContext()) {
5745     // Finalize the clauses that need pre-built expressions for CodeGen.
5746     for (OMPClause *C : Clauses) {
5747       if (auto *LC = dyn_cast<OMPLinearClause>(C))
5748         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
5749                                      B.NumIterations, *this, CurScope,
5750                                      DSAStack))
5751           return StmtError();
5752     }
5753   }
5754 
5755   setFunctionHasBranchProtectedScope();
5756   return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
5757                                  Clauses, AStmt, B, DSAStack->isCancelRegion());
5758 }
5759 
5760 StmtResult Sema::ActOnOpenMPForSimdDirective(
5761     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5762     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
5763   if (!AStmt)
5764     return StmtError();
5765 
5766   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5767   OMPLoopDirective::HelperExprs B;
5768   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5769   // define the nested loops number.
5770   unsigned NestedLoopCount =
5771       checkOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
5772                       getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5773                       VarsWithImplicitDSA, B);
5774   if (NestedLoopCount == 0)
5775     return StmtError();
5776 
5777   assert((CurContext->isDependentContext() || B.builtAll()) &&
5778          "omp for simd loop exprs were not built");
5779 
5780   if (!CurContext->isDependentContext()) {
5781     // Finalize the clauses that need pre-built expressions for CodeGen.
5782     for (OMPClause *C : Clauses) {
5783       if (auto *LC = dyn_cast<OMPLinearClause>(C))
5784         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
5785                                      B.NumIterations, *this, CurScope,
5786                                      DSAStack))
5787           return StmtError();
5788     }
5789   }
5790 
5791   if (checkSimdlenSafelenSpecified(*this, Clauses))
5792     return StmtError();
5793 
5794   setFunctionHasBranchProtectedScope();
5795   return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
5796                                      Clauses, AStmt, B);
5797 }
5798 
5799 StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
5800                                               Stmt *AStmt,
5801                                               SourceLocation StartLoc,
5802                                               SourceLocation EndLoc) {
5803   if (!AStmt)
5804     return StmtError();
5805 
5806   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5807   auto BaseStmt = AStmt;
5808   while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
5809     BaseStmt = CS->getCapturedStmt();
5810   if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
5811     auto S = C->children();
5812     if (S.begin() == S.end())
5813       return StmtError();
5814     // All associated statements must be '#pragma omp section' except for
5815     // the first one.
5816     for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
5817       if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
5818         if (SectionStmt)
5819           Diag(SectionStmt->getBeginLoc(),
5820                diag::err_omp_sections_substmt_not_section);
5821         return StmtError();
5822       }
5823       cast<OMPSectionDirective>(SectionStmt)
5824           ->setHasCancel(DSAStack->isCancelRegion());
5825     }
5826   } else {
5827     Diag(AStmt->getBeginLoc(), diag::err_omp_sections_not_compound_stmt);
5828     return StmtError();
5829   }
5830 
5831   setFunctionHasBranchProtectedScope();
5832 
5833   return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
5834                                       DSAStack->isCancelRegion());
5835 }
5836 
5837 StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
5838                                              SourceLocation StartLoc,
5839                                              SourceLocation EndLoc) {
5840   if (!AStmt)
5841     return StmtError();
5842 
5843   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5844 
5845   setFunctionHasBranchProtectedScope();
5846   DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
5847 
5848   return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
5849                                      DSAStack->isCancelRegion());
5850 }
5851 
5852 StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
5853                                             Stmt *AStmt,
5854                                             SourceLocation StartLoc,
5855                                             SourceLocation EndLoc) {
5856   if (!AStmt)
5857     return StmtError();
5858 
5859   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5860 
5861   setFunctionHasBranchProtectedScope();
5862 
5863   // OpenMP [2.7.3, single Construct, Restrictions]
5864   // The copyprivate clause must not be used with the nowait clause.
5865   const OMPClause *Nowait = nullptr;
5866   const OMPClause *Copyprivate = nullptr;
5867   for (const OMPClause *Clause : Clauses) {
5868     if (Clause->getClauseKind() == OMPC_nowait)
5869       Nowait = Clause;
5870     else if (Clause->getClauseKind() == OMPC_copyprivate)
5871       Copyprivate = Clause;
5872     if (Copyprivate && Nowait) {
5873       Diag(Copyprivate->getBeginLoc(),
5874            diag::err_omp_single_copyprivate_with_nowait);
5875       Diag(Nowait->getBeginLoc(), diag::note_omp_nowait_clause_here);
5876       return StmtError();
5877     }
5878   }
5879 
5880   return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
5881 }
5882 
5883 StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
5884                                             SourceLocation StartLoc,
5885                                             SourceLocation EndLoc) {
5886   if (!AStmt)
5887     return StmtError();
5888 
5889   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5890 
5891   setFunctionHasBranchProtectedScope();
5892 
5893   return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
5894 }
5895 
5896 StmtResult Sema::ActOnOpenMPCriticalDirective(
5897     const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
5898     Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
5899   if (!AStmt)
5900     return StmtError();
5901 
5902   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5903 
5904   bool ErrorFound = false;
5905   llvm::APSInt Hint;
5906   SourceLocation HintLoc;
5907   bool DependentHint = false;
5908   for (const OMPClause *C : Clauses) {
5909     if (C->getClauseKind() == OMPC_hint) {
5910       if (!DirName.getName()) {
5911         Diag(C->getBeginLoc(), diag::err_omp_hint_clause_no_name);
5912         ErrorFound = true;
5913       }
5914       Expr *E = cast<OMPHintClause>(C)->getHint();
5915       if (E->isTypeDependent() || E->isValueDependent() ||
5916           E->isInstantiationDependent()) {
5917         DependentHint = true;
5918       } else {
5919         Hint = E->EvaluateKnownConstInt(Context);
5920         HintLoc = C->getBeginLoc();
5921       }
5922     }
5923   }
5924   if (ErrorFound)
5925     return StmtError();
5926   const auto Pair = DSAStack->getCriticalWithHint(DirName);
5927   if (Pair.first && DirName.getName() && !DependentHint) {
5928     if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
5929       Diag(StartLoc, diag::err_omp_critical_with_hint);
5930       if (HintLoc.isValid())
5931         Diag(HintLoc, diag::note_omp_critical_hint_here)
5932             << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
5933       else
5934         Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
5935       if (const auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
5936         Diag(C->getBeginLoc(), diag::note_omp_critical_hint_here)
5937             << 1
5938             << C->getHint()->EvaluateKnownConstInt(Context).toString(
5939                    /*Radix=*/10, /*Signed=*/false);
5940       } else {
5941         Diag(Pair.first->getBeginLoc(), diag::note_omp_critical_no_hint) << 1;
5942       }
5943     }
5944   }
5945 
5946   setFunctionHasBranchProtectedScope();
5947 
5948   auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
5949                                            Clauses, AStmt);
5950   if (!Pair.first && DirName.getName() && !DependentHint)
5951     DSAStack->addCriticalWithHint(Dir, Hint);
5952   return Dir;
5953 }
5954 
5955 StmtResult Sema::ActOnOpenMPParallelForDirective(
5956     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5957     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
5958   if (!AStmt)
5959     return StmtError();
5960 
5961   auto *CS = cast<CapturedStmt>(AStmt);
5962   // 1.2.2 OpenMP Language Terminology
5963   // Structured block - An executable statement with a single entry at the
5964   // top and a single exit at the bottom.
5965   // The point of exit cannot be a branch out of the structured block.
5966   // longjmp() and throw() must not violate the entry/exit criteria.
5967   CS->getCapturedDecl()->setNothrow();
5968 
5969   OMPLoopDirective::HelperExprs B;
5970   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5971   // define the nested loops number.
5972   unsigned NestedLoopCount =
5973       checkOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
5974                       getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5975                       VarsWithImplicitDSA, B);
5976   if (NestedLoopCount == 0)
5977     return StmtError();
5978 
5979   assert((CurContext->isDependentContext() || B.builtAll()) &&
5980          "omp parallel for loop exprs were not built");
5981 
5982   if (!CurContext->isDependentContext()) {
5983     // Finalize the clauses that need pre-built expressions for CodeGen.
5984     for (OMPClause *C : Clauses) {
5985       if (auto *LC = dyn_cast<OMPLinearClause>(C))
5986         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
5987                                      B.NumIterations, *this, CurScope,
5988                                      DSAStack))
5989           return StmtError();
5990     }
5991   }
5992 
5993   setFunctionHasBranchProtectedScope();
5994   return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
5995                                          NestedLoopCount, Clauses, AStmt, B,
5996                                          DSAStack->isCancelRegion());
5997 }
5998 
5999 StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
6000     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6001     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
6002   if (!AStmt)
6003     return StmtError();
6004 
6005   auto *CS = cast<CapturedStmt>(AStmt);
6006   // 1.2.2 OpenMP Language Terminology
6007   // Structured block - An executable statement with a single entry at the
6008   // top and a single exit at the bottom.
6009   // The point of exit cannot be a branch out of the structured block.
6010   // longjmp() and throw() must not violate the entry/exit criteria.
6011   CS->getCapturedDecl()->setNothrow();
6012 
6013   OMPLoopDirective::HelperExprs B;
6014   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6015   // define the nested loops number.
6016   unsigned NestedLoopCount =
6017       checkOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
6018                       getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6019                       VarsWithImplicitDSA, B);
6020   if (NestedLoopCount == 0)
6021     return StmtError();
6022 
6023   if (!CurContext->isDependentContext()) {
6024     // Finalize the clauses that need pre-built expressions for CodeGen.
6025     for (OMPClause *C : Clauses) {
6026       if (auto *LC = dyn_cast<OMPLinearClause>(C))
6027         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6028                                      B.NumIterations, *this, CurScope,
6029                                      DSAStack))
6030           return StmtError();
6031     }
6032   }
6033 
6034   if (checkSimdlenSafelenSpecified(*this, Clauses))
6035     return StmtError();
6036 
6037   setFunctionHasBranchProtectedScope();
6038   return OMPParallelForSimdDirective::Create(
6039       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6040 }
6041 
6042 StmtResult
6043 Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
6044                                            Stmt *AStmt, SourceLocation StartLoc,
6045                                            SourceLocation EndLoc) {
6046   if (!AStmt)
6047     return StmtError();
6048 
6049   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6050   auto BaseStmt = AStmt;
6051   while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
6052     BaseStmt = CS->getCapturedStmt();
6053   if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
6054     auto S = C->children();
6055     if (S.begin() == S.end())
6056       return StmtError();
6057     // All associated statements must be '#pragma omp section' except for
6058     // the first one.
6059     for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
6060       if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
6061         if (SectionStmt)
6062           Diag(SectionStmt->getBeginLoc(),
6063                diag::err_omp_parallel_sections_substmt_not_section);
6064         return StmtError();
6065       }
6066       cast<OMPSectionDirective>(SectionStmt)
6067           ->setHasCancel(DSAStack->isCancelRegion());
6068     }
6069   } else {
6070     Diag(AStmt->getBeginLoc(),
6071          diag::err_omp_parallel_sections_not_compound_stmt);
6072     return StmtError();
6073   }
6074 
6075   setFunctionHasBranchProtectedScope();
6076 
6077   return OMPParallelSectionsDirective::Create(
6078       Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
6079 }
6080 
6081 StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
6082                                           Stmt *AStmt, SourceLocation StartLoc,
6083                                           SourceLocation EndLoc) {
6084   if (!AStmt)
6085     return StmtError();
6086 
6087   auto *CS = cast<CapturedStmt>(AStmt);
6088   // 1.2.2 OpenMP Language Terminology
6089   // Structured block - An executable statement with a single entry at the
6090   // top and a single exit at the bottom.
6091   // The point of exit cannot be a branch out of the structured block.
6092   // longjmp() and throw() must not violate the entry/exit criteria.
6093   CS->getCapturedDecl()->setNothrow();
6094 
6095   setFunctionHasBranchProtectedScope();
6096 
6097   return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
6098                                   DSAStack->isCancelRegion());
6099 }
6100 
6101 StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
6102                                                SourceLocation EndLoc) {
6103   return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
6104 }
6105 
6106 StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
6107                                              SourceLocation EndLoc) {
6108   return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
6109 }
6110 
6111 StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
6112                                               SourceLocation EndLoc) {
6113   return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
6114 }
6115 
6116 StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
6117                                                Stmt *AStmt,
6118                                                SourceLocation StartLoc,
6119                                                SourceLocation EndLoc) {
6120   if (!AStmt)
6121     return StmtError();
6122 
6123   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6124 
6125   setFunctionHasBranchProtectedScope();
6126 
6127   return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses,
6128                                        AStmt,
6129                                        DSAStack->getTaskgroupReductionRef());
6130 }
6131 
6132 StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
6133                                            SourceLocation StartLoc,
6134                                            SourceLocation EndLoc) {
6135   assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
6136   return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
6137 }
6138 
6139 StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
6140                                              Stmt *AStmt,
6141                                              SourceLocation StartLoc,
6142                                              SourceLocation EndLoc) {
6143   const OMPClause *DependFound = nullptr;
6144   const OMPClause *DependSourceClause = nullptr;
6145   const OMPClause *DependSinkClause = nullptr;
6146   bool ErrorFound = false;
6147   const OMPThreadsClause *TC = nullptr;
6148   const OMPSIMDClause *SC = nullptr;
6149   for (const OMPClause *C : Clauses) {
6150     if (auto *DC = dyn_cast<OMPDependClause>(C)) {
6151       DependFound = C;
6152       if (DC->getDependencyKind() == OMPC_DEPEND_source) {
6153         if (DependSourceClause) {
6154           Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
6155               << getOpenMPDirectiveName(OMPD_ordered)
6156               << getOpenMPClauseName(OMPC_depend) << 2;
6157           ErrorFound = true;
6158         } else {
6159           DependSourceClause = C;
6160         }
6161         if (DependSinkClause) {
6162           Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
6163               << 0;
6164           ErrorFound = true;
6165         }
6166       } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
6167         if (DependSourceClause) {
6168           Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
6169               << 1;
6170           ErrorFound = true;
6171         }
6172         DependSinkClause = C;
6173       }
6174     } else if (C->getClauseKind() == OMPC_threads) {
6175       TC = cast<OMPThreadsClause>(C);
6176     } else if (C->getClauseKind() == OMPC_simd) {
6177       SC = cast<OMPSIMDClause>(C);
6178     }
6179   }
6180   if (!ErrorFound && !SC &&
6181       isOpenMPSimdDirective(DSAStack->getParentDirective())) {
6182     // OpenMP [2.8.1,simd Construct, Restrictions]
6183     // An ordered construct with the simd clause is the only OpenMP construct
6184     // that can appear in the simd region.
6185     Diag(StartLoc, diag::err_omp_prohibited_region_simd);
6186     ErrorFound = true;
6187   } else if (DependFound && (TC || SC)) {
6188     Diag(DependFound->getBeginLoc(), diag::err_omp_depend_clause_thread_simd)
6189         << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
6190     ErrorFound = true;
6191   } else if (DependFound && !DSAStack->getParentOrderedRegionParam().first) {
6192     Diag(DependFound->getBeginLoc(),
6193          diag::err_omp_ordered_directive_without_param);
6194     ErrorFound = true;
6195   } else if (TC || Clauses.empty()) {
6196     if (const Expr *Param = DSAStack->getParentOrderedRegionParam().first) {
6197       SourceLocation ErrLoc = TC ? TC->getBeginLoc() : StartLoc;
6198       Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
6199           << (TC != nullptr);
6200       Diag(Param->getBeginLoc(), diag::note_omp_ordered_param);
6201       ErrorFound = true;
6202     }
6203   }
6204   if ((!AStmt && !DependFound) || ErrorFound)
6205     return StmtError();
6206 
6207   if (AStmt) {
6208     assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6209 
6210     setFunctionHasBranchProtectedScope();
6211   }
6212 
6213   return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
6214 }
6215 
6216 namespace {
6217 /// Helper class for checking expression in 'omp atomic [update]'
6218 /// construct.
6219 class OpenMPAtomicUpdateChecker {
6220   /// Error results for atomic update expressions.
6221   enum ExprAnalysisErrorCode {
6222     /// A statement is not an expression statement.
6223     NotAnExpression,
6224     /// Expression is not builtin binary or unary operation.
6225     NotABinaryOrUnaryExpression,
6226     /// Unary operation is not post-/pre- increment/decrement operation.
6227     NotAnUnaryIncDecExpression,
6228     /// An expression is not of scalar type.
6229     NotAScalarType,
6230     /// A binary operation is not an assignment operation.
6231     NotAnAssignmentOp,
6232     /// RHS part of the binary operation is not a binary expression.
6233     NotABinaryExpression,
6234     /// RHS part is not additive/multiplicative/shift/biwise binary
6235     /// expression.
6236     NotABinaryOperator,
6237     /// RHS binary operation does not have reference to the updated LHS
6238     /// part.
6239     NotAnUpdateExpression,
6240     /// No errors is found.
6241     NoError
6242   };
6243   /// Reference to Sema.
6244   Sema &SemaRef;
6245   /// A location for note diagnostics (when error is found).
6246   SourceLocation NoteLoc;
6247   /// 'x' lvalue part of the source atomic expression.
6248   Expr *X;
6249   /// 'expr' rvalue part of the source atomic expression.
6250   Expr *E;
6251   /// Helper expression of the form
6252   /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
6253   /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
6254   Expr *UpdateExpr;
6255   /// Is 'x' a LHS in a RHS part of full update expression. It is
6256   /// important for non-associative operations.
6257   bool IsXLHSInRHSPart;
6258   BinaryOperatorKind Op;
6259   SourceLocation OpLoc;
6260   /// true if the source expression is a postfix unary operation, false
6261   /// if it is a prefix unary operation.
6262   bool IsPostfixUpdate;
6263 
6264 public:
6265   OpenMPAtomicUpdateChecker(Sema &SemaRef)
6266       : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
6267         IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
6268   /// Check specified statement that it is suitable for 'atomic update'
6269   /// constructs and extract 'x', 'expr' and Operation from the original
6270   /// expression. If DiagId and NoteId == 0, then only check is performed
6271   /// without error notification.
6272   /// \param DiagId Diagnostic which should be emitted if error is found.
6273   /// \param NoteId Diagnostic note for the main error message.
6274   /// \return true if statement is not an update expression, false otherwise.
6275   bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
6276   /// Return the 'x' lvalue part of the source atomic expression.
6277   Expr *getX() const { return X; }
6278   /// Return the 'expr' rvalue part of the source atomic expression.
6279   Expr *getExpr() const { return E; }
6280   /// Return the update expression used in calculation of the updated
6281   /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
6282   /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
6283   Expr *getUpdateExpr() const { return UpdateExpr; }
6284   /// Return true if 'x' is LHS in RHS part of full update expression,
6285   /// false otherwise.
6286   bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
6287 
6288   /// true if the source expression is a postfix unary operation, false
6289   /// if it is a prefix unary operation.
6290   bool isPostfixUpdate() const { return IsPostfixUpdate; }
6291 
6292 private:
6293   bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
6294                             unsigned NoteId = 0);
6295 };
6296 } // namespace
6297 
6298 bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
6299     BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
6300   ExprAnalysisErrorCode ErrorFound = NoError;
6301   SourceLocation ErrorLoc, NoteLoc;
6302   SourceRange ErrorRange, NoteRange;
6303   // Allowed constructs are:
6304   //  x = x binop expr;
6305   //  x = expr binop x;
6306   if (AtomicBinOp->getOpcode() == BO_Assign) {
6307     X = AtomicBinOp->getLHS();
6308     if (const auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
6309             AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
6310       if (AtomicInnerBinOp->isMultiplicativeOp() ||
6311           AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
6312           AtomicInnerBinOp->isBitwiseOp()) {
6313         Op = AtomicInnerBinOp->getOpcode();
6314         OpLoc = AtomicInnerBinOp->getOperatorLoc();
6315         Expr *LHS = AtomicInnerBinOp->getLHS();
6316         Expr *RHS = AtomicInnerBinOp->getRHS();
6317         llvm::FoldingSetNodeID XId, LHSId, RHSId;
6318         X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
6319                                           /*Canonical=*/true);
6320         LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
6321                                             /*Canonical=*/true);
6322         RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
6323                                             /*Canonical=*/true);
6324         if (XId == LHSId) {
6325           E = RHS;
6326           IsXLHSInRHSPart = true;
6327         } else if (XId == RHSId) {
6328           E = LHS;
6329           IsXLHSInRHSPart = false;
6330         } else {
6331           ErrorLoc = AtomicInnerBinOp->getExprLoc();
6332           ErrorRange = AtomicInnerBinOp->getSourceRange();
6333           NoteLoc = X->getExprLoc();
6334           NoteRange = X->getSourceRange();
6335           ErrorFound = NotAnUpdateExpression;
6336         }
6337       } else {
6338         ErrorLoc = AtomicInnerBinOp->getExprLoc();
6339         ErrorRange = AtomicInnerBinOp->getSourceRange();
6340         NoteLoc = AtomicInnerBinOp->getOperatorLoc();
6341         NoteRange = SourceRange(NoteLoc, NoteLoc);
6342         ErrorFound = NotABinaryOperator;
6343       }
6344     } else {
6345       NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
6346       NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
6347       ErrorFound = NotABinaryExpression;
6348     }
6349   } else {
6350     ErrorLoc = AtomicBinOp->getExprLoc();
6351     ErrorRange = AtomicBinOp->getSourceRange();
6352     NoteLoc = AtomicBinOp->getOperatorLoc();
6353     NoteRange = SourceRange(NoteLoc, NoteLoc);
6354     ErrorFound = NotAnAssignmentOp;
6355   }
6356   if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
6357     SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
6358     SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
6359     return true;
6360   }
6361   if (SemaRef.CurContext->isDependentContext())
6362     E = X = UpdateExpr = nullptr;
6363   return ErrorFound != NoError;
6364 }
6365 
6366 bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
6367                                                unsigned NoteId) {
6368   ExprAnalysisErrorCode ErrorFound = NoError;
6369   SourceLocation ErrorLoc, NoteLoc;
6370   SourceRange ErrorRange, NoteRange;
6371   // Allowed constructs are:
6372   //  x++;
6373   //  x--;
6374   //  ++x;
6375   //  --x;
6376   //  x binop= expr;
6377   //  x = x binop expr;
6378   //  x = expr binop x;
6379   if (auto *AtomicBody = dyn_cast<Expr>(S)) {
6380     AtomicBody = AtomicBody->IgnoreParenImpCasts();
6381     if (AtomicBody->getType()->isScalarType() ||
6382         AtomicBody->isInstantiationDependent()) {
6383       if (const auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
6384               AtomicBody->IgnoreParenImpCasts())) {
6385         // Check for Compound Assignment Operation
6386         Op = BinaryOperator::getOpForCompoundAssignment(
6387             AtomicCompAssignOp->getOpcode());
6388         OpLoc = AtomicCompAssignOp->getOperatorLoc();
6389         E = AtomicCompAssignOp->getRHS();
6390         X = AtomicCompAssignOp->getLHS()->IgnoreParens();
6391         IsXLHSInRHSPart = true;
6392       } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
6393                      AtomicBody->IgnoreParenImpCasts())) {
6394         // Check for Binary Operation
6395         if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
6396           return true;
6397       } else if (const auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
6398                      AtomicBody->IgnoreParenImpCasts())) {
6399         // Check for Unary Operation
6400         if (AtomicUnaryOp->isIncrementDecrementOp()) {
6401           IsPostfixUpdate = AtomicUnaryOp->isPostfix();
6402           Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
6403           OpLoc = AtomicUnaryOp->getOperatorLoc();
6404           X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
6405           E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
6406           IsXLHSInRHSPart = true;
6407         } else {
6408           ErrorFound = NotAnUnaryIncDecExpression;
6409           ErrorLoc = AtomicUnaryOp->getExprLoc();
6410           ErrorRange = AtomicUnaryOp->getSourceRange();
6411           NoteLoc = AtomicUnaryOp->getOperatorLoc();
6412           NoteRange = SourceRange(NoteLoc, NoteLoc);
6413         }
6414       } else if (!AtomicBody->isInstantiationDependent()) {
6415         ErrorFound = NotABinaryOrUnaryExpression;
6416         NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
6417         NoteRange = ErrorRange = AtomicBody->getSourceRange();
6418       }
6419     } else {
6420       ErrorFound = NotAScalarType;
6421       NoteLoc = ErrorLoc = AtomicBody->getBeginLoc();
6422       NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
6423     }
6424   } else {
6425     ErrorFound = NotAnExpression;
6426     NoteLoc = ErrorLoc = S->getBeginLoc();
6427     NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
6428   }
6429   if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
6430     SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
6431     SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
6432     return true;
6433   }
6434   if (SemaRef.CurContext->isDependentContext())
6435     E = X = UpdateExpr = nullptr;
6436   if (ErrorFound == NoError && E && X) {
6437     // Build an update expression of form 'OpaqueValueExpr(x) binop
6438     // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
6439     // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
6440     auto *OVEX = new (SemaRef.getASTContext())
6441         OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
6442     auto *OVEExpr = new (SemaRef.getASTContext())
6443         OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
6444     ExprResult Update =
6445         SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
6446                                    IsXLHSInRHSPart ? OVEExpr : OVEX);
6447     if (Update.isInvalid())
6448       return true;
6449     Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
6450                                                Sema::AA_Casting);
6451     if (Update.isInvalid())
6452       return true;
6453     UpdateExpr = Update.get();
6454   }
6455   return ErrorFound != NoError;
6456 }
6457 
6458 StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
6459                                             Stmt *AStmt,
6460                                             SourceLocation StartLoc,
6461                                             SourceLocation EndLoc) {
6462   if (!AStmt)
6463     return StmtError();
6464 
6465   auto *CS = cast<CapturedStmt>(AStmt);
6466   // 1.2.2 OpenMP Language Terminology
6467   // Structured block - An executable statement with a single entry at the
6468   // top and a single exit at the bottom.
6469   // The point of exit cannot be a branch out of the structured block.
6470   // longjmp() and throw() must not violate the entry/exit criteria.
6471   OpenMPClauseKind AtomicKind = OMPC_unknown;
6472   SourceLocation AtomicKindLoc;
6473   for (const OMPClause *C : Clauses) {
6474     if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
6475         C->getClauseKind() == OMPC_update ||
6476         C->getClauseKind() == OMPC_capture) {
6477       if (AtomicKind != OMPC_unknown) {
6478         Diag(C->getBeginLoc(), diag::err_omp_atomic_several_clauses)
6479             << SourceRange(C->getBeginLoc(), C->getEndLoc());
6480         Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
6481             << getOpenMPClauseName(AtomicKind);
6482       } else {
6483         AtomicKind = C->getClauseKind();
6484         AtomicKindLoc = C->getBeginLoc();
6485       }
6486     }
6487   }
6488 
6489   Stmt *Body = CS->getCapturedStmt();
6490   if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
6491     Body = EWC->getSubExpr();
6492 
6493   Expr *X = nullptr;
6494   Expr *V = nullptr;
6495   Expr *E = nullptr;
6496   Expr *UE = nullptr;
6497   bool IsXLHSInRHSPart = false;
6498   bool IsPostfixUpdate = false;
6499   // OpenMP [2.12.6, atomic Construct]
6500   // In the next expressions:
6501   // * x and v (as applicable) are both l-value expressions with scalar type.
6502   // * During the execution of an atomic region, multiple syntactic
6503   // occurrences of x must designate the same storage location.
6504   // * Neither of v and expr (as applicable) may access the storage location
6505   // designated by x.
6506   // * Neither of x and expr (as applicable) may access the storage location
6507   // designated by v.
6508   // * expr is an expression with scalar type.
6509   // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
6510   // * binop, binop=, ++, and -- are not overloaded operators.
6511   // * The expression x binop expr must be numerically equivalent to x binop
6512   // (expr). This requirement is satisfied if the operators in expr have
6513   // precedence greater than binop, or by using parentheses around expr or
6514   // subexpressions of expr.
6515   // * The expression expr binop x must be numerically equivalent to (expr)
6516   // binop x. This requirement is satisfied if the operators in expr have
6517   // precedence equal to or greater than binop, or by using parentheses around
6518   // expr or subexpressions of expr.
6519   // * For forms that allow multiple occurrences of x, the number of times
6520   // that x is evaluated is unspecified.
6521   if (AtomicKind == OMPC_read) {
6522     enum {
6523       NotAnExpression,
6524       NotAnAssignmentOp,
6525       NotAScalarType,
6526       NotAnLValue,
6527       NoError
6528     } ErrorFound = NoError;
6529     SourceLocation ErrorLoc, NoteLoc;
6530     SourceRange ErrorRange, NoteRange;
6531     // If clause is read:
6532     //  v = x;
6533     if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
6534       const auto *AtomicBinOp =
6535           dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
6536       if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
6537         X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
6538         V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
6539         if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
6540             (V->isInstantiationDependent() || V->getType()->isScalarType())) {
6541           if (!X->isLValue() || !V->isLValue()) {
6542             const Expr *NotLValueExpr = X->isLValue() ? V : X;
6543             ErrorFound = NotAnLValue;
6544             ErrorLoc = AtomicBinOp->getExprLoc();
6545             ErrorRange = AtomicBinOp->getSourceRange();
6546             NoteLoc = NotLValueExpr->getExprLoc();
6547             NoteRange = NotLValueExpr->getSourceRange();
6548           }
6549         } else if (!X->isInstantiationDependent() ||
6550                    !V->isInstantiationDependent()) {
6551           const Expr *NotScalarExpr =
6552               (X->isInstantiationDependent() || X->getType()->isScalarType())
6553                   ? V
6554                   : X;
6555           ErrorFound = NotAScalarType;
6556           ErrorLoc = AtomicBinOp->getExprLoc();
6557           ErrorRange = AtomicBinOp->getSourceRange();
6558           NoteLoc = NotScalarExpr->getExprLoc();
6559           NoteRange = NotScalarExpr->getSourceRange();
6560         }
6561       } else if (!AtomicBody->isInstantiationDependent()) {
6562         ErrorFound = NotAnAssignmentOp;
6563         ErrorLoc = AtomicBody->getExprLoc();
6564         ErrorRange = AtomicBody->getSourceRange();
6565         NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
6566                               : AtomicBody->getExprLoc();
6567         NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
6568                                 : AtomicBody->getSourceRange();
6569       }
6570     } else {
6571       ErrorFound = NotAnExpression;
6572       NoteLoc = ErrorLoc = Body->getBeginLoc();
6573       NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
6574     }
6575     if (ErrorFound != NoError) {
6576       Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
6577           << ErrorRange;
6578       Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
6579                                                       << NoteRange;
6580       return StmtError();
6581     }
6582     if (CurContext->isDependentContext())
6583       V = X = nullptr;
6584   } else if (AtomicKind == OMPC_write) {
6585     enum {
6586       NotAnExpression,
6587       NotAnAssignmentOp,
6588       NotAScalarType,
6589       NotAnLValue,
6590       NoError
6591     } ErrorFound = NoError;
6592     SourceLocation ErrorLoc, NoteLoc;
6593     SourceRange ErrorRange, NoteRange;
6594     // If clause is write:
6595     //  x = expr;
6596     if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
6597       const auto *AtomicBinOp =
6598           dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
6599       if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
6600         X = AtomicBinOp->getLHS();
6601         E = AtomicBinOp->getRHS();
6602         if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
6603             (E->isInstantiationDependent() || E->getType()->isScalarType())) {
6604           if (!X->isLValue()) {
6605             ErrorFound = NotAnLValue;
6606             ErrorLoc = AtomicBinOp->getExprLoc();
6607             ErrorRange = AtomicBinOp->getSourceRange();
6608             NoteLoc = X->getExprLoc();
6609             NoteRange = X->getSourceRange();
6610           }
6611         } else if (!X->isInstantiationDependent() ||
6612                    !E->isInstantiationDependent()) {
6613           const Expr *NotScalarExpr =
6614               (X->isInstantiationDependent() || X->getType()->isScalarType())
6615                   ? E
6616                   : X;
6617           ErrorFound = NotAScalarType;
6618           ErrorLoc = AtomicBinOp->getExprLoc();
6619           ErrorRange = AtomicBinOp->getSourceRange();
6620           NoteLoc = NotScalarExpr->getExprLoc();
6621           NoteRange = NotScalarExpr->getSourceRange();
6622         }
6623       } else if (!AtomicBody->isInstantiationDependent()) {
6624         ErrorFound = NotAnAssignmentOp;
6625         ErrorLoc = AtomicBody->getExprLoc();
6626         ErrorRange = AtomicBody->getSourceRange();
6627         NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
6628                               : AtomicBody->getExprLoc();
6629         NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
6630                                 : AtomicBody->getSourceRange();
6631       }
6632     } else {
6633       ErrorFound = NotAnExpression;
6634       NoteLoc = ErrorLoc = Body->getBeginLoc();
6635       NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
6636     }
6637     if (ErrorFound != NoError) {
6638       Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
6639           << ErrorRange;
6640       Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
6641                                                       << NoteRange;
6642       return StmtError();
6643     }
6644     if (CurContext->isDependentContext())
6645       E = X = nullptr;
6646   } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
6647     // If clause is update:
6648     //  x++;
6649     //  x--;
6650     //  ++x;
6651     //  --x;
6652     //  x binop= expr;
6653     //  x = x binop expr;
6654     //  x = expr binop x;
6655     OpenMPAtomicUpdateChecker Checker(*this);
6656     if (Checker.checkStatement(
6657             Body, (AtomicKind == OMPC_update)
6658                       ? diag::err_omp_atomic_update_not_expression_statement
6659                       : diag::err_omp_atomic_not_expression_statement,
6660             diag::note_omp_atomic_update))
6661       return StmtError();
6662     if (!CurContext->isDependentContext()) {
6663       E = Checker.getExpr();
6664       X = Checker.getX();
6665       UE = Checker.getUpdateExpr();
6666       IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
6667     }
6668   } else if (AtomicKind == OMPC_capture) {
6669     enum {
6670       NotAnAssignmentOp,
6671       NotACompoundStatement,
6672       NotTwoSubstatements,
6673       NotASpecificExpression,
6674       NoError
6675     } ErrorFound = NoError;
6676     SourceLocation ErrorLoc, NoteLoc;
6677     SourceRange ErrorRange, NoteRange;
6678     if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
6679       // If clause is a capture:
6680       //  v = x++;
6681       //  v = x--;
6682       //  v = ++x;
6683       //  v = --x;
6684       //  v = x binop= expr;
6685       //  v = x = x binop expr;
6686       //  v = x = expr binop x;
6687       const auto *AtomicBinOp =
6688           dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
6689       if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
6690         V = AtomicBinOp->getLHS();
6691         Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
6692         OpenMPAtomicUpdateChecker Checker(*this);
6693         if (Checker.checkStatement(
6694                 Body, diag::err_omp_atomic_capture_not_expression_statement,
6695                 diag::note_omp_atomic_update))
6696           return StmtError();
6697         E = Checker.getExpr();
6698         X = Checker.getX();
6699         UE = Checker.getUpdateExpr();
6700         IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
6701         IsPostfixUpdate = Checker.isPostfixUpdate();
6702       } else if (!AtomicBody->isInstantiationDependent()) {
6703         ErrorLoc = AtomicBody->getExprLoc();
6704         ErrorRange = AtomicBody->getSourceRange();
6705         NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
6706                               : AtomicBody->getExprLoc();
6707         NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
6708                                 : AtomicBody->getSourceRange();
6709         ErrorFound = NotAnAssignmentOp;
6710       }
6711       if (ErrorFound != NoError) {
6712         Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
6713             << ErrorRange;
6714         Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
6715         return StmtError();
6716       }
6717       if (CurContext->isDependentContext())
6718         UE = V = E = X = nullptr;
6719     } else {
6720       // If clause is a capture:
6721       //  { v = x; x = expr; }
6722       //  { v = x; x++; }
6723       //  { v = x; x--; }
6724       //  { v = x; ++x; }
6725       //  { v = x; --x; }
6726       //  { v = x; x binop= expr; }
6727       //  { v = x; x = x binop expr; }
6728       //  { v = x; x = expr binop x; }
6729       //  { x++; v = x; }
6730       //  { x--; v = x; }
6731       //  { ++x; v = x; }
6732       //  { --x; v = x; }
6733       //  { x binop= expr; v = x; }
6734       //  { x = x binop expr; v = x; }
6735       //  { x = expr binop x; v = x; }
6736       if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
6737         // Check that this is { expr1; expr2; }
6738         if (CS->size() == 2) {
6739           Stmt *First = CS->body_front();
6740           Stmt *Second = CS->body_back();
6741           if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
6742             First = EWC->getSubExpr()->IgnoreParenImpCasts();
6743           if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
6744             Second = EWC->getSubExpr()->IgnoreParenImpCasts();
6745           // Need to find what subexpression is 'v' and what is 'x'.
6746           OpenMPAtomicUpdateChecker Checker(*this);
6747           bool IsUpdateExprFound = !Checker.checkStatement(Second);
6748           BinaryOperator *BinOp = nullptr;
6749           if (IsUpdateExprFound) {
6750             BinOp = dyn_cast<BinaryOperator>(First);
6751             IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
6752           }
6753           if (IsUpdateExprFound && !CurContext->isDependentContext()) {
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             // Check that the first expression has form v = x.
6762             Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
6763             llvm::FoldingSetNodeID XId, PossibleXId;
6764             Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
6765             PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
6766             IsUpdateExprFound = XId == PossibleXId;
6767             if (IsUpdateExprFound) {
6768               V = BinOp->getLHS();
6769               X = Checker.getX();
6770               E = Checker.getExpr();
6771               UE = Checker.getUpdateExpr();
6772               IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
6773               IsPostfixUpdate = true;
6774             }
6775           }
6776           if (!IsUpdateExprFound) {
6777             IsUpdateExprFound = !Checker.checkStatement(First);
6778             BinOp = nullptr;
6779             if (IsUpdateExprFound) {
6780               BinOp = dyn_cast<BinaryOperator>(Second);
6781               IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
6782             }
6783             if (IsUpdateExprFound && !CurContext->isDependentContext()) {
6784               //  { x++; v = x; }
6785               //  { x--; v = x; }
6786               //  { ++x; v = x; }
6787               //  { --x; v = x; }
6788               //  { x binop= expr; v = x; }
6789               //  { x = x binop expr; v = x; }
6790               //  { x = expr binop x; v = x; }
6791               // Check that the second expression has form v = x.
6792               Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
6793               llvm::FoldingSetNodeID XId, PossibleXId;
6794               Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
6795               PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
6796               IsUpdateExprFound = XId == PossibleXId;
6797               if (IsUpdateExprFound) {
6798                 V = BinOp->getLHS();
6799                 X = Checker.getX();
6800                 E = Checker.getExpr();
6801                 UE = Checker.getUpdateExpr();
6802                 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
6803                 IsPostfixUpdate = false;
6804               }
6805             }
6806           }
6807           if (!IsUpdateExprFound) {
6808             //  { v = x; x = expr; }
6809             auto *FirstExpr = dyn_cast<Expr>(First);
6810             auto *SecondExpr = dyn_cast<Expr>(Second);
6811             if (!FirstExpr || !SecondExpr ||
6812                 !(FirstExpr->isInstantiationDependent() ||
6813                   SecondExpr->isInstantiationDependent())) {
6814               auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
6815               if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
6816                 ErrorFound = NotAnAssignmentOp;
6817                 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
6818                                                 : First->getBeginLoc();
6819                 NoteRange = ErrorRange = FirstBinOp
6820                                              ? FirstBinOp->getSourceRange()
6821                                              : SourceRange(ErrorLoc, ErrorLoc);
6822               } else {
6823                 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
6824                 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
6825                   ErrorFound = NotAnAssignmentOp;
6826                   NoteLoc = ErrorLoc = SecondBinOp
6827                                            ? SecondBinOp->getOperatorLoc()
6828                                            : Second->getBeginLoc();
6829                   NoteRange = ErrorRange =
6830                       SecondBinOp ? SecondBinOp->getSourceRange()
6831                                   : SourceRange(ErrorLoc, ErrorLoc);
6832                 } else {
6833                   Expr *PossibleXRHSInFirst =
6834                       FirstBinOp->getRHS()->IgnoreParenImpCasts();
6835                   Expr *PossibleXLHSInSecond =
6836                       SecondBinOp->getLHS()->IgnoreParenImpCasts();
6837                   llvm::FoldingSetNodeID X1Id, X2Id;
6838                   PossibleXRHSInFirst->Profile(X1Id, Context,
6839                                                /*Canonical=*/true);
6840                   PossibleXLHSInSecond->Profile(X2Id, Context,
6841                                                 /*Canonical=*/true);
6842                   IsUpdateExprFound = X1Id == X2Id;
6843                   if (IsUpdateExprFound) {
6844                     V = FirstBinOp->getLHS();
6845                     X = SecondBinOp->getLHS();
6846                     E = SecondBinOp->getRHS();
6847                     UE = nullptr;
6848                     IsXLHSInRHSPart = false;
6849                     IsPostfixUpdate = true;
6850                   } else {
6851                     ErrorFound = NotASpecificExpression;
6852                     ErrorLoc = FirstBinOp->getExprLoc();
6853                     ErrorRange = FirstBinOp->getSourceRange();
6854                     NoteLoc = SecondBinOp->getLHS()->getExprLoc();
6855                     NoteRange = SecondBinOp->getRHS()->getSourceRange();
6856                   }
6857                 }
6858               }
6859             }
6860           }
6861         } else {
6862           NoteLoc = ErrorLoc = Body->getBeginLoc();
6863           NoteRange = ErrorRange =
6864               SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
6865           ErrorFound = NotTwoSubstatements;
6866         }
6867       } else {
6868         NoteLoc = ErrorLoc = Body->getBeginLoc();
6869         NoteRange = ErrorRange =
6870             SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
6871         ErrorFound = NotACompoundStatement;
6872       }
6873       if (ErrorFound != NoError) {
6874         Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
6875             << ErrorRange;
6876         Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
6877         return StmtError();
6878       }
6879       if (CurContext->isDependentContext())
6880         UE = V = E = X = nullptr;
6881     }
6882   }
6883 
6884   setFunctionHasBranchProtectedScope();
6885 
6886   return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
6887                                     X, V, E, UE, IsXLHSInRHSPart,
6888                                     IsPostfixUpdate);
6889 }
6890 
6891 StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
6892                                             Stmt *AStmt,
6893                                             SourceLocation StartLoc,
6894                                             SourceLocation EndLoc) {
6895   if (!AStmt)
6896     return StmtError();
6897 
6898   auto *CS = cast<CapturedStmt>(AStmt);
6899   // 1.2.2 OpenMP Language Terminology
6900   // Structured block - An executable statement with a single entry at the
6901   // top and a single exit at the bottom.
6902   // The point of exit cannot be a branch out of the structured block.
6903   // longjmp() and throw() must not violate the entry/exit criteria.
6904   CS->getCapturedDecl()->setNothrow();
6905   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target);
6906        ThisCaptureLevel > 1; --ThisCaptureLevel) {
6907     CS = cast<CapturedStmt>(CS->getCapturedStmt());
6908     // 1.2.2 OpenMP Language Terminology
6909     // Structured block - An executable statement with a single entry at the
6910     // top and a single exit at the bottom.
6911     // The point of exit cannot be a branch out of the structured block.
6912     // longjmp() and throw() must not violate the entry/exit criteria.
6913     CS->getCapturedDecl()->setNothrow();
6914   }
6915 
6916   // OpenMP [2.16, Nesting of Regions]
6917   // If specified, a teams construct must be contained within a target
6918   // construct. That target construct must contain no statements or directives
6919   // outside of the teams construct.
6920   if (DSAStack->hasInnerTeamsRegion()) {
6921     const Stmt *S = CS->IgnoreContainers(/*IgnoreCaptured=*/true);
6922     bool OMPTeamsFound = true;
6923     if (const auto *CS = dyn_cast<CompoundStmt>(S)) {
6924       auto I = CS->body_begin();
6925       while (I != CS->body_end()) {
6926         const auto *OED = dyn_cast<OMPExecutableDirective>(*I);
6927         if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) {
6928           OMPTeamsFound = false;
6929           break;
6930         }
6931         ++I;
6932       }
6933       assert(I != CS->body_end() && "Not found statement");
6934       S = *I;
6935     } else {
6936       const auto *OED = dyn_cast<OMPExecutableDirective>(S);
6937       OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
6938     }
6939     if (!OMPTeamsFound) {
6940       Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
6941       Diag(DSAStack->getInnerTeamsRegionLoc(),
6942            diag::note_omp_nested_teams_construct_here);
6943       Diag(S->getBeginLoc(), diag::note_omp_nested_statement_here)
6944           << isa<OMPExecutableDirective>(S);
6945       return StmtError();
6946     }
6947   }
6948 
6949   setFunctionHasBranchProtectedScope();
6950 
6951   return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
6952 }
6953 
6954 StmtResult
6955 Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
6956                                          Stmt *AStmt, SourceLocation StartLoc,
6957                                          SourceLocation EndLoc) {
6958   if (!AStmt)
6959     return StmtError();
6960 
6961   auto *CS = cast<CapturedStmt>(AStmt);
6962   // 1.2.2 OpenMP Language Terminology
6963   // Structured block - An executable statement with a single entry at the
6964   // top and a single exit at the bottom.
6965   // The point of exit cannot be a branch out of the structured block.
6966   // longjmp() and throw() must not violate the entry/exit criteria.
6967   CS->getCapturedDecl()->setNothrow();
6968   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel);
6969        ThisCaptureLevel > 1; --ThisCaptureLevel) {
6970     CS = cast<CapturedStmt>(CS->getCapturedStmt());
6971     // 1.2.2 OpenMP Language Terminology
6972     // Structured block - An executable statement with a single entry at the
6973     // top and a single exit at the bottom.
6974     // The point of exit cannot be a branch out of the structured block.
6975     // longjmp() and throw() must not violate the entry/exit criteria.
6976     CS->getCapturedDecl()->setNothrow();
6977   }
6978 
6979   setFunctionHasBranchProtectedScope();
6980 
6981   return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
6982                                             AStmt);
6983 }
6984 
6985 StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
6986     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6987     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
6988   if (!AStmt)
6989     return StmtError();
6990 
6991   auto *CS = cast<CapturedStmt>(AStmt);
6992   // 1.2.2 OpenMP Language Terminology
6993   // Structured block - An executable statement with a single entry at the
6994   // top and a single exit at the bottom.
6995   // The point of exit cannot be a branch out of the structured block.
6996   // longjmp() and throw() must not violate the entry/exit criteria.
6997   CS->getCapturedDecl()->setNothrow();
6998   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
6999        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7000     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7001     // 1.2.2 OpenMP Language Terminology
7002     // Structured block - An executable statement with a single entry at the
7003     // top and a single exit at the bottom.
7004     // The point of exit cannot be a branch out of the structured block.
7005     // longjmp() and throw() must not violate the entry/exit criteria.
7006     CS->getCapturedDecl()->setNothrow();
7007   }
7008 
7009   OMPLoopDirective::HelperExprs B;
7010   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7011   // define the nested loops number.
7012   unsigned NestedLoopCount =
7013       checkOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
7014                       getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
7015                       VarsWithImplicitDSA, B);
7016   if (NestedLoopCount == 0)
7017     return StmtError();
7018 
7019   assert((CurContext->isDependentContext() || B.builtAll()) &&
7020          "omp target parallel for loop exprs were not built");
7021 
7022   if (!CurContext->isDependentContext()) {
7023     // Finalize the clauses that need pre-built expressions for CodeGen.
7024     for (OMPClause *C : Clauses) {
7025       if (auto *LC = dyn_cast<OMPLinearClause>(C))
7026         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7027                                      B.NumIterations, *this, CurScope,
7028                                      DSAStack))
7029           return StmtError();
7030     }
7031   }
7032 
7033   setFunctionHasBranchProtectedScope();
7034   return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
7035                                                NestedLoopCount, Clauses, AStmt,
7036                                                B, DSAStack->isCancelRegion());
7037 }
7038 
7039 /// Check for existence of a map clause in the list of clauses.
7040 static bool hasClauses(ArrayRef<OMPClause *> Clauses,
7041                        const OpenMPClauseKind K) {
7042   return llvm::any_of(
7043       Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; });
7044 }
7045 
7046 template <typename... Params>
7047 static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K,
7048                        const Params... ClauseTypes) {
7049   return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...);
7050 }
7051 
7052 StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
7053                                                 Stmt *AStmt,
7054                                                 SourceLocation StartLoc,
7055                                                 SourceLocation EndLoc) {
7056   if (!AStmt)
7057     return StmtError();
7058 
7059   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
7060 
7061   // OpenMP [2.10.1, Restrictions, p. 97]
7062   // At least one map clause must appear on the directive.
7063   if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr)) {
7064     Diag(StartLoc, diag::err_omp_no_clause_for_directive)
7065         << "'map' or 'use_device_ptr'"
7066         << getOpenMPDirectiveName(OMPD_target_data);
7067     return StmtError();
7068   }
7069 
7070   setFunctionHasBranchProtectedScope();
7071 
7072   return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
7073                                         AStmt);
7074 }
7075 
7076 StmtResult
7077 Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
7078                                           SourceLocation StartLoc,
7079                                           SourceLocation EndLoc, Stmt *AStmt) {
7080   if (!AStmt)
7081     return StmtError();
7082 
7083   auto *CS = cast<CapturedStmt>(AStmt);
7084   // 1.2.2 OpenMP Language Terminology
7085   // Structured block - An executable statement with a single entry at the
7086   // top and a single exit at the bottom.
7087   // The point of exit cannot be a branch out of the structured block.
7088   // longjmp() and throw() must not violate the entry/exit criteria.
7089   CS->getCapturedDecl()->setNothrow();
7090   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_enter_data);
7091        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7092     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7093     // 1.2.2 OpenMP Language Terminology
7094     // Structured block - An executable statement with a single entry at the
7095     // top and a single exit at the bottom.
7096     // The point of exit cannot be a branch out of the structured block.
7097     // longjmp() and throw() must not violate the entry/exit criteria.
7098     CS->getCapturedDecl()->setNothrow();
7099   }
7100 
7101   // OpenMP [2.10.2, Restrictions, p. 99]
7102   // At least one map clause must appear on the directive.
7103   if (!hasClauses(Clauses, OMPC_map)) {
7104     Diag(StartLoc, diag::err_omp_no_clause_for_directive)
7105         << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data);
7106     return StmtError();
7107   }
7108 
7109   return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
7110                                              AStmt);
7111 }
7112 
7113 StmtResult
7114 Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
7115                                          SourceLocation StartLoc,
7116                                          SourceLocation EndLoc, Stmt *AStmt) {
7117   if (!AStmt)
7118     return StmtError();
7119 
7120   auto *CS = cast<CapturedStmt>(AStmt);
7121   // 1.2.2 OpenMP Language Terminology
7122   // Structured block - An executable statement with a single entry at the
7123   // top and a single exit at the bottom.
7124   // The point of exit cannot be a branch out of the structured block.
7125   // longjmp() and throw() must not violate the entry/exit criteria.
7126   CS->getCapturedDecl()->setNothrow();
7127   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_exit_data);
7128        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7129     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7130     // 1.2.2 OpenMP Language Terminology
7131     // Structured block - An executable statement with a single entry at the
7132     // top and a single exit at the bottom.
7133     // The point of exit cannot be a branch out of the structured block.
7134     // longjmp() and throw() must not violate the entry/exit criteria.
7135     CS->getCapturedDecl()->setNothrow();
7136   }
7137 
7138   // OpenMP [2.10.3, Restrictions, p. 102]
7139   // At least one map clause must appear on the directive.
7140   if (!hasClauses(Clauses, OMPC_map)) {
7141     Diag(StartLoc, diag::err_omp_no_clause_for_directive)
7142         << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data);
7143     return StmtError();
7144   }
7145 
7146   return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
7147                                             AStmt);
7148 }
7149 
7150 StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
7151                                                   SourceLocation StartLoc,
7152                                                   SourceLocation EndLoc,
7153                                                   Stmt *AStmt) {
7154   if (!AStmt)
7155     return StmtError();
7156 
7157   auto *CS = cast<CapturedStmt>(AStmt);
7158   // 1.2.2 OpenMP Language Terminology
7159   // Structured block - An executable statement with a single entry at the
7160   // top and a single exit at the bottom.
7161   // The point of exit cannot be a branch out of the structured block.
7162   // longjmp() and throw() must not violate the entry/exit criteria.
7163   CS->getCapturedDecl()->setNothrow();
7164   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_update);
7165        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7166     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7167     // 1.2.2 OpenMP Language Terminology
7168     // Structured block - An executable statement with a single entry at the
7169     // top and a single exit at the bottom.
7170     // The point of exit cannot be a branch out of the structured block.
7171     // longjmp() and throw() must not violate the entry/exit criteria.
7172     CS->getCapturedDecl()->setNothrow();
7173   }
7174 
7175   if (!hasClauses(Clauses, OMPC_to, OMPC_from)) {
7176     Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
7177     return StmtError();
7178   }
7179   return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses,
7180                                           AStmt);
7181 }
7182 
7183 StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
7184                                            Stmt *AStmt, SourceLocation StartLoc,
7185                                            SourceLocation EndLoc) {
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 
7197   setFunctionHasBranchProtectedScope();
7198 
7199   DSAStack->setParentTeamsRegionLoc(StartLoc);
7200 
7201   return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
7202 }
7203 
7204 StmtResult
7205 Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
7206                                             SourceLocation EndLoc,
7207                                             OpenMPDirectiveKind CancelRegion) {
7208   if (DSAStack->isParentNowaitRegion()) {
7209     Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
7210     return StmtError();
7211   }
7212   if (DSAStack->isParentOrderedRegion()) {
7213     Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
7214     return StmtError();
7215   }
7216   return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
7217                                                CancelRegion);
7218 }
7219 
7220 StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
7221                                             SourceLocation StartLoc,
7222                                             SourceLocation EndLoc,
7223                                             OpenMPDirectiveKind CancelRegion) {
7224   if (DSAStack->isParentNowaitRegion()) {
7225     Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
7226     return StmtError();
7227   }
7228   if (DSAStack->isParentOrderedRegion()) {
7229     Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
7230     return StmtError();
7231   }
7232   DSAStack->setParentCancelRegion(/*Cancel=*/true);
7233   return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
7234                                     CancelRegion);
7235 }
7236 
7237 static bool checkGrainsizeNumTasksClauses(Sema &S,
7238                                           ArrayRef<OMPClause *> Clauses) {
7239   const OMPClause *PrevClause = nullptr;
7240   bool ErrorFound = false;
7241   for (const OMPClause *C : Clauses) {
7242     if (C->getClauseKind() == OMPC_grainsize ||
7243         C->getClauseKind() == OMPC_num_tasks) {
7244       if (!PrevClause)
7245         PrevClause = C;
7246       else if (PrevClause->getClauseKind() != C->getClauseKind()) {
7247         S.Diag(C->getBeginLoc(),
7248                diag::err_omp_grainsize_num_tasks_mutually_exclusive)
7249             << getOpenMPClauseName(C->getClauseKind())
7250             << getOpenMPClauseName(PrevClause->getClauseKind());
7251         S.Diag(PrevClause->getBeginLoc(),
7252                diag::note_omp_previous_grainsize_num_tasks)
7253             << getOpenMPClauseName(PrevClause->getClauseKind());
7254         ErrorFound = true;
7255       }
7256     }
7257   }
7258   return ErrorFound;
7259 }
7260 
7261 static bool checkReductionClauseWithNogroup(Sema &S,
7262                                             ArrayRef<OMPClause *> Clauses) {
7263   const OMPClause *ReductionClause = nullptr;
7264   const OMPClause *NogroupClause = nullptr;
7265   for (const OMPClause *C : Clauses) {
7266     if (C->getClauseKind() == OMPC_reduction) {
7267       ReductionClause = C;
7268       if (NogroupClause)
7269         break;
7270       continue;
7271     }
7272     if (C->getClauseKind() == OMPC_nogroup) {
7273       NogroupClause = C;
7274       if (ReductionClause)
7275         break;
7276       continue;
7277     }
7278   }
7279   if (ReductionClause && NogroupClause) {
7280     S.Diag(ReductionClause->getBeginLoc(), diag::err_omp_reduction_with_nogroup)
7281         << SourceRange(NogroupClause->getBeginLoc(),
7282                        NogroupClause->getEndLoc());
7283     return true;
7284   }
7285   return false;
7286 }
7287 
7288 StmtResult Sema::ActOnOpenMPTaskLoopDirective(
7289     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7290     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
7291   if (!AStmt)
7292     return StmtError();
7293 
7294   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
7295   OMPLoopDirective::HelperExprs B;
7296   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7297   // define the nested loops number.
7298   unsigned NestedLoopCount =
7299       checkOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
7300                       /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
7301                       VarsWithImplicitDSA, B);
7302   if (NestedLoopCount == 0)
7303     return StmtError();
7304 
7305   assert((CurContext->isDependentContext() || B.builtAll()) &&
7306          "omp for loop exprs were not built");
7307 
7308   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
7309   // The grainsize clause and num_tasks clause are mutually exclusive and may
7310   // not appear on the same taskloop directive.
7311   if (checkGrainsizeNumTasksClauses(*this, Clauses))
7312     return StmtError();
7313   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
7314   // If a reduction clause is present on the taskloop directive, the nogroup
7315   // clause must not be specified.
7316   if (checkReductionClauseWithNogroup(*this, Clauses))
7317     return StmtError();
7318 
7319   setFunctionHasBranchProtectedScope();
7320   return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
7321                                       NestedLoopCount, Clauses, AStmt, B);
7322 }
7323 
7324 StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
7325     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7326     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
7327   if (!AStmt)
7328     return StmtError();
7329 
7330   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
7331   OMPLoopDirective::HelperExprs B;
7332   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7333   // define the nested loops number.
7334   unsigned NestedLoopCount =
7335       checkOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
7336                       /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
7337                       VarsWithImplicitDSA, B);
7338   if (NestedLoopCount == 0)
7339     return StmtError();
7340 
7341   assert((CurContext->isDependentContext() || B.builtAll()) &&
7342          "omp for loop exprs were not built");
7343 
7344   if (!CurContext->isDependentContext()) {
7345     // Finalize the clauses that need pre-built expressions for CodeGen.
7346     for (OMPClause *C : Clauses) {
7347       if (auto *LC = dyn_cast<OMPLinearClause>(C))
7348         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7349                                      B.NumIterations, *this, CurScope,
7350                                      DSAStack))
7351           return StmtError();
7352     }
7353   }
7354 
7355   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
7356   // The grainsize clause and num_tasks clause are mutually exclusive and may
7357   // not appear on the same taskloop directive.
7358   if (checkGrainsizeNumTasksClauses(*this, Clauses))
7359     return StmtError();
7360   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
7361   // If a reduction clause is present on the taskloop directive, the nogroup
7362   // clause must not be specified.
7363   if (checkReductionClauseWithNogroup(*this, Clauses))
7364     return StmtError();
7365   if (checkSimdlenSafelenSpecified(*this, Clauses))
7366     return StmtError();
7367 
7368   setFunctionHasBranchProtectedScope();
7369   return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
7370                                           NestedLoopCount, Clauses, AStmt, B);
7371 }
7372 
7373 StmtResult Sema::ActOnOpenMPDistributeDirective(
7374     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7375     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
7376   if (!AStmt)
7377     return StmtError();
7378 
7379   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
7380   OMPLoopDirective::HelperExprs B;
7381   // In presence of clause 'collapse' with number of loops, it will
7382   // define the nested loops number.
7383   unsigned NestedLoopCount =
7384       checkOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
7385                       nullptr /*ordered not a clause on distribute*/, AStmt,
7386                       *this, *DSAStack, VarsWithImplicitDSA, B);
7387   if (NestedLoopCount == 0)
7388     return StmtError();
7389 
7390   assert((CurContext->isDependentContext() || B.builtAll()) &&
7391          "omp for loop exprs were not built");
7392 
7393   setFunctionHasBranchProtectedScope();
7394   return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
7395                                         NestedLoopCount, Clauses, AStmt, B);
7396 }
7397 
7398 StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
7399     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7400     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
7401   if (!AStmt)
7402     return StmtError();
7403 
7404   auto *CS = cast<CapturedStmt>(AStmt);
7405   // 1.2.2 OpenMP Language Terminology
7406   // Structured block - An executable statement with a single entry at the
7407   // top and a single exit at the bottom.
7408   // The point of exit cannot be a branch out of the structured block.
7409   // longjmp() and throw() must not violate the entry/exit criteria.
7410   CS->getCapturedDecl()->setNothrow();
7411   for (int ThisCaptureLevel =
7412            getOpenMPCaptureLevels(OMPD_distribute_parallel_for);
7413        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7414     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7415     // 1.2.2 OpenMP Language Terminology
7416     // Structured block - An executable statement with a single entry at the
7417     // top and a single exit at the bottom.
7418     // The point of exit cannot be a branch out of the structured block.
7419     // longjmp() and throw() must not violate the entry/exit criteria.
7420     CS->getCapturedDecl()->setNothrow();
7421   }
7422 
7423   OMPLoopDirective::HelperExprs B;
7424   // In presence of clause 'collapse' with number of loops, it will
7425   // define the nested loops number.
7426   unsigned NestedLoopCount = checkOpenMPLoop(
7427       OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
7428       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
7429       VarsWithImplicitDSA, B);
7430   if (NestedLoopCount == 0)
7431     return StmtError();
7432 
7433   assert((CurContext->isDependentContext() || B.builtAll()) &&
7434          "omp for loop exprs were not built");
7435 
7436   setFunctionHasBranchProtectedScope();
7437   return OMPDistributeParallelForDirective::Create(
7438       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
7439       DSAStack->isCancelRegion());
7440 }
7441 
7442 StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
7443     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7444     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
7445   if (!AStmt)
7446     return StmtError();
7447 
7448   auto *CS = cast<CapturedStmt>(AStmt);
7449   // 1.2.2 OpenMP Language Terminology
7450   // Structured block - An executable statement with a single entry at the
7451   // top and a single exit at the bottom.
7452   // The point of exit cannot be a branch out of the structured block.
7453   // longjmp() and throw() must not violate the entry/exit criteria.
7454   CS->getCapturedDecl()->setNothrow();
7455   for (int ThisCaptureLevel =
7456            getOpenMPCaptureLevels(OMPD_distribute_parallel_for_simd);
7457        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7458     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7459     // 1.2.2 OpenMP Language Terminology
7460     // Structured block - An executable statement with a single entry at the
7461     // top and a single exit at the bottom.
7462     // The point of exit cannot be a branch out of the structured block.
7463     // longjmp() and throw() must not violate the entry/exit criteria.
7464     CS->getCapturedDecl()->setNothrow();
7465   }
7466 
7467   OMPLoopDirective::HelperExprs B;
7468   // In presence of clause 'collapse' with number of loops, it will
7469   // define the nested loops number.
7470   unsigned NestedLoopCount = checkOpenMPLoop(
7471       OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
7472       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
7473       VarsWithImplicitDSA, B);
7474   if (NestedLoopCount == 0)
7475     return StmtError();
7476 
7477   assert((CurContext->isDependentContext() || B.builtAll()) &&
7478          "omp for loop exprs were not built");
7479 
7480   if (!CurContext->isDependentContext()) {
7481     // Finalize the clauses that need pre-built expressions for CodeGen.
7482     for (OMPClause *C : Clauses) {
7483       if (auto *LC = dyn_cast<OMPLinearClause>(C))
7484         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7485                                      B.NumIterations, *this, CurScope,
7486                                      DSAStack))
7487           return StmtError();
7488     }
7489   }
7490 
7491   if (checkSimdlenSafelenSpecified(*this, Clauses))
7492     return StmtError();
7493 
7494   setFunctionHasBranchProtectedScope();
7495   return OMPDistributeParallelForSimdDirective::Create(
7496       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7497 }
7498 
7499 StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
7500     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7501     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
7502   if (!AStmt)
7503     return StmtError();
7504 
7505   auto *CS = cast<CapturedStmt>(AStmt);
7506   // 1.2.2 OpenMP Language Terminology
7507   // Structured block - An executable statement with a single entry at the
7508   // top and a single exit at the bottom.
7509   // The point of exit cannot be a branch out of the structured block.
7510   // longjmp() and throw() must not violate the entry/exit criteria.
7511   CS->getCapturedDecl()->setNothrow();
7512   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_distribute_simd);
7513        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7514     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7515     // 1.2.2 OpenMP Language Terminology
7516     // Structured block - An executable statement with a single entry at the
7517     // top and a single exit at the bottom.
7518     // The point of exit cannot be a branch out of the structured block.
7519     // longjmp() and throw() must not violate the entry/exit criteria.
7520     CS->getCapturedDecl()->setNothrow();
7521   }
7522 
7523   OMPLoopDirective::HelperExprs B;
7524   // In presence of clause 'collapse' with number of loops, it will
7525   // define the nested loops number.
7526   unsigned NestedLoopCount =
7527       checkOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
7528                       nullptr /*ordered not a clause on distribute*/, CS, *this,
7529                       *DSAStack, VarsWithImplicitDSA, B);
7530   if (NestedLoopCount == 0)
7531     return StmtError();
7532 
7533   assert((CurContext->isDependentContext() || B.builtAll()) &&
7534          "omp for loop exprs were not built");
7535 
7536   if (!CurContext->isDependentContext()) {
7537     // Finalize the clauses that need pre-built expressions for CodeGen.
7538     for (OMPClause *C : Clauses) {
7539       if (auto *LC = dyn_cast<OMPLinearClause>(C))
7540         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7541                                      B.NumIterations, *this, CurScope,
7542                                      DSAStack))
7543           return StmtError();
7544     }
7545   }
7546 
7547   if (checkSimdlenSafelenSpecified(*this, Clauses))
7548     return StmtError();
7549 
7550   setFunctionHasBranchProtectedScope();
7551   return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
7552                                             NestedLoopCount, Clauses, AStmt, B);
7553 }
7554 
7555 StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
7556     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7557     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
7558   if (!AStmt)
7559     return StmtError();
7560 
7561   auto *CS = cast<CapturedStmt>(AStmt);
7562   // 1.2.2 OpenMP Language Terminology
7563   // Structured block - An executable statement with a single entry at the
7564   // top and a single exit at the bottom.
7565   // The point of exit cannot be a branch out of the structured block.
7566   // longjmp() and throw() must not violate the entry/exit criteria.
7567   CS->getCapturedDecl()->setNothrow();
7568   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
7569        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7570     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7571     // 1.2.2 OpenMP Language Terminology
7572     // Structured block - An executable statement with a single entry at the
7573     // top and a single exit at the bottom.
7574     // The point of exit cannot be a branch out of the structured block.
7575     // longjmp() and throw() must not violate the entry/exit criteria.
7576     CS->getCapturedDecl()->setNothrow();
7577   }
7578 
7579   OMPLoopDirective::HelperExprs B;
7580   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7581   // define the nested loops number.
7582   unsigned NestedLoopCount = checkOpenMPLoop(
7583       OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
7584       getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
7585       VarsWithImplicitDSA, B);
7586   if (NestedLoopCount == 0)
7587     return StmtError();
7588 
7589   assert((CurContext->isDependentContext() || B.builtAll()) &&
7590          "omp target parallel for simd loop exprs were not built");
7591 
7592   if (!CurContext->isDependentContext()) {
7593     // Finalize the clauses that need pre-built expressions for CodeGen.
7594     for (OMPClause *C : Clauses) {
7595       if (auto *LC = dyn_cast<OMPLinearClause>(C))
7596         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7597                                      B.NumIterations, *this, CurScope,
7598                                      DSAStack))
7599           return StmtError();
7600     }
7601   }
7602   if (checkSimdlenSafelenSpecified(*this, Clauses))
7603     return StmtError();
7604 
7605   setFunctionHasBranchProtectedScope();
7606   return OMPTargetParallelForSimdDirective::Create(
7607       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7608 }
7609 
7610 StmtResult Sema::ActOnOpenMPTargetSimdDirective(
7611     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7612     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
7613   if (!AStmt)
7614     return StmtError();
7615 
7616   auto *CS = cast<CapturedStmt>(AStmt);
7617   // 1.2.2 OpenMP Language Terminology
7618   // Structured block - An executable statement with a single entry at the
7619   // top and a single exit at the bottom.
7620   // The point of exit cannot be a branch out of the structured block.
7621   // longjmp() and throw() must not violate the entry/exit criteria.
7622   CS->getCapturedDecl()->setNothrow();
7623   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_simd);
7624        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7625     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7626     // 1.2.2 OpenMP Language Terminology
7627     // Structured block - An executable statement with a single entry at the
7628     // top and a single exit at the bottom.
7629     // The point of exit cannot be a branch out of the structured block.
7630     // longjmp() and throw() must not violate the entry/exit criteria.
7631     CS->getCapturedDecl()->setNothrow();
7632   }
7633 
7634   OMPLoopDirective::HelperExprs B;
7635   // In presence of clause 'collapse' with number of loops, it will define the
7636   // nested loops number.
7637   unsigned NestedLoopCount =
7638       checkOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
7639                       getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
7640                       VarsWithImplicitDSA, B);
7641   if (NestedLoopCount == 0)
7642     return StmtError();
7643 
7644   assert((CurContext->isDependentContext() || B.builtAll()) &&
7645          "omp target simd loop exprs were not built");
7646 
7647   if (!CurContext->isDependentContext()) {
7648     // Finalize the clauses that need pre-built expressions for CodeGen.
7649     for (OMPClause *C : Clauses) {
7650       if (auto *LC = dyn_cast<OMPLinearClause>(C))
7651         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7652                                      B.NumIterations, *this, CurScope,
7653                                      DSAStack))
7654           return StmtError();
7655     }
7656   }
7657 
7658   if (checkSimdlenSafelenSpecified(*this, Clauses))
7659     return StmtError();
7660 
7661   setFunctionHasBranchProtectedScope();
7662   return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
7663                                         NestedLoopCount, Clauses, AStmt, B);
7664 }
7665 
7666 StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
7667     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7668     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
7669   if (!AStmt)
7670     return StmtError();
7671 
7672   auto *CS = cast<CapturedStmt>(AStmt);
7673   // 1.2.2 OpenMP Language Terminology
7674   // Structured block - An executable statement with a single entry at the
7675   // top and a single exit at the bottom.
7676   // The point of exit cannot be a branch out of the structured block.
7677   // longjmp() and throw() must not violate the entry/exit criteria.
7678   CS->getCapturedDecl()->setNothrow();
7679   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_teams_distribute);
7680        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7681     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7682     // 1.2.2 OpenMP Language Terminology
7683     // Structured block - An executable statement with a single entry at the
7684     // top and a single exit at the bottom.
7685     // The point of exit cannot be a branch out of the structured block.
7686     // longjmp() and throw() must not violate the entry/exit criteria.
7687     CS->getCapturedDecl()->setNothrow();
7688   }
7689 
7690   OMPLoopDirective::HelperExprs B;
7691   // In presence of clause 'collapse' with number of loops, it will
7692   // define the nested loops number.
7693   unsigned NestedLoopCount =
7694       checkOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
7695                       nullptr /*ordered not a clause on distribute*/, CS, *this,
7696                       *DSAStack, VarsWithImplicitDSA, B);
7697   if (NestedLoopCount == 0)
7698     return StmtError();
7699 
7700   assert((CurContext->isDependentContext() || B.builtAll()) &&
7701          "omp teams distribute loop exprs were not built");
7702 
7703   setFunctionHasBranchProtectedScope();
7704 
7705   DSAStack->setParentTeamsRegionLoc(StartLoc);
7706 
7707   return OMPTeamsDistributeDirective::Create(
7708       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7709 }
7710 
7711 StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
7712     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7713     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
7714   if (!AStmt)
7715     return StmtError();
7716 
7717   auto *CS = cast<CapturedStmt>(AStmt);
7718   // 1.2.2 OpenMP Language Terminology
7719   // Structured block - An executable statement with a single entry at the
7720   // top and a single exit at the bottom.
7721   // The point of exit cannot be a branch out of the structured block.
7722   // longjmp() and throw() must not violate the entry/exit criteria.
7723   CS->getCapturedDecl()->setNothrow();
7724   for (int ThisCaptureLevel =
7725            getOpenMPCaptureLevels(OMPD_teams_distribute_simd);
7726        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7727     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7728     // 1.2.2 OpenMP Language Terminology
7729     // Structured block - An executable statement with a single entry at the
7730     // top and a single exit at the bottom.
7731     // The point of exit cannot be a branch out of the structured block.
7732     // longjmp() and throw() must not violate the entry/exit criteria.
7733     CS->getCapturedDecl()->setNothrow();
7734   }
7735 
7736 
7737   OMPLoopDirective::HelperExprs B;
7738   // In presence of clause 'collapse' with number of loops, it will
7739   // define the nested loops number.
7740   unsigned NestedLoopCount = checkOpenMPLoop(
7741       OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
7742       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
7743       VarsWithImplicitDSA, B);
7744 
7745   if (NestedLoopCount == 0)
7746     return StmtError();
7747 
7748   assert((CurContext->isDependentContext() || B.builtAll()) &&
7749          "omp teams distribute simd loop exprs were not built");
7750 
7751   if (!CurContext->isDependentContext()) {
7752     // Finalize the clauses that need pre-built expressions for CodeGen.
7753     for (OMPClause *C : Clauses) {
7754       if (auto *LC = dyn_cast<OMPLinearClause>(C))
7755         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7756                                      B.NumIterations, *this, CurScope,
7757                                      DSAStack))
7758           return StmtError();
7759     }
7760   }
7761 
7762   if (checkSimdlenSafelenSpecified(*this, Clauses))
7763     return StmtError();
7764 
7765   setFunctionHasBranchProtectedScope();
7766 
7767   DSAStack->setParentTeamsRegionLoc(StartLoc);
7768 
7769   return OMPTeamsDistributeSimdDirective::Create(
7770       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7771 }
7772 
7773 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
7774     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7775     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
7776   if (!AStmt)
7777     return StmtError();
7778 
7779   auto *CS = cast<CapturedStmt>(AStmt);
7780   // 1.2.2 OpenMP Language Terminology
7781   // Structured block - An executable statement with a single entry at the
7782   // top and a single exit at the bottom.
7783   // The point of exit cannot be a branch out of the structured block.
7784   // longjmp() and throw() must not violate the entry/exit criteria.
7785   CS->getCapturedDecl()->setNothrow();
7786 
7787   for (int ThisCaptureLevel =
7788            getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for_simd);
7789        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7790     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7791     // 1.2.2 OpenMP Language Terminology
7792     // Structured block - An executable statement with a single entry at the
7793     // top and a single exit at the bottom.
7794     // The point of exit cannot be a branch out of the structured block.
7795     // longjmp() and throw() must not violate the entry/exit criteria.
7796     CS->getCapturedDecl()->setNothrow();
7797   }
7798 
7799   OMPLoopDirective::HelperExprs B;
7800   // In presence of clause 'collapse' with number of loops, it will
7801   // define the nested loops number.
7802   unsigned NestedLoopCount = checkOpenMPLoop(
7803       OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
7804       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
7805       VarsWithImplicitDSA, B);
7806 
7807   if (NestedLoopCount == 0)
7808     return StmtError();
7809 
7810   assert((CurContext->isDependentContext() || B.builtAll()) &&
7811          "omp for loop exprs were not built");
7812 
7813   if (!CurContext->isDependentContext()) {
7814     // Finalize the clauses that need pre-built expressions for CodeGen.
7815     for (OMPClause *C : Clauses) {
7816       if (auto *LC = dyn_cast<OMPLinearClause>(C))
7817         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7818                                      B.NumIterations, *this, CurScope,
7819                                      DSAStack))
7820           return StmtError();
7821     }
7822   }
7823 
7824   if (checkSimdlenSafelenSpecified(*this, Clauses))
7825     return StmtError();
7826 
7827   setFunctionHasBranchProtectedScope();
7828 
7829   DSAStack->setParentTeamsRegionLoc(StartLoc);
7830 
7831   return OMPTeamsDistributeParallelForSimdDirective::Create(
7832       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7833 }
7834 
7835 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
7836     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7837     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
7838   if (!AStmt)
7839     return StmtError();
7840 
7841   auto *CS = cast<CapturedStmt>(AStmt);
7842   // 1.2.2 OpenMP Language Terminology
7843   // Structured block - An executable statement with a single entry at the
7844   // top and a single exit at the bottom.
7845   // The point of exit cannot be a branch out of the structured block.
7846   // longjmp() and throw() must not violate the entry/exit criteria.
7847   CS->getCapturedDecl()->setNothrow();
7848 
7849   for (int ThisCaptureLevel =
7850            getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for);
7851        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7852     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7853     // 1.2.2 OpenMP Language Terminology
7854     // Structured block - An executable statement with a single entry at the
7855     // top and a single exit at the bottom.
7856     // The point of exit cannot be a branch out of the structured block.
7857     // longjmp() and throw() must not violate the entry/exit criteria.
7858     CS->getCapturedDecl()->setNothrow();
7859   }
7860 
7861   OMPLoopDirective::HelperExprs B;
7862   // In presence of clause 'collapse' with number of loops, it will
7863   // define the nested loops number.
7864   unsigned NestedLoopCount = checkOpenMPLoop(
7865       OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
7866       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
7867       VarsWithImplicitDSA, B);
7868 
7869   if (NestedLoopCount == 0)
7870     return StmtError();
7871 
7872   assert((CurContext->isDependentContext() || B.builtAll()) &&
7873          "omp for loop exprs were not built");
7874 
7875   setFunctionHasBranchProtectedScope();
7876 
7877   DSAStack->setParentTeamsRegionLoc(StartLoc);
7878 
7879   return OMPTeamsDistributeParallelForDirective::Create(
7880       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
7881       DSAStack->isCancelRegion());
7882 }
7883 
7884 StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
7885                                                  Stmt *AStmt,
7886                                                  SourceLocation StartLoc,
7887                                                  SourceLocation EndLoc) {
7888   if (!AStmt)
7889     return StmtError();
7890 
7891   auto *CS = cast<CapturedStmt>(AStmt);
7892   // 1.2.2 OpenMP Language Terminology
7893   // Structured block - An executable statement with a single entry at the
7894   // top and a single exit at the bottom.
7895   // The point of exit cannot be a branch out of the structured block.
7896   // longjmp() and throw() must not violate the entry/exit criteria.
7897   CS->getCapturedDecl()->setNothrow();
7898 
7899   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams);
7900        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7901     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7902     // 1.2.2 OpenMP Language Terminology
7903     // Structured block - An executable statement with a single entry at the
7904     // top and a single exit at the bottom.
7905     // The point of exit cannot be a branch out of the structured block.
7906     // longjmp() and throw() must not violate the entry/exit criteria.
7907     CS->getCapturedDecl()->setNothrow();
7908   }
7909   setFunctionHasBranchProtectedScope();
7910 
7911   return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
7912                                          AStmt);
7913 }
7914 
7915 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
7916     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7917     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
7918   if (!AStmt)
7919     return StmtError();
7920 
7921   auto *CS = cast<CapturedStmt>(AStmt);
7922   // 1.2.2 OpenMP Language Terminology
7923   // Structured block - An executable statement with a single entry at the
7924   // top and a single exit at the bottom.
7925   // The point of exit cannot be a branch out of the structured block.
7926   // longjmp() and throw() must not violate the entry/exit criteria.
7927   CS->getCapturedDecl()->setNothrow();
7928   for (int ThisCaptureLevel =
7929            getOpenMPCaptureLevels(OMPD_target_teams_distribute);
7930        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7931     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7932     // 1.2.2 OpenMP Language Terminology
7933     // Structured block - An executable statement with a single entry at the
7934     // top and a single exit at the bottom.
7935     // The point of exit cannot be a branch out of the structured block.
7936     // longjmp() and throw() must not violate the entry/exit criteria.
7937     CS->getCapturedDecl()->setNothrow();
7938   }
7939 
7940   OMPLoopDirective::HelperExprs B;
7941   // In presence of clause 'collapse' with number of loops, it will
7942   // define the nested loops number.
7943   unsigned NestedLoopCount = checkOpenMPLoop(
7944       OMPD_target_teams_distribute, getCollapseNumberExpr(Clauses),
7945       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
7946       VarsWithImplicitDSA, B);
7947   if (NestedLoopCount == 0)
7948     return StmtError();
7949 
7950   assert((CurContext->isDependentContext() || B.builtAll()) &&
7951          "omp target teams distribute loop exprs were not built");
7952 
7953   setFunctionHasBranchProtectedScope();
7954   return OMPTargetTeamsDistributeDirective::Create(
7955       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7956 }
7957 
7958 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
7959     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7960     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
7961   if (!AStmt)
7962     return StmtError();
7963 
7964   auto *CS = cast<CapturedStmt>(AStmt);
7965   // 1.2.2 OpenMP Language Terminology
7966   // Structured block - An executable statement with a single entry at the
7967   // top and a single exit at the bottom.
7968   // The point of exit cannot be a branch out of the structured block.
7969   // longjmp() and throw() must not violate the entry/exit criteria.
7970   CS->getCapturedDecl()->setNothrow();
7971   for (int ThisCaptureLevel =
7972            getOpenMPCaptureLevels(OMPD_target_teams_distribute_parallel_for);
7973        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7974     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7975     // 1.2.2 OpenMP Language Terminology
7976     // Structured block - An executable statement with a single entry at the
7977     // top and a single exit at the bottom.
7978     // The point of exit cannot be a branch out of the structured block.
7979     // longjmp() and throw() must not violate the entry/exit criteria.
7980     CS->getCapturedDecl()->setNothrow();
7981   }
7982 
7983   OMPLoopDirective::HelperExprs B;
7984   // In presence of clause 'collapse' with number of loops, it will
7985   // define the nested loops number.
7986   unsigned NestedLoopCount = checkOpenMPLoop(
7987       OMPD_target_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
7988       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
7989       VarsWithImplicitDSA, B);
7990   if (NestedLoopCount == 0)
7991     return StmtError();
7992 
7993   assert((CurContext->isDependentContext() || B.builtAll()) &&
7994          "omp target teams distribute parallel for loop exprs were not built");
7995 
7996   if (!CurContext->isDependentContext()) {
7997     // Finalize the clauses that need pre-built expressions for CodeGen.
7998     for (OMPClause *C : Clauses) {
7999       if (auto *LC = dyn_cast<OMPLinearClause>(C))
8000         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8001                                      B.NumIterations, *this, CurScope,
8002                                      DSAStack))
8003           return StmtError();
8004     }
8005   }
8006 
8007   setFunctionHasBranchProtectedScope();
8008   return OMPTargetTeamsDistributeParallelForDirective::Create(
8009       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
8010       DSAStack->isCancelRegion());
8011 }
8012 
8013 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
8014     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8015     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
8016   if (!AStmt)
8017     return StmtError();
8018 
8019   auto *CS = cast<CapturedStmt>(AStmt);
8020   // 1.2.2 OpenMP Language Terminology
8021   // Structured block - An executable statement with a single entry at the
8022   // top and a single exit at the bottom.
8023   // The point of exit cannot be a branch out of the structured block.
8024   // longjmp() and throw() must not violate the entry/exit criteria.
8025   CS->getCapturedDecl()->setNothrow();
8026   for (int ThisCaptureLevel = getOpenMPCaptureLevels(
8027            OMPD_target_teams_distribute_parallel_for_simd);
8028        ThisCaptureLevel > 1; --ThisCaptureLevel) {
8029     CS = cast<CapturedStmt>(CS->getCapturedStmt());
8030     // 1.2.2 OpenMP Language Terminology
8031     // Structured block - An executable statement with a single entry at the
8032     // top and a single exit at the bottom.
8033     // The point of exit cannot be a branch out of the structured block.
8034     // longjmp() and throw() must not violate the entry/exit criteria.
8035     CS->getCapturedDecl()->setNothrow();
8036   }
8037 
8038   OMPLoopDirective::HelperExprs B;
8039   // In presence of clause 'collapse' with number of loops, it will
8040   // define the nested loops number.
8041   unsigned NestedLoopCount =
8042       checkOpenMPLoop(OMPD_target_teams_distribute_parallel_for_simd,
8043                       getCollapseNumberExpr(Clauses),
8044                       nullptr /*ordered not a clause on distribute*/, CS, *this,
8045                       *DSAStack, VarsWithImplicitDSA, B);
8046   if (NestedLoopCount == 0)
8047     return StmtError();
8048 
8049   assert((CurContext->isDependentContext() || B.builtAll()) &&
8050          "omp target teams distribute parallel for simd loop exprs were not "
8051          "built");
8052 
8053   if (!CurContext->isDependentContext()) {
8054     // Finalize the clauses that need pre-built expressions for CodeGen.
8055     for (OMPClause *C : Clauses) {
8056       if (auto *LC = dyn_cast<OMPLinearClause>(C))
8057         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8058                                      B.NumIterations, *this, CurScope,
8059                                      DSAStack))
8060           return StmtError();
8061     }
8062   }
8063 
8064   if (checkSimdlenSafelenSpecified(*this, Clauses))
8065     return StmtError();
8066 
8067   setFunctionHasBranchProtectedScope();
8068   return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
8069       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8070 }
8071 
8072 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
8073     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8074     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
8075   if (!AStmt)
8076     return StmtError();
8077 
8078   auto *CS = cast<CapturedStmt>(AStmt);
8079   // 1.2.2 OpenMP Language Terminology
8080   // Structured block - An executable statement with a single entry at the
8081   // top and a single exit at the bottom.
8082   // The point of exit cannot be a branch out of the structured block.
8083   // longjmp() and throw() must not violate the entry/exit criteria.
8084   CS->getCapturedDecl()->setNothrow();
8085   for (int ThisCaptureLevel =
8086            getOpenMPCaptureLevels(OMPD_target_teams_distribute_simd);
8087        ThisCaptureLevel > 1; --ThisCaptureLevel) {
8088     CS = cast<CapturedStmt>(CS->getCapturedStmt());
8089     // 1.2.2 OpenMP Language Terminology
8090     // Structured block - An executable statement with a single entry at the
8091     // top and a single exit at the bottom.
8092     // The point of exit cannot be a branch out of the structured block.
8093     // longjmp() and throw() must not violate the entry/exit criteria.
8094     CS->getCapturedDecl()->setNothrow();
8095   }
8096 
8097   OMPLoopDirective::HelperExprs B;
8098   // In presence of clause 'collapse' with number of loops, it will
8099   // define the nested loops number.
8100   unsigned NestedLoopCount = checkOpenMPLoop(
8101       OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
8102       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
8103       VarsWithImplicitDSA, B);
8104   if (NestedLoopCount == 0)
8105     return StmtError();
8106 
8107   assert((CurContext->isDependentContext() || B.builtAll()) &&
8108          "omp target teams distribute simd loop exprs were not built");
8109 
8110   if (!CurContext->isDependentContext()) {
8111     // Finalize the clauses that need pre-built expressions for CodeGen.
8112     for (OMPClause *C : Clauses) {
8113       if (auto *LC = dyn_cast<OMPLinearClause>(C))
8114         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8115                                      B.NumIterations, *this, CurScope,
8116                                      DSAStack))
8117           return StmtError();
8118     }
8119   }
8120 
8121   if (checkSimdlenSafelenSpecified(*this, Clauses))
8122     return StmtError();
8123 
8124   setFunctionHasBranchProtectedScope();
8125   return OMPTargetTeamsDistributeSimdDirective::Create(
8126       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8127 }
8128 
8129 OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
8130                                              SourceLocation StartLoc,
8131                                              SourceLocation LParenLoc,
8132                                              SourceLocation EndLoc) {
8133   OMPClause *Res = nullptr;
8134   switch (Kind) {
8135   case OMPC_final:
8136     Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
8137     break;
8138   case OMPC_num_threads:
8139     Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
8140     break;
8141   case OMPC_safelen:
8142     Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
8143     break;
8144   case OMPC_simdlen:
8145     Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
8146     break;
8147   case OMPC_collapse:
8148     Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
8149     break;
8150   case OMPC_ordered:
8151     Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
8152     break;
8153   case OMPC_device:
8154     Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
8155     break;
8156   case OMPC_num_teams:
8157     Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
8158     break;
8159   case OMPC_thread_limit:
8160     Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
8161     break;
8162   case OMPC_priority:
8163     Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
8164     break;
8165   case OMPC_grainsize:
8166     Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
8167     break;
8168   case OMPC_num_tasks:
8169     Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
8170     break;
8171   case OMPC_hint:
8172     Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
8173     break;
8174   case OMPC_if:
8175   case OMPC_default:
8176   case OMPC_proc_bind:
8177   case OMPC_schedule:
8178   case OMPC_private:
8179   case OMPC_firstprivate:
8180   case OMPC_lastprivate:
8181   case OMPC_shared:
8182   case OMPC_reduction:
8183   case OMPC_task_reduction:
8184   case OMPC_in_reduction:
8185   case OMPC_linear:
8186   case OMPC_aligned:
8187   case OMPC_copyin:
8188   case OMPC_copyprivate:
8189   case OMPC_nowait:
8190   case OMPC_untied:
8191   case OMPC_mergeable:
8192   case OMPC_threadprivate:
8193   case OMPC_flush:
8194   case OMPC_read:
8195   case OMPC_write:
8196   case OMPC_update:
8197   case OMPC_capture:
8198   case OMPC_seq_cst:
8199   case OMPC_depend:
8200   case OMPC_threads:
8201   case OMPC_simd:
8202   case OMPC_map:
8203   case OMPC_nogroup:
8204   case OMPC_dist_schedule:
8205   case OMPC_defaultmap:
8206   case OMPC_unknown:
8207   case OMPC_uniform:
8208   case OMPC_to:
8209   case OMPC_from:
8210   case OMPC_use_device_ptr:
8211   case OMPC_is_device_ptr:
8212   case OMPC_unified_address:
8213   case OMPC_unified_shared_memory:
8214   case OMPC_reverse_offload:
8215   case OMPC_dynamic_allocators:
8216   case OMPC_atomic_default_mem_order:
8217     llvm_unreachable("Clause is not allowed.");
8218   }
8219   return Res;
8220 }
8221 
8222 // An OpenMP directive such as 'target parallel' has two captured regions:
8223 // for the 'target' and 'parallel' respectively.  This function returns
8224 // the region in which to capture expressions associated with a clause.
8225 // A return value of OMPD_unknown signifies that the expression should not
8226 // be captured.
8227 static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
8228     OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
8229     OpenMPDirectiveKind NameModifier = OMPD_unknown) {
8230   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
8231   switch (CKind) {
8232   case OMPC_if:
8233     switch (DKind) {
8234     case OMPD_target_parallel:
8235     case OMPD_target_parallel_for:
8236     case OMPD_target_parallel_for_simd:
8237       // If this clause applies to the nested 'parallel' region, capture within
8238       // the 'target' region, otherwise do not capture.
8239       if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
8240         CaptureRegion = OMPD_target;
8241       break;
8242     case OMPD_target_teams_distribute_parallel_for:
8243     case OMPD_target_teams_distribute_parallel_for_simd:
8244       // If this clause applies to the nested 'parallel' region, capture within
8245       // the 'teams' region, otherwise do not capture.
8246       if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
8247         CaptureRegion = OMPD_teams;
8248       break;
8249     case OMPD_teams_distribute_parallel_for:
8250     case OMPD_teams_distribute_parallel_for_simd:
8251       CaptureRegion = OMPD_teams;
8252       break;
8253     case OMPD_target_update:
8254     case OMPD_target_enter_data:
8255     case OMPD_target_exit_data:
8256       CaptureRegion = OMPD_task;
8257       break;
8258     case OMPD_cancel:
8259     case OMPD_parallel:
8260     case OMPD_parallel_sections:
8261     case OMPD_parallel_for:
8262     case OMPD_parallel_for_simd:
8263     case OMPD_target:
8264     case OMPD_target_simd:
8265     case OMPD_target_teams:
8266     case OMPD_target_teams_distribute:
8267     case OMPD_target_teams_distribute_simd:
8268     case OMPD_distribute_parallel_for:
8269     case OMPD_distribute_parallel_for_simd:
8270     case OMPD_task:
8271     case OMPD_taskloop:
8272     case OMPD_taskloop_simd:
8273     case OMPD_target_data:
8274       // Do not capture if-clause expressions.
8275       break;
8276     case OMPD_threadprivate:
8277     case OMPD_taskyield:
8278     case OMPD_barrier:
8279     case OMPD_taskwait:
8280     case OMPD_cancellation_point:
8281     case OMPD_flush:
8282     case OMPD_declare_reduction:
8283     case OMPD_declare_simd:
8284     case OMPD_declare_target:
8285     case OMPD_end_declare_target:
8286     case OMPD_teams:
8287     case OMPD_simd:
8288     case OMPD_for:
8289     case OMPD_for_simd:
8290     case OMPD_sections:
8291     case OMPD_section:
8292     case OMPD_single:
8293     case OMPD_master:
8294     case OMPD_critical:
8295     case OMPD_taskgroup:
8296     case OMPD_distribute:
8297     case OMPD_ordered:
8298     case OMPD_atomic:
8299     case OMPD_distribute_simd:
8300     case OMPD_teams_distribute:
8301     case OMPD_teams_distribute_simd:
8302     case OMPD_requires:
8303       llvm_unreachable("Unexpected OpenMP directive with if-clause");
8304     case OMPD_unknown:
8305       llvm_unreachable("Unknown OpenMP directive");
8306     }
8307     break;
8308   case OMPC_num_threads:
8309     switch (DKind) {
8310     case OMPD_target_parallel:
8311     case OMPD_target_parallel_for:
8312     case OMPD_target_parallel_for_simd:
8313       CaptureRegion = OMPD_target;
8314       break;
8315     case OMPD_teams_distribute_parallel_for:
8316     case OMPD_teams_distribute_parallel_for_simd:
8317     case OMPD_target_teams_distribute_parallel_for:
8318     case OMPD_target_teams_distribute_parallel_for_simd:
8319       CaptureRegion = OMPD_teams;
8320       break;
8321     case OMPD_parallel:
8322     case OMPD_parallel_sections:
8323     case OMPD_parallel_for:
8324     case OMPD_parallel_for_simd:
8325     case OMPD_distribute_parallel_for:
8326     case OMPD_distribute_parallel_for_simd:
8327       // Do not capture num_threads-clause expressions.
8328       break;
8329     case OMPD_target_data:
8330     case OMPD_target_enter_data:
8331     case OMPD_target_exit_data:
8332     case OMPD_target_update:
8333     case OMPD_target:
8334     case OMPD_target_simd:
8335     case OMPD_target_teams:
8336     case OMPD_target_teams_distribute:
8337     case OMPD_target_teams_distribute_simd:
8338     case OMPD_cancel:
8339     case OMPD_task:
8340     case OMPD_taskloop:
8341     case OMPD_taskloop_simd:
8342     case OMPD_threadprivate:
8343     case OMPD_taskyield:
8344     case OMPD_barrier:
8345     case OMPD_taskwait:
8346     case OMPD_cancellation_point:
8347     case OMPD_flush:
8348     case OMPD_declare_reduction:
8349     case OMPD_declare_simd:
8350     case OMPD_declare_target:
8351     case OMPD_end_declare_target:
8352     case OMPD_teams:
8353     case OMPD_simd:
8354     case OMPD_for:
8355     case OMPD_for_simd:
8356     case OMPD_sections:
8357     case OMPD_section:
8358     case OMPD_single:
8359     case OMPD_master:
8360     case OMPD_critical:
8361     case OMPD_taskgroup:
8362     case OMPD_distribute:
8363     case OMPD_ordered:
8364     case OMPD_atomic:
8365     case OMPD_distribute_simd:
8366     case OMPD_teams_distribute:
8367     case OMPD_teams_distribute_simd:
8368     case OMPD_requires:
8369       llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
8370     case OMPD_unknown:
8371       llvm_unreachable("Unknown OpenMP directive");
8372     }
8373     break;
8374   case OMPC_num_teams:
8375     switch (DKind) {
8376     case OMPD_target_teams:
8377     case OMPD_target_teams_distribute:
8378     case OMPD_target_teams_distribute_simd:
8379     case OMPD_target_teams_distribute_parallel_for:
8380     case OMPD_target_teams_distribute_parallel_for_simd:
8381       CaptureRegion = OMPD_target;
8382       break;
8383     case OMPD_teams_distribute_parallel_for:
8384     case OMPD_teams_distribute_parallel_for_simd:
8385     case OMPD_teams:
8386     case OMPD_teams_distribute:
8387     case OMPD_teams_distribute_simd:
8388       // Do not capture num_teams-clause expressions.
8389       break;
8390     case OMPD_distribute_parallel_for:
8391     case OMPD_distribute_parallel_for_simd:
8392     case OMPD_task:
8393     case OMPD_taskloop:
8394     case OMPD_taskloop_simd:
8395     case OMPD_target_data:
8396     case OMPD_target_enter_data:
8397     case OMPD_target_exit_data:
8398     case OMPD_target_update:
8399     case OMPD_cancel:
8400     case OMPD_parallel:
8401     case OMPD_parallel_sections:
8402     case OMPD_parallel_for:
8403     case OMPD_parallel_for_simd:
8404     case OMPD_target:
8405     case OMPD_target_simd:
8406     case OMPD_target_parallel:
8407     case OMPD_target_parallel_for:
8408     case OMPD_target_parallel_for_simd:
8409     case OMPD_threadprivate:
8410     case OMPD_taskyield:
8411     case OMPD_barrier:
8412     case OMPD_taskwait:
8413     case OMPD_cancellation_point:
8414     case OMPD_flush:
8415     case OMPD_declare_reduction:
8416     case OMPD_declare_simd:
8417     case OMPD_declare_target:
8418     case OMPD_end_declare_target:
8419     case OMPD_simd:
8420     case OMPD_for:
8421     case OMPD_for_simd:
8422     case OMPD_sections:
8423     case OMPD_section:
8424     case OMPD_single:
8425     case OMPD_master:
8426     case OMPD_critical:
8427     case OMPD_taskgroup:
8428     case OMPD_distribute:
8429     case OMPD_ordered:
8430     case OMPD_atomic:
8431     case OMPD_distribute_simd:
8432     case OMPD_requires:
8433       llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
8434     case OMPD_unknown:
8435       llvm_unreachable("Unknown OpenMP directive");
8436     }
8437     break;
8438   case OMPC_thread_limit:
8439     switch (DKind) {
8440     case OMPD_target_teams:
8441     case OMPD_target_teams_distribute:
8442     case OMPD_target_teams_distribute_simd:
8443     case OMPD_target_teams_distribute_parallel_for:
8444     case OMPD_target_teams_distribute_parallel_for_simd:
8445       CaptureRegion = OMPD_target;
8446       break;
8447     case OMPD_teams_distribute_parallel_for:
8448     case OMPD_teams_distribute_parallel_for_simd:
8449     case OMPD_teams:
8450     case OMPD_teams_distribute:
8451     case OMPD_teams_distribute_simd:
8452       // Do not capture thread_limit-clause expressions.
8453       break;
8454     case OMPD_distribute_parallel_for:
8455     case OMPD_distribute_parallel_for_simd:
8456     case OMPD_task:
8457     case OMPD_taskloop:
8458     case OMPD_taskloop_simd:
8459     case OMPD_target_data:
8460     case OMPD_target_enter_data:
8461     case OMPD_target_exit_data:
8462     case OMPD_target_update:
8463     case OMPD_cancel:
8464     case OMPD_parallel:
8465     case OMPD_parallel_sections:
8466     case OMPD_parallel_for:
8467     case OMPD_parallel_for_simd:
8468     case OMPD_target:
8469     case OMPD_target_simd:
8470     case OMPD_target_parallel:
8471     case OMPD_target_parallel_for:
8472     case OMPD_target_parallel_for_simd:
8473     case OMPD_threadprivate:
8474     case OMPD_taskyield:
8475     case OMPD_barrier:
8476     case OMPD_taskwait:
8477     case OMPD_cancellation_point:
8478     case OMPD_flush:
8479     case OMPD_declare_reduction:
8480     case OMPD_declare_simd:
8481     case OMPD_declare_target:
8482     case OMPD_end_declare_target:
8483     case OMPD_simd:
8484     case OMPD_for:
8485     case OMPD_for_simd:
8486     case OMPD_sections:
8487     case OMPD_section:
8488     case OMPD_single:
8489     case OMPD_master:
8490     case OMPD_critical:
8491     case OMPD_taskgroup:
8492     case OMPD_distribute:
8493     case OMPD_ordered:
8494     case OMPD_atomic:
8495     case OMPD_distribute_simd:
8496     case OMPD_requires:
8497       llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
8498     case OMPD_unknown:
8499       llvm_unreachable("Unknown OpenMP directive");
8500     }
8501     break;
8502   case OMPC_schedule:
8503     switch (DKind) {
8504     case OMPD_parallel_for:
8505     case OMPD_parallel_for_simd:
8506     case OMPD_distribute_parallel_for:
8507     case OMPD_distribute_parallel_for_simd:
8508     case OMPD_teams_distribute_parallel_for:
8509     case OMPD_teams_distribute_parallel_for_simd:
8510     case OMPD_target_parallel_for:
8511     case OMPD_target_parallel_for_simd:
8512     case OMPD_target_teams_distribute_parallel_for:
8513     case OMPD_target_teams_distribute_parallel_for_simd:
8514       CaptureRegion = OMPD_parallel;
8515       break;
8516     case OMPD_for:
8517     case OMPD_for_simd:
8518       // Do not capture schedule-clause expressions.
8519       break;
8520     case OMPD_task:
8521     case OMPD_taskloop:
8522     case OMPD_taskloop_simd:
8523     case OMPD_target_data:
8524     case OMPD_target_enter_data:
8525     case OMPD_target_exit_data:
8526     case OMPD_target_update:
8527     case OMPD_teams:
8528     case OMPD_teams_distribute:
8529     case OMPD_teams_distribute_simd:
8530     case OMPD_target_teams_distribute:
8531     case OMPD_target_teams_distribute_simd:
8532     case OMPD_target:
8533     case OMPD_target_simd:
8534     case OMPD_target_parallel:
8535     case OMPD_cancel:
8536     case OMPD_parallel:
8537     case OMPD_parallel_sections:
8538     case OMPD_threadprivate:
8539     case OMPD_taskyield:
8540     case OMPD_barrier:
8541     case OMPD_taskwait:
8542     case OMPD_cancellation_point:
8543     case OMPD_flush:
8544     case OMPD_declare_reduction:
8545     case OMPD_declare_simd:
8546     case OMPD_declare_target:
8547     case OMPD_end_declare_target:
8548     case OMPD_simd:
8549     case OMPD_sections:
8550     case OMPD_section:
8551     case OMPD_single:
8552     case OMPD_master:
8553     case OMPD_critical:
8554     case OMPD_taskgroup:
8555     case OMPD_distribute:
8556     case OMPD_ordered:
8557     case OMPD_atomic:
8558     case OMPD_distribute_simd:
8559     case OMPD_target_teams:
8560     case OMPD_requires:
8561       llvm_unreachable("Unexpected OpenMP directive with schedule clause");
8562     case OMPD_unknown:
8563       llvm_unreachable("Unknown OpenMP directive");
8564     }
8565     break;
8566   case OMPC_dist_schedule:
8567     switch (DKind) {
8568     case OMPD_teams_distribute_parallel_for:
8569     case OMPD_teams_distribute_parallel_for_simd:
8570     case OMPD_teams_distribute:
8571     case OMPD_teams_distribute_simd:
8572     case OMPD_target_teams_distribute_parallel_for:
8573     case OMPD_target_teams_distribute_parallel_for_simd:
8574     case OMPD_target_teams_distribute:
8575     case OMPD_target_teams_distribute_simd:
8576       CaptureRegion = OMPD_teams;
8577       break;
8578     case OMPD_distribute_parallel_for:
8579     case OMPD_distribute_parallel_for_simd:
8580     case OMPD_distribute:
8581     case OMPD_distribute_simd:
8582       // Do not capture thread_limit-clause expressions.
8583       break;
8584     case OMPD_parallel_for:
8585     case OMPD_parallel_for_simd:
8586     case OMPD_target_parallel_for_simd:
8587     case OMPD_target_parallel_for:
8588     case OMPD_task:
8589     case OMPD_taskloop:
8590     case OMPD_taskloop_simd:
8591     case OMPD_target_data:
8592     case OMPD_target_enter_data:
8593     case OMPD_target_exit_data:
8594     case OMPD_target_update:
8595     case OMPD_teams:
8596     case OMPD_target:
8597     case OMPD_target_simd:
8598     case OMPD_target_parallel:
8599     case OMPD_cancel:
8600     case OMPD_parallel:
8601     case OMPD_parallel_sections:
8602     case OMPD_threadprivate:
8603     case OMPD_taskyield:
8604     case OMPD_barrier:
8605     case OMPD_taskwait:
8606     case OMPD_cancellation_point:
8607     case OMPD_flush:
8608     case OMPD_declare_reduction:
8609     case OMPD_declare_simd:
8610     case OMPD_declare_target:
8611     case OMPD_end_declare_target:
8612     case OMPD_simd:
8613     case OMPD_for:
8614     case OMPD_for_simd:
8615     case OMPD_sections:
8616     case OMPD_section:
8617     case OMPD_single:
8618     case OMPD_master:
8619     case OMPD_critical:
8620     case OMPD_taskgroup:
8621     case OMPD_ordered:
8622     case OMPD_atomic:
8623     case OMPD_target_teams:
8624     case OMPD_requires:
8625       llvm_unreachable("Unexpected OpenMP directive with schedule clause");
8626     case OMPD_unknown:
8627       llvm_unreachable("Unknown OpenMP directive");
8628     }
8629     break;
8630   case OMPC_device:
8631     switch (DKind) {
8632     case OMPD_target_update:
8633     case OMPD_target_enter_data:
8634     case OMPD_target_exit_data:
8635     case OMPD_target:
8636     case OMPD_target_simd:
8637     case OMPD_target_teams:
8638     case OMPD_target_parallel:
8639     case OMPD_target_teams_distribute:
8640     case OMPD_target_teams_distribute_simd:
8641     case OMPD_target_parallel_for:
8642     case OMPD_target_parallel_for_simd:
8643     case OMPD_target_teams_distribute_parallel_for:
8644     case OMPD_target_teams_distribute_parallel_for_simd:
8645       CaptureRegion = OMPD_task;
8646       break;
8647     case OMPD_target_data:
8648       // Do not capture device-clause expressions.
8649       break;
8650     case OMPD_teams_distribute_parallel_for:
8651     case OMPD_teams_distribute_parallel_for_simd:
8652     case OMPD_teams:
8653     case OMPD_teams_distribute:
8654     case OMPD_teams_distribute_simd:
8655     case OMPD_distribute_parallel_for:
8656     case OMPD_distribute_parallel_for_simd:
8657     case OMPD_task:
8658     case OMPD_taskloop:
8659     case OMPD_taskloop_simd:
8660     case OMPD_cancel:
8661     case OMPD_parallel:
8662     case OMPD_parallel_sections:
8663     case OMPD_parallel_for:
8664     case OMPD_parallel_for_simd:
8665     case OMPD_threadprivate:
8666     case OMPD_taskyield:
8667     case OMPD_barrier:
8668     case OMPD_taskwait:
8669     case OMPD_cancellation_point:
8670     case OMPD_flush:
8671     case OMPD_declare_reduction:
8672     case OMPD_declare_simd:
8673     case OMPD_declare_target:
8674     case OMPD_end_declare_target:
8675     case OMPD_simd:
8676     case OMPD_for:
8677     case OMPD_for_simd:
8678     case OMPD_sections:
8679     case OMPD_section:
8680     case OMPD_single:
8681     case OMPD_master:
8682     case OMPD_critical:
8683     case OMPD_taskgroup:
8684     case OMPD_distribute:
8685     case OMPD_ordered:
8686     case OMPD_atomic:
8687     case OMPD_distribute_simd:
8688     case OMPD_requires:
8689       llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
8690     case OMPD_unknown:
8691       llvm_unreachable("Unknown OpenMP directive");
8692     }
8693     break;
8694   case OMPC_firstprivate:
8695   case OMPC_lastprivate:
8696   case OMPC_reduction:
8697   case OMPC_task_reduction:
8698   case OMPC_in_reduction:
8699   case OMPC_linear:
8700   case OMPC_default:
8701   case OMPC_proc_bind:
8702   case OMPC_final:
8703   case OMPC_safelen:
8704   case OMPC_simdlen:
8705   case OMPC_collapse:
8706   case OMPC_private:
8707   case OMPC_shared:
8708   case OMPC_aligned:
8709   case OMPC_copyin:
8710   case OMPC_copyprivate:
8711   case OMPC_ordered:
8712   case OMPC_nowait:
8713   case OMPC_untied:
8714   case OMPC_mergeable:
8715   case OMPC_threadprivate:
8716   case OMPC_flush:
8717   case OMPC_read:
8718   case OMPC_write:
8719   case OMPC_update:
8720   case OMPC_capture:
8721   case OMPC_seq_cst:
8722   case OMPC_depend:
8723   case OMPC_threads:
8724   case OMPC_simd:
8725   case OMPC_map:
8726   case OMPC_priority:
8727   case OMPC_grainsize:
8728   case OMPC_nogroup:
8729   case OMPC_num_tasks:
8730   case OMPC_hint:
8731   case OMPC_defaultmap:
8732   case OMPC_unknown:
8733   case OMPC_uniform:
8734   case OMPC_to:
8735   case OMPC_from:
8736   case OMPC_use_device_ptr:
8737   case OMPC_is_device_ptr:
8738   case OMPC_unified_address:
8739   case OMPC_unified_shared_memory:
8740   case OMPC_reverse_offload:
8741   case OMPC_dynamic_allocators:
8742   case OMPC_atomic_default_mem_order:
8743     llvm_unreachable("Unexpected OpenMP clause.");
8744   }
8745   return CaptureRegion;
8746 }
8747 
8748 OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
8749                                      Expr *Condition, SourceLocation StartLoc,
8750                                      SourceLocation LParenLoc,
8751                                      SourceLocation NameModifierLoc,
8752                                      SourceLocation ColonLoc,
8753                                      SourceLocation EndLoc) {
8754   Expr *ValExpr = Condition;
8755   Stmt *HelperValStmt = nullptr;
8756   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
8757   if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
8758       !Condition->isInstantiationDependent() &&
8759       !Condition->containsUnexpandedParameterPack()) {
8760     ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
8761     if (Val.isInvalid())
8762       return nullptr;
8763 
8764     ValExpr = Val.get();
8765 
8766     OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
8767     CaptureRegion =
8768         getOpenMPCaptureRegionForClause(DKind, OMPC_if, NameModifier);
8769     if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
8770       ValExpr = MakeFullExpr(ValExpr).get();
8771       llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
8772       ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
8773       HelperValStmt = buildPreInits(Context, Captures);
8774     }
8775   }
8776 
8777   return new (Context)
8778       OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
8779                   LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
8780 }
8781 
8782 OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
8783                                         SourceLocation StartLoc,
8784                                         SourceLocation LParenLoc,
8785                                         SourceLocation EndLoc) {
8786   Expr *ValExpr = Condition;
8787   if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
8788       !Condition->isInstantiationDependent() &&
8789       !Condition->containsUnexpandedParameterPack()) {
8790     ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
8791     if (Val.isInvalid())
8792       return nullptr;
8793 
8794     ValExpr = MakeFullExpr(Val.get()).get();
8795   }
8796 
8797   return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
8798 }
8799 ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
8800                                                         Expr *Op) {
8801   if (!Op)
8802     return ExprError();
8803 
8804   class IntConvertDiagnoser : public ICEConvertDiagnoser {
8805   public:
8806     IntConvertDiagnoser()
8807         : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
8808     SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
8809                                          QualType T) override {
8810       return S.Diag(Loc, diag::err_omp_not_integral) << T;
8811     }
8812     SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
8813                                              QualType T) override {
8814       return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
8815     }
8816     SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
8817                                                QualType T,
8818                                                QualType ConvTy) override {
8819       return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
8820     }
8821     SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
8822                                            QualType ConvTy) override {
8823       return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
8824              << ConvTy->isEnumeralType() << ConvTy;
8825     }
8826     SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
8827                                             QualType T) override {
8828       return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
8829     }
8830     SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
8831                                         QualType ConvTy) override {
8832       return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
8833              << ConvTy->isEnumeralType() << ConvTy;
8834     }
8835     SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
8836                                              QualType) override {
8837       llvm_unreachable("conversion functions are permitted");
8838     }
8839   } ConvertDiagnoser;
8840   return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
8841 }
8842 
8843 static bool isNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
8844                                       OpenMPClauseKind CKind,
8845                                       bool StrictlyPositive) {
8846   if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
8847       !ValExpr->isInstantiationDependent()) {
8848     SourceLocation Loc = ValExpr->getExprLoc();
8849     ExprResult Value =
8850         SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
8851     if (Value.isInvalid())
8852       return false;
8853 
8854     ValExpr = Value.get();
8855     // The expression must evaluate to a non-negative integer value.
8856     llvm::APSInt Result;
8857     if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
8858         Result.isSigned() &&
8859         !((!StrictlyPositive && Result.isNonNegative()) ||
8860           (StrictlyPositive && Result.isStrictlyPositive()))) {
8861       SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
8862           << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
8863           << ValExpr->getSourceRange();
8864       return false;
8865     }
8866   }
8867   return true;
8868 }
8869 
8870 OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
8871                                              SourceLocation StartLoc,
8872                                              SourceLocation LParenLoc,
8873                                              SourceLocation EndLoc) {
8874   Expr *ValExpr = NumThreads;
8875   Stmt *HelperValStmt = nullptr;
8876 
8877   // OpenMP [2.5, Restrictions]
8878   //  The num_threads expression must evaluate to a positive integer value.
8879   if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
8880                                  /*StrictlyPositive=*/true))
8881     return nullptr;
8882 
8883   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
8884   OpenMPDirectiveKind CaptureRegion =
8885       getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads);
8886   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
8887     ValExpr = MakeFullExpr(ValExpr).get();
8888     llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
8889     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
8890     HelperValStmt = buildPreInits(Context, Captures);
8891   }
8892 
8893   return new (Context) OMPNumThreadsClause(
8894       ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
8895 }
8896 
8897 ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
8898                                                        OpenMPClauseKind CKind,
8899                                                        bool StrictlyPositive) {
8900   if (!E)
8901     return ExprError();
8902   if (E->isValueDependent() || E->isTypeDependent() ||
8903       E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
8904     return E;
8905   llvm::APSInt Result;
8906   ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
8907   if (ICE.isInvalid())
8908     return ExprError();
8909   if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
8910       (!StrictlyPositive && !Result.isNonNegative())) {
8911     Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
8912         << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
8913         << E->getSourceRange();
8914     return ExprError();
8915   }
8916   if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
8917     Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
8918         << E->getSourceRange();
8919     return ExprError();
8920   }
8921   if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
8922     DSAStack->setAssociatedLoops(Result.getExtValue());
8923   else if (CKind == OMPC_ordered)
8924     DSAStack->setAssociatedLoops(Result.getExtValue());
8925   return ICE;
8926 }
8927 
8928 OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
8929                                           SourceLocation LParenLoc,
8930                                           SourceLocation EndLoc) {
8931   // OpenMP [2.8.1, simd construct, Description]
8932   // The parameter of the safelen clause must be a constant
8933   // positive integer expression.
8934   ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
8935   if (Safelen.isInvalid())
8936     return nullptr;
8937   return new (Context)
8938       OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
8939 }
8940 
8941 OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
8942                                           SourceLocation LParenLoc,
8943                                           SourceLocation EndLoc) {
8944   // OpenMP [2.8.1, simd construct, Description]
8945   // The parameter of the simdlen clause must be a constant
8946   // positive integer expression.
8947   ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
8948   if (Simdlen.isInvalid())
8949     return nullptr;
8950   return new (Context)
8951       OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
8952 }
8953 
8954 OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
8955                                            SourceLocation StartLoc,
8956                                            SourceLocation LParenLoc,
8957                                            SourceLocation EndLoc) {
8958   // OpenMP [2.7.1, loop construct, Description]
8959   // OpenMP [2.8.1, simd construct, Description]
8960   // OpenMP [2.9.6, distribute construct, Description]
8961   // The parameter of the collapse clause must be a constant
8962   // positive integer expression.
8963   ExprResult NumForLoopsResult =
8964       VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
8965   if (NumForLoopsResult.isInvalid())
8966     return nullptr;
8967   return new (Context)
8968       OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
8969 }
8970 
8971 OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
8972                                           SourceLocation EndLoc,
8973                                           SourceLocation LParenLoc,
8974                                           Expr *NumForLoops) {
8975   // OpenMP [2.7.1, loop construct, Description]
8976   // OpenMP [2.8.1, simd construct, Description]
8977   // OpenMP [2.9.6, distribute construct, Description]
8978   // The parameter of the ordered clause must be a constant
8979   // positive integer expression if any.
8980   if (NumForLoops && LParenLoc.isValid()) {
8981     ExprResult NumForLoopsResult =
8982         VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
8983     if (NumForLoopsResult.isInvalid())
8984       return nullptr;
8985     NumForLoops = NumForLoopsResult.get();
8986   } else {
8987     NumForLoops = nullptr;
8988   }
8989   auto *Clause = OMPOrderedClause::Create(
8990       Context, NumForLoops, NumForLoops ? DSAStack->getAssociatedLoops() : 0,
8991       StartLoc, LParenLoc, EndLoc);
8992   DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops, Clause);
8993   return Clause;
8994 }
8995 
8996 OMPClause *Sema::ActOnOpenMPSimpleClause(
8997     OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
8998     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
8999   OMPClause *Res = nullptr;
9000   switch (Kind) {
9001   case OMPC_default:
9002     Res =
9003         ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
9004                                  ArgumentLoc, StartLoc, LParenLoc, EndLoc);
9005     break;
9006   case OMPC_proc_bind:
9007     Res = ActOnOpenMPProcBindClause(
9008         static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
9009         LParenLoc, EndLoc);
9010     break;
9011   case OMPC_atomic_default_mem_order:
9012     Res = ActOnOpenMPAtomicDefaultMemOrderClause(
9013         static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Argument),
9014         ArgumentLoc, StartLoc, LParenLoc, EndLoc);
9015     break;
9016   case OMPC_if:
9017   case OMPC_final:
9018   case OMPC_num_threads:
9019   case OMPC_safelen:
9020   case OMPC_simdlen:
9021   case OMPC_collapse:
9022   case OMPC_schedule:
9023   case OMPC_private:
9024   case OMPC_firstprivate:
9025   case OMPC_lastprivate:
9026   case OMPC_shared:
9027   case OMPC_reduction:
9028   case OMPC_task_reduction:
9029   case OMPC_in_reduction:
9030   case OMPC_linear:
9031   case OMPC_aligned:
9032   case OMPC_copyin:
9033   case OMPC_copyprivate:
9034   case OMPC_ordered:
9035   case OMPC_nowait:
9036   case OMPC_untied:
9037   case OMPC_mergeable:
9038   case OMPC_threadprivate:
9039   case OMPC_flush:
9040   case OMPC_read:
9041   case OMPC_write:
9042   case OMPC_update:
9043   case OMPC_capture:
9044   case OMPC_seq_cst:
9045   case OMPC_depend:
9046   case OMPC_device:
9047   case OMPC_threads:
9048   case OMPC_simd:
9049   case OMPC_map:
9050   case OMPC_num_teams:
9051   case OMPC_thread_limit:
9052   case OMPC_priority:
9053   case OMPC_grainsize:
9054   case OMPC_nogroup:
9055   case OMPC_num_tasks:
9056   case OMPC_hint:
9057   case OMPC_dist_schedule:
9058   case OMPC_defaultmap:
9059   case OMPC_unknown:
9060   case OMPC_uniform:
9061   case OMPC_to:
9062   case OMPC_from:
9063   case OMPC_use_device_ptr:
9064   case OMPC_is_device_ptr:
9065   case OMPC_unified_address:
9066   case OMPC_unified_shared_memory:
9067   case OMPC_reverse_offload:
9068   case OMPC_dynamic_allocators:
9069     llvm_unreachable("Clause is not allowed.");
9070   }
9071   return Res;
9072 }
9073 
9074 static std::string
9075 getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
9076                         ArrayRef<unsigned> Exclude = llvm::None) {
9077   SmallString<256> Buffer;
9078   llvm::raw_svector_ostream Out(Buffer);
9079   unsigned Bound = Last >= 2 ? Last - 2 : 0;
9080   unsigned Skipped = Exclude.size();
9081   auto S = Exclude.begin(), E = Exclude.end();
9082   for (unsigned I = First; I < Last; ++I) {
9083     if (std::find(S, E, I) != E) {
9084       --Skipped;
9085       continue;
9086     }
9087     Out << "'" << getOpenMPSimpleClauseTypeName(K, I) << "'";
9088     if (I == Bound - Skipped)
9089       Out << " or ";
9090     else if (I != Bound + 1 - Skipped)
9091       Out << ", ";
9092   }
9093   return Out.str();
9094 }
9095 
9096 OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
9097                                           SourceLocation KindKwLoc,
9098                                           SourceLocation StartLoc,
9099                                           SourceLocation LParenLoc,
9100                                           SourceLocation EndLoc) {
9101   if (Kind == OMPC_DEFAULT_unknown) {
9102     static_assert(OMPC_DEFAULT_unknown > 0,
9103                   "OMPC_DEFAULT_unknown not greater than 0");
9104     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
9105         << getListOfPossibleValues(OMPC_default, /*First=*/0,
9106                                    /*Last=*/OMPC_DEFAULT_unknown)
9107         << getOpenMPClauseName(OMPC_default);
9108     return nullptr;
9109   }
9110   switch (Kind) {
9111   case OMPC_DEFAULT_none:
9112     DSAStack->setDefaultDSANone(KindKwLoc);
9113     break;
9114   case OMPC_DEFAULT_shared:
9115     DSAStack->setDefaultDSAShared(KindKwLoc);
9116     break;
9117   case OMPC_DEFAULT_unknown:
9118     llvm_unreachable("Clause kind is not allowed.");
9119     break;
9120   }
9121   return new (Context)
9122       OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
9123 }
9124 
9125 OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
9126                                            SourceLocation KindKwLoc,
9127                                            SourceLocation StartLoc,
9128                                            SourceLocation LParenLoc,
9129                                            SourceLocation EndLoc) {
9130   if (Kind == OMPC_PROC_BIND_unknown) {
9131     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
9132         << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
9133                                    /*Last=*/OMPC_PROC_BIND_unknown)
9134         << getOpenMPClauseName(OMPC_proc_bind);
9135     return nullptr;
9136   }
9137   return new (Context)
9138       OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
9139 }
9140 
9141 OMPClause *Sema::ActOnOpenMPAtomicDefaultMemOrderClause(
9142     OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindKwLoc,
9143     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
9144   if (Kind == OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown) {
9145     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
9146         << getListOfPossibleValues(
9147                OMPC_atomic_default_mem_order, /*First=*/0,
9148                /*Last=*/OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown)
9149         << getOpenMPClauseName(OMPC_atomic_default_mem_order);
9150     return nullptr;
9151   }
9152   return new (Context) OMPAtomicDefaultMemOrderClause(Kind, KindKwLoc, StartLoc,
9153                                                       LParenLoc, EndLoc);
9154 }
9155 
9156 OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
9157     OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
9158     SourceLocation StartLoc, SourceLocation LParenLoc,
9159     ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
9160     SourceLocation EndLoc) {
9161   OMPClause *Res = nullptr;
9162   switch (Kind) {
9163   case OMPC_schedule:
9164     enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
9165     assert(Argument.size() == NumberOfElements &&
9166            ArgumentLoc.size() == NumberOfElements);
9167     Res = ActOnOpenMPScheduleClause(
9168         static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
9169         static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
9170         static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
9171         StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
9172         ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
9173     break;
9174   case OMPC_if:
9175     assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
9176     Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
9177                               Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
9178                               DelimLoc, EndLoc);
9179     break;
9180   case OMPC_dist_schedule:
9181     Res = ActOnOpenMPDistScheduleClause(
9182         static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
9183         StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
9184     break;
9185   case OMPC_defaultmap:
9186     enum { Modifier, DefaultmapKind };
9187     Res = ActOnOpenMPDefaultmapClause(
9188         static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
9189         static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
9190         StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
9191         EndLoc);
9192     break;
9193   case OMPC_final:
9194   case OMPC_num_threads:
9195   case OMPC_safelen:
9196   case OMPC_simdlen:
9197   case OMPC_collapse:
9198   case OMPC_default:
9199   case OMPC_proc_bind:
9200   case OMPC_private:
9201   case OMPC_firstprivate:
9202   case OMPC_lastprivate:
9203   case OMPC_shared:
9204   case OMPC_reduction:
9205   case OMPC_task_reduction:
9206   case OMPC_in_reduction:
9207   case OMPC_linear:
9208   case OMPC_aligned:
9209   case OMPC_copyin:
9210   case OMPC_copyprivate:
9211   case OMPC_ordered:
9212   case OMPC_nowait:
9213   case OMPC_untied:
9214   case OMPC_mergeable:
9215   case OMPC_threadprivate:
9216   case OMPC_flush:
9217   case OMPC_read:
9218   case OMPC_write:
9219   case OMPC_update:
9220   case OMPC_capture:
9221   case OMPC_seq_cst:
9222   case OMPC_depend:
9223   case OMPC_device:
9224   case OMPC_threads:
9225   case OMPC_simd:
9226   case OMPC_map:
9227   case OMPC_num_teams:
9228   case OMPC_thread_limit:
9229   case OMPC_priority:
9230   case OMPC_grainsize:
9231   case OMPC_nogroup:
9232   case OMPC_num_tasks:
9233   case OMPC_hint:
9234   case OMPC_unknown:
9235   case OMPC_uniform:
9236   case OMPC_to:
9237   case OMPC_from:
9238   case OMPC_use_device_ptr:
9239   case OMPC_is_device_ptr:
9240   case OMPC_unified_address:
9241   case OMPC_unified_shared_memory:
9242   case OMPC_reverse_offload:
9243   case OMPC_dynamic_allocators:
9244   case OMPC_atomic_default_mem_order:
9245     llvm_unreachable("Clause is not allowed.");
9246   }
9247   return Res;
9248 }
9249 
9250 static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
9251                                    OpenMPScheduleClauseModifier M2,
9252                                    SourceLocation M1Loc, SourceLocation M2Loc) {
9253   if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
9254     SmallVector<unsigned, 2> Excluded;
9255     if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
9256       Excluded.push_back(M2);
9257     if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
9258       Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
9259     if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
9260       Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
9261     S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
9262         << getListOfPossibleValues(OMPC_schedule,
9263                                    /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
9264                                    /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
9265                                    Excluded)
9266         << getOpenMPClauseName(OMPC_schedule);
9267     return true;
9268   }
9269   return false;
9270 }
9271 
9272 OMPClause *Sema::ActOnOpenMPScheduleClause(
9273     OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
9274     OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
9275     SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
9276     SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
9277   if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
9278       checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
9279     return nullptr;
9280   // OpenMP, 2.7.1, Loop Construct, Restrictions
9281   // Either the monotonic modifier or the nonmonotonic modifier can be specified
9282   // but not both.
9283   if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
9284       (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
9285        M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
9286       (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
9287        M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
9288     Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
9289         << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
9290         << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
9291     return nullptr;
9292   }
9293   if (Kind == OMPC_SCHEDULE_unknown) {
9294     std::string Values;
9295     if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
9296       unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
9297       Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
9298                                        /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
9299                                        Exclude);
9300     } else {
9301       Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
9302                                        /*Last=*/OMPC_SCHEDULE_unknown);
9303     }
9304     Diag(KindLoc, diag::err_omp_unexpected_clause_value)
9305         << Values << getOpenMPClauseName(OMPC_schedule);
9306     return nullptr;
9307   }
9308   // OpenMP, 2.7.1, Loop Construct, Restrictions
9309   // The nonmonotonic modifier can only be specified with schedule(dynamic) or
9310   // schedule(guided).
9311   if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
9312        M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
9313       Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
9314     Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
9315          diag::err_omp_schedule_nonmonotonic_static);
9316     return nullptr;
9317   }
9318   Expr *ValExpr = ChunkSize;
9319   Stmt *HelperValStmt = nullptr;
9320   if (ChunkSize) {
9321     if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
9322         !ChunkSize->isInstantiationDependent() &&
9323         !ChunkSize->containsUnexpandedParameterPack()) {
9324       SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
9325       ExprResult Val =
9326           PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
9327       if (Val.isInvalid())
9328         return nullptr;
9329 
9330       ValExpr = Val.get();
9331 
9332       // OpenMP [2.7.1, Restrictions]
9333       //  chunk_size must be a loop invariant integer expression with a positive
9334       //  value.
9335       llvm::APSInt Result;
9336       if (ValExpr->isIntegerConstantExpr(Result, Context)) {
9337         if (Result.isSigned() && !Result.isStrictlyPositive()) {
9338           Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
9339               << "schedule" << 1 << ChunkSize->getSourceRange();
9340           return nullptr;
9341         }
9342       } else if (getOpenMPCaptureRegionForClause(
9343                      DSAStack->getCurrentDirective(), OMPC_schedule) !=
9344                      OMPD_unknown &&
9345                  !CurContext->isDependentContext()) {
9346         ValExpr = MakeFullExpr(ValExpr).get();
9347         llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
9348         ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
9349         HelperValStmt = buildPreInits(Context, Captures);
9350       }
9351     }
9352   }
9353 
9354   return new (Context)
9355       OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
9356                         ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
9357 }
9358 
9359 OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
9360                                    SourceLocation StartLoc,
9361                                    SourceLocation EndLoc) {
9362   OMPClause *Res = nullptr;
9363   switch (Kind) {
9364   case OMPC_ordered:
9365     Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
9366     break;
9367   case OMPC_nowait:
9368     Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
9369     break;
9370   case OMPC_untied:
9371     Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
9372     break;
9373   case OMPC_mergeable:
9374     Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
9375     break;
9376   case OMPC_read:
9377     Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
9378     break;
9379   case OMPC_write:
9380     Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
9381     break;
9382   case OMPC_update:
9383     Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
9384     break;
9385   case OMPC_capture:
9386     Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
9387     break;
9388   case OMPC_seq_cst:
9389     Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
9390     break;
9391   case OMPC_threads:
9392     Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
9393     break;
9394   case OMPC_simd:
9395     Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
9396     break;
9397   case OMPC_nogroup:
9398     Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
9399     break;
9400   case OMPC_unified_address:
9401     Res = ActOnOpenMPUnifiedAddressClause(StartLoc, EndLoc);
9402     break;
9403   case OMPC_unified_shared_memory:
9404     Res = ActOnOpenMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
9405     break;
9406   case OMPC_reverse_offload:
9407     Res = ActOnOpenMPReverseOffloadClause(StartLoc, EndLoc);
9408     break;
9409   case OMPC_dynamic_allocators:
9410     Res = ActOnOpenMPDynamicAllocatorsClause(StartLoc, EndLoc);
9411     break;
9412   case OMPC_if:
9413   case OMPC_final:
9414   case OMPC_num_threads:
9415   case OMPC_safelen:
9416   case OMPC_simdlen:
9417   case OMPC_collapse:
9418   case OMPC_schedule:
9419   case OMPC_private:
9420   case OMPC_firstprivate:
9421   case OMPC_lastprivate:
9422   case OMPC_shared:
9423   case OMPC_reduction:
9424   case OMPC_task_reduction:
9425   case OMPC_in_reduction:
9426   case OMPC_linear:
9427   case OMPC_aligned:
9428   case OMPC_copyin:
9429   case OMPC_copyprivate:
9430   case OMPC_default:
9431   case OMPC_proc_bind:
9432   case OMPC_threadprivate:
9433   case OMPC_flush:
9434   case OMPC_depend:
9435   case OMPC_device:
9436   case OMPC_map:
9437   case OMPC_num_teams:
9438   case OMPC_thread_limit:
9439   case OMPC_priority:
9440   case OMPC_grainsize:
9441   case OMPC_num_tasks:
9442   case OMPC_hint:
9443   case OMPC_dist_schedule:
9444   case OMPC_defaultmap:
9445   case OMPC_unknown:
9446   case OMPC_uniform:
9447   case OMPC_to:
9448   case OMPC_from:
9449   case OMPC_use_device_ptr:
9450   case OMPC_is_device_ptr:
9451   case OMPC_atomic_default_mem_order:
9452     llvm_unreachable("Clause is not allowed.");
9453   }
9454   return Res;
9455 }
9456 
9457 OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
9458                                          SourceLocation EndLoc) {
9459   DSAStack->setNowaitRegion();
9460   return new (Context) OMPNowaitClause(StartLoc, EndLoc);
9461 }
9462 
9463 OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
9464                                          SourceLocation EndLoc) {
9465   return new (Context) OMPUntiedClause(StartLoc, EndLoc);
9466 }
9467 
9468 OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
9469                                             SourceLocation EndLoc) {
9470   return new (Context) OMPMergeableClause(StartLoc, EndLoc);
9471 }
9472 
9473 OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
9474                                        SourceLocation EndLoc) {
9475   return new (Context) OMPReadClause(StartLoc, EndLoc);
9476 }
9477 
9478 OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
9479                                         SourceLocation EndLoc) {
9480   return new (Context) OMPWriteClause(StartLoc, EndLoc);
9481 }
9482 
9483 OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
9484                                          SourceLocation EndLoc) {
9485   return new (Context) OMPUpdateClause(StartLoc, EndLoc);
9486 }
9487 
9488 OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
9489                                           SourceLocation EndLoc) {
9490   return new (Context) OMPCaptureClause(StartLoc, EndLoc);
9491 }
9492 
9493 OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
9494                                          SourceLocation EndLoc) {
9495   return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
9496 }
9497 
9498 OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
9499                                           SourceLocation EndLoc) {
9500   return new (Context) OMPThreadsClause(StartLoc, EndLoc);
9501 }
9502 
9503 OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
9504                                        SourceLocation EndLoc) {
9505   return new (Context) OMPSIMDClause(StartLoc, EndLoc);
9506 }
9507 
9508 OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
9509                                           SourceLocation EndLoc) {
9510   return new (Context) OMPNogroupClause(StartLoc, EndLoc);
9511 }
9512 
9513 OMPClause *Sema::ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc,
9514                                                  SourceLocation EndLoc) {
9515   return new (Context) OMPUnifiedAddressClause(StartLoc, EndLoc);
9516 }
9517 
9518 OMPClause *Sema::ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc,
9519                                                       SourceLocation EndLoc) {
9520   return new (Context) OMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
9521 }
9522 
9523 OMPClause *Sema::ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc,
9524                                                  SourceLocation EndLoc) {
9525   return new (Context) OMPReverseOffloadClause(StartLoc, EndLoc);
9526 }
9527 
9528 OMPClause *Sema::ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc,
9529                                                     SourceLocation EndLoc) {
9530   return new (Context) OMPDynamicAllocatorsClause(StartLoc, EndLoc);
9531 }
9532 
9533 OMPClause *Sema::ActOnOpenMPVarListClause(
9534     OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
9535     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
9536     SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
9537     const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
9538     OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier,
9539     OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
9540     SourceLocation DepLinMapLoc) {
9541   OMPClause *Res = nullptr;
9542   switch (Kind) {
9543   case OMPC_private:
9544     Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
9545     break;
9546   case OMPC_firstprivate:
9547     Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
9548     break;
9549   case OMPC_lastprivate:
9550     Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
9551     break;
9552   case OMPC_shared:
9553     Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
9554     break;
9555   case OMPC_reduction:
9556     Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
9557                                      EndLoc, ReductionIdScopeSpec, ReductionId);
9558     break;
9559   case OMPC_task_reduction:
9560     Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
9561                                          EndLoc, ReductionIdScopeSpec,
9562                                          ReductionId);
9563     break;
9564   case OMPC_in_reduction:
9565     Res =
9566         ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
9567                                      EndLoc, ReductionIdScopeSpec, ReductionId);
9568     break;
9569   case OMPC_linear:
9570     Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
9571                                   LinKind, DepLinMapLoc, ColonLoc, EndLoc);
9572     break;
9573   case OMPC_aligned:
9574     Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
9575                                    ColonLoc, EndLoc);
9576     break;
9577   case OMPC_copyin:
9578     Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
9579     break;
9580   case OMPC_copyprivate:
9581     Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
9582     break;
9583   case OMPC_flush:
9584     Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
9585     break;
9586   case OMPC_depend:
9587     Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
9588                                   StartLoc, LParenLoc, EndLoc);
9589     break;
9590   case OMPC_map:
9591     Res = ActOnOpenMPMapClause(MapTypeModifier, MapType, IsMapTypeImplicit,
9592                                DepLinMapLoc, ColonLoc, VarList, StartLoc,
9593                                LParenLoc, EndLoc);
9594     break;
9595   case OMPC_to:
9596     Res = ActOnOpenMPToClause(VarList, StartLoc, LParenLoc, EndLoc);
9597     break;
9598   case OMPC_from:
9599     Res = ActOnOpenMPFromClause(VarList, StartLoc, LParenLoc, EndLoc);
9600     break;
9601   case OMPC_use_device_ptr:
9602     Res = ActOnOpenMPUseDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
9603     break;
9604   case OMPC_is_device_ptr:
9605     Res = ActOnOpenMPIsDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
9606     break;
9607   case OMPC_if:
9608   case OMPC_final:
9609   case OMPC_num_threads:
9610   case OMPC_safelen:
9611   case OMPC_simdlen:
9612   case OMPC_collapse:
9613   case OMPC_default:
9614   case OMPC_proc_bind:
9615   case OMPC_schedule:
9616   case OMPC_ordered:
9617   case OMPC_nowait:
9618   case OMPC_untied:
9619   case OMPC_mergeable:
9620   case OMPC_threadprivate:
9621   case OMPC_read:
9622   case OMPC_write:
9623   case OMPC_update:
9624   case OMPC_capture:
9625   case OMPC_seq_cst:
9626   case OMPC_device:
9627   case OMPC_threads:
9628   case OMPC_simd:
9629   case OMPC_num_teams:
9630   case OMPC_thread_limit:
9631   case OMPC_priority:
9632   case OMPC_grainsize:
9633   case OMPC_nogroup:
9634   case OMPC_num_tasks:
9635   case OMPC_hint:
9636   case OMPC_dist_schedule:
9637   case OMPC_defaultmap:
9638   case OMPC_unknown:
9639   case OMPC_uniform:
9640   case OMPC_unified_address:
9641   case OMPC_unified_shared_memory:
9642   case OMPC_reverse_offload:
9643   case OMPC_dynamic_allocators:
9644   case OMPC_atomic_default_mem_order:
9645     llvm_unreachable("Clause is not allowed.");
9646   }
9647   return Res;
9648 }
9649 
9650 ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
9651                                        ExprObjectKind OK, SourceLocation Loc) {
9652   ExprResult Res = BuildDeclRefExpr(
9653       Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
9654   if (!Res.isUsable())
9655     return ExprError();
9656   if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
9657     Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
9658     if (!Res.isUsable())
9659       return ExprError();
9660   }
9661   if (VK != VK_LValue && Res.get()->isGLValue()) {
9662     Res = DefaultLvalueConversion(Res.get());
9663     if (!Res.isUsable())
9664       return ExprError();
9665   }
9666   return Res;
9667 }
9668 
9669 static std::pair<ValueDecl *, bool>
9670 getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
9671                SourceRange &ERange, bool AllowArraySection = false) {
9672   if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
9673       RefExpr->containsUnexpandedParameterPack())
9674     return std::make_pair(nullptr, true);
9675 
9676   // OpenMP [3.1, C/C++]
9677   //  A list item is a variable name.
9678   // OpenMP  [2.9.3.3, Restrictions, p.1]
9679   //  A variable that is part of another variable (as an array or
9680   //  structure element) cannot appear in a private clause.
9681   RefExpr = RefExpr->IgnoreParens();
9682   enum {
9683     NoArrayExpr = -1,
9684     ArraySubscript = 0,
9685     OMPArraySection = 1
9686   } IsArrayExpr = NoArrayExpr;
9687   if (AllowArraySection) {
9688     if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
9689       Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
9690       while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
9691         Base = TempASE->getBase()->IgnoreParenImpCasts();
9692       RefExpr = Base;
9693       IsArrayExpr = ArraySubscript;
9694     } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
9695       Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
9696       while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
9697         Base = TempOASE->getBase()->IgnoreParenImpCasts();
9698       while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
9699         Base = TempASE->getBase()->IgnoreParenImpCasts();
9700       RefExpr = Base;
9701       IsArrayExpr = OMPArraySection;
9702     }
9703   }
9704   ELoc = RefExpr->getExprLoc();
9705   ERange = RefExpr->getSourceRange();
9706   RefExpr = RefExpr->IgnoreParenImpCasts();
9707   auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
9708   auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
9709   if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
9710       (S.getCurrentThisType().isNull() || !ME ||
9711        !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
9712        !isa<FieldDecl>(ME->getMemberDecl()))) {
9713     if (IsArrayExpr != NoArrayExpr) {
9714       S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
9715                                                          << ERange;
9716     } else {
9717       S.Diag(ELoc,
9718              AllowArraySection
9719                  ? diag::err_omp_expected_var_name_member_expr_or_array_item
9720                  : diag::err_omp_expected_var_name_member_expr)
9721           << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
9722     }
9723     return std::make_pair(nullptr, false);
9724   }
9725   return std::make_pair(
9726       getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false);
9727 }
9728 
9729 OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
9730                                           SourceLocation StartLoc,
9731                                           SourceLocation LParenLoc,
9732                                           SourceLocation EndLoc) {
9733   SmallVector<Expr *, 8> Vars;
9734   SmallVector<Expr *, 8> PrivateCopies;
9735   for (Expr *RefExpr : VarList) {
9736     assert(RefExpr && "NULL expr in OpenMP private clause.");
9737     SourceLocation ELoc;
9738     SourceRange ERange;
9739     Expr *SimpleRefExpr = RefExpr;
9740     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
9741     if (Res.second) {
9742       // It will be analyzed later.
9743       Vars.push_back(RefExpr);
9744       PrivateCopies.push_back(nullptr);
9745     }
9746     ValueDecl *D = Res.first;
9747     if (!D)
9748       continue;
9749 
9750     QualType Type = D->getType();
9751     auto *VD = dyn_cast<VarDecl>(D);
9752 
9753     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
9754     //  A variable that appears in a private clause must not have an incomplete
9755     //  type or a reference type.
9756     if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
9757       continue;
9758     Type = Type.getNonReferenceType();
9759 
9760     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
9761     // in a Construct]
9762     //  Variables with the predetermined data-sharing attributes may not be
9763     //  listed in data-sharing attributes clauses, except for the cases
9764     //  listed below. For these exceptions only, listing a predetermined
9765     //  variable in a data-sharing attribute clause is allowed and overrides
9766     //  the variable's predetermined data-sharing attributes.
9767     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
9768     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
9769       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
9770                                           << getOpenMPClauseName(OMPC_private);
9771       reportOriginalDsa(*this, DSAStack, D, DVar);
9772       continue;
9773     }
9774 
9775     OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
9776     // Variably modified types are not supported for tasks.
9777     if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
9778         isOpenMPTaskingDirective(CurrDir)) {
9779       Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
9780           << getOpenMPClauseName(OMPC_private) << Type
9781           << getOpenMPDirectiveName(CurrDir);
9782       bool IsDecl =
9783           !VD ||
9784           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
9785       Diag(D->getLocation(),
9786            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
9787           << D;
9788       continue;
9789     }
9790 
9791     // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
9792     // A list item cannot appear in both a map clause and a data-sharing
9793     // attribute clause on the same construct
9794     if (isOpenMPTargetExecutionDirective(CurrDir)) {
9795       OpenMPClauseKind ConflictKind;
9796       if (DSAStack->checkMappableExprComponentListsForDecl(
9797               VD, /*CurrentRegionOnly=*/true,
9798               [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
9799                   OpenMPClauseKind WhereFoundClauseKind) -> bool {
9800                 ConflictKind = WhereFoundClauseKind;
9801                 return true;
9802               })) {
9803         Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
9804             << getOpenMPClauseName(OMPC_private)
9805             << getOpenMPClauseName(ConflictKind)
9806             << getOpenMPDirectiveName(CurrDir);
9807         reportOriginalDsa(*this, DSAStack, D, DVar);
9808         continue;
9809       }
9810     }
9811 
9812     // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
9813     //  A variable of class type (or array thereof) that appears in a private
9814     //  clause requires an accessible, unambiguous default constructor for the
9815     //  class type.
9816     // Generate helper private variable and initialize it with the default
9817     // value. The address of the original variable is replaced by the address of
9818     // the new private variable in CodeGen. This new variable is not added to
9819     // IdResolver, so the code in the OpenMP region uses original variable for
9820     // proper diagnostics.
9821     Type = Type.getUnqualifiedType();
9822     VarDecl *VDPrivate =
9823         buildVarDecl(*this, ELoc, Type, D->getName(),
9824                      D->hasAttrs() ? &D->getAttrs() : nullptr,
9825                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
9826     ActOnUninitializedDecl(VDPrivate);
9827     if (VDPrivate->isInvalidDecl())
9828       continue;
9829     DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
9830         *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
9831 
9832     DeclRefExpr *Ref = nullptr;
9833     if (!VD && !CurContext->isDependentContext())
9834       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
9835     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
9836     Vars.push_back((VD || CurContext->isDependentContext())
9837                        ? RefExpr->IgnoreParens()
9838                        : Ref);
9839     PrivateCopies.push_back(VDPrivateRefExpr);
9840   }
9841 
9842   if (Vars.empty())
9843     return nullptr;
9844 
9845   return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
9846                                   PrivateCopies);
9847 }
9848 
9849 namespace {
9850 class DiagsUninitializedSeveretyRAII {
9851 private:
9852   DiagnosticsEngine &Diags;
9853   SourceLocation SavedLoc;
9854   bool IsIgnored = false;
9855 
9856 public:
9857   DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
9858                                  bool IsIgnored)
9859       : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
9860     if (!IsIgnored) {
9861       Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
9862                         /*Map*/ diag::Severity::Ignored, Loc);
9863     }
9864   }
9865   ~DiagsUninitializedSeveretyRAII() {
9866     if (!IsIgnored)
9867       Diags.popMappings(SavedLoc);
9868   }
9869 };
9870 }
9871 
9872 OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
9873                                                SourceLocation StartLoc,
9874                                                SourceLocation LParenLoc,
9875                                                SourceLocation EndLoc) {
9876   SmallVector<Expr *, 8> Vars;
9877   SmallVector<Expr *, 8> PrivateCopies;
9878   SmallVector<Expr *, 8> Inits;
9879   SmallVector<Decl *, 4> ExprCaptures;
9880   bool IsImplicitClause =
9881       StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
9882   SourceLocation ImplicitClauseLoc = DSAStack->getConstructLoc();
9883 
9884   for (Expr *RefExpr : VarList) {
9885     assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
9886     SourceLocation ELoc;
9887     SourceRange ERange;
9888     Expr *SimpleRefExpr = RefExpr;
9889     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
9890     if (Res.second) {
9891       // It will be analyzed later.
9892       Vars.push_back(RefExpr);
9893       PrivateCopies.push_back(nullptr);
9894       Inits.push_back(nullptr);
9895     }
9896     ValueDecl *D = Res.first;
9897     if (!D)
9898       continue;
9899 
9900     ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
9901     QualType Type = D->getType();
9902     auto *VD = dyn_cast<VarDecl>(D);
9903 
9904     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
9905     //  A variable that appears in a private clause must not have an incomplete
9906     //  type or a reference type.
9907     if (RequireCompleteType(ELoc, Type,
9908                             diag::err_omp_firstprivate_incomplete_type))
9909       continue;
9910     Type = Type.getNonReferenceType();
9911 
9912     // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
9913     //  A variable of class type (or array thereof) that appears in a private
9914     //  clause requires an accessible, unambiguous copy constructor for the
9915     //  class type.
9916     QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
9917 
9918     // If an implicit firstprivate variable found it was checked already.
9919     DSAStackTy::DSAVarData TopDVar;
9920     if (!IsImplicitClause) {
9921       DSAStackTy::DSAVarData DVar =
9922           DSAStack->getTopDSA(D, /*FromParent=*/false);
9923       TopDVar = DVar;
9924       OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
9925       bool IsConstant = ElemType.isConstant(Context);
9926       // OpenMP [2.4.13, Data-sharing Attribute Clauses]
9927       //  A list item that specifies a given variable may not appear in more
9928       // than one clause on the same directive, except that a variable may be
9929       //  specified in both firstprivate and lastprivate clauses.
9930       // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
9931       // A list item may appear in a firstprivate or lastprivate clause but not
9932       // both.
9933       if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
9934           (isOpenMPDistributeDirective(CurrDir) ||
9935            DVar.CKind != OMPC_lastprivate) &&
9936           DVar.RefExpr) {
9937         Diag(ELoc, diag::err_omp_wrong_dsa)
9938             << getOpenMPClauseName(DVar.CKind)
9939             << getOpenMPClauseName(OMPC_firstprivate);
9940         reportOriginalDsa(*this, DSAStack, D, DVar);
9941         continue;
9942       }
9943 
9944       // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
9945       // in a Construct]
9946       //  Variables with the predetermined data-sharing attributes may not be
9947       //  listed in data-sharing attributes clauses, except for the cases
9948       //  listed below. For these exceptions only, listing a predetermined
9949       //  variable in a data-sharing attribute clause is allowed and overrides
9950       //  the variable's predetermined data-sharing attributes.
9951       // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
9952       // in a Construct, C/C++, p.2]
9953       //  Variables with const-qualified type having no mutable member may be
9954       //  listed in a firstprivate clause, even if they are static data members.
9955       if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
9956           DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
9957         Diag(ELoc, diag::err_omp_wrong_dsa)
9958             << getOpenMPClauseName(DVar.CKind)
9959             << getOpenMPClauseName(OMPC_firstprivate);
9960         reportOriginalDsa(*this, DSAStack, D, DVar);
9961         continue;
9962       }
9963 
9964       // OpenMP [2.9.3.4, Restrictions, p.2]
9965       //  A list item that is private within a parallel region must not appear
9966       //  in a firstprivate clause on a worksharing construct if any of the
9967       //  worksharing regions arising from the worksharing construct ever bind
9968       //  to any of the parallel regions arising from the parallel construct.
9969       // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
9970       // A list item that is private within a teams region must not appear in a
9971       // firstprivate clause on a distribute construct if any of the distribute
9972       // regions arising from the distribute construct ever bind to any of the
9973       // teams regions arising from the teams construct.
9974       // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
9975       // A list item that appears in a reduction clause of a teams construct
9976       // must not appear in a firstprivate clause on a distribute construct if
9977       // any of the distribute regions arising from the distribute construct
9978       // ever bind to any of the teams regions arising from the teams construct.
9979       if ((isOpenMPWorksharingDirective(CurrDir) ||
9980            isOpenMPDistributeDirective(CurrDir)) &&
9981           !isOpenMPParallelDirective(CurrDir) &&
9982           !isOpenMPTeamsDirective(CurrDir)) {
9983         DVar = DSAStack->getImplicitDSA(D, true);
9984         if (DVar.CKind != OMPC_shared &&
9985             (isOpenMPParallelDirective(DVar.DKind) ||
9986              isOpenMPTeamsDirective(DVar.DKind) ||
9987              DVar.DKind == OMPD_unknown)) {
9988           Diag(ELoc, diag::err_omp_required_access)
9989               << getOpenMPClauseName(OMPC_firstprivate)
9990               << getOpenMPClauseName(OMPC_shared);
9991           reportOriginalDsa(*this, DSAStack, D, DVar);
9992           continue;
9993         }
9994       }
9995       // OpenMP [2.9.3.4, Restrictions, p.3]
9996       //  A list item that appears in a reduction clause of a parallel construct
9997       //  must not appear in a firstprivate clause on a worksharing or task
9998       //  construct if any of the worksharing or task regions arising from the
9999       //  worksharing or task construct ever bind to any of the parallel regions
10000       //  arising from the parallel construct.
10001       // OpenMP [2.9.3.4, Restrictions, p.4]
10002       //  A list item that appears in a reduction clause in worksharing
10003       //  construct must not appear in a firstprivate clause in a task construct
10004       //  encountered during execution of any of the worksharing regions arising
10005       //  from the worksharing construct.
10006       if (isOpenMPTaskingDirective(CurrDir)) {
10007         DVar = DSAStack->hasInnermostDSA(
10008             D, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
10009             [](OpenMPDirectiveKind K) {
10010               return isOpenMPParallelDirective(K) ||
10011                      isOpenMPWorksharingDirective(K) ||
10012                      isOpenMPTeamsDirective(K);
10013             },
10014             /*FromParent=*/true);
10015         if (DVar.CKind == OMPC_reduction &&
10016             (isOpenMPParallelDirective(DVar.DKind) ||
10017              isOpenMPWorksharingDirective(DVar.DKind) ||
10018              isOpenMPTeamsDirective(DVar.DKind))) {
10019           Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
10020               << getOpenMPDirectiveName(DVar.DKind);
10021           reportOriginalDsa(*this, DSAStack, D, DVar);
10022           continue;
10023         }
10024       }
10025 
10026       // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
10027       // A list item cannot appear in both a map clause and a data-sharing
10028       // attribute clause on the same construct
10029       if (isOpenMPTargetExecutionDirective(CurrDir)) {
10030         OpenMPClauseKind ConflictKind;
10031         if (DSAStack->checkMappableExprComponentListsForDecl(
10032                 VD, /*CurrentRegionOnly=*/true,
10033                 [&ConflictKind](
10034                     OMPClauseMappableExprCommon::MappableExprComponentListRef,
10035                     OpenMPClauseKind WhereFoundClauseKind) {
10036                   ConflictKind = WhereFoundClauseKind;
10037                   return true;
10038                 })) {
10039           Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
10040               << getOpenMPClauseName(OMPC_firstprivate)
10041               << getOpenMPClauseName(ConflictKind)
10042               << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
10043           reportOriginalDsa(*this, DSAStack, D, DVar);
10044           continue;
10045         }
10046       }
10047     }
10048 
10049     // Variably modified types are not supported for tasks.
10050     if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
10051         isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
10052       Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
10053           << getOpenMPClauseName(OMPC_firstprivate) << Type
10054           << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
10055       bool IsDecl =
10056           !VD ||
10057           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
10058       Diag(D->getLocation(),
10059            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
10060           << D;
10061       continue;
10062     }
10063 
10064     Type = Type.getUnqualifiedType();
10065     VarDecl *VDPrivate =
10066         buildVarDecl(*this, ELoc, Type, D->getName(),
10067                      D->hasAttrs() ? &D->getAttrs() : nullptr,
10068                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
10069     // Generate helper private variable and initialize it with the value of the
10070     // original variable. The address of the original variable is replaced by
10071     // the address of the new private variable in the CodeGen. This new variable
10072     // is not added to IdResolver, so the code in the OpenMP region uses
10073     // original variable for proper diagnostics and variable capturing.
10074     Expr *VDInitRefExpr = nullptr;
10075     // For arrays generate initializer for single element and replace it by the
10076     // original array element in CodeGen.
10077     if (Type->isArrayType()) {
10078       VarDecl *VDInit =
10079           buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
10080       VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
10081       Expr *Init = DefaultLvalueConversion(VDInitRefExpr).get();
10082       ElemType = ElemType.getUnqualifiedType();
10083       VarDecl *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
10084                                          ".firstprivate.temp");
10085       InitializedEntity Entity =
10086           InitializedEntity::InitializeVariable(VDInitTemp);
10087       InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
10088 
10089       InitializationSequence InitSeq(*this, Entity, Kind, Init);
10090       ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
10091       if (Result.isInvalid())
10092         VDPrivate->setInvalidDecl();
10093       else
10094         VDPrivate->setInit(Result.getAs<Expr>());
10095       // Remove temp variable declaration.
10096       Context.Deallocate(VDInitTemp);
10097     } else {
10098       VarDecl *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
10099                                      ".firstprivate.temp");
10100       VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
10101                                        RefExpr->getExprLoc());
10102       AddInitializerToDecl(VDPrivate,
10103                            DefaultLvalueConversion(VDInitRefExpr).get(),
10104                            /*DirectInit=*/false);
10105     }
10106     if (VDPrivate->isInvalidDecl()) {
10107       if (IsImplicitClause) {
10108         Diag(RefExpr->getExprLoc(),
10109              diag::note_omp_task_predetermined_firstprivate_here);
10110       }
10111       continue;
10112     }
10113     CurContext->addDecl(VDPrivate);
10114     DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
10115         *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
10116         RefExpr->getExprLoc());
10117     DeclRefExpr *Ref = nullptr;
10118     if (!VD && !CurContext->isDependentContext()) {
10119       if (TopDVar.CKind == OMPC_lastprivate) {
10120         Ref = TopDVar.PrivateCopy;
10121       } else {
10122         Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
10123         if (!isOpenMPCapturedDecl(D))
10124           ExprCaptures.push_back(Ref->getDecl());
10125       }
10126     }
10127     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
10128     Vars.push_back((VD || CurContext->isDependentContext())
10129                        ? RefExpr->IgnoreParens()
10130                        : Ref);
10131     PrivateCopies.push_back(VDPrivateRefExpr);
10132     Inits.push_back(VDInitRefExpr);
10133   }
10134 
10135   if (Vars.empty())
10136     return nullptr;
10137 
10138   return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
10139                                        Vars, PrivateCopies, Inits,
10140                                        buildPreInits(Context, ExprCaptures));
10141 }
10142 
10143 OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
10144                                               SourceLocation StartLoc,
10145                                               SourceLocation LParenLoc,
10146                                               SourceLocation EndLoc) {
10147   SmallVector<Expr *, 8> Vars;
10148   SmallVector<Expr *, 8> SrcExprs;
10149   SmallVector<Expr *, 8> DstExprs;
10150   SmallVector<Expr *, 8> AssignmentOps;
10151   SmallVector<Decl *, 4> ExprCaptures;
10152   SmallVector<Expr *, 4> ExprPostUpdates;
10153   for (Expr *RefExpr : VarList) {
10154     assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
10155     SourceLocation ELoc;
10156     SourceRange ERange;
10157     Expr *SimpleRefExpr = RefExpr;
10158     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
10159     if (Res.second) {
10160       // It will be analyzed later.
10161       Vars.push_back(RefExpr);
10162       SrcExprs.push_back(nullptr);
10163       DstExprs.push_back(nullptr);
10164       AssignmentOps.push_back(nullptr);
10165     }
10166     ValueDecl *D = Res.first;
10167     if (!D)
10168       continue;
10169 
10170     QualType Type = D->getType();
10171     auto *VD = dyn_cast<VarDecl>(D);
10172 
10173     // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
10174     //  A variable that appears in a lastprivate clause must not have an
10175     //  incomplete type or a reference type.
10176     if (RequireCompleteType(ELoc, Type,
10177                             diag::err_omp_lastprivate_incomplete_type))
10178       continue;
10179     Type = Type.getNonReferenceType();
10180 
10181     OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
10182     // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
10183     // in a Construct]
10184     //  Variables with the predetermined data-sharing attributes may not be
10185     //  listed in data-sharing attributes clauses, except for the cases
10186     //  listed below.
10187     // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
10188     // A list item may appear in a firstprivate or lastprivate clause but not
10189     // both.
10190     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
10191     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
10192         (isOpenMPDistributeDirective(CurrDir) ||
10193          DVar.CKind != OMPC_firstprivate) &&
10194         (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
10195       Diag(ELoc, diag::err_omp_wrong_dsa)
10196           << getOpenMPClauseName(DVar.CKind)
10197           << getOpenMPClauseName(OMPC_lastprivate);
10198       reportOriginalDsa(*this, DSAStack, D, DVar);
10199       continue;
10200     }
10201 
10202     // OpenMP [2.14.3.5, Restrictions, p.2]
10203     // A list item that is private within a parallel region, or that appears in
10204     // the reduction clause of a parallel construct, must not appear in a
10205     // lastprivate clause on a worksharing construct if any of the corresponding
10206     // worksharing regions ever binds to any of the corresponding parallel
10207     // regions.
10208     DSAStackTy::DSAVarData TopDVar = DVar;
10209     if (isOpenMPWorksharingDirective(CurrDir) &&
10210         !isOpenMPParallelDirective(CurrDir) &&
10211         !isOpenMPTeamsDirective(CurrDir)) {
10212       DVar = DSAStack->getImplicitDSA(D, true);
10213       if (DVar.CKind != OMPC_shared) {
10214         Diag(ELoc, diag::err_omp_required_access)
10215             << getOpenMPClauseName(OMPC_lastprivate)
10216             << getOpenMPClauseName(OMPC_shared);
10217         reportOriginalDsa(*this, DSAStack, D, DVar);
10218         continue;
10219       }
10220     }
10221 
10222     // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
10223     //  A variable of class type (or array thereof) that appears in a
10224     //  lastprivate clause requires an accessible, unambiguous default
10225     //  constructor for the class type, unless the list item is also specified
10226     //  in a firstprivate clause.
10227     //  A variable of class type (or array thereof) that appears in a
10228     //  lastprivate clause requires an accessible, unambiguous copy assignment
10229     //  operator for the class type.
10230     Type = Context.getBaseElementType(Type).getNonReferenceType();
10231     VarDecl *SrcVD = buildVarDecl(*this, ERange.getBegin(),
10232                                   Type.getUnqualifiedType(), ".lastprivate.src",
10233                                   D->hasAttrs() ? &D->getAttrs() : nullptr);
10234     DeclRefExpr *PseudoSrcExpr =
10235         buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
10236     VarDecl *DstVD =
10237         buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
10238                      D->hasAttrs() ? &D->getAttrs() : nullptr);
10239     DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
10240     // For arrays generate assignment operation for single element and replace
10241     // it by the original array element in CodeGen.
10242     ExprResult AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
10243                                          PseudoDstExpr, PseudoSrcExpr);
10244     if (AssignmentOp.isInvalid())
10245       continue;
10246     AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
10247                                        /*DiscardedValue=*/true);
10248     if (AssignmentOp.isInvalid())
10249       continue;
10250 
10251     DeclRefExpr *Ref = nullptr;
10252     if (!VD && !CurContext->isDependentContext()) {
10253       if (TopDVar.CKind == OMPC_firstprivate) {
10254         Ref = TopDVar.PrivateCopy;
10255       } else {
10256         Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
10257         if (!isOpenMPCapturedDecl(D))
10258           ExprCaptures.push_back(Ref->getDecl());
10259       }
10260       if (TopDVar.CKind == OMPC_firstprivate ||
10261           (!isOpenMPCapturedDecl(D) &&
10262            Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
10263         ExprResult RefRes = DefaultLvalueConversion(Ref);
10264         if (!RefRes.isUsable())
10265           continue;
10266         ExprResult PostUpdateRes =
10267             BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
10268                        RefRes.get());
10269         if (!PostUpdateRes.isUsable())
10270           continue;
10271         ExprPostUpdates.push_back(
10272             IgnoredValueConversions(PostUpdateRes.get()).get());
10273       }
10274     }
10275     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
10276     Vars.push_back((VD || CurContext->isDependentContext())
10277                        ? RefExpr->IgnoreParens()
10278                        : Ref);
10279     SrcExprs.push_back(PseudoSrcExpr);
10280     DstExprs.push_back(PseudoDstExpr);
10281     AssignmentOps.push_back(AssignmentOp.get());
10282   }
10283 
10284   if (Vars.empty())
10285     return nullptr;
10286 
10287   return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
10288                                       Vars, SrcExprs, DstExprs, AssignmentOps,
10289                                       buildPreInits(Context, ExprCaptures),
10290                                       buildPostUpdate(*this, ExprPostUpdates));
10291 }
10292 
10293 OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
10294                                          SourceLocation StartLoc,
10295                                          SourceLocation LParenLoc,
10296                                          SourceLocation EndLoc) {
10297   SmallVector<Expr *, 8> Vars;
10298   for (Expr *RefExpr : VarList) {
10299     assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
10300     SourceLocation ELoc;
10301     SourceRange ERange;
10302     Expr *SimpleRefExpr = RefExpr;
10303     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
10304     if (Res.second) {
10305       // It will be analyzed later.
10306       Vars.push_back(RefExpr);
10307     }
10308     ValueDecl *D = Res.first;
10309     if (!D)
10310       continue;
10311 
10312     auto *VD = dyn_cast<VarDecl>(D);
10313     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
10314     // in a Construct]
10315     //  Variables with the predetermined data-sharing attributes may not be
10316     //  listed in data-sharing attributes clauses, except for the cases
10317     //  listed below. For these exceptions only, listing a predetermined
10318     //  variable in a data-sharing attribute clause is allowed and overrides
10319     //  the variable's predetermined data-sharing attributes.
10320     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
10321     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
10322         DVar.RefExpr) {
10323       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
10324                                           << getOpenMPClauseName(OMPC_shared);
10325       reportOriginalDsa(*this, DSAStack, D, DVar);
10326       continue;
10327     }
10328 
10329     DeclRefExpr *Ref = nullptr;
10330     if (!VD && isOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
10331       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
10332     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
10333     Vars.push_back((VD || !Ref || CurContext->isDependentContext())
10334                        ? RefExpr->IgnoreParens()
10335                        : Ref);
10336   }
10337 
10338   if (Vars.empty())
10339     return nullptr;
10340 
10341   return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
10342 }
10343 
10344 namespace {
10345 class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
10346   DSAStackTy *Stack;
10347 
10348 public:
10349   bool VisitDeclRefExpr(DeclRefExpr *E) {
10350     if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
10351       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
10352       if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
10353         return false;
10354       if (DVar.CKind != OMPC_unknown)
10355         return true;
10356       DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
10357           VD, isOpenMPPrivate, [](OpenMPDirectiveKind) { return true; },
10358           /*FromParent=*/true);
10359       return DVarPrivate.CKind != OMPC_unknown;
10360     }
10361     return false;
10362   }
10363   bool VisitStmt(Stmt *S) {
10364     for (Stmt *Child : S->children()) {
10365       if (Child && Visit(Child))
10366         return true;
10367     }
10368     return false;
10369   }
10370   explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
10371 };
10372 } // namespace
10373 
10374 namespace {
10375 // Transform MemberExpression for specified FieldDecl of current class to
10376 // DeclRefExpr to specified OMPCapturedExprDecl.
10377 class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
10378   typedef TreeTransform<TransformExprToCaptures> BaseTransform;
10379   ValueDecl *Field = nullptr;
10380   DeclRefExpr *CapturedExpr = nullptr;
10381 
10382 public:
10383   TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
10384       : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
10385 
10386   ExprResult TransformMemberExpr(MemberExpr *E) {
10387     if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
10388         E->getMemberDecl() == Field) {
10389       CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
10390       return CapturedExpr;
10391     }
10392     return BaseTransform::TransformMemberExpr(E);
10393   }
10394   DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
10395 };
10396 } // namespace
10397 
10398 template <typename T, typename U>
10399 static T filterLookupForUDR(SmallVectorImpl<U> &Lookups,
10400                             const llvm::function_ref<T(ValueDecl *)> Gen) {
10401   for (U &Set : Lookups) {
10402     for (auto *D : Set) {
10403       if (T Res = Gen(cast<ValueDecl>(D)))
10404         return Res;
10405     }
10406   }
10407   return T();
10408 }
10409 
10410 static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) {
10411   assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case");
10412 
10413   for (auto RD : D->redecls()) {
10414     // Don't bother with extra checks if we already know this one isn't visible.
10415     if (RD == D)
10416       continue;
10417 
10418     auto ND = cast<NamedDecl>(RD);
10419     if (LookupResult::isVisible(SemaRef, ND))
10420       return ND;
10421   }
10422 
10423   return nullptr;
10424 }
10425 
10426 static void
10427 argumentDependentLookup(Sema &SemaRef, const DeclarationNameInfo &ReductionId,
10428                         SourceLocation Loc, QualType Ty,
10429                         SmallVectorImpl<UnresolvedSet<8>> &Lookups) {
10430   // Find all of the associated namespaces and classes based on the
10431   // arguments we have.
10432   Sema::AssociatedNamespaceSet AssociatedNamespaces;
10433   Sema::AssociatedClassSet AssociatedClasses;
10434   OpaqueValueExpr OVE(Loc, Ty, VK_LValue);
10435   SemaRef.FindAssociatedClassesAndNamespaces(Loc, &OVE, AssociatedNamespaces,
10436                                              AssociatedClasses);
10437 
10438   // C++ [basic.lookup.argdep]p3:
10439   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
10440   //   and let Y be the lookup set produced by argument dependent
10441   //   lookup (defined as follows). If X contains [...] then Y is
10442   //   empty. Otherwise Y is the set of declarations found in the
10443   //   namespaces associated with the argument types as described
10444   //   below. The set of declarations found by the lookup of the name
10445   //   is the union of X and Y.
10446   //
10447   // Here, we compute Y and add its members to the overloaded
10448   // candidate set.
10449   for (auto *NS : AssociatedNamespaces) {
10450     //   When considering an associated namespace, the lookup is the
10451     //   same as the lookup performed when the associated namespace is
10452     //   used as a qualifier (3.4.3.2) except that:
10453     //
10454     //     -- Any using-directives in the associated namespace are
10455     //        ignored.
10456     //
10457     //     -- Any namespace-scope friend functions declared in
10458     //        associated classes are visible within their respective
10459     //        namespaces even if they are not visible during an ordinary
10460     //        lookup (11.4).
10461     DeclContext::lookup_result R = NS->lookup(ReductionId.getName());
10462     for (auto *D : R) {
10463       auto *Underlying = D;
10464       if (auto *USD = dyn_cast<UsingShadowDecl>(D))
10465         Underlying = USD->getTargetDecl();
10466 
10467       if (!isa<OMPDeclareReductionDecl>(Underlying))
10468         continue;
10469 
10470       if (!SemaRef.isVisible(D)) {
10471         D = findAcceptableDecl(SemaRef, D);
10472         if (!D)
10473           continue;
10474         if (auto *USD = dyn_cast<UsingShadowDecl>(D))
10475           Underlying = USD->getTargetDecl();
10476       }
10477       Lookups.emplace_back();
10478       Lookups.back().addDecl(Underlying);
10479     }
10480   }
10481 }
10482 
10483 static ExprResult
10484 buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
10485                          Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
10486                          const DeclarationNameInfo &ReductionId, QualType Ty,
10487                          CXXCastPath &BasePath, Expr *UnresolvedReduction) {
10488   if (ReductionIdScopeSpec.isInvalid())
10489     return ExprError();
10490   SmallVector<UnresolvedSet<8>, 4> Lookups;
10491   if (S) {
10492     LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
10493     Lookup.suppressDiagnostics();
10494     while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
10495       NamedDecl *D = Lookup.getRepresentativeDecl();
10496       do {
10497         S = S->getParent();
10498       } while (S && !S->isDeclScope(D));
10499       if (S)
10500         S = S->getParent();
10501       Lookups.emplace_back();
10502       Lookups.back().append(Lookup.begin(), Lookup.end());
10503       Lookup.clear();
10504     }
10505   } else if (auto *ULE =
10506                  cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
10507     Lookups.push_back(UnresolvedSet<8>());
10508     Decl *PrevD = nullptr;
10509     for (NamedDecl *D : ULE->decls()) {
10510       if (D == PrevD)
10511         Lookups.push_back(UnresolvedSet<8>());
10512       else if (auto *DRD = cast<OMPDeclareReductionDecl>(D))
10513         Lookups.back().addDecl(DRD);
10514       PrevD = D;
10515     }
10516   }
10517   if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() ||
10518       Ty->isInstantiationDependentType() ||
10519       Ty->containsUnexpandedParameterPack() ||
10520       filterLookupForUDR<bool>(Lookups, [](ValueDecl *D) {
10521         return !D->isInvalidDecl() &&
10522                (D->getType()->isDependentType() ||
10523                 D->getType()->isInstantiationDependentType() ||
10524                 D->getType()->containsUnexpandedParameterPack());
10525       })) {
10526     UnresolvedSet<8> ResSet;
10527     for (const UnresolvedSet<8> &Set : Lookups) {
10528       if (Set.empty())
10529         continue;
10530       ResSet.append(Set.begin(), Set.end());
10531       // The last item marks the end of all declarations at the specified scope.
10532       ResSet.addDecl(Set[Set.size() - 1]);
10533     }
10534     return UnresolvedLookupExpr::Create(
10535         SemaRef.Context, /*NamingClass=*/nullptr,
10536         ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
10537         /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
10538   }
10539   // Lookup inside the classes.
10540   // C++ [over.match.oper]p3:
10541   //   For a unary operator @ with an operand of a type whose
10542   //   cv-unqualified version is T1, and for a binary operator @ with
10543   //   a left operand of a type whose cv-unqualified version is T1 and
10544   //   a right operand of a type whose cv-unqualified version is T2,
10545   //   three sets of candidate functions, designated member
10546   //   candidates, non-member candidates and built-in candidates, are
10547   //   constructed as follows:
10548   //     -- If T1 is a complete class type or a class currently being
10549   //        defined, the set of member candidates is the result of the
10550   //        qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
10551   //        the set of member candidates is empty.
10552   LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
10553   Lookup.suppressDiagnostics();
10554   if (const auto *TyRec = Ty->getAs<RecordType>()) {
10555     // Complete the type if it can be completed.
10556     // If the type is neither complete nor being defined, bail out now.
10557     if (SemaRef.isCompleteType(Loc, Ty) || TyRec->isBeingDefined() ||
10558         TyRec->getDecl()->getDefinition()) {
10559       Lookup.clear();
10560       SemaRef.LookupQualifiedName(Lookup, TyRec->getDecl());
10561       if (Lookup.empty()) {
10562         Lookups.emplace_back();
10563         Lookups.back().append(Lookup.begin(), Lookup.end());
10564       }
10565     }
10566   }
10567   // Perform ADL.
10568   argumentDependentLookup(SemaRef, ReductionId, Loc, Ty, Lookups);
10569   if (auto *VD = filterLookupForUDR<ValueDecl *>(
10570           Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
10571             if (!D->isInvalidDecl() &&
10572                 SemaRef.Context.hasSameType(D->getType(), Ty))
10573               return D;
10574             return nullptr;
10575           }))
10576     return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
10577   if (auto *VD = filterLookupForUDR<ValueDecl *>(
10578           Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
10579             if (!D->isInvalidDecl() &&
10580                 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
10581                 !Ty.isMoreQualifiedThan(D->getType()))
10582               return D;
10583             return nullptr;
10584           })) {
10585     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
10586                        /*DetectVirtual=*/false);
10587     if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
10588       if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
10589               VD->getType().getUnqualifiedType()))) {
10590         if (SemaRef.CheckBaseClassAccess(Loc, VD->getType(), Ty, Paths.front(),
10591                                          /*DiagID=*/0) !=
10592             Sema::AR_inaccessible) {
10593           SemaRef.BuildBasePathArray(Paths, BasePath);
10594           return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
10595         }
10596       }
10597     }
10598   }
10599   if (ReductionIdScopeSpec.isSet()) {
10600     SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
10601     return ExprError();
10602   }
10603   return ExprEmpty();
10604 }
10605 
10606 namespace {
10607 /// Data for the reduction-based clauses.
10608 struct ReductionData {
10609   /// List of original reduction items.
10610   SmallVector<Expr *, 8> Vars;
10611   /// List of private copies of the reduction items.
10612   SmallVector<Expr *, 8> Privates;
10613   /// LHS expressions for the reduction_op expressions.
10614   SmallVector<Expr *, 8> LHSs;
10615   /// RHS expressions for the reduction_op expressions.
10616   SmallVector<Expr *, 8> RHSs;
10617   /// Reduction operation expression.
10618   SmallVector<Expr *, 8> ReductionOps;
10619   /// Taskgroup descriptors for the corresponding reduction items in
10620   /// in_reduction clauses.
10621   SmallVector<Expr *, 8> TaskgroupDescriptors;
10622   /// List of captures for clause.
10623   SmallVector<Decl *, 4> ExprCaptures;
10624   /// List of postupdate expressions.
10625   SmallVector<Expr *, 4> ExprPostUpdates;
10626   ReductionData() = delete;
10627   /// Reserves required memory for the reduction data.
10628   ReductionData(unsigned Size) {
10629     Vars.reserve(Size);
10630     Privates.reserve(Size);
10631     LHSs.reserve(Size);
10632     RHSs.reserve(Size);
10633     ReductionOps.reserve(Size);
10634     TaskgroupDescriptors.reserve(Size);
10635     ExprCaptures.reserve(Size);
10636     ExprPostUpdates.reserve(Size);
10637   }
10638   /// Stores reduction item and reduction operation only (required for dependent
10639   /// reduction item).
10640   void push(Expr *Item, Expr *ReductionOp) {
10641     Vars.emplace_back(Item);
10642     Privates.emplace_back(nullptr);
10643     LHSs.emplace_back(nullptr);
10644     RHSs.emplace_back(nullptr);
10645     ReductionOps.emplace_back(ReductionOp);
10646     TaskgroupDescriptors.emplace_back(nullptr);
10647   }
10648   /// Stores reduction data.
10649   void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp,
10650             Expr *TaskgroupDescriptor) {
10651     Vars.emplace_back(Item);
10652     Privates.emplace_back(Private);
10653     LHSs.emplace_back(LHS);
10654     RHSs.emplace_back(RHS);
10655     ReductionOps.emplace_back(ReductionOp);
10656     TaskgroupDescriptors.emplace_back(TaskgroupDescriptor);
10657   }
10658 };
10659 } // namespace
10660 
10661 static bool checkOMPArraySectionConstantForReduction(
10662     ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement,
10663     SmallVectorImpl<llvm::APSInt> &ArraySizes) {
10664   const Expr *Length = OASE->getLength();
10665   if (Length == nullptr) {
10666     // For array sections of the form [1:] or [:], we would need to analyze
10667     // the lower bound...
10668     if (OASE->getColonLoc().isValid())
10669       return false;
10670 
10671     // This is an array subscript which has implicit length 1!
10672     SingleElement = true;
10673     ArraySizes.push_back(llvm::APSInt::get(1));
10674   } else {
10675     Expr::EvalResult Result;
10676     if (!Length->EvaluateAsInt(Result, Context))
10677       return false;
10678 
10679     llvm::APSInt ConstantLengthValue = Result.Val.getInt();
10680     SingleElement = (ConstantLengthValue.getSExtValue() == 1);
10681     ArraySizes.push_back(ConstantLengthValue);
10682   }
10683 
10684   // Get the base of this array section and walk up from there.
10685   const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
10686 
10687   // We require length = 1 for all array sections except the right-most to
10688   // guarantee that the memory region is contiguous and has no holes in it.
10689   while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) {
10690     Length = TempOASE->getLength();
10691     if (Length == nullptr) {
10692       // For array sections of the form [1:] or [:], we would need to analyze
10693       // the lower bound...
10694       if (OASE->getColonLoc().isValid())
10695         return false;
10696 
10697       // This is an array subscript which has implicit length 1!
10698       ArraySizes.push_back(llvm::APSInt::get(1));
10699     } else {
10700       Expr::EvalResult Result;
10701       if (!Length->EvaluateAsInt(Result, Context))
10702         return false;
10703 
10704       llvm::APSInt ConstantLengthValue = Result.Val.getInt();
10705       if (ConstantLengthValue.getSExtValue() != 1)
10706         return false;
10707 
10708       ArraySizes.push_back(ConstantLengthValue);
10709     }
10710     Base = TempOASE->getBase()->IgnoreParenImpCasts();
10711   }
10712 
10713   // If we have a single element, we don't need to add the implicit lengths.
10714   if (!SingleElement) {
10715     while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) {
10716       // Has implicit length 1!
10717       ArraySizes.push_back(llvm::APSInt::get(1));
10718       Base = TempASE->getBase()->IgnoreParenImpCasts();
10719     }
10720   }
10721 
10722   // This array section can be privatized as a single value or as a constant
10723   // sized array.
10724   return true;
10725 }
10726 
10727 static bool actOnOMPReductionKindClause(
10728     Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind,
10729     ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
10730     SourceLocation ColonLoc, SourceLocation EndLoc,
10731     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
10732     ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) {
10733   DeclarationName DN = ReductionId.getName();
10734   OverloadedOperatorKind OOK = DN.getCXXOverloadedOperator();
10735   BinaryOperatorKind BOK = BO_Comma;
10736 
10737   ASTContext &Context = S.Context;
10738   // OpenMP [2.14.3.6, reduction clause]
10739   // C
10740   // reduction-identifier is either an identifier or one of the following
10741   // operators: +, -, *,  &, |, ^, && and ||
10742   // C++
10743   // reduction-identifier is either an id-expression or one of the following
10744   // operators: +, -, *, &, |, ^, && and ||
10745   switch (OOK) {
10746   case OO_Plus:
10747   case OO_Minus:
10748     BOK = BO_Add;
10749     break;
10750   case OO_Star:
10751     BOK = BO_Mul;
10752     break;
10753   case OO_Amp:
10754     BOK = BO_And;
10755     break;
10756   case OO_Pipe:
10757     BOK = BO_Or;
10758     break;
10759   case OO_Caret:
10760     BOK = BO_Xor;
10761     break;
10762   case OO_AmpAmp:
10763     BOK = BO_LAnd;
10764     break;
10765   case OO_PipePipe:
10766     BOK = BO_LOr;
10767     break;
10768   case OO_New:
10769   case OO_Delete:
10770   case OO_Array_New:
10771   case OO_Array_Delete:
10772   case OO_Slash:
10773   case OO_Percent:
10774   case OO_Tilde:
10775   case OO_Exclaim:
10776   case OO_Equal:
10777   case OO_Less:
10778   case OO_Greater:
10779   case OO_LessEqual:
10780   case OO_GreaterEqual:
10781   case OO_PlusEqual:
10782   case OO_MinusEqual:
10783   case OO_StarEqual:
10784   case OO_SlashEqual:
10785   case OO_PercentEqual:
10786   case OO_CaretEqual:
10787   case OO_AmpEqual:
10788   case OO_PipeEqual:
10789   case OO_LessLess:
10790   case OO_GreaterGreater:
10791   case OO_LessLessEqual:
10792   case OO_GreaterGreaterEqual:
10793   case OO_EqualEqual:
10794   case OO_ExclaimEqual:
10795   case OO_Spaceship:
10796   case OO_PlusPlus:
10797   case OO_MinusMinus:
10798   case OO_Comma:
10799   case OO_ArrowStar:
10800   case OO_Arrow:
10801   case OO_Call:
10802   case OO_Subscript:
10803   case OO_Conditional:
10804   case OO_Coawait:
10805   case NUM_OVERLOADED_OPERATORS:
10806     llvm_unreachable("Unexpected reduction identifier");
10807   case OO_None:
10808     if (IdentifierInfo *II = DN.getAsIdentifierInfo()) {
10809       if (II->isStr("max"))
10810         BOK = BO_GT;
10811       else if (II->isStr("min"))
10812         BOK = BO_LT;
10813     }
10814     break;
10815   }
10816   SourceRange ReductionIdRange;
10817   if (ReductionIdScopeSpec.isValid())
10818     ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
10819   else
10820     ReductionIdRange.setBegin(ReductionId.getBeginLoc());
10821   ReductionIdRange.setEnd(ReductionId.getEndLoc());
10822 
10823   auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
10824   bool FirstIter = true;
10825   for (Expr *RefExpr : VarList) {
10826     assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
10827     // OpenMP [2.1, C/C++]
10828     //  A list item is a variable or array section, subject to the restrictions
10829     //  specified in Section 2.4 on page 42 and in each of the sections
10830     // describing clauses and directives for which a list appears.
10831     // OpenMP  [2.14.3.3, Restrictions, p.1]
10832     //  A variable that is part of another variable (as an array or
10833     //  structure element) cannot appear in a private clause.
10834     if (!FirstIter && IR != ER)
10835       ++IR;
10836     FirstIter = false;
10837     SourceLocation ELoc;
10838     SourceRange ERange;
10839     Expr *SimpleRefExpr = RefExpr;
10840     auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
10841                               /*AllowArraySection=*/true);
10842     if (Res.second) {
10843       // Try to find 'declare reduction' corresponding construct before using
10844       // builtin/overloaded operators.
10845       QualType Type = Context.DependentTy;
10846       CXXCastPath BasePath;
10847       ExprResult DeclareReductionRef = buildDeclareReductionRef(
10848           S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
10849           ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
10850       Expr *ReductionOp = nullptr;
10851       if (S.CurContext->isDependentContext() &&
10852           (DeclareReductionRef.isUnset() ||
10853            isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
10854         ReductionOp = DeclareReductionRef.get();
10855       // It will be analyzed later.
10856       RD.push(RefExpr, ReductionOp);
10857     }
10858     ValueDecl *D = Res.first;
10859     if (!D)
10860       continue;
10861 
10862     Expr *TaskgroupDescriptor = nullptr;
10863     QualType Type;
10864     auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
10865     auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
10866     if (ASE) {
10867       Type = ASE->getType().getNonReferenceType();
10868     } else if (OASE) {
10869       QualType BaseType =
10870           OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
10871       if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
10872         Type = ATy->getElementType();
10873       else
10874         Type = BaseType->getPointeeType();
10875       Type = Type.getNonReferenceType();
10876     } else {
10877       Type = Context.getBaseElementType(D->getType().getNonReferenceType());
10878     }
10879     auto *VD = dyn_cast<VarDecl>(D);
10880 
10881     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
10882     //  A variable that appears in a private clause must not have an incomplete
10883     //  type or a reference type.
10884     if (S.RequireCompleteType(ELoc, D->getType(),
10885                               diag::err_omp_reduction_incomplete_type))
10886       continue;
10887     // OpenMP [2.14.3.6, reduction clause, Restrictions]
10888     // A list item that appears in a reduction clause must not be
10889     // const-qualified.
10890     if (Type.getNonReferenceType().isConstant(Context)) {
10891       S.Diag(ELoc, diag::err_omp_const_reduction_list_item) << ERange;
10892       if (!ASE && !OASE) {
10893         bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
10894                                  VarDecl::DeclarationOnly;
10895         S.Diag(D->getLocation(),
10896                IsDecl ? diag::note_previous_decl : diag::note_defined_here)
10897             << D;
10898       }
10899       continue;
10900     }
10901 
10902     OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective();
10903     // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
10904     //  If a list-item is a reference type then it must bind to the same object
10905     //  for all threads of the team.
10906     if (!ASE && !OASE) {
10907       if (VD) {
10908         VarDecl *VDDef = VD->getDefinition();
10909         if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
10910           DSARefChecker Check(Stack);
10911           if (Check.Visit(VDDef->getInit())) {
10912             S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg)
10913                 << getOpenMPClauseName(ClauseKind) << ERange;
10914             S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
10915             continue;
10916           }
10917         }
10918       }
10919 
10920       // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
10921       // in a Construct]
10922       //  Variables with the predetermined data-sharing attributes may not be
10923       //  listed in data-sharing attributes clauses, except for the cases
10924       //  listed below. For these exceptions only, listing a predetermined
10925       //  variable in a data-sharing attribute clause is allowed and overrides
10926       //  the variable's predetermined data-sharing attributes.
10927       // OpenMP [2.14.3.6, Restrictions, p.3]
10928       //  Any number of reduction clauses can be specified on the directive,
10929       //  but a list item can appear only once in the reduction clauses for that
10930       //  directive.
10931       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false);
10932       if (DVar.CKind == OMPC_reduction) {
10933         S.Diag(ELoc, diag::err_omp_once_referenced)
10934             << getOpenMPClauseName(ClauseKind);
10935         if (DVar.RefExpr)
10936           S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
10937         continue;
10938       }
10939       if (DVar.CKind != OMPC_unknown) {
10940         S.Diag(ELoc, diag::err_omp_wrong_dsa)
10941             << getOpenMPClauseName(DVar.CKind)
10942             << getOpenMPClauseName(OMPC_reduction);
10943         reportOriginalDsa(S, Stack, D, DVar);
10944         continue;
10945       }
10946 
10947       // OpenMP [2.14.3.6, Restrictions, p.1]
10948       //  A list item that appears in a reduction clause of a worksharing
10949       //  construct must be shared in the parallel regions to which any of the
10950       //  worksharing regions arising from the worksharing construct bind.
10951       if (isOpenMPWorksharingDirective(CurrDir) &&
10952           !isOpenMPParallelDirective(CurrDir) &&
10953           !isOpenMPTeamsDirective(CurrDir)) {
10954         DVar = Stack->getImplicitDSA(D, true);
10955         if (DVar.CKind != OMPC_shared) {
10956           S.Diag(ELoc, diag::err_omp_required_access)
10957               << getOpenMPClauseName(OMPC_reduction)
10958               << getOpenMPClauseName(OMPC_shared);
10959           reportOriginalDsa(S, Stack, D, DVar);
10960           continue;
10961         }
10962       }
10963     }
10964 
10965     // Try to find 'declare reduction' corresponding construct before using
10966     // builtin/overloaded operators.
10967     CXXCastPath BasePath;
10968     ExprResult DeclareReductionRef = buildDeclareReductionRef(
10969         S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
10970         ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
10971     if (DeclareReductionRef.isInvalid())
10972       continue;
10973     if (S.CurContext->isDependentContext() &&
10974         (DeclareReductionRef.isUnset() ||
10975          isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
10976       RD.push(RefExpr, DeclareReductionRef.get());
10977       continue;
10978     }
10979     if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
10980       // Not allowed reduction identifier is found.
10981       S.Diag(ReductionId.getBeginLoc(),
10982              diag::err_omp_unknown_reduction_identifier)
10983           << Type << ReductionIdRange;
10984       continue;
10985     }
10986 
10987     // OpenMP [2.14.3.6, reduction clause, Restrictions]
10988     // The type of a list item that appears in a reduction clause must be valid
10989     // for the reduction-identifier. For a max or min reduction in C, the type
10990     // of the list item must be an allowed arithmetic data type: char, int,
10991     // float, double, or _Bool, possibly modified with long, short, signed, or
10992     // unsigned. For a max or min reduction in C++, the type of the list item
10993     // must be an allowed arithmetic data type: char, wchar_t, int, float,
10994     // double, or bool, possibly modified with long, short, signed, or unsigned.
10995     if (DeclareReductionRef.isUnset()) {
10996       if ((BOK == BO_GT || BOK == BO_LT) &&
10997           !(Type->isScalarType() ||
10998             (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
10999         S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
11000             << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus;
11001         if (!ASE && !OASE) {
11002           bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
11003                                    VarDecl::DeclarationOnly;
11004           S.Diag(D->getLocation(),
11005                  IsDecl ? diag::note_previous_decl : diag::note_defined_here)
11006               << D;
11007         }
11008         continue;
11009       }
11010       if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
11011           !S.getLangOpts().CPlusPlus && Type->isFloatingType()) {
11012         S.Diag(ELoc, diag::err_omp_clause_floating_type_arg)
11013             << getOpenMPClauseName(ClauseKind);
11014         if (!ASE && !OASE) {
11015           bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
11016                                    VarDecl::DeclarationOnly;
11017           S.Diag(D->getLocation(),
11018                  IsDecl ? diag::note_previous_decl : diag::note_defined_here)
11019               << D;
11020         }
11021         continue;
11022       }
11023     }
11024 
11025     Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
11026     VarDecl *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs",
11027                                   D->hasAttrs() ? &D->getAttrs() : nullptr);
11028     VarDecl *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(),
11029                                   D->hasAttrs() ? &D->getAttrs() : nullptr);
11030     QualType PrivateTy = Type;
11031 
11032     // Try if we can determine constant lengths for all array sections and avoid
11033     // the VLA.
11034     bool ConstantLengthOASE = false;
11035     if (OASE) {
11036       bool SingleElement;
11037       llvm::SmallVector<llvm::APSInt, 4> ArraySizes;
11038       ConstantLengthOASE = checkOMPArraySectionConstantForReduction(
11039           Context, OASE, SingleElement, ArraySizes);
11040 
11041       // If we don't have a single element, we must emit a constant array type.
11042       if (ConstantLengthOASE && !SingleElement) {
11043         for (llvm::APSInt &Size : ArraySizes)
11044           PrivateTy = Context.getConstantArrayType(
11045               PrivateTy, Size, ArrayType::Normal, /*IndexTypeQuals=*/0);
11046       }
11047     }
11048 
11049     if ((OASE && !ConstantLengthOASE) ||
11050         (!OASE && !ASE &&
11051          D->getType().getNonReferenceType()->isVariablyModifiedType())) {
11052       if (!Context.getTargetInfo().isVLASupported() &&
11053           S.shouldDiagnoseTargetSupportFromOpenMP()) {
11054         S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
11055         S.Diag(ELoc, diag::note_vla_unsupported);
11056         continue;
11057       }
11058       // For arrays/array sections only:
11059       // Create pseudo array type for private copy. The size for this array will
11060       // be generated during codegen.
11061       // For array subscripts or single variables Private Ty is the same as Type
11062       // (type of the variable or single array element).
11063       PrivateTy = Context.getVariableArrayType(
11064           Type,
11065           new (Context) OpaqueValueExpr(ELoc, Context.getSizeType(), VK_RValue),
11066           ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
11067     } else if (!ASE && !OASE &&
11068                Context.getAsArrayType(D->getType().getNonReferenceType())) {
11069       PrivateTy = D->getType().getNonReferenceType();
11070     }
11071     // Private copy.
11072     VarDecl *PrivateVD =
11073         buildVarDecl(S, ELoc, PrivateTy, D->getName(),
11074                      D->hasAttrs() ? &D->getAttrs() : nullptr,
11075                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
11076     // Add initializer for private variable.
11077     Expr *Init = nullptr;
11078     DeclRefExpr *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc);
11079     DeclRefExpr *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc);
11080     if (DeclareReductionRef.isUsable()) {
11081       auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
11082       auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
11083       if (DRD->getInitializer()) {
11084         Init = DRDRef;
11085         RHSVD->setInit(DRDRef);
11086         RHSVD->setInitStyle(VarDecl::CallInit);
11087       }
11088     } else {
11089       switch (BOK) {
11090       case BO_Add:
11091       case BO_Xor:
11092       case BO_Or:
11093       case BO_LOr:
11094         // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
11095         if (Type->isScalarType() || Type->isAnyComplexType())
11096           Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get();
11097         break;
11098       case BO_Mul:
11099       case BO_LAnd:
11100         if (Type->isScalarType() || Type->isAnyComplexType()) {
11101           // '*' and '&&' reduction ops - initializer is '1'.
11102           Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get();
11103         }
11104         break;
11105       case BO_And: {
11106         // '&' reduction op - initializer is '~0'.
11107         QualType OrigType = Type;
11108         if (auto *ComplexTy = OrigType->getAs<ComplexType>())
11109           Type = ComplexTy->getElementType();
11110         if (Type->isRealFloatingType()) {
11111           llvm::APFloat InitValue =
11112               llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
11113                                              /*isIEEE=*/true);
11114           Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
11115                                          Type, ELoc);
11116         } else if (Type->isScalarType()) {
11117           uint64_t Size = Context.getTypeSize(Type);
11118           QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
11119           llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
11120           Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
11121         }
11122         if (Init && OrigType->isAnyComplexType()) {
11123           // Init = 0xFFFF + 0xFFFFi;
11124           auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
11125           Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
11126         }
11127         Type = OrigType;
11128         break;
11129       }
11130       case BO_LT:
11131       case BO_GT: {
11132         // 'min' reduction op - initializer is 'Largest representable number in
11133         // the reduction list item type'.
11134         // 'max' reduction op - initializer is 'Least representable number in
11135         // the reduction list item type'.
11136         if (Type->isIntegerType() || Type->isPointerType()) {
11137           bool IsSigned = Type->hasSignedIntegerRepresentation();
11138           uint64_t Size = Context.getTypeSize(Type);
11139           QualType IntTy =
11140               Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
11141           llvm::APInt InitValue =
11142               (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
11143                                         : llvm::APInt::getMinValue(Size)
11144                              : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
11145                                         : llvm::APInt::getMaxValue(Size);
11146           Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
11147           if (Type->isPointerType()) {
11148             // Cast to pointer type.
11149             ExprResult CastExpr = S.BuildCStyleCastExpr(
11150                 ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init);
11151             if (CastExpr.isInvalid())
11152               continue;
11153             Init = CastExpr.get();
11154           }
11155         } else if (Type->isRealFloatingType()) {
11156           llvm::APFloat InitValue = llvm::APFloat::getLargest(
11157               Context.getFloatTypeSemantics(Type), BOK != BO_LT);
11158           Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
11159                                          Type, ELoc);
11160         }
11161         break;
11162       }
11163       case BO_PtrMemD:
11164       case BO_PtrMemI:
11165       case BO_MulAssign:
11166       case BO_Div:
11167       case BO_Rem:
11168       case BO_Sub:
11169       case BO_Shl:
11170       case BO_Shr:
11171       case BO_LE:
11172       case BO_GE:
11173       case BO_EQ:
11174       case BO_NE:
11175       case BO_Cmp:
11176       case BO_AndAssign:
11177       case BO_XorAssign:
11178       case BO_OrAssign:
11179       case BO_Assign:
11180       case BO_AddAssign:
11181       case BO_SubAssign:
11182       case BO_DivAssign:
11183       case BO_RemAssign:
11184       case BO_ShlAssign:
11185       case BO_ShrAssign:
11186       case BO_Comma:
11187         llvm_unreachable("Unexpected reduction operation");
11188       }
11189     }
11190     if (Init && DeclareReductionRef.isUnset())
11191       S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
11192     else if (!Init)
11193       S.ActOnUninitializedDecl(RHSVD);
11194     if (RHSVD->isInvalidDecl())
11195       continue;
11196     if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) {
11197       S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible)
11198           << Type << ReductionIdRange;
11199       bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
11200                                VarDecl::DeclarationOnly;
11201       S.Diag(D->getLocation(),
11202              IsDecl ? diag::note_previous_decl : diag::note_defined_here)
11203           << D;
11204       continue;
11205     }
11206     // Store initializer for single element in private copy. Will be used during
11207     // codegen.
11208     PrivateVD->setInit(RHSVD->getInit());
11209     PrivateVD->setInitStyle(RHSVD->getInitStyle());
11210     DeclRefExpr *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc);
11211     ExprResult ReductionOp;
11212     if (DeclareReductionRef.isUsable()) {
11213       QualType RedTy = DeclareReductionRef.get()->getType();
11214       QualType PtrRedTy = Context.getPointerType(RedTy);
11215       ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
11216       ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
11217       if (!BasePath.empty()) {
11218         LHS = S.DefaultLvalueConversion(LHS.get());
11219         RHS = S.DefaultLvalueConversion(RHS.get());
11220         LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
11221                                        CK_UncheckedDerivedToBase, LHS.get(),
11222                                        &BasePath, LHS.get()->getValueKind());
11223         RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
11224                                        CK_UncheckedDerivedToBase, RHS.get(),
11225                                        &BasePath, RHS.get()->getValueKind());
11226       }
11227       FunctionProtoType::ExtProtoInfo EPI;
11228       QualType Params[] = {PtrRedTy, PtrRedTy};
11229       QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
11230       auto *OVE = new (Context) OpaqueValueExpr(
11231           ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
11232           S.DefaultLvalueConversion(DeclareReductionRef.get()).get());
11233       Expr *Args[] = {LHS.get(), RHS.get()};
11234       ReductionOp = new (Context)
11235           CallExpr(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
11236     } else {
11237       ReductionOp = S.BuildBinOp(
11238           Stack->getCurScope(), ReductionId.getBeginLoc(), BOK, LHSDRE, RHSDRE);
11239       if (ReductionOp.isUsable()) {
11240         if (BOK != BO_LT && BOK != BO_GT) {
11241           ReductionOp =
11242               S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
11243                            BO_Assign, LHSDRE, ReductionOp.get());
11244         } else {
11245           auto *ConditionalOp = new (Context)
11246               ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc, RHSDRE,
11247                                   Type, VK_LValue, OK_Ordinary);
11248           ReductionOp =
11249               S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
11250                            BO_Assign, LHSDRE, ConditionalOp);
11251         }
11252         if (ReductionOp.isUsable())
11253           ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get());
11254       }
11255       if (!ReductionOp.isUsable())
11256         continue;
11257     }
11258 
11259     // OpenMP [2.15.4.6, Restrictions, p.2]
11260     // A list item that appears in an in_reduction clause of a task construct
11261     // must appear in a task_reduction clause of a construct associated with a
11262     // taskgroup region that includes the participating task in its taskgroup
11263     // set. The construct associated with the innermost region that meets this
11264     // condition must specify the same reduction-identifier as the in_reduction
11265     // clause.
11266     if (ClauseKind == OMPC_in_reduction) {
11267       SourceRange ParentSR;
11268       BinaryOperatorKind ParentBOK;
11269       const Expr *ParentReductionOp;
11270       Expr *ParentBOKTD, *ParentReductionOpTD;
11271       DSAStackTy::DSAVarData ParentBOKDSA =
11272           Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK,
11273                                                   ParentBOKTD);
11274       DSAStackTy::DSAVarData ParentReductionOpDSA =
11275           Stack->getTopMostTaskgroupReductionData(
11276               D, ParentSR, ParentReductionOp, ParentReductionOpTD);
11277       bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown;
11278       bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown;
11279       if (!IsParentBOK && !IsParentReductionOp) {
11280         S.Diag(ELoc, diag::err_omp_in_reduction_not_task_reduction);
11281         continue;
11282       }
11283       if ((DeclareReductionRef.isUnset() && IsParentReductionOp) ||
11284           (DeclareReductionRef.isUsable() && IsParentBOK) || BOK != ParentBOK ||
11285           IsParentReductionOp) {
11286         bool EmitError = true;
11287         if (IsParentReductionOp && DeclareReductionRef.isUsable()) {
11288           llvm::FoldingSetNodeID RedId, ParentRedId;
11289           ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true);
11290           DeclareReductionRef.get()->Profile(RedId, Context,
11291                                              /*Canonical=*/true);
11292           EmitError = RedId != ParentRedId;
11293         }
11294         if (EmitError) {
11295           S.Diag(ReductionId.getBeginLoc(),
11296                  diag::err_omp_reduction_identifier_mismatch)
11297               << ReductionIdRange << RefExpr->getSourceRange();
11298           S.Diag(ParentSR.getBegin(),
11299                  diag::note_omp_previous_reduction_identifier)
11300               << ParentSR
11301               << (IsParentBOK ? ParentBOKDSA.RefExpr
11302                               : ParentReductionOpDSA.RefExpr)
11303                      ->getSourceRange();
11304           continue;
11305         }
11306       }
11307       TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD;
11308       assert(TaskgroupDescriptor && "Taskgroup descriptor must be defined.");
11309     }
11310 
11311     DeclRefExpr *Ref = nullptr;
11312     Expr *VarsExpr = RefExpr->IgnoreParens();
11313     if (!VD && !S.CurContext->isDependentContext()) {
11314       if (ASE || OASE) {
11315         TransformExprToCaptures RebuildToCapture(S, D);
11316         VarsExpr =
11317             RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
11318         Ref = RebuildToCapture.getCapturedExpr();
11319       } else {
11320         VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false);
11321       }
11322       if (!S.isOpenMPCapturedDecl(D)) {
11323         RD.ExprCaptures.emplace_back(Ref->getDecl());
11324         if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
11325           ExprResult RefRes = S.DefaultLvalueConversion(Ref);
11326           if (!RefRes.isUsable())
11327             continue;
11328           ExprResult PostUpdateRes =
11329               S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
11330                            RefRes.get());
11331           if (!PostUpdateRes.isUsable())
11332             continue;
11333           if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
11334               Stack->getCurrentDirective() == OMPD_taskgroup) {
11335             S.Diag(RefExpr->getExprLoc(),
11336                    diag::err_omp_reduction_non_addressable_expression)
11337                 << RefExpr->getSourceRange();
11338             continue;
11339           }
11340           RD.ExprPostUpdates.emplace_back(
11341               S.IgnoredValueConversions(PostUpdateRes.get()).get());
11342         }
11343       }
11344     }
11345     // All reduction items are still marked as reduction (to do not increase
11346     // code base size).
11347     Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
11348     if (CurrDir == OMPD_taskgroup) {
11349       if (DeclareReductionRef.isUsable())
11350         Stack->addTaskgroupReductionData(D, ReductionIdRange,
11351                                          DeclareReductionRef.get());
11352       else
11353         Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK);
11354     }
11355     RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(),
11356             TaskgroupDescriptor);
11357   }
11358   return RD.Vars.empty();
11359 }
11360 
11361 OMPClause *Sema::ActOnOpenMPReductionClause(
11362     ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
11363     SourceLocation ColonLoc, SourceLocation EndLoc,
11364     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
11365     ArrayRef<Expr *> UnresolvedReductions) {
11366   ReductionData RD(VarList.size());
11367   if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList,
11368                                   StartLoc, LParenLoc, ColonLoc, EndLoc,
11369                                   ReductionIdScopeSpec, ReductionId,
11370                                   UnresolvedReductions, RD))
11371     return nullptr;
11372 
11373   return OMPReductionClause::Create(
11374       Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
11375       ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
11376       RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
11377       buildPreInits(Context, RD.ExprCaptures),
11378       buildPostUpdate(*this, RD.ExprPostUpdates));
11379 }
11380 
11381 OMPClause *Sema::ActOnOpenMPTaskReductionClause(
11382     ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
11383     SourceLocation ColonLoc, SourceLocation EndLoc,
11384     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
11385     ArrayRef<Expr *> UnresolvedReductions) {
11386   ReductionData RD(VarList.size());
11387   if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction, VarList,
11388                                   StartLoc, LParenLoc, ColonLoc, EndLoc,
11389                                   ReductionIdScopeSpec, ReductionId,
11390                                   UnresolvedReductions, RD))
11391     return nullptr;
11392 
11393   return OMPTaskReductionClause::Create(
11394       Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
11395       ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
11396       RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
11397       buildPreInits(Context, RD.ExprCaptures),
11398       buildPostUpdate(*this, RD.ExprPostUpdates));
11399 }
11400 
11401 OMPClause *Sema::ActOnOpenMPInReductionClause(
11402     ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
11403     SourceLocation ColonLoc, SourceLocation EndLoc,
11404     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
11405     ArrayRef<Expr *> UnresolvedReductions) {
11406   ReductionData RD(VarList.size());
11407   if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList,
11408                                   StartLoc, LParenLoc, ColonLoc, EndLoc,
11409                                   ReductionIdScopeSpec, ReductionId,
11410                                   UnresolvedReductions, RD))
11411     return nullptr;
11412 
11413   return OMPInReductionClause::Create(
11414       Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
11415       ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
11416       RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors,
11417       buildPreInits(Context, RD.ExprCaptures),
11418       buildPostUpdate(*this, RD.ExprPostUpdates));
11419 }
11420 
11421 bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
11422                                      SourceLocation LinLoc) {
11423   if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
11424       LinKind == OMPC_LINEAR_unknown) {
11425     Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
11426     return true;
11427   }
11428   return false;
11429 }
11430 
11431 bool Sema::CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc,
11432                                  OpenMPLinearClauseKind LinKind,
11433                                  QualType Type) {
11434   const auto *VD = dyn_cast_or_null<VarDecl>(D);
11435   // A variable must not have an incomplete type or a reference type.
11436   if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
11437     return true;
11438   if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
11439       !Type->isReferenceType()) {
11440     Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
11441         << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
11442     return true;
11443   }
11444   Type = Type.getNonReferenceType();
11445 
11446   // A list item must not be const-qualified.
11447   if (Type.isConstant(Context)) {
11448     Diag(ELoc, diag::err_omp_const_variable)
11449         << getOpenMPClauseName(OMPC_linear);
11450     if (D) {
11451       bool IsDecl =
11452           !VD ||
11453           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
11454       Diag(D->getLocation(),
11455            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
11456           << D;
11457     }
11458     return true;
11459   }
11460 
11461   // A list item must be of integral or pointer type.
11462   Type = Type.getUnqualifiedType().getCanonicalType();
11463   const auto *Ty = Type.getTypePtrOrNull();
11464   if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
11465               !Ty->isPointerType())) {
11466     Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
11467     if (D) {
11468       bool IsDecl =
11469           !VD ||
11470           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
11471       Diag(D->getLocation(),
11472            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
11473           << D;
11474     }
11475     return true;
11476   }
11477   return false;
11478 }
11479 
11480 OMPClause *Sema::ActOnOpenMPLinearClause(
11481     ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
11482     SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
11483     SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
11484   SmallVector<Expr *, 8> Vars;
11485   SmallVector<Expr *, 8> Privates;
11486   SmallVector<Expr *, 8> Inits;
11487   SmallVector<Decl *, 4> ExprCaptures;
11488   SmallVector<Expr *, 4> ExprPostUpdates;
11489   if (CheckOpenMPLinearModifier(LinKind, LinLoc))
11490     LinKind = OMPC_LINEAR_val;
11491   for (Expr *RefExpr : VarList) {
11492     assert(RefExpr && "NULL expr in OpenMP linear clause.");
11493     SourceLocation ELoc;
11494     SourceRange ERange;
11495     Expr *SimpleRefExpr = RefExpr;
11496     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
11497     if (Res.second) {
11498       // It will be analyzed later.
11499       Vars.push_back(RefExpr);
11500       Privates.push_back(nullptr);
11501       Inits.push_back(nullptr);
11502     }
11503     ValueDecl *D = Res.first;
11504     if (!D)
11505       continue;
11506 
11507     QualType Type = D->getType();
11508     auto *VD = dyn_cast<VarDecl>(D);
11509 
11510     // OpenMP [2.14.3.7, linear clause]
11511     //  A list-item cannot appear in more than one linear clause.
11512     //  A list-item that appears in a linear clause cannot appear in any
11513     //  other data-sharing attribute clause.
11514     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
11515     if (DVar.RefExpr) {
11516       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
11517                                           << getOpenMPClauseName(OMPC_linear);
11518       reportOriginalDsa(*this, DSAStack, D, DVar);
11519       continue;
11520     }
11521 
11522     if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
11523       continue;
11524     Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
11525 
11526     // Build private copy of original var.
11527     VarDecl *Private =
11528         buildVarDecl(*this, ELoc, Type, D->getName(),
11529                      D->hasAttrs() ? &D->getAttrs() : nullptr,
11530                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
11531     DeclRefExpr *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
11532     // Build var to save initial value.
11533     VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
11534     Expr *InitExpr;
11535     DeclRefExpr *Ref = nullptr;
11536     if (!VD && !CurContext->isDependentContext()) {
11537       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
11538       if (!isOpenMPCapturedDecl(D)) {
11539         ExprCaptures.push_back(Ref->getDecl());
11540         if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
11541           ExprResult RefRes = DefaultLvalueConversion(Ref);
11542           if (!RefRes.isUsable())
11543             continue;
11544           ExprResult PostUpdateRes =
11545               BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
11546                          SimpleRefExpr, RefRes.get());
11547           if (!PostUpdateRes.isUsable())
11548             continue;
11549           ExprPostUpdates.push_back(
11550               IgnoredValueConversions(PostUpdateRes.get()).get());
11551         }
11552       }
11553     }
11554     if (LinKind == OMPC_LINEAR_uval)
11555       InitExpr = VD ? VD->getInit() : SimpleRefExpr;
11556     else
11557       InitExpr = VD ? SimpleRefExpr : Ref;
11558     AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
11559                          /*DirectInit=*/false);
11560     DeclRefExpr *InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
11561 
11562     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
11563     Vars.push_back((VD || CurContext->isDependentContext())
11564                        ? RefExpr->IgnoreParens()
11565                        : Ref);
11566     Privates.push_back(PrivateRef);
11567     Inits.push_back(InitRef);
11568   }
11569 
11570   if (Vars.empty())
11571     return nullptr;
11572 
11573   Expr *StepExpr = Step;
11574   Expr *CalcStepExpr = nullptr;
11575   if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
11576       !Step->isInstantiationDependent() &&
11577       !Step->containsUnexpandedParameterPack()) {
11578     SourceLocation StepLoc = Step->getBeginLoc();
11579     ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
11580     if (Val.isInvalid())
11581       return nullptr;
11582     StepExpr = Val.get();
11583 
11584     // Build var to save the step value.
11585     VarDecl *SaveVar =
11586         buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
11587     ExprResult SaveRef =
11588         buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
11589     ExprResult CalcStep =
11590         BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
11591     CalcStep = ActOnFinishFullExpr(CalcStep.get());
11592 
11593     // Warn about zero linear step (it would be probably better specified as
11594     // making corresponding variables 'const').
11595     llvm::APSInt Result;
11596     bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
11597     if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
11598       Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
11599                                                      << (Vars.size() > 1);
11600     if (!IsConstant && CalcStep.isUsable()) {
11601       // Calculate the step beforehand instead of doing this on each iteration.
11602       // (This is not used if the number of iterations may be kfold-ed).
11603       CalcStepExpr = CalcStep.get();
11604     }
11605   }
11606 
11607   return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
11608                                  ColonLoc, EndLoc, Vars, Privates, Inits,
11609                                  StepExpr, CalcStepExpr,
11610                                  buildPreInits(Context, ExprCaptures),
11611                                  buildPostUpdate(*this, ExprPostUpdates));
11612 }
11613 
11614 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
11615                                      Expr *NumIterations, Sema &SemaRef,
11616                                      Scope *S, DSAStackTy *Stack) {
11617   // Walk the vars and build update/final expressions for the CodeGen.
11618   SmallVector<Expr *, 8> Updates;
11619   SmallVector<Expr *, 8> Finals;
11620   Expr *Step = Clause.getStep();
11621   Expr *CalcStep = Clause.getCalcStep();
11622   // OpenMP [2.14.3.7, linear clause]
11623   // If linear-step is not specified it is assumed to be 1.
11624   if (!Step)
11625     Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
11626   else if (CalcStep)
11627     Step = cast<BinaryOperator>(CalcStep)->getLHS();
11628   bool HasErrors = false;
11629   auto CurInit = Clause.inits().begin();
11630   auto CurPrivate = Clause.privates().begin();
11631   OpenMPLinearClauseKind LinKind = Clause.getModifier();
11632   for (Expr *RefExpr : Clause.varlists()) {
11633     SourceLocation ELoc;
11634     SourceRange ERange;
11635     Expr *SimpleRefExpr = RefExpr;
11636     auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange);
11637     ValueDecl *D = Res.first;
11638     if (Res.second || !D) {
11639       Updates.push_back(nullptr);
11640       Finals.push_back(nullptr);
11641       HasErrors = true;
11642       continue;
11643     }
11644     auto &&Info = Stack->isLoopControlVariable(D);
11645     // OpenMP [2.15.11, distribute simd Construct]
11646     // A list item may not appear in a linear clause, unless it is the loop
11647     // iteration variable.
11648     if (isOpenMPDistributeDirective(Stack->getCurrentDirective()) &&
11649         isOpenMPSimdDirective(Stack->getCurrentDirective()) && !Info.first) {
11650       SemaRef.Diag(ELoc,
11651                    diag::err_omp_linear_distribute_var_non_loop_iteration);
11652       Updates.push_back(nullptr);
11653       Finals.push_back(nullptr);
11654       HasErrors = true;
11655       continue;
11656     }
11657     Expr *InitExpr = *CurInit;
11658 
11659     // Build privatized reference to the current linear var.
11660     auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
11661     Expr *CapturedRef;
11662     if (LinKind == OMPC_LINEAR_uval)
11663       CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
11664     else
11665       CapturedRef =
11666           buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
11667                            DE->getType().getUnqualifiedType(), DE->getExprLoc(),
11668                            /*RefersToCapture=*/true);
11669 
11670     // Build update: Var = InitExpr + IV * Step
11671     ExprResult Update;
11672     if (!Info.first)
11673       Update =
11674           buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate,
11675                              InitExpr, IV, Step, /* Subtract */ false);
11676     else
11677       Update = *CurPrivate;
11678     Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getBeginLoc(),
11679                                          /*DiscardedValue=*/true);
11680 
11681     // Build final: Var = InitExpr + NumIterations * Step
11682     ExprResult Final;
11683     if (!Info.first)
11684       Final =
11685           buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
11686                              InitExpr, NumIterations, Step, /*Subtract=*/false);
11687     else
11688       Final = *CurPrivate;
11689     Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getBeginLoc(),
11690                                         /*DiscardedValue=*/true);
11691 
11692     if (!Update.isUsable() || !Final.isUsable()) {
11693       Updates.push_back(nullptr);
11694       Finals.push_back(nullptr);
11695       HasErrors = true;
11696     } else {
11697       Updates.push_back(Update.get());
11698       Finals.push_back(Final.get());
11699     }
11700     ++CurInit;
11701     ++CurPrivate;
11702   }
11703   Clause.setUpdates(Updates);
11704   Clause.setFinals(Finals);
11705   return HasErrors;
11706 }
11707 
11708 OMPClause *Sema::ActOnOpenMPAlignedClause(
11709     ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
11710     SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
11711   SmallVector<Expr *, 8> Vars;
11712   for (Expr *RefExpr : VarList) {
11713     assert(RefExpr && "NULL expr in OpenMP linear clause.");
11714     SourceLocation ELoc;
11715     SourceRange ERange;
11716     Expr *SimpleRefExpr = RefExpr;
11717     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
11718     if (Res.second) {
11719       // It will be analyzed later.
11720       Vars.push_back(RefExpr);
11721     }
11722     ValueDecl *D = Res.first;
11723     if (!D)
11724       continue;
11725 
11726     QualType QType = D->getType();
11727     auto *VD = dyn_cast<VarDecl>(D);
11728 
11729     // OpenMP  [2.8.1, simd construct, Restrictions]
11730     // The type of list items appearing in the aligned clause must be
11731     // array, pointer, reference to array, or reference to pointer.
11732     QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
11733     const Type *Ty = QType.getTypePtrOrNull();
11734     if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
11735       Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
11736           << QType << getLangOpts().CPlusPlus << ERange;
11737       bool IsDecl =
11738           !VD ||
11739           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
11740       Diag(D->getLocation(),
11741            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
11742           << D;
11743       continue;
11744     }
11745 
11746     // OpenMP  [2.8.1, simd construct, Restrictions]
11747     // A list-item cannot appear in more than one aligned clause.
11748     if (const Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
11749       Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
11750       Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
11751           << getOpenMPClauseName(OMPC_aligned);
11752       continue;
11753     }
11754 
11755     DeclRefExpr *Ref = nullptr;
11756     if (!VD && isOpenMPCapturedDecl(D))
11757       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
11758     Vars.push_back(DefaultFunctionArrayConversion(
11759                        (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
11760                        .get());
11761   }
11762 
11763   // OpenMP [2.8.1, simd construct, Description]
11764   // The parameter of the aligned clause, alignment, must be a constant
11765   // positive integer expression.
11766   // If no optional parameter is specified, implementation-defined default
11767   // alignments for SIMD instructions on the target platforms are assumed.
11768   if (Alignment != nullptr) {
11769     ExprResult AlignResult =
11770         VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
11771     if (AlignResult.isInvalid())
11772       return nullptr;
11773     Alignment = AlignResult.get();
11774   }
11775   if (Vars.empty())
11776     return nullptr;
11777 
11778   return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
11779                                   EndLoc, Vars, Alignment);
11780 }
11781 
11782 OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
11783                                          SourceLocation StartLoc,
11784                                          SourceLocation LParenLoc,
11785                                          SourceLocation EndLoc) {
11786   SmallVector<Expr *, 8> Vars;
11787   SmallVector<Expr *, 8> SrcExprs;
11788   SmallVector<Expr *, 8> DstExprs;
11789   SmallVector<Expr *, 8> AssignmentOps;
11790   for (Expr *RefExpr : VarList) {
11791     assert(RefExpr && "NULL expr in OpenMP copyin clause.");
11792     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
11793       // It will be analyzed later.
11794       Vars.push_back(RefExpr);
11795       SrcExprs.push_back(nullptr);
11796       DstExprs.push_back(nullptr);
11797       AssignmentOps.push_back(nullptr);
11798       continue;
11799     }
11800 
11801     SourceLocation ELoc = RefExpr->getExprLoc();
11802     // OpenMP [2.1, C/C++]
11803     //  A list item is a variable name.
11804     // OpenMP  [2.14.4.1, Restrictions, p.1]
11805     //  A list item that appears in a copyin clause must be threadprivate.
11806     auto *DE = dyn_cast<DeclRefExpr>(RefExpr);
11807     if (!DE || !isa<VarDecl>(DE->getDecl())) {
11808       Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
11809           << 0 << RefExpr->getSourceRange();
11810       continue;
11811     }
11812 
11813     Decl *D = DE->getDecl();
11814     auto *VD = cast<VarDecl>(D);
11815 
11816     QualType Type = VD->getType();
11817     if (Type->isDependentType() || Type->isInstantiationDependentType()) {
11818       // It will be analyzed later.
11819       Vars.push_back(DE);
11820       SrcExprs.push_back(nullptr);
11821       DstExprs.push_back(nullptr);
11822       AssignmentOps.push_back(nullptr);
11823       continue;
11824     }
11825 
11826     // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
11827     //  A list item that appears in a copyin clause must be threadprivate.
11828     if (!DSAStack->isThreadPrivate(VD)) {
11829       Diag(ELoc, diag::err_omp_required_access)
11830           << getOpenMPClauseName(OMPC_copyin)
11831           << getOpenMPDirectiveName(OMPD_threadprivate);
11832       continue;
11833     }
11834 
11835     // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
11836     //  A variable of class type (or array thereof) that appears in a
11837     //  copyin clause requires an accessible, unambiguous copy assignment
11838     //  operator for the class type.
11839     QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
11840     VarDecl *SrcVD =
11841         buildVarDecl(*this, DE->getBeginLoc(), ElemType.getUnqualifiedType(),
11842                      ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
11843     DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(
11844         *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
11845     VarDecl *DstVD =
11846         buildVarDecl(*this, DE->getBeginLoc(), ElemType, ".copyin.dst",
11847                      VD->hasAttrs() ? &VD->getAttrs() : nullptr);
11848     DeclRefExpr *PseudoDstExpr =
11849         buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
11850     // For arrays generate assignment operation for single element and replace
11851     // it by the original array element in CodeGen.
11852     ExprResult AssignmentOp =
11853         BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign, PseudoDstExpr,
11854                    PseudoSrcExpr);
11855     if (AssignmentOp.isInvalid())
11856       continue;
11857     AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
11858                                        /*DiscardedValue=*/true);
11859     if (AssignmentOp.isInvalid())
11860       continue;
11861 
11862     DSAStack->addDSA(VD, DE, OMPC_copyin);
11863     Vars.push_back(DE);
11864     SrcExprs.push_back(PseudoSrcExpr);
11865     DstExprs.push_back(PseudoDstExpr);
11866     AssignmentOps.push_back(AssignmentOp.get());
11867   }
11868 
11869   if (Vars.empty())
11870     return nullptr;
11871 
11872   return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
11873                                  SrcExprs, DstExprs, AssignmentOps);
11874 }
11875 
11876 OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
11877                                               SourceLocation StartLoc,
11878                                               SourceLocation LParenLoc,
11879                                               SourceLocation EndLoc) {
11880   SmallVector<Expr *, 8> Vars;
11881   SmallVector<Expr *, 8> SrcExprs;
11882   SmallVector<Expr *, 8> DstExprs;
11883   SmallVector<Expr *, 8> AssignmentOps;
11884   for (Expr *RefExpr : VarList) {
11885     assert(RefExpr && "NULL expr in OpenMP linear clause.");
11886     SourceLocation ELoc;
11887     SourceRange ERange;
11888     Expr *SimpleRefExpr = RefExpr;
11889     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
11890     if (Res.second) {
11891       // It will be analyzed later.
11892       Vars.push_back(RefExpr);
11893       SrcExprs.push_back(nullptr);
11894       DstExprs.push_back(nullptr);
11895       AssignmentOps.push_back(nullptr);
11896     }
11897     ValueDecl *D = Res.first;
11898     if (!D)
11899       continue;
11900 
11901     QualType Type = D->getType();
11902     auto *VD = dyn_cast<VarDecl>(D);
11903 
11904     // OpenMP [2.14.4.2, Restrictions, p.2]
11905     //  A list item that appears in a copyprivate clause may not appear in a
11906     //  private or firstprivate clause on the single construct.
11907     if (!VD || !DSAStack->isThreadPrivate(VD)) {
11908       DSAStackTy::DSAVarData DVar =
11909           DSAStack->getTopDSA(D, /*FromParent=*/false);
11910       if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
11911           DVar.RefExpr) {
11912         Diag(ELoc, diag::err_omp_wrong_dsa)
11913             << getOpenMPClauseName(DVar.CKind)
11914             << getOpenMPClauseName(OMPC_copyprivate);
11915         reportOriginalDsa(*this, DSAStack, D, DVar);
11916         continue;
11917       }
11918 
11919       // OpenMP [2.11.4.2, Restrictions, p.1]
11920       //  All list items that appear in a copyprivate clause must be either
11921       //  threadprivate or private in the enclosing context.
11922       if (DVar.CKind == OMPC_unknown) {
11923         DVar = DSAStack->getImplicitDSA(D, false);
11924         if (DVar.CKind == OMPC_shared) {
11925           Diag(ELoc, diag::err_omp_required_access)
11926               << getOpenMPClauseName(OMPC_copyprivate)
11927               << "threadprivate or private in the enclosing context";
11928           reportOriginalDsa(*this, DSAStack, D, DVar);
11929           continue;
11930         }
11931       }
11932     }
11933 
11934     // Variably modified types are not supported.
11935     if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
11936       Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
11937           << getOpenMPClauseName(OMPC_copyprivate) << Type
11938           << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
11939       bool IsDecl =
11940           !VD ||
11941           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
11942       Diag(D->getLocation(),
11943            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
11944           << D;
11945       continue;
11946     }
11947 
11948     // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
11949     //  A variable of class type (or array thereof) that appears in a
11950     //  copyin clause requires an accessible, unambiguous copy assignment
11951     //  operator for the class type.
11952     Type = Context.getBaseElementType(Type.getNonReferenceType())
11953                .getUnqualifiedType();
11954     VarDecl *SrcVD =
11955         buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.src",
11956                      D->hasAttrs() ? &D->getAttrs() : nullptr);
11957     DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
11958     VarDecl *DstVD =
11959         buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.dst",
11960                      D->hasAttrs() ? &D->getAttrs() : nullptr);
11961     DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
11962     ExprResult AssignmentOp = BuildBinOp(
11963         DSAStack->getCurScope(), ELoc, BO_Assign, PseudoDstExpr, PseudoSrcExpr);
11964     if (AssignmentOp.isInvalid())
11965       continue;
11966     AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
11967                                        /*DiscardedValue=*/true);
11968     if (AssignmentOp.isInvalid())
11969       continue;
11970 
11971     // No need to mark vars as copyprivate, they are already threadprivate or
11972     // implicitly private.
11973     assert(VD || isOpenMPCapturedDecl(D));
11974     Vars.push_back(
11975         VD ? RefExpr->IgnoreParens()
11976            : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
11977     SrcExprs.push_back(PseudoSrcExpr);
11978     DstExprs.push_back(PseudoDstExpr);
11979     AssignmentOps.push_back(AssignmentOp.get());
11980   }
11981 
11982   if (Vars.empty())
11983     return nullptr;
11984 
11985   return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
11986                                       Vars, SrcExprs, DstExprs, AssignmentOps);
11987 }
11988 
11989 OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
11990                                         SourceLocation StartLoc,
11991                                         SourceLocation LParenLoc,
11992                                         SourceLocation EndLoc) {
11993   if (VarList.empty())
11994     return nullptr;
11995 
11996   return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
11997 }
11998 
11999 OMPClause *
12000 Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
12001                               SourceLocation DepLoc, SourceLocation ColonLoc,
12002                               ArrayRef<Expr *> VarList, SourceLocation StartLoc,
12003                               SourceLocation LParenLoc, SourceLocation EndLoc) {
12004   if (DSAStack->getCurrentDirective() == OMPD_ordered &&
12005       DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
12006     Diag(DepLoc, diag::err_omp_unexpected_clause_value)
12007         << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
12008     return nullptr;
12009   }
12010   if (DSAStack->getCurrentDirective() != OMPD_ordered &&
12011       (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
12012        DepKind == OMPC_DEPEND_sink)) {
12013     unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
12014     Diag(DepLoc, diag::err_omp_unexpected_clause_value)
12015         << getListOfPossibleValues(OMPC_depend, /*First=*/0,
12016                                    /*Last=*/OMPC_DEPEND_unknown, Except)
12017         << getOpenMPClauseName(OMPC_depend);
12018     return nullptr;
12019   }
12020   SmallVector<Expr *, 8> Vars;
12021   DSAStackTy::OperatorOffsetTy OpsOffs;
12022   llvm::APSInt DepCounter(/*BitWidth=*/32);
12023   llvm::APSInt TotalDepCount(/*BitWidth=*/32);
12024   if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) {
12025     if (const Expr *OrderedCountExpr =
12026             DSAStack->getParentOrderedRegionParam().first) {
12027       TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
12028       TotalDepCount.setIsUnsigned(/*Val=*/true);
12029     }
12030   }
12031   for (Expr *RefExpr : VarList) {
12032     assert(RefExpr && "NULL expr in OpenMP shared clause.");
12033     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
12034       // It will be analyzed later.
12035       Vars.push_back(RefExpr);
12036       continue;
12037     }
12038 
12039     SourceLocation ELoc = RefExpr->getExprLoc();
12040     Expr *SimpleExpr = RefExpr->IgnoreParenCasts();
12041     if (DepKind == OMPC_DEPEND_sink) {
12042       if (DSAStack->getParentOrderedRegionParam().first &&
12043           DepCounter >= TotalDepCount) {
12044         Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
12045         continue;
12046       }
12047       ++DepCounter;
12048       // OpenMP  [2.13.9, Summary]
12049       // depend(dependence-type : vec), where dependence-type is:
12050       // 'sink' and where vec is the iteration vector, which has the form:
12051       //  x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
12052       // where n is the value specified by the ordered clause in the loop
12053       // directive, xi denotes the loop iteration variable of the i-th nested
12054       // loop associated with the loop directive, and di is a constant
12055       // non-negative integer.
12056       if (CurContext->isDependentContext()) {
12057         // It will be analyzed later.
12058         Vars.push_back(RefExpr);
12059         continue;
12060       }
12061       SimpleExpr = SimpleExpr->IgnoreImplicit();
12062       OverloadedOperatorKind OOK = OO_None;
12063       SourceLocation OOLoc;
12064       Expr *LHS = SimpleExpr;
12065       Expr *RHS = nullptr;
12066       if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
12067         OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
12068         OOLoc = BO->getOperatorLoc();
12069         LHS = BO->getLHS()->IgnoreParenImpCasts();
12070         RHS = BO->getRHS()->IgnoreParenImpCasts();
12071       } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
12072         OOK = OCE->getOperator();
12073         OOLoc = OCE->getOperatorLoc();
12074         LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
12075         RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
12076       } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
12077         OOK = MCE->getMethodDecl()
12078                   ->getNameInfo()
12079                   .getName()
12080                   .getCXXOverloadedOperator();
12081         OOLoc = MCE->getCallee()->getExprLoc();
12082         LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
12083         RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
12084       }
12085       SourceLocation ELoc;
12086       SourceRange ERange;
12087       auto Res = getPrivateItem(*this, LHS, ELoc, ERange);
12088       if (Res.second) {
12089         // It will be analyzed later.
12090         Vars.push_back(RefExpr);
12091       }
12092       ValueDecl *D = Res.first;
12093       if (!D)
12094         continue;
12095 
12096       if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
12097         Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
12098         continue;
12099       }
12100       if (RHS) {
12101         ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
12102             RHS, OMPC_depend, /*StrictlyPositive=*/false);
12103         if (RHSRes.isInvalid())
12104           continue;
12105       }
12106       if (!CurContext->isDependentContext() &&
12107           DSAStack->getParentOrderedRegionParam().first &&
12108           DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
12109         const ValueDecl *VD =
12110             DSAStack->getParentLoopControlVariable(DepCounter.getZExtValue());
12111         if (VD)
12112           Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
12113               << 1 << VD;
12114         else
12115           Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0;
12116         continue;
12117       }
12118       OpsOffs.emplace_back(RHS, OOK);
12119     } else {
12120       auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
12121       if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
12122           (ASE &&
12123            !ASE->getBase()->getType().getNonReferenceType()->isPointerType() &&
12124            !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
12125         Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
12126             << RefExpr->getSourceRange();
12127         continue;
12128       }
12129       bool Suppress = getDiagnostics().getSuppressAllDiagnostics();
12130       getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
12131       ExprResult Res =
12132           CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RefExpr->IgnoreParenImpCasts());
12133       getDiagnostics().setSuppressAllDiagnostics(Suppress);
12134       if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr)) {
12135         Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
12136             << RefExpr->getSourceRange();
12137         continue;
12138       }
12139     }
12140     Vars.push_back(RefExpr->IgnoreParenImpCasts());
12141   }
12142 
12143   if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
12144       TotalDepCount > VarList.size() &&
12145       DSAStack->getParentOrderedRegionParam().first &&
12146       DSAStack->getParentLoopControlVariable(VarList.size() + 1)) {
12147     Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
12148         << 1 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
12149   }
12150   if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
12151       Vars.empty())
12152     return nullptr;
12153 
12154   auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
12155                                     DepKind, DepLoc, ColonLoc, Vars,
12156                                     TotalDepCount.getZExtValue());
12157   if ((DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) &&
12158       DSAStack->isParentOrderedRegion())
12159     DSAStack->addDoacrossDependClause(C, OpsOffs);
12160   return C;
12161 }
12162 
12163 OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
12164                                          SourceLocation LParenLoc,
12165                                          SourceLocation EndLoc) {
12166   Expr *ValExpr = Device;
12167   Stmt *HelperValStmt = nullptr;
12168 
12169   // OpenMP [2.9.1, Restrictions]
12170   // The device expression must evaluate to a non-negative integer value.
12171   if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
12172                                  /*StrictlyPositive=*/false))
12173     return nullptr;
12174 
12175   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
12176   OpenMPDirectiveKind CaptureRegion =
12177       getOpenMPCaptureRegionForClause(DKind, OMPC_device);
12178   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
12179     ValExpr = MakeFullExpr(ValExpr).get();
12180     llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
12181     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
12182     HelperValStmt = buildPreInits(Context, Captures);
12183   }
12184 
12185   return new (Context) OMPDeviceClause(ValExpr, HelperValStmt, CaptureRegion,
12186                                        StartLoc, LParenLoc, EndLoc);
12187 }
12188 
12189 static bool checkTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
12190                               DSAStackTy *Stack, QualType QTy,
12191                               bool FullCheck = true) {
12192   NamedDecl *ND;
12193   if (QTy->isIncompleteType(&ND)) {
12194     SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
12195     return false;
12196   }
12197   if (FullCheck && !SemaRef.CurContext->isDependentContext() &&
12198       !QTy.isTrivialType(SemaRef.Context))
12199     SemaRef.Diag(SL, diag::warn_omp_non_trivial_type_mapped) << QTy << SR;
12200   return true;
12201 }
12202 
12203 /// Return true if it can be proven that the provided array expression
12204 /// (array section or array subscript) does NOT specify the whole size of the
12205 /// array whose base type is \a BaseQTy.
12206 static bool checkArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
12207                                                         const Expr *E,
12208                                                         QualType BaseQTy) {
12209   const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
12210 
12211   // If this is an array subscript, it refers to the whole size if the size of
12212   // the dimension is constant and equals 1. Also, an array section assumes the
12213   // format of an array subscript if no colon is used.
12214   if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
12215     if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
12216       return ATy->getSize().getSExtValue() != 1;
12217     // Size can't be evaluated statically.
12218     return false;
12219   }
12220 
12221   assert(OASE && "Expecting array section if not an array subscript.");
12222   const Expr *LowerBound = OASE->getLowerBound();
12223   const Expr *Length = OASE->getLength();
12224 
12225   // If there is a lower bound that does not evaluates to zero, we are not
12226   // covering the whole dimension.
12227   if (LowerBound) {
12228     Expr::EvalResult Result;
12229     if (!LowerBound->EvaluateAsInt(Result, SemaRef.getASTContext()))
12230       return false; // Can't get the integer value as a constant.
12231 
12232     llvm::APSInt ConstLowerBound = Result.Val.getInt();
12233     if (ConstLowerBound.getSExtValue())
12234       return true;
12235   }
12236 
12237   // If we don't have a length we covering the whole dimension.
12238   if (!Length)
12239     return false;
12240 
12241   // If the base is a pointer, we don't have a way to get the size of the
12242   // pointee.
12243   if (BaseQTy->isPointerType())
12244     return false;
12245 
12246   // We can only check if the length is the same as the size of the dimension
12247   // if we have a constant array.
12248   const auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
12249   if (!CATy)
12250     return false;
12251 
12252   Expr::EvalResult Result;
12253   if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
12254     return false; // Can't get the integer value as a constant.
12255 
12256   llvm::APSInt ConstLength = Result.Val.getInt();
12257   return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
12258 }
12259 
12260 // Return true if it can be proven that the provided array expression (array
12261 // section or array subscript) does NOT specify a single element of the array
12262 // whose base type is \a BaseQTy.
12263 static bool checkArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
12264                                                         const Expr *E,
12265                                                         QualType BaseQTy) {
12266   const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
12267 
12268   // An array subscript always refer to a single element. Also, an array section
12269   // assumes the format of an array subscript if no colon is used.
12270   if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
12271     return false;
12272 
12273   assert(OASE && "Expecting array section if not an array subscript.");
12274   const Expr *Length = OASE->getLength();
12275 
12276   // If we don't have a length we have to check if the array has unitary size
12277   // for this dimension. Also, we should always expect a length if the base type
12278   // is pointer.
12279   if (!Length) {
12280     if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
12281       return ATy->getSize().getSExtValue() != 1;
12282     // We cannot assume anything.
12283     return false;
12284   }
12285 
12286   // Check if the length evaluates to 1.
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 ConstLength.getSExtValue() != 1;
12293 }
12294 
12295 // Return the expression of the base of the mappable expression or null if it
12296 // cannot be determined and do all the necessary checks to see if the expression
12297 // is valid as a standalone mappable expression. In the process, record all the
12298 // components of the expression.
12299 static const Expr *checkMapClauseExpressionBase(
12300     Sema &SemaRef, Expr *E,
12301     OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
12302     OpenMPClauseKind CKind, bool NoDiagnose) {
12303   SourceLocation ELoc = E->getExprLoc();
12304   SourceRange ERange = E->getSourceRange();
12305 
12306   // The base of elements of list in a map clause have to be either:
12307   //  - a reference to variable or field.
12308   //  - a member expression.
12309   //  - an array expression.
12310   //
12311   // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
12312   // reference to 'r'.
12313   //
12314   // If we have:
12315   //
12316   // struct SS {
12317   //   Bla S;
12318   //   foo() {
12319   //     #pragma omp target map (S.Arr[:12]);
12320   //   }
12321   // }
12322   //
12323   // We want to retrieve the member expression 'this->S';
12324 
12325   const Expr *RelevantExpr = nullptr;
12326 
12327   // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
12328   //  If a list item is an array section, it must specify contiguous storage.
12329   //
12330   // For this restriction it is sufficient that we make sure only references
12331   // to variables or fields and array expressions, and that no array sections
12332   // exist except in the rightmost expression (unless they cover the whole
12333   // dimension of the array). E.g. these would be invalid:
12334   //
12335   //   r.ArrS[3:5].Arr[6:7]
12336   //
12337   //   r.ArrS[3:5].x
12338   //
12339   // but these would be valid:
12340   //   r.ArrS[3].Arr[6:7]
12341   //
12342   //   r.ArrS[3].x
12343 
12344   bool AllowUnitySizeArraySection = true;
12345   bool AllowWholeSizeArraySection = true;
12346 
12347   while (!RelevantExpr) {
12348     E = E->IgnoreParenImpCasts();
12349 
12350     if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
12351       if (!isa<VarDecl>(CurE->getDecl()))
12352         return nullptr;
12353 
12354       RelevantExpr = CurE;
12355 
12356       // If we got a reference to a declaration, we should not expect any array
12357       // section before that.
12358       AllowUnitySizeArraySection = false;
12359       AllowWholeSizeArraySection = false;
12360 
12361       // Record the component.
12362       CurComponents.emplace_back(CurE, CurE->getDecl());
12363     } else if (auto *CurE = dyn_cast<MemberExpr>(E)) {
12364       Expr *BaseE = CurE->getBase()->IgnoreParenImpCasts();
12365 
12366       if (isa<CXXThisExpr>(BaseE))
12367         // We found a base expression: this->Val.
12368         RelevantExpr = CurE;
12369       else
12370         E = BaseE;
12371 
12372       if (!isa<FieldDecl>(CurE->getMemberDecl())) {
12373         if (!NoDiagnose) {
12374           SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
12375               << CurE->getSourceRange();
12376           return nullptr;
12377         }
12378         if (RelevantExpr)
12379           return nullptr;
12380         continue;
12381       }
12382 
12383       auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
12384 
12385       // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
12386       //  A bit-field cannot appear in a map clause.
12387       //
12388       if (FD->isBitField()) {
12389         if (!NoDiagnose) {
12390           SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
12391               << CurE->getSourceRange() << getOpenMPClauseName(CKind);
12392           return nullptr;
12393         }
12394         if (RelevantExpr)
12395           return nullptr;
12396         continue;
12397       }
12398 
12399       // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
12400       //  If the type of a list item is a reference to a type T then the type
12401       //  will be considered to be T for all purposes of this clause.
12402       QualType CurType = BaseE->getType().getNonReferenceType();
12403 
12404       // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
12405       //  A list item cannot be a variable that is a member of a structure with
12406       //  a union type.
12407       //
12408       if (CurType->isUnionType()) {
12409         if (!NoDiagnose) {
12410           SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
12411               << CurE->getSourceRange();
12412           return nullptr;
12413         }
12414         continue;
12415       }
12416 
12417       // If we got a member expression, we should not expect any array section
12418       // before that:
12419       //
12420       // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
12421       //  If a list item is an element of a structure, only the rightmost symbol
12422       //  of the variable reference can be an array section.
12423       //
12424       AllowUnitySizeArraySection = false;
12425       AllowWholeSizeArraySection = false;
12426 
12427       // Record the component.
12428       CurComponents.emplace_back(CurE, FD);
12429     } else if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
12430       E = CurE->getBase()->IgnoreParenImpCasts();
12431 
12432       if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
12433         if (!NoDiagnose) {
12434           SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
12435               << 0 << CurE->getSourceRange();
12436           return nullptr;
12437         }
12438         continue;
12439       }
12440 
12441       // If we got an array subscript that express the whole dimension we
12442       // can have any array expressions before. If it only expressing part of
12443       // the dimension, we can only have unitary-size array expressions.
12444       if (checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
12445                                                       E->getType()))
12446         AllowWholeSizeArraySection = false;
12447 
12448       // Record the component - we don't have any declaration associated.
12449       CurComponents.emplace_back(CurE, nullptr);
12450     } else if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
12451       assert(!NoDiagnose && "Array sections cannot be implicitly mapped.");
12452       E = CurE->getBase()->IgnoreParenImpCasts();
12453 
12454       QualType CurType =
12455           OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
12456 
12457       // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
12458       //  If the type of a list item is a reference to a type T then the type
12459       //  will be considered to be T for all purposes of this clause.
12460       if (CurType->isReferenceType())
12461         CurType = CurType->getPointeeType();
12462 
12463       bool IsPointer = CurType->isAnyPointerType();
12464 
12465       if (!IsPointer && !CurType->isArrayType()) {
12466         SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
12467             << 0 << CurE->getSourceRange();
12468         return nullptr;
12469       }
12470 
12471       bool NotWhole =
12472           checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
12473       bool NotUnity =
12474           checkArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
12475 
12476       if (AllowWholeSizeArraySection) {
12477         // Any array section is currently allowed. Allowing a whole size array
12478         // section implies allowing a unity array section as well.
12479         //
12480         // If this array section refers to the whole dimension we can still
12481         // accept other array sections before this one, except if the base is a
12482         // pointer. Otherwise, only unitary sections are accepted.
12483         if (NotWhole || IsPointer)
12484           AllowWholeSizeArraySection = false;
12485       } else if (AllowUnitySizeArraySection && NotUnity) {
12486         // A unity or whole array section is not allowed and that is not
12487         // compatible with the properties of the current array section.
12488         SemaRef.Diag(
12489             ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
12490             << CurE->getSourceRange();
12491         return nullptr;
12492       }
12493 
12494       // Record the component - we don't have any declaration associated.
12495       CurComponents.emplace_back(CurE, nullptr);
12496     } else {
12497       if (!NoDiagnose) {
12498         // If nothing else worked, this is not a valid map clause expression.
12499         SemaRef.Diag(
12500             ELoc, diag::err_omp_expected_named_var_member_or_array_expression)
12501             << ERange;
12502       }
12503       return nullptr;
12504     }
12505   }
12506 
12507   return RelevantExpr;
12508 }
12509 
12510 // Return true if expression E associated with value VD has conflicts with other
12511 // map information.
12512 static bool checkMapConflicts(
12513     Sema &SemaRef, DSAStackTy *DSAS, const ValueDecl *VD, const Expr *E,
12514     bool CurrentRegionOnly,
12515     OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
12516     OpenMPClauseKind CKind) {
12517   assert(VD && E);
12518   SourceLocation ELoc = E->getExprLoc();
12519   SourceRange ERange = E->getSourceRange();
12520 
12521   // In order to easily check the conflicts we need to match each component of
12522   // the expression under test with the components of the expressions that are
12523   // already in the stack.
12524 
12525   assert(!CurComponents.empty() && "Map clause expression with no components!");
12526   assert(CurComponents.back().getAssociatedDeclaration() == VD &&
12527          "Map clause expression with unexpected base!");
12528 
12529   // Variables to help detecting enclosing problems in data environment nests.
12530   bool IsEnclosedByDataEnvironmentExpr = false;
12531   const Expr *EnclosingExpr = nullptr;
12532 
12533   bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
12534       VD, CurrentRegionOnly,
12535       [&IsEnclosedByDataEnvironmentExpr, &SemaRef, VD, CurrentRegionOnly, ELoc,
12536        ERange, CKind, &EnclosingExpr,
12537        CurComponents](OMPClauseMappableExprCommon::MappableExprComponentListRef
12538                           StackComponents,
12539                       OpenMPClauseKind) {
12540         assert(!StackComponents.empty() &&
12541                "Map clause expression with no components!");
12542         assert(StackComponents.back().getAssociatedDeclaration() == VD &&
12543                "Map clause expression with unexpected base!");
12544         (void)VD;
12545 
12546         // The whole expression in the stack.
12547         const Expr *RE = StackComponents.front().getAssociatedExpression();
12548 
12549         // Expressions must start from the same base. Here we detect at which
12550         // point both expressions diverge from each other and see if we can
12551         // detect if the memory referred to both expressions is contiguous and
12552         // do not overlap.
12553         auto CI = CurComponents.rbegin();
12554         auto CE = CurComponents.rend();
12555         auto SI = StackComponents.rbegin();
12556         auto SE = StackComponents.rend();
12557         for (; CI != CE && SI != SE; ++CI, ++SI) {
12558 
12559           // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
12560           //  At most one list item can be an array item derived from a given
12561           //  variable in map clauses of the same construct.
12562           if (CurrentRegionOnly &&
12563               (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
12564                isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
12565               (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
12566                isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
12567             SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
12568                          diag::err_omp_multiple_array_items_in_map_clause)
12569                 << CI->getAssociatedExpression()->getSourceRange();
12570             SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
12571                          diag::note_used_here)
12572                 << SI->getAssociatedExpression()->getSourceRange();
12573             return true;
12574           }
12575 
12576           // Do both expressions have the same kind?
12577           if (CI->getAssociatedExpression()->getStmtClass() !=
12578               SI->getAssociatedExpression()->getStmtClass())
12579             break;
12580 
12581           // Are we dealing with different variables/fields?
12582           if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
12583             break;
12584         }
12585         // Check if the extra components of the expressions in the enclosing
12586         // data environment are redundant for the current base declaration.
12587         // If they are, the maps completely overlap, which is legal.
12588         for (; SI != SE; ++SI) {
12589           QualType Type;
12590           if (const auto *ASE =
12591                   dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
12592             Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
12593           } else if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(
12594                          SI->getAssociatedExpression())) {
12595             const Expr *E = OASE->getBase()->IgnoreParenImpCasts();
12596             Type =
12597                 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
12598           }
12599           if (Type.isNull() || Type->isAnyPointerType() ||
12600               checkArrayExpressionDoesNotReferToWholeSize(
12601                   SemaRef, SI->getAssociatedExpression(), Type))
12602             break;
12603         }
12604 
12605         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
12606         //  List items of map clauses in the same construct must not share
12607         //  original storage.
12608         //
12609         // If the expressions are exactly the same or one is a subset of the
12610         // other, it means they are sharing storage.
12611         if (CI == CE && SI == SE) {
12612           if (CurrentRegionOnly) {
12613             if (CKind == OMPC_map) {
12614               SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
12615             } else {
12616               assert(CKind == OMPC_to || CKind == OMPC_from);
12617               SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
12618                   << ERange;
12619             }
12620             SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
12621                 << RE->getSourceRange();
12622             return true;
12623           }
12624           // If we find the same expression in the enclosing data environment,
12625           // that is legal.
12626           IsEnclosedByDataEnvironmentExpr = true;
12627           return false;
12628         }
12629 
12630         QualType DerivedType =
12631             std::prev(CI)->getAssociatedDeclaration()->getType();
12632         SourceLocation DerivedLoc =
12633             std::prev(CI)->getAssociatedExpression()->getExprLoc();
12634 
12635         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
12636         //  If the type of a list item is a reference to a type T then the type
12637         //  will be considered to be T for all purposes of this clause.
12638         DerivedType = DerivedType.getNonReferenceType();
12639 
12640         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
12641         //  A variable for which the type is pointer and an array section
12642         //  derived from that variable must not appear as list items of map
12643         //  clauses of the same construct.
12644         //
12645         // Also, cover one of the cases in:
12646         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
12647         //  If any part of the original storage of a list item has corresponding
12648         //  storage in the device data environment, all of the original storage
12649         //  must have corresponding storage in the device data environment.
12650         //
12651         if (DerivedType->isAnyPointerType()) {
12652           if (CI == CE || SI == SE) {
12653             SemaRef.Diag(
12654                 DerivedLoc,
12655                 diag::err_omp_pointer_mapped_along_with_derived_section)
12656                 << DerivedLoc;
12657             SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
12658                 << RE->getSourceRange();
12659             return true;
12660           }
12661           if (CI->getAssociatedExpression()->getStmtClass() !=
12662                          SI->getAssociatedExpression()->getStmtClass() ||
12663                      CI->getAssociatedDeclaration()->getCanonicalDecl() ==
12664                          SI->getAssociatedDeclaration()->getCanonicalDecl()) {
12665             assert(CI != CE && SI != SE);
12666             SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_dereferenced)
12667                 << DerivedLoc;
12668             SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
12669                 << RE->getSourceRange();
12670             return true;
12671           }
12672         }
12673 
12674         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
12675         //  List items of map clauses in the same construct must not share
12676         //  original storage.
12677         //
12678         // An expression is a subset of the other.
12679         if (CurrentRegionOnly && (CI == CE || SI == SE)) {
12680           if (CKind == OMPC_map) {
12681             if (CI != CE || SI != SE) {
12682               // Allow constructs like this: map(s, s.ptr[0:1]), where s.ptr is
12683               // a pointer.
12684               auto Begin =
12685                   CI != CE ? CurComponents.begin() : StackComponents.begin();
12686               auto End = CI != CE ? CurComponents.end() : StackComponents.end();
12687               auto It = Begin;
12688               while (It != End && !It->getAssociatedDeclaration())
12689                 std::advance(It, 1);
12690               assert(It != End &&
12691                      "Expected at least one component with the declaration.");
12692               if (It != Begin && It->getAssociatedDeclaration()
12693                                      ->getType()
12694                                      .getCanonicalType()
12695                                      ->isAnyPointerType()) {
12696                 IsEnclosedByDataEnvironmentExpr = false;
12697                 EnclosingExpr = nullptr;
12698                 return false;
12699               }
12700             }
12701             SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
12702           } else {
12703             assert(CKind == OMPC_to || CKind == OMPC_from);
12704             SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
12705                 << ERange;
12706           }
12707           SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
12708               << RE->getSourceRange();
12709           return true;
12710         }
12711 
12712         // The current expression uses the same base as other expression in the
12713         // data environment but does not contain it completely.
12714         if (!CurrentRegionOnly && SI != SE)
12715           EnclosingExpr = RE;
12716 
12717         // The current expression is a subset of the expression in the data
12718         // environment.
12719         IsEnclosedByDataEnvironmentExpr |=
12720             (!CurrentRegionOnly && CI != CE && SI == SE);
12721 
12722         return false;
12723       });
12724 
12725   if (CurrentRegionOnly)
12726     return FoundError;
12727 
12728   // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
12729   //  If any part of the original storage of a list item has corresponding
12730   //  storage in the device data environment, all of the original storage must
12731   //  have corresponding storage in the device data environment.
12732   // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
12733   //  If a list item is an element of a structure, and a different element of
12734   //  the structure has a corresponding list item in the device data environment
12735   //  prior to a task encountering the construct associated with the map clause,
12736   //  then the list item must also have a corresponding list item in the device
12737   //  data environment prior to the task encountering the construct.
12738   //
12739   if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
12740     SemaRef.Diag(ELoc,
12741                  diag::err_omp_original_storage_is_shared_and_does_not_contain)
12742         << ERange;
12743     SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
12744         << EnclosingExpr->getSourceRange();
12745     return true;
12746   }
12747 
12748   return FoundError;
12749 }
12750 
12751 namespace {
12752 // Utility struct that gathers all the related lists associated with a mappable
12753 // expression.
12754 struct MappableVarListInfo {
12755   // The list of expressions.
12756   ArrayRef<Expr *> VarList;
12757   // The list of processed expressions.
12758   SmallVector<Expr *, 16> ProcessedVarList;
12759   // The mappble components for each expression.
12760   OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
12761   // The base declaration of the variable.
12762   SmallVector<ValueDecl *, 16> VarBaseDeclarations;
12763 
12764   MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
12765     // We have a list of components and base declarations for each entry in the
12766     // variable list.
12767     VarComponents.reserve(VarList.size());
12768     VarBaseDeclarations.reserve(VarList.size());
12769   }
12770 };
12771 }
12772 
12773 // Check the validity of the provided variable list for the provided clause kind
12774 // \a CKind. In the check process the valid expressions, and mappable expression
12775 // components and variables are extracted and used to fill \a Vars,
12776 // \a ClauseComponents, and \a ClauseBaseDeclarations. \a MapType and
12777 // \a IsMapTypeImplicit are expected to be valid if the clause kind is 'map'.
12778 static void
12779 checkMappableExpressionList(Sema &SemaRef, DSAStackTy *DSAS,
12780                             OpenMPClauseKind CKind, MappableVarListInfo &MVLI,
12781                             SourceLocation StartLoc,
12782                             OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
12783                             bool IsMapTypeImplicit = false) {
12784   // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
12785   assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
12786          "Unexpected clause kind with mappable expressions!");
12787 
12788   // Keep track of the mappable components and base declarations in this clause.
12789   // Each entry in the list is going to have a list of components associated. We
12790   // record each set of the components so that we can build the clause later on.
12791   // In the end we should have the same amount of declarations and component
12792   // lists.
12793 
12794   for (Expr *RE : MVLI.VarList) {
12795     assert(RE && "Null expr in omp to/from/map clause");
12796     SourceLocation ELoc = RE->getExprLoc();
12797 
12798     const Expr *VE = RE->IgnoreParenLValueCasts();
12799 
12800     if (VE->isValueDependent() || VE->isTypeDependent() ||
12801         VE->isInstantiationDependent() ||
12802         VE->containsUnexpandedParameterPack()) {
12803       // We can only analyze this information once the missing information is
12804       // resolved.
12805       MVLI.ProcessedVarList.push_back(RE);
12806       continue;
12807     }
12808 
12809     Expr *SimpleExpr = RE->IgnoreParenCasts();
12810 
12811     if (!RE->IgnoreParenImpCasts()->isLValue()) {
12812       SemaRef.Diag(ELoc,
12813                    diag::err_omp_expected_named_var_member_or_array_expression)
12814           << RE->getSourceRange();
12815       continue;
12816     }
12817 
12818     OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
12819     ValueDecl *CurDeclaration = nullptr;
12820 
12821     // Obtain the array or member expression bases if required. Also, fill the
12822     // components array with all the components identified in the process.
12823     const Expr *BE = checkMapClauseExpressionBase(
12824         SemaRef, SimpleExpr, CurComponents, CKind, /*NoDiagnose=*/false);
12825     if (!BE)
12826       continue;
12827 
12828     assert(!CurComponents.empty() &&
12829            "Invalid mappable expression information.");
12830 
12831     // For the following checks, we rely on the base declaration which is
12832     // expected to be associated with the last component. The declaration is
12833     // expected to be a variable or a field (if 'this' is being mapped).
12834     CurDeclaration = CurComponents.back().getAssociatedDeclaration();
12835     assert(CurDeclaration && "Null decl on map clause.");
12836     assert(
12837         CurDeclaration->isCanonicalDecl() &&
12838         "Expecting components to have associated only canonical declarations.");
12839 
12840     auto *VD = dyn_cast<VarDecl>(CurDeclaration);
12841     const auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
12842 
12843     assert((VD || FD) && "Only variables or fields are expected here!");
12844     (void)FD;
12845 
12846     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
12847     // threadprivate variables cannot appear in a map clause.
12848     // OpenMP 4.5 [2.10.5, target update Construct]
12849     // threadprivate variables cannot appear in a from clause.
12850     if (VD && DSAS->isThreadPrivate(VD)) {
12851       DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
12852       SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
12853           << getOpenMPClauseName(CKind);
12854       reportOriginalDsa(SemaRef, DSAS, VD, DVar);
12855       continue;
12856     }
12857 
12858     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
12859     //  A list item cannot appear in both a map clause and a data-sharing
12860     //  attribute clause on the same construct.
12861 
12862     // Check conflicts with other map clause expressions. We check the conflicts
12863     // with the current construct separately from the enclosing data
12864     // environment, because the restrictions are different. We only have to
12865     // check conflicts across regions for the map clauses.
12866     if (checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
12867                           /*CurrentRegionOnly=*/true, CurComponents, CKind))
12868       break;
12869     if (CKind == OMPC_map &&
12870         checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
12871                           /*CurrentRegionOnly=*/false, CurComponents, CKind))
12872       break;
12873 
12874     // OpenMP 4.5 [2.10.5, target update Construct]
12875     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
12876     //  If the type of a list item is a reference to a type T then the type will
12877     //  be considered to be T for all purposes of this clause.
12878     auto I = llvm::find_if(
12879         CurComponents,
12880         [](const OMPClauseMappableExprCommon::MappableComponent &MC) {
12881           return MC.getAssociatedDeclaration();
12882         });
12883     assert(I != CurComponents.end() && "Null decl on map clause.");
12884     QualType Type =
12885         I->getAssociatedDeclaration()->getType().getNonReferenceType();
12886 
12887     // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
12888     // A list item in a to or from clause must have a mappable type.
12889     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
12890     //  A list item must have a mappable type.
12891     if (!checkTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
12892                            DSAS, Type))
12893       continue;
12894 
12895     if (CKind == OMPC_map) {
12896       // target enter data
12897       // OpenMP [2.10.2, Restrictions, p. 99]
12898       // A map-type must be specified in all map clauses and must be either
12899       // to or alloc.
12900       OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
12901       if (DKind == OMPD_target_enter_data &&
12902           !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
12903         SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
12904             << (IsMapTypeImplicit ? 1 : 0)
12905             << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
12906             << getOpenMPDirectiveName(DKind);
12907         continue;
12908       }
12909 
12910       // target exit_data
12911       // OpenMP [2.10.3, Restrictions, p. 102]
12912       // A map-type must be specified in all map clauses and must be either
12913       // from, release, or delete.
12914       if (DKind == OMPD_target_exit_data &&
12915           !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
12916             MapType == OMPC_MAP_delete)) {
12917         SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
12918             << (IsMapTypeImplicit ? 1 : 0)
12919             << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
12920             << getOpenMPDirectiveName(DKind);
12921         continue;
12922       }
12923 
12924       // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
12925       // A list item cannot appear in both a map clause and a data-sharing
12926       // attribute clause on the same construct
12927       if (VD && isOpenMPTargetExecutionDirective(DKind)) {
12928         DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
12929         if (isOpenMPPrivate(DVar.CKind)) {
12930           SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
12931               << getOpenMPClauseName(DVar.CKind)
12932               << getOpenMPClauseName(OMPC_map)
12933               << getOpenMPDirectiveName(DSAS->getCurrentDirective());
12934           reportOriginalDsa(SemaRef, DSAS, CurDeclaration, DVar);
12935           continue;
12936         }
12937       }
12938     }
12939 
12940     // Save the current expression.
12941     MVLI.ProcessedVarList.push_back(RE);
12942 
12943     // Store the components in the stack so that they can be used to check
12944     // against other clauses later on.
12945     DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
12946                                           /*WhereFoundClauseKind=*/OMPC_map);
12947 
12948     // Save the components and declaration to create the clause. For purposes of
12949     // the clause creation, any component list that has has base 'this' uses
12950     // null as base declaration.
12951     MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
12952     MVLI.VarComponents.back().append(CurComponents.begin(),
12953                                      CurComponents.end());
12954     MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
12955                                                            : CurDeclaration);
12956   }
12957 }
12958 
12959 OMPClause *
12960 Sema::ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier,
12961                            OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
12962                            SourceLocation MapLoc, SourceLocation ColonLoc,
12963                            ArrayRef<Expr *> VarList, SourceLocation StartLoc,
12964                            SourceLocation LParenLoc, SourceLocation EndLoc) {
12965   MappableVarListInfo MVLI(VarList);
12966   checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, StartLoc,
12967                               MapType, IsMapTypeImplicit);
12968 
12969   // We need to produce a map clause even if we don't have variables so that
12970   // other diagnostics related with non-existing map clauses are accurate.
12971   return OMPMapClause::Create(Context, StartLoc, LParenLoc, EndLoc,
12972                               MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
12973                               MVLI.VarComponents, MapTypeModifier, MapType,
12974                               IsMapTypeImplicit, MapLoc);
12975 }
12976 
12977 QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
12978                                                TypeResult ParsedType) {
12979   assert(ParsedType.isUsable());
12980 
12981   QualType ReductionType = GetTypeFromParser(ParsedType.get());
12982   if (ReductionType.isNull())
12983     return QualType();
12984 
12985   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
12986   // A type name in a declare reduction directive cannot be a function type, an
12987   // array type, a reference type, or a type qualified with const, volatile or
12988   // restrict.
12989   if (ReductionType.hasQualifiers()) {
12990     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
12991     return QualType();
12992   }
12993 
12994   if (ReductionType->isFunctionType()) {
12995     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
12996     return QualType();
12997   }
12998   if (ReductionType->isReferenceType()) {
12999     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
13000     return QualType();
13001   }
13002   if (ReductionType->isArrayType()) {
13003     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
13004     return QualType();
13005   }
13006   return ReductionType;
13007 }
13008 
13009 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
13010     Scope *S, DeclContext *DC, DeclarationName Name,
13011     ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
13012     AccessSpecifier AS, Decl *PrevDeclInScope) {
13013   SmallVector<Decl *, 8> Decls;
13014   Decls.reserve(ReductionTypes.size());
13015 
13016   LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
13017                       forRedeclarationInCurContext());
13018   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
13019   // A reduction-identifier may not be re-declared in the current scope for the
13020   // same type or for a type that is compatible according to the base language
13021   // rules.
13022   llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
13023   OMPDeclareReductionDecl *PrevDRD = nullptr;
13024   bool InCompoundScope = true;
13025   if (S != nullptr) {
13026     // Find previous declaration with the same name not referenced in other
13027     // declarations.
13028     FunctionScopeInfo *ParentFn = getEnclosingFunction();
13029     InCompoundScope =
13030         (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
13031     LookupName(Lookup, S);
13032     FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
13033                          /*AllowInlineNamespace=*/false);
13034     llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
13035     LookupResult::Filter Filter = Lookup.makeFilter();
13036     while (Filter.hasNext()) {
13037       auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
13038       if (InCompoundScope) {
13039         auto I = UsedAsPrevious.find(PrevDecl);
13040         if (I == UsedAsPrevious.end())
13041           UsedAsPrevious[PrevDecl] = false;
13042         if (OMPDeclareReductionDecl *D = PrevDecl->getPrevDeclInScope())
13043           UsedAsPrevious[D] = true;
13044       }
13045       PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
13046           PrevDecl->getLocation();
13047     }
13048     Filter.done();
13049     if (InCompoundScope) {
13050       for (const auto &PrevData : UsedAsPrevious) {
13051         if (!PrevData.second) {
13052           PrevDRD = PrevData.first;
13053           break;
13054         }
13055       }
13056     }
13057   } else if (PrevDeclInScope != nullptr) {
13058     auto *PrevDRDInScope = PrevDRD =
13059         cast<OMPDeclareReductionDecl>(PrevDeclInScope);
13060     do {
13061       PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
13062           PrevDRDInScope->getLocation();
13063       PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
13064     } while (PrevDRDInScope != nullptr);
13065   }
13066   for (const auto &TyData : ReductionTypes) {
13067     const auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
13068     bool Invalid = false;
13069     if (I != PreviousRedeclTypes.end()) {
13070       Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
13071           << TyData.first;
13072       Diag(I->second, diag::note_previous_definition);
13073       Invalid = true;
13074     }
13075     PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
13076     auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
13077                                                 Name, TyData.first, PrevDRD);
13078     DC->addDecl(DRD);
13079     DRD->setAccess(AS);
13080     Decls.push_back(DRD);
13081     if (Invalid)
13082       DRD->setInvalidDecl();
13083     else
13084       PrevDRD = DRD;
13085   }
13086 
13087   return DeclGroupPtrTy::make(
13088       DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
13089 }
13090 
13091 void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
13092   auto *DRD = cast<OMPDeclareReductionDecl>(D);
13093 
13094   // Enter new function scope.
13095   PushFunctionScope();
13096   setFunctionHasBranchProtectedScope();
13097   getCurFunction()->setHasOMPDeclareReductionCombiner();
13098 
13099   if (S != nullptr)
13100     PushDeclContext(S, DRD);
13101   else
13102     CurContext = DRD;
13103 
13104   PushExpressionEvaluationContext(
13105       ExpressionEvaluationContext::PotentiallyEvaluated);
13106 
13107   QualType ReductionType = DRD->getType();
13108   // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
13109   // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
13110   // uses semantics of argument handles by value, but it should be passed by
13111   // reference. C lang does not support references, so pass all parameters as
13112   // pointers.
13113   // Create 'T omp_in;' variable.
13114   VarDecl *OmpInParm =
13115       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
13116   // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
13117   // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
13118   // uses semantics of argument handles by value, but it should be passed by
13119   // reference. C lang does not support references, so pass all parameters as
13120   // pointers.
13121   // Create 'T omp_out;' variable.
13122   VarDecl *OmpOutParm =
13123       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
13124   if (S != nullptr) {
13125     PushOnScopeChains(OmpInParm, S);
13126     PushOnScopeChains(OmpOutParm, S);
13127   } else {
13128     DRD->addDecl(OmpInParm);
13129     DRD->addDecl(OmpOutParm);
13130   }
13131   Expr *InE =
13132       ::buildDeclRefExpr(*this, OmpInParm, ReductionType, D->getLocation());
13133   Expr *OutE =
13134       ::buildDeclRefExpr(*this, OmpOutParm, ReductionType, D->getLocation());
13135   DRD->setCombinerData(InE, OutE);
13136 }
13137 
13138 void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
13139   auto *DRD = cast<OMPDeclareReductionDecl>(D);
13140   DiscardCleanupsInEvaluationContext();
13141   PopExpressionEvaluationContext();
13142 
13143   PopDeclContext();
13144   PopFunctionScopeInfo();
13145 
13146   if (Combiner != nullptr)
13147     DRD->setCombiner(Combiner);
13148   else
13149     DRD->setInvalidDecl();
13150 }
13151 
13152 VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
13153   auto *DRD = cast<OMPDeclareReductionDecl>(D);
13154 
13155   // Enter new function scope.
13156   PushFunctionScope();
13157   setFunctionHasBranchProtectedScope();
13158 
13159   if (S != nullptr)
13160     PushDeclContext(S, DRD);
13161   else
13162     CurContext = DRD;
13163 
13164   PushExpressionEvaluationContext(
13165       ExpressionEvaluationContext::PotentiallyEvaluated);
13166 
13167   QualType ReductionType = DRD->getType();
13168   // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
13169   // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
13170   // uses semantics of argument handles by value, but it should be passed by
13171   // reference. C lang does not support references, so pass all parameters as
13172   // pointers.
13173   // Create 'T omp_priv;' variable.
13174   VarDecl *OmpPrivParm =
13175       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
13176   // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
13177   // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
13178   // uses semantics of argument handles by value, but it should be passed by
13179   // reference. C lang does not support references, so pass all parameters as
13180   // pointers.
13181   // Create 'T omp_orig;' variable.
13182   VarDecl *OmpOrigParm =
13183       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
13184   if (S != nullptr) {
13185     PushOnScopeChains(OmpPrivParm, S);
13186     PushOnScopeChains(OmpOrigParm, S);
13187   } else {
13188     DRD->addDecl(OmpPrivParm);
13189     DRD->addDecl(OmpOrigParm);
13190   }
13191   Expr *OrigE =
13192       ::buildDeclRefExpr(*this, OmpOrigParm, ReductionType, D->getLocation());
13193   Expr *PrivE =
13194       ::buildDeclRefExpr(*this, OmpPrivParm, ReductionType, D->getLocation());
13195   DRD->setInitializerData(OrigE, PrivE);
13196   return OmpPrivParm;
13197 }
13198 
13199 void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
13200                                                      VarDecl *OmpPrivParm) {
13201   auto *DRD = cast<OMPDeclareReductionDecl>(D);
13202   DiscardCleanupsInEvaluationContext();
13203   PopExpressionEvaluationContext();
13204 
13205   PopDeclContext();
13206   PopFunctionScopeInfo();
13207 
13208   if (Initializer != nullptr) {
13209     DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit);
13210   } else if (OmpPrivParm->hasInit()) {
13211     DRD->setInitializer(OmpPrivParm->getInit(),
13212                         OmpPrivParm->isDirectInit()
13213                             ? OMPDeclareReductionDecl::DirectInit
13214                             : OMPDeclareReductionDecl::CopyInit);
13215   } else {
13216     DRD->setInvalidDecl();
13217   }
13218 }
13219 
13220 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
13221     Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
13222   for (Decl *D : DeclReductions.get()) {
13223     if (IsValid) {
13224       if (S)
13225         PushOnScopeChains(cast<OMPDeclareReductionDecl>(D), S,
13226                           /*AddToContext=*/false);
13227     } else {
13228       D->setInvalidDecl();
13229     }
13230   }
13231   return DeclReductions;
13232 }
13233 
13234 OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
13235                                            SourceLocation StartLoc,
13236                                            SourceLocation LParenLoc,
13237                                            SourceLocation EndLoc) {
13238   Expr *ValExpr = NumTeams;
13239   Stmt *HelperValStmt = nullptr;
13240 
13241   // OpenMP [teams Constrcut, Restrictions]
13242   // The num_teams expression must evaluate to a positive integer value.
13243   if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
13244                                  /*StrictlyPositive=*/true))
13245     return nullptr;
13246 
13247   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
13248   OpenMPDirectiveKind CaptureRegion =
13249       getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams);
13250   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
13251     ValExpr = MakeFullExpr(ValExpr).get();
13252     llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
13253     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
13254     HelperValStmt = buildPreInits(Context, Captures);
13255   }
13256 
13257   return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
13258                                          StartLoc, LParenLoc, EndLoc);
13259 }
13260 
13261 OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
13262                                               SourceLocation StartLoc,
13263                                               SourceLocation LParenLoc,
13264                                               SourceLocation EndLoc) {
13265   Expr *ValExpr = ThreadLimit;
13266   Stmt *HelperValStmt = nullptr;
13267 
13268   // OpenMP [teams Constrcut, Restrictions]
13269   // The thread_limit expression must evaluate to a positive integer value.
13270   if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
13271                                  /*StrictlyPositive=*/true))
13272     return nullptr;
13273 
13274   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
13275   OpenMPDirectiveKind CaptureRegion =
13276       getOpenMPCaptureRegionForClause(DKind, OMPC_thread_limit);
13277   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
13278     ValExpr = MakeFullExpr(ValExpr).get();
13279     llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
13280     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
13281     HelperValStmt = buildPreInits(Context, Captures);
13282   }
13283 
13284   return new (Context) OMPThreadLimitClause(
13285       ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
13286 }
13287 
13288 OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
13289                                            SourceLocation StartLoc,
13290                                            SourceLocation LParenLoc,
13291                                            SourceLocation EndLoc) {
13292   Expr *ValExpr = Priority;
13293 
13294   // OpenMP [2.9.1, task Constrcut]
13295   // The priority-value is a non-negative numerical scalar expression.
13296   if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_priority,
13297                                  /*StrictlyPositive=*/false))
13298     return nullptr;
13299 
13300   return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc);
13301 }
13302 
13303 OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
13304                                             SourceLocation StartLoc,
13305                                             SourceLocation LParenLoc,
13306                                             SourceLocation EndLoc) {
13307   Expr *ValExpr = Grainsize;
13308 
13309   // OpenMP [2.9.2, taskloop Constrcut]
13310   // The parameter of the grainsize clause must be a positive integer
13311   // expression.
13312   if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize,
13313                                  /*StrictlyPositive=*/true))
13314     return nullptr;
13315 
13316   return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc);
13317 }
13318 
13319 OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
13320                                            SourceLocation StartLoc,
13321                                            SourceLocation LParenLoc,
13322                                            SourceLocation EndLoc) {
13323   Expr *ValExpr = NumTasks;
13324 
13325   // OpenMP [2.9.2, taskloop Constrcut]
13326   // The parameter of the num_tasks clause must be a positive integer
13327   // expression.
13328   if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks,
13329                                  /*StrictlyPositive=*/true))
13330     return nullptr;
13331 
13332   return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc);
13333 }
13334 
13335 OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
13336                                        SourceLocation LParenLoc,
13337                                        SourceLocation EndLoc) {
13338   // OpenMP [2.13.2, critical construct, Description]
13339   // ... where hint-expression is an integer constant expression that evaluates
13340   // to a valid lock hint.
13341   ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
13342   if (HintExpr.isInvalid())
13343     return nullptr;
13344   return new (Context)
13345       OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
13346 }
13347 
13348 OMPClause *Sema::ActOnOpenMPDistScheduleClause(
13349     OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
13350     SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
13351     SourceLocation EndLoc) {
13352   if (Kind == OMPC_DIST_SCHEDULE_unknown) {
13353     std::string Values;
13354     Values += "'";
13355     Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
13356     Values += "'";
13357     Diag(KindLoc, diag::err_omp_unexpected_clause_value)
13358         << Values << getOpenMPClauseName(OMPC_dist_schedule);
13359     return nullptr;
13360   }
13361   Expr *ValExpr = ChunkSize;
13362   Stmt *HelperValStmt = nullptr;
13363   if (ChunkSize) {
13364     if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
13365         !ChunkSize->isInstantiationDependent() &&
13366         !ChunkSize->containsUnexpandedParameterPack()) {
13367       SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
13368       ExprResult Val =
13369           PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
13370       if (Val.isInvalid())
13371         return nullptr;
13372 
13373       ValExpr = Val.get();
13374 
13375       // OpenMP [2.7.1, Restrictions]
13376       //  chunk_size must be a loop invariant integer expression with a positive
13377       //  value.
13378       llvm::APSInt Result;
13379       if (ValExpr->isIntegerConstantExpr(Result, Context)) {
13380         if (Result.isSigned() && !Result.isStrictlyPositive()) {
13381           Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
13382               << "dist_schedule" << ChunkSize->getSourceRange();
13383           return nullptr;
13384         }
13385       } else if (getOpenMPCaptureRegionForClause(
13386                      DSAStack->getCurrentDirective(), OMPC_dist_schedule) !=
13387                      OMPD_unknown &&
13388                  !CurContext->isDependentContext()) {
13389         ValExpr = MakeFullExpr(ValExpr).get();
13390         llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
13391         ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
13392         HelperValStmt = buildPreInits(Context, Captures);
13393       }
13394     }
13395   }
13396 
13397   return new (Context)
13398       OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
13399                             Kind, ValExpr, HelperValStmt);
13400 }
13401 
13402 OMPClause *Sema::ActOnOpenMPDefaultmapClause(
13403     OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
13404     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
13405     SourceLocation KindLoc, SourceLocation EndLoc) {
13406   // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)'
13407   if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) {
13408     std::string Value;
13409     SourceLocation Loc;
13410     Value += "'";
13411     if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
13412       Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
13413                                              OMPC_DEFAULTMAP_MODIFIER_tofrom);
13414       Loc = MLoc;
13415     } else {
13416       Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
13417                                              OMPC_DEFAULTMAP_scalar);
13418       Loc = KindLoc;
13419     }
13420     Value += "'";
13421     Diag(Loc, diag::err_omp_unexpected_clause_value)
13422         << Value << getOpenMPClauseName(OMPC_defaultmap);
13423     return nullptr;
13424   }
13425   DSAStack->setDefaultDMAToFromScalar(StartLoc);
13426 
13427   return new (Context)
13428       OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
13429 }
13430 
13431 bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
13432   DeclContext *CurLexicalContext = getCurLexicalContext();
13433   if (!CurLexicalContext->isFileContext() &&
13434       !CurLexicalContext->isExternCContext() &&
13435       !CurLexicalContext->isExternCXXContext() &&
13436       !isa<CXXRecordDecl>(CurLexicalContext) &&
13437       !isa<ClassTemplateDecl>(CurLexicalContext) &&
13438       !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) &&
13439       !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) {
13440     Diag(Loc, diag::err_omp_region_not_file_context);
13441     return false;
13442   }
13443   ++DeclareTargetNestingLevel;
13444   return true;
13445 }
13446 
13447 void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
13448   assert(DeclareTargetNestingLevel > 0 &&
13449          "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
13450   --DeclareTargetNestingLevel;
13451 }
13452 
13453 void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope,
13454                                         CXXScopeSpec &ScopeSpec,
13455                                         const DeclarationNameInfo &Id,
13456                                         OMPDeclareTargetDeclAttr::MapTypeTy MT,
13457                                         NamedDeclSetType &SameDirectiveDecls) {
13458   LookupResult Lookup(*this, Id, LookupOrdinaryName);
13459   LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
13460 
13461   if (Lookup.isAmbiguous())
13462     return;
13463   Lookup.suppressDiagnostics();
13464 
13465   if (!Lookup.isSingleResult()) {
13466     if (TypoCorrection Corrected =
13467             CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr,
13468                         llvm::make_unique<VarOrFuncDeclFilterCCC>(*this),
13469                         CTK_ErrorRecovery)) {
13470       diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
13471                                   << Id.getName());
13472       checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
13473       return;
13474     }
13475 
13476     Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
13477     return;
13478   }
13479 
13480   NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
13481   if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND) ||
13482       isa<FunctionTemplateDecl>(ND)) {
13483     if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
13484       Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
13485     llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
13486         OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
13487             cast<ValueDecl>(ND));
13488     if (!Res) {
13489       auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT);
13490       ND->addAttr(A);
13491       if (ASTMutationListener *ML = Context.getASTMutationListener())
13492         ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
13493       checkDeclIsAllowedInOpenMPTarget(nullptr, ND, Id.getLoc());
13494     } else if (*Res != MT) {
13495       Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link)
13496           << Id.getName();
13497     }
13498   } else {
13499     Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
13500   }
13501 }
13502 
13503 static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
13504                                      Sema &SemaRef, Decl *D) {
13505   if (!D || !isa<VarDecl>(D))
13506     return;
13507   auto *VD = cast<VarDecl>(D);
13508   if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
13509     return;
13510   SemaRef.Diag(VD->getLocation(), diag::warn_omp_not_in_target_context);
13511   SemaRef.Diag(SL, diag::note_used_here) << SR;
13512 }
13513 
13514 static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
13515                                    Sema &SemaRef, DSAStackTy *Stack,
13516                                    ValueDecl *VD) {
13517   return VD->hasAttr<OMPDeclareTargetDeclAttr>() ||
13518          checkTypeMappable(SL, SR, SemaRef, Stack, VD->getType(),
13519                            /*FullCheck=*/false);
13520 }
13521 
13522 void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
13523                                             SourceLocation IdLoc) {
13524   if (!D || D->isInvalidDecl())
13525     return;
13526   SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
13527   SourceLocation SL = E ? E->getBeginLoc() : D->getLocation();
13528   if (auto *VD = dyn_cast<VarDecl>(D)) {
13529     // Only global variables can be marked as declare target.
13530     if (!VD->isFileVarDecl() && !VD->isStaticLocal() &&
13531         !VD->isStaticDataMember())
13532       return;
13533     // 2.10.6: threadprivate variable cannot appear in a declare target
13534     // directive.
13535     if (DSAStack->isThreadPrivate(VD)) {
13536       Diag(SL, diag::err_omp_threadprivate_in_target);
13537       reportOriginalDsa(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
13538       return;
13539     }
13540   }
13541   if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(D))
13542     D = FTD->getTemplatedDecl();
13543   if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
13544     llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
13545         OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(FD);
13546     if (Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) {
13547       assert(IdLoc.isValid() && "Source location is expected");
13548       Diag(IdLoc, diag::err_omp_function_in_link_clause);
13549       Diag(FD->getLocation(), diag::note_defined_here) << FD;
13550       return;
13551     }
13552   }
13553   if (auto *VD = dyn_cast<ValueDecl>(D)) {
13554     // Problem if any with var declared with incomplete type will be reported
13555     // as normal, so no need to check it here.
13556     if ((E || !VD->getType()->isIncompleteType()) &&
13557         !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD))
13558       return;
13559     if (!E && !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
13560       // Checking declaration inside declare target region.
13561       if (isa<VarDecl>(D) || isa<FunctionDecl>(D) ||
13562           isa<FunctionTemplateDecl>(D)) {
13563         auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(
13564             Context, OMPDeclareTargetDeclAttr::MT_To);
13565         D->addAttr(A);
13566         if (ASTMutationListener *ML = Context.getASTMutationListener())
13567           ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
13568       }
13569       return;
13570     }
13571   }
13572   if (!E)
13573     return;
13574   checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
13575 }
13576 
13577 OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
13578                                      SourceLocation StartLoc,
13579                                      SourceLocation LParenLoc,
13580                                      SourceLocation EndLoc) {
13581   MappableVarListInfo MVLI(VarList);
13582   checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, StartLoc);
13583   if (MVLI.ProcessedVarList.empty())
13584     return nullptr;
13585 
13586   return OMPToClause::Create(Context, StartLoc, LParenLoc, EndLoc,
13587                              MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
13588                              MVLI.VarComponents);
13589 }
13590 
13591 OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
13592                                        SourceLocation StartLoc,
13593                                        SourceLocation LParenLoc,
13594                                        SourceLocation EndLoc) {
13595   MappableVarListInfo MVLI(VarList);
13596   checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, StartLoc);
13597   if (MVLI.ProcessedVarList.empty())
13598     return nullptr;
13599 
13600   return OMPFromClause::Create(Context, StartLoc, LParenLoc, EndLoc,
13601                                MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
13602                                MVLI.VarComponents);
13603 }
13604 
13605 OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
13606                                                SourceLocation StartLoc,
13607                                                SourceLocation LParenLoc,
13608                                                SourceLocation EndLoc) {
13609   MappableVarListInfo MVLI(VarList);
13610   SmallVector<Expr *, 8> PrivateCopies;
13611   SmallVector<Expr *, 8> Inits;
13612 
13613   for (Expr *RefExpr : VarList) {
13614     assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
13615     SourceLocation ELoc;
13616     SourceRange ERange;
13617     Expr *SimpleRefExpr = RefExpr;
13618     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
13619     if (Res.second) {
13620       // It will be analyzed later.
13621       MVLI.ProcessedVarList.push_back(RefExpr);
13622       PrivateCopies.push_back(nullptr);
13623       Inits.push_back(nullptr);
13624     }
13625     ValueDecl *D = Res.first;
13626     if (!D)
13627       continue;
13628 
13629     QualType Type = D->getType();
13630     Type = Type.getNonReferenceType().getUnqualifiedType();
13631 
13632     auto *VD = dyn_cast<VarDecl>(D);
13633 
13634     // Item should be a pointer or reference to pointer.
13635     if (!Type->isPointerType()) {
13636       Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
13637           << 0 << RefExpr->getSourceRange();
13638       continue;
13639     }
13640 
13641     // Build the private variable and the expression that refers to it.
13642     auto VDPrivate =
13643         buildVarDecl(*this, ELoc, Type, D->getName(),
13644                      D->hasAttrs() ? &D->getAttrs() : nullptr,
13645                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
13646     if (VDPrivate->isInvalidDecl())
13647       continue;
13648 
13649     CurContext->addDecl(VDPrivate);
13650     DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
13651         *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
13652 
13653     // Add temporary variable to initialize the private copy of the pointer.
13654     VarDecl *VDInit =
13655         buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
13656     DeclRefExpr *VDInitRefExpr = buildDeclRefExpr(
13657         *this, VDInit, RefExpr->getType(), RefExpr->getExprLoc());
13658     AddInitializerToDecl(VDPrivate,
13659                          DefaultLvalueConversion(VDInitRefExpr).get(),
13660                          /*DirectInit=*/false);
13661 
13662     // If required, build a capture to implement the privatization initialized
13663     // with the current list item value.
13664     DeclRefExpr *Ref = nullptr;
13665     if (!VD)
13666       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
13667     MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
13668     PrivateCopies.push_back(VDPrivateRefExpr);
13669     Inits.push_back(VDInitRefExpr);
13670 
13671     // We need to add a data sharing attribute for this variable to make sure it
13672     // is correctly captured. A variable that shows up in a use_device_ptr has
13673     // similar properties of a first private variable.
13674     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
13675 
13676     // Create a mappable component for the list item. List items in this clause
13677     // only need a component.
13678     MVLI.VarBaseDeclarations.push_back(D);
13679     MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
13680     MVLI.VarComponents.back().push_back(
13681         OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
13682   }
13683 
13684   if (MVLI.ProcessedVarList.empty())
13685     return nullptr;
13686 
13687   return OMPUseDevicePtrClause::Create(
13688       Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
13689       PrivateCopies, Inits, MVLI.VarBaseDeclarations, MVLI.VarComponents);
13690 }
13691 
13692 OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
13693                                               SourceLocation StartLoc,
13694                                               SourceLocation LParenLoc,
13695                                               SourceLocation EndLoc) {
13696   MappableVarListInfo MVLI(VarList);
13697   for (Expr *RefExpr : VarList) {
13698     assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
13699     SourceLocation ELoc;
13700     SourceRange ERange;
13701     Expr *SimpleRefExpr = RefExpr;
13702     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
13703     if (Res.second) {
13704       // It will be analyzed later.
13705       MVLI.ProcessedVarList.push_back(RefExpr);
13706     }
13707     ValueDecl *D = Res.first;
13708     if (!D)
13709       continue;
13710 
13711     QualType Type = D->getType();
13712     // item should be a pointer or array or reference to pointer or array
13713     if (!Type.getNonReferenceType()->isPointerType() &&
13714         !Type.getNonReferenceType()->isArrayType()) {
13715       Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
13716           << 0 << RefExpr->getSourceRange();
13717       continue;
13718     }
13719 
13720     // Check if the declaration in the clause does not show up in any data
13721     // sharing attribute.
13722     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
13723     if (isOpenMPPrivate(DVar.CKind)) {
13724       Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
13725           << getOpenMPClauseName(DVar.CKind)
13726           << getOpenMPClauseName(OMPC_is_device_ptr)
13727           << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
13728       reportOriginalDsa(*this, DSAStack, D, DVar);
13729       continue;
13730     }
13731 
13732     const Expr *ConflictExpr;
13733     if (DSAStack->checkMappableExprComponentListsForDecl(
13734             D, /*CurrentRegionOnly=*/true,
13735             [&ConflictExpr](
13736                 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
13737                 OpenMPClauseKind) -> bool {
13738               ConflictExpr = R.front().getAssociatedExpression();
13739               return true;
13740             })) {
13741       Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
13742       Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
13743           << ConflictExpr->getSourceRange();
13744       continue;
13745     }
13746 
13747     // Store the components in the stack so that they can be used to check
13748     // against other clauses later on.
13749     OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
13750     DSAStack->addMappableExpressionComponents(
13751         D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
13752 
13753     // Record the expression we've just processed.
13754     MVLI.ProcessedVarList.push_back(SimpleRefExpr);
13755 
13756     // Create a mappable component for the list item. List items in this clause
13757     // only need a component. We use a null declaration to signal fields in
13758     // 'this'.
13759     assert((isa<DeclRefExpr>(SimpleRefExpr) ||
13760             isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
13761            "Unexpected device pointer expression!");
13762     MVLI.VarBaseDeclarations.push_back(
13763         isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
13764     MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
13765     MVLI.VarComponents.back().push_back(MC);
13766   }
13767 
13768   if (MVLI.ProcessedVarList.empty())
13769     return nullptr;
13770 
13771   return OMPIsDevicePtrClause::Create(
13772       Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
13773       MVLI.VarBaseDeclarations, MVLI.VarComponents);
13774 }
13775