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