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 /// \brief This file implements semantic analysis for OpenMP directives and
11 /// clauses.
12 ///
13 //===----------------------------------------------------------------------===//
14 
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/Decl.h"
17 #include "clang/AST/DeclCXX.h"
18 #include "clang/AST/DeclOpenMP.h"
19 #include "clang/AST/StmtCXX.h"
20 #include "clang/AST/StmtOpenMP.h"
21 #include "clang/AST/StmtVisitor.h"
22 #include "clang/Basic/OpenMPKinds.h"
23 #include "clang/Lex/Preprocessor.h"
24 #include "clang/Sema/Initialization.h"
25 #include "clang/Sema/Lookup.h"
26 #include "clang/Sema/Scope.h"
27 #include "clang/Sema/ScopeInfo.h"
28 #include "clang/Sema/SemaInternal.h"
29 using namespace clang;
30 
31 //===----------------------------------------------------------------------===//
32 // Stack of data-sharing attributes for variables
33 //===----------------------------------------------------------------------===//
34 
35 namespace {
36 /// \brief Default data sharing attributes, which can be applied to directive.
37 enum DefaultDataSharingAttributes {
38   DSA_unspecified = 0, /// \brief Data sharing attribute not specified.
39   DSA_none = 1 << 0,   /// \brief Default data sharing attribute 'none'.
40   DSA_shared = 1 << 1  /// \brief Default data sharing attribute 'shared'.
41 };
42 
43 template <class T> struct MatchesAny {
44   explicit MatchesAny(ArrayRef<T> Arr) : Arr(std::move(Arr)) {}
45   bool operator()(T Kind) {
46     for (auto KindEl : Arr)
47       if (KindEl == Kind)
48         return true;
49     return false;
50   }
51 
52 private:
53   ArrayRef<T> Arr;
54 };
55 struct MatchesAlways {
56   MatchesAlways() {}
57   template <class T> bool operator()(T) { return true; }
58 };
59 
60 typedef MatchesAny<OpenMPClauseKind> MatchesAnyClause;
61 typedef MatchesAny<OpenMPDirectiveKind> MatchesAnyDirective;
62 
63 /// \brief Stack for tracking declarations used in OpenMP directives and
64 /// clauses and their data-sharing attributes.
65 class DSAStackTy {
66 public:
67   struct DSAVarData {
68     OpenMPDirectiveKind DKind;
69     OpenMPClauseKind CKind;
70     DeclRefExpr *RefExpr;
71     SourceLocation ImplicitDSALoc;
72     DSAVarData()
73         : DKind(OMPD_unknown), CKind(OMPC_unknown), RefExpr(nullptr),
74           ImplicitDSALoc() {}
75   };
76 
77 private:
78   struct DSAInfo {
79     OpenMPClauseKind Attributes;
80     DeclRefExpr *RefExpr;
81   };
82   typedef llvm::SmallDenseMap<VarDecl *, DSAInfo, 64> DeclSAMapTy;
83   typedef llvm::SmallDenseMap<VarDecl *, DeclRefExpr *, 64> AlignedMapTy;
84 
85   struct SharingMapTy {
86     DeclSAMapTy SharingMap;
87     AlignedMapTy AlignedMap;
88     DefaultDataSharingAttributes DefaultAttr;
89     SourceLocation DefaultAttrLoc;
90     OpenMPDirectiveKind Directive;
91     DeclarationNameInfo DirectiveName;
92     Scope *CurScope;
93     SourceLocation ConstructLoc;
94     bool OrderedRegion;
95     SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
96                  Scope *CurScope, SourceLocation Loc)
97         : SharingMap(), AlignedMap(), DefaultAttr(DSA_unspecified),
98           Directive(DKind), DirectiveName(std::move(Name)), CurScope(CurScope),
99           ConstructLoc(Loc), OrderedRegion(false) {}
100     SharingMapTy()
101         : SharingMap(), AlignedMap(), DefaultAttr(DSA_unspecified),
102           Directive(OMPD_unknown), DirectiveName(), CurScope(nullptr),
103           ConstructLoc(), OrderedRegion(false) {}
104   };
105 
106   typedef SmallVector<SharingMapTy, 64> StackTy;
107 
108   /// \brief Stack of used declaration and their data-sharing attributes.
109   StackTy Stack;
110   Sema &SemaRef;
111 
112   typedef SmallVector<SharingMapTy, 8>::reverse_iterator reverse_iterator;
113 
114   DSAVarData getDSA(StackTy::reverse_iterator Iter, VarDecl *D);
115 
116   /// \brief Checks if the variable is a local for OpenMP region.
117   bool isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter);
118 
119 public:
120   explicit DSAStackTy(Sema &S) : Stack(1), SemaRef(S) {}
121 
122   void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
123             Scope *CurScope, SourceLocation Loc) {
124     Stack.push_back(SharingMapTy(DKind, DirName, CurScope, Loc));
125     Stack.back().DefaultAttrLoc = Loc;
126   }
127 
128   void pop() {
129     assert(Stack.size() > 1 && "Data-sharing attributes stack is empty!");
130     Stack.pop_back();
131   }
132 
133   /// \brief If 'aligned' declaration for given variable \a D was not seen yet,
134   /// add it and return NULL; otherwise return previous occurrence's expression
135   /// for diagnostics.
136   DeclRefExpr *addUniqueAligned(VarDecl *D, DeclRefExpr *NewDE);
137 
138   /// \brief Adds explicit data sharing attribute to the specified declaration.
139   void addDSA(VarDecl *D, DeclRefExpr *E, OpenMPClauseKind A);
140 
141   /// \brief Returns data sharing attributes from top of the stack for the
142   /// specified declaration.
143   DSAVarData getTopDSA(VarDecl *D, bool FromParent);
144   /// \brief Returns data-sharing attributes for the specified declaration.
145   DSAVarData getImplicitDSA(VarDecl *D, bool FromParent);
146   /// \brief Checks if the specified variables has data-sharing attributes which
147   /// match specified \a CPred predicate in any directive which matches \a DPred
148   /// predicate.
149   template <class ClausesPredicate, class DirectivesPredicate>
150   DSAVarData hasDSA(VarDecl *D, ClausesPredicate CPred,
151                     DirectivesPredicate DPred, bool FromParent);
152   /// \brief Checks if the specified variables has data-sharing attributes which
153   /// match specified \a CPred predicate in any innermost directive which
154   /// matches \a DPred predicate.
155   template <class ClausesPredicate, class DirectivesPredicate>
156   DSAVarData hasInnermostDSA(VarDecl *D, ClausesPredicate CPred,
157                              DirectivesPredicate DPred,
158                              bool FromParent);
159   /// \brief Finds a directive which matches specified \a DPred predicate.
160   template <class NamedDirectivesPredicate>
161   bool hasDirective(NamedDirectivesPredicate DPred, bool FromParent);
162 
163   /// \brief Returns currently analyzed directive.
164   OpenMPDirectiveKind getCurrentDirective() const {
165     return Stack.back().Directive;
166   }
167   /// \brief Returns parent directive.
168   OpenMPDirectiveKind getParentDirective() const {
169     if (Stack.size() > 2)
170       return Stack[Stack.size() - 2].Directive;
171     return OMPD_unknown;
172   }
173 
174   /// \brief Set default data sharing attribute to none.
175   void setDefaultDSANone(SourceLocation Loc) {
176     Stack.back().DefaultAttr = DSA_none;
177     Stack.back().DefaultAttrLoc = Loc;
178   }
179   /// \brief Set default data sharing attribute to shared.
180   void setDefaultDSAShared(SourceLocation Loc) {
181     Stack.back().DefaultAttr = DSA_shared;
182     Stack.back().DefaultAttrLoc = Loc;
183   }
184 
185   DefaultDataSharingAttributes getDefaultDSA() const {
186     return Stack.back().DefaultAttr;
187   }
188   SourceLocation getDefaultDSALocation() const {
189     return Stack.back().DefaultAttrLoc;
190   }
191 
192   /// \brief Checks if the specified variable is a threadprivate.
193   bool isThreadPrivate(VarDecl *D) {
194     DSAVarData DVar = getTopDSA(D, false);
195     return isOpenMPThreadPrivate(DVar.CKind);
196   }
197 
198   /// \brief Marks current region as ordered (it has an 'ordered' clause).
199   void setOrderedRegion(bool IsOrdered = true) {
200     Stack.back().OrderedRegion = IsOrdered;
201   }
202   /// \brief Returns true, if parent region is ordered (has associated
203   /// 'ordered' clause), false - otherwise.
204   bool isParentOrderedRegion() const {
205     if (Stack.size() > 2)
206       return Stack[Stack.size() - 2].OrderedRegion;
207     return false;
208   }
209 
210   Scope *getCurScope() const { return Stack.back().CurScope; }
211   Scope *getCurScope() { return Stack.back().CurScope; }
212   SourceLocation getConstructLoc() { return Stack.back().ConstructLoc; }
213 };
214 bool isParallelOrTaskRegion(OpenMPDirectiveKind DKind) {
215   return isOpenMPParallelDirective(DKind) || DKind == OMPD_task ||
216          DKind == OMPD_unknown;
217 }
218 } // namespace
219 
220 DSAStackTy::DSAVarData DSAStackTy::getDSA(StackTy::reverse_iterator Iter,
221                                           VarDecl *D) {
222   DSAVarData DVar;
223   if (Iter == std::prev(Stack.rend())) {
224     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
225     // in a region but not in construct]
226     //  File-scope or namespace-scope variables referenced in called routines
227     //  in the region are shared unless they appear in a threadprivate
228     //  directive.
229     if (!D->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(D))
230       DVar.CKind = OMPC_shared;
231 
232     // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
233     // in a region but not in construct]
234     //  Variables with static storage duration that are declared in called
235     //  routines in the region are shared.
236     if (D->hasGlobalStorage())
237       DVar.CKind = OMPC_shared;
238 
239     return DVar;
240   }
241 
242   DVar.DKind = Iter->Directive;
243   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
244   // in a Construct, C/C++, predetermined, p.1]
245   // Variables with automatic storage duration that are declared in a scope
246   // inside the construct are private.
247   if (isOpenMPLocal(D, Iter) && D->isLocalVarDecl() &&
248       (D->getStorageClass() == SC_Auto || D->getStorageClass() == SC_None)) {
249     DVar.CKind = OMPC_private;
250     return DVar;
251   }
252 
253   // Explicitly specified attributes and local variables with predetermined
254   // attributes.
255   if (Iter->SharingMap.count(D)) {
256     DVar.RefExpr = Iter->SharingMap[D].RefExpr;
257     DVar.CKind = Iter->SharingMap[D].Attributes;
258     DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
259     return DVar;
260   }
261 
262   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
263   // in a Construct, C/C++, implicitly determined, p.1]
264   //  In a parallel or task construct, the data-sharing attributes of these
265   //  variables are determined by the default clause, if present.
266   switch (Iter->DefaultAttr) {
267   case DSA_shared:
268     DVar.CKind = OMPC_shared;
269     DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
270     return DVar;
271   case DSA_none:
272     return DVar;
273   case DSA_unspecified:
274     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
275     // in a Construct, implicitly determined, p.2]
276     //  In a parallel construct, if no default clause is present, these
277     //  variables are shared.
278     DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
279     if (isOpenMPParallelDirective(DVar.DKind)) {
280       DVar.CKind = OMPC_shared;
281       return DVar;
282     }
283 
284     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
285     // in a Construct, implicitly determined, p.4]
286     //  In a task construct, if no default clause is present, a variable that in
287     //  the enclosing context is determined to be shared by all implicit tasks
288     //  bound to the current team is shared.
289     if (DVar.DKind == OMPD_task) {
290       DSAVarData DVarTemp;
291       for (StackTy::reverse_iterator I = std::next(Iter),
292                                      EE = std::prev(Stack.rend());
293            I != EE; ++I) {
294         // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
295         // Referenced
296         // in a Construct, implicitly determined, p.6]
297         //  In a task construct, if no default clause is present, a variable
298         //  whose data-sharing attribute is not determined by the rules above is
299         //  firstprivate.
300         DVarTemp = getDSA(I, D);
301         if (DVarTemp.CKind != OMPC_shared) {
302           DVar.RefExpr = nullptr;
303           DVar.DKind = OMPD_task;
304           DVar.CKind = OMPC_firstprivate;
305           return DVar;
306         }
307         if (isParallelOrTaskRegion(I->Directive))
308           break;
309       }
310       DVar.DKind = OMPD_task;
311       DVar.CKind =
312           (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
313       return DVar;
314     }
315   }
316   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
317   // in a Construct, implicitly determined, p.3]
318   //  For constructs other than task, if no default clause is present, these
319   //  variables inherit their data-sharing attributes from the enclosing
320   //  context.
321   return getDSA(std::next(Iter), D);
322 }
323 
324 DeclRefExpr *DSAStackTy::addUniqueAligned(VarDecl *D, DeclRefExpr *NewDE) {
325   assert(Stack.size() > 1 && "Data sharing attributes stack is empty");
326   auto It = Stack.back().AlignedMap.find(D);
327   if (It == Stack.back().AlignedMap.end()) {
328     assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
329     Stack.back().AlignedMap[D] = NewDE;
330     return nullptr;
331   } else {
332     assert(It->second && "Unexpected nullptr expr in the aligned map");
333     return It->second;
334   }
335   return nullptr;
336 }
337 
338 void DSAStackTy::addDSA(VarDecl *D, DeclRefExpr *E, OpenMPClauseKind A) {
339   if (A == OMPC_threadprivate) {
340     Stack[0].SharingMap[D].Attributes = A;
341     Stack[0].SharingMap[D].RefExpr = E;
342   } else {
343     assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
344     Stack.back().SharingMap[D].Attributes = A;
345     Stack.back().SharingMap[D].RefExpr = E;
346   }
347 }
348 
349 bool DSAStackTy::isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter) {
350   if (Stack.size() > 2) {
351     reverse_iterator I = Iter, E = std::prev(Stack.rend());
352     Scope *TopScope = nullptr;
353     while (I != E && !isParallelOrTaskRegion(I->Directive)) {
354       ++I;
355     }
356     if (I == E)
357       return false;
358     TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
359     Scope *CurScope = getCurScope();
360     while (CurScope != TopScope && !CurScope->isDeclScope(D)) {
361       CurScope = CurScope->getParent();
362     }
363     return CurScope != TopScope;
364   }
365   return false;
366 }
367 
368 DSAStackTy::DSAVarData DSAStackTy::getTopDSA(VarDecl *D, bool FromParent) {
369   DSAVarData DVar;
370 
371   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
372   // in a Construct, C/C++, predetermined, p.1]
373   //  Variables appearing in threadprivate directives are threadprivate.
374   if (D->getTLSKind() != VarDecl::TLS_None) {
375     DVar.CKind = OMPC_threadprivate;
376     return DVar;
377   }
378   if (Stack[0].SharingMap.count(D)) {
379     DVar.RefExpr = Stack[0].SharingMap[D].RefExpr;
380     DVar.CKind = OMPC_threadprivate;
381     return DVar;
382   }
383 
384   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
385   // in a Construct, C/C++, predetermined, p.1]
386   // Variables with automatic storage duration that are declared in a scope
387   // inside the construct are private.
388   OpenMPDirectiveKind Kind =
389       FromParent ? getParentDirective() : getCurrentDirective();
390   auto StartI = std::next(Stack.rbegin());
391   auto EndI = std::prev(Stack.rend());
392   if (FromParent && StartI != EndI) {
393     StartI = std::next(StartI);
394   }
395   if (!isParallelOrTaskRegion(Kind)) {
396     if (isOpenMPLocal(D, StartI) &&
397         ((D->isLocalVarDecl() && (D->getStorageClass() == SC_Auto ||
398                                   D->getStorageClass() == SC_None)) ||
399          isa<ParmVarDecl>(D))) {
400       DVar.CKind = OMPC_private;
401       return DVar;
402     }
403   }
404 
405   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
406   // in a Construct, C/C++, predetermined, p.4]
407   //  Static data members are shared.
408   if (D->isStaticDataMember()) {
409     // Variables with const-qualified type having no mutable member may be
410     // listed in a firstprivate clause, even if they are static data members.
411     DSAVarData DVarTemp = hasDSA(D, MatchesAnyClause(OMPC_firstprivate),
412                                  MatchesAlways(), FromParent);
413     if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr)
414       return DVar;
415 
416     DVar.CKind = OMPC_shared;
417     return DVar;
418   }
419 
420   QualType Type = D->getType().getNonReferenceType().getCanonicalType();
421   bool IsConstant = Type.isConstant(SemaRef.getASTContext());
422   while (Type->isArrayType()) {
423     QualType ElemType = cast<ArrayType>(Type.getTypePtr())->getElementType();
424     Type = ElemType.getNonReferenceType().getCanonicalType();
425   }
426   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
427   // in a Construct, C/C++, predetermined, p.6]
428   //  Variables with const qualified type having no mutable member are
429   //  shared.
430   CXXRecordDecl *RD =
431       SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
432   if (IsConstant &&
433       !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasMutableFields())) {
434     // Variables with const-qualified type having no mutable member may be
435     // listed in a firstprivate clause, even if they are static data members.
436     DSAVarData DVarTemp = hasDSA(D, MatchesAnyClause(OMPC_firstprivate),
437                                  MatchesAlways(), FromParent);
438     if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr)
439       return DVar;
440 
441     DVar.CKind = OMPC_shared;
442     return DVar;
443   }
444 
445   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
446   // in a Construct, C/C++, predetermined, p.7]
447   //  Variables with static storage duration that are declared in a scope
448   //  inside the construct are shared.
449   if (D->isStaticLocal()) {
450     DVar.CKind = OMPC_shared;
451     return DVar;
452   }
453 
454   // Explicitly specified attributes and local variables with predetermined
455   // attributes.
456   auto I = std::prev(StartI);
457   if (I->SharingMap.count(D)) {
458     DVar.RefExpr = I->SharingMap[D].RefExpr;
459     DVar.CKind = I->SharingMap[D].Attributes;
460     DVar.ImplicitDSALoc = I->DefaultAttrLoc;
461   }
462 
463   return DVar;
464 }
465 
466 DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(VarDecl *D, bool FromParent) {
467   auto StartI = Stack.rbegin();
468   auto EndI = std::prev(Stack.rend());
469   if (FromParent && StartI != EndI) {
470     StartI = std::next(StartI);
471   }
472   return getDSA(StartI, D);
473 }
474 
475 template <class ClausesPredicate, class DirectivesPredicate>
476 DSAStackTy::DSAVarData DSAStackTy::hasDSA(VarDecl *D, ClausesPredicate CPred,
477                                           DirectivesPredicate DPred,
478                                           bool FromParent) {
479   auto StartI = std::next(Stack.rbegin());
480   auto EndI = std::prev(Stack.rend());
481   if (FromParent && StartI != EndI) {
482     StartI = std::next(StartI);
483   }
484   for (auto I = StartI, EE = EndI; I != EE; ++I) {
485     if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive))
486       continue;
487     DSAVarData DVar = getDSA(I, D);
488     if (CPred(DVar.CKind))
489       return DVar;
490   }
491   return DSAVarData();
492 }
493 
494 template <class ClausesPredicate, class DirectivesPredicate>
495 DSAStackTy::DSAVarData
496 DSAStackTy::hasInnermostDSA(VarDecl *D, ClausesPredicate CPred,
497                             DirectivesPredicate DPred, bool FromParent) {
498   auto StartI = std::next(Stack.rbegin());
499   auto EndI = std::prev(Stack.rend());
500   if (FromParent && StartI != EndI) {
501     StartI = std::next(StartI);
502   }
503   for (auto I = StartI, EE = EndI; I != EE; ++I) {
504     if (!DPred(I->Directive))
505       break;
506     DSAVarData DVar = getDSA(I, D);
507     if (CPred(DVar.CKind))
508       return DVar;
509     return DSAVarData();
510   }
511   return DSAVarData();
512 }
513 
514 template <class NamedDirectivesPredicate>
515 bool DSAStackTy::hasDirective(NamedDirectivesPredicate DPred, bool FromParent) {
516   auto StartI = std::next(Stack.rbegin());
517   auto EndI = std::prev(Stack.rend());
518   if (FromParent && StartI != EndI) {
519     StartI = std::next(StartI);
520   }
521   for (auto I = StartI, EE = EndI; I != EE; ++I) {
522     if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
523       return true;
524   }
525   return false;
526 }
527 
528 void Sema::InitDataSharingAttributesStack() {
529   VarDataSharingAttributesStack = new DSAStackTy(*this);
530 }
531 
532 #define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
533 
534 void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
535 
536 void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
537                                const DeclarationNameInfo &DirName,
538                                Scope *CurScope, SourceLocation Loc) {
539   DSAStack->push(DKind, DirName, CurScope, Loc);
540   PushExpressionEvaluationContext(PotentiallyEvaluated);
541 }
542 
543 void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
544   // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
545   //  A variable of class type (or array thereof) that appears in a lastprivate
546   //  clause requires an accessible, unambiguous default constructor for the
547   //  class type, unless the list item is also specified in a firstprivate
548   //  clause.
549   if (auto D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
550     for (auto C : D->clauses()) {
551       if (auto Clause = dyn_cast<OMPLastprivateClause>(C)) {
552         for (auto VarRef : Clause->varlists()) {
553           if (VarRef->isValueDependent() || VarRef->isTypeDependent())
554             continue;
555           auto VD = cast<VarDecl>(cast<DeclRefExpr>(VarRef)->getDecl());
556           auto DVar = DSAStack->getTopDSA(VD, false);
557           if (DVar.CKind == OMPC_lastprivate) {
558             SourceLocation ELoc = VarRef->getExprLoc();
559             auto Type = VarRef->getType();
560             if (Type->isArrayType())
561               Type = QualType(Type->getArrayElementTypeNoTypeQual(), 0);
562             CXXRecordDecl *RD =
563                 getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
564             // FIXME This code must be replaced by actual constructing of the
565             // lastprivate variable.
566             if (RD) {
567               CXXConstructorDecl *CD = LookupDefaultConstructor(RD);
568               PartialDiagnostic PD =
569                   PartialDiagnostic(PartialDiagnostic::NullDiagnostic());
570               if (!CD ||
571                   CheckConstructorAccess(
572                       ELoc, CD, InitializedEntity::InitializeTemporary(Type),
573                       CD->getAccess(), PD) == AR_inaccessible ||
574                   CD->isDeleted()) {
575                 Diag(ELoc, diag::err_omp_required_method)
576                     << getOpenMPClauseName(OMPC_lastprivate) << 0;
577                 bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
578                               VarDecl::DeclarationOnly;
579                 Diag(VD->getLocation(), IsDecl ? diag::note_previous_decl
580                                                : diag::note_defined_here)
581                     << VD;
582                 Diag(RD->getLocation(), diag::note_previous_decl) << RD;
583                 continue;
584               }
585               MarkFunctionReferenced(ELoc, CD);
586               DiagnoseUseOfDecl(CD, ELoc);
587             }
588           }
589         }
590       }
591     }
592   }
593 
594   DSAStack->pop();
595   DiscardCleanupsInEvaluationContext();
596   PopExpressionEvaluationContext();
597 }
598 
599 namespace {
600 
601 class VarDeclFilterCCC : public CorrectionCandidateCallback {
602 private:
603   Sema &SemaRef;
604 
605 public:
606   explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
607   bool ValidateCandidate(const TypoCorrection &Candidate) override {
608     NamedDecl *ND = Candidate.getCorrectionDecl();
609     if (VarDecl *VD = dyn_cast_or_null<VarDecl>(ND)) {
610       return VD->hasGlobalStorage() &&
611              SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
612                                    SemaRef.getCurScope());
613     }
614     return false;
615   }
616 };
617 } // namespace
618 
619 ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
620                                          CXXScopeSpec &ScopeSpec,
621                                          const DeclarationNameInfo &Id) {
622   LookupResult Lookup(*this, Id, LookupOrdinaryName);
623   LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
624 
625   if (Lookup.isAmbiguous())
626     return ExprError();
627 
628   VarDecl *VD;
629   if (!Lookup.isSingleResult()) {
630     VarDeclFilterCCC Validator(*this);
631     if (TypoCorrection Corrected =
632             CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, Validator,
633                         CTK_ErrorRecovery)) {
634       diagnoseTypo(Corrected,
635                    PDiag(Lookup.empty()
636                              ? diag::err_undeclared_var_use_suggest
637                              : diag::err_omp_expected_var_arg_suggest)
638                        << Id.getName());
639       VD = Corrected.getCorrectionDeclAs<VarDecl>();
640     } else {
641       Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
642                                        : diag::err_omp_expected_var_arg)
643           << Id.getName();
644       return ExprError();
645     }
646   } else {
647     if (!(VD = Lookup.getAsSingle<VarDecl>())) {
648       Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
649       Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
650       return ExprError();
651     }
652   }
653   Lookup.suppressDiagnostics();
654 
655   // OpenMP [2.9.2, Syntax, C/C++]
656   //   Variables must be file-scope, namespace-scope, or static block-scope.
657   if (!VD->hasGlobalStorage()) {
658     Diag(Id.getLoc(), diag::err_omp_global_var_arg)
659         << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal();
660     bool IsDecl =
661         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
662     Diag(VD->getLocation(),
663          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
664         << VD;
665     return ExprError();
666   }
667 
668   VarDecl *CanonicalVD = VD->getCanonicalDecl();
669   NamedDecl *ND = cast<NamedDecl>(CanonicalVD);
670   // OpenMP [2.9.2, Restrictions, C/C++, p.2]
671   //   A threadprivate directive for file-scope variables must appear outside
672   //   any definition or declaration.
673   if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
674       !getCurLexicalContext()->isTranslationUnit()) {
675     Diag(Id.getLoc(), diag::err_omp_var_scope)
676         << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
677     bool IsDecl =
678         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
679     Diag(VD->getLocation(),
680          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
681         << VD;
682     return ExprError();
683   }
684   // OpenMP [2.9.2, Restrictions, C/C++, p.3]
685   //   A threadprivate directive for static class member variables must appear
686   //   in the class definition, in the same scope in which the member
687   //   variables are declared.
688   if (CanonicalVD->isStaticDataMember() &&
689       !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
690     Diag(Id.getLoc(), diag::err_omp_var_scope)
691         << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
692     bool IsDecl =
693         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
694     Diag(VD->getLocation(),
695          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
696         << VD;
697     return ExprError();
698   }
699   // OpenMP [2.9.2, Restrictions, C/C++, p.4]
700   //   A threadprivate directive for namespace-scope variables must appear
701   //   outside any definition or declaration other than the namespace
702   //   definition itself.
703   if (CanonicalVD->getDeclContext()->isNamespace() &&
704       (!getCurLexicalContext()->isFileContext() ||
705        !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
706     Diag(Id.getLoc(), diag::err_omp_var_scope)
707         << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
708     bool IsDecl =
709         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
710     Diag(VD->getLocation(),
711          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
712         << VD;
713     return ExprError();
714   }
715   // OpenMP [2.9.2, Restrictions, C/C++, p.6]
716   //   A threadprivate directive for static block-scope variables must appear
717   //   in the scope of the variable and not in a nested scope.
718   if (CanonicalVD->isStaticLocal() && CurScope &&
719       !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
720     Diag(Id.getLoc(), diag::err_omp_var_scope)
721         << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
722     bool IsDecl =
723         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
724     Diag(VD->getLocation(),
725          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
726         << VD;
727     return ExprError();
728   }
729 
730   // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
731   //   A threadprivate directive must lexically precede all references to any
732   //   of the variables in its list.
733   if (VD->isUsed()) {
734     Diag(Id.getLoc(), diag::err_omp_var_used)
735         << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
736     return ExprError();
737   }
738 
739   QualType ExprType = VD->getType().getNonReferenceType();
740   ExprResult DE = BuildDeclRefExpr(VD, ExprType, VK_LValue, Id.getLoc());
741   return DE;
742 }
743 
744 Sema::DeclGroupPtrTy
745 Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
746                                         ArrayRef<Expr *> VarList) {
747   if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
748     CurContext->addDecl(D);
749     return DeclGroupPtrTy::make(DeclGroupRef(D));
750   }
751   return DeclGroupPtrTy();
752 }
753 
754 namespace {
755 class LocalVarRefChecker : public ConstStmtVisitor<LocalVarRefChecker, bool> {
756   Sema &SemaRef;
757 
758 public:
759   bool VisitDeclRefExpr(const DeclRefExpr *E) {
760     if (auto VD = dyn_cast<VarDecl>(E->getDecl())) {
761       if (VD->hasLocalStorage()) {
762         SemaRef.Diag(E->getLocStart(),
763                      diag::err_omp_local_var_in_threadprivate_init)
764             << E->getSourceRange();
765         SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
766             << VD << VD->getSourceRange();
767         return true;
768       }
769     }
770     return false;
771   }
772   bool VisitStmt(const Stmt *S) {
773     for (auto Child : S->children()) {
774       if (Child && Visit(Child))
775         return true;
776     }
777     return false;
778   }
779   explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
780 };
781 } // namespace
782 
783 OMPThreadPrivateDecl *
784 Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
785   SmallVector<Expr *, 8> Vars;
786   for (auto &RefExpr : VarList) {
787     DeclRefExpr *DE = cast<DeclRefExpr>(RefExpr);
788     VarDecl *VD = cast<VarDecl>(DE->getDecl());
789     SourceLocation ILoc = DE->getExprLoc();
790 
791     // OpenMP [2.9.2, Restrictions, C/C++, p.10]
792     //   A threadprivate variable must not have an incomplete type.
793     if (RequireCompleteType(ILoc, VD->getType(),
794                             diag::err_omp_threadprivate_incomplete_type)) {
795       continue;
796     }
797 
798     // OpenMP [2.9.2, Restrictions, C/C++, p.10]
799     //   A threadprivate variable must not have a reference type.
800     if (VD->getType()->isReferenceType()) {
801       Diag(ILoc, diag::err_omp_ref_type_arg)
802           << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
803       bool IsDecl =
804           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
805       Diag(VD->getLocation(),
806            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
807           << VD;
808       continue;
809     }
810 
811     // Check if this is a TLS variable.
812     if (VD->getTLSKind()) {
813       Diag(ILoc, diag::err_omp_var_thread_local) << VD;
814       bool IsDecl =
815           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
816       Diag(VD->getLocation(),
817            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
818           << VD;
819       continue;
820     }
821 
822     // Check if initial value of threadprivate variable reference variable with
823     // local storage (it is not supported by runtime).
824     if (auto Init = VD->getAnyInitializer()) {
825       LocalVarRefChecker Checker(*this);
826       if (Checker.Visit(Init))
827         continue;
828     }
829 
830     Vars.push_back(RefExpr);
831     DSAStack->addDSA(VD, DE, OMPC_threadprivate);
832   }
833   OMPThreadPrivateDecl *D = nullptr;
834   if (!Vars.empty()) {
835     D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
836                                      Vars);
837     D->setAccess(AS_public);
838   }
839   return D;
840 }
841 
842 static void ReportOriginalDSA(Sema &SemaRef, DSAStackTy *Stack,
843                               const VarDecl *VD, DSAStackTy::DSAVarData DVar,
844                               bool IsLoopIterVar = false) {
845   if (DVar.RefExpr) {
846     SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
847         << getOpenMPClauseName(DVar.CKind);
848     return;
849   }
850   enum {
851     PDSA_StaticMemberShared,
852     PDSA_StaticLocalVarShared,
853     PDSA_LoopIterVarPrivate,
854     PDSA_LoopIterVarLinear,
855     PDSA_LoopIterVarLastprivate,
856     PDSA_ConstVarShared,
857     PDSA_GlobalVarShared,
858     PDSA_TaskVarFirstprivate,
859     PDSA_LocalVarPrivate,
860     PDSA_Implicit
861   } Reason = PDSA_Implicit;
862   bool ReportHint = false;
863   auto ReportLoc = VD->getLocation();
864   if (IsLoopIterVar) {
865     if (DVar.CKind == OMPC_private)
866       Reason = PDSA_LoopIterVarPrivate;
867     else if (DVar.CKind == OMPC_lastprivate)
868       Reason = PDSA_LoopIterVarLastprivate;
869     else
870       Reason = PDSA_LoopIterVarLinear;
871   } else if (DVar.DKind == OMPD_task && DVar.CKind == OMPC_firstprivate) {
872     Reason = PDSA_TaskVarFirstprivate;
873     ReportLoc = DVar.ImplicitDSALoc;
874   } else if (VD->isStaticLocal())
875     Reason = PDSA_StaticLocalVarShared;
876   else if (VD->isStaticDataMember())
877     Reason = PDSA_StaticMemberShared;
878   else if (VD->isFileVarDecl())
879     Reason = PDSA_GlobalVarShared;
880   else if (VD->getType().isConstant(SemaRef.getASTContext()))
881     Reason = PDSA_ConstVarShared;
882   else if (VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
883     ReportHint = true;
884     Reason = PDSA_LocalVarPrivate;
885   }
886   if (Reason != PDSA_Implicit) {
887     SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
888         << Reason << ReportHint
889         << getOpenMPDirectiveName(Stack->getCurrentDirective());
890   } else if (DVar.ImplicitDSALoc.isValid()) {
891     SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
892         << getOpenMPClauseName(DVar.CKind);
893   }
894 }
895 
896 namespace {
897 class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> {
898   DSAStackTy *Stack;
899   Sema &SemaRef;
900   bool ErrorFound;
901   CapturedStmt *CS;
902   llvm::SmallVector<Expr *, 8> ImplicitFirstprivate;
903   llvm::DenseMap<VarDecl *, Expr *> VarsWithInheritedDSA;
904 
905 public:
906   void VisitDeclRefExpr(DeclRefExpr *E) {
907     if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
908       // Skip internally declared variables.
909       if (VD->isLocalVarDecl() && !CS->capturesVariable(VD))
910         return;
911 
912       auto DVar = Stack->getTopDSA(VD, false);
913       // Check if the variable has explicit DSA set and stop analysis if it so.
914       if (DVar.RefExpr) return;
915 
916       auto ELoc = E->getExprLoc();
917       auto DKind = Stack->getCurrentDirective();
918       // The default(none) clause requires that each variable that is referenced
919       // in the construct, and does not have a predetermined data-sharing
920       // attribute, must have its data-sharing attribute explicitly determined
921       // by being listed in a data-sharing attribute clause.
922       if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
923           isParallelOrTaskRegion(DKind) &&
924           VarsWithInheritedDSA.count(VD) == 0) {
925         VarsWithInheritedDSA[VD] = E;
926         return;
927       }
928 
929       // OpenMP [2.9.3.6, Restrictions, p.2]
930       //  A list item that appears in a reduction clause of the innermost
931       //  enclosing worksharing or parallel construct may not be accessed in an
932       //  explicit task.
933       DVar = Stack->hasInnermostDSA(VD, MatchesAnyClause(OMPC_reduction),
934                                     [](OpenMPDirectiveKind K) -> bool {
935                                       return isOpenMPParallelDirective(K) ||
936                                              isOpenMPWorksharingDirective(K);
937                                     },
938                                     false);
939       if (DKind == OMPD_task && DVar.CKind == OMPC_reduction) {
940         ErrorFound = true;
941         SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
942         ReportOriginalDSA(SemaRef, Stack, VD, DVar);
943         return;
944       }
945 
946       // Define implicit data-sharing attributes for task.
947       DVar = Stack->getImplicitDSA(VD, false);
948       if (DKind == OMPD_task && DVar.CKind != OMPC_shared)
949         ImplicitFirstprivate.push_back(E);
950     }
951   }
952   void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
953     for (auto *C : S->clauses()) {
954       // Skip analysis of arguments of implicitly defined firstprivate clause
955       // for task directives.
956       if (C && (!isa<OMPFirstprivateClause>(C) || C->getLocStart().isValid()))
957         for (auto *CC : C->children()) {
958           if (CC)
959             Visit(CC);
960         }
961     }
962   }
963   void VisitStmt(Stmt *S) {
964     for (auto *C : S->children()) {
965       if (C && !isa<OMPExecutableDirective>(C))
966         Visit(C);
967     }
968   }
969 
970   bool isErrorFound() { return ErrorFound; }
971   ArrayRef<Expr *> getImplicitFirstprivate() { return ImplicitFirstprivate; }
972   llvm::DenseMap<VarDecl *, Expr *> &getVarsWithInheritedDSA() {
973     return VarsWithInheritedDSA;
974   }
975 
976   DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
977       : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {}
978 };
979 } // namespace
980 
981 void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
982   switch (DKind) {
983   case OMPD_parallel: {
984     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
985     QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
986     Sema::CapturedParamNameType Params[] = {
987         std::make_pair(".global_tid.", KmpInt32PtrTy),
988         std::make_pair(".bound_tid.", KmpInt32PtrTy),
989         std::make_pair(StringRef(), QualType()) // __context with shared vars
990     };
991     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
992                              Params);
993     break;
994   }
995   case OMPD_simd: {
996     Sema::CapturedParamNameType Params[] = {
997         std::make_pair(StringRef(), QualType()) // __context with shared vars
998     };
999     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1000                              Params);
1001     break;
1002   }
1003   case OMPD_for: {
1004     Sema::CapturedParamNameType Params[] = {
1005         std::make_pair(StringRef(), QualType()) // __context with shared vars
1006     };
1007     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1008                              Params);
1009     break;
1010   }
1011   case OMPD_sections: {
1012     Sema::CapturedParamNameType Params[] = {
1013         std::make_pair(StringRef(), QualType()) // __context with shared vars
1014     };
1015     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1016                              Params);
1017     break;
1018   }
1019   case OMPD_section: {
1020     Sema::CapturedParamNameType Params[] = {
1021         std::make_pair(StringRef(), QualType()) // __context with shared vars
1022     };
1023     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1024                              Params);
1025     break;
1026   }
1027   case OMPD_single: {
1028     Sema::CapturedParamNameType Params[] = {
1029         std::make_pair(StringRef(), QualType()) // __context with shared vars
1030     };
1031     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1032                              Params);
1033     break;
1034   }
1035   case OMPD_master: {
1036     Sema::CapturedParamNameType Params[] = {
1037         std::make_pair(StringRef(), QualType()) // __context with shared vars
1038     };
1039     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1040                              Params);
1041     break;
1042   }
1043   case OMPD_critical: {
1044     Sema::CapturedParamNameType Params[] = {
1045         std::make_pair(StringRef(), QualType()) // __context with shared vars
1046     };
1047     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1048                              Params);
1049     break;
1050   }
1051   case OMPD_parallel_for: {
1052     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1053     QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
1054     Sema::CapturedParamNameType Params[] = {
1055         std::make_pair(".global_tid.", KmpInt32PtrTy),
1056         std::make_pair(".bound_tid.", KmpInt32PtrTy),
1057         std::make_pair(StringRef(), QualType()) // __context with shared vars
1058     };
1059     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1060                              Params);
1061     break;
1062   }
1063   case OMPD_parallel_sections: {
1064     Sema::CapturedParamNameType Params[] = {
1065         std::make_pair(StringRef(), QualType()) // __context with shared vars
1066     };
1067     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1068                              Params);
1069     break;
1070   }
1071   case OMPD_task: {
1072     Sema::CapturedParamNameType Params[] = {
1073         std::make_pair(StringRef(), QualType()) // __context with shared vars
1074     };
1075     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1076                              Params);
1077     break;
1078   }
1079   case OMPD_taskyield: {
1080     Sema::CapturedParamNameType Params[] = {
1081         std::make_pair(StringRef(), QualType()) // __context with shared vars
1082     };
1083     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1084                              Params);
1085     break;
1086   }
1087   case OMPD_barrier: {
1088     Sema::CapturedParamNameType Params[] = {
1089         std::make_pair(StringRef(), QualType()) // __context with shared vars
1090     };
1091     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1092                              Params);
1093     break;
1094   }
1095   case OMPD_taskwait: {
1096     Sema::CapturedParamNameType Params[] = {
1097         std::make_pair(StringRef(), QualType()) // __context with shared vars
1098     };
1099     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1100                              Params);
1101     break;
1102   }
1103   case OMPD_flush: {
1104     Sema::CapturedParamNameType Params[] = {
1105         std::make_pair(StringRef(), QualType()) // __context with shared vars
1106     };
1107     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1108                              Params);
1109     break;
1110   }
1111   case OMPD_ordered: {
1112     Sema::CapturedParamNameType Params[] = {
1113         std::make_pair(StringRef(), QualType()) // __context with shared vars
1114     };
1115     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1116                              Params);
1117     break;
1118   }
1119   case OMPD_atomic: {
1120     Sema::CapturedParamNameType Params[] = {
1121         std::make_pair(StringRef(), QualType()) // __context with shared vars
1122     };
1123     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1124                              Params);
1125     break;
1126   }
1127   case OMPD_threadprivate:
1128     llvm_unreachable("OpenMP Directive is not allowed");
1129   case OMPD_unknown:
1130     llvm_unreachable("Unknown OpenMP directive");
1131   }
1132 }
1133 
1134 static bool CheckNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack,
1135                                   OpenMPDirectiveKind CurrentRegion,
1136                                   const DeclarationNameInfo &CurrentName,
1137                                   SourceLocation StartLoc) {
1138   // Allowed nesting of constructs
1139   // +------------------+-----------------+------------------------------------+
1140   // | Parent directive | Child directive | Closely (!), No-Closely(+), Both(*)|
1141   // +------------------+-----------------+------------------------------------+
1142   // | parallel         | parallel        | *                                  |
1143   // | parallel         | for             | *                                  |
1144   // | parallel         | master          | *                                  |
1145   // | parallel         | critical        | *                                  |
1146   // | parallel         | simd            | *                                  |
1147   // | parallel         | sections        | *                                  |
1148   // | parallel         | section         | +                                  |
1149   // | parallel         | single          | *                                  |
1150   // | parallel         | parallel for    | *                                  |
1151   // | parallel         |parallel sections| *                                  |
1152   // | parallel         | task            | *                                  |
1153   // | parallel         | taskyield       | *                                  |
1154   // | parallel         | barrier         | *                                  |
1155   // | parallel         | taskwait        | *                                  |
1156   // | parallel         | flush           | *                                  |
1157   // | parallel         | ordered         | +                                  |
1158   // | parallel         | atomic          | *                                  |
1159   // +------------------+-----------------+------------------------------------+
1160   // | for              | parallel        | *                                  |
1161   // | for              | for             | +                                  |
1162   // | for              | master          | +                                  |
1163   // | for              | critical        | *                                  |
1164   // | for              | simd            | *                                  |
1165   // | for              | sections        | +                                  |
1166   // | for              | section         | +                                  |
1167   // | for              | single          | +                                  |
1168   // | for              | parallel for    | *                                  |
1169   // | for              |parallel sections| *                                  |
1170   // | for              | task            | *                                  |
1171   // | for              | taskyield       | *                                  |
1172   // | for              | barrier         | +                                  |
1173   // | for              | taskwait        | *                                  |
1174   // | for              | flush           | *                                  |
1175   // | for              | ordered         | * (if construct is ordered)        |
1176   // | for              | atomic          | *                                  |
1177   // +------------------+-----------------+------------------------------------+
1178   // | master           | parallel        | *                                  |
1179   // | master           | for             | +                                  |
1180   // | master           | master          | *                                  |
1181   // | master           | critical        | *                                  |
1182   // | master           | simd            | *                                  |
1183   // | master           | sections        | +                                  |
1184   // | master           | section         | +                                  |
1185   // | master           | single          | +                                  |
1186   // | master           | parallel for    | *                                  |
1187   // | master           |parallel sections| *                                  |
1188   // | master           | task            | *                                  |
1189   // | master           | taskyield       | *                                  |
1190   // | master           | barrier         | +                                  |
1191   // | master           | taskwait        | *                                  |
1192   // | master           | flush           | *                                  |
1193   // | master           | ordered         | +                                  |
1194   // | master           | atomic          | *                                  |
1195   // +------------------+-----------------+------------------------------------+
1196   // | critical         | parallel        | *                                  |
1197   // | critical         | for             | +                                  |
1198   // | critical         | master          | *                                  |
1199   // | critical         | critical        | * (should have different names)    |
1200   // | critical         | simd            | *                                  |
1201   // | critical         | sections        | +                                  |
1202   // | critical         | section         | +                                  |
1203   // | critical         | single          | +                                  |
1204   // | critical         | parallel for    | *                                  |
1205   // | critical         |parallel sections| *                                  |
1206   // | critical         | task            | *                                  |
1207   // | critical         | taskyield       | *                                  |
1208   // | critical         | barrier         | +                                  |
1209   // | critical         | taskwait        | *                                  |
1210   // | critical         | ordered         | +                                  |
1211   // | critical         | atomic          | *                                  |
1212   // +------------------+-----------------+------------------------------------+
1213   // | simd             | parallel        |                                    |
1214   // | simd             | for             |                                    |
1215   // | simd             | master          |                                    |
1216   // | simd             | critical        |                                    |
1217   // | simd             | simd            |                                    |
1218   // | simd             | sections        |                                    |
1219   // | simd             | section         |                                    |
1220   // | simd             | single          |                                    |
1221   // | simd             | parallel for    |                                    |
1222   // | simd             |parallel sections|                                    |
1223   // | simd             | task            |                                    |
1224   // | simd             | taskyield       |                                    |
1225   // | simd             | barrier         |                                    |
1226   // | simd             | taskwait        |                                    |
1227   // | simd             | flush           |                                    |
1228   // | simd             | ordered         |                                    |
1229   // | simd             | atomic          |                                    |
1230   // +------------------+-----------------+------------------------------------+
1231   // | sections         | parallel        | *                                  |
1232   // | sections         | for             | +                                  |
1233   // | sections         | master          | +                                  |
1234   // | sections         | critical        | *                                  |
1235   // | sections         | simd            | *                                  |
1236   // | sections         | sections        | +                                  |
1237   // | sections         | section         | *                                  |
1238   // | sections         | single          | +                                  |
1239   // | sections         | parallel for    | *                                  |
1240   // | sections         |parallel sections| *                                  |
1241   // | sections         | task            | *                                  |
1242   // | sections         | taskyield       | *                                  |
1243   // | sections         | barrier         | +                                  |
1244   // | sections         | taskwait        | *                                  |
1245   // | sections         | flush           | *                                  |
1246   // | sections         | ordered         | +                                  |
1247   // | sections         | atomic          | *                                  |
1248   // +------------------+-----------------+------------------------------------+
1249   // | section          | parallel        | *                                  |
1250   // | section          | for             | +                                  |
1251   // | section          | master          | +                                  |
1252   // | section          | critical        | *                                  |
1253   // | section          | simd            | *                                  |
1254   // | section          | sections        | +                                  |
1255   // | section          | section         | +                                  |
1256   // | section          | single          | +                                  |
1257   // | section          | parallel for    | *                                  |
1258   // | section          |parallel sections| *                                  |
1259   // | section          | task            | *                                  |
1260   // | section          | taskyield       | *                                  |
1261   // | section          | barrier         | +                                  |
1262   // | section          | taskwait        | *                                  |
1263   // | section          | flush           | *                                  |
1264   // | section          | ordered         | +                                  |
1265   // | section          | atomic          | *                                  |
1266   // +------------------+-----------------+------------------------------------+
1267   // | single           | parallel        | *                                  |
1268   // | single           | for             | +                                  |
1269   // | single           | master          | +                                  |
1270   // | single           | critical        | *                                  |
1271   // | single           | simd            | *                                  |
1272   // | single           | sections        | +                                  |
1273   // | single           | section         | +                                  |
1274   // | single           | single          | +                                  |
1275   // | single           | parallel for    | *                                  |
1276   // | single           |parallel sections| *                                  |
1277   // | single           | task            | *                                  |
1278   // | single           | taskyield       | *                                  |
1279   // | single           | barrier         | +                                  |
1280   // | single           | taskwait        | *                                  |
1281   // | single           | flush           | *                                  |
1282   // | single           | ordered         | +                                  |
1283   // | single           | atomic          | *                                  |
1284   // +------------------+-----------------+------------------------------------+
1285   // | parallel for     | parallel        | *                                  |
1286   // | parallel for     | for             | +                                  |
1287   // | parallel for     | master          | +                                  |
1288   // | parallel for     | critical        | *                                  |
1289   // | parallel for     | simd            | *                                  |
1290   // | parallel for     | sections        | +                                  |
1291   // | parallel for     | section         | +                                  |
1292   // | parallel for     | single          | +                                  |
1293   // | parallel for     | parallel for    | *                                  |
1294   // | parallel for     |parallel sections| *                                  |
1295   // | parallel for     | task            | *                                  |
1296   // | parallel for     | taskyield       | *                                  |
1297   // | parallel for     | barrier         | +                                  |
1298   // | parallel for     | taskwait        | *                                  |
1299   // | parallel for     | flush           | *                                  |
1300   // | parallel for     | ordered         | * (if construct is ordered)        |
1301   // | parallel for     | atomic          | *                                  |
1302   // +------------------+-----------------+------------------------------------+
1303   // | parallel sections| parallel        | *                                  |
1304   // | parallel sections| for             | +                                  |
1305   // | parallel sections| master          | +                                  |
1306   // | parallel sections| critical        | +                                  |
1307   // | parallel sections| simd            | *                                  |
1308   // | parallel sections| sections        | +                                  |
1309   // | parallel sections| section         | *                                  |
1310   // | parallel sections| single          | +                                  |
1311   // | parallel sections| parallel for    | *                                  |
1312   // | parallel sections|parallel sections| *                                  |
1313   // | parallel sections| task            | *                                  |
1314   // | parallel sections| taskyield       | *                                  |
1315   // | parallel sections| barrier         | +                                  |
1316   // | parallel sections| taskwait        | *                                  |
1317   // | parallel sections| flush           | *                                  |
1318   // | parallel sections| ordered         | +                                  |
1319   // | parallel sections| atomic          | *                                  |
1320   // +------------------+-----------------+------------------------------------+
1321   // | task             | parallel        | *                                  |
1322   // | task             | for             | +                                  |
1323   // | task             | master          | +                                  |
1324   // | task             | critical        | *                                  |
1325   // | task             | simd            | *                                  |
1326   // | task             | sections        | +                                  |
1327   // | task             | section         | +                                  |
1328   // | task             | single          | +                                  |
1329   // | task             | parallel for    | *                                  |
1330   // | task             |parallel sections| *                                  |
1331   // | task             | task            | *                                  |
1332   // | task             | taskyield       | *                                  |
1333   // | task             | barrier         | +                                  |
1334   // | task             | taskwait        | *                                  |
1335   // | task             | flush           | *                                  |
1336   // | task             | ordered         | +                                  |
1337   // | task             | atomic          | *                                  |
1338   // +------------------+-----------------+------------------------------------+
1339   // | ordered          | parallel        | *                                  |
1340   // | ordered          | for             | +                                  |
1341   // | ordered          | master          | *                                  |
1342   // | ordered          | critical        | *                                  |
1343   // | ordered          | simd            | *                                  |
1344   // | ordered          | sections        | +                                  |
1345   // | ordered          | section         | +                                  |
1346   // | ordered          | single          | +                                  |
1347   // | ordered          | parallel for    | *                                  |
1348   // | ordered          |parallel sections| *                                  |
1349   // | ordered          | task            | *                                  |
1350   // | ordered          | taskyield       | *                                  |
1351   // | ordered          | barrier         | +                                  |
1352   // | ordered          | taskwait        | *                                  |
1353   // | ordered          | flush           | *                                  |
1354   // | ordered          | ordered         | +                                  |
1355   // | ordered          | atomic          | *                                  |
1356   // +------------------+-----------------+------------------------------------+
1357   if (Stack->getCurScope()) {
1358     auto ParentRegion = Stack->getParentDirective();
1359     bool NestingProhibited = false;
1360     bool CloseNesting = true;
1361     enum {
1362       NoRecommend,
1363       ShouldBeInParallelRegion,
1364       ShouldBeInOrderedRegion
1365     } Recommend = NoRecommend;
1366     if (isOpenMPSimdDirective(ParentRegion)) {
1367       // OpenMP [2.16, Nesting of Regions]
1368       // OpenMP constructs may not be nested inside a simd region.
1369       SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_simd);
1370       return true;
1371     }
1372     if (ParentRegion == OMPD_atomic) {
1373       // OpenMP [2.16, Nesting of Regions]
1374       // OpenMP constructs may not be nested inside an atomic region.
1375       SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
1376       return true;
1377     }
1378     if (CurrentRegion == OMPD_section) {
1379       // OpenMP [2.7.2, sections Construct, Restrictions]
1380       // Orphaned section directives are prohibited. That is, the section
1381       // directives must appear within the sections construct and must not be
1382       // encountered elsewhere in the sections region.
1383       if (ParentRegion != OMPD_sections &&
1384           ParentRegion != OMPD_parallel_sections) {
1385         SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
1386             << (ParentRegion != OMPD_unknown)
1387             << getOpenMPDirectiveName(ParentRegion);
1388         return true;
1389       }
1390       return false;
1391     }
1392     // Allow some constructs to be orphaned (they could be used in functions,
1393     // called from OpenMP regions with the required preconditions).
1394     if (ParentRegion == OMPD_unknown)
1395       return false;
1396     if (CurrentRegion == OMPD_master) {
1397       // OpenMP [2.16, Nesting of Regions]
1398       // A master region may not be closely nested inside a worksharing,
1399       // atomic, or explicit task region.
1400       NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
1401                           ParentRegion == OMPD_task;
1402     } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
1403       // OpenMP [2.16, Nesting of Regions]
1404       // A critical region may not be nested (closely or otherwise) inside a
1405       // critical region with the same name. Note that this restriction is not
1406       // sufficient to prevent deadlock.
1407       SourceLocation PreviousCriticalLoc;
1408       bool DeadLock =
1409           Stack->hasDirective([CurrentName, &PreviousCriticalLoc](
1410                                   OpenMPDirectiveKind K,
1411                                   const DeclarationNameInfo &DNI,
1412                                   SourceLocation Loc)
1413                                   ->bool {
1414                                 if (K == OMPD_critical &&
1415                                     DNI.getName() == CurrentName.getName()) {
1416                                   PreviousCriticalLoc = Loc;
1417                                   return true;
1418                                 } else
1419                                   return false;
1420                               },
1421                               false /* skip top directive */);
1422       if (DeadLock) {
1423         SemaRef.Diag(StartLoc,
1424                      diag::err_omp_prohibited_region_critical_same_name)
1425             << CurrentName.getName();
1426         if (PreviousCriticalLoc.isValid())
1427           SemaRef.Diag(PreviousCriticalLoc,
1428                        diag::note_omp_previous_critical_region);
1429         return true;
1430       }
1431     } else if (CurrentRegion == OMPD_barrier) {
1432       // OpenMP [2.16, Nesting of Regions]
1433       // A barrier region may not be closely nested inside a worksharing,
1434       // explicit task, critical, ordered, atomic, or master region.
1435       NestingProhibited =
1436           isOpenMPWorksharingDirective(ParentRegion) ||
1437           ParentRegion == OMPD_task || ParentRegion == OMPD_master ||
1438           ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered;
1439     } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
1440                !isOpenMPParallelDirective(CurrentRegion) &&
1441                !isOpenMPSimdDirective(CurrentRegion)) {
1442       // OpenMP [2.16, Nesting of Regions]
1443       // A worksharing region may not be closely nested inside a worksharing,
1444       // explicit task, critical, ordered, atomic, or master region.
1445       NestingProhibited =
1446           (isOpenMPWorksharingDirective(ParentRegion) &&
1447            !isOpenMPSimdDirective(ParentRegion)) ||
1448           ParentRegion == OMPD_task || ParentRegion == OMPD_master ||
1449           ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered;
1450       Recommend = ShouldBeInParallelRegion;
1451     } else if (CurrentRegion == OMPD_ordered) {
1452       // OpenMP [2.16, Nesting of Regions]
1453       // An ordered region may not be closely nested inside a critical,
1454       // atomic, or explicit task region.
1455       // An ordered region must be closely nested inside a loop region (or
1456       // parallel loop region) with an ordered clause.
1457       NestingProhibited = ParentRegion == OMPD_critical ||
1458                           ParentRegion == OMPD_task ||
1459                           !Stack->isParentOrderedRegion();
1460       Recommend = ShouldBeInOrderedRegion;
1461     }
1462     if (NestingProhibited) {
1463       SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
1464           << CloseNesting << getOpenMPDirectiveName(ParentRegion) << Recommend
1465           << getOpenMPDirectiveName(CurrentRegion);
1466       return true;
1467     }
1468   }
1469   return false;
1470 }
1471 
1472 StmtResult Sema::ActOnOpenMPExecutableDirective(OpenMPDirectiveKind Kind,
1473                                                 const DeclarationNameInfo &DirName,
1474                                                 ArrayRef<OMPClause *> Clauses,
1475                                                 Stmt *AStmt,
1476                                                 SourceLocation StartLoc,
1477                                                 SourceLocation EndLoc) {
1478   StmtResult Res = StmtError();
1479   if (CheckNestingOfRegions(*this, DSAStack, Kind, DirName, StartLoc))
1480     return StmtError();
1481 
1482   llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
1483   llvm::DenseMap<VarDecl *, Expr *> VarsWithInheritedDSA;
1484   bool ErrorFound = false;
1485   ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
1486   if (AStmt) {
1487     assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
1488 
1489     // Check default data sharing attributes for referenced variables.
1490     DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
1491     DSAChecker.Visit(cast<CapturedStmt>(AStmt)->getCapturedStmt());
1492     if (DSAChecker.isErrorFound())
1493       return StmtError();
1494     // Generate list of implicitly defined firstprivate variables.
1495     VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
1496 
1497     if (!DSAChecker.getImplicitFirstprivate().empty()) {
1498       if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
1499               DSAChecker.getImplicitFirstprivate(), SourceLocation(),
1500               SourceLocation(), SourceLocation())) {
1501         ClausesWithImplicit.push_back(Implicit);
1502         ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
1503                      DSAChecker.getImplicitFirstprivate().size();
1504       } else
1505         ErrorFound = true;
1506     }
1507   }
1508 
1509   switch (Kind) {
1510   case OMPD_parallel:
1511     Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
1512                                        EndLoc);
1513     break;
1514   case OMPD_simd:
1515     Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
1516                                    VarsWithInheritedDSA);
1517     break;
1518   case OMPD_for:
1519     Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
1520                                   VarsWithInheritedDSA);
1521     break;
1522   case OMPD_sections:
1523     Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
1524                                        EndLoc);
1525     break;
1526   case OMPD_section:
1527     assert(ClausesWithImplicit.empty() &&
1528            "No clauses are allowed for 'omp section' directive");
1529     Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
1530     break;
1531   case OMPD_single:
1532     Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
1533                                      EndLoc);
1534     break;
1535   case OMPD_master:
1536     assert(ClausesWithImplicit.empty() &&
1537            "No clauses are allowed for 'omp master' directive");
1538     Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
1539     break;
1540   case OMPD_critical:
1541     assert(ClausesWithImplicit.empty() &&
1542            "No clauses are allowed for 'omp critical' directive");
1543     Res = ActOnOpenMPCriticalDirective(DirName, AStmt, StartLoc, EndLoc);
1544     break;
1545   case OMPD_parallel_for:
1546     Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
1547                                           EndLoc, VarsWithInheritedDSA);
1548     break;
1549   case OMPD_parallel_sections:
1550     Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
1551                                                StartLoc, EndLoc);
1552     break;
1553   case OMPD_task:
1554     Res =
1555         ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
1556     break;
1557   case OMPD_taskyield:
1558     assert(ClausesWithImplicit.empty() &&
1559            "No clauses are allowed for 'omp taskyield' directive");
1560     assert(AStmt == nullptr &&
1561            "No associated statement allowed for 'omp taskyield' directive");
1562     Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
1563     break;
1564   case OMPD_barrier:
1565     assert(ClausesWithImplicit.empty() &&
1566            "No clauses are allowed for 'omp barrier' directive");
1567     assert(AStmt == nullptr &&
1568            "No associated statement allowed for 'omp barrier' directive");
1569     Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
1570     break;
1571   case OMPD_taskwait:
1572     assert(ClausesWithImplicit.empty() &&
1573            "No clauses are allowed for 'omp taskwait' directive");
1574     assert(AStmt == nullptr &&
1575            "No associated statement allowed for 'omp taskwait' directive");
1576     Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
1577     break;
1578   case OMPD_flush:
1579     assert(AStmt == nullptr &&
1580            "No associated statement allowed for 'omp flush' directive");
1581     Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
1582     break;
1583   case OMPD_ordered:
1584     assert(ClausesWithImplicit.empty() &&
1585            "No clauses are allowed for 'omp ordered' directive");
1586     Res = ActOnOpenMPOrderedDirective(AStmt, StartLoc, EndLoc);
1587     break;
1588   case OMPD_atomic:
1589     Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
1590                                      EndLoc);
1591     break;
1592   case OMPD_threadprivate:
1593     llvm_unreachable("OpenMP Directive is not allowed");
1594   case OMPD_unknown:
1595     llvm_unreachable("Unknown OpenMP directive");
1596   }
1597 
1598   for (auto P : VarsWithInheritedDSA) {
1599     Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
1600         << P.first << P.second->getSourceRange();
1601   }
1602   if (!VarsWithInheritedDSA.empty())
1603     return StmtError();
1604 
1605   if (ErrorFound)
1606     return StmtError();
1607   return Res;
1608 }
1609 
1610 StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
1611                                               Stmt *AStmt,
1612                                               SourceLocation StartLoc,
1613                                               SourceLocation EndLoc) {
1614   assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
1615   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
1616   // 1.2.2 OpenMP Language Terminology
1617   // Structured block - An executable statement with a single entry at the
1618   // top and a single exit at the bottom.
1619   // The point of exit cannot be a branch out of the structured block.
1620   // longjmp() and throw() must not violate the entry/exit criteria.
1621   CS->getCapturedDecl()->setNothrow();
1622 
1623   getCurFunction()->setHasBranchProtectedScope();
1624 
1625   return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
1626                                       AStmt);
1627 }
1628 
1629 namespace {
1630 /// \brief Helper class for checking canonical form of the OpenMP loops and
1631 /// extracting iteration space of each loop in the loop nest, that will be used
1632 /// for IR generation.
1633 class OpenMPIterationSpaceChecker {
1634   /// \brief Reference to Sema.
1635   Sema &SemaRef;
1636   /// \brief A location for diagnostics (when there is no some better location).
1637   SourceLocation DefaultLoc;
1638   /// \brief A location for diagnostics (when increment is not compatible).
1639   SourceLocation ConditionLoc;
1640   /// \brief A source location for referring to condition later.
1641   SourceRange ConditionSrcRange;
1642   /// \brief Loop variable.
1643   VarDecl *Var;
1644   /// \brief Reference to loop variable.
1645   DeclRefExpr *VarRef;
1646   /// \brief Lower bound (initializer for the var).
1647   Expr *LB;
1648   /// \brief Upper bound.
1649   Expr *UB;
1650   /// \brief Loop step (increment).
1651   Expr *Step;
1652   /// \brief This flag is true when condition is one of:
1653   ///   Var <  UB
1654   ///   Var <= UB
1655   ///   UB  >  Var
1656   ///   UB  >= Var
1657   bool TestIsLessOp;
1658   /// \brief This flag is true when condition is strict ( < or > ).
1659   bool TestIsStrictOp;
1660   /// \brief This flag is true when step is subtracted on each iteration.
1661   bool SubtractStep;
1662 
1663 public:
1664   OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
1665       : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc),
1666         ConditionSrcRange(SourceRange()), Var(nullptr), VarRef(nullptr),
1667         LB(nullptr), UB(nullptr), Step(nullptr), TestIsLessOp(false),
1668         TestIsStrictOp(false), SubtractStep(false) {}
1669   /// \brief Check init-expr for canonical loop form and save loop counter
1670   /// variable - #Var and its initialization value - #LB.
1671   bool CheckInit(Stmt *S);
1672   /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags
1673   /// for less/greater and for strict/non-strict comparison.
1674   bool CheckCond(Expr *S);
1675   /// \brief Check incr-expr for canonical loop form and return true if it
1676   /// does not conform, otherwise save loop step (#Step).
1677   bool CheckInc(Expr *S);
1678   /// \brief Return the loop counter variable.
1679   VarDecl *GetLoopVar() const { return Var; }
1680   /// \brief Return the reference expression to loop counter variable.
1681   DeclRefExpr *GetLoopVarRefExpr() const { return VarRef; }
1682   /// \brief Return true if any expression is dependent.
1683   bool Dependent() const;
1684 
1685 private:
1686   /// \brief Check the right-hand side of an assignment in the increment
1687   /// expression.
1688   bool CheckIncRHS(Expr *RHS);
1689   /// \brief Helper to set loop counter variable and its initializer.
1690   bool SetVarAndLB(VarDecl *NewVar, DeclRefExpr *NewVarRefExpr, Expr *NewLB);
1691   /// \brief Helper to set upper bound.
1692   bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, const SourceRange &SR,
1693              const SourceLocation &SL);
1694   /// \brief Helper to set loop increment.
1695   bool SetStep(Expr *NewStep, bool Subtract);
1696 };
1697 
1698 bool OpenMPIterationSpaceChecker::Dependent() const {
1699   if (!Var) {
1700     assert(!LB && !UB && !Step);
1701     return false;
1702   }
1703   return Var->getType()->isDependentType() || (LB && LB->isValueDependent()) ||
1704          (UB && UB->isValueDependent()) || (Step && Step->isValueDependent());
1705 }
1706 
1707 bool OpenMPIterationSpaceChecker::SetVarAndLB(VarDecl *NewVar,
1708                                               DeclRefExpr *NewVarRefExpr,
1709                                               Expr *NewLB) {
1710   // State consistency checking to ensure correct usage.
1711   assert(Var == nullptr && LB == nullptr && VarRef == nullptr &&
1712          UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
1713   if (!NewVar || !NewLB)
1714     return true;
1715   Var = NewVar;
1716   VarRef = NewVarRefExpr;
1717   LB = NewLB;
1718   return false;
1719 }
1720 
1721 bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp,
1722                                         const SourceRange &SR,
1723                                         const SourceLocation &SL) {
1724   // State consistency checking to ensure correct usage.
1725   assert(Var != nullptr && LB != nullptr && UB == nullptr && Step == nullptr &&
1726          !TestIsLessOp && !TestIsStrictOp);
1727   if (!NewUB)
1728     return true;
1729   UB = NewUB;
1730   TestIsLessOp = LessOp;
1731   TestIsStrictOp = StrictOp;
1732   ConditionSrcRange = SR;
1733   ConditionLoc = SL;
1734   return false;
1735 }
1736 
1737 bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) {
1738   // State consistency checking to ensure correct usage.
1739   assert(Var != nullptr && LB != nullptr && Step == nullptr);
1740   if (!NewStep)
1741     return true;
1742   if (!NewStep->isValueDependent()) {
1743     // Check that the step is integer expression.
1744     SourceLocation StepLoc = NewStep->getLocStart();
1745     ExprResult Val =
1746         SemaRef.PerformOpenMPImplicitIntegerConversion(StepLoc, NewStep);
1747     if (Val.isInvalid())
1748       return true;
1749     NewStep = Val.get();
1750 
1751     // OpenMP [2.6, Canonical Loop Form, Restrictions]
1752     //  If test-expr is of form var relational-op b and relational-op is < or
1753     //  <= then incr-expr must cause var to increase on each iteration of the
1754     //  loop. If test-expr is of form var relational-op b and relational-op is
1755     //  > or >= then incr-expr must cause var to decrease on each iteration of
1756     //  the loop.
1757     //  If test-expr is of form b relational-op var and relational-op is < or
1758     //  <= then incr-expr must cause var to decrease on each iteration of the
1759     //  loop. If test-expr is of form b relational-op var and relational-op is
1760     //  > or >= then incr-expr must cause var to increase on each iteration of
1761     //  the loop.
1762     llvm::APSInt Result;
1763     bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
1764     bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
1765     bool IsConstNeg =
1766         IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
1767     bool IsConstZero = IsConstant && !Result.getBoolValue();
1768     if (UB && (IsConstZero ||
1769                (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
1770                              : (!IsConstNeg || (IsUnsigned && !Subtract))))) {
1771       SemaRef.Diag(NewStep->getExprLoc(),
1772                    diag::err_omp_loop_incr_not_compatible)
1773           << Var << TestIsLessOp << NewStep->getSourceRange();
1774       SemaRef.Diag(ConditionLoc,
1775                    diag::note_omp_loop_cond_requres_compatible_incr)
1776           << TestIsLessOp << ConditionSrcRange;
1777       return true;
1778     }
1779   }
1780 
1781   Step = NewStep;
1782   SubtractStep = Subtract;
1783   return false;
1784 }
1785 
1786 bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S) {
1787   // Check init-expr for canonical loop form and save loop counter
1788   // variable - #Var and its initialization value - #LB.
1789   // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
1790   //   var = lb
1791   //   integer-type var = lb
1792   //   random-access-iterator-type var = lb
1793   //   pointer-type var = lb
1794   //
1795   if (!S) {
1796     SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
1797     return true;
1798   }
1799   if (Expr *E = dyn_cast<Expr>(S))
1800     S = E->IgnoreParens();
1801   if (auto BO = dyn_cast<BinaryOperator>(S)) {
1802     if (BO->getOpcode() == BO_Assign)
1803       if (auto DRE = dyn_cast<DeclRefExpr>(BO->getLHS()->IgnoreParens()))
1804         return SetVarAndLB(dyn_cast<VarDecl>(DRE->getDecl()), DRE,
1805                            BO->getLHS());
1806   } else if (auto DS = dyn_cast<DeclStmt>(S)) {
1807     if (DS->isSingleDecl()) {
1808       if (auto Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
1809         if (Var->hasInit()) {
1810           // Accept non-canonical init form here but emit ext. warning.
1811           if (Var->getInitStyle() != VarDecl::CInit)
1812             SemaRef.Diag(S->getLocStart(),
1813                          diag::ext_omp_loop_not_canonical_init)
1814                 << S->getSourceRange();
1815           return SetVarAndLB(Var, nullptr, Var->getInit());
1816         }
1817       }
1818     }
1819   } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S))
1820     if (CE->getOperator() == OO_Equal)
1821       if (auto DRE = dyn_cast<DeclRefExpr>(CE->getArg(0)))
1822         return SetVarAndLB(dyn_cast<VarDecl>(DRE->getDecl()), DRE,
1823                            CE->getArg(1));
1824 
1825   SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init)
1826       << S->getSourceRange();
1827   return true;
1828 }
1829 
1830 /// \brief Ignore parenthesizes, implicit casts, copy constructor and return the
1831 /// variable (which may be the loop variable) if possible.
1832 static const VarDecl *GetInitVarDecl(const Expr *E) {
1833   if (!E)
1834     return nullptr;
1835   E = E->IgnoreParenImpCasts();
1836   if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
1837     if (const CXXConstructorDecl *Ctor = CE->getConstructor())
1838       if (Ctor->isCopyConstructor() && CE->getNumArgs() == 1 &&
1839           CE->getArg(0) != nullptr)
1840         E = CE->getArg(0)->IgnoreParenImpCasts();
1841   auto DRE = dyn_cast_or_null<DeclRefExpr>(E);
1842   if (!DRE)
1843     return nullptr;
1844   return dyn_cast<VarDecl>(DRE->getDecl());
1845 }
1846 
1847 bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) {
1848   // Check test-expr for canonical form, save upper-bound UB, flags for
1849   // less/greater and for strict/non-strict comparison.
1850   // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
1851   //   var relational-op b
1852   //   b relational-op var
1853   //
1854   if (!S) {
1855     SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << Var;
1856     return true;
1857   }
1858   S = S->IgnoreParenImpCasts();
1859   SourceLocation CondLoc = S->getLocStart();
1860   if (auto BO = dyn_cast<BinaryOperator>(S)) {
1861     if (BO->isRelationalOp()) {
1862       if (GetInitVarDecl(BO->getLHS()) == Var)
1863         return SetUB(BO->getRHS(),
1864                      (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
1865                      (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
1866                      BO->getSourceRange(), BO->getOperatorLoc());
1867       if (GetInitVarDecl(BO->getRHS()) == Var)
1868         return SetUB(BO->getLHS(),
1869                      (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
1870                      (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
1871                      BO->getSourceRange(), BO->getOperatorLoc());
1872     }
1873   } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S)) {
1874     if (CE->getNumArgs() == 2) {
1875       auto Op = CE->getOperator();
1876       switch (Op) {
1877       case OO_Greater:
1878       case OO_GreaterEqual:
1879       case OO_Less:
1880       case OO_LessEqual:
1881         if (GetInitVarDecl(CE->getArg(0)) == Var)
1882           return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
1883                        Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
1884                        CE->getOperatorLoc());
1885         if (GetInitVarDecl(CE->getArg(1)) == Var)
1886           return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
1887                        Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
1888                        CE->getOperatorLoc());
1889         break;
1890       default:
1891         break;
1892       }
1893     }
1894   }
1895   SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
1896       << S->getSourceRange() << Var;
1897   return true;
1898 }
1899 
1900 bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) {
1901   // RHS of canonical loop form increment can be:
1902   //   var + incr
1903   //   incr + var
1904   //   var - incr
1905   //
1906   RHS = RHS->IgnoreParenImpCasts();
1907   if (auto BO = dyn_cast<BinaryOperator>(RHS)) {
1908     if (BO->isAdditiveOp()) {
1909       bool IsAdd = BO->getOpcode() == BO_Add;
1910       if (GetInitVarDecl(BO->getLHS()) == Var)
1911         return SetStep(BO->getRHS(), !IsAdd);
1912       if (IsAdd && GetInitVarDecl(BO->getRHS()) == Var)
1913         return SetStep(BO->getLHS(), false);
1914     }
1915   } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
1916     bool IsAdd = CE->getOperator() == OO_Plus;
1917     if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
1918       if (GetInitVarDecl(CE->getArg(0)) == Var)
1919         return SetStep(CE->getArg(1), !IsAdd);
1920       if (IsAdd && GetInitVarDecl(CE->getArg(1)) == Var)
1921         return SetStep(CE->getArg(0), false);
1922     }
1923   }
1924   SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr)
1925       << RHS->getSourceRange() << Var;
1926   return true;
1927 }
1928 
1929 bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) {
1930   // Check incr-expr for canonical loop form and return true if it
1931   // does not conform.
1932   // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
1933   //   ++var
1934   //   var++
1935   //   --var
1936   //   var--
1937   //   var += incr
1938   //   var -= incr
1939   //   var = var + incr
1940   //   var = incr + var
1941   //   var = var - incr
1942   //
1943   if (!S) {
1944     SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << Var;
1945     return true;
1946   }
1947   S = S->IgnoreParens();
1948   if (auto UO = dyn_cast<UnaryOperator>(S)) {
1949     if (UO->isIncrementDecrementOp() && GetInitVarDecl(UO->getSubExpr()) == Var)
1950       return SetStep(
1951           SemaRef.ActOnIntegerConstant(UO->getLocStart(),
1952                                        (UO->isDecrementOp() ? -1 : 1)).get(),
1953           false);
1954   } else if (auto BO = dyn_cast<BinaryOperator>(S)) {
1955     switch (BO->getOpcode()) {
1956     case BO_AddAssign:
1957     case BO_SubAssign:
1958       if (GetInitVarDecl(BO->getLHS()) == Var)
1959         return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
1960       break;
1961     case BO_Assign:
1962       if (GetInitVarDecl(BO->getLHS()) == Var)
1963         return CheckIncRHS(BO->getRHS());
1964       break;
1965     default:
1966       break;
1967     }
1968   } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S)) {
1969     switch (CE->getOperator()) {
1970     case OO_PlusPlus:
1971     case OO_MinusMinus:
1972       if (GetInitVarDecl(CE->getArg(0)) == Var)
1973         return SetStep(
1974             SemaRef.ActOnIntegerConstant(
1975                         CE->getLocStart(),
1976                         ((CE->getOperator() == OO_MinusMinus) ? -1 : 1)).get(),
1977             false);
1978       break;
1979     case OO_PlusEqual:
1980     case OO_MinusEqual:
1981       if (GetInitVarDecl(CE->getArg(0)) == Var)
1982         return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
1983       break;
1984     case OO_Equal:
1985       if (GetInitVarDecl(CE->getArg(0)) == Var)
1986         return CheckIncRHS(CE->getArg(1));
1987       break;
1988     default:
1989       break;
1990     }
1991   }
1992   SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr)
1993       << S->getSourceRange() << Var;
1994   return true;
1995 }
1996 } // namespace
1997 
1998 /// \brief Called on a for stmt to check and extract its iteration space
1999 /// for further processing (such as collapsing).
2000 static bool CheckOpenMPIterationSpace(
2001     OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
2002     unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
2003     Expr *NestedLoopCountExpr,
2004     llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
2005   // OpenMP [2.6, Canonical Loop Form]
2006   //   for (init-expr; test-expr; incr-expr) structured-block
2007   auto For = dyn_cast_or_null<ForStmt>(S);
2008   if (!For) {
2009     SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for)
2010         << (NestedLoopCountExpr != nullptr) << getOpenMPDirectiveName(DKind)
2011         << NestedLoopCount << (CurrentNestedLoopCount > 0)
2012         << CurrentNestedLoopCount;
2013     if (NestedLoopCount > 1)
2014       SemaRef.Diag(NestedLoopCountExpr->getExprLoc(),
2015                    diag::note_omp_collapse_expr)
2016           << NestedLoopCountExpr->getSourceRange();
2017     return true;
2018   }
2019   assert(For->getBody());
2020 
2021   OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
2022 
2023   // Check init.
2024   auto Init = For->getInit();
2025   if (ISC.CheckInit(Init)) {
2026     return true;
2027   }
2028 
2029   bool HasErrors = false;
2030 
2031   // Check loop variable's type.
2032   auto Var = ISC.GetLoopVar();
2033 
2034   // OpenMP [2.6, Canonical Loop Form]
2035   // Var is one of the following:
2036   //   A variable of signed or unsigned integer type.
2037   //   For C++, a variable of a random access iterator type.
2038   //   For C, a variable of a pointer type.
2039   auto VarType = Var->getType();
2040   if (!VarType->isDependentType() && !VarType->isIntegerType() &&
2041       !VarType->isPointerType() &&
2042       !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
2043     SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type)
2044         << SemaRef.getLangOpts().CPlusPlus;
2045     HasErrors = true;
2046   }
2047 
2048   // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in a
2049   // Construct
2050   // The loop iteration variable(s) in the associated for-loop(s) of a for or
2051   // parallel for construct is (are) private.
2052   // The loop iteration variable in the associated for-loop of a simd construct
2053   // with just one associated for-loop is linear with a constant-linear-step
2054   // that is the increment of the associated for-loop.
2055   // Exclude loop var from the list of variables with implicitly defined data
2056   // sharing attributes.
2057   while (VarsWithImplicitDSA.count(Var) > 0)
2058     VarsWithImplicitDSA.erase(Var);
2059 
2060   // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced in
2061   // a Construct, C/C++].
2062   // The loop iteration variable in the associated for-loop of a simd construct
2063   // with just one associated for-loop may be listed in a linear clause with a
2064   // constant-linear-step that is the increment of the associated for-loop.
2065   // The loop iteration variable(s) in the associated for-loop(s) of a for or
2066   // parallel for construct may be listed in a private or lastprivate clause.
2067   DSAStackTy::DSAVarData DVar = DSA.getTopDSA(Var, false);
2068   auto LoopVarRefExpr = ISC.GetLoopVarRefExpr();
2069   // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
2070   // declared in the loop and it is predetermined as a private.
2071   auto PredeterminedCKind =
2072       isOpenMPSimdDirective(DKind)
2073           ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
2074           : OMPC_private;
2075   if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
2076         DVar.CKind != PredeterminedCKind) ||
2077        (isOpenMPWorksharingDirective(DKind) && DVar.CKind != OMPC_unknown &&
2078         DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
2079       (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
2080     SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa)
2081         << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
2082         << getOpenMPClauseName(PredeterminedCKind);
2083     ReportOriginalDSA(SemaRef, &DSA, Var, DVar, true);
2084     HasErrors = true;
2085   } else if (LoopVarRefExpr != nullptr) {
2086     // Make the loop iteration variable private (for worksharing constructs),
2087     // linear (for simd directives with the only one associated loop) or
2088     // lastprivate (for simd directives with several collapsed loops).
2089     DSA.addDSA(Var, LoopVarRefExpr, PredeterminedCKind);
2090   }
2091 
2092   assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
2093 
2094   // Check test-expr.
2095   HasErrors |= ISC.CheckCond(For->getCond());
2096 
2097   // Check incr-expr.
2098   HasErrors |= ISC.CheckInc(For->getInc());
2099 
2100   if (ISC.Dependent())
2101     return HasErrors;
2102 
2103   // FIXME: Build loop's iteration space representation.
2104   return HasErrors;
2105 }
2106 
2107 /// \brief A helper routine to skip no-op (attributed, compound) stmts get the
2108 /// next nested for loop. If \a IgnoreCaptured is true, it skips captured stmt
2109 /// to get the first for loop.
2110 static Stmt *IgnoreContainerStmts(Stmt *S, bool IgnoreCaptured) {
2111   if (IgnoreCaptured)
2112     if (auto CapS = dyn_cast_or_null<CapturedStmt>(S))
2113       S = CapS->getCapturedStmt();
2114   // OpenMP [2.8.1, simd construct, Restrictions]
2115   // All loops associated with the construct must be perfectly nested; that is,
2116   // there must be no intervening code nor any OpenMP directive between any two
2117   // loops.
2118   while (true) {
2119     if (auto AS = dyn_cast_or_null<AttributedStmt>(S))
2120       S = AS->getSubStmt();
2121     else if (auto CS = dyn_cast_or_null<CompoundStmt>(S)) {
2122       if (CS->size() != 1)
2123         break;
2124       S = CS->body_back();
2125     } else
2126       break;
2127   }
2128   return S;
2129 }
2130 
2131 /// \brief Called on a for stmt to check itself and nested loops (if any).
2132 /// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
2133 /// number of collapsed loops otherwise.
2134 static unsigned
2135 CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *NestedLoopCountExpr,
2136                 Stmt *AStmt, Sema &SemaRef, DSAStackTy &DSA,
2137                 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
2138   unsigned NestedLoopCount = 1;
2139   if (NestedLoopCountExpr) {
2140     // Found 'collapse' clause - calculate collapse number.
2141     llvm::APSInt Result;
2142     if (NestedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
2143       NestedLoopCount = Result.getLimitedValue();
2144   }
2145   // This is helper routine for loop directives (e.g., 'for', 'simd',
2146   // 'for simd', etc.).
2147   Stmt *CurStmt = IgnoreContainerStmts(AStmt, true);
2148   for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
2149     if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt,
2150                                   NestedLoopCount, NestedLoopCountExpr,
2151                                   VarsWithImplicitDSA))
2152       return 0;
2153     // Move on to the next nested for loop, or to the loop body.
2154     CurStmt = IgnoreContainerStmts(cast<ForStmt>(CurStmt)->getBody(), false);
2155   }
2156 
2157   // FIXME: Build resulting iteration space for IR generation (collapsing
2158   // iteration spaces when loop count > 1 ('collapse' clause)).
2159   return NestedLoopCount;
2160 }
2161 
2162 static Expr *GetCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
2163   auto CollapseFilter = [](const OMPClause *C) -> bool {
2164     return C->getClauseKind() == OMPC_collapse;
2165   };
2166   OMPExecutableDirective::filtered_clause_iterator<decltype(CollapseFilter)> I(
2167       Clauses, CollapseFilter);
2168   if (I)
2169     return cast<OMPCollapseClause>(*I)->getNumForLoops();
2170   return nullptr;
2171 }
2172 
2173 StmtResult Sema::ActOnOpenMPSimdDirective(
2174     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
2175     SourceLocation EndLoc,
2176     llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
2177   // In presence of clause 'collapse', it will define the nested loops number.
2178   unsigned NestedLoopCount =
2179       CheckOpenMPLoop(OMPD_simd, GetCollapseNumberExpr(Clauses), AStmt, *this,
2180                       *DSAStack, VarsWithImplicitDSA);
2181   if (NestedLoopCount == 0)
2182     return StmtError();
2183 
2184   getCurFunction()->setHasBranchProtectedScope();
2185   return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
2186                                   Clauses, AStmt);
2187 }
2188 
2189 StmtResult Sema::ActOnOpenMPForDirective(
2190     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
2191     SourceLocation EndLoc,
2192     llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
2193   // In presence of clause 'collapse', it will define the nested loops number.
2194   unsigned NestedLoopCount =
2195       CheckOpenMPLoop(OMPD_for, GetCollapseNumberExpr(Clauses), AStmt, *this,
2196                       *DSAStack, VarsWithImplicitDSA);
2197   if (NestedLoopCount == 0)
2198     return StmtError();
2199 
2200   getCurFunction()->setHasBranchProtectedScope();
2201   return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
2202                                  Clauses, AStmt);
2203 }
2204 
2205 StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
2206                                               Stmt *AStmt,
2207                                               SourceLocation StartLoc,
2208                                               SourceLocation EndLoc) {
2209   assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
2210   auto BaseStmt = AStmt;
2211   while (CapturedStmt *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
2212     BaseStmt = CS->getCapturedStmt();
2213   if (auto C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
2214     auto S = C->children();
2215     if (!S)
2216       return StmtError();
2217     // All associated statements must be '#pragma omp section' except for
2218     // the first one.
2219     for (++S; S; ++S) {
2220       auto SectionStmt = *S;
2221       if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
2222         if (SectionStmt)
2223           Diag(SectionStmt->getLocStart(),
2224                diag::err_omp_sections_substmt_not_section);
2225         return StmtError();
2226       }
2227     }
2228   } else {
2229     Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt);
2230     return StmtError();
2231   }
2232 
2233   getCurFunction()->setHasBranchProtectedScope();
2234 
2235   return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses,
2236                                       AStmt);
2237 }
2238 
2239 StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
2240                                              SourceLocation StartLoc,
2241                                              SourceLocation EndLoc) {
2242   assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
2243 
2244   getCurFunction()->setHasBranchProtectedScope();
2245 
2246   return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt);
2247 }
2248 
2249 StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
2250                                             Stmt *AStmt,
2251                                             SourceLocation StartLoc,
2252                                             SourceLocation EndLoc) {
2253   assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
2254 
2255   getCurFunction()->setHasBranchProtectedScope();
2256 
2257   return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
2258 }
2259 
2260 StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
2261                                             SourceLocation StartLoc,
2262                                             SourceLocation EndLoc) {
2263   assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
2264 
2265   getCurFunction()->setHasBranchProtectedScope();
2266 
2267   return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
2268 }
2269 
2270 StmtResult
2271 Sema::ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName,
2272                                    Stmt *AStmt, SourceLocation StartLoc,
2273                                    SourceLocation EndLoc) {
2274   assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
2275 
2276   getCurFunction()->setHasBranchProtectedScope();
2277 
2278   return OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
2279                                       AStmt);
2280 }
2281 
2282 StmtResult Sema::ActOnOpenMPParallelForDirective(
2283     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
2284     SourceLocation EndLoc,
2285     llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
2286   assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
2287   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
2288   // 1.2.2 OpenMP Language Terminology
2289   // Structured block - An executable statement with a single entry at the
2290   // top and a single exit at the bottom.
2291   // The point of exit cannot be a branch out of the structured block.
2292   // longjmp() and throw() must not violate the entry/exit criteria.
2293   CS->getCapturedDecl()->setNothrow();
2294 
2295   // In presence of clause 'collapse', it will define the nested loops number.
2296   unsigned NestedLoopCount =
2297       CheckOpenMPLoop(OMPD_parallel_for, GetCollapseNumberExpr(Clauses), AStmt,
2298                       *this, *DSAStack, VarsWithImplicitDSA);
2299   if (NestedLoopCount == 0)
2300     return StmtError();
2301 
2302   getCurFunction()->setHasBranchProtectedScope();
2303   return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
2304                                          NestedLoopCount, Clauses, AStmt);
2305 }
2306 
2307 StmtResult
2308 Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
2309                                            Stmt *AStmt, SourceLocation StartLoc,
2310                                            SourceLocation EndLoc) {
2311   assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
2312   auto BaseStmt = AStmt;
2313   while (CapturedStmt *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
2314     BaseStmt = CS->getCapturedStmt();
2315   if (auto C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
2316     auto S = C->children();
2317     if (!S)
2318       return StmtError();
2319     // All associated statements must be '#pragma omp section' except for
2320     // the first one.
2321     for (++S; S; ++S) {
2322       auto SectionStmt = *S;
2323       if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
2324         if (SectionStmt)
2325           Diag(SectionStmt->getLocStart(),
2326                diag::err_omp_parallel_sections_substmt_not_section);
2327         return StmtError();
2328       }
2329     }
2330   } else {
2331     Diag(AStmt->getLocStart(),
2332          diag::err_omp_parallel_sections_not_compound_stmt);
2333     return StmtError();
2334   }
2335 
2336   getCurFunction()->setHasBranchProtectedScope();
2337 
2338   return OMPParallelSectionsDirective::Create(Context, StartLoc, EndLoc,
2339                                               Clauses, AStmt);
2340 }
2341 
2342 StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
2343                                           Stmt *AStmt, SourceLocation StartLoc,
2344                                           SourceLocation EndLoc) {
2345   assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
2346   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
2347   // 1.2.2 OpenMP Language Terminology
2348   // Structured block - An executable statement with a single entry at the
2349   // top and a single exit at the bottom.
2350   // The point of exit cannot be a branch out of the structured block.
2351   // longjmp() and throw() must not violate the entry/exit criteria.
2352   CS->getCapturedDecl()->setNothrow();
2353 
2354   getCurFunction()->setHasBranchProtectedScope();
2355 
2356   return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
2357 }
2358 
2359 StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
2360                                                SourceLocation EndLoc) {
2361   return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
2362 }
2363 
2364 StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
2365                                              SourceLocation EndLoc) {
2366   return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
2367 }
2368 
2369 StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
2370                                               SourceLocation EndLoc) {
2371   return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
2372 }
2373 
2374 StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
2375                                            SourceLocation StartLoc,
2376                                            SourceLocation EndLoc) {
2377   assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
2378   return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
2379 }
2380 
2381 StmtResult Sema::ActOnOpenMPOrderedDirective(Stmt *AStmt,
2382                                              SourceLocation StartLoc,
2383                                              SourceLocation EndLoc) {
2384   assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
2385 
2386   getCurFunction()->setHasBranchProtectedScope();
2387 
2388   return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, AStmt);
2389 }
2390 
2391 StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
2392                                             Stmt *AStmt,
2393                                             SourceLocation StartLoc,
2394                                             SourceLocation EndLoc) {
2395   assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
2396   auto CS = cast<CapturedStmt>(AStmt);
2397   // 1.2.2 OpenMP Language Terminology
2398   // Structured block - An executable statement with a single entry at the
2399   // top and a single exit at the bottom.
2400   // The point of exit cannot be a branch out of the structured block.
2401   // longjmp() and throw() must not violate the entry/exit criteria.
2402   // TODO further analysis of associated statements and clauses.
2403   OpenMPClauseKind AtomicKind = OMPC_unknown;
2404   SourceLocation AtomicKindLoc;
2405   for (auto *C : Clauses) {
2406     if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
2407         C->getClauseKind() == OMPC_update ||
2408         C->getClauseKind() == OMPC_capture) {
2409       if (AtomicKind != OMPC_unknown) {
2410         Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses)
2411             << SourceRange(C->getLocStart(), C->getLocEnd());
2412         Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
2413             << getOpenMPClauseName(AtomicKind);
2414       } else {
2415         AtomicKind = C->getClauseKind();
2416         AtomicKindLoc = C->getLocStart();
2417       }
2418     }
2419   }
2420   auto Body = CS->getCapturedStmt();
2421   if (AtomicKind == OMPC_read) {
2422     if (!isa<Expr>(Body)) {
2423       Diag(Body->getLocStart(),
2424            diag::err_omp_atomic_read_not_expression_statement);
2425       return StmtError();
2426     }
2427   } else if (AtomicKind == OMPC_write) {
2428     if (!isa<Expr>(Body)) {
2429       Diag(Body->getLocStart(),
2430            diag::err_omp_atomic_write_not_expression_statement);
2431       return StmtError();
2432     }
2433   } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
2434     if (!isa<Expr>(Body)) {
2435       Diag(Body->getLocStart(),
2436            diag::err_omp_atomic_update_not_expression_statement)
2437           << (AtomicKind == OMPC_update);
2438       return StmtError();
2439     }
2440   } else if (AtomicKind == OMPC_capture) {
2441     if (isa<Expr>(Body) && !isa<BinaryOperator>(Body)) {
2442       Diag(Body->getLocStart(),
2443            diag::err_omp_atomic_capture_not_expression_statement);
2444       return StmtError();
2445     } else if (!isa<Expr>(Body) && !isa<CompoundStmt>(Body)) {
2446       Diag(Body->getLocStart(),
2447            diag::err_omp_atomic_capture_not_compound_statement);
2448       return StmtError();
2449     }
2450   }
2451 
2452   getCurFunction()->setHasBranchProtectedScope();
2453 
2454   return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
2455 }
2456 
2457 OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
2458                                              SourceLocation StartLoc,
2459                                              SourceLocation LParenLoc,
2460                                              SourceLocation EndLoc) {
2461   OMPClause *Res = nullptr;
2462   switch (Kind) {
2463   case OMPC_if:
2464     Res = ActOnOpenMPIfClause(Expr, StartLoc, LParenLoc, EndLoc);
2465     break;
2466   case OMPC_final:
2467     Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
2468     break;
2469   case OMPC_num_threads:
2470     Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
2471     break;
2472   case OMPC_safelen:
2473     Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
2474     break;
2475   case OMPC_collapse:
2476     Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
2477     break;
2478   case OMPC_default:
2479   case OMPC_proc_bind:
2480   case OMPC_schedule:
2481   case OMPC_private:
2482   case OMPC_firstprivate:
2483   case OMPC_lastprivate:
2484   case OMPC_shared:
2485   case OMPC_reduction:
2486   case OMPC_linear:
2487   case OMPC_aligned:
2488   case OMPC_copyin:
2489   case OMPC_copyprivate:
2490   case OMPC_ordered:
2491   case OMPC_nowait:
2492   case OMPC_untied:
2493   case OMPC_mergeable:
2494   case OMPC_threadprivate:
2495   case OMPC_flush:
2496   case OMPC_read:
2497   case OMPC_write:
2498   case OMPC_update:
2499   case OMPC_capture:
2500   case OMPC_seq_cst:
2501   case OMPC_unknown:
2502     llvm_unreachable("Clause is not allowed.");
2503   }
2504   return Res;
2505 }
2506 
2507 OMPClause *Sema::ActOnOpenMPIfClause(Expr *Condition, SourceLocation StartLoc,
2508                                      SourceLocation LParenLoc,
2509                                      SourceLocation EndLoc) {
2510   Expr *ValExpr = Condition;
2511   if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
2512       !Condition->isInstantiationDependent() &&
2513       !Condition->containsUnexpandedParameterPack()) {
2514     ExprResult Val = ActOnBooleanCondition(DSAStack->getCurScope(),
2515                                            Condition->getExprLoc(), Condition);
2516     if (Val.isInvalid())
2517       return nullptr;
2518 
2519     ValExpr = Val.get();
2520   }
2521 
2522   return new (Context) OMPIfClause(ValExpr, StartLoc, LParenLoc, EndLoc);
2523 }
2524 
2525 OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
2526                                         SourceLocation StartLoc,
2527                                         SourceLocation LParenLoc,
2528                                         SourceLocation EndLoc) {
2529   Expr *ValExpr = Condition;
2530   if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
2531       !Condition->isInstantiationDependent() &&
2532       !Condition->containsUnexpandedParameterPack()) {
2533     ExprResult Val = ActOnBooleanCondition(DSAStack->getCurScope(),
2534                                            Condition->getExprLoc(), Condition);
2535     if (Val.isInvalid())
2536       return nullptr;
2537 
2538     ValExpr = Val.get();
2539   }
2540 
2541   return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
2542 }
2543 ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
2544                                                         Expr *Op) {
2545   if (!Op)
2546     return ExprError();
2547 
2548   class IntConvertDiagnoser : public ICEConvertDiagnoser {
2549   public:
2550     IntConvertDiagnoser()
2551         : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
2552     SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
2553                                          QualType T) override {
2554       return S.Diag(Loc, diag::err_omp_not_integral) << T;
2555     }
2556     SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
2557                                              QualType T) override {
2558       return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
2559     }
2560     SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
2561                                                QualType T,
2562                                                QualType ConvTy) override {
2563       return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
2564     }
2565     SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
2566                                            QualType ConvTy) override {
2567       return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
2568              << ConvTy->isEnumeralType() << ConvTy;
2569     }
2570     SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
2571                                             QualType T) override {
2572       return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
2573     }
2574     SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
2575                                         QualType ConvTy) override {
2576       return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
2577              << ConvTy->isEnumeralType() << ConvTy;
2578     }
2579     SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
2580                                              QualType) override {
2581       llvm_unreachable("conversion functions are permitted");
2582     }
2583   } ConvertDiagnoser;
2584   return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
2585 }
2586 
2587 OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
2588                                              SourceLocation StartLoc,
2589                                              SourceLocation LParenLoc,
2590                                              SourceLocation EndLoc) {
2591   Expr *ValExpr = NumThreads;
2592   if (!NumThreads->isValueDependent() && !NumThreads->isTypeDependent() &&
2593       !NumThreads->isInstantiationDependent() &&
2594       !NumThreads->containsUnexpandedParameterPack()) {
2595     SourceLocation NumThreadsLoc = NumThreads->getLocStart();
2596     ExprResult Val =
2597         PerformOpenMPImplicitIntegerConversion(NumThreadsLoc, NumThreads);
2598     if (Val.isInvalid())
2599       return nullptr;
2600 
2601     ValExpr = Val.get();
2602 
2603     // OpenMP [2.5, Restrictions]
2604     //  The num_threads expression must evaluate to a positive integer value.
2605     llvm::APSInt Result;
2606     if (ValExpr->isIntegerConstantExpr(Result, Context) && Result.isSigned() &&
2607         !Result.isStrictlyPositive()) {
2608       Diag(NumThreadsLoc, diag::err_omp_negative_expression_in_clause)
2609           << "num_threads" << NumThreads->getSourceRange();
2610       return nullptr;
2611     }
2612   }
2613 
2614   return new (Context)
2615       OMPNumThreadsClause(ValExpr, StartLoc, LParenLoc, EndLoc);
2616 }
2617 
2618 ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
2619                                                        OpenMPClauseKind CKind) {
2620   if (!E)
2621     return ExprError();
2622   if (E->isValueDependent() || E->isTypeDependent() ||
2623       E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
2624     return E;
2625   llvm::APSInt Result;
2626   ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
2627   if (ICE.isInvalid())
2628     return ExprError();
2629   if (!Result.isStrictlyPositive()) {
2630     Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
2631         << getOpenMPClauseName(CKind) << E->getSourceRange();
2632     return ExprError();
2633   }
2634   return ICE;
2635 }
2636 
2637 OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
2638                                           SourceLocation LParenLoc,
2639                                           SourceLocation EndLoc) {
2640   // OpenMP [2.8.1, simd construct, Description]
2641   // The parameter of the safelen clause must be a constant
2642   // positive integer expression.
2643   ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
2644   if (Safelen.isInvalid())
2645     return nullptr;
2646   return new (Context)
2647       OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
2648 }
2649 
2650 OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
2651                                            SourceLocation StartLoc,
2652                                            SourceLocation LParenLoc,
2653                                            SourceLocation EndLoc) {
2654   // OpenMP [2.7.1, loop construct, Description]
2655   // OpenMP [2.8.1, simd construct, Description]
2656   // OpenMP [2.9.6, distribute construct, Description]
2657   // The parameter of the collapse clause must be a constant
2658   // positive integer expression.
2659   ExprResult NumForLoopsResult =
2660       VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
2661   if (NumForLoopsResult.isInvalid())
2662     return nullptr;
2663   return new (Context)
2664       OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
2665 }
2666 
2667 OMPClause *Sema::ActOnOpenMPSimpleClause(
2668     OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
2669     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
2670   OMPClause *Res = nullptr;
2671   switch (Kind) {
2672   case OMPC_default:
2673     Res =
2674         ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
2675                                  ArgumentLoc, StartLoc, LParenLoc, EndLoc);
2676     break;
2677   case OMPC_proc_bind:
2678     Res = ActOnOpenMPProcBindClause(
2679         static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
2680         LParenLoc, EndLoc);
2681     break;
2682   case OMPC_if:
2683   case OMPC_final:
2684   case OMPC_num_threads:
2685   case OMPC_safelen:
2686   case OMPC_collapse:
2687   case OMPC_schedule:
2688   case OMPC_private:
2689   case OMPC_firstprivate:
2690   case OMPC_lastprivate:
2691   case OMPC_shared:
2692   case OMPC_reduction:
2693   case OMPC_linear:
2694   case OMPC_aligned:
2695   case OMPC_copyin:
2696   case OMPC_copyprivate:
2697   case OMPC_ordered:
2698   case OMPC_nowait:
2699   case OMPC_untied:
2700   case OMPC_mergeable:
2701   case OMPC_threadprivate:
2702   case OMPC_flush:
2703   case OMPC_read:
2704   case OMPC_write:
2705   case OMPC_update:
2706   case OMPC_capture:
2707   case OMPC_seq_cst:
2708   case OMPC_unknown:
2709     llvm_unreachable("Clause is not allowed.");
2710   }
2711   return Res;
2712 }
2713 
2714 OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
2715                                           SourceLocation KindKwLoc,
2716                                           SourceLocation StartLoc,
2717                                           SourceLocation LParenLoc,
2718                                           SourceLocation EndLoc) {
2719   if (Kind == OMPC_DEFAULT_unknown) {
2720     std::string Values;
2721     static_assert(OMPC_DEFAULT_unknown > 0,
2722                   "OMPC_DEFAULT_unknown not greater than 0");
2723     std::string Sep(", ");
2724     for (unsigned i = 0; i < OMPC_DEFAULT_unknown; ++i) {
2725       Values += "'";
2726       Values += getOpenMPSimpleClauseTypeName(OMPC_default, i);
2727       Values += "'";
2728       switch (i) {
2729       case OMPC_DEFAULT_unknown - 2:
2730         Values += " or ";
2731         break;
2732       case OMPC_DEFAULT_unknown - 1:
2733         break;
2734       default:
2735         Values += Sep;
2736         break;
2737       }
2738     }
2739     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
2740         << Values << getOpenMPClauseName(OMPC_default);
2741     return nullptr;
2742   }
2743   switch (Kind) {
2744   case OMPC_DEFAULT_none:
2745     DSAStack->setDefaultDSANone(KindKwLoc);
2746     break;
2747   case OMPC_DEFAULT_shared:
2748     DSAStack->setDefaultDSAShared(KindKwLoc);
2749     break;
2750   case OMPC_DEFAULT_unknown:
2751     llvm_unreachable("Clause kind is not allowed.");
2752     break;
2753   }
2754   return new (Context)
2755       OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
2756 }
2757 
2758 OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
2759                                            SourceLocation KindKwLoc,
2760                                            SourceLocation StartLoc,
2761                                            SourceLocation LParenLoc,
2762                                            SourceLocation EndLoc) {
2763   if (Kind == OMPC_PROC_BIND_unknown) {
2764     std::string Values;
2765     std::string Sep(", ");
2766     for (unsigned i = 0; i < OMPC_PROC_BIND_unknown; ++i) {
2767       Values += "'";
2768       Values += getOpenMPSimpleClauseTypeName(OMPC_proc_bind, i);
2769       Values += "'";
2770       switch (i) {
2771       case OMPC_PROC_BIND_unknown - 2:
2772         Values += " or ";
2773         break;
2774       case OMPC_PROC_BIND_unknown - 1:
2775         break;
2776       default:
2777         Values += Sep;
2778         break;
2779       }
2780     }
2781     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
2782         << Values << getOpenMPClauseName(OMPC_proc_bind);
2783     return nullptr;
2784   }
2785   return new (Context)
2786       OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
2787 }
2788 
2789 OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
2790     OpenMPClauseKind Kind, unsigned Argument, Expr *Expr,
2791     SourceLocation StartLoc, SourceLocation LParenLoc,
2792     SourceLocation ArgumentLoc, SourceLocation CommaLoc,
2793     SourceLocation EndLoc) {
2794   OMPClause *Res = nullptr;
2795   switch (Kind) {
2796   case OMPC_schedule:
2797     Res = ActOnOpenMPScheduleClause(
2798         static_cast<OpenMPScheduleClauseKind>(Argument), Expr, StartLoc,
2799         LParenLoc, ArgumentLoc, CommaLoc, EndLoc);
2800     break;
2801   case OMPC_if:
2802   case OMPC_final:
2803   case OMPC_num_threads:
2804   case OMPC_safelen:
2805   case OMPC_collapse:
2806   case OMPC_default:
2807   case OMPC_proc_bind:
2808   case OMPC_private:
2809   case OMPC_firstprivate:
2810   case OMPC_lastprivate:
2811   case OMPC_shared:
2812   case OMPC_reduction:
2813   case OMPC_linear:
2814   case OMPC_aligned:
2815   case OMPC_copyin:
2816   case OMPC_copyprivate:
2817   case OMPC_ordered:
2818   case OMPC_nowait:
2819   case OMPC_untied:
2820   case OMPC_mergeable:
2821   case OMPC_threadprivate:
2822   case OMPC_flush:
2823   case OMPC_read:
2824   case OMPC_write:
2825   case OMPC_update:
2826   case OMPC_capture:
2827   case OMPC_seq_cst:
2828   case OMPC_unknown:
2829     llvm_unreachable("Clause is not allowed.");
2830   }
2831   return Res;
2832 }
2833 
2834 OMPClause *Sema::ActOnOpenMPScheduleClause(
2835     OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
2836     SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
2837     SourceLocation EndLoc) {
2838   if (Kind == OMPC_SCHEDULE_unknown) {
2839     std::string Values;
2840     std::string Sep(", ");
2841     for (unsigned i = 0; i < OMPC_SCHEDULE_unknown; ++i) {
2842       Values += "'";
2843       Values += getOpenMPSimpleClauseTypeName(OMPC_schedule, i);
2844       Values += "'";
2845       switch (i) {
2846       case OMPC_SCHEDULE_unknown - 2:
2847         Values += " or ";
2848         break;
2849       case OMPC_SCHEDULE_unknown - 1:
2850         break;
2851       default:
2852         Values += Sep;
2853         break;
2854       }
2855     }
2856     Diag(KindLoc, diag::err_omp_unexpected_clause_value)
2857         << Values << getOpenMPClauseName(OMPC_schedule);
2858     return nullptr;
2859   }
2860   Expr *ValExpr = ChunkSize;
2861   if (ChunkSize) {
2862     if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
2863         !ChunkSize->isInstantiationDependent() &&
2864         !ChunkSize->containsUnexpandedParameterPack()) {
2865       SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
2866       ExprResult Val =
2867           PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
2868       if (Val.isInvalid())
2869         return nullptr;
2870 
2871       ValExpr = Val.get();
2872 
2873       // OpenMP [2.7.1, Restrictions]
2874       //  chunk_size must be a loop invariant integer expression with a positive
2875       //  value.
2876       llvm::APSInt Result;
2877       if (ValExpr->isIntegerConstantExpr(Result, Context) &&
2878           Result.isSigned() && !Result.isStrictlyPositive()) {
2879         Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
2880             << "schedule" << ChunkSize->getSourceRange();
2881         return nullptr;
2882       }
2883     }
2884   }
2885 
2886   return new (Context) OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc,
2887                                          EndLoc, Kind, ValExpr);
2888 }
2889 
2890 OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
2891                                    SourceLocation StartLoc,
2892                                    SourceLocation EndLoc) {
2893   OMPClause *Res = nullptr;
2894   switch (Kind) {
2895   case OMPC_ordered:
2896     Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
2897     break;
2898   case OMPC_nowait:
2899     Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
2900     break;
2901   case OMPC_untied:
2902     Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
2903     break;
2904   case OMPC_mergeable:
2905     Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
2906     break;
2907   case OMPC_read:
2908     Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
2909     break;
2910   case OMPC_write:
2911     Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
2912     break;
2913   case OMPC_update:
2914     Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
2915     break;
2916   case OMPC_capture:
2917     Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
2918     break;
2919   case OMPC_seq_cst:
2920     Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
2921     break;
2922   case OMPC_if:
2923   case OMPC_final:
2924   case OMPC_num_threads:
2925   case OMPC_safelen:
2926   case OMPC_collapse:
2927   case OMPC_schedule:
2928   case OMPC_private:
2929   case OMPC_firstprivate:
2930   case OMPC_lastprivate:
2931   case OMPC_shared:
2932   case OMPC_reduction:
2933   case OMPC_linear:
2934   case OMPC_aligned:
2935   case OMPC_copyin:
2936   case OMPC_copyprivate:
2937   case OMPC_default:
2938   case OMPC_proc_bind:
2939   case OMPC_threadprivate:
2940   case OMPC_flush:
2941   case OMPC_unknown:
2942     llvm_unreachable("Clause is not allowed.");
2943   }
2944   return Res;
2945 }
2946 
2947 OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
2948                                           SourceLocation EndLoc) {
2949   DSAStack->setOrderedRegion();
2950   return new (Context) OMPOrderedClause(StartLoc, EndLoc);
2951 }
2952 
2953 OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
2954                                          SourceLocation EndLoc) {
2955   return new (Context) OMPNowaitClause(StartLoc, EndLoc);
2956 }
2957 
2958 OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
2959                                          SourceLocation EndLoc) {
2960   return new (Context) OMPUntiedClause(StartLoc, EndLoc);
2961 }
2962 
2963 OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
2964                                             SourceLocation EndLoc) {
2965   return new (Context) OMPMergeableClause(StartLoc, EndLoc);
2966 }
2967 
2968 OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
2969                                        SourceLocation EndLoc) {
2970   return new (Context) OMPReadClause(StartLoc, EndLoc);
2971 }
2972 
2973 OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
2974                                         SourceLocation EndLoc) {
2975   return new (Context) OMPWriteClause(StartLoc, EndLoc);
2976 }
2977 
2978 OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
2979                                          SourceLocation EndLoc) {
2980   return new (Context) OMPUpdateClause(StartLoc, EndLoc);
2981 }
2982 
2983 OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
2984                                           SourceLocation EndLoc) {
2985   return new (Context) OMPCaptureClause(StartLoc, EndLoc);
2986 }
2987 
2988 OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
2989                                          SourceLocation EndLoc) {
2990   return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
2991 }
2992 
2993 OMPClause *Sema::ActOnOpenMPVarListClause(
2994     OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
2995     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
2996     SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
2997     const DeclarationNameInfo &ReductionId) {
2998   OMPClause *Res = nullptr;
2999   switch (Kind) {
3000   case OMPC_private:
3001     Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
3002     break;
3003   case OMPC_firstprivate:
3004     Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
3005     break;
3006   case OMPC_lastprivate:
3007     Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
3008     break;
3009   case OMPC_shared:
3010     Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
3011     break;
3012   case OMPC_reduction:
3013     Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
3014                                      EndLoc, ReductionIdScopeSpec, ReductionId);
3015     break;
3016   case OMPC_linear:
3017     Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
3018                                   ColonLoc, EndLoc);
3019     break;
3020   case OMPC_aligned:
3021     Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
3022                                    ColonLoc, EndLoc);
3023     break;
3024   case OMPC_copyin:
3025     Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
3026     break;
3027   case OMPC_copyprivate:
3028     Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
3029     break;
3030   case OMPC_flush:
3031     Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
3032     break;
3033   case OMPC_if:
3034   case OMPC_final:
3035   case OMPC_num_threads:
3036   case OMPC_safelen:
3037   case OMPC_collapse:
3038   case OMPC_default:
3039   case OMPC_proc_bind:
3040   case OMPC_schedule:
3041   case OMPC_ordered:
3042   case OMPC_nowait:
3043   case OMPC_untied:
3044   case OMPC_mergeable:
3045   case OMPC_threadprivate:
3046   case OMPC_read:
3047   case OMPC_write:
3048   case OMPC_update:
3049   case OMPC_capture:
3050   case OMPC_seq_cst:
3051   case OMPC_unknown:
3052     llvm_unreachable("Clause is not allowed.");
3053   }
3054   return Res;
3055 }
3056 
3057 OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
3058                                           SourceLocation StartLoc,
3059                                           SourceLocation LParenLoc,
3060                                           SourceLocation EndLoc) {
3061   SmallVector<Expr *, 8> Vars;
3062   for (auto &RefExpr : VarList) {
3063     assert(RefExpr && "NULL expr in OpenMP private clause.");
3064     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
3065       // It will be analyzed later.
3066       Vars.push_back(RefExpr);
3067       continue;
3068     }
3069 
3070     SourceLocation ELoc = RefExpr->getExprLoc();
3071     // OpenMP [2.1, C/C++]
3072     //  A list item is a variable name.
3073     // OpenMP  [2.9.3.3, Restrictions, p.1]
3074     //  A variable that is part of another variable (as an array or
3075     //  structure element) cannot appear in a private clause.
3076     DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
3077     if (!DE || !isa<VarDecl>(DE->getDecl())) {
3078       Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
3079       continue;
3080     }
3081     Decl *D = DE->getDecl();
3082     VarDecl *VD = cast<VarDecl>(D);
3083 
3084     QualType Type = VD->getType();
3085     if (Type->isDependentType() || Type->isInstantiationDependentType()) {
3086       // It will be analyzed later.
3087       Vars.push_back(DE);
3088       continue;
3089     }
3090 
3091     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
3092     //  A variable that appears in a private clause must not have an incomplete
3093     //  type or a reference type.
3094     if (RequireCompleteType(ELoc, Type,
3095                             diag::err_omp_private_incomplete_type)) {
3096       continue;
3097     }
3098     if (Type->isReferenceType()) {
3099       Diag(ELoc, diag::err_omp_clause_ref_type_arg)
3100           << getOpenMPClauseName(OMPC_private) << Type;
3101       bool IsDecl =
3102           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
3103       Diag(VD->getLocation(),
3104            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
3105           << VD;
3106       continue;
3107     }
3108 
3109     // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
3110     //  A variable of class type (or array thereof) that appears in a private
3111     //  clause requires an accessible, unambiguous default constructor for the
3112     //  class type.
3113     while (Type.getNonReferenceType()->isArrayType()) {
3114       Type = cast<ArrayType>(Type.getNonReferenceType().getTypePtr())
3115                  ->getElementType();
3116     }
3117     CXXRecordDecl *RD = getLangOpts().CPlusPlus
3118                             ? Type.getNonReferenceType()->getAsCXXRecordDecl()
3119                             : nullptr;
3120     // FIXME This code must be replaced by actual constructing/destructing of
3121     // the private variable.
3122     if (RD) {
3123       CXXConstructorDecl *CD = LookupDefaultConstructor(RD);
3124       PartialDiagnostic PD =
3125           PartialDiagnostic(PartialDiagnostic::NullDiagnostic());
3126       if (!CD ||
3127           CheckConstructorAccess(ELoc, CD,
3128                                  InitializedEntity::InitializeTemporary(Type),
3129                                  CD->getAccess(), PD) == AR_inaccessible ||
3130           CD->isDeleted()) {
3131         Diag(ELoc, diag::err_omp_required_method)
3132             << getOpenMPClauseName(OMPC_private) << 0;
3133         bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
3134                       VarDecl::DeclarationOnly;
3135         Diag(VD->getLocation(),
3136              IsDecl ? diag::note_previous_decl : diag::note_defined_here)
3137             << VD;
3138         Diag(RD->getLocation(), diag::note_previous_decl) << RD;
3139         continue;
3140       }
3141       MarkFunctionReferenced(ELoc, CD);
3142       DiagnoseUseOfDecl(CD, ELoc);
3143 
3144       CXXDestructorDecl *DD = RD->getDestructor();
3145       if (DD) {
3146         if (CheckDestructorAccess(ELoc, DD, PD) == AR_inaccessible ||
3147             DD->isDeleted()) {
3148           Diag(ELoc, diag::err_omp_required_method)
3149               << getOpenMPClauseName(OMPC_private) << 4;
3150           bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
3151                         VarDecl::DeclarationOnly;
3152           Diag(VD->getLocation(),
3153                IsDecl ? diag::note_previous_decl : diag::note_defined_here)
3154               << VD;
3155           Diag(RD->getLocation(), diag::note_previous_decl) << RD;
3156           continue;
3157         }
3158         MarkFunctionReferenced(ELoc, DD);
3159         DiagnoseUseOfDecl(DD, ELoc);
3160       }
3161     }
3162 
3163     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
3164     // in a Construct]
3165     //  Variables with the predetermined data-sharing attributes may not be
3166     //  listed in data-sharing attributes clauses, except for the cases
3167     //  listed below. For these exceptions only, listing a predetermined
3168     //  variable in a data-sharing attribute clause is allowed and overrides
3169     //  the variable's predetermined data-sharing attributes.
3170     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
3171     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
3172       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
3173                                           << getOpenMPClauseName(OMPC_private);
3174       ReportOriginalDSA(*this, DSAStack, VD, DVar);
3175       continue;
3176     }
3177 
3178     DSAStack->addDSA(VD, DE, OMPC_private);
3179     Vars.push_back(DE);
3180   }
3181 
3182   if (Vars.empty())
3183     return nullptr;
3184 
3185   return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
3186 }
3187 
3188 OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
3189                                                SourceLocation StartLoc,
3190                                                SourceLocation LParenLoc,
3191                                                SourceLocation EndLoc) {
3192   SmallVector<Expr *, 8> Vars;
3193   bool IsImplicitClause =
3194       StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
3195   auto ImplicitClauseLoc = DSAStack->getConstructLoc();
3196 
3197   for (auto &RefExpr : VarList) {
3198     assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
3199     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
3200       // It will be analyzed later.
3201       Vars.push_back(RefExpr);
3202       continue;
3203     }
3204 
3205     SourceLocation ELoc = IsImplicitClause ? ImplicitClauseLoc
3206                                            : RefExpr->getExprLoc();
3207     // OpenMP [2.1, C/C++]
3208     //  A list item is a variable name.
3209     // OpenMP  [2.9.3.3, Restrictions, p.1]
3210     //  A variable that is part of another variable (as an array or
3211     //  structure element) cannot appear in a private clause.
3212     DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
3213     if (!DE || !isa<VarDecl>(DE->getDecl())) {
3214       Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
3215       continue;
3216     }
3217     Decl *D = DE->getDecl();
3218     VarDecl *VD = cast<VarDecl>(D);
3219 
3220     QualType Type = VD->getType();
3221     if (Type->isDependentType() || Type->isInstantiationDependentType()) {
3222       // It will be analyzed later.
3223       Vars.push_back(DE);
3224       continue;
3225     }
3226 
3227     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
3228     //  A variable that appears in a private clause must not have an incomplete
3229     //  type or a reference type.
3230     if (RequireCompleteType(ELoc, Type,
3231                             diag::err_omp_firstprivate_incomplete_type)) {
3232       continue;
3233     }
3234     if (Type->isReferenceType()) {
3235       if (IsImplicitClause) {
3236         Diag(ImplicitClauseLoc,
3237              diag::err_omp_task_predetermined_firstprivate_ref_type_arg)
3238             << Type;
3239         Diag(RefExpr->getExprLoc(), diag::note_used_here);
3240       } else {
3241         Diag(ELoc, diag::err_omp_clause_ref_type_arg)
3242             << getOpenMPClauseName(OMPC_firstprivate) << Type;
3243       }
3244       bool IsDecl =
3245           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
3246       Diag(VD->getLocation(),
3247            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
3248           << VD;
3249       continue;
3250     }
3251 
3252     // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
3253     //  A variable of class type (or array thereof) that appears in a private
3254     //  clause requires an accessible, unambiguous copy constructor for the
3255     //  class type.
3256     Type = Context.getBaseElementType(Type);
3257     CXXRecordDecl *RD = getLangOpts().CPlusPlus
3258                             ? Type.getNonReferenceType()->getAsCXXRecordDecl()
3259                             : nullptr;
3260     // FIXME This code must be replaced by actual constructing/destructing of
3261     // the firstprivate variable.
3262     if (RD) {
3263       CXXConstructorDecl *CD = LookupCopyingConstructor(RD, 0);
3264       PartialDiagnostic PD =
3265           PartialDiagnostic(PartialDiagnostic::NullDiagnostic());
3266       if (!CD ||
3267           CheckConstructorAccess(ELoc, CD,
3268                                  InitializedEntity::InitializeTemporary(Type),
3269                                  CD->getAccess(), PD) == AR_inaccessible ||
3270           CD->isDeleted()) {
3271         if (IsImplicitClause) {
3272           Diag(ImplicitClauseLoc,
3273                diag::err_omp_task_predetermined_firstprivate_required_method)
3274               << 0;
3275           Diag(RefExpr->getExprLoc(), diag::note_used_here);
3276         } else {
3277           Diag(ELoc, diag::err_omp_required_method)
3278               << getOpenMPClauseName(OMPC_firstprivate) << 1;
3279         }
3280         bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
3281                       VarDecl::DeclarationOnly;
3282         Diag(VD->getLocation(),
3283              IsDecl ? diag::note_previous_decl : diag::note_defined_here)
3284             << VD;
3285         Diag(RD->getLocation(), diag::note_previous_decl) << RD;
3286         continue;
3287       }
3288       MarkFunctionReferenced(ELoc, CD);
3289       DiagnoseUseOfDecl(CD, ELoc);
3290 
3291       CXXDestructorDecl *DD = RD->getDestructor();
3292       if (DD) {
3293         if (CheckDestructorAccess(ELoc, DD, PD) == AR_inaccessible ||
3294             DD->isDeleted()) {
3295           if (IsImplicitClause) {
3296             Diag(ImplicitClauseLoc,
3297                  diag::err_omp_task_predetermined_firstprivate_required_method)
3298                 << 1;
3299             Diag(RefExpr->getExprLoc(), diag::note_used_here);
3300           } else {
3301             Diag(ELoc, diag::err_omp_required_method)
3302                 << getOpenMPClauseName(OMPC_firstprivate) << 4;
3303           }
3304           bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
3305                         VarDecl::DeclarationOnly;
3306           Diag(VD->getLocation(),
3307                IsDecl ? diag::note_previous_decl : diag::note_defined_here)
3308               << VD;
3309           Diag(RD->getLocation(), diag::note_previous_decl) << RD;
3310           continue;
3311         }
3312         MarkFunctionReferenced(ELoc, DD);
3313         DiagnoseUseOfDecl(DD, ELoc);
3314       }
3315     }
3316 
3317     // If an implicit firstprivate variable found it was checked already.
3318     if (!IsImplicitClause) {
3319       DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
3320       Type = Type.getNonReferenceType().getCanonicalType();
3321       bool IsConstant = Type.isConstant(Context);
3322       Type = Context.getBaseElementType(Type);
3323       // OpenMP [2.4.13, Data-sharing Attribute Clauses]
3324       //  A list item that specifies a given variable may not appear in more
3325       // than one clause on the same directive, except that a variable may be
3326       //  specified in both firstprivate and lastprivate clauses.
3327       if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
3328           DVar.CKind != OMPC_lastprivate && DVar.RefExpr) {
3329         Diag(ELoc, diag::err_omp_wrong_dsa)
3330             << getOpenMPClauseName(DVar.CKind)
3331             << getOpenMPClauseName(OMPC_firstprivate);
3332         ReportOriginalDSA(*this, DSAStack, VD, DVar);
3333         continue;
3334       }
3335 
3336       // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
3337       // in a Construct]
3338       //  Variables with the predetermined data-sharing attributes may not be
3339       //  listed in data-sharing attributes clauses, except for the cases
3340       //  listed below. For these exceptions only, listing a predetermined
3341       //  variable in a data-sharing attribute clause is allowed and overrides
3342       //  the variable's predetermined data-sharing attributes.
3343       // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
3344       // in a Construct, C/C++, p.2]
3345       //  Variables with const-qualified type having no mutable member may be
3346       //  listed in a firstprivate clause, even if they are static data members.
3347       if (!(IsConstant || VD->isStaticDataMember()) && !DVar.RefExpr &&
3348           DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
3349         Diag(ELoc, diag::err_omp_wrong_dsa)
3350             << getOpenMPClauseName(DVar.CKind)
3351             << getOpenMPClauseName(OMPC_firstprivate);
3352         ReportOriginalDSA(*this, DSAStack, VD, DVar);
3353         continue;
3354       }
3355 
3356       OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
3357       // OpenMP [2.9.3.4, Restrictions, p.2]
3358       //  A list item that is private within a parallel region must not appear
3359       //  in a firstprivate clause on a worksharing construct if any of the
3360       //  worksharing regions arising from the worksharing construct ever bind
3361       //  to any of the parallel regions arising from the parallel construct.
3362       if (isOpenMPWorksharingDirective(CurrDir) &&
3363           !isOpenMPParallelDirective(CurrDir)) {
3364         DVar = DSAStack->getImplicitDSA(VD, true);
3365         if (DVar.CKind != OMPC_shared &&
3366             (isOpenMPParallelDirective(DVar.DKind) ||
3367              DVar.DKind == OMPD_unknown)) {
3368           Diag(ELoc, diag::err_omp_required_access)
3369               << getOpenMPClauseName(OMPC_firstprivate)
3370               << getOpenMPClauseName(OMPC_shared);
3371           ReportOriginalDSA(*this, DSAStack, VD, DVar);
3372           continue;
3373         }
3374       }
3375       // OpenMP [2.9.3.4, Restrictions, p.3]
3376       //  A list item that appears in a reduction clause of a parallel construct
3377       //  must not appear in a firstprivate clause on a worksharing or task
3378       //  construct if any of the worksharing or task regions arising from the
3379       //  worksharing or task construct ever bind to any of the parallel regions
3380       //  arising from the parallel construct.
3381       // OpenMP [2.9.3.4, Restrictions, p.4]
3382       //  A list item that appears in a reduction clause in worksharing
3383       //  construct must not appear in a firstprivate clause in a task construct
3384       //  encountered during execution of any of the worksharing regions arising
3385       //  from the worksharing construct.
3386       if (CurrDir == OMPD_task) {
3387         DVar =
3388             DSAStack->hasInnermostDSA(VD, MatchesAnyClause(OMPC_reduction),
3389                                       [](OpenMPDirectiveKind K) -> bool {
3390                                         return isOpenMPParallelDirective(K) ||
3391                                                isOpenMPWorksharingDirective(K);
3392                                       },
3393                                       false);
3394         if (DVar.CKind == OMPC_reduction &&
3395             (isOpenMPParallelDirective(DVar.DKind) ||
3396              isOpenMPWorksharingDirective(DVar.DKind))) {
3397           Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
3398               << getOpenMPDirectiveName(DVar.DKind);
3399           ReportOriginalDSA(*this, DSAStack, VD, DVar);
3400           continue;
3401         }
3402       }
3403     }
3404 
3405     DSAStack->addDSA(VD, DE, OMPC_firstprivate);
3406     Vars.push_back(DE);
3407   }
3408 
3409   if (Vars.empty())
3410     return nullptr;
3411 
3412   return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
3413                                        Vars);
3414 }
3415 
3416 OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
3417                                               SourceLocation StartLoc,
3418                                               SourceLocation LParenLoc,
3419                                               SourceLocation EndLoc) {
3420   SmallVector<Expr *, 8> Vars;
3421   for (auto &RefExpr : VarList) {
3422     assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
3423     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
3424       // It will be analyzed later.
3425       Vars.push_back(RefExpr);
3426       continue;
3427     }
3428 
3429     SourceLocation ELoc = RefExpr->getExprLoc();
3430     // OpenMP [2.1, C/C++]
3431     //  A list item is a variable name.
3432     // OpenMP  [2.14.3.5, Restrictions, p.1]
3433     //  A variable that is part of another variable (as an array or structure
3434     //  element) cannot appear in a lastprivate clause.
3435     DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
3436     if (!DE || !isa<VarDecl>(DE->getDecl())) {
3437       Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
3438       continue;
3439     }
3440     Decl *D = DE->getDecl();
3441     VarDecl *VD = cast<VarDecl>(D);
3442 
3443     QualType Type = VD->getType();
3444     if (Type->isDependentType() || Type->isInstantiationDependentType()) {
3445       // It will be analyzed later.
3446       Vars.push_back(DE);
3447       continue;
3448     }
3449 
3450     // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
3451     //  A variable that appears in a lastprivate clause must not have an
3452     //  incomplete type or a reference type.
3453     if (RequireCompleteType(ELoc, Type,
3454                             diag::err_omp_lastprivate_incomplete_type)) {
3455       continue;
3456     }
3457     if (Type->isReferenceType()) {
3458       Diag(ELoc, diag::err_omp_clause_ref_type_arg)
3459           << getOpenMPClauseName(OMPC_lastprivate) << Type;
3460       bool IsDecl =
3461           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
3462       Diag(VD->getLocation(),
3463            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
3464           << VD;
3465       continue;
3466     }
3467 
3468     // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
3469     // in a Construct]
3470     //  Variables with the predetermined data-sharing attributes may not be
3471     //  listed in data-sharing attributes clauses, except for the cases
3472     //  listed below.
3473     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
3474     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
3475         DVar.CKind != OMPC_firstprivate &&
3476         (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
3477       Diag(ELoc, diag::err_omp_wrong_dsa)
3478           << getOpenMPClauseName(DVar.CKind)
3479           << getOpenMPClauseName(OMPC_lastprivate);
3480       ReportOriginalDSA(*this, DSAStack, VD, DVar);
3481       continue;
3482     }
3483 
3484     OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
3485     // OpenMP [2.14.3.5, Restrictions, p.2]
3486     // A list item that is private within a parallel region, or that appears in
3487     // the reduction clause of a parallel construct, must not appear in a
3488     // lastprivate clause on a worksharing construct if any of the corresponding
3489     // worksharing regions ever binds to any of the corresponding parallel
3490     // regions.
3491     if (isOpenMPWorksharingDirective(CurrDir) &&
3492         !isOpenMPParallelDirective(CurrDir)) {
3493       DVar = DSAStack->getImplicitDSA(VD, true);
3494       if (DVar.CKind != OMPC_shared) {
3495         Diag(ELoc, diag::err_omp_required_access)
3496             << getOpenMPClauseName(OMPC_lastprivate)
3497             << getOpenMPClauseName(OMPC_shared);
3498         ReportOriginalDSA(*this, DSAStack, VD, DVar);
3499         continue;
3500       }
3501     }
3502     // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
3503     //  A variable of class type (or array thereof) that appears in a
3504     //  lastprivate clause requires an accessible, unambiguous default
3505     //  constructor for the class type, unless the list item is also specified
3506     //  in a firstprivate clause.
3507     //  A variable of class type (or array thereof) that appears in a
3508     //  lastprivate clause requires an accessible, unambiguous copy assignment
3509     //  operator for the class type.
3510     while (Type.getNonReferenceType()->isArrayType())
3511       Type = cast<ArrayType>(Type.getNonReferenceType().getTypePtr())
3512                  ->getElementType();
3513     CXXRecordDecl *RD = getLangOpts().CPlusPlus
3514                             ? Type.getNonReferenceType()->getAsCXXRecordDecl()
3515                             : nullptr;
3516     // FIXME This code must be replaced by actual copying and destructing of the
3517     // lastprivate variable.
3518     if (RD) {
3519       CXXMethodDecl *MD = LookupCopyingAssignment(RD, 0, false, 0);
3520       DeclAccessPair FoundDecl = DeclAccessPair::make(MD, MD->getAccess());
3521       if (MD) {
3522         if (CheckMemberAccess(ELoc, RD, FoundDecl) == AR_inaccessible ||
3523             MD->isDeleted()) {
3524           Diag(ELoc, diag::err_omp_required_method)
3525               << getOpenMPClauseName(OMPC_lastprivate) << 2;
3526           bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
3527                         VarDecl::DeclarationOnly;
3528           Diag(VD->getLocation(),
3529                IsDecl ? diag::note_previous_decl : diag::note_defined_here)
3530               << VD;
3531           Diag(RD->getLocation(), diag::note_previous_decl) << RD;
3532           continue;
3533         }
3534         MarkFunctionReferenced(ELoc, MD);
3535         DiagnoseUseOfDecl(MD, ELoc);
3536       }
3537 
3538       CXXDestructorDecl *DD = RD->getDestructor();
3539       if (DD) {
3540         PartialDiagnostic PD =
3541             PartialDiagnostic(PartialDiagnostic::NullDiagnostic());
3542         if (CheckDestructorAccess(ELoc, DD, PD) == AR_inaccessible ||
3543             DD->isDeleted()) {
3544           Diag(ELoc, diag::err_omp_required_method)
3545               << getOpenMPClauseName(OMPC_lastprivate) << 4;
3546           bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
3547                         VarDecl::DeclarationOnly;
3548           Diag(VD->getLocation(),
3549                IsDecl ? diag::note_previous_decl : diag::note_defined_here)
3550               << VD;
3551           Diag(RD->getLocation(), diag::note_previous_decl) << RD;
3552           continue;
3553         }
3554         MarkFunctionReferenced(ELoc, DD);
3555         DiagnoseUseOfDecl(DD, ELoc);
3556       }
3557     }
3558 
3559     if (DVar.CKind != OMPC_firstprivate)
3560       DSAStack->addDSA(VD, DE, OMPC_lastprivate);
3561     Vars.push_back(DE);
3562   }
3563 
3564   if (Vars.empty())
3565     return nullptr;
3566 
3567   return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
3568                                       Vars);
3569 }
3570 
3571 OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
3572                                          SourceLocation StartLoc,
3573                                          SourceLocation LParenLoc,
3574                                          SourceLocation EndLoc) {
3575   SmallVector<Expr *, 8> Vars;
3576   for (auto &RefExpr : VarList) {
3577     assert(RefExpr && "NULL expr in OpenMP shared clause.");
3578     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
3579       // It will be analyzed later.
3580       Vars.push_back(RefExpr);
3581       continue;
3582     }
3583 
3584     SourceLocation ELoc = RefExpr->getExprLoc();
3585     // OpenMP [2.1, C/C++]
3586     //  A list item is a variable name.
3587     // OpenMP  [2.14.3.2, Restrictions, p.1]
3588     //  A variable that is part of another variable (as an array or structure
3589     //  element) cannot appear in a shared unless it is a static data member
3590     //  of a C++ class.
3591     DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
3592     if (!DE || !isa<VarDecl>(DE->getDecl())) {
3593       Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
3594       continue;
3595     }
3596     Decl *D = DE->getDecl();
3597     VarDecl *VD = cast<VarDecl>(D);
3598 
3599     QualType Type = VD->getType();
3600     if (Type->isDependentType() || Type->isInstantiationDependentType()) {
3601       // It will be analyzed later.
3602       Vars.push_back(DE);
3603       continue;
3604     }
3605 
3606     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
3607     // in a Construct]
3608     //  Variables with the predetermined data-sharing attributes may not be
3609     //  listed in data-sharing attributes clauses, except for the cases
3610     //  listed below. For these exceptions only, listing a predetermined
3611     //  variable in a data-sharing attribute clause is allowed and overrides
3612     //  the variable's predetermined data-sharing attributes.
3613     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
3614     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
3615         DVar.RefExpr) {
3616       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
3617                                           << getOpenMPClauseName(OMPC_shared);
3618       ReportOriginalDSA(*this, DSAStack, VD, DVar);
3619       continue;
3620     }
3621 
3622     DSAStack->addDSA(VD, DE, OMPC_shared);
3623     Vars.push_back(DE);
3624   }
3625 
3626   if (Vars.empty())
3627     return nullptr;
3628 
3629   return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
3630 }
3631 
3632 namespace {
3633 class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
3634   DSAStackTy *Stack;
3635 
3636 public:
3637   bool VisitDeclRefExpr(DeclRefExpr *E) {
3638     if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
3639       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false);
3640       if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
3641         return false;
3642       if (DVar.CKind != OMPC_unknown)
3643         return true;
3644       DSAStackTy::DSAVarData DVarPrivate =
3645           Stack->hasDSA(VD, isOpenMPPrivate, MatchesAlways(), false);
3646       if (DVarPrivate.CKind != OMPC_unknown)
3647         return true;
3648       return false;
3649     }
3650     return false;
3651   }
3652   bool VisitStmt(Stmt *S) {
3653     for (auto Child : S->children()) {
3654       if (Child && Visit(Child))
3655         return true;
3656     }
3657     return false;
3658   }
3659   explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
3660 };
3661 } // namespace
3662 
3663 OMPClause *Sema::ActOnOpenMPReductionClause(
3664     ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
3665     SourceLocation ColonLoc, SourceLocation EndLoc,
3666     CXXScopeSpec &ReductionIdScopeSpec,
3667     const DeclarationNameInfo &ReductionId) {
3668   // TODO: Allow scope specification search when 'declare reduction' is
3669   // supported.
3670   assert(ReductionIdScopeSpec.isEmpty() &&
3671          "No support for scoped reduction identifiers yet.");
3672 
3673   auto DN = ReductionId.getName();
3674   auto OOK = DN.getCXXOverloadedOperator();
3675   BinaryOperatorKind BOK = BO_Comma;
3676 
3677   // OpenMP [2.14.3.6, reduction clause]
3678   // C
3679   // reduction-identifier is either an identifier or one of the following
3680   // operators: +, -, *,  &, |, ^, && and ||
3681   // C++
3682   // reduction-identifier is either an id-expression or one of the following
3683   // operators: +, -, *, &, |, ^, && and ||
3684   // FIXME: Only 'min' and 'max' identifiers are supported for now.
3685   switch (OOK) {
3686   case OO_Plus:
3687   case OO_Minus:
3688     BOK = BO_AddAssign;
3689     break;
3690   case OO_Star:
3691     BOK = BO_MulAssign;
3692     break;
3693   case OO_Amp:
3694     BOK = BO_AndAssign;
3695     break;
3696   case OO_Pipe:
3697     BOK = BO_OrAssign;
3698     break;
3699   case OO_Caret:
3700     BOK = BO_XorAssign;
3701     break;
3702   case OO_AmpAmp:
3703     BOK = BO_LAnd;
3704     break;
3705   case OO_PipePipe:
3706     BOK = BO_LOr;
3707     break;
3708   default:
3709     if (auto II = DN.getAsIdentifierInfo()) {
3710       if (II->isStr("max"))
3711         BOK = BO_GT;
3712       else if (II->isStr("min"))
3713         BOK = BO_LT;
3714     }
3715     break;
3716   }
3717   SourceRange ReductionIdRange;
3718   if (ReductionIdScopeSpec.isValid()) {
3719     ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
3720   }
3721   ReductionIdRange.setEnd(ReductionId.getEndLoc());
3722   if (BOK == BO_Comma) {
3723     // Not allowed reduction identifier is found.
3724     Diag(ReductionId.getLocStart(), diag::err_omp_unknown_reduction_identifier)
3725         << ReductionIdRange;
3726     return nullptr;
3727   }
3728 
3729   SmallVector<Expr *, 8> Vars;
3730   for (auto RefExpr : VarList) {
3731     assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
3732     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
3733       // It will be analyzed later.
3734       Vars.push_back(RefExpr);
3735       continue;
3736     }
3737 
3738     if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
3739         RefExpr->isInstantiationDependent() ||
3740         RefExpr->containsUnexpandedParameterPack()) {
3741       // It will be analyzed later.
3742       Vars.push_back(RefExpr);
3743       continue;
3744     }
3745 
3746     auto ELoc = RefExpr->getExprLoc();
3747     auto ERange = RefExpr->getSourceRange();
3748     // OpenMP [2.1, C/C++]
3749     //  A list item is a variable or array section, subject to the restrictions
3750     //  specified in Section 2.4 on page 42 and in each of the sections
3751     // describing clauses and directives for which a list appears.
3752     // OpenMP  [2.14.3.3, Restrictions, p.1]
3753     //  A variable that is part of another variable (as an array or
3754     //  structure element) cannot appear in a private clause.
3755     auto DE = dyn_cast<DeclRefExpr>(RefExpr);
3756     if (!DE || !isa<VarDecl>(DE->getDecl())) {
3757       Diag(ELoc, diag::err_omp_expected_var_name) << ERange;
3758       continue;
3759     }
3760     auto D = DE->getDecl();
3761     auto VD = cast<VarDecl>(D);
3762     auto Type = VD->getType();
3763     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
3764     //  A variable that appears in a private clause must not have an incomplete
3765     //  type or a reference type.
3766     if (RequireCompleteType(ELoc, Type,
3767                             diag::err_omp_reduction_incomplete_type))
3768       continue;
3769     // OpenMP [2.14.3.6, reduction clause, Restrictions]
3770     // Arrays may not appear in a reduction clause.
3771     if (Type.getNonReferenceType()->isArrayType()) {
3772       Diag(ELoc, diag::err_omp_reduction_type_array) << Type << ERange;
3773       bool IsDecl =
3774           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
3775       Diag(VD->getLocation(),
3776            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
3777           << VD;
3778       continue;
3779     }
3780     // OpenMP [2.14.3.6, reduction clause, Restrictions]
3781     // A list item that appears in a reduction clause must not be
3782     // const-qualified.
3783     if (Type.getNonReferenceType().isConstant(Context)) {
3784       Diag(ELoc, diag::err_omp_const_variable)
3785           << getOpenMPClauseName(OMPC_reduction) << Type << ERange;
3786       bool IsDecl =
3787           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
3788       Diag(VD->getLocation(),
3789            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
3790           << VD;
3791       continue;
3792     }
3793     // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
3794     //  If a list-item is a reference type then it must bind to the same object
3795     //  for all threads of the team.
3796     VarDecl *VDDef = VD->getDefinition();
3797     if (Type->isReferenceType() && VDDef) {
3798       DSARefChecker Check(DSAStack);
3799       if (Check.Visit(VDDef->getInit())) {
3800         Diag(ELoc, diag::err_omp_reduction_ref_type_arg) << ERange;
3801         Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
3802         continue;
3803       }
3804     }
3805     // OpenMP [2.14.3.6, reduction clause, Restrictions]
3806     // The type of a list item that appears in a reduction clause must be valid
3807     // for the reduction-identifier. For a max or min reduction in C, the type
3808     // of the list item must be an allowed arithmetic data type: char, int,
3809     // float, double, or _Bool, possibly modified with long, short, signed, or
3810     // unsigned. For a max or min reduction in C++, the type of the list item
3811     // must be an allowed arithmetic data type: char, wchar_t, int, float,
3812     // double, or bool, possibly modified with long, short, signed, or unsigned.
3813     if ((BOK == BO_GT || BOK == BO_LT) &&
3814         !(Type->isScalarType() ||
3815           (getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
3816       Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
3817           << getLangOpts().CPlusPlus;
3818       bool IsDecl =
3819           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
3820       Diag(VD->getLocation(),
3821            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
3822           << VD;
3823       continue;
3824     }
3825     if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
3826         !getLangOpts().CPlusPlus && Type->isFloatingType()) {
3827       Diag(ELoc, diag::err_omp_clause_floating_type_arg);
3828       bool IsDecl =
3829           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
3830       Diag(VD->getLocation(),
3831            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
3832           << VD;
3833       continue;
3834     }
3835     bool Suppress = getDiagnostics().getSuppressAllDiagnostics();
3836     getDiagnostics().setSuppressAllDiagnostics(true);
3837     ExprResult ReductionOp =
3838         BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(), BOK,
3839                    RefExpr, RefExpr);
3840     getDiagnostics().setSuppressAllDiagnostics(Suppress);
3841     if (ReductionOp.isInvalid()) {
3842       Diag(ELoc, diag::err_omp_reduction_id_not_compatible) << Type
3843                                                             << ReductionIdRange;
3844       bool IsDecl =
3845           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
3846       Diag(VD->getLocation(),
3847            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
3848           << VD;
3849       continue;
3850     }
3851 
3852     // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
3853     // in a Construct]
3854     //  Variables with the predetermined data-sharing attributes may not be
3855     //  listed in data-sharing attributes clauses, except for the cases
3856     //  listed below. For these exceptions only, listing a predetermined
3857     //  variable in a data-sharing attribute clause is allowed and overrides
3858     //  the variable's predetermined data-sharing attributes.
3859     // OpenMP [2.14.3.6, Restrictions, p.3]
3860     //  Any number of reduction clauses can be specified on the directive,
3861     //  but a list item can appear only once in the reduction clauses for that
3862     //  directive.
3863     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
3864     if (DVar.CKind == OMPC_reduction) {
3865       Diag(ELoc, diag::err_omp_once_referenced)
3866           << getOpenMPClauseName(OMPC_reduction);
3867       if (DVar.RefExpr) {
3868         Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
3869       }
3870     } else if (DVar.CKind != OMPC_unknown) {
3871       Diag(ELoc, diag::err_omp_wrong_dsa)
3872           << getOpenMPClauseName(DVar.CKind)
3873           << getOpenMPClauseName(OMPC_reduction);
3874       ReportOriginalDSA(*this, DSAStack, VD, DVar);
3875       continue;
3876     }
3877 
3878     // OpenMP [2.14.3.6, Restrictions, p.1]
3879     //  A list item that appears in a reduction clause of a worksharing
3880     //  construct must be shared in the parallel regions to which any of the
3881     //  worksharing regions arising from the worksharing construct bind.
3882     OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
3883     if (isOpenMPWorksharingDirective(CurrDir) &&
3884         !isOpenMPParallelDirective(CurrDir)) {
3885       DVar = DSAStack->getImplicitDSA(VD, true);
3886       if (DVar.CKind != OMPC_shared) {
3887         Diag(ELoc, diag::err_omp_required_access)
3888             << getOpenMPClauseName(OMPC_reduction)
3889             << getOpenMPClauseName(OMPC_shared);
3890         ReportOriginalDSA(*this, DSAStack, VD, DVar);
3891         continue;
3892       }
3893     }
3894 
3895     CXXRecordDecl *RD = getLangOpts().CPlusPlus
3896                             ? Type.getNonReferenceType()->getAsCXXRecordDecl()
3897                             : nullptr;
3898     // FIXME This code must be replaced by actual constructing/destructing of
3899     // the reduction variable.
3900     if (RD) {
3901       CXXConstructorDecl *CD = LookupDefaultConstructor(RD);
3902       PartialDiagnostic PD =
3903           PartialDiagnostic(PartialDiagnostic::NullDiagnostic());
3904       if (!CD ||
3905           CheckConstructorAccess(ELoc, CD,
3906                                  InitializedEntity::InitializeTemporary(Type),
3907                                  CD->getAccess(), PD) == AR_inaccessible ||
3908           CD->isDeleted()) {
3909         Diag(ELoc, diag::err_omp_required_method)
3910             << getOpenMPClauseName(OMPC_reduction) << 0;
3911         bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
3912                       VarDecl::DeclarationOnly;
3913         Diag(VD->getLocation(),
3914              IsDecl ? diag::note_previous_decl : diag::note_defined_here)
3915             << VD;
3916         Diag(RD->getLocation(), diag::note_previous_decl) << RD;
3917         continue;
3918       }
3919       MarkFunctionReferenced(ELoc, CD);
3920       DiagnoseUseOfDecl(CD, ELoc);
3921 
3922       CXXDestructorDecl *DD = RD->getDestructor();
3923       if (DD) {
3924         if (CheckDestructorAccess(ELoc, DD, PD) == AR_inaccessible ||
3925             DD->isDeleted()) {
3926           Diag(ELoc, diag::err_omp_required_method)
3927               << getOpenMPClauseName(OMPC_reduction) << 4;
3928           bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
3929                         VarDecl::DeclarationOnly;
3930           Diag(VD->getLocation(),
3931                IsDecl ? diag::note_previous_decl : diag::note_defined_here)
3932               << VD;
3933           Diag(RD->getLocation(), diag::note_previous_decl) << RD;
3934           continue;
3935         }
3936         MarkFunctionReferenced(ELoc, DD);
3937         DiagnoseUseOfDecl(DD, ELoc);
3938       }
3939     }
3940 
3941     DSAStack->addDSA(VD, DE, OMPC_reduction);
3942     Vars.push_back(DE);
3943   }
3944 
3945   if (Vars.empty())
3946     return nullptr;
3947 
3948   return OMPReductionClause::Create(
3949       Context, StartLoc, LParenLoc, ColonLoc, EndLoc, Vars,
3950       ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId);
3951 }
3952 
3953 OMPClause *Sema::ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
3954                                          SourceLocation StartLoc,
3955                                          SourceLocation LParenLoc,
3956                                          SourceLocation ColonLoc,
3957                                          SourceLocation EndLoc) {
3958   SmallVector<Expr *, 8> Vars;
3959   for (auto &RefExpr : VarList) {
3960     assert(RefExpr && "NULL expr in OpenMP linear clause.");
3961     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
3962       // It will be analyzed later.
3963       Vars.push_back(RefExpr);
3964       continue;
3965     }
3966 
3967     // OpenMP [2.14.3.7, linear clause]
3968     // A list item that appears in a linear clause is subject to the private
3969     // clause semantics described in Section 2.14.3.3 on page 159 except as
3970     // noted. In addition, the value of the new list item on each iteration
3971     // of the associated loop(s) corresponds to the value of the original
3972     // list item before entering the construct plus the logical number of
3973     // the iteration times linear-step.
3974 
3975     SourceLocation ELoc = RefExpr->getExprLoc();
3976     // OpenMP [2.1, C/C++]
3977     //  A list item is a variable name.
3978     // OpenMP  [2.14.3.3, Restrictions, p.1]
3979     //  A variable that is part of another variable (as an array or
3980     //  structure element) cannot appear in a private clause.
3981     DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
3982     if (!DE || !isa<VarDecl>(DE->getDecl())) {
3983       Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
3984       continue;
3985     }
3986 
3987     VarDecl *VD = cast<VarDecl>(DE->getDecl());
3988 
3989     // OpenMP [2.14.3.7, linear clause]
3990     //  A list-item cannot appear in more than one linear clause.
3991     //  A list-item that appears in a linear clause cannot appear in any
3992     //  other data-sharing attribute clause.
3993     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
3994     if (DVar.RefExpr) {
3995       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
3996                                           << getOpenMPClauseName(OMPC_linear);
3997       ReportOriginalDSA(*this, DSAStack, VD, DVar);
3998       continue;
3999     }
4000 
4001     QualType QType = VD->getType();
4002     if (QType->isDependentType() || QType->isInstantiationDependentType()) {
4003       // It will be analyzed later.
4004       Vars.push_back(DE);
4005       continue;
4006     }
4007 
4008     // A variable must not have an incomplete type or a reference type.
4009     if (RequireCompleteType(ELoc, QType,
4010                             diag::err_omp_linear_incomplete_type)) {
4011       continue;
4012     }
4013     if (QType->isReferenceType()) {
4014       Diag(ELoc, diag::err_omp_clause_ref_type_arg)
4015           << getOpenMPClauseName(OMPC_linear) << QType;
4016       bool IsDecl =
4017           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
4018       Diag(VD->getLocation(),
4019            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
4020           << VD;
4021       continue;
4022     }
4023 
4024     // A list item must not be const-qualified.
4025     if (QType.isConstant(Context)) {
4026       Diag(ELoc, diag::err_omp_const_variable)
4027           << getOpenMPClauseName(OMPC_linear);
4028       bool IsDecl =
4029           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
4030       Diag(VD->getLocation(),
4031            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
4032           << VD;
4033       continue;
4034     }
4035 
4036     // A list item must be of integral or pointer type.
4037     QType = QType.getUnqualifiedType().getCanonicalType();
4038     const Type *Ty = QType.getTypePtrOrNull();
4039     if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
4040                 !Ty->isPointerType())) {
4041       Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << QType;
4042       bool IsDecl =
4043           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
4044       Diag(VD->getLocation(),
4045            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
4046           << VD;
4047       continue;
4048     }
4049 
4050     DSAStack->addDSA(VD, DE, OMPC_linear);
4051     Vars.push_back(DE);
4052   }
4053 
4054   if (Vars.empty())
4055     return nullptr;
4056 
4057   Expr *StepExpr = Step;
4058   if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
4059       !Step->isInstantiationDependent() &&
4060       !Step->containsUnexpandedParameterPack()) {
4061     SourceLocation StepLoc = Step->getLocStart();
4062     ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
4063     if (Val.isInvalid())
4064       return nullptr;
4065     StepExpr = Val.get();
4066 
4067     // Warn about zero linear step (it would be probably better specified as
4068     // making corresponding variables 'const').
4069     llvm::APSInt Result;
4070     if (StepExpr->isIntegerConstantExpr(Result, Context) &&
4071         !Result.isNegative() && !Result.isStrictlyPositive())
4072       Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
4073                                                      << (Vars.size() > 1);
4074   }
4075 
4076   return OMPLinearClause::Create(Context, StartLoc, LParenLoc, ColonLoc, EndLoc,
4077                                  Vars, StepExpr);
4078 }
4079 
4080 OMPClause *Sema::ActOnOpenMPAlignedClause(
4081     ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
4082     SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
4083 
4084   SmallVector<Expr *, 8> Vars;
4085   for (auto &RefExpr : VarList) {
4086     assert(RefExpr && "NULL expr in OpenMP aligned clause.");
4087     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
4088       // It will be analyzed later.
4089       Vars.push_back(RefExpr);
4090       continue;
4091     }
4092 
4093     SourceLocation ELoc = RefExpr->getExprLoc();
4094     // OpenMP [2.1, C/C++]
4095     //  A list item is a variable name.
4096     DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
4097     if (!DE || !isa<VarDecl>(DE->getDecl())) {
4098       Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
4099       continue;
4100     }
4101 
4102     VarDecl *VD = cast<VarDecl>(DE->getDecl());
4103 
4104     // OpenMP  [2.8.1, simd construct, Restrictions]
4105     // The type of list items appearing in the aligned clause must be
4106     // array, pointer, reference to array, or reference to pointer.
4107     QualType QType = DE->getType()
4108                          .getNonReferenceType()
4109                          .getUnqualifiedType()
4110                          .getCanonicalType();
4111     const Type *Ty = QType.getTypePtrOrNull();
4112     if (!Ty || (!Ty->isDependentType() && !Ty->isArrayType() &&
4113                 !Ty->isPointerType())) {
4114       Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
4115           << QType << getLangOpts().CPlusPlus << RefExpr->getSourceRange();
4116       bool IsDecl =
4117           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
4118       Diag(VD->getLocation(),
4119            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
4120           << VD;
4121       continue;
4122     }
4123 
4124     // OpenMP  [2.8.1, simd construct, Restrictions]
4125     // A list-item cannot appear in more than one aligned clause.
4126     if (DeclRefExpr *PrevRef = DSAStack->addUniqueAligned(VD, DE)) {
4127       Diag(ELoc, diag::err_omp_aligned_twice) << RefExpr->getSourceRange();
4128       Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
4129           << getOpenMPClauseName(OMPC_aligned);
4130       continue;
4131     }
4132 
4133     Vars.push_back(DE);
4134   }
4135 
4136   // OpenMP [2.8.1, simd construct, Description]
4137   // The parameter of the aligned clause, alignment, must be a constant
4138   // positive integer expression.
4139   // If no optional parameter is specified, implementation-defined default
4140   // alignments for SIMD instructions on the target platforms are assumed.
4141   if (Alignment != nullptr) {
4142     ExprResult AlignResult =
4143         VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
4144     if (AlignResult.isInvalid())
4145       return nullptr;
4146     Alignment = AlignResult.get();
4147   }
4148   if (Vars.empty())
4149     return nullptr;
4150 
4151   return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
4152                                   EndLoc, Vars, Alignment);
4153 }
4154 
4155 OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
4156                                          SourceLocation StartLoc,
4157                                          SourceLocation LParenLoc,
4158                                          SourceLocation EndLoc) {
4159   SmallVector<Expr *, 8> Vars;
4160   for (auto &RefExpr : VarList) {
4161     assert(RefExpr && "NULL expr in OpenMP copyin clause.");
4162     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
4163       // It will be analyzed later.
4164       Vars.push_back(RefExpr);
4165       continue;
4166     }
4167 
4168     SourceLocation ELoc = RefExpr->getExprLoc();
4169     // OpenMP [2.1, C/C++]
4170     //  A list item is a variable name.
4171     // OpenMP  [2.14.4.1, Restrictions, p.1]
4172     //  A list item that appears in a copyin clause must be threadprivate.
4173     DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
4174     if (!DE || !isa<VarDecl>(DE->getDecl())) {
4175       Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
4176       continue;
4177     }
4178 
4179     Decl *D = DE->getDecl();
4180     VarDecl *VD = cast<VarDecl>(D);
4181 
4182     QualType Type = VD->getType();
4183     if (Type->isDependentType() || Type->isInstantiationDependentType()) {
4184       // It will be analyzed later.
4185       Vars.push_back(DE);
4186       continue;
4187     }
4188 
4189     // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
4190     //  A list item that appears in a copyin clause must be threadprivate.
4191     if (!DSAStack->isThreadPrivate(VD)) {
4192       Diag(ELoc, diag::err_omp_required_access)
4193           << getOpenMPClauseName(OMPC_copyin)
4194           << getOpenMPDirectiveName(OMPD_threadprivate);
4195       continue;
4196     }
4197 
4198     // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
4199     //  A variable of class type (or array thereof) that appears in a
4200     //  copyin clause requires an accessible, unambiguous copy assignment
4201     //  operator for the class type.
4202     Type = Context.getBaseElementType(Type);
4203     CXXRecordDecl *RD =
4204         getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
4205     // FIXME This code must be replaced by actual assignment of the
4206     // threadprivate variable.
4207     if (RD) {
4208       CXXMethodDecl *MD = LookupCopyingAssignment(RD, 0, false, 0);
4209       DeclAccessPair FoundDecl = DeclAccessPair::make(MD, MD->getAccess());
4210       if (MD) {
4211         if (CheckMemberAccess(ELoc, RD, FoundDecl) == AR_inaccessible ||
4212             MD->isDeleted()) {
4213           Diag(ELoc, diag::err_omp_required_method)
4214               << getOpenMPClauseName(OMPC_copyin) << 2;
4215           bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
4216                         VarDecl::DeclarationOnly;
4217           Diag(VD->getLocation(),
4218                IsDecl ? diag::note_previous_decl : diag::note_defined_here)
4219               << VD;
4220           Diag(RD->getLocation(), diag::note_previous_decl) << RD;
4221           continue;
4222         }
4223         MarkFunctionReferenced(ELoc, MD);
4224         DiagnoseUseOfDecl(MD, ELoc);
4225       }
4226     }
4227 
4228     DSAStack->addDSA(VD, DE, OMPC_copyin);
4229     Vars.push_back(DE);
4230   }
4231 
4232   if (Vars.empty())
4233     return nullptr;
4234 
4235   return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
4236 }
4237 
4238 OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
4239                                               SourceLocation StartLoc,
4240                                               SourceLocation LParenLoc,
4241                                               SourceLocation EndLoc) {
4242   SmallVector<Expr *, 8> Vars;
4243   for (auto &RefExpr : VarList) {
4244     assert(RefExpr && "NULL expr in OpenMP copyprivate clause.");
4245     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
4246       // It will be analyzed later.
4247       Vars.push_back(RefExpr);
4248       continue;
4249     }
4250 
4251     SourceLocation ELoc = RefExpr->getExprLoc();
4252     // OpenMP [2.1, C/C++]
4253     //  A list item is a variable name.
4254     // OpenMP  [2.14.4.1, Restrictions, p.1]
4255     //  A list item that appears in a copyin clause must be threadprivate.
4256     DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
4257     if (!DE || !isa<VarDecl>(DE->getDecl())) {
4258       Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
4259       continue;
4260     }
4261 
4262     Decl *D = DE->getDecl();
4263     VarDecl *VD = cast<VarDecl>(D);
4264 
4265     QualType Type = VD->getType();
4266     if (Type->isDependentType() || Type->isInstantiationDependentType()) {
4267       // It will be analyzed later.
4268       Vars.push_back(DE);
4269       continue;
4270     }
4271 
4272     // OpenMP [2.14.4.2, Restrictions, p.2]
4273     //  A list item that appears in a copyprivate clause may not appear in a
4274     //  private or firstprivate clause on the single construct.
4275     if (!DSAStack->isThreadPrivate(VD)) {
4276       auto DVar = DSAStack->getTopDSA(VD, false);
4277       if (DVar.CKind != OMPC_copyprivate && DVar.CKind != OMPC_unknown &&
4278           !(DVar.CKind == OMPC_private && !DVar.RefExpr)) {
4279         Diag(ELoc, diag::err_omp_wrong_dsa)
4280             << getOpenMPClauseName(DVar.CKind)
4281             << getOpenMPClauseName(OMPC_copyprivate);
4282         ReportOriginalDSA(*this, DSAStack, VD, DVar);
4283         continue;
4284       }
4285 
4286       // OpenMP [2.11.4.2, Restrictions, p.1]
4287       //  All list items that appear in a copyprivate clause must be either
4288       //  threadprivate or private in the enclosing context.
4289       if (DVar.CKind == OMPC_unknown) {
4290         DVar = DSAStack->getImplicitDSA(VD, false);
4291         if (DVar.CKind == OMPC_shared) {
4292           Diag(ELoc, diag::err_omp_required_access)
4293               << getOpenMPClauseName(OMPC_copyprivate)
4294               << "threadprivate or private in the enclosing context";
4295           ReportOriginalDSA(*this, DSAStack, VD, DVar);
4296           continue;
4297         }
4298       }
4299     }
4300 
4301     // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
4302     //  A variable of class type (or array thereof) that appears in a
4303     //  copyin clause requires an accessible, unambiguous copy assignment
4304     //  operator for the class type.
4305     Type = Context.getBaseElementType(Type);
4306     CXXRecordDecl *RD =
4307         getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
4308     // FIXME This code must be replaced by actual assignment of the
4309     // threadprivate variable.
4310     if (RD) {
4311       CXXMethodDecl *MD = LookupCopyingAssignment(RD, 0, false, 0);
4312       DeclAccessPair FoundDecl = DeclAccessPair::make(MD, MD->getAccess());
4313       if (MD) {
4314         if (CheckMemberAccess(ELoc, RD, FoundDecl) == AR_inaccessible ||
4315             MD->isDeleted()) {
4316           Diag(ELoc, diag::err_omp_required_method)
4317               << getOpenMPClauseName(OMPC_copyprivate) << 2;
4318           bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
4319                         VarDecl::DeclarationOnly;
4320           Diag(VD->getLocation(),
4321                IsDecl ? diag::note_previous_decl : diag::note_defined_here)
4322               << VD;
4323           Diag(RD->getLocation(), diag::note_previous_decl) << RD;
4324           continue;
4325         }
4326         MarkFunctionReferenced(ELoc, MD);
4327         DiagnoseUseOfDecl(MD, ELoc);
4328       }
4329     }
4330 
4331     // No need to mark vars as copyprivate, they are already threadprivate or
4332     // implicitly private.
4333     Vars.push_back(DE);
4334   }
4335 
4336   if (Vars.empty())
4337     return nullptr;
4338 
4339   return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
4340 }
4341 
4342 OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
4343                                         SourceLocation StartLoc,
4344                                         SourceLocation LParenLoc,
4345                                         SourceLocation EndLoc) {
4346   if (VarList.empty())
4347     return nullptr;
4348 
4349   return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
4350 }
4351 
4352