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/Basic/OpenMPKinds.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/Lex/Preprocessor.h"
23 #include "clang/Sema/Initialization.h"
24 #include "clang/Sema/Lookup.h"
25 #include "clang/Sema/Scope.h"
26 #include "clang/Sema/ScopeInfo.h"
27 #include "clang/Sema/SemaInternal.h"
28 using namespace clang;
29 
30 //===----------------------------------------------------------------------===//
31 // Stack of data-sharing attributes for variables
32 //===----------------------------------------------------------------------===//
33 
34 namespace {
35 /// \brief Default data sharing attributes, which can be applied to directive.
36 enum DefaultDataSharingAttributes {
37   DSA_unspecified = 0,   /// \brief Data sharing attribute not specified.
38   DSA_none = 1 << 0,     /// \brief Default data sharing attribute 'none'.
39   DSA_shared = 1 << 1    /// \brief Default data sharing attribute 'shared'.
40 };
41 
42 /// \brief Stack for tracking declarations used in OpenMP directives and
43 /// clauses and their data-sharing attributes.
44 class DSAStackTy {
45 public:
46   struct DSAVarData {
47     OpenMPDirectiveKind DKind;
48     OpenMPClauseKind CKind;
49     DeclRefExpr *RefExpr;
50     DSAVarData() : DKind(OMPD_unknown), CKind(OMPC_unknown), RefExpr(0) { }
51   };
52 private:
53   struct DSAInfo {
54     OpenMPClauseKind Attributes;
55     DeclRefExpr *RefExpr;
56   };
57   typedef llvm::SmallDenseMap<VarDecl *, DSAInfo, 64> DeclSAMapTy;
58 
59   struct SharingMapTy {
60     DeclSAMapTy SharingMap;
61     DefaultDataSharingAttributes DefaultAttr;
62     OpenMPDirectiveKind Directive;
63     DeclarationNameInfo DirectiveName;
64     Scope *CurScope;
65     SharingMapTy(OpenMPDirectiveKind DKind,
66                  const DeclarationNameInfo &Name,
67                  Scope *CurScope)
68       : SharingMap(), DefaultAttr(DSA_unspecified), Directive(DKind),
69         DirectiveName(Name), CurScope(CurScope) { }
70     SharingMapTy()
71       : SharingMap(), DefaultAttr(DSA_unspecified),
72         Directive(OMPD_unknown), DirectiveName(),
73         CurScope(0) { }
74   };
75 
76   typedef SmallVector<SharingMapTy, 64> StackTy;
77 
78   /// \brief Stack of used declaration and their data-sharing attributes.
79   StackTy Stack;
80   Sema &Actions;
81 
82   typedef SmallVector<SharingMapTy, 8>::reverse_iterator reverse_iterator;
83 
84   DSAVarData getDSA(StackTy::reverse_iterator Iter, VarDecl *D);
85 
86   /// \brief Checks if the variable is a local for OpenMP region.
87   bool isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter);
88 public:
89   explicit DSAStackTy(Sema &S) : Stack(1), Actions(S) { }
90 
91   void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
92             Scope *CurScope) {
93     Stack.push_back(SharingMapTy(DKind, DirName, CurScope));
94   }
95 
96   void pop() {
97     assert(Stack.size() > 1 && "Data-sharing attributes stack is empty!");
98     Stack.pop_back();
99   }
100 
101   /// \brief Adds explicit data sharing attribute to the specified declaration.
102   void addDSA(VarDecl *D, DeclRefExpr *E, OpenMPClauseKind A);
103 
104   /// \brief Returns data sharing attributes from top of the stack for the
105   /// specified declaration.
106   DSAVarData getTopDSA(VarDecl *D);
107   /// \brief Returns data-sharing attributes for the specified declaration.
108   DSAVarData getImplicitDSA(VarDecl *D);
109   /// \brief Checks if the specified variables has \a CKind data-sharing
110   /// attribute in \a DKind directive.
111   DSAVarData hasDSA(VarDecl *D, OpenMPClauseKind CKind,
112                     OpenMPDirectiveKind DKind = OMPD_unknown);
113 
114   /// \brief Returns currently analyzed directive.
115   OpenMPDirectiveKind getCurrentDirective() const {
116     return Stack.back().Directive;
117   }
118 
119   /// \brief Set default data sharing attribute to none.
120   void setDefaultDSANone() { Stack.back().DefaultAttr = DSA_none; }
121   /// \brief Set default data sharing attribute to shared.
122   void setDefaultDSAShared() { Stack.back().DefaultAttr = DSA_shared; }
123 
124   DefaultDataSharingAttributes getDefaultDSA() const {
125     return Stack.back().DefaultAttr;
126   }
127 
128   /// \brief Checks if the spewcified variable is threadprivate.
129   bool isThreadPrivate(VarDecl *D) {
130     DSAVarData DVar = getTopDSA(D);
131     return (DVar.CKind == OMPC_threadprivate || DVar.CKind == OMPC_copyin);
132   }
133 
134   Scope *getCurScope() const { return Stack.back().CurScope; }
135   Scope *getCurScope() { return Stack.back().CurScope; }
136 };
137 } // end anonymous namespace.
138 
139 DSAStackTy::DSAVarData DSAStackTy::getDSA(StackTy::reverse_iterator Iter,
140                                           VarDecl *D) {
141   DSAVarData DVar;
142   if (Iter == Stack.rend() - 1) {
143     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
144     // in a region but not in construct]
145     //  File-scope or namespace-scope variables referenced in called routines
146     //  in the region are shared unless they appear in a threadprivate
147     //  directive.
148     // TODO
149     if (!D->isFunctionOrMethodVarDecl())
150       DVar.CKind = OMPC_shared;
151 
152     // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
153     // in a region but not in construct]
154     //  Variables with static storage duration that are declared in called
155     //  routines in the region are shared.
156     if (D->hasGlobalStorage())
157       DVar.CKind = OMPC_shared;
158 
159     return DVar;
160   }
161 
162   DVar.DKind = Iter->Directive;
163   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
164   // in a Construct, C/C++, predetermined, p.1]
165   // Variables with automatic storage duration that are declared in a scope
166   // inside the construct are private.
167   if (DVar.DKind != OMPD_parallel) {
168     if (isOpenMPLocal(D, Iter) && D->isLocalVarDecl() &&
169         (D->getStorageClass() == SC_Auto ||
170          D->getStorageClass() == SC_None)) {
171       DVar.CKind = OMPC_private;
172       return DVar;
173     }
174   }
175 
176   // Explicitly specified attributes and local variables with predetermined
177   // attributes.
178   if (Iter->SharingMap.count(D)) {
179     DVar.RefExpr = Iter->SharingMap[D].RefExpr;
180     DVar.CKind = Iter->SharingMap[D].Attributes;
181     return DVar;
182   }
183 
184   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
185   // in a Construct, C/C++, implicitly determined, p.1]
186   //  In a parallel or task construct, the data-sharing attributes of these
187   //  variables are determined by the default clause, if present.
188   switch (Iter->DefaultAttr) {
189   case DSA_shared:
190     DVar.CKind = OMPC_shared;
191     return DVar;
192   case DSA_none:
193     return DVar;
194   case DSA_unspecified:
195     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
196     // in a Construct, implicitly determined, p.2]
197     //  In a parallel construct, if no default clause is present, these
198     //  variables are shared.
199     if (DVar.DKind == OMPD_parallel) {
200       DVar.CKind = OMPC_shared;
201       return DVar;
202     }
203 
204     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
205     // in a Construct, implicitly determined, p.4]
206     //  In a task construct, if no default clause is present, a variable that in
207     //  the enclosing context is determined to be shared by all implicit tasks
208     //  bound to the current team is shared.
209     // TODO
210     if (DVar.DKind == OMPD_task) {
211       DSAVarData DVarTemp;
212       for (StackTy::reverse_iterator I = std::next(Iter),
213                                      EE = std::prev(Stack.rend());
214            I != EE; ++I) {
215         // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
216         // in a Construct, implicitly determined, p.6]
217         //  In a task construct, if no default clause is present, a variable
218         //  whose data-sharing attribute is not determined by the rules above is
219         //  firstprivate.
220         DVarTemp = getDSA(I, D);
221         if (DVarTemp.CKind != OMPC_shared) {
222           DVar.RefExpr = 0;
223           DVar.DKind = OMPD_task;
224           DVar.CKind = OMPC_firstprivate;
225           return DVar;
226         }
227         if (I->Directive == OMPD_parallel) break;
228       }
229       DVar.DKind = OMPD_task;
230       DVar.CKind =
231         (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
232       return DVar;
233     }
234   }
235   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
236   // in a Construct, implicitly determined, p.3]
237   //  For constructs other than task, if no default clause is present, these
238   //  variables inherit their data-sharing attributes from the enclosing
239   //  context.
240   return getDSA(std::next(Iter), D);
241 }
242 
243 void DSAStackTy::addDSA(VarDecl *D, DeclRefExpr *E, OpenMPClauseKind A) {
244   if (A == OMPC_threadprivate) {
245     Stack[0].SharingMap[D].Attributes = A;
246     Stack[0].SharingMap[D].RefExpr = E;
247   } else {
248     assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
249     Stack.back().SharingMap[D].Attributes = A;
250     Stack.back().SharingMap[D].RefExpr = E;
251   }
252 }
253 
254 bool
255 DSAStackTy::isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter) {
256   if (Stack.size() > 2) {
257     reverse_iterator I = Iter, E = Stack.rend() - 1;
258     Scope *TopScope = 0;
259     while (I != E &&
260            I->Directive != OMPD_parallel) {
261       ++I;
262     }
263     if (I == E) return false;
264     TopScope = I->CurScope ? I->CurScope->getParent() : 0;
265     Scope *CurScope = getCurScope();
266     while (CurScope != TopScope && !CurScope->isDeclScope(D)) {
267       CurScope = CurScope->getParent();
268     }
269     return CurScope != TopScope;
270   }
271   return false;
272 }
273 
274 DSAStackTy::DSAVarData DSAStackTy::getTopDSA(VarDecl *D) {
275   DSAVarData DVar;
276 
277   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
278   // in a Construct, C/C++, predetermined, p.1]
279   //  Variables appearing in threadprivate directives are threadprivate.
280   if (D->getTLSKind() != VarDecl::TLS_None) {
281     DVar.CKind = OMPC_threadprivate;
282     return DVar;
283   }
284   if (Stack[0].SharingMap.count(D)) {
285     DVar.RefExpr = Stack[0].SharingMap[D].RefExpr;
286     DVar.CKind = OMPC_threadprivate;
287     return DVar;
288   }
289 
290   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
291   // in a Construct, C/C++, predetermined, p.1]
292   // Variables with automatic storage duration that are declared in a scope
293   // inside the construct are private.
294   OpenMPDirectiveKind Kind = getCurrentDirective();
295   if (Kind != OMPD_parallel) {
296     if (isOpenMPLocal(D, std::next(Stack.rbegin())) && D->isLocalVarDecl() &&
297         (D->getStorageClass() == SC_Auto ||
298          D->getStorageClass() == SC_None))
299       DVar.CKind = OMPC_private;
300       return DVar;
301   }
302 
303   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
304   // in a Construct, C/C++, predetermined, p.4]
305   //  Static data memebers are shared.
306   if (D->isStaticDataMember()) {
307     // Variables with const-qualified type having no mutable member may be listed
308     // in a firstprivate clause, even if they are static data members.
309     DSAVarData DVarTemp = hasDSA(D, OMPC_firstprivate);
310     if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr)
311       return DVar;
312 
313     DVar.CKind = OMPC_shared;
314     return DVar;
315   }
316 
317   QualType Type = D->getType().getNonReferenceType().getCanonicalType();
318   bool IsConstant = Type.isConstant(Actions.getASTContext());
319   while (Type->isArrayType()) {
320     QualType ElemType = cast<ArrayType>(Type.getTypePtr())->getElementType();
321     Type = ElemType.getNonReferenceType().getCanonicalType();
322   }
323   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
324   // in a Construct, C/C++, predetermined, p.6]
325   //  Variables with const qualified type having no mutable member are
326   //  shared.
327   CXXRecordDecl *RD = Actions.getLangOpts().CPlusPlus ?
328                                 Type->getAsCXXRecordDecl() : 0;
329   if (IsConstant &&
330       !(Actions.getLangOpts().CPlusPlus && RD && RD->hasMutableFields())) {
331     // Variables with const-qualified type having no mutable member may be
332     // listed in a firstprivate clause, even if they are static data members.
333     DSAVarData DVarTemp = hasDSA(D, OMPC_firstprivate);
334     if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr)
335       return DVar;
336 
337     DVar.CKind = OMPC_shared;
338     return DVar;
339   }
340 
341   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
342   // in a Construct, C/C++, predetermined, p.7]
343   //  Variables with static storage duration that are declared in a scope
344   //  inside the construct are shared.
345   if (D->isStaticLocal()) {
346     DVar.CKind = OMPC_shared;
347     return DVar;
348   }
349 
350   // Explicitly specified attributes and local variables with predetermined
351   // attributes.
352   if (Stack.back().SharingMap.count(D)) {
353     DVar.RefExpr = Stack.back().SharingMap[D].RefExpr;
354     DVar.CKind = Stack.back().SharingMap[D].Attributes;
355   }
356 
357   return DVar;
358 }
359 
360 DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(VarDecl *D) {
361   return getDSA(std::next(Stack.rbegin()), D);
362 }
363 
364 DSAStackTy::DSAVarData DSAStackTy::hasDSA(VarDecl *D, OpenMPClauseKind CKind,
365                                           OpenMPDirectiveKind DKind) {
366   for (StackTy::reverse_iterator I = std::next(Stack.rbegin()),
367                                  E = std::prev(Stack.rend());
368        I != E; ++I) {
369     if (DKind != OMPD_unknown && DKind != I->Directive) continue;
370     DSAVarData DVar = getDSA(I, D);
371     if (DVar.CKind == CKind)
372       return DVar;
373   }
374   return DSAVarData();
375 }
376 
377 void Sema::InitDataSharingAttributesStack() {
378   VarDataSharingAttributesStack = new DSAStackTy(*this);
379 }
380 
381 #define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
382 
383 void Sema::DestroyDataSharingAttributesStack() {
384   delete DSAStack;
385 }
386 
387 void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
388                                const DeclarationNameInfo &DirName,
389                                Scope *CurScope) {
390   DSAStack->push(DKind, DirName, CurScope);
391   PushExpressionEvaluationContext(PotentiallyEvaluated);
392 }
393 
394 void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
395   DSAStack->pop();
396   DiscardCleanupsInEvaluationContext();
397   PopExpressionEvaluationContext();
398 }
399 
400 namespace {
401 
402 class VarDeclFilterCCC : public CorrectionCandidateCallback {
403 private:
404   Sema &Actions;
405 public:
406   VarDeclFilterCCC(Sema &S) : Actions(S) { }
407   bool ValidateCandidate(const TypoCorrection &Candidate) override {
408     NamedDecl *ND = Candidate.getCorrectionDecl();
409     if (VarDecl *VD = dyn_cast_or_null<VarDecl>(ND)) {
410       return VD->hasGlobalStorage() &&
411              Actions.isDeclInScope(ND, Actions.getCurLexicalContext(),
412                                    Actions.getCurScope());
413     }
414     return false;
415   }
416 };
417 }
418 
419 ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
420                                          CXXScopeSpec &ScopeSpec,
421                                          const DeclarationNameInfo &Id) {
422   LookupResult Lookup(*this, Id, LookupOrdinaryName);
423   LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
424 
425   if (Lookup.isAmbiguous())
426     return ExprError();
427 
428   VarDecl *VD;
429   if (!Lookup.isSingleResult()) {
430     VarDeclFilterCCC Validator(*this);
431     if (TypoCorrection Corrected = CorrectTypo(Id, LookupOrdinaryName, CurScope,
432                                                0, Validator)) {
433       diagnoseTypo(Corrected,
434                    PDiag(Lookup.empty()? diag::err_undeclared_var_use_suggest
435                                        : diag::err_omp_expected_var_arg_suggest)
436                      << Id.getName());
437       VD = Corrected.getCorrectionDeclAs<VarDecl>();
438     } else {
439       Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
440                                        : diag::err_omp_expected_var_arg)
441           << Id.getName();
442       return ExprError();
443     }
444   } else {
445     if (!(VD = Lookup.getAsSingle<VarDecl>())) {
446       Diag(Id.getLoc(), diag::err_omp_expected_var_arg)
447         << Id.getName();
448       Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
449       return ExprError();
450     }
451   }
452   Lookup.suppressDiagnostics();
453 
454   // OpenMP [2.9.2, Syntax, C/C++]
455   //   Variables must be file-scope, namespace-scope, or static block-scope.
456   if (!VD->hasGlobalStorage()) {
457     Diag(Id.getLoc(), diag::err_omp_global_var_arg)
458       << getOpenMPDirectiveName(OMPD_threadprivate)
459       << !VD->isStaticLocal();
460     bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
461                   VarDecl::DeclarationOnly;
462     Diag(VD->getLocation(),
463          IsDecl ? diag::note_previous_decl : diag::note_defined_here) << VD;
464     return ExprError();
465   }
466 
467   VarDecl *CanonicalVD = VD->getCanonicalDecl();
468   NamedDecl *ND = cast<NamedDecl>(CanonicalVD);
469   // OpenMP [2.9.2, Restrictions, C/C++, p.2]
470   //   A threadprivate directive for file-scope variables must appear outside
471   //   any definition or declaration.
472   if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
473       !getCurLexicalContext()->isTranslationUnit()) {
474     Diag(Id.getLoc(), diag::err_omp_var_scope)
475       << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
476     bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
477                   VarDecl::DeclarationOnly;
478     Diag(VD->getLocation(), IsDecl ? diag::note_previous_decl :
479                                      diag::note_defined_here) << VD;
480     return ExprError();
481   }
482   // OpenMP [2.9.2, Restrictions, C/C++, p.3]
483   //   A threadprivate directive for static class member variables must appear
484   //   in the class definition, in the same scope in which the member
485   //   variables are declared.
486   if (CanonicalVD->isStaticDataMember() &&
487       !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
488     Diag(Id.getLoc(), diag::err_omp_var_scope)
489       << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
490     bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
491                   VarDecl::DeclarationOnly;
492     Diag(VD->getLocation(), IsDecl ? diag::note_previous_decl :
493                                      diag::note_defined_here) << VD;
494     return ExprError();
495   }
496   // OpenMP [2.9.2, Restrictions, C/C++, p.4]
497   //   A threadprivate directive for namespace-scope variables must appear
498   //   outside any definition or declaration other than the namespace
499   //   definition itself.
500   if (CanonicalVD->getDeclContext()->isNamespace() &&
501       (!getCurLexicalContext()->isFileContext() ||
502        !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
503     Diag(Id.getLoc(), diag::err_omp_var_scope)
504       << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
505     bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
506                   VarDecl::DeclarationOnly;
507     Diag(VD->getLocation(), IsDecl ? diag::note_previous_decl :
508                                      diag::note_defined_here) << VD;
509     return ExprError();
510   }
511   // OpenMP [2.9.2, Restrictions, C/C++, p.6]
512   //   A threadprivate directive for static block-scope variables must appear
513   //   in the scope of the variable and not in a nested scope.
514   if (CanonicalVD->isStaticLocal() && CurScope &&
515       !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
516     Diag(Id.getLoc(), diag::err_omp_var_scope)
517       << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
518     bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
519                   VarDecl::DeclarationOnly;
520     Diag(VD->getLocation(), IsDecl ? diag::note_previous_decl :
521                                      diag::note_defined_here) << VD;
522     return ExprError();
523   }
524 
525   // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
526   //   A threadprivate directive must lexically precede all references to any
527   //   of the variables in its list.
528   if (VD->isUsed()) {
529     Diag(Id.getLoc(), diag::err_omp_var_used)
530       << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
531     return ExprError();
532   }
533 
534   QualType ExprType = VD->getType().getNonReferenceType();
535   ExprResult DE = BuildDeclRefExpr(VD, ExprType, VK_LValue, Id.getLoc());
536   return DE;
537 }
538 
539 Sema::DeclGroupPtrTy Sema::ActOnOpenMPThreadprivateDirective(
540                                 SourceLocation Loc,
541                                 ArrayRef<Expr *> VarList) {
542   if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
543     CurContext->addDecl(D);
544     return DeclGroupPtrTy::make(DeclGroupRef(D));
545   }
546   return DeclGroupPtrTy();
547 }
548 
549 OMPThreadPrivateDecl *Sema::CheckOMPThreadPrivateDecl(
550                                  SourceLocation Loc,
551                                  ArrayRef<Expr *> VarList) {
552   SmallVector<Expr *, 8> Vars;
553   for (ArrayRef<Expr *>::iterator I = VarList.begin(),
554                                          E = VarList.end();
555        I != E; ++I) {
556     DeclRefExpr *DE = cast<DeclRefExpr>(*I);
557     VarDecl *VD = cast<VarDecl>(DE->getDecl());
558     SourceLocation ILoc = DE->getExprLoc();
559 
560     // OpenMP [2.9.2, Restrictions, C/C++, p.10]
561     //   A threadprivate variable must not have an incomplete type.
562     if (RequireCompleteType(ILoc, VD->getType(),
563                             diag::err_omp_threadprivate_incomplete_type)) {
564       continue;
565     }
566 
567     // OpenMP [2.9.2, Restrictions, C/C++, p.10]
568     //   A threadprivate variable must not have a reference type.
569     if (VD->getType()->isReferenceType()) {
570       Diag(ILoc, diag::err_omp_ref_type_arg)
571         << getOpenMPDirectiveName(OMPD_threadprivate)
572         << VD->getType();
573       bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
574                     VarDecl::DeclarationOnly;
575       Diag(VD->getLocation(), IsDecl ? diag::note_previous_decl :
576                                        diag::note_defined_here) << VD;
577       continue;
578     }
579 
580     // Check if this is a TLS variable.
581     if (VD->getTLSKind()) {
582       Diag(ILoc, diag::err_omp_var_thread_local) << VD;
583       bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
584                     VarDecl::DeclarationOnly;
585       Diag(VD->getLocation(), IsDecl ? diag::note_previous_decl :
586                                        diag::note_defined_here) << VD;
587       continue;
588     }
589 
590     Vars.push_back(*I);
591     DSAStack->addDSA(VD, DE, OMPC_threadprivate);
592   }
593   OMPThreadPrivateDecl *D = 0;
594   if (!Vars.empty()) {
595     D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
596                                      Vars);
597     D->setAccess(AS_public);
598   }
599   return D;
600 }
601 
602 namespace {
603 class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> {
604   DSAStackTy *Stack;
605   Sema &Actions;
606   bool ErrorFound;
607   CapturedStmt *CS;
608   llvm::SmallVector<Expr *, 8> ImplicitFirstprivate;
609 public:
610   void VisitDeclRefExpr(DeclRefExpr *E) {
611     if(VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
612       // Skip internally declared variables.
613       if (VD->isLocalVarDecl() && !CS->capturesVariable(VD)) return;
614 
615       SourceLocation ELoc = E->getExprLoc();
616 
617       OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
618       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD);
619       if (DVar.CKind != OMPC_unknown) {
620         if (DKind == OMPD_task && DVar.CKind != OMPC_shared &&
621             !Stack->isThreadPrivate(VD) && !DVar.RefExpr)
622           ImplicitFirstprivate.push_back(DVar.RefExpr);
623         return;
624       }
625       // The default(none) clause requires that each variable that is referenced
626       // in the construct, and does not have a predetermined data-sharing
627       // attribute, must have its data-sharing attribute explicitly determined
628       // by being listed in a data-sharing attribute clause.
629       if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
630           (DKind == OMPD_parallel || DKind == OMPD_task)) {
631         ErrorFound = true;
632         Actions.Diag(ELoc, diag::err_omp_no_dsa_for_variable) << VD;
633         return;
634       }
635 
636       // OpenMP [2.9.3.6, Restrictions, p.2]
637       //  A list item that appears in a reduction clause of the innermost
638       //  enclosing worksharing or parallel construct may not be accessed in an
639       //  explicit task.
640       // TODO:
641 
642       // Define implicit data-sharing attributes for task.
643       DVar = Stack->getImplicitDSA(VD);
644       if (DKind == OMPD_task && DVar.CKind != OMPC_shared)
645         ImplicitFirstprivate.push_back(DVar.RefExpr);
646     }
647   }
648   void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
649     for (ArrayRef<OMPClause *>::iterator I = S->clauses().begin(),
650                                          E = S->clauses().end();
651          I != E; ++I)
652       if (OMPClause *C = *I)
653         for (StmtRange R = C->children(); R; ++R)
654           if (Stmt *Child = *R)
655             Visit(Child);
656   }
657   void VisitStmt(Stmt *S) {
658     for (Stmt::child_iterator I = S->child_begin(), E = S->child_end();
659          I != E; ++I)
660       if (Stmt *Child = *I)
661         if (!isa<OMPExecutableDirective>(Child))
662           Visit(Child);
663     }
664 
665   bool isErrorFound() { return ErrorFound; }
666   ArrayRef<Expr *> getImplicitFirstprivate() { return ImplicitFirstprivate; }
667 
668   DSAAttrChecker(DSAStackTy *S, Sema &Actions, CapturedStmt *CS)
669     : Stack(S), Actions(Actions), ErrorFound(false), CS(CS) { }
670 };
671 }
672 
673 StmtResult Sema::ActOnOpenMPExecutableDirective(OpenMPDirectiveKind Kind,
674                                                 ArrayRef<OMPClause *> Clauses,
675                                                 Stmt *AStmt,
676                                                 SourceLocation StartLoc,
677                                                 SourceLocation EndLoc) {
678   assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
679 
680   StmtResult Res = StmtError();
681 
682   // Check default data sharing attributes for referenced variables.
683   DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
684   DSAChecker.Visit(cast<CapturedStmt>(AStmt)->getCapturedStmt());
685   if (DSAChecker.isErrorFound())
686     return StmtError();
687   // Generate list of implicitly defined firstprivate variables.
688   llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
689   ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
690 
691   bool ErrorFound = false;
692   if (!DSAChecker.getImplicitFirstprivate().empty()) {
693     if (OMPClause *Implicit =
694          ActOnOpenMPFirstprivateClause(DSAChecker.getImplicitFirstprivate(),
695                                        SourceLocation(), SourceLocation(),
696                                        SourceLocation())) {
697       ClausesWithImplicit.push_back(Implicit);
698       ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
699                                     DSAChecker.getImplicitFirstprivate().size();
700     } else
701       ErrorFound = true;
702   }
703 
704   switch (Kind) {
705   case OMPD_parallel:
706     Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt,
707                                        StartLoc, EndLoc);
708     break;
709   case OMPD_simd:
710     Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt,
711                                    StartLoc, EndLoc);
712     break;
713   case OMPD_threadprivate:
714   case OMPD_task:
715     llvm_unreachable("OpenMP Directive is not allowed");
716   case OMPD_unknown:
717   case NUM_OPENMP_DIRECTIVES:
718     llvm_unreachable("Unknown OpenMP directive");
719   }
720 
721   if (ErrorFound) return StmtError();
722   return Res;
723 }
724 
725 StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
726                                               Stmt *AStmt,
727                                               SourceLocation StartLoc,
728                                               SourceLocation EndLoc) {
729   getCurFunction()->setHasBranchProtectedScope();
730 
731   return Owned(OMPParallelDirective::Create(Context, StartLoc, EndLoc,
732                                             Clauses, AStmt));
733 }
734 
735 StmtResult Sema::ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses,
736                                           Stmt *AStmt,
737                                           SourceLocation StartLoc,
738                                           SourceLocation EndLoc) {
739   Stmt *CStmt = AStmt;
740   while (CapturedStmt *CS = dyn_cast_or_null<CapturedStmt>(CStmt))
741     CStmt = CS->getCapturedStmt();
742   while (AttributedStmt *AS = dyn_cast_or_null<AttributedStmt>(CStmt))
743     CStmt = AS->getSubStmt();
744   ForStmt *For = dyn_cast<ForStmt>(CStmt);
745   if (!For) {
746     Diag(CStmt->getLocStart(), diag::err_omp_not_for)
747       << getOpenMPDirectiveName(OMPD_simd);
748     return StmtError();
749   }
750 
751   // FIXME: Checking loop canonical form, collapsing etc.
752 
753   getCurFunction()->setHasBranchProtectedScope();
754   return Owned(OMPSimdDirective::Create(Context, StartLoc, EndLoc,
755                                         Clauses, AStmt));
756 }
757 
758 OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind,
759                                              Expr *Expr,
760                                              SourceLocation StartLoc,
761                                              SourceLocation LParenLoc,
762                                              SourceLocation EndLoc) {
763   OMPClause *Res = 0;
764   switch (Kind) {
765   case OMPC_if:
766     Res = ActOnOpenMPIfClause(Expr, StartLoc, LParenLoc, EndLoc);
767     break;
768   case OMPC_num_threads:
769     Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
770     break;
771   case OMPC_safelen:
772     Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
773     break;
774   case OMPC_default:
775   case OMPC_private:
776   case OMPC_firstprivate:
777   case OMPC_shared:
778   case OMPC_copyin:
779   case OMPC_threadprivate:
780   case OMPC_unknown:
781   case NUM_OPENMP_CLAUSES:
782     llvm_unreachable("Clause is not allowed.");
783   }
784   return Res;
785 }
786 
787 OMPClause *Sema::ActOnOpenMPIfClause(Expr *Condition,
788                                      SourceLocation StartLoc,
789                                      SourceLocation LParenLoc,
790                                      SourceLocation EndLoc) {
791   Expr *ValExpr = Condition;
792   if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
793       !Condition->isInstantiationDependent() &&
794       !Condition->containsUnexpandedParameterPack()) {
795     ExprResult Val = ActOnBooleanCondition(DSAStack->getCurScope(),
796                                            Condition->getExprLoc(),
797                                            Condition);
798     if (Val.isInvalid())
799       return 0;
800 
801     ValExpr = Val.take();
802   }
803 
804   return new (Context) OMPIfClause(ValExpr, StartLoc, LParenLoc, EndLoc);
805 }
806 
807 ExprResult Sema::PerformImplicitIntegerConversion(SourceLocation Loc,
808                                                   Expr *Op) {
809   if (!Op)
810     return ExprError();
811 
812   class IntConvertDiagnoser : public ICEConvertDiagnoser {
813   public:
814     IntConvertDiagnoser()
815         : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
816                               false, true) {}
817     SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
818                                          QualType T) override {
819       return S.Diag(Loc, diag::err_omp_not_integral) << T;
820     }
821     SemaDiagnosticBuilder diagnoseIncomplete(
822         Sema &S, SourceLocation Loc, QualType T) override {
823       return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
824     }
825     SemaDiagnosticBuilder diagnoseExplicitConv(
826         Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
827       return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
828     }
829     SemaDiagnosticBuilder noteExplicitConv(
830         Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
831       return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
832                << ConvTy->isEnumeralType() << ConvTy;
833     }
834     SemaDiagnosticBuilder diagnoseAmbiguous(
835         Sema &S, SourceLocation Loc, QualType T) override {
836       return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
837     }
838     SemaDiagnosticBuilder noteAmbiguous(
839         Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
840       return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
841                << ConvTy->isEnumeralType() << ConvTy;
842     }
843     SemaDiagnosticBuilder diagnoseConversion(
844         Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
845       llvm_unreachable("conversion functions are permitted");
846     }
847   } ConvertDiagnoser;
848   return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
849 }
850 
851 OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
852                                              SourceLocation StartLoc,
853                                              SourceLocation LParenLoc,
854                                              SourceLocation EndLoc) {
855   Expr *ValExpr = NumThreads;
856   if (!NumThreads->isValueDependent() && !NumThreads->isTypeDependent() &&
857       !NumThreads->isInstantiationDependent() &&
858       !NumThreads->containsUnexpandedParameterPack()) {
859     SourceLocation NumThreadsLoc = NumThreads->getLocStart();
860     ExprResult Val =
861         PerformImplicitIntegerConversion(NumThreadsLoc, NumThreads);
862     if (Val.isInvalid())
863       return 0;
864 
865     ValExpr = Val.take();
866 
867     // OpenMP [2.5, Restrictions]
868     //  The num_threads expression must evaluate to a positive integer value.
869     llvm::APSInt Result;
870     if (ValExpr->isIntegerConstantExpr(Result, Context) &&
871         Result.isSigned() && !Result.isStrictlyPositive()) {
872       Diag(NumThreadsLoc, diag::err_omp_negative_expression_in_clause)
873           << "num_threads" << NumThreads->getSourceRange();
874       return 0;
875     }
876   }
877 
878   return new (Context) OMPNumThreadsClause(ValExpr, StartLoc, LParenLoc,
879                                            EndLoc);
880 }
881 
882 ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
883                                                        OpenMPClauseKind CKind) {
884   if (!E)
885     return ExprError();
886   if (E->isValueDependent() || E->isTypeDependent() ||
887       E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
888     return Owned(E);
889   llvm::APSInt Result;
890   ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
891   if (ICE.isInvalid())
892     return ExprError();
893   if (!Result.isStrictlyPositive()) {
894     Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
895         << getOpenMPClauseName(CKind) << E->getSourceRange();
896     return ExprError();
897   }
898   return ICE;
899 }
900 
901 OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
902                                           SourceLocation LParenLoc,
903                                           SourceLocation EndLoc) {
904   // OpenMP [2.8.1, simd construct, Description]
905   // The parameter of the safelen clause must be a constant
906   // positive integer expression.
907   ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
908   if (Safelen.isInvalid())
909     return 0;
910   return new (Context)
911       OMPSafelenClause(Safelen.take(), StartLoc, LParenLoc, EndLoc);
912 }
913 
914 OMPClause *Sema::ActOnOpenMPSimpleClause(OpenMPClauseKind Kind,
915                                          unsigned Argument,
916                                          SourceLocation ArgumentLoc,
917                                          SourceLocation StartLoc,
918                                          SourceLocation LParenLoc,
919                                          SourceLocation EndLoc) {
920   OMPClause *Res = 0;
921   switch (Kind) {
922   case OMPC_default:
923     Res =
924       ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
925                                ArgumentLoc, StartLoc, LParenLoc, EndLoc);
926     break;
927   case OMPC_if:
928   case OMPC_num_threads:
929   case OMPC_safelen:
930   case OMPC_private:
931   case OMPC_firstprivate:
932   case OMPC_shared:
933   case OMPC_copyin:
934   case OMPC_threadprivate:
935   case OMPC_unknown:
936   case NUM_OPENMP_CLAUSES:
937     llvm_unreachable("Clause is not allowed.");
938   }
939   return Res;
940 }
941 
942 OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
943                                           SourceLocation KindKwLoc,
944                                           SourceLocation StartLoc,
945                                           SourceLocation LParenLoc,
946                                           SourceLocation EndLoc) {
947   if (Kind == OMPC_DEFAULT_unknown) {
948     std::string Values;
949     static_assert(NUM_OPENMP_DEFAULT_KINDS > 1,
950                   "NUM_OPENMP_DEFAULT_KINDS not greater than 1");
951     std::string Sep(", ");
952     for (unsigned i = OMPC_DEFAULT_unknown + 1;
953          i < NUM_OPENMP_DEFAULT_KINDS; ++i) {
954       Values += "'";
955       Values += getOpenMPSimpleClauseTypeName(OMPC_default, i);
956       Values += "'";
957       switch (i) {
958       case NUM_OPENMP_DEFAULT_KINDS - 2:
959         Values += " or ";
960         break;
961       case NUM_OPENMP_DEFAULT_KINDS - 1:
962         break;
963       default:
964         Values += Sep;
965         break;
966       }
967     }
968     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
969       << Values << getOpenMPClauseName(OMPC_default);
970     return 0;
971   }
972   switch (Kind) {
973   case OMPC_DEFAULT_none:
974     DSAStack->setDefaultDSANone();
975     break;
976   case OMPC_DEFAULT_shared:
977     DSAStack->setDefaultDSAShared();
978     break;
979   case OMPC_DEFAULT_unknown:
980   case NUM_OPENMP_DEFAULT_KINDS:
981     llvm_unreachable("Clause kind is not allowed.");
982     break;
983   }
984   return new (Context) OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc,
985                                         EndLoc);
986 }
987 
988 OMPClause *Sema::ActOnOpenMPVarListClause(OpenMPClauseKind Kind,
989                                           ArrayRef<Expr *> VarList,
990                                           SourceLocation StartLoc,
991                                           SourceLocation LParenLoc,
992                                           SourceLocation EndLoc) {
993   OMPClause *Res = 0;
994   switch (Kind) {
995   case OMPC_private:
996     Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
997     break;
998   case OMPC_firstprivate:
999     Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
1000     break;
1001   case OMPC_shared:
1002     Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
1003     break;
1004   case OMPC_copyin:
1005     Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
1006     break;
1007   case OMPC_if:
1008   case OMPC_num_threads:
1009   case OMPC_safelen:
1010   case OMPC_default:
1011   case OMPC_threadprivate:
1012   case OMPC_unknown:
1013   case NUM_OPENMP_CLAUSES:
1014     llvm_unreachable("Clause is not allowed.");
1015   }
1016   return Res;
1017 }
1018 
1019 OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
1020                                           SourceLocation StartLoc,
1021                                           SourceLocation LParenLoc,
1022                                           SourceLocation EndLoc) {
1023   SmallVector<Expr *, 8> Vars;
1024   for (ArrayRef<Expr *>::iterator I = VarList.begin(), E = VarList.end();
1025        I != E; ++I) {
1026     assert(*I && "NULL expr in OpenMP private clause.");
1027     if (isa<DependentScopeDeclRefExpr>(*I)) {
1028       // It will be analyzed later.
1029       Vars.push_back(*I);
1030       continue;
1031     }
1032 
1033     SourceLocation ELoc = (*I)->getExprLoc();
1034     // OpenMP [2.1, C/C++]
1035     //  A list item is a variable name.
1036     // OpenMP  [2.9.3.3, Restrictions, p.1]
1037     //  A variable that is part of another variable (as an array or
1038     //  structure element) cannot appear in a private clause.
1039     DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(*I);
1040     if (!DE || !isa<VarDecl>(DE->getDecl())) {
1041       Diag(ELoc, diag::err_omp_expected_var_name)
1042         << (*I)->getSourceRange();
1043       continue;
1044     }
1045     Decl *D = DE->getDecl();
1046     VarDecl *VD = cast<VarDecl>(D);
1047 
1048     QualType Type = VD->getType();
1049     if (Type->isDependentType() || Type->isInstantiationDependentType()) {
1050       // It will be analyzed later.
1051       Vars.push_back(DE);
1052       continue;
1053     }
1054 
1055     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
1056     //  A variable that appears in a private clause must not have an incomplete
1057     //  type or a reference type.
1058     if (RequireCompleteType(ELoc, Type,
1059                             diag::err_omp_private_incomplete_type)) {
1060       continue;
1061     }
1062     if (Type->isReferenceType()) {
1063       Diag(ELoc, diag::err_omp_clause_ref_type_arg)
1064         << getOpenMPClauseName(OMPC_private) << Type;
1065       bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
1066                     VarDecl::DeclarationOnly;
1067       Diag(VD->getLocation(), IsDecl ? diag::note_previous_decl :
1068                                        diag::note_defined_here) << VD;
1069       continue;
1070     }
1071 
1072     // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
1073     //  A variable of class type (or array thereof) that appears in a private
1074     //  clause requires an accesible, unambiguous default constructor for the
1075     //  class type.
1076     while (Type.getNonReferenceType()->isArrayType()) {
1077       Type = cast<ArrayType>(
1078                  Type.getNonReferenceType().getTypePtr())->getElementType();
1079     }
1080     CXXRecordDecl *RD = getLangOpts().CPlusPlus ?
1081                           Type.getNonReferenceType()->getAsCXXRecordDecl() : 0;
1082     if (RD) {
1083       CXXConstructorDecl *CD = LookupDefaultConstructor(RD);
1084       PartialDiagnostic PD =
1085         PartialDiagnostic(PartialDiagnostic::NullDiagnostic());
1086       if (!CD ||
1087           CheckConstructorAccess(ELoc, CD,
1088                                  InitializedEntity::InitializeTemporary(Type),
1089                                  CD->getAccess(), PD) == AR_inaccessible ||
1090           CD->isDeleted()) {
1091         Diag(ELoc, diag::err_omp_required_method)
1092              << getOpenMPClauseName(OMPC_private) << 0;
1093         bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
1094                       VarDecl::DeclarationOnly;
1095         Diag(VD->getLocation(), IsDecl ? diag::note_previous_decl :
1096                                          diag::note_defined_here) << VD;
1097         Diag(RD->getLocation(), diag::note_previous_decl) << RD;
1098         continue;
1099       }
1100       MarkFunctionReferenced(ELoc, CD);
1101       DiagnoseUseOfDecl(CD, ELoc);
1102 
1103       CXXDestructorDecl *DD = RD->getDestructor();
1104       if (DD) {
1105         if (CheckDestructorAccess(ELoc, DD, PD) == AR_inaccessible ||
1106             DD->isDeleted()) {
1107           Diag(ELoc, diag::err_omp_required_method)
1108                << getOpenMPClauseName(OMPC_private) << 4;
1109           bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
1110                         VarDecl::DeclarationOnly;
1111           Diag(VD->getLocation(), IsDecl ? diag::note_previous_decl :
1112                                            diag::note_defined_here) << VD;
1113           Diag(RD->getLocation(), diag::note_previous_decl) << RD;
1114           continue;
1115         }
1116         MarkFunctionReferenced(ELoc, DD);
1117         DiagnoseUseOfDecl(DD, ELoc);
1118       }
1119     }
1120 
1121     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1122     // in a Construct]
1123     //  Variables with the predetermined data-sharing attributes may not be
1124     //  listed in data-sharing attributes clauses, except for the cases
1125     //  listed below. For these exceptions only, listing a predetermined
1126     //  variable in a data-sharing attribute clause is allowed and overrides
1127     //  the variable's predetermined data-sharing attributes.
1128     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD);
1129     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
1130       Diag(ELoc, diag::err_omp_wrong_dsa)
1131          << getOpenMPClauseName(DVar.CKind)
1132          << getOpenMPClauseName(OMPC_private);
1133       if (DVar.RefExpr) {
1134         Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
1135              << getOpenMPClauseName(DVar.CKind);
1136       } else {
1137         Diag(VD->getLocation(), diag::note_omp_predetermined_dsa)
1138              << getOpenMPClauseName(DVar.CKind);
1139       }
1140       continue;
1141     }
1142 
1143     DSAStack->addDSA(VD, DE, OMPC_private);
1144     Vars.push_back(DE);
1145   }
1146 
1147   if (Vars.empty()) return 0;
1148 
1149   return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
1150 }
1151 
1152 OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
1153                                                SourceLocation StartLoc,
1154                                                SourceLocation LParenLoc,
1155                                                SourceLocation EndLoc) {
1156   SmallVector<Expr *, 8> Vars;
1157   for (ArrayRef<Expr *>::iterator I = VarList.begin(), E = VarList.end();
1158        I != E; ++I) {
1159     assert(*I && "NULL expr in OpenMP firstprivate clause.");
1160     if (isa<DependentScopeDeclRefExpr>(*I)) {
1161       // It will be analyzed later.
1162       Vars.push_back(*I);
1163       continue;
1164     }
1165 
1166     SourceLocation ELoc = (*I)->getExprLoc();
1167     // OpenMP [2.1, C/C++]
1168     //  A list item is a variable name.
1169     // OpenMP  [2.9.3.3, Restrictions, p.1]
1170     //  A variable that is part of another variable (as an array or
1171     //  structure element) cannot appear in a private clause.
1172     DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(*I);
1173     if (!DE || !isa<VarDecl>(DE->getDecl())) {
1174       Diag(ELoc, diag::err_omp_expected_var_name)
1175         << (*I)->getSourceRange();
1176       continue;
1177     }
1178     Decl *D = DE->getDecl();
1179     VarDecl *VD = cast<VarDecl>(D);
1180 
1181     QualType Type = VD->getType();
1182     if (Type->isDependentType() || Type->isInstantiationDependentType()) {
1183       // It will be analyzed later.
1184       Vars.push_back(DE);
1185       continue;
1186     }
1187 
1188     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
1189     //  A variable that appears in a private clause must not have an incomplete
1190     //  type or a reference type.
1191     if (RequireCompleteType(ELoc, Type,
1192                             diag::err_omp_firstprivate_incomplete_type)) {
1193       continue;
1194     }
1195     if (Type->isReferenceType()) {
1196       Diag(ELoc, diag::err_omp_clause_ref_type_arg)
1197         << getOpenMPClauseName(OMPC_firstprivate) << Type;
1198       bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
1199                     VarDecl::DeclarationOnly;
1200       Diag(VD->getLocation(), IsDecl ? diag::note_previous_decl :
1201                                        diag::note_defined_here) << VD;
1202       continue;
1203     }
1204 
1205     // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
1206     //  A variable of class type (or array thereof) that appears in a private
1207     //  clause requires an accesible, unambiguous copy constructor for the
1208     //  class type.
1209     Type = Context.getBaseElementType(Type);
1210     CXXRecordDecl *RD = getLangOpts().CPlusPlus ?
1211                           Type.getNonReferenceType()->getAsCXXRecordDecl() : 0;
1212     if (RD) {
1213       CXXConstructorDecl *CD = LookupCopyingConstructor(RD, 0);
1214       PartialDiagnostic PD =
1215         PartialDiagnostic(PartialDiagnostic::NullDiagnostic());
1216       if (!CD ||
1217           CheckConstructorAccess(ELoc, CD,
1218                                  InitializedEntity::InitializeTemporary(Type),
1219                                  CD->getAccess(), PD) == AR_inaccessible ||
1220           CD->isDeleted()) {
1221         Diag(ELoc, diag::err_omp_required_method)
1222              << getOpenMPClauseName(OMPC_firstprivate) << 1;
1223         bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
1224                       VarDecl::DeclarationOnly;
1225         Diag(VD->getLocation(), IsDecl ? diag::note_previous_decl :
1226                                          diag::note_defined_here) << VD;
1227         Diag(RD->getLocation(), diag::note_previous_decl) << RD;
1228         continue;
1229       }
1230       MarkFunctionReferenced(ELoc, CD);
1231       DiagnoseUseOfDecl(CD, ELoc);
1232 
1233       CXXDestructorDecl *DD = RD->getDestructor();
1234       if (DD) {
1235         if (CheckDestructorAccess(ELoc, DD, PD) == AR_inaccessible ||
1236             DD->isDeleted()) {
1237           Diag(ELoc, diag::err_omp_required_method)
1238                << getOpenMPClauseName(OMPC_firstprivate) << 4;
1239           bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
1240                         VarDecl::DeclarationOnly;
1241           Diag(VD->getLocation(), IsDecl ? diag::note_previous_decl :
1242                                            diag::note_defined_here) << VD;
1243           Diag(RD->getLocation(), diag::note_previous_decl) << RD;
1244           continue;
1245         }
1246         MarkFunctionReferenced(ELoc, DD);
1247         DiagnoseUseOfDecl(DD, ELoc);
1248       }
1249     }
1250 
1251     // If StartLoc and EndLoc are invalid - this is an implicit firstprivate
1252     // variable and it was checked already.
1253     if (StartLoc.isValid() && EndLoc.isValid()) {
1254       DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD);
1255       Type = Type.getNonReferenceType().getCanonicalType();
1256       bool IsConstant = Type.isConstant(Context);
1257       Type = Context.getBaseElementType(Type);
1258       // OpenMP [2.4.13, Data-sharing Attribute Clauses]
1259       //  A list item that specifies a given variable may not appear in more
1260       // than one clause on the same directive, except that a variable may be
1261       //  specified in both firstprivate and lastprivate clauses.
1262       //  TODO: add processing for lastprivate.
1263       if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
1264           DVar.RefExpr) {
1265         Diag(ELoc, diag::err_omp_wrong_dsa)
1266            << getOpenMPClauseName(DVar.CKind)
1267            << getOpenMPClauseName(OMPC_firstprivate);
1268         Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
1269            << getOpenMPClauseName(DVar.CKind);
1270         continue;
1271       }
1272 
1273       // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1274       // in a Construct]
1275       //  Variables with the predetermined data-sharing attributes may not be
1276       //  listed in data-sharing attributes clauses, except for the cases
1277       //  listed below. For these exceptions only, listing a predetermined
1278       //  variable in a data-sharing attribute clause is allowed and overrides
1279       //  the variable's predetermined data-sharing attributes.
1280       // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1281       // in a Construct, C/C++, p.2]
1282       //  Variables with const-qualified type having no mutable member may be
1283       //  listed in a firstprivate clause, even if they are static data members.
1284       if (!(IsConstant || VD->isStaticDataMember()) && !DVar.RefExpr &&
1285           DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
1286         Diag(ELoc, diag::err_omp_wrong_dsa)
1287            << getOpenMPClauseName(DVar.CKind)
1288            << getOpenMPClauseName(OMPC_firstprivate);
1289         Diag(VD->getLocation(), diag::note_omp_predetermined_dsa)
1290            << getOpenMPClauseName(DVar.CKind);
1291         continue;
1292       }
1293 
1294       // OpenMP [2.9.3.4, Restrictions, p.2]
1295       //  A list item that is private within a parallel region must not appear
1296       //  in a firstprivate clause on a worksharing construct if any of the
1297       //  worksharing regions arising from the worksharing construct ever bind
1298       //  to any of the parallel regions arising from the parallel construct.
1299       // OpenMP [2.9.3.4, Restrictions, p.3]
1300       //  A list item that appears in a reduction clause of a parallel construct
1301       //  must not appear in a firstprivate clause on a worksharing or task
1302       //  construct if any of the worksharing or task regions arising from the
1303       //  worksharing or task construct ever bind to any of the parallel regions
1304       //  arising from the parallel construct.
1305       // OpenMP [2.9.3.4, Restrictions, p.4]
1306       //  A list item that appears in a reduction clause in worksharing
1307       //  construct must not appear in a firstprivate clause in a task construct
1308       //  encountered during execution of any of the worksharing regions arising
1309       //  from the worksharing construct.
1310       // TODO:
1311     }
1312 
1313     DSAStack->addDSA(VD, DE, OMPC_firstprivate);
1314     Vars.push_back(DE);
1315   }
1316 
1317   if (Vars.empty()) return 0;
1318 
1319   return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
1320                                        Vars);
1321 }
1322 
1323 OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
1324                                          SourceLocation StartLoc,
1325                                          SourceLocation LParenLoc,
1326                                          SourceLocation EndLoc) {
1327   SmallVector<Expr *, 8> Vars;
1328   for (ArrayRef<Expr *>::iterator I = VarList.begin(), E = VarList.end();
1329        I != E; ++I) {
1330     assert(*I && "NULL expr in OpenMP shared clause.");
1331     if (isa<DependentScopeDeclRefExpr>(*I)) {
1332       // It will be analyzed later.
1333       Vars.push_back(*I);
1334       continue;
1335     }
1336 
1337     SourceLocation ELoc = (*I)->getExprLoc();
1338     // OpenMP [2.1, C/C++]
1339     //  A list item is a variable name.
1340     // OpenMP  [2.14.3.2, Restrictions, p.1]
1341     //  A variable that is part of another variable (as an array or structure
1342     //  element) cannot appear in a shared unless it is a static data member
1343     //  of a C++ class.
1344     DeclRefExpr *DE = dyn_cast<DeclRefExpr>(*I);
1345     if (!DE || !isa<VarDecl>(DE->getDecl())) {
1346       Diag(ELoc, diag::err_omp_expected_var_name)
1347         << (*I)->getSourceRange();
1348       continue;
1349     }
1350     Decl *D = DE->getDecl();
1351     VarDecl *VD = cast<VarDecl>(D);
1352 
1353     QualType Type = VD->getType();
1354     if (Type->isDependentType() || Type->isInstantiationDependentType()) {
1355       // It will be analyzed later.
1356       Vars.push_back(DE);
1357       continue;
1358     }
1359 
1360     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1361     // in a Construct]
1362     //  Variables with the predetermined data-sharing attributes may not be
1363     //  listed in data-sharing attributes clauses, except for the cases
1364     //  listed below. For these exceptions only, listing a predetermined
1365     //  variable in a data-sharing attribute clause is allowed and overrides
1366     //  the variable's predetermined data-sharing attributes.
1367     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD);
1368     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared && DVar.RefExpr) {
1369       Diag(ELoc, diag::err_omp_wrong_dsa)
1370          << getOpenMPClauseName(DVar.CKind)
1371          << getOpenMPClauseName(OMPC_shared);
1372       Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
1373            << getOpenMPClauseName(DVar.CKind);
1374       continue;
1375     }
1376 
1377     DSAStack->addDSA(VD, DE, OMPC_shared);
1378     Vars.push_back(DE);
1379   }
1380 
1381   if (Vars.empty()) return 0;
1382 
1383   return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
1384 }
1385 
1386 OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
1387                                          SourceLocation StartLoc,
1388                                          SourceLocation LParenLoc,
1389                                          SourceLocation EndLoc) {
1390   SmallVector<Expr *, 8> Vars;
1391   for (ArrayRef<Expr *>::iterator I = VarList.begin(), E = VarList.end();
1392        I != E; ++I) {
1393     assert(*I && "NULL expr in OpenMP copyin clause.");
1394     if (isa<DependentScopeDeclRefExpr>(*I)) {
1395       // It will be analyzed later.
1396       Vars.push_back(*I);
1397       continue;
1398     }
1399 
1400     SourceLocation ELoc = (*I)->getExprLoc();
1401     // OpenMP [2.1, C/C++]
1402     //  A list item is a variable name.
1403     // OpenMP  [2.14.4.1, Restrictions, p.1]
1404     //  A list item that appears in a copyin clause must be threadprivate.
1405     DeclRefExpr *DE = dyn_cast<DeclRefExpr>(*I);
1406     if (!DE || !isa<VarDecl>(DE->getDecl())) {
1407       Diag(ELoc, diag::err_omp_expected_var_name)
1408         << (*I)->getSourceRange();
1409       continue;
1410     }
1411 
1412     Decl *D = DE->getDecl();
1413     VarDecl *VD = cast<VarDecl>(D);
1414 
1415     QualType Type = VD->getType();
1416     if (Type->isDependentType() || Type->isInstantiationDependentType()) {
1417       // It will be analyzed later.
1418       Vars.push_back(DE);
1419       continue;
1420     }
1421 
1422     // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
1423     //  A list item that appears in a copyin clause must be threadprivate.
1424     if (!DSAStack->isThreadPrivate(VD)) {
1425       Diag(ELoc, diag::err_omp_required_access)
1426            << getOpenMPClauseName(OMPC_copyin)
1427            << getOpenMPDirectiveName(OMPD_threadprivate);
1428       continue;
1429     }
1430 
1431     // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
1432     //  A variable of class type (or array thereof) that appears in a
1433     //  copyin clause requires an accesible, unambiguous copy assignment
1434     //  operator for the class type.
1435     Type = Context.getBaseElementType(Type);
1436     CXXRecordDecl *RD = getLangOpts().CPlusPlus ?
1437                           Type->getAsCXXRecordDecl() : 0;
1438     if (RD) {
1439       CXXMethodDecl *MD = LookupCopyingAssignment(RD, 0, false, 0);
1440       DeclAccessPair FoundDecl = DeclAccessPair::make(MD, MD->getAccess());
1441       if (!MD ||
1442           CheckMemberAccess(ELoc, RD, FoundDecl) == AR_inaccessible ||
1443           MD->isDeleted()) {
1444         Diag(ELoc, diag::err_omp_required_method)
1445              << getOpenMPClauseName(OMPC_copyin) << 2;
1446         bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
1447                       VarDecl::DeclarationOnly;
1448         Diag(VD->getLocation(), IsDecl ? diag::note_previous_decl :
1449                                          diag::note_defined_here) << VD;
1450         Diag(RD->getLocation(), diag::note_previous_decl) << RD;
1451         continue;
1452       }
1453       MarkFunctionReferenced(ELoc, MD);
1454       DiagnoseUseOfDecl(MD, ELoc);
1455     }
1456 
1457     DSAStack->addDSA(VD, DE, OMPC_copyin);
1458     Vars.push_back(DE);
1459   }
1460 
1461   if (Vars.empty()) return 0;
1462 
1463   return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
1464 }
1465 
1466 #undef DSAStack
1467