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