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