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