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