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