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/Decl.h"
19 #include "clang/AST/DeclCXX.h"
20 #include "clang/AST/DeclOpenMP.h"
21 #include "clang/AST/StmtCXX.h"
22 #include "clang/AST/StmtOpenMP.h"
23 #include "clang/AST/StmtVisitor.h"
24 #include "clang/Basic/OpenMPKinds.h"
25 #include "clang/Basic/TargetInfo.h"
26 #include "clang/Lex/Preprocessor.h"
27 #include "clang/Sema/Initialization.h"
28 #include "clang/Sema/Lookup.h"
29 #include "clang/Sema/Scope.h"
30 #include "clang/Sema/ScopeInfo.h"
31 #include "clang/Sema/SemaInternal.h"
32 using namespace clang;
33 
34 //===----------------------------------------------------------------------===//
35 // Stack of data-sharing attributes for variables
36 //===----------------------------------------------------------------------===//
37 
38 namespace {
39 /// \brief Default data sharing attributes, which can be applied to directive.
40 enum DefaultDataSharingAttributes {
41   DSA_unspecified = 0, /// \brief Data sharing attribute not specified.
42   DSA_none = 1 << 0,   /// \brief Default data sharing attribute 'none'.
43   DSA_shared = 1 << 1  /// \brief Default data sharing attribute 'shared'.
44 };
45 
46 template <class T> struct MatchesAny {
47   explicit MatchesAny(ArrayRef<T> Arr) : Arr(std::move(Arr)) {}
48   bool operator()(T Kind) {
49     for (auto KindEl : Arr)
50       if (KindEl == Kind)
51         return true;
52     return false;
53   }
54 
55 private:
56   ArrayRef<T> Arr;
57 };
58 struct MatchesAlways {
59   MatchesAlways() {}
60   template <class T> bool operator()(T) { return true; }
61 };
62 
63 typedef MatchesAny<OpenMPClauseKind> MatchesAnyClause;
64 typedef MatchesAny<OpenMPDirectiveKind> MatchesAnyDirective;
65 
66 /// \brief Stack for tracking declarations used in OpenMP directives and
67 /// clauses and their data-sharing attributes.
68 class DSAStackTy {
69 public:
70   struct DSAVarData {
71     OpenMPDirectiveKind DKind;
72     OpenMPClauseKind CKind;
73     Expr *RefExpr;
74     DeclRefExpr *PrivateCopy;
75     SourceLocation ImplicitDSALoc;
76     DSAVarData()
77         : DKind(OMPD_unknown), CKind(OMPC_unknown), RefExpr(nullptr),
78           PrivateCopy(nullptr), ImplicitDSALoc() {}
79   };
80 
81 private:
82   typedef SmallVector<Expr *, 4> MapInfo;
83 
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 llvm::DenseMap<ValueDecl *, unsigned> LoopControlVariablesMapTy;
92   typedef llvm::DenseMap<ValueDecl *, MapInfo> MappedDeclsTy;
93   typedef llvm::StringMap<std::pair<OMPCriticalDirective *, llvm::APSInt>>
94       CriticalsWithHintsTy;
95 
96   struct SharingMapTy {
97     DeclSAMapTy SharingMap;
98     AlignedMapTy AlignedMap;
99     MappedDeclsTy MappedDecls;
100     LoopControlVariablesMapTy LCVMap;
101     DefaultDataSharingAttributes DefaultAttr;
102     SourceLocation DefaultAttrLoc;
103     OpenMPDirectiveKind Directive;
104     DeclarationNameInfo DirectiveName;
105     Scope *CurScope;
106     SourceLocation ConstructLoc;
107     /// \brief first argument (Expr *) contains optional argument of the
108     /// 'ordered' clause, the second one is true if the regions has 'ordered'
109     /// clause, false otherwise.
110     llvm::PointerIntPair<Expr *, 1, bool> OrderedRegion;
111     bool NowaitRegion;
112     bool CancelRegion;
113     unsigned AssociatedLoops;
114     SourceLocation InnerTeamsRegionLoc;
115     SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
116                  Scope *CurScope, SourceLocation Loc)
117         : SharingMap(), AlignedMap(), LCVMap(), DefaultAttr(DSA_unspecified),
118           Directive(DKind), DirectiveName(std::move(Name)), CurScope(CurScope),
119           ConstructLoc(Loc), OrderedRegion(), NowaitRegion(false),
120           CancelRegion(false), AssociatedLoops(1), InnerTeamsRegionLoc() {}
121     SharingMapTy()
122         : SharingMap(), AlignedMap(), LCVMap(), DefaultAttr(DSA_unspecified),
123           Directive(OMPD_unknown), DirectiveName(), CurScope(nullptr),
124           ConstructLoc(), OrderedRegion(), NowaitRegion(false),
125           CancelRegion(false), AssociatedLoops(1), InnerTeamsRegionLoc() {}
126   };
127 
128   typedef SmallVector<SharingMapTy, 4> StackTy;
129 
130   /// \brief Stack of used declaration and their data-sharing attributes.
131   StackTy Stack;
132   /// \brief true, if check for DSA must be from parent directive, false, if
133   /// from current directive.
134   OpenMPClauseKind ClauseKindMode;
135   Sema &SemaRef;
136   bool ForceCapturing;
137   CriticalsWithHintsTy Criticals;
138 
139   typedef SmallVector<SharingMapTy, 8>::reverse_iterator reverse_iterator;
140 
141   DSAVarData getDSA(StackTy::reverse_iterator Iter, ValueDecl *D);
142 
143   /// \brief Checks if the variable is a local for OpenMP region.
144   bool isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter);
145 
146 public:
147   explicit DSAStackTy(Sema &S)
148       : Stack(1), ClauseKindMode(OMPC_unknown), SemaRef(S),
149         ForceCapturing(false) {}
150 
151   bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
152   void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
153 
154   bool isForceVarCapturing() const { return ForceCapturing; }
155   void setForceVarCapturing(bool V) { ForceCapturing = V; }
156 
157   void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
158             Scope *CurScope, SourceLocation Loc) {
159     Stack.push_back(SharingMapTy(DKind, DirName, CurScope, Loc));
160     Stack.back().DefaultAttrLoc = Loc;
161   }
162 
163   void pop() {
164     assert(Stack.size() > 1 && "Data-sharing attributes stack is empty!");
165     Stack.pop_back();
166   }
167 
168   void addCriticalWithHint(OMPCriticalDirective *D, llvm::APSInt Hint) {
169     Criticals[D->getDirectiveName().getAsString()] = std::make_pair(D, Hint);
170   }
171   const std::pair<OMPCriticalDirective *, llvm::APSInt>
172   getCriticalWithHint(const DeclarationNameInfo &Name) const {
173     auto I = Criticals.find(Name.getAsString());
174     if (I != Criticals.end())
175       return I->second;
176     return std::make_pair(nullptr, llvm::APSInt());
177   }
178   /// \brief If 'aligned' declaration for given variable \a D was not seen yet,
179   /// add it and return NULL; otherwise return previous occurrence's expression
180   /// for diagnostics.
181   Expr *addUniqueAligned(ValueDecl *D, Expr *NewDE);
182 
183   /// \brief Register specified variable as loop control variable.
184   void addLoopControlVariable(ValueDecl *D);
185   /// \brief Check if the specified variable is a loop control variable for
186   /// current region.
187   /// \return The index of the loop control variable in the list of associated
188   /// for-loops (from outer to inner).
189   unsigned isLoopControlVariable(ValueDecl *D);
190   /// \brief Check if the specified variable is a loop control variable for
191   /// parent region.
192   /// \return The index of the loop control variable in the list of associated
193   /// for-loops (from outer to inner).
194   unsigned isParentLoopControlVariable(ValueDecl *D);
195   /// \brief Get the loop control variable for the I-th loop (or nullptr) in
196   /// parent directive.
197   ValueDecl *getParentLoopControlVariable(unsigned I);
198 
199   /// \brief Adds explicit data sharing attribute to the specified declaration.
200   void addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A,
201               DeclRefExpr *PrivateCopy = nullptr);
202 
203   /// \brief Returns data sharing attributes from top of the stack for the
204   /// specified declaration.
205   DSAVarData getTopDSA(ValueDecl *D, bool FromParent);
206   /// \brief Returns data-sharing attributes for the specified declaration.
207   DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent);
208   /// \brief Checks if the specified variables has data-sharing attributes which
209   /// match specified \a CPred predicate in any directive which matches \a DPred
210   /// predicate.
211   template <class ClausesPredicate, class DirectivesPredicate>
212   DSAVarData hasDSA(ValueDecl *D, ClausesPredicate CPred,
213                     DirectivesPredicate DPred, bool FromParent);
214   /// \brief Checks if the specified variables has data-sharing attributes which
215   /// match specified \a CPred predicate in any innermost directive which
216   /// matches \a DPred predicate.
217   template <class ClausesPredicate, class DirectivesPredicate>
218   DSAVarData hasInnermostDSA(ValueDecl *D, ClausesPredicate CPred,
219                              DirectivesPredicate DPred, bool FromParent);
220   /// \brief Checks if the specified variables has explicit data-sharing
221   /// attributes which match specified \a CPred predicate at the specified
222   /// OpenMP region.
223   bool hasExplicitDSA(ValueDecl *D,
224                       const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
225                       unsigned Level);
226 
227   /// \brief Returns true if the directive at level \Level matches in the
228   /// specified \a DPred predicate.
229   bool hasExplicitDirective(
230       const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
231       unsigned Level);
232 
233   /// \brief Finds a directive which matches specified \a DPred predicate.
234   template <class NamedDirectivesPredicate>
235   bool hasDirective(NamedDirectivesPredicate DPred, bool FromParent);
236 
237   /// \brief Returns currently analyzed directive.
238   OpenMPDirectiveKind getCurrentDirective() const {
239     return Stack.back().Directive;
240   }
241   /// \brief Returns parent directive.
242   OpenMPDirectiveKind getParentDirective() const {
243     if (Stack.size() > 2)
244       return Stack[Stack.size() - 2].Directive;
245     return OMPD_unknown;
246   }
247   /// \brief Return the directive associated with the provided scope.
248   OpenMPDirectiveKind getDirectiveForScope(const Scope *S) const;
249 
250   /// \brief Set default data sharing attribute to none.
251   void setDefaultDSANone(SourceLocation Loc) {
252     Stack.back().DefaultAttr = DSA_none;
253     Stack.back().DefaultAttrLoc = Loc;
254   }
255   /// \brief Set default data sharing attribute to shared.
256   void setDefaultDSAShared(SourceLocation Loc) {
257     Stack.back().DefaultAttr = DSA_shared;
258     Stack.back().DefaultAttrLoc = Loc;
259   }
260 
261   DefaultDataSharingAttributes getDefaultDSA() const {
262     return Stack.back().DefaultAttr;
263   }
264   SourceLocation getDefaultDSALocation() const {
265     return Stack.back().DefaultAttrLoc;
266   }
267 
268   /// \brief Checks if the specified variable is a threadprivate.
269   bool isThreadPrivate(VarDecl *D) {
270     DSAVarData DVar = getTopDSA(D, false);
271     return isOpenMPThreadPrivate(DVar.CKind);
272   }
273 
274   /// \brief Marks current region as ordered (it has an 'ordered' clause).
275   void setOrderedRegion(bool IsOrdered, Expr *Param) {
276     Stack.back().OrderedRegion.setInt(IsOrdered);
277     Stack.back().OrderedRegion.setPointer(Param);
278   }
279   /// \brief Returns true, if parent region is ordered (has associated
280   /// 'ordered' clause), false - otherwise.
281   bool isParentOrderedRegion() const {
282     if (Stack.size() > 2)
283       return Stack[Stack.size() - 2].OrderedRegion.getInt();
284     return false;
285   }
286   /// \brief Returns optional parameter for the ordered region.
287   Expr *getParentOrderedRegionParam() const {
288     if (Stack.size() > 2)
289       return Stack[Stack.size() - 2].OrderedRegion.getPointer();
290     return nullptr;
291   }
292   /// \brief Marks current region as nowait (it has a 'nowait' clause).
293   void setNowaitRegion(bool IsNowait = true) {
294     Stack.back().NowaitRegion = IsNowait;
295   }
296   /// \brief Returns true, if parent region is nowait (has associated
297   /// 'nowait' clause), false - otherwise.
298   bool isParentNowaitRegion() const {
299     if (Stack.size() > 2)
300       return Stack[Stack.size() - 2].NowaitRegion;
301     return false;
302   }
303   /// \brief Marks parent region as cancel region.
304   void setParentCancelRegion(bool Cancel = true) {
305     if (Stack.size() > 2)
306       Stack[Stack.size() - 2].CancelRegion =
307           Stack[Stack.size() - 2].CancelRegion || Cancel;
308   }
309   /// \brief Return true if current region has inner cancel construct.
310   bool isCancelRegion() const {
311     return Stack.back().CancelRegion;
312   }
313 
314   /// \brief Set collapse value for the region.
315   void setAssociatedLoops(unsigned Val) { Stack.back().AssociatedLoops = Val; }
316   /// \brief Return collapse value for region.
317   unsigned getAssociatedLoops() const { return Stack.back().AssociatedLoops; }
318 
319   /// \brief Marks current target region as one with closely nested teams
320   /// region.
321   void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
322     if (Stack.size() > 2)
323       Stack[Stack.size() - 2].InnerTeamsRegionLoc = TeamsRegionLoc;
324   }
325   /// \brief Returns true, if current region has closely nested teams region.
326   bool hasInnerTeamsRegion() const {
327     return getInnerTeamsRegionLoc().isValid();
328   }
329   /// \brief Returns location of the nested teams region (if any).
330   SourceLocation getInnerTeamsRegionLoc() const {
331     if (Stack.size() > 1)
332       return Stack.back().InnerTeamsRegionLoc;
333     return SourceLocation();
334   }
335 
336   Scope *getCurScope() const { return Stack.back().CurScope; }
337   Scope *getCurScope() { return Stack.back().CurScope; }
338   SourceLocation getConstructLoc() { return Stack.back().ConstructLoc; }
339 
340   // Do the check specified in MapInfoCheck and return true if any issue is
341   // found.
342   template <class MapInfoCheck>
343   bool checkMapInfoForVar(ValueDecl *VD, bool CurrentRegionOnly,
344                           MapInfoCheck Check) {
345     auto SI = Stack.rbegin();
346     auto SE = Stack.rend();
347 
348     if (SI == SE)
349       return false;
350 
351     if (CurrentRegionOnly) {
352       SE = std::next(SI);
353     } else {
354       ++SI;
355     }
356 
357     for (; SI != SE; ++SI) {
358       auto MI = SI->MappedDecls.find(VD);
359       if (MI != SI->MappedDecls.end()) {
360         for (Expr *E : MI->second) {
361           if (Check(E))
362             return true;
363         }
364       }
365     }
366     return false;
367   }
368 
369   void addExprToVarMapInfo(ValueDecl *VD, Expr *E) {
370     if (Stack.size() > 1) {
371       Stack.back().MappedDecls[VD].push_back(E);
372     }
373   }
374 };
375 bool isParallelOrTaskRegion(OpenMPDirectiveKind DKind) {
376   return isOpenMPParallelDirective(DKind) || DKind == OMPD_task ||
377          isOpenMPTeamsDirective(DKind) || DKind == OMPD_unknown ||
378          isOpenMPTaskLoopDirective(DKind);
379 }
380 } // namespace
381 
382 static ValueDecl *getCanonicalDecl(ValueDecl *D) {
383   auto *VD = dyn_cast<VarDecl>(D);
384   auto *FD = dyn_cast<FieldDecl>(D);
385   if (VD  != nullptr) {
386     VD = VD->getCanonicalDecl();
387     D = VD;
388   } else {
389     assert(FD);
390     FD = FD->getCanonicalDecl();
391     D = FD;
392   }
393   return D;
394 }
395 
396 DSAStackTy::DSAVarData DSAStackTy::getDSA(StackTy::reverse_iterator Iter,
397                                           ValueDecl *D) {
398   D = getCanonicalDecl(D);
399   auto *VD = dyn_cast<VarDecl>(D);
400   auto *FD = dyn_cast<FieldDecl>(D);
401   DSAVarData DVar;
402   if (Iter == std::prev(Stack.rend())) {
403     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
404     // in a region but not in construct]
405     //  File-scope or namespace-scope variables referenced in called routines
406     //  in the region are shared unless they appear in a threadprivate
407     //  directive.
408     if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(D))
409       DVar.CKind = OMPC_shared;
410 
411     // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
412     // in a region but not in construct]
413     //  Variables with static storage duration that are declared in called
414     //  routines in the region are shared.
415     if (VD && VD->hasGlobalStorage())
416       DVar.CKind = OMPC_shared;
417 
418     // Non-static data members are shared by default.
419     if (FD)
420       DVar.CKind = OMPC_shared;
421 
422     return DVar;
423   }
424 
425   DVar.DKind = Iter->Directive;
426   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
427   // in a Construct, C/C++, predetermined, p.1]
428   // Variables with automatic storage duration that are declared in a scope
429   // inside the construct are private.
430   if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() &&
431       (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) {
432     DVar.CKind = OMPC_private;
433     return DVar;
434   }
435 
436   // Explicitly specified attributes and local variables with predetermined
437   // attributes.
438   if (Iter->SharingMap.count(D)) {
439     DVar.RefExpr = Iter->SharingMap[D].RefExpr;
440     DVar.PrivateCopy = Iter->SharingMap[D].PrivateCopy;
441     DVar.CKind = Iter->SharingMap[D].Attributes;
442     DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
443     return DVar;
444   }
445 
446   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
447   // in a Construct, C/C++, implicitly determined, p.1]
448   //  In a parallel or task construct, the data-sharing attributes of these
449   //  variables are determined by the default clause, if present.
450   switch (Iter->DefaultAttr) {
451   case DSA_shared:
452     DVar.CKind = OMPC_shared;
453     DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
454     return DVar;
455   case DSA_none:
456     return DVar;
457   case DSA_unspecified:
458     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
459     // in a Construct, implicitly determined, p.2]
460     //  In a parallel construct, if no default clause is present, these
461     //  variables are shared.
462     DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
463     if (isOpenMPParallelDirective(DVar.DKind) ||
464         isOpenMPTeamsDirective(DVar.DKind)) {
465       DVar.CKind = OMPC_shared;
466       return DVar;
467     }
468 
469     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
470     // in a Construct, implicitly determined, p.4]
471     //  In a task construct, if no default clause is present, a variable that in
472     //  the enclosing context is determined to be shared by all implicit tasks
473     //  bound to the current team is shared.
474     if (DVar.DKind == OMPD_task) {
475       DSAVarData DVarTemp;
476       for (StackTy::reverse_iterator I = std::next(Iter), EE = Stack.rend();
477            I != EE; ++I) {
478         // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
479         // Referenced
480         // in a Construct, implicitly determined, p.6]
481         //  In a task construct, if no default clause is present, a variable
482         //  whose data-sharing attribute is not determined by the rules above is
483         //  firstprivate.
484         DVarTemp = getDSA(I, D);
485         if (DVarTemp.CKind != OMPC_shared) {
486           DVar.RefExpr = nullptr;
487           DVar.DKind = OMPD_task;
488           DVar.CKind = OMPC_firstprivate;
489           return DVar;
490         }
491         if (isParallelOrTaskRegion(I->Directive))
492           break;
493       }
494       DVar.DKind = OMPD_task;
495       DVar.CKind =
496           (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
497       return DVar;
498     }
499   }
500   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
501   // in a Construct, implicitly determined, p.3]
502   //  For constructs other than task, if no default clause is present, these
503   //  variables inherit their data-sharing attributes from the enclosing
504   //  context.
505   return getDSA(std::next(Iter), D);
506 }
507 
508 Expr *DSAStackTy::addUniqueAligned(ValueDecl *D, Expr *NewDE) {
509   assert(Stack.size() > 1 && "Data sharing attributes stack is empty");
510   D = getCanonicalDecl(D);
511   auto It = Stack.back().AlignedMap.find(D);
512   if (It == Stack.back().AlignedMap.end()) {
513     assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
514     Stack.back().AlignedMap[D] = NewDE;
515     return nullptr;
516   } else {
517     assert(It->second && "Unexpected nullptr expr in the aligned map");
518     return It->second;
519   }
520   return nullptr;
521 }
522 
523 void DSAStackTy::addLoopControlVariable(ValueDecl *D) {
524   assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
525   D = getCanonicalDecl(D);
526   Stack.back().LCVMap.insert(std::make_pair(D, Stack.back().LCVMap.size() + 1));
527 }
528 
529 unsigned DSAStackTy::isLoopControlVariable(ValueDecl *D) {
530   assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
531   D = getCanonicalDecl(D);
532   return Stack.back().LCVMap.count(D) > 0 ? Stack.back().LCVMap[D] : 0;
533 }
534 
535 unsigned DSAStackTy::isParentLoopControlVariable(ValueDecl *D) {
536   assert(Stack.size() > 2 && "Data-sharing attributes stack is empty");
537   D = getCanonicalDecl(D);
538   return Stack[Stack.size() - 2].LCVMap.count(D) > 0
539              ? Stack[Stack.size() - 2].LCVMap[D]
540              : 0;
541 }
542 
543 ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) {
544   assert(Stack.size() > 2 && "Data-sharing attributes stack is empty");
545   if (Stack[Stack.size() - 2].LCVMap.size() < I)
546     return nullptr;
547   for (auto &Pair : Stack[Stack.size() - 2].LCVMap) {
548     if (Pair.second == I)
549       return Pair.first;
550   }
551   return nullptr;
552 }
553 
554 void DSAStackTy::addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A,
555                         DeclRefExpr *PrivateCopy) {
556   D = getCanonicalDecl(D);
557   if (A == OMPC_threadprivate) {
558     Stack[0].SharingMap[D].Attributes = A;
559     Stack[0].SharingMap[D].RefExpr = E;
560     Stack[0].SharingMap[D].PrivateCopy = nullptr;
561   } else {
562     assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
563     Stack.back().SharingMap[D].Attributes = A;
564     Stack.back().SharingMap[D].RefExpr = E;
565     Stack.back().SharingMap[D].PrivateCopy = PrivateCopy;
566     if (PrivateCopy)
567       addDSA(PrivateCopy->getDecl(), PrivateCopy, A);
568   }
569 }
570 
571 bool DSAStackTy::isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter) {
572   D = D->getCanonicalDecl();
573   if (Stack.size() > 2) {
574     reverse_iterator I = Iter, E = std::prev(Stack.rend());
575     Scope *TopScope = nullptr;
576     while (I != E && !isParallelOrTaskRegion(I->Directive)) {
577       ++I;
578     }
579     if (I == E)
580       return false;
581     TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
582     Scope *CurScope = getCurScope();
583     while (CurScope != TopScope && !CurScope->isDeclScope(D)) {
584       CurScope = CurScope->getParent();
585     }
586     return CurScope != TopScope;
587   }
588   return false;
589 }
590 
591 /// \brief Build a variable declaration for OpenMP loop iteration variable.
592 static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
593                              StringRef Name, const AttrVec *Attrs = nullptr) {
594   DeclContext *DC = SemaRef.CurContext;
595   IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
596   TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
597   VarDecl *Decl =
598       VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
599   if (Attrs) {
600     for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
601          I != E; ++I)
602       Decl->addAttr(*I);
603   }
604   Decl->setImplicit();
605   return Decl;
606 }
607 
608 static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
609                                      SourceLocation Loc,
610                                      bool RefersToCapture = false) {
611   D->setReferenced();
612   D->markUsed(S.Context);
613   return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
614                              SourceLocation(), D, RefersToCapture, Loc, Ty,
615                              VK_LValue);
616 }
617 
618 DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D, bool FromParent) {
619   D = getCanonicalDecl(D);
620   DSAVarData DVar;
621 
622   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
623   // in a Construct, C/C++, predetermined, p.1]
624   //  Variables appearing in threadprivate directives are threadprivate.
625   auto *VD = dyn_cast<VarDecl>(D);
626   if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
627        !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
628          SemaRef.getLangOpts().OpenMPUseTLS &&
629          SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
630       (VD && VD->getStorageClass() == SC_Register &&
631        VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
632     addDSA(D, buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
633                                D->getLocation()),
634            OMPC_threadprivate);
635   }
636   if (Stack[0].SharingMap.count(D)) {
637     DVar.RefExpr = Stack[0].SharingMap[D].RefExpr;
638     DVar.CKind = OMPC_threadprivate;
639     return DVar;
640   }
641 
642   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
643   // in a Construct, C/C++, predetermined, p.4]
644   //  Static data members are shared.
645   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
646   // in a Construct, C/C++, predetermined, p.7]
647   //  Variables with static storage duration that are declared in a scope
648   //  inside the construct are shared.
649   if (VD && VD->isStaticDataMember()) {
650     DSAVarData DVarTemp =
651         hasDSA(D, isOpenMPPrivate, MatchesAlways(), FromParent);
652     if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
653       return DVar;
654 
655     DVar.CKind = OMPC_shared;
656     return DVar;
657   }
658 
659   QualType Type = D->getType().getNonReferenceType().getCanonicalType();
660   bool IsConstant = Type.isConstant(SemaRef.getASTContext());
661   Type = SemaRef.getASTContext().getBaseElementType(Type);
662   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
663   // in a Construct, C/C++, predetermined, p.6]
664   //  Variables with const qualified type having no mutable member are
665   //  shared.
666   CXXRecordDecl *RD =
667       SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
668   if (auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
669     if (auto *CTD = CTSD->getSpecializedTemplate())
670       RD = CTD->getTemplatedDecl();
671   if (IsConstant &&
672       !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasDefinition() &&
673         RD->hasMutableFields())) {
674     // Variables with const-qualified type having no mutable member may be
675     // listed in a firstprivate clause, even if they are static data members.
676     DSAVarData DVarTemp = hasDSA(D, MatchesAnyClause(OMPC_firstprivate),
677                                  MatchesAlways(), FromParent);
678     if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr)
679       return DVar;
680 
681     DVar.CKind = OMPC_shared;
682     return DVar;
683   }
684 
685   // Explicitly specified attributes and local variables with predetermined
686   // attributes.
687   auto StartI = std::next(Stack.rbegin());
688   auto EndI = std::prev(Stack.rend());
689   if (FromParent && StartI != EndI) {
690     StartI = std::next(StartI);
691   }
692   auto I = std::prev(StartI);
693   if (I->SharingMap.count(D)) {
694     DVar.RefExpr = I->SharingMap[D].RefExpr;
695     DVar.PrivateCopy = I->SharingMap[D].PrivateCopy;
696     DVar.CKind = I->SharingMap[D].Attributes;
697     DVar.ImplicitDSALoc = I->DefaultAttrLoc;
698   }
699 
700   return DVar;
701 }
702 
703 DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
704                                                   bool FromParent) {
705   D = getCanonicalDecl(D);
706   auto StartI = Stack.rbegin();
707   auto EndI = std::prev(Stack.rend());
708   if (FromParent && StartI != EndI) {
709     StartI = std::next(StartI);
710   }
711   return getDSA(StartI, D);
712 }
713 
714 template <class ClausesPredicate, class DirectivesPredicate>
715 DSAStackTy::DSAVarData DSAStackTy::hasDSA(ValueDecl *D, ClausesPredicate CPred,
716                                           DirectivesPredicate DPred,
717                                           bool FromParent) {
718   D = getCanonicalDecl(D);
719   auto StartI = std::next(Stack.rbegin());
720   auto EndI = std::prev(Stack.rend());
721   if (FromParent && StartI != EndI) {
722     StartI = std::next(StartI);
723   }
724   for (auto I = StartI, EE = EndI; I != EE; ++I) {
725     if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive))
726       continue;
727     DSAVarData DVar = getDSA(I, D);
728     if (CPred(DVar.CKind))
729       return DVar;
730   }
731   return DSAVarData();
732 }
733 
734 template <class ClausesPredicate, class DirectivesPredicate>
735 DSAStackTy::DSAVarData
736 DSAStackTy::hasInnermostDSA(ValueDecl *D, ClausesPredicate CPred,
737                             DirectivesPredicate DPred, bool FromParent) {
738   D = getCanonicalDecl(D);
739   auto StartI = std::next(Stack.rbegin());
740   auto EndI = std::prev(Stack.rend());
741   if (FromParent && StartI != EndI) {
742     StartI = std::next(StartI);
743   }
744   for (auto I = StartI, EE = EndI; I != EE; ++I) {
745     if (!DPred(I->Directive))
746       break;
747     DSAVarData DVar = getDSA(I, D);
748     if (CPred(DVar.CKind))
749       return DVar;
750     return DSAVarData();
751   }
752   return DSAVarData();
753 }
754 
755 bool DSAStackTy::hasExplicitDSA(
756     ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
757     unsigned Level) {
758   if (CPred(ClauseKindMode))
759     return true;
760   if (isClauseParsingMode())
761     ++Level;
762   D = getCanonicalDecl(D);
763   auto StartI = Stack.rbegin();
764   auto EndI = std::prev(Stack.rend());
765   if (std::distance(StartI, EndI) <= (int)Level)
766     return false;
767   std::advance(StartI, Level);
768   return (StartI->SharingMap.count(D) > 0) && StartI->SharingMap[D].RefExpr &&
769          CPred(StartI->SharingMap[D].Attributes);
770 }
771 
772 bool DSAStackTy::hasExplicitDirective(
773     const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
774     unsigned Level) {
775   if (isClauseParsingMode())
776     ++Level;
777   auto StartI = Stack.rbegin();
778   auto EndI = std::prev(Stack.rend());
779   if (std::distance(StartI, EndI) <= (int)Level)
780     return false;
781   std::advance(StartI, Level);
782   return DPred(StartI->Directive);
783 }
784 
785 template <class NamedDirectivesPredicate>
786 bool DSAStackTy::hasDirective(NamedDirectivesPredicate DPred, bool FromParent) {
787   auto StartI = std::next(Stack.rbegin());
788   auto EndI = std::prev(Stack.rend());
789   if (FromParent && StartI != EndI) {
790     StartI = std::next(StartI);
791   }
792   for (auto I = StartI, EE = EndI; I != EE; ++I) {
793     if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
794       return true;
795   }
796   return false;
797 }
798 
799 OpenMPDirectiveKind DSAStackTy::getDirectiveForScope(const Scope *S) const {
800   for (auto I = Stack.rbegin(), EE = Stack.rend(); I != EE; ++I)
801     if (I->CurScope == S)
802       return I->Directive;
803   return OMPD_unknown;
804 }
805 
806 void Sema::InitDataSharingAttributesStack() {
807   VarDataSharingAttributesStack = new DSAStackTy(*this);
808 }
809 
810 #define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
811 
812 bool Sema::IsOpenMPCapturedByRef(ValueDecl *D,
813                                  const CapturedRegionScopeInfo *RSI) {
814   assert(LangOpts.OpenMP && "OpenMP is not allowed");
815 
816   auto &Ctx = getASTContext();
817   bool IsByRef = true;
818 
819   // Find the directive that is associated with the provided scope.
820   auto DKind = DSAStack->getDirectiveForScope(RSI->TheScope);
821   auto Ty = D->getType();
822 
823   if (isOpenMPTargetExecutionDirective(DKind)) {
824     // This table summarizes how a given variable should be passed to the device
825     // given its type and the clauses where it appears. This table is based on
826     // the description in OpenMP 4.5 [2.10.4, target Construct] and
827     // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
828     //
829     // =========================================================================
830     // | type |  defaultmap   | pvt | first | is_device_ptr |    map   | res.  |
831     // |      |(tofrom:scalar)|     |  pvt  |               |          |       |
832     // =========================================================================
833     // | scl  |               |     |       |       -       |          | bycopy|
834     // | scl  |               |  -  |   x   |       -       |     -    | bycopy|
835     // | scl  |               |  x  |   -   |       -       |     -    | null  |
836     // | scl  |       x       |     |       |       -       |          | byref |
837     // | scl  |       x       |  -  |   x   |       -       |     -    | bycopy|
838     // | scl  |       x       |  x  |   -   |       -       |     -    | null  |
839     // | scl  |               |  -  |   -   |       -       |     x    | byref |
840     // | scl  |       x       |  -  |   -   |       -       |     x    | byref |
841     //
842     // | agg  |      n.a.     |     |       |       -       |          | byref |
843     // | agg  |      n.a.     |  -  |   x   |       -       |     -    | byref |
844     // | agg  |      n.a.     |  x  |   -   |       -       |     -    | null  |
845     // | agg  |      n.a.     |  -  |   -   |       -       |     x    | byref |
846     // | agg  |      n.a.     |  -  |   -   |       -       |    x[]   | byref |
847     //
848     // | ptr  |      n.a.     |     |       |       -       |          | bycopy|
849     // | ptr  |      n.a.     |  -  |   x   |       -       |     -    | bycopy|
850     // | ptr  |      n.a.     |  x  |   -   |       -       |     -    | null  |
851     // | ptr  |      n.a.     |  -  |   -   |       -       |     x    | byref |
852     // | ptr  |      n.a.     |  -  |   -   |       -       |    x[]   | bycopy|
853     // | ptr  |      n.a.     |  -  |   -   |       x       |          | bycopy|
854     // | ptr  |      n.a.     |  -  |   -   |       x       |     x    | bycopy|
855     // | ptr  |      n.a.     |  -  |   -   |       x       |    x[]   | bycopy|
856     // =========================================================================
857     // Legend:
858     //  scl - scalar
859     //  ptr - pointer
860     //  agg - aggregate
861     //  x - applies
862     //  - - invalid in this combination
863     //  [] - mapped with an array section
864     //  byref - should be mapped by reference
865     //  byval - should be mapped by value
866     //  null - initialize a local variable to null on the device
867     //
868     // Observations:
869     //  - All scalar declarations that show up in a map clause have to be passed
870     //    by reference, because they may have been mapped in the enclosing data
871     //    environment.
872     //  - If the scalar value does not fit the size of uintptr, it has to be
873     //    passed by reference, regardless the result in the table above.
874     //  - For pointers mapped by value that have either an implicit map or an
875     //    array section, the runtime library may pass the NULL value to the
876     //    device instead of the value passed to it by the compiler.
877 
878     // FIXME: Right now, only implicit maps are implemented. Properly mapping
879     // values requires having the map, private, and firstprivate clauses SEMA
880     // and parsing in place, which we don't yet.
881 
882     if (Ty->isReferenceType())
883       Ty = Ty->castAs<ReferenceType>()->getPointeeType();
884     IsByRef = !Ty->isScalarType();
885   }
886 
887   // When passing data by value, we need to make sure it fits the uintptr size
888   // and alignment, because the runtime library only deals with uintptr types.
889   // If it does not fit the uintptr size, we need to pass the data by reference
890   // instead.
891   if (!IsByRef &&
892       (Ctx.getTypeSizeInChars(Ty) >
893            Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
894        Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType())))
895     IsByRef = true;
896 
897   return IsByRef;
898 }
899 
900 VarDecl *Sema::IsOpenMPCapturedDecl(ValueDecl *D) {
901   assert(LangOpts.OpenMP && "OpenMP is not allowed");
902   D = getCanonicalDecl(D);
903 
904   // If we are attempting to capture a global variable in a directive with
905   // 'target' we return true so that this global is also mapped to the device.
906   //
907   // FIXME: If the declaration is enclosed in a 'declare target' directive,
908   // then it should not be captured. Therefore, an extra check has to be
909   // inserted here once support for 'declare target' is added.
910   //
911   auto *VD = dyn_cast<VarDecl>(D);
912   if (VD && !VD->hasLocalStorage()) {
913     if (DSAStack->getCurrentDirective() == OMPD_target &&
914         !DSAStack->isClauseParsingMode())
915       return VD;
916     if (DSAStack->getCurScope() &&
917         DSAStack->hasDirective(
918             [](OpenMPDirectiveKind K, const DeclarationNameInfo &DNI,
919                SourceLocation Loc) -> bool {
920               return isOpenMPTargetExecutionDirective(K);
921             },
922             false))
923       return VD;
924   }
925 
926   if (DSAStack->getCurrentDirective() != OMPD_unknown &&
927       (!DSAStack->isClauseParsingMode() ||
928        DSAStack->getParentDirective() != OMPD_unknown)) {
929     if (DSAStack->isLoopControlVariable(D) ||
930         (VD && VD->hasLocalStorage() &&
931          isParallelOrTaskRegion(DSAStack->getCurrentDirective())) ||
932         (VD && DSAStack->isForceVarCapturing()))
933       return VD;
934     auto DVarPrivate = DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
935     if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
936       return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
937     DVarPrivate = DSAStack->hasDSA(D, isOpenMPPrivate, MatchesAlways(),
938                                    DSAStack->isClauseParsingMode());
939     if (DVarPrivate.CKind != OMPC_unknown)
940       return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
941   }
942   return nullptr;
943 }
944 
945 bool Sema::isOpenMPPrivateDecl(ValueDecl *D, unsigned Level) {
946   assert(LangOpts.OpenMP && "OpenMP is not allowed");
947   return DSAStack->hasExplicitDSA(
948       D, [](OpenMPClauseKind K) -> bool { return K == OMPC_private; }, Level);
949 }
950 
951 bool Sema::isOpenMPTargetCapturedDecl(ValueDecl *D, unsigned Level) {
952   assert(LangOpts.OpenMP && "OpenMP is not allowed");
953   // Return true if the current level is no longer enclosed in a target region.
954 
955   auto *VD = dyn_cast<VarDecl>(D);
956   return VD && !VD->hasLocalStorage() &&
957          DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
958                                         Level);
959 }
960 
961 void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
962 
963 void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
964                                const DeclarationNameInfo &DirName,
965                                Scope *CurScope, SourceLocation Loc) {
966   DSAStack->push(DKind, DirName, CurScope, Loc);
967   PushExpressionEvaluationContext(PotentiallyEvaluated);
968 }
969 
970 void Sema::StartOpenMPClause(OpenMPClauseKind K) {
971   DSAStack->setClauseParsingMode(K);
972 }
973 
974 void Sema::EndOpenMPClause() {
975   DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
976 }
977 
978 void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
979   // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
980   //  A variable of class type (or array thereof) that appears in a lastprivate
981   //  clause requires an accessible, unambiguous default constructor for the
982   //  class type, unless the list item is also specified in a firstprivate
983   //  clause.
984   if (auto D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
985     for (auto *C : D->clauses()) {
986       if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
987         SmallVector<Expr *, 8> PrivateCopies;
988         for (auto *DE : Clause->varlists()) {
989           if (DE->isValueDependent() || DE->isTypeDependent()) {
990             PrivateCopies.push_back(nullptr);
991             continue;
992           }
993           auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
994           VarDecl *VD = cast<VarDecl>(DRE->getDecl());
995           QualType Type = VD->getType().getNonReferenceType();
996           auto DVar = DSAStack->getTopDSA(VD, false);
997           if (DVar.CKind == OMPC_lastprivate) {
998             // Generate helper private variable and initialize it with the
999             // default value. The address of the original variable is replaced
1000             // by the address of the new private variable in CodeGen. This new
1001             // variable is not added to IdResolver, so the code in the OpenMP
1002             // region uses original variable for proper diagnostics.
1003             auto *VDPrivate = buildVarDecl(
1004                 *this, DE->getExprLoc(), Type.getUnqualifiedType(),
1005                 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr);
1006             ActOnUninitializedDecl(VDPrivate, /*TypeMayContainAuto=*/false);
1007             if (VDPrivate->isInvalidDecl())
1008               continue;
1009             PrivateCopies.push_back(buildDeclRefExpr(
1010                 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
1011           } else {
1012             // The variable is also a firstprivate, so initialization sequence
1013             // for private copy is generated already.
1014             PrivateCopies.push_back(nullptr);
1015           }
1016         }
1017         // Set initializers to private copies if no errors were found.
1018         if (PrivateCopies.size() == Clause->varlist_size())
1019           Clause->setPrivateCopies(PrivateCopies);
1020       }
1021     }
1022   }
1023 
1024   DSAStack->pop();
1025   DiscardCleanupsInEvaluationContext();
1026   PopExpressionEvaluationContext();
1027 }
1028 
1029 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
1030                                      Expr *NumIterations, Sema &SemaRef,
1031                                      Scope *S);
1032 
1033 namespace {
1034 
1035 class VarDeclFilterCCC : public CorrectionCandidateCallback {
1036 private:
1037   Sema &SemaRef;
1038 
1039 public:
1040   explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
1041   bool ValidateCandidate(const TypoCorrection &Candidate) override {
1042     NamedDecl *ND = Candidate.getCorrectionDecl();
1043     if (VarDecl *VD = dyn_cast_or_null<VarDecl>(ND)) {
1044       return VD->hasGlobalStorage() &&
1045              SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1046                                    SemaRef.getCurScope());
1047     }
1048     return false;
1049   }
1050 };
1051 } // namespace
1052 
1053 ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
1054                                          CXXScopeSpec &ScopeSpec,
1055                                          const DeclarationNameInfo &Id) {
1056   LookupResult Lookup(*this, Id, LookupOrdinaryName);
1057   LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
1058 
1059   if (Lookup.isAmbiguous())
1060     return ExprError();
1061 
1062   VarDecl *VD;
1063   if (!Lookup.isSingleResult()) {
1064     if (TypoCorrection Corrected = CorrectTypo(
1065             Id, LookupOrdinaryName, CurScope, nullptr,
1066             llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) {
1067       diagnoseTypo(Corrected,
1068                    PDiag(Lookup.empty()
1069                              ? diag::err_undeclared_var_use_suggest
1070                              : diag::err_omp_expected_var_arg_suggest)
1071                        << Id.getName());
1072       VD = Corrected.getCorrectionDeclAs<VarDecl>();
1073     } else {
1074       Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
1075                                        : diag::err_omp_expected_var_arg)
1076           << Id.getName();
1077       return ExprError();
1078     }
1079   } else {
1080     if (!(VD = Lookup.getAsSingle<VarDecl>())) {
1081       Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
1082       Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
1083       return ExprError();
1084     }
1085   }
1086   Lookup.suppressDiagnostics();
1087 
1088   // OpenMP [2.9.2, Syntax, C/C++]
1089   //   Variables must be file-scope, namespace-scope, or static block-scope.
1090   if (!VD->hasGlobalStorage()) {
1091     Diag(Id.getLoc(), diag::err_omp_global_var_arg)
1092         << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal();
1093     bool IsDecl =
1094         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1095     Diag(VD->getLocation(),
1096          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1097         << VD;
1098     return ExprError();
1099   }
1100 
1101   VarDecl *CanonicalVD = VD->getCanonicalDecl();
1102   NamedDecl *ND = cast<NamedDecl>(CanonicalVD);
1103   // OpenMP [2.9.2, Restrictions, C/C++, p.2]
1104   //   A threadprivate directive for file-scope variables must appear outside
1105   //   any definition or declaration.
1106   if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
1107       !getCurLexicalContext()->isTranslationUnit()) {
1108     Diag(Id.getLoc(), diag::err_omp_var_scope)
1109         << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1110     bool IsDecl =
1111         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1112     Diag(VD->getLocation(),
1113          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1114         << VD;
1115     return ExprError();
1116   }
1117   // OpenMP [2.9.2, Restrictions, C/C++, p.3]
1118   //   A threadprivate directive for static class member variables must appear
1119   //   in the class definition, in the same scope in which the member
1120   //   variables are declared.
1121   if (CanonicalVD->isStaticDataMember() &&
1122       !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
1123     Diag(Id.getLoc(), diag::err_omp_var_scope)
1124         << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1125     bool IsDecl =
1126         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1127     Diag(VD->getLocation(),
1128          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1129         << VD;
1130     return ExprError();
1131   }
1132   // OpenMP [2.9.2, Restrictions, C/C++, p.4]
1133   //   A threadprivate directive for namespace-scope variables must appear
1134   //   outside any definition or declaration other than the namespace
1135   //   definition itself.
1136   if (CanonicalVD->getDeclContext()->isNamespace() &&
1137       (!getCurLexicalContext()->isFileContext() ||
1138        !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
1139     Diag(Id.getLoc(), diag::err_omp_var_scope)
1140         << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1141     bool IsDecl =
1142         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1143     Diag(VD->getLocation(),
1144          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1145         << VD;
1146     return ExprError();
1147   }
1148   // OpenMP [2.9.2, Restrictions, C/C++, p.6]
1149   //   A threadprivate directive for static block-scope variables must appear
1150   //   in the scope of the variable and not in a nested scope.
1151   if (CanonicalVD->isStaticLocal() && CurScope &&
1152       !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
1153     Diag(Id.getLoc(), diag::err_omp_var_scope)
1154         << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1155     bool IsDecl =
1156         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1157     Diag(VD->getLocation(),
1158          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1159         << VD;
1160     return ExprError();
1161   }
1162 
1163   // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
1164   //   A threadprivate directive must lexically precede all references to any
1165   //   of the variables in its list.
1166   if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) {
1167     Diag(Id.getLoc(), diag::err_omp_var_used)
1168         << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1169     return ExprError();
1170   }
1171 
1172   QualType ExprType = VD->getType().getNonReferenceType();
1173   return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
1174                              SourceLocation(), VD,
1175                              /*RefersToEnclosingVariableOrCapture=*/false,
1176                              Id.getLoc(), ExprType, VK_LValue);
1177 }
1178 
1179 Sema::DeclGroupPtrTy
1180 Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
1181                                         ArrayRef<Expr *> VarList) {
1182   if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
1183     CurContext->addDecl(D);
1184     return DeclGroupPtrTy::make(DeclGroupRef(D));
1185   }
1186   return nullptr;
1187 }
1188 
1189 namespace {
1190 class LocalVarRefChecker : public ConstStmtVisitor<LocalVarRefChecker, bool> {
1191   Sema &SemaRef;
1192 
1193 public:
1194   bool VisitDeclRefExpr(const DeclRefExpr *E) {
1195     if (auto VD = dyn_cast<VarDecl>(E->getDecl())) {
1196       if (VD->hasLocalStorage()) {
1197         SemaRef.Diag(E->getLocStart(),
1198                      diag::err_omp_local_var_in_threadprivate_init)
1199             << E->getSourceRange();
1200         SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
1201             << VD << VD->getSourceRange();
1202         return true;
1203       }
1204     }
1205     return false;
1206   }
1207   bool VisitStmt(const Stmt *S) {
1208     for (auto Child : S->children()) {
1209       if (Child && Visit(Child))
1210         return true;
1211     }
1212     return false;
1213   }
1214   explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
1215 };
1216 } // namespace
1217 
1218 OMPThreadPrivateDecl *
1219 Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
1220   SmallVector<Expr *, 8> Vars;
1221   for (auto &RefExpr : VarList) {
1222     DeclRefExpr *DE = cast<DeclRefExpr>(RefExpr);
1223     VarDecl *VD = cast<VarDecl>(DE->getDecl());
1224     SourceLocation ILoc = DE->getExprLoc();
1225 
1226     // Mark variable as used.
1227     VD->setReferenced();
1228     VD->markUsed(Context);
1229 
1230     QualType QType = VD->getType();
1231     if (QType->isDependentType() || QType->isInstantiationDependentType()) {
1232       // It will be analyzed later.
1233       Vars.push_back(DE);
1234       continue;
1235     }
1236 
1237     // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1238     //   A threadprivate variable must not have an incomplete type.
1239     if (RequireCompleteType(ILoc, VD->getType(),
1240                             diag::err_omp_threadprivate_incomplete_type)) {
1241       continue;
1242     }
1243 
1244     // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1245     //   A threadprivate variable must not have a reference type.
1246     if (VD->getType()->isReferenceType()) {
1247       Diag(ILoc, diag::err_omp_ref_type_arg)
1248           << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
1249       bool IsDecl =
1250           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1251       Diag(VD->getLocation(),
1252            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1253           << VD;
1254       continue;
1255     }
1256 
1257     // Check if this is a TLS variable. If TLS is not being supported, produce
1258     // the corresponding diagnostic.
1259     if ((VD->getTLSKind() != VarDecl::TLS_None &&
1260          !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
1261            getLangOpts().OpenMPUseTLS &&
1262            getASTContext().getTargetInfo().isTLSSupported())) ||
1263         (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
1264          !VD->isLocalVarDecl())) {
1265       Diag(ILoc, diag::err_omp_var_thread_local)
1266           << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
1267       bool IsDecl =
1268           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1269       Diag(VD->getLocation(),
1270            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1271           << VD;
1272       continue;
1273     }
1274 
1275     // Check if initial value of threadprivate variable reference variable with
1276     // local storage (it is not supported by runtime).
1277     if (auto Init = VD->getAnyInitializer()) {
1278       LocalVarRefChecker Checker(*this);
1279       if (Checker.Visit(Init))
1280         continue;
1281     }
1282 
1283     Vars.push_back(RefExpr);
1284     DSAStack->addDSA(VD, DE, OMPC_threadprivate);
1285     VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
1286         Context, SourceRange(Loc, Loc)));
1287     if (auto *ML = Context.getASTMutationListener())
1288       ML->DeclarationMarkedOpenMPThreadPrivate(VD);
1289   }
1290   OMPThreadPrivateDecl *D = nullptr;
1291   if (!Vars.empty()) {
1292     D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
1293                                      Vars);
1294     D->setAccess(AS_public);
1295   }
1296   return D;
1297 }
1298 
1299 static void ReportOriginalDSA(Sema &SemaRef, DSAStackTy *Stack,
1300                               const ValueDecl *D, DSAStackTy::DSAVarData DVar,
1301                               bool IsLoopIterVar = false) {
1302   if (DVar.RefExpr) {
1303     SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
1304         << getOpenMPClauseName(DVar.CKind);
1305     return;
1306   }
1307   enum {
1308     PDSA_StaticMemberShared,
1309     PDSA_StaticLocalVarShared,
1310     PDSA_LoopIterVarPrivate,
1311     PDSA_LoopIterVarLinear,
1312     PDSA_LoopIterVarLastprivate,
1313     PDSA_ConstVarShared,
1314     PDSA_GlobalVarShared,
1315     PDSA_TaskVarFirstprivate,
1316     PDSA_LocalVarPrivate,
1317     PDSA_Implicit
1318   } Reason = PDSA_Implicit;
1319   bool ReportHint = false;
1320   auto ReportLoc = D->getLocation();
1321   auto *VD = dyn_cast<VarDecl>(D);
1322   if (IsLoopIterVar) {
1323     if (DVar.CKind == OMPC_private)
1324       Reason = PDSA_LoopIterVarPrivate;
1325     else if (DVar.CKind == OMPC_lastprivate)
1326       Reason = PDSA_LoopIterVarLastprivate;
1327     else
1328       Reason = PDSA_LoopIterVarLinear;
1329   } else if (DVar.DKind == OMPD_task && DVar.CKind == OMPC_firstprivate) {
1330     Reason = PDSA_TaskVarFirstprivate;
1331     ReportLoc = DVar.ImplicitDSALoc;
1332   } else if (VD && VD->isStaticLocal())
1333     Reason = PDSA_StaticLocalVarShared;
1334   else if (VD && VD->isStaticDataMember())
1335     Reason = PDSA_StaticMemberShared;
1336   else if (VD && VD->isFileVarDecl())
1337     Reason = PDSA_GlobalVarShared;
1338   else if (D->getType().isConstant(SemaRef.getASTContext()))
1339     Reason = PDSA_ConstVarShared;
1340   else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
1341     ReportHint = true;
1342     Reason = PDSA_LocalVarPrivate;
1343   }
1344   if (Reason != PDSA_Implicit) {
1345     SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
1346         << Reason << ReportHint
1347         << getOpenMPDirectiveName(Stack->getCurrentDirective());
1348   } else if (DVar.ImplicitDSALoc.isValid()) {
1349     SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
1350         << getOpenMPClauseName(DVar.CKind);
1351   }
1352 }
1353 
1354 namespace {
1355 class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> {
1356   DSAStackTy *Stack;
1357   Sema &SemaRef;
1358   bool ErrorFound;
1359   CapturedStmt *CS;
1360   llvm::SmallVector<Expr *, 8> ImplicitFirstprivate;
1361   llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
1362 
1363 public:
1364   void VisitDeclRefExpr(DeclRefExpr *E) {
1365     if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
1366       // Skip internally declared variables.
1367       if (VD->isLocalVarDecl() && !CS->capturesVariable(VD))
1368         return;
1369 
1370       auto DVar = Stack->getTopDSA(VD, false);
1371       // Check if the variable has explicit DSA set and stop analysis if it so.
1372       if (DVar.RefExpr) return;
1373 
1374       auto ELoc = E->getExprLoc();
1375       auto DKind = Stack->getCurrentDirective();
1376       // The default(none) clause requires that each variable that is referenced
1377       // in the construct, and does not have a predetermined data-sharing
1378       // attribute, must have its data-sharing attribute explicitly determined
1379       // by being listed in a data-sharing attribute clause.
1380       if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
1381           isParallelOrTaskRegion(DKind) &&
1382           VarsWithInheritedDSA.count(VD) == 0) {
1383         VarsWithInheritedDSA[VD] = E;
1384         return;
1385       }
1386 
1387       // OpenMP [2.9.3.6, Restrictions, p.2]
1388       //  A list item that appears in a reduction clause of the innermost
1389       //  enclosing worksharing or parallel construct may not be accessed in an
1390       //  explicit task.
1391       DVar = Stack->hasInnermostDSA(VD, MatchesAnyClause(OMPC_reduction),
1392                                     [](OpenMPDirectiveKind K) -> bool {
1393                                       return isOpenMPParallelDirective(K) ||
1394                                              isOpenMPWorksharingDirective(K) ||
1395                                              isOpenMPTeamsDirective(K);
1396                                     },
1397                                     false);
1398       if (DKind == OMPD_task && DVar.CKind == OMPC_reduction) {
1399         ErrorFound = true;
1400         SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
1401         ReportOriginalDSA(SemaRef, Stack, VD, DVar);
1402         return;
1403       }
1404 
1405       // Define implicit data-sharing attributes for task.
1406       DVar = Stack->getImplicitDSA(VD, false);
1407       if (DKind == OMPD_task && DVar.CKind != OMPC_shared)
1408         ImplicitFirstprivate.push_back(E);
1409     }
1410   }
1411   void VisitMemberExpr(MemberExpr *E) {
1412     if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
1413       if (auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
1414         auto DVar = Stack->getTopDSA(FD, false);
1415         // Check if the variable has explicit DSA set and stop analysis if it
1416         // so.
1417         if (DVar.RefExpr)
1418           return;
1419 
1420         auto ELoc = E->getExprLoc();
1421         auto DKind = Stack->getCurrentDirective();
1422         // OpenMP [2.9.3.6, Restrictions, p.2]
1423         //  A list item that appears in a reduction clause of the innermost
1424         //  enclosing worksharing or parallel construct may not be accessed in
1425         //  an  explicit task.
1426         DVar =
1427             Stack->hasInnermostDSA(FD, MatchesAnyClause(OMPC_reduction),
1428                                    [](OpenMPDirectiveKind K) -> bool {
1429                                      return isOpenMPParallelDirective(K) ||
1430                                             isOpenMPWorksharingDirective(K) ||
1431                                             isOpenMPTeamsDirective(K);
1432                                    },
1433                                    false);
1434         if (DKind == OMPD_task && DVar.CKind == OMPC_reduction) {
1435           ErrorFound = true;
1436           SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
1437           ReportOriginalDSA(SemaRef, Stack, FD, DVar);
1438           return;
1439         }
1440 
1441         // Define implicit data-sharing attributes for task.
1442         DVar = Stack->getImplicitDSA(FD, false);
1443         if (DKind == OMPD_task && DVar.CKind != OMPC_shared)
1444           ImplicitFirstprivate.push_back(E);
1445       }
1446     }
1447   }
1448   void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
1449     for (auto *C : S->clauses()) {
1450       // Skip analysis of arguments of implicitly defined firstprivate clause
1451       // for task directives.
1452       if (C && (!isa<OMPFirstprivateClause>(C) || C->getLocStart().isValid()))
1453         for (auto *CC : C->children()) {
1454           if (CC)
1455             Visit(CC);
1456         }
1457     }
1458   }
1459   void VisitStmt(Stmt *S) {
1460     for (auto *C : S->children()) {
1461       if (C && !isa<OMPExecutableDirective>(C))
1462         Visit(C);
1463     }
1464   }
1465 
1466   bool isErrorFound() { return ErrorFound; }
1467   ArrayRef<Expr *> getImplicitFirstprivate() { return ImplicitFirstprivate; }
1468   llvm::DenseMap<ValueDecl *, Expr *> &getVarsWithInheritedDSA() {
1469     return VarsWithInheritedDSA;
1470   }
1471 
1472   DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
1473       : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {}
1474 };
1475 } // namespace
1476 
1477 void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
1478   switch (DKind) {
1479   case OMPD_parallel: {
1480     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1481     QualType KmpInt32PtrTy =
1482         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
1483     Sema::CapturedParamNameType Params[] = {
1484         std::make_pair(".global_tid.", KmpInt32PtrTy),
1485         std::make_pair(".bound_tid.", KmpInt32PtrTy),
1486         std::make_pair(StringRef(), QualType()) // __context with shared vars
1487     };
1488     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1489                              Params);
1490     break;
1491   }
1492   case OMPD_simd: {
1493     Sema::CapturedParamNameType Params[] = {
1494         std::make_pair(StringRef(), QualType()) // __context with shared vars
1495     };
1496     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1497                              Params);
1498     break;
1499   }
1500   case OMPD_for: {
1501     Sema::CapturedParamNameType Params[] = {
1502         std::make_pair(StringRef(), QualType()) // __context with shared vars
1503     };
1504     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1505                              Params);
1506     break;
1507   }
1508   case OMPD_for_simd: {
1509     Sema::CapturedParamNameType Params[] = {
1510         std::make_pair(StringRef(), QualType()) // __context with shared vars
1511     };
1512     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1513                              Params);
1514     break;
1515   }
1516   case OMPD_sections: {
1517     Sema::CapturedParamNameType Params[] = {
1518         std::make_pair(StringRef(), QualType()) // __context with shared vars
1519     };
1520     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1521                              Params);
1522     break;
1523   }
1524   case OMPD_section: {
1525     Sema::CapturedParamNameType Params[] = {
1526         std::make_pair(StringRef(), QualType()) // __context with shared vars
1527     };
1528     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1529                              Params);
1530     break;
1531   }
1532   case OMPD_single: {
1533     Sema::CapturedParamNameType Params[] = {
1534         std::make_pair(StringRef(), QualType()) // __context with shared vars
1535     };
1536     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1537                              Params);
1538     break;
1539   }
1540   case OMPD_master: {
1541     Sema::CapturedParamNameType Params[] = {
1542         std::make_pair(StringRef(), QualType()) // __context with shared vars
1543     };
1544     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1545                              Params);
1546     break;
1547   }
1548   case OMPD_critical: {
1549     Sema::CapturedParamNameType Params[] = {
1550         std::make_pair(StringRef(), QualType()) // __context with shared vars
1551     };
1552     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1553                              Params);
1554     break;
1555   }
1556   case OMPD_parallel_for: {
1557     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1558     QualType KmpInt32PtrTy =
1559         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
1560     Sema::CapturedParamNameType Params[] = {
1561         std::make_pair(".global_tid.", KmpInt32PtrTy),
1562         std::make_pair(".bound_tid.", KmpInt32PtrTy),
1563         std::make_pair(StringRef(), QualType()) // __context with shared vars
1564     };
1565     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1566                              Params);
1567     break;
1568   }
1569   case OMPD_parallel_for_simd: {
1570     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1571     QualType KmpInt32PtrTy =
1572         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
1573     Sema::CapturedParamNameType Params[] = {
1574         std::make_pair(".global_tid.", KmpInt32PtrTy),
1575         std::make_pair(".bound_tid.", KmpInt32PtrTy),
1576         std::make_pair(StringRef(), QualType()) // __context with shared vars
1577     };
1578     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1579                              Params);
1580     break;
1581   }
1582   case OMPD_parallel_sections: {
1583     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1584     QualType KmpInt32PtrTy =
1585         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
1586     Sema::CapturedParamNameType Params[] = {
1587         std::make_pair(".global_tid.", KmpInt32PtrTy),
1588         std::make_pair(".bound_tid.", KmpInt32PtrTy),
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_task: {
1596     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1597     QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
1598     FunctionProtoType::ExtProtoInfo EPI;
1599     EPI.Variadic = true;
1600     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
1601     Sema::CapturedParamNameType Params[] = {
1602         std::make_pair(".global_tid.", KmpInt32Ty),
1603         std::make_pair(".part_id.", KmpInt32Ty),
1604         std::make_pair(".privates.",
1605                        Context.VoidPtrTy.withConst().withRestrict()),
1606         std::make_pair(
1607             ".copy_fn.",
1608             Context.getPointerType(CopyFnType).withConst().withRestrict()),
1609         std::make_pair(StringRef(), QualType()) // __context with shared vars
1610     };
1611     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1612                              Params);
1613     // Mark this captured region as inlined, because we don't use outlined
1614     // function directly.
1615     getCurCapturedRegion()->TheCapturedDecl->addAttr(
1616         AlwaysInlineAttr::CreateImplicit(
1617             Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
1618     break;
1619   }
1620   case OMPD_ordered: {
1621     Sema::CapturedParamNameType Params[] = {
1622         std::make_pair(StringRef(), QualType()) // __context with shared vars
1623     };
1624     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1625                              Params);
1626     break;
1627   }
1628   case OMPD_atomic: {
1629     Sema::CapturedParamNameType Params[] = {
1630         std::make_pair(StringRef(), QualType()) // __context with shared vars
1631     };
1632     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1633                              Params);
1634     break;
1635   }
1636   case OMPD_target_data:
1637   case OMPD_target:
1638   case OMPD_target_parallel:
1639   case OMPD_target_parallel_for: {
1640     Sema::CapturedParamNameType Params[] = {
1641         std::make_pair(StringRef(), QualType()) // __context with shared vars
1642     };
1643     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1644                              Params);
1645     break;
1646   }
1647   case OMPD_teams: {
1648     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1649     QualType KmpInt32PtrTy =
1650         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
1651     Sema::CapturedParamNameType Params[] = {
1652         std::make_pair(".global_tid.", KmpInt32PtrTy),
1653         std::make_pair(".bound_tid.", KmpInt32PtrTy),
1654         std::make_pair(StringRef(), QualType()) // __context with shared vars
1655     };
1656     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1657                              Params);
1658     break;
1659   }
1660   case OMPD_taskgroup: {
1661     Sema::CapturedParamNameType Params[] = {
1662         std::make_pair(StringRef(), QualType()) // __context with shared vars
1663     };
1664     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1665                              Params);
1666     break;
1667   }
1668   case OMPD_taskloop: {
1669     Sema::CapturedParamNameType Params[] = {
1670         std::make_pair(StringRef(), QualType()) // __context with shared vars
1671     };
1672     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1673                              Params);
1674     break;
1675   }
1676   case OMPD_taskloop_simd: {
1677     Sema::CapturedParamNameType Params[] = {
1678         std::make_pair(StringRef(), QualType()) // __context with shared vars
1679     };
1680     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1681                              Params);
1682     break;
1683   }
1684   case OMPD_distribute: {
1685     Sema::CapturedParamNameType Params[] = {
1686         std::make_pair(StringRef(), QualType()) // __context with shared vars
1687     };
1688     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1689                              Params);
1690     break;
1691   }
1692   case OMPD_threadprivate:
1693   case OMPD_taskyield:
1694   case OMPD_barrier:
1695   case OMPD_taskwait:
1696   case OMPD_cancellation_point:
1697   case OMPD_cancel:
1698   case OMPD_flush:
1699   case OMPD_target_enter_data:
1700   case OMPD_target_exit_data:
1701     llvm_unreachable("OpenMP Directive is not allowed");
1702   case OMPD_unknown:
1703     llvm_unreachable("Unknown OpenMP directive");
1704   }
1705 }
1706 
1707 static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
1708                                              Expr *CaptureExpr) {
1709   ASTContext &C = S.getASTContext();
1710   Expr *Init = CaptureExpr->IgnoreImpCasts();
1711   QualType Ty = Init->getType();
1712   if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
1713     if (S.getLangOpts().CPlusPlus)
1714       Ty = C.getLValueReferenceType(Ty);
1715     else {
1716       Ty = C.getPointerType(Ty);
1717       ExprResult Res =
1718           S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
1719       if (!Res.isUsable())
1720         return nullptr;
1721       Init = Res.get();
1722     }
1723   }
1724   auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty);
1725   S.CurContext->addHiddenDecl(CED);
1726   S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false,
1727                          /*TypeMayContainAuto=*/true);
1728   return CED;
1729 }
1730 
1731 static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr) {
1732   OMPCapturedExprDecl *CD;
1733   if (auto *VD = S.IsOpenMPCapturedDecl(D))
1734     CD = cast<OMPCapturedExprDecl>(VD);
1735   else
1736     CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr);
1737   return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
1738                           SourceLocation());
1739 }
1740 
1741 static DeclRefExpr *buildCapture(Sema &S, Expr *CaptureExpr) {
1742   auto *CD = buildCaptureDecl(
1743       S, &S.getASTContext().Idents.get(".capture_expr."), CaptureExpr);
1744   return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
1745                           SourceLocation());
1746 }
1747 
1748 StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
1749                                       ArrayRef<OMPClause *> Clauses) {
1750   if (!S.isUsable()) {
1751     ActOnCapturedRegionError();
1752     return StmtError();
1753   }
1754 
1755   OMPOrderedClause *OC = nullptr;
1756   OMPScheduleClause *SC = nullptr;
1757   SmallVector<OMPLinearClause *, 4> LCs;
1758   // This is required for proper codegen.
1759   for (auto *Clause : Clauses) {
1760     if (isOpenMPPrivate(Clause->getClauseKind()) ||
1761         Clause->getClauseKind() == OMPC_copyprivate ||
1762         (getLangOpts().OpenMPUseTLS &&
1763          getASTContext().getTargetInfo().isTLSSupported() &&
1764          Clause->getClauseKind() == OMPC_copyin)) {
1765       DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
1766       // Mark all variables in private list clauses as used in inner region.
1767       for (auto *VarRef : Clause->children()) {
1768         if (auto *E = cast_or_null<Expr>(VarRef)) {
1769           MarkDeclarationsReferencedInExpr(E);
1770         }
1771       }
1772       DSAStack->setForceVarCapturing(/*V=*/false);
1773     } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) {
1774       // Mark all variables in private list clauses as used in inner region.
1775       // Required for proper codegen of combined directives.
1776       // TODO: add processing for other clauses.
1777       if (auto *C = OMPClauseWithPreInit::get(Clause)) {
1778         if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
1779           for (auto *D : DS->decls())
1780             MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
1781         }
1782       }
1783       if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
1784         if (auto *E = C->getPostUpdateExpr())
1785           MarkDeclarationsReferencedInExpr(E);
1786       }
1787     }
1788     if (Clause->getClauseKind() == OMPC_schedule)
1789       SC = cast<OMPScheduleClause>(Clause);
1790     else if (Clause->getClauseKind() == OMPC_ordered)
1791       OC = cast<OMPOrderedClause>(Clause);
1792     else if (Clause->getClauseKind() == OMPC_linear)
1793       LCs.push_back(cast<OMPLinearClause>(Clause));
1794   }
1795   bool ErrorFound = false;
1796   // OpenMP, 2.7.1 Loop Construct, Restrictions
1797   // The nonmonotonic modifier cannot be specified if an ordered clause is
1798   // specified.
1799   if (SC &&
1800       (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
1801        SC->getSecondScheduleModifier() ==
1802            OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
1803       OC) {
1804     Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
1805              ? SC->getFirstScheduleModifierLoc()
1806              : SC->getSecondScheduleModifierLoc(),
1807          diag::err_omp_schedule_nonmonotonic_ordered)
1808         << SourceRange(OC->getLocStart(), OC->getLocEnd());
1809     ErrorFound = true;
1810   }
1811   if (!LCs.empty() && OC && OC->getNumForLoops()) {
1812     for (auto *C : LCs) {
1813       Diag(C->getLocStart(), diag::err_omp_linear_ordered)
1814           << SourceRange(OC->getLocStart(), OC->getLocEnd());
1815     }
1816     ErrorFound = true;
1817   }
1818   if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
1819       isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
1820       OC->getNumForLoops()) {
1821     Diag(OC->getLocStart(), diag::err_omp_ordered_simd)
1822         << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
1823     ErrorFound = true;
1824   }
1825   if (ErrorFound) {
1826     ActOnCapturedRegionError();
1827     return StmtError();
1828   }
1829   return ActOnCapturedRegionEnd(S.get());
1830 }
1831 
1832 static bool CheckNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack,
1833                                   OpenMPDirectiveKind CurrentRegion,
1834                                   const DeclarationNameInfo &CurrentName,
1835                                   OpenMPDirectiveKind CancelRegion,
1836                                   SourceLocation StartLoc) {
1837   // Allowed nesting of constructs
1838   // +------------------+-----------------+------------------------------------+
1839   // | Parent directive | Child directive | Closely (!), No-Closely(+), Both(*)|
1840   // +------------------+-----------------+------------------------------------+
1841   // | parallel         | parallel        | *                                  |
1842   // | parallel         | for             | *                                  |
1843   // | parallel         | for simd        | *                                  |
1844   // | parallel         | master          | *                                  |
1845   // | parallel         | critical        | *                                  |
1846   // | parallel         | simd            | *                                  |
1847   // | parallel         | sections        | *                                  |
1848   // | parallel         | section         | +                                  |
1849   // | parallel         | single          | *                                  |
1850   // | parallel         | parallel for    | *                                  |
1851   // | parallel         |parallel for simd| *                                  |
1852   // | parallel         |parallel sections| *                                  |
1853   // | parallel         | task            | *                                  |
1854   // | parallel         | taskyield       | *                                  |
1855   // | parallel         | barrier         | *                                  |
1856   // | parallel         | taskwait        | *                                  |
1857   // | parallel         | taskgroup       | *                                  |
1858   // | parallel         | flush           | *                                  |
1859   // | parallel         | ordered         | +                                  |
1860   // | parallel         | atomic          | *                                  |
1861   // | parallel         | target          | *                                  |
1862   // | parallel         | target parallel | *                                  |
1863   // | parallel         | target parallel | *                                  |
1864   // |                  | for             |                                    |
1865   // | parallel         | target enter    | *                                  |
1866   // |                  | data            |                                    |
1867   // | parallel         | target exit     | *                                  |
1868   // |                  | data            |                                    |
1869   // | parallel         | teams           | +                                  |
1870   // | parallel         | cancellation    |                                    |
1871   // |                  | point           | !                                  |
1872   // | parallel         | cancel          | !                                  |
1873   // | parallel         | taskloop        | *                                  |
1874   // | parallel         | taskloop simd   | *                                  |
1875   // | parallel         | distribute      |                                    |
1876   // +------------------+-----------------+------------------------------------+
1877   // | for              | parallel        | *                                  |
1878   // | for              | for             | +                                  |
1879   // | for              | for simd        | +                                  |
1880   // | for              | master          | +                                  |
1881   // | for              | critical        | *                                  |
1882   // | for              | simd            | *                                  |
1883   // | for              | sections        | +                                  |
1884   // | for              | section         | +                                  |
1885   // | for              | single          | +                                  |
1886   // | for              | parallel for    | *                                  |
1887   // | for              |parallel for simd| *                                  |
1888   // | for              |parallel sections| *                                  |
1889   // | for              | task            | *                                  |
1890   // | for              | taskyield       | *                                  |
1891   // | for              | barrier         | +                                  |
1892   // | for              | taskwait        | *                                  |
1893   // | for              | taskgroup       | *                                  |
1894   // | for              | flush           | *                                  |
1895   // | for              | ordered         | * (if construct is ordered)        |
1896   // | for              | atomic          | *                                  |
1897   // | for              | target          | *                                  |
1898   // | for              | target parallel | *                                  |
1899   // | for              | target parallel | *                                  |
1900   // |                  | for             |                                    |
1901   // | for              | target enter    | *                                  |
1902   // |                  | data            |                                    |
1903   // | for              | target exit     | *                                  |
1904   // |                  | data            |                                    |
1905   // | for              | teams           | +                                  |
1906   // | for              | cancellation    |                                    |
1907   // |                  | point           | !                                  |
1908   // | for              | cancel          | !                                  |
1909   // | for              | taskloop        | *                                  |
1910   // | for              | taskloop simd   | *                                  |
1911   // | for              | distribute      |                                    |
1912   // +------------------+-----------------+------------------------------------+
1913   // | master           | parallel        | *                                  |
1914   // | master           | for             | +                                  |
1915   // | master           | for simd        | +                                  |
1916   // | master           | master          | *                                  |
1917   // | master           | critical        | *                                  |
1918   // | master           | simd            | *                                  |
1919   // | master           | sections        | +                                  |
1920   // | master           | section         | +                                  |
1921   // | master           | single          | +                                  |
1922   // | master           | parallel for    | *                                  |
1923   // | master           |parallel for simd| *                                  |
1924   // | master           |parallel sections| *                                  |
1925   // | master           | task            | *                                  |
1926   // | master           | taskyield       | *                                  |
1927   // | master           | barrier         | +                                  |
1928   // | master           | taskwait        | *                                  |
1929   // | master           | taskgroup       | *                                  |
1930   // | master           | flush           | *                                  |
1931   // | master           | ordered         | +                                  |
1932   // | master           | atomic          | *                                  |
1933   // | master           | target          | *                                  |
1934   // | master           | target parallel | *                                  |
1935   // | master           | target parallel | *                                  |
1936   // |                  | for             |                                    |
1937   // | master           | target enter    | *                                  |
1938   // |                  | data            |                                    |
1939   // | master           | target exit     | *                                  |
1940   // |                  | data            |                                    |
1941   // | master           | teams           | +                                  |
1942   // | master           | cancellation    |                                    |
1943   // |                  | point           |                                    |
1944   // | master           | cancel          |                                    |
1945   // | master           | taskloop        | *                                  |
1946   // | master           | taskloop simd   | *                                  |
1947   // | master           | distribute      |                                    |
1948   // +------------------+-----------------+------------------------------------+
1949   // | critical         | parallel        | *                                  |
1950   // | critical         | for             | +                                  |
1951   // | critical         | for simd        | +                                  |
1952   // | critical         | master          | *                                  |
1953   // | critical         | critical        | * (should have different names)    |
1954   // | critical         | simd            | *                                  |
1955   // | critical         | sections        | +                                  |
1956   // | critical         | section         | +                                  |
1957   // | critical         | single          | +                                  |
1958   // | critical         | parallel for    | *                                  |
1959   // | critical         |parallel for simd| *                                  |
1960   // | critical         |parallel sections| *                                  |
1961   // | critical         | task            | *                                  |
1962   // | critical         | taskyield       | *                                  |
1963   // | critical         | barrier         | +                                  |
1964   // | critical         | taskwait        | *                                  |
1965   // | critical         | taskgroup       | *                                  |
1966   // | critical         | ordered         | +                                  |
1967   // | critical         | atomic          | *                                  |
1968   // | critical         | target          | *                                  |
1969   // | critical         | target parallel | *                                  |
1970   // | critical         | target parallel | *                                  |
1971   // |                  | for             |                                    |
1972   // | critical         | target enter    | *                                  |
1973   // |                  | data            |                                    |
1974   // | critical         | target exit     | *                                  |
1975   // |                  | data            |                                    |
1976   // | critical         | teams           | +                                  |
1977   // | critical         | cancellation    |                                    |
1978   // |                  | point           |                                    |
1979   // | critical         | cancel          |                                    |
1980   // | critical         | taskloop        | *                                  |
1981   // | critical         | taskloop simd   | *                                  |
1982   // | critical         | distribute      |                                    |
1983   // +------------------+-----------------+------------------------------------+
1984   // | simd             | parallel        |                                    |
1985   // | simd             | for             |                                    |
1986   // | simd             | for simd        |                                    |
1987   // | simd             | master          |                                    |
1988   // | simd             | critical        |                                    |
1989   // | simd             | simd            | *                                  |
1990   // | simd             | sections        |                                    |
1991   // | simd             | section         |                                    |
1992   // | simd             | single          |                                    |
1993   // | simd             | parallel for    |                                    |
1994   // | simd             |parallel for simd|                                    |
1995   // | simd             |parallel sections|                                    |
1996   // | simd             | task            |                                    |
1997   // | simd             | taskyield       |                                    |
1998   // | simd             | barrier         |                                    |
1999   // | simd             | taskwait        |                                    |
2000   // | simd             | taskgroup       |                                    |
2001   // | simd             | flush           |                                    |
2002   // | simd             | ordered         | + (with simd clause)               |
2003   // | simd             | atomic          |                                    |
2004   // | simd             | target          |                                    |
2005   // | simd             | target parallel |                                    |
2006   // | simd             | target parallel |                                    |
2007   // |                  | for             |                                    |
2008   // | simd             | target enter    |                                    |
2009   // |                  | data            |                                    |
2010   // | simd             | target exit     |                                    |
2011   // |                  | data            |                                    |
2012   // | simd             | teams           |                                    |
2013   // | simd             | cancellation    |                                    |
2014   // |                  | point           |                                    |
2015   // | simd             | cancel          |                                    |
2016   // | simd             | taskloop        |                                    |
2017   // | simd             | taskloop simd   |                                    |
2018   // | simd             | distribute      |                                    |
2019   // +------------------+-----------------+------------------------------------+
2020   // | for simd         | parallel        |                                    |
2021   // | for simd         | for             |                                    |
2022   // | for simd         | for simd        |                                    |
2023   // | for simd         | master          |                                    |
2024   // | for simd         | critical        |                                    |
2025   // | for simd         | simd            | *                                  |
2026   // | for simd         | sections        |                                    |
2027   // | for simd         | section         |                                    |
2028   // | for simd         | single          |                                    |
2029   // | for simd         | parallel for    |                                    |
2030   // | for simd         |parallel for simd|                                    |
2031   // | for simd         |parallel sections|                                    |
2032   // | for simd         | task            |                                    |
2033   // | for simd         | taskyield       |                                    |
2034   // | for simd         | barrier         |                                    |
2035   // | for simd         | taskwait        |                                    |
2036   // | for simd         | taskgroup       |                                    |
2037   // | for simd         | flush           |                                    |
2038   // | for simd         | ordered         | + (with simd clause)               |
2039   // | for simd         | atomic          |                                    |
2040   // | for simd         | target          |                                    |
2041   // | for simd         | target parallel |                                    |
2042   // | for simd         | target parallel |                                    |
2043   // |                  | for             |                                    |
2044   // | for simd         | target enter    |                                    |
2045   // |                  | data            |                                    |
2046   // | for simd         | target exit     |                                    |
2047   // |                  | data            |                                    |
2048   // | for simd         | teams           |                                    |
2049   // | for simd         | cancellation    |                                    |
2050   // |                  | point           |                                    |
2051   // | for simd         | cancel          |                                    |
2052   // | for simd         | taskloop        |                                    |
2053   // | for simd         | taskloop simd   |                                    |
2054   // | for simd         | distribute      |                                    |
2055   // +------------------+-----------------+------------------------------------+
2056   // | parallel for simd| parallel        |                                    |
2057   // | parallel for simd| for             |                                    |
2058   // | parallel for simd| for simd        |                                    |
2059   // | parallel for simd| master          |                                    |
2060   // | parallel for simd| critical        |                                    |
2061   // | parallel for simd| simd            | *                                  |
2062   // | parallel for simd| sections        |                                    |
2063   // | parallel for simd| section         |                                    |
2064   // | parallel for simd| single          |                                    |
2065   // | parallel for simd| parallel for    |                                    |
2066   // | parallel for simd|parallel for simd|                                    |
2067   // | parallel for simd|parallel sections|                                    |
2068   // | parallel for simd| task            |                                    |
2069   // | parallel for simd| taskyield       |                                    |
2070   // | parallel for simd| barrier         |                                    |
2071   // | parallel for simd| taskwait        |                                    |
2072   // | parallel for simd| taskgroup       |                                    |
2073   // | parallel for simd| flush           |                                    |
2074   // | parallel for simd| ordered         | + (with simd clause)               |
2075   // | parallel for simd| atomic          |                                    |
2076   // | parallel for simd| target          |                                    |
2077   // | parallel for simd| target parallel |                                    |
2078   // | parallel for simd| target parallel |                                    |
2079   // |                  | for             |                                    |
2080   // | parallel for simd| target enter    |                                    |
2081   // |                  | data            |                                    |
2082   // | parallel for simd| target exit     |                                    |
2083   // |                  | data            |                                    |
2084   // | parallel for simd| teams           |                                    |
2085   // | parallel for simd| cancellation    |                                    |
2086   // |                  | point           |                                    |
2087   // | parallel for simd| cancel          |                                    |
2088   // | parallel for simd| taskloop        |                                    |
2089   // | parallel for simd| taskloop simd   |                                    |
2090   // | parallel for simd| distribute      |                                    |
2091   // +------------------+-----------------+------------------------------------+
2092   // | sections         | parallel        | *                                  |
2093   // | sections         | for             | +                                  |
2094   // | sections         | for simd        | +                                  |
2095   // | sections         | master          | +                                  |
2096   // | sections         | critical        | *                                  |
2097   // | sections         | simd            | *                                  |
2098   // | sections         | sections        | +                                  |
2099   // | sections         | section         | *                                  |
2100   // | sections         | single          | +                                  |
2101   // | sections         | parallel for    | *                                  |
2102   // | sections         |parallel for simd| *                                  |
2103   // | sections         |parallel sections| *                                  |
2104   // | sections         | task            | *                                  |
2105   // | sections         | taskyield       | *                                  |
2106   // | sections         | barrier         | +                                  |
2107   // | sections         | taskwait        | *                                  |
2108   // | sections         | taskgroup       | *                                  |
2109   // | sections         | flush           | *                                  |
2110   // | sections         | ordered         | +                                  |
2111   // | sections         | atomic          | *                                  |
2112   // | sections         | target          | *                                  |
2113   // | sections         | target parallel | *                                  |
2114   // | sections         | target parallel | *                                  |
2115   // |                  | for             |                                    |
2116   // | sections         | target enter    | *                                  |
2117   // |                  | data            |                                    |
2118   // | sections         | target exit     | *                                  |
2119   // |                  | data            |                                    |
2120   // | sections         | teams           | +                                  |
2121   // | sections         | cancellation    |                                    |
2122   // |                  | point           | !                                  |
2123   // | sections         | cancel          | !                                  |
2124   // | sections         | taskloop        | *                                  |
2125   // | sections         | taskloop simd   | *                                  |
2126   // | sections         | distribute      |                                    |
2127   // +------------------+-----------------+------------------------------------+
2128   // | section          | parallel        | *                                  |
2129   // | section          | for             | +                                  |
2130   // | section          | for simd        | +                                  |
2131   // | section          | master          | +                                  |
2132   // | section          | critical        | *                                  |
2133   // | section          | simd            | *                                  |
2134   // | section          | sections        | +                                  |
2135   // | section          | section         | +                                  |
2136   // | section          | single          | +                                  |
2137   // | section          | parallel for    | *                                  |
2138   // | section          |parallel for simd| *                                  |
2139   // | section          |parallel sections| *                                  |
2140   // | section          | task            | *                                  |
2141   // | section          | taskyield       | *                                  |
2142   // | section          | barrier         | +                                  |
2143   // | section          | taskwait        | *                                  |
2144   // | section          | taskgroup       | *                                  |
2145   // | section          | flush           | *                                  |
2146   // | section          | ordered         | +                                  |
2147   // | section          | atomic          | *                                  |
2148   // | section          | target          | *                                  |
2149   // | section          | target parallel | *                                  |
2150   // | section          | target parallel | *                                  |
2151   // |                  | for             |                                    |
2152   // | section          | target enter    | *                                  |
2153   // |                  | data            |                                    |
2154   // | section          | target exit     | *                                  |
2155   // |                  | data            |                                    |
2156   // | section          | teams           | +                                  |
2157   // | section          | cancellation    |                                    |
2158   // |                  | point           | !                                  |
2159   // | section          | cancel          | !                                  |
2160   // | section          | taskloop        | *                                  |
2161   // | section          | taskloop simd   | *                                  |
2162   // | section          | distribute      |                                    |
2163   // +------------------+-----------------+------------------------------------+
2164   // | single           | parallel        | *                                  |
2165   // | single           | for             | +                                  |
2166   // | single           | for simd        | +                                  |
2167   // | single           | master          | +                                  |
2168   // | single           | critical        | *                                  |
2169   // | single           | simd            | *                                  |
2170   // | single           | sections        | +                                  |
2171   // | single           | section         | +                                  |
2172   // | single           | single          | +                                  |
2173   // | single           | parallel for    | *                                  |
2174   // | single           |parallel for simd| *                                  |
2175   // | single           |parallel sections| *                                  |
2176   // | single           | task            | *                                  |
2177   // | single           | taskyield       | *                                  |
2178   // | single           | barrier         | +                                  |
2179   // | single           | taskwait        | *                                  |
2180   // | single           | taskgroup       | *                                  |
2181   // | single           | flush           | *                                  |
2182   // | single           | ordered         | +                                  |
2183   // | single           | atomic          | *                                  |
2184   // | single           | target          | *                                  |
2185   // | single           | target parallel | *                                  |
2186   // | single           | target parallel | *                                  |
2187   // |                  | for             |                                    |
2188   // | single           | target enter    | *                                  |
2189   // |                  | data            |                                    |
2190   // | single           | target exit     | *                                  |
2191   // |                  | data            |                                    |
2192   // | single           | teams           | +                                  |
2193   // | single           | cancellation    |                                    |
2194   // |                  | point           |                                    |
2195   // | single           | cancel          |                                    |
2196   // | single           | taskloop        | *                                  |
2197   // | single           | taskloop simd   | *                                  |
2198   // | single           | distribute      |                                    |
2199   // +------------------+-----------------+------------------------------------+
2200   // | parallel for     | parallel        | *                                  |
2201   // | parallel for     | for             | +                                  |
2202   // | parallel for     | for simd        | +                                  |
2203   // | parallel for     | master          | +                                  |
2204   // | parallel for     | critical        | *                                  |
2205   // | parallel for     | simd            | *                                  |
2206   // | parallel for     | sections        | +                                  |
2207   // | parallel for     | section         | +                                  |
2208   // | parallel for     | single          | +                                  |
2209   // | parallel for     | parallel for    | *                                  |
2210   // | parallel for     |parallel for simd| *                                  |
2211   // | parallel for     |parallel sections| *                                  |
2212   // | parallel for     | task            | *                                  |
2213   // | parallel for     | taskyield       | *                                  |
2214   // | parallel for     | barrier         | +                                  |
2215   // | parallel for     | taskwait        | *                                  |
2216   // | parallel for     | taskgroup       | *                                  |
2217   // | parallel for     | flush           | *                                  |
2218   // | parallel for     | ordered         | * (if construct is ordered)        |
2219   // | parallel for     | atomic          | *                                  |
2220   // | parallel for     | target          | *                                  |
2221   // | parallel for     | target parallel | *                                  |
2222   // | parallel for     | target parallel | *                                  |
2223   // |                  | for             |                                    |
2224   // | parallel for     | target enter    | *                                  |
2225   // |                  | data            |                                    |
2226   // | parallel for     | target exit     | *                                  |
2227   // |                  | data            |                                    |
2228   // | parallel for     | teams           | +                                  |
2229   // | parallel for     | cancellation    |                                    |
2230   // |                  | point           | !                                  |
2231   // | parallel for     | cancel          | !                                  |
2232   // | parallel for     | taskloop        | *                                  |
2233   // | parallel for     | taskloop simd   | *                                  |
2234   // | parallel for     | distribute      |                                    |
2235   // +------------------+-----------------+------------------------------------+
2236   // | parallel sections| parallel        | *                                  |
2237   // | parallel sections| for             | +                                  |
2238   // | parallel sections| for simd        | +                                  |
2239   // | parallel sections| master          | +                                  |
2240   // | parallel sections| critical        | +                                  |
2241   // | parallel sections| simd            | *                                  |
2242   // | parallel sections| sections        | +                                  |
2243   // | parallel sections| section         | *                                  |
2244   // | parallel sections| single          | +                                  |
2245   // | parallel sections| parallel for    | *                                  |
2246   // | parallel sections|parallel for simd| *                                  |
2247   // | parallel sections|parallel sections| *                                  |
2248   // | parallel sections| task            | *                                  |
2249   // | parallel sections| taskyield       | *                                  |
2250   // | parallel sections| barrier         | +                                  |
2251   // | parallel sections| taskwait        | *                                  |
2252   // | parallel sections| taskgroup       | *                                  |
2253   // | parallel sections| flush           | *                                  |
2254   // | parallel sections| ordered         | +                                  |
2255   // | parallel sections| atomic          | *                                  |
2256   // | parallel sections| target          | *                                  |
2257   // | parallel sections| target parallel | *                                  |
2258   // | parallel sections| target parallel | *                                  |
2259   // |                  | for             |                                    |
2260   // | parallel sections| target enter    | *                                  |
2261   // |                  | data            |                                    |
2262   // | parallel sections| target exit     | *                                  |
2263   // |                  | data            |                                    |
2264   // | parallel sections| teams           | +                                  |
2265   // | parallel sections| cancellation    |                                    |
2266   // |                  | point           | !                                  |
2267   // | parallel sections| cancel          | !                                  |
2268   // | parallel sections| taskloop        | *                                  |
2269   // | parallel sections| taskloop simd   | *                                  |
2270   // | parallel sections| distribute      |                                    |
2271   // +------------------+-----------------+------------------------------------+
2272   // | task             | parallel        | *                                  |
2273   // | task             | for             | +                                  |
2274   // | task             | for simd        | +                                  |
2275   // | task             | master          | +                                  |
2276   // | task             | critical        | *                                  |
2277   // | task             | simd            | *                                  |
2278   // | task             | sections        | +                                  |
2279   // | task             | section         | +                                  |
2280   // | task             | single          | +                                  |
2281   // | task             | parallel for    | *                                  |
2282   // | task             |parallel for simd| *                                  |
2283   // | task             |parallel sections| *                                  |
2284   // | task             | task            | *                                  |
2285   // | task             | taskyield       | *                                  |
2286   // | task             | barrier         | +                                  |
2287   // | task             | taskwait        | *                                  |
2288   // | task             | taskgroup       | *                                  |
2289   // | task             | flush           | *                                  |
2290   // | task             | ordered         | +                                  |
2291   // | task             | atomic          | *                                  |
2292   // | task             | target          | *                                  |
2293   // | task             | target parallel | *                                  |
2294   // | task             | target parallel | *                                  |
2295   // |                  | for             |                                    |
2296   // | task             | target enter    | *                                  |
2297   // |                  | data            |                                    |
2298   // | task             | target exit     | *                                  |
2299   // |                  | data            |                                    |
2300   // | task             | teams           | +                                  |
2301   // | task             | cancellation    |                                    |
2302   // |                  | point           | !                                  |
2303   // | task             | cancel          | !                                  |
2304   // | task             | taskloop        | *                                  |
2305   // | task             | taskloop simd   | *                                  |
2306   // | task             | distribute      |                                    |
2307   // +------------------+-----------------+------------------------------------+
2308   // | ordered          | parallel        | *                                  |
2309   // | ordered          | for             | +                                  |
2310   // | ordered          | for simd        | +                                  |
2311   // | ordered          | master          | *                                  |
2312   // | ordered          | critical        | *                                  |
2313   // | ordered          | simd            | *                                  |
2314   // | ordered          | sections        | +                                  |
2315   // | ordered          | section         | +                                  |
2316   // | ordered          | single          | +                                  |
2317   // | ordered          | parallel for    | *                                  |
2318   // | ordered          |parallel for simd| *                                  |
2319   // | ordered          |parallel sections| *                                  |
2320   // | ordered          | task            | *                                  |
2321   // | ordered          | taskyield       | *                                  |
2322   // | ordered          | barrier         | +                                  |
2323   // | ordered          | taskwait        | *                                  |
2324   // | ordered          | taskgroup       | *                                  |
2325   // | ordered          | flush           | *                                  |
2326   // | ordered          | ordered         | +                                  |
2327   // | ordered          | atomic          | *                                  |
2328   // | ordered          | target          | *                                  |
2329   // | ordered          | target parallel | *                                  |
2330   // | ordered          | target parallel | *                                  |
2331   // |                  | for             |                                    |
2332   // | ordered          | target enter    | *                                  |
2333   // |                  | data            |                                    |
2334   // | ordered          | target exit     | *                                  |
2335   // |                  | data            |                                    |
2336   // | ordered          | teams           | +                                  |
2337   // | ordered          | cancellation    |                                    |
2338   // |                  | point           |                                    |
2339   // | ordered          | cancel          |                                    |
2340   // | ordered          | taskloop        | *                                  |
2341   // | ordered          | taskloop simd   | *                                  |
2342   // | ordered          | distribute      |                                    |
2343   // +------------------+-----------------+------------------------------------+
2344   // | atomic           | parallel        |                                    |
2345   // | atomic           | for             |                                    |
2346   // | atomic           | for simd        |                                    |
2347   // | atomic           | master          |                                    |
2348   // | atomic           | critical        |                                    |
2349   // | atomic           | simd            |                                    |
2350   // | atomic           | sections        |                                    |
2351   // | atomic           | section         |                                    |
2352   // | atomic           | single          |                                    |
2353   // | atomic           | parallel for    |                                    |
2354   // | atomic           |parallel for simd|                                    |
2355   // | atomic           |parallel sections|                                    |
2356   // | atomic           | task            |                                    |
2357   // | atomic           | taskyield       |                                    |
2358   // | atomic           | barrier         |                                    |
2359   // | atomic           | taskwait        |                                    |
2360   // | atomic           | taskgroup       |                                    |
2361   // | atomic           | flush           |                                    |
2362   // | atomic           | ordered         |                                    |
2363   // | atomic           | atomic          |                                    |
2364   // | atomic           | target          |                                    |
2365   // | atomic           | target parallel |                                    |
2366   // | atomic           | target parallel |                                    |
2367   // |                  | for             |                                    |
2368   // | atomic           | target enter    |                                    |
2369   // |                  | data            |                                    |
2370   // | atomic           | target exit     |                                    |
2371   // |                  | data            |                                    |
2372   // | atomic           | teams           |                                    |
2373   // | atomic           | cancellation    |                                    |
2374   // |                  | point           |                                    |
2375   // | atomic           | cancel          |                                    |
2376   // | atomic           | taskloop        |                                    |
2377   // | atomic           | taskloop simd   |                                    |
2378   // | atomic           | distribute      |                                    |
2379   // +------------------+-----------------+------------------------------------+
2380   // | target           | parallel        | *                                  |
2381   // | target           | for             | *                                  |
2382   // | target           | for simd        | *                                  |
2383   // | target           | master          | *                                  |
2384   // | target           | critical        | *                                  |
2385   // | target           | simd            | *                                  |
2386   // | target           | sections        | *                                  |
2387   // | target           | section         | *                                  |
2388   // | target           | single          | *                                  |
2389   // | target           | parallel for    | *                                  |
2390   // | target           |parallel for simd| *                                  |
2391   // | target           |parallel sections| *                                  |
2392   // | target           | task            | *                                  |
2393   // | target           | taskyield       | *                                  |
2394   // | target           | barrier         | *                                  |
2395   // | target           | taskwait        | *                                  |
2396   // | target           | taskgroup       | *                                  |
2397   // | target           | flush           | *                                  |
2398   // | target           | ordered         | *                                  |
2399   // | target           | atomic          | *                                  |
2400   // | target           | target          |                                    |
2401   // | target           | target parallel |                                    |
2402   // | target           | target parallel |                                    |
2403   // |                  | for             |                                    |
2404   // | target           | target enter    |                                    |
2405   // |                  | data            |                                    |
2406   // | target           | target exit     |                                    |
2407   // |                  | data            |                                    |
2408   // | target           | teams           | *                                  |
2409   // | target           | cancellation    |                                    |
2410   // |                  | point           |                                    |
2411   // | target           | cancel          |                                    |
2412   // | target           | taskloop        | *                                  |
2413   // | target           | taskloop simd   | *                                  |
2414   // | target           | distribute      |                                    |
2415   // +------------------+-----------------+------------------------------------+
2416   // | target parallel  | parallel        | *                                  |
2417   // | target parallel  | for             | *                                  |
2418   // | target parallel  | for simd        | *                                  |
2419   // | target parallel  | master          | *                                  |
2420   // | target parallel  | critical        | *                                  |
2421   // | target parallel  | simd            | *                                  |
2422   // | target parallel  | sections        | *                                  |
2423   // | target parallel  | section         | *                                  |
2424   // | target parallel  | single          | *                                  |
2425   // | target parallel  | parallel for    | *                                  |
2426   // | target parallel  |parallel for simd| *                                  |
2427   // | target parallel  |parallel sections| *                                  |
2428   // | target parallel  | task            | *                                  |
2429   // | target parallel  | taskyield       | *                                  |
2430   // | target parallel  | barrier         | *                                  |
2431   // | target parallel  | taskwait        | *                                  |
2432   // | target parallel  | taskgroup       | *                                  |
2433   // | target parallel  | flush           | *                                  |
2434   // | target parallel  | ordered         | *                                  |
2435   // | target parallel  | atomic          | *                                  |
2436   // | target parallel  | target          |                                    |
2437   // | target parallel  | target parallel |                                    |
2438   // | target parallel  | target parallel |                                    |
2439   // |                  | for             |                                    |
2440   // | target parallel  | target enter    |                                    |
2441   // |                  | data            |                                    |
2442   // | target parallel  | target exit     |                                    |
2443   // |                  | data            |                                    |
2444   // | target parallel  | teams           |                                    |
2445   // | target parallel  | cancellation    |                                    |
2446   // |                  | point           | !                                  |
2447   // | target parallel  | cancel          | !                                  |
2448   // | target parallel  | taskloop        | *                                  |
2449   // | target parallel  | taskloop simd   | *                                  |
2450   // | target parallel  | distribute      |                                    |
2451   // +------------------+-----------------+------------------------------------+
2452   // | target parallel  | parallel        | *                                  |
2453   // | for              |                 |                                    |
2454   // | target parallel  | for             | *                                  |
2455   // | for              |                 |                                    |
2456   // | target parallel  | for simd        | *                                  |
2457   // | for              |                 |                                    |
2458   // | target parallel  | master          | *                                  |
2459   // | for              |                 |                                    |
2460   // | target parallel  | critical        | *                                  |
2461   // | for              |                 |                                    |
2462   // | target parallel  | simd            | *                                  |
2463   // | for              |                 |                                    |
2464   // | target parallel  | sections        | *                                  |
2465   // | for              |                 |                                    |
2466   // | target parallel  | section         | *                                  |
2467   // | for              |                 |                                    |
2468   // | target parallel  | single          | *                                  |
2469   // | for              |                 |                                    |
2470   // | target parallel  | parallel for    | *                                  |
2471   // | for              |                 |                                    |
2472   // | target parallel  |parallel for simd| *                                  |
2473   // | for              |                 |                                    |
2474   // | target parallel  |parallel sections| *                                  |
2475   // | for              |                 |                                    |
2476   // | target parallel  | task            | *                                  |
2477   // | for              |                 |                                    |
2478   // | target parallel  | taskyield       | *                                  |
2479   // | for              |                 |                                    |
2480   // | target parallel  | barrier         | *                                  |
2481   // | for              |                 |                                    |
2482   // | target parallel  | taskwait        | *                                  |
2483   // | for              |                 |                                    |
2484   // | target parallel  | taskgroup       | *                                  |
2485   // | for              |                 |                                    |
2486   // | target parallel  | flush           | *                                  |
2487   // | for              |                 |                                    |
2488   // | target parallel  | ordered         | *                                  |
2489   // | for              |                 |                                    |
2490   // | target parallel  | atomic          | *                                  |
2491   // | for              |                 |                                    |
2492   // | target parallel  | target          |                                    |
2493   // | for              |                 |                                    |
2494   // | target parallel  | target parallel |                                    |
2495   // | for              |                 |                                    |
2496   // | target parallel  | target parallel |                                    |
2497   // | for              | for             |                                    |
2498   // | target parallel  | target enter    |                                    |
2499   // | for              | data            |                                    |
2500   // | target parallel  | target exit     |                                    |
2501   // | for              | data            |                                    |
2502   // | target parallel  | teams           |                                    |
2503   // | for              |                 |                                    |
2504   // | target parallel  | cancellation    |                                    |
2505   // | for              | point           | !                                  |
2506   // | target parallel  | cancel          | !                                  |
2507   // | for              |                 |                                    |
2508   // | target parallel  | taskloop        | *                                  |
2509   // | for              |                 |                                    |
2510   // | target parallel  | taskloop simd   | *                                  |
2511   // | for              |                 |                                    |
2512   // | target parallel  | distribute      |                                    |
2513   // | for              |                 |                                    |
2514   // +------------------+-----------------+------------------------------------+
2515   // | teams            | parallel        | *                                  |
2516   // | teams            | for             | +                                  |
2517   // | teams            | for simd        | +                                  |
2518   // | teams            | master          | +                                  |
2519   // | teams            | critical        | +                                  |
2520   // | teams            | simd            | +                                  |
2521   // | teams            | sections        | +                                  |
2522   // | teams            | section         | +                                  |
2523   // | teams            | single          | +                                  |
2524   // | teams            | parallel for    | *                                  |
2525   // | teams            |parallel for simd| *                                  |
2526   // | teams            |parallel sections| *                                  |
2527   // | teams            | task            | +                                  |
2528   // | teams            | taskyield       | +                                  |
2529   // | teams            | barrier         | +                                  |
2530   // | teams            | taskwait        | +                                  |
2531   // | teams            | taskgroup       | +                                  |
2532   // | teams            | flush           | +                                  |
2533   // | teams            | ordered         | +                                  |
2534   // | teams            | atomic          | +                                  |
2535   // | teams            | target          | +                                  |
2536   // | teams            | target parallel | +                                  |
2537   // | teams            | target parallel | +                                  |
2538   // |                  | for             |                                    |
2539   // | teams            | target enter    | +                                  |
2540   // |                  | data            |                                    |
2541   // | teams            | target exit     | +                                  |
2542   // |                  | data            |                                    |
2543   // | teams            | teams           | +                                  |
2544   // | teams            | cancellation    |                                    |
2545   // |                  | point           |                                    |
2546   // | teams            | cancel          |                                    |
2547   // | teams            | taskloop        | +                                  |
2548   // | teams            | taskloop simd   | +                                  |
2549   // | teams            | distribute      | !                                  |
2550   // +------------------+-----------------+------------------------------------+
2551   // | taskloop         | parallel        | *                                  |
2552   // | taskloop         | for             | +                                  |
2553   // | taskloop         | for simd        | +                                  |
2554   // | taskloop         | master          | +                                  |
2555   // | taskloop         | critical        | *                                  |
2556   // | taskloop         | simd            | *                                  |
2557   // | taskloop         | sections        | +                                  |
2558   // | taskloop         | section         | +                                  |
2559   // | taskloop         | single          | +                                  |
2560   // | taskloop         | parallel for    | *                                  |
2561   // | taskloop         |parallel for simd| *                                  |
2562   // | taskloop         |parallel sections| *                                  |
2563   // | taskloop         | task            | *                                  |
2564   // | taskloop         | taskyield       | *                                  |
2565   // | taskloop         | barrier         | +                                  |
2566   // | taskloop         | taskwait        | *                                  |
2567   // | taskloop         | taskgroup       | *                                  |
2568   // | taskloop         | flush           | *                                  |
2569   // | taskloop         | ordered         | +                                  |
2570   // | taskloop         | atomic          | *                                  |
2571   // | taskloop         | target          | *                                  |
2572   // | taskloop         | target parallel | *                                  |
2573   // | taskloop         | target parallel | *                                  |
2574   // |                  | for             |                                    |
2575   // | taskloop         | target enter    | *                                  |
2576   // |                  | data            |                                    |
2577   // | taskloop         | target exit     | *                                  |
2578   // |                  | data            |                                    |
2579   // | taskloop         | teams           | +                                  |
2580   // | taskloop         | cancellation    |                                    |
2581   // |                  | point           |                                    |
2582   // | taskloop         | cancel          |                                    |
2583   // | taskloop         | taskloop        | *                                  |
2584   // | taskloop         | distribute      |                                    |
2585   // +------------------+-----------------+------------------------------------+
2586   // | taskloop simd    | parallel        |                                    |
2587   // | taskloop simd    | for             |                                    |
2588   // | taskloop simd    | for simd        |                                    |
2589   // | taskloop simd    | master          |                                    |
2590   // | taskloop simd    | critical        |                                    |
2591   // | taskloop simd    | simd            | *                                  |
2592   // | taskloop simd    | sections        |                                    |
2593   // | taskloop simd    | section         |                                    |
2594   // | taskloop simd    | single          |                                    |
2595   // | taskloop simd    | parallel for    |                                    |
2596   // | taskloop simd    |parallel for simd|                                    |
2597   // | taskloop simd    |parallel sections|                                    |
2598   // | taskloop simd    | task            |                                    |
2599   // | taskloop simd    | taskyield       |                                    |
2600   // | taskloop simd    | barrier         |                                    |
2601   // | taskloop simd    | taskwait        |                                    |
2602   // | taskloop simd    | taskgroup       |                                    |
2603   // | taskloop simd    | flush           |                                    |
2604   // | taskloop simd    | ordered         | + (with simd clause)               |
2605   // | taskloop simd    | atomic          |                                    |
2606   // | taskloop simd    | target          |                                    |
2607   // | taskloop simd    | target parallel |                                    |
2608   // | taskloop simd    | target parallel |                                    |
2609   // |                  | for             |                                    |
2610   // | taskloop simd    | target enter    |                                    |
2611   // |                  | data            |                                    |
2612   // | taskloop simd    | target exit     |                                    |
2613   // |                  | data            |                                    |
2614   // | taskloop simd    | teams           |                                    |
2615   // | taskloop simd    | cancellation    |                                    |
2616   // |                  | point           |                                    |
2617   // | taskloop simd    | cancel          |                                    |
2618   // | taskloop simd    | taskloop        |                                    |
2619   // | taskloop simd    | taskloop simd   |                                    |
2620   // | taskloop simd    | distribute      |                                    |
2621   // +------------------+-----------------+------------------------------------+
2622   // | distribute       | parallel        | *                                  |
2623   // | distribute       | for             | *                                  |
2624   // | distribute       | for simd        | *                                  |
2625   // | distribute       | master          | *                                  |
2626   // | distribute       | critical        | *                                  |
2627   // | distribute       | simd            | *                                  |
2628   // | distribute       | sections        | *                                  |
2629   // | distribute       | section         | *                                  |
2630   // | distribute       | single          | *                                  |
2631   // | distribute       | parallel for    | *                                  |
2632   // | distribute       |parallel for simd| *                                  |
2633   // | distribute       |parallel sections| *                                  |
2634   // | distribute       | task            | *                                  |
2635   // | distribute       | taskyield       | *                                  |
2636   // | distribute       | barrier         | *                                  |
2637   // | distribute       | taskwait        | *                                  |
2638   // | distribute       | taskgroup       | *                                  |
2639   // | distribute       | flush           | *                                  |
2640   // | distribute       | ordered         | +                                  |
2641   // | distribute       | atomic          | *                                  |
2642   // | distribute       | target          |                                    |
2643   // | distribute       | target parallel |                                    |
2644   // | distribute       | target parallel |                                    |
2645   // |                  | for             |                                    |
2646   // | distribute       | target enter    |                                    |
2647   // |                  | data            |                                    |
2648   // | distribute       | target exit     |                                    |
2649   // |                  | data            |                                    |
2650   // | distribute       | teams           |                                    |
2651   // | distribute       | cancellation    | +                                  |
2652   // |                  | point           |                                    |
2653   // | distribute       | cancel          | +                                  |
2654   // | distribute       | taskloop        | *                                  |
2655   // | distribute       | taskloop simd   | *                                  |
2656   // | distribute       | distribute      |                                    |
2657   // +------------------+-----------------+------------------------------------+
2658   if (Stack->getCurScope()) {
2659     auto ParentRegion = Stack->getParentDirective();
2660     auto OffendingRegion = ParentRegion;
2661     bool NestingProhibited = false;
2662     bool CloseNesting = true;
2663     enum {
2664       NoRecommend,
2665       ShouldBeInParallelRegion,
2666       ShouldBeInOrderedRegion,
2667       ShouldBeInTargetRegion,
2668       ShouldBeInTeamsRegion
2669     } Recommend = NoRecommend;
2670     if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered &&
2671         CurrentRegion != OMPD_simd) {
2672       // OpenMP [2.16, Nesting of Regions]
2673       // OpenMP constructs may not be nested inside a simd region.
2674       // OpenMP [2.8.1,simd Construct, Restrictions]
2675       // An ordered construct with the simd clause is the only OpenMP construct
2676       // that can appear in the simd region.
2677       SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_simd);
2678       return true;
2679     }
2680     if (ParentRegion == OMPD_atomic) {
2681       // OpenMP [2.16, Nesting of Regions]
2682       // OpenMP constructs may not be nested inside an atomic region.
2683       SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
2684       return true;
2685     }
2686     if (CurrentRegion == OMPD_section) {
2687       // OpenMP [2.7.2, sections Construct, Restrictions]
2688       // Orphaned section directives are prohibited. That is, the section
2689       // directives must appear within the sections construct and must not be
2690       // encountered elsewhere in the sections region.
2691       if (ParentRegion != OMPD_sections &&
2692           ParentRegion != OMPD_parallel_sections) {
2693         SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
2694             << (ParentRegion != OMPD_unknown)
2695             << getOpenMPDirectiveName(ParentRegion);
2696         return true;
2697       }
2698       return false;
2699     }
2700     // Allow some constructs to be orphaned (they could be used in functions,
2701     // called from OpenMP regions with the required preconditions).
2702     if (ParentRegion == OMPD_unknown)
2703       return false;
2704     if (CurrentRegion == OMPD_cancellation_point ||
2705         CurrentRegion == OMPD_cancel) {
2706       // OpenMP [2.16, Nesting of Regions]
2707       // A cancellation point construct for which construct-type-clause is
2708       // taskgroup must be nested inside a task construct. A cancellation
2709       // point construct for which construct-type-clause is not taskgroup must
2710       // be closely nested inside an OpenMP construct that matches the type
2711       // specified in construct-type-clause.
2712       // A cancel construct for which construct-type-clause is taskgroup must be
2713       // nested inside a task construct. A cancel construct for which
2714       // construct-type-clause is not taskgroup must be closely nested inside an
2715       // OpenMP construct that matches the type specified in
2716       // construct-type-clause.
2717       NestingProhibited =
2718           !((CancelRegion == OMPD_parallel &&
2719              (ParentRegion == OMPD_parallel ||
2720               ParentRegion == OMPD_target_parallel)) ||
2721             (CancelRegion == OMPD_for &&
2722              (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
2723               ParentRegion == OMPD_target_parallel_for)) ||
2724             (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
2725             (CancelRegion == OMPD_sections &&
2726              (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
2727               ParentRegion == OMPD_parallel_sections)));
2728     } else if (CurrentRegion == OMPD_master) {
2729       // OpenMP [2.16, Nesting of Regions]
2730       // A master region may not be closely nested inside a worksharing,
2731       // atomic, or explicit task region.
2732       NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2733                           ParentRegion == OMPD_task ||
2734                           isOpenMPTaskLoopDirective(ParentRegion);
2735     } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
2736       // OpenMP [2.16, Nesting of Regions]
2737       // A critical region may not be nested (closely or otherwise) inside a
2738       // critical region with the same name. Note that this restriction is not
2739       // sufficient to prevent deadlock.
2740       SourceLocation PreviousCriticalLoc;
2741       bool DeadLock =
2742           Stack->hasDirective([CurrentName, &PreviousCriticalLoc](
2743                                   OpenMPDirectiveKind K,
2744                                   const DeclarationNameInfo &DNI,
2745                                   SourceLocation Loc)
2746                                   ->bool {
2747                                 if (K == OMPD_critical &&
2748                                     DNI.getName() == CurrentName.getName()) {
2749                                   PreviousCriticalLoc = Loc;
2750                                   return true;
2751                                 } else
2752                                   return false;
2753                               },
2754                               false /* skip top directive */);
2755       if (DeadLock) {
2756         SemaRef.Diag(StartLoc,
2757                      diag::err_omp_prohibited_region_critical_same_name)
2758             << CurrentName.getName();
2759         if (PreviousCriticalLoc.isValid())
2760           SemaRef.Diag(PreviousCriticalLoc,
2761                        diag::note_omp_previous_critical_region);
2762         return true;
2763       }
2764     } else if (CurrentRegion == OMPD_barrier) {
2765       // OpenMP [2.16, Nesting of Regions]
2766       // A barrier region may not be closely nested inside a worksharing,
2767       // explicit task, critical, ordered, atomic, or master region.
2768       NestingProhibited =
2769           isOpenMPWorksharingDirective(ParentRegion) ||
2770           ParentRegion == OMPD_task || ParentRegion == OMPD_master ||
2771           ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered ||
2772           isOpenMPTaskLoopDirective(ParentRegion);
2773     } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
2774                !isOpenMPParallelDirective(CurrentRegion)) {
2775       // OpenMP [2.16, Nesting of Regions]
2776       // A worksharing region may not be closely nested inside a worksharing,
2777       // explicit task, critical, ordered, atomic, or master region.
2778       NestingProhibited =
2779           isOpenMPWorksharingDirective(ParentRegion) ||
2780           ParentRegion == OMPD_task || ParentRegion == OMPD_master ||
2781           ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered ||
2782           isOpenMPTaskLoopDirective(ParentRegion);
2783       Recommend = ShouldBeInParallelRegion;
2784     } else if (CurrentRegion == OMPD_ordered) {
2785       // OpenMP [2.16, Nesting of Regions]
2786       // An ordered region may not be closely nested inside a critical,
2787       // atomic, or explicit task region.
2788       // An ordered region must be closely nested inside a loop region (or
2789       // parallel loop region) with an ordered clause.
2790       // OpenMP [2.8.1,simd Construct, Restrictions]
2791       // An ordered construct with the simd clause is the only OpenMP construct
2792       // that can appear in the simd region.
2793       NestingProhibited = ParentRegion == OMPD_critical ||
2794                           ParentRegion == OMPD_task ||
2795                           isOpenMPTaskLoopDirective(ParentRegion) ||
2796                           !(isOpenMPSimdDirective(ParentRegion) ||
2797                             Stack->isParentOrderedRegion());
2798       Recommend = ShouldBeInOrderedRegion;
2799     } else if (isOpenMPTeamsDirective(CurrentRegion)) {
2800       // OpenMP [2.16, Nesting of Regions]
2801       // If specified, a teams construct must be contained within a target
2802       // construct.
2803       NestingProhibited = ParentRegion != OMPD_target;
2804       Recommend = ShouldBeInTargetRegion;
2805       Stack->setParentTeamsRegionLoc(Stack->getConstructLoc());
2806     }
2807     if (!NestingProhibited && isOpenMPTeamsDirective(ParentRegion)) {
2808       // OpenMP [2.16, Nesting of Regions]
2809       // distribute, parallel, parallel sections, parallel workshare, and the
2810       // parallel loop and parallel loop SIMD constructs are the only OpenMP
2811       // constructs that can be closely nested in the teams region.
2812       NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
2813                           !isOpenMPDistributeDirective(CurrentRegion);
2814       Recommend = ShouldBeInParallelRegion;
2815     }
2816     if (!NestingProhibited && isOpenMPDistributeDirective(CurrentRegion)) {
2817       // OpenMP 4.5 [2.17 Nesting of Regions]
2818       // The region associated with the distribute construct must be strictly
2819       // nested inside a teams region
2820       NestingProhibited = !isOpenMPTeamsDirective(ParentRegion);
2821       Recommend = ShouldBeInTeamsRegion;
2822     }
2823     if (!NestingProhibited &&
2824         (isOpenMPTargetExecutionDirective(CurrentRegion) ||
2825          isOpenMPTargetDataManagementDirective(CurrentRegion))) {
2826       // OpenMP 4.5 [2.17 Nesting of Regions]
2827       // If a target, target update, target data, target enter data, or
2828       // target exit data construct is encountered during execution of a
2829       // target region, the behavior is unspecified.
2830       NestingProhibited = Stack->hasDirective(
2831           [&OffendingRegion](OpenMPDirectiveKind K,
2832                              const DeclarationNameInfo &DNI,
2833                              SourceLocation Loc) -> bool {
2834             if (isOpenMPTargetExecutionDirective(K)) {
2835               OffendingRegion = K;
2836               return true;
2837             } else
2838               return false;
2839           },
2840           false /* don't skip top directive */);
2841       CloseNesting = false;
2842     }
2843     if (NestingProhibited) {
2844       SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
2845           << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
2846           << Recommend << getOpenMPDirectiveName(CurrentRegion);
2847       return true;
2848     }
2849   }
2850   return false;
2851 }
2852 
2853 static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
2854                            ArrayRef<OMPClause *> Clauses,
2855                            ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
2856   bool ErrorFound = false;
2857   unsigned NamedModifiersNumber = 0;
2858   SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
2859       OMPD_unknown + 1);
2860   SmallVector<SourceLocation, 4> NameModifierLoc;
2861   for (const auto *C : Clauses) {
2862     if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
2863       // At most one if clause without a directive-name-modifier can appear on
2864       // the directive.
2865       OpenMPDirectiveKind CurNM = IC->getNameModifier();
2866       if (FoundNameModifiers[CurNM]) {
2867         S.Diag(C->getLocStart(), diag::err_omp_more_one_clause)
2868             << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
2869             << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
2870         ErrorFound = true;
2871       } else if (CurNM != OMPD_unknown) {
2872         NameModifierLoc.push_back(IC->getNameModifierLoc());
2873         ++NamedModifiersNumber;
2874       }
2875       FoundNameModifiers[CurNM] = IC;
2876       if (CurNM == OMPD_unknown)
2877         continue;
2878       // Check if the specified name modifier is allowed for the current
2879       // directive.
2880       // At most one if clause with the particular directive-name-modifier can
2881       // appear on the directive.
2882       bool MatchFound = false;
2883       for (auto NM : AllowedNameModifiers) {
2884         if (CurNM == NM) {
2885           MatchFound = true;
2886           break;
2887         }
2888       }
2889       if (!MatchFound) {
2890         S.Diag(IC->getNameModifierLoc(),
2891                diag::err_omp_wrong_if_directive_name_modifier)
2892             << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
2893         ErrorFound = true;
2894       }
2895     }
2896   }
2897   // If any if clause on the directive includes a directive-name-modifier then
2898   // all if clauses on the directive must include a directive-name-modifier.
2899   if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
2900     if (NamedModifiersNumber == AllowedNameModifiers.size()) {
2901       S.Diag(FoundNameModifiers[OMPD_unknown]->getLocStart(),
2902              diag::err_omp_no_more_if_clause);
2903     } else {
2904       std::string Values;
2905       std::string Sep(", ");
2906       unsigned AllowedCnt = 0;
2907       unsigned TotalAllowedNum =
2908           AllowedNameModifiers.size() - NamedModifiersNumber;
2909       for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
2910            ++Cnt) {
2911         OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
2912         if (!FoundNameModifiers[NM]) {
2913           Values += "'";
2914           Values += getOpenMPDirectiveName(NM);
2915           Values += "'";
2916           if (AllowedCnt + 2 == TotalAllowedNum)
2917             Values += " or ";
2918           else if (AllowedCnt + 1 != TotalAllowedNum)
2919             Values += Sep;
2920           ++AllowedCnt;
2921         }
2922       }
2923       S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getLocStart(),
2924              diag::err_omp_unnamed_if_clause)
2925           << (TotalAllowedNum > 1) << Values;
2926     }
2927     for (auto Loc : NameModifierLoc) {
2928       S.Diag(Loc, diag::note_omp_previous_named_if_clause);
2929     }
2930     ErrorFound = true;
2931   }
2932   return ErrorFound;
2933 }
2934 
2935 StmtResult Sema::ActOnOpenMPExecutableDirective(
2936     OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
2937     OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
2938     Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
2939   StmtResult Res = StmtError();
2940   if (CheckNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
2941                             StartLoc))
2942     return StmtError();
2943 
2944   llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
2945   llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
2946   bool ErrorFound = false;
2947   ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
2948   if (AStmt) {
2949     assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
2950 
2951     // Check default data sharing attributes for referenced variables.
2952     DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
2953     DSAChecker.Visit(cast<CapturedStmt>(AStmt)->getCapturedStmt());
2954     if (DSAChecker.isErrorFound())
2955       return StmtError();
2956     // Generate list of implicitly defined firstprivate variables.
2957     VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
2958 
2959     if (!DSAChecker.getImplicitFirstprivate().empty()) {
2960       if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
2961               DSAChecker.getImplicitFirstprivate(), SourceLocation(),
2962               SourceLocation(), SourceLocation())) {
2963         ClausesWithImplicit.push_back(Implicit);
2964         ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
2965                      DSAChecker.getImplicitFirstprivate().size();
2966       } else
2967         ErrorFound = true;
2968     }
2969   }
2970 
2971   llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
2972   switch (Kind) {
2973   case OMPD_parallel:
2974     Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
2975                                        EndLoc);
2976     AllowedNameModifiers.push_back(OMPD_parallel);
2977     break;
2978   case OMPD_simd:
2979     Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2980                                    VarsWithInheritedDSA);
2981     break;
2982   case OMPD_for:
2983     Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2984                                   VarsWithInheritedDSA);
2985     break;
2986   case OMPD_for_simd:
2987     Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2988                                       EndLoc, VarsWithInheritedDSA);
2989     break;
2990   case OMPD_sections:
2991     Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
2992                                        EndLoc);
2993     break;
2994   case OMPD_section:
2995     assert(ClausesWithImplicit.empty() &&
2996            "No clauses are allowed for 'omp section' directive");
2997     Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
2998     break;
2999   case OMPD_single:
3000     Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
3001                                      EndLoc);
3002     break;
3003   case OMPD_master:
3004     assert(ClausesWithImplicit.empty() &&
3005            "No clauses are allowed for 'omp master' directive");
3006     Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
3007     break;
3008   case OMPD_critical:
3009     Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
3010                                        StartLoc, EndLoc);
3011     break;
3012   case OMPD_parallel_for:
3013     Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
3014                                           EndLoc, VarsWithInheritedDSA);
3015     AllowedNameModifiers.push_back(OMPD_parallel);
3016     break;
3017   case OMPD_parallel_for_simd:
3018     Res = ActOnOpenMPParallelForSimdDirective(
3019         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3020     AllowedNameModifiers.push_back(OMPD_parallel);
3021     break;
3022   case OMPD_parallel_sections:
3023     Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
3024                                                StartLoc, EndLoc);
3025     AllowedNameModifiers.push_back(OMPD_parallel);
3026     break;
3027   case OMPD_task:
3028     Res =
3029         ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
3030     AllowedNameModifiers.push_back(OMPD_task);
3031     break;
3032   case OMPD_taskyield:
3033     assert(ClausesWithImplicit.empty() &&
3034            "No clauses are allowed for 'omp taskyield' directive");
3035     assert(AStmt == nullptr &&
3036            "No associated statement allowed for 'omp taskyield' directive");
3037     Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
3038     break;
3039   case OMPD_barrier:
3040     assert(ClausesWithImplicit.empty() &&
3041            "No clauses are allowed for 'omp barrier' directive");
3042     assert(AStmt == nullptr &&
3043            "No associated statement allowed for 'omp barrier' directive");
3044     Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
3045     break;
3046   case OMPD_taskwait:
3047     assert(ClausesWithImplicit.empty() &&
3048            "No clauses are allowed for 'omp taskwait' directive");
3049     assert(AStmt == nullptr &&
3050            "No associated statement allowed for 'omp taskwait' directive");
3051     Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
3052     break;
3053   case OMPD_taskgroup:
3054     assert(ClausesWithImplicit.empty() &&
3055            "No clauses are allowed for 'omp taskgroup' directive");
3056     Res = ActOnOpenMPTaskgroupDirective(AStmt, StartLoc, EndLoc);
3057     break;
3058   case OMPD_flush:
3059     assert(AStmt == nullptr &&
3060            "No associated statement allowed for 'omp flush' directive");
3061     Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
3062     break;
3063   case OMPD_ordered:
3064     Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
3065                                       EndLoc);
3066     break;
3067   case OMPD_atomic:
3068     Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
3069                                      EndLoc);
3070     break;
3071   case OMPD_teams:
3072     Res =
3073         ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
3074     break;
3075   case OMPD_target:
3076     Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
3077                                      EndLoc);
3078     AllowedNameModifiers.push_back(OMPD_target);
3079     break;
3080   case OMPD_target_parallel:
3081     Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
3082                                              StartLoc, EndLoc);
3083     AllowedNameModifiers.push_back(OMPD_target);
3084     AllowedNameModifiers.push_back(OMPD_parallel);
3085     break;
3086   case OMPD_target_parallel_for:
3087     Res = ActOnOpenMPTargetParallelForDirective(
3088         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3089     AllowedNameModifiers.push_back(OMPD_target);
3090     AllowedNameModifiers.push_back(OMPD_parallel);
3091     break;
3092   case OMPD_cancellation_point:
3093     assert(ClausesWithImplicit.empty() &&
3094            "No clauses are allowed for 'omp cancellation point' directive");
3095     assert(AStmt == nullptr && "No associated statement allowed for 'omp "
3096                                "cancellation point' directive");
3097     Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
3098     break;
3099   case OMPD_cancel:
3100     assert(AStmt == nullptr &&
3101            "No associated statement allowed for 'omp cancel' directive");
3102     Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
3103                                      CancelRegion);
3104     AllowedNameModifiers.push_back(OMPD_cancel);
3105     break;
3106   case OMPD_target_data:
3107     Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
3108                                          EndLoc);
3109     AllowedNameModifiers.push_back(OMPD_target_data);
3110     break;
3111   case OMPD_target_enter_data:
3112     Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
3113                                               EndLoc);
3114     AllowedNameModifiers.push_back(OMPD_target_enter_data);
3115     break;
3116   case OMPD_target_exit_data:
3117     Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
3118                                              EndLoc);
3119     AllowedNameModifiers.push_back(OMPD_target_exit_data);
3120     break;
3121   case OMPD_taskloop:
3122     Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
3123                                        EndLoc, VarsWithInheritedDSA);
3124     AllowedNameModifiers.push_back(OMPD_taskloop);
3125     break;
3126   case OMPD_taskloop_simd:
3127     Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3128                                            EndLoc, VarsWithInheritedDSA);
3129     AllowedNameModifiers.push_back(OMPD_taskloop);
3130     break;
3131   case OMPD_distribute:
3132     Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
3133                                          EndLoc, VarsWithInheritedDSA);
3134     break;
3135   case OMPD_threadprivate:
3136     llvm_unreachable("OpenMP Directive is not allowed");
3137   case OMPD_unknown:
3138     llvm_unreachable("Unknown OpenMP directive");
3139   }
3140 
3141   for (auto P : VarsWithInheritedDSA) {
3142     Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
3143         << P.first << P.second->getSourceRange();
3144   }
3145   ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound;
3146 
3147   if (!AllowedNameModifiers.empty())
3148     ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
3149                  ErrorFound;
3150 
3151   if (ErrorFound)
3152     return StmtError();
3153   return Res;
3154 }
3155 
3156 StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
3157                                               Stmt *AStmt,
3158                                               SourceLocation StartLoc,
3159                                               SourceLocation EndLoc) {
3160   if (!AStmt)
3161     return StmtError();
3162 
3163   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
3164   // 1.2.2 OpenMP Language Terminology
3165   // Structured block - An executable statement with a single entry at the
3166   // top and a single exit at the bottom.
3167   // The point of exit cannot be a branch out of the structured block.
3168   // longjmp() and throw() must not violate the entry/exit criteria.
3169   CS->getCapturedDecl()->setNothrow();
3170 
3171   getCurFunction()->setHasBranchProtectedScope();
3172 
3173   return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
3174                                       DSAStack->isCancelRegion());
3175 }
3176 
3177 namespace {
3178 /// \brief Helper class for checking canonical form of the OpenMP loops and
3179 /// extracting iteration space of each loop in the loop nest, that will be used
3180 /// for IR generation.
3181 class OpenMPIterationSpaceChecker {
3182   /// \brief Reference to Sema.
3183   Sema &SemaRef;
3184   /// \brief A location for diagnostics (when there is no some better location).
3185   SourceLocation DefaultLoc;
3186   /// \brief A location for diagnostics (when increment is not compatible).
3187   SourceLocation ConditionLoc;
3188   /// \brief A source location for referring to loop init later.
3189   SourceRange InitSrcRange;
3190   /// \brief A source location for referring to condition later.
3191   SourceRange ConditionSrcRange;
3192   /// \brief A source location for referring to increment later.
3193   SourceRange IncrementSrcRange;
3194   /// \brief Loop variable.
3195   VarDecl *Var;
3196   /// \brief Reference to loop variable.
3197   DeclRefExpr *VarRef;
3198   /// \brief Lower bound (initializer for the var).
3199   Expr *LB;
3200   /// \brief Upper bound.
3201   Expr *UB;
3202   /// \brief Loop step (increment).
3203   Expr *Step;
3204   /// \brief This flag is true when condition is one of:
3205   ///   Var <  UB
3206   ///   Var <= UB
3207   ///   UB  >  Var
3208   ///   UB  >= Var
3209   bool TestIsLessOp;
3210   /// \brief This flag is true when condition is strict ( < or > ).
3211   bool TestIsStrictOp;
3212   /// \brief This flag is true when step is subtracted on each iteration.
3213   bool SubtractStep;
3214 
3215 public:
3216   OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
3217       : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc),
3218         InitSrcRange(SourceRange()), ConditionSrcRange(SourceRange()),
3219         IncrementSrcRange(SourceRange()), Var(nullptr), VarRef(nullptr),
3220         LB(nullptr), UB(nullptr), Step(nullptr), TestIsLessOp(false),
3221         TestIsStrictOp(false), SubtractStep(false) {}
3222   /// \brief Check init-expr for canonical loop form and save loop counter
3223   /// variable - #Var and its initialization value - #LB.
3224   bool CheckInit(Stmt *S, bool EmitDiags = true);
3225   /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags
3226   /// for less/greater and for strict/non-strict comparison.
3227   bool CheckCond(Expr *S);
3228   /// \brief Check incr-expr for canonical loop form and return true if it
3229   /// does not conform, otherwise save loop step (#Step).
3230   bool CheckInc(Expr *S);
3231   /// \brief Return the loop counter variable.
3232   VarDecl *GetLoopVar() const { return Var; }
3233   /// \brief Return the reference expression to loop counter variable.
3234   DeclRefExpr *GetLoopVarRefExpr() const { return VarRef; }
3235   /// \brief Source range of the loop init.
3236   SourceRange GetInitSrcRange() const { return InitSrcRange; }
3237   /// \brief Source range of the loop condition.
3238   SourceRange GetConditionSrcRange() const { return ConditionSrcRange; }
3239   /// \brief Source range of the loop increment.
3240   SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; }
3241   /// \brief True if the step should be subtracted.
3242   bool ShouldSubtractStep() const { return SubtractStep; }
3243   /// \brief Build the expression to calculate the number of iterations.
3244   Expr *BuildNumIterations(Scope *S, const bool LimitedType) const;
3245   /// \brief Build the precondition expression for the loops.
3246   Expr *BuildPreCond(Scope *S, Expr *Cond) const;
3247   /// \brief Build reference expression to the counter be used for codegen.
3248   Expr *BuildCounterVar() const;
3249   /// \brief Build reference expression to the private counter be used for
3250   /// codegen.
3251   Expr *BuildPrivateCounterVar() const;
3252   /// \brief Build initization of the counter be used for codegen.
3253   Expr *BuildCounterInit() const;
3254   /// \brief Build step of the counter be used for codegen.
3255   Expr *BuildCounterStep() const;
3256   /// \brief Return true if any expression is dependent.
3257   bool Dependent() const;
3258 
3259 private:
3260   /// \brief Check the right-hand side of an assignment in the increment
3261   /// expression.
3262   bool CheckIncRHS(Expr *RHS);
3263   /// \brief Helper to set loop counter variable and its initializer.
3264   bool SetVarAndLB(VarDecl *NewVar, DeclRefExpr *NewVarRefExpr, Expr *NewLB);
3265   /// \brief Helper to set upper bound.
3266   bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, SourceRange SR,
3267              SourceLocation SL);
3268   /// \brief Helper to set loop increment.
3269   bool SetStep(Expr *NewStep, bool Subtract);
3270 };
3271 
3272 bool OpenMPIterationSpaceChecker::Dependent() const {
3273   if (!Var) {
3274     assert(!LB && !UB && !Step);
3275     return false;
3276   }
3277   return Var->getType()->isDependentType() || (LB && LB->isValueDependent()) ||
3278          (UB && UB->isValueDependent()) || (Step && Step->isValueDependent());
3279 }
3280 
3281 template <typename T>
3282 static T *getExprAsWritten(T *E) {
3283   if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(E))
3284     E = ExprTemp->getSubExpr();
3285 
3286   if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
3287     E = MTE->GetTemporaryExpr();
3288 
3289   while (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
3290     E = Binder->getSubExpr();
3291 
3292   if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
3293     E = ICE->getSubExprAsWritten();
3294   return E->IgnoreParens();
3295 }
3296 
3297 bool OpenMPIterationSpaceChecker::SetVarAndLB(VarDecl *NewVar,
3298                                               DeclRefExpr *NewVarRefExpr,
3299                                               Expr *NewLB) {
3300   // State consistency checking to ensure correct usage.
3301   assert(Var == nullptr && LB == nullptr && VarRef == nullptr &&
3302          UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
3303   if (!NewVar || !NewLB)
3304     return true;
3305   Var = NewVar;
3306   VarRef = NewVarRefExpr;
3307   if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
3308     if (const CXXConstructorDecl *Ctor = CE->getConstructor())
3309       if ((Ctor->isCopyOrMoveConstructor() ||
3310            Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
3311           CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
3312         NewLB = CE->getArg(0)->IgnoreParenImpCasts();
3313   LB = NewLB;
3314   return false;
3315 }
3316 
3317 bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp,
3318                                         SourceRange SR, SourceLocation SL) {
3319   // State consistency checking to ensure correct usage.
3320   assert(Var != nullptr && LB != nullptr && UB == nullptr && Step == nullptr &&
3321          !TestIsLessOp && !TestIsStrictOp);
3322   if (!NewUB)
3323     return true;
3324   UB = NewUB;
3325   TestIsLessOp = LessOp;
3326   TestIsStrictOp = StrictOp;
3327   ConditionSrcRange = SR;
3328   ConditionLoc = SL;
3329   return false;
3330 }
3331 
3332 bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) {
3333   // State consistency checking to ensure correct usage.
3334   assert(Var != nullptr && LB != nullptr && Step == nullptr);
3335   if (!NewStep)
3336     return true;
3337   if (!NewStep->isValueDependent()) {
3338     // Check that the step is integer expression.
3339     SourceLocation StepLoc = NewStep->getLocStart();
3340     ExprResult Val =
3341         SemaRef.PerformOpenMPImplicitIntegerConversion(StepLoc, NewStep);
3342     if (Val.isInvalid())
3343       return true;
3344     NewStep = Val.get();
3345 
3346     // OpenMP [2.6, Canonical Loop Form, Restrictions]
3347     //  If test-expr is of form var relational-op b and relational-op is < or
3348     //  <= then incr-expr must cause var to increase on each iteration of the
3349     //  loop. If test-expr is of form var relational-op b and relational-op is
3350     //  > or >= then incr-expr must cause var to decrease on each iteration of
3351     //  the loop.
3352     //  If test-expr is of form b relational-op var and relational-op is < or
3353     //  <= then incr-expr must cause var to decrease on each iteration of the
3354     //  loop. If test-expr is of form b relational-op var and relational-op is
3355     //  > or >= then incr-expr must cause var to increase on each iteration of
3356     //  the loop.
3357     llvm::APSInt Result;
3358     bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
3359     bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
3360     bool IsConstNeg =
3361         IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
3362     bool IsConstPos =
3363         IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
3364     bool IsConstZero = IsConstant && !Result.getBoolValue();
3365     if (UB && (IsConstZero ||
3366                (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
3367                              : (IsConstPos || (IsUnsigned && !Subtract))))) {
3368       SemaRef.Diag(NewStep->getExprLoc(),
3369                    diag::err_omp_loop_incr_not_compatible)
3370           << Var << TestIsLessOp << NewStep->getSourceRange();
3371       SemaRef.Diag(ConditionLoc,
3372                    diag::note_omp_loop_cond_requres_compatible_incr)
3373           << TestIsLessOp << ConditionSrcRange;
3374       return true;
3375     }
3376     if (TestIsLessOp == Subtract) {
3377       NewStep = SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus,
3378                                              NewStep).get();
3379       Subtract = !Subtract;
3380     }
3381   }
3382 
3383   Step = NewStep;
3384   SubtractStep = Subtract;
3385   return false;
3386 }
3387 
3388 bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S, bool EmitDiags) {
3389   // Check init-expr for canonical loop form and save loop counter
3390   // variable - #Var and its initialization value - #LB.
3391   // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
3392   //   var = lb
3393   //   integer-type var = lb
3394   //   random-access-iterator-type var = lb
3395   //   pointer-type var = lb
3396   //
3397   if (!S) {
3398     if (EmitDiags) {
3399       SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
3400     }
3401     return true;
3402   }
3403   InitSrcRange = S->getSourceRange();
3404   if (Expr *E = dyn_cast<Expr>(S))
3405     S = E->IgnoreParens();
3406   if (auto BO = dyn_cast<BinaryOperator>(S)) {
3407     if (BO->getOpcode() == BO_Assign)
3408       if (auto DRE = dyn_cast<DeclRefExpr>(BO->getLHS()->IgnoreParens()))
3409         return SetVarAndLB(dyn_cast<VarDecl>(DRE->getDecl()), DRE,
3410                            BO->getRHS());
3411   } else if (auto DS = dyn_cast<DeclStmt>(S)) {
3412     if (DS->isSingleDecl()) {
3413       if (auto Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
3414         if (Var->hasInit() && !Var->getType()->isReferenceType()) {
3415           // Accept non-canonical init form here but emit ext. warning.
3416           if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
3417             SemaRef.Diag(S->getLocStart(),
3418                          diag::ext_omp_loop_not_canonical_init)
3419                 << S->getSourceRange();
3420           return SetVarAndLB(Var, nullptr, Var->getInit());
3421         }
3422       }
3423     }
3424   } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S))
3425     if (CE->getOperator() == OO_Equal)
3426       if (auto DRE = dyn_cast<DeclRefExpr>(CE->getArg(0)))
3427         return SetVarAndLB(dyn_cast<VarDecl>(DRE->getDecl()), DRE,
3428                            CE->getArg(1));
3429 
3430   if (EmitDiags) {
3431     SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init)
3432         << S->getSourceRange();
3433   }
3434   return true;
3435 }
3436 
3437 /// \brief Ignore parenthesizes, implicit casts, copy constructor and return the
3438 /// variable (which may be the loop variable) if possible.
3439 static const VarDecl *GetInitVarDecl(const Expr *E) {
3440   if (!E)
3441     return nullptr;
3442   E = getExprAsWritten(E);
3443   if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
3444     if (const CXXConstructorDecl *Ctor = CE->getConstructor())
3445       if ((Ctor->isCopyOrMoveConstructor() ||
3446            Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
3447           CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
3448         E = CE->getArg(0)->IgnoreParenImpCasts();
3449   auto DRE = dyn_cast_or_null<DeclRefExpr>(E);
3450   if (!DRE)
3451     return nullptr;
3452   return dyn_cast<VarDecl>(DRE->getDecl());
3453 }
3454 
3455 bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) {
3456   // Check test-expr for canonical form, save upper-bound UB, flags for
3457   // less/greater and for strict/non-strict comparison.
3458   // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3459   //   var relational-op b
3460   //   b relational-op var
3461   //
3462   if (!S) {
3463     SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << Var;
3464     return true;
3465   }
3466   S = getExprAsWritten(S);
3467   SourceLocation CondLoc = S->getLocStart();
3468   if (auto BO = dyn_cast<BinaryOperator>(S)) {
3469     if (BO->isRelationalOp()) {
3470       if (GetInitVarDecl(BO->getLHS()) == Var)
3471         return SetUB(BO->getRHS(),
3472                      (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
3473                      (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3474                      BO->getSourceRange(), BO->getOperatorLoc());
3475       if (GetInitVarDecl(BO->getRHS()) == Var)
3476         return SetUB(BO->getLHS(),
3477                      (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
3478                      (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3479                      BO->getSourceRange(), BO->getOperatorLoc());
3480     }
3481   } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S)) {
3482     if (CE->getNumArgs() == 2) {
3483       auto Op = CE->getOperator();
3484       switch (Op) {
3485       case OO_Greater:
3486       case OO_GreaterEqual:
3487       case OO_Less:
3488       case OO_LessEqual:
3489         if (GetInitVarDecl(CE->getArg(0)) == Var)
3490           return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
3491                        Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3492                        CE->getOperatorLoc());
3493         if (GetInitVarDecl(CE->getArg(1)) == Var)
3494           return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
3495                        Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3496                        CE->getOperatorLoc());
3497         break;
3498       default:
3499         break;
3500       }
3501     }
3502   }
3503   SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
3504       << S->getSourceRange() << Var;
3505   return true;
3506 }
3507 
3508 bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) {
3509   // RHS of canonical loop form increment can be:
3510   //   var + incr
3511   //   incr + var
3512   //   var - incr
3513   //
3514   RHS = RHS->IgnoreParenImpCasts();
3515   if (auto BO = dyn_cast<BinaryOperator>(RHS)) {
3516     if (BO->isAdditiveOp()) {
3517       bool IsAdd = BO->getOpcode() == BO_Add;
3518       if (GetInitVarDecl(BO->getLHS()) == Var)
3519         return SetStep(BO->getRHS(), !IsAdd);
3520       if (IsAdd && GetInitVarDecl(BO->getRHS()) == Var)
3521         return SetStep(BO->getLHS(), false);
3522     }
3523   } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
3524     bool IsAdd = CE->getOperator() == OO_Plus;
3525     if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
3526       if (GetInitVarDecl(CE->getArg(0)) == Var)
3527         return SetStep(CE->getArg(1), !IsAdd);
3528       if (IsAdd && GetInitVarDecl(CE->getArg(1)) == Var)
3529         return SetStep(CE->getArg(0), false);
3530     }
3531   }
3532   SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr)
3533       << RHS->getSourceRange() << Var;
3534   return true;
3535 }
3536 
3537 bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) {
3538   // Check incr-expr for canonical loop form and return true if it
3539   // does not conform.
3540   // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3541   //   ++var
3542   //   var++
3543   //   --var
3544   //   var--
3545   //   var += incr
3546   //   var -= incr
3547   //   var = var + incr
3548   //   var = incr + var
3549   //   var = var - incr
3550   //
3551   if (!S) {
3552     SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << Var;
3553     return true;
3554   }
3555   IncrementSrcRange = S->getSourceRange();
3556   S = S->IgnoreParens();
3557   if (auto UO = dyn_cast<UnaryOperator>(S)) {
3558     if (UO->isIncrementDecrementOp() && GetInitVarDecl(UO->getSubExpr()) == Var)
3559       return SetStep(
3560           SemaRef.ActOnIntegerConstant(UO->getLocStart(),
3561                                        (UO->isDecrementOp() ? -1 : 1)).get(),
3562           false);
3563   } else if (auto BO = dyn_cast<BinaryOperator>(S)) {
3564     switch (BO->getOpcode()) {
3565     case BO_AddAssign:
3566     case BO_SubAssign:
3567       if (GetInitVarDecl(BO->getLHS()) == Var)
3568         return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
3569       break;
3570     case BO_Assign:
3571       if (GetInitVarDecl(BO->getLHS()) == Var)
3572         return CheckIncRHS(BO->getRHS());
3573       break;
3574     default:
3575       break;
3576     }
3577   } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S)) {
3578     switch (CE->getOperator()) {
3579     case OO_PlusPlus:
3580     case OO_MinusMinus:
3581       if (GetInitVarDecl(CE->getArg(0)) == Var)
3582         return SetStep(
3583             SemaRef.ActOnIntegerConstant(
3584                         CE->getLocStart(),
3585                         ((CE->getOperator() == OO_MinusMinus) ? -1 : 1)).get(),
3586             false);
3587       break;
3588     case OO_PlusEqual:
3589     case OO_MinusEqual:
3590       if (GetInitVarDecl(CE->getArg(0)) == Var)
3591         return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
3592       break;
3593     case OO_Equal:
3594       if (GetInitVarDecl(CE->getArg(0)) == Var)
3595         return CheckIncRHS(CE->getArg(1));
3596       break;
3597     default:
3598       break;
3599     }
3600   }
3601   SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr)
3602       << S->getSourceRange() << Var;
3603   return true;
3604 }
3605 
3606 namespace {
3607 // Transform variables declared in GNU statement expressions to new ones to
3608 // avoid crash on codegen.
3609 class TransformToNewDefs : public TreeTransform<TransformToNewDefs> {
3610   typedef TreeTransform<TransformToNewDefs> BaseTransform;
3611 
3612 public:
3613   TransformToNewDefs(Sema &SemaRef) : BaseTransform(SemaRef) {}
3614 
3615   Decl *TransformDefinition(SourceLocation Loc, Decl *D) {
3616     if (auto *VD = cast<VarDecl>(D))
3617       if (!isa<ParmVarDecl>(D) && !isa<VarTemplateSpecializationDecl>(D) &&
3618           !isa<ImplicitParamDecl>(D)) {
3619         auto *NewVD = VarDecl::Create(
3620             SemaRef.Context, VD->getDeclContext(), VD->getLocStart(),
3621             VD->getLocation(), VD->getIdentifier(), VD->getType(),
3622             VD->getTypeSourceInfo(), VD->getStorageClass());
3623         NewVD->setTSCSpec(VD->getTSCSpec());
3624         NewVD->setInit(VD->getInit());
3625         NewVD->setInitStyle(VD->getInitStyle());
3626         NewVD->setExceptionVariable(VD->isExceptionVariable());
3627         NewVD->setNRVOVariable(VD->isNRVOVariable());
3628         NewVD->setCXXForRangeDecl(VD->isCXXForRangeDecl());
3629         NewVD->setConstexpr(VD->isConstexpr());
3630         NewVD->setInitCapture(VD->isInitCapture());
3631         NewVD->setPreviousDeclInSameBlockScope(
3632             VD->isPreviousDeclInSameBlockScope());
3633         VD->getDeclContext()->addHiddenDecl(NewVD);
3634         if (VD->hasAttrs())
3635           NewVD->setAttrs(VD->getAttrs());
3636         transformedLocalDecl(VD, NewVD);
3637         return NewVD;
3638       }
3639     return BaseTransform::TransformDefinition(Loc, D);
3640   }
3641 
3642   ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
3643     if (auto *NewD = TransformDecl(E->getExprLoc(), E->getDecl()))
3644       if (E->getDecl() != NewD) {
3645         NewD->setReferenced();
3646         NewD->markUsed(SemaRef.Context);
3647         return DeclRefExpr::Create(
3648             SemaRef.Context, E->getQualifierLoc(), E->getTemplateKeywordLoc(),
3649             cast<ValueDecl>(NewD), E->refersToEnclosingVariableOrCapture(),
3650             E->getNameInfo(), E->getType(), E->getValueKind());
3651       }
3652     return BaseTransform::TransformDeclRefExpr(E);
3653   }
3654 };
3655 }
3656 
3657 /// \brief Build the expression to calculate the number of iterations.
3658 Expr *
3659 OpenMPIterationSpaceChecker::BuildNumIterations(Scope *S,
3660                                                 const bool LimitedType) const {
3661   TransformToNewDefs Transform(SemaRef);
3662   ExprResult Diff;
3663   auto VarType = Var->getType().getNonReferenceType();
3664   if (VarType->isIntegerType() || VarType->isPointerType() ||
3665       SemaRef.getLangOpts().CPlusPlus) {
3666     // Upper - Lower
3667     auto *UBExpr = TestIsLessOp ? UB : LB;
3668     auto *LBExpr = TestIsLessOp ? LB : UB;
3669     Expr *Upper = Transform.TransformExpr(UBExpr).get();
3670     Expr *Lower = Transform.TransformExpr(LBExpr).get();
3671     if (!Upper || !Lower)
3672       return nullptr;
3673     if (!SemaRef.Context.hasSameType(Upper->getType(), UBExpr->getType())) {
3674       Upper = SemaRef
3675                   .PerformImplicitConversion(Upper, UBExpr->getType(),
3676                                              Sema::AA_Converting,
3677                                              /*AllowExplicit=*/true)
3678                   .get();
3679     }
3680     if (!SemaRef.Context.hasSameType(Lower->getType(), LBExpr->getType())) {
3681       Lower = SemaRef
3682                   .PerformImplicitConversion(Lower, LBExpr->getType(),
3683                                              Sema::AA_Converting,
3684                                              /*AllowExplicit=*/true)
3685                   .get();
3686     }
3687     if (!Upper || !Lower)
3688       return nullptr;
3689 
3690     Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
3691 
3692     if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
3693       // BuildBinOp already emitted error, this one is to point user to upper
3694       // and lower bound, and to tell what is passed to 'operator-'.
3695       SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx)
3696           << Upper->getSourceRange() << Lower->getSourceRange();
3697       return nullptr;
3698     }
3699   }
3700 
3701   if (!Diff.isUsable())
3702     return nullptr;
3703 
3704   // Upper - Lower [- 1]
3705   if (TestIsStrictOp)
3706     Diff = SemaRef.BuildBinOp(
3707         S, DefaultLoc, BO_Sub, Diff.get(),
3708         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
3709   if (!Diff.isUsable())
3710     return nullptr;
3711 
3712   // Upper - Lower [- 1] + Step
3713   auto *StepNoImp = Step->IgnoreImplicit();
3714   auto NewStep = Transform.TransformExpr(StepNoImp);
3715   if (NewStep.isInvalid())
3716     return nullptr;
3717   if (!SemaRef.Context.hasSameType(NewStep.get()->getType(),
3718                                    StepNoImp->getType())) {
3719     NewStep = SemaRef.PerformImplicitConversion(
3720         NewStep.get(), StepNoImp->getType(), Sema::AA_Converting,
3721         /*AllowExplicit=*/true);
3722     if (NewStep.isInvalid())
3723       return nullptr;
3724   }
3725   Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
3726   if (!Diff.isUsable())
3727     return nullptr;
3728 
3729   // Parentheses (for dumping/debugging purposes only).
3730   Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
3731   if (!Diff.isUsable())
3732     return nullptr;
3733 
3734   // (Upper - Lower [- 1] + Step) / Step
3735   NewStep = Transform.TransformExpr(StepNoImp);
3736   if (NewStep.isInvalid())
3737     return nullptr;
3738   if (!SemaRef.Context.hasSameType(NewStep.get()->getType(),
3739                                    StepNoImp->getType())) {
3740     NewStep = SemaRef.PerformImplicitConversion(
3741         NewStep.get(), StepNoImp->getType(), Sema::AA_Converting,
3742         /*AllowExplicit=*/true);
3743     if (NewStep.isInvalid())
3744       return nullptr;
3745   }
3746   Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
3747   if (!Diff.isUsable())
3748     return nullptr;
3749 
3750   // OpenMP runtime requires 32-bit or 64-bit loop variables.
3751   QualType Type = Diff.get()->getType();
3752   auto &C = SemaRef.Context;
3753   bool UseVarType = VarType->hasIntegerRepresentation() &&
3754                     C.getTypeSize(Type) > C.getTypeSize(VarType);
3755   if (!Type->isIntegerType() || UseVarType) {
3756     unsigned NewSize =
3757         UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
3758     bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
3759                                : Type->hasSignedIntegerRepresentation();
3760     Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
3761     if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
3762       Diff = SemaRef.PerformImplicitConversion(
3763           Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
3764       if (!Diff.isUsable())
3765         return nullptr;
3766     }
3767   }
3768   if (LimitedType) {
3769     unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
3770     if (NewSize != C.getTypeSize(Type)) {
3771       if (NewSize < C.getTypeSize(Type)) {
3772         assert(NewSize == 64 && "incorrect loop var size");
3773         SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
3774             << InitSrcRange << ConditionSrcRange;
3775       }
3776       QualType NewType = C.getIntTypeForBitwidth(
3777           NewSize, Type->hasSignedIntegerRepresentation() ||
3778                        C.getTypeSize(Type) < NewSize);
3779       if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
3780         Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
3781                                                  Sema::AA_Converting, true);
3782         if (!Diff.isUsable())
3783           return nullptr;
3784       }
3785     }
3786   }
3787 
3788   return Diff.get();
3789 }
3790 
3791 Expr *OpenMPIterationSpaceChecker::BuildPreCond(Scope *S, Expr *Cond) const {
3792   // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
3793   bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
3794   SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
3795   TransformToNewDefs Transform(SemaRef);
3796 
3797   auto NewLB = Transform.TransformExpr(LB);
3798   auto NewUB = Transform.TransformExpr(UB);
3799   if (NewLB.isInvalid() || NewUB.isInvalid())
3800     return Cond;
3801   if (!SemaRef.Context.hasSameType(NewLB.get()->getType(), LB->getType())) {
3802     NewLB = SemaRef.PerformImplicitConversion(NewLB.get(), LB->getType(),
3803                                               Sema::AA_Converting,
3804                                               /*AllowExplicit=*/true);
3805   }
3806   if (!SemaRef.Context.hasSameType(NewUB.get()->getType(), UB->getType())) {
3807     NewUB = SemaRef.PerformImplicitConversion(NewUB.get(), UB->getType(),
3808                                               Sema::AA_Converting,
3809                                               /*AllowExplicit=*/true);
3810   }
3811   if (NewLB.isInvalid() || NewUB.isInvalid())
3812     return Cond;
3813   auto CondExpr = SemaRef.BuildBinOp(
3814       S, DefaultLoc, TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE)
3815                                   : (TestIsStrictOp ? BO_GT : BO_GE),
3816       NewLB.get(), NewUB.get());
3817   if (CondExpr.isUsable()) {
3818     if (!SemaRef.Context.hasSameType(CondExpr.get()->getType(),
3819                                      SemaRef.Context.BoolTy))
3820       CondExpr = SemaRef.PerformImplicitConversion(
3821           CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
3822           /*AllowExplicit=*/true);
3823   }
3824   SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
3825   // Otherwise use original loop conditon and evaluate it in runtime.
3826   return CondExpr.isUsable() ? CondExpr.get() : Cond;
3827 }
3828 
3829 /// \brief Build reference expression to the counter be used for codegen.
3830 Expr *OpenMPIterationSpaceChecker::BuildCounterVar() const {
3831   return buildDeclRefExpr(SemaRef, Var, Var->getType().getNonReferenceType(),
3832                           DefaultLoc);
3833 }
3834 
3835 Expr *OpenMPIterationSpaceChecker::BuildPrivateCounterVar() const {
3836   if (Var && !Var->isInvalidDecl()) {
3837     auto Type = Var->getType().getNonReferenceType();
3838     auto *PrivateVar =
3839         buildVarDecl(SemaRef, DefaultLoc, Type, Var->getName(),
3840                      Var->hasAttrs() ? &Var->getAttrs() : nullptr);
3841     if (PrivateVar->isInvalidDecl())
3842       return nullptr;
3843     return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
3844   }
3845   return nullptr;
3846 }
3847 
3848 /// \brief Build initization of the counter be used for codegen.
3849 Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; }
3850 
3851 /// \brief Build step of the counter be used for codegen.
3852 Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; }
3853 
3854 /// \brief Iteration space of a single for loop.
3855 struct LoopIterationSpace {
3856   /// \brief Condition of the loop.
3857   Expr *PreCond;
3858   /// \brief This expression calculates the number of iterations in the loop.
3859   /// It is always possible to calculate it before starting the loop.
3860   Expr *NumIterations;
3861   /// \brief The loop counter variable.
3862   Expr *CounterVar;
3863   /// \brief Private loop counter variable.
3864   Expr *PrivateCounterVar;
3865   /// \brief This is initializer for the initial value of #CounterVar.
3866   Expr *CounterInit;
3867   /// \brief This is step for the #CounterVar used to generate its update:
3868   /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
3869   Expr *CounterStep;
3870   /// \brief Should step be subtracted?
3871   bool Subtract;
3872   /// \brief Source range of the loop init.
3873   SourceRange InitSrcRange;
3874   /// \brief Source range of the loop condition.
3875   SourceRange CondSrcRange;
3876   /// \brief Source range of the loop increment.
3877   SourceRange IncSrcRange;
3878 };
3879 
3880 } // namespace
3881 
3882 void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
3883   assert(getLangOpts().OpenMP && "OpenMP is not active.");
3884   assert(Init && "Expected loop in canonical form.");
3885   unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
3886   if (AssociatedLoops > 0 &&
3887       isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
3888     OpenMPIterationSpaceChecker ISC(*this, ForLoc);
3889     if (!ISC.CheckInit(Init, /*EmitDiags=*/false))
3890       DSAStack->addLoopControlVariable(ISC.GetLoopVar());
3891     DSAStack->setAssociatedLoops(AssociatedLoops - 1);
3892   }
3893 }
3894 
3895 /// \brief Called on a for stmt to check and extract its iteration space
3896 /// for further processing (such as collapsing).
3897 static bool CheckOpenMPIterationSpace(
3898     OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
3899     unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
3900     Expr *CollapseLoopCountExpr, Expr *OrderedLoopCountExpr,
3901     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
3902     LoopIterationSpace &ResultIterSpace) {
3903   // OpenMP [2.6, Canonical Loop Form]
3904   //   for (init-expr; test-expr; incr-expr) structured-block
3905   auto For = dyn_cast_or_null<ForStmt>(S);
3906   if (!For) {
3907     SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for)
3908         << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
3909         << getOpenMPDirectiveName(DKind) << NestedLoopCount
3910         << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
3911     if (NestedLoopCount > 1) {
3912       if (CollapseLoopCountExpr && OrderedLoopCountExpr)
3913         SemaRef.Diag(DSA.getConstructLoc(),
3914                      diag::note_omp_collapse_ordered_expr)
3915             << 2 << CollapseLoopCountExpr->getSourceRange()
3916             << OrderedLoopCountExpr->getSourceRange();
3917       else if (CollapseLoopCountExpr)
3918         SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
3919                      diag::note_omp_collapse_ordered_expr)
3920             << 0 << CollapseLoopCountExpr->getSourceRange();
3921       else
3922         SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
3923                      diag::note_omp_collapse_ordered_expr)
3924             << 1 << OrderedLoopCountExpr->getSourceRange();
3925     }
3926     return true;
3927   }
3928   assert(For->getBody());
3929 
3930   OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
3931 
3932   // Check init.
3933   auto Init = For->getInit();
3934   if (ISC.CheckInit(Init)) {
3935     return true;
3936   }
3937 
3938   bool HasErrors = false;
3939 
3940   // Check loop variable's type.
3941   auto Var = ISC.GetLoopVar();
3942 
3943   // OpenMP [2.6, Canonical Loop Form]
3944   // Var is one of the following:
3945   //   A variable of signed or unsigned integer type.
3946   //   For C++, a variable of a random access iterator type.
3947   //   For C, a variable of a pointer type.
3948   auto VarType = Var->getType().getNonReferenceType();
3949   if (!VarType->isDependentType() && !VarType->isIntegerType() &&
3950       !VarType->isPointerType() &&
3951       !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
3952     SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type)
3953         << SemaRef.getLangOpts().CPlusPlus;
3954     HasErrors = true;
3955   }
3956 
3957   // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in a
3958   // Construct
3959   // The loop iteration variable(s) in the associated for-loop(s) of a for or
3960   // parallel for construct is (are) private.
3961   // The loop iteration variable in the associated for-loop of a simd construct
3962   // with just one associated for-loop is linear with a constant-linear-step
3963   // that is the increment of the associated for-loop.
3964   // Exclude loop var from the list of variables with implicitly defined data
3965   // sharing attributes.
3966   VarsWithImplicitDSA.erase(Var);
3967 
3968   // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced in
3969   // a Construct, C/C++].
3970   // The loop iteration variable in the associated for-loop of a simd construct
3971   // with just one associated for-loop may be listed in a linear clause with a
3972   // constant-linear-step that is the increment of the associated for-loop.
3973   // The loop iteration variable(s) in the associated for-loop(s) of a for or
3974   // parallel for construct may be listed in a private or lastprivate clause.
3975   DSAStackTy::DSAVarData DVar = DSA.getTopDSA(Var, false);
3976   auto LoopVarRefExpr = ISC.GetLoopVarRefExpr();
3977   // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
3978   // declared in the loop and it is predetermined as a private.
3979   auto PredeterminedCKind =
3980       isOpenMPSimdDirective(DKind)
3981           ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
3982           : OMPC_private;
3983   if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
3984         DVar.CKind != PredeterminedCKind) ||
3985        ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
3986          isOpenMPDistributeDirective(DKind)) &&
3987         !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
3988         DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
3989       (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
3990     SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa)
3991         << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
3992         << getOpenMPClauseName(PredeterminedCKind);
3993     if (DVar.RefExpr == nullptr)
3994       DVar.CKind = PredeterminedCKind;
3995     ReportOriginalDSA(SemaRef, &DSA, Var, DVar, /*IsLoopIterVar=*/true);
3996     HasErrors = true;
3997   } else if (LoopVarRefExpr != nullptr) {
3998     // Make the loop iteration variable private (for worksharing constructs),
3999     // linear (for simd directives with the only one associated loop) or
4000     // lastprivate (for simd directives with several collapsed or ordered
4001     // loops).
4002     if (DVar.CKind == OMPC_unknown)
4003       DVar = DSA.hasDSA(Var, isOpenMPPrivate, MatchesAlways(),
4004                         /*FromParent=*/false);
4005     DSA.addDSA(Var, LoopVarRefExpr, PredeterminedCKind);
4006   }
4007 
4008   assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
4009 
4010   // Check test-expr.
4011   HasErrors |= ISC.CheckCond(For->getCond());
4012 
4013   // Check incr-expr.
4014   HasErrors |= ISC.CheckInc(For->getInc());
4015 
4016   if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
4017     return HasErrors;
4018 
4019   // Build the loop's iteration space representation.
4020   ResultIterSpace.PreCond = ISC.BuildPreCond(DSA.getCurScope(), For->getCond());
4021   ResultIterSpace.NumIterations = ISC.BuildNumIterations(
4022       DSA.getCurScope(), (isOpenMPWorksharingDirective(DKind) ||
4023                           isOpenMPTaskLoopDirective(DKind) ||
4024                           isOpenMPDistributeDirective(DKind)));
4025   ResultIterSpace.CounterVar = ISC.BuildCounterVar();
4026   ResultIterSpace.PrivateCounterVar = ISC.BuildPrivateCounterVar();
4027   ResultIterSpace.CounterInit = ISC.BuildCounterInit();
4028   ResultIterSpace.CounterStep = ISC.BuildCounterStep();
4029   ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange();
4030   ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange();
4031   ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange();
4032   ResultIterSpace.Subtract = ISC.ShouldSubtractStep();
4033 
4034   HasErrors |= (ResultIterSpace.PreCond == nullptr ||
4035                 ResultIterSpace.NumIterations == nullptr ||
4036                 ResultIterSpace.CounterVar == nullptr ||
4037                 ResultIterSpace.PrivateCounterVar == nullptr ||
4038                 ResultIterSpace.CounterInit == nullptr ||
4039                 ResultIterSpace.CounterStep == nullptr);
4040 
4041   return HasErrors;
4042 }
4043 
4044 /// \brief Build 'VarRef = Start.
4045 static ExprResult BuildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc,
4046                                    ExprResult VarRef, ExprResult Start) {
4047   TransformToNewDefs Transform(SemaRef);
4048   // Build 'VarRef = Start.
4049   auto *StartNoImp = Start.get()->IgnoreImplicit();
4050   auto NewStart = Transform.TransformExpr(StartNoImp);
4051   if (NewStart.isInvalid())
4052     return ExprError();
4053   if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
4054                                    StartNoImp->getType())) {
4055     NewStart = SemaRef.PerformImplicitConversion(
4056         NewStart.get(), StartNoImp->getType(), Sema::AA_Converting,
4057         /*AllowExplicit=*/true);
4058     if (NewStart.isInvalid())
4059       return ExprError();
4060   }
4061   if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
4062                                    VarRef.get()->getType())) {
4063     NewStart = SemaRef.PerformImplicitConversion(
4064         NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
4065         /*AllowExplicit=*/true);
4066     if (!NewStart.isUsable())
4067       return ExprError();
4068   }
4069 
4070   auto Init =
4071       SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
4072   return Init;
4073 }
4074 
4075 /// \brief Build 'VarRef = Start + Iter * Step'.
4076 static ExprResult BuildCounterUpdate(Sema &SemaRef, Scope *S,
4077                                      SourceLocation Loc, ExprResult VarRef,
4078                                      ExprResult Start, ExprResult Iter,
4079                                      ExprResult Step, bool Subtract) {
4080   // Add parentheses (for debugging purposes only).
4081   Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
4082   if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
4083       !Step.isUsable())
4084     return ExprError();
4085 
4086   auto *StepNoImp = Step.get()->IgnoreImplicit();
4087   TransformToNewDefs Transform(SemaRef);
4088   auto NewStep = Transform.TransformExpr(StepNoImp);
4089   if (NewStep.isInvalid())
4090     return ExprError();
4091   if (!SemaRef.Context.hasSameType(NewStep.get()->getType(),
4092                                    StepNoImp->getType())) {
4093     NewStep = SemaRef.PerformImplicitConversion(
4094         NewStep.get(), StepNoImp->getType(), Sema::AA_Converting,
4095         /*AllowExplicit=*/true);
4096     if (NewStep.isInvalid())
4097       return ExprError();
4098   }
4099   ExprResult Update =
4100       SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
4101   if (!Update.isUsable())
4102     return ExprError();
4103 
4104   // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
4105   // 'VarRef = Start (+|-) Iter * Step'.
4106   auto *StartNoImp = Start.get()->IgnoreImplicit();
4107   auto NewStart = Transform.TransformExpr(StartNoImp);
4108   if (NewStart.isInvalid())
4109     return ExprError();
4110   if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
4111                                    StartNoImp->getType())) {
4112     NewStart = SemaRef.PerformImplicitConversion(
4113         NewStart.get(), StartNoImp->getType(), Sema::AA_Converting,
4114         /*AllowExplicit=*/true);
4115     if (NewStart.isInvalid())
4116       return ExprError();
4117   }
4118 
4119   // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
4120   ExprResult SavedUpdate = Update;
4121   ExprResult UpdateVal;
4122   if (VarRef.get()->getType()->isOverloadableType() ||
4123       NewStart.get()->getType()->isOverloadableType() ||
4124       Update.get()->getType()->isOverloadableType()) {
4125     bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
4126     SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
4127     Update =
4128         SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
4129     if (Update.isUsable()) {
4130       UpdateVal =
4131           SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
4132                              VarRef.get(), SavedUpdate.get());
4133       if (UpdateVal.isUsable()) {
4134         Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
4135                                             UpdateVal.get());
4136       }
4137     }
4138     SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
4139   }
4140 
4141   // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
4142   if (!Update.isUsable() || !UpdateVal.isUsable()) {
4143     Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
4144                                 NewStart.get(), SavedUpdate.get());
4145     if (!Update.isUsable())
4146       return ExprError();
4147 
4148     if (!SemaRef.Context.hasSameType(Update.get()->getType(),
4149                                      VarRef.get()->getType())) {
4150       Update = SemaRef.PerformImplicitConversion(
4151           Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
4152       if (!Update.isUsable())
4153         return ExprError();
4154     }
4155 
4156     Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
4157   }
4158   return Update;
4159 }
4160 
4161 /// \brief Convert integer expression \a E to make it have at least \a Bits
4162 /// bits.
4163 static ExprResult WidenIterationCount(unsigned Bits, Expr *E,
4164                                       Sema &SemaRef) {
4165   if (E == nullptr)
4166     return ExprError();
4167   auto &C = SemaRef.Context;
4168   QualType OldType = E->getType();
4169   unsigned HasBits = C.getTypeSize(OldType);
4170   if (HasBits >= Bits)
4171     return ExprResult(E);
4172   // OK to convert to signed, because new type has more bits than old.
4173   QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
4174   return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
4175                                            true);
4176 }
4177 
4178 /// \brief Check if the given expression \a E is a constant integer that fits
4179 /// into \a Bits bits.
4180 static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) {
4181   if (E == nullptr)
4182     return false;
4183   llvm::APSInt Result;
4184   if (E->isIntegerConstantExpr(Result, SemaRef.Context))
4185     return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
4186   return false;
4187 }
4188 
4189 /// \brief Called on a for stmt to check itself and nested loops (if any).
4190 /// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
4191 /// number of collapsed loops otherwise.
4192 static unsigned
4193 CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
4194                 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
4195                 DSAStackTy &DSA,
4196                 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
4197                 OMPLoopDirective::HelperExprs &Built) {
4198   unsigned NestedLoopCount = 1;
4199   if (CollapseLoopCountExpr) {
4200     // Found 'collapse' clause - calculate collapse number.
4201     llvm::APSInt Result;
4202     if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
4203       NestedLoopCount = Result.getLimitedValue();
4204   }
4205   if (OrderedLoopCountExpr) {
4206     // Found 'ordered' clause - calculate collapse number.
4207     llvm::APSInt Result;
4208     if (OrderedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
4209       if (Result.getLimitedValue() < NestedLoopCount) {
4210         SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
4211                      diag::err_omp_wrong_ordered_loop_count)
4212             << OrderedLoopCountExpr->getSourceRange();
4213         SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
4214                      diag::note_collapse_loop_count)
4215             << CollapseLoopCountExpr->getSourceRange();
4216       }
4217       NestedLoopCount = Result.getLimitedValue();
4218     }
4219   }
4220   // This is helper routine for loop directives (e.g., 'for', 'simd',
4221   // 'for simd', etc.).
4222   SmallVector<LoopIterationSpace, 4> IterSpaces;
4223   IterSpaces.resize(NestedLoopCount);
4224   Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
4225   for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
4226     if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt,
4227                                   NestedLoopCount, CollapseLoopCountExpr,
4228                                   OrderedLoopCountExpr, VarsWithImplicitDSA,
4229                                   IterSpaces[Cnt]))
4230       return 0;
4231     // Move on to the next nested for loop, or to the loop body.
4232     // OpenMP [2.8.1, simd construct, Restrictions]
4233     // All loops associated with the construct must be perfectly nested; that
4234     // is, there must be no intervening code nor any OpenMP directive between
4235     // any two loops.
4236     CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
4237   }
4238 
4239   Built.clear(/* size */ NestedLoopCount);
4240 
4241   if (SemaRef.CurContext->isDependentContext())
4242     return NestedLoopCount;
4243 
4244   // An example of what is generated for the following code:
4245   //
4246   //   #pragma omp simd collapse(2) ordered(2)
4247   //   for (i = 0; i < NI; ++i)
4248   //     for (k = 0; k < NK; ++k)
4249   //       for (j = J0; j < NJ; j+=2) {
4250   //         <loop body>
4251   //       }
4252   //
4253   // We generate the code below.
4254   // Note: the loop body may be outlined in CodeGen.
4255   // Note: some counters may be C++ classes, operator- is used to find number of
4256   // iterations and operator+= to calculate counter value.
4257   // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
4258   // or i64 is currently supported).
4259   //
4260   //   #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
4261   //   for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
4262   //     .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
4263   //     .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
4264   //     // similar updates for vars in clauses (e.g. 'linear')
4265   //     <loop body (using local i and j)>
4266   //   }
4267   //   i = NI; // assign final values of counters
4268   //   j = NJ;
4269   //
4270 
4271   // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
4272   // the iteration counts of the collapsed for loops.
4273   // Precondition tests if there is at least one iteration (all conditions are
4274   // true).
4275   auto PreCond = ExprResult(IterSpaces[0].PreCond);
4276   auto N0 = IterSpaces[0].NumIterations;
4277   ExprResult LastIteration32 = WidenIterationCount(
4278       32 /* Bits */, SemaRef.PerformImplicitConversion(
4279                                 N0->IgnoreImpCasts(), N0->getType(),
4280                                 Sema::AA_Converting, /*AllowExplicit=*/true)
4281                          .get(),
4282       SemaRef);
4283   ExprResult LastIteration64 = WidenIterationCount(
4284       64 /* Bits */, SemaRef.PerformImplicitConversion(
4285                                 N0->IgnoreImpCasts(), N0->getType(),
4286                                 Sema::AA_Converting, /*AllowExplicit=*/true)
4287                          .get(),
4288       SemaRef);
4289 
4290   if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
4291     return NestedLoopCount;
4292 
4293   auto &C = SemaRef.Context;
4294   bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
4295 
4296   Scope *CurScope = DSA.getCurScope();
4297   for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
4298     if (PreCond.isUsable()) {
4299       PreCond = SemaRef.BuildBinOp(CurScope, SourceLocation(), BO_LAnd,
4300                                    PreCond.get(), IterSpaces[Cnt].PreCond);
4301     }
4302     auto N = IterSpaces[Cnt].NumIterations;
4303     AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
4304     if (LastIteration32.isUsable())
4305       LastIteration32 = SemaRef.BuildBinOp(
4306           CurScope, SourceLocation(), BO_Mul, LastIteration32.get(),
4307           SemaRef.PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
4308                                             Sema::AA_Converting,
4309                                             /*AllowExplicit=*/true)
4310               .get());
4311     if (LastIteration64.isUsable())
4312       LastIteration64 = SemaRef.BuildBinOp(
4313           CurScope, SourceLocation(), BO_Mul, LastIteration64.get(),
4314           SemaRef.PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
4315                                             Sema::AA_Converting,
4316                                             /*AllowExplicit=*/true)
4317               .get());
4318   }
4319 
4320   // Choose either the 32-bit or 64-bit version.
4321   ExprResult LastIteration = LastIteration64;
4322   if (LastIteration32.isUsable() &&
4323       C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
4324       (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
4325        FitsInto(
4326            32 /* Bits */,
4327            LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
4328            LastIteration64.get(), SemaRef)))
4329     LastIteration = LastIteration32;
4330 
4331   if (!LastIteration.isUsable())
4332     return 0;
4333 
4334   // Save the number of iterations.
4335   ExprResult NumIterations = LastIteration;
4336   {
4337     LastIteration = SemaRef.BuildBinOp(
4338         CurScope, SourceLocation(), BO_Sub, LastIteration.get(),
4339         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4340     if (!LastIteration.isUsable())
4341       return 0;
4342   }
4343 
4344   // Calculate the last iteration number beforehand instead of doing this on
4345   // each iteration. Do not do this if the number of iterations may be kfold-ed.
4346   llvm::APSInt Result;
4347   bool IsConstant =
4348       LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
4349   ExprResult CalcLastIteration;
4350   if (!IsConstant) {
4351     SourceLocation SaveLoc;
4352     VarDecl *SaveVar =
4353         buildVarDecl(SemaRef, SaveLoc, LastIteration.get()->getType(),
4354                      ".omp.last.iteration");
4355     ExprResult SaveRef = buildDeclRefExpr(
4356         SemaRef, SaveVar, LastIteration.get()->getType(), SaveLoc);
4357     CalcLastIteration = SemaRef.BuildBinOp(CurScope, SaveLoc, BO_Assign,
4358                                            SaveRef.get(), LastIteration.get());
4359     LastIteration = SaveRef;
4360 
4361     // Prepare SaveRef + 1.
4362     NumIterations = SemaRef.BuildBinOp(
4363         CurScope, SaveLoc, BO_Add, SaveRef.get(),
4364         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4365     if (!NumIterations.isUsable())
4366       return 0;
4367   }
4368 
4369   SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
4370 
4371   QualType VType = LastIteration.get()->getType();
4372   // Build variables passed into runtime, nesessary for worksharing directives.
4373   ExprResult LB, UB, IL, ST, EUB;
4374   if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
4375       isOpenMPDistributeDirective(DKind)) {
4376     // Lower bound variable, initialized with zero.
4377     VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
4378     LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
4379     SemaRef.AddInitializerToDecl(
4380         LBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4381         /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
4382 
4383     // Upper bound variable, initialized with last iteration number.
4384     VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
4385     UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
4386     SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
4387                                  /*DirectInit*/ false,
4388                                  /*TypeMayContainAuto*/ false);
4389 
4390     // A 32-bit variable-flag where runtime returns 1 for the last iteration.
4391     // This will be used to implement clause 'lastprivate'.
4392     QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
4393     VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
4394     IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
4395     SemaRef.AddInitializerToDecl(
4396         ILDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4397         /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
4398 
4399     // Stride variable returned by runtime (we initialize it to 1 by default).
4400     VarDecl *STDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.stride");
4401     ST = buildDeclRefExpr(SemaRef, STDecl, VType, InitLoc);
4402     SemaRef.AddInitializerToDecl(
4403         STDecl, SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
4404         /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
4405 
4406     // Build expression: UB = min(UB, LastIteration)
4407     // It is nesessary for CodeGen of directives with static scheduling.
4408     ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
4409                                                 UB.get(), LastIteration.get());
4410     ExprResult CondOp = SemaRef.ActOnConditionalOp(
4411         InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get());
4412     EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
4413                              CondOp.get());
4414     EUB = SemaRef.ActOnFinishFullExpr(EUB.get());
4415   }
4416 
4417   // Build the iteration variable and its initialization before loop.
4418   ExprResult IV;
4419   ExprResult Init;
4420   {
4421     VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.iv");
4422     IV = buildDeclRefExpr(SemaRef, IVDecl, VType, InitLoc);
4423     Expr *RHS = (isOpenMPWorksharingDirective(DKind) ||
4424                  isOpenMPTaskLoopDirective(DKind) ||
4425                  isOpenMPDistributeDirective(DKind))
4426                     ? LB.get()
4427                     : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
4428     Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
4429     Init = SemaRef.ActOnFinishFullExpr(Init.get());
4430   }
4431 
4432   // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops.
4433   SourceLocation CondLoc;
4434   ExprResult Cond =
4435       (isOpenMPWorksharingDirective(DKind) ||
4436        isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
4437           ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get())
4438           : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
4439                                NumIterations.get());
4440 
4441   // Loop increment (IV = IV + 1)
4442   SourceLocation IncLoc;
4443   ExprResult Inc =
4444       SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
4445                          SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
4446   if (!Inc.isUsable())
4447     return 0;
4448   Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
4449   Inc = SemaRef.ActOnFinishFullExpr(Inc.get());
4450   if (!Inc.isUsable())
4451     return 0;
4452 
4453   // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
4454   // Used for directives with static scheduling.
4455   ExprResult NextLB, NextUB;
4456   if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
4457       isOpenMPDistributeDirective(DKind)) {
4458     // LB + ST
4459     NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
4460     if (!NextLB.isUsable())
4461       return 0;
4462     // LB = LB + ST
4463     NextLB =
4464         SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
4465     NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get());
4466     if (!NextLB.isUsable())
4467       return 0;
4468     // UB + ST
4469     NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
4470     if (!NextUB.isUsable())
4471       return 0;
4472     // UB = UB + ST
4473     NextUB =
4474         SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
4475     NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get());
4476     if (!NextUB.isUsable())
4477       return 0;
4478   }
4479 
4480   // Build updates and final values of the loop counters.
4481   bool HasErrors = false;
4482   Built.Counters.resize(NestedLoopCount);
4483   Built.Inits.resize(NestedLoopCount);
4484   Built.Updates.resize(NestedLoopCount);
4485   Built.Finals.resize(NestedLoopCount);
4486   {
4487     ExprResult Div;
4488     // Go from inner nested loop to outer.
4489     for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
4490       LoopIterationSpace &IS = IterSpaces[Cnt];
4491       SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
4492       // Build: Iter = (IV / Div) % IS.NumIters
4493       // where Div is product of previous iterations' IS.NumIters.
4494       ExprResult Iter;
4495       if (Div.isUsable()) {
4496         Iter =
4497             SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get());
4498       } else {
4499         Iter = IV;
4500         assert((Cnt == (int)NestedLoopCount - 1) &&
4501                "unusable div expected on first iteration only");
4502       }
4503 
4504       if (Cnt != 0 && Iter.isUsable())
4505         Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(),
4506                                   IS.NumIterations);
4507       if (!Iter.isUsable()) {
4508         HasErrors = true;
4509         break;
4510       }
4511 
4512       // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
4513       auto *CounterVar = buildDeclRefExpr(
4514           SemaRef, cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl()),
4515           IS.CounterVar->getType(), IS.CounterVar->getExprLoc(),
4516           /*RefersToCapture=*/true);
4517       ExprResult Init = BuildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
4518                                          IS.CounterInit);
4519       if (!Init.isUsable()) {
4520         HasErrors = true;
4521         break;
4522       }
4523       ExprResult Update =
4524           BuildCounterUpdate(SemaRef, CurScope, UpdLoc, CounterVar,
4525                              IS.CounterInit, Iter, IS.CounterStep, IS.Subtract);
4526       if (!Update.isUsable()) {
4527         HasErrors = true;
4528         break;
4529       }
4530 
4531       // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
4532       ExprResult Final = BuildCounterUpdate(
4533           SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
4534           IS.NumIterations, IS.CounterStep, IS.Subtract);
4535       if (!Final.isUsable()) {
4536         HasErrors = true;
4537         break;
4538       }
4539 
4540       // Build Div for the next iteration: Div <- Div * IS.NumIters
4541       if (Cnt != 0) {
4542         if (Div.isUnset())
4543           Div = IS.NumIterations;
4544         else
4545           Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(),
4546                                    IS.NumIterations);
4547 
4548         // Add parentheses (for debugging purposes only).
4549         if (Div.isUsable())
4550           Div = SemaRef.ActOnParenExpr(UpdLoc, UpdLoc, Div.get());
4551         if (!Div.isUsable()) {
4552           HasErrors = true;
4553           break;
4554         }
4555       }
4556       if (!Update.isUsable() || !Final.isUsable()) {
4557         HasErrors = true;
4558         break;
4559       }
4560       // Save results
4561       Built.Counters[Cnt] = IS.CounterVar;
4562       Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
4563       Built.Inits[Cnt] = Init.get();
4564       Built.Updates[Cnt] = Update.get();
4565       Built.Finals[Cnt] = Final.get();
4566     }
4567   }
4568 
4569   if (HasErrors)
4570     return 0;
4571 
4572   // Save results
4573   Built.IterationVarRef = IV.get();
4574   Built.LastIteration = LastIteration.get();
4575   Built.NumIterations = NumIterations.get();
4576   Built.CalcLastIteration =
4577       SemaRef.ActOnFinishFullExpr(CalcLastIteration.get()).get();
4578   Built.PreCond = PreCond.get();
4579   Built.Cond = Cond.get();
4580   Built.Init = Init.get();
4581   Built.Inc = Inc.get();
4582   Built.LB = LB.get();
4583   Built.UB = UB.get();
4584   Built.IL = IL.get();
4585   Built.ST = ST.get();
4586   Built.EUB = EUB.get();
4587   Built.NLB = NextLB.get();
4588   Built.NUB = NextUB.get();
4589 
4590   return NestedLoopCount;
4591 }
4592 
4593 static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
4594   auto CollapseClauses =
4595       OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
4596   if (CollapseClauses.begin() != CollapseClauses.end())
4597     return (*CollapseClauses.begin())->getNumForLoops();
4598   return nullptr;
4599 }
4600 
4601 static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
4602   auto OrderedClauses =
4603       OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
4604   if (OrderedClauses.begin() != OrderedClauses.end())
4605     return (*OrderedClauses.begin())->getNumForLoops();
4606   return nullptr;
4607 }
4608 
4609 static bool checkSimdlenSafelenValues(Sema &S, const Expr *Simdlen,
4610                                       const Expr *Safelen) {
4611   llvm::APSInt SimdlenRes, SafelenRes;
4612   if (Simdlen->isValueDependent() || Simdlen->isTypeDependent() ||
4613       Simdlen->isInstantiationDependent() ||
4614       Simdlen->containsUnexpandedParameterPack())
4615     return false;
4616   if (Safelen->isValueDependent() || Safelen->isTypeDependent() ||
4617       Safelen->isInstantiationDependent() ||
4618       Safelen->containsUnexpandedParameterPack())
4619     return false;
4620   Simdlen->EvaluateAsInt(SimdlenRes, S.Context);
4621   Safelen->EvaluateAsInt(SafelenRes, S.Context);
4622   // OpenMP 4.1 [2.8.1, simd Construct, Restrictions]
4623   // If both simdlen and safelen clauses are specified, the value of the simdlen
4624   // parameter must be less than or equal to the value of the safelen parameter.
4625   if (SimdlenRes > SafelenRes) {
4626     S.Diag(Simdlen->getExprLoc(), diag::err_omp_wrong_simdlen_safelen_values)
4627         << Simdlen->getSourceRange() << Safelen->getSourceRange();
4628     return true;
4629   }
4630   return false;
4631 }
4632 
4633 StmtResult Sema::ActOnOpenMPSimdDirective(
4634     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4635     SourceLocation EndLoc,
4636     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
4637   if (!AStmt)
4638     return StmtError();
4639 
4640   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4641   OMPLoopDirective::HelperExprs B;
4642   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4643   // define the nested loops number.
4644   unsigned NestedLoopCount = CheckOpenMPLoop(
4645       OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
4646       AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
4647   if (NestedLoopCount == 0)
4648     return StmtError();
4649 
4650   assert((CurContext->isDependentContext() || B.builtAll()) &&
4651          "omp simd loop exprs were not built");
4652 
4653   if (!CurContext->isDependentContext()) {
4654     // Finalize the clauses that need pre-built expressions for CodeGen.
4655     for (auto C : Clauses) {
4656       if (auto LC = dyn_cast<OMPLinearClause>(C))
4657         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
4658                                      B.NumIterations, *this, CurScope))
4659           return StmtError();
4660     }
4661   }
4662 
4663   // OpenMP 4.1 [2.8.1, simd Construct, Restrictions]
4664   // If both simdlen and safelen clauses are specified, the value of the simdlen
4665   // parameter must be less than or equal to the value of the safelen parameter.
4666   OMPSafelenClause *Safelen = nullptr;
4667   OMPSimdlenClause *Simdlen = nullptr;
4668   for (auto *Clause : Clauses) {
4669     if (Clause->getClauseKind() == OMPC_safelen)
4670       Safelen = cast<OMPSafelenClause>(Clause);
4671     else if (Clause->getClauseKind() == OMPC_simdlen)
4672       Simdlen = cast<OMPSimdlenClause>(Clause);
4673     if (Safelen && Simdlen)
4674       break;
4675   }
4676   if (Simdlen && Safelen &&
4677       checkSimdlenSafelenValues(*this, Simdlen->getSimdlen(),
4678                                 Safelen->getSafelen()))
4679     return StmtError();
4680 
4681   getCurFunction()->setHasBranchProtectedScope();
4682   return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
4683                                   Clauses, AStmt, B);
4684 }
4685 
4686 StmtResult Sema::ActOnOpenMPForDirective(
4687     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4688     SourceLocation EndLoc,
4689     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
4690   if (!AStmt)
4691     return StmtError();
4692 
4693   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4694   OMPLoopDirective::HelperExprs B;
4695   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4696   // define the nested loops number.
4697   unsigned NestedLoopCount = CheckOpenMPLoop(
4698       OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
4699       AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
4700   if (NestedLoopCount == 0)
4701     return StmtError();
4702 
4703   assert((CurContext->isDependentContext() || B.builtAll()) &&
4704          "omp for loop exprs were not built");
4705 
4706   if (!CurContext->isDependentContext()) {
4707     // Finalize the clauses that need pre-built expressions for CodeGen.
4708     for (auto C : Clauses) {
4709       if (auto LC = dyn_cast<OMPLinearClause>(C))
4710         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
4711                                      B.NumIterations, *this, CurScope))
4712           return StmtError();
4713     }
4714   }
4715 
4716   getCurFunction()->setHasBranchProtectedScope();
4717   return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
4718                                  Clauses, AStmt, B, DSAStack->isCancelRegion());
4719 }
4720 
4721 StmtResult Sema::ActOnOpenMPForSimdDirective(
4722     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4723     SourceLocation EndLoc,
4724     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
4725   if (!AStmt)
4726     return StmtError();
4727 
4728   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4729   OMPLoopDirective::HelperExprs B;
4730   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4731   // define the nested loops number.
4732   unsigned NestedLoopCount =
4733       CheckOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
4734                       getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4735                       VarsWithImplicitDSA, B);
4736   if (NestedLoopCount == 0)
4737     return StmtError();
4738 
4739   assert((CurContext->isDependentContext() || B.builtAll()) &&
4740          "omp for simd loop exprs were not built");
4741 
4742   if (!CurContext->isDependentContext()) {
4743     // Finalize the clauses that need pre-built expressions for CodeGen.
4744     for (auto C : Clauses) {
4745       if (auto LC = dyn_cast<OMPLinearClause>(C))
4746         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
4747                                      B.NumIterations, *this, CurScope))
4748           return StmtError();
4749     }
4750   }
4751 
4752   // OpenMP 4.1 [2.8.1, simd Construct, Restrictions]
4753   // If both simdlen and safelen clauses are specified, the value of the simdlen
4754   // parameter must be less than or equal to the value of the safelen parameter.
4755   OMPSafelenClause *Safelen = nullptr;
4756   OMPSimdlenClause *Simdlen = nullptr;
4757   for (auto *Clause : Clauses) {
4758     if (Clause->getClauseKind() == OMPC_safelen)
4759       Safelen = cast<OMPSafelenClause>(Clause);
4760     else if (Clause->getClauseKind() == OMPC_simdlen)
4761       Simdlen = cast<OMPSimdlenClause>(Clause);
4762     if (Safelen && Simdlen)
4763       break;
4764   }
4765   if (Simdlen && Safelen &&
4766       checkSimdlenSafelenValues(*this, Simdlen->getSimdlen(),
4767                                 Safelen->getSafelen()))
4768     return StmtError();
4769 
4770   getCurFunction()->setHasBranchProtectedScope();
4771   return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
4772                                      Clauses, AStmt, B);
4773 }
4774 
4775 StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
4776                                               Stmt *AStmt,
4777                                               SourceLocation StartLoc,
4778                                               SourceLocation EndLoc) {
4779   if (!AStmt)
4780     return StmtError();
4781 
4782   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4783   auto BaseStmt = AStmt;
4784   while (CapturedStmt *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
4785     BaseStmt = CS->getCapturedStmt();
4786   if (auto C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
4787     auto S = C->children();
4788     if (S.begin() == S.end())
4789       return StmtError();
4790     // All associated statements must be '#pragma omp section' except for
4791     // the first one.
4792     for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
4793       if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
4794         if (SectionStmt)
4795           Diag(SectionStmt->getLocStart(),
4796                diag::err_omp_sections_substmt_not_section);
4797         return StmtError();
4798       }
4799       cast<OMPSectionDirective>(SectionStmt)
4800           ->setHasCancel(DSAStack->isCancelRegion());
4801     }
4802   } else {
4803     Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt);
4804     return StmtError();
4805   }
4806 
4807   getCurFunction()->setHasBranchProtectedScope();
4808 
4809   return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
4810                                       DSAStack->isCancelRegion());
4811 }
4812 
4813 StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
4814                                              SourceLocation StartLoc,
4815                                              SourceLocation EndLoc) {
4816   if (!AStmt)
4817     return StmtError();
4818 
4819   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4820 
4821   getCurFunction()->setHasBranchProtectedScope();
4822   DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
4823 
4824   return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
4825                                      DSAStack->isCancelRegion());
4826 }
4827 
4828 StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
4829                                             Stmt *AStmt,
4830                                             SourceLocation StartLoc,
4831                                             SourceLocation EndLoc) {
4832   if (!AStmt)
4833     return StmtError();
4834 
4835   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4836 
4837   getCurFunction()->setHasBranchProtectedScope();
4838 
4839   // OpenMP [2.7.3, single Construct, Restrictions]
4840   // The copyprivate clause must not be used with the nowait clause.
4841   OMPClause *Nowait = nullptr;
4842   OMPClause *Copyprivate = nullptr;
4843   for (auto *Clause : Clauses) {
4844     if (Clause->getClauseKind() == OMPC_nowait)
4845       Nowait = Clause;
4846     else if (Clause->getClauseKind() == OMPC_copyprivate)
4847       Copyprivate = Clause;
4848     if (Copyprivate && Nowait) {
4849       Diag(Copyprivate->getLocStart(),
4850            diag::err_omp_single_copyprivate_with_nowait);
4851       Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here);
4852       return StmtError();
4853     }
4854   }
4855 
4856   return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
4857 }
4858 
4859 StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
4860                                             SourceLocation StartLoc,
4861                                             SourceLocation EndLoc) {
4862   if (!AStmt)
4863     return StmtError();
4864 
4865   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4866 
4867   getCurFunction()->setHasBranchProtectedScope();
4868 
4869   return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
4870 }
4871 
4872 StmtResult Sema::ActOnOpenMPCriticalDirective(
4873     const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
4874     Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
4875   if (!AStmt)
4876     return StmtError();
4877 
4878   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4879 
4880   bool ErrorFound = false;
4881   llvm::APSInt Hint;
4882   SourceLocation HintLoc;
4883   bool DependentHint = false;
4884   for (auto *C : Clauses) {
4885     if (C->getClauseKind() == OMPC_hint) {
4886       if (!DirName.getName()) {
4887         Diag(C->getLocStart(), diag::err_omp_hint_clause_no_name);
4888         ErrorFound = true;
4889       }
4890       Expr *E = cast<OMPHintClause>(C)->getHint();
4891       if (E->isTypeDependent() || E->isValueDependent() ||
4892           E->isInstantiationDependent())
4893         DependentHint = true;
4894       else {
4895         Hint = E->EvaluateKnownConstInt(Context);
4896         HintLoc = C->getLocStart();
4897       }
4898     }
4899   }
4900   if (ErrorFound)
4901     return StmtError();
4902   auto Pair = DSAStack->getCriticalWithHint(DirName);
4903   if (Pair.first && DirName.getName() && !DependentHint) {
4904     if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
4905       Diag(StartLoc, diag::err_omp_critical_with_hint);
4906       if (HintLoc.isValid()) {
4907         Diag(HintLoc, diag::note_omp_critical_hint_here)
4908             << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
4909       } else
4910         Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
4911       if (auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
4912         Diag(C->getLocStart(), diag::note_omp_critical_hint_here)
4913             << 1
4914             << C->getHint()->EvaluateKnownConstInt(Context).toString(
4915                    /*Radix=*/10, /*Signed=*/false);
4916       } else
4917         Diag(Pair.first->getLocStart(), diag::note_omp_critical_no_hint) << 1;
4918     }
4919   }
4920 
4921   getCurFunction()->setHasBranchProtectedScope();
4922 
4923   auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
4924                                            Clauses, AStmt);
4925   if (!Pair.first && DirName.getName() && !DependentHint)
4926     DSAStack->addCriticalWithHint(Dir, Hint);
4927   return Dir;
4928 }
4929 
4930 StmtResult Sema::ActOnOpenMPParallelForDirective(
4931     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4932     SourceLocation EndLoc,
4933     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
4934   if (!AStmt)
4935     return StmtError();
4936 
4937   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
4938   // 1.2.2 OpenMP Language Terminology
4939   // Structured block - An executable statement with a single entry at the
4940   // top and a single exit at the bottom.
4941   // The point of exit cannot be a branch out of the structured block.
4942   // longjmp() and throw() must not violate the entry/exit criteria.
4943   CS->getCapturedDecl()->setNothrow();
4944 
4945   OMPLoopDirective::HelperExprs B;
4946   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4947   // define the nested loops number.
4948   unsigned NestedLoopCount =
4949       CheckOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
4950                       getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4951                       VarsWithImplicitDSA, B);
4952   if (NestedLoopCount == 0)
4953     return StmtError();
4954 
4955   assert((CurContext->isDependentContext() || B.builtAll()) &&
4956          "omp parallel for loop exprs were not built");
4957 
4958   if (!CurContext->isDependentContext()) {
4959     // Finalize the clauses that need pre-built expressions for CodeGen.
4960     for (auto C : Clauses) {
4961       if (auto LC = dyn_cast<OMPLinearClause>(C))
4962         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
4963                                      B.NumIterations, *this, CurScope))
4964           return StmtError();
4965     }
4966   }
4967 
4968   getCurFunction()->setHasBranchProtectedScope();
4969   return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
4970                                          NestedLoopCount, Clauses, AStmt, B,
4971                                          DSAStack->isCancelRegion());
4972 }
4973 
4974 StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
4975     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4976     SourceLocation EndLoc,
4977     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
4978   if (!AStmt)
4979     return StmtError();
4980 
4981   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
4982   // 1.2.2 OpenMP Language Terminology
4983   // Structured block - An executable statement with a single entry at the
4984   // top and a single exit at the bottom.
4985   // The point of exit cannot be a branch out of the structured block.
4986   // longjmp() and throw() must not violate the entry/exit criteria.
4987   CS->getCapturedDecl()->setNothrow();
4988 
4989   OMPLoopDirective::HelperExprs B;
4990   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4991   // define the nested loops number.
4992   unsigned NestedLoopCount =
4993       CheckOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
4994                       getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4995                       VarsWithImplicitDSA, B);
4996   if (NestedLoopCount == 0)
4997     return StmtError();
4998 
4999   if (!CurContext->isDependentContext()) {
5000     // Finalize the clauses that need pre-built expressions for CodeGen.
5001     for (auto C : Clauses) {
5002       if (auto LC = dyn_cast<OMPLinearClause>(C))
5003         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
5004                                      B.NumIterations, *this, CurScope))
5005           return StmtError();
5006     }
5007   }
5008 
5009   // OpenMP 4.1 [2.8.1, simd Construct, Restrictions]
5010   // If both simdlen and safelen clauses are specified, the value of the simdlen
5011   // parameter must be less than or equal to the value of the safelen parameter.
5012   OMPSafelenClause *Safelen = nullptr;
5013   OMPSimdlenClause *Simdlen = nullptr;
5014   for (auto *Clause : Clauses) {
5015     if (Clause->getClauseKind() == OMPC_safelen)
5016       Safelen = cast<OMPSafelenClause>(Clause);
5017     else if (Clause->getClauseKind() == OMPC_simdlen)
5018       Simdlen = cast<OMPSimdlenClause>(Clause);
5019     if (Safelen && Simdlen)
5020       break;
5021   }
5022   if (Simdlen && Safelen &&
5023       checkSimdlenSafelenValues(*this, Simdlen->getSimdlen(),
5024                                 Safelen->getSafelen()))
5025     return StmtError();
5026 
5027   getCurFunction()->setHasBranchProtectedScope();
5028   return OMPParallelForSimdDirective::Create(
5029       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
5030 }
5031 
5032 StmtResult
5033 Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
5034                                            Stmt *AStmt, SourceLocation StartLoc,
5035                                            SourceLocation EndLoc) {
5036   if (!AStmt)
5037     return StmtError();
5038 
5039   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5040   auto BaseStmt = AStmt;
5041   while (CapturedStmt *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
5042     BaseStmt = CS->getCapturedStmt();
5043   if (auto C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
5044     auto S = C->children();
5045     if (S.begin() == S.end())
5046       return StmtError();
5047     // All associated statements must be '#pragma omp section' except for
5048     // the first one.
5049     for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
5050       if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
5051         if (SectionStmt)
5052           Diag(SectionStmt->getLocStart(),
5053                diag::err_omp_parallel_sections_substmt_not_section);
5054         return StmtError();
5055       }
5056       cast<OMPSectionDirective>(SectionStmt)
5057           ->setHasCancel(DSAStack->isCancelRegion());
5058     }
5059   } else {
5060     Diag(AStmt->getLocStart(),
5061          diag::err_omp_parallel_sections_not_compound_stmt);
5062     return StmtError();
5063   }
5064 
5065   getCurFunction()->setHasBranchProtectedScope();
5066 
5067   return OMPParallelSectionsDirective::Create(
5068       Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
5069 }
5070 
5071 StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
5072                                           Stmt *AStmt, SourceLocation StartLoc,
5073                                           SourceLocation EndLoc) {
5074   if (!AStmt)
5075     return StmtError();
5076 
5077   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5078   // 1.2.2 OpenMP Language Terminology
5079   // Structured block - An executable statement with a single entry at the
5080   // top and a single exit at the bottom.
5081   // The point of exit cannot be a branch out of the structured block.
5082   // longjmp() and throw() must not violate the entry/exit criteria.
5083   CS->getCapturedDecl()->setNothrow();
5084 
5085   getCurFunction()->setHasBranchProtectedScope();
5086 
5087   return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
5088                                   DSAStack->isCancelRegion());
5089 }
5090 
5091 StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
5092                                                SourceLocation EndLoc) {
5093   return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
5094 }
5095 
5096 StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
5097                                              SourceLocation EndLoc) {
5098   return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
5099 }
5100 
5101 StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
5102                                               SourceLocation EndLoc) {
5103   return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
5104 }
5105 
5106 StmtResult Sema::ActOnOpenMPTaskgroupDirective(Stmt *AStmt,
5107                                                SourceLocation StartLoc,
5108                                                SourceLocation EndLoc) {
5109   if (!AStmt)
5110     return StmtError();
5111 
5112   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5113 
5114   getCurFunction()->setHasBranchProtectedScope();
5115 
5116   return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, AStmt);
5117 }
5118 
5119 StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
5120                                            SourceLocation StartLoc,
5121                                            SourceLocation EndLoc) {
5122   assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
5123   return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
5124 }
5125 
5126 StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
5127                                              Stmt *AStmt,
5128                                              SourceLocation StartLoc,
5129                                              SourceLocation EndLoc) {
5130   OMPClause *DependFound = nullptr;
5131   OMPClause *DependSourceClause = nullptr;
5132   OMPClause *DependSinkClause = nullptr;
5133   bool ErrorFound = false;
5134   OMPThreadsClause *TC = nullptr;
5135   OMPSIMDClause *SC = nullptr;
5136   for (auto *C : Clauses) {
5137     if (auto *DC = dyn_cast<OMPDependClause>(C)) {
5138       DependFound = C;
5139       if (DC->getDependencyKind() == OMPC_DEPEND_source) {
5140         if (DependSourceClause) {
5141           Diag(C->getLocStart(), diag::err_omp_more_one_clause)
5142               << getOpenMPDirectiveName(OMPD_ordered)
5143               << getOpenMPClauseName(OMPC_depend) << 2;
5144           ErrorFound = true;
5145         } else
5146           DependSourceClause = C;
5147         if (DependSinkClause) {
5148           Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
5149               << 0;
5150           ErrorFound = true;
5151         }
5152       } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
5153         if (DependSourceClause) {
5154           Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
5155               << 1;
5156           ErrorFound = true;
5157         }
5158         DependSinkClause = C;
5159       }
5160     } else if (C->getClauseKind() == OMPC_threads)
5161       TC = cast<OMPThreadsClause>(C);
5162     else if (C->getClauseKind() == OMPC_simd)
5163       SC = cast<OMPSIMDClause>(C);
5164   }
5165   if (!ErrorFound && !SC &&
5166       isOpenMPSimdDirective(DSAStack->getParentDirective())) {
5167     // OpenMP [2.8.1,simd Construct, Restrictions]
5168     // An ordered construct with the simd clause is the only OpenMP construct
5169     // that can appear in the simd region.
5170     Diag(StartLoc, diag::err_omp_prohibited_region_simd);
5171     ErrorFound = true;
5172   } else if (DependFound && (TC || SC)) {
5173     Diag(DependFound->getLocStart(), diag::err_omp_depend_clause_thread_simd)
5174         << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
5175     ErrorFound = true;
5176   } else if (DependFound && !DSAStack->getParentOrderedRegionParam()) {
5177     Diag(DependFound->getLocStart(),
5178          diag::err_omp_ordered_directive_without_param);
5179     ErrorFound = true;
5180   } else if (TC || Clauses.empty()) {
5181     if (auto *Param = DSAStack->getParentOrderedRegionParam()) {
5182       SourceLocation ErrLoc = TC ? TC->getLocStart() : StartLoc;
5183       Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
5184           << (TC != nullptr);
5185       Diag(Param->getLocStart(), diag::note_omp_ordered_param);
5186       ErrorFound = true;
5187     }
5188   }
5189   if ((!AStmt && !DependFound) || ErrorFound)
5190     return StmtError();
5191 
5192   if (AStmt) {
5193     assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5194 
5195     getCurFunction()->setHasBranchProtectedScope();
5196   }
5197 
5198   return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
5199 }
5200 
5201 namespace {
5202 /// \brief Helper class for checking expression in 'omp atomic [update]'
5203 /// construct.
5204 class OpenMPAtomicUpdateChecker {
5205   /// \brief Error results for atomic update expressions.
5206   enum ExprAnalysisErrorCode {
5207     /// \brief A statement is not an expression statement.
5208     NotAnExpression,
5209     /// \brief Expression is not builtin binary or unary operation.
5210     NotABinaryOrUnaryExpression,
5211     /// \brief Unary operation is not post-/pre- increment/decrement operation.
5212     NotAnUnaryIncDecExpression,
5213     /// \brief An expression is not of scalar type.
5214     NotAScalarType,
5215     /// \brief A binary operation is not an assignment operation.
5216     NotAnAssignmentOp,
5217     /// \brief RHS part of the binary operation is not a binary expression.
5218     NotABinaryExpression,
5219     /// \brief RHS part is not additive/multiplicative/shift/biwise binary
5220     /// expression.
5221     NotABinaryOperator,
5222     /// \brief RHS binary operation does not have reference to the updated LHS
5223     /// part.
5224     NotAnUpdateExpression,
5225     /// \brief No errors is found.
5226     NoError
5227   };
5228   /// \brief Reference to Sema.
5229   Sema &SemaRef;
5230   /// \brief A location for note diagnostics (when error is found).
5231   SourceLocation NoteLoc;
5232   /// \brief 'x' lvalue part of the source atomic expression.
5233   Expr *X;
5234   /// \brief 'expr' rvalue part of the source atomic expression.
5235   Expr *E;
5236   /// \brief Helper expression of the form
5237   /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
5238   /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
5239   Expr *UpdateExpr;
5240   /// \brief Is 'x' a LHS in a RHS part of full update expression. It is
5241   /// important for non-associative operations.
5242   bool IsXLHSInRHSPart;
5243   BinaryOperatorKind Op;
5244   SourceLocation OpLoc;
5245   /// \brief true if the source expression is a postfix unary operation, false
5246   /// if it is a prefix unary operation.
5247   bool IsPostfixUpdate;
5248 
5249 public:
5250   OpenMPAtomicUpdateChecker(Sema &SemaRef)
5251       : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
5252         IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
5253   /// \brief Check specified statement that it is suitable for 'atomic update'
5254   /// constructs and extract 'x', 'expr' and Operation from the original
5255   /// expression. If DiagId and NoteId == 0, then only check is performed
5256   /// without error notification.
5257   /// \param DiagId Diagnostic which should be emitted if error is found.
5258   /// \param NoteId Diagnostic note for the main error message.
5259   /// \return true if statement is not an update expression, false otherwise.
5260   bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
5261   /// \brief Return the 'x' lvalue part of the source atomic expression.
5262   Expr *getX() const { return X; }
5263   /// \brief Return the 'expr' rvalue part of the source atomic expression.
5264   Expr *getExpr() const { return E; }
5265   /// \brief Return the update expression used in calculation of the updated
5266   /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
5267   /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
5268   Expr *getUpdateExpr() const { return UpdateExpr; }
5269   /// \brief Return true if 'x' is LHS in RHS part of full update expression,
5270   /// false otherwise.
5271   bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
5272 
5273   /// \brief true if the source expression is a postfix unary operation, false
5274   /// if it is a prefix unary operation.
5275   bool isPostfixUpdate() const { return IsPostfixUpdate; }
5276 
5277 private:
5278   bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
5279                             unsigned NoteId = 0);
5280 };
5281 } // namespace
5282 
5283 bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
5284     BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
5285   ExprAnalysisErrorCode ErrorFound = NoError;
5286   SourceLocation ErrorLoc, NoteLoc;
5287   SourceRange ErrorRange, NoteRange;
5288   // Allowed constructs are:
5289   //  x = x binop expr;
5290   //  x = expr binop x;
5291   if (AtomicBinOp->getOpcode() == BO_Assign) {
5292     X = AtomicBinOp->getLHS();
5293     if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
5294             AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
5295       if (AtomicInnerBinOp->isMultiplicativeOp() ||
5296           AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
5297           AtomicInnerBinOp->isBitwiseOp()) {
5298         Op = AtomicInnerBinOp->getOpcode();
5299         OpLoc = AtomicInnerBinOp->getOperatorLoc();
5300         auto *LHS = AtomicInnerBinOp->getLHS();
5301         auto *RHS = AtomicInnerBinOp->getRHS();
5302         llvm::FoldingSetNodeID XId, LHSId, RHSId;
5303         X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
5304                                           /*Canonical=*/true);
5305         LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
5306                                             /*Canonical=*/true);
5307         RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
5308                                             /*Canonical=*/true);
5309         if (XId == LHSId) {
5310           E = RHS;
5311           IsXLHSInRHSPart = true;
5312         } else if (XId == RHSId) {
5313           E = LHS;
5314           IsXLHSInRHSPart = false;
5315         } else {
5316           ErrorLoc = AtomicInnerBinOp->getExprLoc();
5317           ErrorRange = AtomicInnerBinOp->getSourceRange();
5318           NoteLoc = X->getExprLoc();
5319           NoteRange = X->getSourceRange();
5320           ErrorFound = NotAnUpdateExpression;
5321         }
5322       } else {
5323         ErrorLoc = AtomicInnerBinOp->getExprLoc();
5324         ErrorRange = AtomicInnerBinOp->getSourceRange();
5325         NoteLoc = AtomicInnerBinOp->getOperatorLoc();
5326         NoteRange = SourceRange(NoteLoc, NoteLoc);
5327         ErrorFound = NotABinaryOperator;
5328       }
5329     } else {
5330       NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
5331       NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
5332       ErrorFound = NotABinaryExpression;
5333     }
5334   } else {
5335     ErrorLoc = AtomicBinOp->getExprLoc();
5336     ErrorRange = AtomicBinOp->getSourceRange();
5337     NoteLoc = AtomicBinOp->getOperatorLoc();
5338     NoteRange = SourceRange(NoteLoc, NoteLoc);
5339     ErrorFound = NotAnAssignmentOp;
5340   }
5341   if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
5342     SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
5343     SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
5344     return true;
5345   } else if (SemaRef.CurContext->isDependentContext())
5346     E = X = UpdateExpr = nullptr;
5347   return ErrorFound != NoError;
5348 }
5349 
5350 bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
5351                                                unsigned NoteId) {
5352   ExprAnalysisErrorCode ErrorFound = NoError;
5353   SourceLocation ErrorLoc, NoteLoc;
5354   SourceRange ErrorRange, NoteRange;
5355   // Allowed constructs are:
5356   //  x++;
5357   //  x--;
5358   //  ++x;
5359   //  --x;
5360   //  x binop= expr;
5361   //  x = x binop expr;
5362   //  x = expr binop x;
5363   if (auto *AtomicBody = dyn_cast<Expr>(S)) {
5364     AtomicBody = AtomicBody->IgnoreParenImpCasts();
5365     if (AtomicBody->getType()->isScalarType() ||
5366         AtomicBody->isInstantiationDependent()) {
5367       if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
5368               AtomicBody->IgnoreParenImpCasts())) {
5369         // Check for Compound Assignment Operation
5370         Op = BinaryOperator::getOpForCompoundAssignment(
5371             AtomicCompAssignOp->getOpcode());
5372         OpLoc = AtomicCompAssignOp->getOperatorLoc();
5373         E = AtomicCompAssignOp->getRHS();
5374         X = AtomicCompAssignOp->getLHS();
5375         IsXLHSInRHSPart = true;
5376       } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
5377                      AtomicBody->IgnoreParenImpCasts())) {
5378         // Check for Binary Operation
5379         if(checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
5380           return true;
5381       } else if (auto *AtomicUnaryOp =
5382                  dyn_cast<UnaryOperator>(AtomicBody->IgnoreParenImpCasts())) {
5383         // Check for Unary Operation
5384         if (AtomicUnaryOp->isIncrementDecrementOp()) {
5385           IsPostfixUpdate = AtomicUnaryOp->isPostfix();
5386           Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
5387           OpLoc = AtomicUnaryOp->getOperatorLoc();
5388           X = AtomicUnaryOp->getSubExpr();
5389           E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
5390           IsXLHSInRHSPart = true;
5391         } else {
5392           ErrorFound = NotAnUnaryIncDecExpression;
5393           ErrorLoc = AtomicUnaryOp->getExprLoc();
5394           ErrorRange = AtomicUnaryOp->getSourceRange();
5395           NoteLoc = AtomicUnaryOp->getOperatorLoc();
5396           NoteRange = SourceRange(NoteLoc, NoteLoc);
5397         }
5398       } else if (!AtomicBody->isInstantiationDependent()) {
5399         ErrorFound = NotABinaryOrUnaryExpression;
5400         NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
5401         NoteRange = ErrorRange = AtomicBody->getSourceRange();
5402       }
5403     } else {
5404       ErrorFound = NotAScalarType;
5405       NoteLoc = ErrorLoc = AtomicBody->getLocStart();
5406       NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5407     }
5408   } else {
5409     ErrorFound = NotAnExpression;
5410     NoteLoc = ErrorLoc = S->getLocStart();
5411     NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5412   }
5413   if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
5414     SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
5415     SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
5416     return true;
5417   } else if (SemaRef.CurContext->isDependentContext())
5418     E = X = UpdateExpr = nullptr;
5419   if (ErrorFound == NoError && E && X) {
5420     // Build an update expression of form 'OpaqueValueExpr(x) binop
5421     // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
5422     // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
5423     auto *OVEX = new (SemaRef.getASTContext())
5424         OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
5425     auto *OVEExpr = new (SemaRef.getASTContext())
5426         OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
5427     auto Update =
5428         SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
5429                                    IsXLHSInRHSPart ? OVEExpr : OVEX);
5430     if (Update.isInvalid())
5431       return true;
5432     Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
5433                                                Sema::AA_Casting);
5434     if (Update.isInvalid())
5435       return true;
5436     UpdateExpr = Update.get();
5437   }
5438   return ErrorFound != NoError;
5439 }
5440 
5441 StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
5442                                             Stmt *AStmt,
5443                                             SourceLocation StartLoc,
5444                                             SourceLocation EndLoc) {
5445   if (!AStmt)
5446     return StmtError();
5447 
5448   auto CS = cast<CapturedStmt>(AStmt);
5449   // 1.2.2 OpenMP Language Terminology
5450   // Structured block - An executable statement with a single entry at the
5451   // top and a single exit at the bottom.
5452   // The point of exit cannot be a branch out of the structured block.
5453   // longjmp() and throw() must not violate the entry/exit criteria.
5454   OpenMPClauseKind AtomicKind = OMPC_unknown;
5455   SourceLocation AtomicKindLoc;
5456   for (auto *C : Clauses) {
5457     if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
5458         C->getClauseKind() == OMPC_update ||
5459         C->getClauseKind() == OMPC_capture) {
5460       if (AtomicKind != OMPC_unknown) {
5461         Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses)
5462             << SourceRange(C->getLocStart(), C->getLocEnd());
5463         Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
5464             << getOpenMPClauseName(AtomicKind);
5465       } else {
5466         AtomicKind = C->getClauseKind();
5467         AtomicKindLoc = C->getLocStart();
5468       }
5469     }
5470   }
5471 
5472   auto Body = CS->getCapturedStmt();
5473   if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
5474     Body = EWC->getSubExpr();
5475 
5476   Expr *X = nullptr;
5477   Expr *V = nullptr;
5478   Expr *E = nullptr;
5479   Expr *UE = nullptr;
5480   bool IsXLHSInRHSPart = false;
5481   bool IsPostfixUpdate = false;
5482   // OpenMP [2.12.6, atomic Construct]
5483   // In the next expressions:
5484   // * x and v (as applicable) are both l-value expressions with scalar type.
5485   // * During the execution of an atomic region, multiple syntactic
5486   // occurrences of x must designate the same storage location.
5487   // * Neither of v and expr (as applicable) may access the storage location
5488   // designated by x.
5489   // * Neither of x and expr (as applicable) may access the storage location
5490   // designated by v.
5491   // * expr is an expression with scalar type.
5492   // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
5493   // * binop, binop=, ++, and -- are not overloaded operators.
5494   // * The expression x binop expr must be numerically equivalent to x binop
5495   // (expr). This requirement is satisfied if the operators in expr have
5496   // precedence greater than binop, or by using parentheses around expr or
5497   // subexpressions of expr.
5498   // * The expression expr binop x must be numerically equivalent to (expr)
5499   // binop x. This requirement is satisfied if the operators in expr have
5500   // precedence equal to or greater than binop, or by using parentheses around
5501   // expr or subexpressions of expr.
5502   // * For forms that allow multiple occurrences of x, the number of times
5503   // that x is evaluated is unspecified.
5504   if (AtomicKind == OMPC_read) {
5505     enum {
5506       NotAnExpression,
5507       NotAnAssignmentOp,
5508       NotAScalarType,
5509       NotAnLValue,
5510       NoError
5511     } ErrorFound = NoError;
5512     SourceLocation ErrorLoc, NoteLoc;
5513     SourceRange ErrorRange, NoteRange;
5514     // If clause is read:
5515     //  v = x;
5516     if (auto AtomicBody = dyn_cast<Expr>(Body)) {
5517       auto AtomicBinOp =
5518           dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5519       if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
5520         X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
5521         V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
5522         if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
5523             (V->isInstantiationDependent() || V->getType()->isScalarType())) {
5524           if (!X->isLValue() || !V->isLValue()) {
5525             auto NotLValueExpr = X->isLValue() ? V : X;
5526             ErrorFound = NotAnLValue;
5527             ErrorLoc = AtomicBinOp->getExprLoc();
5528             ErrorRange = AtomicBinOp->getSourceRange();
5529             NoteLoc = NotLValueExpr->getExprLoc();
5530             NoteRange = NotLValueExpr->getSourceRange();
5531           }
5532         } else if (!X->isInstantiationDependent() ||
5533                    !V->isInstantiationDependent()) {
5534           auto NotScalarExpr =
5535               (X->isInstantiationDependent() || X->getType()->isScalarType())
5536                   ? V
5537                   : X;
5538           ErrorFound = NotAScalarType;
5539           ErrorLoc = AtomicBinOp->getExprLoc();
5540           ErrorRange = AtomicBinOp->getSourceRange();
5541           NoteLoc = NotScalarExpr->getExprLoc();
5542           NoteRange = NotScalarExpr->getSourceRange();
5543         }
5544       } else if (!AtomicBody->isInstantiationDependent()) {
5545         ErrorFound = NotAnAssignmentOp;
5546         ErrorLoc = AtomicBody->getExprLoc();
5547         ErrorRange = AtomicBody->getSourceRange();
5548         NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5549                               : AtomicBody->getExprLoc();
5550         NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5551                                 : AtomicBody->getSourceRange();
5552       }
5553     } else {
5554       ErrorFound = NotAnExpression;
5555       NoteLoc = ErrorLoc = Body->getLocStart();
5556       NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5557     }
5558     if (ErrorFound != NoError) {
5559       Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
5560           << ErrorRange;
5561       Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
5562                                                       << NoteRange;
5563       return StmtError();
5564     } else if (CurContext->isDependentContext())
5565       V = X = nullptr;
5566   } else if (AtomicKind == OMPC_write) {
5567     enum {
5568       NotAnExpression,
5569       NotAnAssignmentOp,
5570       NotAScalarType,
5571       NotAnLValue,
5572       NoError
5573     } ErrorFound = NoError;
5574     SourceLocation ErrorLoc, NoteLoc;
5575     SourceRange ErrorRange, NoteRange;
5576     // If clause is write:
5577     //  x = expr;
5578     if (auto AtomicBody = dyn_cast<Expr>(Body)) {
5579       auto AtomicBinOp =
5580           dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5581       if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
5582         X = AtomicBinOp->getLHS();
5583         E = AtomicBinOp->getRHS();
5584         if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
5585             (E->isInstantiationDependent() || E->getType()->isScalarType())) {
5586           if (!X->isLValue()) {
5587             ErrorFound = NotAnLValue;
5588             ErrorLoc = AtomicBinOp->getExprLoc();
5589             ErrorRange = AtomicBinOp->getSourceRange();
5590             NoteLoc = X->getExprLoc();
5591             NoteRange = X->getSourceRange();
5592           }
5593         } else if (!X->isInstantiationDependent() ||
5594                    !E->isInstantiationDependent()) {
5595           auto NotScalarExpr =
5596               (X->isInstantiationDependent() || X->getType()->isScalarType())
5597                   ? E
5598                   : X;
5599           ErrorFound = NotAScalarType;
5600           ErrorLoc = AtomicBinOp->getExprLoc();
5601           ErrorRange = AtomicBinOp->getSourceRange();
5602           NoteLoc = NotScalarExpr->getExprLoc();
5603           NoteRange = NotScalarExpr->getSourceRange();
5604         }
5605       } else if (!AtomicBody->isInstantiationDependent()) {
5606         ErrorFound = NotAnAssignmentOp;
5607         ErrorLoc = AtomicBody->getExprLoc();
5608         ErrorRange = AtomicBody->getSourceRange();
5609         NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5610                               : AtomicBody->getExprLoc();
5611         NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5612                                 : AtomicBody->getSourceRange();
5613       }
5614     } else {
5615       ErrorFound = NotAnExpression;
5616       NoteLoc = ErrorLoc = Body->getLocStart();
5617       NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5618     }
5619     if (ErrorFound != NoError) {
5620       Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
5621           << ErrorRange;
5622       Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
5623                                                       << NoteRange;
5624       return StmtError();
5625     } else if (CurContext->isDependentContext())
5626       E = X = nullptr;
5627   } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
5628     // If clause is update:
5629     //  x++;
5630     //  x--;
5631     //  ++x;
5632     //  --x;
5633     //  x binop= expr;
5634     //  x = x binop expr;
5635     //  x = expr binop x;
5636     OpenMPAtomicUpdateChecker Checker(*this);
5637     if (Checker.checkStatement(
5638             Body, (AtomicKind == OMPC_update)
5639                       ? diag::err_omp_atomic_update_not_expression_statement
5640                       : diag::err_omp_atomic_not_expression_statement,
5641             diag::note_omp_atomic_update))
5642       return StmtError();
5643     if (!CurContext->isDependentContext()) {
5644       E = Checker.getExpr();
5645       X = Checker.getX();
5646       UE = Checker.getUpdateExpr();
5647       IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
5648     }
5649   } else if (AtomicKind == OMPC_capture) {
5650     enum {
5651       NotAnAssignmentOp,
5652       NotACompoundStatement,
5653       NotTwoSubstatements,
5654       NotASpecificExpression,
5655       NoError
5656     } ErrorFound = NoError;
5657     SourceLocation ErrorLoc, NoteLoc;
5658     SourceRange ErrorRange, NoteRange;
5659     if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5660       // If clause is a capture:
5661       //  v = x++;
5662       //  v = x--;
5663       //  v = ++x;
5664       //  v = --x;
5665       //  v = x binop= expr;
5666       //  v = x = x binop expr;
5667       //  v = x = expr binop x;
5668       auto *AtomicBinOp =
5669           dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5670       if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
5671         V = AtomicBinOp->getLHS();
5672         Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
5673         OpenMPAtomicUpdateChecker Checker(*this);
5674         if (Checker.checkStatement(
5675                 Body, diag::err_omp_atomic_capture_not_expression_statement,
5676                 diag::note_omp_atomic_update))
5677           return StmtError();
5678         E = Checker.getExpr();
5679         X = Checker.getX();
5680         UE = Checker.getUpdateExpr();
5681         IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
5682         IsPostfixUpdate = Checker.isPostfixUpdate();
5683       } else if (!AtomicBody->isInstantiationDependent()) {
5684         ErrorLoc = AtomicBody->getExprLoc();
5685         ErrorRange = AtomicBody->getSourceRange();
5686         NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5687                               : AtomicBody->getExprLoc();
5688         NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5689                                 : AtomicBody->getSourceRange();
5690         ErrorFound = NotAnAssignmentOp;
5691       }
5692       if (ErrorFound != NoError) {
5693         Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
5694             << ErrorRange;
5695         Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
5696         return StmtError();
5697       } else if (CurContext->isDependentContext()) {
5698         UE = V = E = X = nullptr;
5699       }
5700     } else {
5701       // If clause is a capture:
5702       //  { v = x; x = expr; }
5703       //  { v = x; x++; }
5704       //  { v = x; x--; }
5705       //  { v = x; ++x; }
5706       //  { v = x; --x; }
5707       //  { v = x; x binop= expr; }
5708       //  { v = x; x = x binop expr; }
5709       //  { v = x; x = expr binop x; }
5710       //  { x++; v = x; }
5711       //  { x--; v = x; }
5712       //  { ++x; v = x; }
5713       //  { --x; v = x; }
5714       //  { x binop= expr; v = x; }
5715       //  { x = x binop expr; v = x; }
5716       //  { x = expr binop x; v = x; }
5717       if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
5718         // Check that this is { expr1; expr2; }
5719         if (CS->size() == 2) {
5720           auto *First = CS->body_front();
5721           auto *Second = CS->body_back();
5722           if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
5723             First = EWC->getSubExpr()->IgnoreParenImpCasts();
5724           if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
5725             Second = EWC->getSubExpr()->IgnoreParenImpCasts();
5726           // Need to find what subexpression is 'v' and what is 'x'.
5727           OpenMPAtomicUpdateChecker Checker(*this);
5728           bool IsUpdateExprFound = !Checker.checkStatement(Second);
5729           BinaryOperator *BinOp = nullptr;
5730           if (IsUpdateExprFound) {
5731             BinOp = dyn_cast<BinaryOperator>(First);
5732             IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
5733           }
5734           if (IsUpdateExprFound && !CurContext->isDependentContext()) {
5735             //  { v = x; x++; }
5736             //  { v = x; x--; }
5737             //  { v = x; ++x; }
5738             //  { v = x; --x; }
5739             //  { v = x; x binop= expr; }
5740             //  { v = x; x = x binop expr; }
5741             //  { v = x; x = expr binop x; }
5742             // Check that the first expression has form v = x.
5743             auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
5744             llvm::FoldingSetNodeID XId, PossibleXId;
5745             Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
5746             PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
5747             IsUpdateExprFound = XId == PossibleXId;
5748             if (IsUpdateExprFound) {
5749               V = BinOp->getLHS();
5750               X = Checker.getX();
5751               E = Checker.getExpr();
5752               UE = Checker.getUpdateExpr();
5753               IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
5754               IsPostfixUpdate = true;
5755             }
5756           }
5757           if (!IsUpdateExprFound) {
5758             IsUpdateExprFound = !Checker.checkStatement(First);
5759             BinOp = nullptr;
5760             if (IsUpdateExprFound) {
5761               BinOp = dyn_cast<BinaryOperator>(Second);
5762               IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
5763             }
5764             if (IsUpdateExprFound && !CurContext->isDependentContext()) {
5765               //  { x++; v = x; }
5766               //  { x--; v = x; }
5767               //  { ++x; v = x; }
5768               //  { --x; v = x; }
5769               //  { x binop= expr; v = x; }
5770               //  { x = x binop expr; v = x; }
5771               //  { x = expr binop x; v = x; }
5772               // Check that the second expression has form v = x.
5773               auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
5774               llvm::FoldingSetNodeID XId, PossibleXId;
5775               Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
5776               PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
5777               IsUpdateExprFound = XId == PossibleXId;
5778               if (IsUpdateExprFound) {
5779                 V = BinOp->getLHS();
5780                 X = Checker.getX();
5781                 E = Checker.getExpr();
5782                 UE = Checker.getUpdateExpr();
5783                 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
5784                 IsPostfixUpdate = false;
5785               }
5786             }
5787           }
5788           if (!IsUpdateExprFound) {
5789             //  { v = x; x = expr; }
5790             auto *FirstExpr = dyn_cast<Expr>(First);
5791             auto *SecondExpr = dyn_cast<Expr>(Second);
5792             if (!FirstExpr || !SecondExpr ||
5793                 !(FirstExpr->isInstantiationDependent() ||
5794                   SecondExpr->isInstantiationDependent())) {
5795               auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
5796               if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
5797                 ErrorFound = NotAnAssignmentOp;
5798                 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
5799                                                 : First->getLocStart();
5800                 NoteRange = ErrorRange = FirstBinOp
5801                                              ? FirstBinOp->getSourceRange()
5802                                              : SourceRange(ErrorLoc, ErrorLoc);
5803               } else {
5804                 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
5805                 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
5806                   ErrorFound = NotAnAssignmentOp;
5807                   NoteLoc = ErrorLoc = SecondBinOp
5808                                            ? SecondBinOp->getOperatorLoc()
5809                                            : Second->getLocStart();
5810                   NoteRange = ErrorRange =
5811                       SecondBinOp ? SecondBinOp->getSourceRange()
5812                                   : SourceRange(ErrorLoc, ErrorLoc);
5813                 } else {
5814                   auto *PossibleXRHSInFirst =
5815                       FirstBinOp->getRHS()->IgnoreParenImpCasts();
5816                   auto *PossibleXLHSInSecond =
5817                       SecondBinOp->getLHS()->IgnoreParenImpCasts();
5818                   llvm::FoldingSetNodeID X1Id, X2Id;
5819                   PossibleXRHSInFirst->Profile(X1Id, Context,
5820                                                /*Canonical=*/true);
5821                   PossibleXLHSInSecond->Profile(X2Id, Context,
5822                                                 /*Canonical=*/true);
5823                   IsUpdateExprFound = X1Id == X2Id;
5824                   if (IsUpdateExprFound) {
5825                     V = FirstBinOp->getLHS();
5826                     X = SecondBinOp->getLHS();
5827                     E = SecondBinOp->getRHS();
5828                     UE = nullptr;
5829                     IsXLHSInRHSPart = false;
5830                     IsPostfixUpdate = true;
5831                   } else {
5832                     ErrorFound = NotASpecificExpression;
5833                     ErrorLoc = FirstBinOp->getExprLoc();
5834                     ErrorRange = FirstBinOp->getSourceRange();
5835                     NoteLoc = SecondBinOp->getLHS()->getExprLoc();
5836                     NoteRange = SecondBinOp->getRHS()->getSourceRange();
5837                   }
5838                 }
5839               }
5840             }
5841           }
5842         } else {
5843           NoteLoc = ErrorLoc = Body->getLocStart();
5844           NoteRange = ErrorRange =
5845               SourceRange(Body->getLocStart(), Body->getLocStart());
5846           ErrorFound = NotTwoSubstatements;
5847         }
5848       } else {
5849         NoteLoc = ErrorLoc = Body->getLocStart();
5850         NoteRange = ErrorRange =
5851             SourceRange(Body->getLocStart(), Body->getLocStart());
5852         ErrorFound = NotACompoundStatement;
5853       }
5854       if (ErrorFound != NoError) {
5855         Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
5856             << ErrorRange;
5857         Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
5858         return StmtError();
5859       } else if (CurContext->isDependentContext()) {
5860         UE = V = E = X = nullptr;
5861       }
5862     }
5863   }
5864 
5865   getCurFunction()->setHasBranchProtectedScope();
5866 
5867   return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
5868                                     X, V, E, UE, IsXLHSInRHSPart,
5869                                     IsPostfixUpdate);
5870 }
5871 
5872 StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
5873                                             Stmt *AStmt,
5874                                             SourceLocation StartLoc,
5875                                             SourceLocation EndLoc) {
5876   if (!AStmt)
5877     return StmtError();
5878 
5879   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5880   // 1.2.2 OpenMP Language Terminology
5881   // Structured block - An executable statement with a single entry at the
5882   // top and a single exit at the bottom.
5883   // The point of exit cannot be a branch out of the structured block.
5884   // longjmp() and throw() must not violate the entry/exit criteria.
5885   CS->getCapturedDecl()->setNothrow();
5886 
5887   // OpenMP [2.16, Nesting of Regions]
5888   // If specified, a teams construct must be contained within a target
5889   // construct. That target construct must contain no statements or directives
5890   // outside of the teams construct.
5891   if (DSAStack->hasInnerTeamsRegion()) {
5892     auto S = AStmt->IgnoreContainers(/*IgnoreCaptured*/ true);
5893     bool OMPTeamsFound = true;
5894     if (auto *CS = dyn_cast<CompoundStmt>(S)) {
5895       auto I = CS->body_begin();
5896       while (I != CS->body_end()) {
5897         auto OED = dyn_cast<OMPExecutableDirective>(*I);
5898         if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) {
5899           OMPTeamsFound = false;
5900           break;
5901         }
5902         ++I;
5903       }
5904       assert(I != CS->body_end() && "Not found statement");
5905       S = *I;
5906     }
5907     if (!OMPTeamsFound) {
5908       Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
5909       Diag(DSAStack->getInnerTeamsRegionLoc(),
5910            diag::note_omp_nested_teams_construct_here);
5911       Diag(S->getLocStart(), diag::note_omp_nested_statement_here)
5912           << isa<OMPExecutableDirective>(S);
5913       return StmtError();
5914     }
5915   }
5916 
5917   getCurFunction()->setHasBranchProtectedScope();
5918 
5919   return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
5920 }
5921 
5922 StmtResult
5923 Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
5924                                          Stmt *AStmt, SourceLocation StartLoc,
5925                                          SourceLocation EndLoc) {
5926   if (!AStmt)
5927     return StmtError();
5928 
5929   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5930   // 1.2.2 OpenMP Language Terminology
5931   // Structured block - An executable statement with a single entry at the
5932   // top and a single exit at the bottom.
5933   // The point of exit cannot be a branch out of the structured block.
5934   // longjmp() and throw() must not violate the entry/exit criteria.
5935   CS->getCapturedDecl()->setNothrow();
5936 
5937   getCurFunction()->setHasBranchProtectedScope();
5938 
5939   return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
5940                                             AStmt);
5941 }
5942 
5943 StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
5944     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5945     SourceLocation EndLoc,
5946     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5947   if (!AStmt)
5948     return StmtError();
5949 
5950   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5951   // 1.2.2 OpenMP Language Terminology
5952   // Structured block - An executable statement with a single entry at the
5953   // top and a single exit at the bottom.
5954   // The point of exit cannot be a branch out of the structured block.
5955   // longjmp() and throw() must not violate the entry/exit criteria.
5956   CS->getCapturedDecl()->setNothrow();
5957 
5958   OMPLoopDirective::HelperExprs B;
5959   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5960   // define the nested loops number.
5961   unsigned NestedLoopCount =
5962       CheckOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
5963                       getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5964                       VarsWithImplicitDSA, B);
5965   if (NestedLoopCount == 0)
5966     return StmtError();
5967 
5968   assert((CurContext->isDependentContext() || B.builtAll()) &&
5969          "omp target parallel for loop exprs were not built");
5970 
5971   if (!CurContext->isDependentContext()) {
5972     // Finalize the clauses that need pre-built expressions for CodeGen.
5973     for (auto C : Clauses) {
5974       if (auto LC = dyn_cast<OMPLinearClause>(C))
5975         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
5976                                      B.NumIterations, *this, CurScope))
5977           return StmtError();
5978     }
5979   }
5980 
5981   getCurFunction()->setHasBranchProtectedScope();
5982   return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
5983                                                NestedLoopCount, Clauses, AStmt,
5984                                                B, DSAStack->isCancelRegion());
5985 }
5986 
5987 /// \brief Check for existence of a map clause in the list of clauses.
5988 static bool HasMapClause(ArrayRef<OMPClause *> Clauses) {
5989   for (ArrayRef<OMPClause *>::iterator I = Clauses.begin(), E = Clauses.end();
5990        I != E; ++I) {
5991     if (*I != nullptr && (*I)->getClauseKind() == OMPC_map) {
5992       return true;
5993     }
5994   }
5995 
5996   return false;
5997 }
5998 
5999 StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
6000                                                 Stmt *AStmt,
6001                                                 SourceLocation StartLoc,
6002                                                 SourceLocation EndLoc) {
6003   if (!AStmt)
6004     return StmtError();
6005 
6006   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6007 
6008   // OpenMP [2.10.1, Restrictions, p. 97]
6009   // At least one map clause must appear on the directive.
6010   if (!HasMapClause(Clauses)) {
6011     Diag(StartLoc, diag::err_omp_no_map_for_directive) <<
6012         getOpenMPDirectiveName(OMPD_target_data);
6013     return StmtError();
6014   }
6015 
6016   getCurFunction()->setHasBranchProtectedScope();
6017 
6018   return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
6019                                         AStmt);
6020 }
6021 
6022 StmtResult
6023 Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
6024                                           SourceLocation StartLoc,
6025                                           SourceLocation EndLoc) {
6026   // OpenMP [2.10.2, Restrictions, p. 99]
6027   // At least one map clause must appear on the directive.
6028   if (!HasMapClause(Clauses)) {
6029     Diag(StartLoc, diag::err_omp_no_map_for_directive)
6030         << getOpenMPDirectiveName(OMPD_target_enter_data);
6031     return StmtError();
6032   }
6033 
6034   return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc,
6035                                              Clauses);
6036 }
6037 
6038 StmtResult
6039 Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
6040                                          SourceLocation StartLoc,
6041                                          SourceLocation EndLoc) {
6042   // OpenMP [2.10.3, Restrictions, p. 102]
6043   // At least one map clause must appear on the directive.
6044   if (!HasMapClause(Clauses)) {
6045     Diag(StartLoc, diag::err_omp_no_map_for_directive)
6046         << getOpenMPDirectiveName(OMPD_target_exit_data);
6047     return StmtError();
6048   }
6049 
6050   return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses);
6051 }
6052 
6053 StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
6054                                            Stmt *AStmt, SourceLocation StartLoc,
6055                                            SourceLocation EndLoc) {
6056   if (!AStmt)
6057     return StmtError();
6058 
6059   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6060   // 1.2.2 OpenMP Language Terminology
6061   // Structured block - An executable statement with a single entry at the
6062   // top and a single exit at the bottom.
6063   // The point of exit cannot be a branch out of the structured block.
6064   // longjmp() and throw() must not violate the entry/exit criteria.
6065   CS->getCapturedDecl()->setNothrow();
6066 
6067   getCurFunction()->setHasBranchProtectedScope();
6068 
6069   return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
6070 }
6071 
6072 StmtResult
6073 Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
6074                                             SourceLocation EndLoc,
6075                                             OpenMPDirectiveKind CancelRegion) {
6076   if (CancelRegion != OMPD_parallel && CancelRegion != OMPD_for &&
6077       CancelRegion != OMPD_sections && CancelRegion != OMPD_taskgroup) {
6078     Diag(StartLoc, diag::err_omp_wrong_cancel_region)
6079         << getOpenMPDirectiveName(CancelRegion);
6080     return StmtError();
6081   }
6082   if (DSAStack->isParentNowaitRegion()) {
6083     Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
6084     return StmtError();
6085   }
6086   if (DSAStack->isParentOrderedRegion()) {
6087     Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
6088     return StmtError();
6089   }
6090   return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
6091                                                CancelRegion);
6092 }
6093 
6094 StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
6095                                             SourceLocation StartLoc,
6096                                             SourceLocation EndLoc,
6097                                             OpenMPDirectiveKind CancelRegion) {
6098   if (CancelRegion != OMPD_parallel && CancelRegion != OMPD_for &&
6099       CancelRegion != OMPD_sections && CancelRegion != OMPD_taskgroup) {
6100     Diag(StartLoc, diag::err_omp_wrong_cancel_region)
6101         << getOpenMPDirectiveName(CancelRegion);
6102     return StmtError();
6103   }
6104   if (DSAStack->isParentNowaitRegion()) {
6105     Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
6106     return StmtError();
6107   }
6108   if (DSAStack->isParentOrderedRegion()) {
6109     Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
6110     return StmtError();
6111   }
6112   DSAStack->setParentCancelRegion(/*Cancel=*/true);
6113   return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
6114                                     CancelRegion);
6115 }
6116 
6117 static bool checkGrainsizeNumTasksClauses(Sema &S,
6118                                           ArrayRef<OMPClause *> Clauses) {
6119   OMPClause *PrevClause = nullptr;
6120   bool ErrorFound = false;
6121   for (auto *C : Clauses) {
6122     if (C->getClauseKind() == OMPC_grainsize ||
6123         C->getClauseKind() == OMPC_num_tasks) {
6124       if (!PrevClause)
6125         PrevClause = C;
6126       else if (PrevClause->getClauseKind() != C->getClauseKind()) {
6127         S.Diag(C->getLocStart(),
6128                diag::err_omp_grainsize_num_tasks_mutually_exclusive)
6129             << getOpenMPClauseName(C->getClauseKind())
6130             << getOpenMPClauseName(PrevClause->getClauseKind());
6131         S.Diag(PrevClause->getLocStart(),
6132                diag::note_omp_previous_grainsize_num_tasks)
6133             << getOpenMPClauseName(PrevClause->getClauseKind());
6134         ErrorFound = true;
6135       }
6136     }
6137   }
6138   return ErrorFound;
6139 }
6140 
6141 StmtResult Sema::ActOnOpenMPTaskLoopDirective(
6142     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6143     SourceLocation EndLoc,
6144     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6145   if (!AStmt)
6146     return StmtError();
6147 
6148   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6149   OMPLoopDirective::HelperExprs B;
6150   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6151   // define the nested loops number.
6152   unsigned NestedLoopCount =
6153       CheckOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
6154                       /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
6155                       VarsWithImplicitDSA, B);
6156   if (NestedLoopCount == 0)
6157     return StmtError();
6158 
6159   assert((CurContext->isDependentContext() || B.builtAll()) &&
6160          "omp for loop exprs were not built");
6161 
6162   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6163   // The grainsize clause and num_tasks clause are mutually exclusive and may
6164   // not appear on the same taskloop directive.
6165   if (checkGrainsizeNumTasksClauses(*this, Clauses))
6166     return StmtError();
6167 
6168   getCurFunction()->setHasBranchProtectedScope();
6169   return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
6170                                       NestedLoopCount, Clauses, AStmt, B);
6171 }
6172 
6173 StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
6174     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6175     SourceLocation EndLoc,
6176     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6177   if (!AStmt)
6178     return StmtError();
6179 
6180   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6181   OMPLoopDirective::HelperExprs B;
6182   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6183   // define the nested loops number.
6184   unsigned NestedLoopCount =
6185       CheckOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
6186                       /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
6187                       VarsWithImplicitDSA, B);
6188   if (NestedLoopCount == 0)
6189     return StmtError();
6190 
6191   assert((CurContext->isDependentContext() || B.builtAll()) &&
6192          "omp for loop exprs were not built");
6193 
6194   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6195   // The grainsize clause and num_tasks clause are mutually exclusive and may
6196   // not appear on the same taskloop directive.
6197   if (checkGrainsizeNumTasksClauses(*this, Clauses))
6198     return StmtError();
6199 
6200   getCurFunction()->setHasBranchProtectedScope();
6201   return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
6202                                           NestedLoopCount, Clauses, AStmt, B);
6203 }
6204 
6205 StmtResult Sema::ActOnOpenMPDistributeDirective(
6206     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6207     SourceLocation EndLoc,
6208     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6209   if (!AStmt)
6210     return StmtError();
6211 
6212   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6213   OMPLoopDirective::HelperExprs B;
6214   // In presence of clause 'collapse' with number of loops, it will
6215   // define the nested loops number.
6216   unsigned NestedLoopCount =
6217       CheckOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
6218                       nullptr /*ordered not a clause on distribute*/, AStmt,
6219                       *this, *DSAStack, VarsWithImplicitDSA, B);
6220   if (NestedLoopCount == 0)
6221     return StmtError();
6222 
6223   assert((CurContext->isDependentContext() || B.builtAll()) &&
6224          "omp for loop exprs were not built");
6225 
6226   getCurFunction()->setHasBranchProtectedScope();
6227   return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
6228                                         NestedLoopCount, Clauses, AStmt, B);
6229 }
6230 
6231 OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
6232                                              SourceLocation StartLoc,
6233                                              SourceLocation LParenLoc,
6234                                              SourceLocation EndLoc) {
6235   OMPClause *Res = nullptr;
6236   switch (Kind) {
6237   case OMPC_final:
6238     Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
6239     break;
6240   case OMPC_num_threads:
6241     Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
6242     break;
6243   case OMPC_safelen:
6244     Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
6245     break;
6246   case OMPC_simdlen:
6247     Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
6248     break;
6249   case OMPC_collapse:
6250     Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
6251     break;
6252   case OMPC_ordered:
6253     Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
6254     break;
6255   case OMPC_device:
6256     Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
6257     break;
6258   case OMPC_num_teams:
6259     Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
6260     break;
6261   case OMPC_thread_limit:
6262     Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
6263     break;
6264   case OMPC_priority:
6265     Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
6266     break;
6267   case OMPC_grainsize:
6268     Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
6269     break;
6270   case OMPC_num_tasks:
6271     Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
6272     break;
6273   case OMPC_hint:
6274     Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
6275     break;
6276   case OMPC_if:
6277   case OMPC_default:
6278   case OMPC_proc_bind:
6279   case OMPC_schedule:
6280   case OMPC_private:
6281   case OMPC_firstprivate:
6282   case OMPC_lastprivate:
6283   case OMPC_shared:
6284   case OMPC_reduction:
6285   case OMPC_linear:
6286   case OMPC_aligned:
6287   case OMPC_copyin:
6288   case OMPC_copyprivate:
6289   case OMPC_nowait:
6290   case OMPC_untied:
6291   case OMPC_mergeable:
6292   case OMPC_threadprivate:
6293   case OMPC_flush:
6294   case OMPC_read:
6295   case OMPC_write:
6296   case OMPC_update:
6297   case OMPC_capture:
6298   case OMPC_seq_cst:
6299   case OMPC_depend:
6300   case OMPC_threads:
6301   case OMPC_simd:
6302   case OMPC_map:
6303   case OMPC_nogroup:
6304   case OMPC_dist_schedule:
6305   case OMPC_defaultmap:
6306   case OMPC_unknown:
6307     llvm_unreachable("Clause is not allowed.");
6308   }
6309   return Res;
6310 }
6311 
6312 OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
6313                                      Expr *Condition, SourceLocation StartLoc,
6314                                      SourceLocation LParenLoc,
6315                                      SourceLocation NameModifierLoc,
6316                                      SourceLocation ColonLoc,
6317                                      SourceLocation EndLoc) {
6318   Expr *ValExpr = Condition;
6319   if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
6320       !Condition->isInstantiationDependent() &&
6321       !Condition->containsUnexpandedParameterPack()) {
6322     ExprResult Val = ActOnBooleanCondition(DSAStack->getCurScope(),
6323                                            Condition->getExprLoc(), Condition);
6324     if (Val.isInvalid())
6325       return nullptr;
6326 
6327     ValExpr = Val.get();
6328   }
6329 
6330   return new (Context) OMPIfClause(NameModifier, ValExpr, StartLoc, LParenLoc,
6331                                    NameModifierLoc, ColonLoc, EndLoc);
6332 }
6333 
6334 OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
6335                                         SourceLocation StartLoc,
6336                                         SourceLocation LParenLoc,
6337                                         SourceLocation EndLoc) {
6338   Expr *ValExpr = Condition;
6339   if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
6340       !Condition->isInstantiationDependent() &&
6341       !Condition->containsUnexpandedParameterPack()) {
6342     ExprResult Val = ActOnBooleanCondition(DSAStack->getCurScope(),
6343                                            Condition->getExprLoc(), Condition);
6344     if (Val.isInvalid())
6345       return nullptr;
6346 
6347     ValExpr = Val.get();
6348   }
6349 
6350   return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
6351 }
6352 ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
6353                                                         Expr *Op) {
6354   if (!Op)
6355     return ExprError();
6356 
6357   class IntConvertDiagnoser : public ICEConvertDiagnoser {
6358   public:
6359     IntConvertDiagnoser()
6360         : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
6361     SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
6362                                          QualType T) override {
6363       return S.Diag(Loc, diag::err_omp_not_integral) << T;
6364     }
6365     SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
6366                                              QualType T) override {
6367       return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
6368     }
6369     SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
6370                                                QualType T,
6371                                                QualType ConvTy) override {
6372       return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
6373     }
6374     SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
6375                                            QualType ConvTy) override {
6376       return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
6377              << ConvTy->isEnumeralType() << ConvTy;
6378     }
6379     SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
6380                                             QualType T) override {
6381       return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
6382     }
6383     SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
6384                                         QualType ConvTy) override {
6385       return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
6386              << ConvTy->isEnumeralType() << ConvTy;
6387     }
6388     SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
6389                                              QualType) override {
6390       llvm_unreachable("conversion functions are permitted");
6391     }
6392   } ConvertDiagnoser;
6393   return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
6394 }
6395 
6396 static bool IsNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
6397                                       OpenMPClauseKind CKind,
6398                                       bool StrictlyPositive) {
6399   if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
6400       !ValExpr->isInstantiationDependent()) {
6401     SourceLocation Loc = ValExpr->getExprLoc();
6402     ExprResult Value =
6403         SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
6404     if (Value.isInvalid())
6405       return false;
6406 
6407     ValExpr = Value.get();
6408     // The expression must evaluate to a non-negative integer value.
6409     llvm::APSInt Result;
6410     if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
6411         Result.isSigned() &&
6412         !((!StrictlyPositive && Result.isNonNegative()) ||
6413           (StrictlyPositive && Result.isStrictlyPositive()))) {
6414       SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
6415           << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
6416           << ValExpr->getSourceRange();
6417       return false;
6418     }
6419   }
6420   return true;
6421 }
6422 
6423 OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
6424                                              SourceLocation StartLoc,
6425                                              SourceLocation LParenLoc,
6426                                              SourceLocation EndLoc) {
6427   Expr *ValExpr = NumThreads;
6428 
6429   // OpenMP [2.5, Restrictions]
6430   //  The num_threads expression must evaluate to a positive integer value.
6431   if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
6432                                  /*StrictlyPositive=*/true))
6433     return nullptr;
6434 
6435   return new (Context)
6436       OMPNumThreadsClause(ValExpr, StartLoc, LParenLoc, EndLoc);
6437 }
6438 
6439 ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
6440                                                        OpenMPClauseKind CKind,
6441                                                        bool StrictlyPositive) {
6442   if (!E)
6443     return ExprError();
6444   if (E->isValueDependent() || E->isTypeDependent() ||
6445       E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
6446     return E;
6447   llvm::APSInt Result;
6448   ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
6449   if (ICE.isInvalid())
6450     return ExprError();
6451   if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
6452       (!StrictlyPositive && !Result.isNonNegative())) {
6453     Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
6454         << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
6455         << E->getSourceRange();
6456     return ExprError();
6457   }
6458   if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
6459     Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
6460         << E->getSourceRange();
6461     return ExprError();
6462   }
6463   if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
6464     DSAStack->setAssociatedLoops(Result.getExtValue());
6465   else if (CKind == OMPC_ordered)
6466     DSAStack->setAssociatedLoops(Result.getExtValue());
6467   return ICE;
6468 }
6469 
6470 OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
6471                                           SourceLocation LParenLoc,
6472                                           SourceLocation EndLoc) {
6473   // OpenMP [2.8.1, simd construct, Description]
6474   // The parameter of the safelen clause must be a constant
6475   // positive integer expression.
6476   ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
6477   if (Safelen.isInvalid())
6478     return nullptr;
6479   return new (Context)
6480       OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
6481 }
6482 
6483 OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
6484                                           SourceLocation LParenLoc,
6485                                           SourceLocation EndLoc) {
6486   // OpenMP [2.8.1, simd construct, Description]
6487   // The parameter of the simdlen clause must be a constant
6488   // positive integer expression.
6489   ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
6490   if (Simdlen.isInvalid())
6491     return nullptr;
6492   return new (Context)
6493       OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
6494 }
6495 
6496 OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
6497                                            SourceLocation StartLoc,
6498                                            SourceLocation LParenLoc,
6499                                            SourceLocation EndLoc) {
6500   // OpenMP [2.7.1, loop construct, Description]
6501   // OpenMP [2.8.1, simd construct, Description]
6502   // OpenMP [2.9.6, distribute construct, Description]
6503   // The parameter of the collapse clause must be a constant
6504   // positive integer expression.
6505   ExprResult NumForLoopsResult =
6506       VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
6507   if (NumForLoopsResult.isInvalid())
6508     return nullptr;
6509   return new (Context)
6510       OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
6511 }
6512 
6513 OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
6514                                           SourceLocation EndLoc,
6515                                           SourceLocation LParenLoc,
6516                                           Expr *NumForLoops) {
6517   // OpenMP [2.7.1, loop construct, Description]
6518   // OpenMP [2.8.1, simd construct, Description]
6519   // OpenMP [2.9.6, distribute construct, Description]
6520   // The parameter of the ordered clause must be a constant
6521   // positive integer expression if any.
6522   if (NumForLoops && LParenLoc.isValid()) {
6523     ExprResult NumForLoopsResult =
6524         VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
6525     if (NumForLoopsResult.isInvalid())
6526       return nullptr;
6527     NumForLoops = NumForLoopsResult.get();
6528   } else
6529     NumForLoops = nullptr;
6530   DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops);
6531   return new (Context)
6532       OMPOrderedClause(NumForLoops, StartLoc, LParenLoc, EndLoc);
6533 }
6534 
6535 OMPClause *Sema::ActOnOpenMPSimpleClause(
6536     OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
6537     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
6538   OMPClause *Res = nullptr;
6539   switch (Kind) {
6540   case OMPC_default:
6541     Res =
6542         ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
6543                                  ArgumentLoc, StartLoc, LParenLoc, EndLoc);
6544     break;
6545   case OMPC_proc_bind:
6546     Res = ActOnOpenMPProcBindClause(
6547         static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
6548         LParenLoc, EndLoc);
6549     break;
6550   case OMPC_if:
6551   case OMPC_final:
6552   case OMPC_num_threads:
6553   case OMPC_safelen:
6554   case OMPC_simdlen:
6555   case OMPC_collapse:
6556   case OMPC_schedule:
6557   case OMPC_private:
6558   case OMPC_firstprivate:
6559   case OMPC_lastprivate:
6560   case OMPC_shared:
6561   case OMPC_reduction:
6562   case OMPC_linear:
6563   case OMPC_aligned:
6564   case OMPC_copyin:
6565   case OMPC_copyprivate:
6566   case OMPC_ordered:
6567   case OMPC_nowait:
6568   case OMPC_untied:
6569   case OMPC_mergeable:
6570   case OMPC_threadprivate:
6571   case OMPC_flush:
6572   case OMPC_read:
6573   case OMPC_write:
6574   case OMPC_update:
6575   case OMPC_capture:
6576   case OMPC_seq_cst:
6577   case OMPC_depend:
6578   case OMPC_device:
6579   case OMPC_threads:
6580   case OMPC_simd:
6581   case OMPC_map:
6582   case OMPC_num_teams:
6583   case OMPC_thread_limit:
6584   case OMPC_priority:
6585   case OMPC_grainsize:
6586   case OMPC_nogroup:
6587   case OMPC_num_tasks:
6588   case OMPC_hint:
6589   case OMPC_dist_schedule:
6590   case OMPC_defaultmap:
6591   case OMPC_unknown:
6592     llvm_unreachable("Clause is not allowed.");
6593   }
6594   return Res;
6595 }
6596 
6597 static std::string
6598 getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
6599                         ArrayRef<unsigned> Exclude = llvm::None) {
6600   std::string Values;
6601   unsigned Bound = Last >= 2 ? Last - 2 : 0;
6602   unsigned Skipped = Exclude.size();
6603   auto S = Exclude.begin(), E = Exclude.end();
6604   for (unsigned i = First; i < Last; ++i) {
6605     if (std::find(S, E, i) != E) {
6606       --Skipped;
6607       continue;
6608     }
6609     Values += "'";
6610     Values += getOpenMPSimpleClauseTypeName(K, i);
6611     Values += "'";
6612     if (i == Bound - Skipped)
6613       Values += " or ";
6614     else if (i != Bound + 1 - Skipped)
6615       Values += ", ";
6616   }
6617   return Values;
6618 }
6619 
6620 OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
6621                                           SourceLocation KindKwLoc,
6622                                           SourceLocation StartLoc,
6623                                           SourceLocation LParenLoc,
6624                                           SourceLocation EndLoc) {
6625   if (Kind == OMPC_DEFAULT_unknown) {
6626     static_assert(OMPC_DEFAULT_unknown > 0,
6627                   "OMPC_DEFAULT_unknown not greater than 0");
6628     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
6629         << getListOfPossibleValues(OMPC_default, /*First=*/0,
6630                                    /*Last=*/OMPC_DEFAULT_unknown)
6631         << getOpenMPClauseName(OMPC_default);
6632     return nullptr;
6633   }
6634   switch (Kind) {
6635   case OMPC_DEFAULT_none:
6636     DSAStack->setDefaultDSANone(KindKwLoc);
6637     break;
6638   case OMPC_DEFAULT_shared:
6639     DSAStack->setDefaultDSAShared(KindKwLoc);
6640     break;
6641   case OMPC_DEFAULT_unknown:
6642     llvm_unreachable("Clause kind is not allowed.");
6643     break;
6644   }
6645   return new (Context)
6646       OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
6647 }
6648 
6649 OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
6650                                            SourceLocation KindKwLoc,
6651                                            SourceLocation StartLoc,
6652                                            SourceLocation LParenLoc,
6653                                            SourceLocation EndLoc) {
6654   if (Kind == OMPC_PROC_BIND_unknown) {
6655     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
6656         << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
6657                                    /*Last=*/OMPC_PROC_BIND_unknown)
6658         << getOpenMPClauseName(OMPC_proc_bind);
6659     return nullptr;
6660   }
6661   return new (Context)
6662       OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
6663 }
6664 
6665 OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
6666     OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
6667     SourceLocation StartLoc, SourceLocation LParenLoc,
6668     ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
6669     SourceLocation EndLoc) {
6670   OMPClause *Res = nullptr;
6671   switch (Kind) {
6672   case OMPC_schedule:
6673     enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
6674     assert(Argument.size() == NumberOfElements &&
6675            ArgumentLoc.size() == NumberOfElements);
6676     Res = ActOnOpenMPScheduleClause(
6677         static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
6678         static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
6679         static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
6680         StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
6681         ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
6682     break;
6683   case OMPC_if:
6684     assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
6685     Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
6686                               Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
6687                               DelimLoc, EndLoc);
6688     break;
6689   case OMPC_dist_schedule:
6690     Res = ActOnOpenMPDistScheduleClause(
6691         static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
6692         StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
6693     break;
6694   case OMPC_defaultmap:
6695     enum { Modifier, DefaultmapKind };
6696     Res = ActOnOpenMPDefaultmapClause(
6697         static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
6698         static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
6699         StartLoc, LParenLoc, ArgumentLoc[Modifier],
6700         ArgumentLoc[DefaultmapKind], EndLoc);
6701     break;
6702   case OMPC_final:
6703   case OMPC_num_threads:
6704   case OMPC_safelen:
6705   case OMPC_simdlen:
6706   case OMPC_collapse:
6707   case OMPC_default:
6708   case OMPC_proc_bind:
6709   case OMPC_private:
6710   case OMPC_firstprivate:
6711   case OMPC_lastprivate:
6712   case OMPC_shared:
6713   case OMPC_reduction:
6714   case OMPC_linear:
6715   case OMPC_aligned:
6716   case OMPC_copyin:
6717   case OMPC_copyprivate:
6718   case OMPC_ordered:
6719   case OMPC_nowait:
6720   case OMPC_untied:
6721   case OMPC_mergeable:
6722   case OMPC_threadprivate:
6723   case OMPC_flush:
6724   case OMPC_read:
6725   case OMPC_write:
6726   case OMPC_update:
6727   case OMPC_capture:
6728   case OMPC_seq_cst:
6729   case OMPC_depend:
6730   case OMPC_device:
6731   case OMPC_threads:
6732   case OMPC_simd:
6733   case OMPC_map:
6734   case OMPC_num_teams:
6735   case OMPC_thread_limit:
6736   case OMPC_priority:
6737   case OMPC_grainsize:
6738   case OMPC_nogroup:
6739   case OMPC_num_tasks:
6740   case OMPC_hint:
6741   case OMPC_unknown:
6742     llvm_unreachable("Clause is not allowed.");
6743   }
6744   return Res;
6745 }
6746 
6747 static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
6748                                    OpenMPScheduleClauseModifier M2,
6749                                    SourceLocation M1Loc, SourceLocation M2Loc) {
6750   if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
6751     SmallVector<unsigned, 2> Excluded;
6752     if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
6753       Excluded.push_back(M2);
6754     if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
6755       Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
6756     if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
6757       Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
6758     S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
6759         << getListOfPossibleValues(OMPC_schedule,
6760                                    /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
6761                                    /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
6762                                    Excluded)
6763         << getOpenMPClauseName(OMPC_schedule);
6764     return true;
6765   }
6766   return false;
6767 }
6768 
6769 OMPClause *Sema::ActOnOpenMPScheduleClause(
6770     OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
6771     OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
6772     SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
6773     SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
6774   if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
6775       checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
6776     return nullptr;
6777   // OpenMP, 2.7.1, Loop Construct, Restrictions
6778   // Either the monotonic modifier or the nonmonotonic modifier can be specified
6779   // but not both.
6780   if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
6781       (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
6782        M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
6783       (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
6784        M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
6785     Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
6786         << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
6787         << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
6788     return nullptr;
6789   }
6790   if (Kind == OMPC_SCHEDULE_unknown) {
6791     std::string Values;
6792     if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
6793       unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
6794       Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
6795                                        /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
6796                                        Exclude);
6797     } else {
6798       Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
6799                                        /*Last=*/OMPC_SCHEDULE_unknown);
6800     }
6801     Diag(KindLoc, diag::err_omp_unexpected_clause_value)
6802         << Values << getOpenMPClauseName(OMPC_schedule);
6803     return nullptr;
6804   }
6805   // OpenMP, 2.7.1, Loop Construct, Restrictions
6806   // The nonmonotonic modifier can only be specified with schedule(dynamic) or
6807   // schedule(guided).
6808   if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
6809        M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
6810       Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
6811     Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
6812          diag::err_omp_schedule_nonmonotonic_static);
6813     return nullptr;
6814   }
6815   Expr *ValExpr = ChunkSize;
6816   Stmt *HelperValStmt = nullptr;
6817   if (ChunkSize) {
6818     if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
6819         !ChunkSize->isInstantiationDependent() &&
6820         !ChunkSize->containsUnexpandedParameterPack()) {
6821       SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
6822       ExprResult Val =
6823           PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
6824       if (Val.isInvalid())
6825         return nullptr;
6826 
6827       ValExpr = Val.get();
6828 
6829       // OpenMP [2.7.1, Restrictions]
6830       //  chunk_size must be a loop invariant integer expression with a positive
6831       //  value.
6832       llvm::APSInt Result;
6833       if (ValExpr->isIntegerConstantExpr(Result, Context)) {
6834         if (Result.isSigned() && !Result.isStrictlyPositive()) {
6835           Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
6836               << "schedule" << 1 << ChunkSize->getSourceRange();
6837           return nullptr;
6838         }
6839       } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) {
6840         ValExpr = buildCapture(*this, ValExpr);
6841         Decl *D = cast<DeclRefExpr>(ValExpr)->getDecl();
6842         HelperValStmt =
6843             new (Context) DeclStmt(DeclGroupRef::Create(Context, &D,
6844                                                         /*NumDecls=*/1),
6845                                    SourceLocation(), SourceLocation());
6846         ValExpr = DefaultLvalueConversion(ValExpr).get();
6847       }
6848     }
6849   }
6850 
6851   return new (Context)
6852       OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
6853                         ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
6854 }
6855 
6856 OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
6857                                    SourceLocation StartLoc,
6858                                    SourceLocation EndLoc) {
6859   OMPClause *Res = nullptr;
6860   switch (Kind) {
6861   case OMPC_ordered:
6862     Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
6863     break;
6864   case OMPC_nowait:
6865     Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
6866     break;
6867   case OMPC_untied:
6868     Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
6869     break;
6870   case OMPC_mergeable:
6871     Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
6872     break;
6873   case OMPC_read:
6874     Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
6875     break;
6876   case OMPC_write:
6877     Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
6878     break;
6879   case OMPC_update:
6880     Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
6881     break;
6882   case OMPC_capture:
6883     Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
6884     break;
6885   case OMPC_seq_cst:
6886     Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
6887     break;
6888   case OMPC_threads:
6889     Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
6890     break;
6891   case OMPC_simd:
6892     Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
6893     break;
6894   case OMPC_nogroup:
6895     Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
6896     break;
6897   case OMPC_if:
6898   case OMPC_final:
6899   case OMPC_num_threads:
6900   case OMPC_safelen:
6901   case OMPC_simdlen:
6902   case OMPC_collapse:
6903   case OMPC_schedule:
6904   case OMPC_private:
6905   case OMPC_firstprivate:
6906   case OMPC_lastprivate:
6907   case OMPC_shared:
6908   case OMPC_reduction:
6909   case OMPC_linear:
6910   case OMPC_aligned:
6911   case OMPC_copyin:
6912   case OMPC_copyprivate:
6913   case OMPC_default:
6914   case OMPC_proc_bind:
6915   case OMPC_threadprivate:
6916   case OMPC_flush:
6917   case OMPC_depend:
6918   case OMPC_device:
6919   case OMPC_map:
6920   case OMPC_num_teams:
6921   case OMPC_thread_limit:
6922   case OMPC_priority:
6923   case OMPC_grainsize:
6924   case OMPC_num_tasks:
6925   case OMPC_hint:
6926   case OMPC_dist_schedule:
6927   case OMPC_defaultmap:
6928   case OMPC_unknown:
6929     llvm_unreachable("Clause is not allowed.");
6930   }
6931   return Res;
6932 }
6933 
6934 OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
6935                                          SourceLocation EndLoc) {
6936   DSAStack->setNowaitRegion();
6937   return new (Context) OMPNowaitClause(StartLoc, EndLoc);
6938 }
6939 
6940 OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
6941                                          SourceLocation EndLoc) {
6942   return new (Context) OMPUntiedClause(StartLoc, EndLoc);
6943 }
6944 
6945 OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
6946                                             SourceLocation EndLoc) {
6947   return new (Context) OMPMergeableClause(StartLoc, EndLoc);
6948 }
6949 
6950 OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
6951                                        SourceLocation EndLoc) {
6952   return new (Context) OMPReadClause(StartLoc, EndLoc);
6953 }
6954 
6955 OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
6956                                         SourceLocation EndLoc) {
6957   return new (Context) OMPWriteClause(StartLoc, EndLoc);
6958 }
6959 
6960 OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
6961                                          SourceLocation EndLoc) {
6962   return new (Context) OMPUpdateClause(StartLoc, EndLoc);
6963 }
6964 
6965 OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
6966                                           SourceLocation EndLoc) {
6967   return new (Context) OMPCaptureClause(StartLoc, EndLoc);
6968 }
6969 
6970 OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
6971                                          SourceLocation EndLoc) {
6972   return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
6973 }
6974 
6975 OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
6976                                           SourceLocation EndLoc) {
6977   return new (Context) OMPThreadsClause(StartLoc, EndLoc);
6978 }
6979 
6980 OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
6981                                        SourceLocation EndLoc) {
6982   return new (Context) OMPSIMDClause(StartLoc, EndLoc);
6983 }
6984 
6985 OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
6986                                           SourceLocation EndLoc) {
6987   return new (Context) OMPNogroupClause(StartLoc, EndLoc);
6988 }
6989 
6990 OMPClause *Sema::ActOnOpenMPVarListClause(
6991     OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
6992     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
6993     SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
6994     const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
6995     OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier,
6996     OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
6997     SourceLocation DepLinMapLoc) {
6998   OMPClause *Res = nullptr;
6999   switch (Kind) {
7000   case OMPC_private:
7001     Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7002     break;
7003   case OMPC_firstprivate:
7004     Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7005     break;
7006   case OMPC_lastprivate:
7007     Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7008     break;
7009   case OMPC_shared:
7010     Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
7011     break;
7012   case OMPC_reduction:
7013     Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
7014                                      EndLoc, ReductionIdScopeSpec, ReductionId);
7015     break;
7016   case OMPC_linear:
7017     Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
7018                                   LinKind, DepLinMapLoc, ColonLoc, EndLoc);
7019     break;
7020   case OMPC_aligned:
7021     Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
7022                                    ColonLoc, EndLoc);
7023     break;
7024   case OMPC_copyin:
7025     Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
7026     break;
7027   case OMPC_copyprivate:
7028     Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7029     break;
7030   case OMPC_flush:
7031     Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
7032     break;
7033   case OMPC_depend:
7034     Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
7035                                   StartLoc, LParenLoc, EndLoc);
7036     break;
7037   case OMPC_map:
7038     Res = ActOnOpenMPMapClause(MapTypeModifier, MapType, IsMapTypeImplicit,
7039                                DepLinMapLoc, ColonLoc, VarList, StartLoc,
7040                                LParenLoc, EndLoc);
7041     break;
7042   case OMPC_if:
7043   case OMPC_final:
7044   case OMPC_num_threads:
7045   case OMPC_safelen:
7046   case OMPC_simdlen:
7047   case OMPC_collapse:
7048   case OMPC_default:
7049   case OMPC_proc_bind:
7050   case OMPC_schedule:
7051   case OMPC_ordered:
7052   case OMPC_nowait:
7053   case OMPC_untied:
7054   case OMPC_mergeable:
7055   case OMPC_threadprivate:
7056   case OMPC_read:
7057   case OMPC_write:
7058   case OMPC_update:
7059   case OMPC_capture:
7060   case OMPC_seq_cst:
7061   case OMPC_device:
7062   case OMPC_threads:
7063   case OMPC_simd:
7064   case OMPC_num_teams:
7065   case OMPC_thread_limit:
7066   case OMPC_priority:
7067   case OMPC_grainsize:
7068   case OMPC_nogroup:
7069   case OMPC_num_tasks:
7070   case OMPC_hint:
7071   case OMPC_dist_schedule:
7072   case OMPC_defaultmap:
7073   case OMPC_unknown:
7074     llvm_unreachable("Clause is not allowed.");
7075   }
7076   return Res;
7077 }
7078 
7079 ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
7080                                        ExprObjectKind OK) {
7081   SourceLocation Loc = Capture->getInit()->getExprLoc();
7082   ExprResult Res = BuildDeclRefExpr(
7083       Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
7084   if (!Res.isUsable())
7085     return ExprError();
7086   if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
7087     Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
7088     if (!Res.isUsable())
7089       return ExprError();
7090   }
7091   if (VK != VK_LValue && Res.get()->isGLValue()) {
7092     Res = DefaultLvalueConversion(Res.get());
7093     if (!Res.isUsable())
7094       return ExprError();
7095   }
7096   return Res;
7097 }
7098 
7099 static std::pair<ValueDecl *, bool> getPrivateItem(Sema &S, Expr *RefExpr) {
7100   if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
7101       RefExpr->containsUnexpandedParameterPack())
7102     return std::make_pair(nullptr, true);
7103 
7104   SourceLocation ELoc = RefExpr->getExprLoc();
7105   SourceRange SR = RefExpr->getSourceRange();
7106   // OpenMP [3.1, C/C++]
7107   //  A list item is a variable name.
7108   // OpenMP  [2.9.3.3, Restrictions, p.1]
7109   //  A variable that is part of another variable (as an array or
7110   //  structure element) cannot appear in a private clause.
7111   RefExpr = RefExpr->IgnoreParens();
7112   auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
7113   auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
7114   if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
7115       (S.getCurrentThisType().isNull() || !ME ||
7116        !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
7117        !isa<FieldDecl>(ME->getMemberDecl()))) {
7118     S.Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
7119         << (S.getCurrentThisType().isNull() ? 0 : 1) << SR;
7120     return std::make_pair(nullptr, false);
7121   }
7122   return std::make_pair(DE ? DE->getDecl() : ME->getMemberDecl(), false);
7123 }
7124 
7125 OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
7126                                           SourceLocation StartLoc,
7127                                           SourceLocation LParenLoc,
7128                                           SourceLocation EndLoc) {
7129   SmallVector<Expr *, 8> Vars;
7130   SmallVector<Expr *, 8> PrivateCopies;
7131   for (auto &RefExpr : VarList) {
7132     assert(RefExpr && "NULL expr in OpenMP private clause.");
7133     auto Res = getPrivateItem(*this, RefExpr);
7134     if (Res.second) {
7135       // It will be analyzed later.
7136       Vars.push_back(RefExpr);
7137       PrivateCopies.push_back(nullptr);
7138     }
7139     ValueDecl *D = Res.first;
7140     if (!D)
7141       continue;
7142 
7143     SourceLocation ELoc = RefExpr->getExprLoc();
7144     QualType Type = D->getType();
7145     auto *VD = dyn_cast<VarDecl>(D);
7146 
7147     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
7148     //  A variable that appears in a private clause must not have an incomplete
7149     //  type or a reference type.
7150     if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
7151       continue;
7152     Type = Type.getNonReferenceType();
7153 
7154     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
7155     // in a Construct]
7156     //  Variables with the predetermined data-sharing attributes may not be
7157     //  listed in data-sharing attributes clauses, except for the cases
7158     //  listed below. For these exceptions only, listing a predetermined
7159     //  variable in a data-sharing attribute clause is allowed and overrides
7160     //  the variable's predetermined data-sharing attributes.
7161     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
7162     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
7163       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
7164                                           << getOpenMPClauseName(OMPC_private);
7165       ReportOriginalDSA(*this, DSAStack, D, DVar);
7166       continue;
7167     }
7168 
7169     // Variably modified types are not supported for tasks.
7170     if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
7171         DSAStack->getCurrentDirective() == OMPD_task) {
7172       Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
7173           << getOpenMPClauseName(OMPC_private) << Type
7174           << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
7175       bool IsDecl =
7176           !VD ||
7177           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
7178       Diag(D->getLocation(),
7179            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
7180           << D;
7181       continue;
7182     }
7183 
7184     // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
7185     //  A variable of class type (or array thereof) that appears in a private
7186     //  clause requires an accessible, unambiguous default constructor for the
7187     //  class type.
7188     // Generate helper private variable and initialize it with the default
7189     // value. The address of the original variable is replaced by the address of
7190     // the new private variable in CodeGen. This new variable is not added to
7191     // IdResolver, so the code in the OpenMP region uses original variable for
7192     // proper diagnostics.
7193     Type = Type.getUnqualifiedType();
7194     auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
7195                                   D->hasAttrs() ? &D->getAttrs() : nullptr);
7196     ActOnUninitializedDecl(VDPrivate, /*TypeMayContainAuto=*/false);
7197     if (VDPrivate->isInvalidDecl())
7198       continue;
7199     auto VDPrivateRefExpr = buildDeclRefExpr(
7200         *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
7201 
7202     DeclRefExpr *Ref = nullptr;
7203     if (!VD)
7204       Ref = buildCapture(*this, D, RefExpr);
7205     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
7206     Vars.push_back(VD ? RefExpr->IgnoreParens() : Ref);
7207     PrivateCopies.push_back(VDPrivateRefExpr);
7208   }
7209 
7210   if (Vars.empty())
7211     return nullptr;
7212 
7213   return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
7214                                   PrivateCopies);
7215 }
7216 
7217 namespace {
7218 class DiagsUninitializedSeveretyRAII {
7219 private:
7220   DiagnosticsEngine &Diags;
7221   SourceLocation SavedLoc;
7222   bool IsIgnored;
7223 
7224 public:
7225   DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
7226                                  bool IsIgnored)
7227       : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
7228     if (!IsIgnored) {
7229       Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
7230                         /*Map*/ diag::Severity::Ignored, Loc);
7231     }
7232   }
7233   ~DiagsUninitializedSeveretyRAII() {
7234     if (!IsIgnored)
7235       Diags.popMappings(SavedLoc);
7236   }
7237 };
7238 }
7239 
7240 OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
7241                                                SourceLocation StartLoc,
7242                                                SourceLocation LParenLoc,
7243                                                SourceLocation EndLoc) {
7244   SmallVector<Expr *, 8> Vars;
7245   SmallVector<Expr *, 8> PrivateCopies;
7246   SmallVector<Expr *, 8> Inits;
7247   SmallVector<Decl *, 4> ExprCaptures;
7248   bool IsImplicitClause =
7249       StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
7250   auto ImplicitClauseLoc = DSAStack->getConstructLoc();
7251 
7252   for (auto &RefExpr : VarList) {
7253     assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
7254     auto Res = getPrivateItem(*this, RefExpr);
7255     if (Res.second) {
7256       // It will be analyzed later.
7257       Vars.push_back(RefExpr);
7258       PrivateCopies.push_back(nullptr);
7259       Inits.push_back(nullptr);
7260     }
7261     ValueDecl *D = Res.first;
7262     if (!D)
7263       continue;
7264 
7265     SourceLocation ELoc =
7266         IsImplicitClause ? ImplicitClauseLoc : RefExpr->getExprLoc();
7267     QualType Type = D->getType();
7268     auto *VD = dyn_cast<VarDecl>(D);
7269 
7270     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
7271     //  A variable that appears in a private clause must not have an incomplete
7272     //  type or a reference type.
7273     if (RequireCompleteType(ELoc, Type,
7274                             diag::err_omp_firstprivate_incomplete_type))
7275       continue;
7276     Type = Type.getNonReferenceType();
7277 
7278     // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
7279     //  A variable of class type (or array thereof) that appears in a private
7280     //  clause requires an accessible, unambiguous copy constructor for the
7281     //  class type.
7282     auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
7283 
7284     // If an implicit firstprivate variable found it was checked already.
7285     DSAStackTy::DSAVarData TopDVar;
7286     if (!IsImplicitClause) {
7287       DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
7288       TopDVar = DVar;
7289       bool IsConstant = ElemType.isConstant(Context);
7290       // OpenMP [2.4.13, Data-sharing Attribute Clauses]
7291       //  A list item that specifies a given variable may not appear in more
7292       // than one clause on the same directive, except that a variable may be
7293       //  specified in both firstprivate and lastprivate clauses.
7294       if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
7295           DVar.CKind != OMPC_lastprivate && DVar.RefExpr) {
7296         Diag(ELoc, diag::err_omp_wrong_dsa)
7297             << getOpenMPClauseName(DVar.CKind)
7298             << getOpenMPClauseName(OMPC_firstprivate);
7299         ReportOriginalDSA(*this, DSAStack, D, DVar);
7300         continue;
7301       }
7302 
7303       // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
7304       // in a Construct]
7305       //  Variables with the predetermined data-sharing attributes may not be
7306       //  listed in data-sharing attributes clauses, except for the cases
7307       //  listed below. For these exceptions only, listing a predetermined
7308       //  variable in a data-sharing attribute clause is allowed and overrides
7309       //  the variable's predetermined data-sharing attributes.
7310       // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
7311       // in a Construct, C/C++, p.2]
7312       //  Variables with const-qualified type having no mutable member may be
7313       //  listed in a firstprivate clause, even if they are static data members.
7314       if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
7315           DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
7316         Diag(ELoc, diag::err_omp_wrong_dsa)
7317             << getOpenMPClauseName(DVar.CKind)
7318             << getOpenMPClauseName(OMPC_firstprivate);
7319         ReportOriginalDSA(*this, DSAStack, D, DVar);
7320         continue;
7321       }
7322 
7323       OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
7324       // OpenMP [2.9.3.4, Restrictions, p.2]
7325       //  A list item that is private within a parallel region must not appear
7326       //  in a firstprivate clause on a worksharing construct if any of the
7327       //  worksharing regions arising from the worksharing construct ever bind
7328       //  to any of the parallel regions arising from the parallel construct.
7329       if (isOpenMPWorksharingDirective(CurrDir) &&
7330           !isOpenMPParallelDirective(CurrDir)) {
7331         DVar = DSAStack->getImplicitDSA(D, true);
7332         if (DVar.CKind != OMPC_shared &&
7333             (isOpenMPParallelDirective(DVar.DKind) ||
7334              DVar.DKind == OMPD_unknown)) {
7335           Diag(ELoc, diag::err_omp_required_access)
7336               << getOpenMPClauseName(OMPC_firstprivate)
7337               << getOpenMPClauseName(OMPC_shared);
7338           ReportOriginalDSA(*this, DSAStack, D, DVar);
7339           continue;
7340         }
7341       }
7342       // OpenMP [2.9.3.4, Restrictions, p.3]
7343       //  A list item that appears in a reduction clause of a parallel construct
7344       //  must not appear in a firstprivate clause on a worksharing or task
7345       //  construct if any of the worksharing or task regions arising from the
7346       //  worksharing or task construct ever bind to any of the parallel regions
7347       //  arising from the parallel construct.
7348       // OpenMP [2.9.3.4, Restrictions, p.4]
7349       //  A list item that appears in a reduction clause in worksharing
7350       //  construct must not appear in a firstprivate clause in a task construct
7351       //  encountered during execution of any of the worksharing regions arising
7352       //  from the worksharing construct.
7353       if (CurrDir == OMPD_task) {
7354         DVar =
7355             DSAStack->hasInnermostDSA(D, MatchesAnyClause(OMPC_reduction),
7356                                       [](OpenMPDirectiveKind K) -> bool {
7357                                         return isOpenMPParallelDirective(K) ||
7358                                                isOpenMPWorksharingDirective(K);
7359                                       },
7360                                       false);
7361         if (DVar.CKind == OMPC_reduction &&
7362             (isOpenMPParallelDirective(DVar.DKind) ||
7363              isOpenMPWorksharingDirective(DVar.DKind))) {
7364           Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
7365               << getOpenMPDirectiveName(DVar.DKind);
7366           ReportOriginalDSA(*this, DSAStack, D, DVar);
7367           continue;
7368         }
7369       }
7370 
7371       // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
7372       // A list item that is private within a teams region must not appear in a
7373       // firstprivate clause on a distribute construct if any of the distribute
7374       // regions arising from the distribute construct ever bind to any of the
7375       // teams regions arising from the teams construct.
7376       // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
7377       // A list item that appears in a reduction clause of a teams construct
7378       // must not appear in a firstprivate clause on a distribute construct if
7379       // any of the distribute regions arising from the distribute construct
7380       // ever bind to any of the teams regions arising from the teams construct.
7381       // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
7382       // A list item may appear in a firstprivate or lastprivate clause but not
7383       // both.
7384       if (CurrDir == OMPD_distribute) {
7385         DVar = DSAStack->hasInnermostDSA(D, MatchesAnyClause(OMPC_private),
7386                                          [](OpenMPDirectiveKind K) -> bool {
7387                                            return isOpenMPTeamsDirective(K);
7388                                          },
7389                                          false);
7390         if (DVar.CKind == OMPC_private && isOpenMPTeamsDirective(DVar.DKind)) {
7391           Diag(ELoc, diag::err_omp_firstprivate_distribute_private_teams);
7392           ReportOriginalDSA(*this, DSAStack, D, DVar);
7393           continue;
7394         }
7395         DVar = DSAStack->hasInnermostDSA(D, MatchesAnyClause(OMPC_reduction),
7396                                          [](OpenMPDirectiveKind K) -> bool {
7397                                            return isOpenMPTeamsDirective(K);
7398                                          },
7399                                          false);
7400         if (DVar.CKind == OMPC_reduction &&
7401             isOpenMPTeamsDirective(DVar.DKind)) {
7402           Diag(ELoc, diag::err_omp_firstprivate_distribute_in_teams_reduction);
7403           ReportOriginalDSA(*this, DSAStack, D, DVar);
7404           continue;
7405         }
7406         DVar = DSAStack->getTopDSA(D, false);
7407         if (DVar.CKind == OMPC_lastprivate) {
7408           Diag(ELoc, diag::err_omp_firstprivate_and_lastprivate_in_distribute);
7409           ReportOriginalDSA(*this, DSAStack, D, DVar);
7410           continue;
7411         }
7412       }
7413     }
7414 
7415     // Variably modified types are not supported for tasks.
7416     if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
7417         DSAStack->getCurrentDirective() == OMPD_task) {
7418       Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
7419           << getOpenMPClauseName(OMPC_firstprivate) << Type
7420           << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
7421       bool IsDecl =
7422           !VD ||
7423           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
7424       Diag(D->getLocation(),
7425            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
7426           << D;
7427       continue;
7428     }
7429 
7430     Type = Type.getUnqualifiedType();
7431     auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
7432                                   D->hasAttrs() ? &D->getAttrs() : nullptr);
7433     // Generate helper private variable and initialize it with the value of the
7434     // original variable. The address of the original variable is replaced by
7435     // the address of the new private variable in the CodeGen. This new variable
7436     // is not added to IdResolver, so the code in the OpenMP region uses
7437     // original variable for proper diagnostics and variable capturing.
7438     Expr *VDInitRefExpr = nullptr;
7439     // For arrays generate initializer for single element and replace it by the
7440     // original array element in CodeGen.
7441     if (Type->isArrayType()) {
7442       auto VDInit =
7443           buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
7444       VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
7445       auto Init = DefaultLvalueConversion(VDInitRefExpr).get();
7446       ElemType = ElemType.getUnqualifiedType();
7447       auto *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
7448                                       ".firstprivate.temp");
7449       InitializedEntity Entity =
7450           InitializedEntity::InitializeVariable(VDInitTemp);
7451       InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
7452 
7453       InitializationSequence InitSeq(*this, Entity, Kind, Init);
7454       ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
7455       if (Result.isInvalid())
7456         VDPrivate->setInvalidDecl();
7457       else
7458         VDPrivate->setInit(Result.getAs<Expr>());
7459       // Remove temp variable declaration.
7460       Context.Deallocate(VDInitTemp);
7461     } else {
7462       auto *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
7463                                   ".firstprivate.temp");
7464       VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
7465                                        RefExpr->getExprLoc());
7466       AddInitializerToDecl(VDPrivate,
7467                            DefaultLvalueConversion(VDInitRefExpr).get(),
7468                            /*DirectInit=*/false, /*TypeMayContainAuto=*/false);
7469     }
7470     if (VDPrivate->isInvalidDecl()) {
7471       if (IsImplicitClause) {
7472         Diag(RefExpr->getExprLoc(),
7473              diag::note_omp_task_predetermined_firstprivate_here);
7474       }
7475       continue;
7476     }
7477     CurContext->addDecl(VDPrivate);
7478     auto VDPrivateRefExpr = buildDeclRefExpr(
7479         *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
7480         RefExpr->getExprLoc());
7481     DeclRefExpr *Ref = nullptr;
7482     if (!VD) {
7483       if (TopDVar.CKind == OMPC_lastprivate)
7484         Ref = TopDVar.PrivateCopy;
7485       else {
7486         Ref = buildCapture(*this, D, RefExpr);
7487         if (!IsOpenMPCapturedDecl(D))
7488           ExprCaptures.push_back(Ref->getDecl());
7489       }
7490     }
7491     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
7492     Vars.push_back(VD ? RefExpr->IgnoreParens() : Ref);
7493     PrivateCopies.push_back(VDPrivateRefExpr);
7494     Inits.push_back(VDInitRefExpr);
7495   }
7496 
7497   if (Vars.empty())
7498     return nullptr;
7499   Stmt *PreInit = nullptr;
7500   if (!ExprCaptures.empty()) {
7501     PreInit = new (Context)
7502         DeclStmt(DeclGroupRef::Create(Context, ExprCaptures.begin(),
7503                                       ExprCaptures.size()),
7504                  SourceLocation(), SourceLocation());
7505   }
7506 
7507   return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
7508                                        Vars, PrivateCopies, Inits, PreInit);
7509 }
7510 
7511 OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
7512                                               SourceLocation StartLoc,
7513                                               SourceLocation LParenLoc,
7514                                               SourceLocation EndLoc) {
7515   SmallVector<Expr *, 8> Vars;
7516   SmallVector<Expr *, 8> SrcExprs;
7517   SmallVector<Expr *, 8> DstExprs;
7518   SmallVector<Expr *, 8> AssignmentOps;
7519   SmallVector<Decl *, 4> ExprCaptures;
7520   SmallVector<Expr *, 4> ExprPostUpdates;
7521   for (auto &RefExpr : VarList) {
7522     assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
7523     auto Res = getPrivateItem(*this, RefExpr);
7524     if (Res.second) {
7525       // It will be analyzed later.
7526       Vars.push_back(RefExpr);
7527       SrcExprs.push_back(nullptr);
7528       DstExprs.push_back(nullptr);
7529       AssignmentOps.push_back(nullptr);
7530     }
7531     ValueDecl *D = Res.first;
7532     if (!D)
7533       continue;
7534 
7535     SourceLocation ELoc = RefExpr->getExprLoc();
7536     QualType Type = D->getType();
7537     auto *VD = dyn_cast<VarDecl>(D);
7538 
7539     // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
7540     //  A variable that appears in a lastprivate clause must not have an
7541     //  incomplete type or a reference type.
7542     if (RequireCompleteType(ELoc, Type,
7543                             diag::err_omp_lastprivate_incomplete_type))
7544       continue;
7545     Type = Type.getNonReferenceType();
7546 
7547     // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
7548     // in a Construct]
7549     //  Variables with the predetermined data-sharing attributes may not be
7550     //  listed in data-sharing attributes clauses, except for the cases
7551     //  listed below.
7552     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
7553     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
7554         DVar.CKind != OMPC_firstprivate &&
7555         (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
7556       Diag(ELoc, diag::err_omp_wrong_dsa)
7557           << getOpenMPClauseName(DVar.CKind)
7558           << getOpenMPClauseName(OMPC_lastprivate);
7559       ReportOriginalDSA(*this, DSAStack, D, DVar);
7560       continue;
7561     }
7562 
7563     OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
7564     // OpenMP [2.14.3.5, Restrictions, p.2]
7565     // A list item that is private within a parallel region, or that appears in
7566     // the reduction clause of a parallel construct, must not appear in a
7567     // lastprivate clause on a worksharing construct if any of the corresponding
7568     // worksharing regions ever binds to any of the corresponding parallel
7569     // regions.
7570     DSAStackTy::DSAVarData TopDVar = DVar;
7571     if (isOpenMPWorksharingDirective(CurrDir) &&
7572         !isOpenMPParallelDirective(CurrDir)) {
7573       DVar = DSAStack->getImplicitDSA(D, true);
7574       if (DVar.CKind != OMPC_shared) {
7575         Diag(ELoc, diag::err_omp_required_access)
7576             << getOpenMPClauseName(OMPC_lastprivate)
7577             << getOpenMPClauseName(OMPC_shared);
7578         ReportOriginalDSA(*this, DSAStack, D, DVar);
7579         continue;
7580       }
7581     }
7582 
7583     // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
7584     // A list item may appear in a firstprivate or lastprivate clause but not
7585     // both.
7586     if (CurrDir == OMPD_distribute) {
7587       DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
7588       if (DVar.CKind == OMPC_firstprivate) {
7589         Diag(ELoc, diag::err_omp_firstprivate_and_lastprivate_in_distribute);
7590         ReportOriginalDSA(*this, DSAStack, D, DVar);
7591         continue;
7592       }
7593     }
7594 
7595     // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
7596     //  A variable of class type (or array thereof) that appears in a
7597     //  lastprivate clause requires an accessible, unambiguous default
7598     //  constructor for the class type, unless the list item is also specified
7599     //  in a firstprivate clause.
7600     //  A variable of class type (or array thereof) that appears in a
7601     //  lastprivate clause requires an accessible, unambiguous copy assignment
7602     //  operator for the class type.
7603     Type = Context.getBaseElementType(Type).getNonReferenceType();
7604     auto *SrcVD = buildVarDecl(*this, RefExpr->getLocStart(),
7605                                Type.getUnqualifiedType(), ".lastprivate.src",
7606                                D->hasAttrs() ? &D->getAttrs() : nullptr);
7607     auto *PseudoSrcExpr =
7608         buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
7609     auto *DstVD =
7610         buildVarDecl(*this, RefExpr->getLocStart(), Type, ".lastprivate.dst",
7611                      D->hasAttrs() ? &D->getAttrs() : nullptr);
7612     auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
7613     // For arrays generate assignment operation for single element and replace
7614     // it by the original array element in CodeGen.
7615     auto AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
7616                                    PseudoDstExpr, PseudoSrcExpr);
7617     if (AssignmentOp.isInvalid())
7618       continue;
7619     AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
7620                                        /*DiscardedValue=*/true);
7621     if (AssignmentOp.isInvalid())
7622       continue;
7623 
7624     DeclRefExpr *Ref = nullptr;
7625     if (!VD) {
7626       if (TopDVar.CKind == OMPC_firstprivate)
7627         Ref = TopDVar.PrivateCopy;
7628       else {
7629         Ref = buildCapture(*this, D, RefExpr);
7630         if (!IsOpenMPCapturedDecl(D))
7631           ExprCaptures.push_back(Ref->getDecl());
7632       }
7633       if (TopDVar.CKind == OMPC_firstprivate ||
7634           (!IsOpenMPCapturedDecl(D) &&
7635            !Ref->getDecl()->getType()->isReferenceType())) {
7636         ExprResult RefRes = DefaultLvalueConversion(Ref);
7637         if (!RefRes.isUsable())
7638           continue;
7639         ExprResult PostUpdateRes =
7640             BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
7641                        RefExpr->IgnoreParenLValueCasts(), RefRes.get());
7642         if (!PostUpdateRes.isUsable())
7643           continue;
7644         ExprPostUpdates.push_back(PostUpdateRes.get());
7645       }
7646     }
7647     if (TopDVar.CKind != OMPC_firstprivate)
7648       DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
7649     Vars.push_back(VD ? RefExpr->IgnoreParens() : Ref);
7650     SrcExprs.push_back(PseudoSrcExpr);
7651     DstExprs.push_back(PseudoDstExpr);
7652     AssignmentOps.push_back(AssignmentOp.get());
7653   }
7654 
7655   if (Vars.empty())
7656     return nullptr;
7657   Stmt *PreInit = nullptr;
7658   if (!ExprCaptures.empty()) {
7659     PreInit = new (Context)
7660         DeclStmt(DeclGroupRef::Create(Context, ExprCaptures.begin(),
7661                                       ExprCaptures.size()),
7662                  SourceLocation(), SourceLocation());
7663   }
7664   Expr *PostUpdate = nullptr;
7665   if (!ExprPostUpdates.empty()) {
7666     for (auto *E : ExprPostUpdates) {
7667       ExprResult PostUpdateRes =
7668           PostUpdate
7669               ? CreateBuiltinBinOp(SourceLocation(), BO_Comma, PostUpdate, E)
7670               : E;
7671       PostUpdate = PostUpdateRes.get();
7672     }
7673   }
7674 
7675   return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
7676                                       Vars, SrcExprs, DstExprs, AssignmentOps,
7677                                       PreInit, PostUpdate);
7678 }
7679 
7680 OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
7681                                          SourceLocation StartLoc,
7682                                          SourceLocation LParenLoc,
7683                                          SourceLocation EndLoc) {
7684   SmallVector<Expr *, 8> Vars;
7685   for (auto &RefExpr : VarList) {
7686     assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
7687     auto Res = getPrivateItem(*this, RefExpr);
7688     if (Res.second) {
7689       // It will be analyzed later.
7690       Vars.push_back(RefExpr);
7691     }
7692     ValueDecl *D = Res.first;
7693     if (!D)
7694       continue;
7695 
7696     SourceLocation ELoc = RefExpr->getExprLoc();
7697     auto *VD = dyn_cast<VarDecl>(D);
7698     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
7699     // in a Construct]
7700     //  Variables with the predetermined data-sharing attributes may not be
7701     //  listed in data-sharing attributes clauses, except for the cases
7702     //  listed below. For these exceptions only, listing a predetermined
7703     //  variable in a data-sharing attribute clause is allowed and overrides
7704     //  the variable's predetermined data-sharing attributes.
7705     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
7706     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
7707         DVar.RefExpr) {
7708       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
7709                                           << getOpenMPClauseName(OMPC_shared);
7710       ReportOriginalDSA(*this, DSAStack, D, DVar);
7711       continue;
7712     }
7713 
7714     DeclRefExpr *Ref = nullptr;
7715     if (!VD)
7716       Ref = buildCapture(*this, D, RefExpr);
7717     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
7718     Vars.push_back(VD ? RefExpr->IgnoreParens() : Ref);
7719   }
7720 
7721   if (Vars.empty())
7722     return nullptr;
7723 
7724   return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
7725 }
7726 
7727 namespace {
7728 class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
7729   DSAStackTy *Stack;
7730 
7731 public:
7732   bool VisitDeclRefExpr(DeclRefExpr *E) {
7733     if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
7734       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false);
7735       if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
7736         return false;
7737       if (DVar.CKind != OMPC_unknown)
7738         return true;
7739       DSAStackTy::DSAVarData DVarPrivate =
7740           Stack->hasDSA(VD, isOpenMPPrivate, MatchesAlways(), false);
7741       if (DVarPrivate.CKind != OMPC_unknown)
7742         return true;
7743       return false;
7744     }
7745     return false;
7746   }
7747   bool VisitStmt(Stmt *S) {
7748     for (auto Child : S->children()) {
7749       if (Child && Visit(Child))
7750         return true;
7751     }
7752     return false;
7753   }
7754   explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
7755 };
7756 } // namespace
7757 
7758 OMPClause *Sema::ActOnOpenMPReductionClause(
7759     ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
7760     SourceLocation ColonLoc, SourceLocation EndLoc,
7761     CXXScopeSpec &ReductionIdScopeSpec,
7762     const DeclarationNameInfo &ReductionId) {
7763   // TODO: Allow scope specification search when 'declare reduction' is
7764   // supported.
7765   assert(ReductionIdScopeSpec.isEmpty() &&
7766          "No support for scoped reduction identifiers yet.");
7767 
7768   auto DN = ReductionId.getName();
7769   auto OOK = DN.getCXXOverloadedOperator();
7770   BinaryOperatorKind BOK = BO_Comma;
7771 
7772   // OpenMP [2.14.3.6, reduction clause]
7773   // C
7774   // reduction-identifier is either an identifier or one of the following
7775   // operators: +, -, *,  &, |, ^, && and ||
7776   // C++
7777   // reduction-identifier is either an id-expression or one of the following
7778   // operators: +, -, *, &, |, ^, && and ||
7779   // FIXME: Only 'min' and 'max' identifiers are supported for now.
7780   switch (OOK) {
7781   case OO_Plus:
7782   case OO_Minus:
7783     BOK = BO_Add;
7784     break;
7785   case OO_Star:
7786     BOK = BO_Mul;
7787     break;
7788   case OO_Amp:
7789     BOK = BO_And;
7790     break;
7791   case OO_Pipe:
7792     BOK = BO_Or;
7793     break;
7794   case OO_Caret:
7795     BOK = BO_Xor;
7796     break;
7797   case OO_AmpAmp:
7798     BOK = BO_LAnd;
7799     break;
7800   case OO_PipePipe:
7801     BOK = BO_LOr;
7802     break;
7803   case OO_New:
7804   case OO_Delete:
7805   case OO_Array_New:
7806   case OO_Array_Delete:
7807   case OO_Slash:
7808   case OO_Percent:
7809   case OO_Tilde:
7810   case OO_Exclaim:
7811   case OO_Equal:
7812   case OO_Less:
7813   case OO_Greater:
7814   case OO_LessEqual:
7815   case OO_GreaterEqual:
7816   case OO_PlusEqual:
7817   case OO_MinusEqual:
7818   case OO_StarEqual:
7819   case OO_SlashEqual:
7820   case OO_PercentEqual:
7821   case OO_CaretEqual:
7822   case OO_AmpEqual:
7823   case OO_PipeEqual:
7824   case OO_LessLess:
7825   case OO_GreaterGreater:
7826   case OO_LessLessEqual:
7827   case OO_GreaterGreaterEqual:
7828   case OO_EqualEqual:
7829   case OO_ExclaimEqual:
7830   case OO_PlusPlus:
7831   case OO_MinusMinus:
7832   case OO_Comma:
7833   case OO_ArrowStar:
7834   case OO_Arrow:
7835   case OO_Call:
7836   case OO_Subscript:
7837   case OO_Conditional:
7838   case OO_Coawait:
7839   case NUM_OVERLOADED_OPERATORS:
7840     llvm_unreachable("Unexpected reduction identifier");
7841   case OO_None:
7842     if (auto II = DN.getAsIdentifierInfo()) {
7843       if (II->isStr("max"))
7844         BOK = BO_GT;
7845       else if (II->isStr("min"))
7846         BOK = BO_LT;
7847     }
7848     break;
7849   }
7850   SourceRange ReductionIdRange;
7851   if (ReductionIdScopeSpec.isValid()) {
7852     ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
7853   }
7854   ReductionIdRange.setEnd(ReductionId.getEndLoc());
7855   if (BOK == BO_Comma) {
7856     // Not allowed reduction identifier is found.
7857     Diag(ReductionId.getLocStart(), diag::err_omp_unknown_reduction_identifier)
7858         << ReductionIdRange;
7859     return nullptr;
7860   }
7861 
7862   SmallVector<Expr *, 8> Vars;
7863   SmallVector<Expr *, 8> Privates;
7864   SmallVector<Expr *, 8> LHSs;
7865   SmallVector<Expr *, 8> RHSs;
7866   SmallVector<Expr *, 8> ReductionOps;
7867   for (auto RefExpr : VarList) {
7868     assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
7869     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
7870       // It will be analyzed later.
7871       Vars.push_back(RefExpr);
7872       Privates.push_back(nullptr);
7873       LHSs.push_back(nullptr);
7874       RHSs.push_back(nullptr);
7875       ReductionOps.push_back(nullptr);
7876       continue;
7877     }
7878 
7879     if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
7880         RefExpr->isInstantiationDependent() ||
7881         RefExpr->containsUnexpandedParameterPack()) {
7882       // It will be analyzed later.
7883       Vars.push_back(RefExpr);
7884       Privates.push_back(nullptr);
7885       LHSs.push_back(nullptr);
7886       RHSs.push_back(nullptr);
7887       ReductionOps.push_back(nullptr);
7888       continue;
7889     }
7890 
7891     auto ELoc = RefExpr->getExprLoc();
7892     auto ERange = RefExpr->getSourceRange();
7893     // OpenMP [2.1, C/C++]
7894     //  A list item is a variable or array section, subject to the restrictions
7895     //  specified in Section 2.4 on page 42 and in each of the sections
7896     // describing clauses and directives for which a list appears.
7897     // OpenMP  [2.14.3.3, Restrictions, p.1]
7898     //  A variable that is part of another variable (as an array or
7899     //  structure element) cannot appear in a private clause.
7900     auto *DE = dyn_cast<DeclRefExpr>(RefExpr);
7901     auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr);
7902     auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr);
7903     if (!ASE && !OASE && (!DE || !isa<VarDecl>(DE->getDecl()))) {
7904       Diag(ELoc, diag::err_omp_expected_var_name_member_expr_or_array_item)
7905           << 0 << ERange;
7906       continue;
7907     }
7908     QualType Type;
7909     VarDecl *VD = nullptr;
7910     if (DE) {
7911       auto D = DE->getDecl();
7912       VD = cast<VarDecl>(D);
7913       Type = Context.getBaseElementType(VD->getType().getNonReferenceType());
7914     } else if (ASE) {
7915       Type = ASE->getType().getNonReferenceType();
7916       auto *Base = ASE->getBase()->IgnoreParenImpCasts();
7917       while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
7918         Base = TempASE->getBase()->IgnoreParenImpCasts();
7919       DE = dyn_cast<DeclRefExpr>(Base);
7920       if (DE)
7921         VD = dyn_cast<VarDecl>(DE->getDecl());
7922       if (!VD) {
7923         Diag(Base->getExprLoc(), diag::err_omp_expected_base_var_name)
7924             << 0 << Base->getSourceRange();
7925         continue;
7926       }
7927     } else if (OASE) {
7928       auto BaseType = OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
7929       if (auto *ATy = BaseType->getAsArrayTypeUnsafe())
7930         Type = ATy->getElementType();
7931       else
7932         Type = BaseType->getPointeeType();
7933       Type = Type.getNonReferenceType();
7934       auto *Base = OASE->getBase()->IgnoreParenImpCasts();
7935       while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
7936         Base = TempOASE->getBase()->IgnoreParenImpCasts();
7937       while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
7938         Base = TempASE->getBase()->IgnoreParenImpCasts();
7939       DE = dyn_cast<DeclRefExpr>(Base);
7940       if (DE)
7941         VD = dyn_cast<VarDecl>(DE->getDecl());
7942       if (!VD) {
7943         Diag(Base->getExprLoc(), diag::err_omp_expected_base_var_name)
7944             << 1 << Base->getSourceRange();
7945         continue;
7946       }
7947     }
7948 
7949     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
7950     //  A variable that appears in a private clause must not have an incomplete
7951     //  type or a reference type.
7952     if (RequireCompleteType(ELoc, Type,
7953                             diag::err_omp_reduction_incomplete_type))
7954       continue;
7955     // OpenMP [2.14.3.6, reduction clause, Restrictions]
7956     // A list item that appears in a reduction clause must not be
7957     // const-qualified.
7958     if (Type.getNonReferenceType().isConstant(Context)) {
7959       Diag(ELoc, diag::err_omp_const_reduction_list_item)
7960           << getOpenMPClauseName(OMPC_reduction) << Type << ERange;
7961       if (!ASE && !OASE) {
7962         bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
7963                       VarDecl::DeclarationOnly;
7964         Diag(VD->getLocation(),
7965              IsDecl ? diag::note_previous_decl : diag::note_defined_here)
7966             << VD;
7967       }
7968       continue;
7969     }
7970     // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
7971     //  If a list-item is a reference type then it must bind to the same object
7972     //  for all threads of the team.
7973     if (!ASE && !OASE) {
7974       VarDecl *VDDef = VD->getDefinition();
7975       if (VD->getType()->isReferenceType() && VDDef) {
7976         DSARefChecker Check(DSAStack);
7977         if (Check.Visit(VDDef->getInit())) {
7978           Diag(ELoc, diag::err_omp_reduction_ref_type_arg) << ERange;
7979           Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
7980           continue;
7981         }
7982       }
7983     }
7984     // OpenMP [2.14.3.6, reduction clause, Restrictions]
7985     // The type of a list item that appears in a reduction clause must be valid
7986     // for the reduction-identifier. For a max or min reduction in C, the type
7987     // of the list item must be an allowed arithmetic data type: char, int,
7988     // float, double, or _Bool, possibly modified with long, short, signed, or
7989     // unsigned. For a max or min reduction in C++, the type of the list item
7990     // must be an allowed arithmetic data type: char, wchar_t, int, float,
7991     // double, or bool, possibly modified with long, short, signed, or unsigned.
7992     if ((BOK == BO_GT || BOK == BO_LT) &&
7993         !(Type->isScalarType() ||
7994           (getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
7995       Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
7996           << getLangOpts().CPlusPlus;
7997       if (!ASE && !OASE) {
7998         bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
7999                       VarDecl::DeclarationOnly;
8000         Diag(VD->getLocation(),
8001              IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8002             << VD;
8003       }
8004       continue;
8005     }
8006     if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
8007         !getLangOpts().CPlusPlus && Type->isFloatingType()) {
8008       Diag(ELoc, diag::err_omp_clause_floating_type_arg);
8009       if (!ASE && !OASE) {
8010         bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
8011                       VarDecl::DeclarationOnly;
8012         Diag(VD->getLocation(),
8013              IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8014             << VD;
8015       }
8016       continue;
8017     }
8018     // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
8019     // in a Construct]
8020     //  Variables with the predetermined data-sharing attributes may not be
8021     //  listed in data-sharing attributes clauses, except for the cases
8022     //  listed below. For these exceptions only, listing a predetermined
8023     //  variable in a data-sharing attribute clause is allowed and overrides
8024     //  the variable's predetermined data-sharing attributes.
8025     // OpenMP [2.14.3.6, Restrictions, p.3]
8026     //  Any number of reduction clauses can be specified on the directive,
8027     //  but a list item can appear only once in the reduction clauses for that
8028     //  directive.
8029     DSAStackTy::DSAVarData DVar;
8030     DVar = DSAStack->getTopDSA(VD, false);
8031     if (DVar.CKind == OMPC_reduction) {
8032       Diag(ELoc, diag::err_omp_once_referenced)
8033           << getOpenMPClauseName(OMPC_reduction);
8034       if (DVar.RefExpr) {
8035         Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
8036       }
8037     } else if (DVar.CKind != OMPC_unknown) {
8038       Diag(ELoc, diag::err_omp_wrong_dsa)
8039           << getOpenMPClauseName(DVar.CKind)
8040           << getOpenMPClauseName(OMPC_reduction);
8041       ReportOriginalDSA(*this, DSAStack, VD, DVar);
8042       continue;
8043     }
8044 
8045     // OpenMP [2.14.3.6, Restrictions, p.1]
8046     //  A list item that appears in a reduction clause of a worksharing
8047     //  construct must be shared in the parallel regions to which any of the
8048     //  worksharing regions arising from the worksharing construct bind.
8049     OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
8050     if (isOpenMPWorksharingDirective(CurrDir) &&
8051         !isOpenMPParallelDirective(CurrDir)) {
8052       DVar = DSAStack->getImplicitDSA(VD, true);
8053       if (DVar.CKind != OMPC_shared) {
8054         Diag(ELoc, diag::err_omp_required_access)
8055             << getOpenMPClauseName(OMPC_reduction)
8056             << getOpenMPClauseName(OMPC_shared);
8057         ReportOriginalDSA(*this, DSAStack, VD, DVar);
8058         continue;
8059       }
8060     }
8061 
8062     Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
8063     auto *LHSVD = buildVarDecl(*this, ELoc, Type, ".reduction.lhs",
8064                                VD->hasAttrs() ? &VD->getAttrs() : nullptr);
8065     auto *RHSVD = buildVarDecl(*this, ELoc, Type, VD->getName(),
8066                                VD->hasAttrs() ? &VD->getAttrs() : nullptr);
8067     auto PrivateTy = Type;
8068     if (OASE ||
8069         (DE && VD->getType().getNonReferenceType()->isVariablyModifiedType())) {
8070       // For arays/array sections only:
8071       // Create pseudo array type for private copy. The size for this array will
8072       // be generated during codegen.
8073       // For array subscripts or single variables Private Ty is the same as Type
8074       // (type of the variable or single array element).
8075       PrivateTy = Context.getVariableArrayType(
8076           Type, new (Context) OpaqueValueExpr(SourceLocation(),
8077                                               Context.getSizeType(), VK_RValue),
8078           ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
8079     } else if (DE &&
8080                Context.getAsArrayType(VD->getType().getNonReferenceType()))
8081       PrivateTy = VD->getType().getNonReferenceType();
8082     // Private copy.
8083     auto *PrivateVD = buildVarDecl(*this, ELoc, PrivateTy, VD->getName(),
8084                                    VD->hasAttrs() ? &VD->getAttrs() : nullptr);
8085     // Add initializer for private variable.
8086     Expr *Init = nullptr;
8087     switch (BOK) {
8088     case BO_Add:
8089     case BO_Xor:
8090     case BO_Or:
8091     case BO_LOr:
8092       // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
8093       if (Type->isScalarType() || Type->isAnyComplexType()) {
8094         Init = ActOnIntegerConstant(ELoc, /*Val=*/0).get();
8095       }
8096       break;
8097     case BO_Mul:
8098     case BO_LAnd:
8099       if (Type->isScalarType() || Type->isAnyComplexType()) {
8100         // '*' and '&&' reduction ops - initializer is '1'.
8101         Init = ActOnIntegerConstant(ELoc, /*Val=*/1).get();
8102       }
8103       break;
8104     case BO_And: {
8105       // '&' reduction op - initializer is '~0'.
8106       QualType OrigType = Type;
8107       if (auto *ComplexTy = OrigType->getAs<ComplexType>()) {
8108         Type = ComplexTy->getElementType();
8109       }
8110       if (Type->isRealFloatingType()) {
8111         llvm::APFloat InitValue =
8112             llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
8113                                            /*isIEEE=*/true);
8114         Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
8115                                        Type, ELoc);
8116       } else if (Type->isScalarType()) {
8117         auto Size = Context.getTypeSize(Type);
8118         QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
8119         llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
8120         Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
8121       }
8122       if (Init && OrigType->isAnyComplexType()) {
8123         // Init = 0xFFFF + 0xFFFFi;
8124         auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
8125         Init = CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
8126       }
8127       Type = OrigType;
8128       break;
8129     }
8130     case BO_LT:
8131     case BO_GT: {
8132       // 'min' reduction op - initializer is 'Largest representable number in
8133       // the reduction list item type'.
8134       // 'max' reduction op - initializer is 'Least representable number in
8135       // the reduction list item type'.
8136       if (Type->isIntegerType() || Type->isPointerType()) {
8137         bool IsSigned = Type->hasSignedIntegerRepresentation();
8138         auto Size = Context.getTypeSize(Type);
8139         QualType IntTy =
8140             Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
8141         llvm::APInt InitValue =
8142             (BOK != BO_LT)
8143                 ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
8144                            : llvm::APInt::getMinValue(Size)
8145                 : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
8146                            : llvm::APInt::getMaxValue(Size);
8147         Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
8148         if (Type->isPointerType()) {
8149           // Cast to pointer type.
8150           auto CastExpr = BuildCStyleCastExpr(
8151               SourceLocation(), Context.getTrivialTypeSourceInfo(Type, ELoc),
8152               SourceLocation(), Init);
8153           if (CastExpr.isInvalid())
8154             continue;
8155           Init = CastExpr.get();
8156         }
8157       } else if (Type->isRealFloatingType()) {
8158         llvm::APFloat InitValue = llvm::APFloat::getLargest(
8159             Context.getFloatTypeSemantics(Type), BOK != BO_LT);
8160         Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
8161                                        Type, ELoc);
8162       }
8163       break;
8164     }
8165     case BO_PtrMemD:
8166     case BO_PtrMemI:
8167     case BO_MulAssign:
8168     case BO_Div:
8169     case BO_Rem:
8170     case BO_Sub:
8171     case BO_Shl:
8172     case BO_Shr:
8173     case BO_LE:
8174     case BO_GE:
8175     case BO_EQ:
8176     case BO_NE:
8177     case BO_AndAssign:
8178     case BO_XorAssign:
8179     case BO_OrAssign:
8180     case BO_Assign:
8181     case BO_AddAssign:
8182     case BO_SubAssign:
8183     case BO_DivAssign:
8184     case BO_RemAssign:
8185     case BO_ShlAssign:
8186     case BO_ShrAssign:
8187     case BO_Comma:
8188       llvm_unreachable("Unexpected reduction operation");
8189     }
8190     if (Init) {
8191       AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false,
8192                            /*TypeMayContainAuto=*/false);
8193     } else
8194       ActOnUninitializedDecl(RHSVD, /*TypeMayContainAuto=*/false);
8195     if (!RHSVD->hasInit()) {
8196       Diag(ELoc, diag::err_omp_reduction_id_not_compatible) << Type
8197                                                             << ReductionIdRange;
8198       if (VD) {
8199         bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
8200                       VarDecl::DeclarationOnly;
8201         Diag(VD->getLocation(),
8202              IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8203             << VD;
8204       }
8205       continue;
8206     }
8207     // Store initializer for single element in private copy. Will be used during
8208     // codegen.
8209     PrivateVD->setInit(RHSVD->getInit());
8210     PrivateVD->setInitStyle(RHSVD->getInitStyle());
8211     auto *LHSDRE = buildDeclRefExpr(*this, LHSVD, Type, ELoc);
8212     auto *RHSDRE = buildDeclRefExpr(*this, RHSVD, Type, ELoc);
8213     auto *PrivateDRE = buildDeclRefExpr(*this, PrivateVD, PrivateTy, ELoc);
8214     ExprResult ReductionOp =
8215         BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(), BOK,
8216                    LHSDRE, RHSDRE);
8217     if (ReductionOp.isUsable()) {
8218       if (BOK != BO_LT && BOK != BO_GT) {
8219         ReductionOp =
8220             BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
8221                        BO_Assign, LHSDRE, ReductionOp.get());
8222       } else {
8223         auto *ConditionalOp = new (Context) ConditionalOperator(
8224             ReductionOp.get(), SourceLocation(), LHSDRE, SourceLocation(),
8225             RHSDRE, Type, VK_LValue, OK_Ordinary);
8226         ReductionOp =
8227             BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
8228                        BO_Assign, LHSDRE, ConditionalOp);
8229       }
8230       ReductionOp = ActOnFinishFullExpr(ReductionOp.get());
8231     }
8232     if (ReductionOp.isInvalid())
8233       continue;
8234 
8235     DSAStack->addDSA(VD, DE, OMPC_reduction);
8236     Vars.push_back(RefExpr);
8237     Privates.push_back(PrivateDRE);
8238     LHSs.push_back(LHSDRE);
8239     RHSs.push_back(RHSDRE);
8240     ReductionOps.push_back(ReductionOp.get());
8241   }
8242 
8243   if (Vars.empty())
8244     return nullptr;
8245 
8246   return OMPReductionClause::Create(
8247       Context, StartLoc, LParenLoc, ColonLoc, EndLoc, Vars,
8248       ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, Privates,
8249       LHSs, RHSs, ReductionOps);
8250 }
8251 
8252 OMPClause *Sema::ActOnOpenMPLinearClause(
8253     ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
8254     SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
8255     SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
8256   SmallVector<Expr *, 8> Vars;
8257   SmallVector<Expr *, 8> Privates;
8258   SmallVector<Expr *, 8> Inits;
8259   if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
8260       LinKind == OMPC_LINEAR_unknown) {
8261     Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
8262     LinKind = OMPC_LINEAR_val;
8263   }
8264   for (auto &RefExpr : VarList) {
8265     assert(RefExpr && "NULL expr in OpenMP linear clause.");
8266     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
8267       // It will be analyzed later.
8268       Vars.push_back(RefExpr);
8269       Privates.push_back(nullptr);
8270       Inits.push_back(nullptr);
8271       continue;
8272     }
8273 
8274     // OpenMP [2.14.3.7, linear clause]
8275     // A list item that appears in a linear clause is subject to the private
8276     // clause semantics described in Section 2.14.3.3 on page 159 except as
8277     // noted. In addition, the value of the new list item on each iteration
8278     // of the associated loop(s) corresponds to the value of the original
8279     // list item before entering the construct plus the logical number of
8280     // the iteration times linear-step.
8281 
8282     SourceLocation ELoc = RefExpr->getExprLoc();
8283     // OpenMP [2.1, C/C++]
8284     //  A list item is a variable name.
8285     // OpenMP  [2.14.3.3, Restrictions, p.1]
8286     //  A variable that is part of another variable (as an array or
8287     //  structure element) cannot appear in a private clause.
8288     DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
8289     if (!DE || !isa<VarDecl>(DE->getDecl())) {
8290       Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
8291           << 0 << RefExpr->getSourceRange();
8292       continue;
8293     }
8294 
8295     VarDecl *VD = cast<VarDecl>(DE->getDecl());
8296 
8297     // OpenMP [2.14.3.7, linear clause]
8298     //  A list-item cannot appear in more than one linear clause.
8299     //  A list-item that appears in a linear clause cannot appear in any
8300     //  other data-sharing attribute clause.
8301     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
8302     if (DVar.RefExpr) {
8303       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
8304                                           << getOpenMPClauseName(OMPC_linear);
8305       ReportOriginalDSA(*this, DSAStack, VD, DVar);
8306       continue;
8307     }
8308 
8309     QualType QType = VD->getType();
8310     if (QType->isDependentType() || QType->isInstantiationDependentType()) {
8311       // It will be analyzed later.
8312       Vars.push_back(DE);
8313       Privates.push_back(nullptr);
8314       Inits.push_back(nullptr);
8315       continue;
8316     }
8317 
8318     // A variable must not have an incomplete type or a reference type.
8319     if (RequireCompleteType(ELoc, QType,
8320                             diag::err_omp_linear_incomplete_type)) {
8321       continue;
8322     }
8323     if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
8324         !QType->isReferenceType()) {
8325       Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
8326           << QType << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
8327       continue;
8328     }
8329     QType = QType.getNonReferenceType();
8330 
8331     // A list item must not be const-qualified.
8332     if (QType.isConstant(Context)) {
8333       Diag(ELoc, diag::err_omp_const_variable)
8334           << getOpenMPClauseName(OMPC_linear);
8335       bool IsDecl =
8336           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
8337       Diag(VD->getLocation(),
8338            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8339           << VD;
8340       continue;
8341     }
8342 
8343     // A list item must be of integral or pointer type.
8344     QType = QType.getUnqualifiedType().getCanonicalType();
8345     const Type *Ty = QType.getTypePtrOrNull();
8346     if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
8347                 !Ty->isPointerType())) {
8348       Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << QType;
8349       bool IsDecl =
8350           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
8351       Diag(VD->getLocation(),
8352            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8353           << VD;
8354       continue;
8355     }
8356 
8357     // Build private copy of original var.
8358     auto *Private = buildVarDecl(*this, ELoc, QType, VD->getName(),
8359                                  VD->hasAttrs() ? &VD->getAttrs() : nullptr);
8360     auto *PrivateRef = buildDeclRefExpr(
8361         *this, Private, DE->getType().getUnqualifiedType(), DE->getExprLoc());
8362     // Build var to save initial value.
8363     VarDecl *Init = buildVarDecl(*this, ELoc, QType, ".linear.start");
8364     Expr *InitExpr;
8365     if (LinKind == OMPC_LINEAR_uval)
8366       InitExpr = VD->getInit();
8367     else
8368       InitExpr = DE;
8369     AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
8370                          /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
8371     auto InitRef = buildDeclRefExpr(
8372         *this, Init, DE->getType().getUnqualifiedType(), DE->getExprLoc());
8373     DSAStack->addDSA(VD, DE, OMPC_linear);
8374     Vars.push_back(DE);
8375     Privates.push_back(PrivateRef);
8376     Inits.push_back(InitRef);
8377   }
8378 
8379   if (Vars.empty())
8380     return nullptr;
8381 
8382   Expr *StepExpr = Step;
8383   Expr *CalcStepExpr = nullptr;
8384   if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
8385       !Step->isInstantiationDependent() &&
8386       !Step->containsUnexpandedParameterPack()) {
8387     SourceLocation StepLoc = Step->getLocStart();
8388     ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
8389     if (Val.isInvalid())
8390       return nullptr;
8391     StepExpr = Val.get();
8392 
8393     // Build var to save the step value.
8394     VarDecl *SaveVar =
8395         buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
8396     ExprResult SaveRef =
8397         buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
8398     ExprResult CalcStep =
8399         BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
8400     CalcStep = ActOnFinishFullExpr(CalcStep.get());
8401 
8402     // Warn about zero linear step (it would be probably better specified as
8403     // making corresponding variables 'const').
8404     llvm::APSInt Result;
8405     bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
8406     if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
8407       Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
8408                                                      << (Vars.size() > 1);
8409     if (!IsConstant && CalcStep.isUsable()) {
8410       // Calculate the step beforehand instead of doing this on each iteration.
8411       // (This is not used if the number of iterations may be kfold-ed).
8412       CalcStepExpr = CalcStep.get();
8413     }
8414   }
8415 
8416   return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
8417                                  ColonLoc, EndLoc, Vars, Privates, Inits,
8418                                  StepExpr, CalcStepExpr);
8419 }
8420 
8421 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
8422                                      Expr *NumIterations, Sema &SemaRef,
8423                                      Scope *S) {
8424   // Walk the vars and build update/final expressions for the CodeGen.
8425   SmallVector<Expr *, 8> Updates;
8426   SmallVector<Expr *, 8> Finals;
8427   Expr *Step = Clause.getStep();
8428   Expr *CalcStep = Clause.getCalcStep();
8429   // OpenMP [2.14.3.7, linear clause]
8430   // If linear-step is not specified it is assumed to be 1.
8431   if (Step == nullptr)
8432     Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
8433   else if (CalcStep)
8434     Step = cast<BinaryOperator>(CalcStep)->getLHS();
8435   bool HasErrors = false;
8436   auto CurInit = Clause.inits().begin();
8437   auto CurPrivate = Clause.privates().begin();
8438   auto LinKind = Clause.getModifier();
8439   for (auto &RefExpr : Clause.varlists()) {
8440     Expr *InitExpr = *CurInit;
8441 
8442     // Build privatized reference to the current linear var.
8443     auto DE = cast<DeclRefExpr>(RefExpr);
8444     Expr *CapturedRef;
8445     if (LinKind == OMPC_LINEAR_uval)
8446       CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
8447     else
8448       CapturedRef =
8449           buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
8450                            DE->getType().getUnqualifiedType(), DE->getExprLoc(),
8451                            /*RefersToCapture=*/true);
8452 
8453     // Build update: Var = InitExpr + IV * Step
8454     ExprResult Update =
8455         BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate,
8456                            InitExpr, IV, Step, /* Subtract */ false);
8457     Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getLocStart(),
8458                                          /*DiscardedValue=*/true);
8459 
8460     // Build final: Var = InitExpr + NumIterations * Step
8461     ExprResult Final =
8462         BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
8463                            InitExpr, NumIterations, Step, /* Subtract */ false);
8464     Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getLocStart(),
8465                                         /*DiscardedValue=*/true);
8466     if (!Update.isUsable() || !Final.isUsable()) {
8467       Updates.push_back(nullptr);
8468       Finals.push_back(nullptr);
8469       HasErrors = true;
8470     } else {
8471       Updates.push_back(Update.get());
8472       Finals.push_back(Final.get());
8473     }
8474     ++CurInit;
8475     ++CurPrivate;
8476   }
8477   Clause.setUpdates(Updates);
8478   Clause.setFinals(Finals);
8479   return HasErrors;
8480 }
8481 
8482 OMPClause *Sema::ActOnOpenMPAlignedClause(
8483     ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
8484     SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
8485 
8486   SmallVector<Expr *, 8> Vars;
8487   for (auto &RefExpr : VarList) {
8488     assert(RefExpr && "NULL expr in OpenMP aligned clause.");
8489     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
8490       // It will be analyzed later.
8491       Vars.push_back(RefExpr);
8492       continue;
8493     }
8494 
8495     SourceLocation ELoc = RefExpr->getExprLoc();
8496     // OpenMP [2.1, C/C++]
8497     //  A list item is a variable name.
8498     DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
8499     if (!DE || !isa<VarDecl>(DE->getDecl())) {
8500       Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
8501           << 0 << RefExpr->getSourceRange();
8502       continue;
8503     }
8504 
8505     VarDecl *VD = cast<VarDecl>(DE->getDecl());
8506 
8507     // OpenMP  [2.8.1, simd construct, Restrictions]
8508     // The type of list items appearing in the aligned clause must be
8509     // array, pointer, reference to array, or reference to pointer.
8510     QualType QType = VD->getType();
8511     QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
8512     const Type *Ty = QType.getTypePtrOrNull();
8513     if (!Ty || (!Ty->isDependentType() && !Ty->isArrayType() &&
8514                 !Ty->isPointerType())) {
8515       Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
8516           << QType << getLangOpts().CPlusPlus << RefExpr->getSourceRange();
8517       bool IsDecl =
8518           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
8519       Diag(VD->getLocation(),
8520            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8521           << VD;
8522       continue;
8523     }
8524 
8525     // OpenMP  [2.8.1, simd construct, Restrictions]
8526     // A list-item cannot appear in more than one aligned clause.
8527     if (Expr *PrevRef = DSAStack->addUniqueAligned(VD, DE)) {
8528       Diag(ELoc, diag::err_omp_aligned_twice) << RefExpr->getSourceRange();
8529       Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
8530           << getOpenMPClauseName(OMPC_aligned);
8531       continue;
8532     }
8533 
8534     Vars.push_back(DE);
8535   }
8536 
8537   // OpenMP [2.8.1, simd construct, Description]
8538   // The parameter of the aligned clause, alignment, must be a constant
8539   // positive integer expression.
8540   // If no optional parameter is specified, implementation-defined default
8541   // alignments for SIMD instructions on the target platforms are assumed.
8542   if (Alignment != nullptr) {
8543     ExprResult AlignResult =
8544         VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
8545     if (AlignResult.isInvalid())
8546       return nullptr;
8547     Alignment = AlignResult.get();
8548   }
8549   if (Vars.empty())
8550     return nullptr;
8551 
8552   return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
8553                                   EndLoc, Vars, Alignment);
8554 }
8555 
8556 OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
8557                                          SourceLocation StartLoc,
8558                                          SourceLocation LParenLoc,
8559                                          SourceLocation EndLoc) {
8560   SmallVector<Expr *, 8> Vars;
8561   SmallVector<Expr *, 8> SrcExprs;
8562   SmallVector<Expr *, 8> DstExprs;
8563   SmallVector<Expr *, 8> AssignmentOps;
8564   for (auto &RefExpr : VarList) {
8565     assert(RefExpr && "NULL expr in OpenMP copyin clause.");
8566     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
8567       // It will be analyzed later.
8568       Vars.push_back(RefExpr);
8569       SrcExprs.push_back(nullptr);
8570       DstExprs.push_back(nullptr);
8571       AssignmentOps.push_back(nullptr);
8572       continue;
8573     }
8574 
8575     SourceLocation ELoc = RefExpr->getExprLoc();
8576     // OpenMP [2.1, C/C++]
8577     //  A list item is a variable name.
8578     // OpenMP  [2.14.4.1, Restrictions, p.1]
8579     //  A list item that appears in a copyin clause must be threadprivate.
8580     DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
8581     if (!DE || !isa<VarDecl>(DE->getDecl())) {
8582       Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
8583           << 0 << RefExpr->getSourceRange();
8584       continue;
8585     }
8586 
8587     Decl *D = DE->getDecl();
8588     VarDecl *VD = cast<VarDecl>(D);
8589 
8590     QualType Type = VD->getType();
8591     if (Type->isDependentType() || Type->isInstantiationDependentType()) {
8592       // It will be analyzed later.
8593       Vars.push_back(DE);
8594       SrcExprs.push_back(nullptr);
8595       DstExprs.push_back(nullptr);
8596       AssignmentOps.push_back(nullptr);
8597       continue;
8598     }
8599 
8600     // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
8601     //  A list item that appears in a copyin clause must be threadprivate.
8602     if (!DSAStack->isThreadPrivate(VD)) {
8603       Diag(ELoc, diag::err_omp_required_access)
8604           << getOpenMPClauseName(OMPC_copyin)
8605           << getOpenMPDirectiveName(OMPD_threadprivate);
8606       continue;
8607     }
8608 
8609     // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
8610     //  A variable of class type (or array thereof) that appears in a
8611     //  copyin clause requires an accessible, unambiguous copy assignment
8612     //  operator for the class type.
8613     auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
8614     auto *SrcVD =
8615         buildVarDecl(*this, DE->getLocStart(), ElemType.getUnqualifiedType(),
8616                      ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
8617     auto *PseudoSrcExpr = buildDeclRefExpr(
8618         *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
8619     auto *DstVD =
8620         buildVarDecl(*this, DE->getLocStart(), ElemType, ".copyin.dst",
8621                      VD->hasAttrs() ? &VD->getAttrs() : nullptr);
8622     auto *PseudoDstExpr =
8623         buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
8624     // For arrays generate assignment operation for single element and replace
8625     // it by the original array element in CodeGen.
8626     auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
8627                                    PseudoDstExpr, PseudoSrcExpr);
8628     if (AssignmentOp.isInvalid())
8629       continue;
8630     AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
8631                                        /*DiscardedValue=*/true);
8632     if (AssignmentOp.isInvalid())
8633       continue;
8634 
8635     DSAStack->addDSA(VD, DE, OMPC_copyin);
8636     Vars.push_back(DE);
8637     SrcExprs.push_back(PseudoSrcExpr);
8638     DstExprs.push_back(PseudoDstExpr);
8639     AssignmentOps.push_back(AssignmentOp.get());
8640   }
8641 
8642   if (Vars.empty())
8643     return nullptr;
8644 
8645   return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
8646                                  SrcExprs, DstExprs, AssignmentOps);
8647 }
8648 
8649 OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
8650                                               SourceLocation StartLoc,
8651                                               SourceLocation LParenLoc,
8652                                               SourceLocation EndLoc) {
8653   SmallVector<Expr *, 8> Vars;
8654   SmallVector<Expr *, 8> SrcExprs;
8655   SmallVector<Expr *, 8> DstExprs;
8656   SmallVector<Expr *, 8> AssignmentOps;
8657   for (auto &RefExpr : VarList) {
8658     assert(RefExpr && "NULL expr in OpenMP copyprivate clause.");
8659     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
8660       // It will be analyzed later.
8661       Vars.push_back(RefExpr);
8662       SrcExprs.push_back(nullptr);
8663       DstExprs.push_back(nullptr);
8664       AssignmentOps.push_back(nullptr);
8665       continue;
8666     }
8667 
8668     SourceLocation ELoc = RefExpr->getExprLoc();
8669     // OpenMP [2.1, C/C++]
8670     //  A list item is a variable name.
8671     // OpenMP  [2.14.4.1, Restrictions, p.1]
8672     //  A list item that appears in a copyin clause must be threadprivate.
8673     DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
8674     if (!DE || !isa<VarDecl>(DE->getDecl())) {
8675       Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
8676           << 0 << RefExpr->getSourceRange();
8677       continue;
8678     }
8679 
8680     Decl *D = DE->getDecl();
8681     VarDecl *VD = cast<VarDecl>(D);
8682 
8683     QualType Type = VD->getType();
8684     if (Type->isDependentType() || Type->isInstantiationDependentType()) {
8685       // It will be analyzed later.
8686       Vars.push_back(DE);
8687       SrcExprs.push_back(nullptr);
8688       DstExprs.push_back(nullptr);
8689       AssignmentOps.push_back(nullptr);
8690       continue;
8691     }
8692 
8693     // OpenMP [2.14.4.2, Restrictions, p.2]
8694     //  A list item that appears in a copyprivate clause may not appear in a
8695     //  private or firstprivate clause on the single construct.
8696     if (!DSAStack->isThreadPrivate(VD)) {
8697       auto DVar = DSAStack->getTopDSA(VD, false);
8698       if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
8699           DVar.RefExpr) {
8700         Diag(ELoc, diag::err_omp_wrong_dsa)
8701             << getOpenMPClauseName(DVar.CKind)
8702             << getOpenMPClauseName(OMPC_copyprivate);
8703         ReportOriginalDSA(*this, DSAStack, VD, DVar);
8704         continue;
8705       }
8706 
8707       // OpenMP [2.11.4.2, Restrictions, p.1]
8708       //  All list items that appear in a copyprivate clause must be either
8709       //  threadprivate or private in the enclosing context.
8710       if (DVar.CKind == OMPC_unknown) {
8711         DVar = DSAStack->getImplicitDSA(VD, false);
8712         if (DVar.CKind == OMPC_shared) {
8713           Diag(ELoc, diag::err_omp_required_access)
8714               << getOpenMPClauseName(OMPC_copyprivate)
8715               << "threadprivate or private in the enclosing context";
8716           ReportOriginalDSA(*this, DSAStack, VD, DVar);
8717           continue;
8718         }
8719       }
8720     }
8721 
8722     // Variably modified types are not supported.
8723     if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
8724       Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
8725           << getOpenMPClauseName(OMPC_copyprivate) << Type
8726           << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
8727       bool IsDecl =
8728           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
8729       Diag(VD->getLocation(),
8730            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8731           << VD;
8732       continue;
8733     }
8734 
8735     // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
8736     //  A variable of class type (or array thereof) that appears in a
8737     //  copyin clause requires an accessible, unambiguous copy assignment
8738     //  operator for the class type.
8739     Type = Context.getBaseElementType(Type.getNonReferenceType())
8740                .getUnqualifiedType();
8741     auto *SrcVD =
8742         buildVarDecl(*this, DE->getLocStart(), Type, ".copyprivate.src",
8743                      VD->hasAttrs() ? &VD->getAttrs() : nullptr);
8744     auto *PseudoSrcExpr =
8745         buildDeclRefExpr(*this, SrcVD, Type, DE->getExprLoc());
8746     auto *DstVD =
8747         buildVarDecl(*this, DE->getLocStart(), Type, ".copyprivate.dst",
8748                      VD->hasAttrs() ? &VD->getAttrs() : nullptr);
8749     auto *PseudoDstExpr =
8750         buildDeclRefExpr(*this, DstVD, Type, DE->getExprLoc());
8751     auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
8752                                    PseudoDstExpr, PseudoSrcExpr);
8753     if (AssignmentOp.isInvalid())
8754       continue;
8755     AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
8756                                        /*DiscardedValue=*/true);
8757     if (AssignmentOp.isInvalid())
8758       continue;
8759 
8760     // No need to mark vars as copyprivate, they are already threadprivate or
8761     // implicitly private.
8762     Vars.push_back(DE);
8763     SrcExprs.push_back(PseudoSrcExpr);
8764     DstExprs.push_back(PseudoDstExpr);
8765     AssignmentOps.push_back(AssignmentOp.get());
8766   }
8767 
8768   if (Vars.empty())
8769     return nullptr;
8770 
8771   return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
8772                                       Vars, SrcExprs, DstExprs, AssignmentOps);
8773 }
8774 
8775 OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
8776                                         SourceLocation StartLoc,
8777                                         SourceLocation LParenLoc,
8778                                         SourceLocation EndLoc) {
8779   if (VarList.empty())
8780     return nullptr;
8781 
8782   return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
8783 }
8784 
8785 OMPClause *
8786 Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
8787                               SourceLocation DepLoc, SourceLocation ColonLoc,
8788                               ArrayRef<Expr *> VarList, SourceLocation StartLoc,
8789                               SourceLocation LParenLoc, SourceLocation EndLoc) {
8790   if (DSAStack->getCurrentDirective() == OMPD_ordered &&
8791       DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
8792     Diag(DepLoc, diag::err_omp_unexpected_clause_value)
8793         << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
8794     return nullptr;
8795   }
8796   if (DSAStack->getCurrentDirective() != OMPD_ordered &&
8797       (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
8798        DepKind == OMPC_DEPEND_sink)) {
8799     unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
8800     Diag(DepLoc, diag::err_omp_unexpected_clause_value)
8801         << getListOfPossibleValues(OMPC_depend, /*First=*/0,
8802                                    /*Last=*/OMPC_DEPEND_unknown, Except)
8803         << getOpenMPClauseName(OMPC_depend);
8804     return nullptr;
8805   }
8806   SmallVector<Expr *, 8> Vars;
8807   llvm::APSInt DepCounter(/*BitWidth=*/32);
8808   llvm::APSInt TotalDepCount(/*BitWidth=*/32);
8809   if (DepKind == OMPC_DEPEND_sink) {
8810     if (auto *OrderedCountExpr = DSAStack->getParentOrderedRegionParam()) {
8811       TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
8812       TotalDepCount.setIsUnsigned(/*Val=*/true);
8813     }
8814   }
8815   if ((DepKind != OMPC_DEPEND_sink && DepKind != OMPC_DEPEND_source) ||
8816       DSAStack->getParentOrderedRegionParam()) {
8817     for (auto &RefExpr : VarList) {
8818       assert(RefExpr && "NULL expr in OpenMP shared clause.");
8819       if (isa<DependentScopeDeclRefExpr>(RefExpr) ||
8820           (DepKind == OMPC_DEPEND_sink && CurContext->isDependentContext())) {
8821         // It will be analyzed later.
8822         Vars.push_back(RefExpr);
8823         continue;
8824       }
8825 
8826       SourceLocation ELoc = RefExpr->getExprLoc();
8827       auto *SimpleExpr = RefExpr->IgnoreParenCasts();
8828       if (DepKind == OMPC_DEPEND_sink) {
8829         if (DepCounter >= TotalDepCount) {
8830           Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
8831           continue;
8832         }
8833         ++DepCounter;
8834         // OpenMP  [2.13.9, Summary]
8835         // depend(dependence-type : vec), where dependence-type is:
8836         // 'sink' and where vec is the iteration vector, which has the form:
8837         //  x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
8838         // where n is the value specified by the ordered clause in the loop
8839         // directive, xi denotes the loop iteration variable of the i-th nested
8840         // loop associated with the loop directive, and di is a constant
8841         // non-negative integer.
8842         SimpleExpr = SimpleExpr->IgnoreImplicit();
8843         auto *DE = dyn_cast<DeclRefExpr>(SimpleExpr);
8844         if (!DE) {
8845           OverloadedOperatorKind OOK = OO_None;
8846           SourceLocation OOLoc;
8847           Expr *LHS, *RHS;
8848           if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
8849             OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
8850             OOLoc = BO->getOperatorLoc();
8851             LHS = BO->getLHS()->IgnoreParenImpCasts();
8852             RHS = BO->getRHS()->IgnoreParenImpCasts();
8853           } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
8854             OOK = OCE->getOperator();
8855             OOLoc = OCE->getOperatorLoc();
8856             LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
8857             RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
8858           } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
8859             OOK = MCE->getMethodDecl()
8860                       ->getNameInfo()
8861                       .getName()
8862                       .getCXXOverloadedOperator();
8863             OOLoc = MCE->getCallee()->getExprLoc();
8864             LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
8865             RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
8866           } else {
8867             Diag(ELoc, diag::err_omp_depend_sink_wrong_expr);
8868             continue;
8869           }
8870           DE = dyn_cast<DeclRefExpr>(LHS);
8871           if (!DE) {
8872             Diag(LHS->getExprLoc(),
8873                  diag::err_omp_depend_sink_expected_loop_iteration)
8874                 << DSAStack->getParentLoopControlVariable(
8875                     DepCounter.getZExtValue());
8876             continue;
8877           }
8878           if (OOK != OO_Plus && OOK != OO_Minus) {
8879             Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
8880             continue;
8881           }
8882           ExprResult Res = VerifyPositiveIntegerConstantInClause(
8883               RHS, OMPC_depend, /*StrictlyPositive=*/false);
8884           if (Res.isInvalid())
8885             continue;
8886         }
8887         auto *VD = dyn_cast<VarDecl>(DE->getDecl());
8888         if (!CurContext->isDependentContext() &&
8889             DSAStack->getParentOrderedRegionParam() &&
8890             (!VD || DepCounter != DSAStack->isParentLoopControlVariable(VD))) {
8891           Diag(DE->getExprLoc(),
8892                diag::err_omp_depend_sink_expected_loop_iteration)
8893               << DSAStack->getParentLoopControlVariable(
8894                   DepCounter.getZExtValue());
8895           continue;
8896         }
8897       } else {
8898         // OpenMP  [2.11.1.1, Restrictions, p.3]
8899         //  A variable that is part of another variable (such as a field of a
8900         //  structure) but is not an array element or an array section cannot
8901         //  appear  in a depend clause.
8902         auto *DE = dyn_cast<DeclRefExpr>(SimpleExpr);
8903         auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
8904         auto *OASE = dyn_cast<OMPArraySectionExpr>(SimpleExpr);
8905         if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
8906             (!ASE && !DE && !OASE) || (DE && !isa<VarDecl>(DE->getDecl())) ||
8907             (ASE &&
8908              !ASE->getBase()
8909                   ->getType()
8910                   .getNonReferenceType()
8911                   ->isPointerType() &&
8912              !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
8913           Diag(ELoc, diag::err_omp_expected_var_name_member_expr_or_array_item)
8914               << 0 << RefExpr->getSourceRange();
8915           continue;
8916         }
8917       }
8918 
8919       Vars.push_back(RefExpr->IgnoreParenImpCasts());
8920     }
8921 
8922     if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
8923         TotalDepCount > VarList.size() &&
8924         DSAStack->getParentOrderedRegionParam()) {
8925       Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
8926           << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
8927     }
8928     if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
8929         Vars.empty())
8930       return nullptr;
8931   }
8932 
8933   return OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc, DepKind,
8934                                  DepLoc, ColonLoc, Vars);
8935 }
8936 
8937 OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
8938                                          SourceLocation LParenLoc,
8939                                          SourceLocation EndLoc) {
8940   Expr *ValExpr = Device;
8941 
8942   // OpenMP [2.9.1, Restrictions]
8943   // The device expression must evaluate to a non-negative integer value.
8944   if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
8945                                  /*StrictlyPositive=*/false))
8946     return nullptr;
8947 
8948   return new (Context) OMPDeviceClause(ValExpr, StartLoc, LParenLoc, EndLoc);
8949 }
8950 
8951 static bool IsCXXRecordForMappable(Sema &SemaRef, SourceLocation Loc,
8952                                    DSAStackTy *Stack, CXXRecordDecl *RD) {
8953   if (!RD || RD->isInvalidDecl())
8954     return true;
8955 
8956   if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(RD))
8957     if (auto *CTD = CTSD->getSpecializedTemplate())
8958       RD = CTD->getTemplatedDecl();
8959   auto QTy = SemaRef.Context.getRecordType(RD);
8960   if (RD->isDynamicClass()) {
8961     SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
8962     SemaRef.Diag(RD->getLocation(), diag::note_omp_polymorphic_in_target);
8963     return false;
8964   }
8965   auto *DC = RD;
8966   bool IsCorrect = true;
8967   for (auto *I : DC->decls()) {
8968     if (I) {
8969       if (auto *MD = dyn_cast<CXXMethodDecl>(I)) {
8970         if (MD->isStatic()) {
8971           SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
8972           SemaRef.Diag(MD->getLocation(),
8973                        diag::note_omp_static_member_in_target);
8974           IsCorrect = false;
8975         }
8976       } else if (auto *VD = dyn_cast<VarDecl>(I)) {
8977         if (VD->isStaticDataMember()) {
8978           SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
8979           SemaRef.Diag(VD->getLocation(),
8980                        diag::note_omp_static_member_in_target);
8981           IsCorrect = false;
8982         }
8983       }
8984     }
8985   }
8986 
8987   for (auto &I : RD->bases()) {
8988     if (!IsCXXRecordForMappable(SemaRef, I.getLocStart(), Stack,
8989                                 I.getType()->getAsCXXRecordDecl()))
8990       IsCorrect = false;
8991   }
8992   return IsCorrect;
8993 }
8994 
8995 static bool CheckTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
8996                               DSAStackTy *Stack, QualType QTy) {
8997   NamedDecl *ND;
8998   if (QTy->isIncompleteType(&ND)) {
8999     SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
9000     return false;
9001   } else if (CXXRecordDecl *RD = dyn_cast_or_null<CXXRecordDecl>(ND)) {
9002     if (!RD->isInvalidDecl() &&
9003         !IsCXXRecordForMappable(SemaRef, SL, Stack, RD))
9004       return false;
9005   }
9006   return true;
9007 }
9008 
9009 // Return the expression of the base of the map clause or null if it cannot
9010 // be determined and do all the necessary checks to see if the expression is
9011 // valid as a standalone map clause expression.
9012 static Expr *CheckMapClauseExpressionBase(Sema &SemaRef, Expr *E) {
9013   SourceLocation ELoc = E->getExprLoc();
9014   SourceRange ERange = E->getSourceRange();
9015 
9016   // The base of elements of list in a map clause have to be either:
9017   //  - a reference to variable or field.
9018   //  - a member expression.
9019   //  - an array expression.
9020   //
9021   // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
9022   // reference to 'r'.
9023   //
9024   // If we have:
9025   //
9026   // struct SS {
9027   //   Bla S;
9028   //   foo() {
9029   //     #pragma omp target map (S.Arr[:12]);
9030   //   }
9031   // }
9032   //
9033   // We want to retrieve the member expression 'this->S';
9034 
9035   Expr *RelevantExpr = nullptr;
9036 
9037   // Flags to help capture some memory
9038 
9039   // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
9040   //  If a list item is an array section, it must specify contiguous storage.
9041   //
9042   // For this restriction it is sufficient that we make sure only references
9043   // to variables or fields and array expressions, and that no array sections
9044   // exist except in the rightmost expression. E.g. these would be invalid:
9045   //
9046   //   r.ArrS[3:5].Arr[6:7]
9047   //
9048   //   r.ArrS[3:5].x
9049   //
9050   // but these would be valid:
9051   //   r.ArrS[3].Arr[6:7]
9052   //
9053   //   r.ArrS[3].x
9054 
9055   bool IsRightMostExpression = true;
9056 
9057   while (!RelevantExpr) {
9058     auto AllowArraySection = IsRightMostExpression;
9059     IsRightMostExpression = false;
9060 
9061     E = E->IgnoreParenImpCasts();
9062 
9063     if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
9064       if (!isa<VarDecl>(CurE->getDecl()))
9065         break;
9066 
9067       RelevantExpr = CurE;
9068       continue;
9069     }
9070 
9071     if (auto *CurE = dyn_cast<MemberExpr>(E)) {
9072       auto *BaseE = CurE->getBase()->IgnoreParenImpCasts();
9073 
9074       if (isa<CXXThisExpr>(BaseE))
9075         // We found a base expression: this->Val.
9076         RelevantExpr = CurE;
9077       else
9078         E = BaseE;
9079 
9080       if (!isa<FieldDecl>(CurE->getMemberDecl())) {
9081         SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
9082             << CurE->getSourceRange();
9083         break;
9084       }
9085 
9086       auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
9087 
9088       // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
9089       //  A bit-field cannot appear in a map clause.
9090       //
9091       if (FD->isBitField()) {
9092         SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_map_clause)
9093             << CurE->getSourceRange();
9094         break;
9095       }
9096 
9097       // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
9098       //  If the type of a list item is a reference to a type T then the type
9099       //  will be considered to be T for all purposes of this clause.
9100       QualType CurType = BaseE->getType();
9101       if (CurType->isReferenceType())
9102         CurType = CurType->getPointeeType();
9103 
9104       // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
9105       //  A list item cannot be a variable that is a member of a structure with
9106       //  a union type.
9107       //
9108       if (auto *RT = CurType->getAs<RecordType>())
9109         if (RT->isUnionType()) {
9110           SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
9111               << CurE->getSourceRange();
9112           break;
9113         }
9114 
9115       continue;
9116     }
9117 
9118     if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
9119       E = CurE->getBase()->IgnoreParenImpCasts();
9120 
9121       if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
9122         SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
9123             << 0 << CurE->getSourceRange();
9124         break;
9125       }
9126       continue;
9127     }
9128 
9129     if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
9130       // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
9131       //  If a list item is an element of a structure, only the rightmost symbol
9132       //  of the variable reference can be an array section.
9133       //
9134       if (!AllowArraySection) {
9135         SemaRef.Diag(ELoc, diag::err_omp_array_section_in_rightmost_expression)
9136             << CurE->getSourceRange();
9137         break;
9138       }
9139 
9140       E = CurE->getBase()->IgnoreParenImpCasts();
9141 
9142       // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
9143       //  If the type of a list item is a reference to a type T then the type
9144       //  will be considered to be T for all purposes of this clause.
9145       QualType CurType = E->getType();
9146       if (CurType->isReferenceType())
9147         CurType = CurType->getPointeeType();
9148 
9149       if (!CurType->isAnyPointerType() && !CurType->isArrayType()) {
9150         SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
9151             << 0 << CurE->getSourceRange();
9152         break;
9153       }
9154 
9155       continue;
9156     }
9157 
9158     // If nothing else worked, this is not a valid map clause expression.
9159     SemaRef.Diag(ELoc,
9160                  diag::err_omp_expected_named_var_member_or_array_expression)
9161         << ERange;
9162     break;
9163   }
9164 
9165   return RelevantExpr;
9166 }
9167 
9168 // Return true if expression E associated with value VD has conflicts with other
9169 // map information.
9170 static bool CheckMapConflicts(Sema &SemaRef, DSAStackTy *DSAS, ValueDecl *VD,
9171                               Expr *E, bool CurrentRegionOnly) {
9172   assert(VD && E);
9173 
9174   // Types used to organize the components of a valid map clause.
9175   typedef std::pair<Expr *, ValueDecl *> MapExpressionComponent;
9176   typedef SmallVector<MapExpressionComponent, 4> MapExpressionComponents;
9177 
9178   // Helper to extract the components in the map clause expression E and store
9179   // them into MEC. This assumes that E is a valid map clause expression, i.e.
9180   // it has already passed the single clause checks.
9181   auto ExtractMapExpressionComponents = [](Expr *TE,
9182                                            MapExpressionComponents &MEC) {
9183     while (true) {
9184       TE = TE->IgnoreParenImpCasts();
9185 
9186       if (auto *CurE = dyn_cast<DeclRefExpr>(TE)) {
9187         MEC.push_back(
9188             MapExpressionComponent(CurE, cast<VarDecl>(CurE->getDecl())));
9189         break;
9190       }
9191 
9192       if (auto *CurE = dyn_cast<MemberExpr>(TE)) {
9193         auto *BaseE = CurE->getBase()->IgnoreParenImpCasts();
9194 
9195         MEC.push_back(MapExpressionComponent(
9196             CurE, cast<FieldDecl>(CurE->getMemberDecl())));
9197         if (isa<CXXThisExpr>(BaseE))
9198           break;
9199 
9200         TE = BaseE;
9201         continue;
9202       }
9203 
9204       if (auto *CurE = dyn_cast<ArraySubscriptExpr>(TE)) {
9205         MEC.push_back(MapExpressionComponent(CurE, nullptr));
9206         TE = CurE->getBase()->IgnoreParenImpCasts();
9207         continue;
9208       }
9209 
9210       if (auto *CurE = dyn_cast<OMPArraySectionExpr>(TE)) {
9211         MEC.push_back(MapExpressionComponent(CurE, nullptr));
9212         TE = CurE->getBase()->IgnoreParenImpCasts();
9213         continue;
9214       }
9215 
9216       llvm_unreachable(
9217           "Expecting only valid map clause expressions at this point!");
9218     }
9219   };
9220 
9221   SourceLocation ELoc = E->getExprLoc();
9222   SourceRange ERange = E->getSourceRange();
9223 
9224   // In order to easily check the conflicts we need to match each component of
9225   // the expression under test with the components of the expressions that are
9226   // already in the stack.
9227 
9228   MapExpressionComponents CurComponents;
9229   ExtractMapExpressionComponents(E, CurComponents);
9230 
9231   assert(!CurComponents.empty() && "Map clause expression with no components!");
9232   assert(CurComponents.back().second == VD &&
9233          "Map clause expression with unexpected base!");
9234 
9235   // Variables to help detecting enclosing problems in data environment nests.
9236   bool IsEnclosedByDataEnvironmentExpr = false;
9237   Expr *EnclosingExpr = nullptr;
9238 
9239   bool FoundError =
9240       DSAS->checkMapInfoForVar(VD, CurrentRegionOnly, [&](Expr *RE) -> bool {
9241         MapExpressionComponents StackComponents;
9242         ExtractMapExpressionComponents(RE, StackComponents);
9243         assert(!StackComponents.empty() &&
9244                "Map clause expression with no components!");
9245         assert(StackComponents.back().second == VD &&
9246                "Map clause expression with unexpected base!");
9247 
9248         // Expressions must start from the same base. Here we detect at which
9249         // point both expressions diverge from each other and see if we can
9250         // detect if the memory referred to both expressions is contiguous and
9251         // do not overlap.
9252         auto CI = CurComponents.rbegin();
9253         auto CE = CurComponents.rend();
9254         auto SI = StackComponents.rbegin();
9255         auto SE = StackComponents.rend();
9256         for (; CI != CE && SI != SE; ++CI, ++SI) {
9257 
9258           // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
9259           //  At most one list item can be an array item derived from a given
9260           //  variable in map clauses of the same construct.
9261           if (CurrentRegionOnly && (isa<ArraySubscriptExpr>(CI->first) ||
9262                                     isa<OMPArraySectionExpr>(CI->first)) &&
9263               (isa<ArraySubscriptExpr>(SI->first) ||
9264                isa<OMPArraySectionExpr>(SI->first))) {
9265             SemaRef.Diag(CI->first->getExprLoc(),
9266                          diag::err_omp_multiple_array_items_in_map_clause)
9267                 << CI->first->getSourceRange();
9268             ;
9269             SemaRef.Diag(SI->first->getExprLoc(), diag::note_used_here)
9270                 << SI->first->getSourceRange();
9271             return true;
9272           }
9273 
9274           // Do both expressions have the same kind?
9275           if (CI->first->getStmtClass() != SI->first->getStmtClass())
9276             break;
9277 
9278           // Are we dealing with different variables/fields?
9279           if (CI->second != SI->second)
9280             break;
9281         }
9282 
9283         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
9284         //  List items of map clauses in the same construct must not share
9285         //  original storage.
9286         //
9287         // If the expressions are exactly the same or one is a subset of the
9288         // other, it means they are sharing storage.
9289         if (CI == CE && SI == SE) {
9290           if (CurrentRegionOnly) {
9291             SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
9292             SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
9293                 << RE->getSourceRange();
9294             return true;
9295           } else {
9296             // If we find the same expression in the enclosing data environment,
9297             // that is legal.
9298             IsEnclosedByDataEnvironmentExpr = true;
9299             return false;
9300           }
9301         }
9302 
9303         QualType DerivedType = std::prev(CI)->first->getType();
9304         SourceLocation DerivedLoc = std::prev(CI)->first->getExprLoc();
9305 
9306         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
9307         //  If the type of a list item is a reference to a type T then the type
9308         //  will be considered to be T for all purposes of this clause.
9309         if (DerivedType->isReferenceType())
9310           DerivedType = DerivedType->getPointeeType();
9311 
9312         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
9313         //  A variable for which the type is pointer and an array section
9314         //  derived from that variable must not appear as list items of map
9315         //  clauses of the same construct.
9316         //
9317         // Also, cover one of the cases in:
9318         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
9319         //  If any part of the original storage of a list item has corresponding
9320         //  storage in the device data environment, all of the original storage
9321         //  must have corresponding storage in the device data environment.
9322         //
9323         if (DerivedType->isAnyPointerType()) {
9324           if (CI == CE || SI == SE) {
9325             SemaRef.Diag(
9326                 DerivedLoc,
9327                 diag::err_omp_pointer_mapped_along_with_derived_section)
9328                 << DerivedLoc;
9329           } else {
9330             assert(CI != CE && SI != SE);
9331             SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_derreferenced)
9332                 << DerivedLoc;
9333           }
9334           SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
9335               << RE->getSourceRange();
9336           return true;
9337         }
9338 
9339         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
9340         //  List items of map clauses in the same construct must not share
9341         //  original storage.
9342         //
9343         // An expression is a subset of the other.
9344         if (CurrentRegionOnly && (CI == CE || SI == SE)) {
9345           SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
9346           SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
9347               << RE->getSourceRange();
9348           return true;
9349         }
9350 
9351         // The current expression uses the same base as other expression in the
9352         // data environment but does not contain it completelly.
9353         if (!CurrentRegionOnly && SI != SE)
9354           EnclosingExpr = RE;
9355 
9356         // The current expression is a subset of the expression in the data
9357         // environment.
9358         IsEnclosedByDataEnvironmentExpr |=
9359             (!CurrentRegionOnly && CI != CE && SI == SE);
9360 
9361         return false;
9362       });
9363 
9364   if (CurrentRegionOnly)
9365     return FoundError;
9366 
9367   // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
9368   //  If any part of the original storage of a list item has corresponding
9369   //  storage in the device data environment, all of the original storage must
9370   //  have corresponding storage in the device data environment.
9371   // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
9372   //  If a list item is an element of a structure, and a different element of
9373   //  the structure has a corresponding list item in the device data environment
9374   //  prior to a task encountering the construct associated with the map clause,
9375   //  then the list item must also have a correspnding list item in the device
9376   //  data environment prior to the task encountering the construct.
9377   //
9378   if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
9379     SemaRef.Diag(ELoc,
9380                  diag::err_omp_original_storage_is_shared_and_does_not_contain)
9381         << ERange;
9382     SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
9383         << EnclosingExpr->getSourceRange();
9384     return true;
9385   }
9386 
9387   return FoundError;
9388 }
9389 
9390 OMPClause *
9391 Sema::ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier,
9392                            OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
9393                            SourceLocation MapLoc, SourceLocation ColonLoc,
9394                            ArrayRef<Expr *> VarList, SourceLocation StartLoc,
9395                            SourceLocation LParenLoc, SourceLocation EndLoc) {
9396   SmallVector<Expr *, 4> Vars;
9397 
9398   for (auto &RE : VarList) {
9399     assert(RE && "Null expr in omp map");
9400     if (isa<DependentScopeDeclRefExpr>(RE)) {
9401       // It will be analyzed later.
9402       Vars.push_back(RE);
9403       continue;
9404     }
9405     SourceLocation ELoc = RE->getExprLoc();
9406 
9407     auto *VE = RE->IgnoreParenLValueCasts();
9408 
9409     if (VE->isValueDependent() || VE->isTypeDependent() ||
9410         VE->isInstantiationDependent() ||
9411         VE->containsUnexpandedParameterPack()) {
9412       // We can only analyze this information once the missing information is
9413       // resolved.
9414       Vars.push_back(RE);
9415       continue;
9416     }
9417 
9418     auto *SimpleExpr = RE->IgnoreParenCasts();
9419 
9420     if (!RE->IgnoreParenImpCasts()->isLValue()) {
9421       Diag(ELoc, diag::err_omp_expected_named_var_member_or_array_expression)
9422           << RE->getSourceRange();
9423       continue;
9424     }
9425 
9426     // Obtain the array or member expression bases if required.
9427     auto *BE = CheckMapClauseExpressionBase(*this, SimpleExpr);
9428     if (!BE)
9429       continue;
9430 
9431     // If the base is a reference to a variable, we rely on that variable for
9432     // the following checks. If it is a 'this' expression we rely on the field.
9433     ValueDecl *D = nullptr;
9434     if (auto *DRE = dyn_cast<DeclRefExpr>(BE)) {
9435       D = DRE->getDecl();
9436     } else {
9437       auto *ME = cast<MemberExpr>(BE);
9438       assert(isa<CXXThisExpr>(ME->getBase()) && "Unexpected expression!");
9439       D = ME->getMemberDecl();
9440     }
9441     assert(D && "Null decl on map clause.");
9442 
9443     auto *VD = dyn_cast<VarDecl>(D);
9444     auto *FD = dyn_cast<FieldDecl>(D);
9445 
9446     assert((VD || FD) && "Only variables or fields are expected here!");
9447     (void)FD;
9448 
9449     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
9450     //  threadprivate variables cannot appear in a map clause.
9451     if (VD && DSAStack->isThreadPrivate(VD)) {
9452       auto DVar = DSAStack->getTopDSA(VD, false);
9453       Diag(ELoc, diag::err_omp_threadprivate_in_map);
9454       ReportOriginalDSA(*this, DSAStack, VD, DVar);
9455       continue;
9456     }
9457 
9458     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
9459     //  A list item cannot appear in both a map clause and a data-sharing
9460     //  attribute clause on the same construct.
9461     //
9462     // TODO: Implement this check - it cannot currently be tested because of
9463     // missing implementation of the other data sharing clauses in target
9464     // directives.
9465 
9466     // Check conflicts with other map clause expressions. We check the conflicts
9467     // with the current construct separately from the enclosing data
9468     // environment, because the restrictions are different.
9469     if (CheckMapConflicts(*this, DSAStack, D, SimpleExpr,
9470                           /*CurrentRegionOnly=*/true))
9471       break;
9472     if (CheckMapConflicts(*this, DSAStack, D, SimpleExpr,
9473                           /*CurrentRegionOnly=*/false))
9474       break;
9475 
9476     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
9477     //  If the type of a list item is a reference to a type T then the type will
9478     //  be considered to be T for all purposes of this clause.
9479     QualType Type = D->getType();
9480     if (Type->isReferenceType())
9481       Type = Type->getPointeeType();
9482 
9483     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
9484     //  A list item must have a mappable type.
9485     if (!CheckTypeMappable(VE->getExprLoc(), VE->getSourceRange(), *this,
9486                            DSAStack, Type))
9487       continue;
9488 
9489     // target enter data
9490     // OpenMP [2.10.2, Restrictions, p. 99]
9491     // A map-type must be specified in all map clauses and must be either
9492     // to or alloc.
9493     OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
9494     if (DKind == OMPD_target_enter_data &&
9495         !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
9496       Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
9497           << (IsMapTypeImplicit ? 1 : 0)
9498           << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
9499           << getOpenMPDirectiveName(DKind);
9500       continue;
9501     }
9502 
9503     // target exit_data
9504     // OpenMP [2.10.3, Restrictions, p. 102]
9505     // A map-type must be specified in all map clauses and must be either
9506     // from, release, or delete.
9507     DKind = DSAStack->getCurrentDirective();
9508     if (DKind == OMPD_target_exit_data &&
9509         !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
9510           MapType == OMPC_MAP_delete)) {
9511       Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
9512           << (IsMapTypeImplicit ? 1 : 0)
9513           << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
9514           << getOpenMPDirectiveName(DKind);
9515       continue;
9516     }
9517 
9518     Vars.push_back(RE);
9519     DSAStack->addExprToVarMapInfo(D, RE);
9520   }
9521 
9522   // We need to produce a map clause even if we don't have variables so that
9523   // other diagnostics related with non-existing map clauses are accurate.
9524   return OMPMapClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
9525                               MapTypeModifier, MapType, IsMapTypeImplicit,
9526                               MapLoc);
9527 }
9528 
9529 OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
9530                                            SourceLocation StartLoc,
9531                                            SourceLocation LParenLoc,
9532                                            SourceLocation EndLoc) {
9533   Expr *ValExpr = NumTeams;
9534 
9535   // OpenMP [teams Constrcut, Restrictions]
9536   // The num_teams expression must evaluate to a positive integer value.
9537   if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
9538                                  /*StrictlyPositive=*/true))
9539     return nullptr;
9540 
9541   return new (Context) OMPNumTeamsClause(ValExpr, StartLoc, LParenLoc, EndLoc);
9542 }
9543 
9544 OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
9545                                               SourceLocation StartLoc,
9546                                               SourceLocation LParenLoc,
9547                                               SourceLocation EndLoc) {
9548   Expr *ValExpr = ThreadLimit;
9549 
9550   // OpenMP [teams Constrcut, Restrictions]
9551   // The thread_limit expression must evaluate to a positive integer value.
9552   if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
9553                                  /*StrictlyPositive=*/true))
9554     return nullptr;
9555 
9556   return new (Context) OMPThreadLimitClause(ValExpr, StartLoc, LParenLoc,
9557                                             EndLoc);
9558 }
9559 
9560 OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
9561                                            SourceLocation StartLoc,
9562                                            SourceLocation LParenLoc,
9563                                            SourceLocation EndLoc) {
9564   Expr *ValExpr = Priority;
9565 
9566   // OpenMP [2.9.1, task Constrcut]
9567   // The priority-value is a non-negative numerical scalar expression.
9568   if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_priority,
9569                                  /*StrictlyPositive=*/false))
9570     return nullptr;
9571 
9572   return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc);
9573 }
9574 
9575 OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
9576                                             SourceLocation StartLoc,
9577                                             SourceLocation LParenLoc,
9578                                             SourceLocation EndLoc) {
9579   Expr *ValExpr = Grainsize;
9580 
9581   // OpenMP [2.9.2, taskloop Constrcut]
9582   // The parameter of the grainsize clause must be a positive integer
9583   // expression.
9584   if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize,
9585                                  /*StrictlyPositive=*/true))
9586     return nullptr;
9587 
9588   return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc);
9589 }
9590 
9591 OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
9592                                            SourceLocation StartLoc,
9593                                            SourceLocation LParenLoc,
9594                                            SourceLocation EndLoc) {
9595   Expr *ValExpr = NumTasks;
9596 
9597   // OpenMP [2.9.2, taskloop Constrcut]
9598   // The parameter of the num_tasks clause must be a positive integer
9599   // expression.
9600   if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks,
9601                                  /*StrictlyPositive=*/true))
9602     return nullptr;
9603 
9604   return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc);
9605 }
9606 
9607 OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
9608                                        SourceLocation LParenLoc,
9609                                        SourceLocation EndLoc) {
9610   // OpenMP [2.13.2, critical construct, Description]
9611   // ... where hint-expression is an integer constant expression that evaluates
9612   // to a valid lock hint.
9613   ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
9614   if (HintExpr.isInvalid())
9615     return nullptr;
9616   return new (Context)
9617       OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
9618 }
9619 
9620 OMPClause *Sema::ActOnOpenMPDistScheduleClause(
9621     OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
9622     SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
9623     SourceLocation EndLoc) {
9624   if (Kind == OMPC_DIST_SCHEDULE_unknown) {
9625     std::string Values;
9626     Values += "'";
9627     Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
9628     Values += "'";
9629     Diag(KindLoc, diag::err_omp_unexpected_clause_value)
9630         << Values << getOpenMPClauseName(OMPC_dist_schedule);
9631     return nullptr;
9632   }
9633   Expr *ValExpr = ChunkSize;
9634   Stmt *HelperValStmt = nullptr;
9635   if (ChunkSize) {
9636     if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
9637         !ChunkSize->isInstantiationDependent() &&
9638         !ChunkSize->containsUnexpandedParameterPack()) {
9639       SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
9640       ExprResult Val =
9641           PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
9642       if (Val.isInvalid())
9643         return nullptr;
9644 
9645       ValExpr = Val.get();
9646 
9647       // OpenMP [2.7.1, Restrictions]
9648       //  chunk_size must be a loop invariant integer expression with a positive
9649       //  value.
9650       llvm::APSInt Result;
9651       if (ValExpr->isIntegerConstantExpr(Result, Context)) {
9652         if (Result.isSigned() && !Result.isStrictlyPositive()) {
9653           Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
9654               << "dist_schedule" << ChunkSize->getSourceRange();
9655           return nullptr;
9656         }
9657       } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) {
9658         ValExpr = buildCapture(*this, ValExpr);
9659         Decl *D = cast<DeclRefExpr>(ValExpr)->getDecl();
9660         HelperValStmt =
9661             new (Context) DeclStmt(DeclGroupRef::Create(Context, &D,
9662                                                         /*NumDecls=*/1),
9663                                    SourceLocation(), SourceLocation());
9664         ValExpr = DefaultLvalueConversion(ValExpr).get();
9665       }
9666     }
9667   }
9668 
9669   return new (Context)
9670       OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
9671                             Kind, ValExpr, HelperValStmt);
9672 }
9673 
9674 OMPClause *Sema::ActOnOpenMPDefaultmapClause(
9675     OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
9676     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
9677     SourceLocation KindLoc, SourceLocation EndLoc) {
9678   // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)'
9679   if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom ||
9680       Kind != OMPC_DEFAULTMAP_scalar) {
9681     std::string Value;
9682     SourceLocation Loc;
9683     Value += "'";
9684     if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
9685       Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
9686                  OMPC_DEFAULTMAP_MODIFIER_tofrom);
9687       Loc = MLoc;
9688     } else {
9689       Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
9690                  OMPC_DEFAULTMAP_scalar);
9691       Loc = KindLoc;
9692     }
9693     Value += "'";
9694     Diag(Loc, diag::err_omp_unexpected_clause_value)
9695         << Value << getOpenMPClauseName(OMPC_defaultmap);
9696     return nullptr;
9697   }
9698 
9699   return new (Context)
9700       OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
9701 }
9702