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/ASTMutationListener.h"
17 #include "clang/AST/Decl.h"
18 #include "clang/AST/DeclCXX.h"
19 #include "clang/AST/DeclOpenMP.h"
20 #include "clang/AST/StmtCXX.h"
21 #include "clang/AST/StmtOpenMP.h"
22 #include "clang/AST/StmtVisitor.h"
23 #include "clang/Basic/OpenMPKinds.h"
24 #include "clang/Lex/Preprocessor.h"
25 #include "clang/Sema/Initialization.h"
26 #include "clang/Sema/Lookup.h"
27 #include "clang/Sema/Scope.h"
28 #include "clang/Sema/ScopeInfo.h"
29 #include "clang/Sema/SemaInternal.h"
30 using namespace clang;
31 
32 //===----------------------------------------------------------------------===//
33 // Stack of data-sharing attributes for variables
34 //===----------------------------------------------------------------------===//
35 
36 namespace {
37 /// \brief Default data sharing attributes, which can be applied to directive.
38 enum DefaultDataSharingAttributes {
39   DSA_unspecified = 0, /// \brief Data sharing attribute not specified.
40   DSA_none = 1 << 0,   /// \brief Default data sharing attribute 'none'.
41   DSA_shared = 1 << 1  /// \brief Default data sharing attribute 'shared'.
42 };
43 
44 template <class T> struct MatchesAny {
45   explicit MatchesAny(ArrayRef<T> Arr) : Arr(std::move(Arr)) {}
46   bool operator()(T Kind) {
47     for (auto KindEl : Arr)
48       if (KindEl == Kind)
49         return true;
50     return false;
51   }
52 
53 private:
54   ArrayRef<T> Arr;
55 };
56 struct MatchesAlways {
57   MatchesAlways() {}
58   template <class T> bool operator()(T) { return true; }
59 };
60 
61 typedef MatchesAny<OpenMPClauseKind> MatchesAnyClause;
62 typedef MatchesAny<OpenMPDirectiveKind> MatchesAnyDirective;
63 
64 /// \brief Stack for tracking declarations used in OpenMP directives and
65 /// clauses and their data-sharing attributes.
66 class DSAStackTy {
67 public:
68   struct DSAVarData {
69     OpenMPDirectiveKind DKind;
70     OpenMPClauseKind CKind;
71     DeclRefExpr *RefExpr;
72     SourceLocation ImplicitDSALoc;
73     DSAVarData()
74         : DKind(OMPD_unknown), CKind(OMPC_unknown), RefExpr(nullptr),
75           ImplicitDSALoc() {}
76   };
77 
78 private:
79   struct DSAInfo {
80     OpenMPClauseKind Attributes;
81     DeclRefExpr *RefExpr;
82   };
83   typedef llvm::SmallDenseMap<VarDecl *, DSAInfo, 64> DeclSAMapTy;
84   typedef llvm::SmallDenseMap<VarDecl *, DeclRefExpr *, 64> AlignedMapTy;
85 
86   struct SharingMapTy {
87     DeclSAMapTy SharingMap;
88     AlignedMapTy AlignedMap;
89     DefaultDataSharingAttributes DefaultAttr;
90     SourceLocation DefaultAttrLoc;
91     OpenMPDirectiveKind Directive;
92     DeclarationNameInfo DirectiveName;
93     Scope *CurScope;
94     SourceLocation ConstructLoc;
95     bool OrderedRegion;
96     SourceLocation InnerTeamsRegionLoc;
97     SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
98                  Scope *CurScope, SourceLocation Loc)
99         : SharingMap(), AlignedMap(), DefaultAttr(DSA_unspecified),
100           Directive(DKind), DirectiveName(std::move(Name)), CurScope(CurScope),
101           ConstructLoc(Loc), OrderedRegion(false), InnerTeamsRegionLoc() {}
102     SharingMapTy()
103         : SharingMap(), AlignedMap(), DefaultAttr(DSA_unspecified),
104           Directive(OMPD_unknown), DirectiveName(), CurScope(nullptr),
105           ConstructLoc(), OrderedRegion(false), InnerTeamsRegionLoc() {}
106   };
107 
108   typedef SmallVector<SharingMapTy, 64> StackTy;
109 
110   /// \brief Stack of used declaration and their data-sharing attributes.
111   StackTy Stack;
112   Sema &SemaRef;
113 
114   typedef SmallVector<SharingMapTy, 8>::reverse_iterator reverse_iterator;
115 
116   DSAVarData getDSA(StackTy::reverse_iterator Iter, VarDecl *D);
117 
118   /// \brief Checks if the variable is a local for OpenMP region.
119   bool isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter);
120 
121 public:
122   explicit DSAStackTy(Sema &S) : Stack(1), SemaRef(S) {}
123 
124   void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
125             Scope *CurScope, SourceLocation Loc) {
126     Stack.push_back(SharingMapTy(DKind, DirName, CurScope, Loc));
127     Stack.back().DefaultAttrLoc = Loc;
128   }
129 
130   void pop() {
131     assert(Stack.size() > 1 && "Data-sharing attributes stack is empty!");
132     Stack.pop_back();
133   }
134 
135   /// \brief If 'aligned' declaration for given variable \a D was not seen yet,
136   /// add it and return NULL; otherwise return previous occurrence's expression
137   /// for diagnostics.
138   DeclRefExpr *addUniqueAligned(VarDecl *D, DeclRefExpr *NewDE);
139 
140   /// \brief Adds explicit data sharing attribute to the specified declaration.
141   void addDSA(VarDecl *D, DeclRefExpr *E, OpenMPClauseKind A);
142 
143   /// \brief Returns data sharing attributes from top of the stack for the
144   /// specified declaration.
145   DSAVarData getTopDSA(VarDecl *D, bool FromParent);
146   /// \brief Returns data-sharing attributes for the specified declaration.
147   DSAVarData getImplicitDSA(VarDecl *D, bool FromParent);
148   /// \brief Checks if the specified variables has data-sharing attributes which
149   /// match specified \a CPred predicate in any directive which matches \a DPred
150   /// predicate.
151   template <class ClausesPredicate, class DirectivesPredicate>
152   DSAVarData hasDSA(VarDecl *D, ClausesPredicate CPred,
153                     DirectivesPredicate DPred, bool FromParent);
154   /// \brief Checks if the specified variables has data-sharing attributes which
155   /// match specified \a CPred predicate in any innermost directive which
156   /// matches \a DPred predicate.
157   template <class ClausesPredicate, class DirectivesPredicate>
158   DSAVarData hasInnermostDSA(VarDecl *D, ClausesPredicate CPred,
159                              DirectivesPredicate DPred,
160                              bool FromParent);
161   /// \brief Finds a directive which matches specified \a DPred predicate.
162   template <class NamedDirectivesPredicate>
163   bool hasDirective(NamedDirectivesPredicate DPred, bool FromParent);
164 
165   /// \brief Returns currently analyzed directive.
166   OpenMPDirectiveKind getCurrentDirective() const {
167     return Stack.back().Directive;
168   }
169   /// \brief Returns parent directive.
170   OpenMPDirectiveKind getParentDirective() const {
171     if (Stack.size() > 2)
172       return Stack[Stack.size() - 2].Directive;
173     return OMPD_unknown;
174   }
175 
176   /// \brief Set default data sharing attribute to none.
177   void setDefaultDSANone(SourceLocation Loc) {
178     Stack.back().DefaultAttr = DSA_none;
179     Stack.back().DefaultAttrLoc = Loc;
180   }
181   /// \brief Set default data sharing attribute to shared.
182   void setDefaultDSAShared(SourceLocation Loc) {
183     Stack.back().DefaultAttr = DSA_shared;
184     Stack.back().DefaultAttrLoc = Loc;
185   }
186 
187   DefaultDataSharingAttributes getDefaultDSA() const {
188     return Stack.back().DefaultAttr;
189   }
190   SourceLocation getDefaultDSALocation() const {
191     return Stack.back().DefaultAttrLoc;
192   }
193 
194   /// \brief Checks if the specified variable is a threadprivate.
195   bool isThreadPrivate(VarDecl *D) {
196     DSAVarData DVar = getTopDSA(D, false);
197     return isOpenMPThreadPrivate(DVar.CKind);
198   }
199 
200   /// \brief Marks current region as ordered (it has an 'ordered' clause).
201   void setOrderedRegion(bool IsOrdered = true) {
202     Stack.back().OrderedRegion = IsOrdered;
203   }
204   /// \brief Returns true, if parent region is ordered (has associated
205   /// 'ordered' clause), false - otherwise.
206   bool isParentOrderedRegion() const {
207     if (Stack.size() > 2)
208       return Stack[Stack.size() - 2].OrderedRegion;
209     return false;
210   }
211 
212   /// \brief Marks current target region as one with closely nested teams
213   /// region.
214   void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
215     if (Stack.size() > 2)
216       Stack[Stack.size() - 2].InnerTeamsRegionLoc = TeamsRegionLoc;
217   }
218   /// \brief Returns true, if current region has closely nested teams region.
219   bool hasInnerTeamsRegion() const {
220     return getInnerTeamsRegionLoc().isValid();
221   }
222   /// \brief Returns location of the nested teams region (if any).
223   SourceLocation getInnerTeamsRegionLoc() const {
224     if (Stack.size() > 1)
225       return Stack.back().InnerTeamsRegionLoc;
226     return SourceLocation();
227   }
228 
229   Scope *getCurScope() const { return Stack.back().CurScope; }
230   Scope *getCurScope() { return Stack.back().CurScope; }
231   SourceLocation getConstructLoc() { return Stack.back().ConstructLoc; }
232 };
233 bool isParallelOrTaskRegion(OpenMPDirectiveKind DKind) {
234   return isOpenMPParallelDirective(DKind) || DKind == OMPD_task ||
235          isOpenMPTeamsDirective(DKind) || DKind == OMPD_unknown;
236 }
237 } // namespace
238 
239 DSAStackTy::DSAVarData DSAStackTy::getDSA(StackTy::reverse_iterator Iter,
240                                           VarDecl *D) {
241   DSAVarData DVar;
242   if (Iter == std::prev(Stack.rend())) {
243     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
244     // in a region but not in construct]
245     //  File-scope or namespace-scope variables referenced in called routines
246     //  in the region are shared unless they appear in a threadprivate
247     //  directive.
248     if (!D->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(D))
249       DVar.CKind = OMPC_shared;
250 
251     // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
252     // in a region but not in construct]
253     //  Variables with static storage duration that are declared in called
254     //  routines in the region are shared.
255     if (D->hasGlobalStorage())
256       DVar.CKind = OMPC_shared;
257 
258     return DVar;
259   }
260 
261   DVar.DKind = Iter->Directive;
262   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
263   // in a Construct, C/C++, predetermined, p.1]
264   // Variables with automatic storage duration that are declared in a scope
265   // inside the construct are private.
266   if (isOpenMPLocal(D, Iter) && D->isLocalVarDecl() &&
267       (D->getStorageClass() == SC_Auto || D->getStorageClass() == SC_None)) {
268     DVar.CKind = OMPC_private;
269     return DVar;
270   }
271 
272   // Explicitly specified attributes and local variables with predetermined
273   // attributes.
274   if (Iter->SharingMap.count(D)) {
275     DVar.RefExpr = Iter->SharingMap[D].RefExpr;
276     DVar.CKind = Iter->SharingMap[D].Attributes;
277     DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
278     return DVar;
279   }
280 
281   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
282   // in a Construct, C/C++, implicitly determined, p.1]
283   //  In a parallel or task construct, the data-sharing attributes of these
284   //  variables are determined by the default clause, if present.
285   switch (Iter->DefaultAttr) {
286   case DSA_shared:
287     DVar.CKind = OMPC_shared;
288     DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
289     return DVar;
290   case DSA_none:
291     return DVar;
292   case DSA_unspecified:
293     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
294     // in a Construct, implicitly determined, p.2]
295     //  In a parallel construct, if no default clause is present, these
296     //  variables are shared.
297     DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
298     if (isOpenMPParallelDirective(DVar.DKind) ||
299         isOpenMPTeamsDirective(DVar.DKind)) {
300       DVar.CKind = OMPC_shared;
301       return DVar;
302     }
303 
304     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
305     // in a Construct, implicitly determined, p.4]
306     //  In a task construct, if no default clause is present, a variable that in
307     //  the enclosing context is determined to be shared by all implicit tasks
308     //  bound to the current team is shared.
309     if (DVar.DKind == OMPD_task) {
310       DSAVarData DVarTemp;
311       for (StackTy::reverse_iterator I = std::next(Iter),
312                                      EE = std::prev(Stack.rend());
313            I != EE; ++I) {
314         // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
315         // Referenced
316         // in a Construct, implicitly determined, p.6]
317         //  In a task construct, if no default clause is present, a variable
318         //  whose data-sharing attribute is not determined by the rules above is
319         //  firstprivate.
320         DVarTemp = getDSA(I, D);
321         if (DVarTemp.CKind != OMPC_shared) {
322           DVar.RefExpr = nullptr;
323           DVar.DKind = OMPD_task;
324           DVar.CKind = OMPC_firstprivate;
325           return DVar;
326         }
327         if (isParallelOrTaskRegion(I->Directive))
328           break;
329       }
330       DVar.DKind = OMPD_task;
331       DVar.CKind =
332           (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
333       return DVar;
334     }
335   }
336   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
337   // in a Construct, implicitly determined, p.3]
338   //  For constructs other than task, if no default clause is present, these
339   //  variables inherit their data-sharing attributes from the enclosing
340   //  context.
341   return getDSA(std::next(Iter), D);
342 }
343 
344 DeclRefExpr *DSAStackTy::addUniqueAligned(VarDecl *D, DeclRefExpr *NewDE) {
345   assert(Stack.size() > 1 && "Data sharing attributes stack is empty");
346   auto It = Stack.back().AlignedMap.find(D);
347   if (It == Stack.back().AlignedMap.end()) {
348     assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
349     Stack.back().AlignedMap[D] = NewDE;
350     return nullptr;
351   } else {
352     assert(It->second && "Unexpected nullptr expr in the aligned map");
353     return It->second;
354   }
355   return nullptr;
356 }
357 
358 void DSAStackTy::addDSA(VarDecl *D, DeclRefExpr *E, OpenMPClauseKind A) {
359   if (A == OMPC_threadprivate) {
360     Stack[0].SharingMap[D].Attributes = A;
361     Stack[0].SharingMap[D].RefExpr = E;
362   } else {
363     assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
364     Stack.back().SharingMap[D].Attributes = A;
365     Stack.back().SharingMap[D].RefExpr = E;
366   }
367 }
368 
369 bool DSAStackTy::isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter) {
370   if (Stack.size() > 2) {
371     reverse_iterator I = Iter, E = std::prev(Stack.rend());
372     Scope *TopScope = nullptr;
373     while (I != E && !isParallelOrTaskRegion(I->Directive)) {
374       ++I;
375     }
376     if (I == E)
377       return false;
378     TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
379     Scope *CurScope = getCurScope();
380     while (CurScope != TopScope && !CurScope->isDeclScope(D)) {
381       CurScope = CurScope->getParent();
382     }
383     return CurScope != TopScope;
384   }
385   return false;
386 }
387 
388 DSAStackTy::DSAVarData DSAStackTy::getTopDSA(VarDecl *D, bool FromParent) {
389   DSAVarData DVar;
390 
391   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
392   // in a Construct, C/C++, predetermined, p.1]
393   //  Variables appearing in threadprivate directives are threadprivate.
394   if (D->getTLSKind() != VarDecl::TLS_None) {
395     DVar.CKind = OMPC_threadprivate;
396     return DVar;
397   }
398   if (Stack[0].SharingMap.count(D)) {
399     DVar.RefExpr = Stack[0].SharingMap[D].RefExpr;
400     DVar.CKind = OMPC_threadprivate;
401     return DVar;
402   }
403 
404   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
405   // in a Construct, C/C++, predetermined, p.1]
406   // Variables with automatic storage duration that are declared in a scope
407   // inside the construct are private.
408   OpenMPDirectiveKind Kind =
409       FromParent ? getParentDirective() : getCurrentDirective();
410   auto StartI = std::next(Stack.rbegin());
411   auto EndI = std::prev(Stack.rend());
412   if (FromParent && StartI != EndI) {
413     StartI = std::next(StartI);
414   }
415   if (!isParallelOrTaskRegion(Kind)) {
416     if (isOpenMPLocal(D, StartI) &&
417         ((D->isLocalVarDecl() && (D->getStorageClass() == SC_Auto ||
418                                   D->getStorageClass() == SC_None)) ||
419          isa<ParmVarDecl>(D))) {
420       DVar.CKind = OMPC_private;
421       return DVar;
422     }
423   }
424 
425   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
426   // in a Construct, C/C++, predetermined, p.4]
427   //  Static data members are shared.
428   if (D->isStaticDataMember()) {
429     // Variables with const-qualified type having no mutable member may be
430     // listed in a firstprivate clause, even if they are static data members.
431     DSAVarData DVarTemp = hasDSA(D, MatchesAnyClause(OMPC_firstprivate),
432                                  MatchesAlways(), FromParent);
433     if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr)
434       return DVar;
435 
436     DVar.CKind = OMPC_shared;
437     return DVar;
438   }
439 
440   QualType Type = D->getType().getNonReferenceType().getCanonicalType();
441   bool IsConstant = Type.isConstant(SemaRef.getASTContext());
442   while (Type->isArrayType()) {
443     QualType ElemType = cast<ArrayType>(Type.getTypePtr())->getElementType();
444     Type = ElemType.getNonReferenceType().getCanonicalType();
445   }
446   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
447   // in a Construct, C/C++, predetermined, p.6]
448   //  Variables with const qualified type having no mutable member are
449   //  shared.
450   CXXRecordDecl *RD =
451       SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
452   if (IsConstant &&
453       !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasMutableFields())) {
454     // Variables with const-qualified type having no mutable member may be
455     // listed in a firstprivate clause, even if they are static data members.
456     DSAVarData DVarTemp = hasDSA(D, MatchesAnyClause(OMPC_firstprivate),
457                                  MatchesAlways(), FromParent);
458     if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr)
459       return DVar;
460 
461     DVar.CKind = OMPC_shared;
462     return DVar;
463   }
464 
465   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
466   // in a Construct, C/C++, predetermined, p.7]
467   //  Variables with static storage duration that are declared in a scope
468   //  inside the construct are shared.
469   if (D->isStaticLocal()) {
470     DVar.CKind = OMPC_shared;
471     return DVar;
472   }
473 
474   // Explicitly specified attributes and local variables with predetermined
475   // attributes.
476   auto I = std::prev(StartI);
477   if (I->SharingMap.count(D)) {
478     DVar.RefExpr = I->SharingMap[D].RefExpr;
479     DVar.CKind = I->SharingMap[D].Attributes;
480     DVar.ImplicitDSALoc = I->DefaultAttrLoc;
481   }
482 
483   return DVar;
484 }
485 
486 DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(VarDecl *D, bool FromParent) {
487   auto StartI = Stack.rbegin();
488   auto EndI = std::prev(Stack.rend());
489   if (FromParent && StartI != EndI) {
490     StartI = std::next(StartI);
491   }
492   return getDSA(StartI, D);
493 }
494 
495 template <class ClausesPredicate, class DirectivesPredicate>
496 DSAStackTy::DSAVarData DSAStackTy::hasDSA(VarDecl *D, ClausesPredicate CPred,
497                                           DirectivesPredicate DPred,
498                                           bool FromParent) {
499   auto StartI = std::next(Stack.rbegin());
500   auto EndI = std::prev(Stack.rend());
501   if (FromParent && StartI != EndI) {
502     StartI = std::next(StartI);
503   }
504   for (auto I = StartI, EE = EndI; I != EE; ++I) {
505     if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive))
506       continue;
507     DSAVarData DVar = getDSA(I, D);
508     if (CPred(DVar.CKind))
509       return DVar;
510   }
511   return DSAVarData();
512 }
513 
514 template <class ClausesPredicate, class DirectivesPredicate>
515 DSAStackTy::DSAVarData
516 DSAStackTy::hasInnermostDSA(VarDecl *D, ClausesPredicate CPred,
517                             DirectivesPredicate DPred, bool FromParent) {
518   auto StartI = std::next(Stack.rbegin());
519   auto EndI = std::prev(Stack.rend());
520   if (FromParent && StartI != EndI) {
521     StartI = std::next(StartI);
522   }
523   for (auto I = StartI, EE = EndI; I != EE; ++I) {
524     if (!DPred(I->Directive))
525       break;
526     DSAVarData DVar = getDSA(I, D);
527     if (CPred(DVar.CKind))
528       return DVar;
529     return DSAVarData();
530   }
531   return DSAVarData();
532 }
533 
534 template <class NamedDirectivesPredicate>
535 bool DSAStackTy::hasDirective(NamedDirectivesPredicate DPred, bool FromParent) {
536   auto StartI = std::next(Stack.rbegin());
537   auto EndI = std::prev(Stack.rend());
538   if (FromParent && StartI != EndI) {
539     StartI = std::next(StartI);
540   }
541   for (auto I = StartI, EE = EndI; I != EE; ++I) {
542     if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
543       return true;
544   }
545   return false;
546 }
547 
548 void Sema::InitDataSharingAttributesStack() {
549   VarDataSharingAttributesStack = new DSAStackTy(*this);
550 }
551 
552 #define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
553 
554 void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
555 
556 void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
557                                const DeclarationNameInfo &DirName,
558                                Scope *CurScope, SourceLocation Loc) {
559   DSAStack->push(DKind, DirName, CurScope, Loc);
560   PushExpressionEvaluationContext(PotentiallyEvaluated);
561 }
562 
563 void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
564   // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
565   //  A variable of class type (or array thereof) that appears in a lastprivate
566   //  clause requires an accessible, unambiguous default constructor for the
567   //  class type, unless the list item is also specified in a firstprivate
568   //  clause.
569   if (auto D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
570     for (auto C : D->clauses()) {
571       if (auto Clause = dyn_cast<OMPLastprivateClause>(C)) {
572         for (auto VarRef : Clause->varlists()) {
573           if (VarRef->isValueDependent() || VarRef->isTypeDependent())
574             continue;
575           auto VD = cast<VarDecl>(cast<DeclRefExpr>(VarRef)->getDecl());
576           auto DVar = DSAStack->getTopDSA(VD, false);
577           if (DVar.CKind == OMPC_lastprivate) {
578             SourceLocation ELoc = VarRef->getExprLoc();
579             auto Type = VarRef->getType();
580             if (Type->isArrayType())
581               Type = QualType(Type->getArrayElementTypeNoTypeQual(), 0);
582             CXXRecordDecl *RD =
583                 getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
584             // FIXME This code must be replaced by actual constructing of the
585             // lastprivate variable.
586             if (RD) {
587               CXXConstructorDecl *CD = LookupDefaultConstructor(RD);
588               PartialDiagnostic PD =
589                   PartialDiagnostic(PartialDiagnostic::NullDiagnostic());
590               if (!CD ||
591                   CheckConstructorAccess(
592                       ELoc, CD, InitializedEntity::InitializeTemporary(Type),
593                       CD->getAccess(), PD) == AR_inaccessible ||
594                   CD->isDeleted()) {
595                 Diag(ELoc, diag::err_omp_required_method)
596                     << getOpenMPClauseName(OMPC_lastprivate) << 0;
597                 bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
598                               VarDecl::DeclarationOnly;
599                 Diag(VD->getLocation(), IsDecl ? diag::note_previous_decl
600                                                : diag::note_defined_here)
601                     << VD;
602                 Diag(RD->getLocation(), diag::note_previous_decl) << RD;
603                 continue;
604               }
605               MarkFunctionReferenced(ELoc, CD);
606               DiagnoseUseOfDecl(CD, ELoc);
607             }
608           }
609         }
610       }
611     }
612   }
613 
614   DSAStack->pop();
615   DiscardCleanupsInEvaluationContext();
616   PopExpressionEvaluationContext();
617 }
618 
619 namespace {
620 
621 class VarDeclFilterCCC : public CorrectionCandidateCallback {
622 private:
623   Sema &SemaRef;
624 
625 public:
626   explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
627   bool ValidateCandidate(const TypoCorrection &Candidate) override {
628     NamedDecl *ND = Candidate.getCorrectionDecl();
629     if (VarDecl *VD = dyn_cast_or_null<VarDecl>(ND)) {
630       return VD->hasGlobalStorage() &&
631              SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
632                                    SemaRef.getCurScope());
633     }
634     return false;
635   }
636 };
637 } // namespace
638 
639 ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
640                                          CXXScopeSpec &ScopeSpec,
641                                          const DeclarationNameInfo &Id) {
642   LookupResult Lookup(*this, Id, LookupOrdinaryName);
643   LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
644 
645   if (Lookup.isAmbiguous())
646     return ExprError();
647 
648   VarDecl *VD;
649   if (!Lookup.isSingleResult()) {
650     if (TypoCorrection Corrected = CorrectTypo(
651             Id, LookupOrdinaryName, CurScope, nullptr,
652             llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) {
653       diagnoseTypo(Corrected,
654                    PDiag(Lookup.empty()
655                              ? diag::err_undeclared_var_use_suggest
656                              : diag::err_omp_expected_var_arg_suggest)
657                        << Id.getName());
658       VD = Corrected.getCorrectionDeclAs<VarDecl>();
659     } else {
660       Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
661                                        : diag::err_omp_expected_var_arg)
662           << Id.getName();
663       return ExprError();
664     }
665   } else {
666     if (!(VD = Lookup.getAsSingle<VarDecl>())) {
667       Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
668       Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
669       return ExprError();
670     }
671   }
672   Lookup.suppressDiagnostics();
673 
674   // OpenMP [2.9.2, Syntax, C/C++]
675   //   Variables must be file-scope, namespace-scope, or static block-scope.
676   if (!VD->hasGlobalStorage()) {
677     Diag(Id.getLoc(), diag::err_omp_global_var_arg)
678         << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal();
679     bool IsDecl =
680         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
681     Diag(VD->getLocation(),
682          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
683         << VD;
684     return ExprError();
685   }
686 
687   VarDecl *CanonicalVD = VD->getCanonicalDecl();
688   NamedDecl *ND = cast<NamedDecl>(CanonicalVD);
689   // OpenMP [2.9.2, Restrictions, C/C++, p.2]
690   //   A threadprivate directive for file-scope variables must appear outside
691   //   any definition or declaration.
692   if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
693       !getCurLexicalContext()->isTranslationUnit()) {
694     Diag(Id.getLoc(), diag::err_omp_var_scope)
695         << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
696     bool IsDecl =
697         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
698     Diag(VD->getLocation(),
699          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
700         << VD;
701     return ExprError();
702   }
703   // OpenMP [2.9.2, Restrictions, C/C++, p.3]
704   //   A threadprivate directive for static class member variables must appear
705   //   in the class definition, in the same scope in which the member
706   //   variables are declared.
707   if (CanonicalVD->isStaticDataMember() &&
708       !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
709     Diag(Id.getLoc(), diag::err_omp_var_scope)
710         << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
711     bool IsDecl =
712         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
713     Diag(VD->getLocation(),
714          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
715         << VD;
716     return ExprError();
717   }
718   // OpenMP [2.9.2, Restrictions, C/C++, p.4]
719   //   A threadprivate directive for namespace-scope variables must appear
720   //   outside any definition or declaration other than the namespace
721   //   definition itself.
722   if (CanonicalVD->getDeclContext()->isNamespace() &&
723       (!getCurLexicalContext()->isFileContext() ||
724        !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
725     Diag(Id.getLoc(), diag::err_omp_var_scope)
726         << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
727     bool IsDecl =
728         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
729     Diag(VD->getLocation(),
730          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
731         << VD;
732     return ExprError();
733   }
734   // OpenMP [2.9.2, Restrictions, C/C++, p.6]
735   //   A threadprivate directive for static block-scope variables must appear
736   //   in the scope of the variable and not in a nested scope.
737   if (CanonicalVD->isStaticLocal() && CurScope &&
738       !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
739     Diag(Id.getLoc(), diag::err_omp_var_scope)
740         << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
741     bool IsDecl =
742         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
743     Diag(VD->getLocation(),
744          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
745         << VD;
746     return ExprError();
747   }
748 
749   // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
750   //   A threadprivate directive must lexically precede all references to any
751   //   of the variables in its list.
752   if (VD->isUsed()) {
753     Diag(Id.getLoc(), diag::err_omp_var_used)
754         << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
755     return ExprError();
756   }
757 
758   QualType ExprType = VD->getType().getNonReferenceType();
759   ExprResult DE = BuildDeclRefExpr(VD, ExprType, VK_LValue, Id.getLoc());
760   return DE;
761 }
762 
763 Sema::DeclGroupPtrTy
764 Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
765                                         ArrayRef<Expr *> VarList) {
766   if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
767     CurContext->addDecl(D);
768     return DeclGroupPtrTy::make(DeclGroupRef(D));
769   }
770   return DeclGroupPtrTy();
771 }
772 
773 namespace {
774 class LocalVarRefChecker : public ConstStmtVisitor<LocalVarRefChecker, bool> {
775   Sema &SemaRef;
776 
777 public:
778   bool VisitDeclRefExpr(const DeclRefExpr *E) {
779     if (auto VD = dyn_cast<VarDecl>(E->getDecl())) {
780       if (VD->hasLocalStorage()) {
781         SemaRef.Diag(E->getLocStart(),
782                      diag::err_omp_local_var_in_threadprivate_init)
783             << E->getSourceRange();
784         SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
785             << VD << VD->getSourceRange();
786         return true;
787       }
788     }
789     return false;
790   }
791   bool VisitStmt(const Stmt *S) {
792     for (auto Child : S->children()) {
793       if (Child && Visit(Child))
794         return true;
795     }
796     return false;
797   }
798   explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
799 };
800 } // namespace
801 
802 OMPThreadPrivateDecl *
803 Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
804   SmallVector<Expr *, 8> Vars;
805   for (auto &RefExpr : VarList) {
806     DeclRefExpr *DE = cast<DeclRefExpr>(RefExpr);
807     VarDecl *VD = cast<VarDecl>(DE->getDecl());
808     SourceLocation ILoc = DE->getExprLoc();
809 
810     // OpenMP [2.9.2, Restrictions, C/C++, p.10]
811     //   A threadprivate variable must not have an incomplete type.
812     if (RequireCompleteType(ILoc, VD->getType(),
813                             diag::err_omp_threadprivate_incomplete_type)) {
814       continue;
815     }
816 
817     // OpenMP [2.9.2, Restrictions, C/C++, p.10]
818     //   A threadprivate variable must not have a reference type.
819     if (VD->getType()->isReferenceType()) {
820       Diag(ILoc, diag::err_omp_ref_type_arg)
821           << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
822       bool IsDecl =
823           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
824       Diag(VD->getLocation(),
825            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
826           << VD;
827       continue;
828     }
829 
830     // Check if this is a TLS variable.
831     if (VD->getTLSKind()) {
832       Diag(ILoc, diag::err_omp_var_thread_local) << VD;
833       bool IsDecl =
834           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
835       Diag(VD->getLocation(),
836            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
837           << VD;
838       continue;
839     }
840 
841     // Check if initial value of threadprivate variable reference variable with
842     // local storage (it is not supported by runtime).
843     if (auto Init = VD->getAnyInitializer()) {
844       LocalVarRefChecker Checker(*this);
845       if (Checker.Visit(Init))
846         continue;
847     }
848 
849     Vars.push_back(RefExpr);
850     DSAStack->addDSA(VD, DE, OMPC_threadprivate);
851     VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
852         Context, SourceRange(Loc, Loc)));
853     if (auto *ML = Context.getASTMutationListener())
854       ML->DeclarationMarkedOpenMPThreadPrivate(VD);
855   }
856   OMPThreadPrivateDecl *D = nullptr;
857   if (!Vars.empty()) {
858     D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
859                                      Vars);
860     D->setAccess(AS_public);
861   }
862   return D;
863 }
864 
865 static void ReportOriginalDSA(Sema &SemaRef, DSAStackTy *Stack,
866                               const VarDecl *VD, DSAStackTy::DSAVarData DVar,
867                               bool IsLoopIterVar = false) {
868   if (DVar.RefExpr) {
869     SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
870         << getOpenMPClauseName(DVar.CKind);
871     return;
872   }
873   enum {
874     PDSA_StaticMemberShared,
875     PDSA_StaticLocalVarShared,
876     PDSA_LoopIterVarPrivate,
877     PDSA_LoopIterVarLinear,
878     PDSA_LoopIterVarLastprivate,
879     PDSA_ConstVarShared,
880     PDSA_GlobalVarShared,
881     PDSA_TaskVarFirstprivate,
882     PDSA_LocalVarPrivate,
883     PDSA_Implicit
884   } Reason = PDSA_Implicit;
885   bool ReportHint = false;
886   auto ReportLoc = VD->getLocation();
887   if (IsLoopIterVar) {
888     if (DVar.CKind == OMPC_private)
889       Reason = PDSA_LoopIterVarPrivate;
890     else if (DVar.CKind == OMPC_lastprivate)
891       Reason = PDSA_LoopIterVarLastprivate;
892     else
893       Reason = PDSA_LoopIterVarLinear;
894   } else if (DVar.DKind == OMPD_task && DVar.CKind == OMPC_firstprivate) {
895     Reason = PDSA_TaskVarFirstprivate;
896     ReportLoc = DVar.ImplicitDSALoc;
897   } else if (VD->isStaticLocal())
898     Reason = PDSA_StaticLocalVarShared;
899   else if (VD->isStaticDataMember())
900     Reason = PDSA_StaticMemberShared;
901   else if (VD->isFileVarDecl())
902     Reason = PDSA_GlobalVarShared;
903   else if (VD->getType().isConstant(SemaRef.getASTContext()))
904     Reason = PDSA_ConstVarShared;
905   else if (VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
906     ReportHint = true;
907     Reason = PDSA_LocalVarPrivate;
908   }
909   if (Reason != PDSA_Implicit) {
910     SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
911         << Reason << ReportHint
912         << getOpenMPDirectiveName(Stack->getCurrentDirective());
913   } else if (DVar.ImplicitDSALoc.isValid()) {
914     SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
915         << getOpenMPClauseName(DVar.CKind);
916   }
917 }
918 
919 namespace {
920 class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> {
921   DSAStackTy *Stack;
922   Sema &SemaRef;
923   bool ErrorFound;
924   CapturedStmt *CS;
925   llvm::SmallVector<Expr *, 8> ImplicitFirstprivate;
926   llvm::DenseMap<VarDecl *, Expr *> VarsWithInheritedDSA;
927 
928 public:
929   void VisitDeclRefExpr(DeclRefExpr *E) {
930     if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
931       // Skip internally declared variables.
932       if (VD->isLocalVarDecl() && !CS->capturesVariable(VD))
933         return;
934 
935       auto DVar = Stack->getTopDSA(VD, false);
936       // Check if the variable has explicit DSA set and stop analysis if it so.
937       if (DVar.RefExpr) return;
938 
939       auto ELoc = E->getExprLoc();
940       auto DKind = Stack->getCurrentDirective();
941       // The default(none) clause requires that each variable that is referenced
942       // in the construct, and does not have a predetermined data-sharing
943       // attribute, must have its data-sharing attribute explicitly determined
944       // by being listed in a data-sharing attribute clause.
945       if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
946           isParallelOrTaskRegion(DKind) &&
947           VarsWithInheritedDSA.count(VD) == 0) {
948         VarsWithInheritedDSA[VD] = E;
949         return;
950       }
951 
952       // OpenMP [2.9.3.6, Restrictions, p.2]
953       //  A list item that appears in a reduction clause of the innermost
954       //  enclosing worksharing or parallel construct may not be accessed in an
955       //  explicit task.
956       DVar = Stack->hasInnermostDSA(VD, MatchesAnyClause(OMPC_reduction),
957                                     [](OpenMPDirectiveKind K) -> bool {
958                                       return isOpenMPParallelDirective(K) ||
959                                              isOpenMPWorksharingDirective(K) ||
960                                              isOpenMPTeamsDirective(K);
961                                     },
962                                     false);
963       if (DKind == OMPD_task && DVar.CKind == OMPC_reduction) {
964         ErrorFound = true;
965         SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
966         ReportOriginalDSA(SemaRef, Stack, VD, DVar);
967         return;
968       }
969 
970       // Define implicit data-sharing attributes for task.
971       DVar = Stack->getImplicitDSA(VD, false);
972       if (DKind == OMPD_task && DVar.CKind != OMPC_shared)
973         ImplicitFirstprivate.push_back(E);
974     }
975   }
976   void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
977     for (auto *C : S->clauses()) {
978       // Skip analysis of arguments of implicitly defined firstprivate clause
979       // for task directives.
980       if (C && (!isa<OMPFirstprivateClause>(C) || C->getLocStart().isValid()))
981         for (auto *CC : C->children()) {
982           if (CC)
983             Visit(CC);
984         }
985     }
986   }
987   void VisitStmt(Stmt *S) {
988     for (auto *C : S->children()) {
989       if (C && !isa<OMPExecutableDirective>(C))
990         Visit(C);
991     }
992   }
993 
994   bool isErrorFound() { return ErrorFound; }
995   ArrayRef<Expr *> getImplicitFirstprivate() { return ImplicitFirstprivate; }
996   llvm::DenseMap<VarDecl *, Expr *> &getVarsWithInheritedDSA() {
997     return VarsWithInheritedDSA;
998   }
999 
1000   DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
1001       : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {}
1002 };
1003 } // namespace
1004 
1005 void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
1006   switch (DKind) {
1007   case OMPD_parallel: {
1008     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1009     QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
1010     Sema::CapturedParamNameType Params[] = {
1011         std::make_pair(".global_tid.", KmpInt32PtrTy),
1012         std::make_pair(".bound_tid.", KmpInt32PtrTy),
1013         std::make_pair(StringRef(), QualType()) // __context with shared vars
1014     };
1015     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1016                              Params);
1017     break;
1018   }
1019   case OMPD_simd: {
1020     Sema::CapturedParamNameType Params[] = {
1021         std::make_pair(StringRef(), QualType()) // __context with shared vars
1022     };
1023     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1024                              Params);
1025     break;
1026   }
1027   case OMPD_for: {
1028     Sema::CapturedParamNameType Params[] = {
1029         std::make_pair(StringRef(), QualType()) // __context with shared vars
1030     };
1031     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1032                              Params);
1033     break;
1034   }
1035   case OMPD_for_simd: {
1036     Sema::CapturedParamNameType Params[] = {
1037         std::make_pair(StringRef(), QualType()) // __context with shared vars
1038     };
1039     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1040                              Params);
1041     break;
1042   }
1043   case OMPD_sections: {
1044     Sema::CapturedParamNameType Params[] = {
1045         std::make_pair(StringRef(), QualType()) // __context with shared vars
1046     };
1047     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1048                              Params);
1049     break;
1050   }
1051   case OMPD_section: {
1052     Sema::CapturedParamNameType Params[] = {
1053         std::make_pair(StringRef(), QualType()) // __context with shared vars
1054     };
1055     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1056                              Params);
1057     break;
1058   }
1059   case OMPD_single: {
1060     Sema::CapturedParamNameType Params[] = {
1061         std::make_pair(StringRef(), QualType()) // __context with shared vars
1062     };
1063     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1064                              Params);
1065     break;
1066   }
1067   case OMPD_master: {
1068     Sema::CapturedParamNameType Params[] = {
1069         std::make_pair(StringRef(), QualType()) // __context with shared vars
1070     };
1071     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1072                              Params);
1073     break;
1074   }
1075   case OMPD_critical: {
1076     Sema::CapturedParamNameType Params[] = {
1077         std::make_pair(StringRef(), QualType()) // __context with shared vars
1078     };
1079     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1080                              Params);
1081     break;
1082   }
1083   case OMPD_parallel_for: {
1084     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1085     QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
1086     Sema::CapturedParamNameType Params[] = {
1087         std::make_pair(".global_tid.", KmpInt32PtrTy),
1088         std::make_pair(".bound_tid.", KmpInt32PtrTy),
1089         std::make_pair(StringRef(), QualType()) // __context with shared vars
1090     };
1091     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1092                              Params);
1093     break;
1094   }
1095   case OMPD_parallel_for_simd: {
1096     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1097     QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
1098     Sema::CapturedParamNameType Params[] = {
1099         std::make_pair(".global_tid.", KmpInt32PtrTy),
1100         std::make_pair(".bound_tid.", KmpInt32PtrTy),
1101         std::make_pair(StringRef(), QualType()) // __context with shared vars
1102     };
1103     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1104                              Params);
1105     break;
1106   }
1107   case OMPD_parallel_sections: {
1108     Sema::CapturedParamNameType Params[] = {
1109         std::make_pair(StringRef(), QualType()) // __context with shared vars
1110     };
1111     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1112                              Params);
1113     break;
1114   }
1115   case OMPD_task: {
1116     Sema::CapturedParamNameType Params[] = {
1117         std::make_pair(StringRef(), QualType()) // __context with shared vars
1118     };
1119     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1120                              Params);
1121     break;
1122   }
1123   case OMPD_ordered: {
1124     Sema::CapturedParamNameType Params[] = {
1125         std::make_pair(StringRef(), QualType()) // __context with shared vars
1126     };
1127     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1128                              Params);
1129     break;
1130   }
1131   case OMPD_atomic: {
1132     Sema::CapturedParamNameType Params[] = {
1133         std::make_pair(StringRef(), QualType()) // __context with shared vars
1134     };
1135     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1136                              Params);
1137     break;
1138   }
1139   case OMPD_target: {
1140     Sema::CapturedParamNameType Params[] = {
1141         std::make_pair(StringRef(), QualType()) // __context with shared vars
1142     };
1143     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1144                              Params);
1145     break;
1146   }
1147   case OMPD_teams: {
1148     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1149     QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
1150     Sema::CapturedParamNameType Params[] = {
1151         std::make_pair(".global_tid.", KmpInt32PtrTy),
1152         std::make_pair(".bound_tid.", KmpInt32PtrTy),
1153         std::make_pair(StringRef(), QualType()) // __context with shared vars
1154     };
1155     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1156                              Params);
1157     break;
1158   }
1159   case OMPD_threadprivate:
1160   case OMPD_taskyield:
1161   case OMPD_barrier:
1162   case OMPD_taskwait:
1163   case OMPD_flush:
1164     llvm_unreachable("OpenMP Directive is not allowed");
1165   case OMPD_unknown:
1166     llvm_unreachable("Unknown OpenMP directive");
1167   }
1168 }
1169 
1170 static bool CheckNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack,
1171                                   OpenMPDirectiveKind CurrentRegion,
1172                                   const DeclarationNameInfo &CurrentName,
1173                                   SourceLocation StartLoc) {
1174   // Allowed nesting of constructs
1175   // +------------------+-----------------+------------------------------------+
1176   // | Parent directive | Child directive | Closely (!), No-Closely(+), Both(*)|
1177   // +------------------+-----------------+------------------------------------+
1178   // | parallel         | parallel        | *                                  |
1179   // | parallel         | for             | *                                  |
1180   // | parallel         | for simd        | *                                  |
1181   // | parallel         | master          | *                                  |
1182   // | parallel         | critical        | *                                  |
1183   // | parallel         | simd            | *                                  |
1184   // | parallel         | sections        | *                                  |
1185   // | parallel         | section         | +                                  |
1186   // | parallel         | single          | *                                  |
1187   // | parallel         | parallel for    | *                                  |
1188   // | parallel         |parallel for simd| *                                  |
1189   // | parallel         |parallel sections| *                                  |
1190   // | parallel         | task            | *                                  |
1191   // | parallel         | taskyield       | *                                  |
1192   // | parallel         | barrier         | *                                  |
1193   // | parallel         | taskwait        | *                                  |
1194   // | parallel         | flush           | *                                  |
1195   // | parallel         | ordered         | +                                  |
1196   // | parallel         | atomic          | *                                  |
1197   // | parallel         | target          | *                                  |
1198   // | parallel         | teams           | +                                  |
1199   // +------------------+-----------------+------------------------------------+
1200   // | for              | parallel        | *                                  |
1201   // | for              | for             | +                                  |
1202   // | for              | for simd        | +                                  |
1203   // | for              | master          | +                                  |
1204   // | for              | critical        | *                                  |
1205   // | for              | simd            | *                                  |
1206   // | for              | sections        | +                                  |
1207   // | for              | section         | +                                  |
1208   // | for              | single          | +                                  |
1209   // | for              | parallel for    | *                                  |
1210   // | for              |parallel for simd| *                                  |
1211   // | for              |parallel sections| *                                  |
1212   // | for              | task            | *                                  |
1213   // | for              | taskyield       | *                                  |
1214   // | for              | barrier         | +                                  |
1215   // | for              | taskwait        | *                                  |
1216   // | for              | flush           | *                                  |
1217   // | for              | ordered         | * (if construct is ordered)        |
1218   // | for              | atomic          | *                                  |
1219   // | for              | target          | *                                  |
1220   // | for              | teams           | +                                  |
1221   // +------------------+-----------------+------------------------------------+
1222   // | master           | parallel        | *                                  |
1223   // | master           | for             | +                                  |
1224   // | master           | for simd        | +                                  |
1225   // | master           | master          | *                                  |
1226   // | master           | critical        | *                                  |
1227   // | master           | simd            | *                                  |
1228   // | master           | sections        | +                                  |
1229   // | master           | section         | +                                  |
1230   // | master           | single          | +                                  |
1231   // | master           | parallel for    | *                                  |
1232   // | master           |parallel for simd| *                                  |
1233   // | master           |parallel sections| *                                  |
1234   // | master           | task            | *                                  |
1235   // | master           | taskyield       | *                                  |
1236   // | master           | barrier         | +                                  |
1237   // | master           | taskwait        | *                                  |
1238   // | master           | flush           | *                                  |
1239   // | master           | ordered         | +                                  |
1240   // | master           | atomic          | *                                  |
1241   // | master           | target          | *                                  |
1242   // | master           | teams           | +                                  |
1243   // +------------------+-----------------+------------------------------------+
1244   // | critical         | parallel        | *                                  |
1245   // | critical         | for             | +                                  |
1246   // | critical         | for simd        | +                                  |
1247   // | critical         | master          | *                                  |
1248   // | critical         | critical        | * (should have different names)    |
1249   // | critical         | simd            | *                                  |
1250   // | critical         | sections        | +                                  |
1251   // | critical         | section         | +                                  |
1252   // | critical         | single          | +                                  |
1253   // | critical         | parallel for    | *                                  |
1254   // | critical         |parallel for simd| *                                  |
1255   // | critical         |parallel sections| *                                  |
1256   // | critical         | task            | *                                  |
1257   // | critical         | taskyield       | *                                  |
1258   // | critical         | barrier         | +                                  |
1259   // | critical         | taskwait        | *                                  |
1260   // | critical         | ordered         | +                                  |
1261   // | critical         | atomic          | *                                  |
1262   // | critical         | target          | *                                  |
1263   // | critical         | teams           | +                                  |
1264   // +------------------+-----------------+------------------------------------+
1265   // | simd             | parallel        |                                    |
1266   // | simd             | for             |                                    |
1267   // | simd             | for simd        |                                    |
1268   // | simd             | master          |                                    |
1269   // | simd             | critical        |                                    |
1270   // | simd             | simd            |                                    |
1271   // | simd             | sections        |                                    |
1272   // | simd             | section         |                                    |
1273   // | simd             | single          |                                    |
1274   // | simd             | parallel for    |                                    |
1275   // | simd             |parallel for simd|                                    |
1276   // | simd             |parallel sections|                                    |
1277   // | simd             | task            |                                    |
1278   // | simd             | taskyield       |                                    |
1279   // | simd             | barrier         |                                    |
1280   // | simd             | taskwait        |                                    |
1281   // | simd             | flush           |                                    |
1282   // | simd             | ordered         |                                    |
1283   // | simd             | atomic          |                                    |
1284   // | simd             | target          |                                    |
1285   // | simd             | teams           |                                    |
1286   // +------------------+-----------------+------------------------------------+
1287   // | for simd         | parallel        |                                    |
1288   // | for simd         | for             |                                    |
1289   // | for simd         | for simd        |                                    |
1290   // | for simd         | master          |                                    |
1291   // | for simd         | critical        |                                    |
1292   // | for simd         | simd            |                                    |
1293   // | for simd         | sections        |                                    |
1294   // | for simd         | section         |                                    |
1295   // | for simd         | single          |                                    |
1296   // | for simd         | parallel for    |                                    |
1297   // | for simd         |parallel for simd|                                    |
1298   // | for simd         |parallel sections|                                    |
1299   // | for simd         | task            |                                    |
1300   // | for simd         | taskyield       |                                    |
1301   // | for simd         | barrier         |                                    |
1302   // | for simd         | taskwait        |                                    |
1303   // | for simd         | flush           |                                    |
1304   // | for simd         | ordered         |                                    |
1305   // | for simd         | atomic          |                                    |
1306   // | for simd         | target          |                                    |
1307   // | for simd         | teams           |                                    |
1308   // +------------------+-----------------+------------------------------------+
1309   // | parallel for simd| parallel        |                                    |
1310   // | parallel for simd| for             |                                    |
1311   // | parallel for simd| for simd        |                                    |
1312   // | parallel for simd| master          |                                    |
1313   // | parallel for simd| critical        |                                    |
1314   // | parallel for simd| simd            |                                    |
1315   // | parallel for simd| sections        |                                    |
1316   // | parallel for simd| section         |                                    |
1317   // | parallel for simd| single          |                                    |
1318   // | parallel for simd| parallel for    |                                    |
1319   // | parallel for simd|parallel for simd|                                    |
1320   // | parallel for simd|parallel sections|                                    |
1321   // | parallel for simd| task            |                                    |
1322   // | parallel for simd| taskyield       |                                    |
1323   // | parallel for simd| barrier         |                                    |
1324   // | parallel for simd| taskwait        |                                    |
1325   // | parallel for simd| flush           |                                    |
1326   // | parallel for simd| ordered         |                                    |
1327   // | parallel for simd| atomic          |                                    |
1328   // | parallel for simd| target          |                                    |
1329   // | parallel for simd| teams           |                                    |
1330   // +------------------+-----------------+------------------------------------+
1331   // | sections         | parallel        | *                                  |
1332   // | sections         | for             | +                                  |
1333   // | sections         | for simd        | +                                  |
1334   // | sections         | master          | +                                  |
1335   // | sections         | critical        | *                                  |
1336   // | sections         | simd            | *                                  |
1337   // | sections         | sections        | +                                  |
1338   // | sections         | section         | *                                  |
1339   // | sections         | single          | +                                  |
1340   // | sections         | parallel for    | *                                  |
1341   // | sections         |parallel for simd| *                                  |
1342   // | sections         |parallel sections| *                                  |
1343   // | sections         | task            | *                                  |
1344   // | sections         | taskyield       | *                                  |
1345   // | sections         | barrier         | +                                  |
1346   // | sections         | taskwait        | *                                  |
1347   // | sections         | flush           | *                                  |
1348   // | sections         | ordered         | +                                  |
1349   // | sections         | atomic          | *                                  |
1350   // | sections         | target          | *                                  |
1351   // | sections         | teams           | +                                  |
1352   // +------------------+-----------------+------------------------------------+
1353   // | section          | parallel        | *                                  |
1354   // | section          | for             | +                                  |
1355   // | section          | for simd        | +                                  |
1356   // | section          | master          | +                                  |
1357   // | section          | critical        | *                                  |
1358   // | section          | simd            | *                                  |
1359   // | section          | sections        | +                                  |
1360   // | section          | section         | +                                  |
1361   // | section          | single          | +                                  |
1362   // | section          | parallel for    | *                                  |
1363   // | section          |parallel for simd| *                                  |
1364   // | section          |parallel sections| *                                  |
1365   // | section          | task            | *                                  |
1366   // | section          | taskyield       | *                                  |
1367   // | section          | barrier         | +                                  |
1368   // | section          | taskwait        | *                                  |
1369   // | section          | flush           | *                                  |
1370   // | section          | ordered         | +                                  |
1371   // | section          | atomic          | *                                  |
1372   // | section          | target          | *                                  |
1373   // | section          | teams           | +                                  |
1374   // +------------------+-----------------+------------------------------------+
1375   // | single           | parallel        | *                                  |
1376   // | single           | for             | +                                  |
1377   // | single           | for simd        | +                                  |
1378   // | single           | master          | +                                  |
1379   // | single           | critical        | *                                  |
1380   // | single           | simd            | *                                  |
1381   // | single           | sections        | +                                  |
1382   // | single           | section         | +                                  |
1383   // | single           | single          | +                                  |
1384   // | single           | parallel for    | *                                  |
1385   // | single           |parallel for simd| *                                  |
1386   // | single           |parallel sections| *                                  |
1387   // | single           | task            | *                                  |
1388   // | single           | taskyield       | *                                  |
1389   // | single           | barrier         | +                                  |
1390   // | single           | taskwait        | *                                  |
1391   // | single           | flush           | *                                  |
1392   // | single           | ordered         | +                                  |
1393   // | single           | atomic          | *                                  |
1394   // | single           | target          | *                                  |
1395   // | single           | teams           | +                                  |
1396   // +------------------+-----------------+------------------------------------+
1397   // | parallel for     | parallel        | *                                  |
1398   // | parallel for     | for             | +                                  |
1399   // | parallel for     | for simd        | +                                  |
1400   // | parallel for     | master          | +                                  |
1401   // | parallel for     | critical        | *                                  |
1402   // | parallel for     | simd            | *                                  |
1403   // | parallel for     | sections        | +                                  |
1404   // | parallel for     | section         | +                                  |
1405   // | parallel for     | single          | +                                  |
1406   // | parallel for     | parallel for    | *                                  |
1407   // | parallel for     |parallel for simd| *                                  |
1408   // | parallel for     |parallel sections| *                                  |
1409   // | parallel for     | task            | *                                  |
1410   // | parallel for     | taskyield       | *                                  |
1411   // | parallel for     | barrier         | +                                  |
1412   // | parallel for     | taskwait        | *                                  |
1413   // | parallel for     | flush           | *                                  |
1414   // | parallel for     | ordered         | * (if construct is ordered)        |
1415   // | parallel for     | atomic          | *                                  |
1416   // | parallel for     | target          | *                                  |
1417   // | parallel for     | teams           | +                                  |
1418   // +------------------+-----------------+------------------------------------+
1419   // | parallel sections| parallel        | *                                  |
1420   // | parallel sections| for             | +                                  |
1421   // | parallel sections| for simd        | +                                  |
1422   // | parallel sections| master          | +                                  |
1423   // | parallel sections| critical        | +                                  |
1424   // | parallel sections| simd            | *                                  |
1425   // | parallel sections| sections        | +                                  |
1426   // | parallel sections| section         | *                                  |
1427   // | parallel sections| single          | +                                  |
1428   // | parallel sections| parallel for    | *                                  |
1429   // | parallel sections|parallel for simd| *                                  |
1430   // | parallel sections|parallel sections| *                                  |
1431   // | parallel sections| task            | *                                  |
1432   // | parallel sections| taskyield       | *                                  |
1433   // | parallel sections| barrier         | +                                  |
1434   // | parallel sections| taskwait        | *                                  |
1435   // | parallel sections| flush           | *                                  |
1436   // | parallel sections| ordered         | +                                  |
1437   // | parallel sections| atomic          | *                                  |
1438   // | parallel sections| target          | *                                  |
1439   // | parallel sections| teams           | +                                  |
1440   // +------------------+-----------------+------------------------------------+
1441   // | task             | parallel        | *                                  |
1442   // | task             | for             | +                                  |
1443   // | task             | for simd        | +                                  |
1444   // | task             | master          | +                                  |
1445   // | task             | critical        | *                                  |
1446   // | task             | simd            | *                                  |
1447   // | task             | sections        | +                                  |
1448   // | task             | section         | +                                  |
1449   // | task             | single          | +                                  |
1450   // | task             | parallel for    | *                                  |
1451   // | task             |parallel for simd| *                                  |
1452   // | task             |parallel sections| *                                  |
1453   // | task             | task            | *                                  |
1454   // | task             | taskyield       | *                                  |
1455   // | task             | barrier         | +                                  |
1456   // | task             | taskwait        | *                                  |
1457   // | task             | flush           | *                                  |
1458   // | task             | ordered         | +                                  |
1459   // | task             | atomic          | *                                  |
1460   // | task             | target          | *                                  |
1461   // | task             | teams           | +                                  |
1462   // +------------------+-----------------+------------------------------------+
1463   // | ordered          | parallel        | *                                  |
1464   // | ordered          | for             | +                                  |
1465   // | ordered          | for simd        | +                                  |
1466   // | ordered          | master          | *                                  |
1467   // | ordered          | critical        | *                                  |
1468   // | ordered          | simd            | *                                  |
1469   // | ordered          | sections        | +                                  |
1470   // | ordered          | section         | +                                  |
1471   // | ordered          | single          | +                                  |
1472   // | ordered          | parallel for    | *                                  |
1473   // | ordered          |parallel for simd| *                                  |
1474   // | ordered          |parallel sections| *                                  |
1475   // | ordered          | task            | *                                  |
1476   // | ordered          | taskyield       | *                                  |
1477   // | ordered          | barrier         | +                                  |
1478   // | ordered          | taskwait        | *                                  |
1479   // | ordered          | flush           | *                                  |
1480   // | ordered          | ordered         | +                                  |
1481   // | ordered          | atomic          | *                                  |
1482   // | ordered          | target          | *                                  |
1483   // | ordered          | teams           | +                                  |
1484   // +------------------+-----------------+------------------------------------+
1485   // | atomic           | parallel        |                                    |
1486   // | atomic           | for             |                                    |
1487   // | atomic           | for simd        |                                    |
1488   // | atomic           | master          |                                    |
1489   // | atomic           | critical        |                                    |
1490   // | atomic           | simd            |                                    |
1491   // | atomic           | sections        |                                    |
1492   // | atomic           | section         |                                    |
1493   // | atomic           | single          |                                    |
1494   // | atomic           | parallel for    |                                    |
1495   // | atomic           |parallel for simd|                                    |
1496   // | atomic           |parallel sections|                                    |
1497   // | atomic           | task            |                                    |
1498   // | atomic           | taskyield       |                                    |
1499   // | atomic           | barrier         |                                    |
1500   // | atomic           | taskwait        |                                    |
1501   // | atomic           | flush           |                                    |
1502   // | atomic           | ordered         |                                    |
1503   // | atomic           | atomic          |                                    |
1504   // | atomic           | target          |                                    |
1505   // | atomic           | teams           |                                    |
1506   // +------------------+-----------------+------------------------------------+
1507   // | target           | parallel        | *                                  |
1508   // | target           | for             | *                                  |
1509   // | target           | for simd        | *                                  |
1510   // | target           | master          | *                                  |
1511   // | target           | critical        | *                                  |
1512   // | target           | simd            | *                                  |
1513   // | target           | sections        | *                                  |
1514   // | target           | section         | *                                  |
1515   // | target           | single          | *                                  |
1516   // | target           | parallel for    | *                                  |
1517   // | target           |parallel for simd| *                                  |
1518   // | target           |parallel sections| *                                  |
1519   // | target           | task            | *                                  |
1520   // | target           | taskyield       | *                                  |
1521   // | target           | barrier         | *                                  |
1522   // | target           | taskwait        | *                                  |
1523   // | target           | flush           | *                                  |
1524   // | target           | ordered         | *                                  |
1525   // | target           | atomic          | *                                  |
1526   // | target           | target          | *                                  |
1527   // | target           | teams           | *                                  |
1528   // +------------------+-----------------+------------------------------------+
1529   // | teams            | parallel        | *                                  |
1530   // | teams            | for             | +                                  |
1531   // | teams            | for simd        | +                                  |
1532   // | teams            | master          | +                                  |
1533   // | teams            | critical        | +                                  |
1534   // | teams            | simd            | +                                  |
1535   // | teams            | sections        | +                                  |
1536   // | teams            | section         | +                                  |
1537   // | teams            | single          | +                                  |
1538   // | teams            | parallel for    | *                                  |
1539   // | teams            |parallel for simd| *                                  |
1540   // | teams            |parallel sections| *                                  |
1541   // | teams            | task            | +                                  |
1542   // | teams            | taskyield       | +                                  |
1543   // | teams            | barrier         | +                                  |
1544   // | teams            | taskwait        | +                                  |
1545   // | teams            | flush           | +                                  |
1546   // | teams            | ordered         | +                                  |
1547   // | teams            | atomic          | +                                  |
1548   // | teams            | target          | +                                  |
1549   // | teams            | teams           | +                                  |
1550   // +------------------+-----------------+------------------------------------+
1551   if (Stack->getCurScope()) {
1552     auto ParentRegion = Stack->getParentDirective();
1553     bool NestingProhibited = false;
1554     bool CloseNesting = true;
1555     enum {
1556       NoRecommend,
1557       ShouldBeInParallelRegion,
1558       ShouldBeInOrderedRegion,
1559       ShouldBeInTargetRegion
1560     } Recommend = NoRecommend;
1561     if (isOpenMPSimdDirective(ParentRegion)) {
1562       // OpenMP [2.16, Nesting of Regions]
1563       // OpenMP constructs may not be nested inside a simd region.
1564       SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_simd);
1565       return true;
1566     }
1567     if (ParentRegion == OMPD_atomic) {
1568       // OpenMP [2.16, Nesting of Regions]
1569       // OpenMP constructs may not be nested inside an atomic region.
1570       SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
1571       return true;
1572     }
1573     if (CurrentRegion == OMPD_section) {
1574       // OpenMP [2.7.2, sections Construct, Restrictions]
1575       // Orphaned section directives are prohibited. That is, the section
1576       // directives must appear within the sections construct and must not be
1577       // encountered elsewhere in the sections region.
1578       if (ParentRegion != OMPD_sections &&
1579           ParentRegion != OMPD_parallel_sections) {
1580         SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
1581             << (ParentRegion != OMPD_unknown)
1582             << getOpenMPDirectiveName(ParentRegion);
1583         return true;
1584       }
1585       return false;
1586     }
1587     // Allow some constructs to be orphaned (they could be used in functions,
1588     // called from OpenMP regions with the required preconditions).
1589     if (ParentRegion == OMPD_unknown)
1590       return false;
1591     if (CurrentRegion == OMPD_master) {
1592       // OpenMP [2.16, Nesting of Regions]
1593       // A master region may not be closely nested inside a worksharing,
1594       // atomic, or explicit task region.
1595       NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
1596                           ParentRegion == OMPD_task;
1597     } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
1598       // OpenMP [2.16, Nesting of Regions]
1599       // A critical region may not be nested (closely or otherwise) inside a
1600       // critical region with the same name. Note that this restriction is not
1601       // sufficient to prevent deadlock.
1602       SourceLocation PreviousCriticalLoc;
1603       bool DeadLock =
1604           Stack->hasDirective([CurrentName, &PreviousCriticalLoc](
1605                                   OpenMPDirectiveKind K,
1606                                   const DeclarationNameInfo &DNI,
1607                                   SourceLocation Loc)
1608                                   ->bool {
1609                                 if (K == OMPD_critical &&
1610                                     DNI.getName() == CurrentName.getName()) {
1611                                   PreviousCriticalLoc = Loc;
1612                                   return true;
1613                                 } else
1614                                   return false;
1615                               },
1616                               false /* skip top directive */);
1617       if (DeadLock) {
1618         SemaRef.Diag(StartLoc,
1619                      diag::err_omp_prohibited_region_critical_same_name)
1620             << CurrentName.getName();
1621         if (PreviousCriticalLoc.isValid())
1622           SemaRef.Diag(PreviousCriticalLoc,
1623                        diag::note_omp_previous_critical_region);
1624         return true;
1625       }
1626     } else if (CurrentRegion == OMPD_barrier) {
1627       // OpenMP [2.16, Nesting of Regions]
1628       // A barrier region may not be closely nested inside a worksharing,
1629       // explicit task, critical, ordered, atomic, or master region.
1630       NestingProhibited =
1631           isOpenMPWorksharingDirective(ParentRegion) ||
1632           ParentRegion == OMPD_task || ParentRegion == OMPD_master ||
1633           ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered;
1634     } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
1635                !isOpenMPParallelDirective(CurrentRegion)) {
1636       // OpenMP [2.16, Nesting of Regions]
1637       // A worksharing region may not be closely nested inside a worksharing,
1638       // explicit task, critical, ordered, atomic, or master region.
1639       NestingProhibited =
1640           isOpenMPWorksharingDirective(ParentRegion) ||
1641           ParentRegion == OMPD_task || ParentRegion == OMPD_master ||
1642           ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered;
1643       Recommend = ShouldBeInParallelRegion;
1644     } else if (CurrentRegion == OMPD_ordered) {
1645       // OpenMP [2.16, Nesting of Regions]
1646       // An ordered region may not be closely nested inside a critical,
1647       // atomic, or explicit task region.
1648       // An ordered region must be closely nested inside a loop region (or
1649       // parallel loop region) with an ordered clause.
1650       NestingProhibited = ParentRegion == OMPD_critical ||
1651                           ParentRegion == OMPD_task ||
1652                           !Stack->isParentOrderedRegion();
1653       Recommend = ShouldBeInOrderedRegion;
1654     } else if (isOpenMPTeamsDirective(CurrentRegion)) {
1655       // OpenMP [2.16, Nesting of Regions]
1656       // If specified, a teams construct must be contained within a target
1657       // construct.
1658       NestingProhibited = ParentRegion != OMPD_target;
1659       Recommend = ShouldBeInTargetRegion;
1660       Stack->setParentTeamsRegionLoc(Stack->getConstructLoc());
1661     }
1662     if (!NestingProhibited && isOpenMPTeamsDirective(ParentRegion)) {
1663       // OpenMP [2.16, Nesting of Regions]
1664       // distribute, parallel, parallel sections, parallel workshare, and the
1665       // parallel loop and parallel loop SIMD constructs are the only OpenMP
1666       // constructs that can be closely nested in the teams region.
1667       // TODO: add distribute directive.
1668       NestingProhibited = !isOpenMPParallelDirective(CurrentRegion);
1669       Recommend = ShouldBeInParallelRegion;
1670     }
1671     if (NestingProhibited) {
1672       SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
1673           << CloseNesting << getOpenMPDirectiveName(ParentRegion) << Recommend
1674           << getOpenMPDirectiveName(CurrentRegion);
1675       return true;
1676     }
1677   }
1678   return false;
1679 }
1680 
1681 StmtResult Sema::ActOnOpenMPExecutableDirective(OpenMPDirectiveKind Kind,
1682                                                 const DeclarationNameInfo &DirName,
1683                                                 ArrayRef<OMPClause *> Clauses,
1684                                                 Stmt *AStmt,
1685                                                 SourceLocation StartLoc,
1686                                                 SourceLocation EndLoc) {
1687   StmtResult Res = StmtError();
1688   if (CheckNestingOfRegions(*this, DSAStack, Kind, DirName, StartLoc))
1689     return StmtError();
1690 
1691   llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
1692   llvm::DenseMap<VarDecl *, Expr *> VarsWithInheritedDSA;
1693   bool ErrorFound = false;
1694   ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
1695   if (AStmt) {
1696     assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
1697 
1698     // Check default data sharing attributes for referenced variables.
1699     DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
1700     DSAChecker.Visit(cast<CapturedStmt>(AStmt)->getCapturedStmt());
1701     if (DSAChecker.isErrorFound())
1702       return StmtError();
1703     // Generate list of implicitly defined firstprivate variables.
1704     VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
1705 
1706     if (!DSAChecker.getImplicitFirstprivate().empty()) {
1707       if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
1708               DSAChecker.getImplicitFirstprivate(), SourceLocation(),
1709               SourceLocation(), SourceLocation())) {
1710         ClausesWithImplicit.push_back(Implicit);
1711         ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
1712                      DSAChecker.getImplicitFirstprivate().size();
1713       } else
1714         ErrorFound = true;
1715     }
1716   }
1717 
1718   switch (Kind) {
1719   case OMPD_parallel:
1720     Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
1721                                        EndLoc);
1722     break;
1723   case OMPD_simd:
1724     Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
1725                                    VarsWithInheritedDSA);
1726     break;
1727   case OMPD_for:
1728     Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
1729                                   VarsWithInheritedDSA);
1730     break;
1731   case OMPD_for_simd:
1732     Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
1733                                       EndLoc, VarsWithInheritedDSA);
1734     break;
1735   case OMPD_sections:
1736     Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
1737                                        EndLoc);
1738     break;
1739   case OMPD_section:
1740     assert(ClausesWithImplicit.empty() &&
1741            "No clauses are allowed for 'omp section' directive");
1742     Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
1743     break;
1744   case OMPD_single:
1745     Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
1746                                      EndLoc);
1747     break;
1748   case OMPD_master:
1749     assert(ClausesWithImplicit.empty() &&
1750            "No clauses are allowed for 'omp master' directive");
1751     Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
1752     break;
1753   case OMPD_critical:
1754     assert(ClausesWithImplicit.empty() &&
1755            "No clauses are allowed for 'omp critical' directive");
1756     Res = ActOnOpenMPCriticalDirective(DirName, AStmt, StartLoc, EndLoc);
1757     break;
1758   case OMPD_parallel_for:
1759     Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
1760                                           EndLoc, VarsWithInheritedDSA);
1761     break;
1762   case OMPD_parallel_for_simd:
1763     Res = ActOnOpenMPParallelForSimdDirective(
1764         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
1765     break;
1766   case OMPD_parallel_sections:
1767     Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
1768                                                StartLoc, EndLoc);
1769     break;
1770   case OMPD_task:
1771     Res =
1772         ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
1773     break;
1774   case OMPD_taskyield:
1775     assert(ClausesWithImplicit.empty() &&
1776            "No clauses are allowed for 'omp taskyield' directive");
1777     assert(AStmt == nullptr &&
1778            "No associated statement allowed for 'omp taskyield' directive");
1779     Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
1780     break;
1781   case OMPD_barrier:
1782     assert(ClausesWithImplicit.empty() &&
1783            "No clauses are allowed for 'omp barrier' directive");
1784     assert(AStmt == nullptr &&
1785            "No associated statement allowed for 'omp barrier' directive");
1786     Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
1787     break;
1788   case OMPD_taskwait:
1789     assert(ClausesWithImplicit.empty() &&
1790            "No clauses are allowed for 'omp taskwait' directive");
1791     assert(AStmt == nullptr &&
1792            "No associated statement allowed for 'omp taskwait' directive");
1793     Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
1794     break;
1795   case OMPD_flush:
1796     assert(AStmt == nullptr &&
1797            "No associated statement allowed for 'omp flush' directive");
1798     Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
1799     break;
1800   case OMPD_ordered:
1801     assert(ClausesWithImplicit.empty() &&
1802            "No clauses are allowed for 'omp ordered' directive");
1803     Res = ActOnOpenMPOrderedDirective(AStmt, StartLoc, EndLoc);
1804     break;
1805   case OMPD_atomic:
1806     Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
1807                                      EndLoc);
1808     break;
1809   case OMPD_teams:
1810     Res =
1811         ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
1812     break;
1813   case OMPD_target:
1814     Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
1815                                      EndLoc);
1816     break;
1817   case OMPD_threadprivate:
1818     llvm_unreachable("OpenMP Directive is not allowed");
1819   case OMPD_unknown:
1820     llvm_unreachable("Unknown OpenMP directive");
1821   }
1822 
1823   for (auto P : VarsWithInheritedDSA) {
1824     Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
1825         << P.first << P.second->getSourceRange();
1826   }
1827   if (!VarsWithInheritedDSA.empty())
1828     return StmtError();
1829 
1830   if (ErrorFound)
1831     return StmtError();
1832   return Res;
1833 }
1834 
1835 StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
1836                                               Stmt *AStmt,
1837                                               SourceLocation StartLoc,
1838                                               SourceLocation EndLoc) {
1839   assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
1840   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
1841   // 1.2.2 OpenMP Language Terminology
1842   // Structured block - An executable statement with a single entry at the
1843   // top and a single exit at the bottom.
1844   // The point of exit cannot be a branch out of the structured block.
1845   // longjmp() and throw() must not violate the entry/exit criteria.
1846   CS->getCapturedDecl()->setNothrow();
1847 
1848   getCurFunction()->setHasBranchProtectedScope();
1849 
1850   return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
1851                                       AStmt);
1852 }
1853 
1854 namespace {
1855 /// \brief Helper class for checking canonical form of the OpenMP loops and
1856 /// extracting iteration space of each loop in the loop nest, that will be used
1857 /// for IR generation.
1858 class OpenMPIterationSpaceChecker {
1859   /// \brief Reference to Sema.
1860   Sema &SemaRef;
1861   /// \brief A location for diagnostics (when there is no some better location).
1862   SourceLocation DefaultLoc;
1863   /// \brief A location for diagnostics (when increment is not compatible).
1864   SourceLocation ConditionLoc;
1865   /// \brief A source location for referring to loop init later.
1866   SourceRange InitSrcRange;
1867   /// \brief A source location for referring to condition later.
1868   SourceRange ConditionSrcRange;
1869   /// \brief A source location for referring to increment later.
1870   SourceRange IncrementSrcRange;
1871   /// \brief Loop variable.
1872   VarDecl *Var;
1873   /// \brief Reference to loop variable.
1874   DeclRefExpr *VarRef;
1875   /// \brief Lower bound (initializer for the var).
1876   Expr *LB;
1877   /// \brief Upper bound.
1878   Expr *UB;
1879   /// \brief Loop step (increment).
1880   Expr *Step;
1881   /// \brief This flag is true when condition is one of:
1882   ///   Var <  UB
1883   ///   Var <= UB
1884   ///   UB  >  Var
1885   ///   UB  >= Var
1886   bool TestIsLessOp;
1887   /// \brief This flag is true when condition is strict ( < or > ).
1888   bool TestIsStrictOp;
1889   /// \brief This flag is true when step is subtracted on each iteration.
1890   bool SubtractStep;
1891 
1892 public:
1893   OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
1894       : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc),
1895         InitSrcRange(SourceRange()), ConditionSrcRange(SourceRange()),
1896         IncrementSrcRange(SourceRange()), Var(nullptr), VarRef(nullptr),
1897         LB(nullptr), UB(nullptr), Step(nullptr), TestIsLessOp(false),
1898         TestIsStrictOp(false), SubtractStep(false) {}
1899   /// \brief Check init-expr for canonical loop form and save loop counter
1900   /// variable - #Var and its initialization value - #LB.
1901   bool CheckInit(Stmt *S);
1902   /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags
1903   /// for less/greater and for strict/non-strict comparison.
1904   bool CheckCond(Expr *S);
1905   /// \brief Check incr-expr for canonical loop form and return true if it
1906   /// does not conform, otherwise save loop step (#Step).
1907   bool CheckInc(Expr *S);
1908   /// \brief Return the loop counter variable.
1909   VarDecl *GetLoopVar() const { return Var; }
1910   /// \brief Return the reference expression to loop counter variable.
1911   DeclRefExpr *GetLoopVarRefExpr() const { return VarRef; }
1912   /// \brief Source range of the loop init.
1913   SourceRange GetInitSrcRange() const { return InitSrcRange; }
1914   /// \brief Source range of the loop condition.
1915   SourceRange GetConditionSrcRange() const { return ConditionSrcRange; }
1916   /// \brief Source range of the loop increment.
1917   SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; }
1918   /// \brief True if the step should be subtracted.
1919   bool ShouldSubtractStep() const { return SubtractStep; }
1920   /// \brief Build the expression to calculate the number of iterations.
1921   Expr *BuildNumIterations(Scope *S, const bool LimitedType) const;
1922   /// \brief Build reference expression to the counter be used for codegen.
1923   Expr *BuildCounterVar() const;
1924   /// \brief Build initization of the counter be used for codegen.
1925   Expr *BuildCounterInit() const;
1926   /// \brief Build step of the counter be used for codegen.
1927   Expr *BuildCounterStep() const;
1928   /// \brief Return true if any expression is dependent.
1929   bool Dependent() const;
1930 
1931 private:
1932   /// \brief Check the right-hand side of an assignment in the increment
1933   /// expression.
1934   bool CheckIncRHS(Expr *RHS);
1935   /// \brief Helper to set loop counter variable and its initializer.
1936   bool SetVarAndLB(VarDecl *NewVar, DeclRefExpr *NewVarRefExpr, Expr *NewLB);
1937   /// \brief Helper to set upper bound.
1938   bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, const SourceRange &SR,
1939              const SourceLocation &SL);
1940   /// \brief Helper to set loop increment.
1941   bool SetStep(Expr *NewStep, bool Subtract);
1942 };
1943 
1944 bool OpenMPIterationSpaceChecker::Dependent() const {
1945   if (!Var) {
1946     assert(!LB && !UB && !Step);
1947     return false;
1948   }
1949   return Var->getType()->isDependentType() || (LB && LB->isValueDependent()) ||
1950          (UB && UB->isValueDependent()) || (Step && Step->isValueDependent());
1951 }
1952 
1953 bool OpenMPIterationSpaceChecker::SetVarAndLB(VarDecl *NewVar,
1954                                               DeclRefExpr *NewVarRefExpr,
1955                                               Expr *NewLB) {
1956   // State consistency checking to ensure correct usage.
1957   assert(Var == nullptr && LB == nullptr && VarRef == nullptr &&
1958          UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
1959   if (!NewVar || !NewLB)
1960     return true;
1961   Var = NewVar;
1962   VarRef = NewVarRefExpr;
1963   LB = NewLB;
1964   return false;
1965 }
1966 
1967 bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp,
1968                                         const SourceRange &SR,
1969                                         const SourceLocation &SL) {
1970   // State consistency checking to ensure correct usage.
1971   assert(Var != nullptr && LB != nullptr && UB == nullptr && Step == nullptr &&
1972          !TestIsLessOp && !TestIsStrictOp);
1973   if (!NewUB)
1974     return true;
1975   UB = NewUB;
1976   TestIsLessOp = LessOp;
1977   TestIsStrictOp = StrictOp;
1978   ConditionSrcRange = SR;
1979   ConditionLoc = SL;
1980   return false;
1981 }
1982 
1983 bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) {
1984   // State consistency checking to ensure correct usage.
1985   assert(Var != nullptr && LB != nullptr && Step == nullptr);
1986   if (!NewStep)
1987     return true;
1988   if (!NewStep->isValueDependent()) {
1989     // Check that the step is integer expression.
1990     SourceLocation StepLoc = NewStep->getLocStart();
1991     ExprResult Val =
1992         SemaRef.PerformOpenMPImplicitIntegerConversion(StepLoc, NewStep);
1993     if (Val.isInvalid())
1994       return true;
1995     NewStep = Val.get();
1996 
1997     // OpenMP [2.6, Canonical Loop Form, Restrictions]
1998     //  If test-expr is of form var relational-op b and relational-op is < or
1999     //  <= then incr-expr must cause var to increase on each iteration of the
2000     //  loop. If test-expr is of form var relational-op b and relational-op is
2001     //  > or >= then incr-expr must cause var to decrease on each iteration of
2002     //  the loop.
2003     //  If test-expr is of form b relational-op var and relational-op is < or
2004     //  <= then incr-expr must cause var to decrease on each iteration of the
2005     //  loop. If test-expr is of form b relational-op var and relational-op is
2006     //  > or >= then incr-expr must cause var to increase on each iteration of
2007     //  the loop.
2008     llvm::APSInt Result;
2009     bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
2010     bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
2011     bool IsConstNeg =
2012         IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
2013     bool IsConstPos =
2014         IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
2015     bool IsConstZero = IsConstant && !Result.getBoolValue();
2016     if (UB && (IsConstZero ||
2017                (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
2018                              : (IsConstPos || (IsUnsigned && !Subtract))))) {
2019       SemaRef.Diag(NewStep->getExprLoc(),
2020                    diag::err_omp_loop_incr_not_compatible)
2021           << Var << TestIsLessOp << NewStep->getSourceRange();
2022       SemaRef.Diag(ConditionLoc,
2023                    diag::note_omp_loop_cond_requres_compatible_incr)
2024           << TestIsLessOp << ConditionSrcRange;
2025       return true;
2026     }
2027     if (TestIsLessOp == Subtract) {
2028       NewStep = SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus,
2029                                              NewStep).get();
2030       Subtract = !Subtract;
2031     }
2032   }
2033 
2034   Step = NewStep;
2035   SubtractStep = Subtract;
2036   return false;
2037 }
2038 
2039 bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S) {
2040   // Check init-expr for canonical loop form and save loop counter
2041   // variable - #Var and its initialization value - #LB.
2042   // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
2043   //   var = lb
2044   //   integer-type var = lb
2045   //   random-access-iterator-type var = lb
2046   //   pointer-type var = lb
2047   //
2048   if (!S) {
2049     SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
2050     return true;
2051   }
2052   InitSrcRange = S->getSourceRange();
2053   if (Expr *E = dyn_cast<Expr>(S))
2054     S = E->IgnoreParens();
2055   if (auto BO = dyn_cast<BinaryOperator>(S)) {
2056     if (BO->getOpcode() == BO_Assign)
2057       if (auto DRE = dyn_cast<DeclRefExpr>(BO->getLHS()->IgnoreParens()))
2058         return SetVarAndLB(dyn_cast<VarDecl>(DRE->getDecl()), DRE,
2059                            BO->getRHS());
2060   } else if (auto DS = dyn_cast<DeclStmt>(S)) {
2061     if (DS->isSingleDecl()) {
2062       if (auto Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
2063         if (Var->hasInit()) {
2064           // Accept non-canonical init form here but emit ext. warning.
2065           if (Var->getInitStyle() != VarDecl::CInit)
2066             SemaRef.Diag(S->getLocStart(),
2067                          diag::ext_omp_loop_not_canonical_init)
2068                 << S->getSourceRange();
2069           return SetVarAndLB(Var, nullptr, Var->getInit());
2070         }
2071       }
2072     }
2073   } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S))
2074     if (CE->getOperator() == OO_Equal)
2075       if (auto DRE = dyn_cast<DeclRefExpr>(CE->getArg(0)))
2076         return SetVarAndLB(dyn_cast<VarDecl>(DRE->getDecl()), DRE,
2077                            CE->getArg(1));
2078 
2079   SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init)
2080       << S->getSourceRange();
2081   return true;
2082 }
2083 
2084 /// \brief Ignore parenthesizes, implicit casts, copy constructor and return the
2085 /// variable (which may be the loop variable) if possible.
2086 static const VarDecl *GetInitVarDecl(const Expr *E) {
2087   if (!E)
2088     return nullptr;
2089   E = E->IgnoreParenImpCasts();
2090   if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
2091     if (const CXXConstructorDecl *Ctor = CE->getConstructor())
2092       if (Ctor->isCopyConstructor() && CE->getNumArgs() == 1 &&
2093           CE->getArg(0) != nullptr)
2094         E = CE->getArg(0)->IgnoreParenImpCasts();
2095   auto DRE = dyn_cast_or_null<DeclRefExpr>(E);
2096   if (!DRE)
2097     return nullptr;
2098   return dyn_cast<VarDecl>(DRE->getDecl());
2099 }
2100 
2101 bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) {
2102   // Check test-expr for canonical form, save upper-bound UB, flags for
2103   // less/greater and for strict/non-strict comparison.
2104   // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
2105   //   var relational-op b
2106   //   b relational-op var
2107   //
2108   if (!S) {
2109     SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << Var;
2110     return true;
2111   }
2112   S = S->IgnoreParenImpCasts();
2113   SourceLocation CondLoc = S->getLocStart();
2114   if (auto BO = dyn_cast<BinaryOperator>(S)) {
2115     if (BO->isRelationalOp()) {
2116       if (GetInitVarDecl(BO->getLHS()) == Var)
2117         return SetUB(BO->getRHS(),
2118                      (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
2119                      (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
2120                      BO->getSourceRange(), BO->getOperatorLoc());
2121       if (GetInitVarDecl(BO->getRHS()) == Var)
2122         return SetUB(BO->getLHS(),
2123                      (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
2124                      (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
2125                      BO->getSourceRange(), BO->getOperatorLoc());
2126     }
2127   } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S)) {
2128     if (CE->getNumArgs() == 2) {
2129       auto Op = CE->getOperator();
2130       switch (Op) {
2131       case OO_Greater:
2132       case OO_GreaterEqual:
2133       case OO_Less:
2134       case OO_LessEqual:
2135         if (GetInitVarDecl(CE->getArg(0)) == Var)
2136           return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
2137                        Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
2138                        CE->getOperatorLoc());
2139         if (GetInitVarDecl(CE->getArg(1)) == Var)
2140           return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
2141                        Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
2142                        CE->getOperatorLoc());
2143         break;
2144       default:
2145         break;
2146       }
2147     }
2148   }
2149   SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
2150       << S->getSourceRange() << Var;
2151   return true;
2152 }
2153 
2154 bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) {
2155   // RHS of canonical loop form increment can be:
2156   //   var + incr
2157   //   incr + var
2158   //   var - incr
2159   //
2160   RHS = RHS->IgnoreParenImpCasts();
2161   if (auto BO = dyn_cast<BinaryOperator>(RHS)) {
2162     if (BO->isAdditiveOp()) {
2163       bool IsAdd = BO->getOpcode() == BO_Add;
2164       if (GetInitVarDecl(BO->getLHS()) == Var)
2165         return SetStep(BO->getRHS(), !IsAdd);
2166       if (IsAdd && GetInitVarDecl(BO->getRHS()) == Var)
2167         return SetStep(BO->getLHS(), false);
2168     }
2169   } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
2170     bool IsAdd = CE->getOperator() == OO_Plus;
2171     if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
2172       if (GetInitVarDecl(CE->getArg(0)) == Var)
2173         return SetStep(CE->getArg(1), !IsAdd);
2174       if (IsAdd && GetInitVarDecl(CE->getArg(1)) == Var)
2175         return SetStep(CE->getArg(0), false);
2176     }
2177   }
2178   SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr)
2179       << RHS->getSourceRange() << Var;
2180   return true;
2181 }
2182 
2183 bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) {
2184   // Check incr-expr for canonical loop form and return true if it
2185   // does not conform.
2186   // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
2187   //   ++var
2188   //   var++
2189   //   --var
2190   //   var--
2191   //   var += incr
2192   //   var -= incr
2193   //   var = var + incr
2194   //   var = incr + var
2195   //   var = var - incr
2196   //
2197   if (!S) {
2198     SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << Var;
2199     return true;
2200   }
2201   IncrementSrcRange = S->getSourceRange();
2202   S = S->IgnoreParens();
2203   if (auto UO = dyn_cast<UnaryOperator>(S)) {
2204     if (UO->isIncrementDecrementOp() && GetInitVarDecl(UO->getSubExpr()) == Var)
2205       return SetStep(
2206           SemaRef.ActOnIntegerConstant(UO->getLocStart(),
2207                                        (UO->isDecrementOp() ? -1 : 1)).get(),
2208           false);
2209   } else if (auto BO = dyn_cast<BinaryOperator>(S)) {
2210     switch (BO->getOpcode()) {
2211     case BO_AddAssign:
2212     case BO_SubAssign:
2213       if (GetInitVarDecl(BO->getLHS()) == Var)
2214         return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
2215       break;
2216     case BO_Assign:
2217       if (GetInitVarDecl(BO->getLHS()) == Var)
2218         return CheckIncRHS(BO->getRHS());
2219       break;
2220     default:
2221       break;
2222     }
2223   } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S)) {
2224     switch (CE->getOperator()) {
2225     case OO_PlusPlus:
2226     case OO_MinusMinus:
2227       if (GetInitVarDecl(CE->getArg(0)) == Var)
2228         return SetStep(
2229             SemaRef.ActOnIntegerConstant(
2230                         CE->getLocStart(),
2231                         ((CE->getOperator() == OO_MinusMinus) ? -1 : 1)).get(),
2232             false);
2233       break;
2234     case OO_PlusEqual:
2235     case OO_MinusEqual:
2236       if (GetInitVarDecl(CE->getArg(0)) == Var)
2237         return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
2238       break;
2239     case OO_Equal:
2240       if (GetInitVarDecl(CE->getArg(0)) == Var)
2241         return CheckIncRHS(CE->getArg(1));
2242       break;
2243     default:
2244       break;
2245     }
2246   }
2247   SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr)
2248       << S->getSourceRange() << Var;
2249   return true;
2250 }
2251 
2252 /// \brief Build the expression to calculate the number of iterations.
2253 Expr *
2254 OpenMPIterationSpaceChecker::BuildNumIterations(Scope *S,
2255                                                 const bool LimitedType) const {
2256   ExprResult Diff;
2257   if (Var->getType()->isIntegerType() || Var->getType()->isPointerType() ||
2258       SemaRef.getLangOpts().CPlusPlus) {
2259     // Upper - Lower
2260     Expr *Upper = TestIsLessOp ? UB : LB;
2261     Expr *Lower = TestIsLessOp ? LB : UB;
2262 
2263     Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
2264 
2265     if (!Diff.isUsable() && Var->getType()->getAsCXXRecordDecl()) {
2266       // BuildBinOp already emitted error, this one is to point user to upper
2267       // and lower bound, and to tell what is passed to 'operator-'.
2268       SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx)
2269           << Upper->getSourceRange() << Lower->getSourceRange();
2270       return nullptr;
2271     }
2272   }
2273 
2274   if (!Diff.isUsable())
2275     return nullptr;
2276 
2277   // Upper - Lower [- 1]
2278   if (TestIsStrictOp)
2279     Diff = SemaRef.BuildBinOp(
2280         S, DefaultLoc, BO_Sub, Diff.get(),
2281         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
2282   if (!Diff.isUsable())
2283     return nullptr;
2284 
2285   // Upper - Lower [- 1] + Step
2286   Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(),
2287                             Step->IgnoreImplicit());
2288   if (!Diff.isUsable())
2289     return nullptr;
2290 
2291   // Parentheses (for dumping/debugging purposes only).
2292   Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
2293   if (!Diff.isUsable())
2294     return nullptr;
2295 
2296   // (Upper - Lower [- 1] + Step) / Step
2297   Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(),
2298                             Step->IgnoreImplicit());
2299   if (!Diff.isUsable())
2300     return nullptr;
2301 
2302   // OpenMP runtime requires 32-bit or 64-bit loop variables.
2303   if (LimitedType) {
2304     auto &C = SemaRef.Context;
2305     QualType Type = Diff.get()->getType();
2306     unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
2307     if (NewSize != C.getTypeSize(Type)) {
2308       if (NewSize < C.getTypeSize(Type)) {
2309         assert(NewSize == 64 && "incorrect loop var size");
2310         SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
2311             << InitSrcRange << ConditionSrcRange;
2312       }
2313       QualType NewType = C.getIntTypeForBitwidth(
2314           NewSize, Type->hasSignedIntegerRepresentation());
2315       Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
2316                                                Sema::AA_Converting, true);
2317       if (!Diff.isUsable())
2318         return nullptr;
2319     }
2320   }
2321 
2322   return Diff.get();
2323 }
2324 
2325 /// \brief Build reference expression to the counter be used for codegen.
2326 Expr *OpenMPIterationSpaceChecker::BuildCounterVar() const {
2327   return DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
2328                              GetIncrementSrcRange().getBegin(), Var, false,
2329                              DefaultLoc, Var->getType(), VK_LValue);
2330 }
2331 
2332 /// \brief Build initization of the counter be used for codegen.
2333 Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; }
2334 
2335 /// \brief Build step of the counter be used for codegen.
2336 Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; }
2337 
2338 /// \brief Iteration space of a single for loop.
2339 struct LoopIterationSpace {
2340   /// \brief This expression calculates the number of iterations in the loop.
2341   /// It is always possible to calculate it before starting the loop.
2342   Expr *NumIterations;
2343   /// \brief The loop counter variable.
2344   Expr *CounterVar;
2345   /// \brief This is initializer for the initial value of #CounterVar.
2346   Expr *CounterInit;
2347   /// \brief This is step for the #CounterVar used to generate its update:
2348   /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
2349   Expr *CounterStep;
2350   /// \brief Should step be subtracted?
2351   bool Subtract;
2352   /// \brief Source range of the loop init.
2353   SourceRange InitSrcRange;
2354   /// \brief Source range of the loop condition.
2355   SourceRange CondSrcRange;
2356   /// \brief Source range of the loop increment.
2357   SourceRange IncSrcRange;
2358 };
2359 
2360 /// \brief The resulting expressions built for the OpenMP loop CodeGen for the
2361 /// whole collapsed loop nest. See class OMPLoopDirective for their description.
2362 struct BuiltLoopExprs {
2363   Expr *IterationVarRef;
2364   Expr *LastIteration;
2365   Expr *CalcLastIteration;
2366   Expr *PreCond;
2367   Expr *Cond;
2368   Expr *SeparatedCond;
2369   Expr *Init;
2370   Expr *Inc;
2371   SmallVector<Expr *, 4> Counters;
2372   SmallVector<Expr *, 4> Updates;
2373   SmallVector<Expr *, 4> Finals;
2374 
2375   bool builtAll() {
2376     return IterationVarRef != nullptr && LastIteration != nullptr &&
2377            PreCond != nullptr && Cond != nullptr && SeparatedCond != nullptr &&
2378            Init != nullptr && Inc != nullptr;
2379   }
2380   void clear(unsigned size) {
2381     IterationVarRef = nullptr;
2382     LastIteration = nullptr;
2383     CalcLastIteration = nullptr;
2384     PreCond = nullptr;
2385     Cond = nullptr;
2386     SeparatedCond = nullptr;
2387     Init = nullptr;
2388     Inc = nullptr;
2389     Counters.resize(size);
2390     Updates.resize(size);
2391     Finals.resize(size);
2392     for (unsigned i = 0; i < size; ++i) {
2393       Counters[i] = nullptr;
2394       Updates[i] = nullptr;
2395       Finals[i] = nullptr;
2396     }
2397   }
2398 };
2399 
2400 } // namespace
2401 
2402 /// \brief Called on a for stmt to check and extract its iteration space
2403 /// for further processing (such as collapsing).
2404 static bool CheckOpenMPIterationSpace(
2405     OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
2406     unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
2407     Expr *NestedLoopCountExpr,
2408     llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA,
2409     LoopIterationSpace &ResultIterSpace) {
2410   // OpenMP [2.6, Canonical Loop Form]
2411   //   for (init-expr; test-expr; incr-expr) structured-block
2412   auto For = dyn_cast_or_null<ForStmt>(S);
2413   if (!For) {
2414     SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for)
2415         << (NestedLoopCountExpr != nullptr) << getOpenMPDirectiveName(DKind)
2416         << NestedLoopCount << (CurrentNestedLoopCount > 0)
2417         << CurrentNestedLoopCount;
2418     if (NestedLoopCount > 1)
2419       SemaRef.Diag(NestedLoopCountExpr->getExprLoc(),
2420                    diag::note_omp_collapse_expr)
2421           << NestedLoopCountExpr->getSourceRange();
2422     return true;
2423   }
2424   assert(For->getBody());
2425 
2426   OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
2427 
2428   // Check init.
2429   auto Init = For->getInit();
2430   if (ISC.CheckInit(Init)) {
2431     return true;
2432   }
2433 
2434   bool HasErrors = false;
2435 
2436   // Check loop variable's type.
2437   auto Var = ISC.GetLoopVar();
2438 
2439   // OpenMP [2.6, Canonical Loop Form]
2440   // Var is one of the following:
2441   //   A variable of signed or unsigned integer type.
2442   //   For C++, a variable of a random access iterator type.
2443   //   For C, a variable of a pointer type.
2444   auto VarType = Var->getType();
2445   if (!VarType->isDependentType() && !VarType->isIntegerType() &&
2446       !VarType->isPointerType() &&
2447       !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
2448     SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type)
2449         << SemaRef.getLangOpts().CPlusPlus;
2450     HasErrors = true;
2451   }
2452 
2453   // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in a
2454   // Construct
2455   // The loop iteration variable(s) in the associated for-loop(s) of a for or
2456   // parallel for construct is (are) private.
2457   // The loop iteration variable in the associated for-loop of a simd construct
2458   // with just one associated for-loop is linear with a constant-linear-step
2459   // that is the increment of the associated for-loop.
2460   // Exclude loop var from the list of variables with implicitly defined data
2461   // sharing attributes.
2462   VarsWithImplicitDSA.erase(Var);
2463 
2464   // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced in
2465   // a Construct, C/C++].
2466   // The loop iteration variable in the associated for-loop of a simd construct
2467   // with just one associated for-loop may be listed in a linear clause with a
2468   // constant-linear-step that is the increment of the associated for-loop.
2469   // The loop iteration variable(s) in the associated for-loop(s) of a for or
2470   // parallel for construct may be listed in a private or lastprivate clause.
2471   DSAStackTy::DSAVarData DVar = DSA.getTopDSA(Var, false);
2472   auto LoopVarRefExpr = ISC.GetLoopVarRefExpr();
2473   // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
2474   // declared in the loop and it is predetermined as a private.
2475   auto PredeterminedCKind =
2476       isOpenMPSimdDirective(DKind)
2477           ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
2478           : OMPC_private;
2479   if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
2480         DVar.CKind != PredeterminedCKind) ||
2481        (isOpenMPWorksharingDirective(DKind) && !isOpenMPSimdDirective(DKind) &&
2482         DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private &&
2483         DVar.CKind != OMPC_lastprivate)) &&
2484       (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
2485     SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa)
2486         << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
2487         << getOpenMPClauseName(PredeterminedCKind);
2488     ReportOriginalDSA(SemaRef, &DSA, Var, DVar, true);
2489     HasErrors = true;
2490   } else if (LoopVarRefExpr != nullptr) {
2491     // Make the loop iteration variable private (for worksharing constructs),
2492     // linear (for simd directives with the only one associated loop) or
2493     // lastprivate (for simd directives with several collapsed loops).
2494     // FIXME: the next check and error message must be removed once the
2495     // capturing of global variables in loops is fixed.
2496     if (DVar.CKind == OMPC_unknown)
2497       DVar = DSA.hasDSA(Var, isOpenMPPrivate, MatchesAlways(),
2498                         /*FromParent=*/false);
2499     if (!Var->hasLocalStorage() && DVar.CKind == OMPC_unknown) {
2500       SemaRef.Diag(Init->getLocStart(), diag::err_omp_global_loop_var_dsa)
2501           << getOpenMPClauseName(PredeterminedCKind)
2502           << getOpenMPDirectiveName(DKind);
2503       HasErrors = true;
2504     } else
2505       DSA.addDSA(Var, LoopVarRefExpr, PredeterminedCKind);
2506   }
2507 
2508   assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
2509 
2510   // Check test-expr.
2511   HasErrors |= ISC.CheckCond(For->getCond());
2512 
2513   // Check incr-expr.
2514   HasErrors |= ISC.CheckInc(For->getInc());
2515 
2516   if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
2517     return HasErrors;
2518 
2519   // Build the loop's iteration space representation.
2520   ResultIterSpace.NumIterations = ISC.BuildNumIterations(
2521       DSA.getCurScope(), /* LimitedType */ isOpenMPWorksharingDirective(DKind));
2522   ResultIterSpace.CounterVar = ISC.BuildCounterVar();
2523   ResultIterSpace.CounterInit = ISC.BuildCounterInit();
2524   ResultIterSpace.CounterStep = ISC.BuildCounterStep();
2525   ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange();
2526   ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange();
2527   ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange();
2528   ResultIterSpace.Subtract = ISC.ShouldSubtractStep();
2529 
2530   HasErrors |= (ResultIterSpace.NumIterations == nullptr ||
2531                 ResultIterSpace.CounterVar == nullptr ||
2532                 ResultIterSpace.CounterInit == nullptr ||
2533                 ResultIterSpace.CounterStep == nullptr);
2534 
2535   return HasErrors;
2536 }
2537 
2538 /// \brief Build a variable declaration for OpenMP loop iteration variable.
2539 static VarDecl *BuildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
2540                              StringRef Name) {
2541   DeclContext *DC = SemaRef.CurContext;
2542   IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
2543   TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
2544   VarDecl *Decl =
2545       VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
2546   Decl->setImplicit();
2547   return Decl;
2548 }
2549 
2550 /// \brief Build 'VarRef = Start + Iter * Step'.
2551 static ExprResult BuildCounterUpdate(Sema &SemaRef, Scope *S,
2552                                      SourceLocation Loc, ExprResult VarRef,
2553                                      ExprResult Start, ExprResult Iter,
2554                                      ExprResult Step, bool Subtract) {
2555   // Add parentheses (for debugging purposes only).
2556   Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
2557   if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
2558       !Step.isUsable())
2559     return ExprError();
2560 
2561   ExprResult Update = SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(),
2562                                          Step.get()->IgnoreImplicit());
2563   if (!Update.isUsable())
2564     return ExprError();
2565 
2566   // Build 'VarRef = Start + Iter * Step'.
2567   Update = SemaRef.BuildBinOp(S, Loc, (Subtract ? BO_Sub : BO_Add),
2568                               Start.get()->IgnoreImplicit(), Update.get());
2569   if (!Update.isUsable())
2570     return ExprError();
2571 
2572   Update = SemaRef.PerformImplicitConversion(
2573       Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
2574   if (!Update.isUsable())
2575     return ExprError();
2576 
2577   Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
2578   return Update;
2579 }
2580 
2581 /// \brief Convert integer expression \a E to make it have at least \a Bits
2582 /// bits.
2583 static ExprResult WidenIterationCount(unsigned Bits, Expr *E,
2584                                       Sema &SemaRef) {
2585   if (E == nullptr)
2586     return ExprError();
2587   auto &C = SemaRef.Context;
2588   QualType OldType = E->getType();
2589   unsigned HasBits = C.getTypeSize(OldType);
2590   if (HasBits >= Bits)
2591     return ExprResult(E);
2592   // OK to convert to signed, because new type has more bits than old.
2593   QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
2594   return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
2595                                            true);
2596 }
2597 
2598 /// \brief Check if the given expression \a E is a constant integer that fits
2599 /// into \a Bits bits.
2600 static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) {
2601   if (E == nullptr)
2602     return false;
2603   llvm::APSInt Result;
2604   if (E->isIntegerConstantExpr(Result, SemaRef.Context))
2605     return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
2606   return false;
2607 }
2608 
2609 /// \brief Called on a for stmt to check itself and nested loops (if any).
2610 /// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
2611 /// number of collapsed loops otherwise.
2612 static unsigned
2613 CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *NestedLoopCountExpr,
2614                 Stmt *AStmt, Sema &SemaRef, DSAStackTy &DSA,
2615                 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA,
2616                 BuiltLoopExprs &Built) {
2617   unsigned NestedLoopCount = 1;
2618   if (NestedLoopCountExpr) {
2619     // Found 'collapse' clause - calculate collapse number.
2620     llvm::APSInt Result;
2621     if (NestedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
2622       NestedLoopCount = Result.getLimitedValue();
2623   }
2624   // This is helper routine for loop directives (e.g., 'for', 'simd',
2625   // 'for simd', etc.).
2626   SmallVector<LoopIterationSpace, 4> IterSpaces;
2627   IterSpaces.resize(NestedLoopCount);
2628   Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
2629   for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
2630     if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt,
2631                                   NestedLoopCount, NestedLoopCountExpr,
2632                                   VarsWithImplicitDSA, IterSpaces[Cnt]))
2633       return 0;
2634     // Move on to the next nested for loop, or to the loop body.
2635     // OpenMP [2.8.1, simd construct, Restrictions]
2636     // All loops associated with the construct must be perfectly nested; that
2637     // is, there must be no intervening code nor any OpenMP directive between
2638     // any two loops.
2639     CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
2640   }
2641 
2642   Built.clear(/* size */ NestedLoopCount);
2643 
2644   if (SemaRef.CurContext->isDependentContext())
2645     return NestedLoopCount;
2646 
2647   // An example of what is generated for the following code:
2648   //
2649   //   #pragma omp simd collapse(2)
2650   //   for (i = 0; i < NI; ++i)
2651   //     for (j = J0; j < NJ; j+=2) {
2652   //     <loop body>
2653   //   }
2654   //
2655   // We generate the code below.
2656   // Note: the loop body may be outlined in CodeGen.
2657   // Note: some counters may be C++ classes, operator- is used to find number of
2658   // iterations and operator+= to calculate counter value.
2659   // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
2660   // or i64 is currently supported).
2661   //
2662   //   #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
2663   //   for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
2664   //     .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
2665   //     .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
2666   //     // similar updates for vars in clauses (e.g. 'linear')
2667   //     <loop body (using local i and j)>
2668   //   }
2669   //   i = NI; // assign final values of counters
2670   //   j = NJ;
2671   //
2672 
2673   // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
2674   // the iteration counts of the collapsed for loops.
2675   auto N0 = IterSpaces[0].NumIterations;
2676   ExprResult LastIteration32 = WidenIterationCount(32 /* Bits */, N0, SemaRef);
2677   ExprResult LastIteration64 = WidenIterationCount(64 /* Bits */, N0, SemaRef);
2678 
2679   if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
2680     return NestedLoopCount;
2681 
2682   auto &C = SemaRef.Context;
2683   bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
2684 
2685   Scope *CurScope = DSA.getCurScope();
2686   for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
2687     auto N = IterSpaces[Cnt].NumIterations;
2688     AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
2689     if (LastIteration32.isUsable())
2690       LastIteration32 = SemaRef.BuildBinOp(CurScope, SourceLocation(), BO_Mul,
2691                                            LastIteration32.get(), N);
2692     if (LastIteration64.isUsable())
2693       LastIteration64 = SemaRef.BuildBinOp(CurScope, SourceLocation(), BO_Mul,
2694                                            LastIteration64.get(), N);
2695   }
2696 
2697   // Choose either the 32-bit or 64-bit version.
2698   ExprResult LastIteration = LastIteration64;
2699   if (LastIteration32.isUsable() &&
2700       C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
2701       (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
2702        FitsInto(
2703            32 /* Bits */,
2704            LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
2705            LastIteration64.get(), SemaRef)))
2706     LastIteration = LastIteration32;
2707 
2708   if (!LastIteration.isUsable())
2709     return 0;
2710 
2711   // Save the number of iterations.
2712   ExprResult NumIterations = LastIteration;
2713   {
2714     LastIteration = SemaRef.BuildBinOp(
2715         CurScope, SourceLocation(), BO_Sub, LastIteration.get(),
2716         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
2717     if (!LastIteration.isUsable())
2718       return 0;
2719   }
2720 
2721   // Calculate the last iteration number beforehand instead of doing this on
2722   // each iteration. Do not do this if the number of iterations may be kfold-ed.
2723   llvm::APSInt Result;
2724   bool IsConstant =
2725       LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
2726   ExprResult CalcLastIteration;
2727   if (!IsConstant) {
2728     SourceLocation SaveLoc;
2729     VarDecl *SaveVar =
2730         BuildVarDecl(SemaRef, SaveLoc, LastIteration.get()->getType(),
2731                      ".omp.last.iteration");
2732     ExprResult SaveRef = SemaRef.BuildDeclRefExpr(
2733         SaveVar, LastIteration.get()->getType(), VK_LValue, SaveLoc);
2734     CalcLastIteration = SemaRef.BuildBinOp(CurScope, SaveLoc, BO_Assign,
2735                                            SaveRef.get(), LastIteration.get());
2736     LastIteration = SaveRef;
2737 
2738     // Prepare SaveRef + 1.
2739     NumIterations = SemaRef.BuildBinOp(
2740         CurScope, SaveLoc, BO_Add, SaveRef.get(),
2741         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
2742     if (!NumIterations.isUsable())
2743       return 0;
2744   }
2745 
2746   SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
2747 
2748   // Precondition tests if there is at least one iteration (LastIteration > 0).
2749   ExprResult PreCond = SemaRef.BuildBinOp(
2750       CurScope, InitLoc, BO_GT, LastIteration.get(),
2751       SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get());
2752 
2753   // Build the iteration variable and its initialization to zero before loop.
2754   ExprResult IV;
2755   ExprResult Init;
2756   {
2757     VarDecl *IVDecl = BuildVarDecl(SemaRef, InitLoc,
2758                                    LastIteration.get()->getType(), ".omp.iv");
2759     IV = SemaRef.BuildDeclRefExpr(IVDecl, LastIteration.get()->getType(),
2760                                   VK_LValue, InitLoc);
2761     Init = SemaRef.BuildBinOp(
2762         CurScope, InitLoc, BO_Assign, IV.get(),
2763         SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get());
2764   }
2765 
2766   // Loop condition (IV < NumIterations)
2767   SourceLocation CondLoc;
2768   ExprResult Cond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
2769                                        NumIterations.get());
2770   // Loop condition with 1 iteration separated (IV < LastIteration)
2771   ExprResult SeparatedCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT,
2772                                                 IV.get(), LastIteration.get());
2773 
2774   // Loop increment (IV = IV + 1)
2775   SourceLocation IncLoc;
2776   ExprResult Inc =
2777       SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
2778                          SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
2779   if (!Inc.isUsable())
2780     return 0;
2781   Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
2782 
2783   // Build updates and final values of the loop counters.
2784   bool HasErrors = false;
2785   Built.Counters.resize(NestedLoopCount);
2786   Built.Updates.resize(NestedLoopCount);
2787   Built.Finals.resize(NestedLoopCount);
2788   {
2789     ExprResult Div;
2790     // Go from inner nested loop to outer.
2791     for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
2792       LoopIterationSpace &IS = IterSpaces[Cnt];
2793       SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
2794       // Build: Iter = (IV / Div) % IS.NumIters
2795       // where Div is product of previous iterations' IS.NumIters.
2796       ExprResult Iter;
2797       if (Div.isUsable()) {
2798         Iter =
2799             SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get());
2800       } else {
2801         Iter = IV;
2802         assert((Cnt == (int)NestedLoopCount - 1) &&
2803                "unusable div expected on first iteration only");
2804       }
2805 
2806       if (Cnt != 0 && Iter.isUsable())
2807         Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(),
2808                                   IS.NumIterations);
2809       if (!Iter.isUsable()) {
2810         HasErrors = true;
2811         break;
2812       }
2813 
2814       // Build update: IS.CounterVar = IS.Start + Iter * IS.Step
2815       ExprResult Update =
2816           BuildCounterUpdate(SemaRef, CurScope, UpdLoc, IS.CounterVar,
2817                              IS.CounterInit, Iter, IS.CounterStep, IS.Subtract);
2818       if (!Update.isUsable()) {
2819         HasErrors = true;
2820         break;
2821       }
2822 
2823       // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
2824       ExprResult Final = BuildCounterUpdate(
2825           SemaRef, CurScope, UpdLoc, IS.CounterVar, IS.CounterInit,
2826           IS.NumIterations, IS.CounterStep, IS.Subtract);
2827       if (!Final.isUsable()) {
2828         HasErrors = true;
2829         break;
2830       }
2831 
2832       // Build Div for the next iteration: Div <- Div * IS.NumIters
2833       if (Cnt != 0) {
2834         if (Div.isUnset())
2835           Div = IS.NumIterations;
2836         else
2837           Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(),
2838                                    IS.NumIterations);
2839 
2840         // Add parentheses (for debugging purposes only).
2841         if (Div.isUsable())
2842           Div = SemaRef.ActOnParenExpr(UpdLoc, UpdLoc, Div.get());
2843         if (!Div.isUsable()) {
2844           HasErrors = true;
2845           break;
2846         }
2847       }
2848       if (!Update.isUsable() || !Final.isUsable()) {
2849         HasErrors = true;
2850         break;
2851       }
2852       // Save results
2853       Built.Counters[Cnt] = IS.CounterVar;
2854       Built.Updates[Cnt] = Update.get();
2855       Built.Finals[Cnt] = Final.get();
2856     }
2857   }
2858 
2859   if (HasErrors)
2860     return 0;
2861 
2862   // Save results
2863   Built.IterationVarRef = IV.get();
2864   Built.LastIteration = LastIteration.get();
2865   Built.CalcLastIteration = CalcLastIteration.get();
2866   Built.PreCond = PreCond.get();
2867   Built.Cond = Cond.get();
2868   Built.SeparatedCond = SeparatedCond.get();
2869   Built.Init = Init.get();
2870   Built.Inc = Inc.get();
2871 
2872   return NestedLoopCount;
2873 }
2874 
2875 static Expr *GetCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
2876   auto CollapseFilter = [](const OMPClause *C) -> bool {
2877     return C->getClauseKind() == OMPC_collapse;
2878   };
2879   OMPExecutableDirective::filtered_clause_iterator<decltype(CollapseFilter)> I(
2880       Clauses, CollapseFilter);
2881   if (I)
2882     return cast<OMPCollapseClause>(*I)->getNumForLoops();
2883   return nullptr;
2884 }
2885 
2886 StmtResult Sema::ActOnOpenMPSimdDirective(
2887     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
2888     SourceLocation EndLoc,
2889     llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
2890   BuiltLoopExprs B;
2891   // In presence of clause 'collapse', it will define the nested loops number.
2892   unsigned NestedLoopCount =
2893       CheckOpenMPLoop(OMPD_simd, GetCollapseNumberExpr(Clauses), AStmt, *this,
2894                       *DSAStack, VarsWithImplicitDSA, B);
2895   if (NestedLoopCount == 0)
2896     return StmtError();
2897 
2898   assert((CurContext->isDependentContext() || B.builtAll()) &&
2899          "omp simd loop exprs were not built");
2900 
2901   getCurFunction()->setHasBranchProtectedScope();
2902   return OMPSimdDirective::Create(
2903       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt,
2904       B.IterationVarRef, B.LastIteration, B.CalcLastIteration, B.PreCond,
2905       B.Cond, B.SeparatedCond, B.Init, B.Inc, B.Counters, B.Updates, B.Finals);
2906 }
2907 
2908 StmtResult Sema::ActOnOpenMPForDirective(
2909     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
2910     SourceLocation EndLoc,
2911     llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
2912   BuiltLoopExprs B;
2913   // In presence of clause 'collapse', it will define the nested loops number.
2914   unsigned NestedLoopCount =
2915       CheckOpenMPLoop(OMPD_for, GetCollapseNumberExpr(Clauses), AStmt, *this,
2916                       *DSAStack, VarsWithImplicitDSA, B);
2917   if (NestedLoopCount == 0)
2918     return StmtError();
2919 
2920   assert((CurContext->isDependentContext() || B.builtAll()) &&
2921          "omp for loop exprs were not built");
2922 
2923   getCurFunction()->setHasBranchProtectedScope();
2924   return OMPForDirective::Create(
2925       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt,
2926       B.IterationVarRef, B.LastIteration, B.CalcLastIteration, B.PreCond,
2927       B.Cond, B.SeparatedCond, B.Init, B.Inc, B.Counters, B.Updates, B.Finals);
2928 }
2929 
2930 StmtResult Sema::ActOnOpenMPForSimdDirective(
2931     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
2932     SourceLocation EndLoc,
2933     llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
2934   BuiltLoopExprs B;
2935   // In presence of clause 'collapse', it will define the nested loops number.
2936   unsigned NestedLoopCount =
2937       CheckOpenMPLoop(OMPD_for_simd, GetCollapseNumberExpr(Clauses), AStmt,
2938                       *this, *DSAStack, VarsWithImplicitDSA, B);
2939   if (NestedLoopCount == 0)
2940     return StmtError();
2941 
2942   getCurFunction()->setHasBranchProtectedScope();
2943   return OMPForSimdDirective::Create(
2944       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt,
2945       B.IterationVarRef, B.LastIteration, B.CalcLastIteration, B.PreCond,
2946       B.Cond, B.SeparatedCond, B.Init, B.Inc, B.Counters, B.Updates, B.Finals);
2947 }
2948 
2949 StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
2950                                               Stmt *AStmt,
2951                                               SourceLocation StartLoc,
2952                                               SourceLocation EndLoc) {
2953   assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
2954   auto BaseStmt = AStmt;
2955   while (CapturedStmt *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
2956     BaseStmt = CS->getCapturedStmt();
2957   if (auto C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
2958     auto S = C->children();
2959     if (!S)
2960       return StmtError();
2961     // All associated statements must be '#pragma omp section' except for
2962     // the first one.
2963     for (++S; S; ++S) {
2964       auto SectionStmt = *S;
2965       if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
2966         if (SectionStmt)
2967           Diag(SectionStmt->getLocStart(),
2968                diag::err_omp_sections_substmt_not_section);
2969         return StmtError();
2970       }
2971     }
2972   } else {
2973     Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt);
2974     return StmtError();
2975   }
2976 
2977   getCurFunction()->setHasBranchProtectedScope();
2978 
2979   return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses,
2980                                       AStmt);
2981 }
2982 
2983 StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
2984                                              SourceLocation StartLoc,
2985                                              SourceLocation EndLoc) {
2986   assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
2987 
2988   getCurFunction()->setHasBranchProtectedScope();
2989 
2990   return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt);
2991 }
2992 
2993 StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
2994                                             Stmt *AStmt,
2995                                             SourceLocation StartLoc,
2996                                             SourceLocation EndLoc) {
2997   assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
2998 
2999   getCurFunction()->setHasBranchProtectedScope();
3000 
3001   return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
3002 }
3003 
3004 StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
3005                                             SourceLocation StartLoc,
3006                                             SourceLocation EndLoc) {
3007   assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3008 
3009   getCurFunction()->setHasBranchProtectedScope();
3010 
3011   return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
3012 }
3013 
3014 StmtResult
3015 Sema::ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName,
3016                                    Stmt *AStmt, SourceLocation StartLoc,
3017                                    SourceLocation EndLoc) {
3018   assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3019 
3020   getCurFunction()->setHasBranchProtectedScope();
3021 
3022   return OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
3023                                       AStmt);
3024 }
3025 
3026 StmtResult Sema::ActOnOpenMPParallelForDirective(
3027     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
3028     SourceLocation EndLoc,
3029     llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
3030   assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3031   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
3032   // 1.2.2 OpenMP Language Terminology
3033   // Structured block - An executable statement with a single entry at the
3034   // top and a single exit at the bottom.
3035   // The point of exit cannot be a branch out of the structured block.
3036   // longjmp() and throw() must not violate the entry/exit criteria.
3037   CS->getCapturedDecl()->setNothrow();
3038 
3039   BuiltLoopExprs B;
3040   // In presence of clause 'collapse', it will define the nested loops number.
3041   unsigned NestedLoopCount =
3042       CheckOpenMPLoop(OMPD_parallel_for, GetCollapseNumberExpr(Clauses), AStmt,
3043                       *this, *DSAStack, VarsWithImplicitDSA, B);
3044   if (NestedLoopCount == 0)
3045     return StmtError();
3046 
3047   assert((CurContext->isDependentContext() || B.builtAll()) &&
3048          "omp parallel for loop exprs were not built");
3049 
3050   getCurFunction()->setHasBranchProtectedScope();
3051   return OMPParallelForDirective::Create(
3052       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt,
3053       B.IterationVarRef, B.LastIteration, B.CalcLastIteration, B.PreCond,
3054       B.Cond, B.SeparatedCond, B.Init, B.Inc, B.Counters, B.Updates, B.Finals);
3055 }
3056 
3057 StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
3058     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
3059     SourceLocation EndLoc,
3060     llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
3061   assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3062   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
3063   // 1.2.2 OpenMP Language Terminology
3064   // Structured block - An executable statement with a single entry at the
3065   // top and a single exit at the bottom.
3066   // The point of exit cannot be a branch out of the structured block.
3067   // longjmp() and throw() must not violate the entry/exit criteria.
3068   CS->getCapturedDecl()->setNothrow();
3069 
3070   BuiltLoopExprs B;
3071   // In presence of clause 'collapse', it will define the nested loops number.
3072   unsigned NestedLoopCount =
3073       CheckOpenMPLoop(OMPD_parallel_for_simd, GetCollapseNumberExpr(Clauses),
3074                       AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
3075   if (NestedLoopCount == 0)
3076     return StmtError();
3077 
3078   getCurFunction()->setHasBranchProtectedScope();
3079   return OMPParallelForSimdDirective::Create(
3080       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt,
3081       B.IterationVarRef, B.LastIteration, B.CalcLastIteration, B.PreCond,
3082       B.Cond, B.SeparatedCond, B.Init, B.Inc, B.Counters, B.Updates, B.Finals);
3083 }
3084 
3085 StmtResult
3086 Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
3087                                            Stmt *AStmt, SourceLocation StartLoc,
3088                                            SourceLocation EndLoc) {
3089   assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3090   auto BaseStmt = AStmt;
3091   while (CapturedStmt *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
3092     BaseStmt = CS->getCapturedStmt();
3093   if (auto C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
3094     auto S = C->children();
3095     if (!S)
3096       return StmtError();
3097     // All associated statements must be '#pragma omp section' except for
3098     // the first one.
3099     for (++S; S; ++S) {
3100       auto SectionStmt = *S;
3101       if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
3102         if (SectionStmt)
3103           Diag(SectionStmt->getLocStart(),
3104                diag::err_omp_parallel_sections_substmt_not_section);
3105         return StmtError();
3106       }
3107     }
3108   } else {
3109     Diag(AStmt->getLocStart(),
3110          diag::err_omp_parallel_sections_not_compound_stmt);
3111     return StmtError();
3112   }
3113 
3114   getCurFunction()->setHasBranchProtectedScope();
3115 
3116   return OMPParallelSectionsDirective::Create(Context, StartLoc, EndLoc,
3117                                               Clauses, AStmt);
3118 }
3119 
3120 StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
3121                                           Stmt *AStmt, SourceLocation StartLoc,
3122                                           SourceLocation EndLoc) {
3123   assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3124   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
3125   // 1.2.2 OpenMP Language Terminology
3126   // Structured block - An executable statement with a single entry at the
3127   // top and a single exit at the bottom.
3128   // The point of exit cannot be a branch out of the structured block.
3129   // longjmp() and throw() must not violate the entry/exit criteria.
3130   CS->getCapturedDecl()->setNothrow();
3131 
3132   getCurFunction()->setHasBranchProtectedScope();
3133 
3134   return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
3135 }
3136 
3137 StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
3138                                                SourceLocation EndLoc) {
3139   return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
3140 }
3141 
3142 StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
3143                                              SourceLocation EndLoc) {
3144   return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
3145 }
3146 
3147 StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
3148                                               SourceLocation EndLoc) {
3149   return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
3150 }
3151 
3152 StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
3153                                            SourceLocation StartLoc,
3154                                            SourceLocation EndLoc) {
3155   assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
3156   return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
3157 }
3158 
3159 StmtResult Sema::ActOnOpenMPOrderedDirective(Stmt *AStmt,
3160                                              SourceLocation StartLoc,
3161                                              SourceLocation EndLoc) {
3162   assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3163 
3164   getCurFunction()->setHasBranchProtectedScope();
3165 
3166   return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, AStmt);
3167 }
3168 
3169 StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
3170                                             Stmt *AStmt,
3171                                             SourceLocation StartLoc,
3172                                             SourceLocation EndLoc) {
3173   assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3174   auto CS = cast<CapturedStmt>(AStmt);
3175   // 1.2.2 OpenMP Language Terminology
3176   // Structured block - An executable statement with a single entry at the
3177   // top and a single exit at the bottom.
3178   // The point of exit cannot be a branch out of the structured block.
3179   // longjmp() and throw() must not violate the entry/exit criteria.
3180   // TODO further analysis of associated statements and clauses.
3181   OpenMPClauseKind AtomicKind = OMPC_unknown;
3182   SourceLocation AtomicKindLoc;
3183   for (auto *C : Clauses) {
3184     if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
3185         C->getClauseKind() == OMPC_update ||
3186         C->getClauseKind() == OMPC_capture) {
3187       if (AtomicKind != OMPC_unknown) {
3188         Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses)
3189             << SourceRange(C->getLocStart(), C->getLocEnd());
3190         Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
3191             << getOpenMPClauseName(AtomicKind);
3192       } else {
3193         AtomicKind = C->getClauseKind();
3194         AtomicKindLoc = C->getLocStart();
3195       }
3196     }
3197   }
3198 
3199   auto Body = CS->getCapturedStmt();
3200   Expr *X = nullptr;
3201   Expr *V = nullptr;
3202   Expr *E = nullptr;
3203   // OpenMP [2.12.6, atomic Construct]
3204   // In the next expressions:
3205   // * x and v (as applicable) are both l-value expressions with scalar type.
3206   // * During the execution of an atomic region, multiple syntactic
3207   // occurrences of x must designate the same storage location.
3208   // * Neither of v and expr (as applicable) may access the storage location
3209   // designated by x.
3210   // * Neither of x and expr (as applicable) may access the storage location
3211   // designated by v.
3212   // * expr is an expression with scalar type.
3213   // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
3214   // * binop, binop=, ++, and -- are not overloaded operators.
3215   // * The expression x binop expr must be numerically equivalent to x binop
3216   // (expr). This requirement is satisfied if the operators in expr have
3217   // precedence greater than binop, or by using parentheses around expr or
3218   // subexpressions of expr.
3219   // * The expression expr binop x must be numerically equivalent to (expr)
3220   // binop x. This requirement is satisfied if the operators in expr have
3221   // precedence equal to or greater than binop, or by using parentheses around
3222   // expr or subexpressions of expr.
3223   // * For forms that allow multiple occurrences of x, the number of times
3224   // that x is evaluated is unspecified.
3225   enum {
3226     NotAnExpression,
3227     NotAnAssignmentOp,
3228     NotAScalarType,
3229     NotAnLValue,
3230     NoError
3231   } ErrorFound = NoError;
3232   if (AtomicKind == OMPC_read) {
3233     SourceLocation ErrorLoc, NoteLoc;
3234     SourceRange ErrorRange, NoteRange;
3235     // If clause is read:
3236     //  v = x;
3237     if (auto AtomicBody = dyn_cast<Expr>(Body)) {
3238       auto AtomicBinOp =
3239           dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
3240       if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
3241         X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
3242         V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
3243         if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
3244             (V->isInstantiationDependent() || V->getType()->isScalarType())) {
3245           if (!X->isLValue() || !V->isLValue()) {
3246             auto NotLValueExpr = X->isLValue() ? V : X;
3247             ErrorFound = NotAnLValue;
3248             ErrorLoc = AtomicBinOp->getExprLoc();
3249             ErrorRange = AtomicBinOp->getSourceRange();
3250             NoteLoc = NotLValueExpr->getExprLoc();
3251             NoteRange = NotLValueExpr->getSourceRange();
3252           }
3253         } else if (!X->isInstantiationDependent() ||
3254                    !V->isInstantiationDependent()) {
3255           auto NotScalarExpr =
3256               (X->isInstantiationDependent() || X->getType()->isScalarType())
3257                   ? V
3258                   : X;
3259           ErrorFound = NotAScalarType;
3260           ErrorLoc = AtomicBinOp->getExprLoc();
3261           ErrorRange = AtomicBinOp->getSourceRange();
3262           NoteLoc = NotScalarExpr->getExprLoc();
3263           NoteRange = NotScalarExpr->getSourceRange();
3264         }
3265       } else {
3266         ErrorFound = NotAnAssignmentOp;
3267         ErrorLoc = AtomicBody->getExprLoc();
3268         ErrorRange = AtomicBody->getSourceRange();
3269         NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
3270                               : AtomicBody->getExprLoc();
3271         NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
3272                                 : AtomicBody->getSourceRange();
3273       }
3274     } else {
3275       ErrorFound = NotAnExpression;
3276       NoteLoc = ErrorLoc = Body->getLocStart();
3277       NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
3278     }
3279     if (ErrorFound != NoError) {
3280       Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
3281           << ErrorRange;
3282       Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
3283                                                       << NoteRange;
3284       return StmtError();
3285     } else if (CurContext->isDependentContext())
3286       V = X = nullptr;
3287   } else if (AtomicKind == OMPC_write) {
3288     SourceLocation ErrorLoc, NoteLoc;
3289     SourceRange ErrorRange, NoteRange;
3290     // If clause is write:
3291     //  x = expr;
3292     if (auto AtomicBody = dyn_cast<Expr>(Body)) {
3293       auto AtomicBinOp =
3294           dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
3295       if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
3296         X = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
3297         E = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
3298         if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
3299             (E->isInstantiationDependent() || E->getType()->isScalarType())) {
3300           if (!X->isLValue()) {
3301             ErrorFound = NotAnLValue;
3302             ErrorLoc = AtomicBinOp->getExprLoc();
3303             ErrorRange = AtomicBinOp->getSourceRange();
3304             NoteLoc = X->getExprLoc();
3305             NoteRange = X->getSourceRange();
3306           }
3307         } else if (!X->isInstantiationDependent() ||
3308                    !E->isInstantiationDependent()) {
3309           auto NotScalarExpr =
3310               (X->isInstantiationDependent() || X->getType()->isScalarType())
3311                   ? E
3312                   : X;
3313           ErrorFound = NotAScalarType;
3314           ErrorLoc = AtomicBinOp->getExprLoc();
3315           ErrorRange = AtomicBinOp->getSourceRange();
3316           NoteLoc = NotScalarExpr->getExprLoc();
3317           NoteRange = NotScalarExpr->getSourceRange();
3318         }
3319       } else {
3320         ErrorFound = NotAnAssignmentOp;
3321         ErrorLoc = AtomicBody->getExprLoc();
3322         ErrorRange = AtomicBody->getSourceRange();
3323         NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
3324                               : AtomicBody->getExprLoc();
3325         NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
3326                                 : AtomicBody->getSourceRange();
3327       }
3328     } else {
3329       ErrorFound = NotAnExpression;
3330       NoteLoc = ErrorLoc = Body->getLocStart();
3331       NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
3332     }
3333     if (ErrorFound != NoError) {
3334       Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
3335           << ErrorRange;
3336       Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
3337                                                       << NoteRange;
3338       return StmtError();
3339     } else if (CurContext->isDependentContext())
3340       E = X = nullptr;
3341   } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
3342     if (!isa<Expr>(Body)) {
3343       Diag(Body->getLocStart(),
3344            diag::err_omp_atomic_update_not_expression_statement)
3345           << (AtomicKind == OMPC_update);
3346       return StmtError();
3347     }
3348   } else if (AtomicKind == OMPC_capture) {
3349     if (isa<Expr>(Body) && !isa<BinaryOperator>(Body)) {
3350       Diag(Body->getLocStart(),
3351            diag::err_omp_atomic_capture_not_expression_statement);
3352       return StmtError();
3353     } else if (!isa<Expr>(Body) && !isa<CompoundStmt>(Body)) {
3354       Diag(Body->getLocStart(),
3355            diag::err_omp_atomic_capture_not_compound_statement);
3356       return StmtError();
3357     }
3358   }
3359 
3360   getCurFunction()->setHasBranchProtectedScope();
3361 
3362   return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
3363                                     X, V, E);
3364 }
3365 
3366 StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
3367                                             Stmt *AStmt,
3368                                             SourceLocation StartLoc,
3369                                             SourceLocation EndLoc) {
3370   assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3371 
3372   // OpenMP [2.16, Nesting of Regions]
3373   // If specified, a teams construct must be contained within a target
3374   // construct. That target construct must contain no statements or directives
3375   // outside of the teams construct.
3376   if (DSAStack->hasInnerTeamsRegion()) {
3377     auto S = AStmt->IgnoreContainers(/*IgnoreCaptured*/ true);
3378     bool OMPTeamsFound = true;
3379     if (auto *CS = dyn_cast<CompoundStmt>(S)) {
3380       auto I = CS->body_begin();
3381       while (I != CS->body_end()) {
3382         auto OED = dyn_cast<OMPExecutableDirective>(*I);
3383         if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) {
3384           OMPTeamsFound = false;
3385           break;
3386         }
3387         ++I;
3388       }
3389       assert(I != CS->body_end() && "Not found statement");
3390       S = *I;
3391     }
3392     if (!OMPTeamsFound) {
3393       Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
3394       Diag(DSAStack->getInnerTeamsRegionLoc(),
3395            diag::note_omp_nested_teams_construct_here);
3396       Diag(S->getLocStart(), diag::note_omp_nested_statement_here)
3397           << isa<OMPExecutableDirective>(S);
3398       return StmtError();
3399     }
3400   }
3401 
3402   getCurFunction()->setHasBranchProtectedScope();
3403 
3404   return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
3405 }
3406 
3407 StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
3408                                            Stmt *AStmt, SourceLocation StartLoc,
3409                                            SourceLocation EndLoc) {
3410   assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3411   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
3412   // 1.2.2 OpenMP Language Terminology
3413   // Structured block - An executable statement with a single entry at the
3414   // top and a single exit at the bottom.
3415   // The point of exit cannot be a branch out of the structured block.
3416   // longjmp() and throw() must not violate the entry/exit criteria.
3417   CS->getCapturedDecl()->setNothrow();
3418 
3419   getCurFunction()->setHasBranchProtectedScope();
3420 
3421   return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
3422 }
3423 
3424 OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
3425                                              SourceLocation StartLoc,
3426                                              SourceLocation LParenLoc,
3427                                              SourceLocation EndLoc) {
3428   OMPClause *Res = nullptr;
3429   switch (Kind) {
3430   case OMPC_if:
3431     Res = ActOnOpenMPIfClause(Expr, StartLoc, LParenLoc, EndLoc);
3432     break;
3433   case OMPC_final:
3434     Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
3435     break;
3436   case OMPC_num_threads:
3437     Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
3438     break;
3439   case OMPC_safelen:
3440     Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
3441     break;
3442   case OMPC_collapse:
3443     Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
3444     break;
3445   case OMPC_default:
3446   case OMPC_proc_bind:
3447   case OMPC_schedule:
3448   case OMPC_private:
3449   case OMPC_firstprivate:
3450   case OMPC_lastprivate:
3451   case OMPC_shared:
3452   case OMPC_reduction:
3453   case OMPC_linear:
3454   case OMPC_aligned:
3455   case OMPC_copyin:
3456   case OMPC_copyprivate:
3457   case OMPC_ordered:
3458   case OMPC_nowait:
3459   case OMPC_untied:
3460   case OMPC_mergeable:
3461   case OMPC_threadprivate:
3462   case OMPC_flush:
3463   case OMPC_read:
3464   case OMPC_write:
3465   case OMPC_update:
3466   case OMPC_capture:
3467   case OMPC_seq_cst:
3468   case OMPC_unknown:
3469     llvm_unreachable("Clause is not allowed.");
3470   }
3471   return Res;
3472 }
3473 
3474 OMPClause *Sema::ActOnOpenMPIfClause(Expr *Condition, SourceLocation StartLoc,
3475                                      SourceLocation LParenLoc,
3476                                      SourceLocation EndLoc) {
3477   Expr *ValExpr = Condition;
3478   if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
3479       !Condition->isInstantiationDependent() &&
3480       !Condition->containsUnexpandedParameterPack()) {
3481     ExprResult Val = ActOnBooleanCondition(DSAStack->getCurScope(),
3482                                            Condition->getExprLoc(), Condition);
3483     if (Val.isInvalid())
3484       return nullptr;
3485 
3486     ValExpr = Val.get();
3487   }
3488 
3489   return new (Context) OMPIfClause(ValExpr, StartLoc, LParenLoc, EndLoc);
3490 }
3491 
3492 OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
3493                                         SourceLocation StartLoc,
3494                                         SourceLocation LParenLoc,
3495                                         SourceLocation EndLoc) {
3496   Expr *ValExpr = Condition;
3497   if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
3498       !Condition->isInstantiationDependent() &&
3499       !Condition->containsUnexpandedParameterPack()) {
3500     ExprResult Val = ActOnBooleanCondition(DSAStack->getCurScope(),
3501                                            Condition->getExprLoc(), Condition);
3502     if (Val.isInvalid())
3503       return nullptr;
3504 
3505     ValExpr = Val.get();
3506   }
3507 
3508   return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
3509 }
3510 ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
3511                                                         Expr *Op) {
3512   if (!Op)
3513     return ExprError();
3514 
3515   class IntConvertDiagnoser : public ICEConvertDiagnoser {
3516   public:
3517     IntConvertDiagnoser()
3518         : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
3519     SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
3520                                          QualType T) override {
3521       return S.Diag(Loc, diag::err_omp_not_integral) << T;
3522     }
3523     SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
3524                                              QualType T) override {
3525       return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
3526     }
3527     SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
3528                                                QualType T,
3529                                                QualType ConvTy) override {
3530       return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
3531     }
3532     SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
3533                                            QualType ConvTy) override {
3534       return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
3535              << ConvTy->isEnumeralType() << ConvTy;
3536     }
3537     SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
3538                                             QualType T) override {
3539       return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
3540     }
3541     SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
3542                                         QualType ConvTy) override {
3543       return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
3544              << ConvTy->isEnumeralType() << ConvTy;
3545     }
3546     SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
3547                                              QualType) override {
3548       llvm_unreachable("conversion functions are permitted");
3549     }
3550   } ConvertDiagnoser;
3551   return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
3552 }
3553 
3554 OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
3555                                              SourceLocation StartLoc,
3556                                              SourceLocation LParenLoc,
3557                                              SourceLocation EndLoc) {
3558   Expr *ValExpr = NumThreads;
3559   if (!NumThreads->isValueDependent() && !NumThreads->isTypeDependent() &&
3560       !NumThreads->containsUnexpandedParameterPack()) {
3561     SourceLocation NumThreadsLoc = NumThreads->getLocStart();
3562     ExprResult Val =
3563         PerformOpenMPImplicitIntegerConversion(NumThreadsLoc, NumThreads);
3564     if (Val.isInvalid())
3565       return nullptr;
3566 
3567     ValExpr = Val.get();
3568 
3569     // OpenMP [2.5, Restrictions]
3570     //  The num_threads expression must evaluate to a positive integer value.
3571     llvm::APSInt Result;
3572     if (ValExpr->isIntegerConstantExpr(Result, Context) && Result.isSigned() &&
3573         !Result.isStrictlyPositive()) {
3574       Diag(NumThreadsLoc, diag::err_omp_negative_expression_in_clause)
3575           << "num_threads" << NumThreads->getSourceRange();
3576       return nullptr;
3577     }
3578   }
3579 
3580   return new (Context)
3581       OMPNumThreadsClause(ValExpr, StartLoc, LParenLoc, EndLoc);
3582 }
3583 
3584 ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
3585                                                        OpenMPClauseKind CKind) {
3586   if (!E)
3587     return ExprError();
3588   if (E->isValueDependent() || E->isTypeDependent() ||
3589       E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
3590     return E;
3591   llvm::APSInt Result;
3592   ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
3593   if (ICE.isInvalid())
3594     return ExprError();
3595   if (!Result.isStrictlyPositive()) {
3596     Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
3597         << getOpenMPClauseName(CKind) << E->getSourceRange();
3598     return ExprError();
3599   }
3600   if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
3601     Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
3602         << E->getSourceRange();
3603     return ExprError();
3604   }
3605   return ICE;
3606 }
3607 
3608 OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
3609                                           SourceLocation LParenLoc,
3610                                           SourceLocation EndLoc) {
3611   // OpenMP [2.8.1, simd construct, Description]
3612   // The parameter of the safelen clause must be a constant
3613   // positive integer expression.
3614   ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
3615   if (Safelen.isInvalid())
3616     return nullptr;
3617   return new (Context)
3618       OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
3619 }
3620 
3621 OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
3622                                            SourceLocation StartLoc,
3623                                            SourceLocation LParenLoc,
3624                                            SourceLocation EndLoc) {
3625   // OpenMP [2.7.1, loop construct, Description]
3626   // OpenMP [2.8.1, simd construct, Description]
3627   // OpenMP [2.9.6, distribute construct, Description]
3628   // The parameter of the collapse clause must be a constant
3629   // positive integer expression.
3630   ExprResult NumForLoopsResult =
3631       VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
3632   if (NumForLoopsResult.isInvalid())
3633     return nullptr;
3634   return new (Context)
3635       OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
3636 }
3637 
3638 OMPClause *Sema::ActOnOpenMPSimpleClause(
3639     OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
3640     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
3641   OMPClause *Res = nullptr;
3642   switch (Kind) {
3643   case OMPC_default:
3644     Res =
3645         ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
3646                                  ArgumentLoc, StartLoc, LParenLoc, EndLoc);
3647     break;
3648   case OMPC_proc_bind:
3649     Res = ActOnOpenMPProcBindClause(
3650         static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
3651         LParenLoc, EndLoc);
3652     break;
3653   case OMPC_if:
3654   case OMPC_final:
3655   case OMPC_num_threads:
3656   case OMPC_safelen:
3657   case OMPC_collapse:
3658   case OMPC_schedule:
3659   case OMPC_private:
3660   case OMPC_firstprivate:
3661   case OMPC_lastprivate:
3662   case OMPC_shared:
3663   case OMPC_reduction:
3664   case OMPC_linear:
3665   case OMPC_aligned:
3666   case OMPC_copyin:
3667   case OMPC_copyprivate:
3668   case OMPC_ordered:
3669   case OMPC_nowait:
3670   case OMPC_untied:
3671   case OMPC_mergeable:
3672   case OMPC_threadprivate:
3673   case OMPC_flush:
3674   case OMPC_read:
3675   case OMPC_write:
3676   case OMPC_update:
3677   case OMPC_capture:
3678   case OMPC_seq_cst:
3679   case OMPC_unknown:
3680     llvm_unreachable("Clause is not allowed.");
3681   }
3682   return Res;
3683 }
3684 
3685 OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
3686                                           SourceLocation KindKwLoc,
3687                                           SourceLocation StartLoc,
3688                                           SourceLocation LParenLoc,
3689                                           SourceLocation EndLoc) {
3690   if (Kind == OMPC_DEFAULT_unknown) {
3691     std::string Values;
3692     static_assert(OMPC_DEFAULT_unknown > 0,
3693                   "OMPC_DEFAULT_unknown not greater than 0");
3694     std::string Sep(", ");
3695     for (unsigned i = 0; i < OMPC_DEFAULT_unknown; ++i) {
3696       Values += "'";
3697       Values += getOpenMPSimpleClauseTypeName(OMPC_default, i);
3698       Values += "'";
3699       switch (i) {
3700       case OMPC_DEFAULT_unknown - 2:
3701         Values += " or ";
3702         break;
3703       case OMPC_DEFAULT_unknown - 1:
3704         break;
3705       default:
3706         Values += Sep;
3707         break;
3708       }
3709     }
3710     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
3711         << Values << getOpenMPClauseName(OMPC_default);
3712     return nullptr;
3713   }
3714   switch (Kind) {
3715   case OMPC_DEFAULT_none:
3716     DSAStack->setDefaultDSANone(KindKwLoc);
3717     break;
3718   case OMPC_DEFAULT_shared:
3719     DSAStack->setDefaultDSAShared(KindKwLoc);
3720     break;
3721   case OMPC_DEFAULT_unknown:
3722     llvm_unreachable("Clause kind is not allowed.");
3723     break;
3724   }
3725   return new (Context)
3726       OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
3727 }
3728 
3729 OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
3730                                            SourceLocation KindKwLoc,
3731                                            SourceLocation StartLoc,
3732                                            SourceLocation LParenLoc,
3733                                            SourceLocation EndLoc) {
3734   if (Kind == OMPC_PROC_BIND_unknown) {
3735     std::string Values;
3736     std::string Sep(", ");
3737     for (unsigned i = 0; i < OMPC_PROC_BIND_unknown; ++i) {
3738       Values += "'";
3739       Values += getOpenMPSimpleClauseTypeName(OMPC_proc_bind, i);
3740       Values += "'";
3741       switch (i) {
3742       case OMPC_PROC_BIND_unknown - 2:
3743         Values += " or ";
3744         break;
3745       case OMPC_PROC_BIND_unknown - 1:
3746         break;
3747       default:
3748         Values += Sep;
3749         break;
3750       }
3751     }
3752     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
3753         << Values << getOpenMPClauseName(OMPC_proc_bind);
3754     return nullptr;
3755   }
3756   return new (Context)
3757       OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
3758 }
3759 
3760 OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
3761     OpenMPClauseKind Kind, unsigned Argument, Expr *Expr,
3762     SourceLocation StartLoc, SourceLocation LParenLoc,
3763     SourceLocation ArgumentLoc, SourceLocation CommaLoc,
3764     SourceLocation EndLoc) {
3765   OMPClause *Res = nullptr;
3766   switch (Kind) {
3767   case OMPC_schedule:
3768     Res = ActOnOpenMPScheduleClause(
3769         static_cast<OpenMPScheduleClauseKind>(Argument), Expr, StartLoc,
3770         LParenLoc, ArgumentLoc, CommaLoc, EndLoc);
3771     break;
3772   case OMPC_if:
3773   case OMPC_final:
3774   case OMPC_num_threads:
3775   case OMPC_safelen:
3776   case OMPC_collapse:
3777   case OMPC_default:
3778   case OMPC_proc_bind:
3779   case OMPC_private:
3780   case OMPC_firstprivate:
3781   case OMPC_lastprivate:
3782   case OMPC_shared:
3783   case OMPC_reduction:
3784   case OMPC_linear:
3785   case OMPC_aligned:
3786   case OMPC_copyin:
3787   case OMPC_copyprivate:
3788   case OMPC_ordered:
3789   case OMPC_nowait:
3790   case OMPC_untied:
3791   case OMPC_mergeable:
3792   case OMPC_threadprivate:
3793   case OMPC_flush:
3794   case OMPC_read:
3795   case OMPC_write:
3796   case OMPC_update:
3797   case OMPC_capture:
3798   case OMPC_seq_cst:
3799   case OMPC_unknown:
3800     llvm_unreachable("Clause is not allowed.");
3801   }
3802   return Res;
3803 }
3804 
3805 OMPClause *Sema::ActOnOpenMPScheduleClause(
3806     OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
3807     SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
3808     SourceLocation EndLoc) {
3809   if (Kind == OMPC_SCHEDULE_unknown) {
3810     std::string Values;
3811     std::string Sep(", ");
3812     for (unsigned i = 0; i < OMPC_SCHEDULE_unknown; ++i) {
3813       Values += "'";
3814       Values += getOpenMPSimpleClauseTypeName(OMPC_schedule, i);
3815       Values += "'";
3816       switch (i) {
3817       case OMPC_SCHEDULE_unknown - 2:
3818         Values += " or ";
3819         break;
3820       case OMPC_SCHEDULE_unknown - 1:
3821         break;
3822       default:
3823         Values += Sep;
3824         break;
3825       }
3826     }
3827     Diag(KindLoc, diag::err_omp_unexpected_clause_value)
3828         << Values << getOpenMPClauseName(OMPC_schedule);
3829     return nullptr;
3830   }
3831   Expr *ValExpr = ChunkSize;
3832   if (ChunkSize) {
3833     if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
3834         !ChunkSize->isInstantiationDependent() &&
3835         !ChunkSize->containsUnexpandedParameterPack()) {
3836       SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
3837       ExprResult Val =
3838           PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
3839       if (Val.isInvalid())
3840         return nullptr;
3841 
3842       ValExpr = Val.get();
3843 
3844       // OpenMP [2.7.1, Restrictions]
3845       //  chunk_size must be a loop invariant integer expression with a positive
3846       //  value.
3847       llvm::APSInt Result;
3848       if (ValExpr->isIntegerConstantExpr(Result, Context) &&
3849           Result.isSigned() && !Result.isStrictlyPositive()) {
3850         Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
3851             << "schedule" << ChunkSize->getSourceRange();
3852         return nullptr;
3853       }
3854     }
3855   }
3856 
3857   return new (Context) OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc,
3858                                          EndLoc, Kind, ValExpr);
3859 }
3860 
3861 OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
3862                                    SourceLocation StartLoc,
3863                                    SourceLocation EndLoc) {
3864   OMPClause *Res = nullptr;
3865   switch (Kind) {
3866   case OMPC_ordered:
3867     Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
3868     break;
3869   case OMPC_nowait:
3870     Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
3871     break;
3872   case OMPC_untied:
3873     Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
3874     break;
3875   case OMPC_mergeable:
3876     Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
3877     break;
3878   case OMPC_read:
3879     Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
3880     break;
3881   case OMPC_write:
3882     Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
3883     break;
3884   case OMPC_update:
3885     Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
3886     break;
3887   case OMPC_capture:
3888     Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
3889     break;
3890   case OMPC_seq_cst:
3891     Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
3892     break;
3893   case OMPC_if:
3894   case OMPC_final:
3895   case OMPC_num_threads:
3896   case OMPC_safelen:
3897   case OMPC_collapse:
3898   case OMPC_schedule:
3899   case OMPC_private:
3900   case OMPC_firstprivate:
3901   case OMPC_lastprivate:
3902   case OMPC_shared:
3903   case OMPC_reduction:
3904   case OMPC_linear:
3905   case OMPC_aligned:
3906   case OMPC_copyin:
3907   case OMPC_copyprivate:
3908   case OMPC_default:
3909   case OMPC_proc_bind:
3910   case OMPC_threadprivate:
3911   case OMPC_flush:
3912   case OMPC_unknown:
3913     llvm_unreachable("Clause is not allowed.");
3914   }
3915   return Res;
3916 }
3917 
3918 OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
3919                                           SourceLocation EndLoc) {
3920   DSAStack->setOrderedRegion();
3921   return new (Context) OMPOrderedClause(StartLoc, EndLoc);
3922 }
3923 
3924 OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
3925                                          SourceLocation EndLoc) {
3926   return new (Context) OMPNowaitClause(StartLoc, EndLoc);
3927 }
3928 
3929 OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
3930                                          SourceLocation EndLoc) {
3931   return new (Context) OMPUntiedClause(StartLoc, EndLoc);
3932 }
3933 
3934 OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
3935                                             SourceLocation EndLoc) {
3936   return new (Context) OMPMergeableClause(StartLoc, EndLoc);
3937 }
3938 
3939 OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
3940                                        SourceLocation EndLoc) {
3941   return new (Context) OMPReadClause(StartLoc, EndLoc);
3942 }
3943 
3944 OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
3945                                         SourceLocation EndLoc) {
3946   return new (Context) OMPWriteClause(StartLoc, EndLoc);
3947 }
3948 
3949 OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
3950                                          SourceLocation EndLoc) {
3951   return new (Context) OMPUpdateClause(StartLoc, EndLoc);
3952 }
3953 
3954 OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
3955                                           SourceLocation EndLoc) {
3956   return new (Context) OMPCaptureClause(StartLoc, EndLoc);
3957 }
3958 
3959 OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
3960                                          SourceLocation EndLoc) {
3961   return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
3962 }
3963 
3964 OMPClause *Sema::ActOnOpenMPVarListClause(
3965     OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
3966     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
3967     SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
3968     const DeclarationNameInfo &ReductionId) {
3969   OMPClause *Res = nullptr;
3970   switch (Kind) {
3971   case OMPC_private:
3972     Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
3973     break;
3974   case OMPC_firstprivate:
3975     Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
3976     break;
3977   case OMPC_lastprivate:
3978     Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
3979     break;
3980   case OMPC_shared:
3981     Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
3982     break;
3983   case OMPC_reduction:
3984     Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
3985                                      EndLoc, ReductionIdScopeSpec, ReductionId);
3986     break;
3987   case OMPC_linear:
3988     Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
3989                                   ColonLoc, EndLoc);
3990     break;
3991   case OMPC_aligned:
3992     Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
3993                                    ColonLoc, EndLoc);
3994     break;
3995   case OMPC_copyin:
3996     Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
3997     break;
3998   case OMPC_copyprivate:
3999     Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
4000     break;
4001   case OMPC_flush:
4002     Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
4003     break;
4004   case OMPC_if:
4005   case OMPC_final:
4006   case OMPC_num_threads:
4007   case OMPC_safelen:
4008   case OMPC_collapse:
4009   case OMPC_default:
4010   case OMPC_proc_bind:
4011   case OMPC_schedule:
4012   case OMPC_ordered:
4013   case OMPC_nowait:
4014   case OMPC_untied:
4015   case OMPC_mergeable:
4016   case OMPC_threadprivate:
4017   case OMPC_read:
4018   case OMPC_write:
4019   case OMPC_update:
4020   case OMPC_capture:
4021   case OMPC_seq_cst:
4022   case OMPC_unknown:
4023     llvm_unreachable("Clause is not allowed.");
4024   }
4025   return Res;
4026 }
4027 
4028 OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
4029                                           SourceLocation StartLoc,
4030                                           SourceLocation LParenLoc,
4031                                           SourceLocation EndLoc) {
4032   SmallVector<Expr *, 8> Vars;
4033   SmallVector<Expr *, 8> PrivateCopies;
4034   for (auto &RefExpr : VarList) {
4035     assert(RefExpr && "NULL expr in OpenMP private clause.");
4036     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
4037       // It will be analyzed later.
4038       Vars.push_back(RefExpr);
4039       PrivateCopies.push_back(nullptr);
4040       continue;
4041     }
4042 
4043     SourceLocation ELoc = RefExpr->getExprLoc();
4044     // OpenMP [2.1, C/C++]
4045     //  A list item is a variable name.
4046     // OpenMP  [2.9.3.3, Restrictions, p.1]
4047     //  A variable that is part of another variable (as an array or
4048     //  structure element) cannot appear in a private clause.
4049     DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
4050     if (!DE || !isa<VarDecl>(DE->getDecl())) {
4051       Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
4052       continue;
4053     }
4054     Decl *D = DE->getDecl();
4055     VarDecl *VD = cast<VarDecl>(D);
4056 
4057     QualType Type = VD->getType();
4058     if (Type->isDependentType() || Type->isInstantiationDependentType()) {
4059       // It will be analyzed later.
4060       Vars.push_back(DE);
4061       PrivateCopies.push_back(nullptr);
4062       continue;
4063     }
4064 
4065     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
4066     //  A variable that appears in a private clause must not have an incomplete
4067     //  type or a reference type.
4068     if (RequireCompleteType(ELoc, Type,
4069                             diag::err_omp_private_incomplete_type)) {
4070       continue;
4071     }
4072     if (Type->isReferenceType()) {
4073       Diag(ELoc, diag::err_omp_clause_ref_type_arg)
4074           << getOpenMPClauseName(OMPC_private) << Type;
4075       bool IsDecl =
4076           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
4077       Diag(VD->getLocation(),
4078            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
4079           << VD;
4080       continue;
4081     }
4082 
4083     // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
4084     //  A variable of class type (or array thereof) that appears in a private
4085     //  clause requires an accessible, unambiguous default constructor for the
4086     //  class type.
4087     while (Type->isArrayType()) {
4088       Type = cast<ArrayType>(Type.getTypePtr())->getElementType();
4089     }
4090 
4091     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
4092     // in a Construct]
4093     //  Variables with the predetermined data-sharing attributes may not be
4094     //  listed in data-sharing attributes clauses, except for the cases
4095     //  listed below. For these exceptions only, listing a predetermined
4096     //  variable in a data-sharing attribute clause is allowed and overrides
4097     //  the variable's predetermined data-sharing attributes.
4098     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
4099     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
4100       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
4101                                           << getOpenMPClauseName(OMPC_private);
4102       ReportOriginalDSA(*this, DSAStack, VD, DVar);
4103       continue;
4104     }
4105 
4106     // Generate helper private variable and initialize it with the default
4107     // value. The address of the original variable is replaced by the address of
4108     // the new private variable in CodeGen. This new variable is not added to
4109     // IdResolver, so the code in the OpenMP region uses original variable for
4110     // proper diagnostics.
4111     auto VDPrivate =
4112         VarDecl::Create(Context, CurContext, DE->getLocStart(),
4113                         DE->getExprLoc(), VD->getIdentifier(), VD->getType(),
4114                         VD->getTypeSourceInfo(), /*S*/ SC_Auto);
4115     ActOnUninitializedDecl(VDPrivate, /*TypeMayContainAuto*/ false);
4116     if (VDPrivate->isInvalidDecl())
4117       continue;
4118     CurContext->addDecl(VDPrivate);
4119     auto VDPrivateRefExpr = DeclRefExpr::Create(
4120         Context, /*QualifierLoc*/ NestedNameSpecifierLoc(),
4121         /*TemplateKWLoc*/ SourceLocation(), VDPrivate,
4122         /*isEnclosingLocal*/ false, /*NameLoc*/ SourceLocation(), DE->getType(),
4123         /*VK*/ VK_LValue);
4124 
4125     DSAStack->addDSA(VD, DE, OMPC_private);
4126     Vars.push_back(DE);
4127     PrivateCopies.push_back(VDPrivateRefExpr);
4128   }
4129 
4130   if (Vars.empty())
4131     return nullptr;
4132 
4133   return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
4134                                   PrivateCopies);
4135 }
4136 
4137 namespace {
4138 class DiagsUninitializedSeveretyRAII {
4139 private:
4140   DiagnosticsEngine &Diags;
4141   SourceLocation SavedLoc;
4142   bool IsIgnored;
4143 
4144 public:
4145   DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
4146                                  bool IsIgnored)
4147       : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
4148     if (!IsIgnored) {
4149       Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
4150                         /*Map*/ diag::Severity::Ignored, Loc);
4151     }
4152   }
4153   ~DiagsUninitializedSeveretyRAII() {
4154     if (!IsIgnored)
4155       Diags.popMappings(SavedLoc);
4156   }
4157 };
4158 }
4159 
4160 OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
4161                                                SourceLocation StartLoc,
4162                                                SourceLocation LParenLoc,
4163                                                SourceLocation EndLoc) {
4164   SmallVector<Expr *, 8> Vars;
4165   SmallVector<Expr *, 8> PrivateCopies;
4166   SmallVector<Expr *, 8> Inits;
4167   bool IsImplicitClause =
4168       StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
4169   auto ImplicitClauseLoc = DSAStack->getConstructLoc();
4170 
4171   for (auto &RefExpr : VarList) {
4172     assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
4173     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
4174       // It will be analyzed later.
4175       Vars.push_back(RefExpr);
4176       PrivateCopies.push_back(nullptr);
4177       Inits.push_back(nullptr);
4178       continue;
4179     }
4180 
4181     SourceLocation ELoc =
4182         IsImplicitClause ? ImplicitClauseLoc : RefExpr->getExprLoc();
4183     // OpenMP [2.1, C/C++]
4184     //  A list item is a variable name.
4185     // OpenMP  [2.9.3.3, Restrictions, p.1]
4186     //  A variable that is part of another variable (as an array or
4187     //  structure element) cannot appear in a private clause.
4188     DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
4189     if (!DE || !isa<VarDecl>(DE->getDecl())) {
4190       Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
4191       continue;
4192     }
4193     Decl *D = DE->getDecl();
4194     VarDecl *VD = cast<VarDecl>(D);
4195 
4196     QualType Type = VD->getType();
4197     if (Type->isDependentType() || Type->isInstantiationDependentType()) {
4198       // It will be analyzed later.
4199       Vars.push_back(DE);
4200       PrivateCopies.push_back(nullptr);
4201       Inits.push_back(nullptr);
4202       continue;
4203     }
4204 
4205     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
4206     //  A variable that appears in a private clause must not have an incomplete
4207     //  type or a reference type.
4208     if (RequireCompleteType(ELoc, Type,
4209                             diag::err_omp_firstprivate_incomplete_type)) {
4210       continue;
4211     }
4212     if (Type->isReferenceType()) {
4213       if (IsImplicitClause) {
4214         Diag(ImplicitClauseLoc,
4215              diag::err_omp_task_predetermined_firstprivate_ref_type_arg)
4216             << Type;
4217         Diag(RefExpr->getExprLoc(), diag::note_used_here);
4218       } else {
4219         Diag(ELoc, diag::err_omp_clause_ref_type_arg)
4220             << getOpenMPClauseName(OMPC_firstprivate) << Type;
4221       }
4222       bool IsDecl =
4223           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
4224       Diag(VD->getLocation(),
4225            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
4226           << VD;
4227       continue;
4228     }
4229 
4230     // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
4231     //  A variable of class type (or array thereof) that appears in a private
4232     //  clause requires an accessible, unambiguous copy constructor for the
4233     //  class type.
4234     Type = Context.getBaseElementType(Type);
4235 
4236     // If an implicit firstprivate variable found it was checked already.
4237     if (!IsImplicitClause) {
4238       DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
4239       Type = Type.getNonReferenceType().getCanonicalType();
4240       bool IsConstant = Type.isConstant(Context);
4241       Type = Context.getBaseElementType(Type);
4242       // OpenMP [2.4.13, Data-sharing Attribute Clauses]
4243       //  A list item that specifies a given variable may not appear in more
4244       // than one clause on the same directive, except that a variable may be
4245       //  specified in both firstprivate and lastprivate clauses.
4246       if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
4247           DVar.CKind != OMPC_lastprivate && DVar.RefExpr) {
4248         Diag(ELoc, diag::err_omp_wrong_dsa)
4249             << getOpenMPClauseName(DVar.CKind)
4250             << getOpenMPClauseName(OMPC_firstprivate);
4251         ReportOriginalDSA(*this, DSAStack, VD, DVar);
4252         continue;
4253       }
4254 
4255       // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
4256       // in a Construct]
4257       //  Variables with the predetermined data-sharing attributes may not be
4258       //  listed in data-sharing attributes clauses, except for the cases
4259       //  listed below. For these exceptions only, listing a predetermined
4260       //  variable in a data-sharing attribute clause is allowed and overrides
4261       //  the variable's predetermined data-sharing attributes.
4262       // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
4263       // in a Construct, C/C++, p.2]
4264       //  Variables with const-qualified type having no mutable member may be
4265       //  listed in a firstprivate clause, even if they are static data members.
4266       if (!(IsConstant || VD->isStaticDataMember()) && !DVar.RefExpr &&
4267           DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
4268         Diag(ELoc, diag::err_omp_wrong_dsa)
4269             << getOpenMPClauseName(DVar.CKind)
4270             << getOpenMPClauseName(OMPC_firstprivate);
4271         ReportOriginalDSA(*this, DSAStack, VD, DVar);
4272         continue;
4273       }
4274 
4275       OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
4276       // OpenMP [2.9.3.4, Restrictions, p.2]
4277       //  A list item that is private within a parallel region must not appear
4278       //  in a firstprivate clause on a worksharing construct if any of the
4279       //  worksharing regions arising from the worksharing construct ever bind
4280       //  to any of the parallel regions arising from the parallel construct.
4281       if (isOpenMPWorksharingDirective(CurrDir) &&
4282           !isOpenMPParallelDirective(CurrDir)) {
4283         DVar = DSAStack->getImplicitDSA(VD, true);
4284         if (DVar.CKind != OMPC_shared &&
4285             (isOpenMPParallelDirective(DVar.DKind) ||
4286              DVar.DKind == OMPD_unknown)) {
4287           Diag(ELoc, diag::err_omp_required_access)
4288               << getOpenMPClauseName(OMPC_firstprivate)
4289               << getOpenMPClauseName(OMPC_shared);
4290           ReportOriginalDSA(*this, DSAStack, VD, DVar);
4291           continue;
4292         }
4293       }
4294       // OpenMP [2.9.3.4, Restrictions, p.3]
4295       //  A list item that appears in a reduction clause of a parallel construct
4296       //  must not appear in a firstprivate clause on a worksharing or task
4297       //  construct if any of the worksharing or task regions arising from the
4298       //  worksharing or task construct ever bind to any of the parallel regions
4299       //  arising from the parallel construct.
4300       // OpenMP [2.9.3.4, Restrictions, p.4]
4301       //  A list item that appears in a reduction clause in worksharing
4302       //  construct must not appear in a firstprivate clause in a task construct
4303       //  encountered during execution of any of the worksharing regions arising
4304       //  from the worksharing construct.
4305       if (CurrDir == OMPD_task) {
4306         DVar =
4307             DSAStack->hasInnermostDSA(VD, MatchesAnyClause(OMPC_reduction),
4308                                       [](OpenMPDirectiveKind K) -> bool {
4309                                         return isOpenMPParallelDirective(K) ||
4310                                                isOpenMPWorksharingDirective(K);
4311                                       },
4312                                       false);
4313         if (DVar.CKind == OMPC_reduction &&
4314             (isOpenMPParallelDirective(DVar.DKind) ||
4315              isOpenMPWorksharingDirective(DVar.DKind))) {
4316           Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
4317               << getOpenMPDirectiveName(DVar.DKind);
4318           ReportOriginalDSA(*this, DSAStack, VD, DVar);
4319           continue;
4320         }
4321       }
4322     }
4323 
4324     Type = Type.getUnqualifiedType();
4325     auto VDPrivate = VarDecl::Create(Context, CurContext, DE->getLocStart(),
4326                                      ELoc, VD->getIdentifier(), VD->getType(),
4327                                      VD->getTypeSourceInfo(), /*S*/ SC_Auto);
4328     // Generate helper private variable and initialize it with the value of the
4329     // original variable. The address of the original variable is replaced by
4330     // the address of the new private variable in the CodeGen. This new variable
4331     // is not added to IdResolver, so the code in the OpenMP region uses
4332     // original variable for proper diagnostics and variable capturing.
4333     Expr *VDInitRefExpr = nullptr;
4334     // For arrays generate initializer for single element and replace it by the
4335     // original array element in CodeGen.
4336     if (DE->getType()->isArrayType()) {
4337       auto VDInit = VarDecl::Create(Context, CurContext, DE->getLocStart(),
4338                                     ELoc, VD->getIdentifier(), Type,
4339                                     VD->getTypeSourceInfo(), /*S*/ SC_Auto);
4340       CurContext->addHiddenDecl(VDInit);
4341       VDInitRefExpr = DeclRefExpr::Create(
4342           Context, /*QualifierLoc*/ NestedNameSpecifierLoc(),
4343           /*TemplateKWLoc*/ SourceLocation(), VDInit,
4344           /*isEnclosingLocal*/ false, ELoc, Type,
4345           /*VK*/ VK_LValue);
4346       VDInit->setIsUsed();
4347       auto Init = DefaultLvalueConversion(VDInitRefExpr).get();
4348       InitializedEntity Entity = InitializedEntity::InitializeVariable(VDInit);
4349       InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
4350 
4351       InitializationSequence InitSeq(*this, Entity, Kind, Init);
4352       ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
4353       if (Result.isInvalid())
4354         VDPrivate->setInvalidDecl();
4355       else
4356         VDPrivate->setInit(Result.getAs<Expr>());
4357     } else {
4358       AddInitializerToDecl(VDPrivate, DefaultLvalueConversion(DE).get(),
4359                            /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
4360     }
4361     if (VDPrivate->isInvalidDecl()) {
4362       if (IsImplicitClause) {
4363         Diag(DE->getExprLoc(),
4364              diag::note_omp_task_predetermined_firstprivate_here);
4365       }
4366       continue;
4367     }
4368     CurContext->addDecl(VDPrivate);
4369     auto VDPrivateRefExpr = DeclRefExpr::Create(
4370         Context, /*QualifierLoc*/ NestedNameSpecifierLoc(),
4371         /*TemplateKWLoc*/ SourceLocation(), VDPrivate,
4372         /*isEnclosingLocal*/ false, DE->getLocStart(), DE->getType(),
4373         /*VK*/ VK_LValue);
4374     DSAStack->addDSA(VD, DE, OMPC_firstprivate);
4375     Vars.push_back(DE);
4376     PrivateCopies.push_back(VDPrivateRefExpr);
4377     Inits.push_back(VDInitRefExpr);
4378   }
4379 
4380   if (Vars.empty())
4381     return nullptr;
4382 
4383   return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
4384                                        Vars, PrivateCopies, Inits);
4385 }
4386 
4387 OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
4388                                               SourceLocation StartLoc,
4389                                               SourceLocation LParenLoc,
4390                                               SourceLocation EndLoc) {
4391   SmallVector<Expr *, 8> Vars;
4392   for (auto &RefExpr : VarList) {
4393     assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
4394     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
4395       // It will be analyzed later.
4396       Vars.push_back(RefExpr);
4397       continue;
4398     }
4399 
4400     SourceLocation ELoc = RefExpr->getExprLoc();
4401     // OpenMP [2.1, C/C++]
4402     //  A list item is a variable name.
4403     // OpenMP  [2.14.3.5, Restrictions, p.1]
4404     //  A variable that is part of another variable (as an array or structure
4405     //  element) cannot appear in a lastprivate clause.
4406     DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
4407     if (!DE || !isa<VarDecl>(DE->getDecl())) {
4408       Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
4409       continue;
4410     }
4411     Decl *D = DE->getDecl();
4412     VarDecl *VD = cast<VarDecl>(D);
4413 
4414     QualType Type = VD->getType();
4415     if (Type->isDependentType() || Type->isInstantiationDependentType()) {
4416       // It will be analyzed later.
4417       Vars.push_back(DE);
4418       continue;
4419     }
4420 
4421     // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
4422     //  A variable that appears in a lastprivate clause must not have an
4423     //  incomplete type or a reference type.
4424     if (RequireCompleteType(ELoc, Type,
4425                             diag::err_omp_lastprivate_incomplete_type)) {
4426       continue;
4427     }
4428     if (Type->isReferenceType()) {
4429       Diag(ELoc, diag::err_omp_clause_ref_type_arg)
4430           << getOpenMPClauseName(OMPC_lastprivate) << Type;
4431       bool IsDecl =
4432           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
4433       Diag(VD->getLocation(),
4434            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
4435           << VD;
4436       continue;
4437     }
4438 
4439     // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
4440     // in a Construct]
4441     //  Variables with the predetermined data-sharing attributes may not be
4442     //  listed in data-sharing attributes clauses, except for the cases
4443     //  listed below.
4444     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
4445     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
4446         DVar.CKind != OMPC_firstprivate &&
4447         (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
4448       Diag(ELoc, diag::err_omp_wrong_dsa)
4449           << getOpenMPClauseName(DVar.CKind)
4450           << getOpenMPClauseName(OMPC_lastprivate);
4451       ReportOriginalDSA(*this, DSAStack, VD, DVar);
4452       continue;
4453     }
4454 
4455     OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
4456     // OpenMP [2.14.3.5, Restrictions, p.2]
4457     // A list item that is private within a parallel region, or that appears in
4458     // the reduction clause of a parallel construct, must not appear in a
4459     // lastprivate clause on a worksharing construct if any of the corresponding
4460     // worksharing regions ever binds to any of the corresponding parallel
4461     // regions.
4462     if (isOpenMPWorksharingDirective(CurrDir) &&
4463         !isOpenMPParallelDirective(CurrDir)) {
4464       DVar = DSAStack->getImplicitDSA(VD, true);
4465       if (DVar.CKind != OMPC_shared) {
4466         Diag(ELoc, diag::err_omp_required_access)
4467             << getOpenMPClauseName(OMPC_lastprivate)
4468             << getOpenMPClauseName(OMPC_shared);
4469         ReportOriginalDSA(*this, DSAStack, VD, DVar);
4470         continue;
4471       }
4472     }
4473     // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
4474     //  A variable of class type (or array thereof) that appears in a
4475     //  lastprivate clause requires an accessible, unambiguous default
4476     //  constructor for the class type, unless the list item is also specified
4477     //  in a firstprivate clause.
4478     //  A variable of class type (or array thereof) that appears in a
4479     //  lastprivate clause requires an accessible, unambiguous copy assignment
4480     //  operator for the class type.
4481     while (Type.getNonReferenceType()->isArrayType())
4482       Type = cast<ArrayType>(Type.getNonReferenceType().getTypePtr())
4483                  ->getElementType();
4484     CXXRecordDecl *RD = getLangOpts().CPlusPlus
4485                             ? Type.getNonReferenceType()->getAsCXXRecordDecl()
4486                             : nullptr;
4487     // FIXME This code must be replaced by actual copying and destructing of the
4488     // lastprivate variable.
4489     if (RD) {
4490       CXXMethodDecl *MD = LookupCopyingAssignment(RD, 0, false, 0);
4491       DeclAccessPair FoundDecl = DeclAccessPair::make(MD, MD->getAccess());
4492       if (MD) {
4493         if (CheckMemberAccess(ELoc, RD, FoundDecl) == AR_inaccessible ||
4494             MD->isDeleted()) {
4495           Diag(ELoc, diag::err_omp_required_method)
4496               << getOpenMPClauseName(OMPC_lastprivate) << 2;
4497           bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
4498                         VarDecl::DeclarationOnly;
4499           Diag(VD->getLocation(),
4500                IsDecl ? diag::note_previous_decl : diag::note_defined_here)
4501               << VD;
4502           Diag(RD->getLocation(), diag::note_previous_decl) << RD;
4503           continue;
4504         }
4505         MarkFunctionReferenced(ELoc, MD);
4506         DiagnoseUseOfDecl(MD, ELoc);
4507       }
4508 
4509       CXXDestructorDecl *DD = RD->getDestructor();
4510       if (DD) {
4511         PartialDiagnostic PD =
4512             PartialDiagnostic(PartialDiagnostic::NullDiagnostic());
4513         if (CheckDestructorAccess(ELoc, DD, PD) == AR_inaccessible ||
4514             DD->isDeleted()) {
4515           Diag(ELoc, diag::err_omp_required_method)
4516               << getOpenMPClauseName(OMPC_lastprivate) << 4;
4517           bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
4518                         VarDecl::DeclarationOnly;
4519           Diag(VD->getLocation(),
4520                IsDecl ? diag::note_previous_decl : diag::note_defined_here)
4521               << VD;
4522           Diag(RD->getLocation(), diag::note_previous_decl) << RD;
4523           continue;
4524         }
4525         MarkFunctionReferenced(ELoc, DD);
4526         DiagnoseUseOfDecl(DD, ELoc);
4527       }
4528     }
4529 
4530     if (DVar.CKind != OMPC_firstprivate)
4531       DSAStack->addDSA(VD, DE, OMPC_lastprivate);
4532     Vars.push_back(DE);
4533   }
4534 
4535   if (Vars.empty())
4536     return nullptr;
4537 
4538   return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
4539                                       Vars);
4540 }
4541 
4542 OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
4543                                          SourceLocation StartLoc,
4544                                          SourceLocation LParenLoc,
4545                                          SourceLocation EndLoc) {
4546   SmallVector<Expr *, 8> Vars;
4547   for (auto &RefExpr : VarList) {
4548     assert(RefExpr && "NULL expr in OpenMP shared clause.");
4549     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
4550       // It will be analyzed later.
4551       Vars.push_back(RefExpr);
4552       continue;
4553     }
4554 
4555     SourceLocation ELoc = RefExpr->getExprLoc();
4556     // OpenMP [2.1, C/C++]
4557     //  A list item is a variable name.
4558     // OpenMP  [2.14.3.2, Restrictions, p.1]
4559     //  A variable that is part of another variable (as an array or structure
4560     //  element) cannot appear in a shared unless it is a static data member
4561     //  of a C++ class.
4562     DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
4563     if (!DE || !isa<VarDecl>(DE->getDecl())) {
4564       Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
4565       continue;
4566     }
4567     Decl *D = DE->getDecl();
4568     VarDecl *VD = cast<VarDecl>(D);
4569 
4570     QualType Type = VD->getType();
4571     if (Type->isDependentType() || Type->isInstantiationDependentType()) {
4572       // It will be analyzed later.
4573       Vars.push_back(DE);
4574       continue;
4575     }
4576 
4577     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
4578     // in a Construct]
4579     //  Variables with the predetermined data-sharing attributes may not be
4580     //  listed in data-sharing attributes clauses, except for the cases
4581     //  listed below. For these exceptions only, listing a predetermined
4582     //  variable in a data-sharing attribute clause is allowed and overrides
4583     //  the variable's predetermined data-sharing attributes.
4584     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
4585     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
4586         DVar.RefExpr) {
4587       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
4588                                           << getOpenMPClauseName(OMPC_shared);
4589       ReportOriginalDSA(*this, DSAStack, VD, DVar);
4590       continue;
4591     }
4592 
4593     DSAStack->addDSA(VD, DE, OMPC_shared);
4594     Vars.push_back(DE);
4595   }
4596 
4597   if (Vars.empty())
4598     return nullptr;
4599 
4600   return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
4601 }
4602 
4603 namespace {
4604 class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
4605   DSAStackTy *Stack;
4606 
4607 public:
4608   bool VisitDeclRefExpr(DeclRefExpr *E) {
4609     if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
4610       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false);
4611       if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
4612         return false;
4613       if (DVar.CKind != OMPC_unknown)
4614         return true;
4615       DSAStackTy::DSAVarData DVarPrivate =
4616           Stack->hasDSA(VD, isOpenMPPrivate, MatchesAlways(), false);
4617       if (DVarPrivate.CKind != OMPC_unknown)
4618         return true;
4619       return false;
4620     }
4621     return false;
4622   }
4623   bool VisitStmt(Stmt *S) {
4624     for (auto Child : S->children()) {
4625       if (Child && Visit(Child))
4626         return true;
4627     }
4628     return false;
4629   }
4630   explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
4631 };
4632 } // namespace
4633 
4634 OMPClause *Sema::ActOnOpenMPReductionClause(
4635     ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
4636     SourceLocation ColonLoc, SourceLocation EndLoc,
4637     CXXScopeSpec &ReductionIdScopeSpec,
4638     const DeclarationNameInfo &ReductionId) {
4639   // TODO: Allow scope specification search when 'declare reduction' is
4640   // supported.
4641   assert(ReductionIdScopeSpec.isEmpty() &&
4642          "No support for scoped reduction identifiers yet.");
4643 
4644   auto DN = ReductionId.getName();
4645   auto OOK = DN.getCXXOverloadedOperator();
4646   BinaryOperatorKind BOK = BO_Comma;
4647 
4648   // OpenMP [2.14.3.6, reduction clause]
4649   // C
4650   // reduction-identifier is either an identifier or one of the following
4651   // operators: +, -, *,  &, |, ^, && and ||
4652   // C++
4653   // reduction-identifier is either an id-expression or one of the following
4654   // operators: +, -, *, &, |, ^, && and ||
4655   // FIXME: Only 'min' and 'max' identifiers are supported for now.
4656   switch (OOK) {
4657   case OO_Plus:
4658   case OO_Minus:
4659     BOK = BO_AddAssign;
4660     break;
4661   case OO_Star:
4662     BOK = BO_MulAssign;
4663     break;
4664   case OO_Amp:
4665     BOK = BO_AndAssign;
4666     break;
4667   case OO_Pipe:
4668     BOK = BO_OrAssign;
4669     break;
4670   case OO_Caret:
4671     BOK = BO_XorAssign;
4672     break;
4673   case OO_AmpAmp:
4674     BOK = BO_LAnd;
4675     break;
4676   case OO_PipePipe:
4677     BOK = BO_LOr;
4678     break;
4679   default:
4680     if (auto II = DN.getAsIdentifierInfo()) {
4681       if (II->isStr("max"))
4682         BOK = BO_GT;
4683       else if (II->isStr("min"))
4684         BOK = BO_LT;
4685     }
4686     break;
4687   }
4688   SourceRange ReductionIdRange;
4689   if (ReductionIdScopeSpec.isValid()) {
4690     ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
4691   }
4692   ReductionIdRange.setEnd(ReductionId.getEndLoc());
4693   if (BOK == BO_Comma) {
4694     // Not allowed reduction identifier is found.
4695     Diag(ReductionId.getLocStart(), diag::err_omp_unknown_reduction_identifier)
4696         << ReductionIdRange;
4697     return nullptr;
4698   }
4699 
4700   SmallVector<Expr *, 8> Vars;
4701   for (auto RefExpr : VarList) {
4702     assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
4703     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
4704       // It will be analyzed later.
4705       Vars.push_back(RefExpr);
4706       continue;
4707     }
4708 
4709     if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
4710         RefExpr->isInstantiationDependent() ||
4711         RefExpr->containsUnexpandedParameterPack()) {
4712       // It will be analyzed later.
4713       Vars.push_back(RefExpr);
4714       continue;
4715     }
4716 
4717     auto ELoc = RefExpr->getExprLoc();
4718     auto ERange = RefExpr->getSourceRange();
4719     // OpenMP [2.1, C/C++]
4720     //  A list item is a variable or array section, subject to the restrictions
4721     //  specified in Section 2.4 on page 42 and in each of the sections
4722     // describing clauses and directives for which a list appears.
4723     // OpenMP  [2.14.3.3, Restrictions, p.1]
4724     //  A variable that is part of another variable (as an array or
4725     //  structure element) cannot appear in a private clause.
4726     auto DE = dyn_cast<DeclRefExpr>(RefExpr);
4727     if (!DE || !isa<VarDecl>(DE->getDecl())) {
4728       Diag(ELoc, diag::err_omp_expected_var_name) << ERange;
4729       continue;
4730     }
4731     auto D = DE->getDecl();
4732     auto VD = cast<VarDecl>(D);
4733     auto Type = VD->getType();
4734     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
4735     //  A variable that appears in a private clause must not have an incomplete
4736     //  type or a reference type.
4737     if (RequireCompleteType(ELoc, Type,
4738                             diag::err_omp_reduction_incomplete_type))
4739       continue;
4740     // OpenMP [2.14.3.6, reduction clause, Restrictions]
4741     // Arrays may not appear in a reduction clause.
4742     if (Type.getNonReferenceType()->isArrayType()) {
4743       Diag(ELoc, diag::err_omp_reduction_type_array) << Type << ERange;
4744       bool IsDecl =
4745           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
4746       Diag(VD->getLocation(),
4747            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
4748           << VD;
4749       continue;
4750     }
4751     // OpenMP [2.14.3.6, reduction clause, Restrictions]
4752     // A list item that appears in a reduction clause must not be
4753     // const-qualified.
4754     if (Type.getNonReferenceType().isConstant(Context)) {
4755       Diag(ELoc, diag::err_omp_const_variable)
4756           << getOpenMPClauseName(OMPC_reduction) << Type << ERange;
4757       bool IsDecl =
4758           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
4759       Diag(VD->getLocation(),
4760            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
4761           << VD;
4762       continue;
4763     }
4764     // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
4765     //  If a list-item is a reference type then it must bind to the same object
4766     //  for all threads of the team.
4767     VarDecl *VDDef = VD->getDefinition();
4768     if (Type->isReferenceType() && VDDef) {
4769       DSARefChecker Check(DSAStack);
4770       if (Check.Visit(VDDef->getInit())) {
4771         Diag(ELoc, diag::err_omp_reduction_ref_type_arg) << ERange;
4772         Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
4773         continue;
4774       }
4775     }
4776     // OpenMP [2.14.3.6, reduction clause, Restrictions]
4777     // The type of a list item that appears in a reduction clause must be valid
4778     // for the reduction-identifier. For a max or min reduction in C, the type
4779     // of the list item must be an allowed arithmetic data type: char, int,
4780     // float, double, or _Bool, possibly modified with long, short, signed, or
4781     // unsigned. For a max or min reduction in C++, the type of the list item
4782     // must be an allowed arithmetic data type: char, wchar_t, int, float,
4783     // double, or bool, possibly modified with long, short, signed, or unsigned.
4784     if ((BOK == BO_GT || BOK == BO_LT) &&
4785         !(Type->isScalarType() ||
4786           (getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
4787       Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
4788           << getLangOpts().CPlusPlus;
4789       bool IsDecl =
4790           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
4791       Diag(VD->getLocation(),
4792            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
4793           << VD;
4794       continue;
4795     }
4796     if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
4797         !getLangOpts().CPlusPlus && Type->isFloatingType()) {
4798       Diag(ELoc, diag::err_omp_clause_floating_type_arg);
4799       bool IsDecl =
4800           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
4801       Diag(VD->getLocation(),
4802            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
4803           << VD;
4804       continue;
4805     }
4806     bool Suppress = getDiagnostics().getSuppressAllDiagnostics();
4807     getDiagnostics().setSuppressAllDiagnostics(true);
4808     ExprResult ReductionOp =
4809         BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(), BOK,
4810                    RefExpr, RefExpr);
4811     getDiagnostics().setSuppressAllDiagnostics(Suppress);
4812     if (ReductionOp.isInvalid()) {
4813       Diag(ELoc, diag::err_omp_reduction_id_not_compatible) << Type
4814                                                             << ReductionIdRange;
4815       bool IsDecl =
4816           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
4817       Diag(VD->getLocation(),
4818            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
4819           << VD;
4820       continue;
4821     }
4822 
4823     // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
4824     // in a Construct]
4825     //  Variables with the predetermined data-sharing attributes may not be
4826     //  listed in data-sharing attributes clauses, except for the cases
4827     //  listed below. For these exceptions only, listing a predetermined
4828     //  variable in a data-sharing attribute clause is allowed and overrides
4829     //  the variable's predetermined data-sharing attributes.
4830     // OpenMP [2.14.3.6, Restrictions, p.3]
4831     //  Any number of reduction clauses can be specified on the directive,
4832     //  but a list item can appear only once in the reduction clauses for that
4833     //  directive.
4834     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
4835     if (DVar.CKind == OMPC_reduction) {
4836       Diag(ELoc, diag::err_omp_once_referenced)
4837           << getOpenMPClauseName(OMPC_reduction);
4838       if (DVar.RefExpr) {
4839         Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
4840       }
4841     } else if (DVar.CKind != OMPC_unknown) {
4842       Diag(ELoc, diag::err_omp_wrong_dsa)
4843           << getOpenMPClauseName(DVar.CKind)
4844           << getOpenMPClauseName(OMPC_reduction);
4845       ReportOriginalDSA(*this, DSAStack, VD, DVar);
4846       continue;
4847     }
4848 
4849     // OpenMP [2.14.3.6, Restrictions, p.1]
4850     //  A list item that appears in a reduction clause of a worksharing
4851     //  construct must be shared in the parallel regions to which any of the
4852     //  worksharing regions arising from the worksharing construct bind.
4853     OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
4854     if (isOpenMPWorksharingDirective(CurrDir) &&
4855         !isOpenMPParallelDirective(CurrDir)) {
4856       DVar = DSAStack->getImplicitDSA(VD, true);
4857       if (DVar.CKind != OMPC_shared) {
4858         Diag(ELoc, diag::err_omp_required_access)
4859             << getOpenMPClauseName(OMPC_reduction)
4860             << getOpenMPClauseName(OMPC_shared);
4861         ReportOriginalDSA(*this, DSAStack, VD, DVar);
4862         continue;
4863       }
4864     }
4865 
4866     CXXRecordDecl *RD = getLangOpts().CPlusPlus
4867                             ? Type.getNonReferenceType()->getAsCXXRecordDecl()
4868                             : nullptr;
4869     // FIXME This code must be replaced by actual constructing/destructing of
4870     // the reduction variable.
4871     if (RD) {
4872       CXXConstructorDecl *CD = LookupDefaultConstructor(RD);
4873       PartialDiagnostic PD =
4874           PartialDiagnostic(PartialDiagnostic::NullDiagnostic());
4875       if (!CD ||
4876           CheckConstructorAccess(ELoc, CD,
4877                                  InitializedEntity::InitializeTemporary(Type),
4878                                  CD->getAccess(), PD) == AR_inaccessible ||
4879           CD->isDeleted()) {
4880         Diag(ELoc, diag::err_omp_required_method)
4881             << getOpenMPClauseName(OMPC_reduction) << 0;
4882         bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
4883                       VarDecl::DeclarationOnly;
4884         Diag(VD->getLocation(),
4885              IsDecl ? diag::note_previous_decl : diag::note_defined_here)
4886             << VD;
4887         Diag(RD->getLocation(), diag::note_previous_decl) << RD;
4888         continue;
4889       }
4890       MarkFunctionReferenced(ELoc, CD);
4891       DiagnoseUseOfDecl(CD, ELoc);
4892 
4893       CXXDestructorDecl *DD = RD->getDestructor();
4894       if (DD) {
4895         if (CheckDestructorAccess(ELoc, DD, PD) == AR_inaccessible ||
4896             DD->isDeleted()) {
4897           Diag(ELoc, diag::err_omp_required_method)
4898               << getOpenMPClauseName(OMPC_reduction) << 4;
4899           bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
4900                         VarDecl::DeclarationOnly;
4901           Diag(VD->getLocation(),
4902                IsDecl ? diag::note_previous_decl : diag::note_defined_here)
4903               << VD;
4904           Diag(RD->getLocation(), diag::note_previous_decl) << RD;
4905           continue;
4906         }
4907         MarkFunctionReferenced(ELoc, DD);
4908         DiagnoseUseOfDecl(DD, ELoc);
4909       }
4910     }
4911 
4912     DSAStack->addDSA(VD, DE, OMPC_reduction);
4913     Vars.push_back(DE);
4914   }
4915 
4916   if (Vars.empty())
4917     return nullptr;
4918 
4919   return OMPReductionClause::Create(
4920       Context, StartLoc, LParenLoc, ColonLoc, EndLoc, Vars,
4921       ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId);
4922 }
4923 
4924 OMPClause *Sema::ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
4925                                          SourceLocation StartLoc,
4926                                          SourceLocation LParenLoc,
4927                                          SourceLocation ColonLoc,
4928                                          SourceLocation EndLoc) {
4929   SmallVector<Expr *, 8> Vars;
4930   for (auto &RefExpr : VarList) {
4931     assert(RefExpr && "NULL expr in OpenMP linear clause.");
4932     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
4933       // It will be analyzed later.
4934       Vars.push_back(RefExpr);
4935       continue;
4936     }
4937 
4938     // OpenMP [2.14.3.7, linear clause]
4939     // A list item that appears in a linear clause is subject to the private
4940     // clause semantics described in Section 2.14.3.3 on page 159 except as
4941     // noted. In addition, the value of the new list item on each iteration
4942     // of the associated loop(s) corresponds to the value of the original
4943     // list item before entering the construct plus the logical number of
4944     // the iteration times linear-step.
4945 
4946     SourceLocation ELoc = RefExpr->getExprLoc();
4947     // OpenMP [2.1, C/C++]
4948     //  A list item is a variable name.
4949     // OpenMP  [2.14.3.3, Restrictions, p.1]
4950     //  A variable that is part of another variable (as an array or
4951     //  structure element) cannot appear in a private clause.
4952     DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
4953     if (!DE || !isa<VarDecl>(DE->getDecl())) {
4954       Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
4955       continue;
4956     }
4957 
4958     VarDecl *VD = cast<VarDecl>(DE->getDecl());
4959 
4960     // OpenMP [2.14.3.7, linear clause]
4961     //  A list-item cannot appear in more than one linear clause.
4962     //  A list-item that appears in a linear clause cannot appear in any
4963     //  other data-sharing attribute clause.
4964     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
4965     if (DVar.RefExpr) {
4966       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
4967                                           << getOpenMPClauseName(OMPC_linear);
4968       ReportOriginalDSA(*this, DSAStack, VD, DVar);
4969       continue;
4970     }
4971 
4972     QualType QType = VD->getType();
4973     if (QType->isDependentType() || QType->isInstantiationDependentType()) {
4974       // It will be analyzed later.
4975       Vars.push_back(DE);
4976       continue;
4977     }
4978 
4979     // A variable must not have an incomplete type or a reference type.
4980     if (RequireCompleteType(ELoc, QType,
4981                             diag::err_omp_linear_incomplete_type)) {
4982       continue;
4983     }
4984     if (QType->isReferenceType()) {
4985       Diag(ELoc, diag::err_omp_clause_ref_type_arg)
4986           << getOpenMPClauseName(OMPC_linear) << QType;
4987       bool IsDecl =
4988           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
4989       Diag(VD->getLocation(),
4990            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
4991           << VD;
4992       continue;
4993     }
4994 
4995     // A list item must not be const-qualified.
4996     if (QType.isConstant(Context)) {
4997       Diag(ELoc, diag::err_omp_const_variable)
4998           << getOpenMPClauseName(OMPC_linear);
4999       bool IsDecl =
5000           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5001       Diag(VD->getLocation(),
5002            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5003           << VD;
5004       continue;
5005     }
5006 
5007     // A list item must be of integral or pointer type.
5008     QType = QType.getUnqualifiedType().getCanonicalType();
5009     const Type *Ty = QType.getTypePtrOrNull();
5010     if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
5011                 !Ty->isPointerType())) {
5012       Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << QType;
5013       bool IsDecl =
5014           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5015       Diag(VD->getLocation(),
5016            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5017           << VD;
5018       continue;
5019     }
5020 
5021     DSAStack->addDSA(VD, DE, OMPC_linear);
5022     Vars.push_back(DE);
5023   }
5024 
5025   if (Vars.empty())
5026     return nullptr;
5027 
5028   Expr *StepExpr = Step;
5029   if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
5030       !Step->isInstantiationDependent() &&
5031       !Step->containsUnexpandedParameterPack()) {
5032     SourceLocation StepLoc = Step->getLocStart();
5033     ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
5034     if (Val.isInvalid())
5035       return nullptr;
5036     StepExpr = Val.get();
5037 
5038     // Warn about zero linear step (it would be probably better specified as
5039     // making corresponding variables 'const').
5040     llvm::APSInt Result;
5041     if (StepExpr->isIntegerConstantExpr(Result, Context) &&
5042         !Result.isNegative() && !Result.isStrictlyPositive())
5043       Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
5044                                                      << (Vars.size() > 1);
5045   }
5046 
5047   return OMPLinearClause::Create(Context, StartLoc, LParenLoc, ColonLoc, EndLoc,
5048                                  Vars, StepExpr);
5049 }
5050 
5051 OMPClause *Sema::ActOnOpenMPAlignedClause(
5052     ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
5053     SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
5054 
5055   SmallVector<Expr *, 8> Vars;
5056   for (auto &RefExpr : VarList) {
5057     assert(RefExpr && "NULL expr in OpenMP aligned clause.");
5058     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
5059       // It will be analyzed later.
5060       Vars.push_back(RefExpr);
5061       continue;
5062     }
5063 
5064     SourceLocation ELoc = RefExpr->getExprLoc();
5065     // OpenMP [2.1, C/C++]
5066     //  A list item is a variable name.
5067     DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
5068     if (!DE || !isa<VarDecl>(DE->getDecl())) {
5069       Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
5070       continue;
5071     }
5072 
5073     VarDecl *VD = cast<VarDecl>(DE->getDecl());
5074 
5075     // OpenMP  [2.8.1, simd construct, Restrictions]
5076     // The type of list items appearing in the aligned clause must be
5077     // array, pointer, reference to array, or reference to pointer.
5078     QualType QType = DE->getType()
5079                          .getNonReferenceType()
5080                          .getUnqualifiedType()
5081                          .getCanonicalType();
5082     const Type *Ty = QType.getTypePtrOrNull();
5083     if (!Ty || (!Ty->isDependentType() && !Ty->isArrayType() &&
5084                 !Ty->isPointerType())) {
5085       Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
5086           << QType << getLangOpts().CPlusPlus << RefExpr->getSourceRange();
5087       bool IsDecl =
5088           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5089       Diag(VD->getLocation(),
5090            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5091           << VD;
5092       continue;
5093     }
5094 
5095     // OpenMP  [2.8.1, simd construct, Restrictions]
5096     // A list-item cannot appear in more than one aligned clause.
5097     if (DeclRefExpr *PrevRef = DSAStack->addUniqueAligned(VD, DE)) {
5098       Diag(ELoc, diag::err_omp_aligned_twice) << RefExpr->getSourceRange();
5099       Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
5100           << getOpenMPClauseName(OMPC_aligned);
5101       continue;
5102     }
5103 
5104     Vars.push_back(DE);
5105   }
5106 
5107   // OpenMP [2.8.1, simd construct, Description]
5108   // The parameter of the aligned clause, alignment, must be a constant
5109   // positive integer expression.
5110   // If no optional parameter is specified, implementation-defined default
5111   // alignments for SIMD instructions on the target platforms are assumed.
5112   if (Alignment != nullptr) {
5113     ExprResult AlignResult =
5114         VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
5115     if (AlignResult.isInvalid())
5116       return nullptr;
5117     Alignment = AlignResult.get();
5118   }
5119   if (Vars.empty())
5120     return nullptr;
5121 
5122   return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
5123                                   EndLoc, Vars, Alignment);
5124 }
5125 
5126 OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
5127                                          SourceLocation StartLoc,
5128                                          SourceLocation LParenLoc,
5129                                          SourceLocation EndLoc) {
5130   SmallVector<Expr *, 8> Vars;
5131   for (auto &RefExpr : VarList) {
5132     assert(RefExpr && "NULL expr in OpenMP copyin clause.");
5133     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
5134       // It will be analyzed later.
5135       Vars.push_back(RefExpr);
5136       continue;
5137     }
5138 
5139     SourceLocation ELoc = RefExpr->getExprLoc();
5140     // OpenMP [2.1, C/C++]
5141     //  A list item is a variable name.
5142     // OpenMP  [2.14.4.1, Restrictions, p.1]
5143     //  A list item that appears in a copyin clause must be threadprivate.
5144     DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
5145     if (!DE || !isa<VarDecl>(DE->getDecl())) {
5146       Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
5147       continue;
5148     }
5149 
5150     Decl *D = DE->getDecl();
5151     VarDecl *VD = cast<VarDecl>(D);
5152 
5153     QualType Type = VD->getType();
5154     if (Type->isDependentType() || Type->isInstantiationDependentType()) {
5155       // It will be analyzed later.
5156       Vars.push_back(DE);
5157       continue;
5158     }
5159 
5160     // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
5161     //  A list item that appears in a copyin clause must be threadprivate.
5162     if (!DSAStack->isThreadPrivate(VD)) {
5163       Diag(ELoc, diag::err_omp_required_access)
5164           << getOpenMPClauseName(OMPC_copyin)
5165           << getOpenMPDirectiveName(OMPD_threadprivate);
5166       continue;
5167     }
5168 
5169     // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
5170     //  A variable of class type (or array thereof) that appears in a
5171     //  copyin clause requires an accessible, unambiguous copy assignment
5172     //  operator for the class type.
5173     Type = Context.getBaseElementType(Type);
5174     CXXRecordDecl *RD =
5175         getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
5176     // FIXME This code must be replaced by actual assignment of the
5177     // threadprivate variable.
5178     if (RD) {
5179       CXXMethodDecl *MD = LookupCopyingAssignment(RD, 0, false, 0);
5180       DeclAccessPair FoundDecl = DeclAccessPair::make(MD, MD->getAccess());
5181       if (MD) {
5182         if (CheckMemberAccess(ELoc, RD, FoundDecl) == AR_inaccessible ||
5183             MD->isDeleted()) {
5184           Diag(ELoc, diag::err_omp_required_method)
5185               << getOpenMPClauseName(OMPC_copyin) << 2;
5186           bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
5187                         VarDecl::DeclarationOnly;
5188           Diag(VD->getLocation(),
5189                IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5190               << VD;
5191           Diag(RD->getLocation(), diag::note_previous_decl) << RD;
5192           continue;
5193         }
5194         MarkFunctionReferenced(ELoc, MD);
5195         DiagnoseUseOfDecl(MD, ELoc);
5196       }
5197     }
5198 
5199     DSAStack->addDSA(VD, DE, OMPC_copyin);
5200     Vars.push_back(DE);
5201   }
5202 
5203   if (Vars.empty())
5204     return nullptr;
5205 
5206   return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
5207 }
5208 
5209 OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
5210                                               SourceLocation StartLoc,
5211                                               SourceLocation LParenLoc,
5212                                               SourceLocation EndLoc) {
5213   SmallVector<Expr *, 8> Vars;
5214   for (auto &RefExpr : VarList) {
5215     assert(RefExpr && "NULL expr in OpenMP copyprivate clause.");
5216     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
5217       // It will be analyzed later.
5218       Vars.push_back(RefExpr);
5219       continue;
5220     }
5221 
5222     SourceLocation ELoc = RefExpr->getExprLoc();
5223     // OpenMP [2.1, C/C++]
5224     //  A list item is a variable name.
5225     // OpenMP  [2.14.4.1, Restrictions, p.1]
5226     //  A list item that appears in a copyin clause must be threadprivate.
5227     DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
5228     if (!DE || !isa<VarDecl>(DE->getDecl())) {
5229       Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
5230       continue;
5231     }
5232 
5233     Decl *D = DE->getDecl();
5234     VarDecl *VD = cast<VarDecl>(D);
5235 
5236     QualType Type = VD->getType();
5237     if (Type->isDependentType() || Type->isInstantiationDependentType()) {
5238       // It will be analyzed later.
5239       Vars.push_back(DE);
5240       continue;
5241     }
5242 
5243     // OpenMP [2.14.4.2, Restrictions, p.2]
5244     //  A list item that appears in a copyprivate clause may not appear in a
5245     //  private or firstprivate clause on the single construct.
5246     if (!DSAStack->isThreadPrivate(VD)) {
5247       auto DVar = DSAStack->getTopDSA(VD, false);
5248       if (DVar.CKind != OMPC_copyprivate && DVar.CKind != OMPC_unknown &&
5249           !(DVar.CKind == OMPC_private && !DVar.RefExpr)) {
5250         Diag(ELoc, diag::err_omp_wrong_dsa)
5251             << getOpenMPClauseName(DVar.CKind)
5252             << getOpenMPClauseName(OMPC_copyprivate);
5253         ReportOriginalDSA(*this, DSAStack, VD, DVar);
5254         continue;
5255       }
5256 
5257       // OpenMP [2.11.4.2, Restrictions, p.1]
5258       //  All list items that appear in a copyprivate clause must be either
5259       //  threadprivate or private in the enclosing context.
5260       if (DVar.CKind == OMPC_unknown) {
5261         DVar = DSAStack->getImplicitDSA(VD, false);
5262         if (DVar.CKind == OMPC_shared) {
5263           Diag(ELoc, diag::err_omp_required_access)
5264               << getOpenMPClauseName(OMPC_copyprivate)
5265               << "threadprivate or private in the enclosing context";
5266           ReportOriginalDSA(*this, DSAStack, VD, DVar);
5267           continue;
5268         }
5269       }
5270     }
5271 
5272     // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
5273     //  A variable of class type (or array thereof) that appears in a
5274     //  copyin clause requires an accessible, unambiguous copy assignment
5275     //  operator for the class type.
5276     Type = Context.getBaseElementType(Type);
5277     CXXRecordDecl *RD =
5278         getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
5279     // FIXME This code must be replaced by actual assignment of the
5280     // threadprivate variable.
5281     if (RD) {
5282       CXXMethodDecl *MD = LookupCopyingAssignment(RD, 0, false, 0);
5283       DeclAccessPair FoundDecl = DeclAccessPair::make(MD, MD->getAccess());
5284       if (MD) {
5285         if (CheckMemberAccess(ELoc, RD, FoundDecl) == AR_inaccessible ||
5286             MD->isDeleted()) {
5287           Diag(ELoc, diag::err_omp_required_method)
5288               << getOpenMPClauseName(OMPC_copyprivate) << 2;
5289           bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
5290                         VarDecl::DeclarationOnly;
5291           Diag(VD->getLocation(),
5292                IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5293               << VD;
5294           Diag(RD->getLocation(), diag::note_previous_decl) << RD;
5295           continue;
5296         }
5297         MarkFunctionReferenced(ELoc, MD);
5298         DiagnoseUseOfDecl(MD, ELoc);
5299       }
5300     }
5301 
5302     // No need to mark vars as copyprivate, they are already threadprivate or
5303     // implicitly private.
5304     Vars.push_back(DE);
5305   }
5306 
5307   if (Vars.empty())
5308     return nullptr;
5309 
5310   return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
5311 }
5312 
5313 OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
5314                                         SourceLocation StartLoc,
5315                                         SourceLocation LParenLoc,
5316                                         SourceLocation EndLoc) {
5317   if (VarList.empty())
5318     return nullptr;
5319 
5320   return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
5321 }
5322 
5323