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