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 "TreeTransform.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTMutationListener.h"
18 #include "clang/AST/CXXInheritance.h"
19 #include "clang/AST/Decl.h"
20 #include "clang/AST/DeclCXX.h"
21 #include "clang/AST/DeclOpenMP.h"
22 #include "clang/AST/StmtCXX.h"
23 #include "clang/AST/StmtOpenMP.h"
24 #include "clang/AST/StmtVisitor.h"
25 #include "clang/AST/TypeOrdering.h"
26 #include "clang/Basic/OpenMPKinds.h"
27 #include "clang/Basic/TargetInfo.h"
28 #include "clang/Lex/Preprocessor.h"
29 #include "clang/Sema/Initialization.h"
30 #include "clang/Sema/Lookup.h"
31 #include "clang/Sema/Scope.h"
32 #include "clang/Sema/ScopeInfo.h"
33 #include "clang/Sema/SemaInternal.h"
34 using namespace clang;
35 
36 //===----------------------------------------------------------------------===//
37 // Stack of data-sharing attributes for variables
38 //===----------------------------------------------------------------------===//
39 
40 namespace {
41 /// \brief Default data sharing attributes, which can be applied to directive.
42 enum DefaultDataSharingAttributes {
43   DSA_unspecified = 0, /// \brief Data sharing attribute not specified.
44   DSA_none = 1 << 0,   /// \brief Default data sharing attribute 'none'.
45   DSA_shared = 1 << 1  /// \brief Default data sharing attribute 'shared'.
46 };
47 
48 template <class T> struct MatchesAny {
49   explicit MatchesAny(ArrayRef<T> Arr) : Arr(std::move(Arr)) {}
50   bool operator()(T Kind) {
51     for (auto KindEl : Arr)
52       if (KindEl == Kind)
53         return true;
54     return false;
55   }
56 
57 private:
58   ArrayRef<T> Arr;
59 };
60 struct MatchesAlways {
61   MatchesAlways() {}
62   template <class T> bool operator()(T) { return true; }
63 };
64 
65 typedef MatchesAny<OpenMPClauseKind> MatchesAnyClause;
66 typedef MatchesAny<OpenMPDirectiveKind> MatchesAnyDirective;
67 
68 /// \brief Stack for tracking declarations used in OpenMP directives and
69 /// clauses and their data-sharing attributes.
70 class DSAStackTy {
71 public:
72   struct DSAVarData {
73     OpenMPDirectiveKind DKind;
74     OpenMPClauseKind CKind;
75     Expr *RefExpr;
76     DeclRefExpr *PrivateCopy;
77     SourceLocation ImplicitDSALoc;
78     DSAVarData()
79         : DKind(OMPD_unknown), CKind(OMPC_unknown), RefExpr(nullptr),
80           PrivateCopy(nullptr), ImplicitDSALoc() {}
81   };
82 
83 private:
84   struct DSAInfo {
85     OpenMPClauseKind Attributes;
86     Expr *RefExpr;
87     DeclRefExpr *PrivateCopy;
88   };
89   typedef llvm::DenseMap<ValueDecl *, DSAInfo> DeclSAMapTy;
90   typedef llvm::DenseMap<ValueDecl *, Expr *> AlignedMapTy;
91   typedef std::pair<unsigned, VarDecl *> LCDeclInfo;
92   typedef llvm::DenseMap<ValueDecl *, LCDeclInfo> LoopControlVariablesMapTy;
93   typedef llvm::DenseMap<
94       ValueDecl *, OMPClauseMappableExprCommon::MappableExprComponentLists>
95       MappedExprComponentsTy;
96   typedef llvm::StringMap<std::pair<OMPCriticalDirective *, llvm::APSInt>>
97       CriticalsWithHintsTy;
98 
99   struct SharingMapTy {
100     DeclSAMapTy SharingMap;
101     AlignedMapTy AlignedMap;
102     MappedExprComponentsTy MappedExprComponents;
103     LoopControlVariablesMapTy LCVMap;
104     DefaultDataSharingAttributes DefaultAttr;
105     SourceLocation DefaultAttrLoc;
106     OpenMPDirectiveKind Directive;
107     DeclarationNameInfo DirectiveName;
108     Scope *CurScope;
109     SourceLocation ConstructLoc;
110     /// \brief first argument (Expr *) contains optional argument of the
111     /// 'ordered' clause, the second one is true if the regions has 'ordered'
112     /// clause, false otherwise.
113     llvm::PointerIntPair<Expr *, 1, bool> OrderedRegion;
114     bool NowaitRegion;
115     bool CancelRegion;
116     unsigned AssociatedLoops;
117     SourceLocation InnerTeamsRegionLoc;
118     SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
119                  Scope *CurScope, SourceLocation Loc)
120         : SharingMap(), AlignedMap(), LCVMap(), DefaultAttr(DSA_unspecified),
121           Directive(DKind), DirectiveName(std::move(Name)), CurScope(CurScope),
122           ConstructLoc(Loc), OrderedRegion(), NowaitRegion(false),
123           CancelRegion(false), AssociatedLoops(1), InnerTeamsRegionLoc() {}
124     SharingMapTy()
125         : SharingMap(), AlignedMap(), LCVMap(), DefaultAttr(DSA_unspecified),
126           Directive(OMPD_unknown), DirectiveName(), CurScope(nullptr),
127           ConstructLoc(), OrderedRegion(), NowaitRegion(false),
128           CancelRegion(false), AssociatedLoops(1), InnerTeamsRegionLoc() {}
129   };
130 
131   typedef SmallVector<SharingMapTy, 4> StackTy;
132 
133   /// \brief Stack of used declaration and their data-sharing attributes.
134   StackTy Stack;
135   /// \brief true, if check for DSA must be from parent directive, false, if
136   /// from current directive.
137   OpenMPClauseKind ClauseKindMode;
138   Sema &SemaRef;
139   bool ForceCapturing;
140   CriticalsWithHintsTy Criticals;
141 
142   typedef SmallVector<SharingMapTy, 8>::reverse_iterator reverse_iterator;
143 
144   DSAVarData getDSA(StackTy::reverse_iterator& Iter, ValueDecl *D);
145 
146   /// \brief Checks if the variable is a local for OpenMP region.
147   bool isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter);
148 
149 public:
150   explicit DSAStackTy(Sema &S)
151       : Stack(1), ClauseKindMode(OMPC_unknown), SemaRef(S),
152         ForceCapturing(false) {}
153 
154   bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
155   void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
156 
157   bool isForceVarCapturing() const { return ForceCapturing; }
158   void setForceVarCapturing(bool V) { ForceCapturing = V; }
159 
160   void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
161             Scope *CurScope, SourceLocation Loc) {
162     Stack.push_back(SharingMapTy(DKind, DirName, CurScope, Loc));
163     Stack.back().DefaultAttrLoc = Loc;
164   }
165 
166   void pop() {
167     assert(Stack.size() > 1 && "Data-sharing attributes stack is empty!");
168     Stack.pop_back();
169   }
170 
171   void addCriticalWithHint(OMPCriticalDirective *D, llvm::APSInt Hint) {
172     Criticals[D->getDirectiveName().getAsString()] = std::make_pair(D, Hint);
173   }
174   const std::pair<OMPCriticalDirective *, llvm::APSInt>
175   getCriticalWithHint(const DeclarationNameInfo &Name) const {
176     auto I = Criticals.find(Name.getAsString());
177     if (I != Criticals.end())
178       return I->second;
179     return std::make_pair(nullptr, llvm::APSInt());
180   }
181   /// \brief If 'aligned' declaration for given variable \a D was not seen yet,
182   /// add it and return NULL; otherwise return previous occurrence's expression
183   /// for diagnostics.
184   Expr *addUniqueAligned(ValueDecl *D, Expr *NewDE);
185 
186   /// \brief Register specified variable as loop control variable.
187   void addLoopControlVariable(ValueDecl *D, VarDecl *Capture);
188   /// \brief Check if the specified variable is a loop control variable for
189   /// current region.
190   /// \return The index of the loop control variable in the list of associated
191   /// for-loops (from outer to inner).
192   LCDeclInfo isLoopControlVariable(ValueDecl *D);
193   /// \brief Check if the specified variable is a loop control variable for
194   /// parent region.
195   /// \return The index of the loop control variable in the list of associated
196   /// for-loops (from outer to inner).
197   LCDeclInfo isParentLoopControlVariable(ValueDecl *D);
198   /// \brief Get the loop control variable for the I-th loop (or nullptr) in
199   /// parent directive.
200   ValueDecl *getParentLoopControlVariable(unsigned I);
201 
202   /// \brief Adds explicit data sharing attribute to the specified declaration.
203   void addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A,
204               DeclRefExpr *PrivateCopy = nullptr);
205 
206   /// \brief Returns data sharing attributes from top of the stack for the
207   /// specified declaration.
208   DSAVarData getTopDSA(ValueDecl *D, bool FromParent);
209   /// \brief Returns data-sharing attributes for the specified declaration.
210   DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent);
211   /// \brief Checks if the specified variables has data-sharing attributes which
212   /// match specified \a CPred predicate in any directive which matches \a DPred
213   /// predicate.
214   template <class ClausesPredicate, class DirectivesPredicate>
215   DSAVarData hasDSA(ValueDecl *D, ClausesPredicate CPred,
216                     DirectivesPredicate DPred, bool FromParent);
217   /// \brief Checks if the specified variables has data-sharing attributes which
218   /// match specified \a CPred predicate in any innermost directive which
219   /// matches \a DPred predicate.
220   template <class ClausesPredicate, class DirectivesPredicate>
221   DSAVarData hasInnermostDSA(ValueDecl *D, ClausesPredicate CPred,
222                              DirectivesPredicate DPred, bool FromParent);
223   /// \brief Checks if the specified variables has explicit data-sharing
224   /// attributes which match specified \a CPred predicate at the specified
225   /// OpenMP region.
226   bool hasExplicitDSA(ValueDecl *D,
227                       const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
228                       unsigned Level);
229 
230   /// \brief Returns true if the directive at level \Level matches in the
231   /// specified \a DPred predicate.
232   bool hasExplicitDirective(
233       const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
234       unsigned Level);
235 
236   /// \brief Finds a directive which matches specified \a DPred predicate.
237   template <class NamedDirectivesPredicate>
238   bool hasDirective(NamedDirectivesPredicate DPred, bool FromParent);
239 
240   /// \brief Returns currently analyzed directive.
241   OpenMPDirectiveKind getCurrentDirective() const {
242     return Stack.back().Directive;
243   }
244   /// \brief Returns parent directive.
245   OpenMPDirectiveKind getParentDirective() const {
246     if (Stack.size() > 2)
247       return Stack[Stack.size() - 2].Directive;
248     return OMPD_unknown;
249   }
250   /// \brief Return the directive associated with the provided scope.
251   OpenMPDirectiveKind getDirectiveForScope(const Scope *S) const;
252 
253   /// \brief Set default data sharing attribute to none.
254   void setDefaultDSANone(SourceLocation Loc) {
255     Stack.back().DefaultAttr = DSA_none;
256     Stack.back().DefaultAttrLoc = Loc;
257   }
258   /// \brief Set default data sharing attribute to shared.
259   void setDefaultDSAShared(SourceLocation Loc) {
260     Stack.back().DefaultAttr = DSA_shared;
261     Stack.back().DefaultAttrLoc = Loc;
262   }
263 
264   DefaultDataSharingAttributes getDefaultDSA() const {
265     return Stack.back().DefaultAttr;
266   }
267   SourceLocation getDefaultDSALocation() const {
268     return Stack.back().DefaultAttrLoc;
269   }
270 
271   /// \brief Checks if the specified variable is a threadprivate.
272   bool isThreadPrivate(VarDecl *D) {
273     DSAVarData DVar = getTopDSA(D, false);
274     return isOpenMPThreadPrivate(DVar.CKind);
275   }
276 
277   /// \brief Marks current region as ordered (it has an 'ordered' clause).
278   void setOrderedRegion(bool IsOrdered, Expr *Param) {
279     Stack.back().OrderedRegion.setInt(IsOrdered);
280     Stack.back().OrderedRegion.setPointer(Param);
281   }
282   /// \brief Returns true, if parent region is ordered (has associated
283   /// 'ordered' clause), false - otherwise.
284   bool isParentOrderedRegion() const {
285     if (Stack.size() > 2)
286       return Stack[Stack.size() - 2].OrderedRegion.getInt();
287     return false;
288   }
289   /// \brief Returns optional parameter for the ordered region.
290   Expr *getParentOrderedRegionParam() const {
291     if (Stack.size() > 2)
292       return Stack[Stack.size() - 2].OrderedRegion.getPointer();
293     return nullptr;
294   }
295   /// \brief Marks current region as nowait (it has a 'nowait' clause).
296   void setNowaitRegion(bool IsNowait = true) {
297     Stack.back().NowaitRegion = IsNowait;
298   }
299   /// \brief Returns true, if parent region is nowait (has associated
300   /// 'nowait' clause), false - otherwise.
301   bool isParentNowaitRegion() const {
302     if (Stack.size() > 2)
303       return Stack[Stack.size() - 2].NowaitRegion;
304     return false;
305   }
306   /// \brief Marks parent region as cancel region.
307   void setParentCancelRegion(bool Cancel = true) {
308     if (Stack.size() > 2)
309       Stack[Stack.size() - 2].CancelRegion =
310           Stack[Stack.size() - 2].CancelRegion || Cancel;
311   }
312   /// \brief Return true if current region has inner cancel construct.
313   bool isCancelRegion() const {
314     return Stack.back().CancelRegion;
315   }
316 
317   /// \brief Set collapse value for the region.
318   void setAssociatedLoops(unsigned Val) { Stack.back().AssociatedLoops = Val; }
319   /// \brief Return collapse value for region.
320   unsigned getAssociatedLoops() const { return Stack.back().AssociatedLoops; }
321 
322   /// \brief Marks current target region as one with closely nested teams
323   /// region.
324   void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
325     if (Stack.size() > 2)
326       Stack[Stack.size() - 2].InnerTeamsRegionLoc = TeamsRegionLoc;
327   }
328   /// \brief Returns true, if current region has closely nested teams region.
329   bool hasInnerTeamsRegion() const {
330     return getInnerTeamsRegionLoc().isValid();
331   }
332   /// \brief Returns location of the nested teams region (if any).
333   SourceLocation getInnerTeamsRegionLoc() const {
334     if (Stack.size() > 1)
335       return Stack.back().InnerTeamsRegionLoc;
336     return SourceLocation();
337   }
338 
339   Scope *getCurScope() const { return Stack.back().CurScope; }
340   Scope *getCurScope() { return Stack.back().CurScope; }
341   SourceLocation getConstructLoc() { return Stack.back().ConstructLoc; }
342 
343   // Do the check specified in \a Check to all component lists and return true
344   // if any issue is found.
345   bool checkMappableExprComponentListsForDecl(
346       ValueDecl *VD, bool CurrentRegionOnly,
347       const llvm::function_ref<bool(
348           OMPClauseMappableExprCommon::MappableExprComponentListRef)> &Check) {
349     auto SI = Stack.rbegin();
350     auto SE = Stack.rend();
351 
352     if (SI == SE)
353       return false;
354 
355     if (CurrentRegionOnly) {
356       SE = std::next(SI);
357     } else {
358       ++SI;
359     }
360 
361     for (; SI != SE; ++SI) {
362       auto MI = SI->MappedExprComponents.find(VD);
363       if (MI != SI->MappedExprComponents.end())
364         for (auto &L : MI->second)
365           if (Check(L))
366             return true;
367     }
368     return false;
369   }
370 
371   // Create a new mappable expression component list associated with a given
372   // declaration and initialize it with the provided list of components.
373   void addMappableExpressionComponents(
374       ValueDecl *VD,
375       OMPClauseMappableExprCommon::MappableExprComponentListRef Components) {
376     assert(Stack.size() > 1 &&
377            "Not expecting to retrieve components from a empty stack!");
378     auto &MEC = Stack.back().MappedExprComponents[VD];
379     // Create new entry and append the new components there.
380     MEC.resize(MEC.size() + 1);
381     MEC.back().append(Components.begin(), Components.end());
382   }
383 };
384 bool isParallelOrTaskRegion(OpenMPDirectiveKind DKind) {
385   return isOpenMPParallelDirective(DKind) || isOpenMPTaskingDirective(DKind) ||
386          isOpenMPTeamsDirective(DKind) || DKind == OMPD_unknown;
387 }
388 } // namespace
389 
390 static ValueDecl *getCanonicalDecl(ValueDecl *D) {
391   auto *VD = dyn_cast<VarDecl>(D);
392   auto *FD = dyn_cast<FieldDecl>(D);
393   if (VD  != nullptr) {
394     VD = VD->getCanonicalDecl();
395     D = VD;
396   } else {
397     assert(FD);
398     FD = FD->getCanonicalDecl();
399     D = FD;
400   }
401   return D;
402 }
403 
404 DSAStackTy::DSAVarData DSAStackTy::getDSA(StackTy::reverse_iterator& Iter,
405                                           ValueDecl *D) {
406   D = getCanonicalDecl(D);
407   auto *VD = dyn_cast<VarDecl>(D);
408   auto *FD = dyn_cast<FieldDecl>(D);
409   DSAVarData DVar;
410   if (Iter == std::prev(Stack.rend())) {
411     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
412     // in a region but not in construct]
413     //  File-scope or namespace-scope variables referenced in called routines
414     //  in the region are shared unless they appear in a threadprivate
415     //  directive.
416     if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(D))
417       DVar.CKind = OMPC_shared;
418 
419     // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
420     // in a region but not in construct]
421     //  Variables with static storage duration that are declared in called
422     //  routines in the region are shared.
423     if (VD && VD->hasGlobalStorage())
424       DVar.CKind = OMPC_shared;
425 
426     // Non-static data members are shared by default.
427     if (FD)
428       DVar.CKind = OMPC_shared;
429 
430     return DVar;
431   }
432 
433   DVar.DKind = Iter->Directive;
434   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
435   // in a Construct, C/C++, predetermined, p.1]
436   // Variables with automatic storage duration that are declared in a scope
437   // inside the construct are private.
438   if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() &&
439       (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) {
440     DVar.CKind = OMPC_private;
441     return DVar;
442   }
443 
444   // Explicitly specified attributes and local variables with predetermined
445   // attributes.
446   if (Iter->SharingMap.count(D)) {
447     DVar.RefExpr = Iter->SharingMap[D].RefExpr;
448     DVar.PrivateCopy = Iter->SharingMap[D].PrivateCopy;
449     DVar.CKind = Iter->SharingMap[D].Attributes;
450     DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
451     return DVar;
452   }
453 
454   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
455   // in a Construct, C/C++, implicitly determined, p.1]
456   //  In a parallel or task construct, the data-sharing attributes of these
457   //  variables are determined by the default clause, if present.
458   switch (Iter->DefaultAttr) {
459   case DSA_shared:
460     DVar.CKind = OMPC_shared;
461     DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
462     return DVar;
463   case DSA_none:
464     return DVar;
465   case DSA_unspecified:
466     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
467     // in a Construct, implicitly determined, p.2]
468     //  In a parallel construct, if no default clause is present, these
469     //  variables are shared.
470     DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
471     if (isOpenMPParallelDirective(DVar.DKind) ||
472         isOpenMPTeamsDirective(DVar.DKind)) {
473       DVar.CKind = OMPC_shared;
474       return DVar;
475     }
476 
477     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
478     // in a Construct, implicitly determined, p.4]
479     //  In a task construct, if no default clause is present, a variable that in
480     //  the enclosing context is determined to be shared by all implicit tasks
481     //  bound to the current team is shared.
482     if (isOpenMPTaskingDirective(DVar.DKind)) {
483       DSAVarData DVarTemp;
484       for (StackTy::reverse_iterator I = std::next(Iter), EE = Stack.rend();
485            I != EE; ++I) {
486         // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
487         // Referenced in a Construct, implicitly determined, p.6]
488         //  In a task construct, if no default clause is present, a variable
489         //  whose data-sharing attribute is not determined by the rules above is
490         //  firstprivate.
491         DVarTemp = getDSA(I, D);
492         if (DVarTemp.CKind != OMPC_shared) {
493           DVar.RefExpr = nullptr;
494           DVar.CKind = OMPC_firstprivate;
495           return DVar;
496         }
497         if (isParallelOrTaskRegion(I->Directive))
498           break;
499       }
500       DVar.CKind =
501           (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
502       return DVar;
503     }
504   }
505   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
506   // in a Construct, implicitly determined, p.3]
507   //  For constructs other than task, if no default clause is present, these
508   //  variables inherit their data-sharing attributes from the enclosing
509   //  context.
510   return getDSA(++Iter, D);
511 }
512 
513 Expr *DSAStackTy::addUniqueAligned(ValueDecl *D, Expr *NewDE) {
514   assert(Stack.size() > 1 && "Data sharing attributes stack is empty");
515   D = getCanonicalDecl(D);
516   auto It = Stack.back().AlignedMap.find(D);
517   if (It == Stack.back().AlignedMap.end()) {
518     assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
519     Stack.back().AlignedMap[D] = NewDE;
520     return nullptr;
521   } else {
522     assert(It->second && "Unexpected nullptr expr in the aligned map");
523     return It->second;
524   }
525   return nullptr;
526 }
527 
528 void DSAStackTy::addLoopControlVariable(ValueDecl *D, VarDecl *Capture) {
529   assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
530   D = getCanonicalDecl(D);
531   Stack.back().LCVMap.insert(
532       std::make_pair(D, LCDeclInfo(Stack.back().LCVMap.size() + 1, Capture)));
533 }
534 
535 DSAStackTy::LCDeclInfo DSAStackTy::isLoopControlVariable(ValueDecl *D) {
536   assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
537   D = getCanonicalDecl(D);
538   return Stack.back().LCVMap.count(D) > 0 ? Stack.back().LCVMap[D]
539                                           : LCDeclInfo(0, nullptr);
540 }
541 
542 DSAStackTy::LCDeclInfo DSAStackTy::isParentLoopControlVariable(ValueDecl *D) {
543   assert(Stack.size() > 2 && "Data-sharing attributes stack is empty");
544   D = getCanonicalDecl(D);
545   return Stack[Stack.size() - 2].LCVMap.count(D) > 0
546              ? Stack[Stack.size() - 2].LCVMap[D]
547              : LCDeclInfo(0, nullptr);
548 }
549 
550 ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) {
551   assert(Stack.size() > 2 && "Data-sharing attributes stack is empty");
552   if (Stack[Stack.size() - 2].LCVMap.size() < I)
553     return nullptr;
554   for (auto &Pair : Stack[Stack.size() - 2].LCVMap) {
555     if (Pair.second.first == I)
556       return Pair.first;
557   }
558   return nullptr;
559 }
560 
561 void DSAStackTy::addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A,
562                         DeclRefExpr *PrivateCopy) {
563   D = getCanonicalDecl(D);
564   if (A == OMPC_threadprivate) {
565     Stack[0].SharingMap[D].Attributes = A;
566     Stack[0].SharingMap[D].RefExpr = E;
567     Stack[0].SharingMap[D].PrivateCopy = nullptr;
568   } else {
569     assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
570     Stack.back().SharingMap[D].Attributes = A;
571     Stack.back().SharingMap[D].RefExpr = E;
572     Stack.back().SharingMap[D].PrivateCopy = PrivateCopy;
573     if (PrivateCopy)
574       addDSA(PrivateCopy->getDecl(), PrivateCopy, A);
575   }
576 }
577 
578 bool DSAStackTy::isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter) {
579   D = D->getCanonicalDecl();
580   if (Stack.size() > 2) {
581     reverse_iterator I = Iter, E = std::prev(Stack.rend());
582     Scope *TopScope = nullptr;
583     while (I != E && !isParallelOrTaskRegion(I->Directive)) {
584       ++I;
585     }
586     if (I == E)
587       return false;
588     TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
589     Scope *CurScope = getCurScope();
590     while (CurScope != TopScope && !CurScope->isDeclScope(D)) {
591       CurScope = CurScope->getParent();
592     }
593     return CurScope != TopScope;
594   }
595   return false;
596 }
597 
598 /// \brief Build a variable declaration for OpenMP loop iteration variable.
599 static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
600                              StringRef Name, const AttrVec *Attrs = nullptr) {
601   DeclContext *DC = SemaRef.CurContext;
602   IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
603   TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
604   VarDecl *Decl =
605       VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
606   if (Attrs) {
607     for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
608          I != E; ++I)
609       Decl->addAttr(*I);
610   }
611   Decl->setImplicit();
612   return Decl;
613 }
614 
615 static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
616                                      SourceLocation Loc,
617                                      bool RefersToCapture = false) {
618   D->setReferenced();
619   D->markUsed(S.Context);
620   return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
621                              SourceLocation(), D, RefersToCapture, Loc, Ty,
622                              VK_LValue);
623 }
624 
625 DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D, bool FromParent) {
626   D = getCanonicalDecl(D);
627   DSAVarData DVar;
628 
629   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
630   // in a Construct, C/C++, predetermined, p.1]
631   //  Variables appearing in threadprivate directives are threadprivate.
632   auto *VD = dyn_cast<VarDecl>(D);
633   if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
634        !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
635          SemaRef.getLangOpts().OpenMPUseTLS &&
636          SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
637       (VD && VD->getStorageClass() == SC_Register &&
638        VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
639     addDSA(D, buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
640                                D->getLocation()),
641            OMPC_threadprivate);
642   }
643   if (Stack[0].SharingMap.count(D)) {
644     DVar.RefExpr = Stack[0].SharingMap[D].RefExpr;
645     DVar.CKind = OMPC_threadprivate;
646     return DVar;
647   }
648 
649   if (Stack.size() == 1) {
650     // Not in OpenMP execution region and top scope was already checked.
651     return DVar;
652   }
653 
654   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
655   // in a Construct, C/C++, predetermined, p.4]
656   //  Static data members are shared.
657   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
658   // in a Construct, C/C++, predetermined, p.7]
659   //  Variables with static storage duration that are declared in a scope
660   //  inside the construct are shared.
661   if (VD && VD->isStaticDataMember()) {
662     DSAVarData DVarTemp =
663         hasDSA(D, isOpenMPPrivate, MatchesAlways(), FromParent);
664     if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
665       return DVar;
666 
667     DVar.CKind = OMPC_shared;
668     return DVar;
669   }
670 
671   QualType Type = D->getType().getNonReferenceType().getCanonicalType();
672   bool IsConstant = Type.isConstant(SemaRef.getASTContext());
673   Type = SemaRef.getASTContext().getBaseElementType(Type);
674   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
675   // in a Construct, C/C++, predetermined, p.6]
676   //  Variables with const qualified type having no mutable member are
677   //  shared.
678   CXXRecordDecl *RD =
679       SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
680   if (auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
681     if (auto *CTD = CTSD->getSpecializedTemplate())
682       RD = CTD->getTemplatedDecl();
683   if (IsConstant &&
684       !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasDefinition() &&
685         RD->hasMutableFields())) {
686     // Variables with const-qualified type having no mutable member may be
687     // listed in a firstprivate clause, even if they are static data members.
688     DSAVarData DVarTemp = hasDSA(D, MatchesAnyClause(OMPC_firstprivate),
689                                  MatchesAlways(), FromParent);
690     if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr)
691       return DVar;
692 
693     DVar.CKind = OMPC_shared;
694     return DVar;
695   }
696 
697   // Explicitly specified attributes and local variables with predetermined
698   // attributes.
699   auto StartI = std::next(Stack.rbegin());
700   auto EndI = std::prev(Stack.rend());
701   if (FromParent && StartI != EndI) {
702     StartI = std::next(StartI);
703   }
704   auto I = std::prev(StartI);
705   if (I->SharingMap.count(D)) {
706     DVar.RefExpr = I->SharingMap[D].RefExpr;
707     DVar.PrivateCopy = I->SharingMap[D].PrivateCopy;
708     DVar.CKind = I->SharingMap[D].Attributes;
709     DVar.ImplicitDSALoc = I->DefaultAttrLoc;
710   }
711 
712   return DVar;
713 }
714 
715 DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
716                                                   bool FromParent) {
717   D = getCanonicalDecl(D);
718   auto StartI = Stack.rbegin();
719   auto EndI = std::prev(Stack.rend());
720   if (FromParent && StartI != EndI) {
721     StartI = std::next(StartI);
722   }
723   return getDSA(StartI, D);
724 }
725 
726 template <class ClausesPredicate, class DirectivesPredicate>
727 DSAStackTy::DSAVarData DSAStackTy::hasDSA(ValueDecl *D, ClausesPredicate CPred,
728                                           DirectivesPredicate DPred,
729                                           bool FromParent) {
730   D = getCanonicalDecl(D);
731   auto StartI = std::next(Stack.rbegin());
732   auto EndI = Stack.rend();
733   if (FromParent && StartI != EndI) {
734     StartI = std::next(StartI);
735   }
736   for (auto I = StartI, EE = EndI; I != EE; ++I) {
737     if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive))
738       continue;
739     DSAVarData DVar = getDSA(I, D);
740     if (CPred(DVar.CKind))
741       return DVar;
742   }
743   return DSAVarData();
744 }
745 
746 template <class ClausesPredicate, class DirectivesPredicate>
747 DSAStackTy::DSAVarData
748 DSAStackTy::hasInnermostDSA(ValueDecl *D, ClausesPredicate CPred,
749                             DirectivesPredicate DPred, bool FromParent) {
750   D = getCanonicalDecl(D);
751   auto StartI = std::next(Stack.rbegin());
752   auto EndI = Stack.rend();
753   if (FromParent && StartI != EndI) {
754     StartI = std::next(StartI);
755   }
756   for (auto I = StartI, EE = EndI; I != EE; ++I) {
757     if (!DPred(I->Directive))
758       break;
759     DSAVarData DVar = getDSA(I, D);
760     if (CPred(DVar.CKind))
761       return DVar;
762     return DSAVarData();
763   }
764   return DSAVarData();
765 }
766 
767 bool DSAStackTy::hasExplicitDSA(
768     ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
769     unsigned Level) {
770   if (CPred(ClauseKindMode))
771     return true;
772   if (isClauseParsingMode())
773     ++Level;
774   D = getCanonicalDecl(D);
775   auto StartI = Stack.rbegin();
776   auto EndI = std::prev(Stack.rend());
777   if (std::distance(StartI, EndI) <= (int)Level)
778     return false;
779   std::advance(StartI, Level);
780   return (StartI->SharingMap.count(D) > 0) && StartI->SharingMap[D].RefExpr &&
781          CPred(StartI->SharingMap[D].Attributes);
782 }
783 
784 bool DSAStackTy::hasExplicitDirective(
785     const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
786     unsigned Level) {
787   if (isClauseParsingMode())
788     ++Level;
789   auto StartI = Stack.rbegin();
790   auto EndI = std::prev(Stack.rend());
791   if (std::distance(StartI, EndI) <= (int)Level)
792     return false;
793   std::advance(StartI, Level);
794   return DPred(StartI->Directive);
795 }
796 
797 template <class NamedDirectivesPredicate>
798 bool DSAStackTy::hasDirective(NamedDirectivesPredicate DPred, bool FromParent) {
799   auto StartI = std::next(Stack.rbegin());
800   auto EndI = std::prev(Stack.rend());
801   if (FromParent && StartI != EndI) {
802     StartI = std::next(StartI);
803   }
804   for (auto I = StartI, EE = EndI; I != EE; ++I) {
805     if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
806       return true;
807   }
808   return false;
809 }
810 
811 OpenMPDirectiveKind DSAStackTy::getDirectiveForScope(const Scope *S) const {
812   for (auto I = Stack.rbegin(), EE = Stack.rend(); I != EE; ++I)
813     if (I->CurScope == S)
814       return I->Directive;
815   return OMPD_unknown;
816 }
817 
818 void Sema::InitDataSharingAttributesStack() {
819   VarDataSharingAttributesStack = new DSAStackTy(*this);
820 }
821 
822 #define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
823 
824 bool Sema::IsOpenMPCapturedByRef(ValueDecl *D,
825                                  const CapturedRegionScopeInfo *RSI) {
826   assert(LangOpts.OpenMP && "OpenMP is not allowed");
827 
828   auto &Ctx = getASTContext();
829   bool IsByRef = true;
830 
831   // Find the directive that is associated with the provided scope.
832   auto DKind = DSAStack->getDirectiveForScope(RSI->TheScope);
833   auto Ty = D->getType();
834 
835   if (isOpenMPTargetExecutionDirective(DKind)) {
836     // This table summarizes how a given variable should be passed to the device
837     // given its type and the clauses where it appears. This table is based on
838     // the description in OpenMP 4.5 [2.10.4, target Construct] and
839     // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
840     //
841     // =========================================================================
842     // | type |  defaultmap   | pvt | first | is_device_ptr |    map   | res.  |
843     // |      |(tofrom:scalar)|     |  pvt  |               |          |       |
844     // =========================================================================
845     // | scl  |               |     |       |       -       |          | bycopy|
846     // | scl  |               |  -  |   x   |       -       |     -    | bycopy|
847     // | scl  |               |  x  |   -   |       -       |     -    | null  |
848     // | scl  |       x       |     |       |       -       |          | byref |
849     // | scl  |       x       |  -  |   x   |       -       |     -    | bycopy|
850     // | scl  |       x       |  x  |   -   |       -       |     -    | null  |
851     // | scl  |               |  -  |   -   |       -       |     x    | byref |
852     // | scl  |       x       |  -  |   -   |       -       |     x    | byref |
853     //
854     // | agg  |      n.a.     |     |       |       -       |          | byref |
855     // | agg  |      n.a.     |  -  |   x   |       -       |     -    | byref |
856     // | agg  |      n.a.     |  x  |   -   |       -       |     -    | null  |
857     // | agg  |      n.a.     |  -  |   -   |       -       |     x    | byref |
858     // | agg  |      n.a.     |  -  |   -   |       -       |    x[]   | byref |
859     //
860     // | ptr  |      n.a.     |     |       |       -       |          | bycopy|
861     // | ptr  |      n.a.     |  -  |   x   |       -       |     -    | bycopy|
862     // | ptr  |      n.a.     |  x  |   -   |       -       |     -    | null  |
863     // | ptr  |      n.a.     |  -  |   -   |       -       |     x    | byref |
864     // | ptr  |      n.a.     |  -  |   -   |       -       |    x[]   | bycopy|
865     // | ptr  |      n.a.     |  -  |   -   |       x       |          | bycopy|
866     // | ptr  |      n.a.     |  -  |   -   |       x       |     x    | bycopy|
867     // | ptr  |      n.a.     |  -  |   -   |       x       |    x[]   | bycopy|
868     // =========================================================================
869     // Legend:
870     //  scl - scalar
871     //  ptr - pointer
872     //  agg - aggregate
873     //  x - applies
874     //  - - invalid in this combination
875     //  [] - mapped with an array section
876     //  byref - should be mapped by reference
877     //  byval - should be mapped by value
878     //  null - initialize a local variable to null on the device
879     //
880     // Observations:
881     //  - All scalar declarations that show up in a map clause have to be passed
882     //    by reference, because they may have been mapped in the enclosing data
883     //    environment.
884     //  - If the scalar value does not fit the size of uintptr, it has to be
885     //    passed by reference, regardless the result in the table above.
886     //  - For pointers mapped by value that have either an implicit map or an
887     //    array section, the runtime library may pass the NULL value to the
888     //    device instead of the value passed to it by the compiler.
889 
890 
891     if (Ty->isReferenceType())
892       Ty = Ty->castAs<ReferenceType>()->getPointeeType();
893 
894     // Locate map clauses and see if the variable being captured is referred to
895     // in any of those clauses. Here we only care about variables, not fields,
896     // because fields are part of aggregates.
897     bool IsVariableUsedInMapClause = false;
898     bool IsVariableAssociatedWithSection = false;
899 
900     DSAStack->checkMappableExprComponentListsForDecl(
901         D, /*CurrentRegionOnly=*/true,
902         [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
903                 MapExprComponents) {
904 
905           auto EI = MapExprComponents.rbegin();
906           auto EE = MapExprComponents.rend();
907 
908           assert(EI != EE && "Invalid map expression!");
909 
910           if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
911             IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
912 
913           ++EI;
914           if (EI == EE)
915             return false;
916 
917           if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
918               isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
919               isa<MemberExpr>(EI->getAssociatedExpression())) {
920             IsVariableAssociatedWithSection = true;
921             // There is nothing more we need to know about this variable.
922             return true;
923           }
924 
925           // Keep looking for more map info.
926           return false;
927         });
928 
929     if (IsVariableUsedInMapClause) {
930       // If variable is identified in a map clause it is always captured by
931       // reference except if it is a pointer that is dereferenced somehow.
932       IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
933     } else {
934       // By default, all the data that has a scalar type is mapped by copy.
935       IsByRef = !Ty->isScalarType();
936     }
937   }
938 
939   // When passing data by copy, we need to make sure it fits the uintptr size
940   // and alignment, because the runtime library only deals with uintptr types.
941   // If it does not fit the uintptr size, we need to pass the data by reference
942   // instead.
943   if (!IsByRef &&
944       (Ctx.getTypeSizeInChars(Ty) >
945            Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
946        Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType())))
947     IsByRef = true;
948 
949   return IsByRef;
950 }
951 
952 VarDecl *Sema::IsOpenMPCapturedDecl(ValueDecl *D) {
953   assert(LangOpts.OpenMP && "OpenMP is not allowed");
954   D = getCanonicalDecl(D);
955 
956   // If we are attempting to capture a global variable in a directive with
957   // 'target' we return true so that this global is also mapped to the device.
958   //
959   // FIXME: If the declaration is enclosed in a 'declare target' directive,
960   // then it should not be captured. Therefore, an extra check has to be
961   // inserted here once support for 'declare target' is added.
962   //
963   auto *VD = dyn_cast<VarDecl>(D);
964   if (VD && !VD->hasLocalStorage()) {
965     if (DSAStack->getCurrentDirective() == OMPD_target &&
966         !DSAStack->isClauseParsingMode())
967       return VD;
968     if (DSAStack->getCurScope() &&
969         DSAStack->hasDirective(
970             [](OpenMPDirectiveKind K, const DeclarationNameInfo &DNI,
971                SourceLocation Loc) -> bool {
972               return isOpenMPTargetExecutionDirective(K);
973             },
974             false))
975       return VD;
976   }
977 
978   if (DSAStack->getCurrentDirective() != OMPD_unknown &&
979       (!DSAStack->isClauseParsingMode() ||
980        DSAStack->getParentDirective() != OMPD_unknown)) {
981     auto &&Info = DSAStack->isLoopControlVariable(D);
982     if (Info.first ||
983         (VD && VD->hasLocalStorage() &&
984          isParallelOrTaskRegion(DSAStack->getCurrentDirective())) ||
985         (VD && DSAStack->isForceVarCapturing()))
986       return VD ? VD : Info.second;
987     auto DVarPrivate = DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
988     if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
989       return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
990     DVarPrivate = DSAStack->hasDSA(D, isOpenMPPrivate, MatchesAlways(),
991                                    DSAStack->isClauseParsingMode());
992     if (DVarPrivate.CKind != OMPC_unknown)
993       return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
994   }
995   return nullptr;
996 }
997 
998 bool Sema::isOpenMPPrivateDecl(ValueDecl *D, unsigned Level) {
999   assert(LangOpts.OpenMP && "OpenMP is not allowed");
1000   return DSAStack->hasExplicitDSA(
1001       D, [](OpenMPClauseKind K) -> bool { return K == OMPC_private; }, Level);
1002 }
1003 
1004 bool Sema::isOpenMPTargetCapturedDecl(ValueDecl *D, unsigned Level) {
1005   assert(LangOpts.OpenMP && "OpenMP is not allowed");
1006   // Return true if the current level is no longer enclosed in a target region.
1007 
1008   auto *VD = dyn_cast<VarDecl>(D);
1009   return VD && !VD->hasLocalStorage() &&
1010          DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
1011                                         Level);
1012 }
1013 
1014 void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
1015 
1016 void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
1017                                const DeclarationNameInfo &DirName,
1018                                Scope *CurScope, SourceLocation Loc) {
1019   DSAStack->push(DKind, DirName, CurScope, Loc);
1020   PushExpressionEvaluationContext(PotentiallyEvaluated);
1021 }
1022 
1023 void Sema::StartOpenMPClause(OpenMPClauseKind K) {
1024   DSAStack->setClauseParsingMode(K);
1025 }
1026 
1027 void Sema::EndOpenMPClause() {
1028   DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
1029 }
1030 
1031 void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
1032   // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
1033   //  A variable of class type (or array thereof) that appears in a lastprivate
1034   //  clause requires an accessible, unambiguous default constructor for the
1035   //  class type, unless the list item is also specified in a firstprivate
1036   //  clause.
1037   if (auto D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
1038     for (auto *C : D->clauses()) {
1039       if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
1040         SmallVector<Expr *, 8> PrivateCopies;
1041         for (auto *DE : Clause->varlists()) {
1042           if (DE->isValueDependent() || DE->isTypeDependent()) {
1043             PrivateCopies.push_back(nullptr);
1044             continue;
1045           }
1046           auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
1047           VarDecl *VD = cast<VarDecl>(DRE->getDecl());
1048           QualType Type = VD->getType().getNonReferenceType();
1049           auto DVar = DSAStack->getTopDSA(VD, false);
1050           if (DVar.CKind == OMPC_lastprivate) {
1051             // Generate helper private variable and initialize it with the
1052             // default value. The address of the original variable is replaced
1053             // by the address of the new private variable in CodeGen. This new
1054             // variable is not added to IdResolver, so the code in the OpenMP
1055             // region uses original variable for proper diagnostics.
1056             auto *VDPrivate = buildVarDecl(
1057                 *this, DE->getExprLoc(), Type.getUnqualifiedType(),
1058                 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr);
1059             ActOnUninitializedDecl(VDPrivate, /*TypeMayContainAuto=*/false);
1060             if (VDPrivate->isInvalidDecl())
1061               continue;
1062             PrivateCopies.push_back(buildDeclRefExpr(
1063                 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
1064           } else {
1065             // The variable is also a firstprivate, so initialization sequence
1066             // for private copy is generated already.
1067             PrivateCopies.push_back(nullptr);
1068           }
1069         }
1070         // Set initializers to private copies if no errors were found.
1071         if (PrivateCopies.size() == Clause->varlist_size())
1072           Clause->setPrivateCopies(PrivateCopies);
1073       }
1074     }
1075   }
1076 
1077   DSAStack->pop();
1078   DiscardCleanupsInEvaluationContext();
1079   PopExpressionEvaluationContext();
1080 }
1081 
1082 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
1083                                      Expr *NumIterations, Sema &SemaRef,
1084                                      Scope *S, DSAStackTy *Stack);
1085 
1086 namespace {
1087 
1088 class VarDeclFilterCCC : public CorrectionCandidateCallback {
1089 private:
1090   Sema &SemaRef;
1091 
1092 public:
1093   explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
1094   bool ValidateCandidate(const TypoCorrection &Candidate) override {
1095     NamedDecl *ND = Candidate.getCorrectionDecl();
1096     if (VarDecl *VD = dyn_cast_or_null<VarDecl>(ND)) {
1097       return VD->hasGlobalStorage() &&
1098              SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1099                                    SemaRef.getCurScope());
1100     }
1101     return false;
1102   }
1103 };
1104 
1105 class VarOrFuncDeclFilterCCC : public CorrectionCandidateCallback {
1106 private:
1107   Sema &SemaRef;
1108 
1109 public:
1110   explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
1111   bool ValidateCandidate(const TypoCorrection &Candidate) override {
1112     NamedDecl *ND = Candidate.getCorrectionDecl();
1113     if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) {
1114       return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1115                                    SemaRef.getCurScope());
1116     }
1117     return false;
1118   }
1119 };
1120 
1121 } // namespace
1122 
1123 ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
1124                                          CXXScopeSpec &ScopeSpec,
1125                                          const DeclarationNameInfo &Id) {
1126   LookupResult Lookup(*this, Id, LookupOrdinaryName);
1127   LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
1128 
1129   if (Lookup.isAmbiguous())
1130     return ExprError();
1131 
1132   VarDecl *VD;
1133   if (!Lookup.isSingleResult()) {
1134     if (TypoCorrection Corrected = CorrectTypo(
1135             Id, LookupOrdinaryName, CurScope, nullptr,
1136             llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) {
1137       diagnoseTypo(Corrected,
1138                    PDiag(Lookup.empty()
1139                              ? diag::err_undeclared_var_use_suggest
1140                              : diag::err_omp_expected_var_arg_suggest)
1141                        << Id.getName());
1142       VD = Corrected.getCorrectionDeclAs<VarDecl>();
1143     } else {
1144       Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
1145                                        : diag::err_omp_expected_var_arg)
1146           << Id.getName();
1147       return ExprError();
1148     }
1149   } else {
1150     if (!(VD = Lookup.getAsSingle<VarDecl>())) {
1151       Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
1152       Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
1153       return ExprError();
1154     }
1155   }
1156   Lookup.suppressDiagnostics();
1157 
1158   // OpenMP [2.9.2, Syntax, C/C++]
1159   //   Variables must be file-scope, namespace-scope, or static block-scope.
1160   if (!VD->hasGlobalStorage()) {
1161     Diag(Id.getLoc(), diag::err_omp_global_var_arg)
1162         << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal();
1163     bool IsDecl =
1164         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1165     Diag(VD->getLocation(),
1166          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1167         << VD;
1168     return ExprError();
1169   }
1170 
1171   VarDecl *CanonicalVD = VD->getCanonicalDecl();
1172   NamedDecl *ND = cast<NamedDecl>(CanonicalVD);
1173   // OpenMP [2.9.2, Restrictions, C/C++, p.2]
1174   //   A threadprivate directive for file-scope variables must appear outside
1175   //   any definition or declaration.
1176   if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
1177       !getCurLexicalContext()->isTranslationUnit()) {
1178     Diag(Id.getLoc(), diag::err_omp_var_scope)
1179         << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1180     bool IsDecl =
1181         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1182     Diag(VD->getLocation(),
1183          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1184         << VD;
1185     return ExprError();
1186   }
1187   // OpenMP [2.9.2, Restrictions, C/C++, p.3]
1188   //   A threadprivate directive for static class member variables must appear
1189   //   in the class definition, in the same scope in which the member
1190   //   variables are declared.
1191   if (CanonicalVD->isStaticDataMember() &&
1192       !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
1193     Diag(Id.getLoc(), diag::err_omp_var_scope)
1194         << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1195     bool IsDecl =
1196         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1197     Diag(VD->getLocation(),
1198          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1199         << VD;
1200     return ExprError();
1201   }
1202   // OpenMP [2.9.2, Restrictions, C/C++, p.4]
1203   //   A threadprivate directive for namespace-scope variables must appear
1204   //   outside any definition or declaration other than the namespace
1205   //   definition itself.
1206   if (CanonicalVD->getDeclContext()->isNamespace() &&
1207       (!getCurLexicalContext()->isFileContext() ||
1208        !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
1209     Diag(Id.getLoc(), diag::err_omp_var_scope)
1210         << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1211     bool IsDecl =
1212         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1213     Diag(VD->getLocation(),
1214          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1215         << VD;
1216     return ExprError();
1217   }
1218   // OpenMP [2.9.2, Restrictions, C/C++, p.6]
1219   //   A threadprivate directive for static block-scope variables must appear
1220   //   in the scope of the variable and not in a nested scope.
1221   if (CanonicalVD->isStaticLocal() && CurScope &&
1222       !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
1223     Diag(Id.getLoc(), diag::err_omp_var_scope)
1224         << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1225     bool IsDecl =
1226         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1227     Diag(VD->getLocation(),
1228          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1229         << VD;
1230     return ExprError();
1231   }
1232 
1233   // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
1234   //   A threadprivate directive must lexically precede all references to any
1235   //   of the variables in its list.
1236   if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) {
1237     Diag(Id.getLoc(), diag::err_omp_var_used)
1238         << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1239     return ExprError();
1240   }
1241 
1242   QualType ExprType = VD->getType().getNonReferenceType();
1243   return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
1244                              SourceLocation(), VD,
1245                              /*RefersToEnclosingVariableOrCapture=*/false,
1246                              Id.getLoc(), ExprType, VK_LValue);
1247 }
1248 
1249 Sema::DeclGroupPtrTy
1250 Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
1251                                         ArrayRef<Expr *> VarList) {
1252   if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
1253     CurContext->addDecl(D);
1254     return DeclGroupPtrTy::make(DeclGroupRef(D));
1255   }
1256   return nullptr;
1257 }
1258 
1259 namespace {
1260 class LocalVarRefChecker : public ConstStmtVisitor<LocalVarRefChecker, bool> {
1261   Sema &SemaRef;
1262 
1263 public:
1264   bool VisitDeclRefExpr(const DeclRefExpr *E) {
1265     if (auto VD = dyn_cast<VarDecl>(E->getDecl())) {
1266       if (VD->hasLocalStorage()) {
1267         SemaRef.Diag(E->getLocStart(),
1268                      diag::err_omp_local_var_in_threadprivate_init)
1269             << E->getSourceRange();
1270         SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
1271             << VD << VD->getSourceRange();
1272         return true;
1273       }
1274     }
1275     return false;
1276   }
1277   bool VisitStmt(const Stmt *S) {
1278     for (auto Child : S->children()) {
1279       if (Child && Visit(Child))
1280         return true;
1281     }
1282     return false;
1283   }
1284   explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
1285 };
1286 } // namespace
1287 
1288 OMPThreadPrivateDecl *
1289 Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
1290   SmallVector<Expr *, 8> Vars;
1291   for (auto &RefExpr : VarList) {
1292     DeclRefExpr *DE = cast<DeclRefExpr>(RefExpr);
1293     VarDecl *VD = cast<VarDecl>(DE->getDecl());
1294     SourceLocation ILoc = DE->getExprLoc();
1295 
1296     // Mark variable as used.
1297     VD->setReferenced();
1298     VD->markUsed(Context);
1299 
1300     QualType QType = VD->getType();
1301     if (QType->isDependentType() || QType->isInstantiationDependentType()) {
1302       // It will be analyzed later.
1303       Vars.push_back(DE);
1304       continue;
1305     }
1306 
1307     // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1308     //   A threadprivate variable must not have an incomplete type.
1309     if (RequireCompleteType(ILoc, VD->getType(),
1310                             diag::err_omp_threadprivate_incomplete_type)) {
1311       continue;
1312     }
1313 
1314     // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1315     //   A threadprivate variable must not have a reference type.
1316     if (VD->getType()->isReferenceType()) {
1317       Diag(ILoc, diag::err_omp_ref_type_arg)
1318           << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
1319       bool IsDecl =
1320           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1321       Diag(VD->getLocation(),
1322            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1323           << VD;
1324       continue;
1325     }
1326 
1327     // Check if this is a TLS variable. If TLS is not being supported, produce
1328     // the corresponding diagnostic.
1329     if ((VD->getTLSKind() != VarDecl::TLS_None &&
1330          !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
1331            getLangOpts().OpenMPUseTLS &&
1332            getASTContext().getTargetInfo().isTLSSupported())) ||
1333         (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
1334          !VD->isLocalVarDecl())) {
1335       Diag(ILoc, diag::err_omp_var_thread_local)
1336           << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
1337       bool IsDecl =
1338           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1339       Diag(VD->getLocation(),
1340            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1341           << VD;
1342       continue;
1343     }
1344 
1345     // Check if initial value of threadprivate variable reference variable with
1346     // local storage (it is not supported by runtime).
1347     if (auto Init = VD->getAnyInitializer()) {
1348       LocalVarRefChecker Checker(*this);
1349       if (Checker.Visit(Init))
1350         continue;
1351     }
1352 
1353     Vars.push_back(RefExpr);
1354     DSAStack->addDSA(VD, DE, OMPC_threadprivate);
1355     VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
1356         Context, SourceRange(Loc, Loc)));
1357     if (auto *ML = Context.getASTMutationListener())
1358       ML->DeclarationMarkedOpenMPThreadPrivate(VD);
1359   }
1360   OMPThreadPrivateDecl *D = nullptr;
1361   if (!Vars.empty()) {
1362     D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
1363                                      Vars);
1364     D->setAccess(AS_public);
1365   }
1366   return D;
1367 }
1368 
1369 static void ReportOriginalDSA(Sema &SemaRef, DSAStackTy *Stack,
1370                               const ValueDecl *D, DSAStackTy::DSAVarData DVar,
1371                               bool IsLoopIterVar = false) {
1372   if (DVar.RefExpr) {
1373     SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
1374         << getOpenMPClauseName(DVar.CKind);
1375     return;
1376   }
1377   enum {
1378     PDSA_StaticMemberShared,
1379     PDSA_StaticLocalVarShared,
1380     PDSA_LoopIterVarPrivate,
1381     PDSA_LoopIterVarLinear,
1382     PDSA_LoopIterVarLastprivate,
1383     PDSA_ConstVarShared,
1384     PDSA_GlobalVarShared,
1385     PDSA_TaskVarFirstprivate,
1386     PDSA_LocalVarPrivate,
1387     PDSA_Implicit
1388   } Reason = PDSA_Implicit;
1389   bool ReportHint = false;
1390   auto ReportLoc = D->getLocation();
1391   auto *VD = dyn_cast<VarDecl>(D);
1392   if (IsLoopIterVar) {
1393     if (DVar.CKind == OMPC_private)
1394       Reason = PDSA_LoopIterVarPrivate;
1395     else if (DVar.CKind == OMPC_lastprivate)
1396       Reason = PDSA_LoopIterVarLastprivate;
1397     else
1398       Reason = PDSA_LoopIterVarLinear;
1399   } else if (isOpenMPTaskingDirective(DVar.DKind) &&
1400              DVar.CKind == OMPC_firstprivate) {
1401     Reason = PDSA_TaskVarFirstprivate;
1402     ReportLoc = DVar.ImplicitDSALoc;
1403   } else if (VD && VD->isStaticLocal())
1404     Reason = PDSA_StaticLocalVarShared;
1405   else if (VD && VD->isStaticDataMember())
1406     Reason = PDSA_StaticMemberShared;
1407   else if (VD && VD->isFileVarDecl())
1408     Reason = PDSA_GlobalVarShared;
1409   else if (D->getType().isConstant(SemaRef.getASTContext()))
1410     Reason = PDSA_ConstVarShared;
1411   else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
1412     ReportHint = true;
1413     Reason = PDSA_LocalVarPrivate;
1414   }
1415   if (Reason != PDSA_Implicit) {
1416     SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
1417         << Reason << ReportHint
1418         << getOpenMPDirectiveName(Stack->getCurrentDirective());
1419   } else if (DVar.ImplicitDSALoc.isValid()) {
1420     SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
1421         << getOpenMPClauseName(DVar.CKind);
1422   }
1423 }
1424 
1425 namespace {
1426 class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> {
1427   DSAStackTy *Stack;
1428   Sema &SemaRef;
1429   bool ErrorFound;
1430   CapturedStmt *CS;
1431   llvm::SmallVector<Expr *, 8> ImplicitFirstprivate;
1432   llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
1433 
1434 public:
1435   void VisitDeclRefExpr(DeclRefExpr *E) {
1436     if (E->isTypeDependent() || E->isValueDependent() ||
1437         E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
1438       return;
1439     if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
1440       // Skip internally declared variables.
1441       if (VD->isLocalVarDecl() && !CS->capturesVariable(VD))
1442         return;
1443 
1444       auto DVar = Stack->getTopDSA(VD, false);
1445       // Check if the variable has explicit DSA set and stop analysis if it so.
1446       if (DVar.RefExpr) return;
1447 
1448       auto ELoc = E->getExprLoc();
1449       auto DKind = Stack->getCurrentDirective();
1450       // The default(none) clause requires that each variable that is referenced
1451       // in the construct, and does not have a predetermined data-sharing
1452       // attribute, must have its data-sharing attribute explicitly determined
1453       // by being listed in a data-sharing attribute clause.
1454       if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
1455           isParallelOrTaskRegion(DKind) &&
1456           VarsWithInheritedDSA.count(VD) == 0) {
1457         VarsWithInheritedDSA[VD] = E;
1458         return;
1459       }
1460 
1461       // OpenMP [2.9.3.6, Restrictions, p.2]
1462       //  A list item that appears in a reduction clause of the innermost
1463       //  enclosing worksharing or parallel construct may not be accessed in an
1464       //  explicit task.
1465       DVar = Stack->hasInnermostDSA(VD, MatchesAnyClause(OMPC_reduction),
1466                                     [](OpenMPDirectiveKind K) -> bool {
1467                                       return isOpenMPParallelDirective(K) ||
1468                                              isOpenMPWorksharingDirective(K) ||
1469                                              isOpenMPTeamsDirective(K);
1470                                     },
1471                                     false);
1472       if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
1473         ErrorFound = true;
1474         SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
1475         ReportOriginalDSA(SemaRef, Stack, VD, DVar);
1476         return;
1477       }
1478 
1479       // Define implicit data-sharing attributes for task.
1480       DVar = Stack->getImplicitDSA(VD, false);
1481       if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
1482           !Stack->isLoopControlVariable(VD).first)
1483         ImplicitFirstprivate.push_back(E);
1484     }
1485   }
1486   void VisitMemberExpr(MemberExpr *E) {
1487     if (E->isTypeDependent() || E->isValueDependent() ||
1488         E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
1489       return;
1490     if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
1491       if (auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
1492         auto DVar = Stack->getTopDSA(FD, false);
1493         // Check if the variable has explicit DSA set and stop analysis if it
1494         // so.
1495         if (DVar.RefExpr)
1496           return;
1497 
1498         auto ELoc = E->getExprLoc();
1499         auto DKind = Stack->getCurrentDirective();
1500         // OpenMP [2.9.3.6, Restrictions, p.2]
1501         //  A list item that appears in a reduction clause of the innermost
1502         //  enclosing worksharing or parallel construct may not be accessed in
1503         //  an  explicit task.
1504         DVar =
1505             Stack->hasInnermostDSA(FD, MatchesAnyClause(OMPC_reduction),
1506                                    [](OpenMPDirectiveKind K) -> bool {
1507                                      return isOpenMPParallelDirective(K) ||
1508                                             isOpenMPWorksharingDirective(K) ||
1509                                             isOpenMPTeamsDirective(K);
1510                                    },
1511                                    false);
1512         if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
1513           ErrorFound = true;
1514           SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
1515           ReportOriginalDSA(SemaRef, Stack, FD, DVar);
1516           return;
1517         }
1518 
1519         // Define implicit data-sharing attributes for task.
1520         DVar = Stack->getImplicitDSA(FD, false);
1521         if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
1522             !Stack->isLoopControlVariable(FD).first)
1523           ImplicitFirstprivate.push_back(E);
1524       }
1525     }
1526   }
1527   void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
1528     for (auto *C : S->clauses()) {
1529       // Skip analysis of arguments of implicitly defined firstprivate clause
1530       // for task directives.
1531       if (C && (!isa<OMPFirstprivateClause>(C) || C->getLocStart().isValid()))
1532         for (auto *CC : C->children()) {
1533           if (CC)
1534             Visit(CC);
1535         }
1536     }
1537   }
1538   void VisitStmt(Stmt *S) {
1539     for (auto *C : S->children()) {
1540       if (C && !isa<OMPExecutableDirective>(C))
1541         Visit(C);
1542     }
1543   }
1544 
1545   bool isErrorFound() { return ErrorFound; }
1546   ArrayRef<Expr *> getImplicitFirstprivate() { return ImplicitFirstprivate; }
1547   llvm::DenseMap<ValueDecl *, Expr *> &getVarsWithInheritedDSA() {
1548     return VarsWithInheritedDSA;
1549   }
1550 
1551   DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
1552       : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {}
1553 };
1554 } // namespace
1555 
1556 void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
1557   switch (DKind) {
1558   case OMPD_parallel: {
1559     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1560     QualType KmpInt32PtrTy =
1561         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
1562     Sema::CapturedParamNameType Params[] = {
1563         std::make_pair(".global_tid.", KmpInt32PtrTy),
1564         std::make_pair(".bound_tid.", KmpInt32PtrTy),
1565         std::make_pair(StringRef(), QualType()) // __context with shared vars
1566     };
1567     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1568                              Params);
1569     break;
1570   }
1571   case OMPD_simd: {
1572     Sema::CapturedParamNameType Params[] = {
1573         std::make_pair(StringRef(), QualType()) // __context with shared vars
1574     };
1575     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1576                              Params);
1577     break;
1578   }
1579   case OMPD_for: {
1580     Sema::CapturedParamNameType Params[] = {
1581         std::make_pair(StringRef(), QualType()) // __context with shared vars
1582     };
1583     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1584                              Params);
1585     break;
1586   }
1587   case OMPD_for_simd: {
1588     Sema::CapturedParamNameType Params[] = {
1589         std::make_pair(StringRef(), QualType()) // __context with shared vars
1590     };
1591     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1592                              Params);
1593     break;
1594   }
1595   case OMPD_sections: {
1596     Sema::CapturedParamNameType Params[] = {
1597         std::make_pair(StringRef(), QualType()) // __context with shared vars
1598     };
1599     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1600                              Params);
1601     break;
1602   }
1603   case OMPD_section: {
1604     Sema::CapturedParamNameType Params[] = {
1605         std::make_pair(StringRef(), QualType()) // __context with shared vars
1606     };
1607     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1608                              Params);
1609     break;
1610   }
1611   case OMPD_single: {
1612     Sema::CapturedParamNameType Params[] = {
1613         std::make_pair(StringRef(), QualType()) // __context with shared vars
1614     };
1615     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1616                              Params);
1617     break;
1618   }
1619   case OMPD_master: {
1620     Sema::CapturedParamNameType Params[] = {
1621         std::make_pair(StringRef(), QualType()) // __context with shared vars
1622     };
1623     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1624                              Params);
1625     break;
1626   }
1627   case OMPD_critical: {
1628     Sema::CapturedParamNameType Params[] = {
1629         std::make_pair(StringRef(), QualType()) // __context with shared vars
1630     };
1631     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1632                              Params);
1633     break;
1634   }
1635   case OMPD_parallel_for: {
1636     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1637     QualType KmpInt32PtrTy =
1638         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
1639     Sema::CapturedParamNameType Params[] = {
1640         std::make_pair(".global_tid.", KmpInt32PtrTy),
1641         std::make_pair(".bound_tid.", KmpInt32PtrTy),
1642         std::make_pair(StringRef(), QualType()) // __context with shared vars
1643     };
1644     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1645                              Params);
1646     break;
1647   }
1648   case OMPD_parallel_for_simd: {
1649     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1650     QualType KmpInt32PtrTy =
1651         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
1652     Sema::CapturedParamNameType Params[] = {
1653         std::make_pair(".global_tid.", KmpInt32PtrTy),
1654         std::make_pair(".bound_tid.", KmpInt32PtrTy),
1655         std::make_pair(StringRef(), QualType()) // __context with shared vars
1656     };
1657     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1658                              Params);
1659     break;
1660   }
1661   case OMPD_parallel_sections: {
1662     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1663     QualType KmpInt32PtrTy =
1664         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
1665     Sema::CapturedParamNameType Params[] = {
1666         std::make_pair(".global_tid.", KmpInt32PtrTy),
1667         std::make_pair(".bound_tid.", KmpInt32PtrTy),
1668         std::make_pair(StringRef(), QualType()) // __context with shared vars
1669     };
1670     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1671                              Params);
1672     break;
1673   }
1674   case OMPD_task: {
1675     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1676     QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
1677     FunctionProtoType::ExtProtoInfo EPI;
1678     EPI.Variadic = true;
1679     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
1680     Sema::CapturedParamNameType Params[] = {
1681         std::make_pair(".global_tid.", KmpInt32Ty),
1682         std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
1683         std::make_pair(".privates.", Context.VoidPtrTy.withConst()),
1684         std::make_pair(".copy_fn.",
1685                        Context.getPointerType(CopyFnType).withConst()),
1686         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
1687         std::make_pair(StringRef(), QualType()) // __context with shared vars
1688     };
1689     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1690                              Params);
1691     // Mark this captured region as inlined, because we don't use outlined
1692     // function directly.
1693     getCurCapturedRegion()->TheCapturedDecl->addAttr(
1694         AlwaysInlineAttr::CreateImplicit(
1695             Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
1696     break;
1697   }
1698   case OMPD_ordered: {
1699     Sema::CapturedParamNameType Params[] = {
1700         std::make_pair(StringRef(), QualType()) // __context with shared vars
1701     };
1702     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1703                              Params);
1704     break;
1705   }
1706   case OMPD_atomic: {
1707     Sema::CapturedParamNameType Params[] = {
1708         std::make_pair(StringRef(), QualType()) // __context with shared vars
1709     };
1710     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1711                              Params);
1712     break;
1713   }
1714   case OMPD_target_data:
1715   case OMPD_target:
1716   case OMPD_target_parallel:
1717   case OMPD_target_parallel_for: {
1718     Sema::CapturedParamNameType Params[] = {
1719         std::make_pair(StringRef(), QualType()) // __context with shared vars
1720     };
1721     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1722                              Params);
1723     break;
1724   }
1725   case OMPD_teams: {
1726     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1727     QualType KmpInt32PtrTy =
1728         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
1729     Sema::CapturedParamNameType Params[] = {
1730         std::make_pair(".global_tid.", KmpInt32PtrTy),
1731         std::make_pair(".bound_tid.", KmpInt32PtrTy),
1732         std::make_pair(StringRef(), QualType()) // __context with shared vars
1733     };
1734     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1735                              Params);
1736     break;
1737   }
1738   case OMPD_taskgroup: {
1739     Sema::CapturedParamNameType Params[] = {
1740         std::make_pair(StringRef(), QualType()) // __context with shared vars
1741     };
1742     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1743                              Params);
1744     break;
1745   }
1746   case OMPD_taskloop:
1747   case OMPD_taskloop_simd: {
1748     QualType KmpInt32Ty =
1749         Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1750     QualType KmpUInt64Ty =
1751         Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
1752     QualType KmpInt64Ty =
1753         Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
1754     QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
1755     FunctionProtoType::ExtProtoInfo EPI;
1756     EPI.Variadic = true;
1757     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
1758     Sema::CapturedParamNameType Params[] = {
1759         std::make_pair(".global_tid.", KmpInt32Ty),
1760         std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
1761         std::make_pair(".privates.",
1762                        Context.VoidPtrTy.withConst().withRestrict()),
1763         std::make_pair(
1764             ".copy_fn.",
1765             Context.getPointerType(CopyFnType).withConst().withRestrict()),
1766         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
1767         std::make_pair(".lb.", KmpUInt64Ty),
1768         std::make_pair(".ub.", KmpUInt64Ty), std::make_pair(".st.", KmpInt64Ty),
1769         std::make_pair(".liter.", KmpInt32Ty),
1770         std::make_pair(StringRef(), QualType()) // __context with shared vars
1771     };
1772     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1773                              Params);
1774     // Mark this captured region as inlined, because we don't use outlined
1775     // function directly.
1776     getCurCapturedRegion()->TheCapturedDecl->addAttr(
1777         AlwaysInlineAttr::CreateImplicit(
1778             Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
1779     break;
1780   }
1781   case OMPD_distribute: {
1782     Sema::CapturedParamNameType Params[] = {
1783         std::make_pair(StringRef(), QualType()) // __context with shared vars
1784     };
1785     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1786                              Params);
1787     break;
1788   }
1789   case OMPD_threadprivate:
1790   case OMPD_taskyield:
1791   case OMPD_barrier:
1792   case OMPD_taskwait:
1793   case OMPD_cancellation_point:
1794   case OMPD_cancel:
1795   case OMPD_flush:
1796   case OMPD_target_enter_data:
1797   case OMPD_target_exit_data:
1798   case OMPD_declare_reduction:
1799   case OMPD_declare_simd:
1800   case OMPD_declare_target:
1801   case OMPD_end_declare_target:
1802     llvm_unreachable("OpenMP Directive is not allowed");
1803   case OMPD_unknown:
1804     llvm_unreachable("Unknown OpenMP directive");
1805   }
1806 }
1807 
1808 static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
1809                                              Expr *CaptureExpr, bool WithInit,
1810                                              bool AsExpression) {
1811   assert(CaptureExpr);
1812   ASTContext &C = S.getASTContext();
1813   Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
1814   QualType Ty = Init->getType();
1815   if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
1816     if (S.getLangOpts().CPlusPlus)
1817       Ty = C.getLValueReferenceType(Ty);
1818     else {
1819       Ty = C.getPointerType(Ty);
1820       ExprResult Res =
1821           S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
1822       if (!Res.isUsable())
1823         return nullptr;
1824       Init = Res.get();
1825     }
1826     WithInit = true;
1827   }
1828   auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty);
1829   if (!WithInit)
1830     CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C, SourceRange()));
1831   S.CurContext->addHiddenDecl(CED);
1832   S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false,
1833                          /*TypeMayContainAuto=*/true);
1834   return CED;
1835 }
1836 
1837 static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
1838                                  bool WithInit) {
1839   OMPCapturedExprDecl *CD;
1840   if (auto *VD = S.IsOpenMPCapturedDecl(D))
1841     CD = cast<OMPCapturedExprDecl>(VD);
1842   else
1843     CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
1844                           /*AsExpression=*/false);
1845   return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
1846                           CaptureExpr->getExprLoc());
1847 }
1848 
1849 static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
1850   if (!Ref) {
1851     auto *CD =
1852         buildCaptureDecl(S, &S.getASTContext().Idents.get(".capture_expr."),
1853                          CaptureExpr, /*WithInit=*/true, /*AsExpression=*/true);
1854     Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
1855                            CaptureExpr->getExprLoc());
1856   }
1857   ExprResult Res = Ref;
1858   if (!S.getLangOpts().CPlusPlus &&
1859       CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
1860       Ref->getType()->isPointerType())
1861     Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
1862   if (!Res.isUsable())
1863     return ExprError();
1864   return CaptureExpr->isGLValue() ? Res : S.DefaultLvalueConversion(Res.get());
1865 }
1866 
1867 StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
1868                                       ArrayRef<OMPClause *> Clauses) {
1869   if (!S.isUsable()) {
1870     ActOnCapturedRegionError();
1871     return StmtError();
1872   }
1873 
1874   OMPOrderedClause *OC = nullptr;
1875   OMPScheduleClause *SC = nullptr;
1876   SmallVector<OMPLinearClause *, 4> LCs;
1877   // This is required for proper codegen.
1878   for (auto *Clause : Clauses) {
1879     if (isOpenMPPrivate(Clause->getClauseKind()) ||
1880         Clause->getClauseKind() == OMPC_copyprivate ||
1881         (getLangOpts().OpenMPUseTLS &&
1882          getASTContext().getTargetInfo().isTLSSupported() &&
1883          Clause->getClauseKind() == OMPC_copyin)) {
1884       DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
1885       // Mark all variables in private list clauses as used in inner region.
1886       for (auto *VarRef : Clause->children()) {
1887         if (auto *E = cast_or_null<Expr>(VarRef)) {
1888           MarkDeclarationsReferencedInExpr(E);
1889         }
1890       }
1891       DSAStack->setForceVarCapturing(/*V=*/false);
1892     } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) {
1893       // Mark all variables in private list clauses as used in inner region.
1894       // Required for proper codegen of combined directives.
1895       // TODO: add processing for other clauses.
1896       if (auto *C = OMPClauseWithPreInit::get(Clause)) {
1897         if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
1898           for (auto *D : DS->decls())
1899             MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
1900         }
1901       }
1902       if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
1903         if (auto *E = C->getPostUpdateExpr())
1904           MarkDeclarationsReferencedInExpr(E);
1905       }
1906     }
1907     if (Clause->getClauseKind() == OMPC_schedule)
1908       SC = cast<OMPScheduleClause>(Clause);
1909     else if (Clause->getClauseKind() == OMPC_ordered)
1910       OC = cast<OMPOrderedClause>(Clause);
1911     else if (Clause->getClauseKind() == OMPC_linear)
1912       LCs.push_back(cast<OMPLinearClause>(Clause));
1913   }
1914   bool ErrorFound = false;
1915   // OpenMP, 2.7.1 Loop Construct, Restrictions
1916   // The nonmonotonic modifier cannot be specified if an ordered clause is
1917   // specified.
1918   if (SC &&
1919       (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
1920        SC->getSecondScheduleModifier() ==
1921            OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
1922       OC) {
1923     Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
1924              ? SC->getFirstScheduleModifierLoc()
1925              : SC->getSecondScheduleModifierLoc(),
1926          diag::err_omp_schedule_nonmonotonic_ordered)
1927         << SourceRange(OC->getLocStart(), OC->getLocEnd());
1928     ErrorFound = true;
1929   }
1930   if (!LCs.empty() && OC && OC->getNumForLoops()) {
1931     for (auto *C : LCs) {
1932       Diag(C->getLocStart(), diag::err_omp_linear_ordered)
1933           << SourceRange(OC->getLocStart(), OC->getLocEnd());
1934     }
1935     ErrorFound = true;
1936   }
1937   if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
1938       isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
1939       OC->getNumForLoops()) {
1940     Diag(OC->getLocStart(), diag::err_omp_ordered_simd)
1941         << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
1942     ErrorFound = true;
1943   }
1944   if (ErrorFound) {
1945     ActOnCapturedRegionError();
1946     return StmtError();
1947   }
1948   return ActOnCapturedRegionEnd(S.get());
1949 }
1950 
1951 static bool CheckNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack,
1952                                   OpenMPDirectiveKind CurrentRegion,
1953                                   const DeclarationNameInfo &CurrentName,
1954                                   OpenMPDirectiveKind CancelRegion,
1955                                   SourceLocation StartLoc) {
1956   // Allowed nesting of constructs
1957   // +------------------+-----------------+------------------------------------+
1958   // | Parent directive | Child directive | Closely (!), No-Closely(+), Both(*)|
1959   // +------------------+-----------------+------------------------------------+
1960   // | parallel         | parallel        | *                                  |
1961   // | parallel         | for             | *                                  |
1962   // | parallel         | for simd        | *                                  |
1963   // | parallel         | master          | *                                  |
1964   // | parallel         | critical        | *                                  |
1965   // | parallel         | simd            | *                                  |
1966   // | parallel         | sections        | *                                  |
1967   // | parallel         | section         | +                                  |
1968   // | parallel         | single          | *                                  |
1969   // | parallel         | parallel for    | *                                  |
1970   // | parallel         |parallel for simd| *                                  |
1971   // | parallel         |parallel sections| *                                  |
1972   // | parallel         | task            | *                                  |
1973   // | parallel         | taskyield       | *                                  |
1974   // | parallel         | barrier         | *                                  |
1975   // | parallel         | taskwait        | *                                  |
1976   // | parallel         | taskgroup       | *                                  |
1977   // | parallel         | flush           | *                                  |
1978   // | parallel         | ordered         | +                                  |
1979   // | parallel         | atomic          | *                                  |
1980   // | parallel         | target          | *                                  |
1981   // | parallel         | target parallel | *                                  |
1982   // | parallel         | target parallel | *                                  |
1983   // |                  | for             |                                    |
1984   // | parallel         | target enter    | *                                  |
1985   // |                  | data            |                                    |
1986   // | parallel         | target exit     | *                                  |
1987   // |                  | data            |                                    |
1988   // | parallel         | teams           | +                                  |
1989   // | parallel         | cancellation    |                                    |
1990   // |                  | point           | !                                  |
1991   // | parallel         | cancel          | !                                  |
1992   // | parallel         | taskloop        | *                                  |
1993   // | parallel         | taskloop simd   | *                                  |
1994   // | parallel         | distribute      |                                    |
1995   // +------------------+-----------------+------------------------------------+
1996   // | for              | parallel        | *                                  |
1997   // | for              | for             | +                                  |
1998   // | for              | for simd        | +                                  |
1999   // | for              | master          | +                                  |
2000   // | for              | critical        | *                                  |
2001   // | for              | simd            | *                                  |
2002   // | for              | sections        | +                                  |
2003   // | for              | section         | +                                  |
2004   // | for              | single          | +                                  |
2005   // | for              | parallel for    | *                                  |
2006   // | for              |parallel for simd| *                                  |
2007   // | for              |parallel sections| *                                  |
2008   // | for              | task            | *                                  |
2009   // | for              | taskyield       | *                                  |
2010   // | for              | barrier         | +                                  |
2011   // | for              | taskwait        | *                                  |
2012   // | for              | taskgroup       | *                                  |
2013   // | for              | flush           | *                                  |
2014   // | for              | ordered         | * (if construct is ordered)        |
2015   // | for              | atomic          | *                                  |
2016   // | for              | target          | *                                  |
2017   // | for              | target parallel | *                                  |
2018   // | for              | target parallel | *                                  |
2019   // |                  | for             |                                    |
2020   // | for              | target enter    | *                                  |
2021   // |                  | data            |                                    |
2022   // | for              | target exit     | *                                  |
2023   // |                  | data            |                                    |
2024   // | for              | teams           | +                                  |
2025   // | for              | cancellation    |                                    |
2026   // |                  | point           | !                                  |
2027   // | for              | cancel          | !                                  |
2028   // | for              | taskloop        | *                                  |
2029   // | for              | taskloop simd   | *                                  |
2030   // | for              | distribute      |                                    |
2031   // +------------------+-----------------+------------------------------------+
2032   // | master           | parallel        | *                                  |
2033   // | master           | for             | +                                  |
2034   // | master           | for simd        | +                                  |
2035   // | master           | master          | *                                  |
2036   // | master           | critical        | *                                  |
2037   // | master           | simd            | *                                  |
2038   // | master           | sections        | +                                  |
2039   // | master           | section         | +                                  |
2040   // | master           | single          | +                                  |
2041   // | master           | parallel for    | *                                  |
2042   // | master           |parallel for simd| *                                  |
2043   // | master           |parallel sections| *                                  |
2044   // | master           | task            | *                                  |
2045   // | master           | taskyield       | *                                  |
2046   // | master           | barrier         | +                                  |
2047   // | master           | taskwait        | *                                  |
2048   // | master           | taskgroup       | *                                  |
2049   // | master           | flush           | *                                  |
2050   // | master           | ordered         | +                                  |
2051   // | master           | atomic          | *                                  |
2052   // | master           | target          | *                                  |
2053   // | master           | target parallel | *                                  |
2054   // | master           | target parallel | *                                  |
2055   // |                  | for             |                                    |
2056   // | master           | target enter    | *                                  |
2057   // |                  | data            |                                    |
2058   // | master           | target exit     | *                                  |
2059   // |                  | data            |                                    |
2060   // | master           | teams           | +                                  |
2061   // | master           | cancellation    |                                    |
2062   // |                  | point           |                                    |
2063   // | master           | cancel          |                                    |
2064   // | master           | taskloop        | *                                  |
2065   // | master           | taskloop simd   | *                                  |
2066   // | master           | distribute      |                                    |
2067   // +------------------+-----------------+------------------------------------+
2068   // | critical         | parallel        | *                                  |
2069   // | critical         | for             | +                                  |
2070   // | critical         | for simd        | +                                  |
2071   // | critical         | master          | *                                  |
2072   // | critical         | critical        | * (should have different names)    |
2073   // | critical         | simd            | *                                  |
2074   // | critical         | sections        | +                                  |
2075   // | critical         | section         | +                                  |
2076   // | critical         | single          | +                                  |
2077   // | critical         | parallel for    | *                                  |
2078   // | critical         |parallel for simd| *                                  |
2079   // | critical         |parallel sections| *                                  |
2080   // | critical         | task            | *                                  |
2081   // | critical         | taskyield       | *                                  |
2082   // | critical         | barrier         | +                                  |
2083   // | critical         | taskwait        | *                                  |
2084   // | critical         | taskgroup       | *                                  |
2085   // | critical         | ordered         | +                                  |
2086   // | critical         | atomic          | *                                  |
2087   // | critical         | target          | *                                  |
2088   // | critical         | target parallel | *                                  |
2089   // | critical         | target parallel | *                                  |
2090   // |                  | for             |                                    |
2091   // | critical         | target enter    | *                                  |
2092   // |                  | data            |                                    |
2093   // | critical         | target exit     | *                                  |
2094   // |                  | data            |                                    |
2095   // | critical         | teams           | +                                  |
2096   // | critical         | cancellation    |                                    |
2097   // |                  | point           |                                    |
2098   // | critical         | cancel          |                                    |
2099   // | critical         | taskloop        | *                                  |
2100   // | critical         | taskloop simd   | *                                  |
2101   // | critical         | distribute      |                                    |
2102   // +------------------+-----------------+------------------------------------+
2103   // | simd             | parallel        |                                    |
2104   // | simd             | for             |                                    |
2105   // | simd             | for simd        |                                    |
2106   // | simd             | master          |                                    |
2107   // | simd             | critical        |                                    |
2108   // | simd             | simd            | *                                  |
2109   // | simd             | sections        |                                    |
2110   // | simd             | section         |                                    |
2111   // | simd             | single          |                                    |
2112   // | simd             | parallel for    |                                    |
2113   // | simd             |parallel for simd|                                    |
2114   // | simd             |parallel sections|                                    |
2115   // | simd             | task            |                                    |
2116   // | simd             | taskyield       |                                    |
2117   // | simd             | barrier         |                                    |
2118   // | simd             | taskwait        |                                    |
2119   // | simd             | taskgroup       |                                    |
2120   // | simd             | flush           |                                    |
2121   // | simd             | ordered         | + (with simd clause)               |
2122   // | simd             | atomic          |                                    |
2123   // | simd             | target          |                                    |
2124   // | simd             | target parallel |                                    |
2125   // | simd             | target parallel |                                    |
2126   // |                  | for             |                                    |
2127   // | simd             | target enter    |                                    |
2128   // |                  | data            |                                    |
2129   // | simd             | target exit     |                                    |
2130   // |                  | data            |                                    |
2131   // | simd             | teams           |                                    |
2132   // | simd             | cancellation    |                                    |
2133   // |                  | point           |                                    |
2134   // | simd             | cancel          |                                    |
2135   // | simd             | taskloop        |                                    |
2136   // | simd             | taskloop simd   |                                    |
2137   // | simd             | distribute      |                                    |
2138   // +------------------+-----------------+------------------------------------+
2139   // | for simd         | parallel        |                                    |
2140   // | for simd         | for             |                                    |
2141   // | for simd         | for simd        |                                    |
2142   // | for simd         | master          |                                    |
2143   // | for simd         | critical        |                                    |
2144   // | for simd         | simd            | *                                  |
2145   // | for simd         | sections        |                                    |
2146   // | for simd         | section         |                                    |
2147   // | for simd         | single          |                                    |
2148   // | for simd         | parallel for    |                                    |
2149   // | for simd         |parallel for simd|                                    |
2150   // | for simd         |parallel sections|                                    |
2151   // | for simd         | task            |                                    |
2152   // | for simd         | taskyield       |                                    |
2153   // | for simd         | barrier         |                                    |
2154   // | for simd         | taskwait        |                                    |
2155   // | for simd         | taskgroup       |                                    |
2156   // | for simd         | flush           |                                    |
2157   // | for simd         | ordered         | + (with simd clause)               |
2158   // | for simd         | atomic          |                                    |
2159   // | for simd         | target          |                                    |
2160   // | for simd         | target parallel |                                    |
2161   // | for simd         | target parallel |                                    |
2162   // |                  | for             |                                    |
2163   // | for simd         | target enter    |                                    |
2164   // |                  | data            |                                    |
2165   // | for simd         | target exit     |                                    |
2166   // |                  | data            |                                    |
2167   // | for simd         | teams           |                                    |
2168   // | for simd         | cancellation    |                                    |
2169   // |                  | point           |                                    |
2170   // | for simd         | cancel          |                                    |
2171   // | for simd         | taskloop        |                                    |
2172   // | for simd         | taskloop simd   |                                    |
2173   // | for simd         | distribute      |                                    |
2174   // +------------------+-----------------+------------------------------------+
2175   // | parallel for simd| parallel        |                                    |
2176   // | parallel for simd| for             |                                    |
2177   // | parallel for simd| for simd        |                                    |
2178   // | parallel for simd| master          |                                    |
2179   // | parallel for simd| critical        |                                    |
2180   // | parallel for simd| simd            | *                                  |
2181   // | parallel for simd| sections        |                                    |
2182   // | parallel for simd| section         |                                    |
2183   // | parallel for simd| single          |                                    |
2184   // | parallel for simd| parallel for    |                                    |
2185   // | parallel for simd|parallel for simd|                                    |
2186   // | parallel for simd|parallel sections|                                    |
2187   // | parallel for simd| task            |                                    |
2188   // | parallel for simd| taskyield       |                                    |
2189   // | parallel for simd| barrier         |                                    |
2190   // | parallel for simd| taskwait        |                                    |
2191   // | parallel for simd| taskgroup       |                                    |
2192   // | parallel for simd| flush           |                                    |
2193   // | parallel for simd| ordered         | + (with simd clause)               |
2194   // | parallel for simd| atomic          |                                    |
2195   // | parallel for simd| target          |                                    |
2196   // | parallel for simd| target parallel |                                    |
2197   // | parallel for simd| target parallel |                                    |
2198   // |                  | for             |                                    |
2199   // | parallel for simd| target enter    |                                    |
2200   // |                  | data            |                                    |
2201   // | parallel for simd| target exit     |                                    |
2202   // |                  | data            |                                    |
2203   // | parallel for simd| teams           |                                    |
2204   // | parallel for simd| cancellation    |                                    |
2205   // |                  | point           |                                    |
2206   // | parallel for simd| cancel          |                                    |
2207   // | parallel for simd| taskloop        |                                    |
2208   // | parallel for simd| taskloop simd   |                                    |
2209   // | parallel for simd| distribute      |                                    |
2210   // +------------------+-----------------+------------------------------------+
2211   // | sections         | parallel        | *                                  |
2212   // | sections         | for             | +                                  |
2213   // | sections         | for simd        | +                                  |
2214   // | sections         | master          | +                                  |
2215   // | sections         | critical        | *                                  |
2216   // | sections         | simd            | *                                  |
2217   // | sections         | sections        | +                                  |
2218   // | sections         | section         | *                                  |
2219   // | sections         | single          | +                                  |
2220   // | sections         | parallel for    | *                                  |
2221   // | sections         |parallel for simd| *                                  |
2222   // | sections         |parallel sections| *                                  |
2223   // | sections         | task            | *                                  |
2224   // | sections         | taskyield       | *                                  |
2225   // | sections         | barrier         | +                                  |
2226   // | sections         | taskwait        | *                                  |
2227   // | sections         | taskgroup       | *                                  |
2228   // | sections         | flush           | *                                  |
2229   // | sections         | ordered         | +                                  |
2230   // | sections         | atomic          | *                                  |
2231   // | sections         | target          | *                                  |
2232   // | sections         | target parallel | *                                  |
2233   // | sections         | target parallel | *                                  |
2234   // |                  | for             |                                    |
2235   // | sections         | target enter    | *                                  |
2236   // |                  | data            |                                    |
2237   // | sections         | target exit     | *                                  |
2238   // |                  | data            |                                    |
2239   // | sections         | teams           | +                                  |
2240   // | sections         | cancellation    |                                    |
2241   // |                  | point           | !                                  |
2242   // | sections         | cancel          | !                                  |
2243   // | sections         | taskloop        | *                                  |
2244   // | sections         | taskloop simd   | *                                  |
2245   // | sections         | distribute      |                                    |
2246   // +------------------+-----------------+------------------------------------+
2247   // | section          | parallel        | *                                  |
2248   // | section          | for             | +                                  |
2249   // | section          | for simd        | +                                  |
2250   // | section          | master          | +                                  |
2251   // | section          | critical        | *                                  |
2252   // | section          | simd            | *                                  |
2253   // | section          | sections        | +                                  |
2254   // | section          | section         | +                                  |
2255   // | section          | single          | +                                  |
2256   // | section          | parallel for    | *                                  |
2257   // | section          |parallel for simd| *                                  |
2258   // | section          |parallel sections| *                                  |
2259   // | section          | task            | *                                  |
2260   // | section          | taskyield       | *                                  |
2261   // | section          | barrier         | +                                  |
2262   // | section          | taskwait        | *                                  |
2263   // | section          | taskgroup       | *                                  |
2264   // | section          | flush           | *                                  |
2265   // | section          | ordered         | +                                  |
2266   // | section          | atomic          | *                                  |
2267   // | section          | target          | *                                  |
2268   // | section          | target parallel | *                                  |
2269   // | section          | target parallel | *                                  |
2270   // |                  | for             |                                    |
2271   // | section          | target enter    | *                                  |
2272   // |                  | data            |                                    |
2273   // | section          | target exit     | *                                  |
2274   // |                  | data            |                                    |
2275   // | section          | teams           | +                                  |
2276   // | section          | cancellation    |                                    |
2277   // |                  | point           | !                                  |
2278   // | section          | cancel          | !                                  |
2279   // | section          | taskloop        | *                                  |
2280   // | section          | taskloop simd   | *                                  |
2281   // | section          | distribute      |                                    |
2282   // +------------------+-----------------+------------------------------------+
2283   // | single           | parallel        | *                                  |
2284   // | single           | for             | +                                  |
2285   // | single           | for simd        | +                                  |
2286   // | single           | master          | +                                  |
2287   // | single           | critical        | *                                  |
2288   // | single           | simd            | *                                  |
2289   // | single           | sections        | +                                  |
2290   // | single           | section         | +                                  |
2291   // | single           | single          | +                                  |
2292   // | single           | parallel for    | *                                  |
2293   // | single           |parallel for simd| *                                  |
2294   // | single           |parallel sections| *                                  |
2295   // | single           | task            | *                                  |
2296   // | single           | taskyield       | *                                  |
2297   // | single           | barrier         | +                                  |
2298   // | single           | taskwait        | *                                  |
2299   // | single           | taskgroup       | *                                  |
2300   // | single           | flush           | *                                  |
2301   // | single           | ordered         | +                                  |
2302   // | single           | atomic          | *                                  |
2303   // | single           | target          | *                                  |
2304   // | single           | target parallel | *                                  |
2305   // | single           | target parallel | *                                  |
2306   // |                  | for             |                                    |
2307   // | single           | target enter    | *                                  |
2308   // |                  | data            |                                    |
2309   // | single           | target exit     | *                                  |
2310   // |                  | data            |                                    |
2311   // | single           | teams           | +                                  |
2312   // | single           | cancellation    |                                    |
2313   // |                  | point           |                                    |
2314   // | single           | cancel          |                                    |
2315   // | single           | taskloop        | *                                  |
2316   // | single           | taskloop simd   | *                                  |
2317   // | single           | distribute      |                                    |
2318   // +------------------+-----------------+------------------------------------+
2319   // | parallel for     | parallel        | *                                  |
2320   // | parallel for     | for             | +                                  |
2321   // | parallel for     | for simd        | +                                  |
2322   // | parallel for     | master          | +                                  |
2323   // | parallel for     | critical        | *                                  |
2324   // | parallel for     | simd            | *                                  |
2325   // | parallel for     | sections        | +                                  |
2326   // | parallel for     | section         | +                                  |
2327   // | parallel for     | single          | +                                  |
2328   // | parallel for     | parallel for    | *                                  |
2329   // | parallel for     |parallel for simd| *                                  |
2330   // | parallel for     |parallel sections| *                                  |
2331   // | parallel for     | task            | *                                  |
2332   // | parallel for     | taskyield       | *                                  |
2333   // | parallel for     | barrier         | +                                  |
2334   // | parallel for     | taskwait        | *                                  |
2335   // | parallel for     | taskgroup       | *                                  |
2336   // | parallel for     | flush           | *                                  |
2337   // | parallel for     | ordered         | * (if construct is ordered)        |
2338   // | parallel for     | atomic          | *                                  |
2339   // | parallel for     | target          | *                                  |
2340   // | parallel for     | target parallel | *                                  |
2341   // | parallel for     | target parallel | *                                  |
2342   // |                  | for             |                                    |
2343   // | parallel for     | target enter    | *                                  |
2344   // |                  | data            |                                    |
2345   // | parallel for     | target exit     | *                                  |
2346   // |                  | data            |                                    |
2347   // | parallel for     | teams           | +                                  |
2348   // | parallel for     | cancellation    |                                    |
2349   // |                  | point           | !                                  |
2350   // | parallel for     | cancel          | !                                  |
2351   // | parallel for     | taskloop        | *                                  |
2352   // | parallel for     | taskloop simd   | *                                  |
2353   // | parallel for     | distribute      |                                    |
2354   // +------------------+-----------------+------------------------------------+
2355   // | parallel sections| parallel        | *                                  |
2356   // | parallel sections| for             | +                                  |
2357   // | parallel sections| for simd        | +                                  |
2358   // | parallel sections| master          | +                                  |
2359   // | parallel sections| critical        | +                                  |
2360   // | parallel sections| simd            | *                                  |
2361   // | parallel sections| sections        | +                                  |
2362   // | parallel sections| section         | *                                  |
2363   // | parallel sections| single          | +                                  |
2364   // | parallel sections| parallel for    | *                                  |
2365   // | parallel sections|parallel for simd| *                                  |
2366   // | parallel sections|parallel sections| *                                  |
2367   // | parallel sections| task            | *                                  |
2368   // | parallel sections| taskyield       | *                                  |
2369   // | parallel sections| barrier         | +                                  |
2370   // | parallel sections| taskwait        | *                                  |
2371   // | parallel sections| taskgroup       | *                                  |
2372   // | parallel sections| flush           | *                                  |
2373   // | parallel sections| ordered         | +                                  |
2374   // | parallel sections| atomic          | *                                  |
2375   // | parallel sections| target          | *                                  |
2376   // | parallel sections| target parallel | *                                  |
2377   // | parallel sections| target parallel | *                                  |
2378   // |                  | for             |                                    |
2379   // | parallel sections| target enter    | *                                  |
2380   // |                  | data            |                                    |
2381   // | parallel sections| target exit     | *                                  |
2382   // |                  | data            |                                    |
2383   // | parallel sections| teams           | +                                  |
2384   // | parallel sections| cancellation    |                                    |
2385   // |                  | point           | !                                  |
2386   // | parallel sections| cancel          | !                                  |
2387   // | parallel sections| taskloop        | *                                  |
2388   // | parallel sections| taskloop simd   | *                                  |
2389   // | parallel sections| distribute      |                                    |
2390   // +------------------+-----------------+------------------------------------+
2391   // | task             | parallel        | *                                  |
2392   // | task             | for             | +                                  |
2393   // | task             | for simd        | +                                  |
2394   // | task             | master          | +                                  |
2395   // | task             | critical        | *                                  |
2396   // | task             | simd            | *                                  |
2397   // | task             | sections        | +                                  |
2398   // | task             | section         | +                                  |
2399   // | task             | single          | +                                  |
2400   // | task             | parallel for    | *                                  |
2401   // | task             |parallel for simd| *                                  |
2402   // | task             |parallel sections| *                                  |
2403   // | task             | task            | *                                  |
2404   // | task             | taskyield       | *                                  |
2405   // | task             | barrier         | +                                  |
2406   // | task             | taskwait        | *                                  |
2407   // | task             | taskgroup       | *                                  |
2408   // | task             | flush           | *                                  |
2409   // | task             | ordered         | +                                  |
2410   // | task             | atomic          | *                                  |
2411   // | task             | target          | *                                  |
2412   // | task             | target parallel | *                                  |
2413   // | task             | target parallel | *                                  |
2414   // |                  | for             |                                    |
2415   // | task             | target enter    | *                                  |
2416   // |                  | data            |                                    |
2417   // | task             | target exit     | *                                  |
2418   // |                  | data            |                                    |
2419   // | task             | teams           | +                                  |
2420   // | task             | cancellation    |                                    |
2421   // |                  | point           | !                                  |
2422   // | task             | cancel          | !                                  |
2423   // | task             | taskloop        | *                                  |
2424   // | task             | taskloop simd   | *                                  |
2425   // | task             | distribute      |                                    |
2426   // +------------------+-----------------+------------------------------------+
2427   // | ordered          | parallel        | *                                  |
2428   // | ordered          | for             | +                                  |
2429   // | ordered          | for simd        | +                                  |
2430   // | ordered          | master          | *                                  |
2431   // | ordered          | critical        | *                                  |
2432   // | ordered          | simd            | *                                  |
2433   // | ordered          | sections        | +                                  |
2434   // | ordered          | section         | +                                  |
2435   // | ordered          | single          | +                                  |
2436   // | ordered          | parallel for    | *                                  |
2437   // | ordered          |parallel for simd| *                                  |
2438   // | ordered          |parallel sections| *                                  |
2439   // | ordered          | task            | *                                  |
2440   // | ordered          | taskyield       | *                                  |
2441   // | ordered          | barrier         | +                                  |
2442   // | ordered          | taskwait        | *                                  |
2443   // | ordered          | taskgroup       | *                                  |
2444   // | ordered          | flush           | *                                  |
2445   // | ordered          | ordered         | +                                  |
2446   // | ordered          | atomic          | *                                  |
2447   // | ordered          | target          | *                                  |
2448   // | ordered          | target parallel | *                                  |
2449   // | ordered          | target parallel | *                                  |
2450   // |                  | for             |                                    |
2451   // | ordered          | target enter    | *                                  |
2452   // |                  | data            |                                    |
2453   // | ordered          | target exit     | *                                  |
2454   // |                  | data            |                                    |
2455   // | ordered          | teams           | +                                  |
2456   // | ordered          | cancellation    |                                    |
2457   // |                  | point           |                                    |
2458   // | ordered          | cancel          |                                    |
2459   // | ordered          | taskloop        | *                                  |
2460   // | ordered          | taskloop simd   | *                                  |
2461   // | ordered          | distribute      |                                    |
2462   // +------------------+-----------------+------------------------------------+
2463   // | atomic           | parallel        |                                    |
2464   // | atomic           | for             |                                    |
2465   // | atomic           | for simd        |                                    |
2466   // | atomic           | master          |                                    |
2467   // | atomic           | critical        |                                    |
2468   // | atomic           | simd            |                                    |
2469   // | atomic           | sections        |                                    |
2470   // | atomic           | section         |                                    |
2471   // | atomic           | single          |                                    |
2472   // | atomic           | parallel for    |                                    |
2473   // | atomic           |parallel for simd|                                    |
2474   // | atomic           |parallel sections|                                    |
2475   // | atomic           | task            |                                    |
2476   // | atomic           | taskyield       |                                    |
2477   // | atomic           | barrier         |                                    |
2478   // | atomic           | taskwait        |                                    |
2479   // | atomic           | taskgroup       |                                    |
2480   // | atomic           | flush           |                                    |
2481   // | atomic           | ordered         |                                    |
2482   // | atomic           | atomic          |                                    |
2483   // | atomic           | target          |                                    |
2484   // | atomic           | target parallel |                                    |
2485   // | atomic           | target parallel |                                    |
2486   // |                  | for             |                                    |
2487   // | atomic           | target enter    |                                    |
2488   // |                  | data            |                                    |
2489   // | atomic           | target exit     |                                    |
2490   // |                  | data            |                                    |
2491   // | atomic           | teams           |                                    |
2492   // | atomic           | cancellation    |                                    |
2493   // |                  | point           |                                    |
2494   // | atomic           | cancel          |                                    |
2495   // | atomic           | taskloop        |                                    |
2496   // | atomic           | taskloop simd   |                                    |
2497   // | atomic           | distribute      |                                    |
2498   // +------------------+-----------------+------------------------------------+
2499   // | target           | parallel        | *                                  |
2500   // | target           | for             | *                                  |
2501   // | target           | for simd        | *                                  |
2502   // | target           | master          | *                                  |
2503   // | target           | critical        | *                                  |
2504   // | target           | simd            | *                                  |
2505   // | target           | sections        | *                                  |
2506   // | target           | section         | *                                  |
2507   // | target           | single          | *                                  |
2508   // | target           | parallel for    | *                                  |
2509   // | target           |parallel for simd| *                                  |
2510   // | target           |parallel sections| *                                  |
2511   // | target           | task            | *                                  |
2512   // | target           | taskyield       | *                                  |
2513   // | target           | barrier         | *                                  |
2514   // | target           | taskwait        | *                                  |
2515   // | target           | taskgroup       | *                                  |
2516   // | target           | flush           | *                                  |
2517   // | target           | ordered         | *                                  |
2518   // | target           | atomic          | *                                  |
2519   // | target           | target          |                                    |
2520   // | target           | target parallel |                                    |
2521   // | target           | target parallel |                                    |
2522   // |                  | for             |                                    |
2523   // | target           | target enter    |                                    |
2524   // |                  | data            |                                    |
2525   // | target           | target exit     |                                    |
2526   // |                  | data            |                                    |
2527   // | target           | teams           | *                                  |
2528   // | target           | cancellation    |                                    |
2529   // |                  | point           |                                    |
2530   // | target           | cancel          |                                    |
2531   // | target           | taskloop        | *                                  |
2532   // | target           | taskloop simd   | *                                  |
2533   // | target           | distribute      |                                    |
2534   // +------------------+-----------------+------------------------------------+
2535   // | target parallel  | parallel        | *                                  |
2536   // | target parallel  | for             | *                                  |
2537   // | target parallel  | for simd        | *                                  |
2538   // | target parallel  | master          | *                                  |
2539   // | target parallel  | critical        | *                                  |
2540   // | target parallel  | simd            | *                                  |
2541   // | target parallel  | sections        | *                                  |
2542   // | target parallel  | section         | *                                  |
2543   // | target parallel  | single          | *                                  |
2544   // | target parallel  | parallel for    | *                                  |
2545   // | target parallel  |parallel for simd| *                                  |
2546   // | target parallel  |parallel sections| *                                  |
2547   // | target parallel  | task            | *                                  |
2548   // | target parallel  | taskyield       | *                                  |
2549   // | target parallel  | barrier         | *                                  |
2550   // | target parallel  | taskwait        | *                                  |
2551   // | target parallel  | taskgroup       | *                                  |
2552   // | target parallel  | flush           | *                                  |
2553   // | target parallel  | ordered         | *                                  |
2554   // | target parallel  | atomic          | *                                  |
2555   // | target parallel  | target          |                                    |
2556   // | target parallel  | target parallel |                                    |
2557   // | target parallel  | target parallel |                                    |
2558   // |                  | for             |                                    |
2559   // | target parallel  | target enter    |                                    |
2560   // |                  | data            |                                    |
2561   // | target parallel  | target exit     |                                    |
2562   // |                  | data            |                                    |
2563   // | target parallel  | teams           |                                    |
2564   // | target parallel  | cancellation    |                                    |
2565   // |                  | point           | !                                  |
2566   // | target parallel  | cancel          | !                                  |
2567   // | target parallel  | taskloop        | *                                  |
2568   // | target parallel  | taskloop simd   | *                                  |
2569   // | target parallel  | distribute      |                                    |
2570   // +------------------+-----------------+------------------------------------+
2571   // | target parallel  | parallel        | *                                  |
2572   // | for              |                 |                                    |
2573   // | target parallel  | for             | *                                  |
2574   // | for              |                 |                                    |
2575   // | target parallel  | for simd        | *                                  |
2576   // | for              |                 |                                    |
2577   // | target parallel  | master          | *                                  |
2578   // | for              |                 |                                    |
2579   // | target parallel  | critical        | *                                  |
2580   // | for              |                 |                                    |
2581   // | target parallel  | simd            | *                                  |
2582   // | for              |                 |                                    |
2583   // | target parallel  | sections        | *                                  |
2584   // | for              |                 |                                    |
2585   // | target parallel  | section         | *                                  |
2586   // | for              |                 |                                    |
2587   // | target parallel  | single          | *                                  |
2588   // | for              |                 |                                    |
2589   // | target parallel  | parallel for    | *                                  |
2590   // | for              |                 |                                    |
2591   // | target parallel  |parallel for simd| *                                  |
2592   // | for              |                 |                                    |
2593   // | target parallel  |parallel sections| *                                  |
2594   // | for              |                 |                                    |
2595   // | target parallel  | task            | *                                  |
2596   // | for              |                 |                                    |
2597   // | target parallel  | taskyield       | *                                  |
2598   // | for              |                 |                                    |
2599   // | target parallel  | barrier         | *                                  |
2600   // | for              |                 |                                    |
2601   // | target parallel  | taskwait        | *                                  |
2602   // | for              |                 |                                    |
2603   // | target parallel  | taskgroup       | *                                  |
2604   // | for              |                 |                                    |
2605   // | target parallel  | flush           | *                                  |
2606   // | for              |                 |                                    |
2607   // | target parallel  | ordered         | *                                  |
2608   // | for              |                 |                                    |
2609   // | target parallel  | atomic          | *                                  |
2610   // | for              |                 |                                    |
2611   // | target parallel  | target          |                                    |
2612   // | for              |                 |                                    |
2613   // | target parallel  | target parallel |                                    |
2614   // | for              |                 |                                    |
2615   // | target parallel  | target parallel |                                    |
2616   // | for              | for             |                                    |
2617   // | target parallel  | target enter    |                                    |
2618   // | for              | data            |                                    |
2619   // | target parallel  | target exit     |                                    |
2620   // | for              | data            |                                    |
2621   // | target parallel  | teams           |                                    |
2622   // | for              |                 |                                    |
2623   // | target parallel  | cancellation    |                                    |
2624   // | for              | point           | !                                  |
2625   // | target parallel  | cancel          | !                                  |
2626   // | for              |                 |                                    |
2627   // | target parallel  | taskloop        | *                                  |
2628   // | for              |                 |                                    |
2629   // | target parallel  | taskloop simd   | *                                  |
2630   // | for              |                 |                                    |
2631   // | target parallel  | distribute      |                                    |
2632   // | for              |                 |                                    |
2633   // +------------------+-----------------+------------------------------------+
2634   // | teams            | parallel        | *                                  |
2635   // | teams            | for             | +                                  |
2636   // | teams            | for simd        | +                                  |
2637   // | teams            | master          | +                                  |
2638   // | teams            | critical        | +                                  |
2639   // | teams            | simd            | +                                  |
2640   // | teams            | sections        | +                                  |
2641   // | teams            | section         | +                                  |
2642   // | teams            | single          | +                                  |
2643   // | teams            | parallel for    | *                                  |
2644   // | teams            |parallel for simd| *                                  |
2645   // | teams            |parallel sections| *                                  |
2646   // | teams            | task            | +                                  |
2647   // | teams            | taskyield       | +                                  |
2648   // | teams            | barrier         | +                                  |
2649   // | teams            | taskwait        | +                                  |
2650   // | teams            | taskgroup       | +                                  |
2651   // | teams            | flush           | +                                  |
2652   // | teams            | ordered         | +                                  |
2653   // | teams            | atomic          | +                                  |
2654   // | teams            | target          | +                                  |
2655   // | teams            | target parallel | +                                  |
2656   // | teams            | target parallel | +                                  |
2657   // |                  | for             |                                    |
2658   // | teams            | target enter    | +                                  |
2659   // |                  | data            |                                    |
2660   // | teams            | target exit     | +                                  |
2661   // |                  | data            |                                    |
2662   // | teams            | teams           | +                                  |
2663   // | teams            | cancellation    |                                    |
2664   // |                  | point           |                                    |
2665   // | teams            | cancel          |                                    |
2666   // | teams            | taskloop        | +                                  |
2667   // | teams            | taskloop simd   | +                                  |
2668   // | teams            | distribute      | !                                  |
2669   // +------------------+-----------------+------------------------------------+
2670   // | taskloop         | parallel        | *                                  |
2671   // | taskloop         | for             | +                                  |
2672   // | taskloop         | for simd        | +                                  |
2673   // | taskloop         | master          | +                                  |
2674   // | taskloop         | critical        | *                                  |
2675   // | taskloop         | simd            | *                                  |
2676   // | taskloop         | sections        | +                                  |
2677   // | taskloop         | section         | +                                  |
2678   // | taskloop         | single          | +                                  |
2679   // | taskloop         | parallel for    | *                                  |
2680   // | taskloop         |parallel for simd| *                                  |
2681   // | taskloop         |parallel sections| *                                  |
2682   // | taskloop         | task            | *                                  |
2683   // | taskloop         | taskyield       | *                                  |
2684   // | taskloop         | barrier         | +                                  |
2685   // | taskloop         | taskwait        | *                                  |
2686   // | taskloop         | taskgroup       | *                                  |
2687   // | taskloop         | flush           | *                                  |
2688   // | taskloop         | ordered         | +                                  |
2689   // | taskloop         | atomic          | *                                  |
2690   // | taskloop         | target          | *                                  |
2691   // | taskloop         | target parallel | *                                  |
2692   // | taskloop         | target parallel | *                                  |
2693   // |                  | for             |                                    |
2694   // | taskloop         | target enter    | *                                  |
2695   // |                  | data            |                                    |
2696   // | taskloop         | target exit     | *                                  |
2697   // |                  | data            |                                    |
2698   // | taskloop         | teams           | +                                  |
2699   // | taskloop         | cancellation    |                                    |
2700   // |                  | point           |                                    |
2701   // | taskloop         | cancel          |                                    |
2702   // | taskloop         | taskloop        | *                                  |
2703   // | taskloop         | distribute      |                                    |
2704   // +------------------+-----------------+------------------------------------+
2705   // | taskloop simd    | parallel        |                                    |
2706   // | taskloop simd    | for             |                                    |
2707   // | taskloop simd    | for simd        |                                    |
2708   // | taskloop simd    | master          |                                    |
2709   // | taskloop simd    | critical        |                                    |
2710   // | taskloop simd    | simd            | *                                  |
2711   // | taskloop simd    | sections        |                                    |
2712   // | taskloop simd    | section         |                                    |
2713   // | taskloop simd    | single          |                                    |
2714   // | taskloop simd    | parallel for    |                                    |
2715   // | taskloop simd    |parallel for simd|                                    |
2716   // | taskloop simd    |parallel sections|                                    |
2717   // | taskloop simd    | task            |                                    |
2718   // | taskloop simd    | taskyield       |                                    |
2719   // | taskloop simd    | barrier         |                                    |
2720   // | taskloop simd    | taskwait        |                                    |
2721   // | taskloop simd    | taskgroup       |                                    |
2722   // | taskloop simd    | flush           |                                    |
2723   // | taskloop simd    | ordered         | + (with simd clause)               |
2724   // | taskloop simd    | atomic          |                                    |
2725   // | taskloop simd    | target          |                                    |
2726   // | taskloop simd    | target parallel |                                    |
2727   // | taskloop simd    | target parallel |                                    |
2728   // |                  | for             |                                    |
2729   // | taskloop simd    | target enter    |                                    |
2730   // |                  | data            |                                    |
2731   // | taskloop simd    | target exit     |                                    |
2732   // |                  | data            |                                    |
2733   // | taskloop simd    | teams           |                                    |
2734   // | taskloop simd    | cancellation    |                                    |
2735   // |                  | point           |                                    |
2736   // | taskloop simd    | cancel          |                                    |
2737   // | taskloop simd    | taskloop        |                                    |
2738   // | taskloop simd    | taskloop simd   |                                    |
2739   // | taskloop simd    | distribute      |                                    |
2740   // +------------------+-----------------+------------------------------------+
2741   // | distribute       | parallel        | *                                  |
2742   // | distribute       | for             | *                                  |
2743   // | distribute       | for simd        | *                                  |
2744   // | distribute       | master          | *                                  |
2745   // | distribute       | critical        | *                                  |
2746   // | distribute       | simd            | *                                  |
2747   // | distribute       | sections        | *                                  |
2748   // | distribute       | section         | *                                  |
2749   // | distribute       | single          | *                                  |
2750   // | distribute       | parallel for    | *                                  |
2751   // | distribute       |parallel for simd| *                                  |
2752   // | distribute       |parallel sections| *                                  |
2753   // | distribute       | task            | *                                  |
2754   // | distribute       | taskyield       | *                                  |
2755   // | distribute       | barrier         | *                                  |
2756   // | distribute       | taskwait        | *                                  |
2757   // | distribute       | taskgroup       | *                                  |
2758   // | distribute       | flush           | *                                  |
2759   // | distribute       | ordered         | +                                  |
2760   // | distribute       | atomic          | *                                  |
2761   // | distribute       | target          |                                    |
2762   // | distribute       | target parallel |                                    |
2763   // | distribute       | target parallel |                                    |
2764   // |                  | for             |                                    |
2765   // | distribute       | target enter    |                                    |
2766   // |                  | data            |                                    |
2767   // | distribute       | target exit     |                                    |
2768   // |                  | data            |                                    |
2769   // | distribute       | teams           |                                    |
2770   // | distribute       | cancellation    | +                                  |
2771   // |                  | point           |                                    |
2772   // | distribute       | cancel          | +                                  |
2773   // | distribute       | taskloop        | *                                  |
2774   // | distribute       | taskloop simd   | *                                  |
2775   // | distribute       | distribute      |                                    |
2776   // +------------------+-----------------+------------------------------------+
2777   if (Stack->getCurScope()) {
2778     auto ParentRegion = Stack->getParentDirective();
2779     auto OffendingRegion = ParentRegion;
2780     bool NestingProhibited = false;
2781     bool CloseNesting = true;
2782     enum {
2783       NoRecommend,
2784       ShouldBeInParallelRegion,
2785       ShouldBeInOrderedRegion,
2786       ShouldBeInTargetRegion,
2787       ShouldBeInTeamsRegion
2788     } Recommend = NoRecommend;
2789     if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered &&
2790         CurrentRegion != OMPD_simd) {
2791       // OpenMP [2.16, Nesting of Regions]
2792       // OpenMP constructs may not be nested inside a simd region.
2793       // OpenMP [2.8.1,simd Construct, Restrictions]
2794       // An ordered construct with the simd clause is the only OpenMP construct
2795       // that can appear in the simd region.
2796       SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_simd);
2797       return true;
2798     }
2799     if (ParentRegion == OMPD_atomic) {
2800       // OpenMP [2.16, Nesting of Regions]
2801       // OpenMP constructs may not be nested inside an atomic region.
2802       SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
2803       return true;
2804     }
2805     if (CurrentRegion == OMPD_section) {
2806       // OpenMP [2.7.2, sections Construct, Restrictions]
2807       // Orphaned section directives are prohibited. That is, the section
2808       // directives must appear within the sections construct and must not be
2809       // encountered elsewhere in the sections region.
2810       if (ParentRegion != OMPD_sections &&
2811           ParentRegion != OMPD_parallel_sections) {
2812         SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
2813             << (ParentRegion != OMPD_unknown)
2814             << getOpenMPDirectiveName(ParentRegion);
2815         return true;
2816       }
2817       return false;
2818     }
2819     // Allow some constructs to be orphaned (they could be used in functions,
2820     // called from OpenMP regions with the required preconditions).
2821     if (ParentRegion == OMPD_unknown)
2822       return false;
2823     if (CurrentRegion == OMPD_cancellation_point ||
2824         CurrentRegion == OMPD_cancel) {
2825       // OpenMP [2.16, Nesting of Regions]
2826       // A cancellation point construct for which construct-type-clause is
2827       // taskgroup must be nested inside a task construct. A cancellation
2828       // point construct for which construct-type-clause is not taskgroup must
2829       // be closely nested inside an OpenMP construct that matches the type
2830       // specified in construct-type-clause.
2831       // A cancel construct for which construct-type-clause is taskgroup must be
2832       // nested inside a task construct. A cancel construct for which
2833       // construct-type-clause is not taskgroup must be closely nested inside an
2834       // OpenMP construct that matches the type specified in
2835       // construct-type-clause.
2836       NestingProhibited =
2837           !((CancelRegion == OMPD_parallel &&
2838              (ParentRegion == OMPD_parallel ||
2839               ParentRegion == OMPD_target_parallel)) ||
2840             (CancelRegion == OMPD_for &&
2841              (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
2842               ParentRegion == OMPD_target_parallel_for)) ||
2843             (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
2844             (CancelRegion == OMPD_sections &&
2845              (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
2846               ParentRegion == OMPD_parallel_sections)));
2847     } else if (CurrentRegion == OMPD_master) {
2848       // OpenMP [2.16, Nesting of Regions]
2849       // A master region may not be closely nested inside a worksharing,
2850       // atomic, or explicit task region.
2851       NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2852                           isOpenMPTaskingDirective(ParentRegion);
2853     } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
2854       // OpenMP [2.16, Nesting of Regions]
2855       // A critical region may not be nested (closely or otherwise) inside a
2856       // critical region with the same name. Note that this restriction is not
2857       // sufficient to prevent deadlock.
2858       SourceLocation PreviousCriticalLoc;
2859       bool DeadLock =
2860           Stack->hasDirective([CurrentName, &PreviousCriticalLoc](
2861                                   OpenMPDirectiveKind K,
2862                                   const DeclarationNameInfo &DNI,
2863                                   SourceLocation Loc)
2864                                   ->bool {
2865                                 if (K == OMPD_critical &&
2866                                     DNI.getName() == CurrentName.getName()) {
2867                                   PreviousCriticalLoc = Loc;
2868                                   return true;
2869                                 } else
2870                                   return false;
2871                               },
2872                               false /* skip top directive */);
2873       if (DeadLock) {
2874         SemaRef.Diag(StartLoc,
2875                      diag::err_omp_prohibited_region_critical_same_name)
2876             << CurrentName.getName();
2877         if (PreviousCriticalLoc.isValid())
2878           SemaRef.Diag(PreviousCriticalLoc,
2879                        diag::note_omp_previous_critical_region);
2880         return true;
2881       }
2882     } else if (CurrentRegion == OMPD_barrier) {
2883       // OpenMP [2.16, Nesting of Regions]
2884       // A barrier region may not be closely nested inside a worksharing,
2885       // explicit task, critical, ordered, atomic, or master region.
2886       NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2887                           isOpenMPTaskingDirective(ParentRegion) ||
2888                           ParentRegion == OMPD_master ||
2889                           ParentRegion == OMPD_critical ||
2890                           ParentRegion == OMPD_ordered;
2891     } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
2892                !isOpenMPParallelDirective(CurrentRegion)) {
2893       // OpenMP [2.16, Nesting of Regions]
2894       // A worksharing region may not be closely nested inside a worksharing,
2895       // explicit task, critical, ordered, atomic, or master region.
2896       NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2897                           isOpenMPTaskingDirective(ParentRegion) ||
2898                           ParentRegion == OMPD_master ||
2899                           ParentRegion == OMPD_critical ||
2900                           ParentRegion == OMPD_ordered;
2901       Recommend = ShouldBeInParallelRegion;
2902     } else if (CurrentRegion == OMPD_ordered) {
2903       // OpenMP [2.16, Nesting of Regions]
2904       // An ordered region may not be closely nested inside a critical,
2905       // atomic, or explicit task region.
2906       // An ordered region must be closely nested inside a loop region (or
2907       // parallel loop region) with an ordered clause.
2908       // OpenMP [2.8.1,simd Construct, Restrictions]
2909       // An ordered construct with the simd clause is the only OpenMP construct
2910       // that can appear in the simd region.
2911       NestingProhibited = ParentRegion == OMPD_critical ||
2912                           isOpenMPTaskingDirective(ParentRegion) ||
2913                           !(isOpenMPSimdDirective(ParentRegion) ||
2914                             Stack->isParentOrderedRegion());
2915       Recommend = ShouldBeInOrderedRegion;
2916     } else if (isOpenMPTeamsDirective(CurrentRegion)) {
2917       // OpenMP [2.16, Nesting of Regions]
2918       // If specified, a teams construct must be contained within a target
2919       // construct.
2920       NestingProhibited = ParentRegion != OMPD_target;
2921       Recommend = ShouldBeInTargetRegion;
2922       Stack->setParentTeamsRegionLoc(Stack->getConstructLoc());
2923     }
2924     if (!NestingProhibited && isOpenMPTeamsDirective(ParentRegion)) {
2925       // OpenMP [2.16, Nesting of Regions]
2926       // distribute, parallel, parallel sections, parallel workshare, and the
2927       // parallel loop and parallel loop SIMD constructs are the only OpenMP
2928       // constructs that can be closely nested in the teams region.
2929       NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
2930                           !isOpenMPDistributeDirective(CurrentRegion);
2931       Recommend = ShouldBeInParallelRegion;
2932     }
2933     if (!NestingProhibited && isOpenMPDistributeDirective(CurrentRegion)) {
2934       // OpenMP 4.5 [2.17 Nesting of Regions]
2935       // The region associated with the distribute construct must be strictly
2936       // nested inside a teams region
2937       NestingProhibited = !isOpenMPTeamsDirective(ParentRegion);
2938       Recommend = ShouldBeInTeamsRegion;
2939     }
2940     if (!NestingProhibited &&
2941         (isOpenMPTargetExecutionDirective(CurrentRegion) ||
2942          isOpenMPTargetDataManagementDirective(CurrentRegion))) {
2943       // OpenMP 4.5 [2.17 Nesting of Regions]
2944       // If a target, target update, target data, target enter data, or
2945       // target exit data construct is encountered during execution of a
2946       // target region, the behavior is unspecified.
2947       NestingProhibited = Stack->hasDirective(
2948           [&OffendingRegion](OpenMPDirectiveKind K,
2949                              const DeclarationNameInfo &DNI,
2950                              SourceLocation Loc) -> bool {
2951             if (isOpenMPTargetExecutionDirective(K)) {
2952               OffendingRegion = K;
2953               return true;
2954             } else
2955               return false;
2956           },
2957           false /* don't skip top directive */);
2958       CloseNesting = false;
2959     }
2960     if (NestingProhibited) {
2961       SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
2962           << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
2963           << Recommend << getOpenMPDirectiveName(CurrentRegion);
2964       return true;
2965     }
2966   }
2967   return false;
2968 }
2969 
2970 static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
2971                            ArrayRef<OMPClause *> Clauses,
2972                            ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
2973   bool ErrorFound = false;
2974   unsigned NamedModifiersNumber = 0;
2975   SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
2976       OMPD_unknown + 1);
2977   SmallVector<SourceLocation, 4> NameModifierLoc;
2978   for (const auto *C : Clauses) {
2979     if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
2980       // At most one if clause without a directive-name-modifier can appear on
2981       // the directive.
2982       OpenMPDirectiveKind CurNM = IC->getNameModifier();
2983       if (FoundNameModifiers[CurNM]) {
2984         S.Diag(C->getLocStart(), diag::err_omp_more_one_clause)
2985             << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
2986             << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
2987         ErrorFound = true;
2988       } else if (CurNM != OMPD_unknown) {
2989         NameModifierLoc.push_back(IC->getNameModifierLoc());
2990         ++NamedModifiersNumber;
2991       }
2992       FoundNameModifiers[CurNM] = IC;
2993       if (CurNM == OMPD_unknown)
2994         continue;
2995       // Check if the specified name modifier is allowed for the current
2996       // directive.
2997       // At most one if clause with the particular directive-name-modifier can
2998       // appear on the directive.
2999       bool MatchFound = false;
3000       for (auto NM : AllowedNameModifiers) {
3001         if (CurNM == NM) {
3002           MatchFound = true;
3003           break;
3004         }
3005       }
3006       if (!MatchFound) {
3007         S.Diag(IC->getNameModifierLoc(),
3008                diag::err_omp_wrong_if_directive_name_modifier)
3009             << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
3010         ErrorFound = true;
3011       }
3012     }
3013   }
3014   // If any if clause on the directive includes a directive-name-modifier then
3015   // all if clauses on the directive must include a directive-name-modifier.
3016   if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
3017     if (NamedModifiersNumber == AllowedNameModifiers.size()) {
3018       S.Diag(FoundNameModifiers[OMPD_unknown]->getLocStart(),
3019              diag::err_omp_no_more_if_clause);
3020     } else {
3021       std::string Values;
3022       std::string Sep(", ");
3023       unsigned AllowedCnt = 0;
3024       unsigned TotalAllowedNum =
3025           AllowedNameModifiers.size() - NamedModifiersNumber;
3026       for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
3027            ++Cnt) {
3028         OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
3029         if (!FoundNameModifiers[NM]) {
3030           Values += "'";
3031           Values += getOpenMPDirectiveName(NM);
3032           Values += "'";
3033           if (AllowedCnt + 2 == TotalAllowedNum)
3034             Values += " or ";
3035           else if (AllowedCnt + 1 != TotalAllowedNum)
3036             Values += Sep;
3037           ++AllowedCnt;
3038         }
3039       }
3040       S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getLocStart(),
3041              diag::err_omp_unnamed_if_clause)
3042           << (TotalAllowedNum > 1) << Values;
3043     }
3044     for (auto Loc : NameModifierLoc) {
3045       S.Diag(Loc, diag::note_omp_previous_named_if_clause);
3046     }
3047     ErrorFound = true;
3048   }
3049   return ErrorFound;
3050 }
3051 
3052 StmtResult Sema::ActOnOpenMPExecutableDirective(
3053     OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
3054     OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
3055     Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
3056   StmtResult Res = StmtError();
3057   if (CheckNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
3058                             StartLoc))
3059     return StmtError();
3060 
3061   llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
3062   llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
3063   bool ErrorFound = false;
3064   ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
3065   if (AStmt) {
3066     assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
3067 
3068     // Check default data sharing attributes for referenced variables.
3069     DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
3070     DSAChecker.Visit(cast<CapturedStmt>(AStmt)->getCapturedStmt());
3071     if (DSAChecker.isErrorFound())
3072       return StmtError();
3073     // Generate list of implicitly defined firstprivate variables.
3074     VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
3075 
3076     if (!DSAChecker.getImplicitFirstprivate().empty()) {
3077       if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
3078               DSAChecker.getImplicitFirstprivate(), SourceLocation(),
3079               SourceLocation(), SourceLocation())) {
3080         ClausesWithImplicit.push_back(Implicit);
3081         ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
3082                      DSAChecker.getImplicitFirstprivate().size();
3083       } else
3084         ErrorFound = true;
3085     }
3086   }
3087 
3088   llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
3089   switch (Kind) {
3090   case OMPD_parallel:
3091     Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
3092                                        EndLoc);
3093     AllowedNameModifiers.push_back(OMPD_parallel);
3094     break;
3095   case OMPD_simd:
3096     Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
3097                                    VarsWithInheritedDSA);
3098     break;
3099   case OMPD_for:
3100     Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
3101                                   VarsWithInheritedDSA);
3102     break;
3103   case OMPD_for_simd:
3104     Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3105                                       EndLoc, VarsWithInheritedDSA);
3106     break;
3107   case OMPD_sections:
3108     Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
3109                                        EndLoc);
3110     break;
3111   case OMPD_section:
3112     assert(ClausesWithImplicit.empty() &&
3113            "No clauses are allowed for 'omp section' directive");
3114     Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
3115     break;
3116   case OMPD_single:
3117     Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
3118                                      EndLoc);
3119     break;
3120   case OMPD_master:
3121     assert(ClausesWithImplicit.empty() &&
3122            "No clauses are allowed for 'omp master' directive");
3123     Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
3124     break;
3125   case OMPD_critical:
3126     Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
3127                                        StartLoc, EndLoc);
3128     break;
3129   case OMPD_parallel_for:
3130     Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
3131                                           EndLoc, VarsWithInheritedDSA);
3132     AllowedNameModifiers.push_back(OMPD_parallel);
3133     break;
3134   case OMPD_parallel_for_simd:
3135     Res = ActOnOpenMPParallelForSimdDirective(
3136         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3137     AllowedNameModifiers.push_back(OMPD_parallel);
3138     break;
3139   case OMPD_parallel_sections:
3140     Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
3141                                                StartLoc, EndLoc);
3142     AllowedNameModifiers.push_back(OMPD_parallel);
3143     break;
3144   case OMPD_task:
3145     Res =
3146         ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
3147     AllowedNameModifiers.push_back(OMPD_task);
3148     break;
3149   case OMPD_taskyield:
3150     assert(ClausesWithImplicit.empty() &&
3151            "No clauses are allowed for 'omp taskyield' directive");
3152     assert(AStmt == nullptr &&
3153            "No associated statement allowed for 'omp taskyield' directive");
3154     Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
3155     break;
3156   case OMPD_barrier:
3157     assert(ClausesWithImplicit.empty() &&
3158            "No clauses are allowed for 'omp barrier' directive");
3159     assert(AStmt == nullptr &&
3160            "No associated statement allowed for 'omp barrier' directive");
3161     Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
3162     break;
3163   case OMPD_taskwait:
3164     assert(ClausesWithImplicit.empty() &&
3165            "No clauses are allowed for 'omp taskwait' directive");
3166     assert(AStmt == nullptr &&
3167            "No associated statement allowed for 'omp taskwait' directive");
3168     Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
3169     break;
3170   case OMPD_taskgroup:
3171     assert(ClausesWithImplicit.empty() &&
3172            "No clauses are allowed for 'omp taskgroup' directive");
3173     Res = ActOnOpenMPTaskgroupDirective(AStmt, StartLoc, EndLoc);
3174     break;
3175   case OMPD_flush:
3176     assert(AStmt == nullptr &&
3177            "No associated statement allowed for 'omp flush' directive");
3178     Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
3179     break;
3180   case OMPD_ordered:
3181     Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
3182                                       EndLoc);
3183     break;
3184   case OMPD_atomic:
3185     Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
3186                                      EndLoc);
3187     break;
3188   case OMPD_teams:
3189     Res =
3190         ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
3191     break;
3192   case OMPD_target:
3193     Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
3194                                      EndLoc);
3195     AllowedNameModifiers.push_back(OMPD_target);
3196     break;
3197   case OMPD_target_parallel:
3198     Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
3199                                              StartLoc, EndLoc);
3200     AllowedNameModifiers.push_back(OMPD_target);
3201     AllowedNameModifiers.push_back(OMPD_parallel);
3202     break;
3203   case OMPD_target_parallel_for:
3204     Res = ActOnOpenMPTargetParallelForDirective(
3205         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3206     AllowedNameModifiers.push_back(OMPD_target);
3207     AllowedNameModifiers.push_back(OMPD_parallel);
3208     break;
3209   case OMPD_cancellation_point:
3210     assert(ClausesWithImplicit.empty() &&
3211            "No clauses are allowed for 'omp cancellation point' directive");
3212     assert(AStmt == nullptr && "No associated statement allowed for 'omp "
3213                                "cancellation point' directive");
3214     Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
3215     break;
3216   case OMPD_cancel:
3217     assert(AStmt == nullptr &&
3218            "No associated statement allowed for 'omp cancel' directive");
3219     Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
3220                                      CancelRegion);
3221     AllowedNameModifiers.push_back(OMPD_cancel);
3222     break;
3223   case OMPD_target_data:
3224     Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
3225                                          EndLoc);
3226     AllowedNameModifiers.push_back(OMPD_target_data);
3227     break;
3228   case OMPD_target_enter_data:
3229     Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
3230                                               EndLoc);
3231     AllowedNameModifiers.push_back(OMPD_target_enter_data);
3232     break;
3233   case OMPD_target_exit_data:
3234     Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
3235                                              EndLoc);
3236     AllowedNameModifiers.push_back(OMPD_target_exit_data);
3237     break;
3238   case OMPD_taskloop:
3239     Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
3240                                        EndLoc, VarsWithInheritedDSA);
3241     AllowedNameModifiers.push_back(OMPD_taskloop);
3242     break;
3243   case OMPD_taskloop_simd:
3244     Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3245                                            EndLoc, VarsWithInheritedDSA);
3246     AllowedNameModifiers.push_back(OMPD_taskloop);
3247     break;
3248   case OMPD_distribute:
3249     Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
3250                                          EndLoc, VarsWithInheritedDSA);
3251     break;
3252   case OMPD_declare_target:
3253   case OMPD_end_declare_target:
3254   case OMPD_threadprivate:
3255   case OMPD_declare_reduction:
3256   case OMPD_declare_simd:
3257     llvm_unreachable("OpenMP Directive is not allowed");
3258   case OMPD_unknown:
3259     llvm_unreachable("Unknown OpenMP directive");
3260   }
3261 
3262   for (auto P : VarsWithInheritedDSA) {
3263     Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
3264         << P.first << P.second->getSourceRange();
3265   }
3266   ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound;
3267 
3268   if (!AllowedNameModifiers.empty())
3269     ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
3270                  ErrorFound;
3271 
3272   if (ErrorFound)
3273     return StmtError();
3274   return Res;
3275 }
3276 
3277 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
3278     DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
3279     ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
3280     ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
3281     ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
3282   assert(Aligneds.size() == Alignments.size());
3283   assert(Linears.size() == LinModifiers.size());
3284   assert(Linears.size() == Steps.size());
3285   if (!DG || DG.get().isNull())
3286     return DeclGroupPtrTy();
3287 
3288   if (!DG.get().isSingleDecl()) {
3289     Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd);
3290     return DG;
3291   }
3292   auto *ADecl = DG.get().getSingleDecl();
3293   if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
3294     ADecl = FTD->getTemplatedDecl();
3295 
3296   auto *FD = dyn_cast<FunctionDecl>(ADecl);
3297   if (!FD) {
3298     Diag(ADecl->getLocation(), diag::err_omp_function_expected);
3299     return DeclGroupPtrTy();
3300   }
3301 
3302   // OpenMP [2.8.2, declare simd construct, Description]
3303   // The parameter of the simdlen clause must be a constant positive integer
3304   // expression.
3305   ExprResult SL;
3306   if (Simdlen)
3307     SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
3308   // OpenMP [2.8.2, declare simd construct, Description]
3309   // The special this pointer can be used as if was one of the arguments to the
3310   // function in any of the linear, aligned, or uniform clauses.
3311   // The uniform clause declares one or more arguments to have an invariant
3312   // value for all concurrent invocations of the function in the execution of a
3313   // single SIMD loop.
3314   llvm::DenseMap<Decl *, Expr *> UniformedArgs;
3315   Expr *UniformedLinearThis = nullptr;
3316   for (auto *E : Uniforms) {
3317     E = E->IgnoreParenImpCasts();
3318     if (auto *DRE = dyn_cast<DeclRefExpr>(E))
3319       if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
3320         if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
3321             FD->getParamDecl(PVD->getFunctionScopeIndex())
3322                     ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
3323           UniformedArgs.insert(std::make_pair(PVD->getCanonicalDecl(), E));
3324           continue;
3325         }
3326     if (isa<CXXThisExpr>(E)) {
3327       UniformedLinearThis = E;
3328       continue;
3329     }
3330     Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3331         << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
3332   }
3333   // OpenMP [2.8.2, declare simd construct, Description]
3334   // The aligned clause declares that the object to which each list item points
3335   // is aligned to the number of bytes expressed in the optional parameter of
3336   // the aligned clause.
3337   // The special this pointer can be used as if was one of the arguments to the
3338   // function in any of the linear, aligned, or uniform clauses.
3339   // The type of list items appearing in the aligned clause must be array,
3340   // pointer, reference to array, or reference to pointer.
3341   llvm::DenseMap<Decl *, Expr *> AlignedArgs;
3342   Expr *AlignedThis = nullptr;
3343   for (auto *E : Aligneds) {
3344     E = E->IgnoreParenImpCasts();
3345     if (auto *DRE = dyn_cast<DeclRefExpr>(E))
3346       if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3347         auto *CanonPVD = PVD->getCanonicalDecl();
3348         if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
3349             FD->getParamDecl(PVD->getFunctionScopeIndex())
3350                     ->getCanonicalDecl() == CanonPVD) {
3351           // OpenMP  [2.8.1, simd construct, Restrictions]
3352           // A list-item cannot appear in more than one aligned clause.
3353           if (AlignedArgs.count(CanonPVD) > 0) {
3354             Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
3355                 << 1 << E->getSourceRange();
3356             Diag(AlignedArgs[CanonPVD]->getExprLoc(),
3357                  diag::note_omp_explicit_dsa)
3358                 << getOpenMPClauseName(OMPC_aligned);
3359             continue;
3360           }
3361           AlignedArgs[CanonPVD] = E;
3362           QualType QTy = PVD->getType()
3363                              .getNonReferenceType()
3364                              .getUnqualifiedType()
3365                              .getCanonicalType();
3366           const Type *Ty = QTy.getTypePtrOrNull();
3367           if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
3368             Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
3369                 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
3370             Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
3371           }
3372           continue;
3373         }
3374       }
3375     if (isa<CXXThisExpr>(E)) {
3376       if (AlignedThis) {
3377         Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
3378             << 2 << E->getSourceRange();
3379         Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
3380             << getOpenMPClauseName(OMPC_aligned);
3381       }
3382       AlignedThis = E;
3383       continue;
3384     }
3385     Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3386         << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
3387   }
3388   // The optional parameter of the aligned clause, alignment, must be a constant
3389   // positive integer expression. If no optional parameter is specified,
3390   // implementation-defined default alignments for SIMD instructions on the
3391   // target platforms are assumed.
3392   SmallVector<Expr *, 4> NewAligns;
3393   for (auto *E : Alignments) {
3394     ExprResult Align;
3395     if (E)
3396       Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
3397     NewAligns.push_back(Align.get());
3398   }
3399   // OpenMP [2.8.2, declare simd construct, Description]
3400   // The linear clause declares one or more list items to be private to a SIMD
3401   // lane and to have a linear relationship with respect to the iteration space
3402   // of a loop.
3403   // The special this pointer can be used as if was one of the arguments to the
3404   // function in any of the linear, aligned, or uniform clauses.
3405   // When a linear-step expression is specified in a linear clause it must be
3406   // either a constant integer expression or an integer-typed parameter that is
3407   // specified in a uniform clause on the directive.
3408   llvm::DenseMap<Decl *, Expr *> LinearArgs;
3409   const bool IsUniformedThis = UniformedLinearThis != nullptr;
3410   auto MI = LinModifiers.begin();
3411   for (auto *E : Linears) {
3412     auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
3413     ++MI;
3414     E = E->IgnoreParenImpCasts();
3415     if (auto *DRE = dyn_cast<DeclRefExpr>(E))
3416       if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3417         auto *CanonPVD = PVD->getCanonicalDecl();
3418         if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
3419             FD->getParamDecl(PVD->getFunctionScopeIndex())
3420                     ->getCanonicalDecl() == CanonPVD) {
3421           // OpenMP  [2.15.3.7, linear Clause, Restrictions]
3422           // A list-item cannot appear in more than one linear clause.
3423           if (LinearArgs.count(CanonPVD) > 0) {
3424             Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3425                 << getOpenMPClauseName(OMPC_linear)
3426                 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
3427             Diag(LinearArgs[CanonPVD]->getExprLoc(),
3428                  diag::note_omp_explicit_dsa)
3429                 << getOpenMPClauseName(OMPC_linear);
3430             continue;
3431           }
3432           // Each argument can appear in at most one uniform or linear clause.
3433           if (UniformedArgs.count(CanonPVD) > 0) {
3434             Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3435                 << getOpenMPClauseName(OMPC_linear)
3436                 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
3437             Diag(UniformedArgs[CanonPVD]->getExprLoc(),
3438                  diag::note_omp_explicit_dsa)
3439                 << getOpenMPClauseName(OMPC_uniform);
3440             continue;
3441           }
3442           LinearArgs[CanonPVD] = E;
3443           if (E->isValueDependent() || E->isTypeDependent() ||
3444               E->isInstantiationDependent() ||
3445               E->containsUnexpandedParameterPack())
3446             continue;
3447           (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
3448                                       PVD->getOriginalType());
3449           continue;
3450         }
3451       }
3452     if (isa<CXXThisExpr>(E)) {
3453       if (UniformedLinearThis) {
3454         Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3455             << getOpenMPClauseName(OMPC_linear)
3456             << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
3457             << E->getSourceRange();
3458         Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
3459             << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
3460                                                    : OMPC_linear);
3461         continue;
3462       }
3463       UniformedLinearThis = E;
3464       if (E->isValueDependent() || E->isTypeDependent() ||
3465           E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
3466         continue;
3467       (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
3468                                   E->getType());
3469       continue;
3470     }
3471     Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3472         << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
3473   }
3474   Expr *Step = nullptr;
3475   Expr *NewStep = nullptr;
3476   SmallVector<Expr *, 4> NewSteps;
3477   for (auto *E : Steps) {
3478     // Skip the same step expression, it was checked already.
3479     if (Step == E || !E) {
3480       NewSteps.push_back(E ? NewStep : nullptr);
3481       continue;
3482     }
3483     Step = E;
3484     if (auto *DRE = dyn_cast<DeclRefExpr>(Step))
3485       if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3486         auto *CanonPVD = PVD->getCanonicalDecl();
3487         if (UniformedArgs.count(CanonPVD) == 0) {
3488           Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
3489               << Step->getSourceRange();
3490         } else if (E->isValueDependent() || E->isTypeDependent() ||
3491                    E->isInstantiationDependent() ||
3492                    E->containsUnexpandedParameterPack() ||
3493                    CanonPVD->getType()->hasIntegerRepresentation())
3494           NewSteps.push_back(Step);
3495         else {
3496           Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
3497               << Step->getSourceRange();
3498         }
3499         continue;
3500       }
3501     NewStep = Step;
3502     if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
3503         !Step->isInstantiationDependent() &&
3504         !Step->containsUnexpandedParameterPack()) {
3505       NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
3506                     .get();
3507       if (NewStep)
3508         NewStep = VerifyIntegerConstantExpression(NewStep).get();
3509     }
3510     NewSteps.push_back(NewStep);
3511   }
3512   auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
3513       Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
3514       Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
3515       const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
3516       const_cast<Expr **>(Linears.data()), Linears.size(),
3517       const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
3518       NewSteps.data(), NewSteps.size(), SR);
3519   ADecl->addAttr(NewAttr);
3520   return ConvertDeclToDeclGroup(ADecl);
3521 }
3522 
3523 StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
3524                                               Stmt *AStmt,
3525                                               SourceLocation StartLoc,
3526                                               SourceLocation EndLoc) {
3527   if (!AStmt)
3528     return StmtError();
3529 
3530   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
3531   // 1.2.2 OpenMP Language Terminology
3532   // Structured block - An executable statement with a single entry at the
3533   // top and a single exit at the bottom.
3534   // The point of exit cannot be a branch out of the structured block.
3535   // longjmp() and throw() must not violate the entry/exit criteria.
3536   CS->getCapturedDecl()->setNothrow();
3537 
3538   getCurFunction()->setHasBranchProtectedScope();
3539 
3540   return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
3541                                       DSAStack->isCancelRegion());
3542 }
3543 
3544 namespace {
3545 /// \brief Helper class for checking canonical form of the OpenMP loops and
3546 /// extracting iteration space of each loop in the loop nest, that will be used
3547 /// for IR generation.
3548 class OpenMPIterationSpaceChecker {
3549   /// \brief Reference to Sema.
3550   Sema &SemaRef;
3551   /// \brief A location for diagnostics (when there is no some better location).
3552   SourceLocation DefaultLoc;
3553   /// \brief A location for diagnostics (when increment is not compatible).
3554   SourceLocation ConditionLoc;
3555   /// \brief A source location for referring to loop init later.
3556   SourceRange InitSrcRange;
3557   /// \brief A source location for referring to condition later.
3558   SourceRange ConditionSrcRange;
3559   /// \brief A source location for referring to increment later.
3560   SourceRange IncrementSrcRange;
3561   /// \brief Loop variable.
3562   ValueDecl *LCDecl = nullptr;
3563   /// \brief Reference to loop variable.
3564   Expr *LCRef = nullptr;
3565   /// \brief Lower bound (initializer for the var).
3566   Expr *LB = nullptr;
3567   /// \brief Upper bound.
3568   Expr *UB = nullptr;
3569   /// \brief Loop step (increment).
3570   Expr *Step = nullptr;
3571   /// \brief This flag is true when condition is one of:
3572   ///   Var <  UB
3573   ///   Var <= UB
3574   ///   UB  >  Var
3575   ///   UB  >= Var
3576   bool TestIsLessOp = false;
3577   /// \brief This flag is true when condition is strict ( < or > ).
3578   bool TestIsStrictOp = false;
3579   /// \brief This flag is true when step is subtracted on each iteration.
3580   bool SubtractStep = false;
3581 
3582 public:
3583   OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
3584       : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {}
3585   /// \brief Check init-expr for canonical loop form and save loop counter
3586   /// variable - #Var and its initialization value - #LB.
3587   bool CheckInit(Stmt *S, bool EmitDiags = true);
3588   /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags
3589   /// for less/greater and for strict/non-strict comparison.
3590   bool CheckCond(Expr *S);
3591   /// \brief Check incr-expr for canonical loop form and return true if it
3592   /// does not conform, otherwise save loop step (#Step).
3593   bool CheckInc(Expr *S);
3594   /// \brief Return the loop counter variable.
3595   ValueDecl *GetLoopDecl() const { return LCDecl; }
3596   /// \brief Return the reference expression to loop counter variable.
3597   Expr *GetLoopDeclRefExpr() const { return LCRef; }
3598   /// \brief Source range of the loop init.
3599   SourceRange GetInitSrcRange() const { return InitSrcRange; }
3600   /// \brief Source range of the loop condition.
3601   SourceRange GetConditionSrcRange() const { return ConditionSrcRange; }
3602   /// \brief Source range of the loop increment.
3603   SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; }
3604   /// \brief True if the step should be subtracted.
3605   bool ShouldSubtractStep() const { return SubtractStep; }
3606   /// \brief Build the expression to calculate the number of iterations.
3607   Expr *
3608   BuildNumIterations(Scope *S, const bool LimitedType,
3609                      llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
3610   /// \brief Build the precondition expression for the loops.
3611   Expr *BuildPreCond(Scope *S, Expr *Cond,
3612                      llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
3613   /// \brief Build reference expression to the counter be used for codegen.
3614   DeclRefExpr *BuildCounterVar(llvm::MapVector<Expr *, DeclRefExpr *> &Captures,
3615                                DSAStackTy &DSA) const;
3616   /// \brief Build reference expression to the private counter be used for
3617   /// codegen.
3618   Expr *BuildPrivateCounterVar() const;
3619   /// \brief Build initization of the counter be used for codegen.
3620   Expr *BuildCounterInit() const;
3621   /// \brief Build step of the counter be used for codegen.
3622   Expr *BuildCounterStep() const;
3623   /// \brief Return true if any expression is dependent.
3624   bool Dependent() const;
3625 
3626 private:
3627   /// \brief Check the right-hand side of an assignment in the increment
3628   /// expression.
3629   bool CheckIncRHS(Expr *RHS);
3630   /// \brief Helper to set loop counter variable and its initializer.
3631   bool SetLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB);
3632   /// \brief Helper to set upper bound.
3633   bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, SourceRange SR,
3634              SourceLocation SL);
3635   /// \brief Helper to set loop increment.
3636   bool SetStep(Expr *NewStep, bool Subtract);
3637 };
3638 
3639 bool OpenMPIterationSpaceChecker::Dependent() const {
3640   if (!LCDecl) {
3641     assert(!LB && !UB && !Step);
3642     return false;
3643   }
3644   return LCDecl->getType()->isDependentType() ||
3645          (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
3646          (Step && Step->isValueDependent());
3647 }
3648 
3649 static Expr *getExprAsWritten(Expr *E) {
3650   if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(E))
3651     E = ExprTemp->getSubExpr();
3652 
3653   if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
3654     E = MTE->GetTemporaryExpr();
3655 
3656   while (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
3657     E = Binder->getSubExpr();
3658 
3659   if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
3660     E = ICE->getSubExprAsWritten();
3661   return E->IgnoreParens();
3662 }
3663 
3664 bool OpenMPIterationSpaceChecker::SetLCDeclAndLB(ValueDecl *NewLCDecl,
3665                                                  Expr *NewLCRefExpr,
3666                                                  Expr *NewLB) {
3667   // State consistency checking to ensure correct usage.
3668   assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
3669          UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
3670   if (!NewLCDecl || !NewLB)
3671     return true;
3672   LCDecl = getCanonicalDecl(NewLCDecl);
3673   LCRef = NewLCRefExpr;
3674   if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
3675     if (const CXXConstructorDecl *Ctor = CE->getConstructor())
3676       if ((Ctor->isCopyOrMoveConstructor() ||
3677            Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
3678           CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
3679         NewLB = CE->getArg(0)->IgnoreParenImpCasts();
3680   LB = NewLB;
3681   return false;
3682 }
3683 
3684 bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp,
3685                                         SourceRange SR, SourceLocation SL) {
3686   // State consistency checking to ensure correct usage.
3687   assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
3688          Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
3689   if (!NewUB)
3690     return true;
3691   UB = NewUB;
3692   TestIsLessOp = LessOp;
3693   TestIsStrictOp = StrictOp;
3694   ConditionSrcRange = SR;
3695   ConditionLoc = SL;
3696   return false;
3697 }
3698 
3699 bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) {
3700   // State consistency checking to ensure correct usage.
3701   assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
3702   if (!NewStep)
3703     return true;
3704   if (!NewStep->isValueDependent()) {
3705     // Check that the step is integer expression.
3706     SourceLocation StepLoc = NewStep->getLocStart();
3707     ExprResult Val =
3708         SemaRef.PerformOpenMPImplicitIntegerConversion(StepLoc, NewStep);
3709     if (Val.isInvalid())
3710       return true;
3711     NewStep = Val.get();
3712 
3713     // OpenMP [2.6, Canonical Loop Form, Restrictions]
3714     //  If test-expr is of form var relational-op b and relational-op is < or
3715     //  <= then incr-expr must cause var to increase on each iteration of the
3716     //  loop. If test-expr is of form var relational-op b and relational-op is
3717     //  > or >= then incr-expr must cause var to decrease on each iteration of
3718     //  the loop.
3719     //  If test-expr is of form b relational-op var and relational-op is < or
3720     //  <= then incr-expr must cause var to decrease on each iteration of the
3721     //  loop. If test-expr is of form b relational-op var and relational-op is
3722     //  > or >= then incr-expr must cause var to increase on each iteration of
3723     //  the loop.
3724     llvm::APSInt Result;
3725     bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
3726     bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
3727     bool IsConstNeg =
3728         IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
3729     bool IsConstPos =
3730         IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
3731     bool IsConstZero = IsConstant && !Result.getBoolValue();
3732     if (UB && (IsConstZero ||
3733                (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
3734                              : (IsConstPos || (IsUnsigned && !Subtract))))) {
3735       SemaRef.Diag(NewStep->getExprLoc(),
3736                    diag::err_omp_loop_incr_not_compatible)
3737           << LCDecl << TestIsLessOp << NewStep->getSourceRange();
3738       SemaRef.Diag(ConditionLoc,
3739                    diag::note_omp_loop_cond_requres_compatible_incr)
3740           << TestIsLessOp << ConditionSrcRange;
3741       return true;
3742     }
3743     if (TestIsLessOp == Subtract) {
3744       NewStep = SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus,
3745                                              NewStep).get();
3746       Subtract = !Subtract;
3747     }
3748   }
3749 
3750   Step = NewStep;
3751   SubtractStep = Subtract;
3752   return false;
3753 }
3754 
3755 bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S, bool EmitDiags) {
3756   // Check init-expr for canonical loop form and save loop counter
3757   // variable - #Var and its initialization value - #LB.
3758   // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
3759   //   var = lb
3760   //   integer-type var = lb
3761   //   random-access-iterator-type var = lb
3762   //   pointer-type var = lb
3763   //
3764   if (!S) {
3765     if (EmitDiags) {
3766       SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
3767     }
3768     return true;
3769   }
3770   InitSrcRange = S->getSourceRange();
3771   if (Expr *E = dyn_cast<Expr>(S))
3772     S = E->IgnoreParens();
3773   if (auto BO = dyn_cast<BinaryOperator>(S)) {
3774     if (BO->getOpcode() == BO_Assign) {
3775       auto *LHS = BO->getLHS()->IgnoreParens();
3776       if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
3777         if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
3778           if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3779             return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3780         return SetLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS());
3781       }
3782       if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
3783         if (ME->isArrow() &&
3784             isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3785           return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3786       }
3787     }
3788   } else if (auto DS = dyn_cast<DeclStmt>(S)) {
3789     if (DS->isSingleDecl()) {
3790       if (auto Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
3791         if (Var->hasInit() && !Var->getType()->isReferenceType()) {
3792           // Accept non-canonical init form here but emit ext. warning.
3793           if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
3794             SemaRef.Diag(S->getLocStart(),
3795                          diag::ext_omp_loop_not_canonical_init)
3796                 << S->getSourceRange();
3797           return SetLCDeclAndLB(Var, nullptr, Var->getInit());
3798         }
3799       }
3800     }
3801   } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S)) {
3802     if (CE->getOperator() == OO_Equal) {
3803       auto *LHS = CE->getArg(0);
3804       if (auto DRE = dyn_cast<DeclRefExpr>(LHS)) {
3805         if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
3806           if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3807             return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3808         return SetLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1));
3809       }
3810       if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
3811         if (ME->isArrow() &&
3812             isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3813           return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3814       }
3815     }
3816   }
3817 
3818   if (Dependent() || SemaRef.CurContext->isDependentContext())
3819     return false;
3820   if (EmitDiags) {
3821     SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init)
3822         << S->getSourceRange();
3823   }
3824   return true;
3825 }
3826 
3827 /// \brief Ignore parenthesizes, implicit casts, copy constructor and return the
3828 /// variable (which may be the loop variable) if possible.
3829 static const ValueDecl *GetInitLCDecl(Expr *E) {
3830   if (!E)
3831     return nullptr;
3832   E = getExprAsWritten(E);
3833   if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
3834     if (const CXXConstructorDecl *Ctor = CE->getConstructor())
3835       if ((Ctor->isCopyOrMoveConstructor() ||
3836            Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
3837           CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
3838         E = CE->getArg(0)->IgnoreParenImpCasts();
3839   if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
3840     if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
3841       if (auto *CED = dyn_cast<OMPCapturedExprDecl>(VD))
3842         if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3843           return getCanonicalDecl(ME->getMemberDecl());
3844       return getCanonicalDecl(VD);
3845     }
3846   }
3847   if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
3848     if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3849       return getCanonicalDecl(ME->getMemberDecl());
3850   return nullptr;
3851 }
3852 
3853 bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) {
3854   // Check test-expr for canonical form, save upper-bound UB, flags for
3855   // less/greater and for strict/non-strict comparison.
3856   // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3857   //   var relational-op b
3858   //   b relational-op var
3859   //
3860   if (!S) {
3861     SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl;
3862     return true;
3863   }
3864   S = getExprAsWritten(S);
3865   SourceLocation CondLoc = S->getLocStart();
3866   if (auto BO = dyn_cast<BinaryOperator>(S)) {
3867     if (BO->isRelationalOp()) {
3868       if (GetInitLCDecl(BO->getLHS()) == LCDecl)
3869         return SetUB(BO->getRHS(),
3870                      (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
3871                      (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3872                      BO->getSourceRange(), BO->getOperatorLoc());
3873       if (GetInitLCDecl(BO->getRHS()) == LCDecl)
3874         return SetUB(BO->getLHS(),
3875                      (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
3876                      (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3877                      BO->getSourceRange(), BO->getOperatorLoc());
3878     }
3879   } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S)) {
3880     if (CE->getNumArgs() == 2) {
3881       auto Op = CE->getOperator();
3882       switch (Op) {
3883       case OO_Greater:
3884       case OO_GreaterEqual:
3885       case OO_Less:
3886       case OO_LessEqual:
3887         if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
3888           return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
3889                        Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3890                        CE->getOperatorLoc());
3891         if (GetInitLCDecl(CE->getArg(1)) == LCDecl)
3892           return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
3893                        Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3894                        CE->getOperatorLoc());
3895         break;
3896       default:
3897         break;
3898       }
3899     }
3900   }
3901   if (Dependent() || SemaRef.CurContext->isDependentContext())
3902     return false;
3903   SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
3904       << S->getSourceRange() << LCDecl;
3905   return true;
3906 }
3907 
3908 bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) {
3909   // RHS of canonical loop form increment can be:
3910   //   var + incr
3911   //   incr + var
3912   //   var - incr
3913   //
3914   RHS = RHS->IgnoreParenImpCasts();
3915   if (auto BO = dyn_cast<BinaryOperator>(RHS)) {
3916     if (BO->isAdditiveOp()) {
3917       bool IsAdd = BO->getOpcode() == BO_Add;
3918       if (GetInitLCDecl(BO->getLHS()) == LCDecl)
3919         return SetStep(BO->getRHS(), !IsAdd);
3920       if (IsAdd && GetInitLCDecl(BO->getRHS()) == LCDecl)
3921         return SetStep(BO->getLHS(), false);
3922     }
3923   } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
3924     bool IsAdd = CE->getOperator() == OO_Plus;
3925     if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
3926       if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
3927         return SetStep(CE->getArg(1), !IsAdd);
3928       if (IsAdd && GetInitLCDecl(CE->getArg(1)) == LCDecl)
3929         return SetStep(CE->getArg(0), false);
3930     }
3931   }
3932   if (Dependent() || SemaRef.CurContext->isDependentContext())
3933     return false;
3934   SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr)
3935       << RHS->getSourceRange() << LCDecl;
3936   return true;
3937 }
3938 
3939 bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) {
3940   // Check incr-expr for canonical loop form and return true if it
3941   // does not conform.
3942   // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3943   //   ++var
3944   //   var++
3945   //   --var
3946   //   var--
3947   //   var += incr
3948   //   var -= incr
3949   //   var = var + incr
3950   //   var = incr + var
3951   //   var = var - incr
3952   //
3953   if (!S) {
3954     SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
3955     return true;
3956   }
3957   IncrementSrcRange = S->getSourceRange();
3958   S = S->IgnoreParens();
3959   if (auto UO = dyn_cast<UnaryOperator>(S)) {
3960     if (UO->isIncrementDecrementOp() &&
3961         GetInitLCDecl(UO->getSubExpr()) == LCDecl)
3962       return SetStep(
3963           SemaRef.ActOnIntegerConstant(UO->getLocStart(),
3964                                        (UO->isDecrementOp() ? -1 : 1)).get(),
3965           false);
3966   } else if (auto BO = dyn_cast<BinaryOperator>(S)) {
3967     switch (BO->getOpcode()) {
3968     case BO_AddAssign:
3969     case BO_SubAssign:
3970       if (GetInitLCDecl(BO->getLHS()) == LCDecl)
3971         return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
3972       break;
3973     case BO_Assign:
3974       if (GetInitLCDecl(BO->getLHS()) == LCDecl)
3975         return CheckIncRHS(BO->getRHS());
3976       break;
3977     default:
3978       break;
3979     }
3980   } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S)) {
3981     switch (CE->getOperator()) {
3982     case OO_PlusPlus:
3983     case OO_MinusMinus:
3984       if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
3985         return SetStep(
3986             SemaRef.ActOnIntegerConstant(
3987                         CE->getLocStart(),
3988                         ((CE->getOperator() == OO_MinusMinus) ? -1 : 1)).get(),
3989             false);
3990       break;
3991     case OO_PlusEqual:
3992     case OO_MinusEqual:
3993       if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
3994         return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
3995       break;
3996     case OO_Equal:
3997       if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
3998         return CheckIncRHS(CE->getArg(1));
3999       break;
4000     default:
4001       break;
4002     }
4003   }
4004   if (Dependent() || SemaRef.CurContext->isDependentContext())
4005     return false;
4006   SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr)
4007       << S->getSourceRange() << LCDecl;
4008   return true;
4009 }
4010 
4011 static ExprResult
4012 tryBuildCapture(Sema &SemaRef, Expr *Capture,
4013                 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
4014   if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
4015     return SemaRef.PerformImplicitConversion(
4016         Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
4017         /*AllowExplicit=*/true);
4018   auto I = Captures.find(Capture);
4019   if (I != Captures.end())
4020     return buildCapture(SemaRef, Capture, I->second);
4021   DeclRefExpr *Ref = nullptr;
4022   ExprResult Res = buildCapture(SemaRef, Capture, Ref);
4023   Captures[Capture] = Ref;
4024   return Res;
4025 }
4026 
4027 /// \brief Build the expression to calculate the number of iterations.
4028 Expr *OpenMPIterationSpaceChecker::BuildNumIterations(
4029     Scope *S, const bool LimitedType,
4030     llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
4031   ExprResult Diff;
4032   auto VarType = LCDecl->getType().getNonReferenceType();
4033   if (VarType->isIntegerType() || VarType->isPointerType() ||
4034       SemaRef.getLangOpts().CPlusPlus) {
4035     // Upper - Lower
4036     auto *UBExpr = TestIsLessOp ? UB : LB;
4037     auto *LBExpr = TestIsLessOp ? LB : UB;
4038     Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
4039     Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
4040     if (!Upper || !Lower)
4041       return nullptr;
4042 
4043     Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
4044 
4045     if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
4046       // BuildBinOp already emitted error, this one is to point user to upper
4047       // and lower bound, and to tell what is passed to 'operator-'.
4048       SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx)
4049           << Upper->getSourceRange() << Lower->getSourceRange();
4050       return nullptr;
4051     }
4052   }
4053 
4054   if (!Diff.isUsable())
4055     return nullptr;
4056 
4057   // Upper - Lower [- 1]
4058   if (TestIsStrictOp)
4059     Diff = SemaRef.BuildBinOp(
4060         S, DefaultLoc, BO_Sub, Diff.get(),
4061         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4062   if (!Diff.isUsable())
4063     return nullptr;
4064 
4065   // Upper - Lower [- 1] + Step
4066   auto NewStep = tryBuildCapture(SemaRef, Step, Captures);
4067   if (!NewStep.isUsable())
4068     return nullptr;
4069   Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
4070   if (!Diff.isUsable())
4071     return nullptr;
4072 
4073   // Parentheses (for dumping/debugging purposes only).
4074   Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
4075   if (!Diff.isUsable())
4076     return nullptr;
4077 
4078   // (Upper - Lower [- 1] + Step) / Step
4079   Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
4080   if (!Diff.isUsable())
4081     return nullptr;
4082 
4083   // OpenMP runtime requires 32-bit or 64-bit loop variables.
4084   QualType Type = Diff.get()->getType();
4085   auto &C = SemaRef.Context;
4086   bool UseVarType = VarType->hasIntegerRepresentation() &&
4087                     C.getTypeSize(Type) > C.getTypeSize(VarType);
4088   if (!Type->isIntegerType() || UseVarType) {
4089     unsigned NewSize =
4090         UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
4091     bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
4092                                : Type->hasSignedIntegerRepresentation();
4093     Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
4094     if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
4095       Diff = SemaRef.PerformImplicitConversion(
4096           Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
4097       if (!Diff.isUsable())
4098         return nullptr;
4099     }
4100   }
4101   if (LimitedType) {
4102     unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
4103     if (NewSize != C.getTypeSize(Type)) {
4104       if (NewSize < C.getTypeSize(Type)) {
4105         assert(NewSize == 64 && "incorrect loop var size");
4106         SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
4107             << InitSrcRange << ConditionSrcRange;
4108       }
4109       QualType NewType = C.getIntTypeForBitwidth(
4110           NewSize, Type->hasSignedIntegerRepresentation() ||
4111                        C.getTypeSize(Type) < NewSize);
4112       if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
4113         Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
4114                                                  Sema::AA_Converting, true);
4115         if (!Diff.isUsable())
4116           return nullptr;
4117       }
4118     }
4119   }
4120 
4121   return Diff.get();
4122 }
4123 
4124 Expr *OpenMPIterationSpaceChecker::BuildPreCond(
4125     Scope *S, Expr *Cond,
4126     llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
4127   // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
4128   bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
4129   SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
4130 
4131   auto NewLB = tryBuildCapture(SemaRef, LB, Captures);
4132   auto NewUB = tryBuildCapture(SemaRef, UB, Captures);
4133   if (!NewLB.isUsable() || !NewUB.isUsable())
4134     return nullptr;
4135 
4136   auto CondExpr = SemaRef.BuildBinOp(
4137       S, DefaultLoc, TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE)
4138                                   : (TestIsStrictOp ? BO_GT : BO_GE),
4139       NewLB.get(), NewUB.get());
4140   if (CondExpr.isUsable()) {
4141     if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
4142                                                 SemaRef.Context.BoolTy))
4143       CondExpr = SemaRef.PerformImplicitConversion(
4144           CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
4145           /*AllowExplicit=*/true);
4146   }
4147   SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
4148   // Otherwise use original loop conditon and evaluate it in runtime.
4149   return CondExpr.isUsable() ? CondExpr.get() : Cond;
4150 }
4151 
4152 /// \brief Build reference expression to the counter be used for codegen.
4153 DeclRefExpr *OpenMPIterationSpaceChecker::BuildCounterVar(
4154     llvm::MapVector<Expr *, DeclRefExpr *> &Captures, DSAStackTy &DSA) const {
4155   auto *VD = dyn_cast<VarDecl>(LCDecl);
4156   if (!VD) {
4157     VD = SemaRef.IsOpenMPCapturedDecl(LCDecl);
4158     auto *Ref = buildDeclRefExpr(
4159         SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
4160     DSAStackTy::DSAVarData Data = DSA.getTopDSA(LCDecl, /*FromParent=*/false);
4161     // If the loop control decl is explicitly marked as private, do not mark it
4162     // as captured again.
4163     if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
4164       Captures.insert(std::make_pair(LCRef, Ref));
4165     return Ref;
4166   }
4167   return buildDeclRefExpr(SemaRef, VD, VD->getType().getNonReferenceType(),
4168                           DefaultLoc);
4169 }
4170 
4171 Expr *OpenMPIterationSpaceChecker::BuildPrivateCounterVar() const {
4172   if (LCDecl && !LCDecl->isInvalidDecl()) {
4173     auto Type = LCDecl->getType().getNonReferenceType();
4174     auto *PrivateVar =
4175         buildVarDecl(SemaRef, DefaultLoc, Type, LCDecl->getName(),
4176                      LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr);
4177     if (PrivateVar->isInvalidDecl())
4178       return nullptr;
4179     return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
4180   }
4181   return nullptr;
4182 }
4183 
4184 /// \brief Build initization of the counter be used for codegen.
4185 Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; }
4186 
4187 /// \brief Build step of the counter be used for codegen.
4188 Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; }
4189 
4190 /// \brief Iteration space of a single for loop.
4191 struct LoopIterationSpace {
4192   /// \brief Condition of the loop.
4193   Expr *PreCond;
4194   /// \brief This expression calculates the number of iterations in the loop.
4195   /// It is always possible to calculate it before starting the loop.
4196   Expr *NumIterations;
4197   /// \brief The loop counter variable.
4198   Expr *CounterVar;
4199   /// \brief Private loop counter variable.
4200   Expr *PrivateCounterVar;
4201   /// \brief This is initializer for the initial value of #CounterVar.
4202   Expr *CounterInit;
4203   /// \brief This is step for the #CounterVar used to generate its update:
4204   /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
4205   Expr *CounterStep;
4206   /// \brief Should step be subtracted?
4207   bool Subtract;
4208   /// \brief Source range of the loop init.
4209   SourceRange InitSrcRange;
4210   /// \brief Source range of the loop condition.
4211   SourceRange CondSrcRange;
4212   /// \brief Source range of the loop increment.
4213   SourceRange IncSrcRange;
4214 };
4215 
4216 } // namespace
4217 
4218 void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
4219   assert(getLangOpts().OpenMP && "OpenMP is not active.");
4220   assert(Init && "Expected loop in canonical form.");
4221   unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
4222   if (AssociatedLoops > 0 &&
4223       isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
4224     OpenMPIterationSpaceChecker ISC(*this, ForLoc);
4225     if (!ISC.CheckInit(Init, /*EmitDiags=*/false)) {
4226       if (auto *D = ISC.GetLoopDecl()) {
4227         auto *VD = dyn_cast<VarDecl>(D);
4228         if (!VD) {
4229           if (auto *Private = IsOpenMPCapturedDecl(D))
4230             VD = Private;
4231           else {
4232             auto *Ref = buildCapture(*this, D, ISC.GetLoopDeclRefExpr(),
4233                                      /*WithInit=*/false);
4234             VD = cast<VarDecl>(Ref->getDecl());
4235           }
4236         }
4237         DSAStack->addLoopControlVariable(D, VD);
4238       }
4239     }
4240     DSAStack->setAssociatedLoops(AssociatedLoops - 1);
4241   }
4242 }
4243 
4244 /// \brief Called on a for stmt to check and extract its iteration space
4245 /// for further processing (such as collapsing).
4246 static bool CheckOpenMPIterationSpace(
4247     OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
4248     unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
4249     Expr *CollapseLoopCountExpr, Expr *OrderedLoopCountExpr,
4250     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
4251     LoopIterationSpace &ResultIterSpace,
4252     llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
4253   // OpenMP [2.6, Canonical Loop Form]
4254   //   for (init-expr; test-expr; incr-expr) structured-block
4255   auto For = dyn_cast_or_null<ForStmt>(S);
4256   if (!For) {
4257     SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for)
4258         << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
4259         << getOpenMPDirectiveName(DKind) << NestedLoopCount
4260         << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
4261     if (NestedLoopCount > 1) {
4262       if (CollapseLoopCountExpr && OrderedLoopCountExpr)
4263         SemaRef.Diag(DSA.getConstructLoc(),
4264                      diag::note_omp_collapse_ordered_expr)
4265             << 2 << CollapseLoopCountExpr->getSourceRange()
4266             << OrderedLoopCountExpr->getSourceRange();
4267       else if (CollapseLoopCountExpr)
4268         SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
4269                      diag::note_omp_collapse_ordered_expr)
4270             << 0 << CollapseLoopCountExpr->getSourceRange();
4271       else
4272         SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
4273                      diag::note_omp_collapse_ordered_expr)
4274             << 1 << OrderedLoopCountExpr->getSourceRange();
4275     }
4276     return true;
4277   }
4278   assert(For->getBody());
4279 
4280   OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
4281 
4282   // Check init.
4283   auto Init = For->getInit();
4284   if (ISC.CheckInit(Init))
4285     return true;
4286 
4287   bool HasErrors = false;
4288 
4289   // Check loop variable's type.
4290   if (auto *LCDecl = ISC.GetLoopDecl()) {
4291     auto *LoopDeclRefExpr = ISC.GetLoopDeclRefExpr();
4292 
4293     // OpenMP [2.6, Canonical Loop Form]
4294     // Var is one of the following:
4295     //   A variable of signed or unsigned integer type.
4296     //   For C++, a variable of a random access iterator type.
4297     //   For C, a variable of a pointer type.
4298     auto VarType = LCDecl->getType().getNonReferenceType();
4299     if (!VarType->isDependentType() && !VarType->isIntegerType() &&
4300         !VarType->isPointerType() &&
4301         !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
4302       SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type)
4303           << SemaRef.getLangOpts().CPlusPlus;
4304       HasErrors = true;
4305     }
4306 
4307     // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
4308     // a Construct
4309     // The loop iteration variable(s) in the associated for-loop(s) of a for or
4310     // parallel for construct is (are) private.
4311     // The loop iteration variable in the associated for-loop of a simd
4312     // construct with just one associated for-loop is linear with a
4313     // constant-linear-step that is the increment of the associated for-loop.
4314     // Exclude loop var from the list of variables with implicitly defined data
4315     // sharing attributes.
4316     VarsWithImplicitDSA.erase(LCDecl);
4317 
4318     // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
4319     // in a Construct, C/C++].
4320     // The loop iteration variable in the associated for-loop of a simd
4321     // construct with just one associated for-loop may be listed in a linear
4322     // clause with a constant-linear-step that is the increment of the
4323     // associated for-loop.
4324     // The loop iteration variable(s) in the associated for-loop(s) of a for or
4325     // parallel for construct may be listed in a private or lastprivate clause.
4326     DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false);
4327     // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
4328     // declared in the loop and it is predetermined as a private.
4329     auto PredeterminedCKind =
4330         isOpenMPSimdDirective(DKind)
4331             ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
4332             : OMPC_private;
4333     if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
4334           DVar.CKind != PredeterminedCKind) ||
4335          ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
4336            isOpenMPDistributeDirective(DKind)) &&
4337           !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
4338           DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
4339         (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
4340       SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa)
4341           << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
4342           << getOpenMPClauseName(PredeterminedCKind);
4343       if (DVar.RefExpr == nullptr)
4344         DVar.CKind = PredeterminedCKind;
4345       ReportOriginalDSA(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true);
4346       HasErrors = true;
4347     } else if (LoopDeclRefExpr != nullptr) {
4348       // Make the loop iteration variable private (for worksharing constructs),
4349       // linear (for simd directives with the only one associated loop) or
4350       // lastprivate (for simd directives with several collapsed or ordered
4351       // loops).
4352       if (DVar.CKind == OMPC_unknown)
4353         DVar = DSA.hasDSA(LCDecl, isOpenMPPrivate, MatchesAlways(),
4354                           /*FromParent=*/false);
4355       DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind);
4356     }
4357 
4358     assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
4359 
4360     // Check test-expr.
4361     HasErrors |= ISC.CheckCond(For->getCond());
4362 
4363     // Check incr-expr.
4364     HasErrors |= ISC.CheckInc(For->getInc());
4365   }
4366 
4367   if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
4368     return HasErrors;
4369 
4370   // Build the loop's iteration space representation.
4371   ResultIterSpace.PreCond =
4372       ISC.BuildPreCond(DSA.getCurScope(), For->getCond(), Captures);
4373   ResultIterSpace.NumIterations = ISC.BuildNumIterations(
4374       DSA.getCurScope(),
4375       (isOpenMPWorksharingDirective(DKind) ||
4376        isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)),
4377       Captures);
4378   ResultIterSpace.CounterVar = ISC.BuildCounterVar(Captures, DSA);
4379   ResultIterSpace.PrivateCounterVar = ISC.BuildPrivateCounterVar();
4380   ResultIterSpace.CounterInit = ISC.BuildCounterInit();
4381   ResultIterSpace.CounterStep = ISC.BuildCounterStep();
4382   ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange();
4383   ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange();
4384   ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange();
4385   ResultIterSpace.Subtract = ISC.ShouldSubtractStep();
4386 
4387   HasErrors |= (ResultIterSpace.PreCond == nullptr ||
4388                 ResultIterSpace.NumIterations == nullptr ||
4389                 ResultIterSpace.CounterVar == nullptr ||
4390                 ResultIterSpace.PrivateCounterVar == nullptr ||
4391                 ResultIterSpace.CounterInit == nullptr ||
4392                 ResultIterSpace.CounterStep == nullptr);
4393 
4394   return HasErrors;
4395 }
4396 
4397 /// \brief Build 'VarRef = Start.
4398 static ExprResult
4399 BuildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
4400                  ExprResult Start,
4401                  llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
4402   // Build 'VarRef = Start.
4403   auto NewStart = tryBuildCapture(SemaRef, Start.get(), Captures);
4404   if (!NewStart.isUsable())
4405     return ExprError();
4406   if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
4407                                    VarRef.get()->getType())) {
4408     NewStart = SemaRef.PerformImplicitConversion(
4409         NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
4410         /*AllowExplicit=*/true);
4411     if (!NewStart.isUsable())
4412       return ExprError();
4413   }
4414 
4415   auto Init =
4416       SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
4417   return Init;
4418 }
4419 
4420 /// \brief Build 'VarRef = Start + Iter * Step'.
4421 static ExprResult
4422 BuildCounterUpdate(Sema &SemaRef, Scope *S, SourceLocation Loc,
4423                    ExprResult VarRef, ExprResult Start, ExprResult Iter,
4424                    ExprResult Step, bool Subtract,
4425                    llvm::MapVector<Expr *, DeclRefExpr *> *Captures = nullptr) {
4426   // Add parentheses (for debugging purposes only).
4427   Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
4428   if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
4429       !Step.isUsable())
4430     return ExprError();
4431 
4432   ExprResult NewStep = Step;
4433   if (Captures)
4434     NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
4435   if (NewStep.isInvalid())
4436     return ExprError();
4437   ExprResult Update =
4438       SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
4439   if (!Update.isUsable())
4440     return ExprError();
4441 
4442   // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
4443   // 'VarRef = Start (+|-) Iter * Step'.
4444   ExprResult NewStart = Start;
4445   if (Captures)
4446     NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
4447   if (NewStart.isInvalid())
4448     return ExprError();
4449 
4450   // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
4451   ExprResult SavedUpdate = Update;
4452   ExprResult UpdateVal;
4453   if (VarRef.get()->getType()->isOverloadableType() ||
4454       NewStart.get()->getType()->isOverloadableType() ||
4455       Update.get()->getType()->isOverloadableType()) {
4456     bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
4457     SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
4458     Update =
4459         SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
4460     if (Update.isUsable()) {
4461       UpdateVal =
4462           SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
4463                              VarRef.get(), SavedUpdate.get());
4464       if (UpdateVal.isUsable()) {
4465         Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
4466                                             UpdateVal.get());
4467       }
4468     }
4469     SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
4470   }
4471 
4472   // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
4473   if (!Update.isUsable() || !UpdateVal.isUsable()) {
4474     Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
4475                                 NewStart.get(), SavedUpdate.get());
4476     if (!Update.isUsable())
4477       return ExprError();
4478 
4479     if (!SemaRef.Context.hasSameType(Update.get()->getType(),
4480                                      VarRef.get()->getType())) {
4481       Update = SemaRef.PerformImplicitConversion(
4482           Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
4483       if (!Update.isUsable())
4484         return ExprError();
4485     }
4486 
4487     Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
4488   }
4489   return Update;
4490 }
4491 
4492 /// \brief Convert integer expression \a E to make it have at least \a Bits
4493 /// bits.
4494 static ExprResult WidenIterationCount(unsigned Bits, Expr *E,
4495                                       Sema &SemaRef) {
4496   if (E == nullptr)
4497     return ExprError();
4498   auto &C = SemaRef.Context;
4499   QualType OldType = E->getType();
4500   unsigned HasBits = C.getTypeSize(OldType);
4501   if (HasBits >= Bits)
4502     return ExprResult(E);
4503   // OK to convert to signed, because new type has more bits than old.
4504   QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
4505   return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
4506                                            true);
4507 }
4508 
4509 /// \brief Check if the given expression \a E is a constant integer that fits
4510 /// into \a Bits bits.
4511 static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) {
4512   if (E == nullptr)
4513     return false;
4514   llvm::APSInt Result;
4515   if (E->isIntegerConstantExpr(Result, SemaRef.Context))
4516     return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
4517   return false;
4518 }
4519 
4520 /// Build preinits statement for the given declarations.
4521 static Stmt *buildPreInits(ASTContext &Context,
4522                            SmallVectorImpl<Decl *> &PreInits) {
4523   if (!PreInits.empty()) {
4524     return new (Context) DeclStmt(
4525         DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
4526         SourceLocation(), SourceLocation());
4527   }
4528   return nullptr;
4529 }
4530 
4531 /// Build preinits statement for the given declarations.
4532 static Stmt *buildPreInits(ASTContext &Context,
4533                            llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
4534   if (!Captures.empty()) {
4535     SmallVector<Decl *, 16> PreInits;
4536     for (auto &Pair : Captures)
4537       PreInits.push_back(Pair.second->getDecl());
4538     return buildPreInits(Context, PreInits);
4539   }
4540   return nullptr;
4541 }
4542 
4543 /// Build postupdate expression for the given list of postupdates expressions.
4544 static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
4545   Expr *PostUpdate = nullptr;
4546   if (!PostUpdates.empty()) {
4547     for (auto *E : PostUpdates) {
4548       Expr *ConvE = S.BuildCStyleCastExpr(
4549                          E->getExprLoc(),
4550                          S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
4551                          E->getExprLoc(), E)
4552                         .get();
4553       PostUpdate = PostUpdate
4554                        ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
4555                                               PostUpdate, ConvE)
4556                              .get()
4557                        : ConvE;
4558     }
4559   }
4560   return PostUpdate;
4561 }
4562 
4563 /// \brief Called on a for stmt to check itself and nested loops (if any).
4564 /// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
4565 /// number of collapsed loops otherwise.
4566 static unsigned
4567 CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
4568                 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
4569                 DSAStackTy &DSA,
4570                 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
4571                 OMPLoopDirective::HelperExprs &Built) {
4572   unsigned NestedLoopCount = 1;
4573   if (CollapseLoopCountExpr) {
4574     // Found 'collapse' clause - calculate collapse number.
4575     llvm::APSInt Result;
4576     if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
4577       NestedLoopCount = Result.getLimitedValue();
4578   }
4579   if (OrderedLoopCountExpr) {
4580     // Found 'ordered' clause - calculate collapse number.
4581     llvm::APSInt Result;
4582     if (OrderedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
4583       if (Result.getLimitedValue() < NestedLoopCount) {
4584         SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
4585                      diag::err_omp_wrong_ordered_loop_count)
4586             << OrderedLoopCountExpr->getSourceRange();
4587         SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
4588                      diag::note_collapse_loop_count)
4589             << CollapseLoopCountExpr->getSourceRange();
4590       }
4591       NestedLoopCount = Result.getLimitedValue();
4592     }
4593   }
4594   // This is helper routine for loop directives (e.g., 'for', 'simd',
4595   // 'for simd', etc.).
4596   llvm::MapVector<Expr *, DeclRefExpr *> Captures;
4597   SmallVector<LoopIterationSpace, 4> IterSpaces;
4598   IterSpaces.resize(NestedLoopCount);
4599   Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
4600   for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
4601     if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt,
4602                                   NestedLoopCount, CollapseLoopCountExpr,
4603                                   OrderedLoopCountExpr, VarsWithImplicitDSA,
4604                                   IterSpaces[Cnt], Captures))
4605       return 0;
4606     // Move on to the next nested for loop, or to the loop body.
4607     // OpenMP [2.8.1, simd construct, Restrictions]
4608     // All loops associated with the construct must be perfectly nested; that
4609     // is, there must be no intervening code nor any OpenMP directive between
4610     // any two loops.
4611     CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
4612   }
4613 
4614   Built.clear(/* size */ NestedLoopCount);
4615 
4616   if (SemaRef.CurContext->isDependentContext())
4617     return NestedLoopCount;
4618 
4619   // An example of what is generated for the following code:
4620   //
4621   //   #pragma omp simd collapse(2) ordered(2)
4622   //   for (i = 0; i < NI; ++i)
4623   //     for (k = 0; k < NK; ++k)
4624   //       for (j = J0; j < NJ; j+=2) {
4625   //         <loop body>
4626   //       }
4627   //
4628   // We generate the code below.
4629   // Note: the loop body may be outlined in CodeGen.
4630   // Note: some counters may be C++ classes, operator- is used to find number of
4631   // iterations and operator+= to calculate counter value.
4632   // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
4633   // or i64 is currently supported).
4634   //
4635   //   #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
4636   //   for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
4637   //     .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
4638   //     .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
4639   //     // similar updates for vars in clauses (e.g. 'linear')
4640   //     <loop body (using local i and j)>
4641   //   }
4642   //   i = NI; // assign final values of counters
4643   //   j = NJ;
4644   //
4645 
4646   // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
4647   // the iteration counts of the collapsed for loops.
4648   // Precondition tests if there is at least one iteration (all conditions are
4649   // true).
4650   auto PreCond = ExprResult(IterSpaces[0].PreCond);
4651   auto N0 = IterSpaces[0].NumIterations;
4652   ExprResult LastIteration32 = WidenIterationCount(
4653       32 /* Bits */, SemaRef.PerformImplicitConversion(
4654                                 N0->IgnoreImpCasts(), N0->getType(),
4655                                 Sema::AA_Converting, /*AllowExplicit=*/true)
4656                          .get(),
4657       SemaRef);
4658   ExprResult LastIteration64 = WidenIterationCount(
4659       64 /* Bits */, SemaRef.PerformImplicitConversion(
4660                                 N0->IgnoreImpCasts(), N0->getType(),
4661                                 Sema::AA_Converting, /*AllowExplicit=*/true)
4662                          .get(),
4663       SemaRef);
4664 
4665   if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
4666     return NestedLoopCount;
4667 
4668   auto &C = SemaRef.Context;
4669   bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
4670 
4671   Scope *CurScope = DSA.getCurScope();
4672   for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
4673     if (PreCond.isUsable()) {
4674       PreCond = SemaRef.BuildBinOp(CurScope, SourceLocation(), BO_LAnd,
4675                                    PreCond.get(), IterSpaces[Cnt].PreCond);
4676     }
4677     auto N = IterSpaces[Cnt].NumIterations;
4678     AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
4679     if (LastIteration32.isUsable())
4680       LastIteration32 = SemaRef.BuildBinOp(
4681           CurScope, SourceLocation(), BO_Mul, LastIteration32.get(),
4682           SemaRef.PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
4683                                             Sema::AA_Converting,
4684                                             /*AllowExplicit=*/true)
4685               .get());
4686     if (LastIteration64.isUsable())
4687       LastIteration64 = SemaRef.BuildBinOp(
4688           CurScope, SourceLocation(), BO_Mul, LastIteration64.get(),
4689           SemaRef.PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
4690                                             Sema::AA_Converting,
4691                                             /*AllowExplicit=*/true)
4692               .get());
4693   }
4694 
4695   // Choose either the 32-bit or 64-bit version.
4696   ExprResult LastIteration = LastIteration64;
4697   if (LastIteration32.isUsable() &&
4698       C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
4699       (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
4700        FitsInto(
4701            32 /* Bits */,
4702            LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
4703            LastIteration64.get(), SemaRef)))
4704     LastIteration = LastIteration32;
4705   QualType VType = LastIteration.get()->getType();
4706   QualType RealVType = VType;
4707   QualType StrideVType = VType;
4708   if (isOpenMPTaskLoopDirective(DKind)) {
4709     VType =
4710         SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
4711     StrideVType =
4712         SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
4713   }
4714 
4715   if (!LastIteration.isUsable())
4716     return 0;
4717 
4718   // Save the number of iterations.
4719   ExprResult NumIterations = LastIteration;
4720   {
4721     LastIteration = SemaRef.BuildBinOp(
4722         CurScope, SourceLocation(), BO_Sub, LastIteration.get(),
4723         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4724     if (!LastIteration.isUsable())
4725       return 0;
4726   }
4727 
4728   // Calculate the last iteration number beforehand instead of doing this on
4729   // each iteration. Do not do this if the number of iterations may be kfold-ed.
4730   llvm::APSInt Result;
4731   bool IsConstant =
4732       LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
4733   ExprResult CalcLastIteration;
4734   if (!IsConstant) {
4735     ExprResult SaveRef =
4736         tryBuildCapture(SemaRef, LastIteration.get(), Captures);
4737     LastIteration = SaveRef;
4738 
4739     // Prepare SaveRef + 1.
4740     NumIterations = SemaRef.BuildBinOp(
4741         CurScope, SourceLocation(), BO_Add, SaveRef.get(),
4742         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4743     if (!NumIterations.isUsable())
4744       return 0;
4745   }
4746 
4747   SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
4748 
4749   // Build variables passed into runtime, nesessary for worksharing directives.
4750   ExprResult LB, UB, IL, ST, EUB;
4751   if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
4752       isOpenMPDistributeDirective(DKind)) {
4753     // Lower bound variable, initialized with zero.
4754     VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
4755     LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
4756     SemaRef.AddInitializerToDecl(
4757         LBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4758         /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
4759 
4760     // Upper bound variable, initialized with last iteration number.
4761     VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
4762     UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
4763     SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
4764                                  /*DirectInit*/ false,
4765                                  /*TypeMayContainAuto*/ false);
4766 
4767     // A 32-bit variable-flag where runtime returns 1 for the last iteration.
4768     // This will be used to implement clause 'lastprivate'.
4769     QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
4770     VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
4771     IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
4772     SemaRef.AddInitializerToDecl(
4773         ILDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4774         /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
4775 
4776     // Stride variable returned by runtime (we initialize it to 1 by default).
4777     VarDecl *STDecl =
4778         buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
4779     ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
4780     SemaRef.AddInitializerToDecl(
4781         STDecl, SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
4782         /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
4783 
4784     // Build expression: UB = min(UB, LastIteration)
4785     // It is nesessary for CodeGen of directives with static scheduling.
4786     ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
4787                                                 UB.get(), LastIteration.get());
4788     ExprResult CondOp = SemaRef.ActOnConditionalOp(
4789         InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get());
4790     EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
4791                              CondOp.get());
4792     EUB = SemaRef.ActOnFinishFullExpr(EUB.get());
4793   }
4794 
4795   // Build the iteration variable and its initialization before loop.
4796   ExprResult IV;
4797   ExprResult Init;
4798   {
4799     VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
4800     IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
4801     Expr *RHS = (isOpenMPWorksharingDirective(DKind) ||
4802                  isOpenMPTaskLoopDirective(DKind) ||
4803                  isOpenMPDistributeDirective(DKind))
4804                     ? LB.get()
4805                     : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
4806     Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
4807     Init = SemaRef.ActOnFinishFullExpr(Init.get());
4808   }
4809 
4810   // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops.
4811   SourceLocation CondLoc;
4812   ExprResult Cond =
4813       (isOpenMPWorksharingDirective(DKind) ||
4814        isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
4815           ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get())
4816           : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
4817                                NumIterations.get());
4818 
4819   // Loop increment (IV = IV + 1)
4820   SourceLocation IncLoc;
4821   ExprResult Inc =
4822       SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
4823                          SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
4824   if (!Inc.isUsable())
4825     return 0;
4826   Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
4827   Inc = SemaRef.ActOnFinishFullExpr(Inc.get());
4828   if (!Inc.isUsable())
4829     return 0;
4830 
4831   // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
4832   // Used for directives with static scheduling.
4833   ExprResult NextLB, NextUB;
4834   if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
4835       isOpenMPDistributeDirective(DKind)) {
4836     // LB + ST
4837     NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
4838     if (!NextLB.isUsable())
4839       return 0;
4840     // LB = LB + ST
4841     NextLB =
4842         SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
4843     NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get());
4844     if (!NextLB.isUsable())
4845       return 0;
4846     // UB + ST
4847     NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
4848     if (!NextUB.isUsable())
4849       return 0;
4850     // UB = UB + ST
4851     NextUB =
4852         SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
4853     NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get());
4854     if (!NextUB.isUsable())
4855       return 0;
4856   }
4857 
4858   // Build updates and final values of the loop counters.
4859   bool HasErrors = false;
4860   Built.Counters.resize(NestedLoopCount);
4861   Built.Inits.resize(NestedLoopCount);
4862   Built.Updates.resize(NestedLoopCount);
4863   Built.Finals.resize(NestedLoopCount);
4864   {
4865     ExprResult Div;
4866     // Go from inner nested loop to outer.
4867     for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
4868       LoopIterationSpace &IS = IterSpaces[Cnt];
4869       SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
4870       // Build: Iter = (IV / Div) % IS.NumIters
4871       // where Div is product of previous iterations' IS.NumIters.
4872       ExprResult Iter;
4873       if (Div.isUsable()) {
4874         Iter =
4875             SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get());
4876       } else {
4877         Iter = IV;
4878         assert((Cnt == (int)NestedLoopCount - 1) &&
4879                "unusable div expected on first iteration only");
4880       }
4881 
4882       if (Cnt != 0 && Iter.isUsable())
4883         Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(),
4884                                   IS.NumIterations);
4885       if (!Iter.isUsable()) {
4886         HasErrors = true;
4887         break;
4888       }
4889 
4890       // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
4891       auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
4892       auto *CounterVar = buildDeclRefExpr(SemaRef, VD, IS.CounterVar->getType(),
4893                                           IS.CounterVar->getExprLoc(),
4894                                           /*RefersToCapture=*/true);
4895       ExprResult Init = BuildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
4896                                          IS.CounterInit, Captures);
4897       if (!Init.isUsable()) {
4898         HasErrors = true;
4899         break;
4900       }
4901       ExprResult Update = BuildCounterUpdate(
4902           SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
4903           IS.CounterStep, IS.Subtract, &Captures);
4904       if (!Update.isUsable()) {
4905         HasErrors = true;
4906         break;
4907       }
4908 
4909       // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
4910       ExprResult Final = BuildCounterUpdate(
4911           SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
4912           IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures);
4913       if (!Final.isUsable()) {
4914         HasErrors = true;
4915         break;
4916       }
4917 
4918       // Build Div for the next iteration: Div <- Div * IS.NumIters
4919       if (Cnt != 0) {
4920         if (Div.isUnset())
4921           Div = IS.NumIterations;
4922         else
4923           Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(),
4924                                    IS.NumIterations);
4925 
4926         // Add parentheses (for debugging purposes only).
4927         if (Div.isUsable())
4928           Div = SemaRef.ActOnParenExpr(UpdLoc, UpdLoc, Div.get());
4929         if (!Div.isUsable()) {
4930           HasErrors = true;
4931           break;
4932         }
4933       }
4934       if (!Update.isUsable() || !Final.isUsable()) {
4935         HasErrors = true;
4936         break;
4937       }
4938       // Save results
4939       Built.Counters[Cnt] = IS.CounterVar;
4940       Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
4941       Built.Inits[Cnt] = Init.get();
4942       Built.Updates[Cnt] = Update.get();
4943       Built.Finals[Cnt] = Final.get();
4944     }
4945   }
4946 
4947   if (HasErrors)
4948     return 0;
4949 
4950   // Save results
4951   Built.IterationVarRef = IV.get();
4952   Built.LastIteration = LastIteration.get();
4953   Built.NumIterations = NumIterations.get();
4954   Built.CalcLastIteration =
4955       SemaRef.ActOnFinishFullExpr(CalcLastIteration.get()).get();
4956   Built.PreCond = PreCond.get();
4957   Built.PreInits = buildPreInits(C, Captures);
4958   Built.Cond = Cond.get();
4959   Built.Init = Init.get();
4960   Built.Inc = Inc.get();
4961   Built.LB = LB.get();
4962   Built.UB = UB.get();
4963   Built.IL = IL.get();
4964   Built.ST = ST.get();
4965   Built.EUB = EUB.get();
4966   Built.NLB = NextLB.get();
4967   Built.NUB = NextUB.get();
4968 
4969   return NestedLoopCount;
4970 }
4971 
4972 static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
4973   auto CollapseClauses =
4974       OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
4975   if (CollapseClauses.begin() != CollapseClauses.end())
4976     return (*CollapseClauses.begin())->getNumForLoops();
4977   return nullptr;
4978 }
4979 
4980 static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
4981   auto OrderedClauses =
4982       OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
4983   if (OrderedClauses.begin() != OrderedClauses.end())
4984     return (*OrderedClauses.begin())->getNumForLoops();
4985   return nullptr;
4986 }
4987 
4988 static bool checkSimdlenSafelenValues(Sema &S, const Expr *Simdlen,
4989                                       const Expr *Safelen) {
4990   llvm::APSInt SimdlenRes, SafelenRes;
4991   if (Simdlen->isValueDependent() || Simdlen->isTypeDependent() ||
4992       Simdlen->isInstantiationDependent() ||
4993       Simdlen->containsUnexpandedParameterPack())
4994     return false;
4995   if (Safelen->isValueDependent() || Safelen->isTypeDependent() ||
4996       Safelen->isInstantiationDependent() ||
4997       Safelen->containsUnexpandedParameterPack())
4998     return false;
4999   Simdlen->EvaluateAsInt(SimdlenRes, S.Context);
5000   Safelen->EvaluateAsInt(SafelenRes, S.Context);
5001   // OpenMP 4.1 [2.8.1, simd Construct, Restrictions]
5002   // If both simdlen and safelen clauses are specified, the value of the simdlen
5003   // parameter must be less than or equal to the value of the safelen parameter.
5004   if (SimdlenRes > SafelenRes) {
5005     S.Diag(Simdlen->getExprLoc(), diag::err_omp_wrong_simdlen_safelen_values)
5006         << Simdlen->getSourceRange() << Safelen->getSourceRange();
5007     return true;
5008   }
5009   return false;
5010 }
5011 
5012 StmtResult Sema::ActOnOpenMPSimdDirective(
5013     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5014     SourceLocation EndLoc,
5015     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5016   if (!AStmt)
5017     return StmtError();
5018 
5019   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5020   OMPLoopDirective::HelperExprs B;
5021   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5022   // define the nested loops number.
5023   unsigned NestedLoopCount = CheckOpenMPLoop(
5024       OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
5025       AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
5026   if (NestedLoopCount == 0)
5027     return StmtError();
5028 
5029   assert((CurContext->isDependentContext() || B.builtAll()) &&
5030          "omp simd loop exprs were not built");
5031 
5032   if (!CurContext->isDependentContext()) {
5033     // Finalize the clauses that need pre-built expressions for CodeGen.
5034     for (auto C : Clauses) {
5035       if (auto LC = dyn_cast<OMPLinearClause>(C))
5036         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
5037                                      B.NumIterations, *this, CurScope,
5038                                      DSAStack))
5039           return StmtError();
5040     }
5041   }
5042 
5043   // OpenMP 4.1 [2.8.1, simd Construct, Restrictions]
5044   // If both simdlen and safelen clauses are specified, the value of the simdlen
5045   // parameter must be less than or equal to the value of the safelen parameter.
5046   OMPSafelenClause *Safelen = nullptr;
5047   OMPSimdlenClause *Simdlen = nullptr;
5048   for (auto *Clause : Clauses) {
5049     if (Clause->getClauseKind() == OMPC_safelen)
5050       Safelen = cast<OMPSafelenClause>(Clause);
5051     else if (Clause->getClauseKind() == OMPC_simdlen)
5052       Simdlen = cast<OMPSimdlenClause>(Clause);
5053     if (Safelen && Simdlen)
5054       break;
5055   }
5056   if (Simdlen && Safelen &&
5057       checkSimdlenSafelenValues(*this, Simdlen->getSimdlen(),
5058                                 Safelen->getSafelen()))
5059     return StmtError();
5060 
5061   getCurFunction()->setHasBranchProtectedScope();
5062   return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
5063                                   Clauses, AStmt, B);
5064 }
5065 
5066 StmtResult Sema::ActOnOpenMPForDirective(
5067     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5068     SourceLocation EndLoc,
5069     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5070   if (!AStmt)
5071     return StmtError();
5072 
5073   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5074   OMPLoopDirective::HelperExprs B;
5075   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5076   // define the nested loops number.
5077   unsigned NestedLoopCount = CheckOpenMPLoop(
5078       OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
5079       AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
5080   if (NestedLoopCount == 0)
5081     return StmtError();
5082 
5083   assert((CurContext->isDependentContext() || B.builtAll()) &&
5084          "omp for loop exprs were not built");
5085 
5086   if (!CurContext->isDependentContext()) {
5087     // Finalize the clauses that need pre-built expressions for CodeGen.
5088     for (auto C : Clauses) {
5089       if (auto LC = dyn_cast<OMPLinearClause>(C))
5090         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
5091                                      B.NumIterations, *this, CurScope,
5092                                      DSAStack))
5093           return StmtError();
5094     }
5095   }
5096 
5097   getCurFunction()->setHasBranchProtectedScope();
5098   return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
5099                                  Clauses, AStmt, B, DSAStack->isCancelRegion());
5100 }
5101 
5102 StmtResult Sema::ActOnOpenMPForSimdDirective(
5103     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5104     SourceLocation EndLoc,
5105     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5106   if (!AStmt)
5107     return StmtError();
5108 
5109   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5110   OMPLoopDirective::HelperExprs B;
5111   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5112   // define the nested loops number.
5113   unsigned NestedLoopCount =
5114       CheckOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
5115                       getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5116                       VarsWithImplicitDSA, B);
5117   if (NestedLoopCount == 0)
5118     return StmtError();
5119 
5120   assert((CurContext->isDependentContext() || B.builtAll()) &&
5121          "omp for simd loop exprs were not built");
5122 
5123   if (!CurContext->isDependentContext()) {
5124     // Finalize the clauses that need pre-built expressions for CodeGen.
5125     for (auto C : Clauses) {
5126       if (auto LC = dyn_cast<OMPLinearClause>(C))
5127         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
5128                                      B.NumIterations, *this, CurScope,
5129                                      DSAStack))
5130           return StmtError();
5131     }
5132   }
5133 
5134   // OpenMP 4.1 [2.8.1, simd Construct, Restrictions]
5135   // If both simdlen and safelen clauses are specified, the value of the simdlen
5136   // parameter must be less than or equal to the value of the safelen parameter.
5137   OMPSafelenClause *Safelen = nullptr;
5138   OMPSimdlenClause *Simdlen = nullptr;
5139   for (auto *Clause : Clauses) {
5140     if (Clause->getClauseKind() == OMPC_safelen)
5141       Safelen = cast<OMPSafelenClause>(Clause);
5142     else if (Clause->getClauseKind() == OMPC_simdlen)
5143       Simdlen = cast<OMPSimdlenClause>(Clause);
5144     if (Safelen && Simdlen)
5145       break;
5146   }
5147   if (Simdlen && Safelen &&
5148       checkSimdlenSafelenValues(*this, Simdlen->getSimdlen(),
5149                                 Safelen->getSafelen()))
5150     return StmtError();
5151 
5152   getCurFunction()->setHasBranchProtectedScope();
5153   return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
5154                                      Clauses, AStmt, B);
5155 }
5156 
5157 StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
5158                                               Stmt *AStmt,
5159                                               SourceLocation StartLoc,
5160                                               SourceLocation EndLoc) {
5161   if (!AStmt)
5162     return StmtError();
5163 
5164   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5165   auto BaseStmt = AStmt;
5166   while (CapturedStmt *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
5167     BaseStmt = CS->getCapturedStmt();
5168   if (auto C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
5169     auto S = C->children();
5170     if (S.begin() == S.end())
5171       return StmtError();
5172     // All associated statements must be '#pragma omp section' except for
5173     // the first one.
5174     for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
5175       if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
5176         if (SectionStmt)
5177           Diag(SectionStmt->getLocStart(),
5178                diag::err_omp_sections_substmt_not_section);
5179         return StmtError();
5180       }
5181       cast<OMPSectionDirective>(SectionStmt)
5182           ->setHasCancel(DSAStack->isCancelRegion());
5183     }
5184   } else {
5185     Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt);
5186     return StmtError();
5187   }
5188 
5189   getCurFunction()->setHasBranchProtectedScope();
5190 
5191   return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
5192                                       DSAStack->isCancelRegion());
5193 }
5194 
5195 StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
5196                                              SourceLocation StartLoc,
5197                                              SourceLocation EndLoc) {
5198   if (!AStmt)
5199     return StmtError();
5200 
5201   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5202 
5203   getCurFunction()->setHasBranchProtectedScope();
5204   DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
5205 
5206   return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
5207                                      DSAStack->isCancelRegion());
5208 }
5209 
5210 StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
5211                                             Stmt *AStmt,
5212                                             SourceLocation StartLoc,
5213                                             SourceLocation EndLoc) {
5214   if (!AStmt)
5215     return StmtError();
5216 
5217   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5218 
5219   getCurFunction()->setHasBranchProtectedScope();
5220 
5221   // OpenMP [2.7.3, single Construct, Restrictions]
5222   // The copyprivate clause must not be used with the nowait clause.
5223   OMPClause *Nowait = nullptr;
5224   OMPClause *Copyprivate = nullptr;
5225   for (auto *Clause : Clauses) {
5226     if (Clause->getClauseKind() == OMPC_nowait)
5227       Nowait = Clause;
5228     else if (Clause->getClauseKind() == OMPC_copyprivate)
5229       Copyprivate = Clause;
5230     if (Copyprivate && Nowait) {
5231       Diag(Copyprivate->getLocStart(),
5232            diag::err_omp_single_copyprivate_with_nowait);
5233       Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here);
5234       return StmtError();
5235     }
5236   }
5237 
5238   return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
5239 }
5240 
5241 StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
5242                                             SourceLocation StartLoc,
5243                                             SourceLocation EndLoc) {
5244   if (!AStmt)
5245     return StmtError();
5246 
5247   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5248 
5249   getCurFunction()->setHasBranchProtectedScope();
5250 
5251   return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
5252 }
5253 
5254 StmtResult Sema::ActOnOpenMPCriticalDirective(
5255     const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
5256     Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
5257   if (!AStmt)
5258     return StmtError();
5259 
5260   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5261 
5262   bool ErrorFound = false;
5263   llvm::APSInt Hint;
5264   SourceLocation HintLoc;
5265   bool DependentHint = false;
5266   for (auto *C : Clauses) {
5267     if (C->getClauseKind() == OMPC_hint) {
5268       if (!DirName.getName()) {
5269         Diag(C->getLocStart(), diag::err_omp_hint_clause_no_name);
5270         ErrorFound = true;
5271       }
5272       Expr *E = cast<OMPHintClause>(C)->getHint();
5273       if (E->isTypeDependent() || E->isValueDependent() ||
5274           E->isInstantiationDependent())
5275         DependentHint = true;
5276       else {
5277         Hint = E->EvaluateKnownConstInt(Context);
5278         HintLoc = C->getLocStart();
5279       }
5280     }
5281   }
5282   if (ErrorFound)
5283     return StmtError();
5284   auto Pair = DSAStack->getCriticalWithHint(DirName);
5285   if (Pair.first && DirName.getName() && !DependentHint) {
5286     if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
5287       Diag(StartLoc, diag::err_omp_critical_with_hint);
5288       if (HintLoc.isValid()) {
5289         Diag(HintLoc, diag::note_omp_critical_hint_here)
5290             << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
5291       } else
5292         Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
5293       if (auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
5294         Diag(C->getLocStart(), diag::note_omp_critical_hint_here)
5295             << 1
5296             << C->getHint()->EvaluateKnownConstInt(Context).toString(
5297                    /*Radix=*/10, /*Signed=*/false);
5298       } else
5299         Diag(Pair.first->getLocStart(), diag::note_omp_critical_no_hint) << 1;
5300     }
5301   }
5302 
5303   getCurFunction()->setHasBranchProtectedScope();
5304 
5305   auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
5306                                            Clauses, AStmt);
5307   if (!Pair.first && DirName.getName() && !DependentHint)
5308     DSAStack->addCriticalWithHint(Dir, Hint);
5309   return Dir;
5310 }
5311 
5312 StmtResult Sema::ActOnOpenMPParallelForDirective(
5313     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5314     SourceLocation EndLoc,
5315     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5316   if (!AStmt)
5317     return StmtError();
5318 
5319   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5320   // 1.2.2 OpenMP Language Terminology
5321   // Structured block - An executable statement with a single entry at the
5322   // top and a single exit at the bottom.
5323   // The point of exit cannot be a branch out of the structured block.
5324   // longjmp() and throw() must not violate the entry/exit criteria.
5325   CS->getCapturedDecl()->setNothrow();
5326 
5327   OMPLoopDirective::HelperExprs B;
5328   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5329   // define the nested loops number.
5330   unsigned NestedLoopCount =
5331       CheckOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
5332                       getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5333                       VarsWithImplicitDSA, B);
5334   if (NestedLoopCount == 0)
5335     return StmtError();
5336 
5337   assert((CurContext->isDependentContext() || B.builtAll()) &&
5338          "omp parallel for loop exprs were not built");
5339 
5340   if (!CurContext->isDependentContext()) {
5341     // Finalize the clauses that need pre-built expressions for CodeGen.
5342     for (auto C : Clauses) {
5343       if (auto LC = dyn_cast<OMPLinearClause>(C))
5344         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
5345                                      B.NumIterations, *this, CurScope,
5346                                      DSAStack))
5347           return StmtError();
5348     }
5349   }
5350 
5351   getCurFunction()->setHasBranchProtectedScope();
5352   return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
5353                                          NestedLoopCount, Clauses, AStmt, B,
5354                                          DSAStack->isCancelRegion());
5355 }
5356 
5357 StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
5358     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5359     SourceLocation EndLoc,
5360     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5361   if (!AStmt)
5362     return StmtError();
5363 
5364   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5365   // 1.2.2 OpenMP Language Terminology
5366   // Structured block - An executable statement with a single entry at the
5367   // top and a single exit at the bottom.
5368   // The point of exit cannot be a branch out of the structured block.
5369   // longjmp() and throw() must not violate the entry/exit criteria.
5370   CS->getCapturedDecl()->setNothrow();
5371 
5372   OMPLoopDirective::HelperExprs B;
5373   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5374   // define the nested loops number.
5375   unsigned NestedLoopCount =
5376       CheckOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
5377                       getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5378                       VarsWithImplicitDSA, B);
5379   if (NestedLoopCount == 0)
5380     return StmtError();
5381 
5382   if (!CurContext->isDependentContext()) {
5383     // Finalize the clauses that need pre-built expressions for CodeGen.
5384     for (auto C : Clauses) {
5385       if (auto LC = dyn_cast<OMPLinearClause>(C))
5386         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
5387                                      B.NumIterations, *this, CurScope,
5388                                      DSAStack))
5389           return StmtError();
5390     }
5391   }
5392 
5393   // OpenMP 4.1 [2.8.1, simd Construct, Restrictions]
5394   // If both simdlen and safelen clauses are specified, the value of the simdlen
5395   // parameter must be less than or equal to the value of the safelen parameter.
5396   OMPSafelenClause *Safelen = nullptr;
5397   OMPSimdlenClause *Simdlen = nullptr;
5398   for (auto *Clause : Clauses) {
5399     if (Clause->getClauseKind() == OMPC_safelen)
5400       Safelen = cast<OMPSafelenClause>(Clause);
5401     else if (Clause->getClauseKind() == OMPC_simdlen)
5402       Simdlen = cast<OMPSimdlenClause>(Clause);
5403     if (Safelen && Simdlen)
5404       break;
5405   }
5406   if (Simdlen && Safelen &&
5407       checkSimdlenSafelenValues(*this, Simdlen->getSimdlen(),
5408                                 Safelen->getSafelen()))
5409     return StmtError();
5410 
5411   getCurFunction()->setHasBranchProtectedScope();
5412   return OMPParallelForSimdDirective::Create(
5413       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
5414 }
5415 
5416 StmtResult
5417 Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
5418                                            Stmt *AStmt, SourceLocation StartLoc,
5419                                            SourceLocation EndLoc) {
5420   if (!AStmt)
5421     return StmtError();
5422 
5423   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5424   auto BaseStmt = AStmt;
5425   while (CapturedStmt *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
5426     BaseStmt = CS->getCapturedStmt();
5427   if (auto C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
5428     auto S = C->children();
5429     if (S.begin() == S.end())
5430       return StmtError();
5431     // All associated statements must be '#pragma omp section' except for
5432     // the first one.
5433     for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
5434       if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
5435         if (SectionStmt)
5436           Diag(SectionStmt->getLocStart(),
5437                diag::err_omp_parallel_sections_substmt_not_section);
5438         return StmtError();
5439       }
5440       cast<OMPSectionDirective>(SectionStmt)
5441           ->setHasCancel(DSAStack->isCancelRegion());
5442     }
5443   } else {
5444     Diag(AStmt->getLocStart(),
5445          diag::err_omp_parallel_sections_not_compound_stmt);
5446     return StmtError();
5447   }
5448 
5449   getCurFunction()->setHasBranchProtectedScope();
5450 
5451   return OMPParallelSectionsDirective::Create(
5452       Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
5453 }
5454 
5455 StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
5456                                           Stmt *AStmt, SourceLocation StartLoc,
5457                                           SourceLocation EndLoc) {
5458   if (!AStmt)
5459     return StmtError();
5460 
5461   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5462   // 1.2.2 OpenMP Language Terminology
5463   // Structured block - An executable statement with a single entry at the
5464   // top and a single exit at the bottom.
5465   // The point of exit cannot be a branch out of the structured block.
5466   // longjmp() and throw() must not violate the entry/exit criteria.
5467   CS->getCapturedDecl()->setNothrow();
5468 
5469   getCurFunction()->setHasBranchProtectedScope();
5470 
5471   return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
5472                                   DSAStack->isCancelRegion());
5473 }
5474 
5475 StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
5476                                                SourceLocation EndLoc) {
5477   return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
5478 }
5479 
5480 StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
5481                                              SourceLocation EndLoc) {
5482   return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
5483 }
5484 
5485 StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
5486                                               SourceLocation EndLoc) {
5487   return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
5488 }
5489 
5490 StmtResult Sema::ActOnOpenMPTaskgroupDirective(Stmt *AStmt,
5491                                                SourceLocation StartLoc,
5492                                                SourceLocation EndLoc) {
5493   if (!AStmt)
5494     return StmtError();
5495 
5496   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5497 
5498   getCurFunction()->setHasBranchProtectedScope();
5499 
5500   return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, AStmt);
5501 }
5502 
5503 StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
5504                                            SourceLocation StartLoc,
5505                                            SourceLocation EndLoc) {
5506   assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
5507   return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
5508 }
5509 
5510 StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
5511                                              Stmt *AStmt,
5512                                              SourceLocation StartLoc,
5513                                              SourceLocation EndLoc) {
5514   OMPClause *DependFound = nullptr;
5515   OMPClause *DependSourceClause = nullptr;
5516   OMPClause *DependSinkClause = nullptr;
5517   bool ErrorFound = false;
5518   OMPThreadsClause *TC = nullptr;
5519   OMPSIMDClause *SC = nullptr;
5520   for (auto *C : Clauses) {
5521     if (auto *DC = dyn_cast<OMPDependClause>(C)) {
5522       DependFound = C;
5523       if (DC->getDependencyKind() == OMPC_DEPEND_source) {
5524         if (DependSourceClause) {
5525           Diag(C->getLocStart(), diag::err_omp_more_one_clause)
5526               << getOpenMPDirectiveName(OMPD_ordered)
5527               << getOpenMPClauseName(OMPC_depend) << 2;
5528           ErrorFound = true;
5529         } else
5530           DependSourceClause = C;
5531         if (DependSinkClause) {
5532           Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
5533               << 0;
5534           ErrorFound = true;
5535         }
5536       } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
5537         if (DependSourceClause) {
5538           Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
5539               << 1;
5540           ErrorFound = true;
5541         }
5542         DependSinkClause = C;
5543       }
5544     } else if (C->getClauseKind() == OMPC_threads)
5545       TC = cast<OMPThreadsClause>(C);
5546     else if (C->getClauseKind() == OMPC_simd)
5547       SC = cast<OMPSIMDClause>(C);
5548   }
5549   if (!ErrorFound && !SC &&
5550       isOpenMPSimdDirective(DSAStack->getParentDirective())) {
5551     // OpenMP [2.8.1,simd Construct, Restrictions]
5552     // An ordered construct with the simd clause is the only OpenMP construct
5553     // that can appear in the simd region.
5554     Diag(StartLoc, diag::err_omp_prohibited_region_simd);
5555     ErrorFound = true;
5556   } else if (DependFound && (TC || SC)) {
5557     Diag(DependFound->getLocStart(), diag::err_omp_depend_clause_thread_simd)
5558         << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
5559     ErrorFound = true;
5560   } else if (DependFound && !DSAStack->getParentOrderedRegionParam()) {
5561     Diag(DependFound->getLocStart(),
5562          diag::err_omp_ordered_directive_without_param);
5563     ErrorFound = true;
5564   } else if (TC || Clauses.empty()) {
5565     if (auto *Param = DSAStack->getParentOrderedRegionParam()) {
5566       SourceLocation ErrLoc = TC ? TC->getLocStart() : StartLoc;
5567       Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
5568           << (TC != nullptr);
5569       Diag(Param->getLocStart(), diag::note_omp_ordered_param);
5570       ErrorFound = true;
5571     }
5572   }
5573   if ((!AStmt && !DependFound) || ErrorFound)
5574     return StmtError();
5575 
5576   if (AStmt) {
5577     assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5578 
5579     getCurFunction()->setHasBranchProtectedScope();
5580   }
5581 
5582   return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
5583 }
5584 
5585 namespace {
5586 /// \brief Helper class for checking expression in 'omp atomic [update]'
5587 /// construct.
5588 class OpenMPAtomicUpdateChecker {
5589   /// \brief Error results for atomic update expressions.
5590   enum ExprAnalysisErrorCode {
5591     /// \brief A statement is not an expression statement.
5592     NotAnExpression,
5593     /// \brief Expression is not builtin binary or unary operation.
5594     NotABinaryOrUnaryExpression,
5595     /// \brief Unary operation is not post-/pre- increment/decrement operation.
5596     NotAnUnaryIncDecExpression,
5597     /// \brief An expression is not of scalar type.
5598     NotAScalarType,
5599     /// \brief A binary operation is not an assignment operation.
5600     NotAnAssignmentOp,
5601     /// \brief RHS part of the binary operation is not a binary expression.
5602     NotABinaryExpression,
5603     /// \brief RHS part is not additive/multiplicative/shift/biwise binary
5604     /// expression.
5605     NotABinaryOperator,
5606     /// \brief RHS binary operation does not have reference to the updated LHS
5607     /// part.
5608     NotAnUpdateExpression,
5609     /// \brief No errors is found.
5610     NoError
5611   };
5612   /// \brief Reference to Sema.
5613   Sema &SemaRef;
5614   /// \brief A location for note diagnostics (when error is found).
5615   SourceLocation NoteLoc;
5616   /// \brief 'x' lvalue part of the source atomic expression.
5617   Expr *X;
5618   /// \brief 'expr' rvalue part of the source atomic expression.
5619   Expr *E;
5620   /// \brief Helper expression of the form
5621   /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
5622   /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
5623   Expr *UpdateExpr;
5624   /// \brief Is 'x' a LHS in a RHS part of full update expression. It is
5625   /// important for non-associative operations.
5626   bool IsXLHSInRHSPart;
5627   BinaryOperatorKind Op;
5628   SourceLocation OpLoc;
5629   /// \brief true if the source expression is a postfix unary operation, false
5630   /// if it is a prefix unary operation.
5631   bool IsPostfixUpdate;
5632 
5633 public:
5634   OpenMPAtomicUpdateChecker(Sema &SemaRef)
5635       : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
5636         IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
5637   /// \brief Check specified statement that it is suitable for 'atomic update'
5638   /// constructs and extract 'x', 'expr' and Operation from the original
5639   /// expression. If DiagId and NoteId == 0, then only check is performed
5640   /// without error notification.
5641   /// \param DiagId Diagnostic which should be emitted if error is found.
5642   /// \param NoteId Diagnostic note for the main error message.
5643   /// \return true if statement is not an update expression, false otherwise.
5644   bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
5645   /// \brief Return the 'x' lvalue part of the source atomic expression.
5646   Expr *getX() const { return X; }
5647   /// \brief Return the 'expr' rvalue part of the source atomic expression.
5648   Expr *getExpr() const { return E; }
5649   /// \brief Return the update expression used in calculation of the updated
5650   /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
5651   /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
5652   Expr *getUpdateExpr() const { return UpdateExpr; }
5653   /// \brief Return true if 'x' is LHS in RHS part of full update expression,
5654   /// false otherwise.
5655   bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
5656 
5657   /// \brief true if the source expression is a postfix unary operation, false
5658   /// if it is a prefix unary operation.
5659   bool isPostfixUpdate() const { return IsPostfixUpdate; }
5660 
5661 private:
5662   bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
5663                             unsigned NoteId = 0);
5664 };
5665 } // namespace
5666 
5667 bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
5668     BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
5669   ExprAnalysisErrorCode ErrorFound = NoError;
5670   SourceLocation ErrorLoc, NoteLoc;
5671   SourceRange ErrorRange, NoteRange;
5672   // Allowed constructs are:
5673   //  x = x binop expr;
5674   //  x = expr binop x;
5675   if (AtomicBinOp->getOpcode() == BO_Assign) {
5676     X = AtomicBinOp->getLHS();
5677     if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
5678             AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
5679       if (AtomicInnerBinOp->isMultiplicativeOp() ||
5680           AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
5681           AtomicInnerBinOp->isBitwiseOp()) {
5682         Op = AtomicInnerBinOp->getOpcode();
5683         OpLoc = AtomicInnerBinOp->getOperatorLoc();
5684         auto *LHS = AtomicInnerBinOp->getLHS();
5685         auto *RHS = AtomicInnerBinOp->getRHS();
5686         llvm::FoldingSetNodeID XId, LHSId, RHSId;
5687         X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
5688                                           /*Canonical=*/true);
5689         LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
5690                                             /*Canonical=*/true);
5691         RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
5692                                             /*Canonical=*/true);
5693         if (XId == LHSId) {
5694           E = RHS;
5695           IsXLHSInRHSPart = true;
5696         } else if (XId == RHSId) {
5697           E = LHS;
5698           IsXLHSInRHSPart = false;
5699         } else {
5700           ErrorLoc = AtomicInnerBinOp->getExprLoc();
5701           ErrorRange = AtomicInnerBinOp->getSourceRange();
5702           NoteLoc = X->getExprLoc();
5703           NoteRange = X->getSourceRange();
5704           ErrorFound = NotAnUpdateExpression;
5705         }
5706       } else {
5707         ErrorLoc = AtomicInnerBinOp->getExprLoc();
5708         ErrorRange = AtomicInnerBinOp->getSourceRange();
5709         NoteLoc = AtomicInnerBinOp->getOperatorLoc();
5710         NoteRange = SourceRange(NoteLoc, NoteLoc);
5711         ErrorFound = NotABinaryOperator;
5712       }
5713     } else {
5714       NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
5715       NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
5716       ErrorFound = NotABinaryExpression;
5717     }
5718   } else {
5719     ErrorLoc = AtomicBinOp->getExprLoc();
5720     ErrorRange = AtomicBinOp->getSourceRange();
5721     NoteLoc = AtomicBinOp->getOperatorLoc();
5722     NoteRange = SourceRange(NoteLoc, NoteLoc);
5723     ErrorFound = NotAnAssignmentOp;
5724   }
5725   if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
5726     SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
5727     SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
5728     return true;
5729   } else if (SemaRef.CurContext->isDependentContext())
5730     E = X = UpdateExpr = nullptr;
5731   return ErrorFound != NoError;
5732 }
5733 
5734 bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
5735                                                unsigned NoteId) {
5736   ExprAnalysisErrorCode ErrorFound = NoError;
5737   SourceLocation ErrorLoc, NoteLoc;
5738   SourceRange ErrorRange, NoteRange;
5739   // Allowed constructs are:
5740   //  x++;
5741   //  x--;
5742   //  ++x;
5743   //  --x;
5744   //  x binop= expr;
5745   //  x = x binop expr;
5746   //  x = expr binop x;
5747   if (auto *AtomicBody = dyn_cast<Expr>(S)) {
5748     AtomicBody = AtomicBody->IgnoreParenImpCasts();
5749     if (AtomicBody->getType()->isScalarType() ||
5750         AtomicBody->isInstantiationDependent()) {
5751       if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
5752               AtomicBody->IgnoreParenImpCasts())) {
5753         // Check for Compound Assignment Operation
5754         Op = BinaryOperator::getOpForCompoundAssignment(
5755             AtomicCompAssignOp->getOpcode());
5756         OpLoc = AtomicCompAssignOp->getOperatorLoc();
5757         E = AtomicCompAssignOp->getRHS();
5758         X = AtomicCompAssignOp->getLHS();
5759         IsXLHSInRHSPart = true;
5760       } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
5761                      AtomicBody->IgnoreParenImpCasts())) {
5762         // Check for Binary Operation
5763         if(checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
5764           return true;
5765       } else if (auto *AtomicUnaryOp =
5766                  dyn_cast<UnaryOperator>(AtomicBody->IgnoreParenImpCasts())) {
5767         // Check for Unary Operation
5768         if (AtomicUnaryOp->isIncrementDecrementOp()) {
5769           IsPostfixUpdate = AtomicUnaryOp->isPostfix();
5770           Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
5771           OpLoc = AtomicUnaryOp->getOperatorLoc();
5772           X = AtomicUnaryOp->getSubExpr();
5773           E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
5774           IsXLHSInRHSPart = true;
5775         } else {
5776           ErrorFound = NotAnUnaryIncDecExpression;
5777           ErrorLoc = AtomicUnaryOp->getExprLoc();
5778           ErrorRange = AtomicUnaryOp->getSourceRange();
5779           NoteLoc = AtomicUnaryOp->getOperatorLoc();
5780           NoteRange = SourceRange(NoteLoc, NoteLoc);
5781         }
5782       } else if (!AtomicBody->isInstantiationDependent()) {
5783         ErrorFound = NotABinaryOrUnaryExpression;
5784         NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
5785         NoteRange = ErrorRange = AtomicBody->getSourceRange();
5786       }
5787     } else {
5788       ErrorFound = NotAScalarType;
5789       NoteLoc = ErrorLoc = AtomicBody->getLocStart();
5790       NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5791     }
5792   } else {
5793     ErrorFound = NotAnExpression;
5794     NoteLoc = ErrorLoc = S->getLocStart();
5795     NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5796   }
5797   if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
5798     SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
5799     SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
5800     return true;
5801   } else if (SemaRef.CurContext->isDependentContext())
5802     E = X = UpdateExpr = nullptr;
5803   if (ErrorFound == NoError && E && X) {
5804     // Build an update expression of form 'OpaqueValueExpr(x) binop
5805     // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
5806     // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
5807     auto *OVEX = new (SemaRef.getASTContext())
5808         OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
5809     auto *OVEExpr = new (SemaRef.getASTContext())
5810         OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
5811     auto Update =
5812         SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
5813                                    IsXLHSInRHSPart ? OVEExpr : OVEX);
5814     if (Update.isInvalid())
5815       return true;
5816     Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
5817                                                Sema::AA_Casting);
5818     if (Update.isInvalid())
5819       return true;
5820     UpdateExpr = Update.get();
5821   }
5822   return ErrorFound != NoError;
5823 }
5824 
5825 StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
5826                                             Stmt *AStmt,
5827                                             SourceLocation StartLoc,
5828                                             SourceLocation EndLoc) {
5829   if (!AStmt)
5830     return StmtError();
5831 
5832   auto CS = cast<CapturedStmt>(AStmt);
5833   // 1.2.2 OpenMP Language Terminology
5834   // Structured block - An executable statement with a single entry at the
5835   // top and a single exit at the bottom.
5836   // The point of exit cannot be a branch out of the structured block.
5837   // longjmp() and throw() must not violate the entry/exit criteria.
5838   OpenMPClauseKind AtomicKind = OMPC_unknown;
5839   SourceLocation AtomicKindLoc;
5840   for (auto *C : Clauses) {
5841     if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
5842         C->getClauseKind() == OMPC_update ||
5843         C->getClauseKind() == OMPC_capture) {
5844       if (AtomicKind != OMPC_unknown) {
5845         Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses)
5846             << SourceRange(C->getLocStart(), C->getLocEnd());
5847         Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
5848             << getOpenMPClauseName(AtomicKind);
5849       } else {
5850         AtomicKind = C->getClauseKind();
5851         AtomicKindLoc = C->getLocStart();
5852       }
5853     }
5854   }
5855 
5856   auto Body = CS->getCapturedStmt();
5857   if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
5858     Body = EWC->getSubExpr();
5859 
5860   Expr *X = nullptr;
5861   Expr *V = nullptr;
5862   Expr *E = nullptr;
5863   Expr *UE = nullptr;
5864   bool IsXLHSInRHSPart = false;
5865   bool IsPostfixUpdate = false;
5866   // OpenMP [2.12.6, atomic Construct]
5867   // In the next expressions:
5868   // * x and v (as applicable) are both l-value expressions with scalar type.
5869   // * During the execution of an atomic region, multiple syntactic
5870   // occurrences of x must designate the same storage location.
5871   // * Neither of v and expr (as applicable) may access the storage location
5872   // designated by x.
5873   // * Neither of x and expr (as applicable) may access the storage location
5874   // designated by v.
5875   // * expr is an expression with scalar type.
5876   // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
5877   // * binop, binop=, ++, and -- are not overloaded operators.
5878   // * The expression x binop expr must be numerically equivalent to x binop
5879   // (expr). This requirement is satisfied if the operators in expr have
5880   // precedence greater than binop, or by using parentheses around expr or
5881   // subexpressions of expr.
5882   // * The expression expr binop x must be numerically equivalent to (expr)
5883   // binop x. This requirement is satisfied if the operators in expr have
5884   // precedence equal to or greater than binop, or by using parentheses around
5885   // expr or subexpressions of expr.
5886   // * For forms that allow multiple occurrences of x, the number of times
5887   // that x is evaluated is unspecified.
5888   if (AtomicKind == OMPC_read) {
5889     enum {
5890       NotAnExpression,
5891       NotAnAssignmentOp,
5892       NotAScalarType,
5893       NotAnLValue,
5894       NoError
5895     } ErrorFound = NoError;
5896     SourceLocation ErrorLoc, NoteLoc;
5897     SourceRange ErrorRange, NoteRange;
5898     // If clause is read:
5899     //  v = x;
5900     if (auto AtomicBody = dyn_cast<Expr>(Body)) {
5901       auto AtomicBinOp =
5902           dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5903       if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
5904         X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
5905         V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
5906         if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
5907             (V->isInstantiationDependent() || V->getType()->isScalarType())) {
5908           if (!X->isLValue() || !V->isLValue()) {
5909             auto NotLValueExpr = X->isLValue() ? V : X;
5910             ErrorFound = NotAnLValue;
5911             ErrorLoc = AtomicBinOp->getExprLoc();
5912             ErrorRange = AtomicBinOp->getSourceRange();
5913             NoteLoc = NotLValueExpr->getExprLoc();
5914             NoteRange = NotLValueExpr->getSourceRange();
5915           }
5916         } else if (!X->isInstantiationDependent() ||
5917                    !V->isInstantiationDependent()) {
5918           auto NotScalarExpr =
5919               (X->isInstantiationDependent() || X->getType()->isScalarType())
5920                   ? V
5921                   : X;
5922           ErrorFound = NotAScalarType;
5923           ErrorLoc = AtomicBinOp->getExprLoc();
5924           ErrorRange = AtomicBinOp->getSourceRange();
5925           NoteLoc = NotScalarExpr->getExprLoc();
5926           NoteRange = NotScalarExpr->getSourceRange();
5927         }
5928       } else if (!AtomicBody->isInstantiationDependent()) {
5929         ErrorFound = NotAnAssignmentOp;
5930         ErrorLoc = AtomicBody->getExprLoc();
5931         ErrorRange = AtomicBody->getSourceRange();
5932         NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5933                               : AtomicBody->getExprLoc();
5934         NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5935                                 : AtomicBody->getSourceRange();
5936       }
5937     } else {
5938       ErrorFound = NotAnExpression;
5939       NoteLoc = ErrorLoc = Body->getLocStart();
5940       NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5941     }
5942     if (ErrorFound != NoError) {
5943       Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
5944           << ErrorRange;
5945       Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
5946                                                       << NoteRange;
5947       return StmtError();
5948     } else if (CurContext->isDependentContext())
5949       V = X = nullptr;
5950   } else if (AtomicKind == OMPC_write) {
5951     enum {
5952       NotAnExpression,
5953       NotAnAssignmentOp,
5954       NotAScalarType,
5955       NotAnLValue,
5956       NoError
5957     } ErrorFound = NoError;
5958     SourceLocation ErrorLoc, NoteLoc;
5959     SourceRange ErrorRange, NoteRange;
5960     // If clause is write:
5961     //  x = expr;
5962     if (auto AtomicBody = dyn_cast<Expr>(Body)) {
5963       auto AtomicBinOp =
5964           dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5965       if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
5966         X = AtomicBinOp->getLHS();
5967         E = AtomicBinOp->getRHS();
5968         if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
5969             (E->isInstantiationDependent() || E->getType()->isScalarType())) {
5970           if (!X->isLValue()) {
5971             ErrorFound = NotAnLValue;
5972             ErrorLoc = AtomicBinOp->getExprLoc();
5973             ErrorRange = AtomicBinOp->getSourceRange();
5974             NoteLoc = X->getExprLoc();
5975             NoteRange = X->getSourceRange();
5976           }
5977         } else if (!X->isInstantiationDependent() ||
5978                    !E->isInstantiationDependent()) {
5979           auto NotScalarExpr =
5980               (X->isInstantiationDependent() || X->getType()->isScalarType())
5981                   ? E
5982                   : X;
5983           ErrorFound = NotAScalarType;
5984           ErrorLoc = AtomicBinOp->getExprLoc();
5985           ErrorRange = AtomicBinOp->getSourceRange();
5986           NoteLoc = NotScalarExpr->getExprLoc();
5987           NoteRange = NotScalarExpr->getSourceRange();
5988         }
5989       } else if (!AtomicBody->isInstantiationDependent()) {
5990         ErrorFound = NotAnAssignmentOp;
5991         ErrorLoc = AtomicBody->getExprLoc();
5992         ErrorRange = AtomicBody->getSourceRange();
5993         NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5994                               : AtomicBody->getExprLoc();
5995         NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5996                                 : AtomicBody->getSourceRange();
5997       }
5998     } else {
5999       ErrorFound = NotAnExpression;
6000       NoteLoc = ErrorLoc = Body->getLocStart();
6001       NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
6002     }
6003     if (ErrorFound != NoError) {
6004       Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
6005           << ErrorRange;
6006       Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
6007                                                       << NoteRange;
6008       return StmtError();
6009     } else if (CurContext->isDependentContext())
6010       E = X = nullptr;
6011   } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
6012     // If clause is update:
6013     //  x++;
6014     //  x--;
6015     //  ++x;
6016     //  --x;
6017     //  x binop= expr;
6018     //  x = x binop expr;
6019     //  x = expr binop x;
6020     OpenMPAtomicUpdateChecker Checker(*this);
6021     if (Checker.checkStatement(
6022             Body, (AtomicKind == OMPC_update)
6023                       ? diag::err_omp_atomic_update_not_expression_statement
6024                       : diag::err_omp_atomic_not_expression_statement,
6025             diag::note_omp_atomic_update))
6026       return StmtError();
6027     if (!CurContext->isDependentContext()) {
6028       E = Checker.getExpr();
6029       X = Checker.getX();
6030       UE = Checker.getUpdateExpr();
6031       IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
6032     }
6033   } else if (AtomicKind == OMPC_capture) {
6034     enum {
6035       NotAnAssignmentOp,
6036       NotACompoundStatement,
6037       NotTwoSubstatements,
6038       NotASpecificExpression,
6039       NoError
6040     } ErrorFound = NoError;
6041     SourceLocation ErrorLoc, NoteLoc;
6042     SourceRange ErrorRange, NoteRange;
6043     if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
6044       // If clause is a capture:
6045       //  v = x++;
6046       //  v = x--;
6047       //  v = ++x;
6048       //  v = --x;
6049       //  v = x binop= expr;
6050       //  v = x = x binop expr;
6051       //  v = x = expr binop x;
6052       auto *AtomicBinOp =
6053           dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
6054       if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
6055         V = AtomicBinOp->getLHS();
6056         Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
6057         OpenMPAtomicUpdateChecker Checker(*this);
6058         if (Checker.checkStatement(
6059                 Body, diag::err_omp_atomic_capture_not_expression_statement,
6060                 diag::note_omp_atomic_update))
6061           return StmtError();
6062         E = Checker.getExpr();
6063         X = Checker.getX();
6064         UE = Checker.getUpdateExpr();
6065         IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
6066         IsPostfixUpdate = Checker.isPostfixUpdate();
6067       } else if (!AtomicBody->isInstantiationDependent()) {
6068         ErrorLoc = AtomicBody->getExprLoc();
6069         ErrorRange = AtomicBody->getSourceRange();
6070         NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
6071                               : AtomicBody->getExprLoc();
6072         NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
6073                                 : AtomicBody->getSourceRange();
6074         ErrorFound = NotAnAssignmentOp;
6075       }
6076       if (ErrorFound != NoError) {
6077         Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
6078             << ErrorRange;
6079         Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
6080         return StmtError();
6081       } else if (CurContext->isDependentContext()) {
6082         UE = V = E = X = nullptr;
6083       }
6084     } else {
6085       // If clause is a capture:
6086       //  { v = x; x = expr; }
6087       //  { v = x; x++; }
6088       //  { v = x; x--; }
6089       //  { v = x; ++x; }
6090       //  { v = x; --x; }
6091       //  { v = x; x binop= expr; }
6092       //  { v = x; x = x binop expr; }
6093       //  { v = x; x = expr binop x; }
6094       //  { x++; v = x; }
6095       //  { x--; v = x; }
6096       //  { ++x; v = x; }
6097       //  { --x; v = x; }
6098       //  { x binop= expr; v = x; }
6099       //  { x = x binop expr; v = x; }
6100       //  { x = expr binop x; v = x; }
6101       if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
6102         // Check that this is { expr1; expr2; }
6103         if (CS->size() == 2) {
6104           auto *First = CS->body_front();
6105           auto *Second = CS->body_back();
6106           if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
6107             First = EWC->getSubExpr()->IgnoreParenImpCasts();
6108           if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
6109             Second = EWC->getSubExpr()->IgnoreParenImpCasts();
6110           // Need to find what subexpression is 'v' and what is 'x'.
6111           OpenMPAtomicUpdateChecker Checker(*this);
6112           bool IsUpdateExprFound = !Checker.checkStatement(Second);
6113           BinaryOperator *BinOp = nullptr;
6114           if (IsUpdateExprFound) {
6115             BinOp = dyn_cast<BinaryOperator>(First);
6116             IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
6117           }
6118           if (IsUpdateExprFound && !CurContext->isDependentContext()) {
6119             //  { v = x; x++; }
6120             //  { v = x; x--; }
6121             //  { v = x; ++x; }
6122             //  { v = x; --x; }
6123             //  { v = x; x binop= expr; }
6124             //  { v = x; x = x binop expr; }
6125             //  { v = x; x = expr binop x; }
6126             // Check that the first expression has form v = x.
6127             auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
6128             llvm::FoldingSetNodeID XId, PossibleXId;
6129             Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
6130             PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
6131             IsUpdateExprFound = XId == PossibleXId;
6132             if (IsUpdateExprFound) {
6133               V = BinOp->getLHS();
6134               X = Checker.getX();
6135               E = Checker.getExpr();
6136               UE = Checker.getUpdateExpr();
6137               IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
6138               IsPostfixUpdate = true;
6139             }
6140           }
6141           if (!IsUpdateExprFound) {
6142             IsUpdateExprFound = !Checker.checkStatement(First);
6143             BinOp = nullptr;
6144             if (IsUpdateExprFound) {
6145               BinOp = dyn_cast<BinaryOperator>(Second);
6146               IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
6147             }
6148             if (IsUpdateExprFound && !CurContext->isDependentContext()) {
6149               //  { x++; v = x; }
6150               //  { x--; v = x; }
6151               //  { ++x; v = x; }
6152               //  { --x; v = x; }
6153               //  { x binop= expr; v = x; }
6154               //  { x = x binop expr; v = x; }
6155               //  { x = expr binop x; v = x; }
6156               // Check that the second expression has form v = x.
6157               auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
6158               llvm::FoldingSetNodeID XId, PossibleXId;
6159               Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
6160               PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
6161               IsUpdateExprFound = XId == PossibleXId;
6162               if (IsUpdateExprFound) {
6163                 V = BinOp->getLHS();
6164                 X = Checker.getX();
6165                 E = Checker.getExpr();
6166                 UE = Checker.getUpdateExpr();
6167                 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
6168                 IsPostfixUpdate = false;
6169               }
6170             }
6171           }
6172           if (!IsUpdateExprFound) {
6173             //  { v = x; x = expr; }
6174             auto *FirstExpr = dyn_cast<Expr>(First);
6175             auto *SecondExpr = dyn_cast<Expr>(Second);
6176             if (!FirstExpr || !SecondExpr ||
6177                 !(FirstExpr->isInstantiationDependent() ||
6178                   SecondExpr->isInstantiationDependent())) {
6179               auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
6180               if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
6181                 ErrorFound = NotAnAssignmentOp;
6182                 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
6183                                                 : First->getLocStart();
6184                 NoteRange = ErrorRange = FirstBinOp
6185                                              ? FirstBinOp->getSourceRange()
6186                                              : SourceRange(ErrorLoc, ErrorLoc);
6187               } else {
6188                 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
6189                 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
6190                   ErrorFound = NotAnAssignmentOp;
6191                   NoteLoc = ErrorLoc = SecondBinOp
6192                                            ? SecondBinOp->getOperatorLoc()
6193                                            : Second->getLocStart();
6194                   NoteRange = ErrorRange =
6195                       SecondBinOp ? SecondBinOp->getSourceRange()
6196                                   : SourceRange(ErrorLoc, ErrorLoc);
6197                 } else {
6198                   auto *PossibleXRHSInFirst =
6199                       FirstBinOp->getRHS()->IgnoreParenImpCasts();
6200                   auto *PossibleXLHSInSecond =
6201                       SecondBinOp->getLHS()->IgnoreParenImpCasts();
6202                   llvm::FoldingSetNodeID X1Id, X2Id;
6203                   PossibleXRHSInFirst->Profile(X1Id, Context,
6204                                                /*Canonical=*/true);
6205                   PossibleXLHSInSecond->Profile(X2Id, Context,
6206                                                 /*Canonical=*/true);
6207                   IsUpdateExprFound = X1Id == X2Id;
6208                   if (IsUpdateExprFound) {
6209                     V = FirstBinOp->getLHS();
6210                     X = SecondBinOp->getLHS();
6211                     E = SecondBinOp->getRHS();
6212                     UE = nullptr;
6213                     IsXLHSInRHSPart = false;
6214                     IsPostfixUpdate = true;
6215                   } else {
6216                     ErrorFound = NotASpecificExpression;
6217                     ErrorLoc = FirstBinOp->getExprLoc();
6218                     ErrorRange = FirstBinOp->getSourceRange();
6219                     NoteLoc = SecondBinOp->getLHS()->getExprLoc();
6220                     NoteRange = SecondBinOp->getRHS()->getSourceRange();
6221                   }
6222                 }
6223               }
6224             }
6225           }
6226         } else {
6227           NoteLoc = ErrorLoc = Body->getLocStart();
6228           NoteRange = ErrorRange =
6229               SourceRange(Body->getLocStart(), Body->getLocStart());
6230           ErrorFound = NotTwoSubstatements;
6231         }
6232       } else {
6233         NoteLoc = ErrorLoc = Body->getLocStart();
6234         NoteRange = ErrorRange =
6235             SourceRange(Body->getLocStart(), Body->getLocStart());
6236         ErrorFound = NotACompoundStatement;
6237       }
6238       if (ErrorFound != NoError) {
6239         Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
6240             << ErrorRange;
6241         Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
6242         return StmtError();
6243       } else if (CurContext->isDependentContext()) {
6244         UE = V = E = X = nullptr;
6245       }
6246     }
6247   }
6248 
6249   getCurFunction()->setHasBranchProtectedScope();
6250 
6251   return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
6252                                     X, V, E, UE, IsXLHSInRHSPart,
6253                                     IsPostfixUpdate);
6254 }
6255 
6256 StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
6257                                             Stmt *AStmt,
6258                                             SourceLocation StartLoc,
6259                                             SourceLocation EndLoc) {
6260   if (!AStmt)
6261     return StmtError();
6262 
6263   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6264   // 1.2.2 OpenMP Language Terminology
6265   // Structured block - An executable statement with a single entry at the
6266   // top and a single exit at the bottom.
6267   // The point of exit cannot be a branch out of the structured block.
6268   // longjmp() and throw() must not violate the entry/exit criteria.
6269   CS->getCapturedDecl()->setNothrow();
6270 
6271   // OpenMP [2.16, Nesting of Regions]
6272   // If specified, a teams construct must be contained within a target
6273   // construct. That target construct must contain no statements or directives
6274   // outside of the teams construct.
6275   if (DSAStack->hasInnerTeamsRegion()) {
6276     auto S = AStmt->IgnoreContainers(/*IgnoreCaptured*/ true);
6277     bool OMPTeamsFound = true;
6278     if (auto *CS = dyn_cast<CompoundStmt>(S)) {
6279       auto I = CS->body_begin();
6280       while (I != CS->body_end()) {
6281         auto OED = dyn_cast<OMPExecutableDirective>(*I);
6282         if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) {
6283           OMPTeamsFound = false;
6284           break;
6285         }
6286         ++I;
6287       }
6288       assert(I != CS->body_end() && "Not found statement");
6289       S = *I;
6290     }
6291     if (!OMPTeamsFound) {
6292       Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
6293       Diag(DSAStack->getInnerTeamsRegionLoc(),
6294            diag::note_omp_nested_teams_construct_here);
6295       Diag(S->getLocStart(), diag::note_omp_nested_statement_here)
6296           << isa<OMPExecutableDirective>(S);
6297       return StmtError();
6298     }
6299   }
6300 
6301   getCurFunction()->setHasBranchProtectedScope();
6302 
6303   return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
6304 }
6305 
6306 StmtResult
6307 Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
6308                                          Stmt *AStmt, SourceLocation StartLoc,
6309                                          SourceLocation EndLoc) {
6310   if (!AStmt)
6311     return StmtError();
6312 
6313   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6314   // 1.2.2 OpenMP Language Terminology
6315   // Structured block - An executable statement with a single entry at the
6316   // top and a single exit at the bottom.
6317   // The point of exit cannot be a branch out of the structured block.
6318   // longjmp() and throw() must not violate the entry/exit criteria.
6319   CS->getCapturedDecl()->setNothrow();
6320 
6321   getCurFunction()->setHasBranchProtectedScope();
6322 
6323   return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
6324                                             AStmt);
6325 }
6326 
6327 StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
6328     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6329     SourceLocation EndLoc,
6330     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6331   if (!AStmt)
6332     return StmtError();
6333 
6334   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6335   // 1.2.2 OpenMP Language Terminology
6336   // Structured block - An executable statement with a single entry at the
6337   // top and a single exit at the bottom.
6338   // The point of exit cannot be a branch out of the structured block.
6339   // longjmp() and throw() must not violate the entry/exit criteria.
6340   CS->getCapturedDecl()->setNothrow();
6341 
6342   OMPLoopDirective::HelperExprs B;
6343   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6344   // define the nested loops number.
6345   unsigned NestedLoopCount =
6346       CheckOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
6347                       getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6348                       VarsWithImplicitDSA, B);
6349   if (NestedLoopCount == 0)
6350     return StmtError();
6351 
6352   assert((CurContext->isDependentContext() || B.builtAll()) &&
6353          "omp target parallel for loop exprs were not built");
6354 
6355   if (!CurContext->isDependentContext()) {
6356     // Finalize the clauses that need pre-built expressions for CodeGen.
6357     for (auto C : Clauses) {
6358       if (auto LC = dyn_cast<OMPLinearClause>(C))
6359         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6360                                      B.NumIterations, *this, CurScope,
6361                                      DSAStack))
6362           return StmtError();
6363     }
6364   }
6365 
6366   getCurFunction()->setHasBranchProtectedScope();
6367   return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
6368                                                NestedLoopCount, Clauses, AStmt,
6369                                                B, DSAStack->isCancelRegion());
6370 }
6371 
6372 /// \brief Check for existence of a map clause in the list of clauses.
6373 static bool HasMapClause(ArrayRef<OMPClause *> Clauses) {
6374   for (ArrayRef<OMPClause *>::iterator I = Clauses.begin(), E = Clauses.end();
6375        I != E; ++I) {
6376     if (*I != nullptr && (*I)->getClauseKind() == OMPC_map) {
6377       return true;
6378     }
6379   }
6380 
6381   return false;
6382 }
6383 
6384 StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
6385                                                 Stmt *AStmt,
6386                                                 SourceLocation StartLoc,
6387                                                 SourceLocation EndLoc) {
6388   if (!AStmt)
6389     return StmtError();
6390 
6391   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6392 
6393   // OpenMP [2.10.1, Restrictions, p. 97]
6394   // At least one map clause must appear on the directive.
6395   if (!HasMapClause(Clauses)) {
6396     Diag(StartLoc, diag::err_omp_no_map_for_directive) <<
6397         getOpenMPDirectiveName(OMPD_target_data);
6398     return StmtError();
6399   }
6400 
6401   getCurFunction()->setHasBranchProtectedScope();
6402 
6403   return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
6404                                         AStmt);
6405 }
6406 
6407 StmtResult
6408 Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
6409                                           SourceLocation StartLoc,
6410                                           SourceLocation EndLoc) {
6411   // OpenMP [2.10.2, Restrictions, p. 99]
6412   // At least one map clause must appear on the directive.
6413   if (!HasMapClause(Clauses)) {
6414     Diag(StartLoc, diag::err_omp_no_map_for_directive)
6415         << getOpenMPDirectiveName(OMPD_target_enter_data);
6416     return StmtError();
6417   }
6418 
6419   return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc,
6420                                              Clauses);
6421 }
6422 
6423 StmtResult
6424 Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
6425                                          SourceLocation StartLoc,
6426                                          SourceLocation EndLoc) {
6427   // OpenMP [2.10.3, Restrictions, p. 102]
6428   // At least one map clause must appear on the directive.
6429   if (!HasMapClause(Clauses)) {
6430     Diag(StartLoc, diag::err_omp_no_map_for_directive)
6431         << getOpenMPDirectiveName(OMPD_target_exit_data);
6432     return StmtError();
6433   }
6434 
6435   return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses);
6436 }
6437 
6438 StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
6439                                            Stmt *AStmt, SourceLocation StartLoc,
6440                                            SourceLocation EndLoc) {
6441   if (!AStmt)
6442     return StmtError();
6443 
6444   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6445   // 1.2.2 OpenMP Language Terminology
6446   // Structured block - An executable statement with a single entry at the
6447   // top and a single exit at the bottom.
6448   // The point of exit cannot be a branch out of the structured block.
6449   // longjmp() and throw() must not violate the entry/exit criteria.
6450   CS->getCapturedDecl()->setNothrow();
6451 
6452   getCurFunction()->setHasBranchProtectedScope();
6453 
6454   return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
6455 }
6456 
6457 StmtResult
6458 Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
6459                                             SourceLocation EndLoc,
6460                                             OpenMPDirectiveKind CancelRegion) {
6461   if (CancelRegion != OMPD_parallel && CancelRegion != OMPD_for &&
6462       CancelRegion != OMPD_sections && CancelRegion != OMPD_taskgroup) {
6463     Diag(StartLoc, diag::err_omp_wrong_cancel_region)
6464         << getOpenMPDirectiveName(CancelRegion);
6465     return StmtError();
6466   }
6467   if (DSAStack->isParentNowaitRegion()) {
6468     Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
6469     return StmtError();
6470   }
6471   if (DSAStack->isParentOrderedRegion()) {
6472     Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
6473     return StmtError();
6474   }
6475   return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
6476                                                CancelRegion);
6477 }
6478 
6479 StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
6480                                             SourceLocation StartLoc,
6481                                             SourceLocation EndLoc,
6482                                             OpenMPDirectiveKind CancelRegion) {
6483   if (CancelRegion != OMPD_parallel && CancelRegion != OMPD_for &&
6484       CancelRegion != OMPD_sections && CancelRegion != OMPD_taskgroup) {
6485     Diag(StartLoc, diag::err_omp_wrong_cancel_region)
6486         << getOpenMPDirectiveName(CancelRegion);
6487     return StmtError();
6488   }
6489   if (DSAStack->isParentNowaitRegion()) {
6490     Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
6491     return StmtError();
6492   }
6493   if (DSAStack->isParentOrderedRegion()) {
6494     Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
6495     return StmtError();
6496   }
6497   DSAStack->setParentCancelRegion(/*Cancel=*/true);
6498   return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
6499                                     CancelRegion);
6500 }
6501 
6502 static bool checkGrainsizeNumTasksClauses(Sema &S,
6503                                           ArrayRef<OMPClause *> Clauses) {
6504   OMPClause *PrevClause = nullptr;
6505   bool ErrorFound = false;
6506   for (auto *C : Clauses) {
6507     if (C->getClauseKind() == OMPC_grainsize ||
6508         C->getClauseKind() == OMPC_num_tasks) {
6509       if (!PrevClause)
6510         PrevClause = C;
6511       else if (PrevClause->getClauseKind() != C->getClauseKind()) {
6512         S.Diag(C->getLocStart(),
6513                diag::err_omp_grainsize_num_tasks_mutually_exclusive)
6514             << getOpenMPClauseName(C->getClauseKind())
6515             << getOpenMPClauseName(PrevClause->getClauseKind());
6516         S.Diag(PrevClause->getLocStart(),
6517                diag::note_omp_previous_grainsize_num_tasks)
6518             << getOpenMPClauseName(PrevClause->getClauseKind());
6519         ErrorFound = true;
6520       }
6521     }
6522   }
6523   return ErrorFound;
6524 }
6525 
6526 StmtResult Sema::ActOnOpenMPTaskLoopDirective(
6527     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6528     SourceLocation EndLoc,
6529     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6530   if (!AStmt)
6531     return StmtError();
6532 
6533   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6534   OMPLoopDirective::HelperExprs B;
6535   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6536   // define the nested loops number.
6537   unsigned NestedLoopCount =
6538       CheckOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
6539                       /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
6540                       VarsWithImplicitDSA, B);
6541   if (NestedLoopCount == 0)
6542     return StmtError();
6543 
6544   assert((CurContext->isDependentContext() || B.builtAll()) &&
6545          "omp for loop exprs were not built");
6546 
6547   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6548   // The grainsize clause and num_tasks clause are mutually exclusive and may
6549   // not appear on the same taskloop directive.
6550   if (checkGrainsizeNumTasksClauses(*this, Clauses))
6551     return StmtError();
6552 
6553   getCurFunction()->setHasBranchProtectedScope();
6554   return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
6555                                       NestedLoopCount, Clauses, AStmt, B);
6556 }
6557 
6558 StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
6559     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6560     SourceLocation EndLoc,
6561     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6562   if (!AStmt)
6563     return StmtError();
6564 
6565   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6566   OMPLoopDirective::HelperExprs B;
6567   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6568   // define the nested loops number.
6569   unsigned NestedLoopCount =
6570       CheckOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
6571                       /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
6572                       VarsWithImplicitDSA, B);
6573   if (NestedLoopCount == 0)
6574     return StmtError();
6575 
6576   assert((CurContext->isDependentContext() || B.builtAll()) &&
6577          "omp for loop exprs were not built");
6578 
6579   if (!CurContext->isDependentContext()) {
6580     // Finalize the clauses that need pre-built expressions for CodeGen.
6581     for (auto C : Clauses) {
6582       if (auto LC = dyn_cast<OMPLinearClause>(C))
6583         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6584                                      B.NumIterations, *this, CurScope,
6585                                      DSAStack))
6586           return StmtError();
6587     }
6588   }
6589 
6590   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6591   // The grainsize clause and num_tasks clause are mutually exclusive and may
6592   // not appear on the same taskloop directive.
6593   if (checkGrainsizeNumTasksClauses(*this, Clauses))
6594     return StmtError();
6595 
6596   getCurFunction()->setHasBranchProtectedScope();
6597   return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
6598                                           NestedLoopCount, Clauses, AStmt, B);
6599 }
6600 
6601 StmtResult Sema::ActOnOpenMPDistributeDirective(
6602     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6603     SourceLocation EndLoc,
6604     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6605   if (!AStmt)
6606     return StmtError();
6607 
6608   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6609   OMPLoopDirective::HelperExprs B;
6610   // In presence of clause 'collapse' with number of loops, it will
6611   // define the nested loops number.
6612   unsigned NestedLoopCount =
6613       CheckOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
6614                       nullptr /*ordered not a clause on distribute*/, AStmt,
6615                       *this, *DSAStack, VarsWithImplicitDSA, B);
6616   if (NestedLoopCount == 0)
6617     return StmtError();
6618 
6619   assert((CurContext->isDependentContext() || B.builtAll()) &&
6620          "omp for loop exprs were not built");
6621 
6622   getCurFunction()->setHasBranchProtectedScope();
6623   return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
6624                                         NestedLoopCount, Clauses, AStmt, B);
6625 }
6626 
6627 OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
6628                                              SourceLocation StartLoc,
6629                                              SourceLocation LParenLoc,
6630                                              SourceLocation EndLoc) {
6631   OMPClause *Res = nullptr;
6632   switch (Kind) {
6633   case OMPC_final:
6634     Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
6635     break;
6636   case OMPC_num_threads:
6637     Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
6638     break;
6639   case OMPC_safelen:
6640     Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
6641     break;
6642   case OMPC_simdlen:
6643     Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
6644     break;
6645   case OMPC_collapse:
6646     Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
6647     break;
6648   case OMPC_ordered:
6649     Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
6650     break;
6651   case OMPC_device:
6652     Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
6653     break;
6654   case OMPC_num_teams:
6655     Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
6656     break;
6657   case OMPC_thread_limit:
6658     Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
6659     break;
6660   case OMPC_priority:
6661     Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
6662     break;
6663   case OMPC_grainsize:
6664     Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
6665     break;
6666   case OMPC_num_tasks:
6667     Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
6668     break;
6669   case OMPC_hint:
6670     Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
6671     break;
6672   case OMPC_if:
6673   case OMPC_default:
6674   case OMPC_proc_bind:
6675   case OMPC_schedule:
6676   case OMPC_private:
6677   case OMPC_firstprivate:
6678   case OMPC_lastprivate:
6679   case OMPC_shared:
6680   case OMPC_reduction:
6681   case OMPC_linear:
6682   case OMPC_aligned:
6683   case OMPC_copyin:
6684   case OMPC_copyprivate:
6685   case OMPC_nowait:
6686   case OMPC_untied:
6687   case OMPC_mergeable:
6688   case OMPC_threadprivate:
6689   case OMPC_flush:
6690   case OMPC_read:
6691   case OMPC_write:
6692   case OMPC_update:
6693   case OMPC_capture:
6694   case OMPC_seq_cst:
6695   case OMPC_depend:
6696   case OMPC_threads:
6697   case OMPC_simd:
6698   case OMPC_map:
6699   case OMPC_nogroup:
6700   case OMPC_dist_schedule:
6701   case OMPC_defaultmap:
6702   case OMPC_unknown:
6703   case OMPC_uniform:
6704     llvm_unreachable("Clause is not allowed.");
6705   }
6706   return Res;
6707 }
6708 
6709 OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
6710                                      Expr *Condition, SourceLocation StartLoc,
6711                                      SourceLocation LParenLoc,
6712                                      SourceLocation NameModifierLoc,
6713                                      SourceLocation ColonLoc,
6714                                      SourceLocation EndLoc) {
6715   Expr *ValExpr = Condition;
6716   if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
6717       !Condition->isInstantiationDependent() &&
6718       !Condition->containsUnexpandedParameterPack()) {
6719     ExprResult Val = ActOnBooleanCondition(DSAStack->getCurScope(),
6720                                            Condition->getExprLoc(), Condition);
6721     if (Val.isInvalid())
6722       return nullptr;
6723 
6724     ValExpr = Val.get();
6725   }
6726 
6727   return new (Context) OMPIfClause(NameModifier, ValExpr, StartLoc, LParenLoc,
6728                                    NameModifierLoc, ColonLoc, EndLoc);
6729 }
6730 
6731 OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
6732                                         SourceLocation StartLoc,
6733                                         SourceLocation LParenLoc,
6734                                         SourceLocation EndLoc) {
6735   Expr *ValExpr = Condition;
6736   if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
6737       !Condition->isInstantiationDependent() &&
6738       !Condition->containsUnexpandedParameterPack()) {
6739     ExprResult Val = ActOnBooleanCondition(DSAStack->getCurScope(),
6740                                            Condition->getExprLoc(), Condition);
6741     if (Val.isInvalid())
6742       return nullptr;
6743 
6744     ValExpr = Val.get();
6745   }
6746 
6747   return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
6748 }
6749 ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
6750                                                         Expr *Op) {
6751   if (!Op)
6752     return ExprError();
6753 
6754   class IntConvertDiagnoser : public ICEConvertDiagnoser {
6755   public:
6756     IntConvertDiagnoser()
6757         : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
6758     SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
6759                                          QualType T) override {
6760       return S.Diag(Loc, diag::err_omp_not_integral) << T;
6761     }
6762     SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
6763                                              QualType T) override {
6764       return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
6765     }
6766     SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
6767                                                QualType T,
6768                                                QualType ConvTy) override {
6769       return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
6770     }
6771     SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
6772                                            QualType ConvTy) override {
6773       return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
6774              << ConvTy->isEnumeralType() << ConvTy;
6775     }
6776     SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
6777                                             QualType T) override {
6778       return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
6779     }
6780     SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
6781                                         QualType ConvTy) override {
6782       return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
6783              << ConvTy->isEnumeralType() << ConvTy;
6784     }
6785     SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
6786                                              QualType) override {
6787       llvm_unreachable("conversion functions are permitted");
6788     }
6789   } ConvertDiagnoser;
6790   return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
6791 }
6792 
6793 static bool IsNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
6794                                       OpenMPClauseKind CKind,
6795                                       bool StrictlyPositive) {
6796   if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
6797       !ValExpr->isInstantiationDependent()) {
6798     SourceLocation Loc = ValExpr->getExprLoc();
6799     ExprResult Value =
6800         SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
6801     if (Value.isInvalid())
6802       return false;
6803 
6804     ValExpr = Value.get();
6805     // The expression must evaluate to a non-negative integer value.
6806     llvm::APSInt Result;
6807     if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
6808         Result.isSigned() &&
6809         !((!StrictlyPositive && Result.isNonNegative()) ||
6810           (StrictlyPositive && Result.isStrictlyPositive()))) {
6811       SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
6812           << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
6813           << ValExpr->getSourceRange();
6814       return false;
6815     }
6816   }
6817   return true;
6818 }
6819 
6820 OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
6821                                              SourceLocation StartLoc,
6822                                              SourceLocation LParenLoc,
6823                                              SourceLocation EndLoc) {
6824   Expr *ValExpr = NumThreads;
6825 
6826   // OpenMP [2.5, Restrictions]
6827   //  The num_threads expression must evaluate to a positive integer value.
6828   if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
6829                                  /*StrictlyPositive=*/true))
6830     return nullptr;
6831 
6832   return new (Context)
6833       OMPNumThreadsClause(ValExpr, StartLoc, LParenLoc, EndLoc);
6834 }
6835 
6836 ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
6837                                                        OpenMPClauseKind CKind,
6838                                                        bool StrictlyPositive) {
6839   if (!E)
6840     return ExprError();
6841   if (E->isValueDependent() || E->isTypeDependent() ||
6842       E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
6843     return E;
6844   llvm::APSInt Result;
6845   ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
6846   if (ICE.isInvalid())
6847     return ExprError();
6848   if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
6849       (!StrictlyPositive && !Result.isNonNegative())) {
6850     Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
6851         << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
6852         << E->getSourceRange();
6853     return ExprError();
6854   }
6855   if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
6856     Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
6857         << E->getSourceRange();
6858     return ExprError();
6859   }
6860   if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
6861     DSAStack->setAssociatedLoops(Result.getExtValue());
6862   else if (CKind == OMPC_ordered)
6863     DSAStack->setAssociatedLoops(Result.getExtValue());
6864   return ICE;
6865 }
6866 
6867 OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
6868                                           SourceLocation LParenLoc,
6869                                           SourceLocation EndLoc) {
6870   // OpenMP [2.8.1, simd construct, Description]
6871   // The parameter of the safelen clause must be a constant
6872   // positive integer expression.
6873   ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
6874   if (Safelen.isInvalid())
6875     return nullptr;
6876   return new (Context)
6877       OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
6878 }
6879 
6880 OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
6881                                           SourceLocation LParenLoc,
6882                                           SourceLocation EndLoc) {
6883   // OpenMP [2.8.1, simd construct, Description]
6884   // The parameter of the simdlen clause must be a constant
6885   // positive integer expression.
6886   ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
6887   if (Simdlen.isInvalid())
6888     return nullptr;
6889   return new (Context)
6890       OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
6891 }
6892 
6893 OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
6894                                            SourceLocation StartLoc,
6895                                            SourceLocation LParenLoc,
6896                                            SourceLocation EndLoc) {
6897   // OpenMP [2.7.1, loop construct, Description]
6898   // OpenMP [2.8.1, simd construct, Description]
6899   // OpenMP [2.9.6, distribute construct, Description]
6900   // The parameter of the collapse clause must be a constant
6901   // positive integer expression.
6902   ExprResult NumForLoopsResult =
6903       VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
6904   if (NumForLoopsResult.isInvalid())
6905     return nullptr;
6906   return new (Context)
6907       OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
6908 }
6909 
6910 OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
6911                                           SourceLocation EndLoc,
6912                                           SourceLocation LParenLoc,
6913                                           Expr *NumForLoops) {
6914   // OpenMP [2.7.1, loop construct, Description]
6915   // OpenMP [2.8.1, simd construct, Description]
6916   // OpenMP [2.9.6, distribute construct, Description]
6917   // The parameter of the ordered clause must be a constant
6918   // positive integer expression if any.
6919   if (NumForLoops && LParenLoc.isValid()) {
6920     ExprResult NumForLoopsResult =
6921         VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
6922     if (NumForLoopsResult.isInvalid())
6923       return nullptr;
6924     NumForLoops = NumForLoopsResult.get();
6925   } else
6926     NumForLoops = nullptr;
6927   DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops);
6928   return new (Context)
6929       OMPOrderedClause(NumForLoops, StartLoc, LParenLoc, EndLoc);
6930 }
6931 
6932 OMPClause *Sema::ActOnOpenMPSimpleClause(
6933     OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
6934     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
6935   OMPClause *Res = nullptr;
6936   switch (Kind) {
6937   case OMPC_default:
6938     Res =
6939         ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
6940                                  ArgumentLoc, StartLoc, LParenLoc, EndLoc);
6941     break;
6942   case OMPC_proc_bind:
6943     Res = ActOnOpenMPProcBindClause(
6944         static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
6945         LParenLoc, EndLoc);
6946     break;
6947   case OMPC_if:
6948   case OMPC_final:
6949   case OMPC_num_threads:
6950   case OMPC_safelen:
6951   case OMPC_simdlen:
6952   case OMPC_collapse:
6953   case OMPC_schedule:
6954   case OMPC_private:
6955   case OMPC_firstprivate:
6956   case OMPC_lastprivate:
6957   case OMPC_shared:
6958   case OMPC_reduction:
6959   case OMPC_linear:
6960   case OMPC_aligned:
6961   case OMPC_copyin:
6962   case OMPC_copyprivate:
6963   case OMPC_ordered:
6964   case OMPC_nowait:
6965   case OMPC_untied:
6966   case OMPC_mergeable:
6967   case OMPC_threadprivate:
6968   case OMPC_flush:
6969   case OMPC_read:
6970   case OMPC_write:
6971   case OMPC_update:
6972   case OMPC_capture:
6973   case OMPC_seq_cst:
6974   case OMPC_depend:
6975   case OMPC_device:
6976   case OMPC_threads:
6977   case OMPC_simd:
6978   case OMPC_map:
6979   case OMPC_num_teams:
6980   case OMPC_thread_limit:
6981   case OMPC_priority:
6982   case OMPC_grainsize:
6983   case OMPC_nogroup:
6984   case OMPC_num_tasks:
6985   case OMPC_hint:
6986   case OMPC_dist_schedule:
6987   case OMPC_defaultmap:
6988   case OMPC_unknown:
6989   case OMPC_uniform:
6990     llvm_unreachable("Clause is not allowed.");
6991   }
6992   return Res;
6993 }
6994 
6995 static std::string
6996 getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
6997                         ArrayRef<unsigned> Exclude = llvm::None) {
6998   std::string Values;
6999   unsigned Bound = Last >= 2 ? Last - 2 : 0;
7000   unsigned Skipped = Exclude.size();
7001   auto S = Exclude.begin(), E = Exclude.end();
7002   for (unsigned i = First; i < Last; ++i) {
7003     if (std::find(S, E, i) != E) {
7004       --Skipped;
7005       continue;
7006     }
7007     Values += "'";
7008     Values += getOpenMPSimpleClauseTypeName(K, i);
7009     Values += "'";
7010     if (i == Bound - Skipped)
7011       Values += " or ";
7012     else if (i != Bound + 1 - Skipped)
7013       Values += ", ";
7014   }
7015   return Values;
7016 }
7017 
7018 OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
7019                                           SourceLocation KindKwLoc,
7020                                           SourceLocation StartLoc,
7021                                           SourceLocation LParenLoc,
7022                                           SourceLocation EndLoc) {
7023   if (Kind == OMPC_DEFAULT_unknown) {
7024     static_assert(OMPC_DEFAULT_unknown > 0,
7025                   "OMPC_DEFAULT_unknown not greater than 0");
7026     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
7027         << getListOfPossibleValues(OMPC_default, /*First=*/0,
7028                                    /*Last=*/OMPC_DEFAULT_unknown)
7029         << getOpenMPClauseName(OMPC_default);
7030     return nullptr;
7031   }
7032   switch (Kind) {
7033   case OMPC_DEFAULT_none:
7034     DSAStack->setDefaultDSANone(KindKwLoc);
7035     break;
7036   case OMPC_DEFAULT_shared:
7037     DSAStack->setDefaultDSAShared(KindKwLoc);
7038     break;
7039   case OMPC_DEFAULT_unknown:
7040     llvm_unreachable("Clause kind is not allowed.");
7041     break;
7042   }
7043   return new (Context)
7044       OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
7045 }
7046 
7047 OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
7048                                            SourceLocation KindKwLoc,
7049                                            SourceLocation StartLoc,
7050                                            SourceLocation LParenLoc,
7051                                            SourceLocation EndLoc) {
7052   if (Kind == OMPC_PROC_BIND_unknown) {
7053     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
7054         << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
7055                                    /*Last=*/OMPC_PROC_BIND_unknown)
7056         << getOpenMPClauseName(OMPC_proc_bind);
7057     return nullptr;
7058   }
7059   return new (Context)
7060       OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
7061 }
7062 
7063 OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
7064     OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
7065     SourceLocation StartLoc, SourceLocation LParenLoc,
7066     ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
7067     SourceLocation EndLoc) {
7068   OMPClause *Res = nullptr;
7069   switch (Kind) {
7070   case OMPC_schedule:
7071     enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
7072     assert(Argument.size() == NumberOfElements &&
7073            ArgumentLoc.size() == NumberOfElements);
7074     Res = ActOnOpenMPScheduleClause(
7075         static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
7076         static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
7077         static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
7078         StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
7079         ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
7080     break;
7081   case OMPC_if:
7082     assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
7083     Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
7084                               Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
7085                               DelimLoc, EndLoc);
7086     break;
7087   case OMPC_dist_schedule:
7088     Res = ActOnOpenMPDistScheduleClause(
7089         static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
7090         StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
7091     break;
7092   case OMPC_defaultmap:
7093     enum { Modifier, DefaultmapKind };
7094     Res = ActOnOpenMPDefaultmapClause(
7095         static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
7096         static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
7097         StartLoc, LParenLoc, ArgumentLoc[Modifier],
7098         ArgumentLoc[DefaultmapKind], EndLoc);
7099     break;
7100   case OMPC_final:
7101   case OMPC_num_threads:
7102   case OMPC_safelen:
7103   case OMPC_simdlen:
7104   case OMPC_collapse:
7105   case OMPC_default:
7106   case OMPC_proc_bind:
7107   case OMPC_private:
7108   case OMPC_firstprivate:
7109   case OMPC_lastprivate:
7110   case OMPC_shared:
7111   case OMPC_reduction:
7112   case OMPC_linear:
7113   case OMPC_aligned:
7114   case OMPC_copyin:
7115   case OMPC_copyprivate:
7116   case OMPC_ordered:
7117   case OMPC_nowait:
7118   case OMPC_untied:
7119   case OMPC_mergeable:
7120   case OMPC_threadprivate:
7121   case OMPC_flush:
7122   case OMPC_read:
7123   case OMPC_write:
7124   case OMPC_update:
7125   case OMPC_capture:
7126   case OMPC_seq_cst:
7127   case OMPC_depend:
7128   case OMPC_device:
7129   case OMPC_threads:
7130   case OMPC_simd:
7131   case OMPC_map:
7132   case OMPC_num_teams:
7133   case OMPC_thread_limit:
7134   case OMPC_priority:
7135   case OMPC_grainsize:
7136   case OMPC_nogroup:
7137   case OMPC_num_tasks:
7138   case OMPC_hint:
7139   case OMPC_unknown:
7140   case OMPC_uniform:
7141     llvm_unreachable("Clause is not allowed.");
7142   }
7143   return Res;
7144 }
7145 
7146 static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
7147                                    OpenMPScheduleClauseModifier M2,
7148                                    SourceLocation M1Loc, SourceLocation M2Loc) {
7149   if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
7150     SmallVector<unsigned, 2> Excluded;
7151     if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
7152       Excluded.push_back(M2);
7153     if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
7154       Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
7155     if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
7156       Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
7157     S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
7158         << getListOfPossibleValues(OMPC_schedule,
7159                                    /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
7160                                    /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
7161                                    Excluded)
7162         << getOpenMPClauseName(OMPC_schedule);
7163     return true;
7164   }
7165   return false;
7166 }
7167 
7168 OMPClause *Sema::ActOnOpenMPScheduleClause(
7169     OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
7170     OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
7171     SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
7172     SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
7173   if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
7174       checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
7175     return nullptr;
7176   // OpenMP, 2.7.1, Loop Construct, Restrictions
7177   // Either the monotonic modifier or the nonmonotonic modifier can be specified
7178   // but not both.
7179   if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
7180       (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
7181        M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
7182       (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
7183        M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
7184     Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
7185         << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
7186         << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
7187     return nullptr;
7188   }
7189   if (Kind == OMPC_SCHEDULE_unknown) {
7190     std::string Values;
7191     if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
7192       unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
7193       Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
7194                                        /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
7195                                        Exclude);
7196     } else {
7197       Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
7198                                        /*Last=*/OMPC_SCHEDULE_unknown);
7199     }
7200     Diag(KindLoc, diag::err_omp_unexpected_clause_value)
7201         << Values << getOpenMPClauseName(OMPC_schedule);
7202     return nullptr;
7203   }
7204   // OpenMP, 2.7.1, Loop Construct, Restrictions
7205   // The nonmonotonic modifier can only be specified with schedule(dynamic) or
7206   // schedule(guided).
7207   if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
7208        M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
7209       Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
7210     Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
7211          diag::err_omp_schedule_nonmonotonic_static);
7212     return nullptr;
7213   }
7214   Expr *ValExpr = ChunkSize;
7215   Stmt *HelperValStmt = nullptr;
7216   if (ChunkSize) {
7217     if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
7218         !ChunkSize->isInstantiationDependent() &&
7219         !ChunkSize->containsUnexpandedParameterPack()) {
7220       SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
7221       ExprResult Val =
7222           PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
7223       if (Val.isInvalid())
7224         return nullptr;
7225 
7226       ValExpr = Val.get();
7227 
7228       // OpenMP [2.7.1, Restrictions]
7229       //  chunk_size must be a loop invariant integer expression with a positive
7230       //  value.
7231       llvm::APSInt Result;
7232       if (ValExpr->isIntegerConstantExpr(Result, Context)) {
7233         if (Result.isSigned() && !Result.isStrictlyPositive()) {
7234           Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
7235               << "schedule" << 1 << ChunkSize->getSourceRange();
7236           return nullptr;
7237         }
7238       } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) {
7239         llvm::MapVector<Expr *, DeclRefExpr *> Captures;
7240         ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
7241         HelperValStmt = buildPreInits(Context, Captures);
7242       }
7243     }
7244   }
7245 
7246   return new (Context)
7247       OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
7248                         ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
7249 }
7250 
7251 OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
7252                                    SourceLocation StartLoc,
7253                                    SourceLocation EndLoc) {
7254   OMPClause *Res = nullptr;
7255   switch (Kind) {
7256   case OMPC_ordered:
7257     Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
7258     break;
7259   case OMPC_nowait:
7260     Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
7261     break;
7262   case OMPC_untied:
7263     Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
7264     break;
7265   case OMPC_mergeable:
7266     Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
7267     break;
7268   case OMPC_read:
7269     Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
7270     break;
7271   case OMPC_write:
7272     Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
7273     break;
7274   case OMPC_update:
7275     Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
7276     break;
7277   case OMPC_capture:
7278     Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
7279     break;
7280   case OMPC_seq_cst:
7281     Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
7282     break;
7283   case OMPC_threads:
7284     Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
7285     break;
7286   case OMPC_simd:
7287     Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
7288     break;
7289   case OMPC_nogroup:
7290     Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
7291     break;
7292   case OMPC_if:
7293   case OMPC_final:
7294   case OMPC_num_threads:
7295   case OMPC_safelen:
7296   case OMPC_simdlen:
7297   case OMPC_collapse:
7298   case OMPC_schedule:
7299   case OMPC_private:
7300   case OMPC_firstprivate:
7301   case OMPC_lastprivate:
7302   case OMPC_shared:
7303   case OMPC_reduction:
7304   case OMPC_linear:
7305   case OMPC_aligned:
7306   case OMPC_copyin:
7307   case OMPC_copyprivate:
7308   case OMPC_default:
7309   case OMPC_proc_bind:
7310   case OMPC_threadprivate:
7311   case OMPC_flush:
7312   case OMPC_depend:
7313   case OMPC_device:
7314   case OMPC_map:
7315   case OMPC_num_teams:
7316   case OMPC_thread_limit:
7317   case OMPC_priority:
7318   case OMPC_grainsize:
7319   case OMPC_num_tasks:
7320   case OMPC_hint:
7321   case OMPC_dist_schedule:
7322   case OMPC_defaultmap:
7323   case OMPC_unknown:
7324   case OMPC_uniform:
7325     llvm_unreachable("Clause is not allowed.");
7326   }
7327   return Res;
7328 }
7329 
7330 OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
7331                                          SourceLocation EndLoc) {
7332   DSAStack->setNowaitRegion();
7333   return new (Context) OMPNowaitClause(StartLoc, EndLoc);
7334 }
7335 
7336 OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
7337                                          SourceLocation EndLoc) {
7338   return new (Context) OMPUntiedClause(StartLoc, EndLoc);
7339 }
7340 
7341 OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
7342                                             SourceLocation EndLoc) {
7343   return new (Context) OMPMergeableClause(StartLoc, EndLoc);
7344 }
7345 
7346 OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
7347                                        SourceLocation EndLoc) {
7348   return new (Context) OMPReadClause(StartLoc, EndLoc);
7349 }
7350 
7351 OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
7352                                         SourceLocation EndLoc) {
7353   return new (Context) OMPWriteClause(StartLoc, EndLoc);
7354 }
7355 
7356 OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
7357                                          SourceLocation EndLoc) {
7358   return new (Context) OMPUpdateClause(StartLoc, EndLoc);
7359 }
7360 
7361 OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
7362                                           SourceLocation EndLoc) {
7363   return new (Context) OMPCaptureClause(StartLoc, EndLoc);
7364 }
7365 
7366 OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
7367                                          SourceLocation EndLoc) {
7368   return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
7369 }
7370 
7371 OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
7372                                           SourceLocation EndLoc) {
7373   return new (Context) OMPThreadsClause(StartLoc, EndLoc);
7374 }
7375 
7376 OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
7377                                        SourceLocation EndLoc) {
7378   return new (Context) OMPSIMDClause(StartLoc, EndLoc);
7379 }
7380 
7381 OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
7382                                           SourceLocation EndLoc) {
7383   return new (Context) OMPNogroupClause(StartLoc, EndLoc);
7384 }
7385 
7386 OMPClause *Sema::ActOnOpenMPVarListClause(
7387     OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
7388     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
7389     SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
7390     const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
7391     OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier,
7392     OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
7393     SourceLocation DepLinMapLoc) {
7394   OMPClause *Res = nullptr;
7395   switch (Kind) {
7396   case OMPC_private:
7397     Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7398     break;
7399   case OMPC_firstprivate:
7400     Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7401     break;
7402   case OMPC_lastprivate:
7403     Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7404     break;
7405   case OMPC_shared:
7406     Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
7407     break;
7408   case OMPC_reduction:
7409     Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
7410                                      EndLoc, ReductionIdScopeSpec, ReductionId);
7411     break;
7412   case OMPC_linear:
7413     Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
7414                                   LinKind, DepLinMapLoc, ColonLoc, EndLoc);
7415     break;
7416   case OMPC_aligned:
7417     Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
7418                                    ColonLoc, EndLoc);
7419     break;
7420   case OMPC_copyin:
7421     Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
7422     break;
7423   case OMPC_copyprivate:
7424     Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7425     break;
7426   case OMPC_flush:
7427     Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
7428     break;
7429   case OMPC_depend:
7430     Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
7431                                   StartLoc, LParenLoc, EndLoc);
7432     break;
7433   case OMPC_map:
7434     Res = ActOnOpenMPMapClause(MapTypeModifier, MapType, IsMapTypeImplicit,
7435                                DepLinMapLoc, ColonLoc, VarList, StartLoc,
7436                                LParenLoc, EndLoc);
7437     break;
7438   case OMPC_if:
7439   case OMPC_final:
7440   case OMPC_num_threads:
7441   case OMPC_safelen:
7442   case OMPC_simdlen:
7443   case OMPC_collapse:
7444   case OMPC_default:
7445   case OMPC_proc_bind:
7446   case OMPC_schedule:
7447   case OMPC_ordered:
7448   case OMPC_nowait:
7449   case OMPC_untied:
7450   case OMPC_mergeable:
7451   case OMPC_threadprivate:
7452   case OMPC_read:
7453   case OMPC_write:
7454   case OMPC_update:
7455   case OMPC_capture:
7456   case OMPC_seq_cst:
7457   case OMPC_device:
7458   case OMPC_threads:
7459   case OMPC_simd:
7460   case OMPC_num_teams:
7461   case OMPC_thread_limit:
7462   case OMPC_priority:
7463   case OMPC_grainsize:
7464   case OMPC_nogroup:
7465   case OMPC_num_tasks:
7466   case OMPC_hint:
7467   case OMPC_dist_schedule:
7468   case OMPC_defaultmap:
7469   case OMPC_unknown:
7470   case OMPC_uniform:
7471     llvm_unreachable("Clause is not allowed.");
7472   }
7473   return Res;
7474 }
7475 
7476 ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
7477                                        ExprObjectKind OK, SourceLocation Loc) {
7478   ExprResult Res = BuildDeclRefExpr(
7479       Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
7480   if (!Res.isUsable())
7481     return ExprError();
7482   if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
7483     Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
7484     if (!Res.isUsable())
7485       return ExprError();
7486   }
7487   if (VK != VK_LValue && Res.get()->isGLValue()) {
7488     Res = DefaultLvalueConversion(Res.get());
7489     if (!Res.isUsable())
7490       return ExprError();
7491   }
7492   return Res;
7493 }
7494 
7495 static std::pair<ValueDecl *, bool>
7496 getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
7497                SourceRange &ERange, bool AllowArraySection = false) {
7498   if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
7499       RefExpr->containsUnexpandedParameterPack())
7500     return std::make_pair(nullptr, true);
7501 
7502   // OpenMP [3.1, C/C++]
7503   //  A list item is a variable name.
7504   // OpenMP  [2.9.3.3, Restrictions, p.1]
7505   //  A variable that is part of another variable (as an array or
7506   //  structure element) cannot appear in a private clause.
7507   RefExpr = RefExpr->IgnoreParens();
7508   enum {
7509     NoArrayExpr = -1,
7510     ArraySubscript = 0,
7511     OMPArraySection = 1
7512   } IsArrayExpr = NoArrayExpr;
7513   if (AllowArraySection) {
7514     if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
7515       auto *Base = ASE->getBase()->IgnoreParenImpCasts();
7516       while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
7517         Base = TempASE->getBase()->IgnoreParenImpCasts();
7518       RefExpr = Base;
7519       IsArrayExpr = ArraySubscript;
7520     } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
7521       auto *Base = OASE->getBase()->IgnoreParenImpCasts();
7522       while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
7523         Base = TempOASE->getBase()->IgnoreParenImpCasts();
7524       while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
7525         Base = TempASE->getBase()->IgnoreParenImpCasts();
7526       RefExpr = Base;
7527       IsArrayExpr = OMPArraySection;
7528     }
7529   }
7530   ELoc = RefExpr->getExprLoc();
7531   ERange = RefExpr->getSourceRange();
7532   RefExpr = RefExpr->IgnoreParenImpCasts();
7533   auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
7534   auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
7535   if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
7536       (S.getCurrentThisType().isNull() || !ME ||
7537        !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
7538        !isa<FieldDecl>(ME->getMemberDecl()))) {
7539     if (IsArrayExpr != NoArrayExpr)
7540       S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
7541                                                          << ERange;
7542     else {
7543       S.Diag(ELoc,
7544              AllowArraySection
7545                  ? diag::err_omp_expected_var_name_member_expr_or_array_item
7546                  : diag::err_omp_expected_var_name_member_expr)
7547           << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
7548     }
7549     return std::make_pair(nullptr, false);
7550   }
7551   return std::make_pair(DE ? DE->getDecl() : ME->getMemberDecl(), false);
7552 }
7553 
7554 OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
7555                                           SourceLocation StartLoc,
7556                                           SourceLocation LParenLoc,
7557                                           SourceLocation EndLoc) {
7558   SmallVector<Expr *, 8> Vars;
7559   SmallVector<Expr *, 8> PrivateCopies;
7560   for (auto &RefExpr : VarList) {
7561     assert(RefExpr && "NULL expr in OpenMP private clause.");
7562     SourceLocation ELoc;
7563     SourceRange ERange;
7564     Expr *SimpleRefExpr = RefExpr;
7565     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
7566     if (Res.second) {
7567       // It will be analyzed later.
7568       Vars.push_back(RefExpr);
7569       PrivateCopies.push_back(nullptr);
7570     }
7571     ValueDecl *D = Res.first;
7572     if (!D)
7573       continue;
7574 
7575     QualType Type = D->getType();
7576     auto *VD = dyn_cast<VarDecl>(D);
7577 
7578     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
7579     //  A variable that appears in a private clause must not have an incomplete
7580     //  type or a reference type.
7581     if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
7582       continue;
7583     Type = Type.getNonReferenceType();
7584 
7585     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
7586     // in a Construct]
7587     //  Variables with the predetermined data-sharing attributes may not be
7588     //  listed in data-sharing attributes clauses, except for the cases
7589     //  listed below. For these exceptions only, listing a predetermined
7590     //  variable in a data-sharing attribute clause is allowed and overrides
7591     //  the variable's predetermined data-sharing attributes.
7592     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
7593     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
7594       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
7595                                           << getOpenMPClauseName(OMPC_private);
7596       ReportOriginalDSA(*this, DSAStack, D, DVar);
7597       continue;
7598     }
7599 
7600     // Variably modified types are not supported for tasks.
7601     if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
7602         isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
7603       Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
7604           << getOpenMPClauseName(OMPC_private) << Type
7605           << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
7606       bool IsDecl =
7607           !VD ||
7608           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
7609       Diag(D->getLocation(),
7610            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
7611           << D;
7612       continue;
7613     }
7614 
7615     // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
7616     // A list item cannot appear in both a map clause and a data-sharing
7617     // attribute clause on the same construct
7618     if (DSAStack->getCurrentDirective() == OMPD_target) {
7619       if (DSAStack->checkMappableExprComponentListsForDecl(
7620               VD, /* CurrentRegionOnly = */ true,
7621               [&](OMPClauseMappableExprCommon::MappableExprComponentListRef)
7622                   -> bool { return true; })) {
7623         Diag(ELoc, diag::err_omp_variable_in_map_and_dsa)
7624             << getOpenMPClauseName(OMPC_private)
7625             << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
7626         ReportOriginalDSA(*this, DSAStack, D, DVar);
7627         continue;
7628       }
7629     }
7630 
7631     // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
7632     //  A variable of class type (or array thereof) that appears in a private
7633     //  clause requires an accessible, unambiguous default constructor for the
7634     //  class type.
7635     // Generate helper private variable and initialize it with the default
7636     // value. The address of the original variable is replaced by the address of
7637     // the new private variable in CodeGen. This new variable is not added to
7638     // IdResolver, so the code in the OpenMP region uses original variable for
7639     // proper diagnostics.
7640     Type = Type.getUnqualifiedType();
7641     auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
7642                                   D->hasAttrs() ? &D->getAttrs() : nullptr);
7643     ActOnUninitializedDecl(VDPrivate, /*TypeMayContainAuto=*/false);
7644     if (VDPrivate->isInvalidDecl())
7645       continue;
7646     auto VDPrivateRefExpr = buildDeclRefExpr(
7647         *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
7648 
7649     DeclRefExpr *Ref = nullptr;
7650     if (!VD)
7651       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
7652     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
7653     Vars.push_back(VD ? RefExpr->IgnoreParens() : Ref);
7654     PrivateCopies.push_back(VDPrivateRefExpr);
7655   }
7656 
7657   if (Vars.empty())
7658     return nullptr;
7659 
7660   return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
7661                                   PrivateCopies);
7662 }
7663 
7664 namespace {
7665 class DiagsUninitializedSeveretyRAII {
7666 private:
7667   DiagnosticsEngine &Diags;
7668   SourceLocation SavedLoc;
7669   bool IsIgnored;
7670 
7671 public:
7672   DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
7673                                  bool IsIgnored)
7674       : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
7675     if (!IsIgnored) {
7676       Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
7677                         /*Map*/ diag::Severity::Ignored, Loc);
7678     }
7679   }
7680   ~DiagsUninitializedSeveretyRAII() {
7681     if (!IsIgnored)
7682       Diags.popMappings(SavedLoc);
7683   }
7684 };
7685 }
7686 
7687 OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
7688                                                SourceLocation StartLoc,
7689                                                SourceLocation LParenLoc,
7690                                                SourceLocation EndLoc) {
7691   SmallVector<Expr *, 8> Vars;
7692   SmallVector<Expr *, 8> PrivateCopies;
7693   SmallVector<Expr *, 8> Inits;
7694   SmallVector<Decl *, 4> ExprCaptures;
7695   bool IsImplicitClause =
7696       StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
7697   auto ImplicitClauseLoc = DSAStack->getConstructLoc();
7698 
7699   for (auto &RefExpr : VarList) {
7700     assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
7701     SourceLocation ELoc;
7702     SourceRange ERange;
7703     Expr *SimpleRefExpr = RefExpr;
7704     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
7705     if (Res.second) {
7706       // It will be analyzed later.
7707       Vars.push_back(RefExpr);
7708       PrivateCopies.push_back(nullptr);
7709       Inits.push_back(nullptr);
7710     }
7711     ValueDecl *D = Res.first;
7712     if (!D)
7713       continue;
7714 
7715     ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
7716     QualType Type = D->getType();
7717     auto *VD = dyn_cast<VarDecl>(D);
7718 
7719     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
7720     //  A variable that appears in a private clause must not have an incomplete
7721     //  type or a reference type.
7722     if (RequireCompleteType(ELoc, Type,
7723                             diag::err_omp_firstprivate_incomplete_type))
7724       continue;
7725     Type = Type.getNonReferenceType();
7726 
7727     // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
7728     //  A variable of class type (or array thereof) that appears in a private
7729     //  clause requires an accessible, unambiguous copy constructor for the
7730     //  class type.
7731     auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
7732 
7733     // If an implicit firstprivate variable found it was checked already.
7734     DSAStackTy::DSAVarData TopDVar;
7735     if (!IsImplicitClause) {
7736       DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
7737       TopDVar = DVar;
7738       bool IsConstant = ElemType.isConstant(Context);
7739       // OpenMP [2.4.13, Data-sharing Attribute Clauses]
7740       //  A list item that specifies a given variable may not appear in more
7741       // than one clause on the same directive, except that a variable may be
7742       //  specified in both firstprivate and lastprivate clauses.
7743       if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
7744           DVar.CKind != OMPC_lastprivate && DVar.RefExpr) {
7745         Diag(ELoc, diag::err_omp_wrong_dsa)
7746             << getOpenMPClauseName(DVar.CKind)
7747             << getOpenMPClauseName(OMPC_firstprivate);
7748         ReportOriginalDSA(*this, DSAStack, D, DVar);
7749         continue;
7750       }
7751 
7752       // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
7753       // in a Construct]
7754       //  Variables with the predetermined data-sharing attributes may not be
7755       //  listed in data-sharing attributes clauses, except for the cases
7756       //  listed below. For these exceptions only, listing a predetermined
7757       //  variable in a data-sharing attribute clause is allowed and overrides
7758       //  the variable's predetermined data-sharing attributes.
7759       // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
7760       // in a Construct, C/C++, p.2]
7761       //  Variables with const-qualified type having no mutable member may be
7762       //  listed in a firstprivate clause, even if they are static data members.
7763       if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
7764           DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
7765         Diag(ELoc, diag::err_omp_wrong_dsa)
7766             << getOpenMPClauseName(DVar.CKind)
7767             << getOpenMPClauseName(OMPC_firstprivate);
7768         ReportOriginalDSA(*this, DSAStack, D, DVar);
7769         continue;
7770       }
7771 
7772       OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
7773       // OpenMP [2.9.3.4, Restrictions, p.2]
7774       //  A list item that is private within a parallel region must not appear
7775       //  in a firstprivate clause on a worksharing construct if any of the
7776       //  worksharing regions arising from the worksharing construct ever bind
7777       //  to any of the parallel regions arising from the parallel construct.
7778       if (isOpenMPWorksharingDirective(CurrDir) &&
7779           !isOpenMPParallelDirective(CurrDir)) {
7780         DVar = DSAStack->getImplicitDSA(D, true);
7781         if (DVar.CKind != OMPC_shared &&
7782             (isOpenMPParallelDirective(DVar.DKind) ||
7783              DVar.DKind == OMPD_unknown)) {
7784           Diag(ELoc, diag::err_omp_required_access)
7785               << getOpenMPClauseName(OMPC_firstprivate)
7786               << getOpenMPClauseName(OMPC_shared);
7787           ReportOriginalDSA(*this, DSAStack, D, DVar);
7788           continue;
7789         }
7790       }
7791       // OpenMP [2.9.3.4, Restrictions, p.3]
7792       //  A list item that appears in a reduction clause of a parallel construct
7793       //  must not appear in a firstprivate clause on a worksharing or task
7794       //  construct if any of the worksharing or task regions arising from the
7795       //  worksharing or task construct ever bind to any of the parallel regions
7796       //  arising from the parallel construct.
7797       // OpenMP [2.9.3.4, Restrictions, p.4]
7798       //  A list item that appears in a reduction clause in worksharing
7799       //  construct must not appear in a firstprivate clause in a task construct
7800       //  encountered during execution of any of the worksharing regions arising
7801       //  from the worksharing construct.
7802       if (isOpenMPTaskingDirective(CurrDir)) {
7803         DVar =
7804             DSAStack->hasInnermostDSA(D, MatchesAnyClause(OMPC_reduction),
7805                                       [](OpenMPDirectiveKind K) -> bool {
7806                                         return isOpenMPParallelDirective(K) ||
7807                                                isOpenMPWorksharingDirective(K);
7808                                       },
7809                                       false);
7810         if (DVar.CKind == OMPC_reduction &&
7811             (isOpenMPParallelDirective(DVar.DKind) ||
7812              isOpenMPWorksharingDirective(DVar.DKind))) {
7813           Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
7814               << getOpenMPDirectiveName(DVar.DKind);
7815           ReportOriginalDSA(*this, DSAStack, D, DVar);
7816           continue;
7817         }
7818       }
7819 
7820       // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
7821       // A list item that is private within a teams region must not appear in a
7822       // firstprivate clause on a distribute construct if any of the distribute
7823       // regions arising from the distribute construct ever bind to any of the
7824       // teams regions arising from the teams construct.
7825       // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
7826       // A list item that appears in a reduction clause of a teams construct
7827       // must not appear in a firstprivate clause on a distribute construct if
7828       // any of the distribute regions arising from the distribute construct
7829       // ever bind to any of the teams regions arising from the teams construct.
7830       // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
7831       // A list item may appear in a firstprivate or lastprivate clause but not
7832       // both.
7833       if (CurrDir == OMPD_distribute) {
7834         DVar = DSAStack->hasInnermostDSA(D, MatchesAnyClause(OMPC_private),
7835                                          [](OpenMPDirectiveKind K) -> bool {
7836                                            return isOpenMPTeamsDirective(K);
7837                                          },
7838                                          false);
7839         if (DVar.CKind == OMPC_private && isOpenMPTeamsDirective(DVar.DKind)) {
7840           Diag(ELoc, diag::err_omp_firstprivate_distribute_private_teams);
7841           ReportOriginalDSA(*this, DSAStack, D, DVar);
7842           continue;
7843         }
7844         DVar = DSAStack->hasInnermostDSA(D, MatchesAnyClause(OMPC_reduction),
7845                                          [](OpenMPDirectiveKind K) -> bool {
7846                                            return isOpenMPTeamsDirective(K);
7847                                          },
7848                                          false);
7849         if (DVar.CKind == OMPC_reduction &&
7850             isOpenMPTeamsDirective(DVar.DKind)) {
7851           Diag(ELoc, diag::err_omp_firstprivate_distribute_in_teams_reduction);
7852           ReportOriginalDSA(*this, DSAStack, D, DVar);
7853           continue;
7854         }
7855         DVar = DSAStack->getTopDSA(D, false);
7856         if (DVar.CKind == OMPC_lastprivate) {
7857           Diag(ELoc, diag::err_omp_firstprivate_and_lastprivate_in_distribute);
7858           ReportOriginalDSA(*this, DSAStack, D, DVar);
7859           continue;
7860         }
7861       }
7862       // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
7863       // A list item cannot appear in both a map clause and a data-sharing
7864       // attribute clause on the same construct
7865       if (CurrDir == OMPD_target) {
7866         if (DSAStack->checkMappableExprComponentListsForDecl(
7867                 VD, /* CurrentRegionOnly = */ true,
7868                 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef)
7869                     -> bool { return true; })) {
7870           Diag(ELoc, diag::err_omp_variable_in_map_and_dsa)
7871               << getOpenMPClauseName(OMPC_firstprivate)
7872               << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
7873           ReportOriginalDSA(*this, DSAStack, D, DVar);
7874           continue;
7875         }
7876       }
7877     }
7878 
7879     // Variably modified types are not supported for tasks.
7880     if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
7881         isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
7882       Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
7883           << getOpenMPClauseName(OMPC_firstprivate) << Type
7884           << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
7885       bool IsDecl =
7886           !VD ||
7887           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
7888       Diag(D->getLocation(),
7889            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
7890           << D;
7891       continue;
7892     }
7893 
7894     Type = Type.getUnqualifiedType();
7895     auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
7896                                   D->hasAttrs() ? &D->getAttrs() : nullptr);
7897     // Generate helper private variable and initialize it with the value of the
7898     // original variable. The address of the original variable is replaced by
7899     // the address of the new private variable in the CodeGen. This new variable
7900     // is not added to IdResolver, so the code in the OpenMP region uses
7901     // original variable for proper diagnostics and variable capturing.
7902     Expr *VDInitRefExpr = nullptr;
7903     // For arrays generate initializer for single element and replace it by the
7904     // original array element in CodeGen.
7905     if (Type->isArrayType()) {
7906       auto VDInit =
7907           buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
7908       VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
7909       auto Init = DefaultLvalueConversion(VDInitRefExpr).get();
7910       ElemType = ElemType.getUnqualifiedType();
7911       auto *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
7912                                       ".firstprivate.temp");
7913       InitializedEntity Entity =
7914           InitializedEntity::InitializeVariable(VDInitTemp);
7915       InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
7916 
7917       InitializationSequence InitSeq(*this, Entity, Kind, Init);
7918       ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
7919       if (Result.isInvalid())
7920         VDPrivate->setInvalidDecl();
7921       else
7922         VDPrivate->setInit(Result.getAs<Expr>());
7923       // Remove temp variable declaration.
7924       Context.Deallocate(VDInitTemp);
7925     } else {
7926       auto *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
7927                                   ".firstprivate.temp");
7928       VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
7929                                        RefExpr->getExprLoc());
7930       AddInitializerToDecl(VDPrivate,
7931                            DefaultLvalueConversion(VDInitRefExpr).get(),
7932                            /*DirectInit=*/false, /*TypeMayContainAuto=*/false);
7933     }
7934     if (VDPrivate->isInvalidDecl()) {
7935       if (IsImplicitClause) {
7936         Diag(RefExpr->getExprLoc(),
7937              diag::note_omp_task_predetermined_firstprivate_here);
7938       }
7939       continue;
7940     }
7941     CurContext->addDecl(VDPrivate);
7942     auto VDPrivateRefExpr = buildDeclRefExpr(
7943         *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
7944         RefExpr->getExprLoc());
7945     DeclRefExpr *Ref = nullptr;
7946     if (!VD) {
7947       if (TopDVar.CKind == OMPC_lastprivate)
7948         Ref = TopDVar.PrivateCopy;
7949       else {
7950         Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
7951         if (!IsOpenMPCapturedDecl(D))
7952           ExprCaptures.push_back(Ref->getDecl());
7953       }
7954     }
7955     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
7956     Vars.push_back(VD ? RefExpr->IgnoreParens() : Ref);
7957     PrivateCopies.push_back(VDPrivateRefExpr);
7958     Inits.push_back(VDInitRefExpr);
7959   }
7960 
7961   if (Vars.empty())
7962     return nullptr;
7963 
7964   return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
7965                                        Vars, PrivateCopies, Inits,
7966                                        buildPreInits(Context, ExprCaptures));
7967 }
7968 
7969 OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
7970                                               SourceLocation StartLoc,
7971                                               SourceLocation LParenLoc,
7972                                               SourceLocation EndLoc) {
7973   SmallVector<Expr *, 8> Vars;
7974   SmallVector<Expr *, 8> SrcExprs;
7975   SmallVector<Expr *, 8> DstExprs;
7976   SmallVector<Expr *, 8> AssignmentOps;
7977   SmallVector<Decl *, 4> ExprCaptures;
7978   SmallVector<Expr *, 4> ExprPostUpdates;
7979   for (auto &RefExpr : VarList) {
7980     assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
7981     SourceLocation ELoc;
7982     SourceRange ERange;
7983     Expr *SimpleRefExpr = RefExpr;
7984     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
7985     if (Res.second) {
7986       // It will be analyzed later.
7987       Vars.push_back(RefExpr);
7988       SrcExprs.push_back(nullptr);
7989       DstExprs.push_back(nullptr);
7990       AssignmentOps.push_back(nullptr);
7991     }
7992     ValueDecl *D = Res.first;
7993     if (!D)
7994       continue;
7995 
7996     QualType Type = D->getType();
7997     auto *VD = dyn_cast<VarDecl>(D);
7998 
7999     // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
8000     //  A variable that appears in a lastprivate clause must not have an
8001     //  incomplete type or a reference type.
8002     if (RequireCompleteType(ELoc, Type,
8003                             diag::err_omp_lastprivate_incomplete_type))
8004       continue;
8005     Type = Type.getNonReferenceType();
8006 
8007     // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
8008     // in a Construct]
8009     //  Variables with the predetermined data-sharing attributes may not be
8010     //  listed in data-sharing attributes clauses, except for the cases
8011     //  listed below.
8012     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
8013     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
8014         DVar.CKind != OMPC_firstprivate &&
8015         (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
8016       Diag(ELoc, diag::err_omp_wrong_dsa)
8017           << getOpenMPClauseName(DVar.CKind)
8018           << getOpenMPClauseName(OMPC_lastprivate);
8019       ReportOriginalDSA(*this, DSAStack, D, DVar);
8020       continue;
8021     }
8022 
8023     OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
8024     // OpenMP [2.14.3.5, Restrictions, p.2]
8025     // A list item that is private within a parallel region, or that appears in
8026     // the reduction clause of a parallel construct, must not appear in a
8027     // lastprivate clause on a worksharing construct if any of the corresponding
8028     // worksharing regions ever binds to any of the corresponding parallel
8029     // regions.
8030     DSAStackTy::DSAVarData TopDVar = DVar;
8031     if (isOpenMPWorksharingDirective(CurrDir) &&
8032         !isOpenMPParallelDirective(CurrDir)) {
8033       DVar = DSAStack->getImplicitDSA(D, true);
8034       if (DVar.CKind != OMPC_shared) {
8035         Diag(ELoc, diag::err_omp_required_access)
8036             << getOpenMPClauseName(OMPC_lastprivate)
8037             << getOpenMPClauseName(OMPC_shared);
8038         ReportOriginalDSA(*this, DSAStack, D, DVar);
8039         continue;
8040       }
8041     }
8042 
8043     // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
8044     // A list item may appear in a firstprivate or lastprivate clause but not
8045     // both.
8046     if (CurrDir == OMPD_distribute) {
8047       DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
8048       if (DVar.CKind == OMPC_firstprivate) {
8049         Diag(ELoc, diag::err_omp_firstprivate_and_lastprivate_in_distribute);
8050         ReportOriginalDSA(*this, DSAStack, D, DVar);
8051         continue;
8052       }
8053     }
8054 
8055     // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
8056     //  A variable of class type (or array thereof) that appears in a
8057     //  lastprivate clause requires an accessible, unambiguous default
8058     //  constructor for the class type, unless the list item is also specified
8059     //  in a firstprivate clause.
8060     //  A variable of class type (or array thereof) that appears in a
8061     //  lastprivate clause requires an accessible, unambiguous copy assignment
8062     //  operator for the class type.
8063     Type = Context.getBaseElementType(Type).getNonReferenceType();
8064     auto *SrcVD = buildVarDecl(*this, ERange.getBegin(),
8065                                Type.getUnqualifiedType(), ".lastprivate.src",
8066                                D->hasAttrs() ? &D->getAttrs() : nullptr);
8067     auto *PseudoSrcExpr =
8068         buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
8069     auto *DstVD =
8070         buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
8071                      D->hasAttrs() ? &D->getAttrs() : nullptr);
8072     auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
8073     // For arrays generate assignment operation for single element and replace
8074     // it by the original array element in CodeGen.
8075     auto AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
8076                                    PseudoDstExpr, PseudoSrcExpr);
8077     if (AssignmentOp.isInvalid())
8078       continue;
8079     AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
8080                                        /*DiscardedValue=*/true);
8081     if (AssignmentOp.isInvalid())
8082       continue;
8083 
8084     DeclRefExpr *Ref = nullptr;
8085     if (!VD) {
8086       if (TopDVar.CKind == OMPC_firstprivate)
8087         Ref = TopDVar.PrivateCopy;
8088       else {
8089         Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
8090         if (!IsOpenMPCapturedDecl(D))
8091           ExprCaptures.push_back(Ref->getDecl());
8092       }
8093       if (TopDVar.CKind == OMPC_firstprivate ||
8094           (!IsOpenMPCapturedDecl(D) &&
8095            Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
8096         ExprResult RefRes = DefaultLvalueConversion(Ref);
8097         if (!RefRes.isUsable())
8098           continue;
8099         ExprResult PostUpdateRes =
8100             BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
8101                        RefRes.get());
8102         if (!PostUpdateRes.isUsable())
8103           continue;
8104         ExprPostUpdates.push_back(
8105             IgnoredValueConversions(PostUpdateRes.get()).get());
8106       }
8107     }
8108     if (TopDVar.CKind != OMPC_firstprivate)
8109       DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
8110     Vars.push_back(VD ? RefExpr->IgnoreParens() : Ref);
8111     SrcExprs.push_back(PseudoSrcExpr);
8112     DstExprs.push_back(PseudoDstExpr);
8113     AssignmentOps.push_back(AssignmentOp.get());
8114   }
8115 
8116   if (Vars.empty())
8117     return nullptr;
8118 
8119   return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
8120                                       Vars, SrcExprs, DstExprs, AssignmentOps,
8121                                       buildPreInits(Context, ExprCaptures),
8122                                       buildPostUpdate(*this, ExprPostUpdates));
8123 }
8124 
8125 OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
8126                                          SourceLocation StartLoc,
8127                                          SourceLocation LParenLoc,
8128                                          SourceLocation EndLoc) {
8129   SmallVector<Expr *, 8> Vars;
8130   for (auto &RefExpr : VarList) {
8131     assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
8132     SourceLocation ELoc;
8133     SourceRange ERange;
8134     Expr *SimpleRefExpr = RefExpr;
8135     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
8136     if (Res.second) {
8137       // It will be analyzed later.
8138       Vars.push_back(RefExpr);
8139     }
8140     ValueDecl *D = Res.first;
8141     if (!D)
8142       continue;
8143 
8144     auto *VD = dyn_cast<VarDecl>(D);
8145     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
8146     // in a Construct]
8147     //  Variables with the predetermined data-sharing attributes may not be
8148     //  listed in data-sharing attributes clauses, except for the cases
8149     //  listed below. For these exceptions only, listing a predetermined
8150     //  variable in a data-sharing attribute clause is allowed and overrides
8151     //  the variable's predetermined data-sharing attributes.
8152     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
8153     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
8154         DVar.RefExpr) {
8155       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
8156                                           << getOpenMPClauseName(OMPC_shared);
8157       ReportOriginalDSA(*this, DSAStack, D, DVar);
8158       continue;
8159     }
8160 
8161     DeclRefExpr *Ref = nullptr;
8162     if (!VD && IsOpenMPCapturedDecl(D))
8163       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
8164     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
8165     Vars.push_back((VD || !Ref) ? RefExpr->IgnoreParens() : Ref);
8166   }
8167 
8168   if (Vars.empty())
8169     return nullptr;
8170 
8171   return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
8172 }
8173 
8174 namespace {
8175 class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
8176   DSAStackTy *Stack;
8177 
8178 public:
8179   bool VisitDeclRefExpr(DeclRefExpr *E) {
8180     if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
8181       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false);
8182       if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
8183         return false;
8184       if (DVar.CKind != OMPC_unknown)
8185         return true;
8186       DSAStackTy::DSAVarData DVarPrivate =
8187           Stack->hasDSA(VD, isOpenMPPrivate, MatchesAlways(), false);
8188       if (DVarPrivate.CKind != OMPC_unknown)
8189         return true;
8190       return false;
8191     }
8192     return false;
8193   }
8194   bool VisitStmt(Stmt *S) {
8195     for (auto Child : S->children()) {
8196       if (Child && Visit(Child))
8197         return true;
8198     }
8199     return false;
8200   }
8201   explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
8202 };
8203 } // namespace
8204 
8205 namespace {
8206 // Transform MemberExpression for specified FieldDecl of current class to
8207 // DeclRefExpr to specified OMPCapturedExprDecl.
8208 class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
8209   typedef TreeTransform<TransformExprToCaptures> BaseTransform;
8210   ValueDecl *Field;
8211   DeclRefExpr *CapturedExpr;
8212 
8213 public:
8214   TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
8215       : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
8216 
8217   ExprResult TransformMemberExpr(MemberExpr *E) {
8218     if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
8219         E->getMemberDecl() == Field) {
8220       CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
8221       return CapturedExpr;
8222     }
8223     return BaseTransform::TransformMemberExpr(E);
8224   }
8225   DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
8226 };
8227 } // namespace
8228 
8229 template <typename T>
8230 static T filterLookupForUDR(SmallVectorImpl<UnresolvedSet<8>> &Lookups,
8231                             const llvm::function_ref<T(ValueDecl *)> &Gen) {
8232   for (auto &Set : Lookups) {
8233     for (auto *D : Set) {
8234       if (auto Res = Gen(cast<ValueDecl>(D)))
8235         return Res;
8236     }
8237   }
8238   return T();
8239 }
8240 
8241 static ExprResult
8242 buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
8243                          Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
8244                          const DeclarationNameInfo &ReductionId, QualType Ty,
8245                          CXXCastPath &BasePath, Expr *UnresolvedReduction) {
8246   if (ReductionIdScopeSpec.isInvalid())
8247     return ExprError();
8248   SmallVector<UnresolvedSet<8>, 4> Lookups;
8249   if (S) {
8250     LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
8251     Lookup.suppressDiagnostics();
8252     while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
8253       auto *D = Lookup.getRepresentativeDecl();
8254       do {
8255         S = S->getParent();
8256       } while (S && !S->isDeclScope(D));
8257       if (S)
8258         S = S->getParent();
8259       Lookups.push_back(UnresolvedSet<8>());
8260       Lookups.back().append(Lookup.begin(), Lookup.end());
8261       Lookup.clear();
8262     }
8263   } else if (auto *ULE =
8264                  cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
8265     Lookups.push_back(UnresolvedSet<8>());
8266     Decl *PrevD = nullptr;
8267     for(auto *D : ULE->decls()) {
8268       if (D == PrevD)
8269         Lookups.push_back(UnresolvedSet<8>());
8270       else if (auto *DRD = cast<OMPDeclareReductionDecl>(D))
8271         Lookups.back().addDecl(DRD);
8272       PrevD = D;
8273     }
8274   }
8275   if (Ty->isDependentType() || Ty->isInstantiationDependentType() ||
8276       Ty->containsUnexpandedParameterPack() ||
8277       filterLookupForUDR<bool>(Lookups, [](ValueDecl *D) -> bool {
8278         return !D->isInvalidDecl() &&
8279                (D->getType()->isDependentType() ||
8280                 D->getType()->isInstantiationDependentType() ||
8281                 D->getType()->containsUnexpandedParameterPack());
8282       })) {
8283     UnresolvedSet<8> ResSet;
8284     for (auto &Set : Lookups) {
8285       ResSet.append(Set.begin(), Set.end());
8286       // The last item marks the end of all declarations at the specified scope.
8287       ResSet.addDecl(Set[Set.size() - 1]);
8288     }
8289     return UnresolvedLookupExpr::Create(
8290         SemaRef.Context, /*NamingClass=*/nullptr,
8291         ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
8292         /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
8293   }
8294   if (auto *VD = filterLookupForUDR<ValueDecl *>(
8295           Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
8296             if (!D->isInvalidDecl() &&
8297                 SemaRef.Context.hasSameType(D->getType(), Ty))
8298               return D;
8299             return nullptr;
8300           }))
8301     return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
8302   if (auto *VD = filterLookupForUDR<ValueDecl *>(
8303           Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
8304             if (!D->isInvalidDecl() &&
8305                 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
8306                 !Ty.isMoreQualifiedThan(D->getType()))
8307               return D;
8308             return nullptr;
8309           })) {
8310     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
8311                        /*DetectVirtual=*/false);
8312     if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
8313       if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
8314               VD->getType().getUnqualifiedType()))) {
8315         if (SemaRef.CheckBaseClassAccess(Loc, VD->getType(), Ty, Paths.front(),
8316                                          /*DiagID=*/0) !=
8317             Sema::AR_inaccessible) {
8318           SemaRef.BuildBasePathArray(Paths, BasePath);
8319           return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
8320         }
8321       }
8322     }
8323   }
8324   if (ReductionIdScopeSpec.isSet()) {
8325     SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
8326     return ExprError();
8327   }
8328   return ExprEmpty();
8329 }
8330 
8331 OMPClause *Sema::ActOnOpenMPReductionClause(
8332     ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
8333     SourceLocation ColonLoc, SourceLocation EndLoc,
8334     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
8335     ArrayRef<Expr *> UnresolvedReductions) {
8336   auto DN = ReductionId.getName();
8337   auto OOK = DN.getCXXOverloadedOperator();
8338   BinaryOperatorKind BOK = BO_Comma;
8339 
8340   // OpenMP [2.14.3.6, reduction clause]
8341   // C
8342   // reduction-identifier is either an identifier or one of the following
8343   // operators: +, -, *,  &, |, ^, && and ||
8344   // C++
8345   // reduction-identifier is either an id-expression or one of the following
8346   // operators: +, -, *, &, |, ^, && and ||
8347   // FIXME: Only 'min' and 'max' identifiers are supported for now.
8348   switch (OOK) {
8349   case OO_Plus:
8350   case OO_Minus:
8351     BOK = BO_Add;
8352     break;
8353   case OO_Star:
8354     BOK = BO_Mul;
8355     break;
8356   case OO_Amp:
8357     BOK = BO_And;
8358     break;
8359   case OO_Pipe:
8360     BOK = BO_Or;
8361     break;
8362   case OO_Caret:
8363     BOK = BO_Xor;
8364     break;
8365   case OO_AmpAmp:
8366     BOK = BO_LAnd;
8367     break;
8368   case OO_PipePipe:
8369     BOK = BO_LOr;
8370     break;
8371   case OO_New:
8372   case OO_Delete:
8373   case OO_Array_New:
8374   case OO_Array_Delete:
8375   case OO_Slash:
8376   case OO_Percent:
8377   case OO_Tilde:
8378   case OO_Exclaim:
8379   case OO_Equal:
8380   case OO_Less:
8381   case OO_Greater:
8382   case OO_LessEqual:
8383   case OO_GreaterEqual:
8384   case OO_PlusEqual:
8385   case OO_MinusEqual:
8386   case OO_StarEqual:
8387   case OO_SlashEqual:
8388   case OO_PercentEqual:
8389   case OO_CaretEqual:
8390   case OO_AmpEqual:
8391   case OO_PipeEqual:
8392   case OO_LessLess:
8393   case OO_GreaterGreater:
8394   case OO_LessLessEqual:
8395   case OO_GreaterGreaterEqual:
8396   case OO_EqualEqual:
8397   case OO_ExclaimEqual:
8398   case OO_PlusPlus:
8399   case OO_MinusMinus:
8400   case OO_Comma:
8401   case OO_ArrowStar:
8402   case OO_Arrow:
8403   case OO_Call:
8404   case OO_Subscript:
8405   case OO_Conditional:
8406   case OO_Coawait:
8407   case NUM_OVERLOADED_OPERATORS:
8408     llvm_unreachable("Unexpected reduction identifier");
8409   case OO_None:
8410     if (auto II = DN.getAsIdentifierInfo()) {
8411       if (II->isStr("max"))
8412         BOK = BO_GT;
8413       else if (II->isStr("min"))
8414         BOK = BO_LT;
8415     }
8416     break;
8417   }
8418   SourceRange ReductionIdRange;
8419   if (ReductionIdScopeSpec.isValid())
8420     ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
8421   ReductionIdRange.setEnd(ReductionId.getEndLoc());
8422 
8423   SmallVector<Expr *, 8> Vars;
8424   SmallVector<Expr *, 8> Privates;
8425   SmallVector<Expr *, 8> LHSs;
8426   SmallVector<Expr *, 8> RHSs;
8427   SmallVector<Expr *, 8> ReductionOps;
8428   SmallVector<Decl *, 4> ExprCaptures;
8429   SmallVector<Expr *, 4> ExprPostUpdates;
8430   auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
8431   bool FirstIter = true;
8432   for (auto RefExpr : VarList) {
8433     assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
8434     // OpenMP [2.1, C/C++]
8435     //  A list item is a variable or array section, subject to the restrictions
8436     //  specified in Section 2.4 on page 42 and in each of the sections
8437     // describing clauses and directives for which a list appears.
8438     // OpenMP  [2.14.3.3, Restrictions, p.1]
8439     //  A variable that is part of another variable (as an array or
8440     //  structure element) cannot appear in a private clause.
8441     if (!FirstIter && IR != ER)
8442       ++IR;
8443     FirstIter = false;
8444     SourceLocation ELoc;
8445     SourceRange ERange;
8446     Expr *SimpleRefExpr = RefExpr;
8447     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
8448                               /*AllowArraySection=*/true);
8449     if (Res.second) {
8450       // It will be analyzed later.
8451       Vars.push_back(RefExpr);
8452       Privates.push_back(nullptr);
8453       LHSs.push_back(nullptr);
8454       RHSs.push_back(nullptr);
8455       // Try to find 'declare reduction' corresponding construct before using
8456       // builtin/overloaded operators.
8457       QualType Type = Context.DependentTy;
8458       CXXCastPath BasePath;
8459       ExprResult DeclareReductionRef = buildDeclareReductionRef(
8460           *this, ELoc, ERange, DSAStack->getCurScope(), ReductionIdScopeSpec,
8461           ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
8462       if (CurContext->isDependentContext() &&
8463           (DeclareReductionRef.isUnset() ||
8464            isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
8465         ReductionOps.push_back(DeclareReductionRef.get());
8466       else
8467         ReductionOps.push_back(nullptr);
8468     }
8469     ValueDecl *D = Res.first;
8470     if (!D)
8471       continue;
8472 
8473     QualType Type;
8474     auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
8475     auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
8476     if (ASE)
8477       Type = ASE->getType().getNonReferenceType();
8478     else if (OASE) {
8479       auto BaseType = OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
8480       if (auto *ATy = BaseType->getAsArrayTypeUnsafe())
8481         Type = ATy->getElementType();
8482       else
8483         Type = BaseType->getPointeeType();
8484       Type = Type.getNonReferenceType();
8485     } else
8486       Type = Context.getBaseElementType(D->getType().getNonReferenceType());
8487     auto *VD = dyn_cast<VarDecl>(D);
8488 
8489     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
8490     //  A variable that appears in a private clause must not have an incomplete
8491     //  type or a reference type.
8492     if (RequireCompleteType(ELoc, Type,
8493                             diag::err_omp_reduction_incomplete_type))
8494       continue;
8495     // OpenMP [2.14.3.6, reduction clause, Restrictions]
8496     // A list item that appears in a reduction clause must not be
8497     // const-qualified.
8498     if (Type.getNonReferenceType().isConstant(Context)) {
8499       Diag(ELoc, diag::err_omp_const_reduction_list_item)
8500           << getOpenMPClauseName(OMPC_reduction) << Type << ERange;
8501       if (!ASE && !OASE) {
8502         bool IsDecl = !VD ||
8503                       VD->isThisDeclarationADefinition(Context) ==
8504                           VarDecl::DeclarationOnly;
8505         Diag(D->getLocation(),
8506              IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8507             << D;
8508       }
8509       continue;
8510     }
8511     // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
8512     //  If a list-item is a reference type then it must bind to the same object
8513     //  for all threads of the team.
8514     if (!ASE && !OASE && VD) {
8515       VarDecl *VDDef = VD->getDefinition();
8516       if (VD->getType()->isReferenceType() && VDDef) {
8517         DSARefChecker Check(DSAStack);
8518         if (Check.Visit(VDDef->getInit())) {
8519           Diag(ELoc, diag::err_omp_reduction_ref_type_arg) << ERange;
8520           Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
8521           continue;
8522         }
8523       }
8524     }
8525 
8526     // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
8527     // in a Construct]
8528     //  Variables with the predetermined data-sharing attributes may not be
8529     //  listed in data-sharing attributes clauses, except for the cases
8530     //  listed below. For these exceptions only, listing a predetermined
8531     //  variable in a data-sharing attribute clause is allowed and overrides
8532     //  the variable's predetermined data-sharing attributes.
8533     // OpenMP [2.14.3.6, Restrictions, p.3]
8534     //  Any number of reduction clauses can be specified on the directive,
8535     //  but a list item can appear only once in the reduction clauses for that
8536     //  directive.
8537     DSAStackTy::DSAVarData DVar;
8538     DVar = DSAStack->getTopDSA(D, false);
8539     if (DVar.CKind == OMPC_reduction) {
8540       Diag(ELoc, diag::err_omp_once_referenced)
8541           << getOpenMPClauseName(OMPC_reduction);
8542       if (DVar.RefExpr)
8543         Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
8544     } else if (DVar.CKind != OMPC_unknown) {
8545       Diag(ELoc, diag::err_omp_wrong_dsa)
8546           << getOpenMPClauseName(DVar.CKind)
8547           << getOpenMPClauseName(OMPC_reduction);
8548       ReportOriginalDSA(*this, DSAStack, D, DVar);
8549       continue;
8550     }
8551 
8552     // OpenMP [2.14.3.6, Restrictions, p.1]
8553     //  A list item that appears in a reduction clause of a worksharing
8554     //  construct must be shared in the parallel regions to which any of the
8555     //  worksharing regions arising from the worksharing construct bind.
8556     OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
8557     if (isOpenMPWorksharingDirective(CurrDir) &&
8558         !isOpenMPParallelDirective(CurrDir)) {
8559       DVar = DSAStack->getImplicitDSA(D, true);
8560       if (DVar.CKind != OMPC_shared) {
8561         Diag(ELoc, diag::err_omp_required_access)
8562             << getOpenMPClauseName(OMPC_reduction)
8563             << getOpenMPClauseName(OMPC_shared);
8564         ReportOriginalDSA(*this, DSAStack, D, DVar);
8565         continue;
8566       }
8567     }
8568 
8569     // Try to find 'declare reduction' corresponding construct before using
8570     // builtin/overloaded operators.
8571     CXXCastPath BasePath;
8572     ExprResult DeclareReductionRef = buildDeclareReductionRef(
8573         *this, ELoc, ERange, DSAStack->getCurScope(), ReductionIdScopeSpec,
8574         ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
8575     if (DeclareReductionRef.isInvalid())
8576       continue;
8577     if (CurContext->isDependentContext() &&
8578         (DeclareReductionRef.isUnset() ||
8579          isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
8580       Vars.push_back(RefExpr);
8581       Privates.push_back(nullptr);
8582       LHSs.push_back(nullptr);
8583       RHSs.push_back(nullptr);
8584       ReductionOps.push_back(DeclareReductionRef.get());
8585       continue;
8586     }
8587     if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
8588       // Not allowed reduction identifier is found.
8589       Diag(ReductionId.getLocStart(),
8590            diag::err_omp_unknown_reduction_identifier)
8591           << Type << ReductionIdRange;
8592       continue;
8593     }
8594 
8595     // OpenMP [2.14.3.6, reduction clause, Restrictions]
8596     // The type of a list item that appears in a reduction clause must be valid
8597     // for the reduction-identifier. For a max or min reduction in C, the type
8598     // of the list item must be an allowed arithmetic data type: char, int,
8599     // float, double, or _Bool, possibly modified with long, short, signed, or
8600     // unsigned. For a max or min reduction in C++, the type of the list item
8601     // must be an allowed arithmetic data type: char, wchar_t, int, float,
8602     // double, or bool, possibly modified with long, short, signed, or unsigned.
8603     if (DeclareReductionRef.isUnset()) {
8604       if ((BOK == BO_GT || BOK == BO_LT) &&
8605           !(Type->isScalarType() ||
8606             (getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
8607         Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
8608             << getLangOpts().CPlusPlus;
8609         if (!ASE && !OASE) {
8610           bool IsDecl = !VD ||
8611                         VD->isThisDeclarationADefinition(Context) ==
8612                             VarDecl::DeclarationOnly;
8613           Diag(D->getLocation(),
8614                IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8615               << D;
8616         }
8617         continue;
8618       }
8619       if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
8620           !getLangOpts().CPlusPlus && Type->isFloatingType()) {
8621         Diag(ELoc, diag::err_omp_clause_floating_type_arg);
8622         if (!ASE && !OASE) {
8623           bool IsDecl = !VD ||
8624                         VD->isThisDeclarationADefinition(Context) ==
8625                             VarDecl::DeclarationOnly;
8626           Diag(D->getLocation(),
8627                IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8628               << D;
8629         }
8630         continue;
8631       }
8632     }
8633 
8634     Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
8635     auto *LHSVD = buildVarDecl(*this, ELoc, Type, ".reduction.lhs",
8636                                D->hasAttrs() ? &D->getAttrs() : nullptr);
8637     auto *RHSVD = buildVarDecl(*this, ELoc, Type, D->getName(),
8638                                D->hasAttrs() ? &D->getAttrs() : nullptr);
8639     auto PrivateTy = Type;
8640     if (OASE ||
8641         (!ASE &&
8642          D->getType().getNonReferenceType()->isVariablyModifiedType())) {
8643       // For arays/array sections only:
8644       // Create pseudo array type for private copy. The size for this array will
8645       // be generated during codegen.
8646       // For array subscripts or single variables Private Ty is the same as Type
8647       // (type of the variable or single array element).
8648       PrivateTy = Context.getVariableArrayType(
8649           Type, new (Context) OpaqueValueExpr(SourceLocation(),
8650                                               Context.getSizeType(), VK_RValue),
8651           ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
8652     } else if (!ASE && !OASE &&
8653                Context.getAsArrayType(D->getType().getNonReferenceType()))
8654       PrivateTy = D->getType().getNonReferenceType();
8655     // Private copy.
8656     auto *PrivateVD = buildVarDecl(*this, ELoc, PrivateTy, D->getName(),
8657                                    D->hasAttrs() ? &D->getAttrs() : nullptr);
8658     // Add initializer for private variable.
8659     Expr *Init = nullptr;
8660     auto *LHSDRE = buildDeclRefExpr(*this, LHSVD, Type, ELoc);
8661     auto *RHSDRE = buildDeclRefExpr(*this, RHSVD, Type, ELoc);
8662     if (DeclareReductionRef.isUsable()) {
8663       auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
8664       auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
8665       if (DRD->getInitializer()) {
8666         Init = DRDRef;
8667         RHSVD->setInit(DRDRef);
8668         RHSVD->setInitStyle(VarDecl::CallInit);
8669       }
8670     } else {
8671       switch (BOK) {
8672       case BO_Add:
8673       case BO_Xor:
8674       case BO_Or:
8675       case BO_LOr:
8676         // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
8677         if (Type->isScalarType() || Type->isAnyComplexType())
8678           Init = ActOnIntegerConstant(ELoc, /*Val=*/0).get();
8679         break;
8680       case BO_Mul:
8681       case BO_LAnd:
8682         if (Type->isScalarType() || Type->isAnyComplexType()) {
8683           // '*' and '&&' reduction ops - initializer is '1'.
8684           Init = ActOnIntegerConstant(ELoc, /*Val=*/1).get();
8685         }
8686         break;
8687       case BO_And: {
8688         // '&' reduction op - initializer is '~0'.
8689         QualType OrigType = Type;
8690         if (auto *ComplexTy = OrigType->getAs<ComplexType>())
8691           Type = ComplexTy->getElementType();
8692         if (Type->isRealFloatingType()) {
8693           llvm::APFloat InitValue =
8694               llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
8695                                              /*isIEEE=*/true);
8696           Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
8697                                          Type, ELoc);
8698         } else if (Type->isScalarType()) {
8699           auto Size = Context.getTypeSize(Type);
8700           QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
8701           llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
8702           Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
8703         }
8704         if (Init && OrigType->isAnyComplexType()) {
8705           // Init = 0xFFFF + 0xFFFFi;
8706           auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
8707           Init = CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
8708         }
8709         Type = OrigType;
8710         break;
8711       }
8712       case BO_LT:
8713       case BO_GT: {
8714         // 'min' reduction op - initializer is 'Largest representable number in
8715         // the reduction list item type'.
8716         // 'max' reduction op - initializer is 'Least representable number in
8717         // the reduction list item type'.
8718         if (Type->isIntegerType() || Type->isPointerType()) {
8719           bool IsSigned = Type->hasSignedIntegerRepresentation();
8720           auto Size = Context.getTypeSize(Type);
8721           QualType IntTy =
8722               Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
8723           llvm::APInt InitValue =
8724               (BOK != BO_LT)
8725                   ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
8726                              : llvm::APInt::getMinValue(Size)
8727                   : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
8728                              : llvm::APInt::getMaxValue(Size);
8729           Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
8730           if (Type->isPointerType()) {
8731             // Cast to pointer type.
8732             auto CastExpr = BuildCStyleCastExpr(
8733                 SourceLocation(), Context.getTrivialTypeSourceInfo(Type, ELoc),
8734                 SourceLocation(), Init);
8735             if (CastExpr.isInvalid())
8736               continue;
8737             Init = CastExpr.get();
8738           }
8739         } else if (Type->isRealFloatingType()) {
8740           llvm::APFloat InitValue = llvm::APFloat::getLargest(
8741               Context.getFloatTypeSemantics(Type), BOK != BO_LT);
8742           Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
8743                                          Type, ELoc);
8744         }
8745         break;
8746       }
8747       case BO_PtrMemD:
8748       case BO_PtrMemI:
8749       case BO_MulAssign:
8750       case BO_Div:
8751       case BO_Rem:
8752       case BO_Sub:
8753       case BO_Shl:
8754       case BO_Shr:
8755       case BO_LE:
8756       case BO_GE:
8757       case BO_EQ:
8758       case BO_NE:
8759       case BO_AndAssign:
8760       case BO_XorAssign:
8761       case BO_OrAssign:
8762       case BO_Assign:
8763       case BO_AddAssign:
8764       case BO_SubAssign:
8765       case BO_DivAssign:
8766       case BO_RemAssign:
8767       case BO_ShlAssign:
8768       case BO_ShrAssign:
8769       case BO_Comma:
8770         llvm_unreachable("Unexpected reduction operation");
8771       }
8772     }
8773     if (Init && DeclareReductionRef.isUnset()) {
8774       AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false,
8775                            /*TypeMayContainAuto=*/false);
8776     } else if (!Init)
8777       ActOnUninitializedDecl(RHSVD, /*TypeMayContainAuto=*/false);
8778     if (RHSVD->isInvalidDecl())
8779       continue;
8780     if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) {
8781       Diag(ELoc, diag::err_omp_reduction_id_not_compatible) << Type
8782                                                             << ReductionIdRange;
8783       bool IsDecl =
8784           !VD ||
8785           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
8786       Diag(D->getLocation(),
8787            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8788           << D;
8789       continue;
8790     }
8791     // Store initializer for single element in private copy. Will be used during
8792     // codegen.
8793     PrivateVD->setInit(RHSVD->getInit());
8794     PrivateVD->setInitStyle(RHSVD->getInitStyle());
8795     auto *PrivateDRE = buildDeclRefExpr(*this, PrivateVD, PrivateTy, ELoc);
8796     ExprResult ReductionOp;
8797     if (DeclareReductionRef.isUsable()) {
8798       QualType RedTy = DeclareReductionRef.get()->getType();
8799       QualType PtrRedTy = Context.getPointerType(RedTy);
8800       ExprResult LHS = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
8801       ExprResult RHS = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
8802       if (!BasePath.empty()) {
8803         LHS = DefaultLvalueConversion(LHS.get());
8804         RHS = DefaultLvalueConversion(RHS.get());
8805         LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
8806                                        CK_UncheckedDerivedToBase, LHS.get(),
8807                                        &BasePath, LHS.get()->getValueKind());
8808         RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
8809                                        CK_UncheckedDerivedToBase, RHS.get(),
8810                                        &BasePath, RHS.get()->getValueKind());
8811       }
8812       FunctionProtoType::ExtProtoInfo EPI;
8813       QualType Params[] = {PtrRedTy, PtrRedTy};
8814       QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
8815       auto *OVE = new (Context) OpaqueValueExpr(
8816           ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
8817           DefaultLvalueConversion(DeclareReductionRef.get()).get());
8818       Expr *Args[] = {LHS.get(), RHS.get()};
8819       ReductionOp = new (Context)
8820           CallExpr(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
8821     } else {
8822       ReductionOp = BuildBinOp(DSAStack->getCurScope(),
8823                                ReductionId.getLocStart(), BOK, LHSDRE, RHSDRE);
8824       if (ReductionOp.isUsable()) {
8825         if (BOK != BO_LT && BOK != BO_GT) {
8826           ReductionOp =
8827               BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
8828                          BO_Assign, LHSDRE, ReductionOp.get());
8829         } else {
8830           auto *ConditionalOp = new (Context) ConditionalOperator(
8831               ReductionOp.get(), SourceLocation(), LHSDRE, SourceLocation(),
8832               RHSDRE, Type, VK_LValue, OK_Ordinary);
8833           ReductionOp =
8834               BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
8835                          BO_Assign, LHSDRE, ConditionalOp);
8836         }
8837         ReductionOp = ActOnFinishFullExpr(ReductionOp.get());
8838       }
8839       if (ReductionOp.isInvalid())
8840         continue;
8841     }
8842 
8843     DeclRefExpr *Ref = nullptr;
8844     Expr *VarsExpr = RefExpr->IgnoreParens();
8845     if (!VD) {
8846       if (ASE || OASE) {
8847         TransformExprToCaptures RebuildToCapture(*this, D);
8848         VarsExpr =
8849             RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
8850         Ref = RebuildToCapture.getCapturedExpr();
8851       } else {
8852         VarsExpr = Ref =
8853             buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
8854       }
8855       if (!IsOpenMPCapturedDecl(D)) {
8856         ExprCaptures.push_back(Ref->getDecl());
8857         if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
8858           ExprResult RefRes = DefaultLvalueConversion(Ref);
8859           if (!RefRes.isUsable())
8860             continue;
8861           ExprResult PostUpdateRes =
8862               BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
8863                          SimpleRefExpr, RefRes.get());
8864           if (!PostUpdateRes.isUsable())
8865             continue;
8866           ExprPostUpdates.push_back(
8867               IgnoredValueConversions(PostUpdateRes.get()).get());
8868         }
8869       }
8870     }
8871     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
8872     Vars.push_back(VarsExpr);
8873     Privates.push_back(PrivateDRE);
8874     LHSs.push_back(LHSDRE);
8875     RHSs.push_back(RHSDRE);
8876     ReductionOps.push_back(ReductionOp.get());
8877   }
8878 
8879   if (Vars.empty())
8880     return nullptr;
8881 
8882   return OMPReductionClause::Create(
8883       Context, StartLoc, LParenLoc, ColonLoc, EndLoc, Vars,
8884       ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, Privates,
8885       LHSs, RHSs, ReductionOps, buildPreInits(Context, ExprCaptures),
8886       buildPostUpdate(*this, ExprPostUpdates));
8887 }
8888 
8889 bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
8890                                      SourceLocation LinLoc) {
8891   if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
8892       LinKind == OMPC_LINEAR_unknown) {
8893     Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
8894     return true;
8895   }
8896   return false;
8897 }
8898 
8899 bool Sema::CheckOpenMPLinearDecl(ValueDecl *D, SourceLocation ELoc,
8900                                  OpenMPLinearClauseKind LinKind,
8901                                  QualType Type) {
8902   auto *VD = dyn_cast_or_null<VarDecl>(D);
8903   // A variable must not have an incomplete type or a reference type.
8904   if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
8905     return true;
8906   if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
8907       !Type->isReferenceType()) {
8908     Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
8909         << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
8910     return true;
8911   }
8912   Type = Type.getNonReferenceType();
8913 
8914   // A list item must not be const-qualified.
8915   if (Type.isConstant(Context)) {
8916     Diag(ELoc, diag::err_omp_const_variable)
8917         << getOpenMPClauseName(OMPC_linear);
8918     if (D) {
8919       bool IsDecl =
8920           !VD ||
8921           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
8922       Diag(D->getLocation(),
8923            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8924           << D;
8925     }
8926     return true;
8927   }
8928 
8929   // A list item must be of integral or pointer type.
8930   Type = Type.getUnqualifiedType().getCanonicalType();
8931   const auto *Ty = Type.getTypePtrOrNull();
8932   if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
8933               !Ty->isPointerType())) {
8934     Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
8935     if (D) {
8936       bool IsDecl =
8937           !VD ||
8938           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
8939       Diag(D->getLocation(),
8940            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8941           << D;
8942     }
8943     return true;
8944   }
8945   return false;
8946 }
8947 
8948 OMPClause *Sema::ActOnOpenMPLinearClause(
8949     ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
8950     SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
8951     SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
8952   SmallVector<Expr *, 8> Vars;
8953   SmallVector<Expr *, 8> Privates;
8954   SmallVector<Expr *, 8> Inits;
8955   SmallVector<Decl *, 4> ExprCaptures;
8956   SmallVector<Expr *, 4> ExprPostUpdates;
8957   if (CheckOpenMPLinearModifier(LinKind, LinLoc))
8958     LinKind = OMPC_LINEAR_val;
8959   for (auto &RefExpr : VarList) {
8960     assert(RefExpr && "NULL expr in OpenMP linear clause.");
8961     SourceLocation ELoc;
8962     SourceRange ERange;
8963     Expr *SimpleRefExpr = RefExpr;
8964     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
8965                               /*AllowArraySection=*/false);
8966     if (Res.second) {
8967       // It will be analyzed later.
8968       Vars.push_back(RefExpr);
8969       Privates.push_back(nullptr);
8970       Inits.push_back(nullptr);
8971     }
8972     ValueDecl *D = Res.first;
8973     if (!D)
8974       continue;
8975 
8976     QualType Type = D->getType();
8977     auto *VD = dyn_cast<VarDecl>(D);
8978 
8979     // OpenMP [2.14.3.7, linear clause]
8980     //  A list-item cannot appear in more than one linear clause.
8981     //  A list-item that appears in a linear clause cannot appear in any
8982     //  other data-sharing attribute clause.
8983     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
8984     if (DVar.RefExpr) {
8985       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
8986                                           << getOpenMPClauseName(OMPC_linear);
8987       ReportOriginalDSA(*this, DSAStack, D, DVar);
8988       continue;
8989     }
8990 
8991     if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
8992       continue;
8993     Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
8994 
8995     // Build private copy of original var.
8996     auto *Private = buildVarDecl(*this, ELoc, Type, D->getName(),
8997                                  D->hasAttrs() ? &D->getAttrs() : nullptr);
8998     auto *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
8999     // Build var to save initial value.
9000     VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
9001     Expr *InitExpr;
9002     DeclRefExpr *Ref = nullptr;
9003     if (!VD) {
9004       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
9005       if (!IsOpenMPCapturedDecl(D)) {
9006         ExprCaptures.push_back(Ref->getDecl());
9007         if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
9008           ExprResult RefRes = DefaultLvalueConversion(Ref);
9009           if (!RefRes.isUsable())
9010             continue;
9011           ExprResult PostUpdateRes =
9012               BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
9013                          SimpleRefExpr, RefRes.get());
9014           if (!PostUpdateRes.isUsable())
9015             continue;
9016           ExprPostUpdates.push_back(
9017               IgnoredValueConversions(PostUpdateRes.get()).get());
9018         }
9019       }
9020     }
9021     if (LinKind == OMPC_LINEAR_uval)
9022       InitExpr = VD ? VD->getInit() : SimpleRefExpr;
9023     else
9024       InitExpr = VD ? SimpleRefExpr : Ref;
9025     AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
9026                          /*DirectInit=*/false, /*TypeMayContainAuto=*/false);
9027     auto InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
9028 
9029     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
9030     Vars.push_back(VD ? RefExpr->IgnoreParens() : Ref);
9031     Privates.push_back(PrivateRef);
9032     Inits.push_back(InitRef);
9033   }
9034 
9035   if (Vars.empty())
9036     return nullptr;
9037 
9038   Expr *StepExpr = Step;
9039   Expr *CalcStepExpr = nullptr;
9040   if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
9041       !Step->isInstantiationDependent() &&
9042       !Step->containsUnexpandedParameterPack()) {
9043     SourceLocation StepLoc = Step->getLocStart();
9044     ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
9045     if (Val.isInvalid())
9046       return nullptr;
9047     StepExpr = Val.get();
9048 
9049     // Build var to save the step value.
9050     VarDecl *SaveVar =
9051         buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
9052     ExprResult SaveRef =
9053         buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
9054     ExprResult CalcStep =
9055         BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
9056     CalcStep = ActOnFinishFullExpr(CalcStep.get());
9057 
9058     // Warn about zero linear step (it would be probably better specified as
9059     // making corresponding variables 'const').
9060     llvm::APSInt Result;
9061     bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
9062     if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
9063       Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
9064                                                      << (Vars.size() > 1);
9065     if (!IsConstant && CalcStep.isUsable()) {
9066       // Calculate the step beforehand instead of doing this on each iteration.
9067       // (This is not used if the number of iterations may be kfold-ed).
9068       CalcStepExpr = CalcStep.get();
9069     }
9070   }
9071 
9072   return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
9073                                  ColonLoc, EndLoc, Vars, Privates, Inits,
9074                                  StepExpr, CalcStepExpr,
9075                                  buildPreInits(Context, ExprCaptures),
9076                                  buildPostUpdate(*this, ExprPostUpdates));
9077 }
9078 
9079 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
9080                                      Expr *NumIterations, Sema &SemaRef,
9081                                      Scope *S, DSAStackTy *Stack) {
9082   // Walk the vars and build update/final expressions for the CodeGen.
9083   SmallVector<Expr *, 8> Updates;
9084   SmallVector<Expr *, 8> Finals;
9085   Expr *Step = Clause.getStep();
9086   Expr *CalcStep = Clause.getCalcStep();
9087   // OpenMP [2.14.3.7, linear clause]
9088   // If linear-step is not specified it is assumed to be 1.
9089   if (Step == nullptr)
9090     Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
9091   else if (CalcStep) {
9092     Step = cast<BinaryOperator>(CalcStep)->getLHS();
9093   }
9094   bool HasErrors = false;
9095   auto CurInit = Clause.inits().begin();
9096   auto CurPrivate = Clause.privates().begin();
9097   auto LinKind = Clause.getModifier();
9098   for (auto &RefExpr : Clause.varlists()) {
9099     SourceLocation ELoc;
9100     SourceRange ERange;
9101     Expr *SimpleRefExpr = RefExpr;
9102     auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange,
9103                               /*AllowArraySection=*/false);
9104     ValueDecl *D = Res.first;
9105     if (Res.second || !D) {
9106       Updates.push_back(nullptr);
9107       Finals.push_back(nullptr);
9108       HasErrors = true;
9109       continue;
9110     }
9111     if (auto *CED = dyn_cast<OMPCapturedExprDecl>(D)) {
9112       D = cast<MemberExpr>(CED->getInit()->IgnoreParenImpCasts())
9113               ->getMemberDecl();
9114     }
9115     auto &&Info = Stack->isLoopControlVariable(D);
9116     Expr *InitExpr = *CurInit;
9117 
9118     // Build privatized reference to the current linear var.
9119     auto DE = cast<DeclRefExpr>(SimpleRefExpr);
9120     Expr *CapturedRef;
9121     if (LinKind == OMPC_LINEAR_uval)
9122       CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
9123     else
9124       CapturedRef =
9125           buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
9126                            DE->getType().getUnqualifiedType(), DE->getExprLoc(),
9127                            /*RefersToCapture=*/true);
9128 
9129     // Build update: Var = InitExpr + IV * Step
9130     ExprResult Update;
9131     if (!Info.first) {
9132       Update =
9133           BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate,
9134                              InitExpr, IV, Step, /* Subtract */ false);
9135     } else
9136       Update = *CurPrivate;
9137     Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getLocStart(),
9138                                          /*DiscardedValue=*/true);
9139 
9140     // Build final: Var = InitExpr + NumIterations * Step
9141     ExprResult Final;
9142     if (!Info.first) {
9143       Final = BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
9144                                  InitExpr, NumIterations, Step,
9145                                  /* Subtract */ false);
9146     } else
9147       Final = *CurPrivate;
9148     Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getLocStart(),
9149                                         /*DiscardedValue=*/true);
9150 
9151     if (!Update.isUsable() || !Final.isUsable()) {
9152       Updates.push_back(nullptr);
9153       Finals.push_back(nullptr);
9154       HasErrors = true;
9155     } else {
9156       Updates.push_back(Update.get());
9157       Finals.push_back(Final.get());
9158     }
9159     ++CurInit;
9160     ++CurPrivate;
9161   }
9162   Clause.setUpdates(Updates);
9163   Clause.setFinals(Finals);
9164   return HasErrors;
9165 }
9166 
9167 OMPClause *Sema::ActOnOpenMPAlignedClause(
9168     ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
9169     SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
9170 
9171   SmallVector<Expr *, 8> Vars;
9172   for (auto &RefExpr : VarList) {
9173     assert(RefExpr && "NULL expr in OpenMP linear clause.");
9174     SourceLocation ELoc;
9175     SourceRange ERange;
9176     Expr *SimpleRefExpr = RefExpr;
9177     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
9178                               /*AllowArraySection=*/false);
9179     if (Res.second) {
9180       // It will be analyzed later.
9181       Vars.push_back(RefExpr);
9182     }
9183     ValueDecl *D = Res.first;
9184     if (!D)
9185       continue;
9186 
9187     QualType QType = D->getType();
9188     auto *VD = dyn_cast<VarDecl>(D);
9189 
9190     // OpenMP  [2.8.1, simd construct, Restrictions]
9191     // The type of list items appearing in the aligned clause must be
9192     // array, pointer, reference to array, or reference to pointer.
9193     QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
9194     const Type *Ty = QType.getTypePtrOrNull();
9195     if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
9196       Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
9197           << QType << getLangOpts().CPlusPlus << ERange;
9198       bool IsDecl =
9199           !VD ||
9200           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
9201       Diag(D->getLocation(),
9202            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
9203           << D;
9204       continue;
9205     }
9206 
9207     // OpenMP  [2.8.1, simd construct, Restrictions]
9208     // A list-item cannot appear in more than one aligned clause.
9209     if (Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
9210       Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
9211       Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
9212           << getOpenMPClauseName(OMPC_aligned);
9213       continue;
9214     }
9215 
9216     DeclRefExpr *Ref = nullptr;
9217     if (!VD && IsOpenMPCapturedDecl(D))
9218       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
9219     Vars.push_back(DefaultFunctionArrayConversion(
9220                        (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
9221                        .get());
9222   }
9223 
9224   // OpenMP [2.8.1, simd construct, Description]
9225   // The parameter of the aligned clause, alignment, must be a constant
9226   // positive integer expression.
9227   // If no optional parameter is specified, implementation-defined default
9228   // alignments for SIMD instructions on the target platforms are assumed.
9229   if (Alignment != nullptr) {
9230     ExprResult AlignResult =
9231         VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
9232     if (AlignResult.isInvalid())
9233       return nullptr;
9234     Alignment = AlignResult.get();
9235   }
9236   if (Vars.empty())
9237     return nullptr;
9238 
9239   return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
9240                                   EndLoc, Vars, Alignment);
9241 }
9242 
9243 OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
9244                                          SourceLocation StartLoc,
9245                                          SourceLocation LParenLoc,
9246                                          SourceLocation EndLoc) {
9247   SmallVector<Expr *, 8> Vars;
9248   SmallVector<Expr *, 8> SrcExprs;
9249   SmallVector<Expr *, 8> DstExprs;
9250   SmallVector<Expr *, 8> AssignmentOps;
9251   for (auto &RefExpr : VarList) {
9252     assert(RefExpr && "NULL expr in OpenMP copyin clause.");
9253     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
9254       // It will be analyzed later.
9255       Vars.push_back(RefExpr);
9256       SrcExprs.push_back(nullptr);
9257       DstExprs.push_back(nullptr);
9258       AssignmentOps.push_back(nullptr);
9259       continue;
9260     }
9261 
9262     SourceLocation ELoc = RefExpr->getExprLoc();
9263     // OpenMP [2.1, C/C++]
9264     //  A list item is a variable name.
9265     // OpenMP  [2.14.4.1, Restrictions, p.1]
9266     //  A list item that appears in a copyin clause must be threadprivate.
9267     DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
9268     if (!DE || !isa<VarDecl>(DE->getDecl())) {
9269       Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
9270           << 0 << RefExpr->getSourceRange();
9271       continue;
9272     }
9273 
9274     Decl *D = DE->getDecl();
9275     VarDecl *VD = cast<VarDecl>(D);
9276 
9277     QualType Type = VD->getType();
9278     if (Type->isDependentType() || Type->isInstantiationDependentType()) {
9279       // It will be analyzed later.
9280       Vars.push_back(DE);
9281       SrcExprs.push_back(nullptr);
9282       DstExprs.push_back(nullptr);
9283       AssignmentOps.push_back(nullptr);
9284       continue;
9285     }
9286 
9287     // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
9288     //  A list item that appears in a copyin clause must be threadprivate.
9289     if (!DSAStack->isThreadPrivate(VD)) {
9290       Diag(ELoc, diag::err_omp_required_access)
9291           << getOpenMPClauseName(OMPC_copyin)
9292           << getOpenMPDirectiveName(OMPD_threadprivate);
9293       continue;
9294     }
9295 
9296     // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
9297     //  A variable of class type (or array thereof) that appears in a
9298     //  copyin clause requires an accessible, unambiguous copy assignment
9299     //  operator for the class type.
9300     auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
9301     auto *SrcVD =
9302         buildVarDecl(*this, DE->getLocStart(), ElemType.getUnqualifiedType(),
9303                      ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
9304     auto *PseudoSrcExpr = buildDeclRefExpr(
9305         *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
9306     auto *DstVD =
9307         buildVarDecl(*this, DE->getLocStart(), ElemType, ".copyin.dst",
9308                      VD->hasAttrs() ? &VD->getAttrs() : nullptr);
9309     auto *PseudoDstExpr =
9310         buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
9311     // For arrays generate assignment operation for single element and replace
9312     // it by the original array element in CodeGen.
9313     auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
9314                                    PseudoDstExpr, PseudoSrcExpr);
9315     if (AssignmentOp.isInvalid())
9316       continue;
9317     AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
9318                                        /*DiscardedValue=*/true);
9319     if (AssignmentOp.isInvalid())
9320       continue;
9321 
9322     DSAStack->addDSA(VD, DE, OMPC_copyin);
9323     Vars.push_back(DE);
9324     SrcExprs.push_back(PseudoSrcExpr);
9325     DstExprs.push_back(PseudoDstExpr);
9326     AssignmentOps.push_back(AssignmentOp.get());
9327   }
9328 
9329   if (Vars.empty())
9330     return nullptr;
9331 
9332   return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
9333                                  SrcExprs, DstExprs, AssignmentOps);
9334 }
9335 
9336 OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
9337                                               SourceLocation StartLoc,
9338                                               SourceLocation LParenLoc,
9339                                               SourceLocation EndLoc) {
9340   SmallVector<Expr *, 8> Vars;
9341   SmallVector<Expr *, 8> SrcExprs;
9342   SmallVector<Expr *, 8> DstExprs;
9343   SmallVector<Expr *, 8> AssignmentOps;
9344   for (auto &RefExpr : VarList) {
9345     assert(RefExpr && "NULL expr in OpenMP linear clause.");
9346     SourceLocation ELoc;
9347     SourceRange ERange;
9348     Expr *SimpleRefExpr = RefExpr;
9349     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
9350                               /*AllowArraySection=*/false);
9351     if (Res.second) {
9352       // It will be analyzed later.
9353       Vars.push_back(RefExpr);
9354       SrcExprs.push_back(nullptr);
9355       DstExprs.push_back(nullptr);
9356       AssignmentOps.push_back(nullptr);
9357     }
9358     ValueDecl *D = Res.first;
9359     if (!D)
9360       continue;
9361 
9362     QualType Type = D->getType();
9363     auto *VD = dyn_cast<VarDecl>(D);
9364 
9365     // OpenMP [2.14.4.2, Restrictions, p.2]
9366     //  A list item that appears in a copyprivate clause may not appear in a
9367     //  private or firstprivate clause on the single construct.
9368     if (!VD || !DSAStack->isThreadPrivate(VD)) {
9369       auto DVar = DSAStack->getTopDSA(D, false);
9370       if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
9371           DVar.RefExpr) {
9372         Diag(ELoc, diag::err_omp_wrong_dsa)
9373             << getOpenMPClauseName(DVar.CKind)
9374             << getOpenMPClauseName(OMPC_copyprivate);
9375         ReportOriginalDSA(*this, DSAStack, D, DVar);
9376         continue;
9377       }
9378 
9379       // OpenMP [2.11.4.2, Restrictions, p.1]
9380       //  All list items that appear in a copyprivate clause must be either
9381       //  threadprivate or private in the enclosing context.
9382       if (DVar.CKind == OMPC_unknown) {
9383         DVar = DSAStack->getImplicitDSA(D, false);
9384         if (DVar.CKind == OMPC_shared) {
9385           Diag(ELoc, diag::err_omp_required_access)
9386               << getOpenMPClauseName(OMPC_copyprivate)
9387               << "threadprivate or private in the enclosing context";
9388           ReportOriginalDSA(*this, DSAStack, D, DVar);
9389           continue;
9390         }
9391       }
9392     }
9393 
9394     // Variably modified types are not supported.
9395     if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
9396       Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
9397           << getOpenMPClauseName(OMPC_copyprivate) << Type
9398           << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
9399       bool IsDecl =
9400           !VD ||
9401           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
9402       Diag(D->getLocation(),
9403            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
9404           << D;
9405       continue;
9406     }
9407 
9408     // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
9409     //  A variable of class type (or array thereof) that appears in a
9410     //  copyin clause requires an accessible, unambiguous copy assignment
9411     //  operator for the class type.
9412     Type = Context.getBaseElementType(Type.getNonReferenceType())
9413                .getUnqualifiedType();
9414     auto *SrcVD =
9415         buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.src",
9416                      D->hasAttrs() ? &D->getAttrs() : nullptr);
9417     auto *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
9418     auto *DstVD =
9419         buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.dst",
9420                      D->hasAttrs() ? &D->getAttrs() : nullptr);
9421     auto *PseudoDstExpr =
9422         buildDeclRefExpr(*this, DstVD, Type, ELoc);
9423     auto AssignmentOp = BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
9424                                    PseudoDstExpr, PseudoSrcExpr);
9425     if (AssignmentOp.isInvalid())
9426       continue;
9427     AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
9428                                        /*DiscardedValue=*/true);
9429     if (AssignmentOp.isInvalid())
9430       continue;
9431 
9432     // No need to mark vars as copyprivate, they are already threadprivate or
9433     // implicitly private.
9434     assert(VD || IsOpenMPCapturedDecl(D));
9435     Vars.push_back(
9436         VD ? RefExpr->IgnoreParens()
9437            : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
9438     SrcExprs.push_back(PseudoSrcExpr);
9439     DstExprs.push_back(PseudoDstExpr);
9440     AssignmentOps.push_back(AssignmentOp.get());
9441   }
9442 
9443   if (Vars.empty())
9444     return nullptr;
9445 
9446   return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
9447                                       Vars, SrcExprs, DstExprs, AssignmentOps);
9448 }
9449 
9450 OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
9451                                         SourceLocation StartLoc,
9452                                         SourceLocation LParenLoc,
9453                                         SourceLocation EndLoc) {
9454   if (VarList.empty())
9455     return nullptr;
9456 
9457   return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
9458 }
9459 
9460 OMPClause *
9461 Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
9462                               SourceLocation DepLoc, SourceLocation ColonLoc,
9463                               ArrayRef<Expr *> VarList, SourceLocation StartLoc,
9464                               SourceLocation LParenLoc, SourceLocation EndLoc) {
9465   if (DSAStack->getCurrentDirective() == OMPD_ordered &&
9466       DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
9467     Diag(DepLoc, diag::err_omp_unexpected_clause_value)
9468         << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
9469     return nullptr;
9470   }
9471   if (DSAStack->getCurrentDirective() != OMPD_ordered &&
9472       (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
9473        DepKind == OMPC_DEPEND_sink)) {
9474     unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
9475     Diag(DepLoc, diag::err_omp_unexpected_clause_value)
9476         << getListOfPossibleValues(OMPC_depend, /*First=*/0,
9477                                    /*Last=*/OMPC_DEPEND_unknown, Except)
9478         << getOpenMPClauseName(OMPC_depend);
9479     return nullptr;
9480   }
9481   SmallVector<Expr *, 8> Vars;
9482   llvm::APSInt DepCounter(/*BitWidth=*/32);
9483   llvm::APSInt TotalDepCount(/*BitWidth=*/32);
9484   if (DepKind == OMPC_DEPEND_sink) {
9485     if (auto *OrderedCountExpr = DSAStack->getParentOrderedRegionParam()) {
9486       TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
9487       TotalDepCount.setIsUnsigned(/*Val=*/true);
9488     }
9489   }
9490   if ((DepKind != OMPC_DEPEND_sink && DepKind != OMPC_DEPEND_source) ||
9491       DSAStack->getParentOrderedRegionParam()) {
9492     for (auto &RefExpr : VarList) {
9493       assert(RefExpr && "NULL expr in OpenMP shared clause.");
9494       if (isa<DependentScopeDeclRefExpr>(RefExpr) ||
9495           (DepKind == OMPC_DEPEND_sink && CurContext->isDependentContext())) {
9496         // It will be analyzed later.
9497         Vars.push_back(RefExpr);
9498         continue;
9499       }
9500 
9501       SourceLocation ELoc = RefExpr->getExprLoc();
9502       auto *SimpleExpr = RefExpr->IgnoreParenCasts();
9503       if (DepKind == OMPC_DEPEND_sink) {
9504         if (DepCounter >= TotalDepCount) {
9505           Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
9506           continue;
9507         }
9508         ++DepCounter;
9509         // OpenMP  [2.13.9, Summary]
9510         // depend(dependence-type : vec), where dependence-type is:
9511         // 'sink' and where vec is the iteration vector, which has the form:
9512         //  x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
9513         // where n is the value specified by the ordered clause in the loop
9514         // directive, xi denotes the loop iteration variable of the i-th nested
9515         // loop associated with the loop directive, and di is a constant
9516         // non-negative integer.
9517         SimpleExpr = SimpleExpr->IgnoreImplicit();
9518         auto *DE = dyn_cast<DeclRefExpr>(SimpleExpr);
9519         if (!DE) {
9520           OverloadedOperatorKind OOK = OO_None;
9521           SourceLocation OOLoc;
9522           Expr *LHS, *RHS;
9523           if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
9524             OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
9525             OOLoc = BO->getOperatorLoc();
9526             LHS = BO->getLHS()->IgnoreParenImpCasts();
9527             RHS = BO->getRHS()->IgnoreParenImpCasts();
9528           } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
9529             OOK = OCE->getOperator();
9530             OOLoc = OCE->getOperatorLoc();
9531             LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
9532             RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
9533           } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
9534             OOK = MCE->getMethodDecl()
9535                       ->getNameInfo()
9536                       .getName()
9537                       .getCXXOverloadedOperator();
9538             OOLoc = MCE->getCallee()->getExprLoc();
9539             LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
9540             RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
9541           } else {
9542             Diag(ELoc, diag::err_omp_depend_sink_wrong_expr);
9543             continue;
9544           }
9545           DE = dyn_cast<DeclRefExpr>(LHS);
9546           if (!DE) {
9547             Diag(LHS->getExprLoc(),
9548                  diag::err_omp_depend_sink_expected_loop_iteration)
9549                 << DSAStack->getParentLoopControlVariable(
9550                     DepCounter.getZExtValue());
9551             continue;
9552           }
9553           if (OOK != OO_Plus && OOK != OO_Minus) {
9554             Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
9555             continue;
9556           }
9557           ExprResult Res = VerifyPositiveIntegerConstantInClause(
9558               RHS, OMPC_depend, /*StrictlyPositive=*/false);
9559           if (Res.isInvalid())
9560             continue;
9561         }
9562         auto *VD = dyn_cast<VarDecl>(DE->getDecl());
9563         if (!CurContext->isDependentContext() &&
9564             DSAStack->getParentOrderedRegionParam() &&
9565             (!VD ||
9566              DepCounter != DSAStack->isParentLoopControlVariable(VD).first)) {
9567           Diag(DE->getExprLoc(),
9568                diag::err_omp_depend_sink_expected_loop_iteration)
9569               << DSAStack->getParentLoopControlVariable(
9570                   DepCounter.getZExtValue());
9571           continue;
9572         }
9573       } else {
9574         // OpenMP  [2.11.1.1, Restrictions, p.3]
9575         //  A variable that is part of another variable (such as a field of a
9576         //  structure) but is not an array element or an array section cannot
9577         //  appear  in a depend clause.
9578         auto *DE = dyn_cast<DeclRefExpr>(SimpleExpr);
9579         auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
9580         auto *OASE = dyn_cast<OMPArraySectionExpr>(SimpleExpr);
9581         if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
9582             (!ASE && !DE && !OASE) || (DE && !isa<VarDecl>(DE->getDecl())) ||
9583             (ASE &&
9584              !ASE->getBase()
9585                   ->getType()
9586                   .getNonReferenceType()
9587                   ->isPointerType() &&
9588              !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
9589           Diag(ELoc, diag::err_omp_expected_var_name_member_expr_or_array_item)
9590               << 0 << RefExpr->getSourceRange();
9591           continue;
9592         }
9593       }
9594 
9595       Vars.push_back(RefExpr->IgnoreParenImpCasts());
9596     }
9597 
9598     if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
9599         TotalDepCount > VarList.size() &&
9600         DSAStack->getParentOrderedRegionParam()) {
9601       Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
9602           << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
9603     }
9604     if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
9605         Vars.empty())
9606       return nullptr;
9607   }
9608 
9609   return OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc, DepKind,
9610                                  DepLoc, ColonLoc, Vars);
9611 }
9612 
9613 OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
9614                                          SourceLocation LParenLoc,
9615                                          SourceLocation EndLoc) {
9616   Expr *ValExpr = Device;
9617 
9618   // OpenMP [2.9.1, Restrictions]
9619   // The device expression must evaluate to a non-negative integer value.
9620   if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
9621                                  /*StrictlyPositive=*/false))
9622     return nullptr;
9623 
9624   return new (Context) OMPDeviceClause(ValExpr, StartLoc, LParenLoc, EndLoc);
9625 }
9626 
9627 static bool IsCXXRecordForMappable(Sema &SemaRef, SourceLocation Loc,
9628                                    DSAStackTy *Stack, CXXRecordDecl *RD) {
9629   if (!RD || RD->isInvalidDecl())
9630     return true;
9631 
9632   if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(RD))
9633     if (auto *CTD = CTSD->getSpecializedTemplate())
9634       RD = CTD->getTemplatedDecl();
9635   auto QTy = SemaRef.Context.getRecordType(RD);
9636   if (RD->isDynamicClass()) {
9637     SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
9638     SemaRef.Diag(RD->getLocation(), diag::note_omp_polymorphic_in_target);
9639     return false;
9640   }
9641   auto *DC = RD;
9642   bool IsCorrect = true;
9643   for (auto *I : DC->decls()) {
9644     if (I) {
9645       if (auto *MD = dyn_cast<CXXMethodDecl>(I)) {
9646         if (MD->isStatic()) {
9647           SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
9648           SemaRef.Diag(MD->getLocation(),
9649                        diag::note_omp_static_member_in_target);
9650           IsCorrect = false;
9651         }
9652       } else if (auto *VD = dyn_cast<VarDecl>(I)) {
9653         if (VD->isStaticDataMember()) {
9654           SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
9655           SemaRef.Diag(VD->getLocation(),
9656                        diag::note_omp_static_member_in_target);
9657           IsCorrect = false;
9658         }
9659       }
9660     }
9661   }
9662 
9663   for (auto &I : RD->bases()) {
9664     if (!IsCXXRecordForMappable(SemaRef, I.getLocStart(), Stack,
9665                                 I.getType()->getAsCXXRecordDecl()))
9666       IsCorrect = false;
9667   }
9668   return IsCorrect;
9669 }
9670 
9671 static bool CheckTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
9672                               DSAStackTy *Stack, QualType QTy) {
9673   NamedDecl *ND;
9674   if (QTy->isIncompleteType(&ND)) {
9675     SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
9676     return false;
9677   } else if (CXXRecordDecl *RD = dyn_cast_or_null<CXXRecordDecl>(ND)) {
9678     if (!RD->isInvalidDecl() &&
9679         !IsCXXRecordForMappable(SemaRef, SL, Stack, RD))
9680       return false;
9681   }
9682   return true;
9683 }
9684 
9685 /// \brief Return true if it can be proven that the provided array expression
9686 /// (array section or array subscript) does NOT specify the whole size of the
9687 /// array whose base type is \a BaseQTy.
9688 static bool CheckArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
9689                                                         const Expr *E,
9690                                                         QualType BaseQTy) {
9691   auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
9692 
9693   // If this is an array subscript, it refers to the whole size if the size of
9694   // the dimension is constant and equals 1. Also, an array section assumes the
9695   // format of an array subscript if no colon is used.
9696   if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
9697     if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
9698       return ATy->getSize().getSExtValue() != 1;
9699     // Size can't be evaluated statically.
9700     return false;
9701   }
9702 
9703   assert(OASE && "Expecting array section if not an array subscript.");
9704   auto *LowerBound = OASE->getLowerBound();
9705   auto *Length = OASE->getLength();
9706 
9707   // If there is a lower bound that does not evaluates to zero, we are not
9708   // convering the whole dimension.
9709   if (LowerBound) {
9710     llvm::APSInt ConstLowerBound;
9711     if (!LowerBound->EvaluateAsInt(ConstLowerBound, SemaRef.getASTContext()))
9712       return false; // Can't get the integer value as a constant.
9713     if (ConstLowerBound.getSExtValue())
9714       return true;
9715   }
9716 
9717   // If we don't have a length we covering the whole dimension.
9718   if (!Length)
9719     return false;
9720 
9721   // If the base is a pointer, we don't have a way to get the size of the
9722   // pointee.
9723   if (BaseQTy->isPointerType())
9724     return false;
9725 
9726   // We can only check if the length is the same as the size of the dimension
9727   // if we have a constant array.
9728   auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
9729   if (!CATy)
9730     return false;
9731 
9732   llvm::APSInt ConstLength;
9733   if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
9734     return false; // Can't get the integer value as a constant.
9735 
9736   return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
9737 }
9738 
9739 // Return true if it can be proven that the provided array expression (array
9740 // section or array subscript) does NOT specify a single element of the array
9741 // whose base type is \a BaseQTy.
9742 static bool CheckArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
9743                                                        const Expr *E,
9744                                                        QualType BaseQTy) {
9745   auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
9746 
9747   // An array subscript always refer to a single element. Also, an array section
9748   // assumes the format of an array subscript if no colon is used.
9749   if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
9750     return false;
9751 
9752   assert(OASE && "Expecting array section if not an array subscript.");
9753   auto *Length = OASE->getLength();
9754 
9755   // If we don't have a length we have to check if the array has unitary size
9756   // for this dimension. Also, we should always expect a length if the base type
9757   // is pointer.
9758   if (!Length) {
9759     if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
9760       return ATy->getSize().getSExtValue() != 1;
9761     // We cannot assume anything.
9762     return false;
9763   }
9764 
9765   // Check if the length evaluates to 1.
9766   llvm::APSInt ConstLength;
9767   if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
9768     return false; // Can't get the integer value as a constant.
9769 
9770   return ConstLength.getSExtValue() != 1;
9771 }
9772 
9773 // Return the expression of the base of the map clause or null if it cannot
9774 // be determined and do all the necessary checks to see if the expression is
9775 // valid as a standalone map clause expression. In the process, record all the
9776 // components of the expression.
9777 static Expr *CheckMapClauseExpressionBase(
9778     Sema &SemaRef, Expr *E,
9779     OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents) {
9780   SourceLocation ELoc = E->getExprLoc();
9781   SourceRange ERange = E->getSourceRange();
9782 
9783   // The base of elements of list in a map clause have to be either:
9784   //  - a reference to variable or field.
9785   //  - a member expression.
9786   //  - an array expression.
9787   //
9788   // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
9789   // reference to 'r'.
9790   //
9791   // If we have:
9792   //
9793   // struct SS {
9794   //   Bla S;
9795   //   foo() {
9796   //     #pragma omp target map (S.Arr[:12]);
9797   //   }
9798   // }
9799   //
9800   // We want to retrieve the member expression 'this->S';
9801 
9802   Expr *RelevantExpr = nullptr;
9803 
9804   // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
9805   //  If a list item is an array section, it must specify contiguous storage.
9806   //
9807   // For this restriction it is sufficient that we make sure only references
9808   // to variables or fields and array expressions, and that no array sections
9809   // exist except in the rightmost expression (unless they cover the whole
9810   // dimension of the array). E.g. these would be invalid:
9811   //
9812   //   r.ArrS[3:5].Arr[6:7]
9813   //
9814   //   r.ArrS[3:5].x
9815   //
9816   // but these would be valid:
9817   //   r.ArrS[3].Arr[6:7]
9818   //
9819   //   r.ArrS[3].x
9820 
9821   bool AllowUnitySizeArraySection = true;
9822   bool AllowWholeSizeArraySection = true;
9823 
9824   while (!RelevantExpr) {
9825     E = E->IgnoreParenImpCasts();
9826 
9827     if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
9828       if (!isa<VarDecl>(CurE->getDecl()))
9829         break;
9830 
9831       RelevantExpr = CurE;
9832 
9833       // If we got a reference to a declaration, we should not expect any array
9834       // section before that.
9835       AllowUnitySizeArraySection = false;
9836       AllowWholeSizeArraySection = false;
9837 
9838       // Record the component.
9839       CurComponents.push_back(OMPClauseMappableExprCommon::MappableComponent(
9840           CurE, CurE->getDecl()));
9841       continue;
9842     }
9843 
9844     if (auto *CurE = dyn_cast<MemberExpr>(E)) {
9845       auto *BaseE = CurE->getBase()->IgnoreParenImpCasts();
9846 
9847       if (isa<CXXThisExpr>(BaseE))
9848         // We found a base expression: this->Val.
9849         RelevantExpr = CurE;
9850       else
9851         E = BaseE;
9852 
9853       if (!isa<FieldDecl>(CurE->getMemberDecl())) {
9854         SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
9855             << CurE->getSourceRange();
9856         break;
9857       }
9858 
9859       auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
9860 
9861       // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
9862       //  A bit-field cannot appear in a map clause.
9863       //
9864       if (FD->isBitField()) {
9865         SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_map_clause)
9866             << CurE->getSourceRange();
9867         break;
9868       }
9869 
9870       // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
9871       //  If the type of a list item is a reference to a type T then the type
9872       //  will be considered to be T for all purposes of this clause.
9873       QualType CurType = BaseE->getType().getNonReferenceType();
9874 
9875       // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
9876       //  A list item cannot be a variable that is a member of a structure with
9877       //  a union type.
9878       //
9879       if (auto *RT = CurType->getAs<RecordType>())
9880         if (RT->isUnionType()) {
9881           SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
9882               << CurE->getSourceRange();
9883           break;
9884         }
9885 
9886       // If we got a member expression, we should not expect any array section
9887       // before that:
9888       //
9889       // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
9890       //  If a list item is an element of a structure, only the rightmost symbol
9891       //  of the variable reference can be an array section.
9892       //
9893       AllowUnitySizeArraySection = false;
9894       AllowWholeSizeArraySection = false;
9895 
9896       // Record the component.
9897       CurComponents.push_back(
9898           OMPClauseMappableExprCommon::MappableComponent(CurE, FD));
9899       continue;
9900     }
9901 
9902     if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
9903       E = CurE->getBase()->IgnoreParenImpCasts();
9904 
9905       if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
9906         SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
9907             << 0 << CurE->getSourceRange();
9908         break;
9909       }
9910 
9911       // If we got an array subscript that express the whole dimension we
9912       // can have any array expressions before. If it only expressing part of
9913       // the dimension, we can only have unitary-size array expressions.
9914       if (CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
9915                                                       E->getType()))
9916         AllowWholeSizeArraySection = false;
9917 
9918       // Record the component - we don't have any declaration associated.
9919       CurComponents.push_back(
9920           OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr));
9921       continue;
9922     }
9923 
9924     if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
9925       E = CurE->getBase()->IgnoreParenImpCasts();
9926 
9927       auto CurType =
9928           OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
9929 
9930       // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
9931       //  If the type of a list item is a reference to a type T then the type
9932       //  will be considered to be T for all purposes of this clause.
9933       if (CurType->isReferenceType())
9934         CurType = CurType->getPointeeType();
9935 
9936       bool IsPointer = CurType->isAnyPointerType();
9937 
9938       if (!IsPointer && !CurType->isArrayType()) {
9939         SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
9940             << 0 << CurE->getSourceRange();
9941         break;
9942       }
9943 
9944       bool NotWhole =
9945           CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
9946       bool NotUnity =
9947           CheckArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
9948 
9949       if (AllowWholeSizeArraySection && AllowUnitySizeArraySection) {
9950         // Any array section is currently allowed.
9951         //
9952         // If this array section refers to the whole dimension we can still
9953         // accept other array sections before this one, except if the base is a
9954         // pointer. Otherwise, only unitary sections are accepted.
9955         if (NotWhole || IsPointer)
9956           AllowWholeSizeArraySection = false;
9957       } else if ((AllowUnitySizeArraySection && NotUnity) ||
9958                  (AllowWholeSizeArraySection && NotWhole)) {
9959         // A unity or whole array section is not allowed and that is not
9960         // compatible with the properties of the current array section.
9961         SemaRef.Diag(
9962             ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
9963             << CurE->getSourceRange();
9964         break;
9965       }
9966 
9967       // Record the component - we don't have any declaration associated.
9968       CurComponents.push_back(
9969           OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr));
9970       continue;
9971     }
9972 
9973     // If nothing else worked, this is not a valid map clause expression.
9974     SemaRef.Diag(ELoc,
9975                  diag::err_omp_expected_named_var_member_or_array_expression)
9976         << ERange;
9977     break;
9978   }
9979 
9980   return RelevantExpr;
9981 }
9982 
9983 // Return true if expression E associated with value VD has conflicts with other
9984 // map information.
9985 static bool CheckMapConflicts(
9986     Sema &SemaRef, DSAStackTy *DSAS, ValueDecl *VD, Expr *E,
9987     bool CurrentRegionOnly,
9988     OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents) {
9989   assert(VD && E);
9990   SourceLocation ELoc = E->getExprLoc();
9991   SourceRange ERange = E->getSourceRange();
9992 
9993   // In order to easily check the conflicts we need to match each component of
9994   // the expression under test with the components of the expressions that are
9995   // already in the stack.
9996 
9997   assert(!CurComponents.empty() && "Map clause expression with no components!");
9998   assert(CurComponents.back().getAssociatedDeclaration() == VD &&
9999          "Map clause expression with unexpected base!");
10000 
10001   // Variables to help detecting enclosing problems in data environment nests.
10002   bool IsEnclosedByDataEnvironmentExpr = false;
10003   const Expr *EnclosingExpr = nullptr;
10004 
10005   bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
10006       VD, CurrentRegionOnly,
10007       [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
10008               StackComponents) -> bool {
10009 
10010         assert(!StackComponents.empty() &&
10011                "Map clause expression with no components!");
10012         assert(StackComponents.back().getAssociatedDeclaration() == VD &&
10013                "Map clause expression with unexpected base!");
10014 
10015         // The whole expression in the stack.
10016         auto *RE = StackComponents.front().getAssociatedExpression();
10017 
10018         // Expressions must start from the same base. Here we detect at which
10019         // point both expressions diverge from each other and see if we can
10020         // detect if the memory referred to both expressions is contiguous and
10021         // do not overlap.
10022         auto CI = CurComponents.rbegin();
10023         auto CE = CurComponents.rend();
10024         auto SI = StackComponents.rbegin();
10025         auto SE = StackComponents.rend();
10026         for (; CI != CE && SI != SE; ++CI, ++SI) {
10027 
10028           // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
10029           //  At most one list item can be an array item derived from a given
10030           //  variable in map clauses of the same construct.
10031           if (CurrentRegionOnly &&
10032               (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
10033                isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
10034               (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
10035                isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
10036             SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
10037                          diag::err_omp_multiple_array_items_in_map_clause)
10038                 << CI->getAssociatedExpression()->getSourceRange();
10039             SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
10040                          diag::note_used_here)
10041                 << SI->getAssociatedExpression()->getSourceRange();
10042             return true;
10043           }
10044 
10045           // Do both expressions have the same kind?
10046           if (CI->getAssociatedExpression()->getStmtClass() !=
10047               SI->getAssociatedExpression()->getStmtClass())
10048             break;
10049 
10050           // Are we dealing with different variables/fields?
10051           if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
10052             break;
10053         }
10054 
10055         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
10056         //  List items of map clauses in the same construct must not share
10057         //  original storage.
10058         //
10059         // If the expressions are exactly the same or one is a subset of the
10060         // other, it means they are sharing storage.
10061         if (CI == CE && SI == SE) {
10062           if (CurrentRegionOnly) {
10063             SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
10064             SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
10065                 << RE->getSourceRange();
10066             return true;
10067           } else {
10068             // If we find the same expression in the enclosing data environment,
10069             // that is legal.
10070             IsEnclosedByDataEnvironmentExpr = true;
10071             return false;
10072           }
10073         }
10074 
10075         QualType DerivedType =
10076             std::prev(CI)->getAssociatedDeclaration()->getType();
10077         SourceLocation DerivedLoc =
10078             std::prev(CI)->getAssociatedExpression()->getExprLoc();
10079 
10080         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
10081         //  If the type of a list item is a reference to a type T then the type
10082         //  will be considered to be T for all purposes of this clause.
10083         DerivedType = DerivedType.getNonReferenceType();
10084 
10085         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
10086         //  A variable for which the type is pointer and an array section
10087         //  derived from that variable must not appear as list items of map
10088         //  clauses of the same construct.
10089         //
10090         // Also, cover one of the cases in:
10091         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
10092         //  If any part of the original storage of a list item has corresponding
10093         //  storage in the device data environment, all of the original storage
10094         //  must have corresponding storage in the device data environment.
10095         //
10096         if (DerivedType->isAnyPointerType()) {
10097           if (CI == CE || SI == SE) {
10098             SemaRef.Diag(
10099                 DerivedLoc,
10100                 diag::err_omp_pointer_mapped_along_with_derived_section)
10101                 << DerivedLoc;
10102           } else {
10103             assert(CI != CE && SI != SE);
10104             SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_derreferenced)
10105                 << DerivedLoc;
10106           }
10107           SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
10108               << RE->getSourceRange();
10109           return true;
10110         }
10111 
10112         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
10113         //  List items of map clauses in the same construct must not share
10114         //  original storage.
10115         //
10116         // An expression is a subset of the other.
10117         if (CurrentRegionOnly && (CI == CE || SI == SE)) {
10118           SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
10119           SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
10120               << RE->getSourceRange();
10121           return true;
10122         }
10123 
10124         // The current expression uses the same base as other expression in the
10125         // data environment but does not contain it completely.
10126         if (!CurrentRegionOnly && SI != SE)
10127           EnclosingExpr = RE;
10128 
10129         // The current expression is a subset of the expression in the data
10130         // environment.
10131         IsEnclosedByDataEnvironmentExpr |=
10132             (!CurrentRegionOnly && CI != CE && SI == SE);
10133 
10134         return false;
10135       });
10136 
10137   if (CurrentRegionOnly)
10138     return FoundError;
10139 
10140   // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
10141   //  If any part of the original storage of a list item has corresponding
10142   //  storage in the device data environment, all of the original storage must
10143   //  have corresponding storage in the device data environment.
10144   // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
10145   //  If a list item is an element of a structure, and a different element of
10146   //  the structure has a corresponding list item in the device data environment
10147   //  prior to a task encountering the construct associated with the map clause,
10148   //  then the list item must also have a corresponding list item in the device
10149   //  data environment prior to the task encountering the construct.
10150   //
10151   if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
10152     SemaRef.Diag(ELoc,
10153                  diag::err_omp_original_storage_is_shared_and_does_not_contain)
10154         << ERange;
10155     SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
10156         << EnclosingExpr->getSourceRange();
10157     return true;
10158   }
10159 
10160   return FoundError;
10161 }
10162 
10163 OMPClause *
10164 Sema::ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier,
10165                            OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
10166                            SourceLocation MapLoc, SourceLocation ColonLoc,
10167                            ArrayRef<Expr *> VarList, SourceLocation StartLoc,
10168                            SourceLocation LParenLoc, SourceLocation EndLoc) {
10169   SmallVector<Expr *, 4> Vars;
10170 
10171   // Keep track of the mappable components and base declarations in this clause.
10172   // Each entry in the list is going to have a list of components associated. We
10173   // record each set of the components so that we can build the clause later on.
10174   // In the end we should have the same amount of declarations and component
10175   // lists.
10176   OMPClauseMappableExprCommon::MappableExprComponentLists ClauseComponents;
10177   SmallVector<ValueDecl *, 16> ClauseBaseDeclarations;
10178 
10179   ClauseComponents.reserve(VarList.size());
10180   ClauseBaseDeclarations.reserve(VarList.size());
10181 
10182   for (auto &RE : VarList) {
10183     assert(RE && "Null expr in omp map");
10184     if (isa<DependentScopeDeclRefExpr>(RE)) {
10185       // It will be analyzed later.
10186       Vars.push_back(RE);
10187       continue;
10188     }
10189     SourceLocation ELoc = RE->getExprLoc();
10190 
10191     auto *VE = RE->IgnoreParenLValueCasts();
10192 
10193     if (VE->isValueDependent() || VE->isTypeDependent() ||
10194         VE->isInstantiationDependent() ||
10195         VE->containsUnexpandedParameterPack()) {
10196       // We can only analyze this information once the missing information is
10197       // resolved.
10198       Vars.push_back(RE);
10199       continue;
10200     }
10201 
10202     auto *SimpleExpr = RE->IgnoreParenCasts();
10203 
10204     if (!RE->IgnoreParenImpCasts()->isLValue()) {
10205       Diag(ELoc, diag::err_omp_expected_named_var_member_or_array_expression)
10206           << RE->getSourceRange();
10207       continue;
10208     }
10209 
10210     OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
10211     ValueDecl *CurDeclaration = nullptr;
10212 
10213     // Obtain the array or member expression bases if required. Also, fill the
10214     // components array with all the components identified in the process.
10215     auto *BE = CheckMapClauseExpressionBase(*this, SimpleExpr, CurComponents);
10216     if (!BE)
10217       continue;
10218 
10219     assert(!CurComponents.empty() &&
10220            "Invalid mappable expression information.");
10221 
10222     // For the following checks, we rely on the base declaration which is
10223     // expected to be associated with the last component. The declaration is
10224     // expected to be a variable or a field (if 'this' is being mapped).
10225     CurDeclaration = CurComponents.back().getAssociatedDeclaration();
10226     assert(CurDeclaration && "Null decl on map clause.");
10227     assert(
10228         CurDeclaration->isCanonicalDecl() &&
10229         "Expecting components to have associated only canonical declarations.");
10230 
10231     auto *VD = dyn_cast<VarDecl>(CurDeclaration);
10232     auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
10233 
10234     assert((VD || FD) && "Only variables or fields are expected here!");
10235     (void)FD;
10236 
10237     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
10238     //  threadprivate variables cannot appear in a map clause.
10239     if (VD && DSAStack->isThreadPrivate(VD)) {
10240       auto DVar = DSAStack->getTopDSA(VD, false);
10241       Diag(ELoc, diag::err_omp_threadprivate_in_map);
10242       ReportOriginalDSA(*this, DSAStack, VD, DVar);
10243       continue;
10244     }
10245 
10246     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
10247     //  A list item cannot appear in both a map clause and a data-sharing
10248     //  attribute clause on the same construct.
10249     //
10250     // TODO: Implement this check - it cannot currently be tested because of
10251     // missing implementation of the other data sharing clauses in target
10252     // directives.
10253 
10254     // Check conflicts with other map clause expressions. We check the conflicts
10255     // with the current construct separately from the enclosing data
10256     // environment, because the restrictions are different.
10257     if (CheckMapConflicts(*this, DSAStack, CurDeclaration, SimpleExpr,
10258                           /*CurrentRegionOnly=*/true, CurComponents))
10259       break;
10260     if (CheckMapConflicts(*this, DSAStack, CurDeclaration, SimpleExpr,
10261                           /*CurrentRegionOnly=*/false, CurComponents))
10262       break;
10263 
10264     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
10265     //  If the type of a list item is a reference to a type T then the type will
10266     //  be considered to be T for all purposes of this clause.
10267     QualType Type = CurDeclaration->getType().getNonReferenceType();
10268 
10269     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
10270     //  A list item must have a mappable type.
10271     if (!CheckTypeMappable(VE->getExprLoc(), VE->getSourceRange(), *this,
10272                            DSAStack, Type))
10273       continue;
10274 
10275     // target enter data
10276     // OpenMP [2.10.2, Restrictions, p. 99]
10277     // A map-type must be specified in all map clauses and must be either
10278     // to or alloc.
10279     OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
10280     if (DKind == OMPD_target_enter_data &&
10281         !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
10282       Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
10283           << (IsMapTypeImplicit ? 1 : 0)
10284           << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
10285           << getOpenMPDirectiveName(DKind);
10286       continue;
10287     }
10288 
10289     // target exit_data
10290     // OpenMP [2.10.3, Restrictions, p. 102]
10291     // A map-type must be specified in all map clauses and must be either
10292     // from, release, or delete.
10293     DKind = DSAStack->getCurrentDirective();
10294     if (DKind == OMPD_target_exit_data &&
10295         !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
10296           MapType == OMPC_MAP_delete)) {
10297       Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
10298           << (IsMapTypeImplicit ? 1 : 0)
10299           << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
10300           << getOpenMPDirectiveName(DKind);
10301       continue;
10302     }
10303 
10304     // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
10305     // A list item cannot appear in both a map clause and a data-sharing
10306     // attribute clause on the same construct
10307     if (DKind == OMPD_target && VD) {
10308       auto DVar = DSAStack->getTopDSA(VD, false);
10309       if (isOpenMPPrivate(DVar.CKind)) {
10310         Diag(ELoc, diag::err_omp_variable_in_map_and_dsa)
10311             << getOpenMPClauseName(DVar.CKind)
10312             << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
10313         ReportOriginalDSA(*this, DSAStack, CurDeclaration, DVar);
10314         continue;
10315       }
10316     }
10317 
10318     // Save the current expression.
10319     Vars.push_back(RE);
10320 
10321     // Store the components in the stack so that they can be used to check
10322     // against other clauses later on.
10323     DSAStack->addMappableExpressionComponents(CurDeclaration, CurComponents);
10324 
10325     // Save the components and declaration to create the clause. For purposes of
10326     // the clause creation, any component list that has has base 'this' uses
10327     // null has
10328     ClauseComponents.resize(ClauseComponents.size() + 1);
10329     ClauseComponents.back().append(CurComponents.begin(), CurComponents.end());
10330     ClauseBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
10331                                                          : CurDeclaration);
10332   }
10333 
10334   // We need to produce a map clause even if we don't have variables so that
10335   // other diagnostics related with non-existing map clauses are accurate.
10336   return OMPMapClause::Create(
10337       Context, StartLoc, LParenLoc, EndLoc, Vars, ClauseBaseDeclarations,
10338       ClauseComponents, MapTypeModifier, MapType, IsMapTypeImplicit, MapLoc);
10339 }
10340 
10341 QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
10342                                                TypeResult ParsedType) {
10343   assert(ParsedType.isUsable());
10344 
10345   QualType ReductionType = GetTypeFromParser(ParsedType.get());
10346   if (ReductionType.isNull())
10347     return QualType();
10348 
10349   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
10350   // A type name in a declare reduction directive cannot be a function type, an
10351   // array type, a reference type, or a type qualified with const, volatile or
10352   // restrict.
10353   if (ReductionType.hasQualifiers()) {
10354     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
10355     return QualType();
10356   }
10357 
10358   if (ReductionType->isFunctionType()) {
10359     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
10360     return QualType();
10361   }
10362   if (ReductionType->isReferenceType()) {
10363     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
10364     return QualType();
10365   }
10366   if (ReductionType->isArrayType()) {
10367     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
10368     return QualType();
10369   }
10370   return ReductionType;
10371 }
10372 
10373 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
10374     Scope *S, DeclContext *DC, DeclarationName Name,
10375     ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
10376     AccessSpecifier AS, Decl *PrevDeclInScope) {
10377   SmallVector<Decl *, 8> Decls;
10378   Decls.reserve(ReductionTypes.size());
10379 
10380   LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
10381                       ForRedeclaration);
10382   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
10383   // A reduction-identifier may not be re-declared in the current scope for the
10384   // same type or for a type that is compatible according to the base language
10385   // rules.
10386   llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
10387   OMPDeclareReductionDecl *PrevDRD = nullptr;
10388   bool InCompoundScope = true;
10389   if (S != nullptr) {
10390     // Find previous declaration with the same name not referenced in other
10391     // declarations.
10392     FunctionScopeInfo *ParentFn = getEnclosingFunction();
10393     InCompoundScope =
10394         (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
10395     LookupName(Lookup, S);
10396     FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
10397                          /*AllowInlineNamespace=*/false);
10398     llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
10399     auto Filter = Lookup.makeFilter();
10400     while (Filter.hasNext()) {
10401       auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
10402       if (InCompoundScope) {
10403         auto I = UsedAsPrevious.find(PrevDecl);
10404         if (I == UsedAsPrevious.end())
10405           UsedAsPrevious[PrevDecl] = false;
10406         if (auto *D = PrevDecl->getPrevDeclInScope())
10407           UsedAsPrevious[D] = true;
10408       }
10409       PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
10410           PrevDecl->getLocation();
10411     }
10412     Filter.done();
10413     if (InCompoundScope) {
10414       for (auto &PrevData : UsedAsPrevious) {
10415         if (!PrevData.second) {
10416           PrevDRD = PrevData.first;
10417           break;
10418         }
10419       }
10420     }
10421   } else if (PrevDeclInScope != nullptr) {
10422     auto *PrevDRDInScope = PrevDRD =
10423         cast<OMPDeclareReductionDecl>(PrevDeclInScope);
10424     do {
10425       PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
10426           PrevDRDInScope->getLocation();
10427       PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
10428     } while (PrevDRDInScope != nullptr);
10429   }
10430   for (auto &TyData : ReductionTypes) {
10431     auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
10432     bool Invalid = false;
10433     if (I != PreviousRedeclTypes.end()) {
10434       Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
10435           << TyData.first;
10436       Diag(I->second, diag::note_previous_definition);
10437       Invalid = true;
10438     }
10439     PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
10440     auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
10441                                                 Name, TyData.first, PrevDRD);
10442     DC->addDecl(DRD);
10443     DRD->setAccess(AS);
10444     Decls.push_back(DRD);
10445     if (Invalid)
10446       DRD->setInvalidDecl();
10447     else
10448       PrevDRD = DRD;
10449   }
10450 
10451   return DeclGroupPtrTy::make(
10452       DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
10453 }
10454 
10455 void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
10456   auto *DRD = cast<OMPDeclareReductionDecl>(D);
10457 
10458   // Enter new function scope.
10459   PushFunctionScope();
10460   getCurFunction()->setHasBranchProtectedScope();
10461   getCurFunction()->setHasOMPDeclareReductionCombiner();
10462 
10463   if (S != nullptr)
10464     PushDeclContext(S, DRD);
10465   else
10466     CurContext = DRD;
10467 
10468   PushExpressionEvaluationContext(PotentiallyEvaluated);
10469 
10470   QualType ReductionType = DRD->getType();
10471   // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
10472   // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
10473   // uses semantics of argument handles by value, but it should be passed by
10474   // reference. C lang does not support references, so pass all parameters as
10475   // pointers.
10476   // Create 'T omp_in;' variable.
10477   auto *OmpInParm =
10478       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
10479   // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
10480   // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
10481   // uses semantics of argument handles by value, but it should be passed by
10482   // reference. C lang does not support references, so pass all parameters as
10483   // pointers.
10484   // Create 'T omp_out;' variable.
10485   auto *OmpOutParm =
10486       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
10487   if (S != nullptr) {
10488     PushOnScopeChains(OmpInParm, S);
10489     PushOnScopeChains(OmpOutParm, S);
10490   } else {
10491     DRD->addDecl(OmpInParm);
10492     DRD->addDecl(OmpOutParm);
10493   }
10494 }
10495 
10496 void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
10497   auto *DRD = cast<OMPDeclareReductionDecl>(D);
10498   DiscardCleanupsInEvaluationContext();
10499   PopExpressionEvaluationContext();
10500 
10501   PopDeclContext();
10502   PopFunctionScopeInfo();
10503 
10504   if (Combiner != nullptr)
10505     DRD->setCombiner(Combiner);
10506   else
10507     DRD->setInvalidDecl();
10508 }
10509 
10510 void Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
10511   auto *DRD = cast<OMPDeclareReductionDecl>(D);
10512 
10513   // Enter new function scope.
10514   PushFunctionScope();
10515   getCurFunction()->setHasBranchProtectedScope();
10516 
10517   if (S != nullptr)
10518     PushDeclContext(S, DRD);
10519   else
10520     CurContext = DRD;
10521 
10522   PushExpressionEvaluationContext(PotentiallyEvaluated);
10523 
10524   QualType ReductionType = DRD->getType();
10525   // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
10526   // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
10527   // uses semantics of argument handles by value, but it should be passed by
10528   // reference. C lang does not support references, so pass all parameters as
10529   // pointers.
10530   // Create 'T omp_priv;' variable.
10531   auto *OmpPrivParm =
10532       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
10533   // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
10534   // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
10535   // uses semantics of argument handles by value, but it should be passed by
10536   // reference. C lang does not support references, so pass all parameters as
10537   // pointers.
10538   // Create 'T omp_orig;' variable.
10539   auto *OmpOrigParm =
10540       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
10541   if (S != nullptr) {
10542     PushOnScopeChains(OmpPrivParm, S);
10543     PushOnScopeChains(OmpOrigParm, S);
10544   } else {
10545     DRD->addDecl(OmpPrivParm);
10546     DRD->addDecl(OmpOrigParm);
10547   }
10548 }
10549 
10550 void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D,
10551                                                      Expr *Initializer) {
10552   auto *DRD = cast<OMPDeclareReductionDecl>(D);
10553   DiscardCleanupsInEvaluationContext();
10554   PopExpressionEvaluationContext();
10555 
10556   PopDeclContext();
10557   PopFunctionScopeInfo();
10558 
10559   if (Initializer != nullptr)
10560     DRD->setInitializer(Initializer);
10561   else
10562     DRD->setInvalidDecl();
10563 }
10564 
10565 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
10566     Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
10567   for (auto *D : DeclReductions.get()) {
10568     if (IsValid) {
10569       auto *DRD = cast<OMPDeclareReductionDecl>(D);
10570       if (S != nullptr)
10571         PushOnScopeChains(DRD, S, /*AddToContext=*/false);
10572     } else
10573       D->setInvalidDecl();
10574   }
10575   return DeclReductions;
10576 }
10577 
10578 OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
10579                                            SourceLocation StartLoc,
10580                                            SourceLocation LParenLoc,
10581                                            SourceLocation EndLoc) {
10582   Expr *ValExpr = NumTeams;
10583 
10584   // OpenMP [teams Constrcut, Restrictions]
10585   // The num_teams expression must evaluate to a positive integer value.
10586   if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
10587                                  /*StrictlyPositive=*/true))
10588     return nullptr;
10589 
10590   return new (Context) OMPNumTeamsClause(ValExpr, StartLoc, LParenLoc, EndLoc);
10591 }
10592 
10593 OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
10594                                               SourceLocation StartLoc,
10595                                               SourceLocation LParenLoc,
10596                                               SourceLocation EndLoc) {
10597   Expr *ValExpr = ThreadLimit;
10598 
10599   // OpenMP [teams Constrcut, Restrictions]
10600   // The thread_limit expression must evaluate to a positive integer value.
10601   if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
10602                                  /*StrictlyPositive=*/true))
10603     return nullptr;
10604 
10605   return new (Context) OMPThreadLimitClause(ValExpr, StartLoc, LParenLoc,
10606                                             EndLoc);
10607 }
10608 
10609 OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
10610                                            SourceLocation StartLoc,
10611                                            SourceLocation LParenLoc,
10612                                            SourceLocation EndLoc) {
10613   Expr *ValExpr = Priority;
10614 
10615   // OpenMP [2.9.1, task Constrcut]
10616   // The priority-value is a non-negative numerical scalar expression.
10617   if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_priority,
10618                                  /*StrictlyPositive=*/false))
10619     return nullptr;
10620 
10621   return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc);
10622 }
10623 
10624 OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
10625                                             SourceLocation StartLoc,
10626                                             SourceLocation LParenLoc,
10627                                             SourceLocation EndLoc) {
10628   Expr *ValExpr = Grainsize;
10629 
10630   // OpenMP [2.9.2, taskloop Constrcut]
10631   // The parameter of the grainsize clause must be a positive integer
10632   // expression.
10633   if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize,
10634                                  /*StrictlyPositive=*/true))
10635     return nullptr;
10636 
10637   return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc);
10638 }
10639 
10640 OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
10641                                            SourceLocation StartLoc,
10642                                            SourceLocation LParenLoc,
10643                                            SourceLocation EndLoc) {
10644   Expr *ValExpr = NumTasks;
10645 
10646   // OpenMP [2.9.2, taskloop Constrcut]
10647   // The parameter of the num_tasks clause must be a positive integer
10648   // expression.
10649   if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks,
10650                                  /*StrictlyPositive=*/true))
10651     return nullptr;
10652 
10653   return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc);
10654 }
10655 
10656 OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
10657                                        SourceLocation LParenLoc,
10658                                        SourceLocation EndLoc) {
10659   // OpenMP [2.13.2, critical construct, Description]
10660   // ... where hint-expression is an integer constant expression that evaluates
10661   // to a valid lock hint.
10662   ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
10663   if (HintExpr.isInvalid())
10664     return nullptr;
10665   return new (Context)
10666       OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
10667 }
10668 
10669 OMPClause *Sema::ActOnOpenMPDistScheduleClause(
10670     OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
10671     SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
10672     SourceLocation EndLoc) {
10673   if (Kind == OMPC_DIST_SCHEDULE_unknown) {
10674     std::string Values;
10675     Values += "'";
10676     Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
10677     Values += "'";
10678     Diag(KindLoc, diag::err_omp_unexpected_clause_value)
10679         << Values << getOpenMPClauseName(OMPC_dist_schedule);
10680     return nullptr;
10681   }
10682   Expr *ValExpr = ChunkSize;
10683   Stmt *HelperValStmt = nullptr;
10684   if (ChunkSize) {
10685     if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
10686         !ChunkSize->isInstantiationDependent() &&
10687         !ChunkSize->containsUnexpandedParameterPack()) {
10688       SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
10689       ExprResult Val =
10690           PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
10691       if (Val.isInvalid())
10692         return nullptr;
10693 
10694       ValExpr = Val.get();
10695 
10696       // OpenMP [2.7.1, Restrictions]
10697       //  chunk_size must be a loop invariant integer expression with a positive
10698       //  value.
10699       llvm::APSInt Result;
10700       if (ValExpr->isIntegerConstantExpr(Result, Context)) {
10701         if (Result.isSigned() && !Result.isStrictlyPositive()) {
10702           Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
10703               << "dist_schedule" << ChunkSize->getSourceRange();
10704           return nullptr;
10705         }
10706       } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) {
10707         llvm::MapVector<Expr *, DeclRefExpr *> Captures;
10708         ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
10709         HelperValStmt = buildPreInits(Context, Captures);
10710       }
10711     }
10712   }
10713 
10714   return new (Context)
10715       OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
10716                             Kind, ValExpr, HelperValStmt);
10717 }
10718 
10719 OMPClause *Sema::ActOnOpenMPDefaultmapClause(
10720     OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
10721     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
10722     SourceLocation KindLoc, SourceLocation EndLoc) {
10723   // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)'
10724   if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom ||
10725       Kind != OMPC_DEFAULTMAP_scalar) {
10726     std::string Value;
10727     SourceLocation Loc;
10728     Value += "'";
10729     if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
10730       Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
10731                  OMPC_DEFAULTMAP_MODIFIER_tofrom);
10732       Loc = MLoc;
10733     } else {
10734       Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
10735                  OMPC_DEFAULTMAP_scalar);
10736       Loc = KindLoc;
10737     }
10738     Value += "'";
10739     Diag(Loc, diag::err_omp_unexpected_clause_value)
10740         << Value << getOpenMPClauseName(OMPC_defaultmap);
10741     return nullptr;
10742   }
10743 
10744   return new (Context)
10745       OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
10746 }
10747 
10748 bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
10749   DeclContext *CurLexicalContext = getCurLexicalContext();
10750   if (!CurLexicalContext->isFileContext() &&
10751       !CurLexicalContext->isExternCContext() &&
10752       !CurLexicalContext->isExternCXXContext()) {
10753     Diag(Loc, diag::err_omp_region_not_file_context);
10754     return false;
10755   }
10756   if (IsInOpenMPDeclareTargetContext) {
10757     Diag(Loc, diag::err_omp_enclosed_declare_target);
10758     return false;
10759   }
10760 
10761   IsInOpenMPDeclareTargetContext = true;
10762   return true;
10763 }
10764 
10765 void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
10766   assert(IsInOpenMPDeclareTargetContext &&
10767          "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
10768 
10769   IsInOpenMPDeclareTargetContext = false;
10770 }
10771 
10772 void
10773 Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope, CXXScopeSpec &ScopeSpec,
10774                                    const DeclarationNameInfo &Id,
10775                                    OMPDeclareTargetDeclAttr::MapTypeTy MT,
10776                                    NamedDeclSetType &SameDirectiveDecls) {
10777   LookupResult Lookup(*this, Id, LookupOrdinaryName);
10778   LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
10779 
10780   if (Lookup.isAmbiguous())
10781     return;
10782   Lookup.suppressDiagnostics();
10783 
10784   if (!Lookup.isSingleResult()) {
10785     if (TypoCorrection Corrected =
10786             CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr,
10787                         llvm::make_unique<VarOrFuncDeclFilterCCC>(*this),
10788                         CTK_ErrorRecovery)) {
10789       diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
10790                                   << Id.getName());
10791       checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
10792       return;
10793     }
10794 
10795     Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
10796     return;
10797   }
10798 
10799   NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
10800   if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) {
10801     if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
10802       Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
10803 
10804     if (!ND->hasAttr<OMPDeclareTargetDeclAttr>()) {
10805       Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT);
10806       ND->addAttr(A);
10807       if (ASTMutationListener *ML = Context.getASTMutationListener())
10808         ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
10809       checkDeclIsAllowedInOpenMPTarget(nullptr, ND);
10810     } else if (ND->getAttr<OMPDeclareTargetDeclAttr>()->getMapType() != MT) {
10811       Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link)
10812           << Id.getName();
10813     }
10814   } else
10815     Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
10816 }
10817 
10818 static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
10819                                      Sema &SemaRef, Decl *D) {
10820   if (!D)
10821     return;
10822   Decl *LD = nullptr;
10823   if (isa<TagDecl>(D)) {
10824     LD = cast<TagDecl>(D)->getDefinition();
10825   } else if (isa<VarDecl>(D)) {
10826     LD = cast<VarDecl>(D)->getDefinition();
10827 
10828     // If this is an implicit variable that is legal and we do not need to do
10829     // anything.
10830     if (cast<VarDecl>(D)->isImplicit()) {
10831       Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
10832           SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
10833       D->addAttr(A);
10834       if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
10835         ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
10836       return;
10837     }
10838 
10839   } else if (isa<FunctionDecl>(D)) {
10840     const FunctionDecl *FD = nullptr;
10841     if (cast<FunctionDecl>(D)->hasBody(FD))
10842       LD = const_cast<FunctionDecl *>(FD);
10843 
10844     // If the definition is associated with the current declaration in the
10845     // target region (it can be e.g. a lambda) that is legal and we do not need
10846     // to do anything else.
10847     if (LD == D) {
10848       Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
10849           SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
10850       D->addAttr(A);
10851       if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
10852         ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
10853       return;
10854     }
10855   }
10856   if (!LD)
10857     LD = D;
10858   if (LD && !LD->hasAttr<OMPDeclareTargetDeclAttr>() &&
10859       (isa<VarDecl>(LD) || isa<FunctionDecl>(LD))) {
10860     // Outlined declaration is not declared target.
10861     if (LD->isOutOfLine()) {
10862       SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
10863       SemaRef.Diag(SL, diag::note_used_here) << SR;
10864     } else {
10865       DeclContext *DC = LD->getDeclContext();
10866       while (DC) {
10867         if (isa<FunctionDecl>(DC) &&
10868             cast<FunctionDecl>(DC)->hasAttr<OMPDeclareTargetDeclAttr>())
10869           break;
10870         DC = DC->getParent();
10871       }
10872       if (DC)
10873         return;
10874 
10875       // Is not declared in target context.
10876       SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
10877       SemaRef.Diag(SL, diag::note_used_here) << SR;
10878     }
10879     // Mark decl as declared target to prevent further diagnostic.
10880     Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
10881         SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
10882     D->addAttr(A);
10883     if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
10884       ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
10885   }
10886 }
10887 
10888 static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
10889                                    Sema &SemaRef, DSAStackTy *Stack,
10890                                    ValueDecl *VD) {
10891   if (VD->hasAttr<OMPDeclareTargetDeclAttr>())
10892     return true;
10893   if (!CheckTypeMappable(SL, SR, SemaRef, Stack, VD->getType()))
10894     return false;
10895   return true;
10896 }
10897 
10898 void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D) {
10899   if (!D || D->isInvalidDecl())
10900     return;
10901   SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
10902   SourceLocation SL = E ? E->getLocStart() : D->getLocation();
10903   // 2.10.6: threadprivate variable cannot appear in a declare target directive.
10904   if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
10905     if (DSAStack->isThreadPrivate(VD)) {
10906       Diag(SL, diag::err_omp_threadprivate_in_target);
10907       ReportOriginalDSA(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
10908       return;
10909     }
10910   }
10911   if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
10912     // Problem if any with var declared with incomplete type will be reported
10913     // as normal, so no need to check it here.
10914     if ((E || !VD->getType()->isIncompleteType()) &&
10915         !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD)) {
10916       // Mark decl as declared target to prevent further diagnostic.
10917       if (isa<VarDecl>(VD) || isa<FunctionDecl>(VD)) {
10918         Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
10919             Context, OMPDeclareTargetDeclAttr::MT_To);
10920         VD->addAttr(A);
10921         if (ASTMutationListener *ML = Context.getASTMutationListener())
10922           ML->DeclarationMarkedOpenMPDeclareTarget(VD, A);
10923       }
10924       return;
10925     }
10926   }
10927   if (!E) {
10928     // Checking declaration inside declare target region.
10929     if (!D->hasAttr<OMPDeclareTargetDeclAttr>() &&
10930         (isa<VarDecl>(D) || isa<FunctionDecl>(D))) {
10931       Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
10932           Context, OMPDeclareTargetDeclAttr::MT_To);
10933       D->addAttr(A);
10934       if (ASTMutationListener *ML = Context.getASTMutationListener())
10935         ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
10936     }
10937     return;
10938   }
10939   checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
10940 }
10941