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