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