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 #include "llvm/ADT/PointerEmbeddedInt.h"
35 using namespace clang;
36 
37 //===----------------------------------------------------------------------===//
38 // Stack of data-sharing attributes for variables
39 //===----------------------------------------------------------------------===//
40 
41 namespace {
42 /// \brief Default data sharing attributes, which can be applied to directive.
43 enum DefaultDataSharingAttributes {
44   DSA_unspecified = 0, /// \brief Data sharing attribute not specified.
45   DSA_none = 1 << 0,   /// \brief Default data sharing attribute 'none'.
46   DSA_shared = 1 << 1  /// \brief Default data sharing attribute 'shared'.
47 };
48 
49 /// \brief Stack for tracking declarations used in OpenMP directives and
50 /// clauses and their data-sharing attributes.
51 class DSAStackTy final {
52 public:
53   struct DSAVarData final {
54     OpenMPDirectiveKind DKind = OMPD_unknown;
55     OpenMPClauseKind CKind = OMPC_unknown;
56     Expr *RefExpr = nullptr;
57     DeclRefExpr *PrivateCopy = nullptr;
58     SourceLocation ImplicitDSALoc;
59     DSAVarData() = default;
60     DSAVarData(OpenMPDirectiveKind DKind, OpenMPClauseKind CKind, Expr *RefExpr,
61                DeclRefExpr *PrivateCopy, SourceLocation ImplicitDSALoc)
62         : DKind(DKind), CKind(CKind), RefExpr(RefExpr),
63           PrivateCopy(PrivateCopy), ImplicitDSALoc(ImplicitDSALoc) {}
64   };
65   typedef llvm::SmallVector<std::pair<Expr *, OverloadedOperatorKind>, 4>
66       OperatorOffsetTy;
67 
68 private:
69   struct DSAInfo final {
70     OpenMPClauseKind Attributes = OMPC_unknown;
71     /// Pointer to a reference expression and a flag which shows that the
72     /// variable is marked as lastprivate(true) or not (false).
73     llvm::PointerIntPair<Expr *, 1, bool> RefExpr;
74     DeclRefExpr *PrivateCopy = nullptr;
75   };
76   typedef llvm::DenseMap<ValueDecl *, DSAInfo> DeclSAMapTy;
77   typedef llvm::DenseMap<ValueDecl *, Expr *> AlignedMapTy;
78   typedef std::pair<unsigned, VarDecl *> LCDeclInfo;
79   typedef llvm::DenseMap<ValueDecl *, LCDeclInfo> LoopControlVariablesMapTy;
80   /// Struct that associates a component with the clause kind where they are
81   /// found.
82   struct MappedExprComponentTy {
83     OMPClauseMappableExprCommon::MappableExprComponentLists Components;
84     OpenMPClauseKind Kind = OMPC_unknown;
85   };
86   typedef llvm::DenseMap<ValueDecl *, MappedExprComponentTy>
87       MappedExprComponentsTy;
88   typedef llvm::StringMap<std::pair<OMPCriticalDirective *, llvm::APSInt>>
89       CriticalsWithHintsTy;
90   typedef llvm::DenseMap<OMPDependClause *, OperatorOffsetTy>
91       DoacrossDependMapTy;
92   struct ReductionData {
93     typedef llvm::PointerEmbeddedInt<BinaryOperatorKind, 16> BOKPtrType;
94     SourceRange ReductionRange;
95     llvm::PointerUnion<const Expr *, BOKPtrType> ReductionOp;
96     ReductionData() = default;
97     void set(BinaryOperatorKind BO, SourceRange RR) {
98       ReductionRange = RR;
99       ReductionOp = BO;
100     }
101     void set(const Expr *RefExpr, SourceRange RR) {
102       ReductionRange = RR;
103       ReductionOp = RefExpr;
104     }
105   };
106   typedef llvm::DenseMap<ValueDecl *, ReductionData> DeclReductionMapTy;
107 
108   struct SharingMapTy final {
109     DeclSAMapTy SharingMap;
110     DeclReductionMapTy ReductionMap;
111     AlignedMapTy AlignedMap;
112     MappedExprComponentsTy MappedExprComponents;
113     LoopControlVariablesMapTy LCVMap;
114     DefaultDataSharingAttributes DefaultAttr = DSA_unspecified;
115     SourceLocation DefaultAttrLoc;
116     OpenMPDirectiveKind Directive = OMPD_unknown;
117     DeclarationNameInfo DirectiveName;
118     Scope *CurScope = nullptr;
119     SourceLocation ConstructLoc;
120     /// Set of 'depend' clauses with 'sink|source' dependence kind. Required to
121     /// get the data (loop counters etc.) about enclosing loop-based construct.
122     /// This data is required during codegen.
123     DoacrossDependMapTy DoacrossDepends;
124     /// \brief first argument (Expr *) contains optional argument of the
125     /// 'ordered' clause, the second one is true if the regions has 'ordered'
126     /// clause, false otherwise.
127     llvm::PointerIntPair<Expr *, 1, bool> OrderedRegion;
128     bool NowaitRegion = false;
129     bool CancelRegion = false;
130     unsigned AssociatedLoops = 1;
131     SourceLocation InnerTeamsRegionLoc;
132     /// Reference to the taskgroup task_reduction reference expression.
133     Expr *TaskgroupReductionRef = nullptr;
134     SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
135                  Scope *CurScope, SourceLocation Loc)
136         : Directive(DKind), DirectiveName(Name), CurScope(CurScope),
137           ConstructLoc(Loc) {}
138     SharingMapTy() = default;
139   };
140 
141   typedef SmallVector<SharingMapTy, 4> StackTy;
142 
143   /// \brief Stack of used declaration and their data-sharing attributes.
144   DeclSAMapTy Threadprivates;
145   const FunctionScopeInfo *CurrentNonCapturingFunctionScope = nullptr;
146   SmallVector<std::pair<StackTy, const FunctionScopeInfo *>, 4> Stack;
147   /// \brief true, if check for DSA must be from parent directive, false, if
148   /// from current directive.
149   OpenMPClauseKind ClauseKindMode = OMPC_unknown;
150   Sema &SemaRef;
151   bool ForceCapturing = false;
152   CriticalsWithHintsTy Criticals;
153 
154   typedef SmallVector<SharingMapTy, 8>::reverse_iterator reverse_iterator;
155 
156   DSAVarData getDSA(StackTy::reverse_iterator &Iter, ValueDecl *D);
157 
158   /// \brief Checks if the variable is a local for OpenMP region.
159   bool isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter);
160 
161   bool isStackEmpty() const {
162     return Stack.empty() ||
163            Stack.back().second != CurrentNonCapturingFunctionScope ||
164            Stack.back().first.empty();
165   }
166 
167 public:
168   explicit DSAStackTy(Sema &S) : SemaRef(S) {}
169 
170   bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
171   void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
172 
173   bool isForceVarCapturing() const { return ForceCapturing; }
174   void setForceVarCapturing(bool V) { ForceCapturing = V; }
175 
176   void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
177             Scope *CurScope, SourceLocation Loc) {
178     if (Stack.empty() ||
179         Stack.back().second != CurrentNonCapturingFunctionScope)
180       Stack.emplace_back(StackTy(), CurrentNonCapturingFunctionScope);
181     Stack.back().first.emplace_back(DKind, DirName, CurScope, Loc);
182     Stack.back().first.back().DefaultAttrLoc = Loc;
183   }
184 
185   void pop() {
186     assert(!Stack.back().first.empty() &&
187            "Data-sharing attributes stack is empty!");
188     Stack.back().first.pop_back();
189   }
190 
191   /// Start new OpenMP region stack in new non-capturing function.
192   void pushFunction() {
193     const FunctionScopeInfo *CurFnScope = SemaRef.getCurFunction();
194     assert(!isa<CapturingScopeInfo>(CurFnScope));
195     CurrentNonCapturingFunctionScope = CurFnScope;
196   }
197   /// Pop region stack for non-capturing function.
198   void popFunction(const FunctionScopeInfo *OldFSI) {
199     if (!Stack.empty() && Stack.back().second == OldFSI) {
200       assert(Stack.back().first.empty());
201       Stack.pop_back();
202     }
203     CurrentNonCapturingFunctionScope = nullptr;
204     for (const FunctionScopeInfo *FSI : llvm::reverse(SemaRef.FunctionScopes)) {
205       if (!isa<CapturingScopeInfo>(FSI)) {
206         CurrentNonCapturingFunctionScope = FSI;
207         break;
208       }
209     }
210   }
211 
212   void addCriticalWithHint(OMPCriticalDirective *D, llvm::APSInt Hint) {
213     Criticals[D->getDirectiveName().getAsString()] = std::make_pair(D, Hint);
214   }
215   const std::pair<OMPCriticalDirective *, llvm::APSInt>
216   getCriticalWithHint(const DeclarationNameInfo &Name) const {
217     auto I = Criticals.find(Name.getAsString());
218     if (I != Criticals.end())
219       return I->second;
220     return std::make_pair(nullptr, llvm::APSInt());
221   }
222   /// \brief If 'aligned' declaration for given variable \a D was not seen yet,
223   /// add it and return NULL; otherwise return previous occurrence's expression
224   /// for diagnostics.
225   Expr *addUniqueAligned(ValueDecl *D, Expr *NewDE);
226 
227   /// \brief Register specified variable as loop control variable.
228   void addLoopControlVariable(ValueDecl *D, VarDecl *Capture);
229   /// \brief Check if the specified variable is a loop control variable for
230   /// current region.
231   /// \return The index of the loop control variable in the list of associated
232   /// for-loops (from outer to inner).
233   LCDeclInfo isLoopControlVariable(ValueDecl *D);
234   /// \brief Check if the specified variable is a loop control variable for
235   /// parent region.
236   /// \return The index of the loop control variable in the list of associated
237   /// for-loops (from outer to inner).
238   LCDeclInfo isParentLoopControlVariable(ValueDecl *D);
239   /// \brief Get the loop control variable for the I-th loop (or nullptr) in
240   /// parent directive.
241   ValueDecl *getParentLoopControlVariable(unsigned I);
242 
243   /// \brief Adds explicit data sharing attribute to the specified declaration.
244   void addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A,
245               DeclRefExpr *PrivateCopy = nullptr);
246 
247   /// Adds additional information for the reduction items with the reduction id
248   /// represented as an operator.
249   void addTaskgroupReductionData(ValueDecl *D, SourceRange SR,
250                                  BinaryOperatorKind BOK);
251   /// Adds additional information for the reduction items with the reduction id
252   /// represented as reduction identifier.
253   void addTaskgroupReductionData(ValueDecl *D, SourceRange SR,
254                                  const Expr *ReductionRef);
255   /// Returns the location and reduction operation from the innermost parent
256   /// region for the given \p D.
257   DSAVarData getTopMostTaskgroupReductionData(ValueDecl *D, SourceRange &SR,
258                                               BinaryOperatorKind &BOK,
259                                               Expr *&TaskgroupDescriptor);
260   /// Returns the location and reduction operation from the innermost parent
261   /// region for the given \p D.
262   DSAVarData getTopMostTaskgroupReductionData(ValueDecl *D, SourceRange &SR,
263                                               const Expr *&ReductionRef,
264                                               Expr *&TaskgroupDescriptor);
265   /// Return reduction reference expression for the current taskgroup.
266   Expr *getTaskgroupReductionRef() const {
267     assert(Stack.back().first.back().Directive == OMPD_taskgroup &&
268            "taskgroup reference expression requested for non taskgroup "
269            "directive.");
270     return Stack.back().first.back().TaskgroupReductionRef;
271   }
272   /// Checks if the given \p VD declaration is actually a taskgroup reduction
273   /// descriptor variable at the \p Level of OpenMP regions.
274   bool isTaskgroupReductionRef(ValueDecl *VD, unsigned Level) const {
275     return Stack.back().first[Level].TaskgroupReductionRef &&
276            cast<DeclRefExpr>(Stack.back().first[Level].TaskgroupReductionRef)
277                    ->getDecl() == VD;
278   }
279 
280   /// \brief Returns data sharing attributes from top of the stack for the
281   /// specified declaration.
282   DSAVarData getTopDSA(ValueDecl *D, bool FromParent);
283   /// \brief Returns data-sharing attributes for the specified declaration.
284   DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent);
285   /// \brief Checks if the specified variables has data-sharing attributes which
286   /// match specified \a CPred predicate in any directive which matches \a DPred
287   /// predicate.
288   DSAVarData hasDSA(ValueDecl *D,
289                     const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
290                     const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
291                     bool FromParent);
292   /// \brief Checks if the specified variables has data-sharing attributes which
293   /// match specified \a CPred predicate in any innermost directive which
294   /// matches \a DPred predicate.
295   DSAVarData
296   hasInnermostDSA(ValueDecl *D,
297                   const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
298                   const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
299                   bool FromParent);
300   /// \brief Checks if the specified variables has explicit data-sharing
301   /// attributes which match specified \a CPred predicate at the specified
302   /// OpenMP region.
303   bool hasExplicitDSA(ValueDecl *D,
304                       const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
305                       unsigned Level, bool NotLastprivate = false);
306 
307   /// \brief Returns true if the directive at level \Level matches in the
308   /// specified \a DPred predicate.
309   bool hasExplicitDirective(
310       const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
311       unsigned Level);
312 
313   /// \brief Finds a directive which matches specified \a DPred predicate.
314   bool hasDirective(const llvm::function_ref<bool(OpenMPDirectiveKind,
315                                                   const DeclarationNameInfo &,
316                                                   SourceLocation)> &DPred,
317                     bool FromParent);
318 
319   /// \brief Returns currently analyzed directive.
320   OpenMPDirectiveKind getCurrentDirective() const {
321     return isStackEmpty() ? OMPD_unknown : Stack.back().first.back().Directive;
322   }
323   /// \brief Returns parent directive.
324   OpenMPDirectiveKind getParentDirective() const {
325     if (isStackEmpty() || Stack.back().first.size() == 1)
326       return OMPD_unknown;
327     return std::next(Stack.back().first.rbegin())->Directive;
328   }
329 
330   /// \brief Set default data sharing attribute to none.
331   void setDefaultDSANone(SourceLocation Loc) {
332     assert(!isStackEmpty());
333     Stack.back().first.back().DefaultAttr = DSA_none;
334     Stack.back().first.back().DefaultAttrLoc = Loc;
335   }
336   /// \brief Set default data sharing attribute to shared.
337   void setDefaultDSAShared(SourceLocation Loc) {
338     assert(!isStackEmpty());
339     Stack.back().first.back().DefaultAttr = DSA_shared;
340     Stack.back().first.back().DefaultAttrLoc = Loc;
341   }
342 
343   DefaultDataSharingAttributes getDefaultDSA() const {
344     return isStackEmpty() ? DSA_unspecified
345                           : Stack.back().first.back().DefaultAttr;
346   }
347   SourceLocation getDefaultDSALocation() const {
348     return isStackEmpty() ? SourceLocation()
349                           : Stack.back().first.back().DefaultAttrLoc;
350   }
351 
352   /// \brief Checks if the specified variable is a threadprivate.
353   bool isThreadPrivate(VarDecl *D) {
354     DSAVarData DVar = getTopDSA(D, false);
355     return isOpenMPThreadPrivate(DVar.CKind);
356   }
357 
358   /// \brief Marks current region as ordered (it has an 'ordered' clause).
359   void setOrderedRegion(bool IsOrdered, Expr *Param) {
360     assert(!isStackEmpty());
361     Stack.back().first.back().OrderedRegion.setInt(IsOrdered);
362     Stack.back().first.back().OrderedRegion.setPointer(Param);
363   }
364   /// \brief Returns true, if parent region is ordered (has associated
365   /// 'ordered' clause), false - otherwise.
366   bool isParentOrderedRegion() const {
367     if (isStackEmpty() || Stack.back().first.size() == 1)
368       return false;
369     return std::next(Stack.back().first.rbegin())->OrderedRegion.getInt();
370   }
371   /// \brief Returns optional parameter for the ordered region.
372   Expr *getParentOrderedRegionParam() const {
373     if (isStackEmpty() || Stack.back().first.size() == 1)
374       return nullptr;
375     return std::next(Stack.back().first.rbegin())->OrderedRegion.getPointer();
376   }
377   /// \brief Marks current region as nowait (it has a 'nowait' clause).
378   void setNowaitRegion(bool IsNowait = true) {
379     assert(!isStackEmpty());
380     Stack.back().first.back().NowaitRegion = IsNowait;
381   }
382   /// \brief Returns true, if parent region is nowait (has associated
383   /// 'nowait' clause), false - otherwise.
384   bool isParentNowaitRegion() const {
385     if (isStackEmpty() || Stack.back().first.size() == 1)
386       return false;
387     return std::next(Stack.back().first.rbegin())->NowaitRegion;
388   }
389   /// \brief Marks parent region as cancel region.
390   void setParentCancelRegion(bool Cancel = true) {
391     if (!isStackEmpty() && Stack.back().first.size() > 1) {
392       auto &StackElemRef = *std::next(Stack.back().first.rbegin());
393       StackElemRef.CancelRegion |= StackElemRef.CancelRegion || Cancel;
394     }
395   }
396   /// \brief Return true if current region has inner cancel construct.
397   bool isCancelRegion() const {
398     return isStackEmpty() ? false : Stack.back().first.back().CancelRegion;
399   }
400 
401   /// \brief Set collapse value for the region.
402   void setAssociatedLoops(unsigned Val) {
403     assert(!isStackEmpty());
404     Stack.back().first.back().AssociatedLoops = Val;
405   }
406   /// \brief Return collapse value for region.
407   unsigned getAssociatedLoops() const {
408     return isStackEmpty() ? 0 : Stack.back().first.back().AssociatedLoops;
409   }
410 
411   /// \brief Marks current target region as one with closely nested teams
412   /// region.
413   void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
414     if (!isStackEmpty() && Stack.back().first.size() > 1) {
415       std::next(Stack.back().first.rbegin())->InnerTeamsRegionLoc =
416           TeamsRegionLoc;
417     }
418   }
419   /// \brief Returns true, if current region has closely nested teams region.
420   bool hasInnerTeamsRegion() const {
421     return getInnerTeamsRegionLoc().isValid();
422   }
423   /// \brief Returns location of the nested teams region (if any).
424   SourceLocation getInnerTeamsRegionLoc() const {
425     return isStackEmpty() ? SourceLocation()
426                           : Stack.back().first.back().InnerTeamsRegionLoc;
427   }
428 
429   Scope *getCurScope() const {
430     return isStackEmpty() ? nullptr : Stack.back().first.back().CurScope;
431   }
432   Scope *getCurScope() {
433     return isStackEmpty() ? nullptr : Stack.back().first.back().CurScope;
434   }
435   SourceLocation getConstructLoc() {
436     return isStackEmpty() ? SourceLocation()
437                           : Stack.back().first.back().ConstructLoc;
438   }
439 
440   /// Do the check specified in \a Check to all component lists and return true
441   /// if any issue is found.
442   bool checkMappableExprComponentListsForDecl(
443       ValueDecl *VD, bool CurrentRegionOnly,
444       const llvm::function_ref<
445           bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
446                OpenMPClauseKind)> &Check) {
447     if (isStackEmpty())
448       return false;
449     auto SI = Stack.back().first.rbegin();
450     auto SE = Stack.back().first.rend();
451 
452     if (SI == SE)
453       return false;
454 
455     if (CurrentRegionOnly) {
456       SE = std::next(SI);
457     } else {
458       ++SI;
459     }
460 
461     for (; SI != SE; ++SI) {
462       auto MI = SI->MappedExprComponents.find(VD);
463       if (MI != SI->MappedExprComponents.end())
464         for (auto &L : MI->second.Components)
465           if (Check(L, MI->second.Kind))
466             return true;
467     }
468     return false;
469   }
470 
471   /// Do the check specified in \a Check to all component lists at a given level
472   /// and return true if any issue is found.
473   bool checkMappableExprComponentListsForDeclAtLevel(
474       ValueDecl *VD, unsigned Level,
475       const llvm::function_ref<
476           bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
477                OpenMPClauseKind)> &Check) {
478     if (isStackEmpty())
479       return false;
480 
481     auto StartI = Stack.back().first.begin();
482     auto EndI = Stack.back().first.end();
483     if (std::distance(StartI, EndI) <= (int)Level)
484       return false;
485     std::advance(StartI, Level);
486 
487     auto MI = StartI->MappedExprComponents.find(VD);
488     if (MI != StartI->MappedExprComponents.end())
489       for (auto &L : MI->second.Components)
490         if (Check(L, MI->second.Kind))
491           return true;
492     return false;
493   }
494 
495   /// Create a new mappable expression component list associated with a given
496   /// declaration and initialize it with the provided list of components.
497   void addMappableExpressionComponents(
498       ValueDecl *VD,
499       OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
500       OpenMPClauseKind WhereFoundClauseKind) {
501     assert(!isStackEmpty() &&
502            "Not expecting to retrieve components from a empty stack!");
503     auto &MEC = Stack.back().first.back().MappedExprComponents[VD];
504     // Create new entry and append the new components there.
505     MEC.Components.resize(MEC.Components.size() + 1);
506     MEC.Components.back().append(Components.begin(), Components.end());
507     MEC.Kind = WhereFoundClauseKind;
508   }
509 
510   unsigned getNestingLevel() const {
511     assert(!isStackEmpty());
512     return Stack.back().first.size() - 1;
513   }
514   void addDoacrossDependClause(OMPDependClause *C, OperatorOffsetTy &OpsOffs) {
515     assert(!isStackEmpty() && Stack.back().first.size() > 1);
516     auto &StackElem = *std::next(Stack.back().first.rbegin());
517     assert(isOpenMPWorksharingDirective(StackElem.Directive));
518     StackElem.DoacrossDepends.insert({C, OpsOffs});
519   }
520   llvm::iterator_range<DoacrossDependMapTy::const_iterator>
521   getDoacrossDependClauses() const {
522     assert(!isStackEmpty());
523     auto &StackElem = Stack.back().first.back();
524     if (isOpenMPWorksharingDirective(StackElem.Directive)) {
525       auto &Ref = StackElem.DoacrossDepends;
526       return llvm::make_range(Ref.begin(), Ref.end());
527     }
528     return llvm::make_range(StackElem.DoacrossDepends.end(),
529                             StackElem.DoacrossDepends.end());
530   }
531 };
532 bool isParallelOrTaskRegion(OpenMPDirectiveKind DKind) {
533   return isOpenMPParallelDirective(DKind) || isOpenMPTaskingDirective(DKind) ||
534          isOpenMPTeamsDirective(DKind) || DKind == OMPD_unknown;
535 }
536 } // namespace
537 
538 static Expr *getExprAsWritten(Expr *E) {
539   if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(E))
540     E = ExprTemp->getSubExpr();
541 
542   if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
543     E = MTE->GetTemporaryExpr();
544 
545   while (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
546     E = Binder->getSubExpr();
547 
548   if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
549     E = ICE->getSubExprAsWritten();
550   return E->IgnoreParens();
551 }
552 
553 static ValueDecl *getCanonicalDecl(ValueDecl *D) {
554   if (auto *CED = dyn_cast<OMPCapturedExprDecl>(D))
555     if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
556       D = ME->getMemberDecl();
557   auto *VD = dyn_cast<VarDecl>(D);
558   auto *FD = dyn_cast<FieldDecl>(D);
559   if (VD != nullptr) {
560     VD = VD->getCanonicalDecl();
561     D = VD;
562   } else {
563     assert(FD);
564     FD = FD->getCanonicalDecl();
565     D = FD;
566   }
567   return D;
568 }
569 
570 DSAStackTy::DSAVarData DSAStackTy::getDSA(StackTy::reverse_iterator &Iter,
571                                           ValueDecl *D) {
572   D = getCanonicalDecl(D);
573   auto *VD = dyn_cast<VarDecl>(D);
574   auto *FD = dyn_cast<FieldDecl>(D);
575   DSAVarData DVar;
576   if (isStackEmpty() || Iter == Stack.back().first.rend()) {
577     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
578     // in a region but not in construct]
579     //  File-scope or namespace-scope variables referenced in called routines
580     //  in the region are shared unless they appear in a threadprivate
581     //  directive.
582     if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(D))
583       DVar.CKind = OMPC_shared;
584 
585     // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
586     // in a region but not in construct]
587     //  Variables with static storage duration that are declared in called
588     //  routines in the region are shared.
589     if (VD && VD->hasGlobalStorage())
590       DVar.CKind = OMPC_shared;
591 
592     // Non-static data members are shared by default.
593     if (FD)
594       DVar.CKind = OMPC_shared;
595 
596     return DVar;
597   }
598 
599   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
600   // in a Construct, C/C++, predetermined, p.1]
601   // Variables with automatic storage duration that are declared in a scope
602   // inside the construct are private.
603   if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() &&
604       (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) {
605     DVar.CKind = OMPC_private;
606     return DVar;
607   }
608 
609   DVar.DKind = Iter->Directive;
610   // Explicitly specified attributes and local variables with predetermined
611   // attributes.
612   if (Iter->SharingMap.count(D)) {
613     DVar.RefExpr = Iter->SharingMap[D].RefExpr.getPointer();
614     DVar.PrivateCopy = Iter->SharingMap[D].PrivateCopy;
615     DVar.CKind = Iter->SharingMap[D].Attributes;
616     DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
617     return DVar;
618   }
619 
620   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
621   // in a Construct, C/C++, implicitly determined, p.1]
622   //  In a parallel or task construct, the data-sharing attributes of these
623   //  variables are determined by the default clause, if present.
624   switch (Iter->DefaultAttr) {
625   case DSA_shared:
626     DVar.CKind = OMPC_shared;
627     DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
628     return DVar;
629   case DSA_none:
630     return DVar;
631   case DSA_unspecified:
632     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
633     // in a Construct, implicitly determined, p.2]
634     //  In a parallel construct, if no default clause is present, these
635     //  variables are shared.
636     DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
637     if (isOpenMPParallelDirective(DVar.DKind) ||
638         isOpenMPTeamsDirective(DVar.DKind)) {
639       DVar.CKind = OMPC_shared;
640       return DVar;
641     }
642 
643     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
644     // in a Construct, implicitly determined, p.4]
645     //  In a task construct, if no default clause is present, a variable that in
646     //  the enclosing context is determined to be shared by all implicit tasks
647     //  bound to the current team is shared.
648     if (isOpenMPTaskingDirective(DVar.DKind)) {
649       DSAVarData DVarTemp;
650       auto I = Iter, E = Stack.back().first.rend();
651       do {
652         ++I;
653         // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
654         // Referenced in a Construct, implicitly determined, p.6]
655         //  In a task construct, if no default clause is present, a variable
656         //  whose data-sharing attribute is not determined by the rules above is
657         //  firstprivate.
658         DVarTemp = getDSA(I, D);
659         if (DVarTemp.CKind != OMPC_shared) {
660           DVar.RefExpr = nullptr;
661           DVar.CKind = OMPC_firstprivate;
662           return DVar;
663         }
664       } while (I != E && !isParallelOrTaskRegion(I->Directive));
665       DVar.CKind =
666           (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
667       return DVar;
668     }
669   }
670   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
671   // in a Construct, implicitly determined, p.3]
672   //  For constructs other than task, if no default clause is present, these
673   //  variables inherit their data-sharing attributes from the enclosing
674   //  context.
675   return getDSA(++Iter, D);
676 }
677 
678 Expr *DSAStackTy::addUniqueAligned(ValueDecl *D, Expr *NewDE) {
679   assert(!isStackEmpty() && "Data sharing attributes stack is empty");
680   D = getCanonicalDecl(D);
681   auto &StackElem = Stack.back().first.back();
682   auto It = StackElem.AlignedMap.find(D);
683   if (It == StackElem.AlignedMap.end()) {
684     assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
685     StackElem.AlignedMap[D] = NewDE;
686     return nullptr;
687   } else {
688     assert(It->second && "Unexpected nullptr expr in the aligned map");
689     return It->second;
690   }
691   return nullptr;
692 }
693 
694 void DSAStackTy::addLoopControlVariable(ValueDecl *D, VarDecl *Capture) {
695   assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
696   D = getCanonicalDecl(D);
697   auto &StackElem = Stack.back().first.back();
698   StackElem.LCVMap.insert(
699       {D, LCDeclInfo(StackElem.LCVMap.size() + 1, Capture)});
700 }
701 
702 DSAStackTy::LCDeclInfo DSAStackTy::isLoopControlVariable(ValueDecl *D) {
703   assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
704   D = getCanonicalDecl(D);
705   auto &StackElem = Stack.back().first.back();
706   auto It = StackElem.LCVMap.find(D);
707   if (It != StackElem.LCVMap.end())
708     return It->second;
709   return {0, nullptr};
710 }
711 
712 DSAStackTy::LCDeclInfo DSAStackTy::isParentLoopControlVariable(ValueDecl *D) {
713   assert(!isStackEmpty() && Stack.back().first.size() > 1 &&
714          "Data-sharing attributes stack is empty");
715   D = getCanonicalDecl(D);
716   auto &StackElem = *std::next(Stack.back().first.rbegin());
717   auto It = StackElem.LCVMap.find(D);
718   if (It != StackElem.LCVMap.end())
719     return It->second;
720   return {0, nullptr};
721 }
722 
723 ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) {
724   assert(!isStackEmpty() && Stack.back().first.size() > 1 &&
725          "Data-sharing attributes stack is empty");
726   auto &StackElem = *std::next(Stack.back().first.rbegin());
727   if (StackElem.LCVMap.size() < I)
728     return nullptr;
729   for (auto &Pair : StackElem.LCVMap)
730     if (Pair.second.first == I)
731       return Pair.first;
732   return nullptr;
733 }
734 
735 void DSAStackTy::addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A,
736                         DeclRefExpr *PrivateCopy) {
737   D = getCanonicalDecl(D);
738   if (A == OMPC_threadprivate) {
739     auto &Data = Threadprivates[D];
740     Data.Attributes = A;
741     Data.RefExpr.setPointer(E);
742     Data.PrivateCopy = nullptr;
743   } else {
744     assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
745     auto &Data = Stack.back().first.back().SharingMap[D];
746     assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
747            (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) ||
748            (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) ||
749            (isLoopControlVariable(D).first && A == OMPC_private));
750     if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) {
751       Data.RefExpr.setInt(/*IntVal=*/true);
752       return;
753     }
754     const bool IsLastprivate =
755         A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate;
756     Data.Attributes = A;
757     Data.RefExpr.setPointerAndInt(E, IsLastprivate);
758     Data.PrivateCopy = PrivateCopy;
759     if (PrivateCopy) {
760       auto &Data = Stack.back().first.back().SharingMap[PrivateCopy->getDecl()];
761       Data.Attributes = A;
762       Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate);
763       Data.PrivateCopy = nullptr;
764     }
765   }
766 }
767 
768 /// \brief Build a variable declaration for OpenMP loop iteration variable.
769 static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
770                              StringRef Name, const AttrVec *Attrs = nullptr) {
771   DeclContext *DC = SemaRef.CurContext;
772   IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
773   TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
774   VarDecl *Decl =
775       VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
776   if (Attrs) {
777     for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
778          I != E; ++I)
779       Decl->addAttr(*I);
780   }
781   Decl->setImplicit();
782   return Decl;
783 }
784 
785 static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
786                                      SourceLocation Loc,
787                                      bool RefersToCapture = false) {
788   D->setReferenced();
789   D->markUsed(S.Context);
790   return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
791                              SourceLocation(), D, RefersToCapture, Loc, Ty,
792                              VK_LValue);
793 }
794 
795 void DSAStackTy::addTaskgroupReductionData(ValueDecl *D, SourceRange SR,
796                                            BinaryOperatorKind BOK) {
797   D = getCanonicalDecl(D);
798   assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
799   assert(
800       Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction &&
801       "Additional reduction info may be specified only for reduction items.");
802   auto &ReductionData = Stack.back().first.back().ReductionMap[D];
803   assert(ReductionData.ReductionRange.isInvalid() &&
804          Stack.back().first.back().Directive == OMPD_taskgroup &&
805          "Additional reduction info may be specified only once for reduction "
806          "items.");
807   ReductionData.set(BOK, SR);
808   Expr *&TaskgroupReductionRef =
809       Stack.back().first.back().TaskgroupReductionRef;
810   if (!TaskgroupReductionRef) {
811     auto *VD = buildVarDecl(SemaRef, SourceLocation(),
812                             SemaRef.Context.VoidPtrTy, ".task_red.");
813     TaskgroupReductionRef = buildDeclRefExpr(
814         SemaRef, VD, SemaRef.Context.VoidPtrTy, SourceLocation());
815   }
816 }
817 
818 void DSAStackTy::addTaskgroupReductionData(ValueDecl *D, SourceRange SR,
819                                            const Expr *ReductionRef) {
820   D = getCanonicalDecl(D);
821   assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
822   assert(
823       Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction &&
824       "Additional reduction info may be specified only for reduction items.");
825   auto &ReductionData = Stack.back().first.back().ReductionMap[D];
826   assert(ReductionData.ReductionRange.isInvalid() &&
827          Stack.back().first.back().Directive == OMPD_taskgroup &&
828          "Additional reduction info may be specified only once for reduction "
829          "items.");
830   ReductionData.set(ReductionRef, SR);
831   Expr *&TaskgroupReductionRef =
832       Stack.back().first.back().TaskgroupReductionRef;
833   if (!TaskgroupReductionRef) {
834     auto *VD = buildVarDecl(SemaRef, SourceLocation(),
835                             SemaRef.Context.VoidPtrTy, ".task_red.");
836     TaskgroupReductionRef = buildDeclRefExpr(
837         SemaRef, VD, SemaRef.Context.VoidPtrTy, SourceLocation());
838   }
839 }
840 
841 DSAStackTy::DSAVarData
842 DSAStackTy::getTopMostTaskgroupReductionData(ValueDecl *D, SourceRange &SR,
843                                              BinaryOperatorKind &BOK,
844                                              Expr *&TaskgroupDescriptor) {
845   D = getCanonicalDecl(D);
846   assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
847   if (Stack.back().first.empty())
848       return DSAVarData();
849   for (auto I = std::next(Stack.back().first.rbegin(), 1),
850             E = Stack.back().first.rend();
851        I != E; std::advance(I, 1)) {
852     auto &Data = I->SharingMap[D];
853     if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
854       continue;
855     auto &ReductionData = I->ReductionMap[D];
856     if (!ReductionData.ReductionOp ||
857         ReductionData.ReductionOp.is<const Expr *>())
858       return DSAVarData();
859     SR = ReductionData.ReductionRange;
860     BOK = ReductionData.ReductionOp.get<ReductionData::BOKPtrType>();
861     assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
862                                        "expression for the descriptor is not "
863                                        "set.");
864     TaskgroupDescriptor = I->TaskgroupReductionRef;
865     return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
866                       Data.PrivateCopy, I->DefaultAttrLoc);
867   }
868   return DSAVarData();
869 }
870 
871 DSAStackTy::DSAVarData
872 DSAStackTy::getTopMostTaskgroupReductionData(ValueDecl *D, SourceRange &SR,
873                                              const Expr *&ReductionRef,
874                                              Expr *&TaskgroupDescriptor) {
875   D = getCanonicalDecl(D);
876   assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
877   if (Stack.back().first.empty())
878       return DSAVarData();
879   for (auto I = std::next(Stack.back().first.rbegin(), 1),
880             E = Stack.back().first.rend();
881        I != E; std::advance(I, 1)) {
882     auto &Data = I->SharingMap[D];
883     if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
884       continue;
885     auto &ReductionData = I->ReductionMap[D];
886     if (!ReductionData.ReductionOp ||
887         !ReductionData.ReductionOp.is<const Expr *>())
888       return DSAVarData();
889     SR = ReductionData.ReductionRange;
890     ReductionRef = ReductionData.ReductionOp.get<const Expr *>();
891     assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
892                                        "expression for the descriptor is not "
893                                        "set.");
894     TaskgroupDescriptor = I->TaskgroupReductionRef;
895     return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
896                       Data.PrivateCopy, I->DefaultAttrLoc);
897   }
898   return DSAVarData();
899 }
900 
901 bool DSAStackTy::isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter) {
902   D = D->getCanonicalDecl();
903   if (!isStackEmpty() && Stack.back().first.size() > 1) {
904     reverse_iterator I = Iter, E = Stack.back().first.rend();
905     Scope *TopScope = nullptr;
906     while (I != E && !isParallelOrTaskRegion(I->Directive))
907       ++I;
908     if (I == E)
909       return false;
910     TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
911     Scope *CurScope = getCurScope();
912     while (CurScope != TopScope && !CurScope->isDeclScope(D))
913       CurScope = CurScope->getParent();
914     return CurScope != TopScope;
915   }
916   return false;
917 }
918 
919 DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D, bool FromParent) {
920   D = getCanonicalDecl(D);
921   DSAVarData DVar;
922 
923   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
924   // in a Construct, C/C++, predetermined, p.1]
925   //  Variables appearing in threadprivate directives are threadprivate.
926   auto *VD = dyn_cast<VarDecl>(D);
927   if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
928        !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
929          SemaRef.getLangOpts().OpenMPUseTLS &&
930          SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
931       (VD && VD->getStorageClass() == SC_Register &&
932        VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
933     addDSA(D, buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
934                                D->getLocation()),
935            OMPC_threadprivate);
936   }
937   auto TI = Threadprivates.find(D);
938   if (TI != Threadprivates.end()) {
939     DVar.RefExpr = TI->getSecond().RefExpr.getPointer();
940     DVar.CKind = OMPC_threadprivate;
941     return DVar;
942   }
943 
944   if (isStackEmpty())
945     // Not in OpenMP execution region and top scope was already checked.
946     return DVar;
947 
948   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
949   // in a Construct, C/C++, predetermined, p.4]
950   //  Static data members are shared.
951   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
952   // in a Construct, C/C++, predetermined, p.7]
953   //  Variables with static storage duration that are declared in a scope
954   //  inside the construct are shared.
955   auto &&MatchesAlways = [](OpenMPDirectiveKind) -> bool { return true; };
956   if (VD && VD->isStaticDataMember()) {
957     DSAVarData DVarTemp = hasDSA(D, isOpenMPPrivate, MatchesAlways, FromParent);
958     if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
959       return DVar;
960 
961     DVar.CKind = OMPC_shared;
962     return DVar;
963   }
964 
965   QualType Type = D->getType().getNonReferenceType().getCanonicalType();
966   bool IsConstant = Type.isConstant(SemaRef.getASTContext());
967   Type = SemaRef.getASTContext().getBaseElementType(Type);
968   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
969   // in a Construct, C/C++, predetermined, p.6]
970   //  Variables with const qualified type having no mutable member are
971   //  shared.
972   CXXRecordDecl *RD =
973       SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
974   if (auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
975     if (auto *CTD = CTSD->getSpecializedTemplate())
976       RD = CTD->getTemplatedDecl();
977   if (IsConstant &&
978       !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasDefinition() &&
979         RD->hasMutableFields())) {
980     // Variables with const-qualified type having no mutable member may be
981     // listed in a firstprivate clause, even if they are static data members.
982     DSAVarData DVarTemp = hasDSA(
983         D, [](OpenMPClauseKind C) -> bool { return C == OMPC_firstprivate; },
984         MatchesAlways, FromParent);
985     if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr)
986       return DVar;
987 
988     DVar.CKind = OMPC_shared;
989     return DVar;
990   }
991 
992   // Explicitly specified attributes and local variables with predetermined
993   // attributes.
994   auto I = Stack.back().first.rbegin();
995   auto EndI = Stack.back().first.rend();
996   if (FromParent && I != EndI)
997     std::advance(I, 1);
998   if (I->SharingMap.count(D)) {
999     DVar.RefExpr = I->SharingMap[D].RefExpr.getPointer();
1000     DVar.PrivateCopy = I->SharingMap[D].PrivateCopy;
1001     DVar.CKind = I->SharingMap[D].Attributes;
1002     DVar.ImplicitDSALoc = I->DefaultAttrLoc;
1003     DVar.DKind = I->Directive;
1004   }
1005 
1006   return DVar;
1007 }
1008 
1009 DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
1010                                                   bool FromParent) {
1011   if (isStackEmpty()) {
1012     StackTy::reverse_iterator I;
1013     return getDSA(I, D);
1014   }
1015   D = getCanonicalDecl(D);
1016   auto StartI = Stack.back().first.rbegin();
1017   auto EndI = Stack.back().first.rend();
1018   if (FromParent && StartI != EndI)
1019     std::advance(StartI, 1);
1020   return getDSA(StartI, D);
1021 }
1022 
1023 DSAStackTy::DSAVarData
1024 DSAStackTy::hasDSA(ValueDecl *D,
1025                    const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
1026                    const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
1027                    bool FromParent) {
1028   if (isStackEmpty())
1029     return {};
1030   D = getCanonicalDecl(D);
1031   auto I = Stack.back().first.rbegin();
1032   auto EndI = Stack.back().first.rend();
1033   if (FromParent && I != EndI)
1034     std::advance(I, 1);
1035   for (; I != EndI; std::advance(I, 1)) {
1036     if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive))
1037       continue;
1038     auto NewI = I;
1039     DSAVarData DVar = getDSA(NewI, D);
1040     if (I == NewI && CPred(DVar.CKind))
1041       return DVar;
1042   }
1043   return {};
1044 }
1045 
1046 DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
1047     ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
1048     const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
1049     bool FromParent) {
1050   if (isStackEmpty())
1051     return {};
1052   D = getCanonicalDecl(D);
1053   auto StartI = Stack.back().first.rbegin();
1054   auto EndI = Stack.back().first.rend();
1055   if (FromParent && StartI != EndI)
1056     std::advance(StartI, 1);
1057   if (StartI == EndI || !DPred(StartI->Directive))
1058     return {};
1059   auto NewI = StartI;
1060   DSAVarData DVar = getDSA(NewI, D);
1061   return (NewI == StartI && CPred(DVar.CKind)) ? DVar : DSAVarData();
1062 }
1063 
1064 bool DSAStackTy::hasExplicitDSA(
1065     ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
1066     unsigned Level, bool NotLastprivate) {
1067   if (CPred(ClauseKindMode))
1068     return true;
1069   if (isStackEmpty())
1070     return false;
1071   D = getCanonicalDecl(D);
1072   auto StartI = Stack.back().first.begin();
1073   auto EndI = Stack.back().first.end();
1074   if (std::distance(StartI, EndI) <= (int)Level)
1075     return false;
1076   std::advance(StartI, Level);
1077   return (StartI->SharingMap.count(D) > 0) &&
1078          StartI->SharingMap[D].RefExpr.getPointer() &&
1079          CPred(StartI->SharingMap[D].Attributes) &&
1080          (!NotLastprivate || !StartI->SharingMap[D].RefExpr.getInt());
1081 }
1082 
1083 bool DSAStackTy::hasExplicitDirective(
1084     const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
1085     unsigned Level) {
1086   if (isStackEmpty())
1087     return false;
1088   auto StartI = Stack.back().first.begin();
1089   auto EndI = Stack.back().first.end();
1090   if (std::distance(StartI, EndI) <= (int)Level)
1091     return false;
1092   std::advance(StartI, Level);
1093   return DPred(StartI->Directive);
1094 }
1095 
1096 bool DSAStackTy::hasDirective(
1097     const llvm::function_ref<bool(OpenMPDirectiveKind,
1098                                   const DeclarationNameInfo &, SourceLocation)>
1099         &DPred,
1100     bool FromParent) {
1101   // We look only in the enclosing region.
1102   if (isStackEmpty())
1103     return false;
1104   auto StartI = std::next(Stack.back().first.rbegin());
1105   auto EndI = Stack.back().first.rend();
1106   if (FromParent && StartI != EndI)
1107     StartI = std::next(StartI);
1108   for (auto I = StartI, EE = EndI; I != EE; ++I) {
1109     if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
1110       return true;
1111   }
1112   return false;
1113 }
1114 
1115 void Sema::InitDataSharingAttributesStack() {
1116   VarDataSharingAttributesStack = new DSAStackTy(*this);
1117 }
1118 
1119 #define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
1120 
1121 void Sema::pushOpenMPFunctionRegion() {
1122   DSAStack->pushFunction();
1123 }
1124 
1125 void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) {
1126   DSAStack->popFunction(OldFSI);
1127 }
1128 
1129 bool Sema::IsOpenMPCapturedByRef(ValueDecl *D, unsigned Level) {
1130   assert(LangOpts.OpenMP && "OpenMP is not allowed");
1131 
1132   auto &Ctx = getASTContext();
1133   bool IsByRef = true;
1134 
1135   // Find the directive that is associated with the provided scope.
1136   auto Ty = D->getType();
1137 
1138   if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
1139     // This table summarizes how a given variable should be passed to the device
1140     // given its type and the clauses where it appears. This table is based on
1141     // the description in OpenMP 4.5 [2.10.4, target Construct] and
1142     // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
1143     //
1144     // =========================================================================
1145     // | type |  defaultmap   | pvt | first | is_device_ptr |    map   | res.  |
1146     // |      |(tofrom:scalar)|     |  pvt  |               |          |       |
1147     // =========================================================================
1148     // | scl  |               |     |       |       -       |          | bycopy|
1149     // | scl  |               |  -  |   x   |       -       |     -    | bycopy|
1150     // | scl  |               |  x  |   -   |       -       |     -    | null  |
1151     // | scl  |       x       |     |       |       -       |          | byref |
1152     // | scl  |       x       |  -  |   x   |       -       |     -    | bycopy|
1153     // | scl  |       x       |  x  |   -   |       -       |     -    | null  |
1154     // | scl  |               |  -  |   -   |       -       |     x    | byref |
1155     // | scl  |       x       |  -  |   -   |       -       |     x    | byref |
1156     //
1157     // | agg  |      n.a.     |     |       |       -       |          | byref |
1158     // | agg  |      n.a.     |  -  |   x   |       -       |     -    | byref |
1159     // | agg  |      n.a.     |  x  |   -   |       -       |     -    | null  |
1160     // | agg  |      n.a.     |  -  |   -   |       -       |     x    | byref |
1161     // | agg  |      n.a.     |  -  |   -   |       -       |    x[]   | byref |
1162     //
1163     // | ptr  |      n.a.     |     |       |       -       |          | bycopy|
1164     // | ptr  |      n.a.     |  -  |   x   |       -       |     -    | bycopy|
1165     // | ptr  |      n.a.     |  x  |   -   |       -       |     -    | null  |
1166     // | ptr  |      n.a.     |  -  |   -   |       -       |     x    | byref |
1167     // | ptr  |      n.a.     |  -  |   -   |       -       |    x[]   | bycopy|
1168     // | ptr  |      n.a.     |  -  |   -   |       x       |          | bycopy|
1169     // | ptr  |      n.a.     |  -  |   -   |       x       |     x    | bycopy|
1170     // | ptr  |      n.a.     |  -  |   -   |       x       |    x[]   | bycopy|
1171     // =========================================================================
1172     // Legend:
1173     //  scl - scalar
1174     //  ptr - pointer
1175     //  agg - aggregate
1176     //  x - applies
1177     //  - - invalid in this combination
1178     //  [] - mapped with an array section
1179     //  byref - should be mapped by reference
1180     //  byval - should be mapped by value
1181     //  null - initialize a local variable to null on the device
1182     //
1183     // Observations:
1184     //  - All scalar declarations that show up in a map clause have to be passed
1185     //    by reference, because they may have been mapped in the enclosing data
1186     //    environment.
1187     //  - If the scalar value does not fit the size of uintptr, it has to be
1188     //    passed by reference, regardless the result in the table above.
1189     //  - For pointers mapped by value that have either an implicit map or an
1190     //    array section, the runtime library may pass the NULL value to the
1191     //    device instead of the value passed to it by the compiler.
1192 
1193     if (Ty->isReferenceType())
1194       Ty = Ty->castAs<ReferenceType>()->getPointeeType();
1195 
1196     // Locate map clauses and see if the variable being captured is referred to
1197     // in any of those clauses. Here we only care about variables, not fields,
1198     // because fields are part of aggregates.
1199     bool IsVariableUsedInMapClause = false;
1200     bool IsVariableAssociatedWithSection = false;
1201 
1202     DSAStack->checkMappableExprComponentListsForDeclAtLevel(
1203         D, Level, [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
1204                 MapExprComponents,
1205             OpenMPClauseKind WhereFoundClauseKind) {
1206           // Only the map clause information influences how a variable is
1207           // captured. E.g. is_device_ptr does not require changing the default
1208           // behavior.
1209           if (WhereFoundClauseKind != OMPC_map)
1210             return false;
1211 
1212           auto EI = MapExprComponents.rbegin();
1213           auto EE = MapExprComponents.rend();
1214 
1215           assert(EI != EE && "Invalid map expression!");
1216 
1217           if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
1218             IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
1219 
1220           ++EI;
1221           if (EI == EE)
1222             return false;
1223 
1224           if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
1225               isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
1226               isa<MemberExpr>(EI->getAssociatedExpression())) {
1227             IsVariableAssociatedWithSection = true;
1228             // There is nothing more we need to know about this variable.
1229             return true;
1230           }
1231 
1232           // Keep looking for more map info.
1233           return false;
1234         });
1235 
1236     if (IsVariableUsedInMapClause) {
1237       // If variable is identified in a map clause it is always captured by
1238       // reference except if it is a pointer that is dereferenced somehow.
1239       IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
1240     } else {
1241       // By default, all the data that has a scalar type is mapped by copy.
1242       IsByRef = !Ty->isScalarType();
1243     }
1244   }
1245 
1246   if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
1247     IsByRef = !DSAStack->hasExplicitDSA(
1248         D, [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; },
1249         Level, /*NotLastprivate=*/true);
1250   }
1251 
1252   // When passing data by copy, we need to make sure it fits the uintptr size
1253   // and alignment, because the runtime library only deals with uintptr types.
1254   // If it does not fit the uintptr size, we need to pass the data by reference
1255   // instead.
1256   if (!IsByRef &&
1257       (Ctx.getTypeSizeInChars(Ty) >
1258            Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
1259        Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
1260     IsByRef = true;
1261   }
1262 
1263   return IsByRef;
1264 }
1265 
1266 unsigned Sema::getOpenMPNestingLevel() const {
1267   assert(getLangOpts().OpenMP);
1268   return DSAStack->getNestingLevel();
1269 }
1270 
1271 VarDecl *Sema::IsOpenMPCapturedDecl(ValueDecl *D) {
1272   assert(LangOpts.OpenMP && "OpenMP is not allowed");
1273   D = getCanonicalDecl(D);
1274 
1275   // If we are attempting to capture a global variable in a directive with
1276   // 'target' we return true so that this global is also mapped to the device.
1277   //
1278   // FIXME: If the declaration is enclosed in a 'declare target' directive,
1279   // then it should not be captured. Therefore, an extra check has to be
1280   // inserted here once support for 'declare target' is added.
1281   //
1282   auto *VD = dyn_cast<VarDecl>(D);
1283   if (VD && !VD->hasLocalStorage()) {
1284     if (DSAStack->getCurrentDirective() == OMPD_target &&
1285         !DSAStack->isClauseParsingMode())
1286       return VD;
1287     if (DSAStack->hasDirective(
1288             [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
1289                SourceLocation) -> bool {
1290               return isOpenMPTargetExecutionDirective(K);
1291             },
1292             false))
1293       return VD;
1294   }
1295 
1296   if (DSAStack->getCurrentDirective() != OMPD_unknown &&
1297       (!DSAStack->isClauseParsingMode() ||
1298        DSAStack->getParentDirective() != OMPD_unknown)) {
1299     auto &&Info = DSAStack->isLoopControlVariable(D);
1300     if (Info.first ||
1301         (VD && VD->hasLocalStorage() &&
1302          isParallelOrTaskRegion(DSAStack->getCurrentDirective())) ||
1303         (VD && DSAStack->isForceVarCapturing()))
1304       return VD ? VD : Info.second;
1305     auto DVarPrivate = DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
1306     if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
1307       return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
1308     DVarPrivate = DSAStack->hasDSA(
1309         D, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
1310         DSAStack->isClauseParsingMode());
1311     if (DVarPrivate.CKind != OMPC_unknown)
1312       return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
1313   }
1314   return nullptr;
1315 }
1316 
1317 bool Sema::isOpenMPPrivateDecl(ValueDecl *D, unsigned Level) {
1318   assert(LangOpts.OpenMP && "OpenMP is not allowed");
1319   return DSAStack->hasExplicitDSA(
1320              D, [](OpenMPClauseKind K) -> bool { return K == OMPC_private; },
1321              Level) ||
1322          // Consider taskgroup reduction descriptor variable a private to avoid
1323          // possible capture in the region.
1324          (DSAStack->hasExplicitDirective(
1325               [](OpenMPDirectiveKind K) { return K == OMPD_taskgroup; },
1326               Level) &&
1327           DSAStack->isTaskgroupReductionRef(D, Level));
1328 }
1329 
1330 bool Sema::isOpenMPTargetCapturedDecl(ValueDecl *D, unsigned Level) {
1331   assert(LangOpts.OpenMP && "OpenMP is not allowed");
1332   // Return true if the current level is no longer enclosed in a target region.
1333 
1334   auto *VD = dyn_cast<VarDecl>(D);
1335   return VD && !VD->hasLocalStorage() &&
1336          DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
1337                                         Level);
1338 }
1339 
1340 void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
1341 
1342 void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
1343                                const DeclarationNameInfo &DirName,
1344                                Scope *CurScope, SourceLocation Loc) {
1345   DSAStack->push(DKind, DirName, CurScope, Loc);
1346   PushExpressionEvaluationContext(
1347       ExpressionEvaluationContext::PotentiallyEvaluated);
1348 }
1349 
1350 void Sema::StartOpenMPClause(OpenMPClauseKind K) {
1351   DSAStack->setClauseParsingMode(K);
1352 }
1353 
1354 void Sema::EndOpenMPClause() {
1355   DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
1356 }
1357 
1358 void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
1359   // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
1360   //  A variable of class type (or array thereof) that appears in a lastprivate
1361   //  clause requires an accessible, unambiguous default constructor for the
1362   //  class type, unless the list item is also specified in a firstprivate
1363   //  clause.
1364   if (auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
1365     for (auto *C : D->clauses()) {
1366       if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
1367         SmallVector<Expr *, 8> PrivateCopies;
1368         for (auto *DE : Clause->varlists()) {
1369           if (DE->isValueDependent() || DE->isTypeDependent()) {
1370             PrivateCopies.push_back(nullptr);
1371             continue;
1372           }
1373           auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
1374           VarDecl *VD = cast<VarDecl>(DRE->getDecl());
1375           QualType Type = VD->getType().getNonReferenceType();
1376           auto DVar = DSAStack->getTopDSA(VD, false);
1377           if (DVar.CKind == OMPC_lastprivate) {
1378             // Generate helper private variable and initialize it with the
1379             // default value. The address of the original variable is replaced
1380             // by the address of the new private variable in CodeGen. This new
1381             // variable is not added to IdResolver, so the code in the OpenMP
1382             // region uses original variable for proper diagnostics.
1383             auto *VDPrivate = buildVarDecl(
1384                 *this, DE->getExprLoc(), Type.getUnqualifiedType(),
1385                 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr);
1386             ActOnUninitializedDecl(VDPrivate);
1387             if (VDPrivate->isInvalidDecl())
1388               continue;
1389             PrivateCopies.push_back(buildDeclRefExpr(
1390                 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
1391           } else {
1392             // The variable is also a firstprivate, so initialization sequence
1393             // for private copy is generated already.
1394             PrivateCopies.push_back(nullptr);
1395           }
1396         }
1397         // Set initializers to private copies if no errors were found.
1398         if (PrivateCopies.size() == Clause->varlist_size())
1399           Clause->setPrivateCopies(PrivateCopies);
1400       }
1401     }
1402   }
1403 
1404   DSAStack->pop();
1405   DiscardCleanupsInEvaluationContext();
1406   PopExpressionEvaluationContext();
1407 }
1408 
1409 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
1410                                      Expr *NumIterations, Sema &SemaRef,
1411                                      Scope *S, DSAStackTy *Stack);
1412 
1413 namespace {
1414 
1415 class VarDeclFilterCCC : public CorrectionCandidateCallback {
1416 private:
1417   Sema &SemaRef;
1418 
1419 public:
1420   explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
1421   bool ValidateCandidate(const TypoCorrection &Candidate) override {
1422     NamedDecl *ND = Candidate.getCorrectionDecl();
1423     if (auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
1424       return VD->hasGlobalStorage() &&
1425              SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1426                                    SemaRef.getCurScope());
1427     }
1428     return false;
1429   }
1430 };
1431 
1432 class VarOrFuncDeclFilterCCC : public CorrectionCandidateCallback {
1433 private:
1434   Sema &SemaRef;
1435 
1436 public:
1437   explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
1438   bool ValidateCandidate(const TypoCorrection &Candidate) override {
1439     NamedDecl *ND = Candidate.getCorrectionDecl();
1440     if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) {
1441       return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1442                                    SemaRef.getCurScope());
1443     }
1444     return false;
1445   }
1446 };
1447 
1448 } // namespace
1449 
1450 ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
1451                                          CXXScopeSpec &ScopeSpec,
1452                                          const DeclarationNameInfo &Id) {
1453   LookupResult Lookup(*this, Id, LookupOrdinaryName);
1454   LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
1455 
1456   if (Lookup.isAmbiguous())
1457     return ExprError();
1458 
1459   VarDecl *VD;
1460   if (!Lookup.isSingleResult()) {
1461     if (TypoCorrection Corrected = CorrectTypo(
1462             Id, LookupOrdinaryName, CurScope, nullptr,
1463             llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) {
1464       diagnoseTypo(Corrected,
1465                    PDiag(Lookup.empty()
1466                              ? diag::err_undeclared_var_use_suggest
1467                              : diag::err_omp_expected_var_arg_suggest)
1468                        << Id.getName());
1469       VD = Corrected.getCorrectionDeclAs<VarDecl>();
1470     } else {
1471       Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
1472                                        : diag::err_omp_expected_var_arg)
1473           << Id.getName();
1474       return ExprError();
1475     }
1476   } else {
1477     if (!(VD = Lookup.getAsSingle<VarDecl>())) {
1478       Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
1479       Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
1480       return ExprError();
1481     }
1482   }
1483   Lookup.suppressDiagnostics();
1484 
1485   // OpenMP [2.9.2, Syntax, C/C++]
1486   //   Variables must be file-scope, namespace-scope, or static block-scope.
1487   if (!VD->hasGlobalStorage()) {
1488     Diag(Id.getLoc(), diag::err_omp_global_var_arg)
1489         << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal();
1490     bool IsDecl =
1491         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1492     Diag(VD->getLocation(),
1493          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1494         << VD;
1495     return ExprError();
1496   }
1497 
1498   VarDecl *CanonicalVD = VD->getCanonicalDecl();
1499   NamedDecl *ND = cast<NamedDecl>(CanonicalVD);
1500   // OpenMP [2.9.2, Restrictions, C/C++, p.2]
1501   //   A threadprivate directive for file-scope variables must appear outside
1502   //   any definition or declaration.
1503   if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
1504       !getCurLexicalContext()->isTranslationUnit()) {
1505     Diag(Id.getLoc(), diag::err_omp_var_scope)
1506         << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1507     bool IsDecl =
1508         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1509     Diag(VD->getLocation(),
1510          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1511         << VD;
1512     return ExprError();
1513   }
1514   // OpenMP [2.9.2, Restrictions, C/C++, p.3]
1515   //   A threadprivate directive for static class member variables must appear
1516   //   in the class definition, in the same scope in which the member
1517   //   variables are declared.
1518   if (CanonicalVD->isStaticDataMember() &&
1519       !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
1520     Diag(Id.getLoc(), diag::err_omp_var_scope)
1521         << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1522     bool IsDecl =
1523         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1524     Diag(VD->getLocation(),
1525          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1526         << VD;
1527     return ExprError();
1528   }
1529   // OpenMP [2.9.2, Restrictions, C/C++, p.4]
1530   //   A threadprivate directive for namespace-scope variables must appear
1531   //   outside any definition or declaration other than the namespace
1532   //   definition itself.
1533   if (CanonicalVD->getDeclContext()->isNamespace() &&
1534       (!getCurLexicalContext()->isFileContext() ||
1535        !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
1536     Diag(Id.getLoc(), diag::err_omp_var_scope)
1537         << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1538     bool IsDecl =
1539         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1540     Diag(VD->getLocation(),
1541          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1542         << VD;
1543     return ExprError();
1544   }
1545   // OpenMP [2.9.2, Restrictions, C/C++, p.6]
1546   //   A threadprivate directive for static block-scope variables must appear
1547   //   in the scope of the variable and not in a nested scope.
1548   if (CanonicalVD->isStaticLocal() && CurScope &&
1549       !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
1550     Diag(Id.getLoc(), diag::err_omp_var_scope)
1551         << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1552     bool IsDecl =
1553         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1554     Diag(VD->getLocation(),
1555          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1556         << VD;
1557     return ExprError();
1558   }
1559 
1560   // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
1561   //   A threadprivate directive must lexically precede all references to any
1562   //   of the variables in its list.
1563   if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) {
1564     Diag(Id.getLoc(), diag::err_omp_var_used)
1565         << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1566     return ExprError();
1567   }
1568 
1569   QualType ExprType = VD->getType().getNonReferenceType();
1570   return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
1571                              SourceLocation(), VD,
1572                              /*RefersToEnclosingVariableOrCapture=*/false,
1573                              Id.getLoc(), ExprType, VK_LValue);
1574 }
1575 
1576 Sema::DeclGroupPtrTy
1577 Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
1578                                         ArrayRef<Expr *> VarList) {
1579   if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
1580     CurContext->addDecl(D);
1581     return DeclGroupPtrTy::make(DeclGroupRef(D));
1582   }
1583   return nullptr;
1584 }
1585 
1586 namespace {
1587 class LocalVarRefChecker : public ConstStmtVisitor<LocalVarRefChecker, bool> {
1588   Sema &SemaRef;
1589 
1590 public:
1591   bool VisitDeclRefExpr(const DeclRefExpr *E) {
1592     if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
1593       if (VD->hasLocalStorage()) {
1594         SemaRef.Diag(E->getLocStart(),
1595                      diag::err_omp_local_var_in_threadprivate_init)
1596             << E->getSourceRange();
1597         SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
1598             << VD << VD->getSourceRange();
1599         return true;
1600       }
1601     }
1602     return false;
1603   }
1604   bool VisitStmt(const Stmt *S) {
1605     for (auto Child : S->children()) {
1606       if (Child && Visit(Child))
1607         return true;
1608     }
1609     return false;
1610   }
1611   explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
1612 };
1613 } // namespace
1614 
1615 OMPThreadPrivateDecl *
1616 Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
1617   SmallVector<Expr *, 8> Vars;
1618   for (auto &RefExpr : VarList) {
1619     DeclRefExpr *DE = cast<DeclRefExpr>(RefExpr);
1620     VarDecl *VD = cast<VarDecl>(DE->getDecl());
1621     SourceLocation ILoc = DE->getExprLoc();
1622 
1623     // Mark variable as used.
1624     VD->setReferenced();
1625     VD->markUsed(Context);
1626 
1627     QualType QType = VD->getType();
1628     if (QType->isDependentType() || QType->isInstantiationDependentType()) {
1629       // It will be analyzed later.
1630       Vars.push_back(DE);
1631       continue;
1632     }
1633 
1634     // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1635     //   A threadprivate variable must not have an incomplete type.
1636     if (RequireCompleteType(ILoc, VD->getType(),
1637                             diag::err_omp_threadprivate_incomplete_type)) {
1638       continue;
1639     }
1640 
1641     // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1642     //   A threadprivate variable must not have a reference type.
1643     if (VD->getType()->isReferenceType()) {
1644       Diag(ILoc, diag::err_omp_ref_type_arg)
1645           << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
1646       bool IsDecl =
1647           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1648       Diag(VD->getLocation(),
1649            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1650           << VD;
1651       continue;
1652     }
1653 
1654     // Check if this is a TLS variable. If TLS is not being supported, produce
1655     // the corresponding diagnostic.
1656     if ((VD->getTLSKind() != VarDecl::TLS_None &&
1657          !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
1658            getLangOpts().OpenMPUseTLS &&
1659            getASTContext().getTargetInfo().isTLSSupported())) ||
1660         (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
1661          !VD->isLocalVarDecl())) {
1662       Diag(ILoc, diag::err_omp_var_thread_local)
1663           << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
1664       bool IsDecl =
1665           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1666       Diag(VD->getLocation(),
1667            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1668           << VD;
1669       continue;
1670     }
1671 
1672     // Check if initial value of threadprivate variable reference variable with
1673     // local storage (it is not supported by runtime).
1674     if (auto Init = VD->getAnyInitializer()) {
1675       LocalVarRefChecker Checker(*this);
1676       if (Checker.Visit(Init))
1677         continue;
1678     }
1679 
1680     Vars.push_back(RefExpr);
1681     DSAStack->addDSA(VD, DE, OMPC_threadprivate);
1682     VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
1683         Context, SourceRange(Loc, Loc)));
1684     if (auto *ML = Context.getASTMutationListener())
1685       ML->DeclarationMarkedOpenMPThreadPrivate(VD);
1686   }
1687   OMPThreadPrivateDecl *D = nullptr;
1688   if (!Vars.empty()) {
1689     D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
1690                                      Vars);
1691     D->setAccess(AS_public);
1692   }
1693   return D;
1694 }
1695 
1696 static void ReportOriginalDSA(Sema &SemaRef, DSAStackTy *Stack,
1697                               const ValueDecl *D, DSAStackTy::DSAVarData DVar,
1698                               bool IsLoopIterVar = false) {
1699   if (DVar.RefExpr) {
1700     SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
1701         << getOpenMPClauseName(DVar.CKind);
1702     return;
1703   }
1704   enum {
1705     PDSA_StaticMemberShared,
1706     PDSA_StaticLocalVarShared,
1707     PDSA_LoopIterVarPrivate,
1708     PDSA_LoopIterVarLinear,
1709     PDSA_LoopIterVarLastprivate,
1710     PDSA_ConstVarShared,
1711     PDSA_GlobalVarShared,
1712     PDSA_TaskVarFirstprivate,
1713     PDSA_LocalVarPrivate,
1714     PDSA_Implicit
1715   } Reason = PDSA_Implicit;
1716   bool ReportHint = false;
1717   auto ReportLoc = D->getLocation();
1718   auto *VD = dyn_cast<VarDecl>(D);
1719   if (IsLoopIterVar) {
1720     if (DVar.CKind == OMPC_private)
1721       Reason = PDSA_LoopIterVarPrivate;
1722     else if (DVar.CKind == OMPC_lastprivate)
1723       Reason = PDSA_LoopIterVarLastprivate;
1724     else
1725       Reason = PDSA_LoopIterVarLinear;
1726   } else if (isOpenMPTaskingDirective(DVar.DKind) &&
1727              DVar.CKind == OMPC_firstprivate) {
1728     Reason = PDSA_TaskVarFirstprivate;
1729     ReportLoc = DVar.ImplicitDSALoc;
1730   } else if (VD && VD->isStaticLocal())
1731     Reason = PDSA_StaticLocalVarShared;
1732   else if (VD && VD->isStaticDataMember())
1733     Reason = PDSA_StaticMemberShared;
1734   else if (VD && VD->isFileVarDecl())
1735     Reason = PDSA_GlobalVarShared;
1736   else if (D->getType().isConstant(SemaRef.getASTContext()))
1737     Reason = PDSA_ConstVarShared;
1738   else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
1739     ReportHint = true;
1740     Reason = PDSA_LocalVarPrivate;
1741   }
1742   if (Reason != PDSA_Implicit) {
1743     SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
1744         << Reason << ReportHint
1745         << getOpenMPDirectiveName(Stack->getCurrentDirective());
1746   } else if (DVar.ImplicitDSALoc.isValid()) {
1747     SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
1748         << getOpenMPClauseName(DVar.CKind);
1749   }
1750 }
1751 
1752 namespace {
1753 class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> {
1754   DSAStackTy *Stack;
1755   Sema &SemaRef;
1756   bool ErrorFound;
1757   CapturedStmt *CS;
1758   llvm::SmallVector<Expr *, 8> ImplicitFirstprivate;
1759   llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
1760 
1761 public:
1762   void VisitDeclRefExpr(DeclRefExpr *E) {
1763     if (E->isTypeDependent() || E->isValueDependent() ||
1764         E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
1765       return;
1766     if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
1767       // Skip internally declared variables.
1768       if (VD->isLocalVarDecl() && !CS->capturesVariable(VD))
1769         return;
1770 
1771       auto DVar = Stack->getTopDSA(VD, false);
1772       // Check if the variable has explicit DSA set and stop analysis if it so.
1773       if (DVar.RefExpr)
1774         return;
1775 
1776       auto ELoc = E->getExprLoc();
1777       auto DKind = Stack->getCurrentDirective();
1778       // The default(none) clause requires that each variable that is referenced
1779       // in the construct, and does not have a predetermined data-sharing
1780       // attribute, must have its data-sharing attribute explicitly determined
1781       // by being listed in a data-sharing attribute clause.
1782       if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
1783           isParallelOrTaskRegion(DKind) &&
1784           VarsWithInheritedDSA.count(VD) == 0) {
1785         VarsWithInheritedDSA[VD] = E;
1786         return;
1787       }
1788 
1789       // OpenMP [2.9.3.6, Restrictions, p.2]
1790       //  A list item that appears in a reduction clause of the innermost
1791       //  enclosing worksharing or parallel construct may not be accessed in an
1792       //  explicit task.
1793       DVar = Stack->hasInnermostDSA(
1794           VD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
1795           [](OpenMPDirectiveKind K) -> bool {
1796             return isOpenMPParallelDirective(K) ||
1797                    isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
1798           },
1799           /*FromParent=*/true);
1800       if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
1801         ErrorFound = true;
1802         SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
1803         ReportOriginalDSA(SemaRef, Stack, VD, DVar);
1804         return;
1805       }
1806 
1807       // Define implicit data-sharing attributes for task.
1808       DVar = Stack->getImplicitDSA(VD, false);
1809       if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
1810           !Stack->isLoopControlVariable(VD).first)
1811         ImplicitFirstprivate.push_back(E);
1812     }
1813   }
1814   void VisitMemberExpr(MemberExpr *E) {
1815     if (E->isTypeDependent() || E->isValueDependent() ||
1816         E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
1817       return;
1818     if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
1819       if (auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
1820         auto DVar = Stack->getTopDSA(FD, false);
1821         // Check if the variable has explicit DSA set and stop analysis if it
1822         // so.
1823         if (DVar.RefExpr)
1824           return;
1825 
1826         auto ELoc = E->getExprLoc();
1827         auto DKind = Stack->getCurrentDirective();
1828         // OpenMP [2.9.3.6, Restrictions, p.2]
1829         //  A list item that appears in a reduction clause of the innermost
1830         //  enclosing worksharing or parallel construct may not be accessed in
1831         //  an  explicit task.
1832         DVar = Stack->hasInnermostDSA(
1833             FD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
1834             [](OpenMPDirectiveKind K) -> bool {
1835               return isOpenMPParallelDirective(K) ||
1836                      isOpenMPWorksharingDirective(K) ||
1837                      isOpenMPTeamsDirective(K);
1838             },
1839             /*FromParent=*/true);
1840         if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
1841           ErrorFound = true;
1842           SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
1843           ReportOriginalDSA(SemaRef, Stack, FD, DVar);
1844           return;
1845         }
1846 
1847         // Define implicit data-sharing attributes for task.
1848         DVar = Stack->getImplicitDSA(FD, false);
1849         if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
1850             !Stack->isLoopControlVariable(FD).first)
1851           ImplicitFirstprivate.push_back(E);
1852       }
1853     } else
1854       Visit(E->getBase());
1855   }
1856   void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
1857     for (auto *C : S->clauses()) {
1858       // Skip analysis of arguments of implicitly defined firstprivate clause
1859       // for task directives.
1860       if (C && (!isa<OMPFirstprivateClause>(C) || C->getLocStart().isValid()))
1861         for (auto *CC : C->children()) {
1862           if (CC)
1863             Visit(CC);
1864         }
1865     }
1866   }
1867   void VisitStmt(Stmt *S) {
1868     for (auto *C : S->children()) {
1869       if (C && !isa<OMPExecutableDirective>(C))
1870         Visit(C);
1871     }
1872   }
1873 
1874   bool isErrorFound() { return ErrorFound; }
1875   ArrayRef<Expr *> getImplicitFirstprivate() { return ImplicitFirstprivate; }
1876   llvm::DenseMap<ValueDecl *, Expr *> &getVarsWithInheritedDSA() {
1877     return VarsWithInheritedDSA;
1878   }
1879 
1880   DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
1881       : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {}
1882 };
1883 } // namespace
1884 
1885 void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
1886   switch (DKind) {
1887   case OMPD_parallel:
1888   case OMPD_parallel_for:
1889   case OMPD_parallel_for_simd:
1890   case OMPD_parallel_sections:
1891   case OMPD_teams: {
1892     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1893     QualType KmpInt32PtrTy =
1894         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
1895     Sema::CapturedParamNameType Params[] = {
1896         std::make_pair(".global_tid.", KmpInt32PtrTy),
1897         std::make_pair(".bound_tid.", KmpInt32PtrTy),
1898         std::make_pair(StringRef(), QualType()) // __context with shared vars
1899     };
1900     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1901                              Params);
1902     break;
1903   }
1904   case OMPD_target_teams:
1905   case OMPD_target_parallel: {
1906     Sema::CapturedParamNameType ParamsTarget[] = {
1907         std::make_pair(StringRef(), QualType()) // __context with shared vars
1908     };
1909     // Start a captured region for 'target' with no implicit parameters.
1910     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1911                              ParamsTarget);
1912     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1913     QualType KmpInt32PtrTy =
1914         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
1915     Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
1916         std::make_pair(".global_tid.", KmpInt32PtrTy),
1917         std::make_pair(".bound_tid.", KmpInt32PtrTy),
1918         std::make_pair(StringRef(), QualType()) // __context with shared vars
1919     };
1920     // Start a captured region for 'teams' or 'parallel'.  Both regions have
1921     // the same implicit parameters.
1922     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1923                              ParamsTeamsOrParallel);
1924     break;
1925   }
1926   case OMPD_simd:
1927   case OMPD_for:
1928   case OMPD_for_simd:
1929   case OMPD_sections:
1930   case OMPD_section:
1931   case OMPD_single:
1932   case OMPD_master:
1933   case OMPD_critical:
1934   case OMPD_taskgroup:
1935   case OMPD_distribute:
1936   case OMPD_ordered:
1937   case OMPD_atomic:
1938   case OMPD_target_data:
1939   case OMPD_target:
1940   case OMPD_target_parallel_for:
1941   case OMPD_target_parallel_for_simd:
1942   case OMPD_target_simd: {
1943     Sema::CapturedParamNameType Params[] = {
1944         std::make_pair(StringRef(), QualType()) // __context with shared vars
1945     };
1946     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1947                              Params);
1948     break;
1949   }
1950   case OMPD_task: {
1951     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1952     QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
1953     FunctionProtoType::ExtProtoInfo EPI;
1954     EPI.Variadic = true;
1955     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
1956     Sema::CapturedParamNameType Params[] = {
1957         std::make_pair(".global_tid.", KmpInt32Ty),
1958         std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
1959         std::make_pair(".privates.", Context.VoidPtrTy.withConst()),
1960         std::make_pair(".copy_fn.",
1961                        Context.getPointerType(CopyFnType).withConst()),
1962         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
1963         std::make_pair(StringRef(), QualType()) // __context with shared vars
1964     };
1965     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1966                              Params);
1967     // Mark this captured region as inlined, because we don't use outlined
1968     // function directly.
1969     getCurCapturedRegion()->TheCapturedDecl->addAttr(
1970         AlwaysInlineAttr::CreateImplicit(
1971             Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
1972     break;
1973   }
1974   case OMPD_taskloop:
1975   case OMPD_taskloop_simd: {
1976     QualType KmpInt32Ty =
1977         Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1978     QualType KmpUInt64Ty =
1979         Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
1980     QualType KmpInt64Ty =
1981         Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
1982     QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
1983     FunctionProtoType::ExtProtoInfo EPI;
1984     EPI.Variadic = true;
1985     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
1986     Sema::CapturedParamNameType Params[] = {
1987         std::make_pair(".global_tid.", KmpInt32Ty),
1988         std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
1989         std::make_pair(".privates.",
1990                        Context.VoidPtrTy.withConst().withRestrict()),
1991         std::make_pair(
1992             ".copy_fn.",
1993             Context.getPointerType(CopyFnType).withConst().withRestrict()),
1994         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
1995         std::make_pair(".lb.", KmpUInt64Ty),
1996         std::make_pair(".ub.", KmpUInt64Ty), std::make_pair(".st.", KmpInt64Ty),
1997         std::make_pair(".liter.", KmpInt32Ty),
1998         std::make_pair(".reductions.",
1999                        Context.VoidPtrTy.withConst().withRestrict()),
2000         std::make_pair(StringRef(), QualType()) // __context with shared vars
2001     };
2002     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2003                              Params);
2004     // Mark this captured region as inlined, because we don't use outlined
2005     // function directly.
2006     getCurCapturedRegion()->TheCapturedDecl->addAttr(
2007         AlwaysInlineAttr::CreateImplicit(
2008             Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
2009     break;
2010   }
2011   case OMPD_distribute_parallel_for_simd:
2012   case OMPD_distribute_simd:
2013   case OMPD_distribute_parallel_for:
2014   case OMPD_teams_distribute:
2015   case OMPD_teams_distribute_simd:
2016   case OMPD_teams_distribute_parallel_for_simd:
2017   case OMPD_teams_distribute_parallel_for:
2018   case OMPD_target_teams_distribute:
2019   case OMPD_target_teams_distribute_parallel_for:
2020   case OMPD_target_teams_distribute_parallel_for_simd:
2021   case OMPD_target_teams_distribute_simd: {
2022     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
2023     QualType KmpInt32PtrTy =
2024         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2025     Sema::CapturedParamNameType Params[] = {
2026         std::make_pair(".global_tid.", KmpInt32PtrTy),
2027         std::make_pair(".bound_tid.", KmpInt32PtrTy),
2028         std::make_pair(".previous.lb.", Context.getSizeType()),
2029         std::make_pair(".previous.ub.", Context.getSizeType()),
2030         std::make_pair(StringRef(), QualType()) // __context with shared vars
2031     };
2032     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2033                              Params);
2034     break;
2035   }
2036   case OMPD_threadprivate:
2037   case OMPD_taskyield:
2038   case OMPD_barrier:
2039   case OMPD_taskwait:
2040   case OMPD_cancellation_point:
2041   case OMPD_cancel:
2042   case OMPD_flush:
2043   case OMPD_target_enter_data:
2044   case OMPD_target_exit_data:
2045   case OMPD_declare_reduction:
2046   case OMPD_declare_simd:
2047   case OMPD_declare_target:
2048   case OMPD_end_declare_target:
2049   case OMPD_target_update:
2050     llvm_unreachable("OpenMP Directive is not allowed");
2051   case OMPD_unknown:
2052     llvm_unreachable("Unknown OpenMP directive");
2053   }
2054 }
2055 
2056 int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
2057   SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
2058   getOpenMPCaptureRegions(CaptureRegions, DKind);
2059   return CaptureRegions.size();
2060 }
2061 
2062 static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
2063                                              Expr *CaptureExpr, bool WithInit,
2064                                              bool AsExpression) {
2065   assert(CaptureExpr);
2066   ASTContext &C = S.getASTContext();
2067   Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
2068   QualType Ty = Init->getType();
2069   if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
2070     if (S.getLangOpts().CPlusPlus)
2071       Ty = C.getLValueReferenceType(Ty);
2072     else {
2073       Ty = C.getPointerType(Ty);
2074       ExprResult Res =
2075           S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
2076       if (!Res.isUsable())
2077         return nullptr;
2078       Init = Res.get();
2079     }
2080     WithInit = true;
2081   }
2082   auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
2083                                           CaptureExpr->getLocStart());
2084   if (!WithInit)
2085     CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C, SourceRange()));
2086   S.CurContext->addHiddenDecl(CED);
2087   S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
2088   return CED;
2089 }
2090 
2091 static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
2092                                  bool WithInit) {
2093   OMPCapturedExprDecl *CD;
2094   if (auto *VD = S.IsOpenMPCapturedDecl(D))
2095     CD = cast<OMPCapturedExprDecl>(VD);
2096   else
2097     CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
2098                           /*AsExpression=*/false);
2099   return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
2100                           CaptureExpr->getExprLoc());
2101 }
2102 
2103 static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
2104   if (!Ref) {
2105     auto *CD =
2106         buildCaptureDecl(S, &S.getASTContext().Idents.get(".capture_expr."),
2107                          CaptureExpr, /*WithInit=*/true, /*AsExpression=*/true);
2108     Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
2109                            CaptureExpr->getExprLoc());
2110   }
2111   ExprResult Res = Ref;
2112   if (!S.getLangOpts().CPlusPlus &&
2113       CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
2114       Ref->getType()->isPointerType())
2115     Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
2116   if (!Res.isUsable())
2117     return ExprError();
2118   return CaptureExpr->isGLValue() ? Res : S.DefaultLvalueConversion(Res.get());
2119 }
2120 
2121 namespace {
2122 // OpenMP directives parsed in this section are represented as a
2123 // CapturedStatement with an associated statement.  If a syntax error
2124 // is detected during the parsing of the associated statement, the
2125 // compiler must abort processing and close the CapturedStatement.
2126 //
2127 // Combined directives such as 'target parallel' have more than one
2128 // nested CapturedStatements.  This RAII ensures that we unwind out
2129 // of all the nested CapturedStatements when an error is found.
2130 class CaptureRegionUnwinderRAII {
2131 private:
2132   Sema &S;
2133   bool &ErrorFound;
2134   OpenMPDirectiveKind DKind;
2135 
2136 public:
2137   CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
2138                             OpenMPDirectiveKind DKind)
2139       : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
2140   ~CaptureRegionUnwinderRAII() {
2141     if (ErrorFound) {
2142       int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
2143       while (--ThisCaptureLevel >= 0)
2144         S.ActOnCapturedRegionError();
2145     }
2146   }
2147 };
2148 } // namespace
2149 
2150 StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
2151                                       ArrayRef<OMPClause *> Clauses) {
2152   bool ErrorFound = false;
2153   CaptureRegionUnwinderRAII CaptureRegionUnwinder(
2154       *this, ErrorFound, DSAStack->getCurrentDirective());
2155   if (!S.isUsable()) {
2156     ErrorFound = true;
2157     return StmtError();
2158   }
2159 
2160   OMPOrderedClause *OC = nullptr;
2161   OMPScheduleClause *SC = nullptr;
2162   SmallVector<OMPLinearClause *, 4> LCs;
2163   SmallVector<OMPClauseWithPreInit *, 8> PICs;
2164   // This is required for proper codegen.
2165   for (auto *Clause : Clauses) {
2166     if (isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) &&
2167         Clause->getClauseKind() == OMPC_in_reduction) {
2168       // Capture taskgroup task_reduction descriptors inside the tasking regions
2169       // with the corresponding in_reduction items.
2170       auto *IRC = cast<OMPInReductionClause>(Clause);
2171       for (auto *E : IRC->taskgroup_descriptors())
2172         if (E)
2173           MarkDeclarationsReferencedInExpr(E);
2174     }
2175     if (isOpenMPPrivate(Clause->getClauseKind()) ||
2176         Clause->getClauseKind() == OMPC_copyprivate ||
2177         (getLangOpts().OpenMPUseTLS &&
2178          getASTContext().getTargetInfo().isTLSSupported() &&
2179          Clause->getClauseKind() == OMPC_copyin)) {
2180       DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
2181       // Mark all variables in private list clauses as used in inner region.
2182       for (auto *VarRef : Clause->children()) {
2183         if (auto *E = cast_or_null<Expr>(VarRef)) {
2184           MarkDeclarationsReferencedInExpr(E);
2185         }
2186       }
2187       DSAStack->setForceVarCapturing(/*V=*/false);
2188     } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) {
2189       if (auto *C = OMPClauseWithPreInit::get(Clause))
2190         PICs.push_back(C);
2191       if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
2192         if (auto *E = C->getPostUpdateExpr())
2193           MarkDeclarationsReferencedInExpr(E);
2194       }
2195     }
2196     if (Clause->getClauseKind() == OMPC_schedule)
2197       SC = cast<OMPScheduleClause>(Clause);
2198     else if (Clause->getClauseKind() == OMPC_ordered)
2199       OC = cast<OMPOrderedClause>(Clause);
2200     else if (Clause->getClauseKind() == OMPC_linear)
2201       LCs.push_back(cast<OMPLinearClause>(Clause));
2202   }
2203   // OpenMP, 2.7.1 Loop Construct, Restrictions
2204   // The nonmonotonic modifier cannot be specified if an ordered clause is
2205   // specified.
2206   if (SC &&
2207       (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
2208        SC->getSecondScheduleModifier() ==
2209            OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
2210       OC) {
2211     Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
2212              ? SC->getFirstScheduleModifierLoc()
2213              : SC->getSecondScheduleModifierLoc(),
2214          diag::err_omp_schedule_nonmonotonic_ordered)
2215         << SourceRange(OC->getLocStart(), OC->getLocEnd());
2216     ErrorFound = true;
2217   }
2218   if (!LCs.empty() && OC && OC->getNumForLoops()) {
2219     for (auto *C : LCs) {
2220       Diag(C->getLocStart(), diag::err_omp_linear_ordered)
2221           << SourceRange(OC->getLocStart(), OC->getLocEnd());
2222     }
2223     ErrorFound = true;
2224   }
2225   if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
2226       isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
2227       OC->getNumForLoops()) {
2228     Diag(OC->getLocStart(), diag::err_omp_ordered_simd)
2229         << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
2230     ErrorFound = true;
2231   }
2232   if (ErrorFound) {
2233     return StmtError();
2234   }
2235   StmtResult SR = S;
2236   SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
2237   getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
2238   for (auto ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
2239     // Mark all variables in private list clauses as used in inner region.
2240     // Required for proper codegen of combined directives.
2241     // TODO: add processing for other clauses.
2242     if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) {
2243       for (auto *C : PICs) {
2244         OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
2245         // Find the particular capture region for the clause if the
2246         // directive is a combined one with multiple capture regions.
2247         // If the directive is not a combined one, the capture region
2248         // associated with the clause is OMPD_unknown and is generated
2249         // only once.
2250         if (CaptureRegion == ThisCaptureRegion ||
2251             CaptureRegion == OMPD_unknown) {
2252           if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
2253             for (auto *D : DS->decls())
2254               MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
2255           }
2256         }
2257       }
2258     }
2259     SR = ActOnCapturedRegionEnd(SR.get());
2260   }
2261   return SR;
2262 }
2263 
2264 static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
2265                               OpenMPDirectiveKind CancelRegion,
2266                               SourceLocation StartLoc) {
2267   // CancelRegion is only needed for cancel and cancellation_point.
2268   if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
2269     return false;
2270 
2271   if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
2272       CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
2273     return false;
2274 
2275   SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
2276       << getOpenMPDirectiveName(CancelRegion);
2277   return true;
2278 }
2279 
2280 static bool checkNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack,
2281                                   OpenMPDirectiveKind CurrentRegion,
2282                                   const DeclarationNameInfo &CurrentName,
2283                                   OpenMPDirectiveKind CancelRegion,
2284                                   SourceLocation StartLoc) {
2285   if (Stack->getCurScope()) {
2286     auto ParentRegion = Stack->getParentDirective();
2287     auto OffendingRegion = ParentRegion;
2288     bool NestingProhibited = false;
2289     bool CloseNesting = true;
2290     bool OrphanSeen = false;
2291     enum {
2292       NoRecommend,
2293       ShouldBeInParallelRegion,
2294       ShouldBeInOrderedRegion,
2295       ShouldBeInTargetRegion,
2296       ShouldBeInTeamsRegion
2297     } Recommend = NoRecommend;
2298     if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
2299       // OpenMP [2.16, Nesting of Regions]
2300       // OpenMP constructs may not be nested inside a simd region.
2301       // OpenMP [2.8.1,simd Construct, Restrictions]
2302       // An ordered construct with the simd clause is the only OpenMP
2303       // construct that can appear in the simd region.
2304       // Allowing a SIMD construct nested in another SIMD construct is an
2305       // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
2306       // message.
2307       SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
2308                                  ? diag::err_omp_prohibited_region_simd
2309                                  : diag::warn_omp_nesting_simd);
2310       return CurrentRegion != OMPD_simd;
2311     }
2312     if (ParentRegion == OMPD_atomic) {
2313       // OpenMP [2.16, Nesting of Regions]
2314       // OpenMP constructs may not be nested inside an atomic region.
2315       SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
2316       return true;
2317     }
2318     if (CurrentRegion == OMPD_section) {
2319       // OpenMP [2.7.2, sections Construct, Restrictions]
2320       // Orphaned section directives are prohibited. That is, the section
2321       // directives must appear within the sections construct and must not be
2322       // encountered elsewhere in the sections region.
2323       if (ParentRegion != OMPD_sections &&
2324           ParentRegion != OMPD_parallel_sections) {
2325         SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
2326             << (ParentRegion != OMPD_unknown)
2327             << getOpenMPDirectiveName(ParentRegion);
2328         return true;
2329       }
2330       return false;
2331     }
2332     // Allow some constructs (except teams) to be orphaned (they could be
2333     // used in functions, called from OpenMP regions with the required
2334     // preconditions).
2335     if (ParentRegion == OMPD_unknown &&
2336         !isOpenMPNestingTeamsDirective(CurrentRegion))
2337       return false;
2338     if (CurrentRegion == OMPD_cancellation_point ||
2339         CurrentRegion == OMPD_cancel) {
2340       // OpenMP [2.16, Nesting of Regions]
2341       // A cancellation point construct for which construct-type-clause is
2342       // taskgroup must be nested inside a task construct. A cancellation
2343       // point construct for which construct-type-clause is not taskgroup must
2344       // be closely nested inside an OpenMP construct that matches the type
2345       // specified in construct-type-clause.
2346       // A cancel construct for which construct-type-clause is taskgroup must be
2347       // nested inside a task construct. A cancel construct for which
2348       // construct-type-clause is not taskgroup must be closely nested inside an
2349       // OpenMP construct that matches the type specified in
2350       // construct-type-clause.
2351       NestingProhibited =
2352           !((CancelRegion == OMPD_parallel &&
2353              (ParentRegion == OMPD_parallel ||
2354               ParentRegion == OMPD_target_parallel)) ||
2355             (CancelRegion == OMPD_for &&
2356              (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
2357               ParentRegion == OMPD_target_parallel_for)) ||
2358             (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
2359             (CancelRegion == OMPD_sections &&
2360              (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
2361               ParentRegion == OMPD_parallel_sections)));
2362     } else if (CurrentRegion == OMPD_master) {
2363       // OpenMP [2.16, Nesting of Regions]
2364       // A master region may not be closely nested inside a worksharing,
2365       // atomic, or explicit task region.
2366       NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2367                           isOpenMPTaskingDirective(ParentRegion);
2368     } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
2369       // OpenMP [2.16, Nesting of Regions]
2370       // A critical region may not be nested (closely or otherwise) inside a
2371       // critical region with the same name. Note that this restriction is not
2372       // sufficient to prevent deadlock.
2373       SourceLocation PreviousCriticalLoc;
2374       bool DeadLock = Stack->hasDirective(
2375           [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
2376                                               const DeclarationNameInfo &DNI,
2377                                               SourceLocation Loc) -> bool {
2378             if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
2379               PreviousCriticalLoc = Loc;
2380               return true;
2381             } else
2382               return false;
2383           },
2384           false /* skip top directive */);
2385       if (DeadLock) {
2386         SemaRef.Diag(StartLoc,
2387                      diag::err_omp_prohibited_region_critical_same_name)
2388             << CurrentName.getName();
2389         if (PreviousCriticalLoc.isValid())
2390           SemaRef.Diag(PreviousCriticalLoc,
2391                        diag::note_omp_previous_critical_region);
2392         return true;
2393       }
2394     } else if (CurrentRegion == OMPD_barrier) {
2395       // OpenMP [2.16, Nesting of Regions]
2396       // A barrier region may not be closely nested inside a worksharing,
2397       // explicit task, critical, ordered, atomic, or master region.
2398       NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2399                           isOpenMPTaskingDirective(ParentRegion) ||
2400                           ParentRegion == OMPD_master ||
2401                           ParentRegion == OMPD_critical ||
2402                           ParentRegion == OMPD_ordered;
2403     } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
2404                !isOpenMPParallelDirective(CurrentRegion) &&
2405                !isOpenMPTeamsDirective(CurrentRegion)) {
2406       // OpenMP [2.16, Nesting of Regions]
2407       // A worksharing region may not be closely nested inside a worksharing,
2408       // explicit task, critical, ordered, atomic, or master region.
2409       NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2410                           isOpenMPTaskingDirective(ParentRegion) ||
2411                           ParentRegion == OMPD_master ||
2412                           ParentRegion == OMPD_critical ||
2413                           ParentRegion == OMPD_ordered;
2414       Recommend = ShouldBeInParallelRegion;
2415     } else if (CurrentRegion == OMPD_ordered) {
2416       // OpenMP [2.16, Nesting of Regions]
2417       // An ordered region may not be closely nested inside a critical,
2418       // atomic, or explicit task region.
2419       // An ordered region must be closely nested inside a loop region (or
2420       // parallel loop region) with an ordered clause.
2421       // OpenMP [2.8.1,simd Construct, Restrictions]
2422       // An ordered construct with the simd clause is the only OpenMP construct
2423       // that can appear in the simd region.
2424       NestingProhibited = ParentRegion == OMPD_critical ||
2425                           isOpenMPTaskingDirective(ParentRegion) ||
2426                           !(isOpenMPSimdDirective(ParentRegion) ||
2427                             Stack->isParentOrderedRegion());
2428       Recommend = ShouldBeInOrderedRegion;
2429     } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
2430       // OpenMP [2.16, Nesting of Regions]
2431       // If specified, a teams construct must be contained within a target
2432       // construct.
2433       NestingProhibited = ParentRegion != OMPD_target;
2434       OrphanSeen = ParentRegion == OMPD_unknown;
2435       Recommend = ShouldBeInTargetRegion;
2436       Stack->setParentTeamsRegionLoc(Stack->getConstructLoc());
2437     }
2438     if (!NestingProhibited &&
2439         !isOpenMPTargetExecutionDirective(CurrentRegion) &&
2440         !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
2441         (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
2442       // OpenMP [2.16, Nesting of Regions]
2443       // distribute, parallel, parallel sections, parallel workshare, and the
2444       // parallel loop and parallel loop SIMD constructs are the only OpenMP
2445       // constructs that can be closely nested in the teams region.
2446       NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
2447                           !isOpenMPDistributeDirective(CurrentRegion);
2448       Recommend = ShouldBeInParallelRegion;
2449     }
2450     if (!NestingProhibited &&
2451         isOpenMPNestingDistributeDirective(CurrentRegion)) {
2452       // OpenMP 4.5 [2.17 Nesting of Regions]
2453       // The region associated with the distribute construct must be strictly
2454       // nested inside a teams region
2455       NestingProhibited =
2456           (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
2457       Recommend = ShouldBeInTeamsRegion;
2458     }
2459     if (!NestingProhibited &&
2460         (isOpenMPTargetExecutionDirective(CurrentRegion) ||
2461          isOpenMPTargetDataManagementDirective(CurrentRegion))) {
2462       // OpenMP 4.5 [2.17 Nesting of Regions]
2463       // If a target, target update, target data, target enter data, or
2464       // target exit data construct is encountered during execution of a
2465       // target region, the behavior is unspecified.
2466       NestingProhibited = Stack->hasDirective(
2467           [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
2468                              SourceLocation) -> bool {
2469             if (isOpenMPTargetExecutionDirective(K)) {
2470               OffendingRegion = K;
2471               return true;
2472             } else
2473               return false;
2474           },
2475           false /* don't skip top directive */);
2476       CloseNesting = false;
2477     }
2478     if (NestingProhibited) {
2479       if (OrphanSeen) {
2480         SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
2481             << getOpenMPDirectiveName(CurrentRegion) << Recommend;
2482       } else {
2483         SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
2484             << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
2485             << Recommend << getOpenMPDirectiveName(CurrentRegion);
2486       }
2487       return true;
2488     }
2489   }
2490   return false;
2491 }
2492 
2493 static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
2494                            ArrayRef<OMPClause *> Clauses,
2495                            ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
2496   bool ErrorFound = false;
2497   unsigned NamedModifiersNumber = 0;
2498   SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
2499       OMPD_unknown + 1);
2500   SmallVector<SourceLocation, 4> NameModifierLoc;
2501   for (const auto *C : Clauses) {
2502     if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
2503       // At most one if clause without a directive-name-modifier can appear on
2504       // the directive.
2505       OpenMPDirectiveKind CurNM = IC->getNameModifier();
2506       if (FoundNameModifiers[CurNM]) {
2507         S.Diag(C->getLocStart(), diag::err_omp_more_one_clause)
2508             << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
2509             << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
2510         ErrorFound = true;
2511       } else if (CurNM != OMPD_unknown) {
2512         NameModifierLoc.push_back(IC->getNameModifierLoc());
2513         ++NamedModifiersNumber;
2514       }
2515       FoundNameModifiers[CurNM] = IC;
2516       if (CurNM == OMPD_unknown)
2517         continue;
2518       // Check if the specified name modifier is allowed for the current
2519       // directive.
2520       // At most one if clause with the particular directive-name-modifier can
2521       // appear on the directive.
2522       bool MatchFound = false;
2523       for (auto NM : AllowedNameModifiers) {
2524         if (CurNM == NM) {
2525           MatchFound = true;
2526           break;
2527         }
2528       }
2529       if (!MatchFound) {
2530         S.Diag(IC->getNameModifierLoc(),
2531                diag::err_omp_wrong_if_directive_name_modifier)
2532             << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
2533         ErrorFound = true;
2534       }
2535     }
2536   }
2537   // If any if clause on the directive includes a directive-name-modifier then
2538   // all if clauses on the directive must include a directive-name-modifier.
2539   if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
2540     if (NamedModifiersNumber == AllowedNameModifiers.size()) {
2541       S.Diag(FoundNameModifiers[OMPD_unknown]->getLocStart(),
2542              diag::err_omp_no_more_if_clause);
2543     } else {
2544       std::string Values;
2545       std::string Sep(", ");
2546       unsigned AllowedCnt = 0;
2547       unsigned TotalAllowedNum =
2548           AllowedNameModifiers.size() - NamedModifiersNumber;
2549       for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
2550            ++Cnt) {
2551         OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
2552         if (!FoundNameModifiers[NM]) {
2553           Values += "'";
2554           Values += getOpenMPDirectiveName(NM);
2555           Values += "'";
2556           if (AllowedCnt + 2 == TotalAllowedNum)
2557             Values += " or ";
2558           else if (AllowedCnt + 1 != TotalAllowedNum)
2559             Values += Sep;
2560           ++AllowedCnt;
2561         }
2562       }
2563       S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getLocStart(),
2564              diag::err_omp_unnamed_if_clause)
2565           << (TotalAllowedNum > 1) << Values;
2566     }
2567     for (auto Loc : NameModifierLoc) {
2568       S.Diag(Loc, diag::note_omp_previous_named_if_clause);
2569     }
2570     ErrorFound = true;
2571   }
2572   return ErrorFound;
2573 }
2574 
2575 StmtResult Sema::ActOnOpenMPExecutableDirective(
2576     OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
2577     OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
2578     Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
2579   StmtResult Res = StmtError();
2580   // First check CancelRegion which is then used in checkNestingOfRegions.
2581   if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
2582       checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
2583                             StartLoc))
2584     return StmtError();
2585 
2586   llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
2587   llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
2588   bool ErrorFound = false;
2589   ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
2590   if (AStmt) {
2591     assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
2592 
2593     // Check default data sharing attributes for referenced variables.
2594     DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
2595     int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
2596     Stmt *S = AStmt;
2597     while (--ThisCaptureLevel >= 0)
2598       S = cast<CapturedStmt>(S)->getCapturedStmt();
2599     DSAChecker.Visit(S);
2600     if (DSAChecker.isErrorFound())
2601       return StmtError();
2602     // Generate list of implicitly defined firstprivate variables.
2603     VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
2604 
2605     SmallVector<Expr *, 4> ImplicitFirstprivates(
2606         DSAChecker.getImplicitFirstprivate().begin(),
2607         DSAChecker.getImplicitFirstprivate().end());
2608     // Mark taskgroup task_reduction descriptors as implicitly firstprivate.
2609     for (auto *C : Clauses) {
2610       if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) {
2611         for (auto *E : IRC->taskgroup_descriptors())
2612           if (E)
2613             ImplicitFirstprivates.emplace_back(E);
2614       }
2615     }
2616     if (!ImplicitFirstprivates.empty()) {
2617       if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
2618               ImplicitFirstprivates, SourceLocation(), SourceLocation(),
2619               SourceLocation())) {
2620         ClausesWithImplicit.push_back(Implicit);
2621         ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
2622                      ImplicitFirstprivates.size();
2623       } else
2624         ErrorFound = true;
2625     }
2626   }
2627 
2628   llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
2629   switch (Kind) {
2630   case OMPD_parallel:
2631     Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
2632                                        EndLoc);
2633     AllowedNameModifiers.push_back(OMPD_parallel);
2634     break;
2635   case OMPD_simd:
2636     Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2637                                    VarsWithInheritedDSA);
2638     break;
2639   case OMPD_for:
2640     Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2641                                   VarsWithInheritedDSA);
2642     break;
2643   case OMPD_for_simd:
2644     Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2645                                       EndLoc, VarsWithInheritedDSA);
2646     break;
2647   case OMPD_sections:
2648     Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
2649                                        EndLoc);
2650     break;
2651   case OMPD_section:
2652     assert(ClausesWithImplicit.empty() &&
2653            "No clauses are allowed for 'omp section' directive");
2654     Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
2655     break;
2656   case OMPD_single:
2657     Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
2658                                      EndLoc);
2659     break;
2660   case OMPD_master:
2661     assert(ClausesWithImplicit.empty() &&
2662            "No clauses are allowed for 'omp master' directive");
2663     Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
2664     break;
2665   case OMPD_critical:
2666     Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
2667                                        StartLoc, EndLoc);
2668     break;
2669   case OMPD_parallel_for:
2670     Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
2671                                           EndLoc, VarsWithInheritedDSA);
2672     AllowedNameModifiers.push_back(OMPD_parallel);
2673     break;
2674   case OMPD_parallel_for_simd:
2675     Res = ActOnOpenMPParallelForSimdDirective(
2676         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2677     AllowedNameModifiers.push_back(OMPD_parallel);
2678     break;
2679   case OMPD_parallel_sections:
2680     Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
2681                                                StartLoc, EndLoc);
2682     AllowedNameModifiers.push_back(OMPD_parallel);
2683     break;
2684   case OMPD_task:
2685     Res =
2686         ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
2687     AllowedNameModifiers.push_back(OMPD_task);
2688     break;
2689   case OMPD_taskyield:
2690     assert(ClausesWithImplicit.empty() &&
2691            "No clauses are allowed for 'omp taskyield' directive");
2692     assert(AStmt == nullptr &&
2693            "No associated statement allowed for 'omp taskyield' directive");
2694     Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
2695     break;
2696   case OMPD_barrier:
2697     assert(ClausesWithImplicit.empty() &&
2698            "No clauses are allowed for 'omp barrier' directive");
2699     assert(AStmt == nullptr &&
2700            "No associated statement allowed for 'omp barrier' directive");
2701     Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
2702     break;
2703   case OMPD_taskwait:
2704     assert(ClausesWithImplicit.empty() &&
2705            "No clauses are allowed for 'omp taskwait' directive");
2706     assert(AStmt == nullptr &&
2707            "No associated statement allowed for 'omp taskwait' directive");
2708     Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
2709     break;
2710   case OMPD_taskgroup:
2711     Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc,
2712                                         EndLoc);
2713     break;
2714   case OMPD_flush:
2715     assert(AStmt == nullptr &&
2716            "No associated statement allowed for 'omp flush' directive");
2717     Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
2718     break;
2719   case OMPD_ordered:
2720     Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
2721                                       EndLoc);
2722     break;
2723   case OMPD_atomic:
2724     Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
2725                                      EndLoc);
2726     break;
2727   case OMPD_teams:
2728     Res =
2729         ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
2730     break;
2731   case OMPD_target:
2732     Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
2733                                      EndLoc);
2734     AllowedNameModifiers.push_back(OMPD_target);
2735     break;
2736   case OMPD_target_parallel:
2737     Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
2738                                              StartLoc, EndLoc);
2739     AllowedNameModifiers.push_back(OMPD_target);
2740     AllowedNameModifiers.push_back(OMPD_parallel);
2741     break;
2742   case OMPD_target_parallel_for:
2743     Res = ActOnOpenMPTargetParallelForDirective(
2744         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2745     AllowedNameModifiers.push_back(OMPD_target);
2746     AllowedNameModifiers.push_back(OMPD_parallel);
2747     break;
2748   case OMPD_cancellation_point:
2749     assert(ClausesWithImplicit.empty() &&
2750            "No clauses are allowed for 'omp cancellation point' directive");
2751     assert(AStmt == nullptr && "No associated statement allowed for 'omp "
2752                                "cancellation point' directive");
2753     Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
2754     break;
2755   case OMPD_cancel:
2756     assert(AStmt == nullptr &&
2757            "No associated statement allowed for 'omp cancel' directive");
2758     Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
2759                                      CancelRegion);
2760     AllowedNameModifiers.push_back(OMPD_cancel);
2761     break;
2762   case OMPD_target_data:
2763     Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
2764                                          EndLoc);
2765     AllowedNameModifiers.push_back(OMPD_target_data);
2766     break;
2767   case OMPD_target_enter_data:
2768     Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
2769                                               EndLoc);
2770     AllowedNameModifiers.push_back(OMPD_target_enter_data);
2771     break;
2772   case OMPD_target_exit_data:
2773     Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
2774                                              EndLoc);
2775     AllowedNameModifiers.push_back(OMPD_target_exit_data);
2776     break;
2777   case OMPD_taskloop:
2778     Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
2779                                        EndLoc, VarsWithInheritedDSA);
2780     AllowedNameModifiers.push_back(OMPD_taskloop);
2781     break;
2782   case OMPD_taskloop_simd:
2783     Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2784                                            EndLoc, VarsWithInheritedDSA);
2785     AllowedNameModifiers.push_back(OMPD_taskloop);
2786     break;
2787   case OMPD_distribute:
2788     Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
2789                                          EndLoc, VarsWithInheritedDSA);
2790     break;
2791   case OMPD_target_update:
2792     assert(!AStmt && "Statement is not allowed for target update");
2793     Res =
2794         ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc, EndLoc);
2795     AllowedNameModifiers.push_back(OMPD_target_update);
2796     break;
2797   case OMPD_distribute_parallel_for:
2798     Res = ActOnOpenMPDistributeParallelForDirective(
2799         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2800     AllowedNameModifiers.push_back(OMPD_parallel);
2801     break;
2802   case OMPD_distribute_parallel_for_simd:
2803     Res = ActOnOpenMPDistributeParallelForSimdDirective(
2804         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2805     AllowedNameModifiers.push_back(OMPD_parallel);
2806     break;
2807   case OMPD_distribute_simd:
2808     Res = ActOnOpenMPDistributeSimdDirective(
2809         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2810     break;
2811   case OMPD_target_parallel_for_simd:
2812     Res = ActOnOpenMPTargetParallelForSimdDirective(
2813         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2814     AllowedNameModifiers.push_back(OMPD_target);
2815     AllowedNameModifiers.push_back(OMPD_parallel);
2816     break;
2817   case OMPD_target_simd:
2818     Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2819                                          EndLoc, VarsWithInheritedDSA);
2820     AllowedNameModifiers.push_back(OMPD_target);
2821     break;
2822   case OMPD_teams_distribute:
2823     Res = ActOnOpenMPTeamsDistributeDirective(
2824         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2825     break;
2826   case OMPD_teams_distribute_simd:
2827     Res = ActOnOpenMPTeamsDistributeSimdDirective(
2828         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2829     break;
2830   case OMPD_teams_distribute_parallel_for_simd:
2831     Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
2832         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2833     AllowedNameModifiers.push_back(OMPD_parallel);
2834     break;
2835   case OMPD_teams_distribute_parallel_for:
2836     Res = ActOnOpenMPTeamsDistributeParallelForDirective(
2837         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2838     AllowedNameModifiers.push_back(OMPD_parallel);
2839     break;
2840   case OMPD_target_teams:
2841     Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
2842                                           EndLoc);
2843     AllowedNameModifiers.push_back(OMPD_target);
2844     break;
2845   case OMPD_target_teams_distribute:
2846     Res = ActOnOpenMPTargetTeamsDistributeDirective(
2847         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2848     AllowedNameModifiers.push_back(OMPD_target);
2849     break;
2850   case OMPD_target_teams_distribute_parallel_for:
2851     Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
2852         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2853     AllowedNameModifiers.push_back(OMPD_target);
2854     AllowedNameModifiers.push_back(OMPD_parallel);
2855     break;
2856   case OMPD_target_teams_distribute_parallel_for_simd:
2857     Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
2858         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2859     AllowedNameModifiers.push_back(OMPD_target);
2860     AllowedNameModifiers.push_back(OMPD_parallel);
2861     break;
2862   case OMPD_target_teams_distribute_simd:
2863     Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
2864         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2865     AllowedNameModifiers.push_back(OMPD_target);
2866     break;
2867   case OMPD_declare_target:
2868   case OMPD_end_declare_target:
2869   case OMPD_threadprivate:
2870   case OMPD_declare_reduction:
2871   case OMPD_declare_simd:
2872     llvm_unreachable("OpenMP Directive is not allowed");
2873   case OMPD_unknown:
2874     llvm_unreachable("Unknown OpenMP directive");
2875   }
2876 
2877   for (auto P : VarsWithInheritedDSA) {
2878     Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
2879         << P.first << P.second->getSourceRange();
2880   }
2881   ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound;
2882 
2883   if (!AllowedNameModifiers.empty())
2884     ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
2885                  ErrorFound;
2886 
2887   if (ErrorFound)
2888     return StmtError();
2889   return Res;
2890 }
2891 
2892 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
2893     DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
2894     ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
2895     ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
2896     ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
2897   assert(Aligneds.size() == Alignments.size());
2898   assert(Linears.size() == LinModifiers.size());
2899   assert(Linears.size() == Steps.size());
2900   if (!DG || DG.get().isNull())
2901     return DeclGroupPtrTy();
2902 
2903   if (!DG.get().isSingleDecl()) {
2904     Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd);
2905     return DG;
2906   }
2907   auto *ADecl = DG.get().getSingleDecl();
2908   if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
2909     ADecl = FTD->getTemplatedDecl();
2910 
2911   auto *FD = dyn_cast<FunctionDecl>(ADecl);
2912   if (!FD) {
2913     Diag(ADecl->getLocation(), diag::err_omp_function_expected);
2914     return DeclGroupPtrTy();
2915   }
2916 
2917   // OpenMP [2.8.2, declare simd construct, Description]
2918   // The parameter of the simdlen clause must be a constant positive integer
2919   // expression.
2920   ExprResult SL;
2921   if (Simdlen)
2922     SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
2923   // OpenMP [2.8.2, declare simd construct, Description]
2924   // The special this pointer can be used as if was one of the arguments to the
2925   // function in any of the linear, aligned, or uniform clauses.
2926   // The uniform clause declares one or more arguments to have an invariant
2927   // value for all concurrent invocations of the function in the execution of a
2928   // single SIMD loop.
2929   llvm::DenseMap<Decl *, Expr *> UniformedArgs;
2930   Expr *UniformedLinearThis = nullptr;
2931   for (auto *E : Uniforms) {
2932     E = E->IgnoreParenImpCasts();
2933     if (auto *DRE = dyn_cast<DeclRefExpr>(E))
2934       if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
2935         if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
2936             FD->getParamDecl(PVD->getFunctionScopeIndex())
2937                     ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
2938           UniformedArgs.insert(std::make_pair(PVD->getCanonicalDecl(), E));
2939           continue;
2940         }
2941     if (isa<CXXThisExpr>(E)) {
2942       UniformedLinearThis = E;
2943       continue;
2944     }
2945     Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
2946         << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
2947   }
2948   // OpenMP [2.8.2, declare simd construct, Description]
2949   // The aligned clause declares that the object to which each list item points
2950   // is aligned to the number of bytes expressed in the optional parameter of
2951   // the aligned clause.
2952   // The special this pointer can be used as if was one of the arguments to the
2953   // function in any of the linear, aligned, or uniform clauses.
2954   // The type of list items appearing in the aligned clause must be array,
2955   // pointer, reference to array, or reference to pointer.
2956   llvm::DenseMap<Decl *, Expr *> AlignedArgs;
2957   Expr *AlignedThis = nullptr;
2958   for (auto *E : Aligneds) {
2959     E = E->IgnoreParenImpCasts();
2960     if (auto *DRE = dyn_cast<DeclRefExpr>(E))
2961       if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2962         auto *CanonPVD = PVD->getCanonicalDecl();
2963         if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
2964             FD->getParamDecl(PVD->getFunctionScopeIndex())
2965                     ->getCanonicalDecl() == CanonPVD) {
2966           // OpenMP  [2.8.1, simd construct, Restrictions]
2967           // A list-item cannot appear in more than one aligned clause.
2968           if (AlignedArgs.count(CanonPVD) > 0) {
2969             Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
2970                 << 1 << E->getSourceRange();
2971             Diag(AlignedArgs[CanonPVD]->getExprLoc(),
2972                  diag::note_omp_explicit_dsa)
2973                 << getOpenMPClauseName(OMPC_aligned);
2974             continue;
2975           }
2976           AlignedArgs[CanonPVD] = E;
2977           QualType QTy = PVD->getType()
2978                              .getNonReferenceType()
2979                              .getUnqualifiedType()
2980                              .getCanonicalType();
2981           const Type *Ty = QTy.getTypePtrOrNull();
2982           if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
2983             Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
2984                 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
2985             Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
2986           }
2987           continue;
2988         }
2989       }
2990     if (isa<CXXThisExpr>(E)) {
2991       if (AlignedThis) {
2992         Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
2993             << 2 << E->getSourceRange();
2994         Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
2995             << getOpenMPClauseName(OMPC_aligned);
2996       }
2997       AlignedThis = E;
2998       continue;
2999     }
3000     Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3001         << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
3002   }
3003   // The optional parameter of the aligned clause, alignment, must be a constant
3004   // positive integer expression. If no optional parameter is specified,
3005   // implementation-defined default alignments for SIMD instructions on the
3006   // target platforms are assumed.
3007   SmallVector<Expr *, 4> NewAligns;
3008   for (auto *E : Alignments) {
3009     ExprResult Align;
3010     if (E)
3011       Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
3012     NewAligns.push_back(Align.get());
3013   }
3014   // OpenMP [2.8.2, declare simd construct, Description]
3015   // The linear clause declares one or more list items to be private to a SIMD
3016   // lane and to have a linear relationship with respect to the iteration space
3017   // of a loop.
3018   // The special this pointer can be used as if was one of the arguments to the
3019   // function in any of the linear, aligned, or uniform clauses.
3020   // When a linear-step expression is specified in a linear clause it must be
3021   // either a constant integer expression or an integer-typed parameter that is
3022   // specified in a uniform clause on the directive.
3023   llvm::DenseMap<Decl *, Expr *> LinearArgs;
3024   const bool IsUniformedThis = UniformedLinearThis != nullptr;
3025   auto MI = LinModifiers.begin();
3026   for (auto *E : Linears) {
3027     auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
3028     ++MI;
3029     E = E->IgnoreParenImpCasts();
3030     if (auto *DRE = dyn_cast<DeclRefExpr>(E))
3031       if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3032         auto *CanonPVD = PVD->getCanonicalDecl();
3033         if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
3034             FD->getParamDecl(PVD->getFunctionScopeIndex())
3035                     ->getCanonicalDecl() == CanonPVD) {
3036           // OpenMP  [2.15.3.7, linear Clause, Restrictions]
3037           // A list-item cannot appear in more than one linear clause.
3038           if (LinearArgs.count(CanonPVD) > 0) {
3039             Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3040                 << getOpenMPClauseName(OMPC_linear)
3041                 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
3042             Diag(LinearArgs[CanonPVD]->getExprLoc(),
3043                  diag::note_omp_explicit_dsa)
3044                 << getOpenMPClauseName(OMPC_linear);
3045             continue;
3046           }
3047           // Each argument can appear in at most one uniform or linear clause.
3048           if (UniformedArgs.count(CanonPVD) > 0) {
3049             Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3050                 << getOpenMPClauseName(OMPC_linear)
3051                 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
3052             Diag(UniformedArgs[CanonPVD]->getExprLoc(),
3053                  diag::note_omp_explicit_dsa)
3054                 << getOpenMPClauseName(OMPC_uniform);
3055             continue;
3056           }
3057           LinearArgs[CanonPVD] = E;
3058           if (E->isValueDependent() || E->isTypeDependent() ||
3059               E->isInstantiationDependent() ||
3060               E->containsUnexpandedParameterPack())
3061             continue;
3062           (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
3063                                       PVD->getOriginalType());
3064           continue;
3065         }
3066       }
3067     if (isa<CXXThisExpr>(E)) {
3068       if (UniformedLinearThis) {
3069         Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3070             << getOpenMPClauseName(OMPC_linear)
3071             << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
3072             << E->getSourceRange();
3073         Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
3074             << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
3075                                                    : OMPC_linear);
3076         continue;
3077       }
3078       UniformedLinearThis = E;
3079       if (E->isValueDependent() || E->isTypeDependent() ||
3080           E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
3081         continue;
3082       (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
3083                                   E->getType());
3084       continue;
3085     }
3086     Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3087         << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
3088   }
3089   Expr *Step = nullptr;
3090   Expr *NewStep = nullptr;
3091   SmallVector<Expr *, 4> NewSteps;
3092   for (auto *E : Steps) {
3093     // Skip the same step expression, it was checked already.
3094     if (Step == E || !E) {
3095       NewSteps.push_back(E ? NewStep : nullptr);
3096       continue;
3097     }
3098     Step = E;
3099     if (auto *DRE = dyn_cast<DeclRefExpr>(Step))
3100       if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3101         auto *CanonPVD = PVD->getCanonicalDecl();
3102         if (UniformedArgs.count(CanonPVD) == 0) {
3103           Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
3104               << Step->getSourceRange();
3105         } else if (E->isValueDependent() || E->isTypeDependent() ||
3106                    E->isInstantiationDependent() ||
3107                    E->containsUnexpandedParameterPack() ||
3108                    CanonPVD->getType()->hasIntegerRepresentation())
3109           NewSteps.push_back(Step);
3110         else {
3111           Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
3112               << Step->getSourceRange();
3113         }
3114         continue;
3115       }
3116     NewStep = Step;
3117     if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
3118         !Step->isInstantiationDependent() &&
3119         !Step->containsUnexpandedParameterPack()) {
3120       NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
3121                     .get();
3122       if (NewStep)
3123         NewStep = VerifyIntegerConstantExpression(NewStep).get();
3124     }
3125     NewSteps.push_back(NewStep);
3126   }
3127   auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
3128       Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
3129       Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
3130       const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
3131       const_cast<Expr **>(Linears.data()), Linears.size(),
3132       const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
3133       NewSteps.data(), NewSteps.size(), SR);
3134   ADecl->addAttr(NewAttr);
3135   return ConvertDeclToDeclGroup(ADecl);
3136 }
3137 
3138 StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
3139                                               Stmt *AStmt,
3140                                               SourceLocation StartLoc,
3141                                               SourceLocation EndLoc) {
3142   if (!AStmt)
3143     return StmtError();
3144 
3145   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
3146   // 1.2.2 OpenMP Language Terminology
3147   // Structured block - An executable statement with a single entry at the
3148   // top and a single exit at the bottom.
3149   // The point of exit cannot be a branch out of the structured block.
3150   // longjmp() and throw() must not violate the entry/exit criteria.
3151   CS->getCapturedDecl()->setNothrow();
3152 
3153   getCurFunction()->setHasBranchProtectedScope();
3154 
3155   return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
3156                                       DSAStack->isCancelRegion());
3157 }
3158 
3159 namespace {
3160 /// \brief Helper class for checking canonical form of the OpenMP loops and
3161 /// extracting iteration space of each loop in the loop nest, that will be used
3162 /// for IR generation.
3163 class OpenMPIterationSpaceChecker {
3164   /// \brief Reference to Sema.
3165   Sema &SemaRef;
3166   /// \brief A location for diagnostics (when there is no some better location).
3167   SourceLocation DefaultLoc;
3168   /// \brief A location for diagnostics (when increment is not compatible).
3169   SourceLocation ConditionLoc;
3170   /// \brief A source location for referring to loop init later.
3171   SourceRange InitSrcRange;
3172   /// \brief A source location for referring to condition later.
3173   SourceRange ConditionSrcRange;
3174   /// \brief A source location for referring to increment later.
3175   SourceRange IncrementSrcRange;
3176   /// \brief Loop variable.
3177   ValueDecl *LCDecl = nullptr;
3178   /// \brief Reference to loop variable.
3179   Expr *LCRef = nullptr;
3180   /// \brief Lower bound (initializer for the var).
3181   Expr *LB = nullptr;
3182   /// \brief Upper bound.
3183   Expr *UB = nullptr;
3184   /// \brief Loop step (increment).
3185   Expr *Step = nullptr;
3186   /// \brief This flag is true when condition is one of:
3187   ///   Var <  UB
3188   ///   Var <= UB
3189   ///   UB  >  Var
3190   ///   UB  >= Var
3191   bool TestIsLessOp = false;
3192   /// \brief This flag is true when condition is strict ( < or > ).
3193   bool TestIsStrictOp = false;
3194   /// \brief This flag is true when step is subtracted on each iteration.
3195   bool SubtractStep = false;
3196 
3197 public:
3198   OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
3199       : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {}
3200   /// \brief Check init-expr for canonical loop form and save loop counter
3201   /// variable - #Var and its initialization value - #LB.
3202   bool CheckInit(Stmt *S, bool EmitDiags = true);
3203   /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags
3204   /// for less/greater and for strict/non-strict comparison.
3205   bool CheckCond(Expr *S);
3206   /// \brief Check incr-expr for canonical loop form and return true if it
3207   /// does not conform, otherwise save loop step (#Step).
3208   bool CheckInc(Expr *S);
3209   /// \brief Return the loop counter variable.
3210   ValueDecl *GetLoopDecl() const { return LCDecl; }
3211   /// \brief Return the reference expression to loop counter variable.
3212   Expr *GetLoopDeclRefExpr() const { return LCRef; }
3213   /// \brief Source range of the loop init.
3214   SourceRange GetInitSrcRange() const { return InitSrcRange; }
3215   /// \brief Source range of the loop condition.
3216   SourceRange GetConditionSrcRange() const { return ConditionSrcRange; }
3217   /// \brief Source range of the loop increment.
3218   SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; }
3219   /// \brief True if the step should be subtracted.
3220   bool ShouldSubtractStep() const { return SubtractStep; }
3221   /// \brief Build the expression to calculate the number of iterations.
3222   Expr *
3223   BuildNumIterations(Scope *S, const bool LimitedType,
3224                      llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
3225   /// \brief Build the precondition expression for the loops.
3226   Expr *BuildPreCond(Scope *S, Expr *Cond,
3227                      llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
3228   /// \brief Build reference expression to the counter be used for codegen.
3229   DeclRefExpr *BuildCounterVar(llvm::MapVector<Expr *, DeclRefExpr *> &Captures,
3230                                DSAStackTy &DSA) const;
3231   /// \brief Build reference expression to the private counter be used for
3232   /// codegen.
3233   Expr *BuildPrivateCounterVar() const;
3234   /// \brief Build initialization of the counter be used for codegen.
3235   Expr *BuildCounterInit() const;
3236   /// \brief Build step of the counter be used for codegen.
3237   Expr *BuildCounterStep() const;
3238   /// \brief Return true if any expression is dependent.
3239   bool Dependent() const;
3240 
3241 private:
3242   /// \brief Check the right-hand side of an assignment in the increment
3243   /// expression.
3244   bool CheckIncRHS(Expr *RHS);
3245   /// \brief Helper to set loop counter variable and its initializer.
3246   bool SetLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB);
3247   /// \brief Helper to set upper bound.
3248   bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, SourceRange SR,
3249              SourceLocation SL);
3250   /// \brief Helper to set loop increment.
3251   bool SetStep(Expr *NewStep, bool Subtract);
3252 };
3253 
3254 bool OpenMPIterationSpaceChecker::Dependent() const {
3255   if (!LCDecl) {
3256     assert(!LB && !UB && !Step);
3257     return false;
3258   }
3259   return LCDecl->getType()->isDependentType() ||
3260          (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
3261          (Step && Step->isValueDependent());
3262 }
3263 
3264 bool OpenMPIterationSpaceChecker::SetLCDeclAndLB(ValueDecl *NewLCDecl,
3265                                                  Expr *NewLCRefExpr,
3266                                                  Expr *NewLB) {
3267   // State consistency checking to ensure correct usage.
3268   assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
3269          UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
3270   if (!NewLCDecl || !NewLB)
3271     return true;
3272   LCDecl = getCanonicalDecl(NewLCDecl);
3273   LCRef = NewLCRefExpr;
3274   if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
3275     if (const CXXConstructorDecl *Ctor = CE->getConstructor())
3276       if ((Ctor->isCopyOrMoveConstructor() ||
3277            Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
3278           CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
3279         NewLB = CE->getArg(0)->IgnoreParenImpCasts();
3280   LB = NewLB;
3281   return false;
3282 }
3283 
3284 bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp,
3285                                         SourceRange SR, SourceLocation SL) {
3286   // State consistency checking to ensure correct usage.
3287   assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
3288          Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
3289   if (!NewUB)
3290     return true;
3291   UB = NewUB;
3292   TestIsLessOp = LessOp;
3293   TestIsStrictOp = StrictOp;
3294   ConditionSrcRange = SR;
3295   ConditionLoc = SL;
3296   return false;
3297 }
3298 
3299 bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) {
3300   // State consistency checking to ensure correct usage.
3301   assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
3302   if (!NewStep)
3303     return true;
3304   if (!NewStep->isValueDependent()) {
3305     // Check that the step is integer expression.
3306     SourceLocation StepLoc = NewStep->getLocStart();
3307     ExprResult Val =
3308         SemaRef.PerformOpenMPImplicitIntegerConversion(StepLoc, NewStep);
3309     if (Val.isInvalid())
3310       return true;
3311     NewStep = Val.get();
3312 
3313     // OpenMP [2.6, Canonical Loop Form, Restrictions]
3314     //  If test-expr is of form var relational-op b and relational-op is < or
3315     //  <= then incr-expr must cause var to increase on each iteration of the
3316     //  loop. If test-expr is of form var relational-op b and relational-op is
3317     //  > or >= then incr-expr must cause var to decrease on each iteration of
3318     //  the loop.
3319     //  If test-expr is of form b relational-op var and relational-op is < or
3320     //  <= then incr-expr must cause var to decrease on each iteration of the
3321     //  loop. If test-expr is of form b relational-op var and relational-op is
3322     //  > or >= then incr-expr must cause var to increase on each iteration of
3323     //  the loop.
3324     llvm::APSInt Result;
3325     bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
3326     bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
3327     bool IsConstNeg =
3328         IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
3329     bool IsConstPos =
3330         IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
3331     bool IsConstZero = IsConstant && !Result.getBoolValue();
3332     if (UB && (IsConstZero ||
3333                (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
3334                              : (IsConstPos || (IsUnsigned && !Subtract))))) {
3335       SemaRef.Diag(NewStep->getExprLoc(),
3336                    diag::err_omp_loop_incr_not_compatible)
3337           << LCDecl << TestIsLessOp << NewStep->getSourceRange();
3338       SemaRef.Diag(ConditionLoc,
3339                    diag::note_omp_loop_cond_requres_compatible_incr)
3340           << TestIsLessOp << ConditionSrcRange;
3341       return true;
3342     }
3343     if (TestIsLessOp == Subtract) {
3344       NewStep =
3345           SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
3346               .get();
3347       Subtract = !Subtract;
3348     }
3349   }
3350 
3351   Step = NewStep;
3352   SubtractStep = Subtract;
3353   return false;
3354 }
3355 
3356 bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S, bool EmitDiags) {
3357   // Check init-expr for canonical loop form and save loop counter
3358   // variable - #Var and its initialization value - #LB.
3359   // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
3360   //   var = lb
3361   //   integer-type var = lb
3362   //   random-access-iterator-type var = lb
3363   //   pointer-type var = lb
3364   //
3365   if (!S) {
3366     if (EmitDiags) {
3367       SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
3368     }
3369     return true;
3370   }
3371   if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
3372     if (!ExprTemp->cleanupsHaveSideEffects())
3373       S = ExprTemp->getSubExpr();
3374 
3375   InitSrcRange = S->getSourceRange();
3376   if (Expr *E = dyn_cast<Expr>(S))
3377     S = E->IgnoreParens();
3378   if (auto *BO = dyn_cast<BinaryOperator>(S)) {
3379     if (BO->getOpcode() == BO_Assign) {
3380       auto *LHS = BO->getLHS()->IgnoreParens();
3381       if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
3382         if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
3383           if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3384             return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3385         return SetLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS());
3386       }
3387       if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
3388         if (ME->isArrow() &&
3389             isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3390           return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3391       }
3392     }
3393   } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
3394     if (DS->isSingleDecl()) {
3395       if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
3396         if (Var->hasInit() && !Var->getType()->isReferenceType()) {
3397           // Accept non-canonical init form here but emit ext. warning.
3398           if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
3399             SemaRef.Diag(S->getLocStart(),
3400                          diag::ext_omp_loop_not_canonical_init)
3401                 << S->getSourceRange();
3402           return SetLCDeclAndLB(Var, nullptr, Var->getInit());
3403         }
3404       }
3405     }
3406   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
3407     if (CE->getOperator() == OO_Equal) {
3408       auto *LHS = CE->getArg(0);
3409       if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
3410         if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
3411           if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3412             return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3413         return SetLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1));
3414       }
3415       if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
3416         if (ME->isArrow() &&
3417             isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3418           return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3419       }
3420     }
3421   }
3422 
3423   if (Dependent() || SemaRef.CurContext->isDependentContext())
3424     return false;
3425   if (EmitDiags) {
3426     SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init)
3427         << S->getSourceRange();
3428   }
3429   return true;
3430 }
3431 
3432 /// \brief Ignore parenthesizes, implicit casts, copy constructor and return the
3433 /// variable (which may be the loop variable) if possible.
3434 static const ValueDecl *GetInitLCDecl(Expr *E) {
3435   if (!E)
3436     return nullptr;
3437   E = getExprAsWritten(E);
3438   if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
3439     if (const CXXConstructorDecl *Ctor = CE->getConstructor())
3440       if ((Ctor->isCopyOrMoveConstructor() ||
3441            Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
3442           CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
3443         E = CE->getArg(0)->IgnoreParenImpCasts();
3444   if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
3445     if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
3446       return getCanonicalDecl(VD);
3447   }
3448   if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
3449     if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3450       return getCanonicalDecl(ME->getMemberDecl());
3451   return nullptr;
3452 }
3453 
3454 bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) {
3455   // Check test-expr for canonical form, save upper-bound UB, flags for
3456   // less/greater and for strict/non-strict comparison.
3457   // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3458   //   var relational-op b
3459   //   b relational-op var
3460   //
3461   if (!S) {
3462     SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl;
3463     return true;
3464   }
3465   S = getExprAsWritten(S);
3466   SourceLocation CondLoc = S->getLocStart();
3467   if (auto *BO = dyn_cast<BinaryOperator>(S)) {
3468     if (BO->isRelationalOp()) {
3469       if (GetInitLCDecl(BO->getLHS()) == LCDecl)
3470         return SetUB(BO->getRHS(),
3471                      (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
3472                      (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3473                      BO->getSourceRange(), BO->getOperatorLoc());
3474       if (GetInitLCDecl(BO->getRHS()) == LCDecl)
3475         return SetUB(BO->getLHS(),
3476                      (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
3477                      (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3478                      BO->getSourceRange(), BO->getOperatorLoc());
3479     }
3480   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
3481     if (CE->getNumArgs() == 2) {
3482       auto Op = CE->getOperator();
3483       switch (Op) {
3484       case OO_Greater:
3485       case OO_GreaterEqual:
3486       case OO_Less:
3487       case OO_LessEqual:
3488         if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
3489           return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
3490                        Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3491                        CE->getOperatorLoc());
3492         if (GetInitLCDecl(CE->getArg(1)) == LCDecl)
3493           return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
3494                        Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3495                        CE->getOperatorLoc());
3496         break;
3497       default:
3498         break;
3499       }
3500     }
3501   }
3502   if (Dependent() || SemaRef.CurContext->isDependentContext())
3503     return false;
3504   SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
3505       << S->getSourceRange() << LCDecl;
3506   return true;
3507 }
3508 
3509 bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) {
3510   // RHS of canonical loop form increment can be:
3511   //   var + incr
3512   //   incr + var
3513   //   var - incr
3514   //
3515   RHS = RHS->IgnoreParenImpCasts();
3516   if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
3517     if (BO->isAdditiveOp()) {
3518       bool IsAdd = BO->getOpcode() == BO_Add;
3519       if (GetInitLCDecl(BO->getLHS()) == LCDecl)
3520         return SetStep(BO->getRHS(), !IsAdd);
3521       if (IsAdd && GetInitLCDecl(BO->getRHS()) == LCDecl)
3522         return SetStep(BO->getLHS(), false);
3523     }
3524   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
3525     bool IsAdd = CE->getOperator() == OO_Plus;
3526     if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
3527       if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
3528         return SetStep(CE->getArg(1), !IsAdd);
3529       if (IsAdd && GetInitLCDecl(CE->getArg(1)) == LCDecl)
3530         return SetStep(CE->getArg(0), false);
3531     }
3532   }
3533   if (Dependent() || SemaRef.CurContext->isDependentContext())
3534     return false;
3535   SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr)
3536       << RHS->getSourceRange() << LCDecl;
3537   return true;
3538 }
3539 
3540 bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) {
3541   // Check incr-expr for canonical loop form and return true if it
3542   // does not conform.
3543   // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3544   //   ++var
3545   //   var++
3546   //   --var
3547   //   var--
3548   //   var += incr
3549   //   var -= incr
3550   //   var = var + incr
3551   //   var = incr + var
3552   //   var = var - incr
3553   //
3554   if (!S) {
3555     SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
3556     return true;
3557   }
3558   if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
3559     if (!ExprTemp->cleanupsHaveSideEffects())
3560       S = ExprTemp->getSubExpr();
3561 
3562   IncrementSrcRange = S->getSourceRange();
3563   S = S->IgnoreParens();
3564   if (auto *UO = dyn_cast<UnaryOperator>(S)) {
3565     if (UO->isIncrementDecrementOp() &&
3566         GetInitLCDecl(UO->getSubExpr()) == LCDecl)
3567       return SetStep(SemaRef
3568                          .ActOnIntegerConstant(UO->getLocStart(),
3569                                                (UO->isDecrementOp() ? -1 : 1))
3570                          .get(),
3571                      false);
3572   } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
3573     switch (BO->getOpcode()) {
3574     case BO_AddAssign:
3575     case BO_SubAssign:
3576       if (GetInitLCDecl(BO->getLHS()) == LCDecl)
3577         return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
3578       break;
3579     case BO_Assign:
3580       if (GetInitLCDecl(BO->getLHS()) == LCDecl)
3581         return CheckIncRHS(BO->getRHS());
3582       break;
3583     default:
3584       break;
3585     }
3586   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
3587     switch (CE->getOperator()) {
3588     case OO_PlusPlus:
3589     case OO_MinusMinus:
3590       if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
3591         return SetStep(SemaRef
3592                            .ActOnIntegerConstant(
3593                                CE->getLocStart(),
3594                                ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
3595                            .get(),
3596                        false);
3597       break;
3598     case OO_PlusEqual:
3599     case OO_MinusEqual:
3600       if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
3601         return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
3602       break;
3603     case OO_Equal:
3604       if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
3605         return CheckIncRHS(CE->getArg(1));
3606       break;
3607     default:
3608       break;
3609     }
3610   }
3611   if (Dependent() || SemaRef.CurContext->isDependentContext())
3612     return false;
3613   SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr)
3614       << S->getSourceRange() << LCDecl;
3615   return true;
3616 }
3617 
3618 static ExprResult
3619 tryBuildCapture(Sema &SemaRef, Expr *Capture,
3620                 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
3621   if (SemaRef.CurContext->isDependentContext())
3622     return ExprResult(Capture);
3623   if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
3624     return SemaRef.PerformImplicitConversion(
3625         Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
3626         /*AllowExplicit=*/true);
3627   auto I = Captures.find(Capture);
3628   if (I != Captures.end())
3629     return buildCapture(SemaRef, Capture, I->second);
3630   DeclRefExpr *Ref = nullptr;
3631   ExprResult Res = buildCapture(SemaRef, Capture, Ref);
3632   Captures[Capture] = Ref;
3633   return Res;
3634 }
3635 
3636 /// \brief Build the expression to calculate the number of iterations.
3637 Expr *OpenMPIterationSpaceChecker::BuildNumIterations(
3638     Scope *S, const bool LimitedType,
3639     llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
3640   ExprResult Diff;
3641   auto VarType = LCDecl->getType().getNonReferenceType();
3642   if (VarType->isIntegerType() || VarType->isPointerType() ||
3643       SemaRef.getLangOpts().CPlusPlus) {
3644     // Upper - Lower
3645     auto *UBExpr = TestIsLessOp ? UB : LB;
3646     auto *LBExpr = TestIsLessOp ? LB : UB;
3647     Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
3648     Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
3649     if (!Upper || !Lower)
3650       return nullptr;
3651 
3652     Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
3653 
3654     if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
3655       // BuildBinOp already emitted error, this one is to point user to upper
3656       // and lower bound, and to tell what is passed to 'operator-'.
3657       SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx)
3658           << Upper->getSourceRange() << Lower->getSourceRange();
3659       return nullptr;
3660     }
3661   }
3662 
3663   if (!Diff.isUsable())
3664     return nullptr;
3665 
3666   // Upper - Lower [- 1]
3667   if (TestIsStrictOp)
3668     Diff = SemaRef.BuildBinOp(
3669         S, DefaultLoc, BO_Sub, Diff.get(),
3670         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
3671   if (!Diff.isUsable())
3672     return nullptr;
3673 
3674   // Upper - Lower [- 1] + Step
3675   auto NewStep = tryBuildCapture(SemaRef, Step, Captures);
3676   if (!NewStep.isUsable())
3677     return nullptr;
3678   Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
3679   if (!Diff.isUsable())
3680     return nullptr;
3681 
3682   // Parentheses (for dumping/debugging purposes only).
3683   Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
3684   if (!Diff.isUsable())
3685     return nullptr;
3686 
3687   // (Upper - Lower [- 1] + Step) / Step
3688   Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
3689   if (!Diff.isUsable())
3690     return nullptr;
3691 
3692   // OpenMP runtime requires 32-bit or 64-bit loop variables.
3693   QualType Type = Diff.get()->getType();
3694   auto &C = SemaRef.Context;
3695   bool UseVarType = VarType->hasIntegerRepresentation() &&
3696                     C.getTypeSize(Type) > C.getTypeSize(VarType);
3697   if (!Type->isIntegerType() || UseVarType) {
3698     unsigned NewSize =
3699         UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
3700     bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
3701                                : Type->hasSignedIntegerRepresentation();
3702     Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
3703     if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
3704       Diff = SemaRef.PerformImplicitConversion(
3705           Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
3706       if (!Diff.isUsable())
3707         return nullptr;
3708     }
3709   }
3710   if (LimitedType) {
3711     unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
3712     if (NewSize != C.getTypeSize(Type)) {
3713       if (NewSize < C.getTypeSize(Type)) {
3714         assert(NewSize == 64 && "incorrect loop var size");
3715         SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
3716             << InitSrcRange << ConditionSrcRange;
3717       }
3718       QualType NewType = C.getIntTypeForBitwidth(
3719           NewSize, Type->hasSignedIntegerRepresentation() ||
3720                        C.getTypeSize(Type) < NewSize);
3721       if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
3722         Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
3723                                                  Sema::AA_Converting, true);
3724         if (!Diff.isUsable())
3725           return nullptr;
3726       }
3727     }
3728   }
3729 
3730   return Diff.get();
3731 }
3732 
3733 Expr *OpenMPIterationSpaceChecker::BuildPreCond(
3734     Scope *S, Expr *Cond,
3735     llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
3736   // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
3737   bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
3738   SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
3739 
3740   auto NewLB = tryBuildCapture(SemaRef, LB, Captures);
3741   auto NewUB = tryBuildCapture(SemaRef, UB, Captures);
3742   if (!NewLB.isUsable() || !NewUB.isUsable())
3743     return nullptr;
3744 
3745   auto CondExpr = SemaRef.BuildBinOp(
3746       S, DefaultLoc, TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE)
3747                                   : (TestIsStrictOp ? BO_GT : BO_GE),
3748       NewLB.get(), NewUB.get());
3749   if (CondExpr.isUsable()) {
3750     if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
3751                                                 SemaRef.Context.BoolTy))
3752       CondExpr = SemaRef.PerformImplicitConversion(
3753           CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
3754           /*AllowExplicit=*/true);
3755   }
3756   SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
3757   // Otherwise use original loop conditon and evaluate it in runtime.
3758   return CondExpr.isUsable() ? CondExpr.get() : Cond;
3759 }
3760 
3761 /// \brief Build reference expression to the counter be used for codegen.
3762 DeclRefExpr *OpenMPIterationSpaceChecker::BuildCounterVar(
3763     llvm::MapVector<Expr *, DeclRefExpr *> &Captures, DSAStackTy &DSA) const {
3764   auto *VD = dyn_cast<VarDecl>(LCDecl);
3765   if (!VD) {
3766     VD = SemaRef.IsOpenMPCapturedDecl(LCDecl);
3767     auto *Ref = buildDeclRefExpr(
3768         SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
3769     DSAStackTy::DSAVarData Data = DSA.getTopDSA(LCDecl, /*FromParent=*/false);
3770     // If the loop control decl is explicitly marked as private, do not mark it
3771     // as captured again.
3772     if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
3773       Captures.insert(std::make_pair(LCRef, Ref));
3774     return Ref;
3775   }
3776   return buildDeclRefExpr(SemaRef, VD, VD->getType().getNonReferenceType(),
3777                           DefaultLoc);
3778 }
3779 
3780 Expr *OpenMPIterationSpaceChecker::BuildPrivateCounterVar() const {
3781   if (LCDecl && !LCDecl->isInvalidDecl()) {
3782     auto Type = LCDecl->getType().getNonReferenceType();
3783     auto *PrivateVar =
3784         buildVarDecl(SemaRef, DefaultLoc, Type, LCDecl->getName(),
3785                      LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr);
3786     if (PrivateVar->isInvalidDecl())
3787       return nullptr;
3788     return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
3789   }
3790   return nullptr;
3791 }
3792 
3793 /// \brief Build initialization of the counter to be used for codegen.
3794 Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; }
3795 
3796 /// \brief Build step of the counter be used for codegen.
3797 Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; }
3798 
3799 /// \brief Iteration space of a single for loop.
3800 struct LoopIterationSpace final {
3801   /// \brief Condition of the loop.
3802   Expr *PreCond = nullptr;
3803   /// \brief This expression calculates the number of iterations in the loop.
3804   /// It is always possible to calculate it before starting the loop.
3805   Expr *NumIterations = nullptr;
3806   /// \brief The loop counter variable.
3807   Expr *CounterVar = nullptr;
3808   /// \brief Private loop counter variable.
3809   Expr *PrivateCounterVar = nullptr;
3810   /// \brief This is initializer for the initial value of #CounterVar.
3811   Expr *CounterInit = nullptr;
3812   /// \brief This is step for the #CounterVar used to generate its update:
3813   /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
3814   Expr *CounterStep = nullptr;
3815   /// \brief Should step be subtracted?
3816   bool Subtract = false;
3817   /// \brief Source range of the loop init.
3818   SourceRange InitSrcRange;
3819   /// \brief Source range of the loop condition.
3820   SourceRange CondSrcRange;
3821   /// \brief Source range of the loop increment.
3822   SourceRange IncSrcRange;
3823 };
3824 
3825 } // namespace
3826 
3827 void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
3828   assert(getLangOpts().OpenMP && "OpenMP is not active.");
3829   assert(Init && "Expected loop in canonical form.");
3830   unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
3831   if (AssociatedLoops > 0 &&
3832       isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
3833     OpenMPIterationSpaceChecker ISC(*this, ForLoc);
3834     if (!ISC.CheckInit(Init, /*EmitDiags=*/false)) {
3835       if (auto *D = ISC.GetLoopDecl()) {
3836         auto *VD = dyn_cast<VarDecl>(D);
3837         if (!VD) {
3838           if (auto *Private = IsOpenMPCapturedDecl(D))
3839             VD = Private;
3840           else {
3841             auto *Ref = buildCapture(*this, D, ISC.GetLoopDeclRefExpr(),
3842                                      /*WithInit=*/false);
3843             VD = cast<VarDecl>(Ref->getDecl());
3844           }
3845         }
3846         DSAStack->addLoopControlVariable(D, VD);
3847       }
3848     }
3849     DSAStack->setAssociatedLoops(AssociatedLoops - 1);
3850   }
3851 }
3852 
3853 /// \brief Called on a for stmt to check and extract its iteration space
3854 /// for further processing (such as collapsing).
3855 static bool CheckOpenMPIterationSpace(
3856     OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
3857     unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
3858     Expr *CollapseLoopCountExpr, Expr *OrderedLoopCountExpr,
3859     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
3860     LoopIterationSpace &ResultIterSpace,
3861     llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
3862   // OpenMP [2.6, Canonical Loop Form]
3863   //   for (init-expr; test-expr; incr-expr) structured-block
3864   auto *For = dyn_cast_or_null<ForStmt>(S);
3865   if (!For) {
3866     SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for)
3867         << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
3868         << getOpenMPDirectiveName(DKind) << NestedLoopCount
3869         << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
3870     if (NestedLoopCount > 1) {
3871       if (CollapseLoopCountExpr && OrderedLoopCountExpr)
3872         SemaRef.Diag(DSA.getConstructLoc(),
3873                      diag::note_omp_collapse_ordered_expr)
3874             << 2 << CollapseLoopCountExpr->getSourceRange()
3875             << OrderedLoopCountExpr->getSourceRange();
3876       else if (CollapseLoopCountExpr)
3877         SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
3878                      diag::note_omp_collapse_ordered_expr)
3879             << 0 << CollapseLoopCountExpr->getSourceRange();
3880       else
3881         SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
3882                      diag::note_omp_collapse_ordered_expr)
3883             << 1 << OrderedLoopCountExpr->getSourceRange();
3884     }
3885     return true;
3886   }
3887   assert(For->getBody());
3888 
3889   OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
3890 
3891   // Check init.
3892   auto Init = For->getInit();
3893   if (ISC.CheckInit(Init))
3894     return true;
3895 
3896   bool HasErrors = false;
3897 
3898   // Check loop variable's type.
3899   if (auto *LCDecl = ISC.GetLoopDecl()) {
3900     auto *LoopDeclRefExpr = ISC.GetLoopDeclRefExpr();
3901 
3902     // OpenMP [2.6, Canonical Loop Form]
3903     // Var is one of the following:
3904     //   A variable of signed or unsigned integer type.
3905     //   For C++, a variable of a random access iterator type.
3906     //   For C, a variable of a pointer type.
3907     auto VarType = LCDecl->getType().getNonReferenceType();
3908     if (!VarType->isDependentType() && !VarType->isIntegerType() &&
3909         !VarType->isPointerType() &&
3910         !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
3911       SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type)
3912           << SemaRef.getLangOpts().CPlusPlus;
3913       HasErrors = true;
3914     }
3915 
3916     // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
3917     // a Construct
3918     // The loop iteration variable(s) in the associated for-loop(s) of a for or
3919     // parallel for construct is (are) private.
3920     // The loop iteration variable in the associated for-loop of a simd
3921     // construct with just one associated for-loop is linear with a
3922     // constant-linear-step that is the increment of the associated for-loop.
3923     // Exclude loop var from the list of variables with implicitly defined data
3924     // sharing attributes.
3925     VarsWithImplicitDSA.erase(LCDecl);
3926 
3927     // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
3928     // in a Construct, C/C++].
3929     // The loop iteration variable in the associated for-loop of a simd
3930     // construct with just one associated for-loop may be listed in a linear
3931     // clause with a constant-linear-step that is the increment of the
3932     // associated for-loop.
3933     // The loop iteration variable(s) in the associated for-loop(s) of a for or
3934     // parallel for construct may be listed in a private or lastprivate clause.
3935     DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false);
3936     // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
3937     // declared in the loop and it is predetermined as a private.
3938     auto PredeterminedCKind =
3939         isOpenMPSimdDirective(DKind)
3940             ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
3941             : OMPC_private;
3942     if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
3943           DVar.CKind != PredeterminedCKind) ||
3944          ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
3945            isOpenMPDistributeDirective(DKind)) &&
3946           !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
3947           DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
3948         (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
3949       SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa)
3950           << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
3951           << getOpenMPClauseName(PredeterminedCKind);
3952       if (DVar.RefExpr == nullptr)
3953         DVar.CKind = PredeterminedCKind;
3954       ReportOriginalDSA(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true);
3955       HasErrors = true;
3956     } else if (LoopDeclRefExpr != nullptr) {
3957       // Make the loop iteration variable private (for worksharing constructs),
3958       // linear (for simd directives with the only one associated loop) or
3959       // lastprivate (for simd directives with several collapsed or ordered
3960       // loops).
3961       if (DVar.CKind == OMPC_unknown)
3962         DVar = DSA.hasDSA(LCDecl, isOpenMPPrivate,
3963                           [](OpenMPDirectiveKind) -> bool { return true; },
3964                           /*FromParent=*/false);
3965       DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind);
3966     }
3967 
3968     assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
3969 
3970     // Check test-expr.
3971     HasErrors |= ISC.CheckCond(For->getCond());
3972 
3973     // Check incr-expr.
3974     HasErrors |= ISC.CheckInc(For->getInc());
3975   }
3976 
3977   if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
3978     return HasErrors;
3979 
3980   // Build the loop's iteration space representation.
3981   ResultIterSpace.PreCond =
3982       ISC.BuildPreCond(DSA.getCurScope(), For->getCond(), Captures);
3983   ResultIterSpace.NumIterations = ISC.BuildNumIterations(
3984       DSA.getCurScope(),
3985       (isOpenMPWorksharingDirective(DKind) ||
3986        isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)),
3987       Captures);
3988   ResultIterSpace.CounterVar = ISC.BuildCounterVar(Captures, DSA);
3989   ResultIterSpace.PrivateCounterVar = ISC.BuildPrivateCounterVar();
3990   ResultIterSpace.CounterInit = ISC.BuildCounterInit();
3991   ResultIterSpace.CounterStep = ISC.BuildCounterStep();
3992   ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange();
3993   ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange();
3994   ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange();
3995   ResultIterSpace.Subtract = ISC.ShouldSubtractStep();
3996 
3997   HasErrors |= (ResultIterSpace.PreCond == nullptr ||
3998                 ResultIterSpace.NumIterations == nullptr ||
3999                 ResultIterSpace.CounterVar == nullptr ||
4000                 ResultIterSpace.PrivateCounterVar == nullptr ||
4001                 ResultIterSpace.CounterInit == nullptr ||
4002                 ResultIterSpace.CounterStep == nullptr);
4003 
4004   return HasErrors;
4005 }
4006 
4007 /// \brief Build 'VarRef = Start.
4008 static ExprResult
4009 BuildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
4010                  ExprResult Start,
4011                  llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
4012   // Build 'VarRef = Start.
4013   auto NewStart = tryBuildCapture(SemaRef, Start.get(), Captures);
4014   if (!NewStart.isUsable())
4015     return ExprError();
4016   if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
4017                                    VarRef.get()->getType())) {
4018     NewStart = SemaRef.PerformImplicitConversion(
4019         NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
4020         /*AllowExplicit=*/true);
4021     if (!NewStart.isUsable())
4022       return ExprError();
4023   }
4024 
4025   auto Init =
4026       SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
4027   return Init;
4028 }
4029 
4030 /// \brief Build 'VarRef = Start + Iter * Step'.
4031 static ExprResult
4032 BuildCounterUpdate(Sema &SemaRef, Scope *S, SourceLocation Loc,
4033                    ExprResult VarRef, ExprResult Start, ExprResult Iter,
4034                    ExprResult Step, bool Subtract,
4035                    llvm::MapVector<Expr *, DeclRefExpr *> *Captures = nullptr) {
4036   // Add parentheses (for debugging purposes only).
4037   Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
4038   if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
4039       !Step.isUsable())
4040     return ExprError();
4041 
4042   ExprResult NewStep = Step;
4043   if (Captures)
4044     NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
4045   if (NewStep.isInvalid())
4046     return ExprError();
4047   ExprResult Update =
4048       SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
4049   if (!Update.isUsable())
4050     return ExprError();
4051 
4052   // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
4053   // 'VarRef = Start (+|-) Iter * Step'.
4054   ExprResult NewStart = Start;
4055   if (Captures)
4056     NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
4057   if (NewStart.isInvalid())
4058     return ExprError();
4059 
4060   // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
4061   ExprResult SavedUpdate = Update;
4062   ExprResult UpdateVal;
4063   if (VarRef.get()->getType()->isOverloadableType() ||
4064       NewStart.get()->getType()->isOverloadableType() ||
4065       Update.get()->getType()->isOverloadableType()) {
4066     bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
4067     SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
4068     Update =
4069         SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
4070     if (Update.isUsable()) {
4071       UpdateVal =
4072           SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
4073                              VarRef.get(), SavedUpdate.get());
4074       if (UpdateVal.isUsable()) {
4075         Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
4076                                             UpdateVal.get());
4077       }
4078     }
4079     SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
4080   }
4081 
4082   // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
4083   if (!Update.isUsable() || !UpdateVal.isUsable()) {
4084     Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
4085                                 NewStart.get(), SavedUpdate.get());
4086     if (!Update.isUsable())
4087       return ExprError();
4088 
4089     if (!SemaRef.Context.hasSameType(Update.get()->getType(),
4090                                      VarRef.get()->getType())) {
4091       Update = SemaRef.PerformImplicitConversion(
4092           Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
4093       if (!Update.isUsable())
4094         return ExprError();
4095     }
4096 
4097     Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
4098   }
4099   return Update;
4100 }
4101 
4102 /// \brief Convert integer expression \a E to make it have at least \a Bits
4103 /// bits.
4104 static ExprResult WidenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
4105   if (E == nullptr)
4106     return ExprError();
4107   auto &C = SemaRef.Context;
4108   QualType OldType = E->getType();
4109   unsigned HasBits = C.getTypeSize(OldType);
4110   if (HasBits >= Bits)
4111     return ExprResult(E);
4112   // OK to convert to signed, because new type has more bits than old.
4113   QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
4114   return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
4115                                            true);
4116 }
4117 
4118 /// \brief Check if the given expression \a E is a constant integer that fits
4119 /// into \a Bits bits.
4120 static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) {
4121   if (E == nullptr)
4122     return false;
4123   llvm::APSInt Result;
4124   if (E->isIntegerConstantExpr(Result, SemaRef.Context))
4125     return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
4126   return false;
4127 }
4128 
4129 /// Build preinits statement for the given declarations.
4130 static Stmt *buildPreInits(ASTContext &Context,
4131                            SmallVectorImpl<Decl *> &PreInits) {
4132   if (!PreInits.empty()) {
4133     return new (Context) DeclStmt(
4134         DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
4135         SourceLocation(), SourceLocation());
4136   }
4137   return nullptr;
4138 }
4139 
4140 /// Build preinits statement for the given declarations.
4141 static Stmt *buildPreInits(ASTContext &Context,
4142                            llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
4143   if (!Captures.empty()) {
4144     SmallVector<Decl *, 16> PreInits;
4145     for (auto &Pair : Captures)
4146       PreInits.push_back(Pair.second->getDecl());
4147     return buildPreInits(Context, PreInits);
4148   }
4149   return nullptr;
4150 }
4151 
4152 /// Build postupdate expression for the given list of postupdates expressions.
4153 static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
4154   Expr *PostUpdate = nullptr;
4155   if (!PostUpdates.empty()) {
4156     for (auto *E : PostUpdates) {
4157       Expr *ConvE = S.BuildCStyleCastExpr(
4158                          E->getExprLoc(),
4159                          S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
4160                          E->getExprLoc(), E)
4161                         .get();
4162       PostUpdate = PostUpdate
4163                        ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
4164                                               PostUpdate, ConvE)
4165                              .get()
4166                        : ConvE;
4167     }
4168   }
4169   return PostUpdate;
4170 }
4171 
4172 /// \brief Called on a for stmt to check itself and nested loops (if any).
4173 /// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
4174 /// number of collapsed loops otherwise.
4175 static unsigned
4176 CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
4177                 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
4178                 DSAStackTy &DSA,
4179                 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
4180                 OMPLoopDirective::HelperExprs &Built) {
4181   unsigned NestedLoopCount = 1;
4182   if (CollapseLoopCountExpr) {
4183     // Found 'collapse' clause - calculate collapse number.
4184     llvm::APSInt Result;
4185     if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
4186       NestedLoopCount = Result.getLimitedValue();
4187   }
4188   if (OrderedLoopCountExpr) {
4189     // Found 'ordered' clause - calculate collapse number.
4190     llvm::APSInt Result;
4191     if (OrderedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
4192       if (Result.getLimitedValue() < NestedLoopCount) {
4193         SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
4194                      diag::err_omp_wrong_ordered_loop_count)
4195             << OrderedLoopCountExpr->getSourceRange();
4196         SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
4197                      diag::note_collapse_loop_count)
4198             << CollapseLoopCountExpr->getSourceRange();
4199       }
4200       NestedLoopCount = Result.getLimitedValue();
4201     }
4202   }
4203   // This is helper routine for loop directives (e.g., 'for', 'simd',
4204   // 'for simd', etc.).
4205   llvm::MapVector<Expr *, DeclRefExpr *> Captures;
4206   SmallVector<LoopIterationSpace, 4> IterSpaces;
4207   IterSpaces.resize(NestedLoopCount);
4208   Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
4209   for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
4210     if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt,
4211                                   NestedLoopCount, CollapseLoopCountExpr,
4212                                   OrderedLoopCountExpr, VarsWithImplicitDSA,
4213                                   IterSpaces[Cnt], Captures))
4214       return 0;
4215     // Move on to the next nested for loop, or to the loop body.
4216     // OpenMP [2.8.1, simd construct, Restrictions]
4217     // All loops associated with the construct must be perfectly nested; that
4218     // is, there must be no intervening code nor any OpenMP directive between
4219     // any two loops.
4220     CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
4221   }
4222 
4223   Built.clear(/* size */ NestedLoopCount);
4224 
4225   if (SemaRef.CurContext->isDependentContext())
4226     return NestedLoopCount;
4227 
4228   // An example of what is generated for the following code:
4229   //
4230   //   #pragma omp simd collapse(2) ordered(2)
4231   //   for (i = 0; i < NI; ++i)
4232   //     for (k = 0; k < NK; ++k)
4233   //       for (j = J0; j < NJ; j+=2) {
4234   //         <loop body>
4235   //       }
4236   //
4237   // We generate the code below.
4238   // Note: the loop body may be outlined in CodeGen.
4239   // Note: some counters may be C++ classes, operator- is used to find number of
4240   // iterations and operator+= to calculate counter value.
4241   // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
4242   // or i64 is currently supported).
4243   //
4244   //   #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
4245   //   for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
4246   //     .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
4247   //     .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
4248   //     // similar updates for vars in clauses (e.g. 'linear')
4249   //     <loop body (using local i and j)>
4250   //   }
4251   //   i = NI; // assign final values of counters
4252   //   j = NJ;
4253   //
4254 
4255   // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
4256   // the iteration counts of the collapsed for loops.
4257   // Precondition tests if there is at least one iteration (all conditions are
4258   // true).
4259   auto PreCond = ExprResult(IterSpaces[0].PreCond);
4260   auto N0 = IterSpaces[0].NumIterations;
4261   ExprResult LastIteration32 = WidenIterationCount(
4262       32 /* Bits */, SemaRef
4263                          .PerformImplicitConversion(
4264                              N0->IgnoreImpCasts(), N0->getType(),
4265                              Sema::AA_Converting, /*AllowExplicit=*/true)
4266                          .get(),
4267       SemaRef);
4268   ExprResult LastIteration64 = WidenIterationCount(
4269       64 /* Bits */, SemaRef
4270                          .PerformImplicitConversion(
4271                              N0->IgnoreImpCasts(), N0->getType(),
4272                              Sema::AA_Converting, /*AllowExplicit=*/true)
4273                          .get(),
4274       SemaRef);
4275 
4276   if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
4277     return NestedLoopCount;
4278 
4279   auto &C = SemaRef.Context;
4280   bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
4281 
4282   Scope *CurScope = DSA.getCurScope();
4283   for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
4284     if (PreCond.isUsable()) {
4285       PreCond =
4286           SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
4287                              PreCond.get(), IterSpaces[Cnt].PreCond);
4288     }
4289     auto N = IterSpaces[Cnt].NumIterations;
4290     SourceLocation Loc = N->getExprLoc();
4291     AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
4292     if (LastIteration32.isUsable())
4293       LastIteration32 = SemaRef.BuildBinOp(
4294           CurScope, Loc, BO_Mul, LastIteration32.get(),
4295           SemaRef
4296               .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
4297                                          Sema::AA_Converting,
4298                                          /*AllowExplicit=*/true)
4299               .get());
4300     if (LastIteration64.isUsable())
4301       LastIteration64 = SemaRef.BuildBinOp(
4302           CurScope, Loc, BO_Mul, LastIteration64.get(),
4303           SemaRef
4304               .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
4305                                          Sema::AA_Converting,
4306                                          /*AllowExplicit=*/true)
4307               .get());
4308   }
4309 
4310   // Choose either the 32-bit or 64-bit version.
4311   ExprResult LastIteration = LastIteration64;
4312   if (LastIteration32.isUsable() &&
4313       C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
4314       (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
4315        FitsInto(
4316            32 /* Bits */,
4317            LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
4318            LastIteration64.get(), SemaRef)))
4319     LastIteration = LastIteration32;
4320   QualType VType = LastIteration.get()->getType();
4321   QualType RealVType = VType;
4322   QualType StrideVType = VType;
4323   if (isOpenMPTaskLoopDirective(DKind)) {
4324     VType =
4325         SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
4326     StrideVType =
4327         SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
4328   }
4329 
4330   if (!LastIteration.isUsable())
4331     return 0;
4332 
4333   // Save the number of iterations.
4334   ExprResult NumIterations = LastIteration;
4335   {
4336     LastIteration = SemaRef.BuildBinOp(
4337         CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
4338         LastIteration.get(),
4339         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4340     if (!LastIteration.isUsable())
4341       return 0;
4342   }
4343 
4344   // Calculate the last iteration number beforehand instead of doing this on
4345   // each iteration. Do not do this if the number of iterations may be kfold-ed.
4346   llvm::APSInt Result;
4347   bool IsConstant =
4348       LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
4349   ExprResult CalcLastIteration;
4350   if (!IsConstant) {
4351     ExprResult SaveRef =
4352         tryBuildCapture(SemaRef, LastIteration.get(), Captures);
4353     LastIteration = SaveRef;
4354 
4355     // Prepare SaveRef + 1.
4356     NumIterations = SemaRef.BuildBinOp(
4357         CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
4358         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4359     if (!NumIterations.isUsable())
4360       return 0;
4361   }
4362 
4363   SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
4364 
4365   // Build variables passed into runtime, necessary for worksharing directives.
4366   ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
4367   if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
4368       isOpenMPDistributeDirective(DKind)) {
4369     // Lower bound variable, initialized with zero.
4370     VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
4371     LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
4372     SemaRef.AddInitializerToDecl(LBDecl,
4373                                  SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4374                                  /*DirectInit*/ false);
4375 
4376     // Upper bound variable, initialized with last iteration number.
4377     VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
4378     UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
4379     SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
4380                                  /*DirectInit*/ false);
4381 
4382     // A 32-bit variable-flag where runtime returns 1 for the last iteration.
4383     // This will be used to implement clause 'lastprivate'.
4384     QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
4385     VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
4386     IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
4387     SemaRef.AddInitializerToDecl(ILDecl,
4388                                  SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4389                                  /*DirectInit*/ false);
4390 
4391     // Stride variable returned by runtime (we initialize it to 1 by default).
4392     VarDecl *STDecl =
4393         buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
4394     ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
4395     SemaRef.AddInitializerToDecl(STDecl,
4396                                  SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
4397                                  /*DirectInit*/ false);
4398 
4399     // Build expression: UB = min(UB, LastIteration)
4400     // It is necessary for CodeGen of directives with static scheduling.
4401     ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
4402                                                 UB.get(), LastIteration.get());
4403     ExprResult CondOp = SemaRef.ActOnConditionalOp(
4404         InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get());
4405     EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
4406                              CondOp.get());
4407     EUB = SemaRef.ActOnFinishFullExpr(EUB.get());
4408 
4409     // If we have a combined directive that combines 'distribute', 'for' or
4410     // 'simd' we need to be able to access the bounds of the schedule of the
4411     // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
4412     // by scheduling 'distribute' have to be passed to the schedule of 'for'.
4413     if (isOpenMPLoopBoundSharingDirective(DKind)) {
4414 
4415       // Lower bound variable, initialized with zero.
4416       VarDecl *CombLBDecl =
4417           buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
4418       CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
4419       SemaRef.AddInitializerToDecl(
4420           CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4421           /*DirectInit*/ false);
4422 
4423       // Upper bound variable, initialized with last iteration number.
4424       VarDecl *CombUBDecl =
4425           buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
4426       CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
4427       SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
4428                                    /*DirectInit*/ false);
4429 
4430       ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
4431           CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
4432       ExprResult CombCondOp =
4433           SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
4434                                      LastIteration.get(), CombUB.get());
4435       CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
4436                                    CombCondOp.get());
4437       CombEUB = SemaRef.ActOnFinishFullExpr(CombEUB.get());
4438 
4439       auto *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
4440       // We expect to have at least 2 more parameters than the 'parallel'
4441       // directive does - the lower and upper bounds of the previous schedule.
4442       assert(CD->getNumParams() >= 4 &&
4443              "Unexpected number of parameters in loop combined directive");
4444 
4445       // Set the proper type for the bounds given what we learned from the
4446       // enclosed loops.
4447       auto *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
4448       auto *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
4449 
4450       // Previous lower and upper bounds are obtained from the region
4451       // parameters.
4452       PrevLB =
4453           buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
4454       PrevUB =
4455           buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
4456     }
4457   }
4458 
4459   // Build the iteration variable and its initialization before loop.
4460   ExprResult IV;
4461   ExprResult Init, CombInit;
4462   {
4463     VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
4464     IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
4465     Expr *RHS =
4466         (isOpenMPWorksharingDirective(DKind) ||
4467          isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
4468             ? LB.get()
4469             : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
4470     Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
4471     Init = SemaRef.ActOnFinishFullExpr(Init.get());
4472 
4473     if (isOpenMPLoopBoundSharingDirective(DKind)) {
4474       Expr *CombRHS =
4475           (isOpenMPWorksharingDirective(DKind) ||
4476            isOpenMPTaskLoopDirective(DKind) ||
4477            isOpenMPDistributeDirective(DKind))
4478               ? CombLB.get()
4479               : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
4480       CombInit =
4481           SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
4482       CombInit = SemaRef.ActOnFinishFullExpr(CombInit.get());
4483     }
4484   }
4485 
4486   // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops.
4487   SourceLocation CondLoc;
4488   ExprResult Cond =
4489       (isOpenMPWorksharingDirective(DKind) ||
4490        isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
4491           ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get())
4492           : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
4493                                NumIterations.get());
4494   ExprResult CombCond;
4495   if (isOpenMPLoopBoundSharingDirective(DKind)) {
4496     CombCond =
4497         SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), CombUB.get());
4498   }
4499   // Loop increment (IV = IV + 1)
4500   SourceLocation IncLoc;
4501   ExprResult Inc =
4502       SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
4503                          SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
4504   if (!Inc.isUsable())
4505     return 0;
4506   Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
4507   Inc = SemaRef.ActOnFinishFullExpr(Inc.get());
4508   if (!Inc.isUsable())
4509     return 0;
4510 
4511   // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
4512   // Used for directives with static scheduling.
4513   // In combined construct, add combined version that use CombLB and CombUB
4514   // base variables for the update
4515   ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
4516   if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
4517       isOpenMPDistributeDirective(DKind)) {
4518     // LB + ST
4519     NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
4520     if (!NextLB.isUsable())
4521       return 0;
4522     // LB = LB + ST
4523     NextLB =
4524         SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
4525     NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get());
4526     if (!NextLB.isUsable())
4527       return 0;
4528     // UB + ST
4529     NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
4530     if (!NextUB.isUsable())
4531       return 0;
4532     // UB = UB + ST
4533     NextUB =
4534         SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
4535     NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get());
4536     if (!NextUB.isUsable())
4537       return 0;
4538     if (isOpenMPLoopBoundSharingDirective(DKind)) {
4539       CombNextLB =
4540           SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
4541       if (!NextLB.isUsable())
4542         return 0;
4543       // LB = LB + ST
4544       CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
4545                                       CombNextLB.get());
4546       CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get());
4547       if (!CombNextLB.isUsable())
4548         return 0;
4549       // UB + ST
4550       CombNextUB =
4551           SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
4552       if (!CombNextUB.isUsable())
4553         return 0;
4554       // UB = UB + ST
4555       CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
4556                                       CombNextUB.get());
4557       CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get());
4558       if (!CombNextUB.isUsable())
4559         return 0;
4560     }
4561   }
4562 
4563   // Create increment expression for distribute loop when combined in a same
4564   // directive with for as IV = IV + ST; ensure upper bound expression based
4565   // on PrevUB instead of NumIterations - used to implement 'for' when found
4566   // in combination with 'distribute', like in 'distribute parallel for'
4567   SourceLocation DistIncLoc;
4568   ExprResult DistCond, DistInc, PrevEUB;
4569   if (isOpenMPLoopBoundSharingDirective(DKind)) {
4570     DistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get());
4571     assert(DistCond.isUsable() && "distribute cond expr was not built");
4572 
4573     DistInc =
4574         SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
4575     assert(DistInc.isUsable() && "distribute inc expr was not built");
4576     DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
4577                                  DistInc.get());
4578     DistInc = SemaRef.ActOnFinishFullExpr(DistInc.get());
4579     assert(DistInc.isUsable() && "distribute inc expr was not built");
4580 
4581     // Build expression: UB = min(UB, prevUB) for #for in composite or combined
4582     // construct
4583     SourceLocation DistEUBLoc;
4584     ExprResult IsUBGreater =
4585         SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get());
4586     ExprResult CondOp = SemaRef.ActOnConditionalOp(
4587         DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get());
4588     PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
4589                                  CondOp.get());
4590     PrevEUB = SemaRef.ActOnFinishFullExpr(PrevEUB.get());
4591   }
4592 
4593   // Build updates and final values of the loop counters.
4594   bool HasErrors = false;
4595   Built.Counters.resize(NestedLoopCount);
4596   Built.Inits.resize(NestedLoopCount);
4597   Built.Updates.resize(NestedLoopCount);
4598   Built.Finals.resize(NestedLoopCount);
4599   SmallVector<Expr *, 4> LoopMultipliers;
4600   {
4601     ExprResult Div;
4602     // Go from inner nested loop to outer.
4603     for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
4604       LoopIterationSpace &IS = IterSpaces[Cnt];
4605       SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
4606       // Build: Iter = (IV / Div) % IS.NumIters
4607       // where Div is product of previous iterations' IS.NumIters.
4608       ExprResult Iter;
4609       if (Div.isUsable()) {
4610         Iter =
4611             SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get());
4612       } else {
4613         Iter = IV;
4614         assert((Cnt == (int)NestedLoopCount - 1) &&
4615                "unusable div expected on first iteration only");
4616       }
4617 
4618       if (Cnt != 0 && Iter.isUsable())
4619         Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(),
4620                                   IS.NumIterations);
4621       if (!Iter.isUsable()) {
4622         HasErrors = true;
4623         break;
4624       }
4625 
4626       // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
4627       auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
4628       auto *CounterVar = buildDeclRefExpr(SemaRef, VD, IS.CounterVar->getType(),
4629                                           IS.CounterVar->getExprLoc(),
4630                                           /*RefersToCapture=*/true);
4631       ExprResult Init = BuildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
4632                                          IS.CounterInit, Captures);
4633       if (!Init.isUsable()) {
4634         HasErrors = true;
4635         break;
4636       }
4637       ExprResult Update = BuildCounterUpdate(
4638           SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
4639           IS.CounterStep, IS.Subtract, &Captures);
4640       if (!Update.isUsable()) {
4641         HasErrors = true;
4642         break;
4643       }
4644 
4645       // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
4646       ExprResult Final = BuildCounterUpdate(
4647           SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
4648           IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures);
4649       if (!Final.isUsable()) {
4650         HasErrors = true;
4651         break;
4652       }
4653 
4654       // Build Div for the next iteration: Div <- Div * IS.NumIters
4655       if (Cnt != 0) {
4656         if (Div.isUnset())
4657           Div = IS.NumIterations;
4658         else
4659           Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(),
4660                                    IS.NumIterations);
4661 
4662         // Add parentheses (for debugging purposes only).
4663         if (Div.isUsable())
4664           Div = tryBuildCapture(SemaRef, Div.get(), Captures);
4665         if (!Div.isUsable()) {
4666           HasErrors = true;
4667           break;
4668         }
4669         LoopMultipliers.push_back(Div.get());
4670       }
4671       if (!Update.isUsable() || !Final.isUsable()) {
4672         HasErrors = true;
4673         break;
4674       }
4675       // Save results
4676       Built.Counters[Cnt] = IS.CounterVar;
4677       Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
4678       Built.Inits[Cnt] = Init.get();
4679       Built.Updates[Cnt] = Update.get();
4680       Built.Finals[Cnt] = Final.get();
4681     }
4682   }
4683 
4684   if (HasErrors)
4685     return 0;
4686 
4687   // Save results
4688   Built.IterationVarRef = IV.get();
4689   Built.LastIteration = LastIteration.get();
4690   Built.NumIterations = NumIterations.get();
4691   Built.CalcLastIteration =
4692       SemaRef.ActOnFinishFullExpr(CalcLastIteration.get()).get();
4693   Built.PreCond = PreCond.get();
4694   Built.PreInits = buildPreInits(C, Captures);
4695   Built.Cond = Cond.get();
4696   Built.Init = Init.get();
4697   Built.Inc = Inc.get();
4698   Built.LB = LB.get();
4699   Built.UB = UB.get();
4700   Built.IL = IL.get();
4701   Built.ST = ST.get();
4702   Built.EUB = EUB.get();
4703   Built.NLB = NextLB.get();
4704   Built.NUB = NextUB.get();
4705   Built.PrevLB = PrevLB.get();
4706   Built.PrevUB = PrevUB.get();
4707   Built.DistInc = DistInc.get();
4708   Built.PrevEUB = PrevEUB.get();
4709   Built.DistCombinedFields.LB = CombLB.get();
4710   Built.DistCombinedFields.UB = CombUB.get();
4711   Built.DistCombinedFields.EUB = CombEUB.get();
4712   Built.DistCombinedFields.Init = CombInit.get();
4713   Built.DistCombinedFields.Cond = CombCond.get();
4714   Built.DistCombinedFields.NLB = CombNextLB.get();
4715   Built.DistCombinedFields.NUB = CombNextUB.get();
4716 
4717   Expr *CounterVal = SemaRef.DefaultLvalueConversion(IV.get()).get();
4718   // Fill data for doacross depend clauses.
4719   for (auto Pair : DSA.getDoacrossDependClauses()) {
4720     if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
4721       Pair.first->setCounterValue(CounterVal);
4722     else {
4723       if (NestedLoopCount != Pair.second.size() ||
4724           NestedLoopCount != LoopMultipliers.size() + 1) {
4725         // Erroneous case - clause has some problems.
4726         Pair.first->setCounterValue(CounterVal);
4727         continue;
4728       }
4729       assert(Pair.first->getDependencyKind() == OMPC_DEPEND_sink);
4730       auto I = Pair.second.rbegin();
4731       auto IS = IterSpaces.rbegin();
4732       auto ILM = LoopMultipliers.rbegin();
4733       Expr *UpCounterVal = CounterVal;
4734       Expr *Multiplier = nullptr;
4735       for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
4736         if (I->first) {
4737           assert(IS->CounterStep);
4738           Expr *NormalizedOffset =
4739               SemaRef
4740                   .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Div,
4741                               I->first, IS->CounterStep)
4742                   .get();
4743           if (Multiplier) {
4744             NormalizedOffset =
4745                 SemaRef
4746                     .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Mul,
4747                                 NormalizedOffset, Multiplier)
4748                     .get();
4749           }
4750           assert(I->second == OO_Plus || I->second == OO_Minus);
4751           BinaryOperatorKind BOK = (I->second == OO_Plus) ? BO_Add : BO_Sub;
4752           UpCounterVal = SemaRef
4753                              .BuildBinOp(CurScope, I->first->getExprLoc(), BOK,
4754                                          UpCounterVal, NormalizedOffset)
4755                              .get();
4756         }
4757         Multiplier = *ILM;
4758         ++I;
4759         ++IS;
4760         ++ILM;
4761       }
4762       Pair.first->setCounterValue(UpCounterVal);
4763     }
4764   }
4765 
4766   return NestedLoopCount;
4767 }
4768 
4769 static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
4770   auto CollapseClauses =
4771       OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
4772   if (CollapseClauses.begin() != CollapseClauses.end())
4773     return (*CollapseClauses.begin())->getNumForLoops();
4774   return nullptr;
4775 }
4776 
4777 static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
4778   auto OrderedClauses =
4779       OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
4780   if (OrderedClauses.begin() != OrderedClauses.end())
4781     return (*OrderedClauses.begin())->getNumForLoops();
4782   return nullptr;
4783 }
4784 
4785 static bool checkSimdlenSafelenSpecified(Sema &S,
4786                                          const ArrayRef<OMPClause *> Clauses) {
4787   OMPSafelenClause *Safelen = nullptr;
4788   OMPSimdlenClause *Simdlen = nullptr;
4789 
4790   for (auto *Clause : Clauses) {
4791     if (Clause->getClauseKind() == OMPC_safelen)
4792       Safelen = cast<OMPSafelenClause>(Clause);
4793     else if (Clause->getClauseKind() == OMPC_simdlen)
4794       Simdlen = cast<OMPSimdlenClause>(Clause);
4795     if (Safelen && Simdlen)
4796       break;
4797   }
4798 
4799   if (Simdlen && Safelen) {
4800     llvm::APSInt SimdlenRes, SafelenRes;
4801     auto SimdlenLength = Simdlen->getSimdlen();
4802     auto SafelenLength = Safelen->getSafelen();
4803     if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
4804         SimdlenLength->isInstantiationDependent() ||
4805         SimdlenLength->containsUnexpandedParameterPack())
4806       return false;
4807     if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
4808         SafelenLength->isInstantiationDependent() ||
4809         SafelenLength->containsUnexpandedParameterPack())
4810       return false;
4811     SimdlenLength->EvaluateAsInt(SimdlenRes, S.Context);
4812     SafelenLength->EvaluateAsInt(SafelenRes, S.Context);
4813     // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
4814     // If both simdlen and safelen clauses are specified, the value of the
4815     // simdlen parameter must be less than or equal to the value of the safelen
4816     // parameter.
4817     if (SimdlenRes > SafelenRes) {
4818       S.Diag(SimdlenLength->getExprLoc(),
4819              diag::err_omp_wrong_simdlen_safelen_values)
4820           << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
4821       return true;
4822     }
4823   }
4824   return false;
4825 }
4826 
4827 StmtResult Sema::ActOnOpenMPSimdDirective(
4828     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4829     SourceLocation EndLoc,
4830     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
4831   if (!AStmt)
4832     return StmtError();
4833 
4834   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4835   OMPLoopDirective::HelperExprs B;
4836   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4837   // define the nested loops number.
4838   unsigned NestedLoopCount = CheckOpenMPLoop(
4839       OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
4840       AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
4841   if (NestedLoopCount == 0)
4842     return StmtError();
4843 
4844   assert((CurContext->isDependentContext() || B.builtAll()) &&
4845          "omp simd loop exprs were not built");
4846 
4847   if (!CurContext->isDependentContext()) {
4848     // Finalize the clauses that need pre-built expressions for CodeGen.
4849     for (auto C : Clauses) {
4850       if (auto *LC = dyn_cast<OMPLinearClause>(C))
4851         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
4852                                      B.NumIterations, *this, CurScope,
4853                                      DSAStack))
4854           return StmtError();
4855     }
4856   }
4857 
4858   if (checkSimdlenSafelenSpecified(*this, Clauses))
4859     return StmtError();
4860 
4861   getCurFunction()->setHasBranchProtectedScope();
4862   return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
4863                                   Clauses, AStmt, B);
4864 }
4865 
4866 StmtResult Sema::ActOnOpenMPForDirective(
4867     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4868     SourceLocation EndLoc,
4869     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
4870   if (!AStmt)
4871     return StmtError();
4872 
4873   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4874   OMPLoopDirective::HelperExprs B;
4875   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4876   // define the nested loops number.
4877   unsigned NestedLoopCount = CheckOpenMPLoop(
4878       OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
4879       AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
4880   if (NestedLoopCount == 0)
4881     return StmtError();
4882 
4883   assert((CurContext->isDependentContext() || B.builtAll()) &&
4884          "omp for loop exprs were not built");
4885 
4886   if (!CurContext->isDependentContext()) {
4887     // Finalize the clauses that need pre-built expressions for CodeGen.
4888     for (auto C : Clauses) {
4889       if (auto *LC = dyn_cast<OMPLinearClause>(C))
4890         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
4891                                      B.NumIterations, *this, CurScope,
4892                                      DSAStack))
4893           return StmtError();
4894     }
4895   }
4896 
4897   getCurFunction()->setHasBranchProtectedScope();
4898   return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
4899                                  Clauses, AStmt, B, DSAStack->isCancelRegion());
4900 }
4901 
4902 StmtResult Sema::ActOnOpenMPForSimdDirective(
4903     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4904     SourceLocation EndLoc,
4905     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
4906   if (!AStmt)
4907     return StmtError();
4908 
4909   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4910   OMPLoopDirective::HelperExprs B;
4911   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4912   // define the nested loops number.
4913   unsigned NestedLoopCount =
4914       CheckOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
4915                       getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4916                       VarsWithImplicitDSA, B);
4917   if (NestedLoopCount == 0)
4918     return StmtError();
4919 
4920   assert((CurContext->isDependentContext() || B.builtAll()) &&
4921          "omp for simd loop exprs were not built");
4922 
4923   if (!CurContext->isDependentContext()) {
4924     // Finalize the clauses that need pre-built expressions for CodeGen.
4925     for (auto C : Clauses) {
4926       if (auto *LC = dyn_cast<OMPLinearClause>(C))
4927         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
4928                                      B.NumIterations, *this, CurScope,
4929                                      DSAStack))
4930           return StmtError();
4931     }
4932   }
4933 
4934   if (checkSimdlenSafelenSpecified(*this, Clauses))
4935     return StmtError();
4936 
4937   getCurFunction()->setHasBranchProtectedScope();
4938   return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
4939                                      Clauses, AStmt, B);
4940 }
4941 
4942 StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
4943                                               Stmt *AStmt,
4944                                               SourceLocation StartLoc,
4945                                               SourceLocation EndLoc) {
4946   if (!AStmt)
4947     return StmtError();
4948 
4949   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4950   auto BaseStmt = AStmt;
4951   while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
4952     BaseStmt = CS->getCapturedStmt();
4953   if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
4954     auto S = C->children();
4955     if (S.begin() == S.end())
4956       return StmtError();
4957     // All associated statements must be '#pragma omp section' except for
4958     // the first one.
4959     for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
4960       if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
4961         if (SectionStmt)
4962           Diag(SectionStmt->getLocStart(),
4963                diag::err_omp_sections_substmt_not_section);
4964         return StmtError();
4965       }
4966       cast<OMPSectionDirective>(SectionStmt)
4967           ->setHasCancel(DSAStack->isCancelRegion());
4968     }
4969   } else {
4970     Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt);
4971     return StmtError();
4972   }
4973 
4974   getCurFunction()->setHasBranchProtectedScope();
4975 
4976   return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
4977                                       DSAStack->isCancelRegion());
4978 }
4979 
4980 StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
4981                                              SourceLocation StartLoc,
4982                                              SourceLocation EndLoc) {
4983   if (!AStmt)
4984     return StmtError();
4985 
4986   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4987 
4988   getCurFunction()->setHasBranchProtectedScope();
4989   DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
4990 
4991   return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
4992                                      DSAStack->isCancelRegion());
4993 }
4994 
4995 StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
4996                                             Stmt *AStmt,
4997                                             SourceLocation StartLoc,
4998                                             SourceLocation EndLoc) {
4999   if (!AStmt)
5000     return StmtError();
5001 
5002   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5003 
5004   getCurFunction()->setHasBranchProtectedScope();
5005 
5006   // OpenMP [2.7.3, single Construct, Restrictions]
5007   // The copyprivate clause must not be used with the nowait clause.
5008   OMPClause *Nowait = nullptr;
5009   OMPClause *Copyprivate = nullptr;
5010   for (auto *Clause : Clauses) {
5011     if (Clause->getClauseKind() == OMPC_nowait)
5012       Nowait = Clause;
5013     else if (Clause->getClauseKind() == OMPC_copyprivate)
5014       Copyprivate = Clause;
5015     if (Copyprivate && Nowait) {
5016       Diag(Copyprivate->getLocStart(),
5017            diag::err_omp_single_copyprivate_with_nowait);
5018       Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here);
5019       return StmtError();
5020     }
5021   }
5022 
5023   return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
5024 }
5025 
5026 StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
5027                                             SourceLocation StartLoc,
5028                                             SourceLocation EndLoc) {
5029   if (!AStmt)
5030     return StmtError();
5031 
5032   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5033 
5034   getCurFunction()->setHasBranchProtectedScope();
5035 
5036   return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
5037 }
5038 
5039 StmtResult Sema::ActOnOpenMPCriticalDirective(
5040     const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
5041     Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
5042   if (!AStmt)
5043     return StmtError();
5044 
5045   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5046 
5047   bool ErrorFound = false;
5048   llvm::APSInt Hint;
5049   SourceLocation HintLoc;
5050   bool DependentHint = false;
5051   for (auto *C : Clauses) {
5052     if (C->getClauseKind() == OMPC_hint) {
5053       if (!DirName.getName()) {
5054         Diag(C->getLocStart(), diag::err_omp_hint_clause_no_name);
5055         ErrorFound = true;
5056       }
5057       Expr *E = cast<OMPHintClause>(C)->getHint();
5058       if (E->isTypeDependent() || E->isValueDependent() ||
5059           E->isInstantiationDependent())
5060         DependentHint = true;
5061       else {
5062         Hint = E->EvaluateKnownConstInt(Context);
5063         HintLoc = C->getLocStart();
5064       }
5065     }
5066   }
5067   if (ErrorFound)
5068     return StmtError();
5069   auto Pair = DSAStack->getCriticalWithHint(DirName);
5070   if (Pair.first && DirName.getName() && !DependentHint) {
5071     if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
5072       Diag(StartLoc, diag::err_omp_critical_with_hint);
5073       if (HintLoc.isValid()) {
5074         Diag(HintLoc, diag::note_omp_critical_hint_here)
5075             << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
5076       } else
5077         Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
5078       if (auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
5079         Diag(C->getLocStart(), diag::note_omp_critical_hint_here)
5080             << 1
5081             << C->getHint()->EvaluateKnownConstInt(Context).toString(
5082                    /*Radix=*/10, /*Signed=*/false);
5083       } else
5084         Diag(Pair.first->getLocStart(), diag::note_omp_critical_no_hint) << 1;
5085     }
5086   }
5087 
5088   getCurFunction()->setHasBranchProtectedScope();
5089 
5090   auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
5091                                            Clauses, AStmt);
5092   if (!Pair.first && DirName.getName() && !DependentHint)
5093     DSAStack->addCriticalWithHint(Dir, Hint);
5094   return Dir;
5095 }
5096 
5097 StmtResult Sema::ActOnOpenMPParallelForDirective(
5098     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5099     SourceLocation EndLoc,
5100     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5101   if (!AStmt)
5102     return StmtError();
5103 
5104   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5105   // 1.2.2 OpenMP Language Terminology
5106   // Structured block - An executable statement with a single entry at the
5107   // top and a single exit at the bottom.
5108   // The point of exit cannot be a branch out of the structured block.
5109   // longjmp() and throw() must not violate the entry/exit criteria.
5110   CS->getCapturedDecl()->setNothrow();
5111 
5112   OMPLoopDirective::HelperExprs B;
5113   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5114   // define the nested loops number.
5115   unsigned NestedLoopCount =
5116       CheckOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
5117                       getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5118                       VarsWithImplicitDSA, B);
5119   if (NestedLoopCount == 0)
5120     return StmtError();
5121 
5122   assert((CurContext->isDependentContext() || B.builtAll()) &&
5123          "omp parallel for loop exprs were not built");
5124 
5125   if (!CurContext->isDependentContext()) {
5126     // Finalize the clauses that need pre-built expressions for CodeGen.
5127     for (auto C : Clauses) {
5128       if (auto *LC = dyn_cast<OMPLinearClause>(C))
5129         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
5130                                      B.NumIterations, *this, CurScope,
5131                                      DSAStack))
5132           return StmtError();
5133     }
5134   }
5135 
5136   getCurFunction()->setHasBranchProtectedScope();
5137   return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
5138                                          NestedLoopCount, Clauses, AStmt, B,
5139                                          DSAStack->isCancelRegion());
5140 }
5141 
5142 StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
5143     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5144     SourceLocation EndLoc,
5145     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5146   if (!AStmt)
5147     return StmtError();
5148 
5149   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5150   // 1.2.2 OpenMP Language Terminology
5151   // Structured block - An executable statement with a single entry at the
5152   // top and a single exit at the bottom.
5153   // The point of exit cannot be a branch out of the structured block.
5154   // longjmp() and throw() must not violate the entry/exit criteria.
5155   CS->getCapturedDecl()->setNothrow();
5156 
5157   OMPLoopDirective::HelperExprs B;
5158   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5159   // define the nested loops number.
5160   unsigned NestedLoopCount =
5161       CheckOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
5162                       getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5163                       VarsWithImplicitDSA, B);
5164   if (NestedLoopCount == 0)
5165     return StmtError();
5166 
5167   if (!CurContext->isDependentContext()) {
5168     // Finalize the clauses that need pre-built expressions for CodeGen.
5169     for (auto C : Clauses) {
5170       if (auto *LC = dyn_cast<OMPLinearClause>(C))
5171         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
5172                                      B.NumIterations, *this, CurScope,
5173                                      DSAStack))
5174           return StmtError();
5175     }
5176   }
5177 
5178   if (checkSimdlenSafelenSpecified(*this, Clauses))
5179     return StmtError();
5180 
5181   getCurFunction()->setHasBranchProtectedScope();
5182   return OMPParallelForSimdDirective::Create(
5183       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
5184 }
5185 
5186 StmtResult
5187 Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
5188                                            Stmt *AStmt, SourceLocation StartLoc,
5189                                            SourceLocation EndLoc) {
5190   if (!AStmt)
5191     return StmtError();
5192 
5193   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5194   auto BaseStmt = AStmt;
5195   while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
5196     BaseStmt = CS->getCapturedStmt();
5197   if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
5198     auto S = C->children();
5199     if (S.begin() == S.end())
5200       return StmtError();
5201     // All associated statements must be '#pragma omp section' except for
5202     // the first one.
5203     for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
5204       if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
5205         if (SectionStmt)
5206           Diag(SectionStmt->getLocStart(),
5207                diag::err_omp_parallel_sections_substmt_not_section);
5208         return StmtError();
5209       }
5210       cast<OMPSectionDirective>(SectionStmt)
5211           ->setHasCancel(DSAStack->isCancelRegion());
5212     }
5213   } else {
5214     Diag(AStmt->getLocStart(),
5215          diag::err_omp_parallel_sections_not_compound_stmt);
5216     return StmtError();
5217   }
5218 
5219   getCurFunction()->setHasBranchProtectedScope();
5220 
5221   return OMPParallelSectionsDirective::Create(
5222       Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
5223 }
5224 
5225 StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
5226                                           Stmt *AStmt, SourceLocation StartLoc,
5227                                           SourceLocation EndLoc) {
5228   if (!AStmt)
5229     return StmtError();
5230 
5231   auto *CS = cast<CapturedStmt>(AStmt);
5232   // 1.2.2 OpenMP Language Terminology
5233   // Structured block - An executable statement with a single entry at the
5234   // top and a single exit at the bottom.
5235   // The point of exit cannot be a branch out of the structured block.
5236   // longjmp() and throw() must not violate the entry/exit criteria.
5237   CS->getCapturedDecl()->setNothrow();
5238 
5239   getCurFunction()->setHasBranchProtectedScope();
5240 
5241   return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
5242                                   DSAStack->isCancelRegion());
5243 }
5244 
5245 StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
5246                                                SourceLocation EndLoc) {
5247   return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
5248 }
5249 
5250 StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
5251                                              SourceLocation EndLoc) {
5252   return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
5253 }
5254 
5255 StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
5256                                               SourceLocation EndLoc) {
5257   return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
5258 }
5259 
5260 StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
5261                                                Stmt *AStmt,
5262                                                SourceLocation StartLoc,
5263                                                SourceLocation EndLoc) {
5264   if (!AStmt)
5265     return StmtError();
5266 
5267   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5268 
5269   getCurFunction()->setHasBranchProtectedScope();
5270 
5271   return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses,
5272                                        AStmt,
5273                                        DSAStack->getTaskgroupReductionRef());
5274 }
5275 
5276 StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
5277                                            SourceLocation StartLoc,
5278                                            SourceLocation EndLoc) {
5279   assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
5280   return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
5281 }
5282 
5283 StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
5284                                              Stmt *AStmt,
5285                                              SourceLocation StartLoc,
5286                                              SourceLocation EndLoc) {
5287   OMPClause *DependFound = nullptr;
5288   OMPClause *DependSourceClause = nullptr;
5289   OMPClause *DependSinkClause = nullptr;
5290   bool ErrorFound = false;
5291   OMPThreadsClause *TC = nullptr;
5292   OMPSIMDClause *SC = nullptr;
5293   for (auto *C : Clauses) {
5294     if (auto *DC = dyn_cast<OMPDependClause>(C)) {
5295       DependFound = C;
5296       if (DC->getDependencyKind() == OMPC_DEPEND_source) {
5297         if (DependSourceClause) {
5298           Diag(C->getLocStart(), diag::err_omp_more_one_clause)
5299               << getOpenMPDirectiveName(OMPD_ordered)
5300               << getOpenMPClauseName(OMPC_depend) << 2;
5301           ErrorFound = true;
5302         } else
5303           DependSourceClause = C;
5304         if (DependSinkClause) {
5305           Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
5306               << 0;
5307           ErrorFound = true;
5308         }
5309       } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
5310         if (DependSourceClause) {
5311           Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
5312               << 1;
5313           ErrorFound = true;
5314         }
5315         DependSinkClause = C;
5316       }
5317     } else if (C->getClauseKind() == OMPC_threads)
5318       TC = cast<OMPThreadsClause>(C);
5319     else if (C->getClauseKind() == OMPC_simd)
5320       SC = cast<OMPSIMDClause>(C);
5321   }
5322   if (!ErrorFound && !SC &&
5323       isOpenMPSimdDirective(DSAStack->getParentDirective())) {
5324     // OpenMP [2.8.1,simd Construct, Restrictions]
5325     // An ordered construct with the simd clause is the only OpenMP construct
5326     // that can appear in the simd region.
5327     Diag(StartLoc, diag::err_omp_prohibited_region_simd);
5328     ErrorFound = true;
5329   } else if (DependFound && (TC || SC)) {
5330     Diag(DependFound->getLocStart(), diag::err_omp_depend_clause_thread_simd)
5331         << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
5332     ErrorFound = true;
5333   } else if (DependFound && !DSAStack->getParentOrderedRegionParam()) {
5334     Diag(DependFound->getLocStart(),
5335          diag::err_omp_ordered_directive_without_param);
5336     ErrorFound = true;
5337   } else if (TC || Clauses.empty()) {
5338     if (auto *Param = DSAStack->getParentOrderedRegionParam()) {
5339       SourceLocation ErrLoc = TC ? TC->getLocStart() : StartLoc;
5340       Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
5341           << (TC != nullptr);
5342       Diag(Param->getLocStart(), diag::note_omp_ordered_param);
5343       ErrorFound = true;
5344     }
5345   }
5346   if ((!AStmt && !DependFound) || ErrorFound)
5347     return StmtError();
5348 
5349   if (AStmt) {
5350     assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5351 
5352     getCurFunction()->setHasBranchProtectedScope();
5353   }
5354 
5355   return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
5356 }
5357 
5358 namespace {
5359 /// \brief Helper class for checking expression in 'omp atomic [update]'
5360 /// construct.
5361 class OpenMPAtomicUpdateChecker {
5362   /// \brief Error results for atomic update expressions.
5363   enum ExprAnalysisErrorCode {
5364     /// \brief A statement is not an expression statement.
5365     NotAnExpression,
5366     /// \brief Expression is not builtin binary or unary operation.
5367     NotABinaryOrUnaryExpression,
5368     /// \brief Unary operation is not post-/pre- increment/decrement operation.
5369     NotAnUnaryIncDecExpression,
5370     /// \brief An expression is not of scalar type.
5371     NotAScalarType,
5372     /// \brief A binary operation is not an assignment operation.
5373     NotAnAssignmentOp,
5374     /// \brief RHS part of the binary operation is not a binary expression.
5375     NotABinaryExpression,
5376     /// \brief RHS part is not additive/multiplicative/shift/biwise binary
5377     /// expression.
5378     NotABinaryOperator,
5379     /// \brief RHS binary operation does not have reference to the updated LHS
5380     /// part.
5381     NotAnUpdateExpression,
5382     /// \brief No errors is found.
5383     NoError
5384   };
5385   /// \brief Reference to Sema.
5386   Sema &SemaRef;
5387   /// \brief A location for note diagnostics (when error is found).
5388   SourceLocation NoteLoc;
5389   /// \brief 'x' lvalue part of the source atomic expression.
5390   Expr *X;
5391   /// \brief 'expr' rvalue part of the source atomic expression.
5392   Expr *E;
5393   /// \brief Helper expression of the form
5394   /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
5395   /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
5396   Expr *UpdateExpr;
5397   /// \brief Is 'x' a LHS in a RHS part of full update expression. It is
5398   /// important for non-associative operations.
5399   bool IsXLHSInRHSPart;
5400   BinaryOperatorKind Op;
5401   SourceLocation OpLoc;
5402   /// \brief true if the source expression is a postfix unary operation, false
5403   /// if it is a prefix unary operation.
5404   bool IsPostfixUpdate;
5405 
5406 public:
5407   OpenMPAtomicUpdateChecker(Sema &SemaRef)
5408       : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
5409         IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
5410   /// \brief Check specified statement that it is suitable for 'atomic update'
5411   /// constructs and extract 'x', 'expr' and Operation from the original
5412   /// expression. If DiagId and NoteId == 0, then only check is performed
5413   /// without error notification.
5414   /// \param DiagId Diagnostic which should be emitted if error is found.
5415   /// \param NoteId Diagnostic note for the main error message.
5416   /// \return true if statement is not an update expression, false otherwise.
5417   bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
5418   /// \brief Return the 'x' lvalue part of the source atomic expression.
5419   Expr *getX() const { return X; }
5420   /// \brief Return the 'expr' rvalue part of the source atomic expression.
5421   Expr *getExpr() const { return E; }
5422   /// \brief Return the update expression used in calculation of the updated
5423   /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
5424   /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
5425   Expr *getUpdateExpr() const { return UpdateExpr; }
5426   /// \brief Return true if 'x' is LHS in RHS part of full update expression,
5427   /// false otherwise.
5428   bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
5429 
5430   /// \brief true if the source expression is a postfix unary operation, false
5431   /// if it is a prefix unary operation.
5432   bool isPostfixUpdate() const { return IsPostfixUpdate; }
5433 
5434 private:
5435   bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
5436                             unsigned NoteId = 0);
5437 };
5438 } // namespace
5439 
5440 bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
5441     BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
5442   ExprAnalysisErrorCode ErrorFound = NoError;
5443   SourceLocation ErrorLoc, NoteLoc;
5444   SourceRange ErrorRange, NoteRange;
5445   // Allowed constructs are:
5446   //  x = x binop expr;
5447   //  x = expr binop x;
5448   if (AtomicBinOp->getOpcode() == BO_Assign) {
5449     X = AtomicBinOp->getLHS();
5450     if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
5451             AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
5452       if (AtomicInnerBinOp->isMultiplicativeOp() ||
5453           AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
5454           AtomicInnerBinOp->isBitwiseOp()) {
5455         Op = AtomicInnerBinOp->getOpcode();
5456         OpLoc = AtomicInnerBinOp->getOperatorLoc();
5457         auto *LHS = AtomicInnerBinOp->getLHS();
5458         auto *RHS = AtomicInnerBinOp->getRHS();
5459         llvm::FoldingSetNodeID XId, LHSId, RHSId;
5460         X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
5461                                           /*Canonical=*/true);
5462         LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
5463                                             /*Canonical=*/true);
5464         RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
5465                                             /*Canonical=*/true);
5466         if (XId == LHSId) {
5467           E = RHS;
5468           IsXLHSInRHSPart = true;
5469         } else if (XId == RHSId) {
5470           E = LHS;
5471           IsXLHSInRHSPart = false;
5472         } else {
5473           ErrorLoc = AtomicInnerBinOp->getExprLoc();
5474           ErrorRange = AtomicInnerBinOp->getSourceRange();
5475           NoteLoc = X->getExprLoc();
5476           NoteRange = X->getSourceRange();
5477           ErrorFound = NotAnUpdateExpression;
5478         }
5479       } else {
5480         ErrorLoc = AtomicInnerBinOp->getExprLoc();
5481         ErrorRange = AtomicInnerBinOp->getSourceRange();
5482         NoteLoc = AtomicInnerBinOp->getOperatorLoc();
5483         NoteRange = SourceRange(NoteLoc, NoteLoc);
5484         ErrorFound = NotABinaryOperator;
5485       }
5486     } else {
5487       NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
5488       NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
5489       ErrorFound = NotABinaryExpression;
5490     }
5491   } else {
5492     ErrorLoc = AtomicBinOp->getExprLoc();
5493     ErrorRange = AtomicBinOp->getSourceRange();
5494     NoteLoc = AtomicBinOp->getOperatorLoc();
5495     NoteRange = SourceRange(NoteLoc, NoteLoc);
5496     ErrorFound = NotAnAssignmentOp;
5497   }
5498   if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
5499     SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
5500     SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
5501     return true;
5502   } else if (SemaRef.CurContext->isDependentContext())
5503     E = X = UpdateExpr = nullptr;
5504   return ErrorFound != NoError;
5505 }
5506 
5507 bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
5508                                                unsigned NoteId) {
5509   ExprAnalysisErrorCode ErrorFound = NoError;
5510   SourceLocation ErrorLoc, NoteLoc;
5511   SourceRange ErrorRange, NoteRange;
5512   // Allowed constructs are:
5513   //  x++;
5514   //  x--;
5515   //  ++x;
5516   //  --x;
5517   //  x binop= expr;
5518   //  x = x binop expr;
5519   //  x = expr binop x;
5520   if (auto *AtomicBody = dyn_cast<Expr>(S)) {
5521     AtomicBody = AtomicBody->IgnoreParenImpCasts();
5522     if (AtomicBody->getType()->isScalarType() ||
5523         AtomicBody->isInstantiationDependent()) {
5524       if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
5525               AtomicBody->IgnoreParenImpCasts())) {
5526         // Check for Compound Assignment Operation
5527         Op = BinaryOperator::getOpForCompoundAssignment(
5528             AtomicCompAssignOp->getOpcode());
5529         OpLoc = AtomicCompAssignOp->getOperatorLoc();
5530         E = AtomicCompAssignOp->getRHS();
5531         X = AtomicCompAssignOp->getLHS()->IgnoreParens();
5532         IsXLHSInRHSPart = true;
5533       } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
5534                      AtomicBody->IgnoreParenImpCasts())) {
5535         // Check for Binary Operation
5536         if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
5537           return true;
5538       } else if (auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
5539                      AtomicBody->IgnoreParenImpCasts())) {
5540         // Check for Unary Operation
5541         if (AtomicUnaryOp->isIncrementDecrementOp()) {
5542           IsPostfixUpdate = AtomicUnaryOp->isPostfix();
5543           Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
5544           OpLoc = AtomicUnaryOp->getOperatorLoc();
5545           X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
5546           E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
5547           IsXLHSInRHSPart = true;
5548         } else {
5549           ErrorFound = NotAnUnaryIncDecExpression;
5550           ErrorLoc = AtomicUnaryOp->getExprLoc();
5551           ErrorRange = AtomicUnaryOp->getSourceRange();
5552           NoteLoc = AtomicUnaryOp->getOperatorLoc();
5553           NoteRange = SourceRange(NoteLoc, NoteLoc);
5554         }
5555       } else if (!AtomicBody->isInstantiationDependent()) {
5556         ErrorFound = NotABinaryOrUnaryExpression;
5557         NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
5558         NoteRange = ErrorRange = AtomicBody->getSourceRange();
5559       }
5560     } else {
5561       ErrorFound = NotAScalarType;
5562       NoteLoc = ErrorLoc = AtomicBody->getLocStart();
5563       NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5564     }
5565   } else {
5566     ErrorFound = NotAnExpression;
5567     NoteLoc = ErrorLoc = S->getLocStart();
5568     NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5569   }
5570   if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
5571     SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
5572     SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
5573     return true;
5574   } else if (SemaRef.CurContext->isDependentContext())
5575     E = X = UpdateExpr = nullptr;
5576   if (ErrorFound == NoError && E && X) {
5577     // Build an update expression of form 'OpaqueValueExpr(x) binop
5578     // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
5579     // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
5580     auto *OVEX = new (SemaRef.getASTContext())
5581         OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
5582     auto *OVEExpr = new (SemaRef.getASTContext())
5583         OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
5584     auto Update =
5585         SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
5586                                    IsXLHSInRHSPart ? OVEExpr : OVEX);
5587     if (Update.isInvalid())
5588       return true;
5589     Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
5590                                                Sema::AA_Casting);
5591     if (Update.isInvalid())
5592       return true;
5593     UpdateExpr = Update.get();
5594   }
5595   return ErrorFound != NoError;
5596 }
5597 
5598 StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
5599                                             Stmt *AStmt,
5600                                             SourceLocation StartLoc,
5601                                             SourceLocation EndLoc) {
5602   if (!AStmt)
5603     return StmtError();
5604 
5605   auto *CS = cast<CapturedStmt>(AStmt);
5606   // 1.2.2 OpenMP Language Terminology
5607   // Structured block - An executable statement with a single entry at the
5608   // top and a single exit at the bottom.
5609   // The point of exit cannot be a branch out of the structured block.
5610   // longjmp() and throw() must not violate the entry/exit criteria.
5611   OpenMPClauseKind AtomicKind = OMPC_unknown;
5612   SourceLocation AtomicKindLoc;
5613   for (auto *C : Clauses) {
5614     if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
5615         C->getClauseKind() == OMPC_update ||
5616         C->getClauseKind() == OMPC_capture) {
5617       if (AtomicKind != OMPC_unknown) {
5618         Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses)
5619             << SourceRange(C->getLocStart(), C->getLocEnd());
5620         Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
5621             << getOpenMPClauseName(AtomicKind);
5622       } else {
5623         AtomicKind = C->getClauseKind();
5624         AtomicKindLoc = C->getLocStart();
5625       }
5626     }
5627   }
5628 
5629   auto Body = CS->getCapturedStmt();
5630   if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
5631     Body = EWC->getSubExpr();
5632 
5633   Expr *X = nullptr;
5634   Expr *V = nullptr;
5635   Expr *E = nullptr;
5636   Expr *UE = nullptr;
5637   bool IsXLHSInRHSPart = false;
5638   bool IsPostfixUpdate = false;
5639   // OpenMP [2.12.6, atomic Construct]
5640   // In the next expressions:
5641   // * x and v (as applicable) are both l-value expressions with scalar type.
5642   // * During the execution of an atomic region, multiple syntactic
5643   // occurrences of x must designate the same storage location.
5644   // * Neither of v and expr (as applicable) may access the storage location
5645   // designated by x.
5646   // * Neither of x and expr (as applicable) may access the storage location
5647   // designated by v.
5648   // * expr is an expression with scalar type.
5649   // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
5650   // * binop, binop=, ++, and -- are not overloaded operators.
5651   // * The expression x binop expr must be numerically equivalent to x binop
5652   // (expr). This requirement is satisfied if the operators in expr have
5653   // precedence greater than binop, or by using parentheses around expr or
5654   // subexpressions of expr.
5655   // * The expression expr binop x must be numerically equivalent to (expr)
5656   // binop x. This requirement is satisfied if the operators in expr have
5657   // precedence equal to or greater than binop, or by using parentheses around
5658   // expr or subexpressions of expr.
5659   // * For forms that allow multiple occurrences of x, the number of times
5660   // that x is evaluated is unspecified.
5661   if (AtomicKind == OMPC_read) {
5662     enum {
5663       NotAnExpression,
5664       NotAnAssignmentOp,
5665       NotAScalarType,
5666       NotAnLValue,
5667       NoError
5668     } ErrorFound = NoError;
5669     SourceLocation ErrorLoc, NoteLoc;
5670     SourceRange ErrorRange, NoteRange;
5671     // If clause is read:
5672     //  v = x;
5673     if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5674       auto *AtomicBinOp =
5675           dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5676       if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
5677         X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
5678         V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
5679         if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
5680             (V->isInstantiationDependent() || V->getType()->isScalarType())) {
5681           if (!X->isLValue() || !V->isLValue()) {
5682             auto NotLValueExpr = X->isLValue() ? V : X;
5683             ErrorFound = NotAnLValue;
5684             ErrorLoc = AtomicBinOp->getExprLoc();
5685             ErrorRange = AtomicBinOp->getSourceRange();
5686             NoteLoc = NotLValueExpr->getExprLoc();
5687             NoteRange = NotLValueExpr->getSourceRange();
5688           }
5689         } else if (!X->isInstantiationDependent() ||
5690                    !V->isInstantiationDependent()) {
5691           auto NotScalarExpr =
5692               (X->isInstantiationDependent() || X->getType()->isScalarType())
5693                   ? V
5694                   : X;
5695           ErrorFound = NotAScalarType;
5696           ErrorLoc = AtomicBinOp->getExprLoc();
5697           ErrorRange = AtomicBinOp->getSourceRange();
5698           NoteLoc = NotScalarExpr->getExprLoc();
5699           NoteRange = NotScalarExpr->getSourceRange();
5700         }
5701       } else if (!AtomicBody->isInstantiationDependent()) {
5702         ErrorFound = NotAnAssignmentOp;
5703         ErrorLoc = AtomicBody->getExprLoc();
5704         ErrorRange = AtomicBody->getSourceRange();
5705         NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5706                               : AtomicBody->getExprLoc();
5707         NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5708                                 : AtomicBody->getSourceRange();
5709       }
5710     } else {
5711       ErrorFound = NotAnExpression;
5712       NoteLoc = ErrorLoc = Body->getLocStart();
5713       NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5714     }
5715     if (ErrorFound != NoError) {
5716       Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
5717           << ErrorRange;
5718       Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
5719                                                       << NoteRange;
5720       return StmtError();
5721     } else if (CurContext->isDependentContext())
5722       V = X = nullptr;
5723   } else if (AtomicKind == OMPC_write) {
5724     enum {
5725       NotAnExpression,
5726       NotAnAssignmentOp,
5727       NotAScalarType,
5728       NotAnLValue,
5729       NoError
5730     } ErrorFound = NoError;
5731     SourceLocation ErrorLoc, NoteLoc;
5732     SourceRange ErrorRange, NoteRange;
5733     // If clause is write:
5734     //  x = expr;
5735     if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5736       auto *AtomicBinOp =
5737           dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5738       if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
5739         X = AtomicBinOp->getLHS();
5740         E = AtomicBinOp->getRHS();
5741         if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
5742             (E->isInstantiationDependent() || E->getType()->isScalarType())) {
5743           if (!X->isLValue()) {
5744             ErrorFound = NotAnLValue;
5745             ErrorLoc = AtomicBinOp->getExprLoc();
5746             ErrorRange = AtomicBinOp->getSourceRange();
5747             NoteLoc = X->getExprLoc();
5748             NoteRange = X->getSourceRange();
5749           }
5750         } else if (!X->isInstantiationDependent() ||
5751                    !E->isInstantiationDependent()) {
5752           auto NotScalarExpr =
5753               (X->isInstantiationDependent() || X->getType()->isScalarType())
5754                   ? E
5755                   : X;
5756           ErrorFound = NotAScalarType;
5757           ErrorLoc = AtomicBinOp->getExprLoc();
5758           ErrorRange = AtomicBinOp->getSourceRange();
5759           NoteLoc = NotScalarExpr->getExprLoc();
5760           NoteRange = NotScalarExpr->getSourceRange();
5761         }
5762       } else if (!AtomicBody->isInstantiationDependent()) {
5763         ErrorFound = NotAnAssignmentOp;
5764         ErrorLoc = AtomicBody->getExprLoc();
5765         ErrorRange = AtomicBody->getSourceRange();
5766         NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5767                               : AtomicBody->getExprLoc();
5768         NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5769                                 : AtomicBody->getSourceRange();
5770       }
5771     } else {
5772       ErrorFound = NotAnExpression;
5773       NoteLoc = ErrorLoc = Body->getLocStart();
5774       NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5775     }
5776     if (ErrorFound != NoError) {
5777       Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
5778           << ErrorRange;
5779       Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
5780                                                       << NoteRange;
5781       return StmtError();
5782     } else if (CurContext->isDependentContext())
5783       E = X = nullptr;
5784   } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
5785     // If clause is update:
5786     //  x++;
5787     //  x--;
5788     //  ++x;
5789     //  --x;
5790     //  x binop= expr;
5791     //  x = x binop expr;
5792     //  x = expr binop x;
5793     OpenMPAtomicUpdateChecker Checker(*this);
5794     if (Checker.checkStatement(
5795             Body, (AtomicKind == OMPC_update)
5796                       ? diag::err_omp_atomic_update_not_expression_statement
5797                       : diag::err_omp_atomic_not_expression_statement,
5798             diag::note_omp_atomic_update))
5799       return StmtError();
5800     if (!CurContext->isDependentContext()) {
5801       E = Checker.getExpr();
5802       X = Checker.getX();
5803       UE = Checker.getUpdateExpr();
5804       IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
5805     }
5806   } else if (AtomicKind == OMPC_capture) {
5807     enum {
5808       NotAnAssignmentOp,
5809       NotACompoundStatement,
5810       NotTwoSubstatements,
5811       NotASpecificExpression,
5812       NoError
5813     } ErrorFound = NoError;
5814     SourceLocation ErrorLoc, NoteLoc;
5815     SourceRange ErrorRange, NoteRange;
5816     if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5817       // If clause is a capture:
5818       //  v = x++;
5819       //  v = x--;
5820       //  v = ++x;
5821       //  v = --x;
5822       //  v = x binop= expr;
5823       //  v = x = x binop expr;
5824       //  v = x = expr binop x;
5825       auto *AtomicBinOp =
5826           dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5827       if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
5828         V = AtomicBinOp->getLHS();
5829         Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
5830         OpenMPAtomicUpdateChecker Checker(*this);
5831         if (Checker.checkStatement(
5832                 Body, diag::err_omp_atomic_capture_not_expression_statement,
5833                 diag::note_omp_atomic_update))
5834           return StmtError();
5835         E = Checker.getExpr();
5836         X = Checker.getX();
5837         UE = Checker.getUpdateExpr();
5838         IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
5839         IsPostfixUpdate = Checker.isPostfixUpdate();
5840       } else if (!AtomicBody->isInstantiationDependent()) {
5841         ErrorLoc = AtomicBody->getExprLoc();
5842         ErrorRange = AtomicBody->getSourceRange();
5843         NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5844                               : AtomicBody->getExprLoc();
5845         NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5846                                 : AtomicBody->getSourceRange();
5847         ErrorFound = NotAnAssignmentOp;
5848       }
5849       if (ErrorFound != NoError) {
5850         Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
5851             << ErrorRange;
5852         Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
5853         return StmtError();
5854       } else if (CurContext->isDependentContext()) {
5855         UE = V = E = X = nullptr;
5856       }
5857     } else {
5858       // If clause is a capture:
5859       //  { v = x; x = expr; }
5860       //  { v = x; x++; }
5861       //  { v = x; x--; }
5862       //  { v = x; ++x; }
5863       //  { v = x; --x; }
5864       //  { v = x; x binop= expr; }
5865       //  { v = x; x = x binop expr; }
5866       //  { v = x; x = expr binop x; }
5867       //  { x++; v = x; }
5868       //  { x--; v = x; }
5869       //  { ++x; v = x; }
5870       //  { --x; v = x; }
5871       //  { x binop= expr; v = x; }
5872       //  { x = x binop expr; v = x; }
5873       //  { x = expr binop x; v = x; }
5874       if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
5875         // Check that this is { expr1; expr2; }
5876         if (CS->size() == 2) {
5877           auto *First = CS->body_front();
5878           auto *Second = CS->body_back();
5879           if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
5880             First = EWC->getSubExpr()->IgnoreParenImpCasts();
5881           if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
5882             Second = EWC->getSubExpr()->IgnoreParenImpCasts();
5883           // Need to find what subexpression is 'v' and what is 'x'.
5884           OpenMPAtomicUpdateChecker Checker(*this);
5885           bool IsUpdateExprFound = !Checker.checkStatement(Second);
5886           BinaryOperator *BinOp = nullptr;
5887           if (IsUpdateExprFound) {
5888             BinOp = dyn_cast<BinaryOperator>(First);
5889             IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
5890           }
5891           if (IsUpdateExprFound && !CurContext->isDependentContext()) {
5892             //  { v = x; x++; }
5893             //  { v = x; x--; }
5894             //  { v = x; ++x; }
5895             //  { v = x; --x; }
5896             //  { v = x; x binop= expr; }
5897             //  { v = x; x = x binop expr; }
5898             //  { v = x; x = expr binop x; }
5899             // Check that the first expression has form v = x.
5900             auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
5901             llvm::FoldingSetNodeID XId, PossibleXId;
5902             Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
5903             PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
5904             IsUpdateExprFound = XId == PossibleXId;
5905             if (IsUpdateExprFound) {
5906               V = BinOp->getLHS();
5907               X = Checker.getX();
5908               E = Checker.getExpr();
5909               UE = Checker.getUpdateExpr();
5910               IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
5911               IsPostfixUpdate = true;
5912             }
5913           }
5914           if (!IsUpdateExprFound) {
5915             IsUpdateExprFound = !Checker.checkStatement(First);
5916             BinOp = nullptr;
5917             if (IsUpdateExprFound) {
5918               BinOp = dyn_cast<BinaryOperator>(Second);
5919               IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
5920             }
5921             if (IsUpdateExprFound && !CurContext->isDependentContext()) {
5922               //  { x++; v = x; }
5923               //  { x--; v = x; }
5924               //  { ++x; v = x; }
5925               //  { --x; v = x; }
5926               //  { x binop= expr; v = x; }
5927               //  { x = x binop expr; v = x; }
5928               //  { x = expr binop x; v = x; }
5929               // Check that the second expression has form v = x.
5930               auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
5931               llvm::FoldingSetNodeID XId, PossibleXId;
5932               Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
5933               PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
5934               IsUpdateExprFound = XId == PossibleXId;
5935               if (IsUpdateExprFound) {
5936                 V = BinOp->getLHS();
5937                 X = Checker.getX();
5938                 E = Checker.getExpr();
5939                 UE = Checker.getUpdateExpr();
5940                 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
5941                 IsPostfixUpdate = false;
5942               }
5943             }
5944           }
5945           if (!IsUpdateExprFound) {
5946             //  { v = x; x = expr; }
5947             auto *FirstExpr = dyn_cast<Expr>(First);
5948             auto *SecondExpr = dyn_cast<Expr>(Second);
5949             if (!FirstExpr || !SecondExpr ||
5950                 !(FirstExpr->isInstantiationDependent() ||
5951                   SecondExpr->isInstantiationDependent())) {
5952               auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
5953               if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
5954                 ErrorFound = NotAnAssignmentOp;
5955                 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
5956                                                 : First->getLocStart();
5957                 NoteRange = ErrorRange = FirstBinOp
5958                                              ? FirstBinOp->getSourceRange()
5959                                              : SourceRange(ErrorLoc, ErrorLoc);
5960               } else {
5961                 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
5962                 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
5963                   ErrorFound = NotAnAssignmentOp;
5964                   NoteLoc = ErrorLoc = SecondBinOp
5965                                            ? SecondBinOp->getOperatorLoc()
5966                                            : Second->getLocStart();
5967                   NoteRange = ErrorRange =
5968                       SecondBinOp ? SecondBinOp->getSourceRange()
5969                                   : SourceRange(ErrorLoc, ErrorLoc);
5970                 } else {
5971                   auto *PossibleXRHSInFirst =
5972                       FirstBinOp->getRHS()->IgnoreParenImpCasts();
5973                   auto *PossibleXLHSInSecond =
5974                       SecondBinOp->getLHS()->IgnoreParenImpCasts();
5975                   llvm::FoldingSetNodeID X1Id, X2Id;
5976                   PossibleXRHSInFirst->Profile(X1Id, Context,
5977                                                /*Canonical=*/true);
5978                   PossibleXLHSInSecond->Profile(X2Id, Context,
5979                                                 /*Canonical=*/true);
5980                   IsUpdateExprFound = X1Id == X2Id;
5981                   if (IsUpdateExprFound) {
5982                     V = FirstBinOp->getLHS();
5983                     X = SecondBinOp->getLHS();
5984                     E = SecondBinOp->getRHS();
5985                     UE = nullptr;
5986                     IsXLHSInRHSPart = false;
5987                     IsPostfixUpdate = true;
5988                   } else {
5989                     ErrorFound = NotASpecificExpression;
5990                     ErrorLoc = FirstBinOp->getExprLoc();
5991                     ErrorRange = FirstBinOp->getSourceRange();
5992                     NoteLoc = SecondBinOp->getLHS()->getExprLoc();
5993                     NoteRange = SecondBinOp->getRHS()->getSourceRange();
5994                   }
5995                 }
5996               }
5997             }
5998           }
5999         } else {
6000           NoteLoc = ErrorLoc = Body->getLocStart();
6001           NoteRange = ErrorRange =
6002               SourceRange(Body->getLocStart(), Body->getLocStart());
6003           ErrorFound = NotTwoSubstatements;
6004         }
6005       } else {
6006         NoteLoc = ErrorLoc = Body->getLocStart();
6007         NoteRange = ErrorRange =
6008             SourceRange(Body->getLocStart(), Body->getLocStart());
6009         ErrorFound = NotACompoundStatement;
6010       }
6011       if (ErrorFound != NoError) {
6012         Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
6013             << ErrorRange;
6014         Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
6015         return StmtError();
6016       } else if (CurContext->isDependentContext()) {
6017         UE = V = E = X = nullptr;
6018       }
6019     }
6020   }
6021 
6022   getCurFunction()->setHasBranchProtectedScope();
6023 
6024   return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
6025                                     X, V, E, UE, IsXLHSInRHSPart,
6026                                     IsPostfixUpdate);
6027 }
6028 
6029 StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
6030                                             Stmt *AStmt,
6031                                             SourceLocation StartLoc,
6032                                             SourceLocation EndLoc) {
6033   if (!AStmt)
6034     return StmtError();
6035 
6036   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6037   // 1.2.2 OpenMP Language Terminology
6038   // Structured block - An executable statement with a single entry at the
6039   // top and a single exit at the bottom.
6040   // The point of exit cannot be a branch out of the structured block.
6041   // longjmp() and throw() must not violate the entry/exit criteria.
6042   CS->getCapturedDecl()->setNothrow();
6043 
6044   // OpenMP [2.16, Nesting of Regions]
6045   // If specified, a teams construct must be contained within a target
6046   // construct. That target construct must contain no statements or directives
6047   // outside of the teams construct.
6048   if (DSAStack->hasInnerTeamsRegion()) {
6049     auto S = AStmt->IgnoreContainers(/*IgnoreCaptured*/ true);
6050     bool OMPTeamsFound = true;
6051     if (auto *CS = dyn_cast<CompoundStmt>(S)) {
6052       auto I = CS->body_begin();
6053       while (I != CS->body_end()) {
6054         auto *OED = dyn_cast<OMPExecutableDirective>(*I);
6055         if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) {
6056           OMPTeamsFound = false;
6057           break;
6058         }
6059         ++I;
6060       }
6061       assert(I != CS->body_end() && "Not found statement");
6062       S = *I;
6063     } else {
6064       auto *OED = dyn_cast<OMPExecutableDirective>(S);
6065       OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
6066     }
6067     if (!OMPTeamsFound) {
6068       Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
6069       Diag(DSAStack->getInnerTeamsRegionLoc(),
6070            diag::note_omp_nested_teams_construct_here);
6071       Diag(S->getLocStart(), diag::note_omp_nested_statement_here)
6072           << isa<OMPExecutableDirective>(S);
6073       return StmtError();
6074     }
6075   }
6076 
6077   getCurFunction()->setHasBranchProtectedScope();
6078 
6079   return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
6080 }
6081 
6082 StmtResult
6083 Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
6084                                          Stmt *AStmt, SourceLocation StartLoc,
6085                                          SourceLocation EndLoc) {
6086   if (!AStmt)
6087     return StmtError();
6088 
6089   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6090   // 1.2.2 OpenMP Language Terminology
6091   // Structured block - An executable statement with a single entry at the
6092   // top and a single exit at the bottom.
6093   // The point of exit cannot be a branch out of the structured block.
6094   // longjmp() and throw() must not violate the entry/exit criteria.
6095   CS->getCapturedDecl()->setNothrow();
6096 
6097   getCurFunction()->setHasBranchProtectedScope();
6098 
6099   return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
6100                                             AStmt);
6101 }
6102 
6103 StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
6104     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6105     SourceLocation EndLoc,
6106     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6107   if (!AStmt)
6108     return StmtError();
6109 
6110   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6111   // 1.2.2 OpenMP Language Terminology
6112   // Structured block - An executable statement with a single entry at the
6113   // top and a single exit at the bottom.
6114   // The point of exit cannot be a branch out of the structured block.
6115   // longjmp() and throw() must not violate the entry/exit criteria.
6116   CS->getCapturedDecl()->setNothrow();
6117 
6118   OMPLoopDirective::HelperExprs B;
6119   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6120   // define the nested loops number.
6121   unsigned NestedLoopCount =
6122       CheckOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
6123                       getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6124                       VarsWithImplicitDSA, B);
6125   if (NestedLoopCount == 0)
6126     return StmtError();
6127 
6128   assert((CurContext->isDependentContext() || B.builtAll()) &&
6129          "omp target parallel for loop exprs were not built");
6130 
6131   if (!CurContext->isDependentContext()) {
6132     // Finalize the clauses that need pre-built expressions for CodeGen.
6133     for (auto C : Clauses) {
6134       if (auto *LC = dyn_cast<OMPLinearClause>(C))
6135         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6136                                      B.NumIterations, *this, CurScope,
6137                                      DSAStack))
6138           return StmtError();
6139     }
6140   }
6141 
6142   getCurFunction()->setHasBranchProtectedScope();
6143   return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
6144                                                NestedLoopCount, Clauses, AStmt,
6145                                                B, DSAStack->isCancelRegion());
6146 }
6147 
6148 /// Check for existence of a map clause in the list of clauses.
6149 static bool hasClauses(ArrayRef<OMPClause *> Clauses,
6150                        const OpenMPClauseKind K) {
6151   return llvm::any_of(
6152       Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; });
6153 }
6154 
6155 template <typename... Params>
6156 static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K,
6157                        const Params... ClauseTypes) {
6158   return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...);
6159 }
6160 
6161 StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
6162                                                 Stmt *AStmt,
6163                                                 SourceLocation StartLoc,
6164                                                 SourceLocation EndLoc) {
6165   if (!AStmt)
6166     return StmtError();
6167 
6168   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6169 
6170   // OpenMP [2.10.1, Restrictions, p. 97]
6171   // At least one map clause must appear on the directive.
6172   if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr)) {
6173     Diag(StartLoc, diag::err_omp_no_clause_for_directive)
6174         << "'map' or 'use_device_ptr'"
6175         << getOpenMPDirectiveName(OMPD_target_data);
6176     return StmtError();
6177   }
6178 
6179   getCurFunction()->setHasBranchProtectedScope();
6180 
6181   return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
6182                                         AStmt);
6183 }
6184 
6185 StmtResult
6186 Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
6187                                           SourceLocation StartLoc,
6188                                           SourceLocation EndLoc) {
6189   // OpenMP [2.10.2, Restrictions, p. 99]
6190   // At least one map clause must appear on the directive.
6191   if (!hasClauses(Clauses, OMPC_map)) {
6192     Diag(StartLoc, diag::err_omp_no_clause_for_directive)
6193         << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data);
6194     return StmtError();
6195   }
6196 
6197   return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc,
6198                                              Clauses);
6199 }
6200 
6201 StmtResult
6202 Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
6203                                          SourceLocation StartLoc,
6204                                          SourceLocation EndLoc) {
6205   // OpenMP [2.10.3, Restrictions, p. 102]
6206   // At least one map clause must appear on the directive.
6207   if (!hasClauses(Clauses, OMPC_map)) {
6208     Diag(StartLoc, diag::err_omp_no_clause_for_directive)
6209         << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data);
6210     return StmtError();
6211   }
6212 
6213   return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses);
6214 }
6215 
6216 StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
6217                                                   SourceLocation StartLoc,
6218                                                   SourceLocation EndLoc) {
6219   if (!hasClauses(Clauses, OMPC_to, OMPC_from)) {
6220     Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
6221     return StmtError();
6222   }
6223   return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses);
6224 }
6225 
6226 StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
6227                                            Stmt *AStmt, SourceLocation StartLoc,
6228                                            SourceLocation EndLoc) {
6229   if (!AStmt)
6230     return StmtError();
6231 
6232   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6233   // 1.2.2 OpenMP Language Terminology
6234   // Structured block - An executable statement with a single entry at the
6235   // top and a single exit at the bottom.
6236   // The point of exit cannot be a branch out of the structured block.
6237   // longjmp() and throw() must not violate the entry/exit criteria.
6238   CS->getCapturedDecl()->setNothrow();
6239 
6240   getCurFunction()->setHasBranchProtectedScope();
6241 
6242   return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
6243 }
6244 
6245 StmtResult
6246 Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
6247                                             SourceLocation EndLoc,
6248                                             OpenMPDirectiveKind CancelRegion) {
6249   if (DSAStack->isParentNowaitRegion()) {
6250     Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
6251     return StmtError();
6252   }
6253   if (DSAStack->isParentOrderedRegion()) {
6254     Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
6255     return StmtError();
6256   }
6257   return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
6258                                                CancelRegion);
6259 }
6260 
6261 StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
6262                                             SourceLocation StartLoc,
6263                                             SourceLocation EndLoc,
6264                                             OpenMPDirectiveKind CancelRegion) {
6265   if (DSAStack->isParentNowaitRegion()) {
6266     Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
6267     return StmtError();
6268   }
6269   if (DSAStack->isParentOrderedRegion()) {
6270     Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
6271     return StmtError();
6272   }
6273   DSAStack->setParentCancelRegion(/*Cancel=*/true);
6274   return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
6275                                     CancelRegion);
6276 }
6277 
6278 static bool checkGrainsizeNumTasksClauses(Sema &S,
6279                                           ArrayRef<OMPClause *> Clauses) {
6280   OMPClause *PrevClause = nullptr;
6281   bool ErrorFound = false;
6282   for (auto *C : Clauses) {
6283     if (C->getClauseKind() == OMPC_grainsize ||
6284         C->getClauseKind() == OMPC_num_tasks) {
6285       if (!PrevClause)
6286         PrevClause = C;
6287       else if (PrevClause->getClauseKind() != C->getClauseKind()) {
6288         S.Diag(C->getLocStart(),
6289                diag::err_omp_grainsize_num_tasks_mutually_exclusive)
6290             << getOpenMPClauseName(C->getClauseKind())
6291             << getOpenMPClauseName(PrevClause->getClauseKind());
6292         S.Diag(PrevClause->getLocStart(),
6293                diag::note_omp_previous_grainsize_num_tasks)
6294             << getOpenMPClauseName(PrevClause->getClauseKind());
6295         ErrorFound = true;
6296       }
6297     }
6298   }
6299   return ErrorFound;
6300 }
6301 
6302 static bool checkReductionClauseWithNogroup(Sema &S,
6303                                             ArrayRef<OMPClause *> Clauses) {
6304   OMPClause *ReductionClause = nullptr;
6305   OMPClause *NogroupClause = nullptr;
6306   for (auto *C : Clauses) {
6307     if (C->getClauseKind() == OMPC_reduction) {
6308       ReductionClause = C;
6309       if (NogroupClause)
6310         break;
6311       continue;
6312     }
6313     if (C->getClauseKind() == OMPC_nogroup) {
6314       NogroupClause = C;
6315       if (ReductionClause)
6316         break;
6317       continue;
6318     }
6319   }
6320   if (ReductionClause && NogroupClause) {
6321     S.Diag(ReductionClause->getLocStart(), diag::err_omp_reduction_with_nogroup)
6322         << SourceRange(NogroupClause->getLocStart(),
6323                        NogroupClause->getLocEnd());
6324     return true;
6325   }
6326   return false;
6327 }
6328 
6329 StmtResult Sema::ActOnOpenMPTaskLoopDirective(
6330     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6331     SourceLocation EndLoc,
6332     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6333   if (!AStmt)
6334     return StmtError();
6335 
6336   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6337   OMPLoopDirective::HelperExprs B;
6338   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6339   // define the nested loops number.
6340   unsigned NestedLoopCount =
6341       CheckOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
6342                       /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
6343                       VarsWithImplicitDSA, B);
6344   if (NestedLoopCount == 0)
6345     return StmtError();
6346 
6347   assert((CurContext->isDependentContext() || B.builtAll()) &&
6348          "omp for loop exprs were not built");
6349 
6350   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6351   // The grainsize clause and num_tasks clause are mutually exclusive and may
6352   // not appear on the same taskloop directive.
6353   if (checkGrainsizeNumTasksClauses(*this, Clauses))
6354     return StmtError();
6355   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6356   // If a reduction clause is present on the taskloop directive, the nogroup
6357   // clause must not be specified.
6358   if (checkReductionClauseWithNogroup(*this, Clauses))
6359     return StmtError();
6360 
6361   getCurFunction()->setHasBranchProtectedScope();
6362   return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
6363                                       NestedLoopCount, Clauses, AStmt, B);
6364 }
6365 
6366 StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
6367     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6368     SourceLocation EndLoc,
6369     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6370   if (!AStmt)
6371     return StmtError();
6372 
6373   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6374   OMPLoopDirective::HelperExprs B;
6375   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6376   // define the nested loops number.
6377   unsigned NestedLoopCount =
6378       CheckOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
6379                       /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
6380                       VarsWithImplicitDSA, B);
6381   if (NestedLoopCount == 0)
6382     return StmtError();
6383 
6384   assert((CurContext->isDependentContext() || B.builtAll()) &&
6385          "omp for loop exprs were not built");
6386 
6387   if (!CurContext->isDependentContext()) {
6388     // Finalize the clauses that need pre-built expressions for CodeGen.
6389     for (auto C : Clauses) {
6390       if (auto *LC = dyn_cast<OMPLinearClause>(C))
6391         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6392                                      B.NumIterations, *this, CurScope,
6393                                      DSAStack))
6394           return StmtError();
6395     }
6396   }
6397 
6398   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6399   // The grainsize clause and num_tasks clause are mutually exclusive and may
6400   // not appear on the same taskloop directive.
6401   if (checkGrainsizeNumTasksClauses(*this, Clauses))
6402     return StmtError();
6403   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6404   // If a reduction clause is present on the taskloop directive, the nogroup
6405   // clause must not be specified.
6406   if (checkReductionClauseWithNogroup(*this, Clauses))
6407     return StmtError();
6408 
6409   getCurFunction()->setHasBranchProtectedScope();
6410   return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
6411                                           NestedLoopCount, Clauses, AStmt, B);
6412 }
6413 
6414 StmtResult Sema::ActOnOpenMPDistributeDirective(
6415     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6416     SourceLocation EndLoc,
6417     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6418   if (!AStmt)
6419     return StmtError();
6420 
6421   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6422   OMPLoopDirective::HelperExprs B;
6423   // In presence of clause 'collapse' with number of loops, it will
6424   // define the nested loops number.
6425   unsigned NestedLoopCount =
6426       CheckOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
6427                       nullptr /*ordered not a clause on distribute*/, AStmt,
6428                       *this, *DSAStack, VarsWithImplicitDSA, B);
6429   if (NestedLoopCount == 0)
6430     return StmtError();
6431 
6432   assert((CurContext->isDependentContext() || B.builtAll()) &&
6433          "omp for loop exprs were not built");
6434 
6435   getCurFunction()->setHasBranchProtectedScope();
6436   return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
6437                                         NestedLoopCount, Clauses, AStmt, B);
6438 }
6439 
6440 StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
6441     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6442     SourceLocation EndLoc,
6443     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6444   if (!AStmt)
6445     return StmtError();
6446 
6447   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6448   // 1.2.2 OpenMP Language Terminology
6449   // Structured block - An executable statement with a single entry at the
6450   // top and a single exit at the bottom.
6451   // The point of exit cannot be a branch out of the structured block.
6452   // longjmp() and throw() must not violate the entry/exit criteria.
6453   CS->getCapturedDecl()->setNothrow();
6454 
6455   OMPLoopDirective::HelperExprs B;
6456   // In presence of clause 'collapse' with number of loops, it will
6457   // define the nested loops number.
6458   unsigned NestedLoopCount = CheckOpenMPLoop(
6459       OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
6460       nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6461       VarsWithImplicitDSA, B);
6462   if (NestedLoopCount == 0)
6463     return StmtError();
6464 
6465   assert((CurContext->isDependentContext() || B.builtAll()) &&
6466          "omp for loop exprs were not built");
6467 
6468   getCurFunction()->setHasBranchProtectedScope();
6469   return OMPDistributeParallelForDirective::Create(
6470       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6471 }
6472 
6473 StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
6474     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6475     SourceLocation EndLoc,
6476     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6477   if (!AStmt)
6478     return StmtError();
6479 
6480   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6481   // 1.2.2 OpenMP Language Terminology
6482   // Structured block - An executable statement with a single entry at the
6483   // top and a single exit at the bottom.
6484   // The point of exit cannot be a branch out of the structured block.
6485   // longjmp() and throw() must not violate the entry/exit criteria.
6486   CS->getCapturedDecl()->setNothrow();
6487 
6488   OMPLoopDirective::HelperExprs B;
6489   // In presence of clause 'collapse' with number of loops, it will
6490   // define the nested loops number.
6491   unsigned NestedLoopCount = CheckOpenMPLoop(
6492       OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
6493       nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6494       VarsWithImplicitDSA, B);
6495   if (NestedLoopCount == 0)
6496     return StmtError();
6497 
6498   assert((CurContext->isDependentContext() || B.builtAll()) &&
6499          "omp for loop exprs were not built");
6500 
6501   if (checkSimdlenSafelenSpecified(*this, Clauses))
6502     return StmtError();
6503 
6504   getCurFunction()->setHasBranchProtectedScope();
6505   return OMPDistributeParallelForSimdDirective::Create(
6506       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6507 }
6508 
6509 StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
6510     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6511     SourceLocation EndLoc,
6512     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6513   if (!AStmt)
6514     return StmtError();
6515 
6516   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6517   // 1.2.2 OpenMP Language Terminology
6518   // Structured block - An executable statement with a single entry at the
6519   // top and a single exit at the bottom.
6520   // The point of exit cannot be a branch out of the structured block.
6521   // longjmp() and throw() must not violate the entry/exit criteria.
6522   CS->getCapturedDecl()->setNothrow();
6523 
6524   OMPLoopDirective::HelperExprs B;
6525   // In presence of clause 'collapse' with number of loops, it will
6526   // define the nested loops number.
6527   unsigned NestedLoopCount =
6528       CheckOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
6529                       nullptr /*ordered not a clause on distribute*/, AStmt,
6530                       *this, *DSAStack, VarsWithImplicitDSA, B);
6531   if (NestedLoopCount == 0)
6532     return StmtError();
6533 
6534   assert((CurContext->isDependentContext() || B.builtAll()) &&
6535          "omp for loop exprs were not built");
6536 
6537   if (checkSimdlenSafelenSpecified(*this, Clauses))
6538     return StmtError();
6539 
6540   getCurFunction()->setHasBranchProtectedScope();
6541   return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
6542                                             NestedLoopCount, Clauses, AStmt, B);
6543 }
6544 
6545 StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
6546     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6547     SourceLocation EndLoc,
6548     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6549   if (!AStmt)
6550     return StmtError();
6551 
6552   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6553   // 1.2.2 OpenMP Language Terminology
6554   // Structured block - An executable statement with a single entry at the
6555   // top and a single exit at the bottom.
6556   // The point of exit cannot be a branch out of the structured block.
6557   // longjmp() and throw() must not violate the entry/exit criteria.
6558   CS->getCapturedDecl()->setNothrow();
6559 
6560   OMPLoopDirective::HelperExprs B;
6561   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6562   // define the nested loops number.
6563   unsigned NestedLoopCount = CheckOpenMPLoop(
6564       OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
6565       getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6566       VarsWithImplicitDSA, B);
6567   if (NestedLoopCount == 0)
6568     return StmtError();
6569 
6570   assert((CurContext->isDependentContext() || B.builtAll()) &&
6571          "omp target parallel for simd loop exprs were not built");
6572 
6573   if (!CurContext->isDependentContext()) {
6574     // Finalize the clauses that need pre-built expressions for CodeGen.
6575     for (auto C : Clauses) {
6576       if (auto *LC = dyn_cast<OMPLinearClause>(C))
6577         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6578                                      B.NumIterations, *this, CurScope,
6579                                      DSAStack))
6580           return StmtError();
6581     }
6582   }
6583   if (checkSimdlenSafelenSpecified(*this, Clauses))
6584     return StmtError();
6585 
6586   getCurFunction()->setHasBranchProtectedScope();
6587   return OMPTargetParallelForSimdDirective::Create(
6588       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6589 }
6590 
6591 StmtResult Sema::ActOnOpenMPTargetSimdDirective(
6592     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6593     SourceLocation EndLoc,
6594     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6595   if (!AStmt)
6596     return StmtError();
6597 
6598   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6599   // 1.2.2 OpenMP Language Terminology
6600   // Structured block - An executable statement with a single entry at the
6601   // top and a single exit at the bottom.
6602   // The point of exit cannot be a branch out of the structured block.
6603   // longjmp() and throw() must not violate the entry/exit criteria.
6604   CS->getCapturedDecl()->setNothrow();
6605 
6606   OMPLoopDirective::HelperExprs B;
6607   // In presence of clause 'collapse' with number of loops, it will define the
6608   // nested loops number.
6609   unsigned NestedLoopCount =
6610       CheckOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
6611                       getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6612                       VarsWithImplicitDSA, B);
6613   if (NestedLoopCount == 0)
6614     return StmtError();
6615 
6616   assert((CurContext->isDependentContext() || B.builtAll()) &&
6617          "omp target simd loop exprs were not built");
6618 
6619   if (!CurContext->isDependentContext()) {
6620     // Finalize the clauses that need pre-built expressions for CodeGen.
6621     for (auto C : Clauses) {
6622       if (auto *LC = dyn_cast<OMPLinearClause>(C))
6623         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6624                                      B.NumIterations, *this, CurScope,
6625                                      DSAStack))
6626           return StmtError();
6627     }
6628   }
6629 
6630   if (checkSimdlenSafelenSpecified(*this, Clauses))
6631     return StmtError();
6632 
6633   getCurFunction()->setHasBranchProtectedScope();
6634   return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
6635                                         NestedLoopCount, Clauses, AStmt, B);
6636 }
6637 
6638 StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
6639     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6640     SourceLocation EndLoc,
6641     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6642   if (!AStmt)
6643     return StmtError();
6644 
6645   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6646   // 1.2.2 OpenMP Language Terminology
6647   // Structured block - An executable statement with a single entry at the
6648   // top and a single exit at the bottom.
6649   // The point of exit cannot be a branch out of the structured block.
6650   // longjmp() and throw() must not violate the entry/exit criteria.
6651   CS->getCapturedDecl()->setNothrow();
6652 
6653   OMPLoopDirective::HelperExprs B;
6654   // In presence of clause 'collapse' with number of loops, it will
6655   // define the nested loops number.
6656   unsigned NestedLoopCount =
6657       CheckOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
6658                       nullptr /*ordered not a clause on distribute*/, AStmt,
6659                       *this, *DSAStack, VarsWithImplicitDSA, B);
6660   if (NestedLoopCount == 0)
6661     return StmtError();
6662 
6663   assert((CurContext->isDependentContext() || B.builtAll()) &&
6664          "omp teams distribute loop exprs were not built");
6665 
6666   getCurFunction()->setHasBranchProtectedScope();
6667   return OMPTeamsDistributeDirective::Create(
6668       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6669 }
6670 
6671 StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
6672     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6673     SourceLocation EndLoc,
6674     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6675   if (!AStmt)
6676     return StmtError();
6677 
6678   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6679   // 1.2.2 OpenMP Language Terminology
6680   // Structured block - An executable statement with a single entry at the
6681   // top and a single exit at the bottom.
6682   // The point of exit cannot be a branch out of the structured block.
6683   // longjmp() and throw() must not violate the entry/exit criteria.
6684   CS->getCapturedDecl()->setNothrow();
6685 
6686   OMPLoopDirective::HelperExprs B;
6687   // In presence of clause 'collapse' with number of loops, it will
6688   // define the nested loops number.
6689   unsigned NestedLoopCount = CheckOpenMPLoop(
6690       OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
6691       nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6692       VarsWithImplicitDSA, B);
6693 
6694   if (NestedLoopCount == 0)
6695     return StmtError();
6696 
6697   assert((CurContext->isDependentContext() || B.builtAll()) &&
6698          "omp teams distribute simd loop exprs were not built");
6699 
6700   if (!CurContext->isDependentContext()) {
6701     // Finalize the clauses that need pre-built expressions for CodeGen.
6702     for (auto C : Clauses) {
6703       if (auto *LC = dyn_cast<OMPLinearClause>(C))
6704         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6705                                      B.NumIterations, *this, CurScope,
6706                                      DSAStack))
6707           return StmtError();
6708     }
6709   }
6710 
6711   if (checkSimdlenSafelenSpecified(*this, Clauses))
6712     return StmtError();
6713 
6714   getCurFunction()->setHasBranchProtectedScope();
6715   return OMPTeamsDistributeSimdDirective::Create(
6716       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6717 }
6718 
6719 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
6720     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6721     SourceLocation EndLoc,
6722     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6723   if (!AStmt)
6724     return StmtError();
6725 
6726   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6727   // 1.2.2 OpenMP Language Terminology
6728   // Structured block - An executable statement with a single entry at the
6729   // top and a single exit at the bottom.
6730   // The point of exit cannot be a branch out of the structured block.
6731   // longjmp() and throw() must not violate the entry/exit criteria.
6732   CS->getCapturedDecl()->setNothrow();
6733 
6734   OMPLoopDirective::HelperExprs B;
6735   // In presence of clause 'collapse' with number of loops, it will
6736   // define the nested loops number.
6737   auto NestedLoopCount = CheckOpenMPLoop(
6738       OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
6739       nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6740       VarsWithImplicitDSA, B);
6741 
6742   if (NestedLoopCount == 0)
6743     return StmtError();
6744 
6745   assert((CurContext->isDependentContext() || B.builtAll()) &&
6746          "omp for loop exprs were not built");
6747 
6748   if (!CurContext->isDependentContext()) {
6749     // Finalize the clauses that need pre-built expressions for CodeGen.
6750     for (auto C : Clauses) {
6751       if (auto *LC = dyn_cast<OMPLinearClause>(C))
6752         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6753                                      B.NumIterations, *this, CurScope,
6754                                      DSAStack))
6755           return StmtError();
6756     }
6757   }
6758 
6759   if (checkSimdlenSafelenSpecified(*this, Clauses))
6760     return StmtError();
6761 
6762   getCurFunction()->setHasBranchProtectedScope();
6763   return OMPTeamsDistributeParallelForSimdDirective::Create(
6764       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6765 }
6766 
6767 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
6768     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6769     SourceLocation EndLoc,
6770     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6771   if (!AStmt)
6772     return StmtError();
6773 
6774   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6775   // 1.2.2 OpenMP Language Terminology
6776   // Structured block - An executable statement with a single entry at the
6777   // top and a single exit at the bottom.
6778   // The point of exit cannot be a branch out of the structured block.
6779   // longjmp() and throw() must not violate the entry/exit criteria.
6780   CS->getCapturedDecl()->setNothrow();
6781 
6782   OMPLoopDirective::HelperExprs B;
6783   // In presence of clause 'collapse' with number of loops, it will
6784   // define the nested loops number.
6785   unsigned NestedLoopCount = CheckOpenMPLoop(
6786       OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
6787       nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6788       VarsWithImplicitDSA, B);
6789 
6790   if (NestedLoopCount == 0)
6791     return StmtError();
6792 
6793   assert((CurContext->isDependentContext() || B.builtAll()) &&
6794          "omp for loop exprs were not built");
6795 
6796   if (!CurContext->isDependentContext()) {
6797     // Finalize the clauses that need pre-built expressions for CodeGen.
6798     for (auto C : Clauses) {
6799       if (auto *LC = dyn_cast<OMPLinearClause>(C))
6800         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6801                                      B.NumIterations, *this, CurScope,
6802                                      DSAStack))
6803           return StmtError();
6804     }
6805   }
6806 
6807   getCurFunction()->setHasBranchProtectedScope();
6808   return OMPTeamsDistributeParallelForDirective::Create(
6809       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6810 }
6811 
6812 StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
6813                                                  Stmt *AStmt,
6814                                                  SourceLocation StartLoc,
6815                                                  SourceLocation EndLoc) {
6816   if (!AStmt)
6817     return StmtError();
6818 
6819   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6820   // 1.2.2 OpenMP Language Terminology
6821   // Structured block - An executable statement with a single entry at the
6822   // top and a single exit at the bottom.
6823   // The point of exit cannot be a branch out of the structured block.
6824   // longjmp() and throw() must not violate the entry/exit criteria.
6825   CS->getCapturedDecl()->setNothrow();
6826 
6827   getCurFunction()->setHasBranchProtectedScope();
6828 
6829   return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
6830                                          AStmt);
6831 }
6832 
6833 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
6834     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6835     SourceLocation EndLoc,
6836     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6837   if (!AStmt)
6838     return StmtError();
6839 
6840   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6841   // 1.2.2 OpenMP Language Terminology
6842   // Structured block - An executable statement with a single entry at the
6843   // top and a single exit at the bottom.
6844   // The point of exit cannot be a branch out of the structured block.
6845   // longjmp() and throw() must not violate the entry/exit criteria.
6846   CS->getCapturedDecl()->setNothrow();
6847 
6848   OMPLoopDirective::HelperExprs B;
6849   // In presence of clause 'collapse' with number of loops, it will
6850   // define the nested loops number.
6851   auto NestedLoopCount = CheckOpenMPLoop(
6852       OMPD_target_teams_distribute,
6853       getCollapseNumberExpr(Clauses),
6854       nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6855       VarsWithImplicitDSA, B);
6856   if (NestedLoopCount == 0)
6857     return StmtError();
6858 
6859   assert((CurContext->isDependentContext() || B.builtAll()) &&
6860          "omp target teams distribute loop exprs were not built");
6861 
6862   getCurFunction()->setHasBranchProtectedScope();
6863   return OMPTargetTeamsDistributeDirective::Create(
6864       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6865 }
6866 
6867 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
6868     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6869     SourceLocation EndLoc,
6870     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6871   if (!AStmt)
6872     return StmtError();
6873 
6874   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6875   // 1.2.2 OpenMP Language Terminology
6876   // Structured block - An executable statement with a single entry at the
6877   // top and a single exit at the bottom.
6878   // The point of exit cannot be a branch out of the structured block.
6879   // longjmp() and throw() must not violate the entry/exit criteria.
6880   CS->getCapturedDecl()->setNothrow();
6881 
6882   OMPLoopDirective::HelperExprs B;
6883   // In presence of clause 'collapse' with number of loops, it will
6884   // define the nested loops number.
6885   auto NestedLoopCount = CheckOpenMPLoop(
6886       OMPD_target_teams_distribute_parallel_for,
6887       getCollapseNumberExpr(Clauses),
6888       nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6889       VarsWithImplicitDSA, B);
6890   if (NestedLoopCount == 0)
6891     return StmtError();
6892 
6893   assert((CurContext->isDependentContext() || B.builtAll()) &&
6894          "omp target teams distribute parallel for loop exprs were not built");
6895 
6896   if (!CurContext->isDependentContext()) {
6897     // Finalize the clauses that need pre-built expressions for CodeGen.
6898     for (auto C : Clauses) {
6899       if (auto *LC = dyn_cast<OMPLinearClause>(C))
6900         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6901                                      B.NumIterations, *this, CurScope,
6902                                      DSAStack))
6903           return StmtError();
6904     }
6905   }
6906 
6907   getCurFunction()->setHasBranchProtectedScope();
6908   return OMPTargetTeamsDistributeParallelForDirective::Create(
6909       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6910 }
6911 
6912 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
6913     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6914     SourceLocation EndLoc,
6915     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6916   if (!AStmt)
6917     return StmtError();
6918 
6919   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6920   // 1.2.2 OpenMP Language Terminology
6921   // Structured block - An executable statement with a single entry at the
6922   // top and a single exit at the bottom.
6923   // The point of exit cannot be a branch out of the structured block.
6924   // longjmp() and throw() must not violate the entry/exit criteria.
6925   CS->getCapturedDecl()->setNothrow();
6926 
6927   OMPLoopDirective::HelperExprs B;
6928   // In presence of clause 'collapse' with number of loops, it will
6929   // define the nested loops number.
6930   auto NestedLoopCount = CheckOpenMPLoop(
6931       OMPD_target_teams_distribute_parallel_for_simd,
6932       getCollapseNumberExpr(Clauses),
6933       nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6934       VarsWithImplicitDSA, B);
6935   if (NestedLoopCount == 0)
6936     return StmtError();
6937 
6938   assert((CurContext->isDependentContext() || B.builtAll()) &&
6939          "omp target teams distribute parallel for simd loop exprs were not "
6940          "built");
6941 
6942   if (!CurContext->isDependentContext()) {
6943     // Finalize the clauses that need pre-built expressions for CodeGen.
6944     for (auto C : Clauses) {
6945       if (auto *LC = dyn_cast<OMPLinearClause>(C))
6946         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6947                                      B.NumIterations, *this, CurScope,
6948                                      DSAStack))
6949           return StmtError();
6950     }
6951   }
6952 
6953   getCurFunction()->setHasBranchProtectedScope();
6954   return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
6955       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6956 }
6957 
6958 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
6959     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6960     SourceLocation EndLoc,
6961     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6962   if (!AStmt)
6963     return StmtError();
6964 
6965   auto *CS = cast<CapturedStmt>(AStmt);
6966   // 1.2.2 OpenMP Language Terminology
6967   // Structured block - An executable statement with a single entry at the
6968   // top and a single exit at the bottom.
6969   // The point of exit cannot be a branch out of the structured block.
6970   // longjmp() and throw() must not violate the entry/exit criteria.
6971   CS->getCapturedDecl()->setNothrow();
6972 
6973   OMPLoopDirective::HelperExprs B;
6974   // In presence of clause 'collapse' with number of loops, it will
6975   // define the nested loops number.
6976   auto NestedLoopCount = CheckOpenMPLoop(
6977       OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
6978       nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6979       VarsWithImplicitDSA, B);
6980   if (NestedLoopCount == 0)
6981     return StmtError();
6982 
6983   assert((CurContext->isDependentContext() || B.builtAll()) &&
6984          "omp target teams distribute simd loop exprs were not built");
6985 
6986   getCurFunction()->setHasBranchProtectedScope();
6987   return OMPTargetTeamsDistributeSimdDirective::Create(
6988       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6989 }
6990 
6991 OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
6992                                              SourceLocation StartLoc,
6993                                              SourceLocation LParenLoc,
6994                                              SourceLocation EndLoc) {
6995   OMPClause *Res = nullptr;
6996   switch (Kind) {
6997   case OMPC_final:
6998     Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
6999     break;
7000   case OMPC_num_threads:
7001     Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
7002     break;
7003   case OMPC_safelen:
7004     Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
7005     break;
7006   case OMPC_simdlen:
7007     Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
7008     break;
7009   case OMPC_collapse:
7010     Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
7011     break;
7012   case OMPC_ordered:
7013     Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
7014     break;
7015   case OMPC_device:
7016     Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
7017     break;
7018   case OMPC_num_teams:
7019     Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
7020     break;
7021   case OMPC_thread_limit:
7022     Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
7023     break;
7024   case OMPC_priority:
7025     Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
7026     break;
7027   case OMPC_grainsize:
7028     Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
7029     break;
7030   case OMPC_num_tasks:
7031     Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
7032     break;
7033   case OMPC_hint:
7034     Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
7035     break;
7036   case OMPC_if:
7037   case OMPC_default:
7038   case OMPC_proc_bind:
7039   case OMPC_schedule:
7040   case OMPC_private:
7041   case OMPC_firstprivate:
7042   case OMPC_lastprivate:
7043   case OMPC_shared:
7044   case OMPC_reduction:
7045   case OMPC_task_reduction:
7046   case OMPC_in_reduction:
7047   case OMPC_linear:
7048   case OMPC_aligned:
7049   case OMPC_copyin:
7050   case OMPC_copyprivate:
7051   case OMPC_nowait:
7052   case OMPC_untied:
7053   case OMPC_mergeable:
7054   case OMPC_threadprivate:
7055   case OMPC_flush:
7056   case OMPC_read:
7057   case OMPC_write:
7058   case OMPC_update:
7059   case OMPC_capture:
7060   case OMPC_seq_cst:
7061   case OMPC_depend:
7062   case OMPC_threads:
7063   case OMPC_simd:
7064   case OMPC_map:
7065   case OMPC_nogroup:
7066   case OMPC_dist_schedule:
7067   case OMPC_defaultmap:
7068   case OMPC_unknown:
7069   case OMPC_uniform:
7070   case OMPC_to:
7071   case OMPC_from:
7072   case OMPC_use_device_ptr:
7073   case OMPC_is_device_ptr:
7074     llvm_unreachable("Clause is not allowed.");
7075   }
7076   return Res;
7077 }
7078 
7079 // An OpenMP directive such as 'target parallel' has two captured regions:
7080 // for the 'target' and 'parallel' respectively.  This function returns
7081 // the region in which to capture expressions associated with a clause.
7082 // A return value of OMPD_unknown signifies that the expression should not
7083 // be captured.
7084 static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
7085     OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
7086     OpenMPDirectiveKind NameModifier = OMPD_unknown) {
7087   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
7088 
7089   switch (CKind) {
7090   case OMPC_if:
7091     switch (DKind) {
7092     case OMPD_target_parallel:
7093       // If this clause applies to the nested 'parallel' region, capture within
7094       // the 'target' region, otherwise do not capture.
7095       if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
7096         CaptureRegion = OMPD_target;
7097       break;
7098     case OMPD_cancel:
7099     case OMPD_parallel:
7100     case OMPD_parallel_sections:
7101     case OMPD_parallel_for:
7102     case OMPD_parallel_for_simd:
7103     case OMPD_target:
7104     case OMPD_target_simd:
7105     case OMPD_target_parallel_for:
7106     case OMPD_target_parallel_for_simd:
7107     case OMPD_target_teams:
7108     case OMPD_target_teams_distribute:
7109     case OMPD_target_teams_distribute_simd:
7110     case OMPD_target_teams_distribute_parallel_for:
7111     case OMPD_target_teams_distribute_parallel_for_simd:
7112     case OMPD_teams_distribute_parallel_for:
7113     case OMPD_teams_distribute_parallel_for_simd:
7114     case OMPD_distribute_parallel_for:
7115     case OMPD_distribute_parallel_for_simd:
7116     case OMPD_task:
7117     case OMPD_taskloop:
7118     case OMPD_taskloop_simd:
7119     case OMPD_target_data:
7120     case OMPD_target_enter_data:
7121     case OMPD_target_exit_data:
7122     case OMPD_target_update:
7123       // Do not capture if-clause expressions.
7124       break;
7125     case OMPD_threadprivate:
7126     case OMPD_taskyield:
7127     case OMPD_barrier:
7128     case OMPD_taskwait:
7129     case OMPD_cancellation_point:
7130     case OMPD_flush:
7131     case OMPD_declare_reduction:
7132     case OMPD_declare_simd:
7133     case OMPD_declare_target:
7134     case OMPD_end_declare_target:
7135     case OMPD_teams:
7136     case OMPD_simd:
7137     case OMPD_for:
7138     case OMPD_for_simd:
7139     case OMPD_sections:
7140     case OMPD_section:
7141     case OMPD_single:
7142     case OMPD_master:
7143     case OMPD_critical:
7144     case OMPD_taskgroup:
7145     case OMPD_distribute:
7146     case OMPD_ordered:
7147     case OMPD_atomic:
7148     case OMPD_distribute_simd:
7149     case OMPD_teams_distribute:
7150     case OMPD_teams_distribute_simd:
7151       llvm_unreachable("Unexpected OpenMP directive with if-clause");
7152     case OMPD_unknown:
7153       llvm_unreachable("Unknown OpenMP directive");
7154     }
7155     break;
7156   case OMPC_num_threads:
7157     switch (DKind) {
7158     case OMPD_target_parallel:
7159       CaptureRegion = OMPD_target;
7160       break;
7161     case OMPD_cancel:
7162     case OMPD_parallel:
7163     case OMPD_parallel_sections:
7164     case OMPD_parallel_for:
7165     case OMPD_parallel_for_simd:
7166     case OMPD_target:
7167     case OMPD_target_simd:
7168     case OMPD_target_parallel_for:
7169     case OMPD_target_parallel_for_simd:
7170     case OMPD_target_teams:
7171     case OMPD_target_teams_distribute:
7172     case OMPD_target_teams_distribute_simd:
7173     case OMPD_target_teams_distribute_parallel_for:
7174     case OMPD_target_teams_distribute_parallel_for_simd:
7175     case OMPD_teams_distribute_parallel_for:
7176     case OMPD_teams_distribute_parallel_for_simd:
7177     case OMPD_distribute_parallel_for:
7178     case OMPD_distribute_parallel_for_simd:
7179     case OMPD_task:
7180     case OMPD_taskloop:
7181     case OMPD_taskloop_simd:
7182     case OMPD_target_data:
7183     case OMPD_target_enter_data:
7184     case OMPD_target_exit_data:
7185     case OMPD_target_update:
7186       // Do not capture num_threads-clause expressions.
7187       break;
7188     case OMPD_threadprivate:
7189     case OMPD_taskyield:
7190     case OMPD_barrier:
7191     case OMPD_taskwait:
7192     case OMPD_cancellation_point:
7193     case OMPD_flush:
7194     case OMPD_declare_reduction:
7195     case OMPD_declare_simd:
7196     case OMPD_declare_target:
7197     case OMPD_end_declare_target:
7198     case OMPD_teams:
7199     case OMPD_simd:
7200     case OMPD_for:
7201     case OMPD_for_simd:
7202     case OMPD_sections:
7203     case OMPD_section:
7204     case OMPD_single:
7205     case OMPD_master:
7206     case OMPD_critical:
7207     case OMPD_taskgroup:
7208     case OMPD_distribute:
7209     case OMPD_ordered:
7210     case OMPD_atomic:
7211     case OMPD_distribute_simd:
7212     case OMPD_teams_distribute:
7213     case OMPD_teams_distribute_simd:
7214       llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
7215     case OMPD_unknown:
7216       llvm_unreachable("Unknown OpenMP directive");
7217     }
7218     break;
7219   case OMPC_num_teams:
7220     switch (DKind) {
7221     case OMPD_target_teams:
7222       CaptureRegion = OMPD_target;
7223       break;
7224     case OMPD_cancel:
7225     case OMPD_parallel:
7226     case OMPD_parallel_sections:
7227     case OMPD_parallel_for:
7228     case OMPD_parallel_for_simd:
7229     case OMPD_target:
7230     case OMPD_target_simd:
7231     case OMPD_target_parallel:
7232     case OMPD_target_parallel_for:
7233     case OMPD_target_parallel_for_simd:
7234     case OMPD_target_teams_distribute:
7235     case OMPD_target_teams_distribute_simd:
7236     case OMPD_target_teams_distribute_parallel_for:
7237     case OMPD_target_teams_distribute_parallel_for_simd:
7238     case OMPD_teams_distribute_parallel_for:
7239     case OMPD_teams_distribute_parallel_for_simd:
7240     case OMPD_distribute_parallel_for:
7241     case OMPD_distribute_parallel_for_simd:
7242     case OMPD_task:
7243     case OMPD_taskloop:
7244     case OMPD_taskloop_simd:
7245     case OMPD_target_data:
7246     case OMPD_target_enter_data:
7247     case OMPD_target_exit_data:
7248     case OMPD_target_update:
7249     case OMPD_teams:
7250     case OMPD_teams_distribute:
7251     case OMPD_teams_distribute_simd:
7252       // Do not capture num_teams-clause expressions.
7253       break;
7254     case OMPD_threadprivate:
7255     case OMPD_taskyield:
7256     case OMPD_barrier:
7257     case OMPD_taskwait:
7258     case OMPD_cancellation_point:
7259     case OMPD_flush:
7260     case OMPD_declare_reduction:
7261     case OMPD_declare_simd:
7262     case OMPD_declare_target:
7263     case OMPD_end_declare_target:
7264     case OMPD_simd:
7265     case OMPD_for:
7266     case OMPD_for_simd:
7267     case OMPD_sections:
7268     case OMPD_section:
7269     case OMPD_single:
7270     case OMPD_master:
7271     case OMPD_critical:
7272     case OMPD_taskgroup:
7273     case OMPD_distribute:
7274     case OMPD_ordered:
7275     case OMPD_atomic:
7276     case OMPD_distribute_simd:
7277       llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
7278     case OMPD_unknown:
7279       llvm_unreachable("Unknown OpenMP directive");
7280     }
7281     break;
7282   case OMPC_thread_limit:
7283     switch (DKind) {
7284     case OMPD_target_teams:
7285       CaptureRegion = OMPD_target;
7286       break;
7287     case OMPD_cancel:
7288     case OMPD_parallel:
7289     case OMPD_parallel_sections:
7290     case OMPD_parallel_for:
7291     case OMPD_parallel_for_simd:
7292     case OMPD_target:
7293     case OMPD_target_simd:
7294     case OMPD_target_parallel:
7295     case OMPD_target_parallel_for:
7296     case OMPD_target_parallel_for_simd:
7297     case OMPD_target_teams_distribute:
7298     case OMPD_target_teams_distribute_simd:
7299     case OMPD_target_teams_distribute_parallel_for:
7300     case OMPD_target_teams_distribute_parallel_for_simd:
7301     case OMPD_teams_distribute_parallel_for:
7302     case OMPD_teams_distribute_parallel_for_simd:
7303     case OMPD_distribute_parallel_for:
7304     case OMPD_distribute_parallel_for_simd:
7305     case OMPD_task:
7306     case OMPD_taskloop:
7307     case OMPD_taskloop_simd:
7308     case OMPD_target_data:
7309     case OMPD_target_enter_data:
7310     case OMPD_target_exit_data:
7311     case OMPD_target_update:
7312     case OMPD_teams:
7313     case OMPD_teams_distribute:
7314     case OMPD_teams_distribute_simd:
7315       // Do not capture thread_limit-clause expressions.
7316       break;
7317     case OMPD_threadprivate:
7318     case OMPD_taskyield:
7319     case OMPD_barrier:
7320     case OMPD_taskwait:
7321     case OMPD_cancellation_point:
7322     case OMPD_flush:
7323     case OMPD_declare_reduction:
7324     case OMPD_declare_simd:
7325     case OMPD_declare_target:
7326     case OMPD_end_declare_target:
7327     case OMPD_simd:
7328     case OMPD_for:
7329     case OMPD_for_simd:
7330     case OMPD_sections:
7331     case OMPD_section:
7332     case OMPD_single:
7333     case OMPD_master:
7334     case OMPD_critical:
7335     case OMPD_taskgroup:
7336     case OMPD_distribute:
7337     case OMPD_ordered:
7338     case OMPD_atomic:
7339     case OMPD_distribute_simd:
7340       llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
7341     case OMPD_unknown:
7342       llvm_unreachable("Unknown OpenMP directive");
7343     }
7344     break;
7345   case OMPC_schedule:
7346   case OMPC_dist_schedule:
7347   case OMPC_firstprivate:
7348   case OMPC_lastprivate:
7349   case OMPC_reduction:
7350   case OMPC_task_reduction:
7351   case OMPC_in_reduction:
7352   case OMPC_linear:
7353   case OMPC_default:
7354   case OMPC_proc_bind:
7355   case OMPC_final:
7356   case OMPC_safelen:
7357   case OMPC_simdlen:
7358   case OMPC_collapse:
7359   case OMPC_private:
7360   case OMPC_shared:
7361   case OMPC_aligned:
7362   case OMPC_copyin:
7363   case OMPC_copyprivate:
7364   case OMPC_ordered:
7365   case OMPC_nowait:
7366   case OMPC_untied:
7367   case OMPC_mergeable:
7368   case OMPC_threadprivate:
7369   case OMPC_flush:
7370   case OMPC_read:
7371   case OMPC_write:
7372   case OMPC_update:
7373   case OMPC_capture:
7374   case OMPC_seq_cst:
7375   case OMPC_depend:
7376   case OMPC_device:
7377   case OMPC_threads:
7378   case OMPC_simd:
7379   case OMPC_map:
7380   case OMPC_priority:
7381   case OMPC_grainsize:
7382   case OMPC_nogroup:
7383   case OMPC_num_tasks:
7384   case OMPC_hint:
7385   case OMPC_defaultmap:
7386   case OMPC_unknown:
7387   case OMPC_uniform:
7388   case OMPC_to:
7389   case OMPC_from:
7390   case OMPC_use_device_ptr:
7391   case OMPC_is_device_ptr:
7392     llvm_unreachable("Unexpected OpenMP clause.");
7393   }
7394   return CaptureRegion;
7395 }
7396 
7397 OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
7398                                      Expr *Condition, SourceLocation StartLoc,
7399                                      SourceLocation LParenLoc,
7400                                      SourceLocation NameModifierLoc,
7401                                      SourceLocation ColonLoc,
7402                                      SourceLocation EndLoc) {
7403   Expr *ValExpr = Condition;
7404   Stmt *HelperValStmt = nullptr;
7405   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
7406   if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
7407       !Condition->isInstantiationDependent() &&
7408       !Condition->containsUnexpandedParameterPack()) {
7409     ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
7410     if (Val.isInvalid())
7411       return nullptr;
7412 
7413     ValExpr = MakeFullExpr(Val.get()).get();
7414 
7415     OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
7416     CaptureRegion =
7417         getOpenMPCaptureRegionForClause(DKind, OMPC_if, NameModifier);
7418     if (CaptureRegion != OMPD_unknown) {
7419       llvm::MapVector<Expr *, DeclRefExpr *> Captures;
7420       ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
7421       HelperValStmt = buildPreInits(Context, Captures);
7422     }
7423   }
7424 
7425   return new (Context)
7426       OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
7427                   LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
7428 }
7429 
7430 OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
7431                                         SourceLocation StartLoc,
7432                                         SourceLocation LParenLoc,
7433                                         SourceLocation EndLoc) {
7434   Expr *ValExpr = Condition;
7435   if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
7436       !Condition->isInstantiationDependent() &&
7437       !Condition->containsUnexpandedParameterPack()) {
7438     ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
7439     if (Val.isInvalid())
7440       return nullptr;
7441 
7442     ValExpr = MakeFullExpr(Val.get()).get();
7443   }
7444 
7445   return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
7446 }
7447 ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
7448                                                         Expr *Op) {
7449   if (!Op)
7450     return ExprError();
7451 
7452   class IntConvertDiagnoser : public ICEConvertDiagnoser {
7453   public:
7454     IntConvertDiagnoser()
7455         : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
7456     SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
7457                                          QualType T) override {
7458       return S.Diag(Loc, diag::err_omp_not_integral) << T;
7459     }
7460     SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
7461                                              QualType T) override {
7462       return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
7463     }
7464     SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
7465                                                QualType T,
7466                                                QualType ConvTy) override {
7467       return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
7468     }
7469     SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
7470                                            QualType ConvTy) override {
7471       return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
7472              << ConvTy->isEnumeralType() << ConvTy;
7473     }
7474     SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
7475                                             QualType T) override {
7476       return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
7477     }
7478     SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
7479                                         QualType ConvTy) override {
7480       return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
7481              << ConvTy->isEnumeralType() << ConvTy;
7482     }
7483     SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
7484                                              QualType) override {
7485       llvm_unreachable("conversion functions are permitted");
7486     }
7487   } ConvertDiagnoser;
7488   return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
7489 }
7490 
7491 static bool IsNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
7492                                       OpenMPClauseKind CKind,
7493                                       bool StrictlyPositive) {
7494   if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
7495       !ValExpr->isInstantiationDependent()) {
7496     SourceLocation Loc = ValExpr->getExprLoc();
7497     ExprResult Value =
7498         SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
7499     if (Value.isInvalid())
7500       return false;
7501 
7502     ValExpr = Value.get();
7503     // The expression must evaluate to a non-negative integer value.
7504     llvm::APSInt Result;
7505     if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
7506         Result.isSigned() &&
7507         !((!StrictlyPositive && Result.isNonNegative()) ||
7508           (StrictlyPositive && Result.isStrictlyPositive()))) {
7509       SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
7510           << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
7511           << ValExpr->getSourceRange();
7512       return false;
7513     }
7514   }
7515   return true;
7516 }
7517 
7518 OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
7519                                              SourceLocation StartLoc,
7520                                              SourceLocation LParenLoc,
7521                                              SourceLocation EndLoc) {
7522   Expr *ValExpr = NumThreads;
7523   Stmt *HelperValStmt = nullptr;
7524   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
7525 
7526   // OpenMP [2.5, Restrictions]
7527   //  The num_threads expression must evaluate to a positive integer value.
7528   if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
7529                                  /*StrictlyPositive=*/true))
7530     return nullptr;
7531 
7532   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
7533   CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads);
7534   if (CaptureRegion != OMPD_unknown) {
7535     llvm::MapVector<Expr *, DeclRefExpr *> Captures;
7536     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
7537     HelperValStmt = buildPreInits(Context, Captures);
7538   }
7539 
7540   return new (Context) OMPNumThreadsClause(
7541       ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
7542 }
7543 
7544 ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
7545                                                        OpenMPClauseKind CKind,
7546                                                        bool StrictlyPositive) {
7547   if (!E)
7548     return ExprError();
7549   if (E->isValueDependent() || E->isTypeDependent() ||
7550       E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
7551     return E;
7552   llvm::APSInt Result;
7553   ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
7554   if (ICE.isInvalid())
7555     return ExprError();
7556   if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
7557       (!StrictlyPositive && !Result.isNonNegative())) {
7558     Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
7559         << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
7560         << E->getSourceRange();
7561     return ExprError();
7562   }
7563   if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
7564     Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
7565         << E->getSourceRange();
7566     return ExprError();
7567   }
7568   if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
7569     DSAStack->setAssociatedLoops(Result.getExtValue());
7570   else if (CKind == OMPC_ordered)
7571     DSAStack->setAssociatedLoops(Result.getExtValue());
7572   return ICE;
7573 }
7574 
7575 OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
7576                                           SourceLocation LParenLoc,
7577                                           SourceLocation EndLoc) {
7578   // OpenMP [2.8.1, simd construct, Description]
7579   // The parameter of the safelen clause must be a constant
7580   // positive integer expression.
7581   ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
7582   if (Safelen.isInvalid())
7583     return nullptr;
7584   return new (Context)
7585       OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
7586 }
7587 
7588 OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
7589                                           SourceLocation LParenLoc,
7590                                           SourceLocation EndLoc) {
7591   // OpenMP [2.8.1, simd construct, Description]
7592   // The parameter of the simdlen clause must be a constant
7593   // positive integer expression.
7594   ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
7595   if (Simdlen.isInvalid())
7596     return nullptr;
7597   return new (Context)
7598       OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
7599 }
7600 
7601 OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
7602                                            SourceLocation StartLoc,
7603                                            SourceLocation LParenLoc,
7604                                            SourceLocation EndLoc) {
7605   // OpenMP [2.7.1, loop construct, Description]
7606   // OpenMP [2.8.1, simd construct, Description]
7607   // OpenMP [2.9.6, distribute construct, Description]
7608   // The parameter of the collapse clause must be a constant
7609   // positive integer expression.
7610   ExprResult NumForLoopsResult =
7611       VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
7612   if (NumForLoopsResult.isInvalid())
7613     return nullptr;
7614   return new (Context)
7615       OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
7616 }
7617 
7618 OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
7619                                           SourceLocation EndLoc,
7620                                           SourceLocation LParenLoc,
7621                                           Expr *NumForLoops) {
7622   // OpenMP [2.7.1, loop construct, Description]
7623   // OpenMP [2.8.1, simd construct, Description]
7624   // OpenMP [2.9.6, distribute construct, Description]
7625   // The parameter of the ordered clause must be a constant
7626   // positive integer expression if any.
7627   if (NumForLoops && LParenLoc.isValid()) {
7628     ExprResult NumForLoopsResult =
7629         VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
7630     if (NumForLoopsResult.isInvalid())
7631       return nullptr;
7632     NumForLoops = NumForLoopsResult.get();
7633   } else
7634     NumForLoops = nullptr;
7635   DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops);
7636   return new (Context)
7637       OMPOrderedClause(NumForLoops, StartLoc, LParenLoc, EndLoc);
7638 }
7639 
7640 OMPClause *Sema::ActOnOpenMPSimpleClause(
7641     OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
7642     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
7643   OMPClause *Res = nullptr;
7644   switch (Kind) {
7645   case OMPC_default:
7646     Res =
7647         ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
7648                                  ArgumentLoc, StartLoc, LParenLoc, EndLoc);
7649     break;
7650   case OMPC_proc_bind:
7651     Res = ActOnOpenMPProcBindClause(
7652         static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
7653         LParenLoc, EndLoc);
7654     break;
7655   case OMPC_if:
7656   case OMPC_final:
7657   case OMPC_num_threads:
7658   case OMPC_safelen:
7659   case OMPC_simdlen:
7660   case OMPC_collapse:
7661   case OMPC_schedule:
7662   case OMPC_private:
7663   case OMPC_firstprivate:
7664   case OMPC_lastprivate:
7665   case OMPC_shared:
7666   case OMPC_reduction:
7667   case OMPC_task_reduction:
7668   case OMPC_in_reduction:
7669   case OMPC_linear:
7670   case OMPC_aligned:
7671   case OMPC_copyin:
7672   case OMPC_copyprivate:
7673   case OMPC_ordered:
7674   case OMPC_nowait:
7675   case OMPC_untied:
7676   case OMPC_mergeable:
7677   case OMPC_threadprivate:
7678   case OMPC_flush:
7679   case OMPC_read:
7680   case OMPC_write:
7681   case OMPC_update:
7682   case OMPC_capture:
7683   case OMPC_seq_cst:
7684   case OMPC_depend:
7685   case OMPC_device:
7686   case OMPC_threads:
7687   case OMPC_simd:
7688   case OMPC_map:
7689   case OMPC_num_teams:
7690   case OMPC_thread_limit:
7691   case OMPC_priority:
7692   case OMPC_grainsize:
7693   case OMPC_nogroup:
7694   case OMPC_num_tasks:
7695   case OMPC_hint:
7696   case OMPC_dist_schedule:
7697   case OMPC_defaultmap:
7698   case OMPC_unknown:
7699   case OMPC_uniform:
7700   case OMPC_to:
7701   case OMPC_from:
7702   case OMPC_use_device_ptr:
7703   case OMPC_is_device_ptr:
7704     llvm_unreachable("Clause is not allowed.");
7705   }
7706   return Res;
7707 }
7708 
7709 static std::string
7710 getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
7711                         ArrayRef<unsigned> Exclude = llvm::None) {
7712   std::string Values;
7713   unsigned Bound = Last >= 2 ? Last - 2 : 0;
7714   unsigned Skipped = Exclude.size();
7715   auto S = Exclude.begin(), E = Exclude.end();
7716   for (unsigned i = First; i < Last; ++i) {
7717     if (std::find(S, E, i) != E) {
7718       --Skipped;
7719       continue;
7720     }
7721     Values += "'";
7722     Values += getOpenMPSimpleClauseTypeName(K, i);
7723     Values += "'";
7724     if (i == Bound - Skipped)
7725       Values += " or ";
7726     else if (i != Bound + 1 - Skipped)
7727       Values += ", ";
7728   }
7729   return Values;
7730 }
7731 
7732 OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
7733                                           SourceLocation KindKwLoc,
7734                                           SourceLocation StartLoc,
7735                                           SourceLocation LParenLoc,
7736                                           SourceLocation EndLoc) {
7737   if (Kind == OMPC_DEFAULT_unknown) {
7738     static_assert(OMPC_DEFAULT_unknown > 0,
7739                   "OMPC_DEFAULT_unknown not greater than 0");
7740     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
7741         << getListOfPossibleValues(OMPC_default, /*First=*/0,
7742                                    /*Last=*/OMPC_DEFAULT_unknown)
7743         << getOpenMPClauseName(OMPC_default);
7744     return nullptr;
7745   }
7746   switch (Kind) {
7747   case OMPC_DEFAULT_none:
7748     DSAStack->setDefaultDSANone(KindKwLoc);
7749     break;
7750   case OMPC_DEFAULT_shared:
7751     DSAStack->setDefaultDSAShared(KindKwLoc);
7752     break;
7753   case OMPC_DEFAULT_unknown:
7754     llvm_unreachable("Clause kind is not allowed.");
7755     break;
7756   }
7757   return new (Context)
7758       OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
7759 }
7760 
7761 OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
7762                                            SourceLocation KindKwLoc,
7763                                            SourceLocation StartLoc,
7764                                            SourceLocation LParenLoc,
7765                                            SourceLocation EndLoc) {
7766   if (Kind == OMPC_PROC_BIND_unknown) {
7767     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
7768         << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
7769                                    /*Last=*/OMPC_PROC_BIND_unknown)
7770         << getOpenMPClauseName(OMPC_proc_bind);
7771     return nullptr;
7772   }
7773   return new (Context)
7774       OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
7775 }
7776 
7777 OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
7778     OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
7779     SourceLocation StartLoc, SourceLocation LParenLoc,
7780     ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
7781     SourceLocation EndLoc) {
7782   OMPClause *Res = nullptr;
7783   switch (Kind) {
7784   case OMPC_schedule:
7785     enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
7786     assert(Argument.size() == NumberOfElements &&
7787            ArgumentLoc.size() == NumberOfElements);
7788     Res = ActOnOpenMPScheduleClause(
7789         static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
7790         static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
7791         static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
7792         StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
7793         ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
7794     break;
7795   case OMPC_if:
7796     assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
7797     Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
7798                               Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
7799                               DelimLoc, EndLoc);
7800     break;
7801   case OMPC_dist_schedule:
7802     Res = ActOnOpenMPDistScheduleClause(
7803         static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
7804         StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
7805     break;
7806   case OMPC_defaultmap:
7807     enum { Modifier, DefaultmapKind };
7808     Res = ActOnOpenMPDefaultmapClause(
7809         static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
7810         static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
7811         StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
7812         EndLoc);
7813     break;
7814   case OMPC_final:
7815   case OMPC_num_threads:
7816   case OMPC_safelen:
7817   case OMPC_simdlen:
7818   case OMPC_collapse:
7819   case OMPC_default:
7820   case OMPC_proc_bind:
7821   case OMPC_private:
7822   case OMPC_firstprivate:
7823   case OMPC_lastprivate:
7824   case OMPC_shared:
7825   case OMPC_reduction:
7826   case OMPC_task_reduction:
7827   case OMPC_in_reduction:
7828   case OMPC_linear:
7829   case OMPC_aligned:
7830   case OMPC_copyin:
7831   case OMPC_copyprivate:
7832   case OMPC_ordered:
7833   case OMPC_nowait:
7834   case OMPC_untied:
7835   case OMPC_mergeable:
7836   case OMPC_threadprivate:
7837   case OMPC_flush:
7838   case OMPC_read:
7839   case OMPC_write:
7840   case OMPC_update:
7841   case OMPC_capture:
7842   case OMPC_seq_cst:
7843   case OMPC_depend:
7844   case OMPC_device:
7845   case OMPC_threads:
7846   case OMPC_simd:
7847   case OMPC_map:
7848   case OMPC_num_teams:
7849   case OMPC_thread_limit:
7850   case OMPC_priority:
7851   case OMPC_grainsize:
7852   case OMPC_nogroup:
7853   case OMPC_num_tasks:
7854   case OMPC_hint:
7855   case OMPC_unknown:
7856   case OMPC_uniform:
7857   case OMPC_to:
7858   case OMPC_from:
7859   case OMPC_use_device_ptr:
7860   case OMPC_is_device_ptr:
7861     llvm_unreachable("Clause is not allowed.");
7862   }
7863   return Res;
7864 }
7865 
7866 static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
7867                                    OpenMPScheduleClauseModifier M2,
7868                                    SourceLocation M1Loc, SourceLocation M2Loc) {
7869   if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
7870     SmallVector<unsigned, 2> Excluded;
7871     if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
7872       Excluded.push_back(M2);
7873     if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
7874       Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
7875     if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
7876       Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
7877     S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
7878         << getListOfPossibleValues(OMPC_schedule,
7879                                    /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
7880                                    /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
7881                                    Excluded)
7882         << getOpenMPClauseName(OMPC_schedule);
7883     return true;
7884   }
7885   return false;
7886 }
7887 
7888 OMPClause *Sema::ActOnOpenMPScheduleClause(
7889     OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
7890     OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
7891     SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
7892     SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
7893   if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
7894       checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
7895     return nullptr;
7896   // OpenMP, 2.7.1, Loop Construct, Restrictions
7897   // Either the monotonic modifier or the nonmonotonic modifier can be specified
7898   // but not both.
7899   if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
7900       (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
7901        M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
7902       (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
7903        M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
7904     Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
7905         << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
7906         << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
7907     return nullptr;
7908   }
7909   if (Kind == OMPC_SCHEDULE_unknown) {
7910     std::string Values;
7911     if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
7912       unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
7913       Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
7914                                        /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
7915                                        Exclude);
7916     } else {
7917       Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
7918                                        /*Last=*/OMPC_SCHEDULE_unknown);
7919     }
7920     Diag(KindLoc, diag::err_omp_unexpected_clause_value)
7921         << Values << getOpenMPClauseName(OMPC_schedule);
7922     return nullptr;
7923   }
7924   // OpenMP, 2.7.1, Loop Construct, Restrictions
7925   // The nonmonotonic modifier can only be specified with schedule(dynamic) or
7926   // schedule(guided).
7927   if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
7928        M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
7929       Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
7930     Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
7931          diag::err_omp_schedule_nonmonotonic_static);
7932     return nullptr;
7933   }
7934   Expr *ValExpr = ChunkSize;
7935   Stmt *HelperValStmt = nullptr;
7936   if (ChunkSize) {
7937     if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
7938         !ChunkSize->isInstantiationDependent() &&
7939         !ChunkSize->containsUnexpandedParameterPack()) {
7940       SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
7941       ExprResult Val =
7942           PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
7943       if (Val.isInvalid())
7944         return nullptr;
7945 
7946       ValExpr = Val.get();
7947 
7948       // OpenMP [2.7.1, Restrictions]
7949       //  chunk_size must be a loop invariant integer expression with a positive
7950       //  value.
7951       llvm::APSInt Result;
7952       if (ValExpr->isIntegerConstantExpr(Result, Context)) {
7953         if (Result.isSigned() && !Result.isStrictlyPositive()) {
7954           Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
7955               << "schedule" << 1 << ChunkSize->getSourceRange();
7956           return nullptr;
7957         }
7958       } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) &&
7959                  !CurContext->isDependentContext()) {
7960         llvm::MapVector<Expr *, DeclRefExpr *> Captures;
7961         ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
7962         HelperValStmt = buildPreInits(Context, Captures);
7963       }
7964     }
7965   }
7966 
7967   return new (Context)
7968       OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
7969                         ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
7970 }
7971 
7972 OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
7973                                    SourceLocation StartLoc,
7974                                    SourceLocation EndLoc) {
7975   OMPClause *Res = nullptr;
7976   switch (Kind) {
7977   case OMPC_ordered:
7978     Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
7979     break;
7980   case OMPC_nowait:
7981     Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
7982     break;
7983   case OMPC_untied:
7984     Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
7985     break;
7986   case OMPC_mergeable:
7987     Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
7988     break;
7989   case OMPC_read:
7990     Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
7991     break;
7992   case OMPC_write:
7993     Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
7994     break;
7995   case OMPC_update:
7996     Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
7997     break;
7998   case OMPC_capture:
7999     Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
8000     break;
8001   case OMPC_seq_cst:
8002     Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
8003     break;
8004   case OMPC_threads:
8005     Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
8006     break;
8007   case OMPC_simd:
8008     Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
8009     break;
8010   case OMPC_nogroup:
8011     Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
8012     break;
8013   case OMPC_if:
8014   case OMPC_final:
8015   case OMPC_num_threads:
8016   case OMPC_safelen:
8017   case OMPC_simdlen:
8018   case OMPC_collapse:
8019   case OMPC_schedule:
8020   case OMPC_private:
8021   case OMPC_firstprivate:
8022   case OMPC_lastprivate:
8023   case OMPC_shared:
8024   case OMPC_reduction:
8025   case OMPC_task_reduction:
8026   case OMPC_in_reduction:
8027   case OMPC_linear:
8028   case OMPC_aligned:
8029   case OMPC_copyin:
8030   case OMPC_copyprivate:
8031   case OMPC_default:
8032   case OMPC_proc_bind:
8033   case OMPC_threadprivate:
8034   case OMPC_flush:
8035   case OMPC_depend:
8036   case OMPC_device:
8037   case OMPC_map:
8038   case OMPC_num_teams:
8039   case OMPC_thread_limit:
8040   case OMPC_priority:
8041   case OMPC_grainsize:
8042   case OMPC_num_tasks:
8043   case OMPC_hint:
8044   case OMPC_dist_schedule:
8045   case OMPC_defaultmap:
8046   case OMPC_unknown:
8047   case OMPC_uniform:
8048   case OMPC_to:
8049   case OMPC_from:
8050   case OMPC_use_device_ptr:
8051   case OMPC_is_device_ptr:
8052     llvm_unreachable("Clause is not allowed.");
8053   }
8054   return Res;
8055 }
8056 
8057 OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
8058                                          SourceLocation EndLoc) {
8059   DSAStack->setNowaitRegion();
8060   return new (Context) OMPNowaitClause(StartLoc, EndLoc);
8061 }
8062 
8063 OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
8064                                          SourceLocation EndLoc) {
8065   return new (Context) OMPUntiedClause(StartLoc, EndLoc);
8066 }
8067 
8068 OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
8069                                             SourceLocation EndLoc) {
8070   return new (Context) OMPMergeableClause(StartLoc, EndLoc);
8071 }
8072 
8073 OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
8074                                        SourceLocation EndLoc) {
8075   return new (Context) OMPReadClause(StartLoc, EndLoc);
8076 }
8077 
8078 OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
8079                                         SourceLocation EndLoc) {
8080   return new (Context) OMPWriteClause(StartLoc, EndLoc);
8081 }
8082 
8083 OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
8084                                          SourceLocation EndLoc) {
8085   return new (Context) OMPUpdateClause(StartLoc, EndLoc);
8086 }
8087 
8088 OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
8089                                           SourceLocation EndLoc) {
8090   return new (Context) OMPCaptureClause(StartLoc, EndLoc);
8091 }
8092 
8093 OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
8094                                          SourceLocation EndLoc) {
8095   return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
8096 }
8097 
8098 OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
8099                                           SourceLocation EndLoc) {
8100   return new (Context) OMPThreadsClause(StartLoc, EndLoc);
8101 }
8102 
8103 OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
8104                                        SourceLocation EndLoc) {
8105   return new (Context) OMPSIMDClause(StartLoc, EndLoc);
8106 }
8107 
8108 OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
8109                                           SourceLocation EndLoc) {
8110   return new (Context) OMPNogroupClause(StartLoc, EndLoc);
8111 }
8112 
8113 OMPClause *Sema::ActOnOpenMPVarListClause(
8114     OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
8115     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
8116     SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
8117     const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
8118     OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier,
8119     OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
8120     SourceLocation DepLinMapLoc) {
8121   OMPClause *Res = nullptr;
8122   switch (Kind) {
8123   case OMPC_private:
8124     Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
8125     break;
8126   case OMPC_firstprivate:
8127     Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
8128     break;
8129   case OMPC_lastprivate:
8130     Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
8131     break;
8132   case OMPC_shared:
8133     Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
8134     break;
8135   case OMPC_reduction:
8136     Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
8137                                      EndLoc, ReductionIdScopeSpec, ReductionId);
8138     break;
8139   case OMPC_task_reduction:
8140     Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
8141                                          EndLoc, ReductionIdScopeSpec,
8142                                          ReductionId);
8143     break;
8144   case OMPC_in_reduction:
8145     Res =
8146         ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
8147                                      EndLoc, ReductionIdScopeSpec, ReductionId);
8148     break;
8149   case OMPC_linear:
8150     Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
8151                                   LinKind, DepLinMapLoc, ColonLoc, EndLoc);
8152     break;
8153   case OMPC_aligned:
8154     Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
8155                                    ColonLoc, EndLoc);
8156     break;
8157   case OMPC_copyin:
8158     Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
8159     break;
8160   case OMPC_copyprivate:
8161     Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
8162     break;
8163   case OMPC_flush:
8164     Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
8165     break;
8166   case OMPC_depend:
8167     Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
8168                                   StartLoc, LParenLoc, EndLoc);
8169     break;
8170   case OMPC_map:
8171     Res = ActOnOpenMPMapClause(MapTypeModifier, MapType, IsMapTypeImplicit,
8172                                DepLinMapLoc, ColonLoc, VarList, StartLoc,
8173                                LParenLoc, EndLoc);
8174     break;
8175   case OMPC_to:
8176     Res = ActOnOpenMPToClause(VarList, StartLoc, LParenLoc, EndLoc);
8177     break;
8178   case OMPC_from:
8179     Res = ActOnOpenMPFromClause(VarList, StartLoc, LParenLoc, EndLoc);
8180     break;
8181   case OMPC_use_device_ptr:
8182     Res = ActOnOpenMPUseDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
8183     break;
8184   case OMPC_is_device_ptr:
8185     Res = ActOnOpenMPIsDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
8186     break;
8187   case OMPC_if:
8188   case OMPC_final:
8189   case OMPC_num_threads:
8190   case OMPC_safelen:
8191   case OMPC_simdlen:
8192   case OMPC_collapse:
8193   case OMPC_default:
8194   case OMPC_proc_bind:
8195   case OMPC_schedule:
8196   case OMPC_ordered:
8197   case OMPC_nowait:
8198   case OMPC_untied:
8199   case OMPC_mergeable:
8200   case OMPC_threadprivate:
8201   case OMPC_read:
8202   case OMPC_write:
8203   case OMPC_update:
8204   case OMPC_capture:
8205   case OMPC_seq_cst:
8206   case OMPC_device:
8207   case OMPC_threads:
8208   case OMPC_simd:
8209   case OMPC_num_teams:
8210   case OMPC_thread_limit:
8211   case OMPC_priority:
8212   case OMPC_grainsize:
8213   case OMPC_nogroup:
8214   case OMPC_num_tasks:
8215   case OMPC_hint:
8216   case OMPC_dist_schedule:
8217   case OMPC_defaultmap:
8218   case OMPC_unknown:
8219   case OMPC_uniform:
8220     llvm_unreachable("Clause is not allowed.");
8221   }
8222   return Res;
8223 }
8224 
8225 ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
8226                                        ExprObjectKind OK, SourceLocation Loc) {
8227   ExprResult Res = BuildDeclRefExpr(
8228       Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
8229   if (!Res.isUsable())
8230     return ExprError();
8231   if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
8232     Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
8233     if (!Res.isUsable())
8234       return ExprError();
8235   }
8236   if (VK != VK_LValue && Res.get()->isGLValue()) {
8237     Res = DefaultLvalueConversion(Res.get());
8238     if (!Res.isUsable())
8239       return ExprError();
8240   }
8241   return Res;
8242 }
8243 
8244 static std::pair<ValueDecl *, bool>
8245 getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
8246                SourceRange &ERange, bool AllowArraySection = false) {
8247   if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
8248       RefExpr->containsUnexpandedParameterPack())
8249     return std::make_pair(nullptr, true);
8250 
8251   // OpenMP [3.1, C/C++]
8252   //  A list item is a variable name.
8253   // OpenMP  [2.9.3.3, Restrictions, p.1]
8254   //  A variable that is part of another variable (as an array or
8255   //  structure element) cannot appear in a private clause.
8256   RefExpr = RefExpr->IgnoreParens();
8257   enum {
8258     NoArrayExpr = -1,
8259     ArraySubscript = 0,
8260     OMPArraySection = 1
8261   } IsArrayExpr = NoArrayExpr;
8262   if (AllowArraySection) {
8263     if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
8264       auto *Base = ASE->getBase()->IgnoreParenImpCasts();
8265       while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
8266         Base = TempASE->getBase()->IgnoreParenImpCasts();
8267       RefExpr = Base;
8268       IsArrayExpr = ArraySubscript;
8269     } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
8270       auto *Base = OASE->getBase()->IgnoreParenImpCasts();
8271       while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
8272         Base = TempOASE->getBase()->IgnoreParenImpCasts();
8273       while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
8274         Base = TempASE->getBase()->IgnoreParenImpCasts();
8275       RefExpr = Base;
8276       IsArrayExpr = OMPArraySection;
8277     }
8278   }
8279   ELoc = RefExpr->getExprLoc();
8280   ERange = RefExpr->getSourceRange();
8281   RefExpr = RefExpr->IgnoreParenImpCasts();
8282   auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
8283   auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
8284   if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
8285       (S.getCurrentThisType().isNull() || !ME ||
8286        !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
8287        !isa<FieldDecl>(ME->getMemberDecl()))) {
8288     if (IsArrayExpr != NoArrayExpr)
8289       S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
8290                                                          << ERange;
8291     else {
8292       S.Diag(ELoc,
8293              AllowArraySection
8294                  ? diag::err_omp_expected_var_name_member_expr_or_array_item
8295                  : diag::err_omp_expected_var_name_member_expr)
8296           << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
8297     }
8298     return std::make_pair(nullptr, false);
8299   }
8300   return std::make_pair(
8301       getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false);
8302 }
8303 
8304 OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
8305                                           SourceLocation StartLoc,
8306                                           SourceLocation LParenLoc,
8307                                           SourceLocation EndLoc) {
8308   SmallVector<Expr *, 8> Vars;
8309   SmallVector<Expr *, 8> PrivateCopies;
8310   for (auto &RefExpr : VarList) {
8311     assert(RefExpr && "NULL expr in OpenMP private clause.");
8312     SourceLocation ELoc;
8313     SourceRange ERange;
8314     Expr *SimpleRefExpr = RefExpr;
8315     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
8316     if (Res.second) {
8317       // It will be analyzed later.
8318       Vars.push_back(RefExpr);
8319       PrivateCopies.push_back(nullptr);
8320     }
8321     ValueDecl *D = Res.first;
8322     if (!D)
8323       continue;
8324 
8325     QualType Type = D->getType();
8326     auto *VD = dyn_cast<VarDecl>(D);
8327 
8328     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
8329     //  A variable that appears in a private clause must not have an incomplete
8330     //  type or a reference type.
8331     if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
8332       continue;
8333     Type = Type.getNonReferenceType();
8334 
8335     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
8336     // in a Construct]
8337     //  Variables with the predetermined data-sharing attributes may not be
8338     //  listed in data-sharing attributes clauses, except for the cases
8339     //  listed below. For these exceptions only, listing a predetermined
8340     //  variable in a data-sharing attribute clause is allowed and overrides
8341     //  the variable's predetermined data-sharing attributes.
8342     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
8343     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
8344       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
8345                                           << getOpenMPClauseName(OMPC_private);
8346       ReportOriginalDSA(*this, DSAStack, D, DVar);
8347       continue;
8348     }
8349 
8350     auto CurrDir = DSAStack->getCurrentDirective();
8351     // Variably modified types are not supported for tasks.
8352     if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
8353         isOpenMPTaskingDirective(CurrDir)) {
8354       Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
8355           << getOpenMPClauseName(OMPC_private) << Type
8356           << getOpenMPDirectiveName(CurrDir);
8357       bool IsDecl =
8358           !VD ||
8359           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
8360       Diag(D->getLocation(),
8361            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8362           << D;
8363       continue;
8364     }
8365 
8366     // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
8367     // A list item cannot appear in both a map clause and a data-sharing
8368     // attribute clause on the same construct
8369     if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel ||
8370         CurrDir == OMPD_target_teams ||
8371         CurrDir == OMPD_target_teams_distribute ||
8372         CurrDir == OMPD_target_teams_distribute_parallel_for ||
8373         CurrDir == OMPD_target_teams_distribute_parallel_for_simd ||
8374         CurrDir == OMPD_target_teams_distribute_simd ||
8375         CurrDir == OMPD_target_parallel_for_simd ||
8376         CurrDir == OMPD_target_parallel_for) {
8377       OpenMPClauseKind ConflictKind;
8378       if (DSAStack->checkMappableExprComponentListsForDecl(
8379               VD, /*CurrentRegionOnly=*/true,
8380               [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
8381                   OpenMPClauseKind WhereFoundClauseKind) -> bool {
8382                 ConflictKind = WhereFoundClauseKind;
8383                 return true;
8384               })) {
8385         Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
8386             << getOpenMPClauseName(OMPC_private)
8387             << getOpenMPClauseName(ConflictKind)
8388             << getOpenMPDirectiveName(CurrDir);
8389         ReportOriginalDSA(*this, DSAStack, D, DVar);
8390         continue;
8391       }
8392     }
8393 
8394     // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
8395     //  A variable of class type (or array thereof) that appears in a private
8396     //  clause requires an accessible, unambiguous default constructor for the
8397     //  class type.
8398     // Generate helper private variable and initialize it with the default
8399     // value. The address of the original variable is replaced by the address of
8400     // the new private variable in CodeGen. This new variable is not added to
8401     // IdResolver, so the code in the OpenMP region uses original variable for
8402     // proper diagnostics.
8403     Type = Type.getUnqualifiedType();
8404     auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
8405                                   D->hasAttrs() ? &D->getAttrs() : nullptr);
8406     ActOnUninitializedDecl(VDPrivate);
8407     if (VDPrivate->isInvalidDecl())
8408       continue;
8409     auto VDPrivateRefExpr = buildDeclRefExpr(
8410         *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
8411 
8412     DeclRefExpr *Ref = nullptr;
8413     if (!VD && !CurContext->isDependentContext())
8414       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
8415     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
8416     Vars.push_back((VD || CurContext->isDependentContext())
8417                        ? RefExpr->IgnoreParens()
8418                        : Ref);
8419     PrivateCopies.push_back(VDPrivateRefExpr);
8420   }
8421 
8422   if (Vars.empty())
8423     return nullptr;
8424 
8425   return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
8426                                   PrivateCopies);
8427 }
8428 
8429 namespace {
8430 class DiagsUninitializedSeveretyRAII {
8431 private:
8432   DiagnosticsEngine &Diags;
8433   SourceLocation SavedLoc;
8434   bool IsIgnored;
8435 
8436 public:
8437   DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
8438                                  bool IsIgnored)
8439       : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
8440     if (!IsIgnored) {
8441       Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
8442                         /*Map*/ diag::Severity::Ignored, Loc);
8443     }
8444   }
8445   ~DiagsUninitializedSeveretyRAII() {
8446     if (!IsIgnored)
8447       Diags.popMappings(SavedLoc);
8448   }
8449 };
8450 }
8451 
8452 OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
8453                                                SourceLocation StartLoc,
8454                                                SourceLocation LParenLoc,
8455                                                SourceLocation EndLoc) {
8456   SmallVector<Expr *, 8> Vars;
8457   SmallVector<Expr *, 8> PrivateCopies;
8458   SmallVector<Expr *, 8> Inits;
8459   SmallVector<Decl *, 4> ExprCaptures;
8460   bool IsImplicitClause =
8461       StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
8462   auto ImplicitClauseLoc = DSAStack->getConstructLoc();
8463 
8464   for (auto &RefExpr : VarList) {
8465     assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
8466     SourceLocation ELoc;
8467     SourceRange ERange;
8468     Expr *SimpleRefExpr = RefExpr;
8469     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
8470     if (Res.second) {
8471       // It will be analyzed later.
8472       Vars.push_back(RefExpr);
8473       PrivateCopies.push_back(nullptr);
8474       Inits.push_back(nullptr);
8475     }
8476     ValueDecl *D = Res.first;
8477     if (!D)
8478       continue;
8479 
8480     ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
8481     QualType Type = D->getType();
8482     auto *VD = dyn_cast<VarDecl>(D);
8483 
8484     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
8485     //  A variable that appears in a private clause must not have an incomplete
8486     //  type or a reference type.
8487     if (RequireCompleteType(ELoc, Type,
8488                             diag::err_omp_firstprivate_incomplete_type))
8489       continue;
8490     Type = Type.getNonReferenceType();
8491 
8492     // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
8493     //  A variable of class type (or array thereof) that appears in a private
8494     //  clause requires an accessible, unambiguous copy constructor for the
8495     //  class type.
8496     auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
8497 
8498     // If an implicit firstprivate variable found it was checked already.
8499     DSAStackTy::DSAVarData TopDVar;
8500     if (!IsImplicitClause) {
8501       DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
8502       TopDVar = DVar;
8503       OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
8504       bool IsConstant = ElemType.isConstant(Context);
8505       // OpenMP [2.4.13, Data-sharing Attribute Clauses]
8506       //  A list item that specifies a given variable may not appear in more
8507       // than one clause on the same directive, except that a variable may be
8508       //  specified in both firstprivate and lastprivate clauses.
8509       // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
8510       // A list item may appear in a firstprivate or lastprivate clause but not
8511       // both.
8512       if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
8513           (CurrDir == OMPD_distribute || DVar.CKind != OMPC_lastprivate) &&
8514           DVar.RefExpr) {
8515         Diag(ELoc, diag::err_omp_wrong_dsa)
8516             << getOpenMPClauseName(DVar.CKind)
8517             << getOpenMPClauseName(OMPC_firstprivate);
8518         ReportOriginalDSA(*this, DSAStack, D, DVar);
8519         continue;
8520       }
8521 
8522       // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
8523       // in a Construct]
8524       //  Variables with the predetermined data-sharing attributes may not be
8525       //  listed in data-sharing attributes clauses, except for the cases
8526       //  listed below. For these exceptions only, listing a predetermined
8527       //  variable in a data-sharing attribute clause is allowed and overrides
8528       //  the variable's predetermined data-sharing attributes.
8529       // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
8530       // in a Construct, C/C++, p.2]
8531       //  Variables with const-qualified type having no mutable member may be
8532       //  listed in a firstprivate clause, even if they are static data members.
8533       if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
8534           DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
8535         Diag(ELoc, diag::err_omp_wrong_dsa)
8536             << getOpenMPClauseName(DVar.CKind)
8537             << getOpenMPClauseName(OMPC_firstprivate);
8538         ReportOriginalDSA(*this, DSAStack, D, DVar);
8539         continue;
8540       }
8541 
8542       // OpenMP [2.9.3.4, Restrictions, p.2]
8543       //  A list item that is private within a parallel region must not appear
8544       //  in a firstprivate clause on a worksharing construct if any of the
8545       //  worksharing regions arising from the worksharing construct ever bind
8546       //  to any of the parallel regions arising from the parallel construct.
8547       // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
8548       // A list item that is private within a teams region must not appear in a
8549       // firstprivate clause on a distribute construct if any of the distribute
8550       // regions arising from the distribute construct ever bind to any of the
8551       // teams regions arising from the teams construct.
8552       // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
8553       // A list item that appears in a reduction clause of a teams construct
8554       // must not appear in a firstprivate clause on a distribute construct if
8555       // any of the distribute regions arising from the distribute construct
8556       // ever bind to any of the teams regions arising from the teams construct.
8557       if ((isOpenMPWorksharingDirective(CurrDir) ||
8558            isOpenMPDistributeDirective(CurrDir)) &&
8559           !isOpenMPParallelDirective(CurrDir) &&
8560           !isOpenMPTeamsDirective(CurrDir)) {
8561         DVar = DSAStack->getImplicitDSA(D, true);
8562         if (DVar.CKind != OMPC_shared &&
8563             (isOpenMPParallelDirective(DVar.DKind) ||
8564              isOpenMPTeamsDirective(DVar.DKind) ||
8565              DVar.DKind == OMPD_unknown)) {
8566           Diag(ELoc, diag::err_omp_required_access)
8567               << getOpenMPClauseName(OMPC_firstprivate)
8568               << getOpenMPClauseName(OMPC_shared);
8569           ReportOriginalDSA(*this, DSAStack, D, DVar);
8570           continue;
8571         }
8572       }
8573       // OpenMP [2.9.3.4, Restrictions, p.3]
8574       //  A list item that appears in a reduction clause of a parallel construct
8575       //  must not appear in a firstprivate clause on a worksharing or task
8576       //  construct if any of the worksharing or task regions arising from the
8577       //  worksharing or task construct ever bind to any of the parallel regions
8578       //  arising from the parallel construct.
8579       // OpenMP [2.9.3.4, Restrictions, p.4]
8580       //  A list item that appears in a reduction clause in worksharing
8581       //  construct must not appear in a firstprivate clause in a task construct
8582       //  encountered during execution of any of the worksharing regions arising
8583       //  from the worksharing construct.
8584       if (isOpenMPTaskingDirective(CurrDir)) {
8585         DVar = DSAStack->hasInnermostDSA(
8586             D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
8587             [](OpenMPDirectiveKind K) -> bool {
8588               return isOpenMPParallelDirective(K) ||
8589                      isOpenMPWorksharingDirective(K) ||
8590                      isOpenMPTeamsDirective(K);
8591             },
8592             /*FromParent=*/true);
8593         if (DVar.CKind == OMPC_reduction &&
8594             (isOpenMPParallelDirective(DVar.DKind) ||
8595              isOpenMPWorksharingDirective(DVar.DKind) ||
8596              isOpenMPTeamsDirective(DVar.DKind))) {
8597           Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
8598               << getOpenMPDirectiveName(DVar.DKind);
8599           ReportOriginalDSA(*this, DSAStack, D, DVar);
8600           continue;
8601         }
8602       }
8603 
8604       // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
8605       // A list item cannot appear in both a map clause and a data-sharing
8606       // attribute clause on the same construct
8607       if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel ||
8608           CurrDir == OMPD_target_teams ||
8609           CurrDir == OMPD_target_teams_distribute ||
8610           CurrDir == OMPD_target_teams_distribute_parallel_for ||
8611           CurrDir == OMPD_target_teams_distribute_parallel_for_simd ||
8612           CurrDir == OMPD_target_teams_distribute_simd ||
8613           CurrDir == OMPD_target_parallel_for_simd ||
8614           CurrDir == OMPD_target_parallel_for) {
8615         OpenMPClauseKind ConflictKind;
8616         if (DSAStack->checkMappableExprComponentListsForDecl(
8617                 VD, /*CurrentRegionOnly=*/true,
8618                 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
8619                     OpenMPClauseKind WhereFoundClauseKind) -> bool {
8620                   ConflictKind = WhereFoundClauseKind;
8621                   return true;
8622                 })) {
8623           Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
8624               << getOpenMPClauseName(OMPC_firstprivate)
8625               << getOpenMPClauseName(ConflictKind)
8626               << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
8627           ReportOriginalDSA(*this, DSAStack, D, DVar);
8628           continue;
8629         }
8630       }
8631     }
8632 
8633     // Variably modified types are not supported for tasks.
8634     if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
8635         isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
8636       Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
8637           << getOpenMPClauseName(OMPC_firstprivate) << Type
8638           << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
8639       bool IsDecl =
8640           !VD ||
8641           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
8642       Diag(D->getLocation(),
8643            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8644           << D;
8645       continue;
8646     }
8647 
8648     Type = Type.getUnqualifiedType();
8649     auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
8650                                   D->hasAttrs() ? &D->getAttrs() : nullptr);
8651     // Generate helper private variable and initialize it with the value of the
8652     // original variable. The address of the original variable is replaced by
8653     // the address of the new private variable in the CodeGen. This new variable
8654     // is not added to IdResolver, so the code in the OpenMP region uses
8655     // original variable for proper diagnostics and variable capturing.
8656     Expr *VDInitRefExpr = nullptr;
8657     // For arrays generate initializer for single element and replace it by the
8658     // original array element in CodeGen.
8659     if (Type->isArrayType()) {
8660       auto VDInit =
8661           buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
8662       VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
8663       auto Init = DefaultLvalueConversion(VDInitRefExpr).get();
8664       ElemType = ElemType.getUnqualifiedType();
8665       auto *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
8666                                       ".firstprivate.temp");
8667       InitializedEntity Entity =
8668           InitializedEntity::InitializeVariable(VDInitTemp);
8669       InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
8670 
8671       InitializationSequence InitSeq(*this, Entity, Kind, Init);
8672       ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
8673       if (Result.isInvalid())
8674         VDPrivate->setInvalidDecl();
8675       else
8676         VDPrivate->setInit(Result.getAs<Expr>());
8677       // Remove temp variable declaration.
8678       Context.Deallocate(VDInitTemp);
8679     } else {
8680       auto *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
8681                                   ".firstprivate.temp");
8682       VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
8683                                        RefExpr->getExprLoc());
8684       AddInitializerToDecl(VDPrivate,
8685                            DefaultLvalueConversion(VDInitRefExpr).get(),
8686                            /*DirectInit=*/false);
8687     }
8688     if (VDPrivate->isInvalidDecl()) {
8689       if (IsImplicitClause) {
8690         Diag(RefExpr->getExprLoc(),
8691              diag::note_omp_task_predetermined_firstprivate_here);
8692       }
8693       continue;
8694     }
8695     CurContext->addDecl(VDPrivate);
8696     auto VDPrivateRefExpr = buildDeclRefExpr(
8697         *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
8698         RefExpr->getExprLoc());
8699     DeclRefExpr *Ref = nullptr;
8700     if (!VD && !CurContext->isDependentContext()) {
8701       if (TopDVar.CKind == OMPC_lastprivate)
8702         Ref = TopDVar.PrivateCopy;
8703       else {
8704         Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
8705         if (!IsOpenMPCapturedDecl(D))
8706           ExprCaptures.push_back(Ref->getDecl());
8707       }
8708     }
8709     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
8710     Vars.push_back((VD || CurContext->isDependentContext())
8711                        ? RefExpr->IgnoreParens()
8712                        : Ref);
8713     PrivateCopies.push_back(VDPrivateRefExpr);
8714     Inits.push_back(VDInitRefExpr);
8715   }
8716 
8717   if (Vars.empty())
8718     return nullptr;
8719 
8720   return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
8721                                        Vars, PrivateCopies, Inits,
8722                                        buildPreInits(Context, ExprCaptures));
8723 }
8724 
8725 OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
8726                                               SourceLocation StartLoc,
8727                                               SourceLocation LParenLoc,
8728                                               SourceLocation EndLoc) {
8729   SmallVector<Expr *, 8> Vars;
8730   SmallVector<Expr *, 8> SrcExprs;
8731   SmallVector<Expr *, 8> DstExprs;
8732   SmallVector<Expr *, 8> AssignmentOps;
8733   SmallVector<Decl *, 4> ExprCaptures;
8734   SmallVector<Expr *, 4> ExprPostUpdates;
8735   for (auto &RefExpr : VarList) {
8736     assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
8737     SourceLocation ELoc;
8738     SourceRange ERange;
8739     Expr *SimpleRefExpr = RefExpr;
8740     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
8741     if (Res.second) {
8742       // It will be analyzed later.
8743       Vars.push_back(RefExpr);
8744       SrcExprs.push_back(nullptr);
8745       DstExprs.push_back(nullptr);
8746       AssignmentOps.push_back(nullptr);
8747     }
8748     ValueDecl *D = Res.first;
8749     if (!D)
8750       continue;
8751 
8752     QualType Type = D->getType();
8753     auto *VD = dyn_cast<VarDecl>(D);
8754 
8755     // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
8756     //  A variable that appears in a lastprivate clause must not have an
8757     //  incomplete type or a reference type.
8758     if (RequireCompleteType(ELoc, Type,
8759                             diag::err_omp_lastprivate_incomplete_type))
8760       continue;
8761     Type = Type.getNonReferenceType();
8762 
8763     OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
8764     // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
8765     // in a Construct]
8766     //  Variables with the predetermined data-sharing attributes may not be
8767     //  listed in data-sharing attributes clauses, except for the cases
8768     //  listed below.
8769     // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
8770     // A list item may appear in a firstprivate or lastprivate clause but not
8771     // both.
8772     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
8773     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
8774         (CurrDir == OMPD_distribute || DVar.CKind != OMPC_firstprivate) &&
8775         (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
8776       Diag(ELoc, diag::err_omp_wrong_dsa)
8777           << getOpenMPClauseName(DVar.CKind)
8778           << getOpenMPClauseName(OMPC_lastprivate);
8779       ReportOriginalDSA(*this, DSAStack, D, DVar);
8780       continue;
8781     }
8782 
8783     // OpenMP [2.14.3.5, Restrictions, p.2]
8784     // A list item that is private within a parallel region, or that appears in
8785     // the reduction clause of a parallel construct, must not appear in a
8786     // lastprivate clause on a worksharing construct if any of the corresponding
8787     // worksharing regions ever binds to any of the corresponding parallel
8788     // regions.
8789     DSAStackTy::DSAVarData TopDVar = DVar;
8790     if (isOpenMPWorksharingDirective(CurrDir) &&
8791         !isOpenMPParallelDirective(CurrDir) &&
8792         !isOpenMPTeamsDirective(CurrDir)) {
8793       DVar = DSAStack->getImplicitDSA(D, true);
8794       if (DVar.CKind != OMPC_shared) {
8795         Diag(ELoc, diag::err_omp_required_access)
8796             << getOpenMPClauseName(OMPC_lastprivate)
8797             << getOpenMPClauseName(OMPC_shared);
8798         ReportOriginalDSA(*this, DSAStack, D, DVar);
8799         continue;
8800       }
8801     }
8802 
8803     // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
8804     //  A variable of class type (or array thereof) that appears in a
8805     //  lastprivate clause requires an accessible, unambiguous default
8806     //  constructor for the class type, unless the list item is also specified
8807     //  in a firstprivate clause.
8808     //  A variable of class type (or array thereof) that appears in a
8809     //  lastprivate clause requires an accessible, unambiguous copy assignment
8810     //  operator for the class type.
8811     Type = Context.getBaseElementType(Type).getNonReferenceType();
8812     auto *SrcVD = buildVarDecl(*this, ERange.getBegin(),
8813                                Type.getUnqualifiedType(), ".lastprivate.src",
8814                                D->hasAttrs() ? &D->getAttrs() : nullptr);
8815     auto *PseudoSrcExpr =
8816         buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
8817     auto *DstVD =
8818         buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
8819                      D->hasAttrs() ? &D->getAttrs() : nullptr);
8820     auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
8821     // For arrays generate assignment operation for single element and replace
8822     // it by the original array element in CodeGen.
8823     auto AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
8824                                    PseudoDstExpr, PseudoSrcExpr);
8825     if (AssignmentOp.isInvalid())
8826       continue;
8827     AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
8828                                        /*DiscardedValue=*/true);
8829     if (AssignmentOp.isInvalid())
8830       continue;
8831 
8832     DeclRefExpr *Ref = nullptr;
8833     if (!VD && !CurContext->isDependentContext()) {
8834       if (TopDVar.CKind == OMPC_firstprivate)
8835         Ref = TopDVar.PrivateCopy;
8836       else {
8837         Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
8838         if (!IsOpenMPCapturedDecl(D))
8839           ExprCaptures.push_back(Ref->getDecl());
8840       }
8841       if (TopDVar.CKind == OMPC_firstprivate ||
8842           (!IsOpenMPCapturedDecl(D) &&
8843            Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
8844         ExprResult RefRes = DefaultLvalueConversion(Ref);
8845         if (!RefRes.isUsable())
8846           continue;
8847         ExprResult PostUpdateRes =
8848             BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
8849                        RefRes.get());
8850         if (!PostUpdateRes.isUsable())
8851           continue;
8852         ExprPostUpdates.push_back(
8853             IgnoredValueConversions(PostUpdateRes.get()).get());
8854       }
8855     }
8856     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
8857     Vars.push_back((VD || CurContext->isDependentContext())
8858                        ? RefExpr->IgnoreParens()
8859                        : Ref);
8860     SrcExprs.push_back(PseudoSrcExpr);
8861     DstExprs.push_back(PseudoDstExpr);
8862     AssignmentOps.push_back(AssignmentOp.get());
8863   }
8864 
8865   if (Vars.empty())
8866     return nullptr;
8867 
8868   return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
8869                                       Vars, SrcExprs, DstExprs, AssignmentOps,
8870                                       buildPreInits(Context, ExprCaptures),
8871                                       buildPostUpdate(*this, ExprPostUpdates));
8872 }
8873 
8874 OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
8875                                          SourceLocation StartLoc,
8876                                          SourceLocation LParenLoc,
8877                                          SourceLocation EndLoc) {
8878   SmallVector<Expr *, 8> Vars;
8879   for (auto &RefExpr : VarList) {
8880     assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
8881     SourceLocation ELoc;
8882     SourceRange ERange;
8883     Expr *SimpleRefExpr = RefExpr;
8884     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
8885     if (Res.second) {
8886       // It will be analyzed later.
8887       Vars.push_back(RefExpr);
8888     }
8889     ValueDecl *D = Res.first;
8890     if (!D)
8891       continue;
8892 
8893     auto *VD = dyn_cast<VarDecl>(D);
8894     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
8895     // in a Construct]
8896     //  Variables with the predetermined data-sharing attributes may not be
8897     //  listed in data-sharing attributes clauses, except for the cases
8898     //  listed below. For these exceptions only, listing a predetermined
8899     //  variable in a data-sharing attribute clause is allowed and overrides
8900     //  the variable's predetermined data-sharing attributes.
8901     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
8902     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
8903         DVar.RefExpr) {
8904       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
8905                                           << getOpenMPClauseName(OMPC_shared);
8906       ReportOriginalDSA(*this, DSAStack, D, DVar);
8907       continue;
8908     }
8909 
8910     DeclRefExpr *Ref = nullptr;
8911     if (!VD && IsOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
8912       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
8913     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
8914     Vars.push_back((VD || !Ref || CurContext->isDependentContext())
8915                        ? RefExpr->IgnoreParens()
8916                        : Ref);
8917   }
8918 
8919   if (Vars.empty())
8920     return nullptr;
8921 
8922   return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
8923 }
8924 
8925 namespace {
8926 class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
8927   DSAStackTy *Stack;
8928 
8929 public:
8930   bool VisitDeclRefExpr(DeclRefExpr *E) {
8931     if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
8932       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false);
8933       if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
8934         return false;
8935       if (DVar.CKind != OMPC_unknown)
8936         return true;
8937       DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
8938           VD, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
8939           /*FromParent=*/true);
8940       if (DVarPrivate.CKind != OMPC_unknown)
8941         return true;
8942       return false;
8943     }
8944     return false;
8945   }
8946   bool VisitStmt(Stmt *S) {
8947     for (auto Child : S->children()) {
8948       if (Child && Visit(Child))
8949         return true;
8950     }
8951     return false;
8952   }
8953   explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
8954 };
8955 } // namespace
8956 
8957 namespace {
8958 // Transform MemberExpression for specified FieldDecl of current class to
8959 // DeclRefExpr to specified OMPCapturedExprDecl.
8960 class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
8961   typedef TreeTransform<TransformExprToCaptures> BaseTransform;
8962   ValueDecl *Field;
8963   DeclRefExpr *CapturedExpr;
8964 
8965 public:
8966   TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
8967       : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
8968 
8969   ExprResult TransformMemberExpr(MemberExpr *E) {
8970     if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
8971         E->getMemberDecl() == Field) {
8972       CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
8973       return CapturedExpr;
8974     }
8975     return BaseTransform::TransformMemberExpr(E);
8976   }
8977   DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
8978 };
8979 } // namespace
8980 
8981 template <typename T>
8982 static T filterLookupForUDR(SmallVectorImpl<UnresolvedSet<8>> &Lookups,
8983                             const llvm::function_ref<T(ValueDecl *)> &Gen) {
8984   for (auto &Set : Lookups) {
8985     for (auto *D : Set) {
8986       if (auto Res = Gen(cast<ValueDecl>(D)))
8987         return Res;
8988     }
8989   }
8990   return T();
8991 }
8992 
8993 static ExprResult
8994 buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
8995                          Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
8996                          const DeclarationNameInfo &ReductionId, QualType Ty,
8997                          CXXCastPath &BasePath, Expr *UnresolvedReduction) {
8998   if (ReductionIdScopeSpec.isInvalid())
8999     return ExprError();
9000   SmallVector<UnresolvedSet<8>, 4> Lookups;
9001   if (S) {
9002     LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
9003     Lookup.suppressDiagnostics();
9004     while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
9005       auto *D = Lookup.getRepresentativeDecl();
9006       do {
9007         S = S->getParent();
9008       } while (S && !S->isDeclScope(D));
9009       if (S)
9010         S = S->getParent();
9011       Lookups.push_back(UnresolvedSet<8>());
9012       Lookups.back().append(Lookup.begin(), Lookup.end());
9013       Lookup.clear();
9014     }
9015   } else if (auto *ULE =
9016                  cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
9017     Lookups.push_back(UnresolvedSet<8>());
9018     Decl *PrevD = nullptr;
9019     for (auto *D : ULE->decls()) {
9020       if (D == PrevD)
9021         Lookups.push_back(UnresolvedSet<8>());
9022       else if (auto *DRD = cast<OMPDeclareReductionDecl>(D))
9023         Lookups.back().addDecl(DRD);
9024       PrevD = D;
9025     }
9026   }
9027   if (Ty->isDependentType() || Ty->isInstantiationDependentType() ||
9028       Ty->containsUnexpandedParameterPack() ||
9029       filterLookupForUDR<bool>(Lookups, [](ValueDecl *D) -> bool {
9030         return !D->isInvalidDecl() &&
9031                (D->getType()->isDependentType() ||
9032                 D->getType()->isInstantiationDependentType() ||
9033                 D->getType()->containsUnexpandedParameterPack());
9034       })) {
9035     UnresolvedSet<8> ResSet;
9036     for (auto &Set : Lookups) {
9037       ResSet.append(Set.begin(), Set.end());
9038       // The last item marks the end of all declarations at the specified scope.
9039       ResSet.addDecl(Set[Set.size() - 1]);
9040     }
9041     return UnresolvedLookupExpr::Create(
9042         SemaRef.Context, /*NamingClass=*/nullptr,
9043         ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
9044         /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
9045   }
9046   if (auto *VD = filterLookupForUDR<ValueDecl *>(
9047           Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
9048             if (!D->isInvalidDecl() &&
9049                 SemaRef.Context.hasSameType(D->getType(), Ty))
9050               return D;
9051             return nullptr;
9052           }))
9053     return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
9054   if (auto *VD = filterLookupForUDR<ValueDecl *>(
9055           Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
9056             if (!D->isInvalidDecl() &&
9057                 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
9058                 !Ty.isMoreQualifiedThan(D->getType()))
9059               return D;
9060             return nullptr;
9061           })) {
9062     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
9063                        /*DetectVirtual=*/false);
9064     if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
9065       if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
9066               VD->getType().getUnqualifiedType()))) {
9067         if (SemaRef.CheckBaseClassAccess(Loc, VD->getType(), Ty, Paths.front(),
9068                                          /*DiagID=*/0) !=
9069             Sema::AR_inaccessible) {
9070           SemaRef.BuildBasePathArray(Paths, BasePath);
9071           return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
9072         }
9073       }
9074     }
9075   }
9076   if (ReductionIdScopeSpec.isSet()) {
9077     SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
9078     return ExprError();
9079   }
9080   return ExprEmpty();
9081 }
9082 
9083 namespace {
9084 /// Data for the reduction-based clauses.
9085 struct ReductionData {
9086   /// List of original reduction items.
9087   SmallVector<Expr *, 8> Vars;
9088   /// List of private copies of the reduction items.
9089   SmallVector<Expr *, 8> Privates;
9090   /// LHS expressions for the reduction_op expressions.
9091   SmallVector<Expr *, 8> LHSs;
9092   /// RHS expressions for the reduction_op expressions.
9093   SmallVector<Expr *, 8> RHSs;
9094   /// Reduction operation expression.
9095   SmallVector<Expr *, 8> ReductionOps;
9096   /// Taskgroup descriptors for the corresponding reduction items in
9097   /// in_reduction clauses.
9098   SmallVector<Expr *, 8> TaskgroupDescriptors;
9099   /// List of captures for clause.
9100   SmallVector<Decl *, 4> ExprCaptures;
9101   /// List of postupdate expressions.
9102   SmallVector<Expr *, 4> ExprPostUpdates;
9103   ReductionData() = delete;
9104   /// Reserves required memory for the reduction data.
9105   ReductionData(unsigned Size) {
9106     Vars.reserve(Size);
9107     Privates.reserve(Size);
9108     LHSs.reserve(Size);
9109     RHSs.reserve(Size);
9110     ReductionOps.reserve(Size);
9111     TaskgroupDescriptors.reserve(Size);
9112     ExprCaptures.reserve(Size);
9113     ExprPostUpdates.reserve(Size);
9114   }
9115   /// Stores reduction item and reduction operation only (required for dependent
9116   /// reduction item).
9117   void push(Expr *Item, Expr *ReductionOp) {
9118     Vars.emplace_back(Item);
9119     Privates.emplace_back(nullptr);
9120     LHSs.emplace_back(nullptr);
9121     RHSs.emplace_back(nullptr);
9122     ReductionOps.emplace_back(ReductionOp);
9123     TaskgroupDescriptors.emplace_back(nullptr);
9124   }
9125   /// Stores reduction data.
9126   void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp,
9127             Expr *TaskgroupDescriptor) {
9128     Vars.emplace_back(Item);
9129     Privates.emplace_back(Private);
9130     LHSs.emplace_back(LHS);
9131     RHSs.emplace_back(RHS);
9132     ReductionOps.emplace_back(ReductionOp);
9133     TaskgroupDescriptors.emplace_back(TaskgroupDescriptor);
9134   }
9135 };
9136 } // namespace
9137 
9138 static bool ActOnOMPReductionKindClause(
9139     Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind,
9140     ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
9141     SourceLocation ColonLoc, SourceLocation EndLoc,
9142     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
9143     ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) {
9144   auto DN = ReductionId.getName();
9145   auto OOK = DN.getCXXOverloadedOperator();
9146   BinaryOperatorKind BOK = BO_Comma;
9147 
9148   ASTContext &Context = S.Context;
9149   // OpenMP [2.14.3.6, reduction clause]
9150   // C
9151   // reduction-identifier is either an identifier or one of the following
9152   // operators: +, -, *,  &, |, ^, && and ||
9153   // C++
9154   // reduction-identifier is either an id-expression or one of the following
9155   // operators: +, -, *, &, |, ^, && and ||
9156   switch (OOK) {
9157   case OO_Plus:
9158   case OO_Minus:
9159     BOK = BO_Add;
9160     break;
9161   case OO_Star:
9162     BOK = BO_Mul;
9163     break;
9164   case OO_Amp:
9165     BOK = BO_And;
9166     break;
9167   case OO_Pipe:
9168     BOK = BO_Or;
9169     break;
9170   case OO_Caret:
9171     BOK = BO_Xor;
9172     break;
9173   case OO_AmpAmp:
9174     BOK = BO_LAnd;
9175     break;
9176   case OO_PipePipe:
9177     BOK = BO_LOr;
9178     break;
9179   case OO_New:
9180   case OO_Delete:
9181   case OO_Array_New:
9182   case OO_Array_Delete:
9183   case OO_Slash:
9184   case OO_Percent:
9185   case OO_Tilde:
9186   case OO_Exclaim:
9187   case OO_Equal:
9188   case OO_Less:
9189   case OO_Greater:
9190   case OO_LessEqual:
9191   case OO_GreaterEqual:
9192   case OO_PlusEqual:
9193   case OO_MinusEqual:
9194   case OO_StarEqual:
9195   case OO_SlashEqual:
9196   case OO_PercentEqual:
9197   case OO_CaretEqual:
9198   case OO_AmpEqual:
9199   case OO_PipeEqual:
9200   case OO_LessLess:
9201   case OO_GreaterGreater:
9202   case OO_LessLessEqual:
9203   case OO_GreaterGreaterEqual:
9204   case OO_EqualEqual:
9205   case OO_ExclaimEqual:
9206   case OO_PlusPlus:
9207   case OO_MinusMinus:
9208   case OO_Comma:
9209   case OO_ArrowStar:
9210   case OO_Arrow:
9211   case OO_Call:
9212   case OO_Subscript:
9213   case OO_Conditional:
9214   case OO_Coawait:
9215   case NUM_OVERLOADED_OPERATORS:
9216     llvm_unreachable("Unexpected reduction identifier");
9217   case OO_None:
9218     if (auto *II = DN.getAsIdentifierInfo()) {
9219       if (II->isStr("max"))
9220         BOK = BO_GT;
9221       else if (II->isStr("min"))
9222         BOK = BO_LT;
9223     }
9224     break;
9225   }
9226   SourceRange ReductionIdRange;
9227   if (ReductionIdScopeSpec.isValid())
9228     ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
9229   else
9230     ReductionIdRange.setBegin(ReductionId.getBeginLoc());
9231   ReductionIdRange.setEnd(ReductionId.getEndLoc());
9232 
9233   auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
9234   bool FirstIter = true;
9235   for (auto RefExpr : VarList) {
9236     assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
9237     // OpenMP [2.1, C/C++]
9238     //  A list item is a variable or array section, subject to the restrictions
9239     //  specified in Section 2.4 on page 42 and in each of the sections
9240     // describing clauses and directives for which a list appears.
9241     // OpenMP  [2.14.3.3, Restrictions, p.1]
9242     //  A variable that is part of another variable (as an array or
9243     //  structure element) cannot appear in a private clause.
9244     if (!FirstIter && IR != ER)
9245       ++IR;
9246     FirstIter = false;
9247     SourceLocation ELoc;
9248     SourceRange ERange;
9249     Expr *SimpleRefExpr = RefExpr;
9250     auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
9251                               /*AllowArraySection=*/true);
9252     if (Res.second) {
9253       // Try to find 'declare reduction' corresponding construct before using
9254       // builtin/overloaded operators.
9255       QualType Type = Context.DependentTy;
9256       CXXCastPath BasePath;
9257       ExprResult DeclareReductionRef = buildDeclareReductionRef(
9258           S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
9259           ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
9260       Expr *ReductionOp = nullptr;
9261       if (S.CurContext->isDependentContext() &&
9262           (DeclareReductionRef.isUnset() ||
9263            isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
9264         ReductionOp = DeclareReductionRef.get();
9265       // It will be analyzed later.
9266       RD.push(RefExpr, ReductionOp);
9267     }
9268     ValueDecl *D = Res.first;
9269     if (!D)
9270       continue;
9271 
9272     Expr *TaskgroupDescriptor = nullptr;
9273     QualType Type;
9274     auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
9275     auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
9276     if (ASE)
9277       Type = ASE->getType().getNonReferenceType();
9278     else if (OASE) {
9279       auto BaseType = OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
9280       if (auto *ATy = BaseType->getAsArrayTypeUnsafe())
9281         Type = ATy->getElementType();
9282       else
9283         Type = BaseType->getPointeeType();
9284       Type = Type.getNonReferenceType();
9285     } else
9286       Type = Context.getBaseElementType(D->getType().getNonReferenceType());
9287     auto *VD = dyn_cast<VarDecl>(D);
9288 
9289     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
9290     //  A variable that appears in a private clause must not have an incomplete
9291     //  type or a reference type.
9292     if (S.RequireCompleteType(ELoc, Type,
9293                               diag::err_omp_reduction_incomplete_type))
9294       continue;
9295     // OpenMP [2.14.3.6, reduction clause, Restrictions]
9296     // A list item that appears in a reduction clause must not be
9297     // const-qualified.
9298     if (Type.getNonReferenceType().isConstant(Context)) {
9299       S.Diag(ELoc, diag::err_omp_const_reduction_list_item) << ERange;
9300       if (!ASE && !OASE) {
9301         bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
9302                                  VarDecl::DeclarationOnly;
9303         S.Diag(D->getLocation(),
9304                IsDecl ? diag::note_previous_decl : diag::note_defined_here)
9305             << D;
9306       }
9307       continue;
9308     }
9309     // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
9310     //  If a list-item is a reference type then it must bind to the same object
9311     //  for all threads of the team.
9312     if (!ASE && !OASE && VD) {
9313       VarDecl *VDDef = VD->getDefinition();
9314       if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
9315         DSARefChecker Check(Stack);
9316         if (Check.Visit(VDDef->getInit())) {
9317           S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg)
9318               << getOpenMPClauseName(ClauseKind) << ERange;
9319           S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
9320           continue;
9321         }
9322       }
9323     }
9324 
9325     // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
9326     // in a Construct]
9327     //  Variables with the predetermined data-sharing attributes may not be
9328     //  listed in data-sharing attributes clauses, except for the cases
9329     //  listed below. For these exceptions only, listing a predetermined
9330     //  variable in a data-sharing attribute clause is allowed and overrides
9331     //  the variable's predetermined data-sharing attributes.
9332     // OpenMP [2.14.3.6, Restrictions, p.3]
9333     //  Any number of reduction clauses can be specified on the directive,
9334     //  but a list item can appear only once in the reduction clauses for that
9335     //  directive.
9336     DSAStackTy::DSAVarData DVar;
9337     DVar = Stack->getTopDSA(D, false);
9338     if (DVar.CKind == OMPC_reduction) {
9339       S.Diag(ELoc, diag::err_omp_once_referenced)
9340           << getOpenMPClauseName(ClauseKind);
9341       if (DVar.RefExpr)
9342         S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
9343       continue;
9344     } else if (DVar.CKind != OMPC_unknown) {
9345       S.Diag(ELoc, diag::err_omp_wrong_dsa)
9346           << getOpenMPClauseName(DVar.CKind)
9347           << getOpenMPClauseName(OMPC_reduction);
9348       ReportOriginalDSA(S, Stack, D, DVar);
9349       continue;
9350     }
9351 
9352     // OpenMP [2.14.3.6, Restrictions, p.1]
9353     //  A list item that appears in a reduction clause of a worksharing
9354     //  construct must be shared in the parallel regions to which any of the
9355     //  worksharing regions arising from the worksharing construct bind.
9356     OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective();
9357     if (isOpenMPWorksharingDirective(CurrDir) &&
9358         !isOpenMPParallelDirective(CurrDir) &&
9359         !isOpenMPTeamsDirective(CurrDir)) {
9360       DVar = Stack->getImplicitDSA(D, true);
9361       if (DVar.CKind != OMPC_shared) {
9362         S.Diag(ELoc, diag::err_omp_required_access)
9363             << getOpenMPClauseName(OMPC_reduction)
9364             << getOpenMPClauseName(OMPC_shared);
9365         ReportOriginalDSA(S, Stack, D, DVar);
9366         continue;
9367       }
9368     }
9369 
9370     // Try to find 'declare reduction' corresponding construct before using
9371     // builtin/overloaded operators.
9372     CXXCastPath BasePath;
9373     ExprResult DeclareReductionRef = buildDeclareReductionRef(
9374         S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
9375         ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
9376     if (DeclareReductionRef.isInvalid())
9377       continue;
9378     if (S.CurContext->isDependentContext() &&
9379         (DeclareReductionRef.isUnset() ||
9380          isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
9381       RD.push(RefExpr, DeclareReductionRef.get());
9382       continue;
9383     }
9384     if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
9385       // Not allowed reduction identifier is found.
9386       S.Diag(ReductionId.getLocStart(),
9387              diag::err_omp_unknown_reduction_identifier)
9388           << Type << ReductionIdRange;
9389       continue;
9390     }
9391 
9392     // OpenMP [2.14.3.6, reduction clause, Restrictions]
9393     // The type of a list item that appears in a reduction clause must be valid
9394     // for the reduction-identifier. For a max or min reduction in C, the type
9395     // of the list item must be an allowed arithmetic data type: char, int,
9396     // float, double, or _Bool, possibly modified with long, short, signed, or
9397     // unsigned. For a max or min reduction in C++, the type of the list item
9398     // must be an allowed arithmetic data type: char, wchar_t, int, float,
9399     // double, or bool, possibly modified with long, short, signed, or unsigned.
9400     if (DeclareReductionRef.isUnset()) {
9401       if ((BOK == BO_GT || BOK == BO_LT) &&
9402           !(Type->isScalarType() ||
9403             (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
9404         S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
9405             << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus;
9406         if (!ASE && !OASE) {
9407           bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
9408                                    VarDecl::DeclarationOnly;
9409           S.Diag(D->getLocation(),
9410                  IsDecl ? diag::note_previous_decl : diag::note_defined_here)
9411               << D;
9412         }
9413         continue;
9414       }
9415       if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
9416           !S.getLangOpts().CPlusPlus && Type->isFloatingType()) {
9417         S.Diag(ELoc, diag::err_omp_clause_floating_type_arg)
9418             << getOpenMPClauseName(ClauseKind);
9419         if (!ASE && !OASE) {
9420           bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
9421                                    VarDecl::DeclarationOnly;
9422           S.Diag(D->getLocation(),
9423                  IsDecl ? diag::note_previous_decl : diag::note_defined_here)
9424               << D;
9425         }
9426         continue;
9427       }
9428     }
9429 
9430     Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
9431     auto *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs",
9432                                D->hasAttrs() ? &D->getAttrs() : nullptr);
9433     auto *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(),
9434                                D->hasAttrs() ? &D->getAttrs() : nullptr);
9435     auto PrivateTy = Type;
9436     if (OASE ||
9437         (!ASE &&
9438          D->getType().getNonReferenceType()->isVariablyModifiedType())) {
9439       // For arrays/array sections only:
9440       // Create pseudo array type for private copy. The size for this array will
9441       // be generated during codegen.
9442       // For array subscripts or single variables Private Ty is the same as Type
9443       // (type of the variable or single array element).
9444       PrivateTy = Context.getVariableArrayType(
9445           Type,
9446           new (Context) OpaqueValueExpr(SourceLocation(), Context.getSizeType(),
9447                                         VK_RValue),
9448           ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
9449     } else if (!ASE && !OASE &&
9450                Context.getAsArrayType(D->getType().getNonReferenceType()))
9451       PrivateTy = D->getType().getNonReferenceType();
9452     // Private copy.
9453     auto *PrivateVD = buildVarDecl(S, ELoc, PrivateTy, D->getName(),
9454                                    D->hasAttrs() ? &D->getAttrs() : nullptr);
9455     // Add initializer for private variable.
9456     Expr *Init = nullptr;
9457     auto *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc);
9458     auto *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc);
9459     if (DeclareReductionRef.isUsable()) {
9460       auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
9461       auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
9462       if (DRD->getInitializer()) {
9463         Init = DRDRef;
9464         RHSVD->setInit(DRDRef);
9465         RHSVD->setInitStyle(VarDecl::CallInit);
9466       }
9467     } else {
9468       switch (BOK) {
9469       case BO_Add:
9470       case BO_Xor:
9471       case BO_Or:
9472       case BO_LOr:
9473         // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
9474         if (Type->isScalarType() || Type->isAnyComplexType())
9475           Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get();
9476         break;
9477       case BO_Mul:
9478       case BO_LAnd:
9479         if (Type->isScalarType() || Type->isAnyComplexType()) {
9480           // '*' and '&&' reduction ops - initializer is '1'.
9481           Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get();
9482         }
9483         break;
9484       case BO_And: {
9485         // '&' reduction op - initializer is '~0'.
9486         QualType OrigType = Type;
9487         if (auto *ComplexTy = OrigType->getAs<ComplexType>())
9488           Type = ComplexTy->getElementType();
9489         if (Type->isRealFloatingType()) {
9490           llvm::APFloat InitValue =
9491               llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
9492                                              /*isIEEE=*/true);
9493           Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
9494                                          Type, ELoc);
9495         } else if (Type->isScalarType()) {
9496           auto Size = Context.getTypeSize(Type);
9497           QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
9498           llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
9499           Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
9500         }
9501         if (Init && OrigType->isAnyComplexType()) {
9502           // Init = 0xFFFF + 0xFFFFi;
9503           auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
9504           Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
9505         }
9506         Type = OrigType;
9507         break;
9508       }
9509       case BO_LT:
9510       case BO_GT: {
9511         // 'min' reduction op - initializer is 'Largest representable number in
9512         // the reduction list item type'.
9513         // 'max' reduction op - initializer is 'Least representable number in
9514         // the reduction list item type'.
9515         if (Type->isIntegerType() || Type->isPointerType()) {
9516           bool IsSigned = Type->hasSignedIntegerRepresentation();
9517           auto Size = Context.getTypeSize(Type);
9518           QualType IntTy =
9519               Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
9520           llvm::APInt InitValue =
9521               (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
9522                                         : llvm::APInt::getMinValue(Size)
9523                              : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
9524                                         : llvm::APInt::getMaxValue(Size);
9525           Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
9526           if (Type->isPointerType()) {
9527             // Cast to pointer type.
9528             auto CastExpr = S.BuildCStyleCastExpr(
9529                 SourceLocation(), Context.getTrivialTypeSourceInfo(Type, ELoc),
9530                 SourceLocation(), Init);
9531             if (CastExpr.isInvalid())
9532               continue;
9533             Init = CastExpr.get();
9534           }
9535         } else if (Type->isRealFloatingType()) {
9536           llvm::APFloat InitValue = llvm::APFloat::getLargest(
9537               Context.getFloatTypeSemantics(Type), BOK != BO_LT);
9538           Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
9539                                          Type, ELoc);
9540         }
9541         break;
9542       }
9543       case BO_PtrMemD:
9544       case BO_PtrMemI:
9545       case BO_MulAssign:
9546       case BO_Div:
9547       case BO_Rem:
9548       case BO_Sub:
9549       case BO_Shl:
9550       case BO_Shr:
9551       case BO_LE:
9552       case BO_GE:
9553       case BO_EQ:
9554       case BO_NE:
9555       case BO_AndAssign:
9556       case BO_XorAssign:
9557       case BO_OrAssign:
9558       case BO_Assign:
9559       case BO_AddAssign:
9560       case BO_SubAssign:
9561       case BO_DivAssign:
9562       case BO_RemAssign:
9563       case BO_ShlAssign:
9564       case BO_ShrAssign:
9565       case BO_Comma:
9566         llvm_unreachable("Unexpected reduction operation");
9567       }
9568     }
9569     if (Init && DeclareReductionRef.isUnset())
9570       S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
9571     else if (!Init)
9572       S.ActOnUninitializedDecl(RHSVD);
9573     if (RHSVD->isInvalidDecl())
9574       continue;
9575     if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) {
9576       S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible)
9577           << Type << ReductionIdRange;
9578       bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
9579                                VarDecl::DeclarationOnly;
9580       S.Diag(D->getLocation(),
9581              IsDecl ? diag::note_previous_decl : diag::note_defined_here)
9582           << D;
9583       continue;
9584     }
9585     // Store initializer for single element in private copy. Will be used during
9586     // codegen.
9587     PrivateVD->setInit(RHSVD->getInit());
9588     PrivateVD->setInitStyle(RHSVD->getInitStyle());
9589     auto *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc);
9590     ExprResult ReductionOp;
9591     if (DeclareReductionRef.isUsable()) {
9592       QualType RedTy = DeclareReductionRef.get()->getType();
9593       QualType PtrRedTy = Context.getPointerType(RedTy);
9594       ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
9595       ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
9596       if (!BasePath.empty()) {
9597         LHS = S.DefaultLvalueConversion(LHS.get());
9598         RHS = S.DefaultLvalueConversion(RHS.get());
9599         LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
9600                                        CK_UncheckedDerivedToBase, LHS.get(),
9601                                        &BasePath, LHS.get()->getValueKind());
9602         RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
9603                                        CK_UncheckedDerivedToBase, RHS.get(),
9604                                        &BasePath, RHS.get()->getValueKind());
9605       }
9606       FunctionProtoType::ExtProtoInfo EPI;
9607       QualType Params[] = {PtrRedTy, PtrRedTy};
9608       QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
9609       auto *OVE = new (Context) OpaqueValueExpr(
9610           ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
9611           S.DefaultLvalueConversion(DeclareReductionRef.get()).get());
9612       Expr *Args[] = {LHS.get(), RHS.get()};
9613       ReductionOp = new (Context)
9614           CallExpr(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
9615     } else {
9616       ReductionOp = S.BuildBinOp(
9617           Stack->getCurScope(), ReductionId.getLocStart(), BOK, LHSDRE, RHSDRE);
9618       if (ReductionOp.isUsable()) {
9619         if (BOK != BO_LT && BOK != BO_GT) {
9620           ReductionOp =
9621               S.BuildBinOp(Stack->getCurScope(), ReductionId.getLocStart(),
9622                            BO_Assign, LHSDRE, ReductionOp.get());
9623         } else {
9624           auto *ConditionalOp = new (Context) ConditionalOperator(
9625               ReductionOp.get(), SourceLocation(), LHSDRE, SourceLocation(),
9626               RHSDRE, Type, VK_LValue, OK_Ordinary);
9627           ReductionOp =
9628               S.BuildBinOp(Stack->getCurScope(), ReductionId.getLocStart(),
9629                            BO_Assign, LHSDRE, ConditionalOp);
9630         }
9631         if (ReductionOp.isUsable())
9632           ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get());
9633       }
9634       if (!ReductionOp.isUsable())
9635         continue;
9636     }
9637 
9638     // OpenMP [2.15.4.6, Restrictions, p.2]
9639     // A list item that appears in an in_reduction clause of a task construct
9640     // must appear in a task_reduction clause of a construct associated with a
9641     // taskgroup region that includes the participating task in its taskgroup
9642     // set. The construct associated with the innermost region that meets this
9643     // condition must specify the same reduction-identifier as the in_reduction
9644     // clause.
9645     if (ClauseKind == OMPC_in_reduction) {
9646       SourceRange ParentSR;
9647       BinaryOperatorKind ParentBOK;
9648       const Expr *ParentReductionOp;
9649       Expr *ParentBOKTD, *ParentReductionOpTD;
9650       DSAStackTy::DSAVarData ParentBOKDSA =
9651           Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK,
9652                                                   ParentBOKTD);
9653       DSAStackTy::DSAVarData ParentReductionOpDSA =
9654           Stack->getTopMostTaskgroupReductionData(
9655               D, ParentSR, ParentReductionOp, ParentReductionOpTD);
9656       bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown;
9657       bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown;
9658       if (!IsParentBOK && !IsParentReductionOp) {
9659         S.Diag(ELoc, diag::err_omp_in_reduction_not_task_reduction);
9660         continue;
9661       }
9662       if ((DeclareReductionRef.isUnset() && IsParentReductionOp) ||
9663           (DeclareReductionRef.isUsable() && IsParentBOK) || BOK != ParentBOK ||
9664           IsParentReductionOp) {
9665         bool EmitError = true;
9666         if (IsParentReductionOp && DeclareReductionRef.isUsable()) {
9667           llvm::FoldingSetNodeID RedId, ParentRedId;
9668           ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true);
9669           DeclareReductionRef.get()->Profile(RedId, Context,
9670                                              /*Canonical=*/true);
9671           EmitError = RedId != ParentRedId;
9672         }
9673         if (EmitError) {
9674           S.Diag(ReductionId.getLocStart(),
9675                  diag::err_omp_reduction_identifier_mismatch)
9676               << ReductionIdRange << RefExpr->getSourceRange();
9677           S.Diag(ParentSR.getBegin(),
9678                  diag::note_omp_previous_reduction_identifier)
9679               << ParentSR
9680               << (IsParentBOK ? ParentBOKDSA.RefExpr
9681                               : ParentReductionOpDSA.RefExpr)
9682                      ->getSourceRange();
9683           continue;
9684         }
9685       }
9686       TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD;
9687       assert(TaskgroupDescriptor && "Taskgroup descriptor must be defined.");
9688     }
9689 
9690     DeclRefExpr *Ref = nullptr;
9691     Expr *VarsExpr = RefExpr->IgnoreParens();
9692     if (!VD && !S.CurContext->isDependentContext()) {
9693       if (ASE || OASE) {
9694         TransformExprToCaptures RebuildToCapture(S, D);
9695         VarsExpr =
9696             RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
9697         Ref = RebuildToCapture.getCapturedExpr();
9698       } else {
9699         VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false);
9700       }
9701       if (!S.IsOpenMPCapturedDecl(D)) {
9702         RD.ExprCaptures.emplace_back(Ref->getDecl());
9703         if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
9704           ExprResult RefRes = S.DefaultLvalueConversion(Ref);
9705           if (!RefRes.isUsable())
9706             continue;
9707           ExprResult PostUpdateRes =
9708               S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
9709                            RefRes.get());
9710           if (!PostUpdateRes.isUsable())
9711             continue;
9712           if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
9713               Stack->getCurrentDirective() == OMPD_taskgroup) {
9714             S.Diag(RefExpr->getExprLoc(),
9715                    diag::err_omp_reduction_non_addressable_expression)
9716                 << RefExpr->getSourceRange();
9717             continue;
9718           }
9719           RD.ExprPostUpdates.emplace_back(
9720               S.IgnoredValueConversions(PostUpdateRes.get()).get());
9721         }
9722       }
9723     }
9724     // All reduction items are still marked as reduction (to do not increase
9725     // code base size).
9726     Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
9727     if (CurrDir == OMPD_taskgroup) {
9728       if (DeclareReductionRef.isUsable())
9729         Stack->addTaskgroupReductionData(D, ReductionIdRange,
9730                                          DeclareReductionRef.get());
9731       else
9732         Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK);
9733     }
9734     RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(),
9735             TaskgroupDescriptor);
9736   }
9737   return RD.Vars.empty();
9738 }
9739 
9740 OMPClause *Sema::ActOnOpenMPReductionClause(
9741     ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
9742     SourceLocation ColonLoc, SourceLocation EndLoc,
9743     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
9744     ArrayRef<Expr *> UnresolvedReductions) {
9745   ReductionData RD(VarList.size());
9746 
9747   if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList,
9748                                   StartLoc, LParenLoc, ColonLoc, EndLoc,
9749                                   ReductionIdScopeSpec, ReductionId,
9750                                   UnresolvedReductions, RD))
9751     return nullptr;
9752 
9753   return OMPReductionClause::Create(
9754       Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
9755       ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
9756       RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
9757       buildPreInits(Context, RD.ExprCaptures),
9758       buildPostUpdate(*this, RD.ExprPostUpdates));
9759 }
9760 
9761 OMPClause *Sema::ActOnOpenMPTaskReductionClause(
9762     ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
9763     SourceLocation ColonLoc, SourceLocation EndLoc,
9764     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
9765     ArrayRef<Expr *> UnresolvedReductions) {
9766   ReductionData RD(VarList.size());
9767 
9768   if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction,
9769                                   VarList, StartLoc, LParenLoc, ColonLoc,
9770                                   EndLoc, ReductionIdScopeSpec, ReductionId,
9771                                   UnresolvedReductions, RD))
9772     return nullptr;
9773 
9774   return OMPTaskReductionClause::Create(
9775       Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
9776       ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
9777       RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
9778       buildPreInits(Context, RD.ExprCaptures),
9779       buildPostUpdate(*this, RD.ExprPostUpdates));
9780 }
9781 
9782 OMPClause *Sema::ActOnOpenMPInReductionClause(
9783     ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
9784     SourceLocation ColonLoc, SourceLocation EndLoc,
9785     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
9786     ArrayRef<Expr *> UnresolvedReductions) {
9787   ReductionData RD(VarList.size());
9788 
9789   if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList,
9790                                   StartLoc, LParenLoc, ColonLoc, EndLoc,
9791                                   ReductionIdScopeSpec, ReductionId,
9792                                   UnresolvedReductions, RD))
9793     return nullptr;
9794 
9795   return OMPInReductionClause::Create(
9796       Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
9797       ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
9798       RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors,
9799       buildPreInits(Context, RD.ExprCaptures),
9800       buildPostUpdate(*this, RD.ExprPostUpdates));
9801 }
9802 
9803 bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
9804                                      SourceLocation LinLoc) {
9805   if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
9806       LinKind == OMPC_LINEAR_unknown) {
9807     Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
9808     return true;
9809   }
9810   return false;
9811 }
9812 
9813 bool Sema::CheckOpenMPLinearDecl(ValueDecl *D, SourceLocation ELoc,
9814                                  OpenMPLinearClauseKind LinKind,
9815                                  QualType Type) {
9816   auto *VD = dyn_cast_or_null<VarDecl>(D);
9817   // A variable must not have an incomplete type or a reference type.
9818   if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
9819     return true;
9820   if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
9821       !Type->isReferenceType()) {
9822     Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
9823         << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
9824     return true;
9825   }
9826   Type = Type.getNonReferenceType();
9827 
9828   // A list item must not be const-qualified.
9829   if (Type.isConstant(Context)) {
9830     Diag(ELoc, diag::err_omp_const_variable)
9831         << getOpenMPClauseName(OMPC_linear);
9832     if (D) {
9833       bool IsDecl =
9834           !VD ||
9835           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
9836       Diag(D->getLocation(),
9837            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
9838           << D;
9839     }
9840     return true;
9841   }
9842 
9843   // A list item must be of integral or pointer type.
9844   Type = Type.getUnqualifiedType().getCanonicalType();
9845   const auto *Ty = Type.getTypePtrOrNull();
9846   if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
9847               !Ty->isPointerType())) {
9848     Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
9849     if (D) {
9850       bool IsDecl =
9851           !VD ||
9852           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
9853       Diag(D->getLocation(),
9854            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
9855           << D;
9856     }
9857     return true;
9858   }
9859   return false;
9860 }
9861 
9862 OMPClause *Sema::ActOnOpenMPLinearClause(
9863     ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
9864     SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
9865     SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
9866   SmallVector<Expr *, 8> Vars;
9867   SmallVector<Expr *, 8> Privates;
9868   SmallVector<Expr *, 8> Inits;
9869   SmallVector<Decl *, 4> ExprCaptures;
9870   SmallVector<Expr *, 4> ExprPostUpdates;
9871   if (CheckOpenMPLinearModifier(LinKind, LinLoc))
9872     LinKind = OMPC_LINEAR_val;
9873   for (auto &RefExpr : VarList) {
9874     assert(RefExpr && "NULL expr in OpenMP linear clause.");
9875     SourceLocation ELoc;
9876     SourceRange ERange;
9877     Expr *SimpleRefExpr = RefExpr;
9878     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
9879                               /*AllowArraySection=*/false);
9880     if (Res.second) {
9881       // It will be analyzed later.
9882       Vars.push_back(RefExpr);
9883       Privates.push_back(nullptr);
9884       Inits.push_back(nullptr);
9885     }
9886     ValueDecl *D = Res.first;
9887     if (!D)
9888       continue;
9889 
9890     QualType Type = D->getType();
9891     auto *VD = dyn_cast<VarDecl>(D);
9892 
9893     // OpenMP [2.14.3.7, linear clause]
9894     //  A list-item cannot appear in more than one linear clause.
9895     //  A list-item that appears in a linear clause cannot appear in any
9896     //  other data-sharing attribute clause.
9897     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
9898     if (DVar.RefExpr) {
9899       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
9900                                           << getOpenMPClauseName(OMPC_linear);
9901       ReportOriginalDSA(*this, DSAStack, D, DVar);
9902       continue;
9903     }
9904 
9905     if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
9906       continue;
9907     Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
9908 
9909     // Build private copy of original var.
9910     auto *Private = buildVarDecl(*this, ELoc, Type, D->getName(),
9911                                  D->hasAttrs() ? &D->getAttrs() : nullptr);
9912     auto *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
9913     // Build var to save initial value.
9914     VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
9915     Expr *InitExpr;
9916     DeclRefExpr *Ref = nullptr;
9917     if (!VD && !CurContext->isDependentContext()) {
9918       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
9919       if (!IsOpenMPCapturedDecl(D)) {
9920         ExprCaptures.push_back(Ref->getDecl());
9921         if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
9922           ExprResult RefRes = DefaultLvalueConversion(Ref);
9923           if (!RefRes.isUsable())
9924             continue;
9925           ExprResult PostUpdateRes =
9926               BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
9927                          SimpleRefExpr, RefRes.get());
9928           if (!PostUpdateRes.isUsable())
9929             continue;
9930           ExprPostUpdates.push_back(
9931               IgnoredValueConversions(PostUpdateRes.get()).get());
9932         }
9933       }
9934     }
9935     if (LinKind == OMPC_LINEAR_uval)
9936       InitExpr = VD ? VD->getInit() : SimpleRefExpr;
9937     else
9938       InitExpr = VD ? SimpleRefExpr : Ref;
9939     AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
9940                          /*DirectInit=*/false);
9941     auto InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
9942 
9943     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
9944     Vars.push_back((VD || CurContext->isDependentContext())
9945                        ? RefExpr->IgnoreParens()
9946                        : Ref);
9947     Privates.push_back(PrivateRef);
9948     Inits.push_back(InitRef);
9949   }
9950 
9951   if (Vars.empty())
9952     return nullptr;
9953 
9954   Expr *StepExpr = Step;
9955   Expr *CalcStepExpr = nullptr;
9956   if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
9957       !Step->isInstantiationDependent() &&
9958       !Step->containsUnexpandedParameterPack()) {
9959     SourceLocation StepLoc = Step->getLocStart();
9960     ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
9961     if (Val.isInvalid())
9962       return nullptr;
9963     StepExpr = Val.get();
9964 
9965     // Build var to save the step value.
9966     VarDecl *SaveVar =
9967         buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
9968     ExprResult SaveRef =
9969         buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
9970     ExprResult CalcStep =
9971         BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
9972     CalcStep = ActOnFinishFullExpr(CalcStep.get());
9973 
9974     // Warn about zero linear step (it would be probably better specified as
9975     // making corresponding variables 'const').
9976     llvm::APSInt Result;
9977     bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
9978     if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
9979       Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
9980                                                      << (Vars.size() > 1);
9981     if (!IsConstant && CalcStep.isUsable()) {
9982       // Calculate the step beforehand instead of doing this on each iteration.
9983       // (This is not used if the number of iterations may be kfold-ed).
9984       CalcStepExpr = CalcStep.get();
9985     }
9986   }
9987 
9988   return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
9989                                  ColonLoc, EndLoc, Vars, Privates, Inits,
9990                                  StepExpr, CalcStepExpr,
9991                                  buildPreInits(Context, ExprCaptures),
9992                                  buildPostUpdate(*this, ExprPostUpdates));
9993 }
9994 
9995 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
9996                                      Expr *NumIterations, Sema &SemaRef,
9997                                      Scope *S, DSAStackTy *Stack) {
9998   // Walk the vars and build update/final expressions for the CodeGen.
9999   SmallVector<Expr *, 8> Updates;
10000   SmallVector<Expr *, 8> Finals;
10001   Expr *Step = Clause.getStep();
10002   Expr *CalcStep = Clause.getCalcStep();
10003   // OpenMP [2.14.3.7, linear clause]
10004   // If linear-step is not specified it is assumed to be 1.
10005   if (Step == nullptr)
10006     Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
10007   else if (CalcStep) {
10008     Step = cast<BinaryOperator>(CalcStep)->getLHS();
10009   }
10010   bool HasErrors = false;
10011   auto CurInit = Clause.inits().begin();
10012   auto CurPrivate = Clause.privates().begin();
10013   auto LinKind = Clause.getModifier();
10014   for (auto &RefExpr : Clause.varlists()) {
10015     SourceLocation ELoc;
10016     SourceRange ERange;
10017     Expr *SimpleRefExpr = RefExpr;
10018     auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange,
10019                               /*AllowArraySection=*/false);
10020     ValueDecl *D = Res.first;
10021     if (Res.second || !D) {
10022       Updates.push_back(nullptr);
10023       Finals.push_back(nullptr);
10024       HasErrors = true;
10025       continue;
10026     }
10027     auto &&Info = Stack->isLoopControlVariable(D);
10028     Expr *InitExpr = *CurInit;
10029 
10030     // Build privatized reference to the current linear var.
10031     auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
10032     Expr *CapturedRef;
10033     if (LinKind == OMPC_LINEAR_uval)
10034       CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
10035     else
10036       CapturedRef =
10037           buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
10038                            DE->getType().getUnqualifiedType(), DE->getExprLoc(),
10039                            /*RefersToCapture=*/true);
10040 
10041     // Build update: Var = InitExpr + IV * Step
10042     ExprResult Update;
10043     if (!Info.first) {
10044       Update =
10045           BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate,
10046                              InitExpr, IV, Step, /* Subtract */ false);
10047     } else
10048       Update = *CurPrivate;
10049     Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getLocStart(),
10050                                          /*DiscardedValue=*/true);
10051 
10052     // Build final: Var = InitExpr + NumIterations * Step
10053     ExprResult Final;
10054     if (!Info.first) {
10055       Final = BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
10056                                  InitExpr, NumIterations, Step,
10057                                  /* Subtract */ false);
10058     } else
10059       Final = *CurPrivate;
10060     Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getLocStart(),
10061                                         /*DiscardedValue=*/true);
10062 
10063     if (!Update.isUsable() || !Final.isUsable()) {
10064       Updates.push_back(nullptr);
10065       Finals.push_back(nullptr);
10066       HasErrors = true;
10067     } else {
10068       Updates.push_back(Update.get());
10069       Finals.push_back(Final.get());
10070     }
10071     ++CurInit;
10072     ++CurPrivate;
10073   }
10074   Clause.setUpdates(Updates);
10075   Clause.setFinals(Finals);
10076   return HasErrors;
10077 }
10078 
10079 OMPClause *Sema::ActOnOpenMPAlignedClause(
10080     ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
10081     SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
10082 
10083   SmallVector<Expr *, 8> Vars;
10084   for (auto &RefExpr : VarList) {
10085     assert(RefExpr && "NULL expr in OpenMP linear clause.");
10086     SourceLocation ELoc;
10087     SourceRange ERange;
10088     Expr *SimpleRefExpr = RefExpr;
10089     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
10090                               /*AllowArraySection=*/false);
10091     if (Res.second) {
10092       // It will be analyzed later.
10093       Vars.push_back(RefExpr);
10094     }
10095     ValueDecl *D = Res.first;
10096     if (!D)
10097       continue;
10098 
10099     QualType QType = D->getType();
10100     auto *VD = dyn_cast<VarDecl>(D);
10101 
10102     // OpenMP  [2.8.1, simd construct, Restrictions]
10103     // The type of list items appearing in the aligned clause must be
10104     // array, pointer, reference to array, or reference to pointer.
10105     QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
10106     const Type *Ty = QType.getTypePtrOrNull();
10107     if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
10108       Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
10109           << QType << getLangOpts().CPlusPlus << ERange;
10110       bool IsDecl =
10111           !VD ||
10112           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
10113       Diag(D->getLocation(),
10114            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
10115           << D;
10116       continue;
10117     }
10118 
10119     // OpenMP  [2.8.1, simd construct, Restrictions]
10120     // A list-item cannot appear in more than one aligned clause.
10121     if (Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
10122       Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
10123       Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
10124           << getOpenMPClauseName(OMPC_aligned);
10125       continue;
10126     }
10127 
10128     DeclRefExpr *Ref = nullptr;
10129     if (!VD && IsOpenMPCapturedDecl(D))
10130       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
10131     Vars.push_back(DefaultFunctionArrayConversion(
10132                        (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
10133                        .get());
10134   }
10135 
10136   // OpenMP [2.8.1, simd construct, Description]
10137   // The parameter of the aligned clause, alignment, must be a constant
10138   // positive integer expression.
10139   // If no optional parameter is specified, implementation-defined default
10140   // alignments for SIMD instructions on the target platforms are assumed.
10141   if (Alignment != nullptr) {
10142     ExprResult AlignResult =
10143         VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
10144     if (AlignResult.isInvalid())
10145       return nullptr;
10146     Alignment = AlignResult.get();
10147   }
10148   if (Vars.empty())
10149     return nullptr;
10150 
10151   return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
10152                                   EndLoc, Vars, Alignment);
10153 }
10154 
10155 OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
10156                                          SourceLocation StartLoc,
10157                                          SourceLocation LParenLoc,
10158                                          SourceLocation EndLoc) {
10159   SmallVector<Expr *, 8> Vars;
10160   SmallVector<Expr *, 8> SrcExprs;
10161   SmallVector<Expr *, 8> DstExprs;
10162   SmallVector<Expr *, 8> AssignmentOps;
10163   for (auto &RefExpr : VarList) {
10164     assert(RefExpr && "NULL expr in OpenMP copyin clause.");
10165     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
10166       // It will be analyzed later.
10167       Vars.push_back(RefExpr);
10168       SrcExprs.push_back(nullptr);
10169       DstExprs.push_back(nullptr);
10170       AssignmentOps.push_back(nullptr);
10171       continue;
10172     }
10173 
10174     SourceLocation ELoc = RefExpr->getExprLoc();
10175     // OpenMP [2.1, C/C++]
10176     //  A list item is a variable name.
10177     // OpenMP  [2.14.4.1, Restrictions, p.1]
10178     //  A list item that appears in a copyin clause must be threadprivate.
10179     DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
10180     if (!DE || !isa<VarDecl>(DE->getDecl())) {
10181       Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
10182           << 0 << RefExpr->getSourceRange();
10183       continue;
10184     }
10185 
10186     Decl *D = DE->getDecl();
10187     VarDecl *VD = cast<VarDecl>(D);
10188 
10189     QualType Type = VD->getType();
10190     if (Type->isDependentType() || Type->isInstantiationDependentType()) {
10191       // It will be analyzed later.
10192       Vars.push_back(DE);
10193       SrcExprs.push_back(nullptr);
10194       DstExprs.push_back(nullptr);
10195       AssignmentOps.push_back(nullptr);
10196       continue;
10197     }
10198 
10199     // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
10200     //  A list item that appears in a copyin clause must be threadprivate.
10201     if (!DSAStack->isThreadPrivate(VD)) {
10202       Diag(ELoc, diag::err_omp_required_access)
10203           << getOpenMPClauseName(OMPC_copyin)
10204           << getOpenMPDirectiveName(OMPD_threadprivate);
10205       continue;
10206     }
10207 
10208     // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
10209     //  A variable of class type (or array thereof) that appears in a
10210     //  copyin clause requires an accessible, unambiguous copy assignment
10211     //  operator for the class type.
10212     auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
10213     auto *SrcVD =
10214         buildVarDecl(*this, DE->getLocStart(), ElemType.getUnqualifiedType(),
10215                      ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
10216     auto *PseudoSrcExpr = buildDeclRefExpr(
10217         *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
10218     auto *DstVD =
10219         buildVarDecl(*this, DE->getLocStart(), ElemType, ".copyin.dst",
10220                      VD->hasAttrs() ? &VD->getAttrs() : nullptr);
10221     auto *PseudoDstExpr =
10222         buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
10223     // For arrays generate assignment operation for single element and replace
10224     // it by the original array element in CodeGen.
10225     auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
10226                                    PseudoDstExpr, PseudoSrcExpr);
10227     if (AssignmentOp.isInvalid())
10228       continue;
10229     AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
10230                                        /*DiscardedValue=*/true);
10231     if (AssignmentOp.isInvalid())
10232       continue;
10233 
10234     DSAStack->addDSA(VD, DE, OMPC_copyin);
10235     Vars.push_back(DE);
10236     SrcExprs.push_back(PseudoSrcExpr);
10237     DstExprs.push_back(PseudoDstExpr);
10238     AssignmentOps.push_back(AssignmentOp.get());
10239   }
10240 
10241   if (Vars.empty())
10242     return nullptr;
10243 
10244   return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
10245                                  SrcExprs, DstExprs, AssignmentOps);
10246 }
10247 
10248 OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
10249                                               SourceLocation StartLoc,
10250                                               SourceLocation LParenLoc,
10251                                               SourceLocation EndLoc) {
10252   SmallVector<Expr *, 8> Vars;
10253   SmallVector<Expr *, 8> SrcExprs;
10254   SmallVector<Expr *, 8> DstExprs;
10255   SmallVector<Expr *, 8> AssignmentOps;
10256   for (auto &RefExpr : VarList) {
10257     assert(RefExpr && "NULL expr in OpenMP linear clause.");
10258     SourceLocation ELoc;
10259     SourceRange ERange;
10260     Expr *SimpleRefExpr = RefExpr;
10261     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
10262                               /*AllowArraySection=*/false);
10263     if (Res.second) {
10264       // It will be analyzed later.
10265       Vars.push_back(RefExpr);
10266       SrcExprs.push_back(nullptr);
10267       DstExprs.push_back(nullptr);
10268       AssignmentOps.push_back(nullptr);
10269     }
10270     ValueDecl *D = Res.first;
10271     if (!D)
10272       continue;
10273 
10274     QualType Type = D->getType();
10275     auto *VD = dyn_cast<VarDecl>(D);
10276 
10277     // OpenMP [2.14.4.2, Restrictions, p.2]
10278     //  A list item that appears in a copyprivate clause may not appear in a
10279     //  private or firstprivate clause on the single construct.
10280     if (!VD || !DSAStack->isThreadPrivate(VD)) {
10281       auto DVar = DSAStack->getTopDSA(D, false);
10282       if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
10283           DVar.RefExpr) {
10284         Diag(ELoc, diag::err_omp_wrong_dsa)
10285             << getOpenMPClauseName(DVar.CKind)
10286             << getOpenMPClauseName(OMPC_copyprivate);
10287         ReportOriginalDSA(*this, DSAStack, D, DVar);
10288         continue;
10289       }
10290 
10291       // OpenMP [2.11.4.2, Restrictions, p.1]
10292       //  All list items that appear in a copyprivate clause must be either
10293       //  threadprivate or private in the enclosing context.
10294       if (DVar.CKind == OMPC_unknown) {
10295         DVar = DSAStack->getImplicitDSA(D, false);
10296         if (DVar.CKind == OMPC_shared) {
10297           Diag(ELoc, diag::err_omp_required_access)
10298               << getOpenMPClauseName(OMPC_copyprivate)
10299               << "threadprivate or private in the enclosing context";
10300           ReportOriginalDSA(*this, DSAStack, D, DVar);
10301           continue;
10302         }
10303       }
10304     }
10305 
10306     // Variably modified types are not supported.
10307     if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
10308       Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
10309           << getOpenMPClauseName(OMPC_copyprivate) << Type
10310           << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
10311       bool IsDecl =
10312           !VD ||
10313           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
10314       Diag(D->getLocation(),
10315            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
10316           << D;
10317       continue;
10318     }
10319 
10320     // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
10321     //  A variable of class type (or array thereof) that appears in a
10322     //  copyin clause requires an accessible, unambiguous copy assignment
10323     //  operator for the class type.
10324     Type = Context.getBaseElementType(Type.getNonReferenceType())
10325                .getUnqualifiedType();
10326     auto *SrcVD =
10327         buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.src",
10328                      D->hasAttrs() ? &D->getAttrs() : nullptr);
10329     auto *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
10330     auto *DstVD =
10331         buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.dst",
10332                      D->hasAttrs() ? &D->getAttrs() : nullptr);
10333     auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
10334     auto AssignmentOp = BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
10335                                    PseudoDstExpr, PseudoSrcExpr);
10336     if (AssignmentOp.isInvalid())
10337       continue;
10338     AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
10339                                        /*DiscardedValue=*/true);
10340     if (AssignmentOp.isInvalid())
10341       continue;
10342 
10343     // No need to mark vars as copyprivate, they are already threadprivate or
10344     // implicitly private.
10345     assert(VD || IsOpenMPCapturedDecl(D));
10346     Vars.push_back(
10347         VD ? RefExpr->IgnoreParens()
10348            : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
10349     SrcExprs.push_back(PseudoSrcExpr);
10350     DstExprs.push_back(PseudoDstExpr);
10351     AssignmentOps.push_back(AssignmentOp.get());
10352   }
10353 
10354   if (Vars.empty())
10355     return nullptr;
10356 
10357   return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
10358                                       Vars, SrcExprs, DstExprs, AssignmentOps);
10359 }
10360 
10361 OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
10362                                         SourceLocation StartLoc,
10363                                         SourceLocation LParenLoc,
10364                                         SourceLocation EndLoc) {
10365   if (VarList.empty())
10366     return nullptr;
10367 
10368   return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
10369 }
10370 
10371 OMPClause *
10372 Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
10373                               SourceLocation DepLoc, SourceLocation ColonLoc,
10374                               ArrayRef<Expr *> VarList, SourceLocation StartLoc,
10375                               SourceLocation LParenLoc, SourceLocation EndLoc) {
10376   if (DSAStack->getCurrentDirective() == OMPD_ordered &&
10377       DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
10378     Diag(DepLoc, diag::err_omp_unexpected_clause_value)
10379         << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
10380     return nullptr;
10381   }
10382   if (DSAStack->getCurrentDirective() != OMPD_ordered &&
10383       (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
10384        DepKind == OMPC_DEPEND_sink)) {
10385     unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
10386     Diag(DepLoc, diag::err_omp_unexpected_clause_value)
10387         << getListOfPossibleValues(OMPC_depend, /*First=*/0,
10388                                    /*Last=*/OMPC_DEPEND_unknown, Except)
10389         << getOpenMPClauseName(OMPC_depend);
10390     return nullptr;
10391   }
10392   SmallVector<Expr *, 8> Vars;
10393   DSAStackTy::OperatorOffsetTy OpsOffs;
10394   llvm::APSInt DepCounter(/*BitWidth=*/32);
10395   llvm::APSInt TotalDepCount(/*BitWidth=*/32);
10396   if (DepKind == OMPC_DEPEND_sink) {
10397     if (auto *OrderedCountExpr = DSAStack->getParentOrderedRegionParam()) {
10398       TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
10399       TotalDepCount.setIsUnsigned(/*Val=*/true);
10400     }
10401   }
10402   if ((DepKind != OMPC_DEPEND_sink && DepKind != OMPC_DEPEND_source) ||
10403       DSAStack->getParentOrderedRegionParam()) {
10404     for (auto &RefExpr : VarList) {
10405       assert(RefExpr && "NULL expr in OpenMP shared clause.");
10406       if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
10407         // It will be analyzed later.
10408         Vars.push_back(RefExpr);
10409         continue;
10410       }
10411 
10412       SourceLocation ELoc = RefExpr->getExprLoc();
10413       auto *SimpleExpr = RefExpr->IgnoreParenCasts();
10414       if (DepKind == OMPC_DEPEND_sink) {
10415         if (DepCounter >= TotalDepCount) {
10416           Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
10417           continue;
10418         }
10419         ++DepCounter;
10420         // OpenMP  [2.13.9, Summary]
10421         // depend(dependence-type : vec), where dependence-type is:
10422         // 'sink' and where vec is the iteration vector, which has the form:
10423         //  x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
10424         // where n is the value specified by the ordered clause in the loop
10425         // directive, xi denotes the loop iteration variable of the i-th nested
10426         // loop associated with the loop directive, and di is a constant
10427         // non-negative integer.
10428         if (CurContext->isDependentContext()) {
10429           // It will be analyzed later.
10430           Vars.push_back(RefExpr);
10431           continue;
10432         }
10433         SimpleExpr = SimpleExpr->IgnoreImplicit();
10434         OverloadedOperatorKind OOK = OO_None;
10435         SourceLocation OOLoc;
10436         Expr *LHS = SimpleExpr;
10437         Expr *RHS = nullptr;
10438         if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
10439           OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
10440           OOLoc = BO->getOperatorLoc();
10441           LHS = BO->getLHS()->IgnoreParenImpCasts();
10442           RHS = BO->getRHS()->IgnoreParenImpCasts();
10443         } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
10444           OOK = OCE->getOperator();
10445           OOLoc = OCE->getOperatorLoc();
10446           LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
10447           RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
10448         } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
10449           OOK = MCE->getMethodDecl()
10450                     ->getNameInfo()
10451                     .getName()
10452                     .getCXXOverloadedOperator();
10453           OOLoc = MCE->getCallee()->getExprLoc();
10454           LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
10455           RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
10456         }
10457         SourceLocation ELoc;
10458         SourceRange ERange;
10459         auto Res = getPrivateItem(*this, LHS, ELoc, ERange,
10460                                   /*AllowArraySection=*/false);
10461         if (Res.second) {
10462           // It will be analyzed later.
10463           Vars.push_back(RefExpr);
10464         }
10465         ValueDecl *D = Res.first;
10466         if (!D)
10467           continue;
10468 
10469         if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
10470           Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
10471           continue;
10472         }
10473         if (RHS) {
10474           ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
10475               RHS, OMPC_depend, /*StrictlyPositive=*/false);
10476           if (RHSRes.isInvalid())
10477             continue;
10478         }
10479         if (!CurContext->isDependentContext() &&
10480             DSAStack->getParentOrderedRegionParam() &&
10481             DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
10482           Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
10483               << DSAStack->getParentLoopControlVariable(
10484                      DepCounter.getZExtValue());
10485           continue;
10486         }
10487         OpsOffs.push_back({RHS, OOK});
10488       } else {
10489         auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
10490         if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
10491             (ASE &&
10492              !ASE->getBase()
10493                   ->getType()
10494                   .getNonReferenceType()
10495                   ->isPointerType() &&
10496              !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
10497           Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
10498               << RefExpr->getSourceRange();
10499           continue;
10500         }
10501         bool Suppress = getDiagnostics().getSuppressAllDiagnostics();
10502         getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
10503         ExprResult Res = CreateBuiltinUnaryOp(SourceLocation(), UO_AddrOf,
10504                                               RefExpr->IgnoreParenImpCasts());
10505         getDiagnostics().setSuppressAllDiagnostics(Suppress);
10506         if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr)) {
10507           Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
10508               << RefExpr->getSourceRange();
10509           continue;
10510         }
10511       }
10512       Vars.push_back(RefExpr->IgnoreParenImpCasts());
10513     }
10514 
10515     if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
10516         TotalDepCount > VarList.size() &&
10517         DSAStack->getParentOrderedRegionParam()) {
10518       Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
10519           << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
10520     }
10521     if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
10522         Vars.empty())
10523       return nullptr;
10524   }
10525   auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
10526                                     DepKind, DepLoc, ColonLoc, Vars);
10527   if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source)
10528     DSAStack->addDoacrossDependClause(C, OpsOffs);
10529   return C;
10530 }
10531 
10532 OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
10533                                          SourceLocation LParenLoc,
10534                                          SourceLocation EndLoc) {
10535   Expr *ValExpr = Device;
10536 
10537   // OpenMP [2.9.1, Restrictions]
10538   // The device expression must evaluate to a non-negative integer value.
10539   if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
10540                                  /*StrictlyPositive=*/false))
10541     return nullptr;
10542 
10543   return new (Context) OMPDeviceClause(ValExpr, StartLoc, LParenLoc, EndLoc);
10544 }
10545 
10546 static bool IsCXXRecordForMappable(Sema &SemaRef, SourceLocation Loc,
10547                                    DSAStackTy *Stack, CXXRecordDecl *RD) {
10548   if (!RD || RD->isInvalidDecl())
10549     return true;
10550 
10551   auto QTy = SemaRef.Context.getRecordType(RD);
10552   if (RD->isDynamicClass()) {
10553     SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
10554     SemaRef.Diag(RD->getLocation(), diag::note_omp_polymorphic_in_target);
10555     return false;
10556   }
10557   auto *DC = RD;
10558   bool IsCorrect = true;
10559   for (auto *I : DC->decls()) {
10560     if (I) {
10561       if (auto *MD = dyn_cast<CXXMethodDecl>(I)) {
10562         if (MD->isStatic()) {
10563           SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
10564           SemaRef.Diag(MD->getLocation(),
10565                        diag::note_omp_static_member_in_target);
10566           IsCorrect = false;
10567         }
10568       } else if (auto *VD = dyn_cast<VarDecl>(I)) {
10569         if (VD->isStaticDataMember()) {
10570           SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
10571           SemaRef.Diag(VD->getLocation(),
10572                        diag::note_omp_static_member_in_target);
10573           IsCorrect = false;
10574         }
10575       }
10576     }
10577   }
10578 
10579   for (auto &I : RD->bases()) {
10580     if (!IsCXXRecordForMappable(SemaRef, I.getLocStart(), Stack,
10581                                 I.getType()->getAsCXXRecordDecl()))
10582       IsCorrect = false;
10583   }
10584   return IsCorrect;
10585 }
10586 
10587 static bool CheckTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
10588                               DSAStackTy *Stack, QualType QTy) {
10589   NamedDecl *ND;
10590   if (QTy->isIncompleteType(&ND)) {
10591     SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
10592     return false;
10593   } else if (CXXRecordDecl *RD = dyn_cast_or_null<CXXRecordDecl>(ND)) {
10594     if (!RD->isInvalidDecl() && !IsCXXRecordForMappable(SemaRef, SL, Stack, RD))
10595       return false;
10596   }
10597   return true;
10598 }
10599 
10600 /// \brief Return true if it can be proven that the provided array expression
10601 /// (array section or array subscript) does NOT specify the whole size of the
10602 /// array whose base type is \a BaseQTy.
10603 static bool CheckArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
10604                                                         const Expr *E,
10605                                                         QualType BaseQTy) {
10606   auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
10607 
10608   // If this is an array subscript, it refers to the whole size if the size of
10609   // the dimension is constant and equals 1. Also, an array section assumes the
10610   // format of an array subscript if no colon is used.
10611   if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
10612     if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
10613       return ATy->getSize().getSExtValue() != 1;
10614     // Size can't be evaluated statically.
10615     return false;
10616   }
10617 
10618   assert(OASE && "Expecting array section if not an array subscript.");
10619   auto *LowerBound = OASE->getLowerBound();
10620   auto *Length = OASE->getLength();
10621 
10622   // If there is a lower bound that does not evaluates to zero, we are not
10623   // covering the whole dimension.
10624   if (LowerBound) {
10625     llvm::APSInt ConstLowerBound;
10626     if (!LowerBound->EvaluateAsInt(ConstLowerBound, SemaRef.getASTContext()))
10627       return false; // Can't get the integer value as a constant.
10628     if (ConstLowerBound.getSExtValue())
10629       return true;
10630   }
10631 
10632   // If we don't have a length we covering the whole dimension.
10633   if (!Length)
10634     return false;
10635 
10636   // If the base is a pointer, we don't have a way to get the size of the
10637   // pointee.
10638   if (BaseQTy->isPointerType())
10639     return false;
10640 
10641   // We can only check if the length is the same as the size of the dimension
10642   // if we have a constant array.
10643   auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
10644   if (!CATy)
10645     return false;
10646 
10647   llvm::APSInt ConstLength;
10648   if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
10649     return false; // Can't get the integer value as a constant.
10650 
10651   return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
10652 }
10653 
10654 // Return true if it can be proven that the provided array expression (array
10655 // section or array subscript) does NOT specify a single element of the array
10656 // whose base type is \a BaseQTy.
10657 static bool CheckArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
10658                                                         const Expr *E,
10659                                                         QualType BaseQTy) {
10660   auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
10661 
10662   // An array subscript always refer to a single element. Also, an array section
10663   // assumes the format of an array subscript if no colon is used.
10664   if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
10665     return false;
10666 
10667   assert(OASE && "Expecting array section if not an array subscript.");
10668   auto *Length = OASE->getLength();
10669 
10670   // If we don't have a length we have to check if the array has unitary size
10671   // for this dimension. Also, we should always expect a length if the base type
10672   // is pointer.
10673   if (!Length) {
10674     if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
10675       return ATy->getSize().getSExtValue() != 1;
10676     // We cannot assume anything.
10677     return false;
10678   }
10679 
10680   // Check if the length evaluates to 1.
10681   llvm::APSInt ConstLength;
10682   if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
10683     return false; // Can't get the integer value as a constant.
10684 
10685   return ConstLength.getSExtValue() != 1;
10686 }
10687 
10688 // Return the expression of the base of the mappable expression or null if it
10689 // cannot be determined and do all the necessary checks to see if the expression
10690 // is valid as a standalone mappable expression. In the process, record all the
10691 // components of the expression.
10692 static Expr *CheckMapClauseExpressionBase(
10693     Sema &SemaRef, Expr *E,
10694     OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
10695     OpenMPClauseKind CKind) {
10696   SourceLocation ELoc = E->getExprLoc();
10697   SourceRange ERange = E->getSourceRange();
10698 
10699   // The base of elements of list in a map clause have to be either:
10700   //  - a reference to variable or field.
10701   //  - a member expression.
10702   //  - an array expression.
10703   //
10704   // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
10705   // reference to 'r'.
10706   //
10707   // If we have:
10708   //
10709   // struct SS {
10710   //   Bla S;
10711   //   foo() {
10712   //     #pragma omp target map (S.Arr[:12]);
10713   //   }
10714   // }
10715   //
10716   // We want to retrieve the member expression 'this->S';
10717 
10718   Expr *RelevantExpr = nullptr;
10719 
10720   // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
10721   //  If a list item is an array section, it must specify contiguous storage.
10722   //
10723   // For this restriction it is sufficient that we make sure only references
10724   // to variables or fields and array expressions, and that no array sections
10725   // exist except in the rightmost expression (unless they cover the whole
10726   // dimension of the array). E.g. these would be invalid:
10727   //
10728   //   r.ArrS[3:5].Arr[6:7]
10729   //
10730   //   r.ArrS[3:5].x
10731   //
10732   // but these would be valid:
10733   //   r.ArrS[3].Arr[6:7]
10734   //
10735   //   r.ArrS[3].x
10736 
10737   bool AllowUnitySizeArraySection = true;
10738   bool AllowWholeSizeArraySection = true;
10739 
10740   while (!RelevantExpr) {
10741     E = E->IgnoreParenImpCasts();
10742 
10743     if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
10744       if (!isa<VarDecl>(CurE->getDecl()))
10745         break;
10746 
10747       RelevantExpr = CurE;
10748 
10749       // If we got a reference to a declaration, we should not expect any array
10750       // section before that.
10751       AllowUnitySizeArraySection = false;
10752       AllowWholeSizeArraySection = false;
10753 
10754       // Record the component.
10755       CurComponents.push_back(OMPClauseMappableExprCommon::MappableComponent(
10756           CurE, CurE->getDecl()));
10757       continue;
10758     }
10759 
10760     if (auto *CurE = dyn_cast<MemberExpr>(E)) {
10761       auto *BaseE = CurE->getBase()->IgnoreParenImpCasts();
10762 
10763       if (isa<CXXThisExpr>(BaseE))
10764         // We found a base expression: this->Val.
10765         RelevantExpr = CurE;
10766       else
10767         E = BaseE;
10768 
10769       if (!isa<FieldDecl>(CurE->getMemberDecl())) {
10770         SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
10771             << CurE->getSourceRange();
10772         break;
10773       }
10774 
10775       auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
10776 
10777       // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
10778       //  A bit-field cannot appear in a map clause.
10779       //
10780       if (FD->isBitField()) {
10781         SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
10782             << CurE->getSourceRange() << getOpenMPClauseName(CKind);
10783         break;
10784       }
10785 
10786       // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
10787       //  If the type of a list item is a reference to a type T then the type
10788       //  will be considered to be T for all purposes of this clause.
10789       QualType CurType = BaseE->getType().getNonReferenceType();
10790 
10791       // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
10792       //  A list item cannot be a variable that is a member of a structure with
10793       //  a union type.
10794       //
10795       if (auto *RT = CurType->getAs<RecordType>())
10796         if (RT->isUnionType()) {
10797           SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
10798               << CurE->getSourceRange();
10799           break;
10800         }
10801 
10802       // If we got a member expression, we should not expect any array section
10803       // before that:
10804       //
10805       // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
10806       //  If a list item is an element of a structure, only the rightmost symbol
10807       //  of the variable reference can be an array section.
10808       //
10809       AllowUnitySizeArraySection = false;
10810       AllowWholeSizeArraySection = false;
10811 
10812       // Record the component.
10813       CurComponents.push_back(
10814           OMPClauseMappableExprCommon::MappableComponent(CurE, FD));
10815       continue;
10816     }
10817 
10818     if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
10819       E = CurE->getBase()->IgnoreParenImpCasts();
10820 
10821       if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
10822         SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
10823             << 0 << CurE->getSourceRange();
10824         break;
10825       }
10826 
10827       // If we got an array subscript that express the whole dimension we
10828       // can have any array expressions before. If it only expressing part of
10829       // the dimension, we can only have unitary-size array expressions.
10830       if (CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
10831                                                       E->getType()))
10832         AllowWholeSizeArraySection = false;
10833 
10834       // Record the component - we don't have any declaration associated.
10835       CurComponents.push_back(
10836           OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr));
10837       continue;
10838     }
10839 
10840     if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
10841       E = CurE->getBase()->IgnoreParenImpCasts();
10842 
10843       auto CurType =
10844           OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
10845 
10846       // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
10847       //  If the type of a list item is a reference to a type T then the type
10848       //  will be considered to be T for all purposes of this clause.
10849       if (CurType->isReferenceType())
10850         CurType = CurType->getPointeeType();
10851 
10852       bool IsPointer = CurType->isAnyPointerType();
10853 
10854       if (!IsPointer && !CurType->isArrayType()) {
10855         SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
10856             << 0 << CurE->getSourceRange();
10857         break;
10858       }
10859 
10860       bool NotWhole =
10861           CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
10862       bool NotUnity =
10863           CheckArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
10864 
10865       if (AllowWholeSizeArraySection) {
10866         // Any array section is currently allowed. Allowing a whole size array
10867         // section implies allowing a unity array section as well.
10868         //
10869         // If this array section refers to the whole dimension we can still
10870         // accept other array sections before this one, except if the base is a
10871         // pointer. Otherwise, only unitary sections are accepted.
10872         if (NotWhole || IsPointer)
10873           AllowWholeSizeArraySection = false;
10874       } else if (AllowUnitySizeArraySection && NotUnity) {
10875         // A unity or whole array section is not allowed and that is not
10876         // compatible with the properties of the current array section.
10877         SemaRef.Diag(
10878             ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
10879             << CurE->getSourceRange();
10880         break;
10881       }
10882 
10883       // Record the component - we don't have any declaration associated.
10884       CurComponents.push_back(
10885           OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr));
10886       continue;
10887     }
10888 
10889     // If nothing else worked, this is not a valid map clause expression.
10890     SemaRef.Diag(ELoc,
10891                  diag::err_omp_expected_named_var_member_or_array_expression)
10892         << ERange;
10893     break;
10894   }
10895 
10896   return RelevantExpr;
10897 }
10898 
10899 // Return true if expression E associated with value VD has conflicts with other
10900 // map information.
10901 static bool CheckMapConflicts(
10902     Sema &SemaRef, DSAStackTy *DSAS, ValueDecl *VD, Expr *E,
10903     bool CurrentRegionOnly,
10904     OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
10905     OpenMPClauseKind CKind) {
10906   assert(VD && E);
10907   SourceLocation ELoc = E->getExprLoc();
10908   SourceRange ERange = E->getSourceRange();
10909 
10910   // In order to easily check the conflicts we need to match each component of
10911   // the expression under test with the components of the expressions that are
10912   // already in the stack.
10913 
10914   assert(!CurComponents.empty() && "Map clause expression with no components!");
10915   assert(CurComponents.back().getAssociatedDeclaration() == VD &&
10916          "Map clause expression with unexpected base!");
10917 
10918   // Variables to help detecting enclosing problems in data environment nests.
10919   bool IsEnclosedByDataEnvironmentExpr = false;
10920   const Expr *EnclosingExpr = nullptr;
10921 
10922   bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
10923       VD, CurrentRegionOnly,
10924       [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
10925               StackComponents,
10926           OpenMPClauseKind) -> bool {
10927 
10928         assert(!StackComponents.empty() &&
10929                "Map clause expression with no components!");
10930         assert(StackComponents.back().getAssociatedDeclaration() == VD &&
10931                "Map clause expression with unexpected base!");
10932 
10933         // The whole expression in the stack.
10934         auto *RE = StackComponents.front().getAssociatedExpression();
10935 
10936         // Expressions must start from the same base. Here we detect at which
10937         // point both expressions diverge from each other and see if we can
10938         // detect if the memory referred to both expressions is contiguous and
10939         // do not overlap.
10940         auto CI = CurComponents.rbegin();
10941         auto CE = CurComponents.rend();
10942         auto SI = StackComponents.rbegin();
10943         auto SE = StackComponents.rend();
10944         for (; CI != CE && SI != SE; ++CI, ++SI) {
10945 
10946           // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
10947           //  At most one list item can be an array item derived from a given
10948           //  variable in map clauses of the same construct.
10949           if (CurrentRegionOnly &&
10950               (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
10951                isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
10952               (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
10953                isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
10954             SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
10955                          diag::err_omp_multiple_array_items_in_map_clause)
10956                 << CI->getAssociatedExpression()->getSourceRange();
10957             SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
10958                          diag::note_used_here)
10959                 << SI->getAssociatedExpression()->getSourceRange();
10960             return true;
10961           }
10962 
10963           // Do both expressions have the same kind?
10964           if (CI->getAssociatedExpression()->getStmtClass() !=
10965               SI->getAssociatedExpression()->getStmtClass())
10966             break;
10967 
10968           // Are we dealing with different variables/fields?
10969           if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
10970             break;
10971         }
10972         // Check if the extra components of the expressions in the enclosing
10973         // data environment are redundant for the current base declaration.
10974         // If they are, the maps completely overlap, which is legal.
10975         for (; SI != SE; ++SI) {
10976           QualType Type;
10977           if (auto *ASE =
10978                   dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
10979             Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
10980           } else if (auto *OASE = dyn_cast<OMPArraySectionExpr>(
10981                          SI->getAssociatedExpression())) {
10982             auto *E = OASE->getBase()->IgnoreParenImpCasts();
10983             Type =
10984                 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
10985           }
10986           if (Type.isNull() || Type->isAnyPointerType() ||
10987               CheckArrayExpressionDoesNotReferToWholeSize(
10988                   SemaRef, SI->getAssociatedExpression(), Type))
10989             break;
10990         }
10991 
10992         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
10993         //  List items of map clauses in the same construct must not share
10994         //  original storage.
10995         //
10996         // If the expressions are exactly the same or one is a subset of the
10997         // other, it means they are sharing storage.
10998         if (CI == CE && SI == SE) {
10999           if (CurrentRegionOnly) {
11000             if (CKind == OMPC_map)
11001               SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
11002             else {
11003               assert(CKind == OMPC_to || CKind == OMPC_from);
11004               SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
11005                   << ERange;
11006             }
11007             SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
11008                 << RE->getSourceRange();
11009             return true;
11010           } else {
11011             // If we find the same expression in the enclosing data environment,
11012             // that is legal.
11013             IsEnclosedByDataEnvironmentExpr = true;
11014             return false;
11015           }
11016         }
11017 
11018         QualType DerivedType =
11019             std::prev(CI)->getAssociatedDeclaration()->getType();
11020         SourceLocation DerivedLoc =
11021             std::prev(CI)->getAssociatedExpression()->getExprLoc();
11022 
11023         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
11024         //  If the type of a list item is a reference to a type T then the type
11025         //  will be considered to be T for all purposes of this clause.
11026         DerivedType = DerivedType.getNonReferenceType();
11027 
11028         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
11029         //  A variable for which the type is pointer and an array section
11030         //  derived from that variable must not appear as list items of map
11031         //  clauses of the same construct.
11032         //
11033         // Also, cover one of the cases in:
11034         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
11035         //  If any part of the original storage of a list item has corresponding
11036         //  storage in the device data environment, all of the original storage
11037         //  must have corresponding storage in the device data environment.
11038         //
11039         if (DerivedType->isAnyPointerType()) {
11040           if (CI == CE || SI == SE) {
11041             SemaRef.Diag(
11042                 DerivedLoc,
11043                 diag::err_omp_pointer_mapped_along_with_derived_section)
11044                 << DerivedLoc;
11045           } else {
11046             assert(CI != CE && SI != SE);
11047             SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_derreferenced)
11048                 << DerivedLoc;
11049           }
11050           SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
11051               << RE->getSourceRange();
11052           return true;
11053         }
11054 
11055         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
11056         //  List items of map clauses in the same construct must not share
11057         //  original storage.
11058         //
11059         // An expression is a subset of the other.
11060         if (CurrentRegionOnly && (CI == CE || SI == SE)) {
11061           if (CKind == OMPC_map)
11062             SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
11063           else {
11064             assert(CKind == OMPC_to || CKind == OMPC_from);
11065             SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
11066                 << ERange;
11067           }
11068           SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
11069               << RE->getSourceRange();
11070           return true;
11071         }
11072 
11073         // The current expression uses the same base as other expression in the
11074         // data environment but does not contain it completely.
11075         if (!CurrentRegionOnly && SI != SE)
11076           EnclosingExpr = RE;
11077 
11078         // The current expression is a subset of the expression in the data
11079         // environment.
11080         IsEnclosedByDataEnvironmentExpr |=
11081             (!CurrentRegionOnly && CI != CE && SI == SE);
11082 
11083         return false;
11084       });
11085 
11086   if (CurrentRegionOnly)
11087     return FoundError;
11088 
11089   // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
11090   //  If any part of the original storage of a list item has corresponding
11091   //  storage in the device data environment, all of the original storage must
11092   //  have corresponding storage in the device data environment.
11093   // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
11094   //  If a list item is an element of a structure, and a different element of
11095   //  the structure has a corresponding list item in the device data environment
11096   //  prior to a task encountering the construct associated with the map clause,
11097   //  then the list item must also have a corresponding list item in the device
11098   //  data environment prior to the task encountering the construct.
11099   //
11100   if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
11101     SemaRef.Diag(ELoc,
11102                  diag::err_omp_original_storage_is_shared_and_does_not_contain)
11103         << ERange;
11104     SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
11105         << EnclosingExpr->getSourceRange();
11106     return true;
11107   }
11108 
11109   return FoundError;
11110 }
11111 
11112 namespace {
11113 // Utility struct that gathers all the related lists associated with a mappable
11114 // expression.
11115 struct MappableVarListInfo final {
11116   // The list of expressions.
11117   ArrayRef<Expr *> VarList;
11118   // The list of processed expressions.
11119   SmallVector<Expr *, 16> ProcessedVarList;
11120   // The mappble components for each expression.
11121   OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
11122   // The base declaration of the variable.
11123   SmallVector<ValueDecl *, 16> VarBaseDeclarations;
11124 
11125   MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
11126     // We have a list of components and base declarations for each entry in the
11127     // variable list.
11128     VarComponents.reserve(VarList.size());
11129     VarBaseDeclarations.reserve(VarList.size());
11130   }
11131 };
11132 }
11133 
11134 // Check the validity of the provided variable list for the provided clause kind
11135 // \a CKind. In the check process the valid expressions, and mappable expression
11136 // components and variables are extracted and used to fill \a Vars,
11137 // \a ClauseComponents, and \a ClauseBaseDeclarations. \a MapType and
11138 // \a IsMapTypeImplicit are expected to be valid if the clause kind is 'map'.
11139 static void
11140 checkMappableExpressionList(Sema &SemaRef, DSAStackTy *DSAS,
11141                             OpenMPClauseKind CKind, MappableVarListInfo &MVLI,
11142                             SourceLocation StartLoc,
11143                             OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
11144                             bool IsMapTypeImplicit = false) {
11145   // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
11146   assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
11147          "Unexpected clause kind with mappable expressions!");
11148 
11149   // Keep track of the mappable components and base declarations in this clause.
11150   // Each entry in the list is going to have a list of components associated. We
11151   // record each set of the components so that we can build the clause later on.
11152   // In the end we should have the same amount of declarations and component
11153   // lists.
11154 
11155   for (auto &RE : MVLI.VarList) {
11156     assert(RE && "Null expr in omp to/from/map clause");
11157     SourceLocation ELoc = RE->getExprLoc();
11158 
11159     auto *VE = RE->IgnoreParenLValueCasts();
11160 
11161     if (VE->isValueDependent() || VE->isTypeDependent() ||
11162         VE->isInstantiationDependent() ||
11163         VE->containsUnexpandedParameterPack()) {
11164       // We can only analyze this information once the missing information is
11165       // resolved.
11166       MVLI.ProcessedVarList.push_back(RE);
11167       continue;
11168     }
11169 
11170     auto *SimpleExpr = RE->IgnoreParenCasts();
11171 
11172     if (!RE->IgnoreParenImpCasts()->isLValue()) {
11173       SemaRef.Diag(ELoc,
11174                    diag::err_omp_expected_named_var_member_or_array_expression)
11175           << RE->getSourceRange();
11176       continue;
11177     }
11178 
11179     OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
11180     ValueDecl *CurDeclaration = nullptr;
11181 
11182     // Obtain the array or member expression bases if required. Also, fill the
11183     // components array with all the components identified in the process.
11184     auto *BE =
11185         CheckMapClauseExpressionBase(SemaRef, SimpleExpr, CurComponents, CKind);
11186     if (!BE)
11187       continue;
11188 
11189     assert(!CurComponents.empty() &&
11190            "Invalid mappable expression information.");
11191 
11192     // For the following checks, we rely on the base declaration which is
11193     // expected to be associated with the last component. The declaration is
11194     // expected to be a variable or a field (if 'this' is being mapped).
11195     CurDeclaration = CurComponents.back().getAssociatedDeclaration();
11196     assert(CurDeclaration && "Null decl on map clause.");
11197     assert(
11198         CurDeclaration->isCanonicalDecl() &&
11199         "Expecting components to have associated only canonical declarations.");
11200 
11201     auto *VD = dyn_cast<VarDecl>(CurDeclaration);
11202     auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
11203 
11204     assert((VD || FD) && "Only variables or fields are expected here!");
11205     (void)FD;
11206 
11207     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
11208     // threadprivate variables cannot appear in a map clause.
11209     // OpenMP 4.5 [2.10.5, target update Construct]
11210     // threadprivate variables cannot appear in a from clause.
11211     if (VD && DSAS->isThreadPrivate(VD)) {
11212       auto DVar = DSAS->getTopDSA(VD, false);
11213       SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
11214           << getOpenMPClauseName(CKind);
11215       ReportOriginalDSA(SemaRef, DSAS, VD, DVar);
11216       continue;
11217     }
11218 
11219     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
11220     //  A list item cannot appear in both a map clause and a data-sharing
11221     //  attribute clause on the same construct.
11222 
11223     // Check conflicts with other map clause expressions. We check the conflicts
11224     // with the current construct separately from the enclosing data
11225     // environment, because the restrictions are different. We only have to
11226     // check conflicts across regions for the map clauses.
11227     if (CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
11228                           /*CurrentRegionOnly=*/true, CurComponents, CKind))
11229       break;
11230     if (CKind == OMPC_map &&
11231         CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
11232                           /*CurrentRegionOnly=*/false, CurComponents, CKind))
11233       break;
11234 
11235     // OpenMP 4.5 [2.10.5, target update Construct]
11236     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
11237     //  If the type of a list item is a reference to a type T then the type will
11238     //  be considered to be T for all purposes of this clause.
11239     QualType Type = CurDeclaration->getType().getNonReferenceType();
11240 
11241     // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
11242     // A list item in a to or from clause must have a mappable type.
11243     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
11244     //  A list item must have a mappable type.
11245     if (!CheckTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
11246                            DSAS, Type))
11247       continue;
11248 
11249     if (CKind == OMPC_map) {
11250       // target enter data
11251       // OpenMP [2.10.2, Restrictions, p. 99]
11252       // A map-type must be specified in all map clauses and must be either
11253       // to or alloc.
11254       OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
11255       if (DKind == OMPD_target_enter_data &&
11256           !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
11257         SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
11258             << (IsMapTypeImplicit ? 1 : 0)
11259             << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
11260             << getOpenMPDirectiveName(DKind);
11261         continue;
11262       }
11263 
11264       // target exit_data
11265       // OpenMP [2.10.3, Restrictions, p. 102]
11266       // A map-type must be specified in all map clauses and must be either
11267       // from, release, or delete.
11268       if (DKind == OMPD_target_exit_data &&
11269           !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
11270             MapType == OMPC_MAP_delete)) {
11271         SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
11272             << (IsMapTypeImplicit ? 1 : 0)
11273             << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
11274             << getOpenMPDirectiveName(DKind);
11275         continue;
11276       }
11277 
11278       // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
11279       // A list item cannot appear in both a map clause and a data-sharing
11280       // attribute clause on the same construct
11281       if ((DKind == OMPD_target || DKind == OMPD_target_teams ||
11282            DKind == OMPD_target_teams_distribute ||
11283            DKind == OMPD_target_teams_distribute_parallel_for ||
11284            DKind == OMPD_target_teams_distribute_parallel_for_simd ||
11285            DKind == OMPD_target_teams_distribute_simd) && VD) {
11286         auto DVar = DSAS->getTopDSA(VD, false);
11287         if (isOpenMPPrivate(DVar.CKind)) {
11288           SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
11289               << getOpenMPClauseName(DVar.CKind)
11290               << getOpenMPClauseName(OMPC_map)
11291               << getOpenMPDirectiveName(DSAS->getCurrentDirective());
11292           ReportOriginalDSA(SemaRef, DSAS, CurDeclaration, DVar);
11293           continue;
11294         }
11295       }
11296     }
11297 
11298     // Save the current expression.
11299     MVLI.ProcessedVarList.push_back(RE);
11300 
11301     // Store the components in the stack so that they can be used to check
11302     // against other clauses later on.
11303     DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
11304                                           /*WhereFoundClauseKind=*/OMPC_map);
11305 
11306     // Save the components and declaration to create the clause. For purposes of
11307     // the clause creation, any component list that has has base 'this' uses
11308     // null as base declaration.
11309     MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
11310     MVLI.VarComponents.back().append(CurComponents.begin(),
11311                                      CurComponents.end());
11312     MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
11313                                                            : CurDeclaration);
11314   }
11315 }
11316 
11317 OMPClause *
11318 Sema::ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier,
11319                            OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
11320                            SourceLocation MapLoc, SourceLocation ColonLoc,
11321                            ArrayRef<Expr *> VarList, SourceLocation StartLoc,
11322                            SourceLocation LParenLoc, SourceLocation EndLoc) {
11323   MappableVarListInfo MVLI(VarList);
11324   checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, StartLoc,
11325                               MapType, IsMapTypeImplicit);
11326 
11327   // We need to produce a map clause even if we don't have variables so that
11328   // other diagnostics related with non-existing map clauses are accurate.
11329   return OMPMapClause::Create(Context, StartLoc, LParenLoc, EndLoc,
11330                               MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
11331                               MVLI.VarComponents, MapTypeModifier, MapType,
11332                               IsMapTypeImplicit, MapLoc);
11333 }
11334 
11335 QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
11336                                                TypeResult ParsedType) {
11337   assert(ParsedType.isUsable());
11338 
11339   QualType ReductionType = GetTypeFromParser(ParsedType.get());
11340   if (ReductionType.isNull())
11341     return QualType();
11342 
11343   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
11344   // A type name in a declare reduction directive cannot be a function type, an
11345   // array type, a reference type, or a type qualified with const, volatile or
11346   // restrict.
11347   if (ReductionType.hasQualifiers()) {
11348     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
11349     return QualType();
11350   }
11351 
11352   if (ReductionType->isFunctionType()) {
11353     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
11354     return QualType();
11355   }
11356   if (ReductionType->isReferenceType()) {
11357     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
11358     return QualType();
11359   }
11360   if (ReductionType->isArrayType()) {
11361     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
11362     return QualType();
11363   }
11364   return ReductionType;
11365 }
11366 
11367 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
11368     Scope *S, DeclContext *DC, DeclarationName Name,
11369     ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
11370     AccessSpecifier AS, Decl *PrevDeclInScope) {
11371   SmallVector<Decl *, 8> Decls;
11372   Decls.reserve(ReductionTypes.size());
11373 
11374   LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
11375                       ForRedeclaration);
11376   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
11377   // A reduction-identifier may not be re-declared in the current scope for the
11378   // same type or for a type that is compatible according to the base language
11379   // rules.
11380   llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
11381   OMPDeclareReductionDecl *PrevDRD = nullptr;
11382   bool InCompoundScope = true;
11383   if (S != nullptr) {
11384     // Find previous declaration with the same name not referenced in other
11385     // declarations.
11386     FunctionScopeInfo *ParentFn = getEnclosingFunction();
11387     InCompoundScope =
11388         (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
11389     LookupName(Lookup, S);
11390     FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
11391                          /*AllowInlineNamespace=*/false);
11392     llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
11393     auto Filter = Lookup.makeFilter();
11394     while (Filter.hasNext()) {
11395       auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
11396       if (InCompoundScope) {
11397         auto I = UsedAsPrevious.find(PrevDecl);
11398         if (I == UsedAsPrevious.end())
11399           UsedAsPrevious[PrevDecl] = false;
11400         if (auto *D = PrevDecl->getPrevDeclInScope())
11401           UsedAsPrevious[D] = true;
11402       }
11403       PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
11404           PrevDecl->getLocation();
11405     }
11406     Filter.done();
11407     if (InCompoundScope) {
11408       for (auto &PrevData : UsedAsPrevious) {
11409         if (!PrevData.second) {
11410           PrevDRD = PrevData.first;
11411           break;
11412         }
11413       }
11414     }
11415   } else if (PrevDeclInScope != nullptr) {
11416     auto *PrevDRDInScope = PrevDRD =
11417         cast<OMPDeclareReductionDecl>(PrevDeclInScope);
11418     do {
11419       PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
11420           PrevDRDInScope->getLocation();
11421       PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
11422     } while (PrevDRDInScope != nullptr);
11423   }
11424   for (auto &TyData : ReductionTypes) {
11425     auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
11426     bool Invalid = false;
11427     if (I != PreviousRedeclTypes.end()) {
11428       Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
11429           << TyData.first;
11430       Diag(I->second, diag::note_previous_definition);
11431       Invalid = true;
11432     }
11433     PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
11434     auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
11435                                                 Name, TyData.first, PrevDRD);
11436     DC->addDecl(DRD);
11437     DRD->setAccess(AS);
11438     Decls.push_back(DRD);
11439     if (Invalid)
11440       DRD->setInvalidDecl();
11441     else
11442       PrevDRD = DRD;
11443   }
11444 
11445   return DeclGroupPtrTy::make(
11446       DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
11447 }
11448 
11449 void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
11450   auto *DRD = cast<OMPDeclareReductionDecl>(D);
11451 
11452   // Enter new function scope.
11453   PushFunctionScope();
11454   getCurFunction()->setHasBranchProtectedScope();
11455   getCurFunction()->setHasOMPDeclareReductionCombiner();
11456 
11457   if (S != nullptr)
11458     PushDeclContext(S, DRD);
11459   else
11460     CurContext = DRD;
11461 
11462   PushExpressionEvaluationContext(
11463       ExpressionEvaluationContext::PotentiallyEvaluated);
11464 
11465   QualType ReductionType = DRD->getType();
11466   // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
11467   // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
11468   // uses semantics of argument handles by value, but it should be passed by
11469   // reference. C lang does not support references, so pass all parameters as
11470   // pointers.
11471   // Create 'T omp_in;' variable.
11472   auto *OmpInParm =
11473       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
11474   // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
11475   // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
11476   // uses semantics of argument handles by value, but it should be passed by
11477   // reference. C lang does not support references, so pass all parameters as
11478   // pointers.
11479   // Create 'T omp_out;' variable.
11480   auto *OmpOutParm =
11481       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
11482   if (S != nullptr) {
11483     PushOnScopeChains(OmpInParm, S);
11484     PushOnScopeChains(OmpOutParm, S);
11485   } else {
11486     DRD->addDecl(OmpInParm);
11487     DRD->addDecl(OmpOutParm);
11488   }
11489 }
11490 
11491 void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
11492   auto *DRD = cast<OMPDeclareReductionDecl>(D);
11493   DiscardCleanupsInEvaluationContext();
11494   PopExpressionEvaluationContext();
11495 
11496   PopDeclContext();
11497   PopFunctionScopeInfo();
11498 
11499   if (Combiner != nullptr)
11500     DRD->setCombiner(Combiner);
11501   else
11502     DRD->setInvalidDecl();
11503 }
11504 
11505 void Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
11506   auto *DRD = cast<OMPDeclareReductionDecl>(D);
11507 
11508   // Enter new function scope.
11509   PushFunctionScope();
11510   getCurFunction()->setHasBranchProtectedScope();
11511 
11512   if (S != nullptr)
11513     PushDeclContext(S, DRD);
11514   else
11515     CurContext = DRD;
11516 
11517   PushExpressionEvaluationContext(
11518       ExpressionEvaluationContext::PotentiallyEvaluated);
11519 
11520   QualType ReductionType = DRD->getType();
11521   // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
11522   // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
11523   // uses semantics of argument handles by value, but it should be passed by
11524   // reference. C lang does not support references, so pass all parameters as
11525   // pointers.
11526   // Create 'T omp_priv;' variable.
11527   auto *OmpPrivParm =
11528       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
11529   // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
11530   // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
11531   // uses semantics of argument handles by value, but it should be passed by
11532   // reference. C lang does not support references, so pass all parameters as
11533   // pointers.
11534   // Create 'T omp_orig;' variable.
11535   auto *OmpOrigParm =
11536       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
11537   if (S != nullptr) {
11538     PushOnScopeChains(OmpPrivParm, S);
11539     PushOnScopeChains(OmpOrigParm, S);
11540   } else {
11541     DRD->addDecl(OmpPrivParm);
11542     DRD->addDecl(OmpOrigParm);
11543   }
11544 }
11545 
11546 void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D,
11547                                                      Expr *Initializer) {
11548   auto *DRD = cast<OMPDeclareReductionDecl>(D);
11549   DiscardCleanupsInEvaluationContext();
11550   PopExpressionEvaluationContext();
11551 
11552   PopDeclContext();
11553   PopFunctionScopeInfo();
11554 
11555   if (Initializer != nullptr)
11556     DRD->setInitializer(Initializer);
11557   else
11558     DRD->setInvalidDecl();
11559 }
11560 
11561 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
11562     Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
11563   for (auto *D : DeclReductions.get()) {
11564     if (IsValid) {
11565       auto *DRD = cast<OMPDeclareReductionDecl>(D);
11566       if (S != nullptr)
11567         PushOnScopeChains(DRD, S, /*AddToContext=*/false);
11568     } else
11569       D->setInvalidDecl();
11570   }
11571   return DeclReductions;
11572 }
11573 
11574 OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
11575                                            SourceLocation StartLoc,
11576                                            SourceLocation LParenLoc,
11577                                            SourceLocation EndLoc) {
11578   Expr *ValExpr = NumTeams;
11579   Stmt *HelperValStmt = nullptr;
11580   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
11581 
11582   // OpenMP [teams Constrcut, Restrictions]
11583   // The num_teams expression must evaluate to a positive integer value.
11584   if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
11585                                  /*StrictlyPositive=*/true))
11586     return nullptr;
11587 
11588   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
11589   CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams);
11590   if (CaptureRegion != OMPD_unknown) {
11591     llvm::MapVector<Expr *, DeclRefExpr *> Captures;
11592     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11593     HelperValStmt = buildPreInits(Context, Captures);
11594   }
11595 
11596   return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
11597                                          StartLoc, LParenLoc, EndLoc);
11598 }
11599 
11600 OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
11601                                               SourceLocation StartLoc,
11602                                               SourceLocation LParenLoc,
11603                                               SourceLocation EndLoc) {
11604   Expr *ValExpr = ThreadLimit;
11605   Stmt *HelperValStmt = nullptr;
11606   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
11607 
11608   // OpenMP [teams Constrcut, Restrictions]
11609   // The thread_limit expression must evaluate to a positive integer value.
11610   if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
11611                                  /*StrictlyPositive=*/true))
11612     return nullptr;
11613 
11614   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
11615   CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_thread_limit);
11616   if (CaptureRegion != OMPD_unknown) {
11617     llvm::MapVector<Expr *, DeclRefExpr *> Captures;
11618     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11619     HelperValStmt = buildPreInits(Context, Captures);
11620   }
11621 
11622   return new (Context) OMPThreadLimitClause(
11623       ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
11624 }
11625 
11626 OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
11627                                            SourceLocation StartLoc,
11628                                            SourceLocation LParenLoc,
11629                                            SourceLocation EndLoc) {
11630   Expr *ValExpr = Priority;
11631 
11632   // OpenMP [2.9.1, task Constrcut]
11633   // The priority-value is a non-negative numerical scalar expression.
11634   if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_priority,
11635                                  /*StrictlyPositive=*/false))
11636     return nullptr;
11637 
11638   return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc);
11639 }
11640 
11641 OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
11642                                             SourceLocation StartLoc,
11643                                             SourceLocation LParenLoc,
11644                                             SourceLocation EndLoc) {
11645   Expr *ValExpr = Grainsize;
11646 
11647   // OpenMP [2.9.2, taskloop Constrcut]
11648   // The parameter of the grainsize clause must be a positive integer
11649   // expression.
11650   if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize,
11651                                  /*StrictlyPositive=*/true))
11652     return nullptr;
11653 
11654   return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc);
11655 }
11656 
11657 OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
11658                                            SourceLocation StartLoc,
11659                                            SourceLocation LParenLoc,
11660                                            SourceLocation EndLoc) {
11661   Expr *ValExpr = NumTasks;
11662 
11663   // OpenMP [2.9.2, taskloop Constrcut]
11664   // The parameter of the num_tasks clause must be a positive integer
11665   // expression.
11666   if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks,
11667                                  /*StrictlyPositive=*/true))
11668     return nullptr;
11669 
11670   return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc);
11671 }
11672 
11673 OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
11674                                        SourceLocation LParenLoc,
11675                                        SourceLocation EndLoc) {
11676   // OpenMP [2.13.2, critical construct, Description]
11677   // ... where hint-expression is an integer constant expression that evaluates
11678   // to a valid lock hint.
11679   ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
11680   if (HintExpr.isInvalid())
11681     return nullptr;
11682   return new (Context)
11683       OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
11684 }
11685 
11686 OMPClause *Sema::ActOnOpenMPDistScheduleClause(
11687     OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
11688     SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
11689     SourceLocation EndLoc) {
11690   if (Kind == OMPC_DIST_SCHEDULE_unknown) {
11691     std::string Values;
11692     Values += "'";
11693     Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
11694     Values += "'";
11695     Diag(KindLoc, diag::err_omp_unexpected_clause_value)
11696         << Values << getOpenMPClauseName(OMPC_dist_schedule);
11697     return nullptr;
11698   }
11699   Expr *ValExpr = ChunkSize;
11700   Stmt *HelperValStmt = nullptr;
11701   if (ChunkSize) {
11702     if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
11703         !ChunkSize->isInstantiationDependent() &&
11704         !ChunkSize->containsUnexpandedParameterPack()) {
11705       SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
11706       ExprResult Val =
11707           PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
11708       if (Val.isInvalid())
11709         return nullptr;
11710 
11711       ValExpr = Val.get();
11712 
11713       // OpenMP [2.7.1, Restrictions]
11714       //  chunk_size must be a loop invariant integer expression with a positive
11715       //  value.
11716       llvm::APSInt Result;
11717       if (ValExpr->isIntegerConstantExpr(Result, Context)) {
11718         if (Result.isSigned() && !Result.isStrictlyPositive()) {
11719           Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
11720               << "dist_schedule" << ChunkSize->getSourceRange();
11721           return nullptr;
11722         }
11723       } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) &&
11724                  !CurContext->isDependentContext()) {
11725         llvm::MapVector<Expr *, DeclRefExpr *> Captures;
11726         ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11727         HelperValStmt = buildPreInits(Context, Captures);
11728       }
11729     }
11730   }
11731 
11732   return new (Context)
11733       OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
11734                             Kind, ValExpr, HelperValStmt);
11735 }
11736 
11737 OMPClause *Sema::ActOnOpenMPDefaultmapClause(
11738     OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
11739     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
11740     SourceLocation KindLoc, SourceLocation EndLoc) {
11741   // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)'
11742   if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) {
11743     std::string Value;
11744     SourceLocation Loc;
11745     Value += "'";
11746     if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
11747       Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
11748                                              OMPC_DEFAULTMAP_MODIFIER_tofrom);
11749       Loc = MLoc;
11750     } else {
11751       Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
11752                                              OMPC_DEFAULTMAP_scalar);
11753       Loc = KindLoc;
11754     }
11755     Value += "'";
11756     Diag(Loc, diag::err_omp_unexpected_clause_value)
11757         << Value << getOpenMPClauseName(OMPC_defaultmap);
11758     return nullptr;
11759   }
11760 
11761   return new (Context)
11762       OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
11763 }
11764 
11765 bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
11766   DeclContext *CurLexicalContext = getCurLexicalContext();
11767   if (!CurLexicalContext->isFileContext() &&
11768       !CurLexicalContext->isExternCContext() &&
11769       !CurLexicalContext->isExternCXXContext()) {
11770     Diag(Loc, diag::err_omp_region_not_file_context);
11771     return false;
11772   }
11773   if (IsInOpenMPDeclareTargetContext) {
11774     Diag(Loc, diag::err_omp_enclosed_declare_target);
11775     return false;
11776   }
11777 
11778   IsInOpenMPDeclareTargetContext = true;
11779   return true;
11780 }
11781 
11782 void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
11783   assert(IsInOpenMPDeclareTargetContext &&
11784          "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
11785 
11786   IsInOpenMPDeclareTargetContext = false;
11787 }
11788 
11789 void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope,
11790                                         CXXScopeSpec &ScopeSpec,
11791                                         const DeclarationNameInfo &Id,
11792                                         OMPDeclareTargetDeclAttr::MapTypeTy MT,
11793                                         NamedDeclSetType &SameDirectiveDecls) {
11794   LookupResult Lookup(*this, Id, LookupOrdinaryName);
11795   LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
11796 
11797   if (Lookup.isAmbiguous())
11798     return;
11799   Lookup.suppressDiagnostics();
11800 
11801   if (!Lookup.isSingleResult()) {
11802     if (TypoCorrection Corrected =
11803             CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr,
11804                         llvm::make_unique<VarOrFuncDeclFilterCCC>(*this),
11805                         CTK_ErrorRecovery)) {
11806       diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
11807                                   << Id.getName());
11808       checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
11809       return;
11810     }
11811 
11812     Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
11813     return;
11814   }
11815 
11816   NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
11817   if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) {
11818     if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
11819       Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
11820 
11821     if (!ND->hasAttr<OMPDeclareTargetDeclAttr>()) {
11822       Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT);
11823       ND->addAttr(A);
11824       if (ASTMutationListener *ML = Context.getASTMutationListener())
11825         ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
11826       checkDeclIsAllowedInOpenMPTarget(nullptr, ND);
11827     } else if (ND->getAttr<OMPDeclareTargetDeclAttr>()->getMapType() != MT) {
11828       Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link)
11829           << Id.getName();
11830     }
11831   } else
11832     Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
11833 }
11834 
11835 static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
11836                                      Sema &SemaRef, Decl *D) {
11837   if (!D)
11838     return;
11839   Decl *LD = nullptr;
11840   if (isa<TagDecl>(D)) {
11841     LD = cast<TagDecl>(D)->getDefinition();
11842   } else if (isa<VarDecl>(D)) {
11843     LD = cast<VarDecl>(D)->getDefinition();
11844 
11845     // If this is an implicit variable that is legal and we do not need to do
11846     // anything.
11847     if (cast<VarDecl>(D)->isImplicit()) {
11848       Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
11849           SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
11850       D->addAttr(A);
11851       if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
11852         ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
11853       return;
11854     }
11855 
11856   } else if (isa<FunctionDecl>(D)) {
11857     const FunctionDecl *FD = nullptr;
11858     if (cast<FunctionDecl>(D)->hasBody(FD))
11859       LD = const_cast<FunctionDecl *>(FD);
11860 
11861     // If the definition is associated with the current declaration in the
11862     // target region (it can be e.g. a lambda) that is legal and we do not need
11863     // to do anything else.
11864     if (LD == D) {
11865       Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
11866           SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
11867       D->addAttr(A);
11868       if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
11869         ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
11870       return;
11871     }
11872   }
11873   if (!LD)
11874     LD = D;
11875   if (LD && !LD->hasAttr<OMPDeclareTargetDeclAttr>() &&
11876       (isa<VarDecl>(LD) || isa<FunctionDecl>(LD))) {
11877     // Outlined declaration is not declared target.
11878     if (LD->isOutOfLine()) {
11879       SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
11880       SemaRef.Diag(SL, diag::note_used_here) << SR;
11881     } else {
11882       DeclContext *DC = LD->getDeclContext();
11883       while (DC) {
11884         if (isa<FunctionDecl>(DC) &&
11885             cast<FunctionDecl>(DC)->hasAttr<OMPDeclareTargetDeclAttr>())
11886           break;
11887         DC = DC->getParent();
11888       }
11889       if (DC)
11890         return;
11891 
11892       // Is not declared in target context.
11893       SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
11894       SemaRef.Diag(SL, diag::note_used_here) << SR;
11895     }
11896     // Mark decl as declared target to prevent further diagnostic.
11897     Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
11898         SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
11899     D->addAttr(A);
11900     if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
11901       ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
11902   }
11903 }
11904 
11905 static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
11906                                    Sema &SemaRef, DSAStackTy *Stack,
11907                                    ValueDecl *VD) {
11908   if (VD->hasAttr<OMPDeclareTargetDeclAttr>())
11909     return true;
11910   if (!CheckTypeMappable(SL, SR, SemaRef, Stack, VD->getType()))
11911     return false;
11912   return true;
11913 }
11914 
11915 void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D) {
11916   if (!D || D->isInvalidDecl())
11917     return;
11918   SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
11919   SourceLocation SL = E ? E->getLocStart() : D->getLocation();
11920   // 2.10.6: threadprivate variable cannot appear in a declare target directive.
11921   if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
11922     if (DSAStack->isThreadPrivate(VD)) {
11923       Diag(SL, diag::err_omp_threadprivate_in_target);
11924       ReportOriginalDSA(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
11925       return;
11926     }
11927   }
11928   if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
11929     // Problem if any with var declared with incomplete type will be reported
11930     // as normal, so no need to check it here.
11931     if ((E || !VD->getType()->isIncompleteType()) &&
11932         !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD)) {
11933       // Mark decl as declared target to prevent further diagnostic.
11934       if (isa<VarDecl>(VD) || isa<FunctionDecl>(VD)) {
11935         Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
11936             Context, OMPDeclareTargetDeclAttr::MT_To);
11937         VD->addAttr(A);
11938         if (ASTMutationListener *ML = Context.getASTMutationListener())
11939           ML->DeclarationMarkedOpenMPDeclareTarget(VD, A);
11940       }
11941       return;
11942     }
11943   }
11944   if (!E) {
11945     // Checking declaration inside declare target region.
11946     if (!D->hasAttr<OMPDeclareTargetDeclAttr>() &&
11947         (isa<VarDecl>(D) || isa<FunctionDecl>(D))) {
11948       Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
11949           Context, OMPDeclareTargetDeclAttr::MT_To);
11950       D->addAttr(A);
11951       if (ASTMutationListener *ML = Context.getASTMutationListener())
11952         ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
11953     }
11954     return;
11955   }
11956   checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
11957 }
11958 
11959 OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
11960                                      SourceLocation StartLoc,
11961                                      SourceLocation LParenLoc,
11962                                      SourceLocation EndLoc) {
11963   MappableVarListInfo MVLI(VarList);
11964   checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, StartLoc);
11965   if (MVLI.ProcessedVarList.empty())
11966     return nullptr;
11967 
11968   return OMPToClause::Create(Context, StartLoc, LParenLoc, EndLoc,
11969                              MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
11970                              MVLI.VarComponents);
11971 }
11972 
11973 OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
11974                                        SourceLocation StartLoc,
11975                                        SourceLocation LParenLoc,
11976                                        SourceLocation EndLoc) {
11977   MappableVarListInfo MVLI(VarList);
11978   checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, StartLoc);
11979   if (MVLI.ProcessedVarList.empty())
11980     return nullptr;
11981 
11982   return OMPFromClause::Create(Context, StartLoc, LParenLoc, EndLoc,
11983                                MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
11984                                MVLI.VarComponents);
11985 }
11986 
11987 OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
11988                                                SourceLocation StartLoc,
11989                                                SourceLocation LParenLoc,
11990                                                SourceLocation EndLoc) {
11991   MappableVarListInfo MVLI(VarList);
11992   SmallVector<Expr *, 8> PrivateCopies;
11993   SmallVector<Expr *, 8> Inits;
11994 
11995   for (auto &RefExpr : VarList) {
11996     assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
11997     SourceLocation ELoc;
11998     SourceRange ERange;
11999     Expr *SimpleRefExpr = RefExpr;
12000     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
12001     if (Res.second) {
12002       // It will be analyzed later.
12003       MVLI.ProcessedVarList.push_back(RefExpr);
12004       PrivateCopies.push_back(nullptr);
12005       Inits.push_back(nullptr);
12006     }
12007     ValueDecl *D = Res.first;
12008     if (!D)
12009       continue;
12010 
12011     QualType Type = D->getType();
12012     Type = Type.getNonReferenceType().getUnqualifiedType();
12013 
12014     auto *VD = dyn_cast<VarDecl>(D);
12015 
12016     // Item should be a pointer or reference to pointer.
12017     if (!Type->isPointerType()) {
12018       Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
12019           << 0 << RefExpr->getSourceRange();
12020       continue;
12021     }
12022 
12023     // Build the private variable and the expression that refers to it.
12024     auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
12025                                   D->hasAttrs() ? &D->getAttrs() : nullptr);
12026     if (VDPrivate->isInvalidDecl())
12027       continue;
12028 
12029     CurContext->addDecl(VDPrivate);
12030     auto VDPrivateRefExpr = buildDeclRefExpr(
12031         *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
12032 
12033     // Add temporary variable to initialize the private copy of the pointer.
12034     auto *VDInit =
12035         buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
12036     auto *VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
12037                                            RefExpr->getExprLoc());
12038     AddInitializerToDecl(VDPrivate,
12039                          DefaultLvalueConversion(VDInitRefExpr).get(),
12040                          /*DirectInit=*/false);
12041 
12042     // If required, build a capture to implement the privatization initialized
12043     // with the current list item value.
12044     DeclRefExpr *Ref = nullptr;
12045     if (!VD)
12046       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
12047     MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
12048     PrivateCopies.push_back(VDPrivateRefExpr);
12049     Inits.push_back(VDInitRefExpr);
12050 
12051     // We need to add a data sharing attribute for this variable to make sure it
12052     // is correctly captured. A variable that shows up in a use_device_ptr has
12053     // similar properties of a first private variable.
12054     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
12055 
12056     // Create a mappable component for the list item. List items in this clause
12057     // only need a component.
12058     MVLI.VarBaseDeclarations.push_back(D);
12059     MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
12060     MVLI.VarComponents.back().push_back(
12061         OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
12062   }
12063 
12064   if (MVLI.ProcessedVarList.empty())
12065     return nullptr;
12066 
12067   return OMPUseDevicePtrClause::Create(
12068       Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
12069       PrivateCopies, Inits, MVLI.VarBaseDeclarations, MVLI.VarComponents);
12070 }
12071 
12072 OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
12073                                               SourceLocation StartLoc,
12074                                               SourceLocation LParenLoc,
12075                                               SourceLocation EndLoc) {
12076   MappableVarListInfo MVLI(VarList);
12077   for (auto &RefExpr : VarList) {
12078     assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
12079     SourceLocation ELoc;
12080     SourceRange ERange;
12081     Expr *SimpleRefExpr = RefExpr;
12082     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
12083     if (Res.second) {
12084       // It will be analyzed later.
12085       MVLI.ProcessedVarList.push_back(RefExpr);
12086     }
12087     ValueDecl *D = Res.first;
12088     if (!D)
12089       continue;
12090 
12091     QualType Type = D->getType();
12092     // item should be a pointer or array or reference to pointer or array
12093     if (!Type.getNonReferenceType()->isPointerType() &&
12094         !Type.getNonReferenceType()->isArrayType()) {
12095       Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
12096           << 0 << RefExpr->getSourceRange();
12097       continue;
12098     }
12099 
12100     // Check if the declaration in the clause does not show up in any data
12101     // sharing attribute.
12102     auto DVar = DSAStack->getTopDSA(D, false);
12103     if (isOpenMPPrivate(DVar.CKind)) {
12104       Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
12105           << getOpenMPClauseName(DVar.CKind)
12106           << getOpenMPClauseName(OMPC_is_device_ptr)
12107           << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
12108       ReportOriginalDSA(*this, DSAStack, D, DVar);
12109       continue;
12110     }
12111 
12112     Expr *ConflictExpr;
12113     if (DSAStack->checkMappableExprComponentListsForDecl(
12114             D, /*CurrentRegionOnly=*/true,
12115             [&ConflictExpr](
12116                 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
12117                 OpenMPClauseKind) -> bool {
12118               ConflictExpr = R.front().getAssociatedExpression();
12119               return true;
12120             })) {
12121       Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
12122       Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
12123           << ConflictExpr->getSourceRange();
12124       continue;
12125     }
12126 
12127     // Store the components in the stack so that they can be used to check
12128     // against other clauses later on.
12129     OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
12130     DSAStack->addMappableExpressionComponents(
12131         D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
12132 
12133     // Record the expression we've just processed.
12134     MVLI.ProcessedVarList.push_back(SimpleRefExpr);
12135 
12136     // Create a mappable component for the list item. List items in this clause
12137     // only need a component. We use a null declaration to signal fields in
12138     // 'this'.
12139     assert((isa<DeclRefExpr>(SimpleRefExpr) ||
12140             isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
12141            "Unexpected device pointer expression!");
12142     MVLI.VarBaseDeclarations.push_back(
12143         isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
12144     MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
12145     MVLI.VarComponents.back().push_back(MC);
12146   }
12147 
12148   if (MVLI.ProcessedVarList.empty())
12149     return nullptr;
12150 
12151   return OMPIsDevicePtrClause::Create(
12152       Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
12153       MVLI.VarBaseDeclarations, MVLI.VarComponents);
12154 }
12155