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