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