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 && I->Directive != OMPD_parallel) {
260       ++I;
261     }
262     if (I == E) return false;
263     TopScope = I->CurScope ? I->CurScope->getParent() : 0;
264     Scope *CurScope = getCurScope();
265     while (CurScope != TopScope && !CurScope->isDeclScope(D)) {
266       CurScope = CurScope->getParent();
267     }
268     return CurScope != TopScope;
269   }
270   return false;
271 }
272 
273 DSAStackTy::DSAVarData DSAStackTy::getTopDSA(VarDecl *D) {
274   DSAVarData DVar;
275 
276   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
277   // in a Construct, C/C++, predetermined, p.1]
278   //  Variables appearing in threadprivate directives are threadprivate.
279   if (D->getTLSKind() != VarDecl::TLS_None) {
280     DVar.CKind = OMPC_threadprivate;
281     return DVar;
282   }
283   if (Stack[0].SharingMap.count(D)) {
284     DVar.RefExpr = Stack[0].SharingMap[D].RefExpr;
285     DVar.CKind = OMPC_threadprivate;
286     return DVar;
287   }
288 
289   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
290   // in a Construct, C/C++, predetermined, p.1]
291   // Variables with automatic storage duration that are declared in a scope
292   // inside the construct are private.
293   OpenMPDirectiveKind Kind = getCurrentDirective();
294   if (Kind != OMPD_parallel) {
295     if (isOpenMPLocal(D, std::next(Stack.rbegin())) && D->isLocalVarDecl() &&
296         (D->getStorageClass() == SC_Auto ||
297          D->getStorageClass() == SC_None)) {
298       DVar.CKind = OMPC_private;
299       return DVar;
300     }
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, CTK_ErrorRecovery)) {
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_linear:
779   case OMPC_copyin:
780   case OMPC_threadprivate:
781   case OMPC_unknown:
782   case NUM_OPENMP_CLAUSES:
783     llvm_unreachable("Clause is not allowed.");
784   }
785   return Res;
786 }
787 
788 OMPClause *Sema::ActOnOpenMPIfClause(Expr *Condition,
789                                      SourceLocation StartLoc,
790                                      SourceLocation LParenLoc,
791                                      SourceLocation EndLoc) {
792   Expr *ValExpr = Condition;
793   if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
794       !Condition->isInstantiationDependent() &&
795       !Condition->containsUnexpandedParameterPack()) {
796     ExprResult Val = ActOnBooleanCondition(DSAStack->getCurScope(),
797                                            Condition->getExprLoc(),
798                                            Condition);
799     if (Val.isInvalid())
800       return 0;
801 
802     ValExpr = Val.take();
803   }
804 
805   return new (Context) OMPIfClause(ValExpr, StartLoc, LParenLoc, EndLoc);
806 }
807 
808 ExprResult Sema::PerformImplicitIntegerConversion(SourceLocation Loc,
809                                                   Expr *Op) {
810   if (!Op)
811     return ExprError();
812 
813   class IntConvertDiagnoser : public ICEConvertDiagnoser {
814   public:
815     IntConvertDiagnoser()
816         : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
817                               false, true) {}
818     SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
819                                          QualType T) override {
820       return S.Diag(Loc, diag::err_omp_not_integral) << T;
821     }
822     SemaDiagnosticBuilder diagnoseIncomplete(
823         Sema &S, SourceLocation Loc, QualType T) override {
824       return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
825     }
826     SemaDiagnosticBuilder diagnoseExplicitConv(
827         Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
828       return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
829     }
830     SemaDiagnosticBuilder noteExplicitConv(
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 diagnoseAmbiguous(
836         Sema &S, SourceLocation Loc, QualType T) override {
837       return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
838     }
839     SemaDiagnosticBuilder noteAmbiguous(
840         Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
841       return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
842                << ConvTy->isEnumeralType() << ConvTy;
843     }
844     SemaDiagnosticBuilder diagnoseConversion(
845         Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
846       llvm_unreachable("conversion functions are permitted");
847     }
848   } ConvertDiagnoser;
849   return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
850 }
851 
852 OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
853                                              SourceLocation StartLoc,
854                                              SourceLocation LParenLoc,
855                                              SourceLocation EndLoc) {
856   Expr *ValExpr = NumThreads;
857   if (!NumThreads->isValueDependent() && !NumThreads->isTypeDependent() &&
858       !NumThreads->isInstantiationDependent() &&
859       !NumThreads->containsUnexpandedParameterPack()) {
860     SourceLocation NumThreadsLoc = NumThreads->getLocStart();
861     ExprResult Val =
862         PerformImplicitIntegerConversion(NumThreadsLoc, NumThreads);
863     if (Val.isInvalid())
864       return 0;
865 
866     ValExpr = Val.take();
867 
868     // OpenMP [2.5, Restrictions]
869     //  The num_threads expression must evaluate to a positive integer value.
870     llvm::APSInt Result;
871     if (ValExpr->isIntegerConstantExpr(Result, Context) &&
872         Result.isSigned() && !Result.isStrictlyPositive()) {
873       Diag(NumThreadsLoc, diag::err_omp_negative_expression_in_clause)
874           << "num_threads" << NumThreads->getSourceRange();
875       return 0;
876     }
877   }
878 
879   return new (Context) OMPNumThreadsClause(ValExpr, StartLoc, LParenLoc,
880                                            EndLoc);
881 }
882 
883 ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
884                                                        OpenMPClauseKind CKind) {
885   if (!E)
886     return ExprError();
887   if (E->isValueDependent() || E->isTypeDependent() ||
888       E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
889     return Owned(E);
890   llvm::APSInt Result;
891   ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
892   if (ICE.isInvalid())
893     return ExprError();
894   if (!Result.isStrictlyPositive()) {
895     Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
896         << getOpenMPClauseName(CKind) << E->getSourceRange();
897     return ExprError();
898   }
899   return ICE;
900 }
901 
902 OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
903                                           SourceLocation LParenLoc,
904                                           SourceLocation EndLoc) {
905   // OpenMP [2.8.1, simd construct, Description]
906   // The parameter of the safelen clause must be a constant
907   // positive integer expression.
908   ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
909   if (Safelen.isInvalid())
910     return 0;
911   return new (Context)
912       OMPSafelenClause(Safelen.take(), StartLoc, LParenLoc, EndLoc);
913 }
914 
915 OMPClause *Sema::ActOnOpenMPSimpleClause(OpenMPClauseKind Kind,
916                                          unsigned Argument,
917                                          SourceLocation ArgumentLoc,
918                                          SourceLocation StartLoc,
919                                          SourceLocation LParenLoc,
920                                          SourceLocation EndLoc) {
921   OMPClause *Res = 0;
922   switch (Kind) {
923   case OMPC_default:
924     Res =
925       ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
926                                ArgumentLoc, StartLoc, LParenLoc, EndLoc);
927     break;
928   case OMPC_if:
929   case OMPC_num_threads:
930   case OMPC_safelen:
931   case OMPC_private:
932   case OMPC_firstprivate:
933   case OMPC_shared:
934   case OMPC_linear:
935   case OMPC_copyin:
936   case OMPC_threadprivate:
937   case OMPC_unknown:
938   case NUM_OPENMP_CLAUSES:
939     llvm_unreachable("Clause is not allowed.");
940   }
941   return Res;
942 }
943 
944 OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
945                                           SourceLocation KindKwLoc,
946                                           SourceLocation StartLoc,
947                                           SourceLocation LParenLoc,
948                                           SourceLocation EndLoc) {
949   if (Kind == OMPC_DEFAULT_unknown) {
950     std::string Values;
951     static_assert(NUM_OPENMP_DEFAULT_KINDS > 1,
952                   "NUM_OPENMP_DEFAULT_KINDS not greater than 1");
953     std::string Sep(", ");
954     for (unsigned i = OMPC_DEFAULT_unknown + 1;
955          i < NUM_OPENMP_DEFAULT_KINDS; ++i) {
956       Values += "'";
957       Values += getOpenMPSimpleClauseTypeName(OMPC_default, i);
958       Values += "'";
959       switch (i) {
960       case NUM_OPENMP_DEFAULT_KINDS - 2:
961         Values += " or ";
962         break;
963       case NUM_OPENMP_DEFAULT_KINDS - 1:
964         break;
965       default:
966         Values += Sep;
967         break;
968       }
969     }
970     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
971       << Values << getOpenMPClauseName(OMPC_default);
972     return 0;
973   }
974   switch (Kind) {
975   case OMPC_DEFAULT_none:
976     DSAStack->setDefaultDSANone();
977     break;
978   case OMPC_DEFAULT_shared:
979     DSAStack->setDefaultDSAShared();
980     break;
981   case OMPC_DEFAULT_unknown:
982   case NUM_OPENMP_DEFAULT_KINDS:
983     llvm_unreachable("Clause kind is not allowed.");
984     break;
985   }
986   return new (Context) OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc,
987                                         EndLoc);
988 }
989 
990 OMPClause *Sema::ActOnOpenMPVarListClause(OpenMPClauseKind Kind,
991                                           ArrayRef<Expr *> VarList,
992                                           Expr *TailExpr,
993                                           SourceLocation StartLoc,
994                                           SourceLocation LParenLoc,
995                                           SourceLocation ColonLoc,
996                                           SourceLocation EndLoc) {
997   OMPClause *Res = 0;
998   switch (Kind) {
999   case OMPC_private:
1000     Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
1001     break;
1002   case OMPC_firstprivate:
1003     Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
1004     break;
1005   case OMPC_shared:
1006     Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
1007     break;
1008   case OMPC_linear:
1009     Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
1010                                   ColonLoc, EndLoc);
1011     break;
1012   case OMPC_copyin:
1013     Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
1014     break;
1015   case OMPC_if:
1016   case OMPC_num_threads:
1017   case OMPC_safelen:
1018   case OMPC_default:
1019   case OMPC_threadprivate:
1020   case OMPC_unknown:
1021   case NUM_OPENMP_CLAUSES:
1022     llvm_unreachable("Clause is not allowed.");
1023   }
1024   return Res;
1025 }
1026 
1027 OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
1028                                           SourceLocation StartLoc,
1029                                           SourceLocation LParenLoc,
1030                                           SourceLocation EndLoc) {
1031   SmallVector<Expr *, 8> Vars;
1032   for (ArrayRef<Expr *>::iterator I = VarList.begin(), E = VarList.end();
1033        I != E; ++I) {
1034     assert(*I && "NULL expr in OpenMP private clause.");
1035     if (isa<DependentScopeDeclRefExpr>(*I)) {
1036       // It will be analyzed later.
1037       Vars.push_back(*I);
1038       continue;
1039     }
1040 
1041     SourceLocation ELoc = (*I)->getExprLoc();
1042     // OpenMP [2.1, C/C++]
1043     //  A list item is a variable name.
1044     // OpenMP  [2.9.3.3, Restrictions, p.1]
1045     //  A variable that is part of another variable (as an array or
1046     //  structure element) cannot appear in a private clause.
1047     DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(*I);
1048     if (!DE || !isa<VarDecl>(DE->getDecl())) {
1049       Diag(ELoc, diag::err_omp_expected_var_name)
1050         << (*I)->getSourceRange();
1051       continue;
1052     }
1053     Decl *D = DE->getDecl();
1054     VarDecl *VD = cast<VarDecl>(D);
1055 
1056     QualType Type = VD->getType();
1057     if (Type->isDependentType() || Type->isInstantiationDependentType()) {
1058       // It will be analyzed later.
1059       Vars.push_back(DE);
1060       continue;
1061     }
1062 
1063     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
1064     //  A variable that appears in a private clause must not have an incomplete
1065     //  type or a reference type.
1066     if (RequireCompleteType(ELoc, Type,
1067                             diag::err_omp_private_incomplete_type)) {
1068       continue;
1069     }
1070     if (Type->isReferenceType()) {
1071       Diag(ELoc, diag::err_omp_clause_ref_type_arg)
1072         << getOpenMPClauseName(OMPC_private) << Type;
1073       bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
1074                     VarDecl::DeclarationOnly;
1075       Diag(VD->getLocation(), IsDecl ? diag::note_previous_decl :
1076                                        diag::note_defined_here) << VD;
1077       continue;
1078     }
1079 
1080     // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
1081     //  A variable of class type (or array thereof) that appears in a private
1082     //  clause requires an accesible, unambiguous default constructor for the
1083     //  class type.
1084     while (Type.getNonReferenceType()->isArrayType()) {
1085       Type = cast<ArrayType>(
1086                  Type.getNonReferenceType().getTypePtr())->getElementType();
1087     }
1088     CXXRecordDecl *RD = getLangOpts().CPlusPlus ?
1089                           Type.getNonReferenceType()->getAsCXXRecordDecl() : 0;
1090     if (RD) {
1091       CXXConstructorDecl *CD = LookupDefaultConstructor(RD);
1092       PartialDiagnostic PD =
1093         PartialDiagnostic(PartialDiagnostic::NullDiagnostic());
1094       if (!CD ||
1095           CheckConstructorAccess(ELoc, CD,
1096                                  InitializedEntity::InitializeTemporary(Type),
1097                                  CD->getAccess(), PD) == AR_inaccessible ||
1098           CD->isDeleted()) {
1099         Diag(ELoc, diag::err_omp_required_method)
1100              << getOpenMPClauseName(OMPC_private) << 0;
1101         bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
1102                       VarDecl::DeclarationOnly;
1103         Diag(VD->getLocation(), IsDecl ? diag::note_previous_decl :
1104                                          diag::note_defined_here) << VD;
1105         Diag(RD->getLocation(), diag::note_previous_decl) << RD;
1106         continue;
1107       }
1108       MarkFunctionReferenced(ELoc, CD);
1109       DiagnoseUseOfDecl(CD, ELoc);
1110 
1111       CXXDestructorDecl *DD = RD->getDestructor();
1112       if (DD) {
1113         if (CheckDestructorAccess(ELoc, DD, PD) == AR_inaccessible ||
1114             DD->isDeleted()) {
1115           Diag(ELoc, diag::err_omp_required_method)
1116                << getOpenMPClauseName(OMPC_private) << 4;
1117           bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
1118                         VarDecl::DeclarationOnly;
1119           Diag(VD->getLocation(), IsDecl ? diag::note_previous_decl :
1120                                            diag::note_defined_here) << VD;
1121           Diag(RD->getLocation(), diag::note_previous_decl) << RD;
1122           continue;
1123         }
1124         MarkFunctionReferenced(ELoc, DD);
1125         DiagnoseUseOfDecl(DD, ELoc);
1126       }
1127     }
1128 
1129     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1130     // in a Construct]
1131     //  Variables with the predetermined data-sharing attributes may not be
1132     //  listed in data-sharing attributes clauses, except for the cases
1133     //  listed below. For these exceptions only, listing a predetermined
1134     //  variable in a data-sharing attribute clause is allowed and overrides
1135     //  the variable's predetermined data-sharing attributes.
1136     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD);
1137     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
1138       Diag(ELoc, diag::err_omp_wrong_dsa)
1139          << getOpenMPClauseName(DVar.CKind)
1140          << getOpenMPClauseName(OMPC_private);
1141       if (DVar.RefExpr) {
1142         Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
1143              << getOpenMPClauseName(DVar.CKind);
1144       } else {
1145         Diag(VD->getLocation(), diag::note_omp_predetermined_dsa)
1146              << getOpenMPClauseName(DVar.CKind);
1147       }
1148       continue;
1149     }
1150 
1151     DSAStack->addDSA(VD, DE, OMPC_private);
1152     Vars.push_back(DE);
1153   }
1154 
1155   if (Vars.empty()) return 0;
1156 
1157   return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
1158 }
1159 
1160 OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
1161                                                SourceLocation StartLoc,
1162                                                SourceLocation LParenLoc,
1163                                                SourceLocation EndLoc) {
1164   SmallVector<Expr *, 8> Vars;
1165   for (ArrayRef<Expr *>::iterator I = VarList.begin(), E = VarList.end();
1166        I != E; ++I) {
1167     assert(*I && "NULL expr in OpenMP firstprivate clause.");
1168     if (isa<DependentScopeDeclRefExpr>(*I)) {
1169       // It will be analyzed later.
1170       Vars.push_back(*I);
1171       continue;
1172     }
1173 
1174     SourceLocation ELoc = (*I)->getExprLoc();
1175     // OpenMP [2.1, C/C++]
1176     //  A list item is a variable name.
1177     // OpenMP  [2.9.3.3, Restrictions, p.1]
1178     //  A variable that is part of another variable (as an array or
1179     //  structure element) cannot appear in a private clause.
1180     DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(*I);
1181     if (!DE || !isa<VarDecl>(DE->getDecl())) {
1182       Diag(ELoc, diag::err_omp_expected_var_name)
1183         << (*I)->getSourceRange();
1184       continue;
1185     }
1186     Decl *D = DE->getDecl();
1187     VarDecl *VD = cast<VarDecl>(D);
1188 
1189     QualType Type = VD->getType();
1190     if (Type->isDependentType() || Type->isInstantiationDependentType()) {
1191       // It will be analyzed later.
1192       Vars.push_back(DE);
1193       continue;
1194     }
1195 
1196     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
1197     //  A variable that appears in a private clause must not have an incomplete
1198     //  type or a reference type.
1199     if (RequireCompleteType(ELoc, Type,
1200                             diag::err_omp_firstprivate_incomplete_type)) {
1201       continue;
1202     }
1203     if (Type->isReferenceType()) {
1204       Diag(ELoc, diag::err_omp_clause_ref_type_arg)
1205         << getOpenMPClauseName(OMPC_firstprivate) << Type;
1206       bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
1207                     VarDecl::DeclarationOnly;
1208       Diag(VD->getLocation(), IsDecl ? diag::note_previous_decl :
1209                                        diag::note_defined_here) << VD;
1210       continue;
1211     }
1212 
1213     // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
1214     //  A variable of class type (or array thereof) that appears in a private
1215     //  clause requires an accesible, unambiguous copy constructor for the
1216     //  class type.
1217     Type = Context.getBaseElementType(Type);
1218     CXXRecordDecl *RD = getLangOpts().CPlusPlus ?
1219                           Type.getNonReferenceType()->getAsCXXRecordDecl() : 0;
1220     if (RD) {
1221       CXXConstructorDecl *CD = LookupCopyingConstructor(RD, 0);
1222       PartialDiagnostic PD =
1223         PartialDiagnostic(PartialDiagnostic::NullDiagnostic());
1224       if (!CD ||
1225           CheckConstructorAccess(ELoc, CD,
1226                                  InitializedEntity::InitializeTemporary(Type),
1227                                  CD->getAccess(), PD) == AR_inaccessible ||
1228           CD->isDeleted()) {
1229         Diag(ELoc, diag::err_omp_required_method)
1230              << getOpenMPClauseName(OMPC_firstprivate) << 1;
1231         bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
1232                       VarDecl::DeclarationOnly;
1233         Diag(VD->getLocation(), IsDecl ? diag::note_previous_decl :
1234                                          diag::note_defined_here) << VD;
1235         Diag(RD->getLocation(), diag::note_previous_decl) << RD;
1236         continue;
1237       }
1238       MarkFunctionReferenced(ELoc, CD);
1239       DiagnoseUseOfDecl(CD, ELoc);
1240 
1241       CXXDestructorDecl *DD = RD->getDestructor();
1242       if (DD) {
1243         if (CheckDestructorAccess(ELoc, DD, PD) == AR_inaccessible ||
1244             DD->isDeleted()) {
1245           Diag(ELoc, diag::err_omp_required_method)
1246                << getOpenMPClauseName(OMPC_firstprivate) << 4;
1247           bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
1248                         VarDecl::DeclarationOnly;
1249           Diag(VD->getLocation(), IsDecl ? diag::note_previous_decl :
1250                                            diag::note_defined_here) << VD;
1251           Diag(RD->getLocation(), diag::note_previous_decl) << RD;
1252           continue;
1253         }
1254         MarkFunctionReferenced(ELoc, DD);
1255         DiagnoseUseOfDecl(DD, ELoc);
1256       }
1257     }
1258 
1259     // If StartLoc and EndLoc are invalid - this is an implicit firstprivate
1260     // variable and it was checked already.
1261     if (StartLoc.isValid() && EndLoc.isValid()) {
1262       DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD);
1263       Type = Type.getNonReferenceType().getCanonicalType();
1264       bool IsConstant = Type.isConstant(Context);
1265       Type = Context.getBaseElementType(Type);
1266       // OpenMP [2.4.13, Data-sharing Attribute Clauses]
1267       //  A list item that specifies a given variable may not appear in more
1268       // than one clause on the same directive, except that a variable may be
1269       //  specified in both firstprivate and lastprivate clauses.
1270       //  TODO: add processing for lastprivate.
1271       if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
1272           DVar.RefExpr) {
1273         Diag(ELoc, diag::err_omp_wrong_dsa)
1274            << getOpenMPClauseName(DVar.CKind)
1275            << getOpenMPClauseName(OMPC_firstprivate);
1276         Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
1277            << getOpenMPClauseName(DVar.CKind);
1278         continue;
1279       }
1280 
1281       // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1282       // in a Construct]
1283       //  Variables with the predetermined data-sharing attributes may not be
1284       //  listed in data-sharing attributes clauses, except for the cases
1285       //  listed below. For these exceptions only, listing a predetermined
1286       //  variable in a data-sharing attribute clause is allowed and overrides
1287       //  the variable's predetermined data-sharing attributes.
1288       // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1289       // in a Construct, C/C++, p.2]
1290       //  Variables with const-qualified type having no mutable member may be
1291       //  listed in a firstprivate clause, even if they are static data members.
1292       if (!(IsConstant || VD->isStaticDataMember()) && !DVar.RefExpr &&
1293           DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
1294         Diag(ELoc, diag::err_omp_wrong_dsa)
1295            << getOpenMPClauseName(DVar.CKind)
1296            << getOpenMPClauseName(OMPC_firstprivate);
1297         Diag(VD->getLocation(), diag::note_omp_predetermined_dsa)
1298            << getOpenMPClauseName(DVar.CKind);
1299         continue;
1300       }
1301 
1302       // OpenMP [2.9.3.4, Restrictions, p.2]
1303       //  A list item that is private within a parallel region must not appear
1304       //  in a firstprivate clause on a worksharing construct if any of the
1305       //  worksharing regions arising from the worksharing construct ever bind
1306       //  to any of the parallel regions arising from the parallel construct.
1307       // OpenMP [2.9.3.4, Restrictions, p.3]
1308       //  A list item that appears in a reduction clause of a parallel construct
1309       //  must not appear in a firstprivate clause on a worksharing or task
1310       //  construct if any of the worksharing or task regions arising from the
1311       //  worksharing or task construct ever bind to any of the parallel regions
1312       //  arising from the parallel construct.
1313       // OpenMP [2.9.3.4, Restrictions, p.4]
1314       //  A list item that appears in a reduction clause in worksharing
1315       //  construct must not appear in a firstprivate clause in a task construct
1316       //  encountered during execution of any of the worksharing regions arising
1317       //  from the worksharing construct.
1318       // TODO:
1319     }
1320 
1321     DSAStack->addDSA(VD, DE, OMPC_firstprivate);
1322     Vars.push_back(DE);
1323   }
1324 
1325   if (Vars.empty()) return 0;
1326 
1327   return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
1328                                        Vars);
1329 }
1330 
1331 OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
1332                                          SourceLocation StartLoc,
1333                                          SourceLocation LParenLoc,
1334                                          SourceLocation EndLoc) {
1335   SmallVector<Expr *, 8> Vars;
1336   for (ArrayRef<Expr *>::iterator I = VarList.begin(), E = VarList.end();
1337        I != E; ++I) {
1338     assert(*I && "NULL expr in OpenMP shared clause.");
1339     if (isa<DependentScopeDeclRefExpr>(*I)) {
1340       // It will be analyzed later.
1341       Vars.push_back(*I);
1342       continue;
1343     }
1344 
1345     SourceLocation ELoc = (*I)->getExprLoc();
1346     // OpenMP [2.1, C/C++]
1347     //  A list item is a variable name.
1348     // OpenMP  [2.14.3.2, Restrictions, p.1]
1349     //  A variable that is part of another variable (as an array or structure
1350     //  element) cannot appear in a shared unless it is a static data member
1351     //  of a C++ class.
1352     DeclRefExpr *DE = dyn_cast<DeclRefExpr>(*I);
1353     if (!DE || !isa<VarDecl>(DE->getDecl())) {
1354       Diag(ELoc, diag::err_omp_expected_var_name)
1355         << (*I)->getSourceRange();
1356       continue;
1357     }
1358     Decl *D = DE->getDecl();
1359     VarDecl *VD = cast<VarDecl>(D);
1360 
1361     QualType Type = VD->getType();
1362     if (Type->isDependentType() || Type->isInstantiationDependentType()) {
1363       // It will be analyzed later.
1364       Vars.push_back(DE);
1365       continue;
1366     }
1367 
1368     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1369     // in a Construct]
1370     //  Variables with the predetermined data-sharing attributes may not be
1371     //  listed in data-sharing attributes clauses, except for the cases
1372     //  listed below. For these exceptions only, listing a predetermined
1373     //  variable in a data-sharing attribute clause is allowed and overrides
1374     //  the variable's predetermined data-sharing attributes.
1375     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD);
1376     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared && DVar.RefExpr) {
1377       Diag(ELoc, diag::err_omp_wrong_dsa)
1378          << getOpenMPClauseName(DVar.CKind)
1379          << getOpenMPClauseName(OMPC_shared);
1380       Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
1381            << getOpenMPClauseName(DVar.CKind);
1382       continue;
1383     }
1384 
1385     DSAStack->addDSA(VD, DE, OMPC_shared);
1386     Vars.push_back(DE);
1387   }
1388 
1389   if (Vars.empty()) return 0;
1390 
1391   return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
1392 }
1393 
1394 OMPClause *Sema::ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
1395                                          SourceLocation StartLoc,
1396                                          SourceLocation LParenLoc,
1397                                          SourceLocation ColonLoc,
1398                                          SourceLocation EndLoc) {
1399   SmallVector<Expr *, 8> Vars;
1400   for (ArrayRef<Expr *>::iterator I = VarList.begin(), E = VarList.end();
1401        I != E; ++I) {
1402     assert(*I && "NULL expr in OpenMP linear clause.");
1403     if (isa<DependentScopeDeclRefExpr>(*I)) {
1404       // It will be analyzed later.
1405       Vars.push_back(*I);
1406       continue;
1407     }
1408 
1409     // OpenMP [2.14.3.7, linear clause]
1410     // A list item that appears in a linear clause is subject to the private
1411     // clause semantics described in Section 2.14.3.3 on page 159 except as
1412     // noted. In addition, the value of the new list item on each iteration
1413     // of the associated loop(s) corresponds to the value of the original
1414     // list item before entering the construct plus the logical number of
1415     // the iteration times linear-step.
1416 
1417     SourceLocation ELoc = (*I)->getExprLoc();
1418     // OpenMP [2.1, C/C++]
1419     //  A list item is a variable name.
1420     // OpenMP  [2.14.3.3, Restrictions, p.1]
1421     //  A variable that is part of another variable (as an array or
1422     //  structure element) cannot appear in a private clause.
1423     DeclRefExpr *DE = dyn_cast<DeclRefExpr>(*I);
1424     if (!DE || !isa<VarDecl>(DE->getDecl())) {
1425       Diag(ELoc, diag::err_omp_expected_var_name) << (*I)->getSourceRange();
1426       continue;
1427     }
1428 
1429     VarDecl *VD = cast<VarDecl>(DE->getDecl());
1430 
1431     // OpenMP [2.14.3.7, linear clause]
1432     //  A list-item cannot appear in more than one linear clause.
1433     //  A list-item that appears in a linear clause cannot appear in any
1434     //  other data-sharing attribute clause.
1435     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD);
1436     if (DVar.RefExpr) {
1437       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
1438                                           << getOpenMPClauseName(OMPC_linear);
1439       Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
1440           << getOpenMPClauseName(DVar.CKind);
1441       continue;
1442     }
1443 
1444     QualType QType = VD->getType();
1445     if (QType->isDependentType() || QType->isInstantiationDependentType()) {
1446       // It will be analyzed later.
1447       Vars.push_back(DE);
1448       continue;
1449     }
1450 
1451     // A variable must not have an incomplete type or a reference type.
1452     if (RequireCompleteType(ELoc, QType,
1453                             diag::err_omp_linear_incomplete_type)) {
1454       continue;
1455     }
1456     if (QType->isReferenceType()) {
1457       Diag(ELoc, diag::err_omp_clause_ref_type_arg)
1458           << getOpenMPClauseName(OMPC_linear) << QType;
1459       bool IsDecl =
1460           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1461       Diag(VD->getLocation(),
1462            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1463           << VD;
1464       continue;
1465     }
1466 
1467     // A list item must not be const-qualified.
1468     if (QType.isConstant(Context)) {
1469       Diag(ELoc, diag::err_omp_const_variable)
1470           << getOpenMPClauseName(OMPC_linear);
1471       bool IsDecl =
1472           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1473       Diag(VD->getLocation(),
1474            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1475           << VD;
1476       continue;
1477     }
1478 
1479     // A list item must be of integral or pointer type.
1480     QType = QType.getUnqualifiedType().getCanonicalType();
1481     const Type *Ty = QType.getTypePtrOrNull();
1482     if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
1483                 !Ty->isPointerType())) {
1484       Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << QType;
1485       bool IsDecl =
1486           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1487       Diag(VD->getLocation(),
1488            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1489           << VD;
1490       continue;
1491     }
1492 
1493     DSAStack->addDSA(VD, DE, OMPC_linear);
1494     Vars.push_back(DE);
1495   }
1496 
1497   if (Vars.empty())
1498     return 0;
1499 
1500   Expr *StepExpr = Step;
1501   if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
1502       !Step->isInstantiationDependent() &&
1503       !Step->containsUnexpandedParameterPack()) {
1504     SourceLocation StepLoc = Step->getLocStart();
1505     ExprResult Val = PerformImplicitIntegerConversion(StepLoc, Step);
1506     if (Val.isInvalid())
1507       return 0;
1508     StepExpr = Val.take();
1509 
1510     // Warn about zero linear step (it would be probably better specified as
1511     // making corresponding variables 'const').
1512     llvm::APSInt Result;
1513     if (StepExpr->isIntegerConstantExpr(Result, Context) &&
1514         !Result.isNegative() && !Result.isStrictlyPositive())
1515       Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
1516                                                      << (Vars.size() > 1);
1517   }
1518 
1519   return OMPLinearClause::Create(Context, StartLoc, LParenLoc, ColonLoc, EndLoc,
1520                                  Vars, StepExpr);
1521 }
1522 
1523 OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
1524                                          SourceLocation StartLoc,
1525                                          SourceLocation LParenLoc,
1526                                          SourceLocation EndLoc) {
1527   SmallVector<Expr *, 8> Vars;
1528   for (ArrayRef<Expr *>::iterator I = VarList.begin(), E = VarList.end();
1529        I != E; ++I) {
1530     assert(*I && "NULL expr in OpenMP copyin clause.");
1531     if (isa<DependentScopeDeclRefExpr>(*I)) {
1532       // It will be analyzed later.
1533       Vars.push_back(*I);
1534       continue;
1535     }
1536 
1537     SourceLocation ELoc = (*I)->getExprLoc();
1538     // OpenMP [2.1, C/C++]
1539     //  A list item is a variable name.
1540     // OpenMP  [2.14.4.1, Restrictions, p.1]
1541     //  A list item that appears in a copyin clause must be threadprivate.
1542     DeclRefExpr *DE = dyn_cast<DeclRefExpr>(*I);
1543     if (!DE || !isa<VarDecl>(DE->getDecl())) {
1544       Diag(ELoc, diag::err_omp_expected_var_name)
1545         << (*I)->getSourceRange();
1546       continue;
1547     }
1548 
1549     Decl *D = DE->getDecl();
1550     VarDecl *VD = cast<VarDecl>(D);
1551 
1552     QualType Type = VD->getType();
1553     if (Type->isDependentType() || Type->isInstantiationDependentType()) {
1554       // It will be analyzed later.
1555       Vars.push_back(DE);
1556       continue;
1557     }
1558 
1559     // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
1560     //  A list item that appears in a copyin clause must be threadprivate.
1561     if (!DSAStack->isThreadPrivate(VD)) {
1562       Diag(ELoc, diag::err_omp_required_access)
1563            << getOpenMPClauseName(OMPC_copyin)
1564            << getOpenMPDirectiveName(OMPD_threadprivate);
1565       continue;
1566     }
1567 
1568     // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
1569     //  A variable of class type (or array thereof) that appears in a
1570     //  copyin clause requires an accesible, unambiguous copy assignment
1571     //  operator for the class type.
1572     Type = Context.getBaseElementType(Type);
1573     CXXRecordDecl *RD = getLangOpts().CPlusPlus ?
1574                           Type->getAsCXXRecordDecl() : 0;
1575     if (RD) {
1576       CXXMethodDecl *MD = LookupCopyingAssignment(RD, 0, false, 0);
1577       DeclAccessPair FoundDecl = DeclAccessPair::make(MD, MD->getAccess());
1578       if (!MD ||
1579           CheckMemberAccess(ELoc, RD, FoundDecl) == AR_inaccessible ||
1580           MD->isDeleted()) {
1581         Diag(ELoc, diag::err_omp_required_method)
1582              << getOpenMPClauseName(OMPC_copyin) << 2;
1583         bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
1584                       VarDecl::DeclarationOnly;
1585         Diag(VD->getLocation(), IsDecl ? diag::note_previous_decl :
1586                                          diag::note_defined_here) << VD;
1587         Diag(RD->getLocation(), diag::note_previous_decl) << RD;
1588         continue;
1589       }
1590       MarkFunctionReferenced(ELoc, MD);
1591       DiagnoseUseOfDecl(MD, ELoc);
1592     }
1593 
1594     DSAStack->addDSA(VD, DE, OMPC_copyin);
1595     Vars.push_back(DE);
1596   }
1597 
1598   if (Vars.empty()) return 0;
1599 
1600   return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
1601 }
1602 
1603 #undef DSAStack
1604